package main import ( "fmt" //import the Paho Go mqtt library mqtt "github.com/eclipse/paho.mqtt.golang" "os" "time" ) //define a function for the default message handler var f mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) { fmt.Printf("TOPIC: %s\n", msg.Topic()) fmt.Printf("MSG: %s\n", msg.Payload()) } var lck chan bool func main() { lck = make(chan bool) println(1) opts := mqtt.NewClientOptions().AddBroker("tcp://192.168.1.93:1883") opts.SetClientID("go-simple") opts.SetDefaultPublishHandler(f) println(2) c := mqtt.NewClient(opts) if token := c.Connect(); token.Wait() && token.Error() != nil { panic(token.Error()) } println(3) msgReceived := func(client mqtt.Client, message mqtt.Message) { fmt.Printf("Received message on topic: %s Message: %s\n", message.Topic(), message.Payload()) } println(4) if token := c.Subscribe("/wph_esp/pub", 0, msgReceived); token.Wait() && token.Error() != nil { fmt.Println(token.Error()) os.Exit(1) } println(5) for i := 0; i < 5; i++ { text := fmt.Sprintf("this is msg #%d!", i) token := c.Publish("/wph_esp/sub", 0, false, text) token.Wait() } <-lck time.Sleep(3 * time.Second) println(6) if token := c.Unsubscribe("/wph_esp/pub"); token.Wait() && token.Error() != nil { fmt.Println(token.Error()) os.Exit(1) } c.Disconnect(250) }