forked from google-home/smart-home-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
state.ts
33 lines (26 loc) · 959 Bytes
/
state.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { readFileSync, writeFile, existsSync } from 'fs';
import { join } from 'path';
import states from "./initial-state";
export function initState(devices: any, dataDir: string) {
// console.log("init devices", devices);
const jsonPath = join(dataDir, "state.json");
const loaded = existsSync(jsonPath) ? JSON.parse(readFileSync(jsonPath, 'utf8')) : {};
const state: any = devices.reduce((obj: any, device: any) => {
const initial = device.traits
.map((t: any) => t.replace("action.devices.traits.", ""))
.reduce(
(s: any, t: string) => Object.assign(s, states[t] || {}),
loaded[device.id] || {
online: true
}
);
obj[device.id] = initial;
return obj;
}, {});
// console.log(state);
// setInterval(() => console.log(state), 10000);
setInterval(() => writeFile(jsonPath, JSON.stringify(state), (err) => {
if (err) console.error(err);
}), 60000);
return state;
}