@@ -2,6 +2,7 @@ package main
2
2
3
3
import (
4
4
"encoding/json"
5
+ "fmt"
5
6
"github.com/brutella/hc"
6
7
"github.com/brutella/hc/accessory"
7
8
"github.com/brutella/log"
@@ -14,7 +15,7 @@ func main() {
14
15
log .Verbose = true
15
16
log .Info = true
16
17
17
- file , err := ioutil .ReadFile ("./config .json" )
18
+ file , err := ioutil .ReadFile ("./hkswitchd .json" )
18
19
if err != nil {
19
20
panic (err )
20
21
}
@@ -55,35 +56,31 @@ func main() {
55
56
Name : accessory_config ["name" ].(string ),
56
57
Manufacturer : accessory_config ["manufacturer" ].(string ),
57
58
}
59
+ control_topic := fmt .Sprintf ("switch_%s/control" , accessory_config ["machine_id" ].(string ))
60
+ state_topic := fmt .Sprintf ("switch_%s/state" , accessory_config ["machine_id" ].(string ))
58
61
59
62
acc := accessory .NewSwitch (info )
60
63
61
64
acc .Switch .On .OnValueRemoteUpdate (func (on bool ) {
62
- if on == true {
63
- err = cli .Publish (& client.PublishOptions {
64
- QoS : mqtt .QoS0 ,
65
- TopicName : []byte (accessory_config ["control_topic" ].(string )),
66
- Message : []byte ("on" ),
67
- })
68
- if err != nil {
69
- panic (err )
70
- }
71
- } else {
72
- err = cli .Publish (& client.PublishOptions {
73
- QoS : mqtt .QoS0 ,
74
- TopicName : []byte (accessory_config ["control_topic" ].(string )),
75
- Message : []byte ("off" ),
76
- })
77
- if err != nil {
78
- panic (err )
79
- }
65
+ value := "off"
66
+ if on {
67
+ value = "on"
68
+ }
69
+ log .Printf ("Switching %s" , value )
70
+ err = cli .Publish (& client.PublishOptions {
71
+ QoS : mqtt .QoS0 ,
72
+ TopicName : []byte (control_topic ),
73
+ Message : []byte (fmt .Sprintf ("power:%s" , value )),
74
+ })
75
+ if err != nil {
76
+ panic (err )
80
77
}
81
78
})
82
79
83
80
err = cli .Subscribe (& client.SubscribeOptions {
84
81
SubReqs : []* client.SubReq {
85
82
& client.SubReq {
86
- TopicFilter : []byte (accessory_config [ " state_topic" ].( string ) ),
83
+ TopicFilter : []byte (state_topic ),
87
84
QoS : mqtt .QoS0 ,
88
85
// Define the processing of the message handler.
89
86
Handler : func (topicName , message []byte ) {
0 commit comments