-
Notifications
You must be signed in to change notification settings - Fork 25
/
main.js
372 lines (331 loc) · 12.5 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
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/**
* ioBroker MiHome
*
* Copyright 2017-2018, bluefox <[email protected]>
*
* License: MIT
*/
'use strict';
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const MiHome = require('./lib/Hub');
const adapterName = require('./package.json').name.split('.').pop();
let objects = {};
let delayed = {};
let connected = null;
let connTimeout;
let hub;
let reconnectTimeout;
let tasks = [];
let browseTimeout;
let adapter;
function startAdapter(options) {
options = options || {};
Object.assign(options, {name: adapterName});
adapter = new utils.Adapter(options);
adapter.on('ready', main);
adapter.on('stateChange', (id, state) => {
if (!id || !state || state.ack) {
return;
}
if (!objects[id]) {
adapter.log.warn('Unknown ID: ' + id);
return;
}
if (hub) {
const pos = id.lastIndexOf('.');
const channelId = id.substring(0, pos);
const attr = id.substring(pos + 1);
if (objects[channelId] && objects[channelId].native) {
const device = hub.getSensor(objects[channelId].native.sid);
if (device && device.Control) {
adapter.log.debug('attr:' + attr); // This is added for debugging
adapter.log.debug('state:' + state.val); // This is added for debugging
device.Control(attr, state.val);
} else {
adapter.log.warn('Cannot control ' + id);
}
} else {
adapter.log.warn('Invalid device: ' + id);
}
}
});
adapter.on('unload', callback => {
browseTimeout && clearTimeout(browseTimeout);
browseTimeout = null;
connTimeout && clearTimeout(connTimeout);
connTimeout = null;
reconnectTimeout && clearTimeout(reconnectTimeout);
reconnectTimeout = null;
if (hub) {
try {
hub.stop(callback);
} catch (e) {
console.error('Cannot stop: ' + e);
callback && callback();
}
} else if (callback) {
callback();
}
});
adapter.on('message', obj => {
if (obj) {
switch (obj.command) {
case 'browse':
let browse = new MiHome.Hub({
port: (obj.message.port || adapter.config.port) + 1,
bind: obj.message.bind || '0.0.0.0',
browse: true
});
let result = [];
browse.on('browse', data => (result.indexOf(data.ip) === -1) && result.push(data.ip));
browse.listen();
browseTimeout = setTimeout(() => {
browseTimeout = null;
browse.stop(() => {
browse = null;
obj.callback && adapter.sendTo(obj.from, obj.command, result, obj.callback);
});
}, 3000);
break;
}
}
});
return adapter;
}
function updateStates(sid, type, data) {
const id = adapter.namespace + '.devices.' + type.replace('.', '_') + '_' + sid;
for (const attr in data) {
if (data.hasOwnProperty(attr)) {
if (objects[id] || objects[id + '.' + attr]) {
// convert hPa => mmHg
if (objects[id + '.' + attr] && objects[id + '.' + attr].common && objects[id + '.' + attr].common.unit === 'mmHg') {
data[attr] = Math.round(data.pressure * 100 / 133.322);
}
// TODO: what should be done if objects[id + '.' + attr] === undefined? Object does not exist, but the value will be set...
if (!objects[id + '.' + attr]) {
adapter.log.warn(`Check, why the object ${id}.${attr} does not exist! But the value ${data[attr]} is set.`);
}
adapter.setForeignState(id + '.' + attr, data[attr], true);
} else {
delayed[id + '.' + attr] = data[attr];
}
}
}
}
function syncObjects(callback) {
if (!tasks || !tasks.length) {
callback && callback();
return;
}
const obj = tasks.shift();
adapter.getForeignObject(obj._id, (err, oObj) => {
if (!oObj) {
objects[obj._id] = obj;
adapter.setForeignObject(obj._id, obj, () => {
if (delayed[obj._id] !== undefined) {
adapter.setForeignState(obj._id, delayed[obj._id], true, () => {
delete delayed[obj._id];
setImmediate(syncObjects, callback);
})
} else {
setImmediate(syncObjects, callback);
}
});
} else {
let changed = false;
// merge info together
for (const a in obj.common) {
if (obj.common.hasOwnProperty(a) && a !== 'name' && oObj.common[a] !== obj.common[a]) {
changed = true;
oObj.common[a] = obj.common[a];
}
}
if (JSON.stringify(obj.native) !== JSON.stringify(oObj.native)) {
changed = true;
oObj.native = obj.native;
}
objects[obj._id] = oObj;
if (changed) {
adapter.setForeignObject(oObj._id, oObj, () => {
if (delayed[oObj._id] !== undefined) {
adapter.setForeignState(oObj._id, delayed[oObj._id], true, () => {
delete delayed[oObj._id];
setImmediate(syncObjects, callback);
})
} else {
setImmediate(syncObjects, callback);
}
});
} else {
if (delayed[oObj._id] !== undefined) {
adapter.setForeignState(oObj._id, delayed[oObj._id], true, () => {
delete delayed[oObj._id];
setImmediate(syncObjects, callback);
})
} else {
// init rotate position with previous value
if (oObj._id.match(/\.rotate_position$/)) {
adapter.getForeignState(oObj._id, (err, state) => {
if (state) {
const pos = oObj._id.lastIndexOf('.');
const channelId = oObj._id.substring(0, pos);
if (objects[channelId]) {
const device = hub.getSensor(objects[channelId].native.sid);
if (device && device.Control) {
device.Control('rotate_position', state.val);
}
}
}
setImmediate(syncObjects, callback);
});
} else {
setImmediate(syncObjects, callback);
}
}
}
}
});
}
function createDevice(device, name, callback) {
const id = adapter.namespace + '.devices.' + device.className.replace('.', '_') + '_' + device.sid;
const isStartTasks = !tasks.length;
const dev = Object.keys(MiHome.Devices).find(id => MiHome.Devices[id].type === device.type);
if (dev) {
for (const attr in MiHome.Devices[dev].states) {
if (!MiHome.Devices[dev].states.hasOwnProperty(attr)) {
continue;
}
adapter.log.debug('Create ' + id + '.' + attr);
const obj = {
_id: id + '.' + attr,
common: MiHome.Devices[dev].states[attr],
type: 'state',
native: {}
};
// use valid units
if (adapter.config.mmHg && obj.common.unit === 'hPa') {
obj.common.unit = 'mmHg';
obj.common.min = 0;
obj.common.max = 1000;
}
tasks.push(obj);
}
} else {
adapter.log.error('Device ' + device.type + ' not found');
}
tasks.push({
_id: id,
common: {
name: name || (dev && dev.fullName) || device.type,
icon: '/icons/' + device.type.replace('.', '_') + '.png'
},
type: 'channel',
native: {
sid: device.sid,
type: device.type
}
});
isStartTasks && syncObjects(callback);
}
function readObjects(callback) {
adapter.getForeignObjects(adapter.namespace + '.devices.*', (err, list) => {
adapter.subscribeStates('devices.*');
objects = list;
callback && callback();
});
}
function disconnected () {
connTimeout = null;
if (connected) {
connected = false;
adapter.log.info(`Change connection status on timeout after ${adapter.config.heartbeatTimeout}ms: false`);
adapter.setState('info.connection', connected, true);
}
stopMihome();
}
function setConnected(conn) {
if (connected !== conn) {
connected = conn;
adapter.log.info('Change connection status: ' + conn);
adapter.setState('info.connection', connected, true);
}
if (conn && adapter.config.heartbeatTimeout) {
if (connTimeout) {
clearTimeout(connTimeout);
}
connTimeout = setTimeout(disconnected, adapter.config.heartbeatTimeout);
}
}
function stopMihome() {
if (hub) {
try {
hub.stop();
hub = null;
} catch (e) {
}
}
if (!reconnectTimeout) {
reconnectTimeout = setTimeout(startMihome, adapter.config.restartInterval);
}
}
function startMihome() {
reconnectTimeout = null;
setConnected(false);
if (!adapter.config.key && (!adapter.config.keys || !adapter.config.keys.find(e => e.key))) {
adapter.log.error('no key defined. Only read is possible');
}
hub = new MiHome.Hub({
port: adapter.config.port,
bind: adapter.config.bind || '0.0.0.0',
key: adapter.config.key,
keys: adapter.config.keys,
sids: adapter.config.sids,
interval: adapter.config.interval
});
hub.on('message', msg => {
setConnected(true);
adapter.log.debug('RAW: ' + JSON.stringify(msg)); // Here's the output in Log ioBrokera of debug RAW lines:
});
hub.on('warning', msg => adapter.log.warn(msg));
hub.on('debug', msg => adapter.log.debug(msg));
hub.on('error', error => {
adapter.log.error(error);
stopMihome();
});
hub.on('device', (device, name) => {
if (device.sid !== '000000000000') { // Ignore devices with empty sid
if (!objects[adapter.namespace + '.devices.' + device.className.replace('.', '_') + '_' + device.sid]) {
adapter.log.debug('NEW device: ' + device.sid + '(' + device.type + ')'); // Here's the output in Log ioBrokera of the lines NEW device:
createDevice(device, name);
} else {
adapter.log.debug('known device: ' + device.sid + '(' + device.type + ')');
}
}
});
hub.on('data', (sid, type, data) => {
if (sid !== '000000000000') { // Ignore devices with empty sid
adapter.log.debug('data: ' + sid + '(' + type + '): ' + JSON.stringify(data)); // data: 000000000000(gateway): {"relay_status":"off"}
updateStates(sid, type, data);
}
});
if (!connTimeout && adapter.config.heartbeatTimeout) {
connTimeout = setTimeout(disconnected, adapter.config.heartbeatTimeout);
}
hub.listen();
}
function main() {
if (adapter.config.heartbeatTimeout === undefined) {
adapter.config.heartbeatTimeout = 20000;
} else {
adapter.config.heartbeatTimeout = parseInt(adapter.config.heartbeatTimeout, 10) || 0;
}
adapter.config.restartInterval = parseInt(adapter.config.restartInterval, 10) || 30000;
readObjects(startMihome);
}
// If started as allInOne/compact mode => return function to create instance
if (module && module.parent) {
module.exports = startAdapter;
} else {
// or start the instance directly
startAdapter();
}