init.go 880 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package mqtt
  2. import (
  3. "errors"
  4. gmqtt "github.com/eclipse/paho.mqtt.golang"
  5. )
  6. var MqttCli *gmqtt.Client
  7. func Setup(addr, username, password string) error {
  8. opts := gmqtt.NewClientOptions().AddBroker(addr)
  9. opts.SetUsername(username)
  10. opts.SetPassword(password)
  11. c := gmqtt.NewClient(opts)
  12. if token := c.Connect(); token.Wait() && token.Error() != nil {
  13. return token.Error()
  14. }
  15. MqttCli = &c
  16. return nil
  17. }
  18. func Publish(c *gmqtt.Client, topic string, content []byte) error {
  19. if c == nil {
  20. return errors.New("client is nil")
  21. }
  22. client := *c
  23. token := client.Publish(topic, 1, false, content)
  24. token.Wait()
  25. return token.Error()
  26. }
  27. func Subscribe(c *gmqtt.Client, topic string, callback gmqtt.MessageHandler) error {
  28. if c == nil {
  29. return errors.New("client is nil")
  30. }
  31. client := *c
  32. token := client.Subscribe(topic, 1, callback)
  33. token.Wait()
  34. return token.Error()
  35. }