ccchatbot/mqtt/service.go

39 lines
766 B
Go
Raw Normal View History

2019-08-07 05:27:18 -05:00
package mqtt
import (
"github.com/bdlm/log"
MQTT "github.com/eclipse/paho.mqtt.golang"
)
type Service struct {
config *Config
client MQTT.Client
}
func Connect(c *Config) *Service {
if c.Broker == "" {
log.Warn("no broker given, starting without mqtt service")
return nil
}
optsPub := MQTT.NewClientOptions()
optsPub.AddBroker(c.Broker)
optsPub.SetClientID(c.ClientID)
if c.Username != "" {
optsPub.SetUsername(c.Username)
}
if c.Password != "" {
optsPub.SetPassword(c.Password)
}
clientPub := MQTT.NewClient(optsPub)
if tokenPub := clientPub.Connect(); tokenPub.Wait() && tokenPub.Error() != nil {
log.Panic(tokenPub.Error())
}
return &Service{config: c, client: clientPub}
}
func (s *Service) Close() {
s.client.Disconnect(250)
}