This repository has been archived on 2025-02-01. You can view files and clone it, but cannot push or open issues or pull requests.
esp8266-temperature/messaging-mqtt/emitter-print-sub.go
2018-04-20 09:43:56 +02:00

51 lines
1.2 KiB
Go

package main
import (
"fmt"
emitter "github.com/emitter-io/go"
"time"
)
func main() {
// Create the options with default values
o := emitter.NewClientOptions()
o.AddBroker("tcp://localhost:1883")
o.SetClientID("go-emitter-subscribe")
// Set the message handler
o.SetOnMessageHandler(func(client emitter.Emitter, msg emitter.Message) {
fmt.Printf("Received message from %s: %s\n", msg.Topic(), msg.Payload())
})
o.SetOnConnectionLostHandler(func(client emitter.Emitter, err error) {
fmt.Printf("Lost connection to broker: %s\n", err.Error())
for {
cToken := client.Connect()
if cToken.Wait() && cToken.Error() != nil {
time.Sleep(5 * time.Second)
} else {
setupSubscribe(client)
break
}
}
})
c := emitter.NewClient(o)
sToken := c.Connect()
if sToken.Wait() && sToken.Error() != nil {
panic("Error on Client.Connect(): " + sToken.Error().Error())
}
setupSubscribe(c)
time.Sleep(600* time.Second)
}
func setupSubscribe(client emitter.Emitter) {
sToken := client.Subscribe("CockozbDw5Bu3EKTJEfaJIBbj1OVGH5P", "test/")
if sToken.Wait() && sToken.Error() != nil {
panic("Error on Subscribe: " + sToken.Error().Error())
}
}