-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.js
331 lines (253 loc) · 9.16 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
/*** MQTT Z-Way HA module ****************************************************
Version: 1.3
(c) Robin Eggenkamp, 2016
-----------------------------------------------------------------------------
Author: Robin Eggenkamp <robin@edubits.nl>
Description:
Publishes the status of devices to a MQTT topic and is able
to set values based on subscribed topics
MQTTClient based on https://github.com/goodfield/zway-mqtt
*****************************************************************************/
// ----------------------------------------------------------------------------
// --- Class definition, inheritance and setup
// ----------------------------------------------------------------------------
function MQTT (id, controller) {
MQTT.super_.call(this, id, controller);
}
inherits(MQTT, BaseModule);
_module = MQTT;
// ----------------------------------------------------------------------------
// --- Module instance initialized
// ----------------------------------------------------------------------------
MQTT.prototype.init = function (config) {
// Call superclass' init (this will process config argument and so on)
MQTT.super_.prototype.init.call(this, config);
var self = this;
// Imports
executeFile(self.moduleBasePath() + "/lib/buffer.js");
executeFile(self.moduleBasePath() + "/lib/mqtt.js");
// Init MQTT client
self.setupMQTTClient();
// Default counters
self.reconnectCount = 0;
self.isStopping = false;
self.isConnected = false;
self.isConnecting = true;
self.client.connect();
var event = self.config.ignore ? "change:metrics:level" : "modify:metrics:level";
self.callback = _.bind(self.updateDevice, self);
self.controller.devices.on(event, self.callback);
self.callbackToggle = _.bind(self.updateToggleDevice, self);
self.controller.devices.on("change:metrics:level", self.callbackToggle);
};
MQTT.prototype.stop = function () {
var self = this;
var event = self.config.ignore ? "change:metrics:level" : "modify:metrics:level";
self.controller.devices.off(event, self.callback);
self.controller.devices.off("change:metrics:level", self.callbackToggle);
// Cleanup
self.isStopping = true;
self.client.close();
// Clear any active reconnect timers
if (self.reconnect_timer) {
clearTimeout(self.reconnect_timer);
self.reconnect_timer = null;
}
MQTT.super_.prototype.stop.call(this);
};
// ----------------------------------------------------------------------------
// --- Module methods
// ----------------------------------------------------------------------------
MQTT.prototype.setupMQTTClient = function () {
var self = this;
var mqttOptions = {
client_id: self.config.clientId,
will_flag: true,
will_topic: self.createTopic("/connected"),
will_message: "0",
will_retain: true
};
if (self.config.clientIdRandomize)
mqttOptions.client_id += "-" + Math.random().toString(16).substr(2, 6);
if (self.config.user != "none")
mqttOptions.username = self.config.user;
if (self.config.password != "none")
mqttOptions.password = self.config.password;
// mqttOptions.infoLogEnabled = true;
self.client = new MQTTClient(self.config.host, parseInt(self.config.port), mqttOptions);
self.client.onLog(function (msg) { self.log(msg.toString()); });
self.client.onError(function (error) { self.error(error.toString()); });
self.client.onDisconnect(function () { self.onDisconnect(); });
self.client.onConnect(function () {
self.log("Connected to " + self.config.host + " as " + self.client.options.client_id);
self.isConnected = true;
self.isConnecting = false;
self.isStopping = false;
self.reconnectCount = 0;
self.client.subscribe(self.createTopic("/#"), {}, function (topic, payload) {
var topic = topic.toString();
if (!topic.endsWith(self.config.topicPostfixStatus) && !topic.endsWith(self.config.topicPostfixSet))
return;
self.controller.devices.each(function (device) {
self.processPublicationsForDevice(device, function (device, publication) {
var deviceTopic = self.createTopic(publication.topic, device);
if (topic == deviceTopic + "/" + self.config.topicPostfixStatus) {
self.updateDevice(device);
}
if (topic == deviceTopic + "/" + self.config.topicPostfixSet) {
var deviceType = device.get('deviceType');
if (deviceType.startsWith("sensor")) {
self.error("Can't perform action on sensor " + device.get("metrics:title"));
return;
}
if (deviceType === "switchMultilevel" && payload !== "on" && payload !== "off" && payload !== "stop") {
device.performCommand("exact", {level: payload + "%"});
} else if (deviceType === "thermostat") {
device.performCommand("exact", {level: payload});
} else {
device.performCommand(payload);
}
}
});
});
});
// Publish connected notification
self.publish(self.createTopic("/connected"), "2", true);
});
};
MQTT.prototype.onDisconnect = function () {
var self = this;
// Reset connected flag
if (self.isConnected === true) self.isConnected = false;
// Reset connecting flag
if (self.isConnecting === true) self.isConnecting = false;
if (self.isStopping) {
self.log("Disconnected due to module stop, not reconnecting");
return;
}
self.error("Disconnected, will retry to connect...");
// Setup a connection retry
self.reconnect_timer = setTimeout(function() {
if (self.isConnecting === true) {
self.log("Connection already in progress, cancelling reconnect");
return;
}
if (self.isConnected === true) {
self.log("Connection already open, cancelling reconnect");
return;
}
self.log("Trying to reconnect (" + self.reconnectCount + ")");
self.reconnectCount++;
self.isConnecting = true;
self.client.connect();
self.log("Reconnect attempt finished");
}, Math.min(self.reconnectCount * 1000, 60000));
};
MQTT.prototype.updateDevice = function (device) {
var self = this;
var value = device.get("metrics:level");
var deviceType = device.get("deviceType");
if (deviceType == "toggleButton") {
return;
}
if (device.get("deviceType") == "switchBinary" || device.get("deviceType") == "sensorBinary") {
if (value == 0) {
value = "off";
} else if (value == 255) {
value = "on";
}
}
self.processPublicationsForDevice(device, function (device, publication) {
var topic = self.createTopic(publication.topic, device);
self.publish(topic, value, publication.retained);
});
};
/**
* The value of toggleButtons doesn't change, so we have to check all level changes.
* For that reason these updates are never retained.
*/
MQTT.prototype.updateToggleDevice = function (device) {
var self = this;
var value = device.get("metrics:level");
var deviceType = device.get("deviceType");
if (deviceType != "toggleButton") {
return;
}
self.processPublicationsForDevice(device, function (device, publication) {
var topic = self.createTopic(publication.topic, device);
self.publish(topic, value, false);
});
};
MQTT.prototype.processPublicationsForDevice = function (device, callback) {
var self = this;
if (! _.isFunction(callback)) {
self.error('Invalid callback for processPublicationsForDevice');
return;
}
_.each(self.config.publications, function (publication) {
switch (publication.type) {
case "all":
callback(device, publication);
break;
case "tag":
if (_.intersection(publication.tags, device.get("tags")).length > 0) {
callback(device, publication);
}
break;
case "single":
if (publication.deviceId == device.id) {
callback(device, publication);
}
break;
}
});
};
MQTT.prototype.publish = function (topic, value, retained) {
var self = this;
if (self.client && self.client.connected) {
var options = {};
options.retain = retained;
self.client.publish(topic, value.toString().trim(), options);
}
};
MQTT.prototype.createTopic = function (pattern, device) {
var self = this;
var topicParts = [].concat(self.config.topicPrefix.split("/"))
.concat(pattern.split("/"));
if (device != undefined) {
topicParts = topicParts.map(function (part) {
return part.replace("%roomName%", self.findRoom(device.get("location")).title.toCamelCase())
.replace("%deviceName%", device.get("metrics:title").toCamelCase())
.replace("%deviceId%", device.id.toString(16));
return part;
});
}
return topicParts.filter(function (part) {
return part !== undefined && part.length > 0;
}).join("/");
};
MQTT.prototype.findRoom = function (roomId) {
var self = this;
var locations = self.controller.locations;
if (locations) {
return locations.filter(function (location) {
return location.id == roomId;
})[0];
}
return undefined;
};
// ----------------------------------------------------------------------------
// --- Utility methods
// ----------------------------------------------------------------------------
String.prototype.toCamelCase = function() {
return this
.replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
.replace(/\s/g, '')
.replace(/^(.)/, function($1) { return $1.toLowerCase(); });
};
String.prototype.startsWith = function (s) {
return this.length >= s.length && this.substr(0, s.length) == s;
};
String.prototype.endsWith = function (s) {
return this.length >= s.length && this.substr(this.length - s.length) == s;
};