hybridgroup.gobot/platforms/mqtt/mqtt_adaptor.go

75 lines
1.6 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
"fmt"
"git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git"
"github.com/hybridgroup/gobot"
"net/url"
2014-11-04 10:30:56 +08:00
)
type MqttAdaptor struct {
2014-11-04 10:56:33 +08:00
gobot.Adaptor
Host string
2014-11-04 13:34:46 +08:00
client *mqtt.MqttClient
2014-11-04 10:30:56 +08:00
}
// NewMqttAdaptor creates a new mqtt adaptor with specified name
2014-11-04 10:56:33 +08:00
func NewMqttAdaptor(name string, host string) *MqttAdaptor {
return &MqttAdaptor{
Adaptor: *gobot.NewAdaptor(
name,
"MqttAdaptor",
),
Host: host,
}
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
2014-11-04 10:30:56 +08:00
func (a *MqttAdaptor) Connect() bool {
2014-11-04 10:56:33 +08:00
opts := createClientOptions("sub", a.Host)
2014-11-04 13:34:46 +08:00
a.client = mqtt.NewClient(opts)
a.client.Start()
2014-11-04 10:56:33 +08:00
return true
2014-11-04 10:30:56 +08:00
}
2014-11-04 13:34:46 +08:00
// Reconnect retries connection to mqtt. Returns true if successful
2014-11-04 10:30:56 +08:00
func (a *MqttAdaptor) Reconnect() bool {
2014-11-04 10:56:33 +08:00
return true
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
2014-11-04 10:30:56 +08:00
func (a *MqttAdaptor) Disconnect() bool {
2014-11-04 13:34:46 +08:00
if a.client != nil {
a.client.Disconnect(500)
2014-11-04 11:47:41 +08:00
}
2014-11-04 10:56:33 +08:00
return true
2014-11-04 10:30:56 +08:00
}
// Finalize returns true if connection to mqtt is finalized succesfully
func (a *MqttAdaptor) Finalize() bool {
2014-11-04 11:47:41 +08:00
a.Disconnect()
2014-11-04 10:56:33 +08:00
return true
2014-11-04 10:30:56 +08:00
}
2014-11-04 10:56:33 +08:00
func (a *MqttAdaptor) Publish(topic string, message []byte) int {
2014-11-04 13:34:46 +08:00
m := mqtt.NewMessage(message)
a.client.PublishMessage(topic, m)
2014-11-04 10:56:33 +08:00
return 0
2014-11-04 10:30:56 +08:00
}
func (a *MqttAdaptor) On(event string, f func(s interface{})) {
t, _ := mqtt.NewTopicFilter(event, 0)
a.client.StartSubscription(func(client *mqtt.MqttClient, msg mqtt.Message) {
f(msg.Payload())
}, t)
2014-11-04 10:56:33 +08:00
}
func createClientOptions(clientId, raw string) *mqtt.ClientOptions {
uri, _ := url.Parse(raw)
opts := mqtt.NewClientOptions()
opts.AddBroker(fmt.Sprintf("tcp://%s", uri.Host))
opts.SetClientId(clientId)
return opts
2014-11-04 10:30:56 +08:00
}