forked from ioBroker/ioBroker.ping
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
580 lines (511 loc) · 20 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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
/**
*
* ioBroker PING Adapter
*
* (c) 2014-2020 bluefox<dogafox@gmail.com>
*
* MIT License
*
*/
/* jshint -W097 */// jshint strict:false
/*jslint node: true */
'use strict';
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const ping = require('./lib/ping');
const adapterName = require('./package.json').name.split('.').pop();
let adapter;
let timer = null;
let stopTimer = null;
let isStopping = false;
const FORBIDDEN_CHARS = /[\]\[*,;'"`<>\\?]/g;
function startAdapter(options) {
options = options || {};
Object.assign(options, {name: adapterName});
adapter = new utils.Adapter(options);
adapter.on('message', obj => obj && processMessage(obj));
adapter.on('ready', () => main(adapter));
adapter.on('unload', () => {
if (timer) {
clearInterval(timer);
timer = null;
}
if (stopTimer) {
clearInterval(stopTimer);
stopTimer = null;
}
isStopping = true;
});
return adapter;
}
function processMessage(obj) {
if (!obj || !obj.command) {
return;
}
switch (obj.command) {
case 'ping': {
// Try to ping one IP or name
if (obj.callback && obj.message) {
ping.probe(obj.message, {log: adapter.log.debug}, (err, result) =>
adapter.sendTo(obj.from, obj.command, {result}, obj.callback));
}
break;
}
}
}
// Terminate adapter after 30 seconds idle
function stop() {
stopTimer && clearTimeout(stopTimer);
stopTimer = null;
// Stop only if schedule mode
if (adapter.common && adapter.common.mode === 'schedule') {
stopTimer = setTimeout(() => {
stopTimer = null;
timer && clearInterval(timer);
timer = null;
isStopping = true;
adapter.stop();
}, 30000);
}
}
function pingAll(taskList, index) {
stopTimer && clearTimeout(stopTimer);
stopTimer = null;
if (index >= taskList.length) {
timer = setTimeout(() => pingAll(taskList, 0), adapter.config.interval);
return;
}
const task = taskList[index];
index++;
adapter.log.debug('Pinging ' + task.host);
ping.probe(task.host, {log: adapter.log.debug}, (err, result) => {
err && adapter.log.error(err);
if (result) {
adapter.log.debug('Ping result for ' + result.host + ': ' + result.alive + ' in ' + (result.ms === null ? '-' : result.ms) + 'ms');
if (task.extendedInfo) {
adapter.setState(task.stateAlive, {val: result.alive, ack: true});
adapter.setState(task.stateTime, {val: result.ms === null ? '-' : result.ms / 1000, ack: true});
let rps = 0;
if (result.alive && result.ms !== null && result.ms > 0) {
rps = result.ms <= 1 ? 1000 : 1000.0 / result.ms;
}
adapter.setState(task.stateRps, { val: rps, ack: true });
} else {
adapter.setState(task.stateAlive, { val: result.alive, ack: true });
}
}
!isStopping && setTimeout(() =>
pingAll(taskList, index), 0);
});
}
function buildId(id) {
return adapter.namespace + (id.device ? '.' + id.device : '') + (id.channel ? '.' + id.channel : '') + (id.state ? '.' + id.state : '');
}
function processTasks(tasks, callback) {
if (!tasks || !tasks.length) {
callback && callback();
} else {
const task = tasks.shift();
adapter.log.debug('Task' + JSON.stringify(task));
// Workaround because of this fixed bug: https://github.com/ioBroker/ioBroker.js-controller/commit/d8d7cf2f34f24e0723a18a1cbd3f8ea23037692d
let timeout = setTimeout(() => {
adapter.log.warn('please update js-controller to at least 1.2.0');
timeout = null;
processTasks(tasks, callback);
}, 1000);
if (task.type === 'create_device') {
adapter.log.debug('Create device id=' + buildId(task.id));
adapter.createDevice(task.id.device, task.data.common, task.data.native, (err, obj) => {
err && adapter.log.error('Cannot create device: ' + buildId(task.id) + ' Error: ' + err);
if (timeout) {
clearTimeout(timeout);
timeout = null;
setImmediate(processTasks, tasks, callback);
}
});
} else if (task.type === 'update_device') {
adapter.log.debug('Update device id=' + buildId(task.id));
adapter.extendObject(task.id, task.data, err => {
err && adapter.log.error('Cannot update device: ' + buildId(task.id) + ' Error: ' + err);
if (timeout) {
clearTimeout(timeout);
timeout = null;
setImmediate(processTasks, tasks, callback);
}
});
} else if (task.type === 'delete_device') {
adapter.log.debug('Delete device id=' + task.id);
adapter.delObject(task.id, err => {
if (err) {
adapter.log.error('Cannot delete device : ' + task.id + ' Error: ' + err);
}
if (timeout) {
clearTimeout(timeout);
timeout = null;
setImmediate(processTasks, tasks, callback);
}
});
} else if (task.type === 'create_channel') {
adapter.log.debug('Create channel id=' + buildId(task.id));
adapter.createChannel(task.id.device, task.id.channel, task.data.common, task.data.native, err => {
err && adapter.log.error('Cannot create channel : ' + buildId(task.id) + ' Error: ' + err);
if (timeout) {
clearTimeout(timeout);
timeout = null;
setImmediate(processTasks, tasks, callback);
}
});
} else if (task.type === 'update_channel') {
adapter.log.debug('Update channel id=' + buildId(task.id));
adapter.extendObject(task.id, task.data, err => {
err && adapter.log.error('Cannot update channel : ' + buildId(task.id) + ' Error: ' + err);
if (timeout) {
clearTimeout(timeout);
timeout = null;
setImmediate(processTasks, tasks, callback);
}
});
} else if (task.type === 'delete_channel') {
adapter.log.debug('Delete channel id=' + task.id);
adapter.delObject(task.id, err => {
err && adapter.log.error('Cannot delete channel : ' + task.id + ' Error: ' + err);
if (timeout) {
clearTimeout(timeout);
timeout = null;
setImmediate(processTasks, tasks, callback);
}
});
} else if (task.type === 'create_state') {
adapter.log.debug('Create state id=' + buildId(task.id));
adapter.createState(task.id.device, task.id.channel, task.id.state, task.data.common, task.data.native, err => {
err && adapter.log.error('Cannot create state : ' + buildId(task.id) + ' Error: ' + err);
if (timeout) {
clearTimeout(timeout);
timeout = null;
setImmediate(processTasks, tasks, callback);
}
});
} else if (task.type === 'update_state') {
adapter.log.debug('Update state id=' + buildId(task.id));
adapter.extendObject(task.id, task.data, err => {
err && adapter.log.error('Cannot update state : ' + buildId(task.id) + ' Error: ' + err);
if (timeout) {
clearTimeout(timeout);
timeout = null;
setImmediate(processTasks, tasks, callback);
}
});
} else if (task.type === 'delete_state') {
adapter.log.debug('Delete state id=' + task.id);
adapter.delObject(task.id, err => {
err && adapter.log.error('Cannot delete state : ' + buildId(task.id) + ' Error: ' + err);
if (timeout) {
clearTimeout(timeout);
timeout = null;
setImmediate(processTasks, tasks, callback);
}
});
} else {
adapter.log.error('Unknown task type: ' + JSON.stringify(task));
if (timeout) {
clearTimeout(timeout);
timeout = null;
setImmediate(processTasks, tasks, callback);
}
}
}
}
function isDevicesEqual(rhs, lhs) {
return rhs.common.name === lhs.common.name;
}
function isChannelsEqual(rhs, lhs) {
return rhs.common.name === lhs.common.name &&
rhs.native.host === lhs.native.host;
}
function isStatesEqual(rhs, lhs) {
return (rhs.common.name === lhs.common.name)
&& (rhs.common.def === lhs.common.def)
&& (rhs.common.min === lhs.common.min)
&& (rhs.common.max === lhs.common.max)
&& (rhs.common.type === lhs.common.type)
&& (rhs.common.unit === lhs.common.unit)
&& (rhs.common.read === lhs.common.read)
&& (rhs.common.write === lhs.common.write)
&& (rhs.common.role === lhs.common.role)
&& (rhs.native.host === lhs.native.host);
}
function prepareTasks(preparedObjects, old_objects) {
const devicesToUpdate = [];
const channelsToUpdate = [];
const statesToUpdate = [];
if (preparedObjects.device) {
const fullID = buildId(preparedObjects.device.id);
const oldObj = old_objects[fullID];
if (oldObj && oldObj.type === 'device') {
if (!isDevicesEqual(oldObj, preparedObjects.device)) {
devicesToUpdate.push({
type: 'update_device',
id: preparedObjects.device.id,
data: {
common: preparedObjects.device.common
}
});
}
old_objects[fullID] = undefined;
} else {
devicesToUpdate.push({
type: 'create_device',
id: preparedObjects.device.id,
data: {
common: preparedObjects.device.common
}
});
}
}
preparedObjects.channels.forEach(channel => {
const fullID = buildId(channel.id);
const oldObj = old_objects[fullID];
if (oldObj && oldObj.type === 'channel') {
if (!isChannelsEqual(oldObj, channel)) {
channelsToUpdate.push({
type: 'update_channel',
id: channel.id,
data: {
common: channel.common,
native: channel.native
}
});
}
old_objects[fullID] = undefined;
} else {
channelsToUpdate.push({
type: 'create_channel',
id: channel.id,
data: {
common: channel.common,
native: channel.native
}
});
}
});
preparedObjects.states.forEach(state => {
const fullID = buildId(state.id);
const oldObj = old_objects[fullID];
if (oldObj && oldObj.type === 'state') {
if (!isStatesEqual(oldObj, state)) {
statesToUpdate.push({
type: 'update_state',
id: state.id,
data: {
common: state.common,
native: state.native
}
});
}
old_objects[fullID] = undefined;
} else {
statesToUpdate.push({
type: 'create_state',
id: state.id,
data: {
common: state.common,
native: state.native
}
});
}
});
const oldEntries = Object.keys(old_objects).map(id => ([id, old_objects[id]])).filter(([id, object]) => object);
const devicesToDelete = oldEntries.filter(([id, object]) => object.type === 'device').map(([id, object]) => ({ type: 'delete_device', id: id }));
const channelsToDelete = oldEntries.filter(([id, object]) => object.type === 'channel').map(([id, object]) => ({ type: 'delete_channel', id: id }));
const stateToDelete = oldEntries.filter(([id, object]) => object.type === 'state').map(([id, object]) => ({ type: 'delete_state', id: id }));
const tasks = stateToDelete.concat(channelsToDelete, devicesToDelete, devicesToUpdate, channelsToUpdate, statesToUpdate);
return tasks;
}
function prepareObjectsForHost(hostDevice, config) {
const host = config.ip;
const name = config.name;
const idName = (config.use_name ? (name || host) : host).replace(FORBIDDEN_CHARS, '_').replace(/[.\s]+/g, '_');
if (config.extended_info) {
const channelID = {device: hostDevice, channel: idName};
const stateAliveID = {device: hostDevice, channel: idName, state: 'alive'};
const stateTimeID = {device: hostDevice, channel: idName, state: 'time'};
const stateRpsID = {device: hostDevice, channel: idName, state: 'rps'};
return {
ping_task: {
host: config.ip,
extendedInfo: true,
stateAlive: stateAliveID,
stateTime: stateTimeID,
stateRps: stateRpsID
},
channel: {
id: channelID,
common: {
name: name || host,
desc: 'Ping of ' + host
},
native: {
host: host
}
},
states: [
{
id: stateAliveID,
common: {
name: 'Alive ' + name || host,
def: false,
type: 'boolean',
read: true,
write: false,
role: 'indicator.reachable',
desc: 'Ping state of ' + host
},
native: {
host: host
}
},
{
id: stateTimeID,
common: {
name: 'Time ' + (name || host),
def: 0,
type: 'number',
unit: 'sec',
read: true,
write: false,
role: 'value.interval',
desc: 'Ping time to ' + host
},
native: {
host: host
}
},
{
id: stateRpsID,
common: {
name: 'RPS ' + (name || host),
def: 0,
min: 0,
max: 1000,
type: 'number',
unit: 'hz',
read: true,
write: false,
role: 'value',
desc: 'Ping round trips per second to ' + host
},
native: {
host: host
}
}
]
};
} else {
const stateID = {device: hostDevice, channel: '', state: idName};
return {
ping_task: {
host: config.ip,
extendedInfo: false,
stateAlive: stateID,
},
states: [
{
id: stateID,
common: {
name: 'Alive ' + name || host,
def: false,
type: 'boolean',
read: true,
write: false,
role: 'indicator.reachable',
desc: 'Ping state of ' + host
},
native: {
host: host
}
}
]
};
}
}
function prepare_objects_by_config() {
const result = {};
const hostDeviceName = adapter.host;
let hostDevice = '';
adapter.log.debug('Host=' + (hostDeviceName || ' no host name'));
if (!adapter.config.noHostname) {
hostDevice = hostDeviceName ? hostDeviceName.replace(FORBIDDEN_CHARS, '_').replace(/[.\s]+/g, '_') : '';
result.device = {
id: {
device: hostDevice
},
common: {
name: hostDeviceName
}
};
}
const pingTaskList = [];
const channels = [];
let states = [];
const usedIDs = {};
for (let k = 0; k < adapter.config.devices.length; k++) {
const device = adapter.config.devices[k];
const config = prepareObjectsForHost(hostDevice, device);
if (config.channel) {
const fullID = buildId(config.channel.id);
if (usedIDs[fullID]) {
adapter.log.warn('Objects with same id = ' + fullID + ' created for two hosts ' + JSON.stringify(usedIDs[fullID]) + ' ' + JSON.stringify(device));
} else {
usedIDs[fullID] = device;
}
channels.push(config.channel);
}
config.states.forEach(state => {
const fullID = buildId(state.id);
if (usedIDs[fullID]) {
adapter.log.warn('Objects with same id = ' + fullID + ' created for two hosts ' + JSON.stringify(usedIDs[fullID]) + ' ' + JSON.stringify(device));
} else {
usedIDs[fullID] = device;
}
});
states = states.concat(config.states);
pingTaskList.push(config.ping_task);
}
result.pingTaskList = pingTaskList;
result.channels = channels;
result.states = states;
return result;
}
function syncConfig(callback) {
adapter.log.debug('Prepare objects');
const preparedObjects = prepare_objects_by_config();
adapter.log.debug('Get existing objects');
adapter.getAdapterObjects(_objects => {
adapter.log.debug('Prepare tasks of objects update');
const tasks = prepareTasks(preparedObjects, _objects);
adapter.log.debug('Start tasks of objects update');
processTasks(tasks, () => {
adapter.log.debug('Finished tasks of objects update');
callback(preparedObjects.pingTaskList);
});
});
}
function main(adapter) {
if (!adapter.config.devices.length) {
adapter.log.warn('No one host configured for ping');
return stop();
}
adapter.config.interval = parseInt(adapter.config.interval, 10);
if (adapter.config.interval < 5000) {
adapter.log.warn('Poll interval is too short. Reset to 5000 ms.');
adapter.config.interval = 5000;
}
syncConfig(pingTaskList =>
pingAll(pingTaskList, 0));
}
// 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();
}