Repository navigation
Expand file tree
/
Copy pathcontroller.go
More file actions
454 lines (414 loc) · 12.5 KB
/
Copy pathcontroller.go
File metadata and controls
454 lines (414 loc) · 12.5 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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
// 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.
//
// Airing is saved in an AiringStore, so it carries on after a restart. A change
// that couldn't be saved isn't made. Everything else is in memory and comes back
// from the thermostats' reports.
//
// 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
// saveTimeout bounds a write to the store.
const saveTimeout = 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
// AwayTarget and AwayRestoreTarget are set while the room is part of away.
// AwayUntil is nil once away has ended and the target from before is on its
// way.
AwayUntil *time.Time
AwayTarget *float64
AwayRestoreTarget *float64
}
// Controller is safe for concurrent use.
type Controller struct {
thermostat Thermostat
now func() time.Time
min, max float64
store Store
wake chan struct{}
// saveMu orders writes to the store, so an older state never overwrites a
// newer one. It is taken before mu.
saveMu sync.Mutex
// mu guards the rooms' state and is never held during a publish. A request
// holds it while its change is saved, so the change and the save are one
// step. 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, carrying on with the
// airing and away saved in store. Saved state for a room that is no longer
// configured is left in the store and ignored.
func New(ctx context.Context, cfg *config.Config, thermostat Thermostat, store Store) (*Controller, error) {
c := &Controller{
thermostat: thermostat,
store: store,
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})
}
if err := c.load(ctx); err != nil {
return nil, err
}
return c, nil
}
// load carries on with what store holds. Anything it adjusts differs from what
// the store holds, so the first tick saves it.
func (c *Controller) load(ctx context.Context) error {
airings, err := c.store.Airings(ctx)
if err != nil {
return fmt.Errorf("load airing: %w", err)
}
for _, a := range airings {
r := c.find(a.RoomID())
if r == nil {
log.Printf("saved airing for unknown room %q ignored", a.RoomID())
continue
}
r.saved.airing, r.saved.hasAiring = airingOf(a), true
if target, ok := a.HeldTarget(); ok && !c.inRange(target) {
// The range was changed since. Dropping the target is safe: the
// thermostat keeps its own.
log.Printf("%s: saved target %v is out of range, dropped", r.cfg.TRV, target)
until, _ := a.Until()
if a, err = RestoreAiring(a.RoomID(), until, a.RestoreMode(), nil); err != nil {
return err
}
}
r.resume(a)
log.Printf("%s: carrying on with saved airing", r.cfg.TRV)
}
aways, err := c.store.Aways(ctx)
if err != nil {
return fmt.Errorf("load away: %w", err)
}
for _, a := range aways {
r := c.find(a.RoomID())
if r == nil {
log.Printf("saved away for unknown room %q ignored", a.RoomID())
continue
}
r.saved.away, r.saved.hasAway = awayOf(a), true
if restore := a.RestoreTarget(); !c.inRange(restore) {
// The range was changed since, so bring back the nearest allowed.
clamped := math.Min(math.Max(restore, c.min), c.max)
log.Printf("%s: saved target %v is out of range, using %v", r.cfg.TRV, restore, clamped)
until, _ := a.Until()
if a, err = RestoreAway(a.RoomID(), until, a.Target(), clamped); err != nil {
return err
}
}
// After airing, so a target held for airing wins.
r.resumeAway(a)
log.Printf("%s: carrying on with saved away", r.cfg.TRV)
}
return nil
}
// 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()
}
for _, r := range c.rooms {
c.saveMu.Lock()
c.mu.Lock()
next := r.toSave()
c.mu.Unlock()
if err := c.save(r, next); err != nil {
// Tried again on the next tick.
log.Printf("%s: save: %v", r.cfg.TRV, err)
}
c.saveMu.Unlock()
}
}
// save writes what differs between next and what the store holds for the room,
// and records each part once it is written. The caller holds saveMu.
func (c *Controller) save(r *room, next saved) error {
ctx, cancel := context.WithTimeout(context.Background(), saveTimeout)
defer cancel()
if next.hasAiring != r.saved.hasAiring || next.airing != r.saved.airing {
var err error
if next.hasAiring {
err = c.store.SaveAiring(ctx, next.airing)
} else {
err = c.store.DeleteAiring(ctx, r.cfg.ID)
}
if err != nil {
return fmt.Errorf("airing: %w", err)
}
r.saved.airing, r.saved.hasAiring = next.airing, next.hasAiring
}
if next.hasAway != r.saved.hasAway || next.away != r.saved.away {
var err error
if next.hasAway {
err = c.store.SaveAway(ctx, next.away)
} else {
err = c.store.DeleteAway(ctx, r.cfg.ID)
}
if err != nil {
return fmt.Errorf("away: %w", err)
}
r.saved.away, r.saved.hasAway = next.away, next.hasAway
}
return nil
}
// change makes a requested change to a room and saves it. If it can't be saved,
// it isn't made.
func (c *Controller) change(r *room, apply func(now time.Time)) error {
return c.changeAll(func(now time.Time) error {
apply(now)
return nil
})
}
// changeAll makes a requested change to any rooms and saves it. If apply fails
// or a room can't be saved, no room changes. A room already saved then differs
// from what the store holds, so the next tick writes its old state back.
func (c *Controller) changeAll(apply func(now time.Time) error) error {
c.saveMu.Lock()
defer c.saveMu.Unlock()
c.mu.Lock()
defer c.mu.Unlock()
before := make([]room, len(c.rooms))
for i, r := range c.rooms {
before[i] = *r
}
undo := func() {
for i, r := range c.rooms {
written := r.saved
*r = before[i]
r.saved = written
}
}
if err := apply(c.now()); err != nil {
undo()
return err
}
for _, r := range c.rooms {
if err := c.save(r, r.toSave()); err != nil {
undo()
log.Printf("%s: save: %v", r.cfg.TRV, err)
return fmt.Errorf("%w: %v", ErrNotSaved, err)
}
}
c.signal()
return nil
}
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. During
// airing the target is saved, and ErrNotSaved means it wasn't accepted.
func (c *Controller) SetTarget(id string, target float64) error {
r := c.find(id)
if r == nil {
return fmt.Errorf("%w: %q", ErrUnknownRoom, id)
}
if !c.inRange(target) {
return fmt.Errorf("%w: %v is not within %v..%v", ErrTargetOutOfRange, target, c.min, c.max)
}
target = math.Round(target*2) / 2
return c.change(r, func(time.Time) { r.setTarget(target) })
}
// inRange reports whether target is allowed. NaN fails both comparisons, so
// this tests for the valid range.
func (c *Controller) inRange(target float64) bool {
return target >= c.min && target <= c.max
}
// StartAiring stops heating a room for d. Called during airing, it sets a new
// end time. ErrNotSaved means airing wasn't started.
func (c *Controller) StartAiring(id string, d time.Duration) error {
r := c.find(id)
if r == nil {
return fmt.Errorf("%w: %q", ErrUnknownRoom, id)
}
return c.change(r, func(now time.Time) { r.startAiring(now.Add(d)) })
}
// StopAiring ends airing now. If the room isn't airing but its thermostat is
// off, it turns it back on. Otherwise it does nothing. ErrNotSaved means nothing
// changed.
func (c *Controller) StopAiring(id string) error {
r := c.find(id)
if r == nil {
return fmt.Errorf("%w: %q", ErrUnknownRoom, id)
}
return c.change(r, r.heatAgain)
}
// 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
}