-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
349 lines (314 loc) · 9.62 KB
/
index.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
process.env.DEBUG = "hubitat";
process.title = process.env.TITLE || "hubitat-microservice";
const debug = require("debug")("hubitat"),
console = require("console"),
WSClient = require("websocket").client,
superagent = require("superagent"),
HostBase = require("microservice-core/HostBase");
const express = require("express"),
app = express(),
port = 4000;
const HUBITAT = process.env.HUBITAT_HUB,
TOKEN = process.env.HUBITAT_TOKEN;
const DEVICES_URL = `http://${HUBITAT}/apps/api/4/devices/all?access_token=${TOKEN}`;
const MAKER_URL = encodeURIComponent("http://nuc1:4000/maker");
const POLL_URL = `http://${HUBITAT}/apps/api/4/postURL/${MAKER_URL}?access_token=${TOKEN}`;
const getDevices = async () => {
try {
const json = await superagent.get(DEVICES_URL);
return JSON.parse(json.text);
} catch (e) {
console.log("getDevices exception", e);
}
};
app.use(express.json());
class Hubitat extends HostBase {
constructor() {
const host = process.env.MQTT_HOST || "mqtt";
const topic = process.env.MQTT_TOPIC || "hubitat";
debug(
"host",
host,
"topic",
topic,
"devices url",
DEVICES_URL,
"POLL_URL",
POLL_URL
);
super(host, topic, true);
this.devices = [];
try {
this.token = process.env.HUBITAT_TOKEN;
this.client.on("connect", () => {
// notify clients we started
this.alert("Alert", "hubitat-microservice running");
this.client.subscribe("hubitat/+/set/#");
this.client.on("message", async (topic, message) => {
message = message.toString();
if (message === "__RESTART__") {
console.log("GOT RESTART", topic, message);
await this.client.publish(topic, null, { retain: false });
await this.client.publish(topic, null, { retain: true });
this.exit(`${process.title} restarting`);
return;
}
console.log("message", topic, message);
const parts = topic.split("/");
if (parts[2] === "set") {
await this.command(parts[1], parts[3], message);
}
});
});
this.client.on("error", (e) => {
// probably are in some wacky state, abort so nodemon/forever will restart us.
this.abort("client error", e.stack);
});
// override publish() in HostBase
this.publish = (key, value) => {
const topic = `hubitat/${key}`;
debug(
new Date().toLocaleTimeString(),
"publish",
topic,
JSON.stringify(value)
);
this.client.publish(topic, JSON.stringify(value), { retain: true });
};
} catch (e) {
this.warn("Error: ", e.message, e.stack);
}
}
async run() {
const devices = await getDevices();
this.devices = {};
for (const device of devices) {
this.devices[device.label] = device;
debug(
`device label(${device.label}) name(${device.name}) type(${device.type})`
);
try {
if (~device.capabilities.indexOf("SwitchLevel")) {
device.level = 100;
}
if (~device.capabilities.indexOf("ColorControl")) {
device.color = { r: 255, g: 0, b: 255 };
}
} catch (e) {
debug("Exception ", e);
}
}
app.post("/maker", (req, res) => {
const newState = {},
event = req.body.content;
// console.log("post event", event);
newState[`${event.displayName}/status/${event.name}`] = isNaN(event.value)
? event.value
: Number(event.value);
this.state = newState;
res.send({});
});
await superagent.get(POLL_URL);
const client = new WSClient();
client.on("connectionFailed", (err) => {
console.log("Connect Error:", err.toString());
});
client.on("error", (e) => {
console.log("ws client error", e);
});
client.on("connect", (connection) => {
debug("ws connected!");
connection.on("error", (err) => {
console.log("Connection Error:", err.toString());
});
connection.on("close", (err) => {
console.log("Connection Close:", err.toString());
});
connection.on("message", (message) => {
try {
const event = JSON.parse(message.utf8Data),
newState = {};
switch (event.source) {
case "DEVICE":
switch (event.name) {
case "pollResponse":
break;
case "temperature":
// debug(
// new Date().toLocaleTimeString(),
// "WS event temperature",
// event.displayName,
// event.value
// );
break;
case "battery":
debug(
new Date().toLocaleTimeString(),
"WS event battery",
event.displayName,
event.value
);
break;
default:
// debug(new Date().toLocaleTimeString(), "WS event", event);
break;
}
break;
case "LOCATION":
debug(
new Date().toLocaleTimeString(),
"WS event location",
event.displayName,
event.name,
event.value
);
break;
default:
debug(new Date().toLocaleTimeString(), "WS event", event);
break;
}
newState[`${event.displayName}/status/${event.name}`] = isNaN(
event.value
)
? event.value
: Number(event.value);
this.state = newState;
if (event.source === "DEVICE") {
const deviceName = event.displayName,
device = this.devices[deviceName],
isButton = ~(device.type || "").toLowerCase().indexOf("button");
if (
isButton &&
event.name !== "temperature" &&
event.name !== "battery" &&
device.capabilities.indexOf("Release") === -1
) {
setTimeout(() => {
newState[`${event.displayName}/status/${event.name}`] = 0;
this.state = newState;
}, 1000);
}
}
} catch (e) {
//
console.log(new Date().toLocaleTimeString(), "exception", e);
const event = JSON.parse(message.utf8Data);
console.log(event, this.devices[event.displayName]);
}
});
});
client.connect("ws://hubitat/eventsocket");
app.listen(port, () => {
console.log(`hubitat-microservice listening on port ${port}`);
});
}
async command(thing, attribute, value) {
console.log("thing", thing, "attribute", attribute, "value", value);
if (thing === "reset") {
this.abort("hubitat-microservice RESET");
return;
}
let uri;
try {
const device = this.devices[thing];
if (!device) {
debug(`Command: Unknown device '${thing}', ${attribute}, ${value}`);
return;
}
try {
const v = Math.round(value);
if (!Number.isNaN(v)) {
value = v;
}
} catch (e) {
//
}
let url = `http://hubitat/apps/api/4/devices/${device.id}/`;
switch (attribute) {
case "level":
device.level = value;
url += `setLevel/${value}`;
break;
case "lock":
case "locked":
device.locked = true;
url += `lock`;
break;
case "unlock":
case "unlocked":
device.locked = false;
url += `unlock`;
break;
case "hue":
url += `setHue/${value}`;
break;
case "saturation":
url += `setSaturation/${value}`;
break;
case "white":
break;
case "whiteLevel":
break;
case "warm":
break;
case "warmLevel":
url += `setWarmWhiteLevel/${value}`;
break;
case "color":
url += `setColor/${value}`;
console.log("color", value);
if (value.r !== undefined) {
device.color = {
r: value.r,
g: value.g,
b: value.b,
};
} else {
device.color = {
r: parseInt(value.substr(0, 2), 16),
g: parseInt(value.substr(2, 2), 16),
b: parseInt(value.substr(4, 2), 16),
};
}
break;
case "effect":
url += `setEffect/${value}`;
break;
case "switch":
url += value;
break;
case "red":
device.color.r = value;
url += `setRedLevel/${value}`;
break;
case "green":
device.color.g = value;
url += `setGreenLevel/${value}`;
break;
case "blue":
device.color.b = value;
url += `setBlueLevel/${value}`;
break;
}
url = `${url}?access_token=${this.token}`;
uri = url;
debug(`command ${thing}.${attribute} = ${value}`, url);
await superagent.get(url);
if (
~device.capabilities.indexOf("ColorControl") &&
attribute === "switch" &&
value === "on"
) {
await this.command(thing, "color", device.color);
await this.command(thing, "level", device.level);
}
} catch (e) {
console.log("GET error", uri, e.message, e.stack);
}
}
}
const main = async () => {
const hub = new Hubitat();
await hub.run();
};
main();