1
0
mirror of https://github.com/hybridgroup/gobot.git synced 2025-05-11 19:29:20 +08:00

Merge pull request #273 from nobodyzzz/mqtt_auth

Add MQTT authentication support
This commit is contained in:
Ron Evans 2016-03-29 12:40:00 -07:00
commit d317e7c407

View File

@ -11,6 +11,8 @@ type MqttAdaptor struct {
name string
Host string
clientID string
username string
password string
client *mqtt.Client
}
@ -22,11 +24,22 @@ func NewMqttAdaptor(name string, host string, clientID string) *MqttAdaptor {
clientID: clientID,
}
}
func NewMqttAdaptorWithAuth(name, host, clientID, username, password string) *MqttAdaptor {
return &MqttAdaptor{
name: name,
Host: host,
clientID: clientID,
username: username,
password: password,
}
}
func (a *MqttAdaptor) Name() string { return a.name }
// Connect returns true if connection to mqtt is established
func (a *MqttAdaptor) Connect() (errs []error) {
a.client = mqtt.NewClient(createClientOptions(a.clientID, a.Host))
a.client = mqtt.NewClient(createClientOptions(a.clientID, a.Host, a.username, a.password))
if token := a.client.Connect(); token.Wait() && token.Error() != nil {
errs = append(errs, token.Error())
}
@ -68,10 +81,14 @@ func (a *MqttAdaptor) On(event string, f func(s []byte)) bool {
return true
}
func createClientOptions(clientId, raw string) *mqtt.ClientOptions {
func createClientOptions(clientId, raw, username, password string) *mqtt.ClientOptions {
opts := mqtt.NewClientOptions()
opts.AddBroker(raw)
opts.SetClientID(clientId)
if username != "" && password != "" {
opts.SetPassword(password)
opts.SetUsername(username)
}
opts.AutoReconnect = false
return opts
}