-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.js
569 lines (499 loc) · 18.8 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
"use strict";
/*
* Created with @iobroker/create-adapter v1.16.0
*/
// The adapter-core module gives you access to the core ioBroker functions
// you need to create an adapter
const utils = require("@iobroker/adapter-core");
const BSB = require("./lib/bsb");
const {InfoObjects} = require("./lib/config");
const bsbutils = require("./lib/bsb_utils");
class Bsblan extends utils.Adapter {
/**
* @param {Partial<ioBroker.AdapterOptions>} [options={}]
*/
constructor(options) {
// @ts-ignore
super({
...options,
name: "bsblan",
});
this.on("ready", this.onReady.bind(this));
this.on("stateChange", this.onStateChange.bind(this));
this.on("unload", this.onUnload.bind(this));
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
// setup timer
this.interval = Number(this.config.interval) || 60;
this.interval *= 1000;
if (this.interval < 10000)
this.interval = 10000;
this.values = this.resolveConfigValues();
await this.migrateExistingObjects();
// only supported bsb_lan > 2.x
await this.updateNativeData();
this.subscribeStates("*");
await this.setupDefaultObjects();
await this.update();
}
getBSB() {
if(!this.bsb) {
this.bsb = new BSB(this.config.host, this.config.user, this.config.password);
}
return this.bsb;
}
resolveConfigValues() {
const bsb = this.getBSB();
const values = new Set();
for (const line of this.config.values.split(/\r?\n/)) {
for (const entry of line.split(",")) {
const value = entry.trim();
if (value.length === 0) {
//ignore
} else if (!bsb.validateParameterId(value)) {
this.log.error(value + " is not a valid id to retrieve.");
} else {
// do not allow adding more than one parameter per address
const id = bsb.getId(value);
let unique = true;
for(const setValue of values) {
if(setValue != value && bsb.getId(setValue) == id) {
this.log.error("Can not add parameter " + value + ". " + setValue + " already exists, only one address is supported per parameter!");
unique = false;
break;
}
}
if(unique) {
values.add(bsb.trimParameterId(value));
}
}
}
}
const valuesArray = [...values].sort(bsbutils.bsbSort);
this.log.info("Values found: " + valuesArray);
return valuesArray;
}
async update() {
this.log.debug("Update default states ...");
await this.updateDefaultStates()
.catch((error) => {
this.errorHandler(error);
this.refreshTimer();
});
this.log.debug("Update parameters ...");
await this.detectNewObjects(this.values)
.then(newValues => this.initializeParameters(newValues))
.then(() => this.connectionHandler(true))
.then(() => this.getBSB().getParameter(this.values))
.then(result => this.setStates(result))
.then(() => this.getBSB().query24hAverages())
.then(result24h => this.set24hAverages(result24h))
.then(() => this.refreshTimer())
.catch((error) => {
this.errorHandler(error);
this.refreshTimer();
});
}
refreshTimer() {
this.log.debug("Reset Timer");
this.timer = setTimeout(() => this.update(), this.interval);
}
/**
* Is called if a subscribed state changes
* @param {string} id
* @param {ioBroker.State | null | undefined} state
*/
async onStateChange(id, state) {
if (state) {
// The state was changed
if (this.bsb && state && !state.ack) {
this.log.info(`Sending write request for ${id} (value: ${state.val})`);
this.getObjectAsync(id)
.then(obj => {
if(obj && obj.native && obj.native.bsb) {
return this.getBSB().write(obj.native.id, state.val, obj.native.bsb.dataType);
} else {
this.log.error(`Error getting BSB native information from: ${id}`);
}
})
.then(response => {
this.log.debug(`Received write response: ${JSON.stringify(response)}`);
return this.getBSB().getParameter(Object.keys(response));
})
.then(result => this.setStates(result))
.catch((error) => {
if (error.name === "BSBWriteError") {
this.log.error(`Error writing value: ${error.message}`);
// ignore
} else {
this.errorHandler(error);
}
});
}
} else {
// The state was deleted
this.log.info(`state ${id} deleted`);
}
}
async initializeParameters(values) {
if (!values || values.size === 0) return;
this.log.info("Setup new objects (" + [...values] + ") ...");
this.categories = await this.getBSB().categories();
const categoryMap = {};
for (const value of values) {
for (const category of Object.keys(this.categories)) {
if (this.getBSB().valueInCategory(value, this.categories[category])) {
const obj = {
id: category,
native: this.categories[category],
values: []
};
if (!categoryMap[category]) {
categoryMap[category] = obj;
}
categoryMap[category].values.push(value);
break;
}
}
}
const queriedValues = await this.getBSB().getParameter(values);
let createdValues = new Set();
for (const category of Object.keys(categoryMap)) {
this.log.info("Fetching category " + category + " " + categoryMap[category].native.name + " ...");
await this.getBSB().category(category)
.then(result => this.setupCategory(categoryMap[category], result, queriedValues))
.then(result => createdValues = new Set([...createdValues, ...result]));
}
this.showInvalidValues(createdValues, values);
this.log.info("Setup objects done.");
return createdValues;
}
showInvalidValues(createdValues, newValues) {
for (const value of newValues) {
if (!createdValues.has(value)) {
this.log.warn("Value not found, skipping: " + value);
}
}
}
detectNewObjects(values) {
// native.id stores the id without the address, so we need also to use only the part without the address
const newValues = new Set();
values.map(value => newValues.add(this.getBSB().getId(value)));
return this.getAdapterObjectsAsync()
.then(records => {
for (const key of Object.keys(records)) {
if (records[key].native) {
const id = records[key].native.id;
if (newValues.has(id)) {
newValues.delete(id);
}
}
}
return newValues;
});
}
setupCategory(category, params, values) {
const name = category.native["name"] + " (" + category.native["min"] + " - " + category.native["max"] + ")";
this.log.info("Setup category " + category.id + ": " + name);
const createdValues = new Set();
for (const value of category.values) {
const id = this.getBSB().getId(value);
if (id in params) {
this.setupObject(id, params[id], values[id])
.catch((error) => this.errorHandler(error));
createdValues.add(value);
}
}
return createdValues;
}
async setupDefaultObjects() {
this.log.info("Fetch device information ...");
await this.getBSB().queryInfo()
.then(info => InfoObjects.map(object => this.setupDefaultObject(object, info)))
.catch(error => this.errorHandler(error));
}
async setupDefaultObject(object, info) {
const name = "info." + object.id;
if (Object.hasOwnProperty.call(info, object.id)) {
await this.setObjectNotExistsAsync(name, object.obj)
.then(response => {
// if the object exists, we get an undefined
if (response !== undefined) {
this.log.info("Add Info Object: " + name + " " + JSON.stringify(response));
}
})
.catch(error => this.errorHandler(error));
}
}
async updateDefaultStates() {
await this.getBSB().queryInfo()
.then(info => this.setDefaultStates(info))
.catch(error => this.errorHandler(error));
}
async setDefaultStates(info) {
for (const object of InfoObjects) {
const name = "info." + object.id;
if (Object.hasOwnProperty.call(info, object.id)) {
// no conversion needed because BSBLAN already delivers string or number
await this.setStateAsync(name, {val: info[object.id], ack: true})
.catch(error => this.errorHandler(error));
}
}
}
async setupObject(key, param, value) {
const name = param.name + " (" + key + ")";
this.log.info("Add Parameter: " + name);
// bsb_lan 2.x feature
let write;
if ("readonly" in value) {
write = value.readonly === 0;
} else {
// bsb_lan 1.x we have to guess or hard-code
write = this.getBSB().isReadWrite(key);
}
const obj = {
type: "state",
common: {
name: name,
type: this.mapType(param.dataType),
role: "value",
read: true,
write: write,
unit: this.parseUnit(value.unit)
},
native: {
id: key,
bsb: param,
}
};
if (param.possibleValues.length > 0) {
obj.common.states = this.createObjectStates(param.possibleValues);
}
// @ts-ignore
await this.setObjectNotExistsAsync(this.createId(key, param.name), obj)
.then(() => this.setStateAsync(this.createId(key, param.name), {
val: this.parseValue(value.value, value.dataType),
ack: true
}))
.catch((error) => this.errorHandler(error));
}
async set24hAvgObject(key, param) {
const name = param.name + " (" + key + ")";
this.log.debug("Set 24h Average: " + name);
const obj = {
type: "state",
common: {
name: name,
type: "number",
role: "value",
read: true,
write: false,
unit: this.parseUnit(param.unit)
},
native: {
id: key,
bsb: param,
avg: "24h"
}
};
await this.setObjectNotExistsAsync("24h", {
type: "channel",
common: {
name: "24h averages"
},
native: {}
});
// @ts-ignore
await this.setObjectNotExistsAsync("24h." + this.createId(key, param.name), obj)
.then(() => this.setStateAsync("24h." + this.createId(key, param.name), {
val: this.parseValue(param.value, param.dataType),
ack: true
}))
.catch((error) => this.errorHandler(error));
}
async set24hAverages(data) {
this.log.debug("/JA Response: " + JSON.stringify(data));
for (const key of Object.keys(data)) {
await this.set24hAvgObject(key, data[key]);
}
}
setStates(data) {
this.log.debug("/JQ Response: " + JSON.stringify(data));
for (const key of Object.keys(data)) {
this.setStateAsync(
this.createId(key, data[key].name),
{
val: this.parseValue(data[key].value, data[key].dataType),
ack: true
}
).catch((error) => this.errorHandler(error));
}
}
createId(key, name) {
const sanitized_key = key.replace(/\./g, "_");
return name.replace(/[\][*,;'"`<>’\\\s?]/g, "_").replace(/\./g, "") + "_(" + sanitized_key + ")";
}
createObjectStates(possibleValues) {
const states = {};
for (const entry of possibleValues) {
states[entry["enumValue"]] = entry["desc"];
}
return states;
}
mapType(type) {
// https://1coderookie.github.io/BSB-LPB-LAN/kap08.html#824-abrufen-und-steuern-mittels-json
switch (type) {
case 0:
return "number"; // number
case 1:
return "number"; // enum
case 2:
return "string"; // Bit value
case 3:
return "string"; // weekday
case 4:
return "string"; // hr/min
case 5:
return "string"; // date/time
case 6:
return "string"; // day/month
case 7:
return "string"; // string
default:
return "string";
}
}
parseValue(value, type) {
switch(type) {
case 0: // number
case 1: // enum
// BSB_LAN returns --- for numbers
// https://github.com/fredlcore/BSB-LAN/issues/469
if (value == "---") {
return 0;
}
return parseFloat(value);
default: // no conversion
return value;
}
}
parseUnit(unit) {
return unit
.replace("°", "°")
.replace("%", "%")
.replace("µ", "u"); // micro
}
async migrateExistingObjects() {
await this.getAdapterObjectsAsync().then(objects => {
for (const id in objects) {
const obj = objects[id];
if (obj.native && obj.native.bsb) {
this.fixReadWrite(obj);
this.fixEmptyStates(obj);
this.extendObject(id, obj);
this.warnInvalidCharacters(obj);
this.fixDataType(obj);
}
}
});
}
fixReadWrite(obj) {
// not needed for objects created from V1 firmware
if ("bsb" in obj.native && "readonly" in obj.native.bsb) {
return;
}
const rw = this.getBSB().isReadWrite(obj.native.id);
if (rw !== obj.common.write) {
this.log.info(`Migrate ${obj._id}: set write = ${rw}`);
obj.common.write = rw;
}
}
fixEmptyStates(obj) {
if (obj.common.states && Object.keys(obj.common.states).length === 0) {
this.log.info(`Migrate ${obj._id}: remove empty states`);
obj.common.states = null;
}
}
warnInvalidCharacters(obj) {
const newId = this.createId(obj.native.id, obj.native.bsb.name);
const oldId = obj._id.split(".");
if (oldId[oldId.length - 1] !== newId) {
this.log.warn(`Object ${obj._id} contains illegal characters, please delete. ${newId} will then be created automatically.`);
}
}
fixDataType(obj) {
if ("bsb" in obj.native && "dataType" in obj.native.bsb) {
const newType = this.mapType(obj.native.bsb.dataType);
if (obj.common.type != newType) {
this.log.info(`Migrate ${obj._id}: Change data type from ${obj.common.type} to ${newType}`);
obj.common.type = newType;
}
}
}
async updateNativeData() {
this.log.info("Updating meta information of parameters ...");
// get all existing objects
const objects = await this.getAdapterObjectsAsync();
// convert into array of dict [iob id, bsb id]
const ids = {};
Object.values(objects)
.filter(obj => obj.native)
.filter(obj => obj.native.id)
.filter(obj => !this.getBSB().validateParameterId(obj.native.id))
.map(obj => ids[obj.native.id] = obj);
// fetch parameter definitions (bsb_lan > 2.x)
const defs = await this.getBSB().getParameterDefinitionAsync(this.values)
.catch(error => this.errorHandler(error));
if(defs != null) {
// merge native data
for (const [bsb_id, obj] of Object.entries(ids)) {
// check if the object has a definition available
if (bsb_id in defs) {
// update native data
obj.native.bsb = defs[bsb_id];
await this.setObjectAsync(obj._id, obj);
}
}
}
}
errorHandler(error) {
this.log.error(error.message);
if (error.stack)
this.log.error(error.stack);
this.connectionHandler(false);
}
connectionHandler(connected) {
if (this.connection !== connected) {
this.connection = connected;
if (connected)
this.log.info("Connection established successfully");
else
this.log.error("Connection failed");
this.setState("info.connection", this.connection, true);
}
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
onUnload(callback) {
try {
clearTimeout(this.timer);
this.log.info("cleaned everything up...");
callback();
} catch (e) {
callback();
}
}
}
// @ts-ignore parent is a valid property on module
if (module && module.parent) {
// Export the constructor in compact mode
module.exports = (options) => new Bsblan(options);
} else {
// otherwise start the instance directly
new Bsblan();
}