forked from evandcoleman/gohome
/
x10.go
88 lines (74 loc) · 1.83 KB
/
x10.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net"
"github.com/brutella/hc/model"
"github.com/brutella/hc/model/accessory"
)
type Device struct {
Name string `json:"name"`
HouseCode string `json:"house_code"`
DeviceID int `json:"device_id"`
Dimmable bool `json:"dimmable"`
}
func X10Devices() []*accessory.Accessory {
file, err := ioutil.ReadFile("./config/x10.json")
if err != nil {
log.Fatalln("Error opening X10 config file", err.Error())
}
var bulbs []Device
if err = json.Unmarshal(file, &bulbs); err != nil {
log.Fatalln("Error parsing X10 config file", err.Error())
}
lightBulbs := []*accessory.Accessory{}
for _, b := range bulbs {
var device Device = b
log.Printf("Creating X10 accessory \"%v\"...\n", device.Name)
info := model.Info{
Name: device.Name,
Manufacturer: "X10",
}
light := accessory.NewLightBulb(info)
light.OnStateChanged(func(on bool) {
var action string
if on {
action = "on"
} else {
action = "off"
}
var method string
if device.Dimmable {
method = "pl"
} else {
method = "rf"
}
cmd := fmt.Sprintf("%s %s%v %s", method, device.HouseCode, device.DeviceID, action)
writeCommand(cmd)
})
light.OnBrightnessChanged(func(val int) {
if device.Dimmable {
dimVal := int((float64(val) / 100) * 70)
cmd := fmt.Sprintf("pl %s%v xdim %v", device.HouseCode, device.DeviceID, dimVal)
writeCommand(cmd)
}
})
lightBulbs = append(lightBulbs, light.Accessory)
}
return lightBulbs
}
func writeCommand(cmd string) {
// TODO: Queue commands and execute serially with a delay
log.Printf("Writing command \"%s\"", cmd)
conn, err := net.Dial("tcp", "localhost:1099")
if err != nil {
log.Println(err)
}
defer conn.Close()
_, err = conn.Write([]byte(cmd + "\n"))
if err != nil {
log.Println(err)
}
}