From 231c17d7c3706f352b9da2e5cf8c86463797e129 Mon Sep 17 00:00:00 2001 From: Siegfried Siegert Date: Sun, 30 Aug 2020 21:08:50 +0200 Subject: [PATCH] Update MQTT message handling - use separate handler - use regexpression for topic check --- mqtt/mqtt.go | 47 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 41 insertions(+), 6 deletions(-) diff --git a/mqtt/mqtt.go b/mqtt/mqtt.go index ef3dbef..f919d54 100644 --- a/mqtt/mqtt.go +++ b/mqtt/mqtt.go @@ -11,6 +11,7 @@ import ( MQTT "github.com/eclipse/paho.mqtt.golang" //"os" "mqttListener/Config" + "regexp" "time" ) @@ -48,12 +49,16 @@ func Listen() { log.Fatal("Client is not connected") return } - client.Subscribe(topic, 0, func(client MQTT.Client, msg MQTT.Message) { - fmt.Printf("---------------------------------------------------\n") - fmt.Printf("TOPIC: %s\n", msg.Topic()) - fmt.Printf("MSG: \n%s\n", msg.Payload()) - //fmt.Printf("* [%s] %s\n", msg.Topic(), string(msg.Payload())) - }) + + client.Subscribe(topic, 0, subscriptionHandler) + /* + client.Subscribe(topic, 0, func(client MQTT.Client, msg MQTT.Message) { + fmt.Printf("---------------------------------------------------\n") + fmt.Printf("TOPIC: %s\n", msg.Topic()) + fmt.Printf("MSG: \n%s\n", msg.Payload()) + //fmt.Printf("* [%s] %s\n", msg.Topic(), string(msg.Payload())) + }) + */ } func Setup() { @@ -106,6 +111,36 @@ func Disconnect() { } var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) { + fmt.Printf("---------------------------------------------------\n") + fmt.Printf("Default Message Handler:\n") fmt.Printf("TOPIC: %s\n", msg.Topic()) fmt.Printf("MSG: %s\n", msg.Payload()) } + +var subscriptionHandler = func(client MQTT.Client, msg MQTT.Message) { + // DEBUG + fmt.Printf("---------------------------------------------------\n") + fmt.Printf("TOPIC: %s\n", msg.Topic()) + fmt.Printf("MSG: \n%s\n", msg.Payload()) + //fmt.Printf("* [%s] %s\n", msg.Topic(), string(msg.Payload())) + + regexpWithType := "\\/ATB\\/[A-Z]+\\/[0-9]+\\/[0-9]+\\/[0-9]+\\/[0-9]+\\/mo" + regexpDefault := "\\/ATB\\/[0-9]+\\/[0-9]+\\/[0-9]+\\/[0-9]+\\/mo" + + matchedWithType, err := regexp.MatchString(regexpWithType, msg.Topic()) + if err != nil { + log.Printf("ERROR: matchedWithType: %s", err.Error()) + } + matchedDefault, err := regexp.MatchString(regexpDefault, msg.Topic()) + if err != nil { + log.Printf("ERROR: matchedDefault: %s", err.Error()) + } + + if matchedWithType { + fmt.Printf("Topic matched regexpWithType\n") + } else if matchedDefault { + fmt.Printf("Topic matched regexpDefault\n") + } else { + log.Printf("ERROR: no matching topic: %s", msg.Topic()) + } +}