-
Notifications
You must be signed in to change notification settings - Fork 0
/
MQTTComms.go
133 lines (109 loc) · 3.34 KB
/
MQTTComms.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package main
import (
MQTT "github.com/eclipse/paho.mqtt.golang"
"github.com/dgrijalva/jwt-go"
"time"
"fmt"
"os"
"log"
"io/ioutil"
"encoding/json"
)
type MQTTComms interface {
ConnectDevice()
publishMessage(topic string, message string)
}
type SensorMessage struct {
UnitOneWaterTemp float64 `json:"unitOneWaterTemp"`
UnitTwoAmbientTemp float64 `json:"unitTwoAmbientTemp"`
PiCPUTemp float64 `json:"piCPUTemp"`
Time string `json:"time"`
}
const (
location = "asia-east1"
projectId = "selfhydro-197504"
registryId = "raspberry-pis"
deviceId = "original-hydro"
)
type mqttComms struct {
client MQTT.Client
}
const (
EVENTSTOPIC = "/devices/" + deviceId + "/events"
JWTEXPIRYINHOURS = 6
)
var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
fmt.Printf("TOPIC: %s\n", msg.Topic())
fmt.Printf("MSG: %s\n", msg.Payload())
}
func (mqtt *mqttComms) ConnectDevice() {
mqtt.authenticateDevice()
timerTillRefresh := time.NewTimer(JWTEXPIRYINHOURS * time.Hour)
go func() {
for {
<-timerTillRefresh.C
fmt.Println("Refreshing JWT Token and reconneting")
mqtt.client.Disconnect(200)
mqtt.authenticateDevice()
timerTillRefresh = time.NewTimer(JWTEXPIRYINHOURS * time.Hour)
}
}()
}
func (mqtt *mqttComms) authenticateDevice() {
tokenString, _ := createJWTToken(projectId)
opts := MQTT.NewClientOptions().AddBroker("ssl://mqtt.googleapis.com:8883")
clientId := "projects/" + projectId + "/locations/" + location + "/registries/" + registryId + "/devices/" + deviceId
opts.SetClientID(clientId)
opts.SetDefaultPublishHandler(f)
opts.SetPassword(tokenString)
opts.SetProtocolVersion(4)
opts.SetUsername("unused")
mqtt.client = MQTT.NewClient(opts)
if token := mqtt.client.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
}
func (mqtt *mqttComms) subscribeToTopic(topic string) {
if token := mqtt.client.Subscribe(topic, 0, nil); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}
}
func (mqtt *mqttComms) unsubscribeFromTopic(topic string) {
if token := mqtt.client.Unsubscribe(topic); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}
mqtt.client.Disconnect(250)
}
func (mqtt *mqttComms) publishMessage(topic string, message string) {
if mqtt.client.IsConnected() {
log.Printf("Sending: %v", message)
token := mqtt.client.Publish(topic, 0, false, message)
response := token.Wait()
log.Printf("Response: %v", response)
} else {
log.Printf("Disconnected from google cloud")
}
}
func createJWTToken(projectId string) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
"iat": time.Now().Unix(),
"exp": time.Now().Add(time.Hour * JWTEXPIRYINHOURS).Unix(),
"aud": projectId,
})
file, err := os.Open("/selfhydro/rsa_private.pem") // For read access.
if err != nil {
log.Fatal(err)
}
key, _ := ioutil.ReadFile(file.Name())
rsaPrivateKey, _ := jwt.ParseRSAPrivateKeyFromPEM(key)
tokenString, err := token.SignedString(rsaPrivateKey)
fmt.Println(tokenString, err)
return tokenString, err
}
func CreateSensorMessage(tempUnitOne float64, tempUnitTwo float64, piCPUTemp float64) (string, error) {
m := SensorMessage{tempUnitOne, tempUnitTwo, piCPUTemp, time.Now().Format("20060102150405")}
jsonMsg, err := json.Marshal(m)
return string(jsonMsg), err
}