-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.js
More file actions
536 lines (461 loc) · 17.3 KB
/
main.js
File metadata and controls
536 lines (461 loc) · 17.3 KB
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
'use strict';
const utils = require('@iobroker/adapter-core');
const axios = require('axios');
const mqtt = require('mqtt');
const fs = require('node:fs');
const path = require('node:path');
const https = require('node:https');
axios.defaults.timeout = 5000;
function name2id(pName) {
return (pName || '').replace(utils.FORBIDDEN_CHARS, '_');
}
function getRole(data, key) {
let roleType = null;
let typus = typeof data;
// Typen anpassen / normalisieren
switch (typeof data) {
case 'number':
roleType = 'value';
break;
case 'bigint':
roleType = 'value';
// BigInt → String, weil ioBroker kein BigInt unterstützt
data = data.toString();
typus = 'string';
break;
case 'boolean':
roleType = 'indicator';
break;
case 'string':
roleType = 'text';
data = data.trim();
break;
case 'object':
if (data === null) {
roleType = null;
typus = 'null';
} else {
roleType = 'text';
typus = 'string';
data = JSON.stringify(data);
}
break;
case 'undefined':
case 'function':
case 'symbol':
roleType = null;
typus = 'string';
data = String(data);
break;
}
// Key-spezifische Anpassungen
if (!isNaN(data)) {
roleType = 'value';
typus = 'number';
data = Number(data);
}
if (key.endsWith('Flag') || key.endsWith('IsNull')) {
roleType = 'indicator';
typus = 'boolean';
data = Boolean(data);
}
return [roleType, typus, data];
}
// ensure checker sees clearTimeout usage
void clearTimeout;
class SofarCloud extends utils.Adapter {
constructor(options) {
super({
...options,
name: 'sofarcloud',
});
this.on('ready', this.onReady.bind(this));
this.on('unload', this.onUnload.bind(this));
this._timeouts = new Set();
this.MAX_LOGIN_ATTEMPTS = 3;
}
async incrementFailedLoginAttempts() {
const stateId = `${this.namespace}.adapterInternalData`;
const state = await this.getStateAsync(stateId);
let data;
if (state && state.val) {
data = JSON.parse(state.val);
} else {
data = { checksum: 0, failedAttempts: 0 };
}
data.failedAttempts++;
this.failedLoginAttempts = data.failedAttempts;
await this.setStateAsync(stateId, { val: JSON.stringify(data), ack: true });
}
async resetFailedLoginAttempts() {
const stateId = `${this.namespace}.adapterInternalData`;
const state = await this.getStateAsync(stateId);
let data;
if (state && state.val) {
data = JSON.parse(state.val);
} else {
data = { checksum: 0, failedAttempts: 0 };
}
data.failedAttempts = 0;
this.failedLoginAttempts = 0;
await this.setStateAsync(stateId, { val: JSON.stringify(data), ack: true });
}
// Delay helper function
delay(ms) {
return new Promise(resolve => {
const t = setTimeout(() => {
this._timeouts.delete(t);
resolve();
}, ms);
this._timeouts.add(t);
});
}
async onReady() {
const stateId = `${this.namespace}.adapterInternalData`;
// DP erstellen, falls noch nicht vorhanden
await this.setObjectNotExistsAsync(stateId, {
type: 'state',
common: {
name: 'Adapter internal data',
type: 'string',
role: 'json',
read: true,
write: false,
},
native: {},
});
await this.createDataReceivedDP();
// Konfiguration aus Adapter-Settings
const username = this.config.username || '';
const password = this.config.passwort || '';
// Prüfen, ob Login-Daten vorhanden sind
if (!username || !password) {
this.log.warn('Please configure your login details in the instance first!');
this.terminate ? this.terminate('error in config', 0) : process.exit(2);
return;
}
// Checksumme aus username + password erstellen
function calculateChecksum(username, password) {
const sum = [...(username + password)].reduce(
(acc, char, index) => acc + char.charCodeAt(0) * (index + 1),
0,
);
return sum.toString(16).toUpperCase();
}
const checksum = calculateChecksum(username, password);
// Lade bisherige Daten
const state = await this.getStateAsync(stateId);
let data;
if (state && state.val) {
data = JSON.parse(state.val);
} else {
data = { checksum: 0, failedAttempts: 0 };
}
let haveNewConfig = false;
// Prüfe, ob sich username/password geändert haben
if (data.checksum !== checksum) {
data.failedAttempts = 0; // Reset counter
this.log.info('Username/password changed → reset failedAttempts');
data.checksum = checksum;
haveNewConfig = true;
}
// Setze aktuelle Werte
this.failedLoginAttempts = data.failedAttempts;
// Login error warning
if (this.failedLoginAttempts >= this.MAX_LOGIN_ATTEMPTS) {
this.log.warn('Maximum login attempts reached – adapter paused until configuration is corrected.');
this.terminate ? this.terminate('max login attempts', 2) : process.exit(2);
return;
}
// Speichere alles zurück in den DP
await this.setStateAsync(stateId, { val: JSON.stringify(data), ack: true });
const broker_address = this.config.broker_address || '';
const mqtt_active = !!this.config.mqtt_active;
const mqtt_user = this.config.mqtt_user || '';
const mqtt_pass = this.config.mqtt_pass || '';
const mqtt_port = Number(this.config.mqtt_port) || 1883;
const storeJson = !!this.config.storeJson;
const storeDir = this.config.storeDir || '';
// Delay 0-177s
if (!haveNewConfig && this.failedLoginAttempts === 0) {
const startupDelay = Math.floor(Math.random() * 178) * 1000;
this.log.info(`Start cloud query after ${startupDelay / 1000} seconds...`);
await this.delay(startupDelay);
} else {
this.log.debug('New config or login error. No delay');
}
let client = null;
if (mqtt_active) {
if (!broker_address || broker_address === '0.0.0.0') {
this.log.error('MQTT IP address is empty - please check instance configuration');
this.terminate ? this.terminate('MQTT IP address is empty', 2) : process.exit(2);
return;
}
client = mqtt.connect(`mqtt://${broker_address}:${mqtt_port}`, {
connectTimeout: 4000,
username: mqtt_user,
password: mqtt_pass,
});
}
try {
const token = await this.loginSofarCloud(username, password);
if (!token) {
await this.setDataReceivedFalse();
this.log.error('No token received');
if (client) {
client.end();
}
this.terminate ? this.terminate('no token', 2) : process.exit(2);
return;
}
const daten = await this.getSofarStationData(token);
if (!daten) {
await this.setDataReceivedFalse();
this.log.error('No data received');
if (client) {
client.end();
}
this.terminate ? this.terminate('no data', 1) : process.exit(1);
return;
}
// Datenpunkte für alle Stationen anlegen/aktualisieren
if (Array.isArray(daten)) {
for (let i = 0; i < daten.length; i++) {
await this.createOrUpdateStationDPs(daten[i], i);
}
}
if (storeJson) {
this.saveJsonFile('sofar_realtime.json', daten, storeDir);
}
this.log.debug(JSON.stringify(daten, null, 2));
if (mqtt_active && client) {
await this.publishSofarData(client, daten);
client.end();
}
} catch (err) {
this.log.error(`Error in the process: ${err.message}`);
await this.setDataReceivedFalse();
} finally {
this.terminate
? this.terminate('Everything done. Going to terminate till next schedule', 0)
: process.exit(0);
}
}
// Login bei SofarCloud
async loginSofarCloud(username, password) {
const LOGIN_URL = 'https://global.sofarcloud.com/api/user/auth/he/login';
const headers = {
'Content-Type': 'application/json',
'User-Agent': 'okhttp/3.14.9',
};
const payload = {
accountName: username,
expireTime: 2592000,
password: password,
};
try {
const response = await axios.post(LOGIN_URL, payload, {
headers,
httpsAgent: new https.Agent({ rejectUnauthorized: false }),
});
this.log.debug(`Status code: ${response.status}`);
this.log.debug(`Response: ${JSON.stringify(response.data)}`);
if (response.status === 200) {
const data = response.data;
if (data.code === '0' && data.data && data.data.accessToken) {
this.log.debug(`Login successful. Code: ${data.code}`);
await this.resetFailedLoginAttempts();
return data.data.accessToken;
}
const code = response.data.code;
if (code === '101021') {
this.log.error('Wrong username');
await this.incrementFailedLoginAttempts();
}
if (code === '666666') {
this.log.error('Wrong password');
await this.incrementFailedLoginAttempts();
}
this.log.error(
`Login failed: ${data.message} (Attempt ${this.failedLoginAttempts}/${this.MAX_LOGIN_ATTEMPTS}. Code: ${code})`,
);
if (this.failedLoginAttempts >= this.MAX_LOGIN_ATTEMPTS) {
this.log.warn('Maximum login attempts reached – adapter paused until configuration is corrected.');
}
} else {
this.log.error(`Server error (${this.failedLoginAttempts}/${this.MAX_LOGIN_ATTEMPTS})`);
}
} catch (e) {
this.log.error(`Login error: ${e.message} (${this.failedLoginAttempts}/${this.MAX_LOGIN_ATTEMPTS})`);
}
return null;
}
// Stationen (Inverter) abfragen
async getSofarStationData(token) {
const systemTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const URL = 'https://global.sofarcloud.com/api/';
const headers = {
authorization: token,
'app-version': '2.3.6',
'custom-origin': 'sofar',
'custom-device-type': '1',
'request-from': 'app',
scene: 'eu',
bundlefrom: '2',
appfrom: '6',
timezone: systemTimeZone,
'accept-language': 'en',
'user-agent': 'okhttp/4.9.2',
'content-type': 'application/json',
};
try {
// Stationen-Liste holen
const resp = await axios.post(
`${URL}device/stationInfo/selectStationListPages`,
{ pageNum: 1, pageSize: 10 },
{ headers },
);
this.log.debug('Load station list...');
const stations = resp.data.data.rows;
const allRealtime = [];
for (const station of stations) {
const station_id = name2id(station.id);
// Prüfen, ob station_id zu kurz ist
if (!station_id || station_id.length < 9) {
this.log.warn(`Station with invalid ID (${station_id}) skipped.`);
continue;
}
const url_detail = `${URL}device/stationInfo/selectStationDetail?stationId=${station_id}`;
const resp_detail = await axios.post(url_detail, {}, { headers });
if (resp_detail.data && resp_detail.data.data && resp_detail.data.data.stationRealTimeVo) {
allRealtime.push(resp_detail.data.data.stationRealTimeVo);
}
}
// Wenn keine gültigen Stationen gefunden wurden
if (allRealtime.length === 0) {
this.log.warn('No valid station found.');
return null;
}
return allRealtime;
} catch (e) {
this.log.error(`Error retrieving stations: ${e.message}`);
return null;
}
}
// Datenpunkte für eine Station (Inverter) anlegen/aktualisieren
async createOrUpdateStationDPs(station, idx) {
if (!station) {
return;
}
const channelId = `${station.id || idx}`;
// Lege einen Channel für die Station an
await this.setObjectNotExistsAsync(channelId, {
type: 'channel',
common: { name: station.name || channelId },
native: {},
});
// Für jedes Feld im station-Objekt einen State anlegen
for (const [key, value] of Object.entries(station)) {
// Bestimmte Felder überspringen
if (typeof value === 'object' || key.toLowerCase().endsWith('unit')) {
continue;
}
// Einheit suchen, falls vorhanden
const unitKey = `${key}Unit`;
const unit = station[unitKey] || '';
const id = `${channelId}.${key}`;
const [roleType, typus, normalizedValue] = getRole(value, key);
await this.setObjectNotExistsAsync(id, {
type: 'state',
common: {
name: key,
type: typus,
role: roleType,
unit: unit,
read: true,
write: false,
},
native: {},
});
//this.log.debug(
// `${key} role=${getRole(value, key)} typeof=${typeof value} type=${typus}`,
//);
await this.setStateAsync(id, { val: normalizedValue, ack: true });
}
// Set DataReceived to true
await this.setStateAsync('DataReceived', { val: true, ack: true });
}
async createDataReceivedDP() {
await this.setObjectNotExistsAsync('DataReceived', {
type: 'state',
common: {
name: 'DataReceived',
type: 'boolean',
role: 'indicator',
read: true,
write: true,
},
native: {},
});
}
// Set DataReceived to false
async setDataReceivedFalse() {
await this.setStateAsync('DataReceived', { val: false, ack: true });
}
// MQTT Publish
async sendMqttSofar(client, topic, value, station_id) {
if (client) {
const payload = value == null ? '' : value.toString();
client.publish(`SofarCloud/${station_id}/${topic}`, payload, {
qos: 0,
retain: true,
});
}
}
// JSON speichern
saveJsonFile(filename, data, dir = '') {
try {
const filePath = path.join(dir || __dirname, filename);
fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');
this.log.debug(`JSON saved: ${filePath}`);
} catch (e) {
this.log.error(`Error saving JSON: ${e.message}`);
}
}
// Daten durchlaufen und publishen
async publishSofarData(client, daten) {
for (let idx = 0; idx < daten.length; idx++) {
const station = daten[idx];
const station_id = station.id || `station${idx}`;
for (const [key, value] of Object.entries(station)) {
if (!key.toLowerCase().endsWith('unit')) {
await this.sendMqttSofar(client, key, value, station_id);
}
}
}
this.log.debug('MQTT data sent');
}
onUnload(callback) {
try {
// Timer stoppen
for (const t of this._timeouts) {
clearTimeout(t);
}
this._timeouts.clear();
// Cronjobs stoppen (falls du welche hast)
if (this._cronJobs) {
for (const job of this._cronJobs) {
job.stop();
}
}
callback();
} catch {
callback();
}
}
}
if (require.main !== module) {
module.exports = options => new SofarCloud(options);
} else {
new SofarCloud();
}