iobroker.wem-canapi 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,6 +8,7 @@
8
8
  </head>
9
9
  <body>
10
10
  <div id="root"></div>
11
+ <script src="../../lib/js/socket.io.js"></script>
11
12
  <script src="index.js"></script>
12
13
  </body>
13
14
  </html>
package/io-package.json CHANGED
@@ -1,134 +1,160 @@
1
1
  {
2
- "common": {
3
- "name": "wem-canapi",
4
- "messagebox": true,
5
- "version": "0.0.2",
6
- "news": {
7
- "0.0.1": {
8
- "en": "initial release",
9
- "de": "Erstveröffentlichung",
10
- "ru": "Начальная версия",
11
- "pt": "lançamento inicial",
12
- "nl": "Eerste uitgave",
13
- "fr": "Première version",
14
- "it": "Versione iniziale",
15
- "es": "Versión inicial",
16
- "pl": "Pierwsze wydanie",
17
- "uk": "Початкова версія",
18
- "zh-cn": "首次出版"
19
- },
20
- "0.0.2": {
21
- "en": "First working release CSV Datapoint has to be approved",
22
- "de": "Erstveröffentlichung",
23
- "ru": "Начальная версия",
24
- "pt": "lançamento inicial",
25
- "nl": "Eerste uitgave",
26
- "fr": "Première version",
27
- "it": "Versione iniziale",
28
- "es": "Versión inicial",
29
- "pl": "Pierwsze wydanie",
30
- "uk": "Початкова версія",
31
- "zh-cn": "首次出版"
32
- }
33
- },
34
- "titleLang": {
35
- "en": "WEM CanAPI",
36
- "de": "WEM CanAPI",
37
- "ru": "WEM-CanAPI",
38
- "pt": "WEM CanAPI",
39
- "nl": "WEM CanAPI",
40
- "fr": "WEM CanAPI",
41
- "it": "WEM CanAPI",
42
- "es": "MEM CanAPI",
43
- "pl": "WEM CanAPI",
44
- "uk": "WEM CanAPI",
45
- "zh-cn": "WEM CanAPI"
46
- },
47
- "desc": {
48
- "en": "Get Values directly from the Weishaupt devices via CanAPI",
49
- "de": "Erhalten Sie Werte direkt von den Weishaupt-Geräten über CanAPI",
50
- "ru": "Получайте значения напрямую с устройств Weishaupt через CanAPI.",
51
- "pt": "Obtenha valores diretamente dos dispositivos Weishaupt via CanAPI",
52
- "nl": "Ontvang waarden rechtstreeks van de Weishaupt-apparaten via CanAPI",
53
- "fr": "Obtenez des valeurs directement depuis les appareils Weishaupt via CanAPI",
54
- "it": "Ottieni valori direttamente dai dispositivi Weishaupt tramite CanAPI",
55
- "es": "Obtenga valores directamente desde los dispositivos Weishaupt a través de CanAPI",
56
- "pl": "Uzyskaj wartości bezpośrednio z urządzeń Weishaupt za pośrednictwem CanAPI",
57
- "uk": "Отримайте значення безпосередньо з пристроїв Weishaupt через CanAPI",
58
- "zh-cn": "通过 CanAPI 直接从 Weishaupt 设备获取值"
59
- },
60
- "authors": [
61
- "TanteJoe <giithub@schubel.info>"
62
- ],
63
- "keywords": [
64
- "WEM Weishaupt CanAPI"
65
- ],
66
- "licenseInformation": {
67
- "type": "free",
68
- "license": "MIT"
69
- },
70
- "platform": "Javascript/Node.js",
71
- "icon": "wem-canapi.png",
72
- "enabled": true,
73
- "extIcon": "https://raw.githubusercontent.com/TanteJoe/ioBroker.wem-canapi/main/admin/wem-canapi.png",
74
- "readme": "https://github.com/TanteJoe/ioBroker.wem-canapi/blob/main/README.md",
75
- "loglevel": "info",
76
- "tier": 3,
77
- "mode": "daemon",
78
- "type": "climate-control",
79
- "compact": true,
80
- "connectionType": "local",
81
- "dataSource": "poll",
82
- "adminUI": {
83
- "config": "materialize",
84
- "tab": "html"
85
- },
86
- "dependencies": [
87
- {
88
- "js-controller": ">=7.2.0"
89
- }
90
- ],
91
- "globalDependencies": [
92
- {
93
- "admin": ">=7.6.20"
94
- }
95
- ]
96
- },
97
- "protectedNative": [
98
- "username",
99
- "password"
100
- ],
101
- "native": {
102
- "host": "",
103
- "port": 80,
104
- "username": "",
105
- "password": "",
106
- "timeout": 5000,
107
- "selectedDatapoints": [],
108
- "importedDatapoints": []
109
- },
110
- "objects": [],
111
- "instanceObjects": [
112
- {
113
- "_id": "info",
114
- "type": "channel",
115
- "common": {
116
- "name": "Information"
117
- },
118
- "native": {}
119
- },
120
- {
121
- "_id": "info.connection",
122
- "type": "state",
123
- "common": {
124
- "name": "Verbindungsstatus",
125
- "type": "boolean",
126
- "role": "indicator.connected",
127
- "read": true,
128
- "write": false,
129
- "def": false
130
- },
131
- "native": {}
132
- }
133
- ]
2
+ "common": {
3
+ "name": "wem-canapi",
4
+ "messagebox": true,
5
+ "version": "0.0.4",
6
+ "news": {
7
+ "0.0.4": {
8
+ "en": "Verify. Datapoints\nDisable Datapoints on 5 Errors\nReset disabled Datapoint\nTransaltion integrated",
9
+ "de": "Prüfen. Datenpunkte\nDatenpunkte bei 5 Fehlern deaktivieren\nDatapoint zurücksetzen\nIntegrierte Übersetzung",
10
+ "ru": "Подтвердите. Точки данных\nОтключите точки данных при 5 ошибках\nСбросить отключенную точку данных\nИнтегрированный перевод",
11
+ "pt": "Verifica. Datapoints\nDesative datapoints em 5 erros\nRedefinir datapoint inativo\nTradução integrada",
12
+ "nl": "Verifiëren. Datapunten\nDatapunten uitschakelen voor 5 fouten\nUitgeschakeld Datapoint opnieuw instellen\nGeïntegreerde vertaling",
13
+ "fr": "Vérifiez. Points de données\nDésactivez les points en cas de 5 erreurs\nPoint de données désactivé\nTraduction intégrée",
14
+ "it": "Verifichi Datapoint\nDisattiva i datapoint su 5 errori\nReimposta Datapoint\nTraduzione integrata",
15
+ "es": "Comprobar. Puntos de datos\nDesactivar puntos de datos en 5 errores\nReiniciar Datapoint\nTraducción integrada",
16
+ "pl": "Zweryfikuj. Punkty danych\nWyłącz punkty danych przy 5 błędach\nZresetuj wyłączony punkt danych\nTransalcja zintegrowana",
17
+ "uk": "Перевірити. Точки даних\nВідключення точок даних по 5 помилках\nСкинути вимкнену точку даних\nТрансальція інтегрована",
18
+ "zh-cn": "验证。数据点\n出现 5 个错误时禁用 DataPoints\n重置已禁用的数据点\n整合翻译"
19
+ },
20
+ "0.0.1": {
21
+ "en": "initial release",
22
+ "de": "Erstveröffentlichung",
23
+ "ru": "первоначальный выпуск",
24
+ "pt": "lançamento inicial",
25
+ "nl": "eerste release",
26
+ "fr": "version initiale",
27
+ "it": "rilascio iniziale",
28
+ "es": "lanzamiento inicial",
29
+ "pl": "pierwsze wydanie",
30
+ "uk": "початковий випуск",
31
+ "zh-cn": "初始版本"
32
+ },
33
+ "0.0.2": {
34
+ "en": "First working release CSV Datapoint has to be approved",
35
+ "de": "Die erste Arbeitsversion von CSV Datapoints müssen getested werden",
36
+ "ru": "Первый рабочий выпуск CSV Datapoint должен быть одобрен.",
37
+ "pt": "A primeira versão de trabalho do CSV Datapoint precisa ser aprovada",
38
+ "nl": "Eerste werkrelease CSV Datapoint moet worden goedgekeurd",
39
+ "fr": "La première version de travail CSV Datapoint doit être approuvée",
40
+ "it": "La prima versione funzionante CSV Datapoint deve essere approvata",
41
+ "es": "La primera versión funcional de CSV Datapoint debe aprobarse",
42
+ "pl": "Pierwsza działająca wersja CSV Datapoint musi zostać zatwierdzona",
43
+ "uk": "Перший робочий випуск CSV Datapoint має бути затверджений",
44
+ "zh-cn": "第一个工作版本 CSV 数据点必须获得批准"
45
+ },
46
+ "0.0.3": {
47
+ "en": "First release with release-Script",
48
+ "de": "Erste Veröffentlichung mit Release-Script",
49
+ "ru": "Первый выпуск с релиз-скриптом",
50
+ "pt": "Primeiro lançamento com release-Script",
51
+ "nl": "Eerste release met release-Script",
52
+ "fr": "Première version avec release-Script",
53
+ "it": "Prima versione con release-Script",
54
+ "es": "Primer lanzamiento con lanzamiento-Script",
55
+ "pl": "Pierwsze wydanie ze skryptem wydania",
56
+ "uk": "Перший випуск зі сценарієм випуску",
57
+ "zh-cn": "第一个版本带有release-Script"
58
+ }
59
+ },
60
+ "titleLang": {
61
+ "en": "WEM CanAPI",
62
+ "de": "WEM CanAPI",
63
+ "ru": "WEM-CanAPI",
64
+ "pt": "WEM CanAPI",
65
+ "nl": "WEM CanAPI",
66
+ "fr": "WEM CanAPI",
67
+ "it": "WEM CanAPI",
68
+ "es": "MEM CanAPI",
69
+ "pl": "WEM CanAPI",
70
+ "uk": "WEM CanAPI",
71
+ "zh-cn": "WEM CanAPI"
72
+ },
73
+ "desc": {
74
+ "en": "Get Values directly from the Weishaupt devices via CanAPI",
75
+ "de": "Erhalten Sie Werte direkt von den Weishaupt-Geräten über CanAPI",
76
+ "ru": "Получайте значения напрямую с устройств Weishaupt через CanAPI.",
77
+ "pt": "Obtenha valores diretamente dos dispositivos Weishaupt via CanAPI",
78
+ "nl": "Ontvang waarden rechtstreeks van de Weishaupt-apparaten via CanAPI",
79
+ "fr": "Obtenez des valeurs directement depuis les appareils Weishaupt via CanAPI",
80
+ "it": "Ottieni valori direttamente dai dispositivi Weishaupt tramite CanAPI",
81
+ "es": "Obtenga valores directamente desde los dispositivos Weishaupt a través de CanAPI",
82
+ "pl": "Uzyskaj wartości bezpośrednio z urządzeń Weishaupt za pośrednictwem CanAPI",
83
+ "uk": "Отримайте значення безпосередньо з пристроїв Weishaupt через CanAPI",
84
+ "zh-cn": "通过 CanAPI 直接从 Weishaupt 设备获取值"
85
+ },
86
+ "authors": [
87
+ "TanteJoe <github@schubel.info>"
88
+ ],
89
+ "keywords": [
90
+ "WEM Weishaupt CanAPI"
91
+ ],
92
+ "licenseInformation": {
93
+ "type": "free",
94
+ "license": "MIT"
95
+ },
96
+ "platform": "Javascript/Node.js",
97
+ "icon": "wem-canapi.png",
98
+ "enabled": true,
99
+ "extIcon": "https://raw.githubusercontent.com/TanteJoe/ioBroker.wem-canapi/main/admin/wem-canapi.png",
100
+ "readme": "https://github.com/TanteJoe/ioBroker.wem-canapi/blob/main/README.md",
101
+ "loglevel": "info",
102
+ "tier": 3,
103
+ "mode": "daemon",
104
+ "type": "climate-control",
105
+ "compact": false,
106
+ "connectionType": "local",
107
+ "dataSource": "poll",
108
+ "adminUI": {
109
+ "config": "materialize",
110
+ "tab": "html"
111
+ },
112
+ "dependencies": [
113
+ {
114
+ "js-controller": ">=7.2.0"
115
+ }
116
+ ],
117
+ "globalDependencies": [
118
+ {
119
+ "admin": ">=7.6.20"
120
+ }
121
+ ]
122
+ },
123
+ "protectedNative": [
124
+ "username",
125
+ "password"
126
+ ],
127
+ "native": {
128
+ "host": "",
129
+ "port": 80,
130
+ "username": "",
131
+ "password": "",
132
+ "timeout": 5000,
133
+ "selectedDatapoints": [],
134
+ "importedDatapoints": []
135
+ },
136
+ "objects": [],
137
+ "instanceObjects": [
138
+ {
139
+ "_id": "info",
140
+ "type": "channel",
141
+ "common": {
142
+ "name": "Information"
143
+ },
144
+ "native": {}
145
+ },
146
+ {
147
+ "_id": "info.connection",
148
+ "type": "state",
149
+ "common": {
150
+ "name": "Verbindungsstatus",
151
+ "type": "boolean",
152
+ "role": "indicator.connected",
153
+ "read": true,
154
+ "write": false,
155
+ "def": false
156
+ },
157
+ "native": {}
158
+ }
159
+ ]
134
160
  }
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- import { adapter } from '@iobroker/adapter-core';
3
+ //import { adapter } from '@iobroker/adapter-core';
4
4
  //import { adapter, Credentials } from '@iobroker/adapter-core';
