Update MQTT message handling

- use separate handler
- use regexpression for topic check
This commit is contained in:
Siegfried Siegert 2020-08-30 21:08:50 +02:00
parent daa79b27ca
commit 231c17d7c3

View File

@ -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())
}
}