-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.js
342 lines (317 loc) · 8.84 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
'use strict';
const utils = require('@iobroker/adapter-core');
const puppeteer = require('puppeteer');
const sleep = require('util').promisify(setTimeout);
let stopped = false;
class RmbBhkw extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: 'rmb-bhkw',
});
this.on('ready', this.onReady.bind(this));
// this.on('objectChange', this.onObjectChange.bind(this));
// this.on('message', this.onMessage.bind(this));
// @ts-ignore
this.on('unload', this.onUnload.bind(this));
}
async onReady() {
const bhkwID = this.config.bhkwID;
const re = /^.*:\/\//;
const browserPath = 'ws://' + this.config.browserPath.replace(re, '');
const externalBrowser = this.config.externalBrowser;
const allowInsecure = this.config.allowInsecure;
const delay = Math.floor(Math.random() * 1000 * 60);
let browser;
const results = [];
await this.setObjectNotExistsAsync('_DataAge', {
type: 'state',
common: {
name: '_DataAge',
type: 'number',
role: 'state',
// @ts-ignore
read: true,
write: false,
unit: 'min',
},
native: {},
});
this.log.info('Delaying for ' + delay / 1000 + ' seconds.');
//await new Promise(() => setTimeout(() => this.log.info('Starte mit Verzögerung'), delay));
await sleep(delay);
if (stopped) {
// @ts-ignore
return;
} else {
this.log.info('Start with Delay');
try {
if (bhkwID < 800 || bhkwID > 99999 || bhkwID == undefined) {
throw new Error('Invalid NeoTower ID. Stopping Adapter.');
}
this.log.info('Reading data for NeoTower ID: ' + bhkwID);
if (externalBrowser) {
this.log.debug('Using external browser: ' + browserPath);
try {
if (allowInsecure) {
//browser = await puppeteer.connect({ browserWSEndpoint: browserPath, ignoreHTTPSErrors: true});
browser = await puppeteer.connect({
browserWSEndpoint: browserPath,
});
} else {
browser = await puppeteer.connect({
browserWSEndpoint: browserPath,
});
}
} catch (error) {
throw new Error(
'Could not establish connection to external browser. Is the URL correct?',
);
}
} else {
this.log.debug('Using the integrated browser');
if (allowInsecure) {
browser = await puppeteer.launch({
args: [
'--proxy-bypass-list=*',
'--disable-gpu',
'--disable-dev-shm-usage',
'--disable-setuid-sandbox',
'--no-first-run',
'--no-sandbox',
'--no-zygote',
'--single-process',
'--ignore-certificate-errors',
'--ignore-certificate-errors-spki-list',
'--enable-features=NetworkService',
],
});
} else {
browser = await puppeteer.launch();
}
}
// @ts-ignore
const page = await browser.newPage();
await page.goto(
'https://rmbenergie.de/rmbreport_br/en/messwerte.php?ident=' + bhkwID,
);
await page.waitForSelector('.auto-style3');
const data = await page.$$eval(
'.auto-style3, .auto-style4',
(items) => {
console.log(items);
return items.map((x) => x.innerHTML);
},
);
// Iterate through node-list and store results as object properties
for (let i = 0; i < 54; i++) {
const unit = data[i + 1].split(' ')[1];
let dataType = 'mixed';
if (
unit === '°C' ||
unit === 'kW' ||
unit === '%' ||
unit === 'bar'
) {
dataType = 'number';
}
results.push({
name: data[i].split(':')[0].replace(/\s\(.+\)/, ''),
value: data[i + 1].split(' ')[0],
unit: unit,
type: dataType,
});
i++;
}
//Get timestamp of last data refresh from website
// @ts-ignore
const timeString = await page.$eval('.auto-style5', (e) =>
e.innerText.split(' '),
);
await page.goto(
'https://rmbenergie.de/rmbreport_br/display.php?ident=' + bhkwID,
);
await page.waitForSelector('div#ladungszahl');
// @ts-ignore
const stateOfCharge = await page.$eval(
'div#ladungszahl',
(e) => e.innerText.split(' ')[0],
);
results.push({
name: 'SoC',
value: stateOfCharge,
type: 'number',
unit: '%',
});
// @ts-ignore
await browser.close();
//Extract dates from string
const time = timeString[3];
const date = timeString[2].split(',')[0];
const now = new Date();
const dateSplit = date.split('.');
const timeSplit = time.split(':');
//If Server is offline, update _DataAge state and quit adapter.
if (date === '01.01.1970' || date == undefined) {
//Get current states from objects
const oldDateString = await this.getStateAsync('_DateLastRefresh');
const oldTimeString = await this.getStateAsync('_TimeLastRefresh');
//If objects do not exist (first time starting adapter), exit immediately
if (!oldDateString || !oldTimeString) {
throw new Error(
'Server is not providing any data. Service potentially offline.',
);
}
// @ts-ignore
const oldDateSplit = oldDateString.val.toString().split('.');
// @ts-ignore
const oldTimeSplit = oldTimeString.val.toString().split(':');
// @ts-ignore
const oldTimeStamp = new Date(
// @ts-ignore
oldDateSplit[2],
// @ts-ignore
oldDateSplit[1] - 1,
oldDateSplit[0],
oldTimeSplit[0],
oldTimeSplit[1],
oldTimeSplit[2],
);
const oldDataAge = Math.floor(
(now.valueOf() - oldTimeStamp.valueOf()) / 1000 / 60,
);
await this.setStateAsync('_DataAge', { val: oldDataAge, ack: true });
throw new Error(
'Server is not providing any data. Service potentially offline.',
);
}
//Calculate time passed since last data refresh
const timeStamp = new Date(
dateSplit[2],
dateSplit[1] - 1,
dateSplit[0],
timeSplit[0],
timeSplit[1],
timeSplit[2],
);
const dataAge = Math.floor(
(now.valueOf() - timeStamp.valueOf()) / 1000 / 60,
);
results.push(
{
name: '_DateLastRefresh',
value: date,
type: 'string',
unit: '',
},
{
name: '_TimeLastRefresh',
value: time,
type: 'string',
unit: '',
},
{
name: '_DataAge',
value: dataAge,
type: 'number',
unit: 'min',
},
);
this.log.info('Succesfully pulled data.');
// @ts-ignore
await this.createAndUpdateStates(results);
//Debug
// this.log.info(results[10].name);
// this.log.info(results[10].value);
// this.log.info(results[10].unit);
// this.log.info(results[10].type);
// this.log.info('Ladestand Speicher: ' + stateOfCharge);
// this.log.info('Alter der Daten:' + dataAge);
} catch (error) {
this.log.error(`Error on pulling data: ${error}`);
} finally {
//Terminate Adapter until next Schedule
// @ts-ignore
this.stop();
}
}
}
// @ts-ignore
async createAndUpdateStates(results) {
try {
// @ts-ignore
this.log.debug('Updating states in ioBroker.');
// @ts-ignore
// eslint-disable-next-line prefer-const
for (let dataPoint of results) {
//Convert numbers and boolean values from text to correct data type
if (dataPoint.type === 'number') {
dataPoint.value = parseFloat(dataPoint.value);
}
if (dataPoint.value === 'AUF' || dataPoint.value == 'EIN') {
dataPoint.value = true;
}
if (dataPoint.value === 'ZU' || dataPoint.value == 'AUS') {
dataPoint.value = false;
}
dataPoint.id = dataPoint.name.replace(this.FORBIDDEN_CHARS, '_');
dataPoint.id = dataPoint.id.replace(/ /g, '_');
// @ts-ignore
await this.setObjectNotExistsAsync(dataPoint.id, {
type: 'state',
common: {
name: dataPoint.name,
type: dataPoint.type,
role: 'state',
read: true,
write: false,
unit: dataPoint.unit,
},
native: {},
});
// @ts-ignore
await this.setStateAsync(dataPoint.id, {
val: dataPoint.value,
ack: true,
});
}
} catch (error) {
// @ts-ignore
this.log.error(`Error on saving data: ${error}`);
}
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
// @ts-ignore
onUnload(callback) {
stopped = true;
try {
// Here you must clear all timeouts or intervals that may still be active
// clearTimeout(timeout1);
// clearInterval(interval1);
// @ts-ignore
this.log.debug('Cleaning up....');
// @ts-ignore
callback();
} catch (e) {
// @ts-ignore
callback();
}
}
// @ts-ignore
}
if (require.main !== module) {
// Export the constructor in compact mode
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
module.exports = (options) => new RmbBhkw(options);
} else {
// otherwise start the instance directly
new RmbBhkw();
}