package mqtt import ( "errors" gmqtt "github.com/eclipse/paho.mqtt.golang" ) var MqttCli *gmqtt.Client func Setup(addr, username, password string) error { opts := gmqtt.NewClientOptions().AddBroker(addr) opts.SetUsername(username) opts.SetPassword(password) c := gmqtt.NewClient(opts) if token := c.Connect(); token.Wait() && token.Error() != nil { return token.Error() } MqttCli = &c return nil } func Publish(c *gmqtt.Client, topic string, content []byte) error { if c == nil { return errors.New("client is nil") } client := *c token := client.Publish(topic, 1, false, content) token.Wait() return token.Error() } func Subscribe(c *gmqtt.Client, topic string, callback gmqtt.MessageHandler) error { if c == nil { return errors.New("client is nil") } client := *c token := client.Subscribe(topic, 1, callback) token.Wait() return token.Error() }