Skip to content

Commit a3051c0

Browse files
author
Stas Turlo
committed
Add MQTT authentication support
1 parent d84d028 commit a3051c0

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

platforms/mqtt/mqtt_adaptor.go

+19-2
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ type MqttAdaptor struct {
1111
name string
1212
Host string
1313
clientID string
14+
username string
15+
password string
1416
client *mqtt.Client
1517
}
1618

@@ -22,11 +24,22 @@ func NewMqttAdaptor(name string, host string, clientID string) *MqttAdaptor {
2224
clientID: clientID,
2325
}
2426
}
27+
28+
func NewMqttAdaptorWithAuth(name, host, clientID, username, password string) *MqttAdaptor {
29+
return &MqttAdaptor{
30+
name: name,
31+
Host: host,
32+
clientID: clientID,
33+
username: username,
34+
password: password,
35+
}
36+
}
37+
2538
func (a *MqttAdaptor) Name() string { return a.name }
2639

2740
// Connect returns true if connection to mqtt is established
2841
func (a *MqttAdaptor) Connect() (errs []error) {
29-
a.client = mqtt.NewClient(createClientOptions(a.clientID, a.Host))
42+
a.client = mqtt.NewClient(createClientOptions(a.clientID, a.Host, a.username, a.password))
3043
if token := a.client.Connect(); token.Wait() && token.Error() != nil {
3144
errs = append(errs, token.Error())
3245
}
@@ -68,10 +81,14 @@ func (a *MqttAdaptor) On(event string, f func(s []byte)) bool {
6881
return true
6982
}
7083

71-
func createClientOptions(clientId, raw string) *mqtt.ClientOptions {
84+
func createClientOptions(clientId, raw, username, password string) *mqtt.ClientOptions {
7285
opts := mqtt.NewClientOptions()
7386
opts.AddBroker(raw)
7487
opts.SetClientID(clientId)
88+
if username != "" && password != "" {
89+
opts.SetPassword(password)
90+
opts.SetUsername(username)
91+
}
7592
opts.AutoReconnect = false
7693
return opts
7794
}

0 commit comments

Comments
 (0)