Files
devplacepy/nodes/extension/src/State.js
T

39 lines
1.0 KiB
JavaScript
Raw Normal View History

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",
SUSPENDED: "suspended",
2026-10-16 07:20:44 +02:00
});
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: "" };
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;
}
}