This repository has been archived by the owner on Feb 19, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmqtt.go
60 lines (52 loc) · 1.51 KB
/
mqtt.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
59
60
package main
import (
"encoding/json"
"fmt"
MQTT "git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git"
"github.com/thethingsnetwork/server-shared"
"log"
"os"
)
type MqttConsumer struct {
client *MQTT.Client
}
func ConnectPaho() (PacketHandler, error) {
uri := os.Getenv("MQTT_BROKER")
opts := MQTT.NewClientOptions().AddBroker(uri)
opts.SetClientID("jolie")
c := MQTT.NewClient(opts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
return nil, token.Error()
}
log.Printf("Connected to %s", uri)
return &MqttConsumer{c}, nil
}
func (c *MqttConsumer) Configure() error {
return nil
}
func (c *MqttConsumer) HandleStatus(status *shared.GatewayStatus) {
buffer, err := json.Marshal(status)
if err != nil {
log.Printf("Failed to serialize gateway status: %s", err.Error())
}
topic := fmt.Sprintf("gateways/%s/status", status.Eui)
token := c.client.Publish(topic, 0, false, buffer)
token.Wait()
if token.Error() != nil {
log.Printf("Failed to publish status: %s", token.Error())
}
log.Printf("Published gateway status to topic %s", topic)
}
func (c *MqttConsumer) HandlePacket(packet *shared.RxPacket) {
buffer, err := json.Marshal(packet)
if err != nil {
log.Printf("Failed to serialize packet: %s", err.Error())
}
topic := fmt.Sprintf("nodes/%s/packets", packet.NodeEui)
token := c.client.Publish(topic, 0, false, buffer)
token.Wait()
if token.Error() != nil {
log.Printf("Failed to publish packet: %s", token.Error())
}
log.Printf("Published packet to topic %s", topic)
}