iobroker.hass 1.4.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/main.js DELETED
@@ -1,489 +0,0 @@
1
- /* jshint -W097 */
2
- /* jshint strict: false */
3
- /* jslint node: true */
4
-
5
- 'use strict';
6
-
7
- const utils = require('@iobroker/adapter-core');
8
- const HASS = require('./lib/hass');
9
- const adapterName = require('./package.json').name.split('.').pop();
10
-
11
- let connected = false;
12
- let hass;
13
- let adapter;
14
- const hassObjects = {};
15
- let delayTimeout = null;
16
- let stopped = false;
17
-
18
- function startAdapter(options) {
19
- options = options || {};
20
- Object.assign(options, {name: adapterName, unload: stop});
21
- adapter = new utils.Adapter(options);
22
-
23
- // is called if a subscribed state changes
24
- adapter.on('stateChange', (id, state) => {
25
- // you can use the ack flag to detect if it is status (true) or command (false)
26
- if (state && !state.ack) {
27
- if (!connected) {
28
- return adapter.log.warn(`Cannot send command to "${id}", because not connected`);
29
- }
30
- /*if (id === adapter.namespace + '.' + '.info.resync') {
31
- queue.push({command: 'resync'});
32
- processQueue();
33
- } else */
34
- if (hassObjects[id]) {
35
- if (!hassObjects[id].common.write) {
36
- adapter.log.warn(`Object ${id} is not writable!`);
37
- } else {
38
- const serviceData = {};
39
- const fields = hassObjects[id].native.fields;
40
- const target = {};
41
-
42
- let requestFields = {};
43
- if (typeof state.val === 'string') {
44
- state.val = state.val.trim();
45
- if (state.val.startsWith('{') && state.val.endsWith('}')) {
46
- try {
47
- requestFields = JSON.parse(state.val) || {};
48
- } catch (err) {
49
- adapter.log.info(`Ignore data for service call ${id} is no valid JSON: ${err.message}`);
50
- requestFields = {};
51
- }
52
- }
53
- }
54
-
55
- // If a non-JSON value was set, and we only have one relevant field, use this field as value
56
- if (fields && Object.keys(requestFields).length === 0) {
57
- const fieldList = Object.keys(fields);
58
- if (fieldList.length === 1 && fieldList[0] !== 'entity_id') {
59
- requestFields[fieldList[0]] = state.val;
60
- } else if (fieldList.length === 2 && fields.entity_id) {
61
- requestFields[fieldList[1 - fields.indexOf('entity_id')]] = state.val;
62
- }
63
- }
64
-
65
- adapter.log.debug(`Prepare service call for ${id} with (mapped) request parameters ${JSON.stringify(requestFields)} from value: ${JSON.stringify(state.val)}`);
66
- if (fields) {
67
- for (const field in fields) {
68
- if (!fields.hasOwnProperty(field)) {
69
- continue;
70
- }
71
-
72
- if (field === 'entity_id') {
73
- target.entity_id = hassObjects[id].native.entity_id
74
- } else if (requestFields[field] !== undefined) {
75
- serviceData[field] = requestFields[field];
76
- }
77
- }
78
- }
79
- const noFields = Object.keys(serviceData).length === 0;
80
- serviceData.entity_id = hassObjects[id].native.entity_id
81
-
82
- adapter.log.debug(`Send to HASS for service ${hassObjects[id].native.attr} with ${hassObjects[id].native.domain || hassObjects[id].native.type} and data ${JSON.stringify(serviceData)}`)
83
- hass.callService(hassObjects[id].native.attr, hassObjects[id].native.domain || hassObjects[id].native.type, serviceData, target, err => {
84
- err && adapter.log.error(`Cannot control ${id}: ${err}`);
85
- if (err && fields && noFields) {
86
- adapter.log.warn(`Please make sure to provide a stringified JSON as value to set relevant fields! Please refer to the Readme for details!`);
87
- adapter.log.warn(`Allowed field keys are: ${Object.keys(fields).join(', ')}`);
88
- }
89
- });
90
- }
91
- }
92
- }
93
- });
94
-
95
- // is called when databases are connected and adapter received configuration.
96
- // start here!
97
- adapter.on('ready', main);
98
-
99
- return adapter;
100
- }
101
-
102
- function stop(callback) {
103
- stopped = true;
104
- delayTimeout && clearTimeout(delayTimeout);
105
- hass && hass.close();
106
- callback && callback();
107
- }
108
-
109
- function getUnit(name) {
110
- name = name.toLowerCase();
111
- if (name.indexOf('temperature') !== -1) {
112
- return '°C';
113
- } else if (name.indexOf('humidity') !== -1) {
114
- return '%';
115
- } else if (name.indexOf('pressure') !== -1) {
116
- return 'hPa';
117
- } else if (name.indexOf('degrees') !== -1) {
118
- return '°';
119
- } else if (name.indexOf('speed') !== -1) {
120
- return 'kmh';
121
- }
122
- return undefined;
123
- }
124
-
125
- function syncStates(states, cb) {
126
- if (!states || !states.length) {
127
- return cb();
128
- }
129
- const state = states.shift();
130
- const id = state.id;
131
- delete state.id;
132
-
133
- adapter.setForeignState(id, state, err => {
134
- err && adapter.log.error(err);
135
- setImmediate(syncStates, states, cb);
136
- });
137
- }
138
-
139
- function syncObjects(objects, cb) {
140
- if (!objects || !objects.length) {
141
- return cb();
142
- }
143
- const obj = objects.shift();
144
- hassObjects[obj._id] = obj;
145
-
146
- adapter.getForeignObject(obj._id, (err, oldObj) => {
147
-
148
- err && adapter.log.error(err);
149
-
150
- if (!oldObj) {
151
- adapter.log.debug(`Create "${obj._id}": ${JSON.stringify(obj.common)}`);
152
- hassObjects[obj._id] = obj;
153
- adapter.setForeignObject(obj._id, obj, err => {
154
- err && adapter.log.error(err);
155
- setImmediate(syncObjects, objects, cb);
156
- });
157
- } else {
158
- hassObjects[obj._id] = oldObj;
159
- if (JSON.stringify(obj.native) !== JSON.stringify(oldObj.native)) {
160
- oldObj.native = obj.native;
161
-
162
- adapter.log.debug(`Update "${obj._id}": ${JSON.stringify(obj.common)}`);
163
- adapter.setForeignObject(obj._id, oldObj, err => {
164
- err => adapter.log.error(err);
165
- setImmediate(syncObjects, objects, cb);
166
- });
167
- } else {
168
- setImmediate(syncObjects, objects, cb);
169
- }
170
- }
171
- });
172
- }
173
-
174
- function syncRoom(room, members, cb) {
175
- adapter.getForeignObject(`enum.rooms.${room}`, (err, obj) => {
176
- if (!obj) {
177
- obj = {
178
- _id: `enum.rooms.${room}`,
179
- type: 'enum',
180
- common: {
181
- name: room,
182
- members: members
183
- },
184
- native: {}
185
- };
186
- adapter.log.debug(`Update "${obj._id}"`);
187
- adapter.setForeignObject(obj._id, obj, err => {
188
- err && adapter.log.error(err);
189
- cb();
190
- });
191
- } else {
192
- obj.common = obj.common || {};
193
- obj.common.members = obj.common.members || [];
194
- let changed = false;
195
- for (let m = 0; m < members.length; m++) {
196
- if (obj.common.members.indexOf(members[m]) === -1) {
197
- changed = true;
198
- obj.common.members.push(members[m]);
199
- }
200
- }
201
- if (changed) {
202
- adapter.log.debug(`Update "${obj._id}"`);
203
- adapter.setForeignObject(obj._id, obj, err => {
204
- err && adapter.log.error(err);
205
- cb();
206
- });
207
- } else {
208
- cb();
209
- }
210
- }
211
- });
212
- }
213
-
214
- const knownAttributes = {
215
- azimuth: {write: false, read: true, unit: '°'},
216
- elevation: {write: false, read: true, unit: '°'}
217
- };
218
-
219
-
220
- const ERRORS = {
221
- 1: 'ERR_CANNOT_CONNECT',
222
- 2: 'ERR_INVALID_AUTH',
223
- 3: 'ERR_CONNECTION_LOST'
224
- };
225
- const mapTypes = {
226
- 'string': 'string',
227
- 'number': 'number',
228
- 'object': 'mixed',
229
- 'boolean': 'boolean'
230
- };
231
- const skipServices = [
232
- 'persistent_notification'
233
- ];
234
-
235
- function parseStates(entities, services, callback) {
236
- const objs = [];
237
- const states = [];
238
- let obj;
239
- let channel;
240
- for (let e = 0; e < entities.length; e++) {
241
- const entity = entities[e];
242
- if (!entity) continue;
243
-
244
- const name = entity.name || (entity.attributes && entity.attributes.friendly_name ? entity.attributes.friendly_name : entity.entity_id);
245
- const desc = entity.attributes && entity.attributes.attribution ? entity.attributes.attribution : undefined;
246
-
247
- channel = {
248
- _id: `${adapter.namespace}.entities.${entity.entity_id}`,
249
- common: {
250
- name: name
251
- },
252
- type: 'channel',
253
- native: {
254
- object_id: entity.object_id,
255
- entity_id: entity.entity_id
256
- }
257
- };
258
- if (desc) channel.common.desc = desc;
259
- objs.push(channel);
260
-
261
- const lc = entity.last_changed ? new Date(entity.last_changed).getTime() : undefined;
262
- const ts = entity.last_updated ? new Date(entity.last_updated).getTime() : undefined;
263
-
264
- if (entity.state !== undefined) {
265
- obj = {
266
- _id: `${adapter.namespace}.entities.${entity.entity_id}.state`,
267
- type: 'state',
268
- common: {
269
- name: `${name} STATE`,
270
- type: typeof entity.state,
271
- read: true,
272
- write: false
273
- },
274
- native: {
275
- object_id: entity.object_id,
276
- domain: entity.domain,
277
- entity_id: entity.entity_id
278
- }
279
- };
280
- if (entity.attributes && entity.attributes.unit_of_measurement) {
281
- obj.common.unit = entity.attributes.unit_of_measurement;
282
- }
283
- adapter.log.debug(`Found Entity state ${obj._id}: ${JSON.stringify(obj.common)} / ${JSON.stringify(obj.native)}`)
284
- objs.push(obj);
285
-
286
- let val = entity.state;
287
- if ((typeof val === 'object' && val !== null) || Array.isArray(val)) {
288
- val = JSON.stringify(val);
289
- }
290
-
291
- states.push({id: obj._id, lc, ts, val, ack: true})
292
- }
293
-
294
- if (entity.attributes) {
295
- for (const attr in entity.attributes) {
296
- if (entity.attributes.hasOwnProperty(attr)) {
297
- if (attr === 'friendly_name' || attr === 'unit_of_measurement' || attr === 'icon') {
298
- continue;
299
- }
300
-
301
- let common;
302
- if (knownAttributes[attr]) {
303
- common = Object.assign({}, knownAttributes[attr]);
304
- } else {
305
- common = {};
306
- }
307
-
308
- const attrId = attr.replace(adapter.FORBIDDEN_CHARS, '_').replace(/\.+$/, '_');
309
- obj = {
310
- _id: `${adapter.namespace}.entities.${entity.entity_id}.${attrId}`,
311
- type: 'state',
312
- common: common,
313
- native: {
314
- object_id: entity.object_id,
315
- domain: entity.domain,
316
- entity_id: entity.entity_id,
317
- attr: attr
318
- }
319
- };
320
- if (!common.name) {
321
- common.name = `${name} ${attr.replace(/_/g, ' ')}`;
322
- }
323
- if (common.read === undefined) {
324
- common.read = true;
325
- }
326
- if (common.write === undefined) {
327
- common.write = false;
328
- }
329
- if (common.type === undefined) {
330
- common.type = mapTypes[typeof entity.attributes[attr]];
331
- }
332
-
333
- adapter.log.debug(`Found Entity attribute ${obj._id}: ${JSON.stringify(obj.common)} / ${JSON.stringify(obj.native)}`)
334
-
335
- objs.push(obj);
336
-
337
- let val = entity.attributes[attr];
338
- if ((typeof val === 'object' && val !== null) || Array.isArray(val)) {
339
- val = JSON.stringify(val);
340
- }
341
-
342
- states.push({id: obj._id, lc, ts, val, ack: true});
343
- }
344
- }
345
- }
346
-
347
- const serviceType = entity.entity_id.split('.')[0];
348
-
349
- if (services[serviceType] && !skipServices.includes(serviceType)) {
350
- const service = services[serviceType];
351
- for (const s in service) {
352
- if (service.hasOwnProperty(s)) {
353
- obj = {
354
- _id: `${adapter.namespace}.entities.${entity.entity_id}.${s}`,
355
- type: 'state',
356
- common: {
357
- desc: service[s].description,
358
- read: false,
359
- write: true,
360
- type: 'mixed'
361
- },
362
- native: {
363
- object_id: entity.object_id,
364
- domain: entity.domain,
365
- fields: service[s].fields,
366
- entity_id: entity.entity_id,
367
- attr: s,
368
- type: serviceType
369
- }
370
- };
371
-
372
- adapter.log.debug(`Found Entity service ${obj._id}: ${JSON.stringify(obj.common)} / ${JSON.stringify(obj.native)}`)
373
-
374
- objs.push(obj);
375
- }
376
- }
377
- }
378
- }
379
-
380
- syncObjects(objs, () =>
381
- syncStates(states, callback));
382
- }
383
-
384
- function main() {
385
- adapter.config.host = adapter.config.host || '127.0.0.1';
386
- adapter.config.port = parseInt(adapter.config.port, 10) || 8123;
387
-
388
- adapter.setState('info.connection', false, true);
389
-
390
- hass = new HASS(adapter.config, adapter.log);
391
-
392
- hass.on('error', err =>
393
- adapter.log.error(err));
394
-
395
- hass.on('state_changed', entity => {
396
- adapter.log.debug(`HASS-Message: State Changed: ${JSON.stringify(entity)}`);
397
- if (!entity || typeof entity.entity_id !== 'string') {
398
- return;
399
- }
400
-
401
- const id = `entities.${entity.entity_id}.`;
402
- const lc = entity.last_changed ? new Date(entity.last_changed).getTime() : undefined;
403
- const ts = entity.last_updated ? new Date(entity.last_updated).getTime() : undefined;
404
- if (entity.state !== undefined) {
405
- if (hassObjects[`${adapter.namespace}.${id}state`]) {
406
- adapter.setState(`${id}state`, {val: entity.state, ack: true, lc: lc, ts: ts});
407
- } else {
408
- adapter.log.info(`State changed for unknown object ${`${id}state`}. Please restart the adapter to resync the objects.`);
409
- }
410
- }
411
- if (entity.attributes) {
412
- for (const attr in entity.attributes) {
413
- if (!entity.attributes.hasOwnProperty(attr) || attr === 'friendly_name' || attr === 'unit_of_measurement' || attr === 'icon'|| !attr.length) {
414
- continue;
415
- }
416
- let val = entity.attributes[attr];
417
- if ((typeof val === 'object' && val !== null) || Array.isArray(val)) {
418
- val = JSON.stringify(val);
419
- }
420
- const attrId = attr.replace(adapter.FORBIDDEN_CHARS, '_').replace(/\.+$/, '_');
421
- if (hassObjects[`${adapter.namespace}.${id}state`]) {
422
- adapter.setState(id + attrId, {val, ack: true, lc, ts});
423
- } else {
424
- adapter.log.info(`State changed for unknown object ${id + attrId}. Please restart the adapter to resync the objects.`);
425
- }
426
- }
427
- }
428
- });
429
-
430
- hass.on('connected', () => {
431
- if (!connected) {
432
- adapter.log.debug('Connected');
433
- connected = true;
434
- adapter.setState('info.connection', true, true);
435
- hass.getConfig((err, config) => {
436
- if (err) {
437
- adapter.log.error(`Cannot read config: ${err}`);
438
- return;
439
- }
440
- //adapter.log.debug(JSON.stringify(config));
441
- delayTimeout = setTimeout(() => {
442
- delayTimeout = null;
443
- !stopped && hass.getStates((err, states) => {
444
- if (stopped) {
445
- return;
446
- }
447
- if (err) {
448
- return adapter.log.error(`Cannot read states: ${err}`);
449
- }
450
- //adapter.log.debug(JSON.stringify(states));
451
- delayTimeout = setTimeout(() => {
452
- delayTimeout = null;
453
- !stopped && hass.getServices((err, services) => {
454
- if (stopped) {
455
- return;
456
- }
457
- if (err) {
458
- adapter.log.error(`Cannot read states: ${err}`);
459
- } else {
460
- //adapter.log.debug(JSON.stringify(services));
461
- parseStates(states, services, () => {
462
- adapter.log.debug('Initial parsing of states done, subscribe to ioBroker states');
463
- adapter.subscribeStates('*');
464
- });
465
- }
466
- })}, 100);
467
- })}, 100);
468
- });
469
- }
470
- });
471
-
472
- hass.on('disconnected', () => {
473
- if (connected) {
474
- adapter.log.debug('Disconnected');
475
- connected = false;
476
- adapter.setState('info.connection', false, true);
477
- }
478
- });
479
-
480
- hass.connect();
481
- }
482
-
483
- // If started as allInOne/compact mode => return function to create instance
484
- if (module && module.parent) {
485
- module.exports = startAdapter;
486
- } else {
487
- // or start the instance directly
488
- startAdapter();
489
- }