5
5
  //import { secureHeapUsed } from 'node:crypto';
6
6
 
@@ -24,14 +24,16 @@ class CanApiClient {
24
24
  * @param {string} [config.password] HTTP-Auth Passwort
25
25
  * @param {number} [config.timeout] Request-Timeout in ms (Standard 5000)
26
26
  * @param {object} config.log ioBroker Logger
27
+ * @param {object} config.adapter ioBrokeradapter
27
28
  */
28
29
  constructor(config) {
29
30
  this.host = config.host;
30
31
  this.port = config.port || 80;
31
- this.username = config.username || 'admin';
32
- this.password = config.password || 'Admin123';
32
+ this.username = config.username || '';
33
+ this.password = config.password || '';
33
34
  this.timeout = config.timeout || 5000;
34
35
  this.log = config.log || console;
36
+ this.adapter = config.adapter;
35
37
 
36
38
  this.baseUrl = `http://${this.host}:${this.port}/ajax/CanApiJson.json`;
37
39
  this.testURL = `http://${this.host}:${this.port}/`;
@@ -101,7 +103,12 @@ class CanApiClient {
101
103
  true,
102
104
  );
103
105
 
104
- await this._httpPost(payload);
106
+ const responseText = await this._httpPost(payload);
107
+ const resp = await this._parseResponse(responseText, Array.of(datapoint));
108
+ if (!resp || resp.length === 0 || resp[0].value === null) {
109
+ this.log.error(`[CanAPI] Schreibfehler ${datapoint.pointName}: Keine gültige Antwort`);
110
+ return false;
111
+ }
105
112
  return true;
106
113
  } catch (e) {
107
114
  this.log.error(`[CanAPI] Schreibfehler ${datapoint.pointName}: ${e.message}`);
@@ -153,22 +160,21 @@ class CanApiClient {
153
160
  });
154
161
 
155
162
  req.on('error', err => {
156
- console.error('Connection error:', err);
163
+ this.log.debug(`Connection error: ${err.message}`);
157
164
  resolve(false); // Bei Verbindungsfehler false zurückgeben
158
165
  });
159
166
 
160
167
  req.on('timeout', () => {
161
168
  req.destroy();
162
- console.error(`Timeout nach ${this.timeout}ms`);
169
+ this.log.debug(`Timeout nach ${this.timeout}ms`);
163
170
  resolve(false); // Bei Timeout false zurückgeben
164
- reject(true);
165
171
  });
166
172
 
167
173
  req.setTimeout(this.timeout);
168
174
  req.end();
169
175
  });
