hybridgroup.gobot/platforms/mqtt/mqtt_adaptor.go

89 lines
2.1 KiB
Go
Raw Normal View History

2014-11-04 10:30:56 +08:00
package mqtt
import paho "github.com/eclipse/paho.mqtt.golang"
2014-11-04 10:30:56 +08:00
type Adaptor struct {
name string
Host string
clientID string
2016-03-23 22:58:13 +08:00
username string
password string
client paho.Client
2014-11-04 10:30:56 +08:00
}
// NewAdaptor creates a new mqtt adaptor with specified host and client id
func NewAdaptor(host string, clientID string) *Adaptor {
return &Adaptor{
Host: host,
clientID: clientID,
2014-11-04 10:56:33 +08:00
}
2014-11-04 10:30:56 +08:00
}
2016-03-23 22:58:13 +08:00
func NewAdaptorWithAuth(host, clientID, username, password string) *Adaptor {
return &Adaptor{
2016-03-23 22:58:13 +08:00
Host: host,
clientID: clientID,
username: username,
password: password,
}
}
func (a *Adaptor) Name() string { return a.name }
func (a *Adaptor) SetName(n string) { a.name = n }
2014-11-04 10:30:56 +08:00
2014-11-04 13:34:46 +08:00
// Connect returns true if connection to mqtt is established
func (a *Adaptor) Connect() (errs []error) {
a.client = paho.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())
}
return
2014-11-04 10:30:56 +08:00
}
2014-11-04 13:34:46 +08:00
// Disconnect returns true if connection to mqtt is closed
func (a *Adaptor) Disconnect() (err error) {
2014-11-04 13:34:46 +08:00
if a.client != nil {
a.client.Disconnect(500)
2014-11-04 11:47:41 +08:00
}
return
2014-11-04 10:30:56 +08:00
}
2016-07-14 00:44:47 +08:00
// Finalize returns true if connection to mqtt is finalized successfully
func (a *Adaptor) Finalize() (errs []error) {
2014-11-04 11:47:41 +08:00
a.Disconnect()
return
2014-11-04 10:30:56 +08:00
}
2014-11-05 00:41:56 +08:00
// Publish a message under a specific topic
func (a *Adaptor) Publish(topic string, message []byte) bool {
2014-11-05 00:33:05 +08:00
if a.client == nil {
return false
}
a.client.Publish(topic, 0, false, message)
2014-11-05 00:33:05 +08:00
return true
2014-11-04 10:30:56 +08:00
}
2014-11-05 00:41:56 +08:00
// Subscribe to a topic, and then call the message handler function when data is received
func (a *Adaptor) On(event string, f func(s []byte)) bool {
2014-11-05 00:33:05 +08:00
if a.client == nil {
return false
}
a.client.Subscribe(event, 0, func(client paho.Client, msg paho.Message) {
f(msg.Payload())
})
2014-11-05 00:33:05 +08:00
return true
2014-11-04 10:56:33 +08:00
}
func createClientOptions(clientId, raw, username, password string) *paho.ClientOptions {
opts := paho.NewClientOptions()
2014-11-04 15:27:21 +08:00
opts.AddBroker(raw)
opts.SetClientID(clientId)
2016-03-23 22:58:13 +08:00
if username != "" && password != "" {
opts.SetPassword(password)
opts.SetUsername(username)
}
opts.AutoReconnect = false
2014-11-04 10:56:33 +08:00
return opts
2014-11-04 10:30:56 +08:00
}