-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
devices.go
70 lines (55 loc) · 1.52 KB
/
devices.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
package telemetry
import (
"encoding/json"
"reflect"
"github.com/e154/smart-home/api/models"
"github.com/e154/smart-home/api/stream"
"github.com/e154/smart-home/api/core"
"github.com/e154/smart-home/api/log"
)
type Devices struct {
Total int64 `json:"total"`
Status map[int64]*models.DeviceState `json:"status"`
}
func (d *Devices) Update() {
var err error
if d.Total, err = models.GetDevicesCount(); err != nil {
log.Error(err.Error())
}
d.Status = core.CorePtr().GetDevicesStates()
}
func (d *Devices) Broadcast() {
d.Update()
msg, _ := json.Marshal(map[string]interface{}{"type": "broadcast",
"value": map[string]interface{}{"type": "telemetry", "body": map[string]interface{}{
"devices": d,
}}},
)
Hub.Broadcast(string(msg))
}
func (d *Devices) BroadcastOne(id int64) {
d.Status = core.CorePtr().GetDevicesStates()
state, ok := d.Status[id]
if !ok {
return
}
msg, _ := json.Marshal(
map[string]interface{}{"type": "broadcast",
"value": map[string]interface{}{"type": "telemetry", "body": map[string]interface{}{
"device": map[string]interface{}{"id": id, "state": state},
"devices": d,
}}},
)
Hub.Broadcast(string(msg))
}
// only on request: 'get.devices.states'
//
func streamGetDevicesStates(client *stream.Client, value interface{}) {
v, ok := reflect.ValueOf(value).Interface().(map[string]interface{})
if !ok {
return
}
Telemetry.Devices.Update()
msg, _ := json.Marshal(map[string]interface{}{"id": v["id"], "states": Telemetry.Devices.Status})
client.Send(string(msg))
}