1
0
mirror of https://github.com/hybridgroup/gobot.git synced 2025-04-29 13:49:14 +08:00
hybridgroup.gobot/platforms/mqtt/mqtt_adaptor.go

78 lines
1.8 KiB
Go
Raw Normal View History

2014-11-03 18:30:56 -08:00
package mqtt
import (
2014-11-03 18:56:33 -08:00
"git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git"
"github.com/hybridgroup/gobot"
2014-11-03 18:30:56 -08:00
)
var _ gobot.Adaptor = (*MqttAdaptor)(nil)
2014-11-03 18:30:56 -08:00
type MqttAdaptor struct {
name string
Host string
clientID string
client *mqtt.MqttClient
2014-11-03 18:30:56 -08:00
}
// NewMqttAdaptor creates a new mqtt adaptor with specified name, host and client id
func NewMqttAdaptor(name string, host string, clientID string) *MqttAdaptor {
2014-11-03 18:56:33 -08:00
return &MqttAdaptor{
name: name,
Host: host,
clientID: clientID,
2014-11-03 18:56:33 -08:00
}
2014-11-03 18:30:56 -08:00
}
func (a *MqttAdaptor) Name() string { return a.name }
2014-11-03 18:30:56 -08:00
2014-11-03 21:34:46 -08:00
// Connect returns true if connection to mqtt is established
func (a *MqttAdaptor) Connect() (errs []error) {
opts := createClientOptions(a.clientID, a.Host)
2014-11-03 21:34:46 -08:00
a.client = mqtt.NewClient(opts)
a.client.Start()
return
2014-11-03 18:30:56 -08:00
}
2014-11-03 21:34:46 -08:00
// Disconnect returns true if connection to mqtt is closed
func (a *MqttAdaptor) Disconnect() (err error) {
2014-11-03 21:34:46 -08:00
if a.client != nil {
a.client.Disconnect(500)
2014-11-03 19:47:41 -08:00
}
return
2014-11-03 18:30:56 -08:00
}
// Finalize returns true if connection to mqtt is finalized succesfully
func (a *MqttAdaptor) Finalize() (errs []error) {
2014-11-03 19:47:41 -08:00
a.Disconnect()
return
2014-11-03 18:30:56 -08:00
}
2014-11-04 08:41:56 -08:00
// Publish a message under a specific topic
2014-11-04 08:33:05 -08:00
func (a *MqttAdaptor) Publish(topic string, message []byte) bool {
if a.client == nil {
return false
}
2014-11-03 21:34:46 -08:00
m := mqtt.NewMessage(message)
a.client.PublishMessage(topic, m)
2014-11-04 08:33:05 -08:00
return true
2014-11-03 18:30:56 -08:00
}
2014-11-04 08:41:56 -08:00
// Subscribe to a topic, and then call the message handler function when data is received
func (a *MqttAdaptor) On(event string, f func(s []byte)) bool {
2014-11-04 08:33:05 -08:00
if a.client == nil {
return false
}
t, _ := mqtt.NewTopicFilter(event, 0)
a.client.StartSubscription(func(client *mqtt.MqttClient, msg mqtt.Message) {
f(msg.Payload())
}, t)
2014-11-04 08:33:05 -08:00
return true
2014-11-03 18:56:33 -08:00
}
func createClientOptions(clientId, raw string) *mqtt.ClientOptions {
opts := mqtt.NewClientOptions()
2014-11-03 23:27:21 -08:00
opts.AddBroker(raw)
2014-11-03 18:56:33 -08:00
opts.SetClientId(clientId)
return opts
2014-11-03 18:30:56 -08:00
}