-
Notifications
You must be signed in to change notification settings - Fork 13
/
sub.go
58 lines (48 loc) · 1.31 KB
/
sub.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package mqtt
// LoraSubscribe subscribe to lora server messages
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/MainfluxLabs/mainflux/logger"
"github.com/MainfluxLabs/mainflux/lora"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
// Subscriber represents the MQTT broker.
type Subscriber interface {
// Subscribes to given subject and receives events.
Subscribe(string) error
}
type broker struct {
svc lora.Service
client mqtt.Client
logger logger.Logger
timeout time.Duration
}
// NewBroker returns new MQTT broker instance.
func NewBroker(svc lora.Service, client mqtt.Client, t time.Duration, log logger.Logger) Subscriber {
return broker{
svc: svc,
client: client,
logger: log,
timeout: t,
}
}
// Subscribe subscribes to the Lora MQTT message broker
func (b broker) Subscribe(subject string) error {
s := b.client.Subscribe(subject, 0, b.handleMsg)
if err := s.Error(); s.WaitTimeout(b.timeout) && err != nil {
return err
}
return nil
}
// handleMsg triggered when new message is received on Lora MQTT broker
func (b broker) handleMsg(c mqtt.Client, msg mqtt.Message) {
m := lora.Message{}
if err := json.Unmarshal(msg.Payload(), &m); err != nil {
b.logger.Warn(fmt.Sprintf("Failed to unmarshal message: %s", err.Error()))
return
}
b.svc.Publish(context.Background(), m)
}