summaryrefslogtreecommitdiff
path: root/main.go
blob: fb8582e74ee9312827620d5e6ef4c553b3aaf457 (plain)
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
package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net"
	"time"

	"github.com/brutella/hc"
	"github.com/brutella/hc/accessory"
	"github.com/brutella/hc/characteristic"
	"golang.org/x/crypto/ssh"
)

// TODO: Use SCP to init controller https://github.com/bramvdbogaerde/go-scp

const (
	CMD_PATH = "/var/etc/persistent/power_control.sh"
)

type Device struct {
	Root      *Device
	Name      string
	Username  string
	Password  string
	Port      int
	Host      string
	Devices   []string
	sshClient *ssh.Client
}

func (d *Device) GetUsername() string {
	if d.Username != "" {
		return d.Username
	} else if d.Root != nil {
		return d.Root.Username
	} else {
		return ""
	}
}

func (d *Device) GetPassword() string {
	if d.Password != "" {
		return d.Password
	} else if d.Root != nil {
		return d.Root.Password
	} else {
		return ""
	}
}

func (d *Device) GetPort() int {
	if d.Port != 0 {
		return d.Port
	} else if d.Root != nil {
		return d.Root.Port
	} else {
		return 22
	}
}

func (d *Device) Connect() error {
	cfg := &ssh.ClientConfig{
		User:            d.GetUsername(),
		Auth:            []ssh.AuthMethod{ssh.Password(d.GetPassword())},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
		Timeout:         0,
	}

	// These devices use really old crufty versions of SSH
	cfg.Config.KeyExchanges = []string{"diffie-hellman-group1-sha1"}
	cfg.Config.Ciphers = append(cfg.Config.Ciphers, "aes128-cbc")

	conn, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", d.Host, d.GetPort()), cfg)
	if err != nil {
		return err
	}

	d.sshClient = conn
	return nil
}

func (d *Device) Disconnect() {
	d.sshClient.Close()
}

func (d *Device) newSession() (*ssh.Session, error) {
	for i := 3; i > 0; i-- {
		if s, err := d.sshClient.NewSession(); err == nil {
			return s, nil
		} else if err != nil && i == 0 {
			fmt.Printf("Session error, failing: %s\n", err)
			return nil, err
		}

		fmt.Println("Session error, reconnecting")
		d.Connect()
	}

	return nil, errors.New("Unable to connect via SSH")
}

func (d *Device) runCommand(cmd string) ([]DeviceOutput, error) {
	sess, err := d.newSession()
	if err != nil {
		fmt.Printf("Session error: %s\n", err)
		return nil, err
	}
	defer sess.Close()

	out, err := sess.Output(cmd)
	if err != nil {
		fmt.Printf("Command error: %s\n", err)
		return nil, err
	}

	if out == nil {
		fmt.Printf("Nil return\n")
		return nil, nil
	} else {
		var r []DeviceOutput
		err = json.Unmarshal(out, &r)
		if err != nil {
			return nil, err
		}
		return r, nil
	}
}

func (d *Device) findOutput(name string) (int, error) {
	for i, e := range d.Devices {
		if e == name {
			return i + 1, nil
		}
	}

	return 0, errors.New("Unknown device")
}

func (d *Device) TurnOn(n string) ([]DeviceOutput, error) {
	o, err := d.findOutput(n)
	if err != nil {
		return nil, err
	}

	out, err := d.runCommand(fmt.Sprintf("%s on %d", CMD_PATH, o))
	if err != nil {
		return nil, err
	} else {
		return out, nil
	}
}

func (d *Device) TurnOff(n string) ([]DeviceOutput, error) {
	o, err := d.findOutput(n)
	if err != nil {
		return nil, err
	}

	out, err := d.runCommand(fmt.Sprintf("%s off %d", CMD_PATH, o))
	if err != nil {
		return nil, err
	} else {
		return out, nil
	}
}

func (d *Device) Toggle(n string, on bool) ([]DeviceOutput, error) {
	if on == true {
		return d.TurnOn(n)
	} else {
		return d.TurnOff(n)
	}
}

func (d *Device) GetReport() ([]DeviceOutput, error) {
	out, err := d.runCommand(fmt.Sprintf("%s report", CMD_PATH))
	if err != nil {
		return nil, err
	} else {
		return out, nil
	}
}

type DeviceOutput struct {
	Output      int     `json:"output"`
	Engaged     bool    `json:"engaged"`
	ActivePower float64 `json:"active_power"`
	EnergySum   float64 `json:"energy_sum"`
	CurrentRMS  float64 `json:"current_rms"`
	VoltageRMS  float64 `json:"voltage_rms"`
	PowerFactor float64 `json:"power_factor"`
}

func LoadAppConfig(filename string) ([]*Device, error) {
	raw, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}

	var cfg []*Device
	err = json.Unmarshal(raw, &cfg)
	if err != nil {
		return nil, err
	}

	if def := cfg[0]; def.Name == "DEFAULT" {
		cfg = cfg[1:]

		for _, v := range cfg {
			v.Root = def
		}
	}

	return cfg, nil
}

type Output struct {
	Device *Device
	Name   string
}

func (o *Output) Toggle(on bool) error {
	_, err := o.Device.Toggle(o.Name, on)
	if err != nil {
		fmt.Println(err)
	}
	return err
}

func GatherReports(devs []*Device) {
	t := time.NewTicker(10 * time.Second)
	defer t.Stop()

	for {
		<-t.C
		for _, d := range devs {
			d.GetReport()
		}
	}
}

func main() {
	devs, err := LoadAppConfig("config.json")
	if err != nil {
		fmt.Println(err)
		return
	}

	reg := []*accessory.Accessory{}
	accs := make(map[*characteristic.Characteristic]*Output, 10)

	// TODO: Do this in a goroutine and add retries for devices so one device
	// doesn't block booting the whole controller
	for _, k := range devs {
		fmt.Printf("Connecting to %s\n", k.Name)

		// TODO: Upgrade or install controller script when first connecting

		if err = k.Connect(); err != nil {
			panic(err)
		}

		report, err := k.GetReport()
		if err != nil {
			panic(err)
		}

		// TODO: Allow the homekit app to provide device and output names
		for i, d := range k.Devices {
			// Unnamed outputs are unused
			if d == "" {
				continue
			}

			sw := accessory.NewSwitch(accessory.Info{Name: d})
			sw.Switch.On.OnValueUpdateFromConn(func(_ net.Conn, c *characteristic.Characteristic, new, _ interface{}) {
				on := new.(bool)
				output := accs[c]
				fmt.Printf("Client changed switch %s to %t\n", output.Name, on)
				output.Toggle(on)
			})
			accs[sw.Switch.On.Characteristic] = &Output{
				Device: k,
				Name:   d,
			}
			sw.Switch.On.UpdateValue(report[i].Engaged)
			reg = append(reg, sw.Accessory)
		}
	}

	br := accessory.NewBridge(accessory.Info{Name: "mFi Bridge"})

	t, err := hc.NewIPTransport(hc.Config{Pin: "00102003", Port: "6969"}, br.Accessory, reg...)
	if err != nil {
		fmt.Println(err)
	}

	hc.OnTermination(func() {
		<-t.Stop()
	})

	// Gathering reports also keeps the SSH connections alive
	go GatherReports(devs)
	t.Start()
}