-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.js
431 lines (379 loc) · 14.7 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
"use strict";
const utils = require("@iobroker/adapter-core");
const axios = require("axios").default;
let url = "";
let updateDataInterval;
let timeout1Scan;
let failedConnectCounter = 0;
class OekofenJson extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: "oekofen-json",
});
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() {
//Build our request URL
url = "http://" + this.config.oekofenIp + ":" + this.config.oekofenPort + "/" + this.config.oekofenPassword;
this.log.debug("[onReady] Generated URL for requests: " + url);
this.log.debug("[onReady] subscribed to rescan datapoint");
this.subscribeStates("info.rescan");
this.log.debug("[onReady] subscribed to update datapoint");
this.subscribeStates("info.update");
this.log.debug("[onReady] info.rescan value set to false");
await this.setStateAsync("info.rescan", false, true);
this.log.debug("[onReady] info.update set to false");
await this.setStateAsync("info.update", false, true);
this.log.debug("[onReady] set failedConnectCounter explicitely to 0");
failedConnectCounter = 0;
//Initiate a delay between Adapter-StartUp and the first connection attempt to OekoFEN
this.log.debug("[onReady] created timeout for 1st scan");
timeout1Scan = setTimeout(async() => await this.initialScan(url), 10000);
//Initialize the connection state with value false; it will be set to true after first successful webrequest
this.log.debug("[onReady] set info.connection to initial false");
this.setStateAsync("info.connection", { val: false, ack: true });
}
/**
* @param {string} url
*/
async initialScan(url) {
this.log.debug("[initialScan] called with url: " + url + " and encoding: latin1");
try {
const response = await axios.get(url + "/all?", { responseEncoding: "latin1" });
if ((response.status === 200) && (typeof response.data === "object")) {
this.log.debug("[initialScan_axios.get] got HTTP/200 response, call parseDataOnStartupAndCreateObjects with response.data");
await this.parseDataOnStartupAndCreateObjects(response.data);
//Set connection to true, if get-request was successful
this.log.debug("[initialScan_axios.get] set info.connection to true as request was successful");
this.setStateAsync("info.connection", { val: true, ack: true });
this.log.debug("[initialScan] set updateDataInterval to " + Number.parseInt(this.config.myRequestInterval)*1000);
updateDataInterval = setInterval(async () => await this.updateData(url), Number.parseInt(this.config.myRequestInterval)*1000);
} else {
throw "axios response code " + response.status;
}
} catch (error) {
this.log.error("[initialScan_axios.get.catch] " + error + " - Adapter exiting now.");
//Set connection to false in case of errors
this.log.debug("[initialScan_axios.get.catch] error while initial request has occured, disable adapter.");
this.setStateAsync("info.connection", { val: false, ack: true });
this.disable();
return;
}
}
/**
* @param {string} url
*/
async updateData(url) {
this.log.debug("[updateData] called with url: " + url + " and encoding: latin1");
//for a normale update, we'll use the normal /all path, this will reduce transmitted data to about half the size
try {
const response = await axios.get(url + "/all", { responseEncoding: "latin1" });
if ((response.status === 200) && (typeof response.data === "object")) {
this.log.debug("[updateData_axios.get] got HTTP/200 response, call parseDataAndSetValues with response.data");
await this.parseDataAndSetValues(response.data, this);
//Set connection to true, if get-request was successful
this.log.debug("[updateData_axios.get] set info.connection to true as request was successful");
this.setStateAsync("info.connection", { val: true, ack: true });
//Reset failedConnectCounter to 0 as connection was successful
failedConnectCounter = 0;
} else {
throw "axios response code " + response.status;
}
} catch (error) {
this.log.error("[updateData_axios.get.catch] " + error);
//Set connection to false in case of errors
this.log.debug("[updateData_axios.get.catch] error while request has occured, setting info.connection to false");
this.setStateAsync("info.connection", { val: false, ack: true });
failedConnectCounter += 1;
//Check if counter gets too high, if yes, disable the adapter.
if (failedConnectCounter > 10) {
this.log.error("[updateData_axios.get.catch] failed to get data 10 in a row. Disabling adapter. Please check your heater.");
this.disable();
}
}
}
/**
* @param {object} jsonData
*/
async parseDataOnStartupAndCreateObjects(jsonData) {
//Check if there are more than 50 Toplevel-Objects, this isn't plausible
const jsonDataLength = Object.keys(jsonData).length;
if (jsonDataLength > 50) {
this.log.error("[parseDataOnStartupAndCreateObjects] jsonDataLength is too big (" + jsonDataLength + ") - Adapter exiting now.");
//Set connection to false in case of errors
this.log.debug("[parseDataOnStartupAndCreateObjects] error while parsing data has occured, disable adapter.");
this.setStateAsync("info.connection", { val: false, ack: true });
this.disable();
return;
}
for (const key of Object.keys(jsonData)) {
//if we reach those top-level-keys, just skip them; e.g. weather-forecast as we not even can manipulate something here
if (key === "forecast") {
continue;
} else {
//create the top-level-keys as channels
this.log.debug("[parseDataOnStartupAndCreateObjects] created channel " + key);
await this.setObjectNotExistsAsync(key, {
type: "channel",
common: {
name: key,
role: "channel",
},
native: {
}
});
}
for (const innerKey of Object.keys(jsonData[key])) {
//iterate through each child of the top-level-keys
let objType;
let objStates;
let objMin;
let objMax;
let objFactor;
let objUnit;
//try to find out, how the datapoint looks like
//For v3.10d try to find out if the current datapoint maybe is a wrongly stringified Number
if ((innerKey !== "name") && ((typeof jsonData[key][innerKey].val === "number") || !isNaN(Number(jsonData[key][innerKey].val)))) {
if (jsonData[key][innerKey].format === undefined) {
objType = "number";
} else {
objType = "number";
const input = jsonData[key][innerKey].format;
const firstDelimiter = "|";
const secondDelimiter = ":";
const cleanInput = input.replace(/#./g, "|");
const output = cleanInput.split(firstDelimiter).reduce( (/** @type {{ [x: string]: any; }} */ newArr, /** @type {string} */ element, /** @type {string | number} */ i) => {
const subArr = element.split(secondDelimiter);
newArr[i] = subArr;
return newArr;
}, []);
objStates = Object.fromEntries(output);
}
} else if(typeof jsonData[key][innerKey].val === "string" || innerKey === "name") {
objType = "string";
} else if(jsonData[key][innerKey].val === undefined) {
objType = "string";
} else {
objType = "mixed";
}
if (jsonData[key][innerKey].factor)
{
objFactor = Number(jsonData[key][innerKey].factor);
} else {
objFactor = undefined;
}
if (jsonData[key][innerKey].min) {
if(objFactor) {
objMin = Number(jsonData[key][innerKey].min) * objFactor;
} else {
objMin = Number(jsonData[key][innerKey].min);
}
} else {
objMin = undefined;
}
if (jsonData[key][innerKey].max) {
if(objFactor) {
objMax = Number(jsonData[key][innerKey].max) * objFactor;
} else {
objMax = Number(jsonData[key][innerKey].max);
}
} else {
objMax = undefined;
}
if (jsonData[key][innerKey].unit) {
if (jsonData[key][innerKey].unit === "?C")
{
objUnit = "°C";
} else {
objUnit = jsonData[key][innerKey].unit;
}
} else {
objUnit = undefined;
}
//As v3.10d sends everything as string, convert everything which could be a number to a number.
//In later versions, Number(aNumber) should just return itself
//ignore the info-datapoint; its useless for iobroker
if (!innerKey.endsWith("_info")) {
await this.setObjectNotExistsAsync(key + "." + innerKey, {
type: "state",
common: {
name: innerKey,
type: objType,
role: "state",
read: true,
write: (innerKey.startsWith("L_") ? false : true),
states: objStates,
min: objMin,
max: objMax,
unit: objUnit
},
native: {
factor: objFactor
}
});
this.log.debug("[parseDataOnStartupAndCreateObjects] created state " + key + "." + innerKey);
//subscribe only to writeable datapoints
if (!innerKey.startsWith("L_")) { this.subscribeStates(key + "." + innerKey); }
}
}
}
}
/**
* @param {object} jsonData
* @param {object} instanceObject
*/
async parseDataAndSetValues(jsonData, instanceObject) {
//Check if there are more than 50 Toplevel-Objects, this isn't plausible
const jsonDataLength = Object.keys(jsonData).length;
if (jsonDataLength > 50) {
this.log.error("[parseDataAndSetValues] jsonDataLength is too big (" + jsonDataLength + ") - Adapter exiting now.");
//Set connection to false in case of errors
this.log.debug("[parseDataAndSetValues] error while parsing data has occured, disable adapter.");
this.setStateAsync("info.connection", { val: false, ack: true });
this.disable();
return;
}
for (const key of Object.keys(jsonData)) {
//if we reach those top-level-keys, just skip them; e.g. weather-forecast as we not even can manipulate something here
if (key === "forecast") {continue;}
for (const innerKey of Object.keys(jsonData[key])) {
try {
//get the object from ioBroker and find out if there's a factor which needs to be applied
this.getObject(key + "." + innerKey, function(err, obj) {
let tNewVal;
// Find out which datatype the object in iobroker is and convert the value
if (obj.common.type === "number") {
tNewVal = Number(jsonData[key][innerKey]);
} else if (obj.common.type === "string") {
tNewVal = String(jsonData[key][innerKey]);
} else {
throw("Datapoint (" + key + "." + innerKey + ") is without type. Data won't get updatet!");
}
if (obj && obj.native.factor) {
instanceObject.setStateAsync(key + "." + innerKey, {val: tNewVal * obj.native.factor, ack: true});
} else {
instanceObject.setStateAsync(key + "." + innerKey, {val: tNewVal, ack: true});
}
});
} catch (error) {
//normally, we won't reach this code
this.log.error("Error in function parseDataAndSetValues: "+ error);
this.setState("info.connection", {val: false, ack: true});
}
}
}
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
onUnload(callback) {
try {
clearTimeout(timeout1Scan);
clearInterval(updateDataInterval);
this.setStateAsync("info.connection", { val: false, ack: true });
callback();
} catch (e) {
callback();
}
}
/**
* Is called if a subscribed state changes
* @param {string} id
* @param {ioBroker.State | null | undefined} state
*/
async onStateChange(id, state) {
//is the onStateChange called by update or rescan trigger?
if (id === this.namespace + ".info.rescan" && !state.ack && state.val) {
clearInterval(updateDataInterval);
this.log.debug("Rescan of all datapoints initiated");
await this.initialScan(url);
await this.setStateAsync(id, false, true);
return;
}
if (id === this.namespace + ".info.update" && !state.ack && state.val) {
this.log.debug("Update of values initiated");
await this.updateData(url);
await this.setStateAsync(id, false, true);
return;
}
if (state && !state.ack) {
//to update the value on the remote-side, we'll need to check if there's a factor applied or min/max is defined
//therefore we'll try to get the datapoint from ioBroker first
const dataPoint = await this.getObjectAsync(id);
if (!dataPoint) {
this.log.error("Error, DataPoint " + id + "not found!");
return "Error, DataPoint not found";
}
//check if this datapoint has a factor defined
if (dataPoint.native.factor) {
const realValue = Number.parseInt(state.val) / dataPoint.native.factor;
if (dataPoint.max) {
const realMax = dataPoint.max / dataPoint.native.factor;
if (realValue > realMax) {
this.log.error("Value " + state.val + " for dataPoint " + id + "is bigger than allowed max (" + dataPoint.max +")");
return "Error; Value bigger than maxVal";
}
}
if (dataPoint.min) {
const realMin = dataPoint.min / dataPoint.native.factor;
if (realValue < realMin) {
this.log.error("Value " + state.val + " for dataPoint " + id + "is smaller than allowed min (" + dataPoint.min +")");
return "Error; Value smaller than minVal";
}
}
//If everything worked till here, send the update to OekoFEN and only if we receive true, set the ack flag
if (await this.sendUpdateToOekofen(id, realValue)) {
this.log.debug(`state ${id} changed: value ${state.val} (realValue=${realValue}) (ack = ${state.ack})`);
await this.setStateAsync(id, state.val, true);
}
} else {
//So no factor is present, just send the update to OekoFEN and only if we receive true, set the ack flag
if (await this.sendUpdateToOekofen(id, state.val)) {
this.log.debug(`state ${id} changed: value ${state.val} (ack = ${state.ack})`);
await this.setStateAsync(id, state.val, true);
}
}
} else {
//this.log.debug(`state ${id} deleted`);
}
}
/**
* @param {string} stateId
* @param {string | number} newValue
*/
async sendUpdateToOekofen(stateId, newValue) {
const urlForUpdate = url + "/" + stateId.replace(this.namespace, "").substring(1) + "=" + newValue;
try {
const res = await axios.get(urlForUpdate, { responseEncoding: "latin1" });
if (res.status === 200) {
return true;
} else {
this.log.error("[sendUpdateToOekofen] Error while making Webrequest: Webserver rejected request");
return false;
}
} catch (error) {
this.log.error("[sendUpdateToOekofen] Error while making Webrequest: " + error);
}
return false;
}
}
if (require.main !== module) {
// Export the constructor in compact mode
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
module.exports = (options) => new OekofenJson(options);
} else {
// otherwise start the instance directly
new OekofenJson();
}