2026-10-16 07:20:44 +02:00
|
|
|
const KEY = "state";
|
|
|
|
|
|
|
|
|
|
export const STATES = Object.freeze({
|
|
|
|
|
OFF: "off",
|
|
|
|
|
CONNECTING: "connecting",
|
|
|
|
|
ONLINE: "online",
|
|
|
|
|
BACKOFF: "backoff",
|
|
|
|
|
HALTED: "halted",
|
2026-10-17 02:23:43 +02:00
|
|
|
SUSPENDED: "suspended",
|
2026-10-16 07:20:44 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
export class State {
|
|
|
|
|
constructor(area, clock = () => Date.now()) {
|
|
|
|
|
this.area = area;
|
|
|
|
|
this.clock = clock;
|
2026-10-17 02:23:43 +02:00
|
|
|
this.data = { state: STATES.OFF, detail: "", since: clock(), deviceUid: "", deviceLabel: "", suspendedUntil: "", lastError: "" };
|
2026-10-16 07:20:44 +02:00
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
}
|