diff --git a/README.md b/README.md index 8762f81..672ff35 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # heating-control -A small web page to adjust the heating per room from a phone on the home network: change a room's target temperature, or mark a window as open so the room doesn't heat. It controls Sonoff TRVZB thermostats through Zigbee2MQTT. +A small web page to adjust the heating per room from a phone on the home network: change a room's target temperature, mark a window as open so the room doesn't heat, or lower every room while away and get the old targets back on their own. It controls Sonoff TRVZB thermostats through Zigbee2MQTT. The heating page at phone width: a green All OK status in the top right, then Office and Bedroom cards, each with the room temperature, whether it is heating, the target, buttons to change it, and Air 5, 15, 30 and 60 buttons @@ -17,6 +17,15 @@ Airing is saved, so it carries on after a restart or release: a room that should - Commands repeat until the thermostat confirms them, every 30 s for about 5 minutes. A target then gives up and shows the thermostat's value. Off and heat-again keep trying every 5 minutes and show a problem on the page, because giving up would mean heating with the window open or a cold room. - A thermostat that is off with no airing is left alone, because someone may have turned it off on purpose. The page offers "Heat again" for it. +## Away + +"Away…" lowers every room to one target until a date and time, then raises each room back to the target it had before, on its own. The page suggests 17 °C and the next day; the end can be at most 30 days ahead. While away, the page shows when it ends and what each room gets back, and "Back now" ends it early. + +- Only rooms whose target is known take part. A room whose target someone changed during away is left alone at the end. +- Starting away again during away sets a new end and target, and keeps the targets from before. +- Raising the target back follows the rules for the end of airing: it repeats until the thermostat confirms it and never gives up, and the page shows a problem if it takes longer than about 5 minutes. A thermostat that is off then gets the target once it heats again, and a room airing at the end gets it when airing ends. +- Away is saved, so it carries on after a restart. If the end passed while the service was down, the targets come back as soon as it runs again. + ## Requirements | Needs | Why | Tested with | @@ -36,11 +45,11 @@ It also needs a writable directory that survives a restart, `dataDir`: the chart ## Saved state -The service keeps one SQLite database, `heating-control.db` in `dataDir`. It holds only what can't come back from the thermostats: for each room that is airing, when airing ends, the mode to go back to, and a target chosen during airing. A room's row is deleted once its thermostat confirms it is heating again, so the file is a few kilobytes. Everything else is in memory and comes back from the thermostats' reports. Migrations are part of the binary and run at start; an older binary refuses a newer database. +The service keeps one SQLite database, `heating-control.db` in `dataDir`. It holds only what can't come back from the thermostats: for each room that is airing, when airing ends, the mode to go back to, and a target chosen during airing; and for each room that is away, when away ends, the away target and the target to go back to. A room's rows are deleted once its thermostat confirms it is heating again or has its target back, so the file is a few kilobytes. Everything else is in memory and comes back from the thermostats' reports. Migrations are part of the binary and run at start; an older binary refuses a newer database. A request is answered only once its change is saved. If saving fails, the change isn't made and the page shows "Not changed". When airing ends while the database can't be written, the room still gets heat back, and the database catches up later. -If the file is lost, nothing unsafe happens: a room that was airing stays off until someone taps "Heat again" (the `TrvStuckOffWarning` alert fires after 2 hours), and a target chosen during airing is lost. Because of that, restoring a backup is optional: an old copy may even hold airing that is long over, which then simply ends at once. The service starts with an empty database if there is none, but refuses to start if it can't open or migrate the file. +If the file is lost, nothing unsafe happens: a room that was airing stays off until someone taps "Heat again" (the `TrvStuckOffWarning` alert fires after 2 hours), a target chosen during airing is lost, and rooms that are away stay at the away target until someone raises them. Because of that, restoring a backup is optional: an old copy may even hold airing or away that is long over, which then simply ends at once. The service starts with an empty database if there is none, but refuses to start if it can't open or migrate the file. To copy the database while the service runs: diff --git a/internal/api/api.gen.go b/internal/api/api.gen.go index 379d2c9..6afd065 100644 --- a/internal/api/api.gen.go +++ b/internal/api/api.gen.go @@ -18,22 +18,43 @@ import ( // Defines values for AiringState. const ( - Active AiringState = "active" - None AiringState = "none" - Restoring AiringState = "restoring" - Starting AiringState = "starting" + AiringStateActive AiringState = "active" + AiringStateNone AiringState = "none" + AiringStateRestoring AiringState = "restoring" + AiringStateStarting AiringState = "starting" ) // Valid indicates whether the value is a known member of the AiringState enum. func (e AiringState) Valid() bool { switch e { - case Active: + case AiringStateActive: return true - case None: + case AiringStateNone: return true - case Restoring: + case AiringStateRestoring: return true - case Starting: + case AiringStateStarting: + return true + default: + return false + } +} + +// Defines values for AwayState. +const ( + AwayStateAway AwayState = "away" + AwayStateNone AwayState = "none" + AwayStateRestoring AwayState = "restoring" +) + +// Valid indicates whether the value is a known member of the AwayState enum. +func (e AwayState) Valid() bool { + switch e { + case AwayStateAway: + return true + case AwayStateNone: + return true + case AwayStateRestoring: return true default: return false @@ -115,6 +136,18 @@ func (e TargetState) Valid() bool { // AiringState none means not airing. starting means airing was accepted and the thermostat hasn't confirmed it's off. active means it's off. restoring means airing has ended and the thermostat hasn't confirmed it's heating again. type AiringState string +// Away The current away, or null if there is none. +type Away struct { + // Target The away target in °C. + Target float64 `json:"target"` + + // Until When the rooms get their targets back. + Until time.Time `json:"until"` +} + +// AwayState none means the room isn't part of away. away means it's at the away target until away ends. restoring means away has ended and the thermostat hasn't confirmed the target from before. +type AwayState string + // Error defines model for Error. type Error struct { Message string `json:"message"` @@ -131,7 +164,13 @@ type Room struct { // AiringUntil When airing ends and heating comes back, or null if not airing. AiringUntil *time.Time `json:"airingUntil"` - // CommandFailed Whether the thermostat hasn't confirmed a command to turn off or heat again. The backend keeps trying, more slowly. + // AwayRestoreTarget The target the room gets back when away ends, or null if it isn't part of away. + AwayRestoreTarget *float64 `json:"awayRestoreTarget"` + + // AwayState none means the room isn't part of away. away means it's at the away target until away ends. restoring means away has ended and the thermostat hasn't confirmed the target from before. + AwayState AwayState `json:"awayState"` + + // CommandFailed Whether the thermostat hasn't confirmed a command to turn off, heat again or take back its target after away. The backend keeps trying, more slowly. CommandFailed bool `json:"commandFailed"` // Heating Whether the thermostat is calling for heat right now. @@ -157,6 +196,9 @@ type Room struct { // RoomList defines model for RoomList. type RoomList struct { + // Away The current away, or null if there is none. + Away *Away `json:"away"` + // Connected Whether the backend is connected to the broker. While it isn't, nothing can be sent and the rooms' values may be out of date. Connected bool `json:"connected"` @@ -183,9 +225,21 @@ type StartAiringRequest struct { // StartAiringRequestMinutes How long to air the room. type StartAiringRequestMinutes int +// StartAwayRequest defines model for StartAwayRequest. +type StartAwayRequest struct { + // Target The away target in °C, within minTarget and maxTarget. + Target float64 `json:"target"` + + // Until When to bring the targets back, at most 30 days ahead. + Until time.Time `json:"until"` +} + // TargetState applied means the thermostat confirmed the target. sending means it's on its way. held means it waits until the thermostat can take it. failed means the thermostat never confirmed the last change, so target shows what it reports instead. type TargetState string +// StartAwayJSONRequestBody defines body for StartAway for application/json ContentType. +type StartAwayJSONRequestBody = StartAwayRequest + // StartRoomAiringJSONRequestBody defines body for StartRoomAiring for application/json ContentType. type StartRoomAiringJSONRequestBody = StartAiringRequest @@ -194,6 +248,12 @@ type SetRoomTargetJSONRequestBody = SetTargetRequest // ServerInterface represents all server handlers. type ServerInterface interface { + // EndAway End away now and bring the old targets back. + // (DELETE /api/away) + EndAway(w http.ResponseWriter, r *http.Request) + // StartAway Lower every room's target until a time, then bring the old targets back. + // (PUT /api/away) + StartAway(w http.ResponseWriter, r *http.Request) // ListRooms List the rooms and the allowed target range. // (GET /api/rooms) ListRooms(w http.ResponseWriter, r *http.Request) @@ -217,6 +277,34 @@ type ServerInterfaceWrapper struct { type MiddlewareFunc func(http.Handler) http.Handler +// EndAway operation middleware +func (siw *ServerInterfaceWrapper) EndAway(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.EndAway(w, r) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r) +} + +// StartAway operation middleware +func (siw *ServerInterfaceWrapper) StartAway(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.StartAway(w, r) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r) +} + // ListRooms operation middleware func (siw *ServerInterfaceWrapper) ListRooms(w http.ResponseWriter, r *http.Request) { @@ -433,10 +521,127 @@ func HandlerWithOptions(si ServerInterface, options StdHTTPServerOptions) http.H m.HandleFunc(http.MethodPost+" "+options.BaseURL+"/api/rooms/{id}/target", wrapper.SetRoomTarget) m.HandleFunc(http.MethodDelete+" "+options.BaseURL+"/api/rooms/{id}/airing", wrapper.StopRoomAiring) m.HandleFunc(http.MethodPost+" "+options.BaseURL+"/api/rooms/{id}/airing", wrapper.StartRoomAiring) + m.HandleFunc(http.MethodDelete+" "+options.BaseURL+"/api/away", wrapper.EndAway) + m.HandleFunc(http.MethodPut+" "+options.BaseURL+"/api/away", wrapper.StartAway) return m } +type EndAwayRequestObject struct { +} + +type EndAwayResponseObject interface { + VisitEndAwayResponse(w http.ResponseWriter) error +} + +type EndAway202Response struct { +} + +func (response EndAway202Response) VisitEndAwayResponse(w http.ResponseWriter) error { + w.WriteHeader(202) + return nil +} + +type EndAway403JSONResponse Error + +func (response EndAway403JSONResponse) VisitEndAwayResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(403) + _, err := buf.WriteTo(w) + return err +} + +type EndAway500JSONResponse Error + +func (response EndAway500JSONResponse) VisitEndAwayResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(500) + _, err := buf.WriteTo(w) + return err +} + +type StartAwayRequestObject struct { + Body *StartAwayJSONRequestBody +} + +type StartAwayResponseObject interface { + VisitStartAwayResponse(w http.ResponseWriter) error +} + +type StartAway202Response struct { +} + +func (response StartAway202Response) VisitStartAwayResponse(w http.ResponseWriter) error { + w.WriteHeader(202) + return nil +} + +type StartAway400JSONResponse Error + +func (response StartAway400JSONResponse) VisitStartAwayResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + _, err := buf.WriteTo(w) + return err +} + +type StartAway403JSONResponse Error + +func (response StartAway403JSONResponse) VisitStartAwayResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(403) + _, err := buf.WriteTo(w) + return err +} + +type StartAway409JSONResponse Error + +func (response StartAway409JSONResponse) VisitStartAwayResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(409) + _, err := buf.WriteTo(w) + return err +} + +type StartAway500JSONResponse Error + +func (response StartAway500JSONResponse) VisitStartAwayResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(500) + _, err := buf.WriteTo(w) + return err +} + type ListRoomsRequestObject struct { } @@ -702,6 +907,12 @@ func (response SetRoomTarget500JSONResponse) VisitSetRoomTargetResponse(w http.R // StrictServerInterface represents all server handlers. type StrictServerInterface interface { + // EndAway End away now and bring the old targets back. + // (DELETE /api/away) + EndAway(ctx context.Context, request EndAwayRequestObject) (EndAwayResponseObject, error) + // StartAway Lower every room's target until a time, then bring the old targets back. + // (PUT /api/away) + StartAway(ctx context.Context, request StartAwayRequestObject) (StartAwayResponseObject, error) // ListRooms List the rooms and the allowed target range. // (GET /api/rooms) ListRooms(ctx context.Context, request ListRoomsRequestObject) (ListRoomsResponseObject, error) @@ -755,6 +966,61 @@ type strictHandler struct { options StrictHTTPServerOptions } +// EndAway operation middleware +func (sh *strictHandler) EndAway(w http.ResponseWriter, r *http.Request) { + var request EndAwayRequestObject + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.EndAway(ctx, request.(EndAwayRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "EndAway") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(EndAwayResponseObject); ok { + if err := validResponse.VisitEndAwayResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// StartAway operation middleware +func (sh *strictHandler) StartAway(w http.ResponseWriter, r *http.Request) { + var request StartAwayRequestObject + + var body StartAwayJSONRequestBody + if err := runtime.BindJSONBody(r, &body); err != nil { + sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) + return + } + request.Body = &body + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.StartAway(ctx, request.(StartAwayRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "StartAway") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(StartAwayResponseObject); ok { + if err := validResponse.VisitStartAwayResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + // ListRooms operation middleware func (sh *strictHandler) ListRooms(w http.ResponseWriter, r *http.Request) { var request ListRoomsRequestObject diff --git a/internal/api/openapi.yaml b/internal/api/openapi.yaml index d54753b..83ef352 100644 --- a/internal/api/openapi.yaml +++ b/internal/api/openapi.yaml @@ -5,7 +5,7 @@ info: The contract between the heating-control backend and its page. Go types and the server interface are generated from this file, so change it first and run `go generate ./...`. - version: 0.3.0 + version: 0.4.0 paths: /api/rooms: get: @@ -173,12 +173,86 @@ paths: application/json: schema: $ref: "#/components/schemas/Error" + /api/away: + put: + operationId: startAway + summary: Lower every room's target until a time, then bring the old targets back. + description: >- + Each room with a known target remembers it and gets the away target. At + until, every room that is still at the away target gets its remembered + target back, confirmed by the thermostat with the same retries as the end + of airing. A room whose target was changed meanwhile is left alone. + Calling this again during away sets a new end time and target and keeps + the remembered targets. A 202 means away was accepted and saved, so it + carries on after a restart: follow away and each room's awayState in the + room list. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/StartAwayRequest" + responses: + "202": + description: Away was accepted. + "400": + description: >- + The body is invalid, until isn't in the future or is more than 30 days + ahead, or the target is outside the allowed range. + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "403": + description: The request came from another website, or by an unknown host name. + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "409": + description: No room's target is known yet, so there's nothing to bring back. + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "500": + description: >- + The server couldn't save the change, so nothing changed, or it failed + to write the response. + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + delete: + operationId: endAway + summary: End away now and bring the old targets back. + description: >- + The same as reaching until now. Without away it does nothing. + responses: + "202": + description: Accepted. + "403": + description: The request came from another website, or by an unknown host name. + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "500": + description: >- + The server couldn't save the change, so nothing changed, or it failed + to write the response. + content: + application/json: + schema: + $ref: "#/components/schemas/Error" components: schemas: RoomList: type: object - required: [rooms, connected, minTarget, maxTarget] + required: [rooms, connected, minTarget, maxTarget, away] properties: + away: + $ref: "#/components/schemas/Away" connected: type: boolean description: >- @@ -198,7 +272,7 @@ components: description: The highest target allowed, in °C. Room: type: object - required: [id, label, temperature, target, targetState, mode, heating, airingState, airingUntil, lastSeen, commandFailed] + required: [id, label, temperature, target, targetState, mode, heating, airingState, airingUntil, awayState, awayRestoreTarget, lastSeen, commandFailed] properties: id: type: string @@ -228,6 +302,15 @@ components: format: date-time nullable: true description: When airing ends and heating comes back, or null if not airing. + awayState: + $ref: "#/components/schemas/AwayState" + awayRestoreTarget: + type: number + format: double + nullable: true + description: >- + The target the room gets back when away ends, or null if it isn't + part of away. lastSeen: type: string format: date-time @@ -236,8 +319,9 @@ components: commandFailed: type: boolean description: >- - Whether the thermostat hasn't confirmed a command to turn off or heat - again. The backend keeps trying, more slowly. + Whether the thermostat hasn't confirmed a command to turn off, heat + again or take back its target after away. The backend keeps trying, + more slowly. Mode: type: string enum: [unknown, "off", auto, heat] @@ -257,6 +341,39 @@ components: none means not airing. starting means airing was accepted and the thermostat hasn't confirmed it's off. active means it's off. restoring means airing has ended and the thermostat hasn't confirmed it's heating again. + Away: + type: object + nullable: true + required: [until, target] + description: The current away, or null if there is none. + properties: + until: + type: string + format: date-time + description: When the rooms get their targets back. + target: + type: number + format: double + description: The away target in °C. + AwayState: + type: string + enum: [none, away, restoring] + description: >- + none means the room isn't part of away. away means it's at the away + target until away ends. restoring means away has ended and the + thermostat hasn't confirmed the target from before. + StartAwayRequest: + type: object + required: [until, target] + properties: + until: + type: string + format: date-time + description: When to bring the targets back, at most 30 days ahead. + target: + type: number + format: double + description: The away target in °C, within minTarget and maxTarget. StartAiringRequest: type: object required: [minutes] diff --git a/internal/controller/airing.go b/internal/controller/airing.go index e6e1415..c23ffdb 100644 --- a/internal/controller/airing.go +++ b/internal/controller/airing.go @@ -69,3 +69,10 @@ func (a airing) RoomID() string { return a.roomID } func (a airing) Until() (time.Time, bool) { return a.until, !a.until.IsZero() } func (a airing) RestoreMode() Mode { return a.restoreMode } func (a airing) HeldTarget() (float64, bool) { return a.heldTarget, a.hasHeldTarget } + +// airingOf returns a as the comparable struct the controller keeps. +func airingOf(a Airing) airing { + until, _ := a.Until() + target, held := a.HeldTarget() + return airing{roomID: a.RoomID(), until: until.UTC(), restoreMode: a.RestoreMode(), heldTarget: target, hasHeldTarget: held} +} diff --git a/internal/controller/away.go b/internal/controller/away.go new file mode 100644 index 0000000..d13c22a --- /dev/null +++ b/internal/controller/away.go @@ -0,0 +1,206 @@ +package controller + +import ( + "context" + "errors" + "fmt" + "math" + "time" +) + +// maxAway is how far ahead away may end. +const maxAway = 30 * 24 * time.Hour + +// ErrAwayUntil is returned for an end of away that isn't in the future or is +// more than 30 days ahead. +var ErrAwayUntil = errors.New("away must end in the future and within 30 days") + +// ErrNoKnownTarget is returned when away starts before any room's target is +// known, so there would be nothing to bring back. +var ErrNoKnownTarget = errors.New("no room's target is known yet") + +// AwayStore keeps each room's part of away, so the old targets come back even +// after a restart. +type AwayStore interface { + // Aways returns every saved away. + Aways(ctx context.Context) ([]Away, error) + // SaveAway replaces the room's saved away. It returns once it is durable. + SaveAway(ctx context.Context, a Away) error + // DeleteAway removes the room's saved away, if there is one. + DeleteAway(ctx context.Context, roomID string) error +} + +// Store is everything the controller saves. +type Store interface { + AiringStore + AwayStore +} + +// Away is a room's part of away: the target it has until away ends, and the +// target it gets back then. +type Away interface { + RoomID() string + // Until is when away ends. ok is false once it has ended and the room is + // waiting for its thermostat to confirm the target from before. + Until() (until time.Time, ok bool) + // Target is the away target. + Target() float64 + // RestoreTarget is the target from before away. + RestoreTarget() float64 +} + +// RestoreAway recreates a saved away. until is the zero time once away has +// ended. +func RestoreAway(roomID string, until time.Time, target, restoreTarget float64) (Away, error) { + if roomID == "" { + return nil, errors.New("away: room id is empty") + } + for _, t := range []float64{target, restoreTarget} { + if math.IsNaN(t) || math.IsInf(t, 0) { + return nil, fmt.Errorf("away: %v isn't a temperature", t) + } + } + return away{roomID: roomID, until: until.UTC(), target: target, restoreTarget: restoreTarget}, nil +} + +// away is comparable with ==, because until is always UTC. +type away struct { + roomID string + until time.Time + target float64 + restoreTarget float64 +} + +func (a away) RoomID() string { return a.roomID } +func (a away) Until() (time.Time, bool) { return a.until, !a.until.IsZero() } +func (a away) Target() float64 { return a.target } +func (a away) RestoreTarget() float64 { return a.restoreTarget } + +// StartAway gives every room with a known target the away target until until, +// and remembers its target to bring back then. Called during away, it sets a +// new end time and target and keeps the remembered targets. Rooms are changed +// together: if one can't be saved, none is. +func (c *Controller) StartAway(until time.Time, target float64) error { + 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.changeAll(func(now time.Time) error { + if !until.After(now) || until.After(now.Add(maxAway)) { + return ErrAwayUntil + } + started := false + for _, r := range c.rooms { + if r.startAway(until.UTC(), target) { + started = true + } + } + if !started { + return ErrNoKnownTarget + } + return nil + }) +} + +// EndAway ends away now: every room still at the away target gets its target +// from before. Without away it does nothing. +func (c *Controller) EndAway() error { + return c.changeAll(func(now time.Time) error { + for _, r := range c.rooms { + if r.awayUntil != nil { + r.endAway() + } + } + return nil + }) +} + +// startAway lowers the room to target until until. It reports false if the room +// can't take part because its target isn't known. +func (r *room) startAway(until time.Time, target float64) bool { + if !r.inAway { + if r.target == nil { + return false + } + r.inAway = true + r.awayRestoreTarget = *r.target + } + if r.target == nil || *r.target != target { + r.setTarget(target) + } + r.awayUntil = &until + r.awayTarget = target + return true +} + +// endAway brings the target from before back, unless someone changed the target +// during away. Without a known target it waits: comparing needs one. +func (r *room) endAway() { + if r.target == nil { + return + } + r.awayUntil = nil + if *r.target != r.awayTarget { + r.inAway = false + return + } + if r.awayRestoreTarget == r.awayTarget { + r.inAway = false + return + } + r.setTarget(r.awayRestoreTarget) +} + +// awayRestoring reports whether away has ended and the target from before isn't +// confirmed yet. Such a target is never given up, like the end of airing. +func (r *room) awayRestoring() bool { + return r.inAway && r.awayUntil == nil +} + +// advanceAway applies what time and confirmations change about away. +func (r *room) advanceAway(now time.Time) { + if r.awayUntil != nil && !now.Before(*r.awayUntil) { + r.endAway() + } + if r.awayRestoring() && !r.targetDirty { + r.inAway = false + } +} + +// pendingAway returns what of the room's away must survive a restart, or false +// if nothing must. +func (r *room) pendingAway() (away, bool) { + if !r.inAway { + return away{}, false + } + a := away{roomID: r.cfg.ID, target: r.awayTarget, restoreTarget: r.awayRestoreTarget} + if r.awayUntil != nil { + a.until = r.awayUntil.UTC() + } + return a, true +} + +// resumeAway carries on with an away saved before a restart. During away the +// thermostat reports the target. Once it has ended, the target from before is +// sent again until the thermostat confirms it. +func (r *room) resumeAway(a Away) { + r.inAway = true + r.awayTarget = a.Target() + r.awayRestoreTarget = a.RestoreTarget() + if until, ok := a.Until(); ok { + r.awayUntil = &until + return + } + // A target held for airing wins: it was chosen later. + if !r.targetDirty { + target := a.RestoreTarget() + r.target = &target + r.targetDirty = true + } +} + +// awayOf returns a as the comparable struct the controller keeps. +func awayOf(a Away) away { + until, _ := a.Until() + return away{roomID: a.RoomID(), until: until.UTC(), target: a.Target(), restoreTarget: a.RestoreTarget()} +} diff --git a/internal/controller/away_test.go b/internal/controller/away_test.go new file mode 100644 index 0000000..5fd2c51 --- /dev/null +++ b/internal/controller/away_test.go @@ -0,0 +1,303 @@ +package controller + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/subpathdev/heating-control/internal/config" +) + +func (h *harness) startAway(d time.Duration, target float64) { + h.t.Helper() + if err := h.c.StartAway(h.now.Add(d), target); err != nil { + h.t.Fatal(err) + } + h.c.tick() +} + +func (h *harness) lastTarget() float64 { + h.t.Helper() + cmd := h.f.sent[len(h.f.sent)-1] + if cmd.Target == nil { + h.t.Fatalf("last command %s has no target", cmd.Kind()) + } + return *cmd.Target +} + +func TestAwayLowersAndBringsTheTargetBack(t *testing.T) { + h := newHarness(t) + h.report("heat", 21) + + h.startAway(48*time.Hour, 17) + h.wantKinds("set_target") + if got := h.lastTarget(); got != 17 { + t.Fatalf("sent %v, want 17", got) + } + h.report("heat", 17) + s := h.status() + if s.AwayUntil == nil || !s.AwayUntil.Equal(h.now.Add(48*time.Hour)) || *s.AwayTarget != 17 || *s.AwayRestoreTarget != 21 { + t.Fatalf("status = %+v", s) + } + a, ok := h.store.getAway("office") + if !ok || a.RestoreTarget() != 21 || a.Target() != 17 { + t.Fatalf("saved away = %+v, %v", a, ok) + } + + h.advance(48*time.Hour - time.Second) + h.wantKinds("set_target") + h.advance(time.Second) + h.wantKinds("set_target", "set_target") + if got := h.lastTarget(); got != 21 { + t.Fatalf("sent %v, want 21", got) + } + s = h.status() + if s.AwayUntil != nil || s.AwayRestoreTarget == nil || s.TargetState != TargetSending { + t.Fatalf("status = %+v, want restoring", s) + } + if a, _ := h.store.getAway("office"); func() bool { _, ok := a.Until(); return ok }() { + t.Fatal("ended away not saved as restoring") + } + + h.report("heat", 21) + h.c.tick() + if s := h.status(); s.AwayRestoreTarget != nil || s.TargetState != TargetApplied { + t.Fatalf("status = %+v, want away over", s) + } + if _, ok := h.store.getAway("office"); ok { + t.Fatal("away still saved after the target was confirmed") + } +} + +func TestAwayLeavesARoomChangedMeanwhileAlone(t *testing.T) { + h := newHarness(t) + h.report("heat", 21) + h.startAway(time.Hour, 17) + h.report("heat", 17) + + // Someone turns the knob. + h.report("heat", 19) + h.advance(time.Hour) + h.wantKinds("set_target") + if s := h.status(); s.AwayRestoreTarget != nil || *s.Target != 19 { + t.Fatalf("status = %+v, want 19 and away over", s) + } + if _, ok := h.store.getAway("office"); ok { + t.Fatal("away still saved") + } +} + +func TestAwayRestoreNeverGivesUp(t *testing.T) { + h := newHarness(t) + h.report("heat", 21) + h.startAway(time.Hour, 17) + h.report("heat", 17) + h.advance(time.Hour) + + for range maxAttempts { + h.advance(retryInterval) + } + s := h.status() + if !s.CommandFailed || s.TargetState != TargetSending || *s.Target != 21 { + t.Fatalf("status = %+v, want still sending 21 and a problem", s) + } + sent := len(h.f.sent) + h.advance(slowRetryInterval) + if len(h.f.sent) != sent+1 || h.lastTarget() != 21 { + t.Fatalf("no slow retry: %v", h.f.kinds()) + } + h.report("heat", 21) + h.c.tick() + if s := h.status(); s.CommandFailed || s.AwayRestoreTarget != nil { + t.Fatalf("status = %+v, want done", s) + } +} + +func TestStartAwayRejects(t *testing.T) { + h := newHarness(t) + if err := h.c.StartAway(h.now.Add(time.Hour), 17); !errors.Is(err, ErrNoKnownTarget) { + t.Fatalf("without a known target: %v, want ErrNoKnownTarget", err) + } + h.report("heat", 21) + tests := []struct { + name string + until time.Time + target float64 + want error + }{ + {"now", h.now, 17, ErrAwayUntil}, + {"past", h.now.Add(-time.Minute), 17, ErrAwayUntil}, + {"too far", h.now.Add(maxAway + time.Second), 17, ErrAwayUntil}, + {"too cold", h.now.Add(time.Hour), 5, ErrTargetOutOfRange}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := h.c.StartAway(tt.until, tt.target); !errors.Is(err, tt.want) { + t.Fatalf("StartAway = %v, want %v", err, tt.want) + } + if s := h.status(); s.AwayRestoreTarget != nil || *s.Target != 21 { + t.Fatalf("status = %+v, want unchanged", s) + } + }) + } + if err := h.c.StartAway(h.now.Add(maxAway), 17); err != nil { + t.Fatalf("exactly 30 days: %v", err) + } +} + +func TestAwayAgainKeepsTheTargetFromBefore(t *testing.T) { + h := newHarness(t) + h.report("heat", 21) + h.startAway(time.Hour, 17) + h.report("heat", 17) + + h.startAway(2*time.Hour, 16) + if got := h.lastTarget(); got != 16 { + t.Fatalf("sent %v, want 16", got) + } + h.report("heat", 16) + if s := h.status(); *s.AwayRestoreTarget != 21 || *s.AwayTarget != 16 { + t.Fatalf("status = %+v", s) + } + h.advance(2 * time.Hour) + if got := h.lastTarget(); got != 21 { + t.Fatalf("sent %v, want 21", got) + } +} + +func TestEndAwayBringsTheTargetBackNow(t *testing.T) { + h := newHarness(t) + h.report("heat", 21) + h.startAway(time.Hour, 17) + h.report("heat", 17) + + if err := h.c.EndAway(); err != nil { + t.Fatal(err) + } + h.c.tick() + if got := h.lastTarget(); got != 21 { + t.Fatalf("sent %v, want 21", got) + } + if err := h.c.EndAway(); err != nil { + t.Fatalf("ending again: %v", err) + } +} + +func TestStartAwayThatCantBeSavedChangesNothing(t *testing.T) { + h := newHarness(t) + h.report("heat", 21) + h.store.err = errors.New("disk full") + + if err := h.c.StartAway(h.now.Add(time.Hour), 17); !errors.Is(err, ErrNotSaved) { + t.Fatalf("StartAway = %v, want ErrNotSaved", err) + } + h.c.tick() + h.wantKinds() + if s := h.status(); s.AwayRestoreTarget != nil || *s.Target != 21 || s.TargetState != TargetApplied { + t.Fatalf("status = %+v, want unchanged", s) + } +} + +func TestAwayDuringAiringWaitsForIt(t *testing.T) { + h := newHarness(t) + h.report("heat", 21) + h.startAiring(30 * time.Minute) + h.report("off", 7) + + h.startAway(10*time.Minute, 17) + h.wantKinds("off") + if s := h.status(); s.TargetState != TargetHeld || *s.Target != 17 { + t.Fatalf("status = %+v", s) + } + + // Away ends during airing, so airing brings back the target from before. + h.advance(10 * time.Minute) + h.wantKinds("off") + h.advance(20 * time.Minute) + h.wantKinds("off", "restore") + if got := h.lastTarget(); got != 21 { + t.Fatalf("restored %v, want 21", got) + } + h.report("heat", 21) + h.c.tick() + if s := h.status(); s.AwayRestoreTarget != nil || s.AiringState != AiringNone { + t.Fatalf("status = %+v, want both over", s) + } +} + +func TestAwayCarriesOnAfterARestart(t *testing.T) { + store := newMemStore() + now := time.Unix(5000, 0) + a, err := RestoreAway("office", now.Add(time.Hour), 17, 21) + if err != nil { + t.Fatal(err) + } + store.aways["office"] = a + + h := restartHarness(t, store, now) + h.report("heat", 17) + h.wantKinds() + h.advance(time.Hour) + if got := h.lastTarget(); got != 21 { + t.Fatalf("sent %v, want 21", got) + } +} + +func TestAwayRestoreCarriesOnAfterARestart(t *testing.T) { + store := newMemStore() + a, err := RestoreAway("office", time.Time{}, 17, 30) + if err != nil { + t.Fatal(err) + } + store.aways["office"] = a + + h := restartHarness(t, store, time.Unix(5000, 0)) + h.report("heat", 17) + // 30 is above the allowed 25 now, so the nearest allowed comes back. + if got := h.lastTarget(); got != 25 { + t.Fatalf("sent %v, want 25", got) + } + if a, _ := store.getAway("office"); a.RestoreTarget() != 25 { + t.Fatalf("store has %v, want the adjusted 25", a.RestoreTarget()) + } + h.report("heat", 25) + h.c.tick() + if _, ok := store.getAway("office"); ok { + t.Fatal("away still saved") + } +} + +func TestAwaySkipsARoomWithoutAKnownTarget(t *testing.T) { + f := &fakeThermostat{} + c, err := New(context.Background(), &config.Config{ + MinTarget: 10, + MaxTarget: 25, + Rooms: []config.Room{ + {ID: "office", Label: "Office", TRV: "trv-office"}, + {ID: "bedroom", Label: "Bedroom", TRV: "trv-bedroom"}, + }, + }, f, newMemStore()) + if err != nil { + t.Fatal(err) + } + c.HandleThermostatState("trv-office", state("heat", 21)) + if err := c.StartAway(time.Now().Add(time.Hour), 17); err != nil { + t.Fatal(err) + } + rooms := c.Rooms() + if rooms[0].AwayRestoreTarget == nil || rooms[1].AwayRestoreTarget != nil { + t.Fatalf("rooms = %+v, want only the office away", rooms) + } +} + +func TestRestoreAwayRejects(t *testing.T) { + nan := 0.0 + nan /= nan + if _, err := RestoreAway("", time.Time{}, 17, 21); err == nil { + t.Error("empty room: want an error") + } + if _, err := RestoreAway("office", time.Time{}, nan, 21); err == nil { + t.Error("NaN: want an error") + } +} diff --git a/internal/controller/controller.go b/internal/controller/controller.go index 32b0ca5..63f05f2 100644 --- a/internal/controller/controller.go +++ b/internal/controller/controller.go @@ -118,6 +118,12 @@ type RoomStatus struct { 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. @@ -125,7 +131,7 @@ type Controller struct { thermostat Thermostat now func() time.Time min, max float64 - store AiringStore + store Store wake chan struct{} // saveMu orders writes to the store, so an older state never overwrites a @@ -139,9 +145,9 @@ type Controller struct { } // New returns a Controller for the configured rooms, carrying on with the -// airing saved in store. A saved airing 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 AiringStore) (*Controller, error) { +// 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, @@ -153,9 +159,18 @@ func New(ctx context.Context, cfg *config.Config, thermostat Thermostat, store A for _, r := range cfg.Rooms { c.rooms = append(c.rooms, &room{cfg: r}) } - airings, err := store.Airings(ctx) + 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 nil, fmt.Errorf("load airing: %w", err) + return fmt.Errorf("load airing: %w", err) } for _, a := range airings { r := c.find(a.RoomID()) @@ -163,30 +178,45 @@ func New(ctx context.Context, cfg *config.Config, thermostat Thermostat, store A log.Printf("saved airing for unknown room %q ignored", a.RoomID()) continue } - trimmed := false + r.saved.airing, r.saved.hasAiring = airingOf(a), true if target, ok := a.HeldTarget(); ok && !c.inRange(target) { - trimmed = true // 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) - a, err = RestoreAiring(a.RoomID(), untilOrZero(a), a.RestoreMode(), nil) - if err != nil { - return nil, err + until, _ := a.Until() + if a, err = RestoreAiring(a.RoomID(), until, a.RestoreMode(), nil); err != nil { + return err } } r.resume(a) - if trimmed { - // The store still has the old target, so the next tick saves this one. - r.hasSaved = false - } log.Printf("%s: carrying on with saved airing", r.cfg.TRV) } - return c, nil -} -func untilOrZero(a Airing) time.Time { - until, _ := a.Until() - return until + 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. @@ -238,52 +268,87 @@ func (c *Controller) tick() { for _, r := range c.rooms { c.saveMu.Lock() c.mu.Lock() - next, ok := r.pending() + next := r.toSave() c.mu.Unlock() - if err := c.save(r, next, ok); err != nil { + if err := c.save(r, next); err != nil { // Tried again on the next tick. - log.Printf("%s: save airing: %v", r.cfg.TRV, err) + log.Printf("%s: save: %v", r.cfg.TRV, err) } c.saveMu.Unlock() } } -// save writes the room's airing if it differs from what the store holds. The -// caller holds saveMu. -func (c *Controller) save(r *room, next airing, ok bool) error { - if ok == r.hasSaved && next == r.saved { - return nil - } +// 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() - var err error - if ok { - err = c.store.SaveAiring(ctx, next) - } else { - err = c.store.DeleteAiring(ctx, r.cfg.ID) + 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 err != nil { - return err + 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 } - r.saved, r.hasSaved = next, ok 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 := *r - apply(c.now()) - next, ok := r.pending() - if err := c.save(r, next, ok); err != nil { - *r = before - log.Printf("%s: save airing: %v", r.cfg.TRV, err) - return fmt.Errorf("%w: %v", ErrNotSaved, err) + 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 diff --git a/internal/controller/room.go b/internal/controller/room.go index df0da77..dd363be 100644 --- a/internal/controller/room.go +++ b/internal/controller/room.go @@ -88,9 +88,31 @@ type room struct { flips int targetFailed bool + // Away: inAway is set from start until the target from before is confirmed. + // awayUntil is nil once away has ended. + inAway bool + awayUntil *time.Time + awayTarget float64 + awayRestoreTarget float64 + // What the store holds for this room. Guarded by Controller.saveMu, not mu. - saved airing - hasSaved bool + saved saved +} + +// saved is what the store holds for a room. It is comparable with ==. +type saved struct { + airing airing + hasAiring bool + away away + hasAway bool +} + +// toSave returns what of the room must survive a restart. +func (r *room) toSave() saved { + var s saved + s.airing, s.hasAiring = r.pending() + s.away, s.hasAway = r.pendingAway() + return s } // decide returns the command the room needs now, if any. It changes nothing. @@ -128,13 +150,14 @@ func (r *room) due(now time.Time) bool { // advance applies what time alone changes. func (r *room) advance(now time.Time) { + r.advanceAway(now) if r.canWrite() && !r.settled && !now.Before(r.onSince.Add(settleTime)) { r.settled = true } switch { case r.airingUntil != nil && !now.Before(*r.airingUntil): r.endAiring(now) - case r.targetDirty && r.airingUntil == nil && !r.restoring && r.canWrite() && + case r.targetDirty && r.airingUntil == nil && !r.restoring && r.canWrite() && !r.awayRestoring() && r.attempts >= maxAttempts && !now.Before(r.lastSent.Add(retryInterval)): // A knob turn and a lost write look the same, so the thermostat wins and // the page says so. @@ -318,6 +341,13 @@ func (r *room) status() RoomStatus { case r.restoring: s.AiringState = AiringRestoring s.CommandFailed = r.attempts >= maxAttempts + case r.awayRestoring(): + s.CommandFailed = r.attempts >= maxAttempts + } + if r.inAway { + s.AwayUntil = r.awayUntil + s.AwayTarget = &r.awayTarget + s.AwayRestoreTarget = &r.awayRestoreTarget } return s } @@ -379,6 +409,4 @@ func (r *room) resume(a Airing) { r.target = &target r.targetDirty = true } - // It's what the store holds, so there's nothing to save until it changes. - r.saved, r.hasSaved = r.pending() } diff --git a/internal/controller/store_test.go b/internal/controller/store_test.go index 54d02ff..6c5b0ad 100644 --- a/internal/controller/store_test.go +++ b/internal/controller/store_test.go @@ -10,16 +10,52 @@ import ( "time" ) -// memStore is an AiringStore in memory. err makes every write fail. +// memStore is a Store in memory. err makes every write fail. type memStore struct { mu sync.Mutex airings map[string]Airing + aways map[string]Away writes int err error } func newMemStore() *memStore { - return &memStore{airings: map[string]Airing{}} + return &memStore{airings: map[string]Airing{}, aways: map[string]Away{}} +} + +func (m *memStore) Aways(context.Context) ([]Away, error) { + m.mu.Lock() + defer m.mu.Unlock() + return slices.Collect(maps.Values(m.aways)), nil +} + +func (m *memStore) SaveAway(_ context.Context, a Away) error { + m.mu.Lock() + defer m.mu.Unlock() + if m.err != nil { + return m.err + } + m.writes++ + m.aways[a.RoomID()] = a + return nil +} + +func (m *memStore) DeleteAway(_ context.Context, roomID string) error { + m.mu.Lock() + defer m.mu.Unlock() + if m.err != nil { + return m.err + } + m.writes++ + delete(m.aways, roomID) + return nil +} + +func (m *memStore) getAway(roomID string) (Away, bool) { + m.mu.Lock() + defer m.mu.Unlock() + a, ok := m.aways[roomID] + return a, ok } func (m *memStore) Airings(context.Context) ([]Airing, error) { diff --git a/internal/sqlite/migrations/0002_away.sql b/internal/sqlite/migrations/0002_away.sql new file mode 100644 index 0000000..2d9b242 --- /dev/null +++ b/internal/sqlite/migrations/0002_away.sql @@ -0,0 +1,11 @@ +-- One row per room that is part of away, until its thermostat confirms the +-- target from before. +CREATE TABLE away ( + room_id TEXT PRIMARY KEY, + -- RFC 3339 in UTC. NULL once away has ended. + until TEXT, + -- The away target, in °C. + target REAL NOT NULL, + -- The target from before away, in °C. + restore_target REAL NOT NULL +) STRICT; diff --git a/internal/sqlite/sqlite.go b/internal/sqlite/sqlite.go index ef79369..07a2faa 100644 --- a/internal/sqlite/sqlite.go +++ b/internal/sqlite/sqlite.go @@ -1,4 +1,5 @@ -// Package sqlite keeps the controller's saved state in a SQLite database. +// Package sqlite keeps the controller's saved airing and away in a SQLite +// database. package sqlite import ( @@ -29,7 +30,7 @@ var migrations embed.FS // DB is the saved state. It is safe for concurrent use. type DB interface { - controller.AiringStore + controller.Store // Backup writes a consistent copy of the database to path, which must not // exist yet. It works while the service runs. Backup(ctx context.Context, path string) error @@ -203,3 +204,66 @@ func (d *db) Backup(ctx context.Context, path string) error { _, err := d.sql.ExecContext(ctx, "VACUUM INTO ?", path) return err } + +// awayRow is a row of the away table. +type awayRow struct { + roomID string + until sql.NullString + target float64 + restoreTarget float64 +} + +func toAwayRow(a controller.Away) awayRow { + row := awayRow{roomID: a.RoomID(), target: a.Target(), restoreTarget: a.RestoreTarget()} + if until, ok := a.Until(); ok { + row.until = sql.NullString{String: until.UTC().Format(time.RFC3339Nano), Valid: true} + } + return row +} + +func (row awayRow) toAway() (controller.Away, error) { + var until time.Time + if row.until.Valid { + var err error + if until, err = time.Parse(time.RFC3339Nano, row.until.String); err != nil { + return nil, fmt.Errorf("room %q: until: %w", row.roomID, err) + } + } + return controller.RestoreAway(row.roomID, until, row.target, row.restoreTarget) +} + +func (d *db) Aways(ctx context.Context) ([]controller.Away, error) { + rows, err := d.sql.QueryContext(ctx, "SELECT room_id, until, target, restore_target FROM away ORDER BY room_id") + if err != nil { + return nil, err + } + defer func() { _ = rows.Close() }() + var out []controller.Away + for rows.Next() { + var row awayRow + if err := rows.Scan(&row.roomID, &row.until, &row.target, &row.restoreTarget); err != nil { + return nil, err + } + a, err := row.toAway() + if err != nil { + return nil, err + } + out = append(out, a) + } + return out, rows.Err() +} + +func (d *db) SaveAway(ctx context.Context, a controller.Away) error { + row := toAwayRow(a) + _, err := d.sql.ExecContext(ctx, ` + INSERT INTO away (room_id, until, target, restore_target) VALUES (?, ?, ?, ?) + ON CONFLICT (room_id) DO UPDATE SET + until = excluded.until, target = excluded.target, restore_target = excluded.restore_target`, + row.roomID, row.until, row.target, row.restoreTarget) + return err +} + +func (d *db) DeleteAway(ctx context.Context, roomID string) error { + _, err := d.sql.ExecContext(ctx, "DELETE FROM away WHERE room_id = ?", roomID) + return err +} diff --git a/internal/sqlite/sqlite_test.go b/internal/sqlite/sqlite_test.go index e3175f4..86bb38c 100644 --- a/internal/sqlite/sqlite_test.go +++ b/internal/sqlite/sqlite_test.go @@ -218,3 +218,133 @@ func (r *recorder) Apply(_ string, cmd controller.Command) error { func report(mode controller.Mode, setpoint float64) controller.ThermostatState { return controller.ThermostatState{Mode: &mode, Setpoint: &setpoint} } + +func TestAwayRoundTrip(t *testing.T) { + ctx := context.Background() + d := open(t, t.TempDir()) + defer func() { _ = d.Close() }() + + until := time.Date(2026, 12, 4, 17, 0, 0, 0, time.UTC) + for _, a := range []controller.Away{ + mustAway(t, "office", until, 17, 21), + mustAway(t, "bedroom", time.Time{}, 17, 19.5), + } { + if err := d.SaveAway(ctx, a); err != nil { + t.Fatal(err) + } + } + got, err := d.Aways(ctx) + if err != nil || len(got) != 2 { + t.Fatalf("Aways = %v, %v", got, err) + } + bedroom, office := got[0], got[1] + if u, ok := office.Until(); !ok || !u.Equal(until) || office.Target() != 17 || office.RestoreTarget() != 21 { + t.Errorf("office = %+v", office) + } + if _, ok := bedroom.Until(); ok || bedroom.RestoreTarget() != 19.5 { + t.Errorf("bedroom = %+v", bedroom) + } + + if err := d.SaveAway(ctx, mustAway(t, "office", time.Time{}, 17, 21)); err != nil { + t.Fatal(err) + } + if err := d.DeleteAway(ctx, "bedroom"); err != nil { + t.Fatal(err) + } + got, err = d.Aways(ctx) + if err != nil || len(got) != 1 { + t.Fatalf("Aways = %v, %v", got, err) + } + if _, ok := got[0].Until(); ok { + t.Fatal("save didn't replace the end time") + } +} + +// A database from the version before away gets the away table. +func TestOpenMigratesAnOlderDatabase(t *testing.T) { + ctx := context.Background() + dir := t.TempDir() + d := open(t, dir) + if err := d.SaveAiring(ctx, airing(t, "office", time.Time{}, controller.ModeHeat, nil)); err != nil { + t.Fatal(err) + } + if _, err := d.(*db).sql.Exec("DROP TABLE away; PRAGMA user_version = 1"); err != nil { + t.Fatal(err) + } + if err := d.Close(); err != nil { + t.Fatal(err) + } + + d = open(t, dir) + defer func() { _ = d.Close() }() + if got, err := d.Airings(ctx); err != nil || len(got) != 1 { + t.Fatalf("airing lost in the migration: %v, %v", got, err) + } + if err := d.SaveAway(ctx, mustAway(t, "office", time.Time{}, 17, 21)); err != nil { + t.Fatalf("away table missing: %v", err) + } +} + +// The end-to-end case for away: away that ends while the service is down still +// brings the target back after it starts again. +func TestAwaySurvivesReopenAndTheRestoreFires(t *testing.T) { + ctx := context.Background() + dir := t.TempDir() + cfg := &config.Config{ + MinTarget: 10, + MaxTarget: 25, + Rooms: []config.Room{{ID: "office", Label: "Office", TRV: "trv-office"}}, + } + + before := open(t, dir) + first, err := controller.New(ctx, cfg, &recorder{}, before) + if err != nil { + t.Fatal(err) + } + first.HandleThermostatState("trv-office", report(controller.ModeHeat, 21)) + if err := first.StartAway(time.Now().Add(50*time.Millisecond), 17); err != nil { + t.Fatal(err) + } + if err := before.Close(); err != nil { + t.Fatal(err) + } + time.Sleep(100 * time.Millisecond) + + after := open(t, dir) + defer func() { _ = after.Close() }() + rec := &recorder{sent: make(chan controller.Command, 10)} + second, err := controller.New(ctx, cfg, rec, after) + if err != nil { + t.Fatal(err) + } + // The thermostat reports the away target it got before the restart. + second.HandleThermostatState("trv-office", report(controller.ModeHeat, 17)) + runCtx, cancel := context.WithCancel(ctx) + done := make(chan struct{}) + go func() { + second.Run(runCtx) + close(done) + }() + defer func() { + cancel() + <-done + }() + + select { + case cmd := <-rec.sent: + if cmd.Kind() != "set_target" || *cmd.Target != 21 { + t.Fatalf("sent %s, want the target 21 back", cmd.Kind()) + } + case <-time.After(5 * time.Second): + t.Fatal("no target after the restart") + } +} + +func mustAway(t *testing.T, room string, until time.Time, target, restore float64) controller.Away { + t.Helper() + a, err := controller.RestoreAway(room, until, target, restore) + if err != nil { + t.Fatal(err) + } + return a +} diff --git a/internal/web/static/index.html b/internal/web/static/index.html index 59bd2c4..4eff374 100644 --- a/internal/web/static/index.html +++ b/internal/web/static/index.html @@ -5,29 +5,27 @@ - - - - - + Heating @@ -73,8 +89,32 @@

Heating

Connecting…
+
+
+ + +
+ +
+

Away

+ + +
+ + +
+
+
-

+ +