const KEY = "state"; export const STATES = Object.freeze({ OFF: "off", CONNECTING: "connecting", ONLINE: "online", BACKOFF: "backoff", HALTED: "halted", SUSPENDED: "suspended", }); export class State { constructor(area, clock = () => Date.now()) { this.area = area; this.clock = clock; this.data = { state: STATES.OFF, detail: "", since: clock(), deviceUid: "", deviceLabel: "", suspendedUntil: "", lastError: "" }; this.chain = Promise.resolve(); } async load() { const stored = (await this.area.get(KEY))[KEY]; if (stored && typeof stored === "object") { this.data = { ...this.data, ...stored }; } } snapshot() { return { ...this.data }; } set(patch) { const changed = patch.state && patch.state !== this.data.state; this.data = { ...this.data, ...patch, since: changed ? this.clock() : this.data.since }; const payload = { ...this.data }; this.chain = this.chain.then(() => this.area.set({ [KEY]: payload })); return this.chain; } }