Skip to content

Commit

Permalink
mqtt: change the On() handler to take the topic as an argument.
Browse files Browse the repository at this point in the history
This allows wildcard subscriptions.

Signed-off-by: Michael Hope <[email protected]>
  • Loading branch information
nzmichaelh committed Apr 17, 2017
1 parent 1e90300 commit 58e1a6d
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 18 deletions.
14 changes: 1 addition & 13 deletions platforms/mqtt/mqtt_adaptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,19 +123,7 @@ func (a *Adaptor) Publish(topic string, message []byte) bool {
}

// On subscribes to a topic, and then calls the message handler function when data is received
func (a *Adaptor) On(event string, f func(s []byte)) bool {
if a.client == nil {
return false
}
a.client.Subscribe(event, 0, func(client paho.Client, msg paho.Message) {
f(msg.Payload())
})
return true
}

// OnTopic subscribes to a topic, and then calls the message handler
// function when data is received
func (a *Adaptor) OnTopic(event string, f func(topic string, s []byte)) bool {
func (a *Adaptor) On(event string, f func(topic string, s []byte)) bool {
if a.client == nil {
return false
}
Expand Down
4 changes: 2 additions & 2 deletions platforms/mqtt/mqtt_adaptor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,15 @@ func TestMqttAdaptorPublishWhenConnected(t *testing.T) {

func TestMqttAdaptorCannotOnUnlessConnected(t *testing.T) {
a := initTestMqttAdaptor()
gobottest.Assert(t, a.On("hola", func(data []byte) {
gobottest.Assert(t, a.On("hola", func(topic string, data []byte) {
fmt.Println("hola")
}), false)
}

func TestMqttAdaptorOnWhenConnected(t *testing.T) {
a := initTestMqttAdaptor()
a.Connect()
gobottest.Assert(t, a.On("hola", func(data []byte) {
gobottest.Assert(t, a.On("hola", func(topic string, data []byte) {
fmt.Println("hola")
}), true)
}
6 changes: 3 additions & 3 deletions platforms/mqtt/mqtt_driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,10 @@ func (m *Driver) Publish(data interface{}) bool {

// On subscribes to data updates for the current device topic,
// and then calls the message handler function when data is received
func (m *Driver) On(n string, f func(d interface{})) error {
func (m *Driver) On(n string, f func(topic string, d interface{})) error {
// TODO: also be able to subscribe to Error updates
f1 := func(s []byte) {
f(s)
f1 := func(topic string, s []byte) {
f(topic, s)
}
m.adaptor().On(m.topic, f1)
return nil
Expand Down

0 comments on commit 58e1a6d

Please sign in to comment.