forked from iobroker-community-adapters/ioBroker.shelly
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
executable file
·317 lines (255 loc) · 10.2 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
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
/* jshint -W097 */
/* jshint strict: false */
/* jslint node: true */
'use strict';
const utils = require('@iobroker/adapter-core');
const objectHelper = require('@apollon/iobroker-tools').objectHelper; // Common adapter utils
const mqttServer = require(__dirname + '/lib/protocol/mqtt');
const coapServer = require(__dirname + '/lib/protocol/coap');
const adapterName = require('./package.json').name.split('.').pop();
const tcpPing = require('tcp-ping');
const EventEmitter = require('events').EventEmitter;
class Shelly extends utils.Adapter {
constructor(options) {
super({
...options,
name: adapterName,
});
this.serverMqtt = null;
this.serverCoap = null;
this.firmwareUpdateTimeout = null;
this.onlineCheckTimeout = null;
this.onlineDevices = {};
this.eventEmitter = new EventEmitter();
this.on('ready', this.onReady.bind(this));
this.on('stateChange', this.onStateChange.bind(this));
this.on('message', this.onMessage.bind(this));
this.on('unload', this.onUnload.bind(this));
this.on('deviceStatusUpdate', this.onDeviceStatusUpdate.bind(this));
}
async onReady() {
try {
// Upgrade older config
if (await this.migrateConfig()) {
return;
}
this.subscribeStates('*');
objectHelper.init(this);
const protocol = this.config.protocol || 'coap';
// Start online check
await this.setOnlineFalse();
this.onlineCheck();
this.autoFirmwareUpdate();
// Start MQTT server
setImmediate(() => {
if (protocol === 'both' || protocol === 'mqtt') {
this.log.info('Starting in MQTT mode. Listening on ' + this.config.bind + ':' + this.config.port);
if (!this.config.mqttusername || this.config.mqttusername.length === 0) { this.log.error('MQTT Username is missing!'); }
if (!this.config.mqttpassword || this.config.mqttpassword.length === 0) { this.log.error('MQTT Password is missing!'); }
this.serverMqtt = new mqttServer.MQTTServer(this, objectHelper, this.eventEmitter);
this.serverMqtt.listen();
}
});
// Start CoAP server
setImmediate(() => {
if (protocol === 'both' || protocol === 'coap') {
this.log.info('Starting in CoAP mode.');
this.serverCoap = new coapServer.CoAPServer(this, objectHelper, this.eventEmitter);
this.serverCoap.listen();
}
});
} catch (error) {
// ...
}
}
/**
* Is called if a subscribed state changes
* @param {string} id
* @param {ioBroker.State | null | undefined} state
*/
onStateChange(id, state) {
// Warning, state can be null if it was deleted
if (state && !state.ack) {
const stateId = id.replace(this.namespace + '.', '');
this.log.debug('stateChange ' + id + ' ' + JSON.stringify(state));
this.log.debug('stateChange ' + id + ' = ' + state.val);
objectHelper.handleStateChange(id, state);
if (stateId === 'info.update') {
this.log.debug(`[firmwareUpdate] info.update state changed - starting update on every device`);
this.eventEmitter.emit('onFirmwareUpdate');
}
}
}
onMessage(msg) {
this.sendTo(msg.from, msg.command, 'Execute command ' + msg.command, msg.callback);
}
onUnload(callback) {
if (this.onlineCheckTimeout) {
this.clearTimeout(this.onlineCheckTimeout);
this.onlineCheckTimeout = null;
}
this.setOnlineFalse();
if (this.firmwareUpdateTimeout) {
this.clearTimeout(this.firmwareUpdateTimeout);
this.firmwareUpdateTimeout = null;
}
try {
this.log.info('Closing Adapter');
if (this.serverCoap) {
try {
this.serverCoap.destroy();
} catch (err) {
// ignore
}
}
if (this.serverMqtt) {
try {
this.serverMqtt.destroy();
} catch (err) {
// ignore
}
}
callback();
} catch (e) {
// this.log.error('Error');
callback();
}
}
async onlineCheck() {
const valPort = 80;
if (this.onlineCheckTimeout) {
this.clearTimeout(this.onlineCheckTimeout);
this.onlineCheckTimeout = null;
}
try {
const deviceIds = await this.getAllDevices();
for (const d in deviceIds) {
const deviceId = deviceIds[d];
const idHostname = deviceId + '.hostname';
const stateHostaname = await this.getStateAsync(idHostname);
const valHostname = stateHostaname ? stateHostaname.val : undefined;
if (valHostname) {
this.log.debug(`onlineCheck of ${idHostname} on ${valHostname}:${valPort}`);
tcpPing.probe(valHostname, valPort, async (error, isAlive) => {
this.emit('deviceStatusUpdate', deviceId, isAlive);
});
}
}
} catch (e) {
this.log.error(e.toString());
}
this.onlineCheckTimeout = this.setTimeout(() => {
this.onlineCheckTimeout = null;
this.onlineCheck();
}, 60 * 1000); // Restart online check in 60 Seconds
}
async onDeviceStatusUpdate(deviceId, status) {
if (!deviceId) return;
this.log.debug(`onDeviceStatusUpdate: ${deviceId}: ${status}`);
// Check if device object exists
const knownDevices = await this.getAllDevices();
if (knownDevices.indexOf(deviceId) === -1) {
this.log.silly(`${deviceId} is not in list of known devices: ${JSON.stringify(knownDevices)}`);
return;
}
// Update online status
const idOnline = deviceId + '.online';
const onlineState = await this.getStateAsync(idOnline);
const prevValue = onlineState && onlineState.val ? (onlineState.val === 'true' || onlineState.val === true) : false;
if (prevValue != status) {
await this.setStateAsync(idOnline, { val: status, ack: true });
}
// Update connection state
const oldOnlineDeviceCount = Object.keys(this.onlineDevices).length;
if (status) {
this.onlineDevices[deviceId] = true;
} else if (Object.prototype.hasOwnProperty.call(this.onlineDevices, deviceId)) {
delete this.onlineDevices[deviceId];
}
const newOnlineDeviceCount = Object.keys(this.onlineDevices).length;
// Check online devices
if (oldOnlineDeviceCount !== newOnlineDeviceCount) {
this.log.debug(`Online devices: ${JSON.stringify(Object.keys(this.onlineDevices))}`);
if (newOnlineDeviceCount > 0) {
this.setStateAsync('info.connection', true, true);
} else {
this.setStateAsync('info.connection', false, true);
}
}
}
isOnline(deviceId) {
return Object.prototype.hasOwnProperty.call(this.onlineDevices, deviceId);
}
async getAllDevices() {
const devices = await this.getDevicesAsync();
return devices.map(device => this.removeNamespace(device._id));
}
async setOnlineFalse() {
const deviceIds = await this.getAllDevices();
for (const d in deviceIds) {
const deviceId = deviceIds[d];
const idOnline = deviceId + '.online';
await this.setStateAsync(idOnline, { val: false, ack: true });
await this.extendObjectAsync(deviceId, {
common: {
color: null // Remove color from previous versions
}
});
}
this.setStateAsync('info.connection', false, true);
}
autoFirmwareUpdate() {
if (this.config.autoupdate) {
this.log.debug(`[firmwareUpdate] Auto-Update enabled - starting update on every device`);
this.eventEmitter.emit('onFirmwareUpdate');
this.firmwareUpdateTimeout = this.setTimeout(() => {
this.firmwareUpdateTimeout = null;
this.autoFirmwareUpdate();
}, 15 * 60 * 1000); // Restart firmware update in 60 Seconds
}
}
removeNamespace(id) {
const re = new RegExp(this.namespace + '*\\.', 'g');
return id.replace(re, '');
}
async migrateConfig() {
const native = {};
if (this.config.http_username) {
native.httpusername = this.config.http_username;
native.http_username = '';
}
if (this.config.http_password) {
native.httppassword = this.config.http_password;
native.http_password = '';
}
if (this.config.user) {
native.mqttusername = this.config.user;
native.user = '';
}
if (this.config.password) {
native.mqttpassword = this.config.password;
native.password = '';
}
if (this.config.keys) {
native.blacklist = this.config.keys.map(b => { return { id: b.blacklist }; });
native.keys = null;
}
if (Object.keys(native).length) {
this.log.info('Migrate some data from old Shelly Adapter version. Restarting Shelly Adapter now!');
await this.extendForeignObjectAsync('system.adapter.' + this.namespace, { native: native });
return true;
}
return false;
}
}
// @ts-ignore parent is a valid property on module
if (module.parent) {
// Export the constructor in compact mode
/**
* @param {Partial<ioBroker.AdapterOptions>} [options={}]
*/
module.exports = (options) => new Shelly(options);
} else {
// otherwise start the instance directly
new Shelly();
}