-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
462 lines (392 loc) · 12.8 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
package main
import (
"github.com/spf13/viper"
"github.com/spf13/cast"
"time"
"net/http"
"io/ioutil"
"encoding/json"
"github.com/boltdb/bolt"
"errors"
"strconv"
MQTT "github.com/eclipse/paho.mqtt.golang"
"regexp"
"github.com/spf13/cobra"
"github.com/op/go-logging"
)
const version = "0.1.0"
type EcoDevices struct {
Id string
Ip string
CheckEvery int
}
type EcoDevicesMeasure struct {
JsonKey string
MQTTTopicLevel string
MQTTQoS int
MQTTRetained bool
Index bool
PriceURL string
Price float64
}
type EcoDevicesResponse struct {
T1Base int `json:"T1_BASE"`
T1Papp int `json:"T1_PAPP"`
T2Base int `json:"T2_BASE"`
T2Papp int `json:"T2_PAPP"`
C1Index int `json:"INDEX_C1"`
C2Index int `json:"INDEX_C2"`
}
var allowedJSONKeys = map[string]bool{
"T1_BASE": true,
"T1_PAPP": true,
}
var RootCmd = &cobra.Command{
Use: "go-ecodevices-mqtt",
Short: "Bind your GCE Ecodevices to MQTT",
Long: `Bind your GCE Ecodevices to MQTT`,
Run: func(cmd *cobra.Command, args []string) {
initConfig()
device, err := getEcoDevices()
if (err != nil) {
log.Fatal(err)
}
log.Debugf("new ecodevices added : %s", device)
deviceMeasures, err := getEcoDevicesMeasures()
if (err != nil) {
log.Fatal(err)
}
log.Debugf("defined measures for %s : %s", device.Id, deviceMeasures)
getEcoDevicesDataRoutine(device, deviceMeasures)
},
}
var (
cfgFile string
log *logging.Logger
)
func init() {
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file")
validConfigFilenames := []string{"json", "js", "yaml", "yml", "toml", "tml"}
_ = RootCmd.PersistentFlags().SetAnnotation("config", cobra.BashCompFilenameExt, validConfigFilenames)
}
func main() {
if err := RootCmd.Execute(); err != nil {
log.Fatal(err)
}
}
func initConfig() () {
if (cfgFile) == "" {
log.Fatal("please specify a config file")
}
viper.SetConfigFile(cfgFile)
err := viper.ReadInConfig()
if err != nil {
log.Fatal(err)
}
if (viper.GetString("db.path") == "") {
log.Fatal("please specify a db path in config")
}
log = logging.MustGetLogger("ecodevices-mqtt")
format := logging.MustStringFormatter(
`%{color}%{time:2006-01-02T15:04:05.999Z-07:00} [%{level}] %{color:reset}%{message}`,
)
logging.SetFormatter(format)
switch viper.GetString("log.level") {
case "CRITICAL":
logging.SetLevel(logging.CRITICAL, "")
break
case "ERROR":
logging.SetLevel(logging.ERROR, "")
break
case "WARNING":
logging.SetLevel(logging.WARNING, "")
break
case "NOTICE":
logging.SetLevel(logging.NOTICE, "")
break
case "INFO":
logging.SetLevel(logging.INFO, "")
break
case "DEBUG":
logging.SetLevel(logging.DEBUG, "")
break
default:
logging.SetLevel(logging.NOTICE, "")
}
}
func getEcoDevicesData(device *EcoDevices) (*EcoDevicesResponse, error) {
ecoDevicesClient := http.Client{
Timeout: time.Second * 20,
}
req, err := http.NewRequest(http.MethodGet, "http://" + device.Ip + "/api/xdevices.json?cmd=10", nil)
if err != nil {
return nil, err
}
res, getErr := ecoDevicesClient.Do(req)
if getErr != nil {
return nil, getErr
}
body, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
return nil, readErr
}
var ecoDevicesResponse EcoDevicesResponse
jsonErr := json.Unmarshal(body, &ecoDevicesResponse)
if jsonErr != nil {
return nil, jsonErr
}
return &ecoDevicesResponse, nil
}
func saveIndex(device *EcoDevices, jsonKey string, index int) (error) {
db, err := bolt.Open(viper.GetString("db.path"), 0600, nil)
if err != nil {
return err
}
defer db.Close()
log.Debugf("saving current index (%d) in database for %s", index, device.Id)
db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucketIfNotExists([]byte(device.Id + "-" + jsonKey + "-indexes"))
if (err != nil) {
return err
}
err = b.Put([]byte(time.Now().Format(time.RFC3339)), []byte(cast.ToString(index)))
if (err != nil) {
return err
}
return nil
})
return nil
}
func saveIndexes(device *EcoDevices, measures []EcoDevicesMeasure, ecoDevicesResponse *EcoDevicesResponse) (error) {
for _, measure := range measures {
if (measure.Index) {
value, err := getEcoDevicesValueFromJSONKey(measure.JsonKey, ecoDevicesResponse)
if (err != nil) {
return err;
}
if (value != 0) {
err := saveIndex(device, measure.JsonKey, value)
if (err != nil) {
return err
}
}
}
}
return nil
}
func getIndexFromStartDate(device *EcoDevices, jsonKey string, startDate *time.Time) (int, error) {
var dayIndex int
bucketName := device.Id + "-" + jsonKey + "-indexes"
db, err := bolt.Open(viper.GetString("db.path"), 0600, nil)
if err != nil {
return 0, err
}
defer db.Close()
tErr := db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucketName))
if (b == nil) {
return errors.New("unable to find bucket " + bucketName)
}
c := b.Cursor()
_, startIndexStr := c.Seek([]byte(startDate.Format(time.RFC3339)));
_, currentIndexStr := c.Last();
currentIndex, err := strconv.Atoi(string(currentIndexStr))
if (err != nil) {
return err
}
startIndex, err := strconv.Atoi(string(startIndexStr))
if (err != nil) {
return err
}
dayIndex = currentIndex - startIndex
return nil
})
if (tErr != nil) {
return 0, tErr
}
return dayIndex, nil
}
func getEcoDevicesDataRoutine(device *EcoDevices, measures []EcoDevicesMeasure) {
for {
ecoDevicesResponse, err := getEcoDevicesData(device)
if (err != nil) {
log.Error(err)
}
log.Debugf("json response for %s : %s", device.Id, ecoDevicesResponse)
err = saveIndexes(device, measures, ecoDevicesResponse);
if (err != nil) {
log.Error(err)
}
err = publishOnMQTT(device, measures, ecoDevicesResponse)
if (err != nil) {
log.Error(err)
}
time.Sleep(time.Duration(device.CheckEvery) * time.Second)
}
}
func getEcoDevicesValueFromJSONKey(jsonKey string, ecoDevicesResponse *EcoDevicesResponse) (int, error) {
switch jsonKey {
case "T1_BASE":
return ecoDevicesResponse.T1Base, nil
case "T2_BASE":
return ecoDevicesResponse.T2Base, nil
case "T1_PAPP":
return ecoDevicesResponse.T1Papp, nil
case "T2_PAPP":
return ecoDevicesResponse.T2Papp, nil
case "INDEX_C1":
return ecoDevicesResponse.C1Index, nil
case "INDEX_C2":
return ecoDevicesResponse.C2Index, nil
default:
return 0, errors.New("unrecognized json key : " + jsonKey)
}
}
func getPriceFromMeasure(measure EcoDevicesMeasure) (float64, error) {
if (measure.PriceURL != "") {
electricityPriceClient := http.Client{
Timeout: time.Second * 5,
}
req, err := http.NewRequest(http.MethodGet, measure.PriceURL, nil)
if err != nil {
return 0.0, err
}
res, getErr := electricityPriceClient.Do(req)
if getErr != nil {
return 0.0, getErr
}
body, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
return 0.0, readErr
}
var re = regexp.MustCompile(`\d+\.\d*`)
for _, match := range re.FindAllString(string(body), -1) {
price, err := strconv.ParseFloat(match, 64)
if err != nil {
return 0.0, err
}
return price, nil
}
} else {
return measure.Price, nil
}
return 0.0, nil
}
func getEcoDevicesMeasures() ([]EcoDevicesMeasure, error) {
configMeasures, err := viper.Get("eco-devices-measures").([]interface{})
if (!err) {
return nil, errors.New("please specify at least one eco-devices measure in config");
}
measures := make([]EcoDevicesMeasure, len(configMeasures))
for index, table := range configMeasures {
if measure, err := table.(map[string]interface{}); err {
if (!allowedJSONKeys[cast.ToString(measure["json-key"])]) {
return nil, errors.New("please specify a valid json-key for eco-devices measure in config")
}
if (cast.ToString(measure["mqtt-topic-level"]) == "") {
return nil, errors.New("please specify an mqtt-topic-level for eco-devices measure in config");
}
measures[index] = EcoDevicesMeasure{
JsonKey: cast.ToString(measure["json-key"]),
MQTTTopicLevel: cast.ToString(measure["mqtt-topic-level"]),
MQTTQoS: cast.ToInt(measure["mqtt-qos"]),
MQTTRetained: cast.ToBool(measure["mqtt-retained"]),
Index: cast.ToBool(measure["index"]),
Price: cast.ToFloat64(measure["price"]),
PriceURL: cast.ToString(measure["price-url"]),
}
}
}
return measures, nil
}
func getEcoDevices() (*EcoDevices, error) {
if (!viper.IsSet("eco-devices")) {
return nil, errors.New("Please define an eco-devices in config")
}
if (!viper.IsSet("eco-devices.ip")) {
return nil, errors.New("Please define an ip for eco-devices in config")
}
id := "eco-devices-0"
if (viper.IsSet("eco-devices.id")) {
id = viper.GetString("eco-devices.id")
}
checkEvery := 60
if (viper.IsSet("eco-devices.check-every")) {
checkEvery = viper.GetInt("eco-devices.check-every")
}
return &EcoDevices{
Id: id,
Ip: viper.GetString("eco-devices.ip"),
CheckEvery: checkEvery,
}, nil
}
func publishOnMQTT(device *EcoDevices, measures []EcoDevicesMeasure, ecoDevicesResponse *EcoDevicesResponse) (error) {
startOfDayDate := time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.Now().Location())
startOfMonthDate := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location())
startOfYearDate := time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
opts := MQTT.NewClientOptions()
opts.AddBroker(viper.GetString("mqtt.uri"))
opts.SetClientID(viper.GetString("mqtt.client-id"))
c := MQTT.NewClient(opts)
if token := c.Connect(); token.WaitTimeout(time.Second * 5) && token.Error() != nil {
return token.Error()
}
for _, measure := range measures {
topic := viper.GetString("mqtt.topic-level") + "/" + device.Id + "/" + measure.MQTTTopicLevel
ecoDeviceValue, _ := getEcoDevicesValueFromJSONKey(measure.JsonKey, ecoDevicesResponse)
if (ecoDeviceValue != 0) {
log.Debugf("publish %s on %s", strconv.Itoa(ecoDeviceValue), topic)
token := c.Publish(topic, byte(measure.MQTTQoS), measure.MQTTRetained, strconv.Itoa(ecoDeviceValue))
token.WaitTimeout(time.Second * 5)
}
currentPrice, errPrice := getPriceFromMeasure(measure)
if (errPrice != nil) {
log.Error(errPrice)
}
if (currentPrice > 0.0) {
log.Debugf("publish %s on %s", strconv.FormatFloat(currentPrice, 'f', 3, 64), topic + "/price")
token := c.Publish(topic + "/price", byte(measure.MQTTQoS), measure.MQTTRetained, strconv.FormatFloat(currentPrice, 'f', 3, 64))
token.WaitTimeout(time.Second * 5)
}
if (measure.Index) {
savedValue, _ := getIndexFromStartDate(device, measure.JsonKey, &startOfDayDate)
log.Debugf("day index for %s is %d", device.Id, savedValue)
if (savedValue != 0) {
log.Debugf("publish %s on %s", strconv.Itoa(savedValue), topic + "/day")
token := c.Publish(topic + "/day", byte(measure.MQTTQoS), measure.MQTTRetained, strconv.Itoa(savedValue))
token.WaitTimeout(time.Second * 5)
if (currentPrice > 0.0) {
log.Debugf("publish %s on %s", strconv.FormatFloat((float64(savedValue) / float64(1000)) * currentPrice, 'f', 2, 64), topic + "/price/day")
token := c.Publish(topic + "/price/day", byte(measure.MQTTQoS), measure.MQTTRetained, strconv.FormatFloat((float64(savedValue) / float64(1000)) * currentPrice, 'f', 2, 64))
token.WaitTimeout(time.Second * 5)
}
}
savedValue, _ = getIndexFromStartDate(device, measure.JsonKey, &startOfMonthDate)
log.Debugf("month index for %s is %d", device.Id, savedValue)
if (savedValue != 0) {
log.Debugf("publish %s on %s", strconv.Itoa(savedValue), topic + "/month")
token := c.Publish(topic + "/month", byte(measure.MQTTQoS), measure.MQTTRetained, strconv.Itoa(savedValue))
token.WaitTimeout(time.Second * 5)
if (currentPrice > 0.0) {
log.Debugf("publish %s on %s", strconv.FormatFloat((float64(savedValue) / float64(1000)) * currentPrice, 'f', 2, 64), topic + "/price/month")
token := c.Publish(topic + "/price/month", byte(measure.MQTTQoS), measure.MQTTRetained, strconv.FormatFloat((float64(savedValue) / float64(1000)) * currentPrice, 'f', 2, 64))
token.WaitTimeout(time.Second * 5)
}
}
savedValue, _ = getIndexFromStartDate(device, measure.JsonKey, &startOfYearDate)
log.Debugf("year index for %s is %d", device.Id, savedValue)
if (savedValue != 0) {
log.Debugf("publish %s on %s", strconv.Itoa(savedValue), topic + "/year")
token := c.Publish(topic + "/year", byte(measure.MQTTQoS), measure.MQTTRetained, strconv.Itoa(savedValue))
token.WaitTimeout(time.Second * 5)
if (currentPrice > 0.0) {
log.Debugf("publish %s on %s", strconv.FormatFloat((float64(savedValue) / float64(1000)) * currentPrice, 'f', 2, 64), topic + "/price/year")
token := c.Publish(topic + "/price/year", byte(measure.MQTTQoS), measure.MQTTRetained, strconv.FormatFloat((float64(savedValue) / float64(1000)) * currentPrice, 'f', 2, 64))
token.WaitTimeout(time.Second * 5)
}
}
}
}
c.Disconnect(250)
return nil
}