@@ -11,6 +11,8 @@ type MqttAdaptor struct {
11
11
name string
12
12
Host string
13
13
clientID string
14
+ username string
15
+ password string
14
16
client * mqtt.Client
15
17
}
16
18
@@ -22,11 +24,22 @@ func NewMqttAdaptor(name string, host string, clientID string) *MqttAdaptor {
22
24
clientID : clientID ,
23
25
}
24
26
}
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
+
25
38
func (a * MqttAdaptor ) Name () string { return a .name }
26
39
27
40
// Connect returns true if connection to mqtt is established
28
41
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 ))
30
43
if token := a .client .Connect (); token .Wait () && token .Error () != nil {
31
44
errs = append (errs , token .Error ())
32
45
}
@@ -68,10 +81,14 @@ func (a *MqttAdaptor) On(event string, f func(s []byte)) bool {
68
81
return true
69
82
}
70
83
71
- func createClientOptions (clientId , raw string ) * mqtt.ClientOptions {
84
+ func createClientOptions (clientId , raw , username , password string ) * mqtt.ClientOptions {
72
85
opts := mqtt .NewClientOptions ()
73
86
opts .AddBroker (raw )
74
87
opts .SetClientID (clientId )
88
+ if username != "" && password != "" {
89
+ opts .SetPassword (password )
90
+ opts .SetUsername (username )
91
+ }
75
92
opts .AutoReconnect = false
76
93
return opts
77
94
}
0 commit comments