This repository has been archived by the owner on May 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
executable file
·340 lines (292 loc) · 8.13 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
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"os"
"os/signal"
"strconv"
"time"
"github.com/gorilla/websocket"
"github.com/influxdata/influxdb1-client/v2"
)
type InfluxDBConfig struct {
Host string
Port int
Database string
}
type WebSocketConfig struct {
Host string
Port int
User string
Password string
}
type Configuration struct {
InfluxDB InfluxDBConfig
WebSocketServer WebSocketConfig
Id string
}
type CalaosJsonMsg struct {
Msg string `json:"msg"`
MsgID string `json:"msg_id"`
}
type CalaosJsonMsgLogin struct {
Msg string `json:"msg"`
Data struct {
Success string `json:"success"`
} `json:"data"`
MsgID string `json:"msg_id"`
}
type CalaosJsonMsgEvent struct {
Msg string `json:"msg"`
Data struct {
EventRaw string `json:"event_raw"`
Data struct {
ID string `json:"id"`
State string `json:"state"`
} `json:"data"`
TypeStr string `json:"type_str"`
Type string `json:"type"`
} `json:"data"`
}
type IOBase struct {
Visible string `json:"visible"`
VarType string `json:"var_type"`
ID string `json:"id"`
IoType string `json:"io_type"`
Name string `json:"name"`
Type string `json:"type"`
GuiType string `json:"gui_type"`
State string `json:"state"`
Rw string `json:"rw,omitempty"`
}
type CalaosJsonMsgHome struct {
Msg string `json:"msg"`
Data struct {
Rooms []struct {
Type string `json:"type"`
Hits string `json:"hits"`
Name string `json:"name"`
Items []IOBase `json:"items"`
} `json:"home"`
Cameras []interface{} `json:"cameras"`
Audio []interface{} `json:"audio"`
} `json:"data"`
MsgID string `json:"msg_id"`
}
var (
loggedin bool
home CalaosJsonMsgHome
configFilename string
config Configuration
ioCache = make(map[string]IOBase)
)
type VarType int
const (
VAR_STRING VarType = iota
VAR_BOOL
VAR_FLOAT
)
func (t VarType) String() string {
return [...]string{"string", "bool", "float"}[t]
}
func VarTypeFromStr(t string) VarType {
return map[string]VarType{
"string": VAR_STRING,
"bool": VAR_BOOL,
"float": VAR_FLOAT,
}[t]
}
func getNameFromId(id string) (ioName, roomName string) {
for i := range home.Data.Rooms {
for j := range home.Data.Rooms[i].Items {
if home.Data.Rooms[i].Items[j].ID == id {
return home.Data.Rooms[i].Items[j].Name, home.Data.Rooms[i].Name
}
}
}
return "", ""
}
func getVarType(id string) VarType {
return VarTypeFromStr(ioCache[id].VarType)
}
func formatStateData(id, state string) interface{} {
switch getVarType(id) {
case VAR_BOOL:
b, err := strconv.ParseBool(state)
if err != nil {
log.Printf("Failed to parse boolean state (%v) for id: %s. err = %v\n", state, id, err)
return ""
}
if b {
return 1
}
return 0
case VAR_FLOAT:
f, err := strconv.ParseFloat(state, 64)
if err != nil {
log.Printf("Failed to parse float state (%v) for id: %s. err = %v\n", state, id, err)
return ""
}
return f
}
return state
}
func main() {
flag.StringVar(&configFilename, "config", "./config.json", "Get the config to use. default value is ./config.json")
flag.Parse()
// Set up channel on which to send signal notifications.
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, os.Interrupt, os.Kill)
log.Print("Opening Configuration filename : " + configFilename)
file, err := os.Open(configFilename)
if err != nil {
log.Println("error:", err)
os.Exit(1)
}
decoder := json.NewDecoder(file)
err = decoder.Decode(&config)
if err != nil {
log.Println("error:", err)
}
loggedin = false
log.Println("Calaos: Opening :", "ws://"+config.WebSocketServer.Host+":"+strconv.Itoa(config.WebSocketServer.Port)+"/api")
websocket_client, _, err := websocket.DefaultDialer.Dial("ws://"+config.WebSocketServer.Host+":"+strconv.Itoa(config.WebSocketServer.Port)+"/api", nil)
if err != nil {
log.Fatal("dial:", err)
}
defer websocket_client.Close()
done := make(chan struct{})
log.Println("Calaos: Try login...")
msg := fmt.Sprintf(`{ "msg": "login", "data": { "cn_user": "%s", "cn_pass": "%s" } }`, config.WebSocketServer.User, config.WebSocketServer.Password)
if err = websocket_client.WriteMessage(websocket.TextMessage, []byte(msg)); err != nil {
log.Println("Write message error")
return
}
go func() {
// Create a new HTTPClient
c, err := client.NewHTTPClient(client.HTTPConfig{
Addr: fmt.Sprintf("http://%s:%d", config.InfluxDB.Host, config.InfluxDB.Port),
})
if err != nil {
log.Fatal(err)
}
// Create a new point batch
bp, err := client.NewBatchPoints(client.BatchPointsConfig{
Database: config.InfluxDB.Database,
Precision: "s",
})
if err != nil {
log.Fatal(err)
}
defer websocket_client.Close()
defer close(done)
for {
_, message, err := websocket_client.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
var msg CalaosJsonMsg
err = json.Unmarshal([]byte(message), &msg)
if err != nil {
log.Println("error:", err)
}
if msg.Msg == "login" {
var loginMsg CalaosJsonMsgLogin
err = json.Unmarshal([]byte(message), &loginMsg)
if err != nil {
log.Println("error:", err)
}
if loginMsg.Data.Success == "true" {
loggedin = true
log.Printf("Calaos: LoggedIn")
getHomeMsg := `{ "msg": "get_home" }`
if err = websocket_client.WriteMessage(websocket.TextMessage, []byte(getHomeMsg)); err != nil {
log.Println("Write message error")
return
}
} else {
loggedin = false
}
}
if loggedin {
if msg.Msg == "event" {
log.Printf("Calaos: event received")
var eventMsg CalaosJsonMsgEvent
err = json.Unmarshal([]byte(message), &eventMsg)
if err != nil {
log.Println("error:", err)
}
name, room := getNameFromId(eventMsg.Data.Data.ID)
log.Println("IO:", name, "("+room+")", "State:", eventMsg.Data.Data.State)
pointKey := fmt.Sprintf("%s - %s (%s)", eventMsg.Data.Data.ID, name, room)
fields := map[string]interface{}{
pointKey: formatStateData(eventMsg.Data.Data.ID, eventMsg.Data.Data.State),
}
pt, err := client.NewPoint(config.Id, nil, fields, time.Now())
if err != nil {
log.Fatal(err)
}
bp.AddPoint(pt)
// Write the batch
if err := c.Write(bp); err != nil {
log.Fatal(err)
}
}
if msg.Msg == "get_home" {
log.Printf("Calaos: get_home received")
err = json.Unmarshal([]byte(message), &home)
if err != nil {
log.Println("error:", err)
}
//fill cache
for i := range home.Data.Rooms {
for j := range home.Data.Rooms[i].Items {
ioCache[home.Data.Rooms[i].Items[j].ID] = home.Data.Rooms[i].Items[j]
//Add a point to initial batch
pointKey := fmt.Sprintf("%s - %s (%s)", home.Data.Rooms[i].Items[j].ID, home.Data.Rooms[i].Items[j].Name, home.Data.Rooms[i].Name)
fields := map[string]interface{}{
pointKey: formatStateData(home.Data.Rooms[i].Items[j].ID, home.Data.Rooms[i].Items[j].State),
}
pt, err := client.NewPoint(config.Id, nil, fields, time.Now())
if err != nil {
log.Fatal(err)
}
bp.AddPoint(pt)
}
}
// Write initial batch
if err := c.Write(bp); err != nil {
log.Fatal(err)
}
//In 10min send a get home again. This is needed to have value for IO that do not change that much over time. Without
//this there will be no data in graphs for a long time (could be 1 day or even more in some cases
time.AfterFunc(10*time.Minute, func() {
getHomeMsg := `{ "msg": "get_home" }`
if err = websocket_client.WriteMessage(websocket.TextMessage, []byte(getHomeMsg)); err != nil {
log.Println("Write message error")
return
}
})
}
}
}
}()
for {
select {
case <-sigc:
log.Println("interrupt")
// To cleanly close a connection, a client should send a close
// frame and wait for the server to close the connection.
err := websocket_client.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
log.Println("write close:", err)
return
}
websocket_client.Close()
return
}
}
}