Repository navigation
Expand file tree
/
Copy pathexample-driver.go
More file actions
80 lines (68 loc) · 2.42 KB
/
Copy pathexample-driver.go
File metadata and controls
80 lines (68 loc) · 2.42 KB
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
package main
import (
"encoding/json"
"fmt"
"log"
sensormanager "mf2c-sensor-manager/sensor-manager"
"os"
"strconv"
"time"
)
func main() {
sensorManagerHost, present := os.LookupEnv("SENSOR_MANAGER_HOST")
if !present {
panic(fmt.Errorf("sensor manager host not specified"))
}
sensorManagerPort, err := strconv.Atoi(os.Getenv("SENSOR_MANAGER_PORT"))
if err != nil {
panic(err)
}
sensorManagerPathSuffix, present := os.LookupEnv("SENSOR_MANAGER_PATH_SUFFIX")
if !present {
panic(fmt.Errorf("sensor manager path suffix not specified (empty is a valid value)"))
}
sensorManagerUsername, present := os.LookupEnv("SENSOR_MANAGER_USERNAME")
if !present {
panic(fmt.Errorf("sensor manager username not specified"))
}
sensorManagerPassword, present := os.LookupEnv("SENSOR_MANAGER_PASSWORD")
if !present {
panic(fmt.Errorf("sensor manager password not specified"))
}
sensorManagerTopic, present := os.LookupEnv("SENSOR_MANAGER_TOPIC")
if !present {
panic(fmt.Errorf("sensor manager topic not specified"))
}
sensorManagerConnectionInfoString := os.Getenv("SENSOR_CONNECTION_INFO")
var sensorManagerConnectionInfo map[string]interface{}
err = json.Unmarshal([]byte(sensorManagerConnectionInfoString), &sensorManagerConnectionInfo)
if err != nil {
panic(err)
}
log.Printf("Connecting to %s:%d", sensorManagerHost, sensorManagerPort)
log.Printf("Using username %s for topic %s", sensorManagerUsername, sensorManagerTopic)
log.Printf("Connection parameters: %+v", sensorManagerConnectionInfo)
mqttClient := sensormanager.ConnectMqttClient(fmt.Sprintf("ws://%s:%d%s", sensorManagerHost, sensorManagerPort, sensorManagerPathSuffix), "example-driver", sensorManagerUsername, sensorManagerPassword)
log.Print("WARNING: a successful connection does not mean writes will succeed - the MQTT server silently drops unauthorised writes!")
for i := 1; true; i++ {
reading := sensormanager.IncomingSensorMessage{
SensorId: "example-driver",
SensorType: "example-driver",
Quantity: "example-count",
Timestamp: time.Now().Format(time.RFC3339Nano),
Value: float64(i),
Unit: "times",
}
readingJson, err := json.Marshal(reading)
if err != nil {
panic(err)
}
sendtoken := mqttClient.Publish(sensorManagerTopic, 0, false, readingJson)
if sendtoken.Wait() && sendtoken.Error() != nil {
log.Print(sendtoken.Error())
} else {
log.Print("Value published.")
}
time.Sleep(1 * time.Second)
}
}