39 lines
766 B
Go
39 lines
766 B
Go
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)
|
|
}
|