summaryrefslogtreecommitdiff
path: root/mqtt-controller/devices.go
blob: 9f113333d7aefeea880acd4c6c500380d131d12f (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
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"strconv"
	"strings"
)

type Direction int

const (
	DirectionInput Direction = iota
	DirectionOutput
)

type Device interface {
	Identity() string
	Connect(*MQTTBroker, chan<- Event, chan<- Metric, chan<- interface{}) (<-chan Command, error)
	OutputOn(int) error
	OutputOff(int) error
	Disconnect() error
}

type Command struct {
	Index  int
	Active bool
}

type Event struct {
	Device    Device
	Index     int
	Active    bool
	Direction Direction
}

type Metric struct {
	Device Device
	Name   string
	Value  interface{}
}

type DeviceAnnounce struct {
	ID                   string `json:"id"`
	IP                   string `json:"ip"`
	MacAddress           string `json:"mac"`
	Model                string `json:"model"`
	FirmwareVersion      string `json:"fw_ver"`
	NewFirmwareAvailable bool   `json:"new_fw"`
}

func NewDevice(b *MQTTBroker, da DeviceAnnounce) (Device, error) {
	switch da.Model {
	case "SHSW-PM":
		return NewShellyDevice(da, 1, 1), nil
	case "SHSW-25":
		return NewShellyDevice(da, 2, 2), nil
	}
	return nil, fmt.Errorf("Unknown device model %s", da.Model)
}

type ShellyDevice struct {
	ID                   string
	Manufacturer         string
	IP                   string // TODO: Fix type
	MacAddress           string // TODO: Fix type
	Model                string // TODO: Fix type
	FirmwareVersion      string // TODO: Fix type
	NewFirmwareAvailable bool
	broker               *MQTTBroker
	inputCount           int
	outputCount          int
	connected            bool
	inputState           []bool
	outputState          []bool
	subscribed           []string
	events               chan<- Event
	metrics              chan<- Metric
	info                 chan<- interface{}
	commands             chan Command
}

func NewShellyDevice(da DeviceAnnounce, inputCount, outputCount int) *ShellyDevice {
	return &ShellyDevice{
		Manufacturer:         "Shelly",
		ID:                   da.ID,
		IP:                   da.IP,
		MacAddress:           da.MacAddress,
		Model:                da.Model,
		FirmwareVersion:      da.FirmwareVersion,
		NewFirmwareAvailable: da.NewFirmwareAvailable,
		inputCount:           inputCount,
		outputCount:          outputCount,
		inputState:           make([]bool, inputCount),
		outputState:          make([]bool, outputCount),
		connected:            false,
		subscribed:           []string{},
		commands:             make(chan Command, 100),
	}
}

var _ Device = (*ShellyDevice)(nil)

func (d *ShellyDevice) Identity() string {
	return d.ID
}

