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:
commit
d317e7c407
@ -11,6 +11,8 @@ type MqttAdaptor struct {
|
|||||||
name string
|
name string
|
||||||
Host string
|
Host string
|
||||||
clientID string
|
clientID string
|
||||||
|
username string
|
||||||
|
password string
|
||||||
client *mqtt.Client
|
client *mqtt.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -22,11 +24,22 @@ func NewMqttAdaptor(name string, host string, clientID string) *MqttAdaptor {
|
|||||||
clientID: clientID,
|
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 }
|
func (a *MqttAdaptor) Name() string { return a.name }
|
||||||
|
|
||||||
// Connect returns true if connection to mqtt is established
|
// Connect returns true if connection to mqtt is established
|
||||||
func (a *MqttAdaptor) Connect() (errs []error) {
|
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 {
|
if token := a.client.Connect(); token.Wait() && token.Error() != nil {
|
||||||
errs = append(errs, token.Error())
|
errs = append(errs, token.Error())
|
||||||
}
|
}
|
||||||
@ -68,10 +81,14 @@ func (a *MqttAdaptor) On(event string, f func(s []byte)) bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func createClientOptions(clientId, raw string) *mqtt.ClientOptions {
|
func createClientOptions(clientId, raw, username, password string) *mqtt.ClientOptions {
|
||||||
opts := mqtt.NewClientOptions()
|
opts := mqtt.NewClientOptions()
|
||||||
opts.AddBroker(raw)
|
opts.AddBroker(raw)
|
||||||
opts.SetClientID(clientId)
|
opts.SetClientID(clientId)
|
||||||
|
if username != "" && password != "" {
|
||||||
|
opts.SetPassword(password)
|
||||||
|
opts.SetUsername(username)
|
||||||
|
}
|
||||||
opts.AutoReconnect = false
|
opts.AutoReconnect = false
|
||||||
return opts
|
return opts
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user