/
main.go
337 lines (278 loc) · 10 KB
/
main.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
package main
import (
"bufio"
"context"
"encoding/json"
"io"
"io/ioutil"
"os"
"runtime"
"strings"
"sync"
"time"
"github.com/alecthomas/kingpin"
"github.com/ericchiang/k8s"
corev1 "github.com/ericchiang/k8s/apis/core/v1"
foundation "github.com/estafette/estafette-foundation"
"github.com/jacobsa/go-serial/serial"
"github.com/rs/zerolog/log"
)
var (
// set when building the application
appgroup string
app string
version string
branch string
revision string
buildDate string
goVersion = runtime.Version()
// application specific config
stateFilePath = kingpin.Flag("state-file-path", "Path to file with state.").Default("/state/state.json").OverrideDefaultFromEnvar("STATE_FILE_PATH").String()
stateFileConfigMapName = kingpin.Flag("state-file-configmap-name", "Name of the configmap with state file.").Default("evohome-hgi80-listener-state").OverrideDefaultFromEnvar("STATE_FILE_CONFIG_MAP_NAME").String()
hgiDevicePath = kingpin.Flag("hgi-device-path", "Path to usb device connecting HGI80.").Default("/dev/ttyUSB0").OverrideDefaultFromEnvar("HGI_DEVICE_PATH").String()
evohomeID = kingpin.Flag("evohome-id", "ID of the Evohome Touch device").Envar("EVOHOME_ID").Required().String()
namespace = kingpin.Flag("namespace", "Namespace the pod runs in.").Envar("NAMESPACE").Required().String()
bigqueryEnable = kingpin.Flag("bigquery-enable", "Toggle to enable or disable bigquery integration").Default("true").OverrideDefaultFromEnvar("BQ_ENABLE").Bool()
bigqueryProjectID = kingpin.Flag("bigquery-project-id", "Google Cloud project id that contains the BigQuery dataset").Envar("BQ_PROJECT_ID").Required().String()
bigqueryDataset = kingpin.Flag("bigquery-dataset", "Name of the BigQuery dataset").Envar("BQ_DATASET").Required().String()
bigqueryTable = kingpin.Flag("bigquery-table", "Name of the BigQuery table").Envar("BQ_TABLE").Required().String()
zoneInfoMap map[int64]ZoneInfo
lastReceivedMessage = time.Now().UTC()
)
func main() {
// parse command line parameters
kingpin.Parse()
// init log format from envvar ESTAFETTE_LOG_FORMAT
foundation.InitLoggingFromEnv(foundation.NewApplicationInfo(appgroup, app, version, branch, revision, buildDate))
bigqueryClient, err := NewBigQueryClient(*bigqueryProjectID, *bigqueryEnable)
if err != nil {
log.Fatal().Err(err).Msg("Failed creating bigquery client")
}
// create kubernetes api client
kubeClient, err := k8s.NewInClusterClient()
if err != nil {
log.Fatal().Err(err).Msg("Failed creating Kubernetes API client")
}
// create command buffer and message processor
commandQueue := make(chan Command, 100)
messageProcessor := NewMessageProcessor(*evohomeID, bigqueryClient, commandQueue)
initBigqueryTable(bigqueryClient)
readStateFromStateFile()
log.Info().Msgf("Listening to serial usb device at %v for messages from evohome touch device with id %v...", *hgiDevicePath, *evohomeID)
f, in := openSerialPort()
defer closeSerialPort(f)
// request zone names from controller approx once every 15 minutes to be able to store measurements with zone name and pick up changes / new zones
go func() {
for {
for i := 0; i < 12; i++ {
log.Info().Msgf("Queueing zone_name command for zone %v", i)
commandQueue <- Command{
messageType: "RQ",
commandName: "zone_name",
destinationID: *evohomeID,
payload: &DefaultPayload{
Values: []int{i, 0},
},
}
}
for i := 0; i < 12; i++ {
log.Info().Msgf("Queueing zone_info command for zone %v", i)
commandQueue <- Command{
messageType: "RQ",
commandName: "zone_info",
destinationID: *evohomeID,
payload: &DefaultPayload{
Values: []int{i},
},
}
}
time.Sleep(time.Duration(applyJitter(900)) * time.Second)
}
}()
// write state to configmap approx every minute to be used by the evohome-bigquery-exporter and on restarts of evohome-hgi80-listener
go func() {
for {
time.Sleep(time.Duration(applyJitterWithPercentage(60, 5)) * time.Second)
writeStateToConfigmap(kubeClient)
}
}()
// safety net for serial port falling asleep
waitGroup := &sync.WaitGroup{}
go func(waitGroup *sync.WaitGroup) {
for {
time.Sleep(time.Duration(applyJitter(120)) * time.Second)
if time.Since(lastReceivedMessage).Minutes() > 2 {
log.Info().Msg("Received last message more than 2 minutes ago, resetting serial port...")
waitGroup.Add(1)
closeSerialPort(f)
f, in = openSerialPort()
defer closeSerialPort(f)
waitGroup.Done()
}
}
}(waitGroup)
// // test various commands to see their response
// log.Info().Msg("Queueing heartbeat / sysinfo command")
// commandQueue <- Command{
// messageType: "RQ",
// commandName: "heartbeat", // sysinfo
// destinationID: *evohomeID,
// payload: &DefaultPayload{
// Values: []int{0},
// },
// }
// log.Info().Msg("Queueing controller_mode command")
// commandQueue <- Command{
// messageType: "RQ",
// commandName: "controller_mode",
// destinationID: *evohomeID,
// payload: &DefaultPayload{
// Values: []int{255},
// },
// }
// log.Info().Msg("Queueing device_info command for device 0")
// commandQueue <- Command{
// messageType: "RQ",
// commandName: "device_info",
// destinationID: *evohomeID,
// payload: &DefaultPayload{
// Values: []int{0, 0, 0},
// },
// }
// execute commands and read from serial port
for {
// wait for serial port reset to finish before continuing
waitGroup.Wait()
// check if there's any commands to send
select {
case command := <-commandQueue:
messageProcessor.SendCommand(f, command)
default:
}
// read from serial port
buf, isPrefix, err := in.ReadLine()
if err != nil {
if err != io.EOF {
log.Warn().Err(err).Msg("Error reading from serial port, resetting port...")
// wait for serial port reset to finish before continuing
waitGroup.Wait()
closeSerialPort(f)
f, in = openSerialPort()
defer closeSerialPort(f)
}
} else if isPrefix {
log.Warn().Str("_msg", string(buf)).Msgf("Message is too long for buffer and split over multiple lines")
} else {
rawmsg := string(buf)
length := len(rawmsg)
// make sure no obvious errors in getting the data....
if length > 40 &&
!strings.Contains(rawmsg, "_ENC") &&
!strings.Contains(rawmsg, "_BAD") &&
!strings.Contains(rawmsg, "BAD") &&
!strings.Contains(rawmsg, "ERR") {
lastReceivedMessage = time.Now().UTC()
isValidMessage, err := messageProcessor.IsValidMessage(rawmsg)
if err != nil {
log.Warn().Err(err).
Str("_msg", rawmsg).
Msg("Message is not valid")
}
if isValidMessage {
message := messageProcessor.DecodeMessage(rawmsg)
messageProcessor.ProcessMessage(message)
}
} else {
log.Debug().Msgf("unknown: %v", rawmsg)
}
}
}
}
func readStateFromStateFile() {
zoneInfoMap = map[int64]ZoneInfo{
252: ZoneInfo{
ID: 252,
Name: "Opentherm",
},
}
// check if state file exists in configmap
var state State
if _, err := os.Stat(*stateFilePath); !os.IsNotExist(err) {
log.Info().Msgf("File %v exists, reading contents...", *stateFilePath)
// read state file
data, err := ioutil.ReadFile(*stateFilePath)
if err != nil {
log.Fatal().Err(err).Msgf("Failed reading file from path %v", *stateFilePath)
}
log.Info().Msgf("Unmarshalling file %v contents...", *stateFilePath)
// unmarshal state file
if err := json.Unmarshal(data, &state); err != nil {
log.Fatal().Err(err).Interface("data", data).Msg("Failed unmarshalling state")
}
zoneInfoMap = state.ZoneInfoMap
}
}
func writeStateToConfigmap(kubeClient *k8s.Client) {
// retrieve configmap
var configMap corev1.ConfigMap
err := kubeClient.Get(context.Background(), *namespace, *stateFileConfigMapName, &configMap)
if err != nil {
log.Error().Err(err).Msgf("Failed retrieving configmap %v", *stateFileConfigMapName)
}
// marshal state to json
state := State{
ZoneInfoMap: zoneInfoMap,
LastUpdated: time.Now().UTC(),
}
stateData, err := json.Marshal(state)
if configMap.Data == nil {
configMap.Data = make(map[string]string)
}
configMap.Data["state.json"] = string(stateData)
// update configmap to have state available when the application runs the next time and for other applications
err = kubeClient.Update(context.Background(), &configMap)
if err != nil {
log.Fatal().Err(err).Msgf("Failed updating configmap %v", *stateFileConfigMapName)
}
log.Info().Msgf("Stored state in configmap %v...", *stateFileConfigMapName)
}
func initBigqueryTable(bigqueryClient BigQueryClient) {
log.Debug().Msgf("Checking if table %v.%v.%v exists...", *bigqueryProjectID, *bigqueryDataset, *bigqueryTable)
tableExist := bigqueryClient.CheckIfTableExists(*bigqueryDataset, *bigqueryTable)
if !tableExist {
log.Debug().Msgf("Creating table %v.%v.%v...", *bigqueryProjectID, *bigqueryDataset, *bigqueryTable)
err := bigqueryClient.CreateTable(*bigqueryDataset, *bigqueryTable, BigQueryMeasurement{}, "inserted_at", true)
if err != nil {
log.Fatal().Err(err).Msg("Failed creating bigquery table")
}
} else {
log.Debug().Msgf("Trying to update table %v.%v.%v schema...", *bigqueryProjectID, *bigqueryDataset, *bigqueryTable)
err := bigqueryClient.UpdateTableSchema(*bigqueryDataset, *bigqueryTable, BigQueryMeasurement{})
if err != nil {
log.Fatal().Err(err).Msg("Failed updating bigquery table schema")
}
}
}
func openSerialPort() (io.ReadWriteCloser, *bufio.Reader) {
options := serial.OpenOptions{
PortName: *hgiDevicePath,
BaudRate: 115200,
DataBits: 8,
StopBits: 1,
MinimumReadSize: 0,
InterCharacterTimeout: 2000,
ParityMode: serial.PARITY_NONE,
Rs485Enable: false,
Rs485RtsHighDuringSend: false,
Rs485RtsHighAfterSend: false,
}
f, err := serial.Open(options)
if err != nil {
log.Fatal().Err(err).Interface("options", options).Msg("Failed opening serial device")
}
return f, bufio.NewReader(f)
}
func closeSerialPort(f io.ReadWriteCloser) {
f.Close()
time.Sleep(5 * time.Second)
}