-
Notifications
You must be signed in to change notification settings - Fork 0
/
hkswitchd.go
114 lines (98 loc) · 2.64 KB
/
hkswitchd.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
package main
import (
"encoding/json"
"fmt"
"github.com/brutella/hc"
"github.com/brutella/hc/accessory"
"github.com/yosssi/gmq/mqtt"
"github.com/yosssi/gmq/mqtt/client"
"io/ioutil"
"log"
"os/user"
"path/filepath"
)
func main() {
usr, _ := user.Current()
file, err := ioutil.ReadFile(filepath.Join(usr.HomeDir, ".config/hkdaemons/hkswitchd.json"))
if err != nil {
panic(err)
}
var config map[string]interface{}
if err := json.Unmarshal(file, &config); err != nil {
panic(err)
}
cli := client.New(&client.Options{
// Define the processing of the error handler.
ErrorHandler: func(err error) {
log.Println(err)
},
})
defer cli.Terminate()
err = cli.Connect(&client.ConnectOptions{
Network: "tcp",
Address: config["broker"].(string),
ClientID: []byte(config["client_id"].(string)),
})
if err != nil {
panic(err)
}
var accessories []*accessory.Accessory
configArr, ok := config["accessories"].([]interface{})
if !ok {
panic(err)
}
for _, accessory_config := range configArr {
accessory_config := accessory_config.(map[string]interface{})
info := accessory.Info{
Name: accessory_config["name"].(string),
Manufacturer: accessory_config["manufacturer"].(string),
}
control_topic := fmt.Sprintf("switch_%s/control", accessory_config["machine_id"].(string))
state_topic := fmt.Sprintf("switch_%s/state", accessory_config["machine_id"].(string))
acc := accessory.NewSwitch(info)
acc.Switch.On.OnValueRemoteUpdate(func(on bool) {
value := 0
if on {
value = 1
}
log.Printf("Switching %s", value)
err = cli.Publish(&client.PublishOptions{
QoS: mqtt.QoS0,
TopicName: []byte(control_topic),
Message: []byte(fmt.Sprintf("%d", value)),
})
if err != nil {
panic(err)
}
})
err = cli.Subscribe(&client.SubscribeOptions{
SubReqs: []*client.SubReq{
&client.SubReq{
TopicFilter: []byte(state_topic),
QoS: mqtt.QoS0,
// Define the processing of the message handler.
Handler: func(topicName, message []byte) {
new_value := "1" == string(message)
if acc.Switch.On.GetValue() != new_value {
log.Printf("Value externally changed to %t\n", new_value)
acc.Switch.On.SetValue(new_value)
}
},
},
},
})
if err != nil {
panic(err)
}
accessories = append(accessories, acc.Accessory)
}
transport_config := hc.Config{Pin: config["pin"].(string), StoragePath: filepath.Join(usr.HomeDir, ".config/hkdaemons/data/hkswitchd")}
t, err := hc.NewIPTransport(transport_config, accessories[0], accessories[1:]...)
if err != nil {
log.Fatal(err)
}
hc.OnTermination(func() {
t.Stop()
})
t.Start()
}