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/paho-print-sub.go
2018-04-20 09:43:56 +02:00

39 lines
877 B
Go

package main
import (
"fmt"
MQTT "github.com/eclipse/paho.mqtt.golang"
"os"
"time"
)
var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
fmt.Printf("TOPIC: %s (%s)\n", msg.Topic(), msg.MessageID())
fmt.Printf("MSG: %s\n", msg.Payload())
}
func main() {
opts := MQTT.NewClientOptions().AddBroker("tcp://localhost:1883")
opts.SetClientID("go-simple")
opts.SetCleanSession(false)
opts.SetDefaultPublishHandler(f)
c := MQTT.NewClient(opts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
if token := c.Subscribe("test/#", 0, nil); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}
time.Sleep(300 * time.Second)
if token := c.Unsubscribe("go-mqtt/sample"); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}
c.Disconnect(250)
}