forked from retoor/devplacepy
Zo doen wijdat in oost
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
const KEY = "state";
|
||||
|
||||
export const STATES = Object.freeze({
|
||||
OFF: "off",
|
||||
CONNECTING: "connecting",
|
||||
ONLINE: "online",
|
||||
BACKOFF: "backoff",
|
||||
HALTED: "halted",
|
||||
});
|
||||
|
||||
export class State {
|
||||
constructor(area, clock = () => Date.now()) {
|
||||
this.area = area;
|
||||
this.clock = clock;
|
||||
this.data = { state: STATES.OFF, detail: "", since: clock(), deviceUid: "", 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user