-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.js
executable file
·100 lines (86 loc) · 2.54 KB
/
main.js
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#!/usr/bin/env node
"use strict";
const mqttusvc = require("mqtt-usvc");
const got = require("got");
async function main() {
const service = await mqttusvc.create();
const { apiKey, pollInterval = 60000 } = service.config;
if (!apiKey) {
console.error("No API Key");
process.exit(1);
}
if (apiKey === "changeme" || !apiKey) {
console.error("Check API configuration");
process.exit(1);
}
const handlers = {
acState: async (deviceId, property, data) => {
console.info("Setting AC state", deviceId, property, data);
let url = `https://home.sensibo.com/api/v2/pods/${deviceId}/acStates`;
let method = "post";
let body = { acState: data };
if (property) {
url += "/" + property;
method = "patch";
body = { newValue: data };
}
url += "?apiKey=" + apiKey;
await got(url, { json: true, body, method });
},
smartmode: async (deviceId, property, data) => {
await got(
`https://home.sensibo.com/api/v2/pods/${deviceId}/smartmode?apiKey=${apiKey}`,
{ json: true, method: "put", body: { enabled: data } }
);
},
};
service.on("message", async (topic, data) => {
try {
console.log("message", topic);
if (!topic.startsWith("~/set/")) return;
const [, , deviceId, action, property] = topic.split("/");
const handler = handlers[action];
if (!handler) {
throw new Error(action + " is not supported");
}
await handler(deviceId, property, data);
await poll();
} catch (err) {
console.error(String(err));
}
});
async function poll() {
try {
const response = await got(
"https://home.sensibo.com/api/v2/users/me/pods?fields=id,acState,connectionStatus,smartMode,measurements&apiKey=" +
apiKey
);
JSON.parse(response.body).result.map((device) => {
const {
id,
acState,
connectionStatus,
smartMode,
measurements = {},
} = device;
const flattened = {
id,
...acState,
...connectionStatus,
smartModeEnabled: (smartMode && smartMode.enabled) || false,
temperature: measurements.temperature,
humidity: measurements.humidity,
};
service.send("~/status/" + id, flattened);
});
} catch (err) {
console.error(String(err.stack));
}
}
setInterval(poll, pollInterval);
service.subscribe("~/set/#");
}
main().catch((err) => {
console.error(err.stack);
process.exit(1);
});