-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
471 lines (428 loc) · 15.7 KB
/
Copy pathmain.js
File metadata and controls
471 lines (428 loc) · 15.7 KB
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
/**
*
* openhab adapter Copyright 2017, bluefox <dogafox@gmail.com>
*
*/
/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
'use strict';
// you have to require the utils module and call adapter function
var utils = require(__dirname + '/lib/utils'); // Get common adapter utils
var request = require('request');
var adapter = utils.adapter('ip-symcon');
var symconTypes = require(__dirname + '/lib/ipsymconTypes').symconTypes;
var client;
var objects = {};
var states = [];
var connected = false;
var connectingTimeout = null;
var pollInterval = null;
var URL;
var es;
var secret = 'Zgfr56gFe87jJOM'; // Will be generated by first start
var packetId = 0;
var map = {};
// is called when adapter shuts down - callback has to be called under any circumstances!
adapter.on('unload', function (callback) {
try {
if (adapter.setState) adapter.setState('info.connection', false, true);
if (client) client.disconnect();
client = null;
adapter.log.info('cleaned everything up...');
callback();
} catch (e) {
callback();
}
});
// is called if a subscribed state changes
adapter.on('stateChange', function (id, state) {
if (state && !state.ack) {
if (objects[id]) {
if (objects[id].common.write && objects[id].native.name) {
states[id] = state.val;
if (!connected) {
adapter.log.warn('Cannot control: no connection to openhab "' + adapter.config.host + '"');
} else {
// convert values
if (objects[id].common.type === 'boolean') {
state.val = (state.val === true || state.val === 'true' || state.val === '1' || state.val === 1 || state.val === 'on' || state.val === 'ON');
} else if (objects[id].common.type === 'number') {
if (typeof state.val !== 'number') {
if (state.val === true || state.val === 'true' || state.val === 'on' || state.val === 'ON') {
state.val = 1;
} else if (state.val === false || state.val === 'false' || state.val === 'off' || state.val === 'OFF') {
state.val = 0;
} else {
state.val = parseFloat((state.val || '0').toString().replace(',', '.'));
}
}
}
if (objects[id].common.role === 'rgb') {
state.val = parseInt(state.val.toString().replace('#'), 16);
}
IPS_SetValue(id, state.val, function (err) {
if (err) {
adapter.setForeignState(id, {val: state.val, ack: true, q: 0x40});
adapter.log.warn('Cannot write "' + id + '": ' + err);
} else {
adapter.setForeignState(id, {val: state.val, ack: true, q: 0});
}
});
}
} else {
adapter.log.warn('State "' + id + '" is read only');
}
} else {
adapter.log.warn('Unknown state "' + id + '"');
}
}
});
// Some message was sent to adapter instance over message box. Used by email, pushover, text2speech, ...
adapter.on('message', function (obj) {
if (typeof obj === 'object' && obj.message) {
if (obj.command === 'send') {
// e.g. send email or pushover or whatever
console.log('send command');
// Send response in callback if required
if (obj.callback) adapter.sendTo(obj.from, obj.command, 'Message received', obj.callback);
}
}
});
// is called when databases are connected and adapter received configuration.
// start here!
adapter.on('ready', function () {
// Generate secret for session manager
if (adapter.config.username) {
adapter.getForeignObject('system.config', function (err, obj) {
if (!err && obj) {
if (!obj.native || !obj.native.secret) {
obj.native = obj.native || {};
require('crypto').randomBytes(24, function (ex, buf) {
secret = buf.toString('hex');
adapter.extendForeignObject('system.config', {native: {secret: secret}});
main();
});
} else {
adapter.config.password = decrypt(obj.native.secret, new Buffer(adapter.config.password, 'base64').toString('binary'));
main();
}
} else {
adapter.logger.error('Cannot find object system.config');
}
});
} else {
main();
}
});
function decrypt(key, value) {
var result = '';
for (var i = 0; i < value.length; ++i) {
result += String.fromCharCode(key[i % key.length].charCodeAt(0) ^ value.charCodeAt(i));
}
return result;
}
function syncObjects(objs, callback) {
if (!objs || !objs.length) {
callback && callback();
return;
}
var obj = objs.shift();
adapter.getForeignObject(obj._id, function (err, oObj) {
if (!oObj) {
objects[obj._id] = obj;
adapter.setForeignObject(obj._id, obj, function () {
setTimeout(syncObjects, 0, objs, callback);
});
} else {
var changed = false;
for (var a in obj.common) {
if (obj.common.hasOwnProperty(a) && 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, function () {
setTimeout(syncObjects, 0, objs, callback);
});
} else {
setTimeout(syncObjects, 0, objs, callback);
}
}
});
}
function IPS_Generic(method, params, callback) {
var auth;
if (adapter.config.username) {
auth = {
auth: {
user: adapter.config.username,
pass: adapter.config.password,
sendImmediately: false
}
};
}
if (typeof params === 'function') {
callback = params;
params = null;
}
var options = {
method: 'post',
body: {
jsonrpc: '2.0',
id: ++packetId,
method: method,
params: params || []
},
auth: auth,
json: true,
url: URL
};
if (packetId >= 0xFFFFFFFF) packetId = 0;
request(options, function (err, res, body) {
if (err) {
adapter.log.error('error posting json: ', err);
if (typeof callback === 'function') callback(err);
} else {
if (typeof callback === 'function') callback(null, body.result);
}
}).on('error', function (err) {
if (err) {
adapter.log.error('error posting json: ', err);
if (typeof callback === 'function') callback(err);
}
});
}
function IPS_GetObject(id, callback) {
IPS_Generic('IPS_GetObject', [id], callback);
}
function IPS_GetObjectList(callback) {
IPS_Generic('IPS_GetObjectList', function (err, list) {
var objs = {};
var count = 0;
if (list && typeof list === 'object') {
for (var i = 0; i < list.length; i++) {
count++;
IPS_GetObject(list[i], function (err, obj) {
objs[obj.ObjectID] = obj;
if (!--count) {
callback(null, objs);
}
});
}
} else {
adapter.log.warn('IP Symcon returned no objects');
callback(null, objs);
}
});
}
function IPS_GetVariable(id, callback) {
IPS_Generic('IPS_GetVariable', [id], callback);
}
function IPS_GetValue(id, callback) {
var _id = id;
if (typeof _id === 'string') {
_id = objects[id].native.ObjectID;
}
IPS_Generic('IPS_GetValue', [_id], function (err, value) {
callback(err, value, id);
});
}
function IPS_SetValue(id, value, callback) {
var _id = id;
if (typeof _id === 'string') {
_id = objects[id].native.ObjectID;
}
IPS_Generic('IPS_SetValue', [_id, value], function (err) {
callback(err, id);
});
}
function IPS_GetVariableList(callback) {
IPS_Generic('IPS_GetVariableList', function (err, list) {
var objs = {};
var count = 0;
if (list && typeof list === 'object') {
for (var i = 0; i < list.length; i++) {
count++;
IPS_GetVariable(list[i], function (err, obj) {
objs[obj.VariableID] = obj;
if (!--count) {
callback(null, objs);
}
});
}
} else {
adapter.log.warn('IP Symcon returned no variables');
callback(null, objs);
}
});
}
function syncStates(_states, callback) {
if (!_states || !_states.length) {
callback && callback();
return;
}
var state = _states.shift();
adapter.getForeignState(state._id, function (err, oState) {
if (!oState) {
adapter.setForeignState(state._id, state.val, function () {
setTimeout(syncStates, 0, _states, callback);
});
} else {
var changed = false;
for (var a in state.val) {
if (state.val.hasOwnProperty(a) &&
(typeof state.val[a] !== 'object' && state.val[a] !== oState[a]) ||
(typeof state.val[a] === 'object' && JSON.stringify(state.val[a]) !== JSON.stringify(oState[a]))) {
changed = true;
oState[a] = state.val[a];
}
}
if (changed) {
adapter.setForeignState(state._id, oState, function () {
setTimeout(syncStates, 0, _states, callback);
});
} else {
setTimeout(syncStates, 0, _states, callback);
}
}
});
}
function getNamePath(id, objs, path) {
path = path || [];
path.unshift(objs[id].ObjectIdent || (objs[id].ObjectName && objs[id].ObjectName.replace(/\s/g, '_')) || id);
if (!objs[id].ParentID) {
return path.join('.');
} else {
return getNamePath(objs[id].ParentID, objs, path);
}
}
function pollVars() {
var count = 0;
var newSates = [];
for (var id in objects) {
if (objects[id].type === 'state') {
count++;
IPS_GetValue(id, function (err, val, _id) {
if (err) {
if (connected) {
setTimeout(connect, adapter.config.reconnectTimeout);
}
updateConnected(false);
return;
}
if (objects[_id].native.VariableProfile === '~UnixTimestamp') {
val = val ? new Date(val * 1000) : '';
} else if (objects[_id].native.VariableProfile === '~HexColor') {
val = '#' + (0x1000000 | val).toString(16).substring(1).toUpperCase();
} else if (objects[_id].native.VariableProfile === '~Intensity.1') {
val *= 100;
}
newSates.push({_id: _id, val: {val: val, ack: true}});
if (!--count) {
syncStates(newSates);
}
});
}
}
}
function connect(callback) {
connectingTimeout = null;
IPS_GetObjectList(function (err, objs) {
if (objs) {
updateConnected(true);
IPS_GetVariableList(function (err, vars) {
var newObjs = [];
var newStates = [];
for (var id in objs) {
if (!objs.hasOwnProperty(id)) continue;
var obj = objs[id];
var _id = adapter.namespace + '.objects.' + getNamePath(id, objs);
var common = {
desc: obj.ObjectInfo,
enabled: !!obj.ObjectIsDisabled,
name: obj.ObjectName
};
if (obj.ObjectType === 2) {
common.read = true;
common.write = obj.ObjectIsReadOnly;
var data = symconTypes(common, vars[id].VariableValue, vars[id].VariableProfile, vars[id].VariableType);
common = data.common;
newStates.push({_id: _id, val: {
val: data.val,
ts: vars[id].VariableUpdated * 1000,
lc: vars[id].VariableChanged,
ack: true
}});
}
newObjs.push({
_id: _id,
common: common,
native: obj,
type: obj.ObjectType === 1 ? 'channel' : 'state'
});
map[id] = _id;
}
syncObjects(newObjs, function () {
syncStates(newStates, function () {
if (pollInterval) clearInterval(pollInterval);
pollInterval = setInterval(pollVars, adapter.config.pollInterval)
});
});
});
} else {
updateConnected(false);
adapter.log.error('Cannot get answer from "' + URL + '/IPS_GetObjectList": ' + err);
connectingTimeout = setTimeout(connect, adapter.config.reconnectTimeout);
callback && callback();
}
});
}
function updateConnected(isConnected) {
if (connected !== isConnected) {
connected = isConnected;
adapter.setState('info.connection', connected, true);
adapter.log.info(isConnected ? 'connected' : 'disconnected');
if (!isConnected) {
es.close();
es = null;
if (pollInterval) {
clearInterval(pollInterval);
pollInterval = false;
}
}
}
}
function main() {
adapter.config.pollInterval = parseInt(adapter.config.pollInterval, 10) || 5000;
if (adapter.config.url) {
adapter.config.protocol = adapter.config.url.match(/^https:/) ? 'https' : 'http';
var url = adapter.config.url.replace('https://', '').replace('http://', '');
var parts = url.split('/');
adapter.config.path = '/' + (parts[1] || '');
parts = parts[0].split(':');
adapter.config.host = parts[0];
adapter.config.port = parts[1] || 80;
delete adapter.config.url;
}
if (adapter.config.host) {
URL = adapter.config.protocol + '://' + adapter.config.host + ':' + (adapter.config.port || 80) + adapter.config.path;
if (URL[URL.length - 1] !== '/') {
URL += '/';
}
} else {
adapter.log.warn('No REST API URL defined.');
return;
}
adapter.config.reconnectTimeout = parseInt(adapter.config.reconnectTimeout, 10) || 30000;
adapter.setState('info.connection', false, true);
connect();
// in this openhab all states changes inside the adapters namespace are subscribed
adapter.subscribeStates('*');
}