From a3051c0fcfb267a4561147b5c757d911a1bc9337 Mon Sep 17 00:00:00 2001 From: Stas Turlo Date: Wed, 23 Mar 2016 17:58:13 +0300 Subject: [PATCH] Add MQTT authentication support --- platforms/mqtt/mqtt_adaptor.go | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/platforms/mqtt/mqtt_adaptor.go b/platforms/mqtt/mqtt_adaptor.go index 5fa3c63d..e22a5f56 100644 --- a/platforms/mqtt/mqtt_adaptor.go +++ b/platforms/mqtt/mqtt_adaptor.go @@ -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 }