mqtt: add Subscribe method; server subscribes and logs incoming messages
This commit is contained in:
@@ -64,6 +64,24 @@ func (c *Client) Publish(topic string, payload []byte) error {
|
||||
return token.Error()
|
||||
}
|
||||
|
||||
// Subscribe subscribes to the given topic and calls the provided handler
|
||||
// for each incoming message.
|
||||
func (c *Client) Subscribe(topic string, handler func(topic string, payload []byte)) error {
|
||||
if c == nil || c.client == nil {
|
||||
return fmt.Errorf("mqtt client not connected")
|
||||
}
|
||||
mh := func(cli paho.Client, msg paho.Message) {
|
||||
if handler != nil {
|
||||
handler(msg.Topic(), msg.Payload())
|
||||
}
|
||||
}
|
||||
token := c.client.Subscribe(topic, 0, mh)
|
||||
if ok := token.WaitTimeout(5 * time.Second); !ok {
|
||||
return fmt.Errorf("subscribe timeout")
|
||||
}
|
||||
return token.Error()
|
||||
}
|
||||
|
||||
func (c *Client) Close() {
|
||||
if c == nil || c.client == nil {
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user