forked from calaos/calaos-homekit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
executable file
·366 lines (315 loc) · 8.44 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
package main
import (
"context"
"encoding/json"
"flag"
"os"
"os/signal"
"strconv"
"syscall"
"github.com/brutella/hap"
"github.com/brutella/hap/accessory"
"github.com/gorilla/websocket"
"github.com/vcaesar/murmur"
log "github.com/sirupsen/logrus"
)
type WebSocketConfig struct {
Host string
Port int
User string
Password string
}
type Configuration struct {
WebSocketServer WebSocketConfig
PinCode string
BridgeName 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 CalaosIO 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"`
IoStyle string `json:"io_style,omitempty"`
}
type CalaosHome struct {
Type string `json:"type"`
Hits string `json:"hits"`
Name string `json:"name"`
IOs []CalaosIO `json:"items"`
}
type CalaosJsonMsgHome struct {
Msg string `json:"msg"`
Data struct {
Home []CalaosHome `json:"home"`
Cameras []interface{} `json:"cameras"`
Audio []interface{} `json:"audio"`
} `json:"data"`
MsgID string `json:"msg_id"`
}
type CalaosJsonSetState struct {
Msg string `json:"msg"`
MsgID string `json:"msg_id"`
Data struct {
Id string `json:"id"`
Value string `json:"value"`
} `json:"data"`
}
var loggedin bool
var home CalaosJsonMsgHome
var configFilename string
var config Configuration
var accessories map[uint64]CalaosAccessory
//var hapIOs []HapIO
var calaosIOs []CalaosIO
var websocketClient *WebSocketClient
func getIOFromId(id string) *CalaosIO {
for i := range home.Data.Home {
for j := range home.Data.Home[i].IOs {
if home.Data.Home[i].IOs[j].ID == id {
return &home.Data.Home[i].IOs[j]
}
}
}
return nil
}
func getNameFromId(id string) string {
for i := range home.Data.Home {
for j := range home.Data.Home[i].IOs {
if home.Data.Home[i].IOs[j].ID == id {
return home.Data.Home[i].IOs[j].Name
}
}
}
return ""
}
func setupCalaosHome() {
for i := range home.Data.Home {
for j := range home.Data.Home[i].IOs {
cio := home.Data.Home[i].IOs[j]
var acc CalaosAccessory
id := uint64(murmur.Sum32(cio.ID))
if cio.Visible != "false" {
switch cio.GuiType {
case "temp":
acc = NewTemperatureSensor(cio, id)
case "analog_in":
if cio.IoStyle == "humidity" {
acc = NewHumiditySensor(cio, id)
}
case "light_dimmer":
acc = NewLightDimmer(cio, id)
case "light":
if cio.IoStyle == "" {
acc = NewLightDimmer(cio, id)
}
//TODO:
// case "shutter":
// acc = NewWindowCovering(cio, id)
case "shutter_smart":
acc = NewSmartShutter(cio, id)
}
if acc != nil {
accessories[id] = acc
}
}
}
}
}
func CalaosUpdate(cio CalaosIO) {
msg := CalaosJsonSetState{}
msg.MsgID = "user_cmd"
msg.Msg = "set_state"
msg.Data.Id = cio.ID
msg.Data.Value = cio.State
str, _ := json.Marshal(msg)
if err := websocketClient.WriteMessage(websocket.TextMessage, []byte(str)); err != nil {
log.Error("Write message error")
return
}
}
func connectedCb(ctx context.Context) {
done := make(chan struct{})
// Send login message through Calaos websocket API
msg := "{ \"msg\": \"login\", \"msg_id\": \"1\", \"data\": { \"cn_user\": \"" + config.WebSocketServer.User + "\", \"cn_pass\": \"" + config.WebSocketServer.Password + "\" } }"
if err := websocketClient.WriteMessage(websocket.TextMessage, []byte(msg)); err != nil {
log.Error("Write message error")
return
}
go func() {
defer websocketClient.Close()
defer close(done)
// Infinite loop
for {
_, message, err := websocketClient.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
//log.Printf("Receive message on Websocket: %s", message)
// Try to decode JSON message
var msg CalaosJsonMsg
err = json.Unmarshal([]byte(message), &msg)
if err != nil {
log.Error("error:", err)
continue
}
// Login message
if msg.Msg == "login" {
var loginMsg CalaosJsonMsgLogin
err = json.Unmarshal([]byte(message), &loginMsg)
if err != nil {
log.Error("error:", err)
continue
}
// Login success
if loginMsg.Data.Success == "true" {
loggedin = true
log.Printf("Logged in")
// We are logged in, send get_home message to get all IO states
getHomeMsg := "{ \"msg\": \"get_home\", \"msg_id\": \"2\" }"
if err = websocketClient.WriteMessage(websocket.TextMessage, []byte(getHomeMsg)); err != nil {
log.Error("Write message error")
continue
}
} else {
loggedin = false
}
}
// If we received and we are logged in
if loggedin {
// Msg event received
if msg.Msg == "event" {
var eventMsg CalaosJsonMsgEvent
err = json.Unmarshal([]byte(message), &eventMsg)
if err != nil {
log.Error("error:", err)
continue
}
// Get the calaos IO from the Map
cio := getIOFromId(eventMsg.Data.Data.ID)
if cio != nil {
cio.State = eventMsg.Data.Data.State
id := uint64(murmur.Sum32(cio.ID))
if acc, found := accessories[id]; found {
acc.Update(cio)
}
}
}
// Receive get_home message
if msg.Msg == "get_home" {
err = json.Unmarshal([]byte(message), &home)
if err != nil {
log.Error("error:", err)
}
// Create a new accessory of type Bridge
// bridge := NewCalaosGateway(config.BridgeName)
info := accessory.Info{
Name: config.BridgeName,
Manufacturer: "Calaos",
Model: "calaos-homekit",
Firmware: "3.0.0",
}
bridge := accessory.NewBridge(info)
// Get a copy of all Calaos IOs
calaosIOs = home.Data.Home[0].IOs
// Associate Bridge and info to a new Ip transport
accessories = make(map[uint64]CalaosAccessory)
setupCalaosHome()
list := []*accessory.A{}
for _, acc := range accessories {
list = append(list, acc.AccessoryGet())
}
// Store the data in the "/Calaos Gateway" directory.
store := hap.NewFsStore("./Calaos Gateway")
server, err := hap.NewServer(store, bridge.A, list...)
if err != nil {
log.Println(err)
continue
} else {
log.Println("Start HAP")
// Set the PIN code
server.Pin = config.PinCode
// Run the server.
go server.ListenAndServe(ctx)
}
}
}
}
}()
}
func main() {
log.Println("Starting Calaos-Homekit")
flag.StringVar(&configFilename, "config", "./config.json", "Get the config to use. default value is ./config.json")
flag.Parse()
// Setup a listener for interrupts and SIGTERM signals to stop the server.
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, os.Kill, syscall.SIGTERM)
ctx, cancel := context.WithCancel(context.Background())
log.Println("Opening Configuration filename : " + configFilename)
file, err := os.Open(configFilename)
if err != nil {
log.Error("error:", err)
os.Exit(1)
}
decoder := json.NewDecoder(file)
err = decoder.Decode(&config)
if err != nil {
log.Error("error:", err)
}
log.Println("Configuration : ")
log.Println(config.WebSocketServer)
uriType := "ws"
if config.WebSocketServer.Port == 443 {
uriType = "wss"
}
calaosURI := uriType + "://" + config.WebSocketServer.Host + ":" + strconv.Itoa(config.WebSocketServer.Port) + "/api"
loggedin = false
log.Println("Opening :", calaosURI)
websocketClient = Dial(calaosURI, func() { connectedCb(ctx) })
// Wait for Ctrl + c to qui app and close websocket properly
for {
select {
case <-c:
// Stop delivering signals.
defer signal.Stop(c)
// Cancel the context to stop the server.
defer cancel()
log.Println("interrupt")
err := websocketClient.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
log.Println("write close:", err)
return
}
websocketClient.Close()
return
}
}
}