-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.js
373 lines (295 loc) · 12.2 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
/* eslint-disable quotes */
'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 request = require('request-promise-native');
const stateAttr = require(__dirname + '/lib/stateAttr.js');
const settings = { Username: "", Password: "", intervall: 30000 }, warnMessages = {};
let isConnected = false;
let timer = null;
const disableSentry = false; // Ensure to set to true during development !
class Discovergy extends utils.Adapter {
/**
* @param {Partial<ioBroker.AdapterOptions>} [options={}]
*/
constructor(options) {
// @ts-ignore
super({
...options,
name: 'discovergy',
});
this.allMeters = {};
this.createdStatesDetails = {};
this.on('ready', this.onReady.bind(this));
this.on('unload', this.onUnload.bind(this));
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
// Load user settings
settings.Username = this.config.Username;
settings.Password = this.config.Password;
settings.intervall = (1000 * this.config.intervall);
this.setState('info.connection', false, true);
isConnected = false
this.log.info('Discovergy Adapter startet, trying to discover meters associated with your account');
//ToDo: Change to lib
// Check if credentials are not empty and decrypt stored password
if (settings.user !== '' && settings.Password !== '') {
// Make a call to Discovergy API and get a list of all meters
await this.doDiscovergyCall('meters', '');
// });
} else {
this.log.error('*** Adapter deactivated, credentials missing in Adapter Settings !!! ***');
this.setForeignState('system.' + this.namespace + '.alive', false);
}
}
// Get all meters connected to Discovergy account
async doDiscovergyCall(endpoint, urlencoded_parameters) {
const requestUrl = `https://api.inexogy.com/public/v1/${endpoint}?${urlencoded_parameters}`;
try {
await request({
url: requestUrl,
headers: {
"Authorization" : 'Basic ' + new Buffer(`${settings.Username}:${settings.Password}`).toString('base64')
}
}, async (error, response, body) => {
if (!error && response.statusCode === 200) {
// We got a response API is
await this.setState('info.connection', true, true);
isConnected = true;
// Retrieve all meter objects from Discovergy API
/** @type {Record<string, any>[]} */
const objArray = JSON.parse(body);
this.log.debug(JSON.stringify(objArray));
// Run truth array off all meter
for (const meters of Object.keys(objArray)) {
// Identify is meter is active and data should be retrieved
if (objArray[meters].firstMeasurementTime != -1) {
// Create device and info channel
this.log.debug(JSON.stringify(objArray[meters]));
await this.createDevice(objArray[meters]['serialNumber']);
await this.createChannel(objArray[meters]['serialNumber'], 'info');
// Create info channel for alle meter devices
for (const infoState in objArray[meters]) {
if (!stateAttr[infoState]) {
this.log.error('State type : ' + infoState + ' unknown, send this information to the developer ==> ' + infoState + ' : ' + JSON.stringify(objArray[meters][infoState]));
} else {
await this.doStateCreate(objArray[meters]['serialNumber'] + '.info.' + infoState, infoState, objArray[meters][infoState]);
}
}
// Exclude RLM meters, no values to receive
if (objArray[meters]['type'] !== 'RLM') {
this.allMeters[objArray[meters]['meterId']] = objArray[meters];
}
} else {
this.log.debug(`Inactive meter detected, ignoring ${objArray[meters]['serialNumber']} | ${objArray[meters]['meterId']}`)
}
}
this.log.info('All meters associated to your account discovered, initialise meters');
this.log.debug('All meters : ' + JSON.stringify(this.allMeters));
await this.dataPolling();
this.log.info(`All meters initialized, polling data every ${this.config.intervall} seconds`);
} else { // error or non-200 status code
this.log.error('Connection_Failed at meter indication run, check your credentials !');
this.setState('info.connection', false, true);
}
});
} catch (e) {
this.log.error(`[doDiscovergyCall] ${e}`);
}
}
// Data polling timer, get read values for every meter (Last reading)
async dataPolling() {
// Loop on all meter and get data
for (const serial in this.allMeters) {
await this.doDiscovergyMeter(`last_reading`, serial, this.allMeters[serial].meterId);
}
// New data polling at intervall time
if (timer) timer = null;
timer = setTimeout(() => {
this.dataPolling();
}, settings.intervall);
}
async doDiscovergyMeter(endpoint, urlencoded_parameters, meterId) {
try {
const stateName = this.allMeters[meterId].serialNumber;
const requestUrl = `https://api.inexogy.com/public/v1/${endpoint}?meterId=${meterId}`;
await request({
url: requestUrl,
headers: {
"Authorization" : 'Basic ' + new Buffer(`${settings.Username}:${settings.Password}`).toString('base64')
}
}, async (error, response, body) => {
if (!error && response.statusCode === 200) {
// we got a response
try {
this.log.debug(`[doDiscovergyMeter] Data : ${JSON.stringify(body)}`)
const data = JSON.parse(body);
for (const attributes in data) {
if (data.time){
await this.doStateCreate(stateName + '.timestamp', 'timestamp', data.time);
}
for (const values in data[attributes]) {
if (stateAttr[values] === undefined) {
this.log.error(`State type : ${values} unknown, send this information to the developer ==> ${values} : ${JSON.stringify(data[attributes][values])}`);
} else {
if (stateAttr[values].type !== undefined) {
switch (values) {
case 'power':
if (data[attributes][values] > 0) {
await this.doStateCreate(stateName + '.Power_Consumption', 'Power_Consumption', data[attributes][values]);
await this.doStateCreate(stateName + '.Power_Delivery', 'Power_Delivery', 0);
} else {
await this.doStateCreate(stateName + '.Power_Delivery', 'Power_Delivery', Math.abs(data[attributes][values]));
await this.doStateCreate(stateName + '.Power_Consumption', 'Power_Consumption', 0);
}
break;
case 'power1':
if (data[attributes][values] > 0) {
await this.doStateCreate(stateName + '.Power_T1_Consumption', 'Power_T1_Consumption', data[attributes][values]);
await this.doStateCreate(stateName + '.Power_T1_Delivery', 'Power_T1_Delivery', 0);
} else {
await this.doStateCreate(stateName + '.Power_T1_Delivery', 'Power_T1_Delivery', Math.abs(data[attributes][values]));
await this.doStateCreate(stateName + '.Power_T1_Consumption', 'Power_T1_Consumption', 0);
}
break;
case 'power2':
if (data[attributes][values] > 0) {
await this.doStateCreate(stateName + '.Power_T2_Consumption', 'Power_T2_Consumption', data[attributes][values]);
await this.doStateCreate(stateName + '.Power_T2_Delivery', 'Power_T2_Delivery', 0);
} else {
await this.doStateCreate(stateName + '.Power_T2_Delivery', 'Power_T2_Delivery', Math.abs(data[attributes][values]));
await this.doStateCreate(stateName + '.Power_T2_Consumption', 'Power_T2_Consumption', 0);
}
break;
case 'power3':
if (data[attributes][values] > 0) {
await this.doStateCreate(stateName + '.Power_T3_Consumption', 'Power_T3_Consumption', data[attributes][values]);
await this.doStateCreate(stateName + '.Power_T3_Delivery', 'Power_T3_Delivery', 0);
} else {
await this.doStateCreate(stateName + '.Power_T3_Delivery', 'Power_T3_Delivery', Math.abs(data[attributes][values]));
await this.doStateCreate(stateName + '.Power_T3_Consumption', 'Power_T3_Consumption', 0);
}
break;
default:
await this.doStateCreate(stateName + '.' + values, values, data[attributes][values]);
}
}
}
}
}
} catch (e) {
this.log.error('[doDiscovergyMeter Response] Error retrieving information for : ' + meterId);
this.setState('info.connection', false, true);
isConnected = false
}
this.setState('info.connection', true, true);
isConnected = true
} else { // error or non-200 status code
this.log.error('[doDiscovergyMeter] Error retrieving information for : ' + meterId);
this.setState('info.connection', false, true);
isConnected = false
}
});
} catch (error) {
this.log.error(`[doDiscovergyMeter] ${error}`);
this.setState('info.connection', false, true);
isConnected = false
}
}
async doStateCreate(stateName, name, value) {
// Strinfnify value if needed
if (typeof(value) === 'object') { value = JSON.stringify(value);}
// Try to get details from state lib, if not use defaults. throw warning if states is not known in attribute list
const common = {};
if (!stateAttr[name]) {
const warnMessage = `State attribute definition missing for ${name}`;
if (warnMessages[name] !== warnMessage) {
warnMessages[name] = warnMessage;
console.warn(warnMessage);
this.log.warn(warnMessage);
// Send information to Sentry
this.sendSentry(warnMessage);
}
}
common.name = stateAttr[name] !== undefined ? stateAttr[name].name || name : name;
common.type = typeof(value);
common.role = stateAttr[name] !== undefined ? stateAttr[name].role || 'state' : 'state';
common.read = true;
common.unit = stateAttr[name] !== undefined ? stateAttr[name].unit || '' : '';
common.write = stateAttr[name] !== undefined ? stateAttr[name].write || false : false;
if ((!this.createdStatesDetails[stateName])
|| (this.createdStatesDetails[stateName]
&& (
common.name !== this.createdStatesDetails[stateName].name
|| common.name !== this.createdStatesDetails[stateName].name
|| common.type !== this.createdStatesDetails[stateName].type
|| common.role !== this.createdStatesDetails[stateName].role
|| common.read !== this.createdStatesDetails[stateName].read
|| common.unit !== this.createdStatesDetails[stateName].unit
|| common.write !== this.createdStatesDetails[stateName].write
)
)) {
console.log(`An attribute has changed : ${stateName}`);
await this.extendObjectAsync(stateName, {
type: 'state',
common
});
} else {
// console.log(`Nothing changed do not update object`);
}
// Store current object definition to memory
this.createdStatesDetails[stateName] = common;
// Handle calculation factor and set state
if (!stateAttr[name] || !stateAttr[name].factor) {
this.setState(stateName, { val: value, ack: true });
} else {
const calcValue = value / stateAttr[name].factor;
this.setState(stateName, { val: calcValue, ack: true });
}
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
onUnload(callback) {
try {
this.setState('info.connection', false, true);
this.log.info('cleaned everything up...');
if (timer) timer = null;
callback();
} catch (e) {
callback();
}
}
sendSentry(msg) {
if (!disableSentry) {
if (this.supportsFeature && this.supportsFeature('PLUGINS')) {
const sentryInstance = this.getPluginInstance('sentry');
if (sentryInstance) {
this.log.info(`[Error caught and sent to Sentry, thank you for collaborating!] error: ${msg}`);
sentryInstance.getSentryObject().captureException(msg);
}
}
} else {
this.log.error(`Sentry disabled, error caught : ${msg}`);
}
}
}
// @ts-ignore parent is a valid property on module
if (module.parent) {
// Export the constructor in compact mode
/**
* @param {Partial<ioBroker.AdapterOptions>} [options={}]
*/
module.exports = (options) => new Discovergy(options);
} else {
// otherwise start the instance directly
new Discovergy();
}