170
176
  } catch (error) {
171
- console.error('Unexpected error:', error);
177
+ this.log.debug(`Unexpected error: ${error.message}`);
172
178
  return false;
173
179
  }
174
180
  }
@@ -263,7 +269,7 @@ class CanApiClient {
263
269
  const factor = this._getResolutionFactor(dp);
264
270
  const rawValue = Math.round(value * factor);
265
271
  const dpadress = dp.readHex.slice(0, -2);
266
- const bitescount = dp.respbites.match(/\d+/g);
272
+ const bitescount = parseInt(dp.respbites, 10);
267
273
  const bits = {
268
274
  1: 0xff,
269
275
  2: 0xffff,
@@ -328,7 +334,7 @@ class CanApiClient {
328
334
  const rawHex = entry.VG;
329
335
  const value = this._convertRawValue(rawHex, dp);
330
336
 
331
- this.log.debug(`[CanAPI] ${dp.pointName}: VW=${rawHex} → ${value} ${dp.unit || ''}`);
337
+ this.log.silly(`[CanAPI] ${dp.pointName}: VW=${rawHex} → ${value} ${dp.unit || ''}`);
332
338
 
333
339
  results.push({ id: dp.id, value, raw: rawHex });
334
340
  });
@@ -353,14 +359,44 @@ class CanApiClient {
353
359
  if (count <= 1 && raw > 32767) raw -= 65536;
354
360
  if (count === 2 && raw > 2147483647) raw -= 4294967296; */
355
361
 
356
- this.log.debug(`Spit result Hex${result[6]}`);
362
+ this.log.silly(`Split result Hex ${result[6]}`);
357
363
  if (result[0] === '05') {
358
364
  this.log.warn(
359
365
  `Fehlercode ${dp.deviceName} ${dp.pointName}: ${result[1]}${result[2]}${result[3]}${result[4]}${result[5]}`,
360
366
  );
367
+ this.adapter._getObj(`${dp.treePath}`).then(obj => {
368
+ if (obj?.common?.color !== undefined) {
369
+ if ((obj.errorcount || 0) <= 4) {
370
+ obj.common.color = '#FFFF44';
371
+ obj.errorcount = (obj.errorcount || 0) + 1;
372
+ this.adapter.setObjectAsync(`${dp.treePath}`, obj);
373
+ } else {
374
+ obj.common.color = '#b917a1';
375
+ obj.errorcount = (obj.errorcount || 0) + 1;
376
+ this.adapter.setObjectAsync(`${dp.treePath}`, obj);
377
+ }
378
+ } else {
379
+ this.adapter.extendObjectAsync(`${dp.treePath}`, {
380
+ common: {
381
+ color: '#ffff44',
382
+ },
383
+ errorcount: 1,
384
+ });
385
+ }
386
+ });
387
+ return null;
361
388
  }
362
-
363
- return result[0] === '05' ? 0 : parseInt(result[6], 16);
389
+ if (!result[6]) {
390
+ this.log.warn(`[CanAPI] Antwort ohne Wert für ${dp.pointName}: ${response}`);
391
+ return null;
392
+ }
393
+ // Temperaturen sind vorzeichenbehaftet (Zweierkomplement über die Breite des Werts)
394
+ const raw = parseInt(result[6], 16);
395
+ const bits = result[6].length * 4;
396
+ if ((dp.dataType || '') === 'Temperatur' && raw >= 2 ** (bits - 1)) {
397
+ return raw - 2 ** bits;
398
+ }
399
+ return raw;
364
400
  }
365
401
 
366
402
  /**
@@ -372,22 +408,39 @@ class CanApiClient {
372
408
  }
373
409
 
374
410
  // Hex → Integer
375
- let raw = this._splitResponse(rawHex, dp);
411
+ const raw = this._splitResponse(rawHex, dp);
412
+ if (raw === null || Number.isNaN(raw)) {
413
+ return null;
414
+ }
376
415
 
377
416
  // Sonderfall Boolean
378
- if ((dp.ioType || '').toLowerCase() === 'boolean') {
417
+ if (CanApiClient.ioType(dp) === 'boolean') {
379
418
  return raw !== 0;
380
419
  }
381
420
 
382
421
  // Auflösung anwenden
383
422
  const factor = this._getResolutionFactor(dp);
384
423
  if (factor !== 1) {
385
- return Math.round((raw / factor) * 10) / 10;
424
+ const decimals = Math.log10(factor);
425
+ return Number((raw / factor).toFixed(decimals));
386
426
  }
387
427
 
388
428
  return raw;
389
429
  }
390
430
 
431
+ /**
432
+ * ioBroker-Datentyp eines Datenpunkts (CSV-Spalte ioType ist leer, daher aus dataType abgeleitet)
433
+ *
434
+ * @param {object} dp
435
+ * @returns {'boolean'|'number'|'string'}
436
+ */
437
+ static ioType(dp) {
438
+ if (dp.ioType) {
439
+ return dp.ioType;
440
+ }
441
+ return (dp.dataType || '').toLowerCase() === 'boolesch' ? 'boolean' : 'number';
442
+ }
443
+
391
444
  /**
392
445
  * Ermittelt den Auflösungsfaktor
393
446
  * "0.1 °C" → 10, "0.01 bar" → 100, sonst 1
package/lib/csvParser.js CHANGED
@@ -1,36 +0,0 @@
1
- 'use strict';
2
-
3
- class CanApiCSVParser {
4
- parse(csvContent) {
5
- if (!csvContent) {
6
- return [];
7
- }
8
-
9
- return {
10
- id: '',
11
- MI: '', //3 field in csv
12
- MX: '',
13
- OX: '',
14
- OS: '',
15
- VS: '',
16
- updateInterval: '', //10 field in csv
17
- deviceGroupName: '',
18
- deviceName: '',
19
- pointName: '', //15 in csv
20
- pointfunction: '',
21
- dataType: '',
22
- resolution: '',
23
- unit: '',
24
- sCov: '',
25
- enumValues: '',
26
- canWrite: '',
27
- ioType: '',
28
- treePath: '',
29
- label: '',
30
- readHex: '',
31
- respbites: '',
32
- };
33
- }
34
- }
35
-
36
- module.exports = CanApiCSVParser;