Repository navigation
Expand file tree
/
Copy pathcontroller.go
More file actions
298 lines (265 loc) · 7.35 KB
/
Copy pathcontroller.go
File metadata and controls
298 lines (265 loc) · 7.35 KB
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
// Package controller keeps what each room should be doing apart from what its
// thermostat reports, and sends commands until the two match.
//
// HTTP handlers and device reports only change state under mu and wake Run,
// which is the only place that talks to a thermostat. So nothing that delivers a
// report ever waits for a publish.
//
// All state is in memory. After a restart a room that was airing stays off until
// someone taps "Heat again" on the page.
//
// Three behaviours of the Sonoff TRVZB shape this code. They were measured on a
// real device (firmware 1.3.0):
// - In system_mode off it reports its frost protection temperature as the
// setpoint, and briefly keeps reporting it after going back to heat. That
// value is never a target the user chose.
// - Writing a setpoint while it is off switches it back to heat, so a target
// changed during that time is held until it can be sent.
// - After a write it can still send a few reports with the old setpoint.
//
// Someone can also turn a thermostat off by hand, so "off" doesn't mean this
// program turned it off. A room is only turned back on if this program turned it
// off, or someone asks for it.
package controller
import (
"context"
"errors"
"fmt"
"log"
"math"
"sync"
"time"
"github.com/subpathdev/heating-control/internal/config"
)
// Mode is a thermostat's system mode. The zero value means it hasn't reported.
type Mode string
// The modes a thermostat can report.
const (
ModeUnknown Mode = ""
ModeOff Mode = "off"
ModeAuto Mode = "auto"
ModeHeat Mode = "heat"
)
// ParseMode converts a reported system mode. An unknown value is an error, so
// a typo or firmware change can't be mistaken for a thermostat that is heating.
func ParseMode(s string) (Mode, error) {
switch m := Mode(s); m {
case ModeOff, ModeAuto, ModeHeat:
return m, nil
default:
return ModeUnknown, fmt.Errorf("unknown system mode %q", s)
}
}
// TargetState says how far a room's target has got.
type TargetState string
// The states of a room's target.
const (
TargetApplied TargetState = "applied"
TargetSending TargetState = "sending"
TargetHeld TargetState = "held"
TargetFailed TargetState = "failed"
)
// AiringState says where a room is in airing.
type AiringState string
// The states of airing.
const (
AiringNone AiringState = "none"
AiringStarting AiringState = "starting"
AiringActive AiringState = "active"
AiringRestoring AiringState = "restoring"
)
// ErrUnknownRoom is returned for a room that isn't configured.
var ErrUnknownRoom = errors.New("unknown room")
// ErrTargetOutOfRange is returned for a target outside the allowed range.
var ErrTargetOutOfRange = errors.New("target out of range")
// tickInterval is how often Run checks timeouts and retries without being woken.
const tickInterval = 5 * time.Second
// Thermostat sends commands to a physical thermostat.
type Thermostat interface {
Apply(trv string, cmd Command) error
}
// ThermostatState is a thermostat's report. Fields it didn't include are nil.
type ThermostatState struct {
Mode *Mode
Setpoint *float64
LocalTemperature *float64
Heating *bool
FrostProtection *float64
}
// RoomStatus is a room's current state.
type RoomStatus struct {
ID string
Label string
Temperature *float64
Target *float64
TargetState TargetState
Mode Mode
Heating bool
AiringState AiringState
AiringUntil *time.Time
LastSeen *time.Time
CommandFailed bool
}
// Controller is safe for concurrent use.
type Controller struct {
thermostat Thermostat
now func() time.Time
min, max float64
wake chan struct{}
// mu guards the rooms' state and is never held during a publish. rooms itself
// and each room's cfg don't change after New.
mu sync.Mutex
rooms []*room
}
// New returns a Controller for the configured rooms.
func New(cfg *config.Config, thermostat Thermostat) *Controller {
c := &Controller{
thermostat: thermostat,
now: time.Now,
min: cfg.MinTarget,
max: cfg.MaxTarget,
wake: make(chan struct{}, 1),
}
for _, r := range cfg.Rooms {
c.rooms = append(c.rooms, &room{cfg: r})
}
return c
}
// Run sends commands until ctx is done.
func (c *Controller) Run(ctx context.Context) {
ticker := time.NewTicker(tickInterval)
defer ticker.Stop()
for {
c.tick()
select {
case <-ctx.Done():
return
case <-ticker.C:
case <-c.wake:
}
}
}
// tick moves every room on by one step.
func (c *Controller) tick() {
for _, r := range c.rooms {
c.mu.Lock()
now := c.now()
r.advance(now)
cmd, send := r.decide(now)
if send {
r.attempts++
r.lastSent = now
r.sentTarget = cmd.Target
}
c.mu.Unlock()
if !send {
continue
}
if err := c.thermostat.Apply(r.cfg.TRV, cmd); err != nil {
log.Printf("%s: %s: %v", r.cfg.TRV, cmd.Kind(), err)
// Never reached the thermostat, so it says nothing about it.
c.mu.Lock()
r.attempts--
r.publishFailed = true
r.sentTarget = nil
c.mu.Unlock()
continue
}
c.mu.Lock()
r.publishFailed = false
c.mu.Unlock()
}
}
func (c *Controller) signal() {
select {
case c.wake <- struct{}{}:
default:
}
}
// Limits returns the allowed target range.
func (c *Controller) Limits() (min, max float64) {
return c.min, c.max
}
// Rooms returns the status of every room, in configured order.
func (c *Controller) Rooms() []RoomStatus {
c.mu.Lock()
defer c.mu.Unlock()
out := make([]RoomStatus, 0, len(c.rooms))
for _, r := range c.rooms {
out = append(out, r.status())
}
return out
}
// SetTarget accepts a new target for a room. Run delivers it when it can.
func (c *Controller) SetTarget(id string, target float64) error {
r := c.find(id)
if r == nil {
return fmt.Errorf("%w: %q", ErrUnknownRoom, id)
}
// NaN fails both comparisons, so test for the valid range.
if !(target >= c.min && target <= c.max) {
return fmt.Errorf("%w: %v is not within %v..%v", ErrTargetOutOfRange, target, c.min, c.max)
}
target = math.Round(target*2) / 2
c.mu.Lock()
r.setTarget(target)
c.mu.Unlock()
c.signal()
return nil
}
// StartAiring stops heating a room for d. Called during airing, it sets a new
// end time.
func (c *Controller) StartAiring(id string, d time.Duration) error {
r := c.find(id)
if r == nil {
return fmt.Errorf("%w: %q", ErrUnknownRoom, id)
}
c.mu.Lock()
r.startAiring(c.now().Add(d))
c.mu.Unlock()
c.signal()
return nil
}
// StopAiring ends airing now. If the room isn't airing but its thermostat is
// off, it turns it back on. Otherwise it does nothing.
func (c *Controller) StopAiring(id string) error {
r := c.find(id)
if r == nil {
return fmt.Errorf("%w: %q", ErrUnknownRoom, id)
}
c.mu.Lock()
r.heatAgain(c.now())
c.mu.Unlock()
c.signal()
return nil
}
// HandleThermostatState records a thermostat's report.
func (c *Controller) HandleThermostatState(trv string, s ThermostatState) {
c.mu.Lock()
for _, r := range c.rooms {
if r.cfg.TRV == trv {
r.report(s, c.now())
break
}
}
c.mu.Unlock()
c.signal()
}
// HandleRoomTemperature records a room sensor's report.
func (c *Controller) HandleRoomTemperature(sensor string, t float64) {
c.mu.Lock()
defer c.mu.Unlock()
for _, r := range c.rooms {
if r.cfg.Sensor == sensor {
r.sensorTemp = &t
}
}
}
func (c *Controller) find(id string) *room {
for _, r := range c.rooms {
if r.cfg.ID == id {
return r
}
}
return nil
}