diff --git a/platforms/mqtt/mqtt_adaptor.go b/platforms/mqtt/mqtt_adaptor.go index 56d8021a..d9bed9a3 100644 --- a/platforms/mqtt/mqtt_adaptor.go +++ b/platforms/mqtt/mqtt_adaptor.go @@ -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 { diff --git a/platforms/mqtt/mqtt_adaptor_test.go b/platforms/mqtt/mqtt_adaptor_test.go index 132697cb..cc222ea3 100644 --- a/platforms/mqtt/mqtt_adaptor_test.go +++ b/platforms/mqtt/mqtt_adaptor_test.go @@ -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) +}