hybridgroup.gobot/platforms/mqtt/mqtt_adaptor.go

80 lines
1.8 KiB
Go
Raw Normal View History

2014-11-04 10:30:56 +08:00
package mqtt
import (
2014-11-04 10:56:33 +08:00
"git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git"
"github.com/hybridgroup/gobot"
2014-11-04 10:30:56 +08:00
)
var _ gobot.AdaptorInterface = (*MqttAdaptor)(nil)
2014-11-04 10:30:56 +08:00
type MqttAdaptor struct {
2014-11-04 10:56:33 +08:00
gobot.Adaptor
Host string
clientID string
client *mqtt.MqttClient
2014-11-04 10: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-04 10:56:33 +08:00
return &MqttAdaptor{
Adaptor: *gobot.NewAdaptor(
name,
"MqttAdaptor",
),
Host: host,
clientID: clientID,
2014-11-04 10:56:33 +08:00
}
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 *MqttAdaptor) Connect() error {
opts := createClientOptions(a.clientID, a.Host)
2014-11-04 13:34:46 +08:00
a.client = mqtt.NewClient(opts)
a.client.Start()
return nil
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 *MqttAdaptor) Disconnect() 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 nil
2014-11-04 10:30:56 +08:00
}
// Finalize returns true if connection to mqtt is finalized succesfully
func (a *MqttAdaptor) Finalize() error {
2014-11-04 11:47:41 +08:00
a.Disconnect()
return nil
2014-11-04 10:30:56 +08:00
}
2014-11-05 00:41:56 +08:00
// Publish a message under a specific topic
2014-11-05 00:33:05 +08:00
func (a *MqttAdaptor) Publish(topic string, message []byte) bool {
if a.client == nil {
return false
}
2014-11-04 13:34:46 +08:00
m := mqtt.NewMessage(message)
a.client.PublishMessage(topic, m)
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 *MqttAdaptor) On(event string, f func(s []byte)) bool {
2014-11-05 00: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-05 00:33:05 +08:00
return true
2014-11-04 10:56:33 +08:00
}
func createClientOptions(clientId, raw string) *mqtt.ClientOptions {
opts := mqtt.NewClientOptions()
2014-11-04 15:27:21 +08:00
opts.AddBroker(raw)
2014-11-04 10:56:33 +08:00
opts.SetClientId(clientId)
return opts
2014-11-04 10:30:56 +08:00
}