func (d *ShellyDevice) handleOutputMessages(topic string, payload []byte) {
	path := strings.Split(topic, "/")[2:]

	switch path[0] {
	case "info":
		p := ShellyStatus{Device: d}
		if err := json.Unmarshal(payload, &p); err != nil {
			log.Printf("Error parsing info packet: %s", err)
			return
		}
		d.info <- p
	case "input":
		idx, err := strconv.Atoi(path[1])
		if err != nil {
			log.Println("Error parsing index")
			return
		}
		state := payload[0] == '0'
		if d.inputState[idx] != state {
			d.events <- Event{
				Device:    d,
				Index:     idx,
				Active:    state,
				Direction: DirectionInput,
			}
			d.inputState[idx] = state
		}
	case "relay":
		idx, err := strconv.Atoi(path[1])
		if err != nil {
			log.Println("Error parsing index")
			return
		}
		if len(path) == 2 {
			state := string(payload) == "on"
			if d.outputState[idx] != state {
				d.events <- Event{
					Device:    d,
					Index:     idx,
					Active:    state,
					Direction: DirectionOutput,
				}
				d.outputState[idx] = state
			}
		} else {
			switch path[2] {
			case "power":
				m, err := strconv.ParseFloat(string(payload), 16)
				if err != nil {
					log.Printf("Failed to parse metric")
					return
				}
				d.metrics <- Metric{
					Device: d,
					Name:   fmt.Sprintf("relay_%d_power", idx),
					Value:  m,
				}
			case "energy":
				m, err := strconv.ParseInt(string(payload), 10, 32)
				if err != nil {
					log.Printf("Failed to parse metric")
					return
				}
				d.metrics <- Metric{
					Device: d,
					Name:   fmt.Sprintf("relay_%d_energy", idx),
					Value:  m,
				}
			case "overpower_value":
				m, err := strconv.ParseInt(string(payload), 10, 32)
				if err != nil {
					log.Printf("Failed to parse metric")
					return
				}
				d.metrics <- Metric{
					Device: d,
					Name:   fmt.Sprintf("relay_%d_overpower_value", idx),
					Value:  m,
				}
			}
		}
	case "temperature":
		m, err := strconv.ParseFloat(string(payload), 16)
		if err != nil {
			log.Printf("Failed to parse metric")
			return
		}
		d.metrics <- Metric{
			Device: d,
			Name:   "temperature_c",
			Value:  m,
		}
	case "overtemperature":
		d.metrics <- Metric{
			Device: d,
			Name:   "is_overtemperature",
			Value:  payload[0] == '1',
		}
	}
}

func (d *ShellyDevice) OutputOn(idx int) error {
	if idx < 0 || idx >= d.outputCount {
		return fmt.Errorf("Index is out of range for device")
	}
	if d.broker == nil {
		return fmt.Errorf("Device is not connected to broker")
	}

	return d.broker.Publish(fmt.Sprintf("shellies/%s/relay/%d/command", d.Identity(), idx), "on")
}

func (d *ShellyDevice) OutputOff(idx int) error {
	if idx < 0 || idx >= d.outputCount {
		return fmt.Errorf("Index is out of range for device")
	}
	if d.broker == nil {
		return fmt.Errorf("Device is not connected to broker")
	}

	return d.broker.Publish(fmt.Sprintf("shellies/%s/relay/%d/command", d.Identity(), idx), "off")
}

func (d *ShellyDevice) Connect(b *MQTTBroker, events chan<- Event, metrics chan<- Metric, info chan<- interface{}) (<-chan Command, error) {
	d.broker = b
	d.events = events
	d.metrics = metrics
	d.info = info

	outputs := []string{
		"shellies/{ID}/info",
		"shellies/{ID}/temperature",
		"shellies/{ID}/overtemperature",
	}

	for i := d.inputCount - 1; i >= 0; i-- {
		outputs = append(outputs, fmt.Sprintf("shellies/{ID}/input/%d", i))
		outputs = append(outputs, fmt.Sprintf("shellies/{ID}/longpush/%d", i))
	}

	for i := d.outputCount - 1; i >= 0; i-- {
		outputs = append(outputs, fmt.Sprintf("shellies/{ID}/relay/%d", i))
		outputs = append(outputs, fmt.Sprintf("shellies/{ID}/relay/%d/power", i))
		outputs = append(outputs, fmt.Sprintf("shellies/{ID}/relay/%d/energy", i))
		outputs = append(outputs, fmt.Sprintf("shellies/{ID}/relay/%d/overpower_value", i))
	}

	// TODO: Handle these
	inputs := []string{
		"",
	}
	_ = inputs

	for _, topic := range outputs {
		tn := strings.Replace(topic, "{ID}", d.ID, 1)
		if err := b.Subscribe(tn, d.handleOutputMessages); err != nil {
			return nil, err
		}
		d.subscribed = append(d.subscribed, tn)
	}

	d.connected = true

	return d.commands, nil
}

func (d *ShellyDevice) Disconnect() error {
	if !d.connected {
		return fmt.Errorf("Device not connected, can not disconnect")
	}
	return nil
}