mqtt.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package main
  2. import (
  3. "fmt"
  4. //import the Paho Go mqtt library
  5. mqtt "github.com/eclipse/paho.mqtt.golang"
  6. "os"
  7. "time"
  8. )
  9. //define a function for the default message handler
  10. var f mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
  11. fmt.Printf("TOPIC: %s\n", msg.Topic())
  12. fmt.Printf("MSG: %s\n", msg.Payload())
  13. }
  14. var lck chan bool
  15. func main() {
  16. lck = make(chan bool)
  17. println(1)
  18. opts := mqtt.NewClientOptions().AddBroker("tcp://192.168.1.93:1883")
  19. opts.SetClientID("go-simple")
  20. opts.SetDefaultPublishHandler(f)
  21. println(2)
  22. c := mqtt.NewClient(opts)
  23. if token := c.Connect(); token.Wait() && token.Error() != nil {
  24. panic(token.Error())
  25. }
  26. println(3)
  27. msgReceived := func(client mqtt.Client, message mqtt.Message) {
  28. fmt.Printf("Received message on topic: %s Message: %s\n", message.Topic(), message.Payload())
  29. }
  30. println(4)
  31. if token := c.Subscribe("/wph_esp/pub", 0, msgReceived); token.Wait() && token.Error() != nil {
  32. fmt.Println(token.Error())
  33. os.Exit(1)
  34. }
  35. println(5)
  36. for i := 0; i < 5; i++ {
  37. text := fmt.Sprintf("this is msg #%d!", i)
  38. token := c.Publish("/wph_esp/sub", 0, false, text)
  39. token.Wait()
  40. }
  41. <-lck
  42. time.Sleep(3 * time.Second)
  43. println(6)
  44. if token := c.Unsubscribe("/wph_esp/pub"); token.Wait() && token.Error() != nil {
  45. fmt.Println(token.Error())
  46. os.Exit(1)
  47. }
  48. c.Disconnect(250)
  49. }