-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
112 lines (86 loc) · 2.39 KB
/
main.go
File metadata and controls
112 lines (86 loc) · 2.39 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
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
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"github.com/fagnercarvalho/docker-rtl-433-mqtt/mqtt"
)
type Sensor struct {
Id any `json:"id"`
// Outdoor temperature/humidity sensor
Temperature float32 `json:"temperature_C"`
Humidity float32 `json:"humidity"`
// Soil moisture sensor
Moisture float32 `json:"moisture"`
}
func (s Sensor) IDAsString() string {
return fmt.Sprint(s.Id)
}
var (
outdoorSensor = "11455"
soilSensor = "0dff63"
)
func main() {
mqttHost := os.Getenv("MQTT_HOST")
mqttPort := os.Getenv("MQTT_PORT")
client, err := mqtt.NewClient[Sensor](mqttHost, mqttPort)
if err != nil {
panic(err)
}
fmt.Println("Get antenna stream")
stdoutPipe := getAntennaStream()
fmt.Println("Reading from stream")
readFromStream(stdoutPipe, client.PublishMessage)
}
func readFromStream(stdoutPipe io.ReadCloser, publicMqttMessage func(topic string, sensor Sensor) (<-chan error, error)) {
scanner := bufio.NewScanner(stdoutPipe)
for scanner.Scan() {
sensorLine := scanner.Text()
fmt.Printf("Read sensor from 433 mhz: %v \n", sensorLine)
var sensor Sensor
err := json.Unmarshal([]byte(sensorLine), &sensor)
if err != nil {
fmt.Printf("Error when trying to unmarshal sensor: %v: %v \n", sensorLine, err)
continue
}
isValid := isValidSensor(sensor.IDAsString())
if !isValid {
fmt.Printf("Sensor %v is not valid, skipping \n", sensor.Id)
continue
}
topic := getTopicBySensorID(sensor.IDAsString())
_, err = publicMqttMessage(topic, sensor)
if err != nil {
fmt.Printf("Error when trying to publish message: %v: %v \n", sensor, err)
}
}
}
func getAntennaStream() io.ReadCloser {
// get telemetry from RTL 433 and send to MQTT
cmd := exec.Command("rtl_433", "-F", "json")
stdoutPipe, err := cmd.StdoutPipe()
if err != nil {
panic(err)
}
if err := cmd.Start(); err != nil {
panic(err)
}
return stdoutPipe
}
func isValidSensor(sensorID string) bool {
return sensorID == outdoorSensor || sensorID == soilSensor
}
// getTopicBySensorID returns the correct MQTT topic to redirect the sensor data by the sensor ID
// 15909 and 0dff63 are the device IDs for the sensors we are getting the telemetry, change to your IDs
func getTopicBySensorID(id string) string {
switch id {
case outdoorSensor:
return "homeassistant/sensor/balcony/state"
case soilSensor:
return "homeassistant/sensor/soil/state"
}
return ""
}