mirror of
https://github.com/hybridgroup/gobot.git
synced 2025-05-11 19:29:20 +08:00
Add a few checks and tests
This commit is contained in:
parent
33367e1af7
commit
71061cdd7f
@ -49,16 +49,24 @@ func (a *MqttAdaptor) Finalize() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (a *MqttAdaptor) Publish(topic string, message []byte) {
|
||||
func (a *MqttAdaptor) Publish(topic string, message []byte) bool {
|
||||
if a.client == nil {
|
||||
return false
|
||||
}
|
||||
m := mqtt.NewMessage(message)
|
||||
a.client.PublishMessage(topic, m)
|
||||
return true
|
||||
}
|
||||
|
||||
func (a *MqttAdaptor) On(event string, f func(s interface{})) {
|
||||
func (a *MqttAdaptor) On(event string, f func(s interface{})) bool {
|
||||
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)
|
||||
return true
|
||||
}
|
||||
|
||||
func createClientOptions(clientId, raw string) *mqtt.ClientOptions {
|
||||
|
@ -1,6 +1,7 @@
|
||||
package mqtt
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/hybridgroup/gobot"
|
||||
"testing"
|
||||
)
|
||||
@ -18,3 +19,31 @@ func TestMqttAdaptorFinalize(t *testing.T) {
|
||||
a := initTestMqttAdaptor()
|
||||
gobot.Assert(t, a.Finalize(), true)
|
||||
}
|
||||
|
||||
func TestMqttAdaptorCannotPublishUnlessConnected(t *testing.T) {
|
||||
a := initTestMqttAdaptor()
|
||||
data := []byte("o")
|
||||
gobot.Assert(t, a.Publish("test", data), false)
|
||||
}
|
||||
|
||||
func TestMqttAdaptorPublishWhenConnected(t *testing.T) {
|
||||
a := initTestMqttAdaptor()
|
||||
a.Connect()
|
||||
data := []byte("o")
|
||||
gobot.Assert(t, a.Publish("test", data), true)
|
||||
}
|
||||
|
||||
func TestMqttAdaptorCannotOnUnlessConnected(t *testing.T) {
|
||||
a := initTestMqttAdaptor()
|
||||
gobot.Assert(t, a.On("hola", func(data interface{}) {
|
||||
fmt.Println("hola")
|
||||
}), false)
|
||||
}
|
||||
|
||||
func TestMqttAdaptorOnWhenConnected(t *testing.T) {
|
||||
a := initTestMqttAdaptor()
|
||||
a.Connect()
|
||||
gobot.Assert(t, a.On("hola", func(data interface{}) {
|
||||
fmt.Println("hola")
|
||||
}), true)
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user