-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.js
1625 lines (1588 loc) · 53.4 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
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @ts-check
'use strict';
/**
* @typedef {Object} StateChangeObject
* @property {boolean} ack
* @property {string} val
*/
/**
* Data for the current device which are not provided by Web-API (IP-Address, MQTT-Password)
* @typedef {Object} Device
* @property {string} Serial Serial number of the device
* @property {string} ProductType Product type of the device
* @property {string} Version
* @property {string} AutoUpdate
* @property {string} NewVersionAvailable
* @property {string} ConnectionType
* @property {string} Name
* @property {string} hostAddress
* @property {string} mqttPassword
* @property {mqtt.MqttClient} mqttClient
* @property {NodeJS.Timeout} updateIntervalHandle
* @property {string} [ipAddress]
*/
// 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 adapterName = require('./package.json').name.split('.').pop() || '';
// Load additional modules
const mqtt = require('mqtt');
// Load utils for this adapter
const dysonUtils = require('./dyson-utils.js');
const {
getDatapoint,
PRODUCTS,
SPECIAL_PROPERTIES,
getNameToDysoncodeTranslation
} = require('./dysonConstants.js');
const { setInterval } = require('node:timers');
// Variable definitions
// let adapter = null;
let adapterIsSetUp = false;
/**
* @type {Device[]}
*/
let devices = [];
let VOC = 0; // Numeric representation of current VOCIndex
let PM25 = 0; // Numeric representation of current PM25Index
let PM10 = 0; // Numeric representation of current PM10Index
let Dust = 0; // Numeric representation of current DustIndex
/**
*
* @param {number} number
* @param {number} min
* @param {number} max
* @returns
*/
function clamp(number, min, max) {
return Math.max(min, Math.min(number, max));
}
/**
* Main class of dyson AirPurifier adapter for ioBroker
*/
class dysonAirPurifier extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions> & {temperatureUnit: 'K' | 'C' | 'F'}} options
*/
constructor(options = { temperatureUnit: 'C' }) {
super({ ...options, name: adapterName });
// this.on('objectChange', this.onObjectChange.bind(this));
this.on('message', this.onMessage.bind(this));
this.on('ready', this.onReady.bind(this));
this.on('stateChange', this.onStateChange.bind(this));
this.on('unload', this.onUnload.bind(this));
}
/**
* onMessage
*
* Some message was sent to this instance over message box. Used by email, pushover, text2speech, ...
* Using this method requires "common.messagebox" property to be set to true in io-package.json
* This function exchanges information between the admin frontend and the backend.
* In detail: it performs the 2 FA login at the dyson API. Therefore it receives messages from admin,
* sends them to dyson and reaches the received data back to admin.
*
* @param {Object} msg - Message object containing all necessary data to request the needed information
*/
async onMessage(msg) {
if (!msg?.callback || !msg?.from?.startsWith('system.adapter.admin')) {
return;
}
switch (msg.command) {
case 'getDyson2faMail':
this.log.debug('OnMessage: Received getDyson2faMail request.');
msg.message.locale = dysonUtils.getDyson2faLocale(msg.message.country);
try {
const response = await dysonUtils.getDyson2faMail(
this,
msg.message.email,
msg.message.password,
msg.message.country,
msg.message.locale
);
this.sendTo(msg.from, msg.command, response, msg.callback);
} catch (error) {
this.log.warn(`Couldn't handle getDyson2faMail message: ${error}`);
this.sendTo(
msg.from,
msg.command,
{ error: error || 'No data' },
msg.callback
);
}
break;
case 'getDysonToken':
this.log.debug('OnMessage: getting Dyson-Token');
try {
const response = await dysonUtils.getDysonToken(
this,
msg.message.email,
msg.message.password,
msg.message.country,
msg.message.challengeId,
msg.message.PIN
);
this.sendTo(msg.from, msg.command, response, msg.callback);
} catch (error) {
this.log.warn(`Couldn't handle getDysonToken message: ${error}`);
this.sendTo(
msg.from,
msg.command,
{ error: error || 'No data' },
msg.callback
);
}
break;
default:
this.log.warn(`Unknown message: ${msg.command}`);
break;
}
}
/**
* @param {string} dysonAction
* @param {string | number} messageValue
* @param {string} id
* @param {any} state
* @returns {Promise<Record<string, any>>}
*/
async #getMessageData(dysonAction, messageValue, id, state) {
switch (dysonAction) {
case 'fnsp': {
// protect upper and lower speed limit of fan
const value = parseInt(
typeof messageValue === 'string'
? messageValue
: messageValue.toString(),
10
);
const clamped = clamp(value, 1, 10);
return { [dysonAction]: clamped.toString().padStart(4, '0') };
}
case 'hmax': {
// Target temperature for heating in KELVIN!
// convert temperature to configured unit
let value = parseInt(
typeof messageValue === 'string'
? messageValue
: messageValue.toString(),
10
);
// @ts-ignore
switch (this.config.temperatureUnit) {
case 'K':
value *= 10;
break;
case 'C':
value = Number((value + 273.15) * 10);
break;
case 'F':
value = Number((value - 32) * (9 / 5) + 273.15);
break;
}
return { [dysonAction]: value.toFixed(0).padStart(4, '0') };
}
case 'ancp':
case 'osal':
case 'osau':
try {
const result = await dysonUtils.getAngles(
this,
dysonAction,
id,
state
);
this.log.debug(`Result of getAngles: ${JSON.stringify(result)}`);
result.osal = parseInt(result.osal.val);
result.osau = parseInt(result.osau.val);
switch (result.ancp.val) {
case 'CUST':
result.ancp = result.osau - result.osal;
break;
case 'BRZE':
result.ancp = 'BRZE';
break;
default:
result.ancp = parseInt(result.ancp.val);
}
if (result.ancp === 'BRZE') {
return {
['ancp']: 'BRZE',
['oson']: 'ON'
};
}
this.log.debug(
`Result of parseInt(result.ancp.val): ${result.ancp}, typeof: ${typeof result.ancp}`
);
if (result.osal + result.ancp > 355) {
result.osau = 355;
result.osal = 355 - result.ancp;
} else if (result.osau - result.ancp < 5) {
result.osal = 5;
result.osau = 5 + result.ancp;
} else {
result.osau = result.osal + result.ancp;
}
return {
['osal']: dysonUtils.zeroFill(result.osal, 4),
['osau']: dysonUtils.zeroFill(result.osau, 4),
// ['ancp']: 'CUST',
['ancp']: await this.getOscillationAngle(result.ancp),
['oson']: 'ON'
};
} catch (error) {
this.log.error(
'An error occurred while trying to retrieve the oscillation angles.'
);
throw error;
}
default:
return {
[dysonAction]:
typeof messageValue === 'number'
? messageValue.toString().padStart(4, '0')
: messageValue
};
}
}
async getOscillationAngle(angle){
if (angle === 0) {
return '0000';
} else if (angle <= 45) {
return '0045';
} else if (angle > 45 && angle <= 90) {
return '0090';
} else if (angle > 180 && angle <= 270) {
return '0180';
} else if (angle > 270 && angle <= 355) {
return '0350';
}
}
/**
* onStateChange
*
* Sends the control mqtt message to your device in case you changed a value
*
* @param {string} id - id of the datapoint that was changed
* @param {StateChangeObject | undefined} state - new state-object of the datapoint after change
*/
async onStateChange(id, state) {
const thisDevice = id.split('.')[2];
const action = id.split('.').pop();
// Warning, state can be null if it was deleted
if (!state || !action) {
return;
}
// state changes by hardware or adapter depending on hardware values
// check if it is an Index calculation
if (state.ack) {
if (!action.includes('Index')) {
return;
}
// if some index has changed recalculate overall AirQuality
this.createOrExtendObject(
`${thisDevice}.AirQuality`,
{
type: 'state',
common: {
name: 'Overall AirQuality (worst value of all indexes except NO2)',
read: true,
write: false,
role: 'value',
type: 'number',
states: {
0: 'Good',
1: 'Medium',
2: 'Bad',
3: 'very Bad',
4: 'extremely Bad',
5: 'worrying'
}
},
native: {}
},
Math.max(VOC, Dust, PM25, PM10)
);
return;
}
// if dysonAction is undefined it's an adapter internal action and has to be handled with the given Name
// pick the dyson internal Action from the result row
const dysonAction = getNameToDysoncodeTranslation(action);
if (!dysonAction) {
this.log.warn(`Unknown Dyson Action ${action}`);
return;
}
// you can use the ack flag to detect if it is status (true) or command (false)
// get the whole data field array
const ActionData = getDatapoint(dysonAction);
const value = state.val;
let messageData = await this.#getMessageData(dysonAction, value, id, state);
// TODO: refactor
// switches defined as boolean must get the proper value to be send
// this is to translate between the needed states for ioBroker and the device
// boolean switches are better for visualizations and other adapters like text2command
if (typeof ActionData !== 'undefined') {
if (
ActionData.type === 'boolean' &&
ActionData.role.startsWith('switch')
) {
// current state is TRUE!
if (state.val) {
// handle special action "humidification" where ON is not ON but HUME
if (dysonAction === 'hume') {
messageData = { [dysonAction]: 'HUMD' };
// handle special action "HeatingMode" where ON is not ON but HEAT
} else if (dysonAction === 'hmod') {
messageData = { [dysonAction]: 'HEAT' };
} else {
messageData = { [dysonAction]: 'ON' };
}
} else {
messageData = { [dysonAction]: 'OFF' };
}
}
}
// check whether fanspeed has been set to Auto
if ('fnsp' === dysonAction && 11 === value){
messageData = {'auto':'ON'};
}
// only send to device if change should set a device value
if (action === 'Hostaddress') {
return;
}
// build the message to be sent to the device
const message = {
msg: 'STATE-SET',
time: new Date().toISOString(),
'mode-reason': 'LAPP',
'state-reason': 'MODE',
data: messageData
};
for (const mqttDevice of devices) {
if (mqttDevice.Serial === thisDevice) {
this.log.debug(
`MANUAL CHANGE: device [${thisDevice}] -> [${action}] -> [${state.val}], id: [${id}]`
);
this.log.debug(
`SENDING this data to device (${thisDevice}): ${JSON.stringify(message)}`
);
await this.setState(id, state.val, true);
mqttDevice.mqttClient.publish(
`${mqttDevice.ProductType}/${thisDevice}/command`,
JSON.stringify(message)
);
// refresh data with a delay of 250 ms to avoid 30 Sec gap
setTimeout(() => {
this.log.debug(`requesting new state of device (${thisDevice}).`);
mqttDevice.mqttClient.publish(
`${mqttDevice.ProductType}/${thisDevice}/command`,
JSON.stringify({
msg: 'REQUEST-CURRENT-STATE',
time: new Date().toISOString()
})
);
}, 100);
}
}
}
/**
* CreateOrUpdateDevice
*
* Creates the base device information
*
* @param {Device} device - Data for the current device which are not provided by Web-API (IP-Address, MQTT-Password)
*/
async CreateOrUpdateDevice(device) {
try {
// create device folder
//this.log.debug('Creating device folder.');
this.createOrExtendObject(
device.Serial,
{
type: 'device',
common: {
name: PRODUCTS[device.ProductType].name,
icon: PRODUCTS[device.ProductType].icon,
type: 'string'
},
native: {}
},
null
);
this.createOrExtendObject(
`${device.Serial}.Firmware`,
{
type: 'channel',
common: {
name: 'Information on devices firmware',
read: true,
write: false,
type: 'string',
role: 'value'
},
native: {}
},
null
);
this.createOrExtendObject(
`${device.Serial}.SystemState`,
{
type: 'folder',
common: {
name: 'Information on devices system state (Filter, Water tank, ...)',
read: true,
write: false,
type: 'string',
role: 'value'
},
native: {}
},
null
);
this.createOrExtendObject(
`${device.Serial}.SystemState.product-errors`,
{
type: 'channel',
common: {
name: 'Information on devices product errors - false=No error, true=Failure',
read: true,
write: false,
type: 'string',
role: 'value'
},
native: {}
},
null
);
this.createOrExtendObject(
`${device.Serial}.SystemState.product-warnings`,
{
type: 'channel',
common: {
name: 'Information on devices product-warnings - false=No error, true=Failure',
read: true,
write: false,
type: 'string',
role: 'value'
},
native: {}
},
null
);
this.createOrExtendObject(
`${device.Serial}.SystemState.module-errors`,
{
type: 'channel',
common: {
name: 'Information on devices module-errors - false=No error, true=Failure',
read: true,
write: false,
type: 'string',
role: 'value'
},
native: {}
},
null
);
this.createOrExtendObject(
`${device.Serial}.SystemState.module-warnings`,
{
type: 'channel',
common: {
name: 'Information on devices module-warnings - false=No error, true=Failure',
read: true,
write: false,
type: 'string',
role: 'value'
},
native: {}
},
null
);
this.createOrExtendObject(
`${device.Serial}.Firmware.Version`,
{
type: 'state',
common: {
name: 'Current firmware version',
read: true,
write: false,
role: 'value',
type: 'string'
},
native: {}
},
device.Version
);
this.createOrExtendObject(
`${device.Serial}.Firmware.Autoupdate`,
{
type: 'state',
common: {
name: "Shows whether the device updates it's firmware automatically if update is available.",
read: true,
write: true,
role: 'indicator',
type: 'boolean'
},
native: {}
},
device.AutoUpdate
);
this.createOrExtendObject(
`${device.Serial}.Firmware.NewVersionAvailable`,
{
type: 'state',
common: {
name: 'Shows whether a firmware update for this device is available online.',
read: true,
write: false,
role: 'indicator',
type: 'boolean'
},
native: {}
},
device.NewVersionAvailable
);
this.createOrExtendObject(
`${device.Serial}.ProductType`,
{
type: 'state',
common: {
name: 'dyson internal productType.',
read: true,
write: false,
role: 'value',
type: 'string'
},
native: {}
},
device.ProductType
);
this.createOrExtendObject(
`${device.Serial}.ConnectionType`,
{
type: 'state',
common: {
name: 'Type of connection.',
read: true,
write: false,
role: 'value',
type: 'string'
},
native: {}
},
device.ConnectionType
);
this.createOrExtendObject(
`${device.Serial}.Name`,
{
type: 'state',
common: {
name: 'Name of device.',
read: true,
write: true,
role: 'value',
type: 'string'
},
native: {}
},
device.Name
);
this.log.debug(`Querying Host-Address of device: ${device.Serial}`);
const hostAddress = await this.getStateAsync(
`${device.Serial}.Hostaddress`
);
this.log.debug(
`Got Host-Address-object [${JSON.stringify(hostAddress)}] for device: ${device.Serial}`
);
if (hostAddress?.val && typeof hostAddress.val === 'string') {
this.log.debug(
`Found predefined Host-Address [${hostAddress.val}] for device: ${device.Serial} in object tree.`
);
device.hostAddress = hostAddress.val;
this.createOrExtendObject(
`${device.Serial}.Hostaddress`,
{
type: 'state',
common: {
name: 'Local host address (or IP) of device.',
read: true,
write: true,
role: 'value',
type: 'string'
},
native: {}
},
hostAddress.val
);
} else {
// No valid IP address of device found. Without we can't proceed. So terminate adapter.
this.createOrExtendObject(
`${device.Serial}.Hostaddress`,
{
type: 'state',
common: {
name: 'Local host address (IP) of device.',
read: true,
write: true,
role: 'value',
type: 'string'
},
native: {}
},
''
);
}
} catch (error) {
this.log.error(
`[CreateOrUpdateDevice] Error: ${error}, Callstack: ${error.stack}`
);
}
}
/**
* processMsg
*
* Processes the current received message and updates relevant data fields
*
* @param {Object} device additional data for the current device which are not provided by Web-API (IP-Address, MQTT-Password)
* @param {string} path Additional subfolders can be given here if needed with a leading dot (eg. .Sensor)!
* @param {Object} message Current State of the device. Message is send by device via mqtt due to request or state change.
*/
async processMsg(device, path, message) {
for (const dysonCode in message) {
// Is this a "product-state" message?
if (dysonCode === 'product-state') {
await this.processMsg(device, '', message[dysonCode]);
return;
}
if (
[
'product-errors',
'product-warnings',
'module-errors',
'module-warnings'
].includes(dysonCode)
//row === 'product-errors' ||
//row === 'product-warnings' ||
//row === 'module-errors' ||
//row === 'module-warnings'
) {
await this.processMsg(
device,
`${path}.${dysonCode}`,
message[dysonCode]
);
}
// Is this a "data" message?
if (dysonCode === 'data') {
await this.processMsg(device, '.Sensor', message[dysonCode]);
if (Object.prototype.hasOwnProperty.call(message[dysonCode], 'p25r')) {
this.createPM25(message, dysonCode, device);
}
if (Object.prototype.hasOwnProperty.call(message[dysonCode], 'p10r')) {
this.createPM10(message, dysonCode, device);
}
if (Object.prototype.hasOwnProperty.call(message[dysonCode], 'pact')) {
this.createDust(message, dysonCode, device);
}
if (Object.prototype.hasOwnProperty.call(message[dysonCode], 'vact')) {
this.createVOC(message, dysonCode, device);
}
if (Object.prototype.hasOwnProperty.call(message[dysonCode], 'va10')) {
this.createVOC(message, dysonCode, device);
}
if (Object.prototype.hasOwnProperty.call(message[dysonCode], 'noxl')) {
this.createNO2(message, dysonCode, device);
}
if (Object.prototype.hasOwnProperty.call(message[dysonCode], 'hchr')) {
this.createHCHO(message, dysonCode, device);
}
return;
}
// Handle all other message types
//this.log.debug(`Processing item [${JSON.stringify(row)}] of Message: ${((typeof message === 'object')? JSON.stringify(message) : message)}` );
const deviceConfig = getDatapoint(dysonCode);
if (deviceConfig === undefined) {
this.log.silly(
`Skipped creating unknown data field for Device:[${device.Serial}], Field: [${dysonCode}] Value:[${typeof message[dysonCode] === 'object' ? JSON.stringify(message[dysonCode]) : message[dysonCode]}]`
);
continue;
}
if (deviceConfig.name === 'skip') {
this.log.silly(
`Skipped creating known but unused data field for Device:[${device.Serial}], Field: [${dysonCode}] Value:[${typeof message[dysonCode] === 'object' ? JSON.stringify(message[dysonCode]) : message[dysonCode]}]`
);
continue;
}
// this.setDysonCode(deviceConfig, dysonUtils.getFieldRewrite(deviceConfig[0]));
// strip leading zeros from numbers
let value;
if (deviceConfig.type === 'number') {
value = parseInt(message[dysonCode], 10);
// TP02: When continuous monitoring is off and the fan is switched off - temperature and humidity loose their values.
// test whether the values are invalid and config.keepValues is true to prevent the old values from being destroyed
if (
dysonCode === 'rhtm' &&
message[dysonCode] === 'OFF' &&
// @ts-ignore
this.config.keepValues
) {
continue;
}
// if field is sleep timer test for value OFF and remap it to a number
if (dysonCode === 'sltm' && message[dysonCode] === 'OFF') {
value = 0;
}
// if field is fan speed test for value AUTO and remap it to a number
if (dysonCode === 'fnsp' && message[dysonCode] === 'AUTO') {
value = 11;
}
if (dysonCode === 'filf') {
// create additional data field filterlifePercent converting value from hours to percent; 4300 is the estimated lifetime in hours by dyson
this.createOrExtendObject(
`${device.Serial + path}.FilterLifePercent`,
{
type: 'state',
common: {
name: deviceConfig.description,
read: true,
write: deviceConfig.writeable,
role: deviceConfig.role,
type: deviceConfig.type,
unit: '%',
states: deviceConfig.displayValues
},
native: {}
},
Number((value * 100) / 4300)
);
}
if (
dysonCode === 'vact' ||
dysonCode === 'va10' ||
dysonCode === 'noxl'
) {
value = Math.floor(value / 10);
}
if (dysonCode === 'hchr') {
value = value / 1000;
}
} else if (deviceConfig.role === 'value.temperature') {
// TP02: When continuous monitoring is off and the fan ist switched off - temperature and humidity loose their values.
// test whether the values are invalid and config.keepValues is true to prevent the old values from being destroyed
if (
message[dysonCode] === 'OFF' &&
// @ts-ignore
this.config.keepValues
) {
continue;
}
value = parseInt(message[dysonCode], 10);
// convert temperature to configured unit
// @ts-ignore
switch (this.config.temperatureUnit) {
case 'K':
deviceConfig.unit = 'K';
value /= 10;
break;
case 'C':
deviceConfig.unit = '°C';
// OLD: deviceConfig[6] = '°' + this.config.temperatureUnit;
value = Number(value / 10 - 273.15).toFixed(2);
break;
case 'F':
deviceConfig.unit = '°F';
// OLD: deviceConfig[6] = '°' + this.config.temperatureUnit;
value = Number((value / 10 - 273.15) * (9 / 5) + 32).toFixed(2);
break;
}
} else if (
deviceConfig.type === 'boolean' &&
deviceConfig.role.startsWith('switch')
) {
// testValue should be the 2nd value in an array or if it's no array, the value itself
const testValue =
typeof message[dysonCode] === 'object'
? message[dysonCode][1]
: message[dysonCode];
//this.log.debug(`${getDataPointName(deviceConfig)} is a bool switch. Current state: [${testValue}]`);
value = ['ON', 'HUMD', 'HEAT'].includes(testValue); // testValue === 'ON' || testValue === 'HUMD' || testValue === 'HEAT';
} else if (
deviceConfig.type === 'boolean' &&
deviceConfig.role.startsWith('indicator')
) {
// testValue should be the 2nd value in an array or if it's no array, the value itself
const testValue =
typeof message[dysonCode] === 'object'
? message[dysonCode][1]
: message[dysonCode];
this.log.silly(
`${deviceConfig.name} is a bool switch. Current state: [${testValue}] --> returnvalue for further processing: ${testValue === 'FAIL'}`
);
value = testValue === 'FAIL';
} else {
// It's no bool switch
value = message[dysonCode];
}
// during state-change message only changed values are being updated
if (typeof value === 'object') {
if (value[0] === value[1]) {
this.log.debug(
`Values for [${deviceConfig.name}] are equal. No update required. Skipping.`
);
continue;
} else {
value = value[1].valueOf();
}
this.log.debug(
`Value is an object. Converting to value: [${JSON.stringify(value)}] --> [${value.valueOf()}]`
);
value = value.valueOf();
}
this.createOrExtendObject(
`${device.Serial + path}.${deviceConfig.name}`,
{
type: 'state',
common: {
name: deviceConfig.description,
read: true,
write: deviceConfig.writeable,
role: deviceConfig.role,
type: deviceConfig.type,
unit: deviceConfig.unit,
states: !deviceConfig.displayValues
? undefined
: SPECIAL_PROPERTIES.has(dysonCode)
? PRODUCTS[device.ProductType][dysonCode]
: deviceConfig.displayValues
},
native: {}
},
value
);
// getWriteable(deviceConfig)=true -> data field is editable, so subscribe for state changes
if (deviceConfig.writeable) {
//this.log.debug('Subscribing for state changes on datapoint: ' + device.Serial + path + '.'+ deviceConfig.name );
this.subscribeStates(`${device.Serial + path}.${deviceConfig.name}`);
}
}
}
/**
* createNO2
*
* creates the data fields for the values itself and the index if the device has a NO2 sensor
*
* @param {Object[]} message the received mqtt message
* @param {number} message[].noxl
* @param {string} row the current data row
* @param {Object} device the device object the data is valid for
*/
createNO2(message, row, device) {
// NO2 QualityIndex
// 0-3: Good, 4-6: Medium, 7-8, Bad, >9: very Bad
let NO2Index = 0;
const value = Math.floor(message[row].noxl / 10);
if (value < 4) {
NO2Index = 0;
} else if (value >= 4 && value <= 6) {
NO2Index = 1;
} else if (value >= 7 && value <= 8) {
NO2Index = 2;
} else if (value >= 9) {
NO2Index = 3;
}
this.createOrExtendObject(
`${device.Serial}.Sensor.NO2Index`,
{
type: 'state',
common: {
name: 'NO2 QualityIndex. 0-3: Good, 4-6: Medium, 7-8, Bad, >9: very Bad',
read: true,
write: false,
role: 'value',
type: 'number',
states: {
0: 'Good',
1: 'Medium',
2: 'Bad',
3: 'very Bad',
4: 'extremely Bad',
5: 'worrying'
}
},
native: {}
},
NO2Index
);
this.subscribeStates(`${device.Serial}.Sensor.NO2Index`);
}
/**
* createHCHO
*
* creates the data fields for the values itself and the index if the device has a HCHO sensor
*
* @param {Object[]} message the received mqtt message
* @param {number} message[].noxl
* @param {string} row the current data row
* @param {Object} device the device object the data is valid for
*/
createHCHO(message, row, device) {
// HCHO QualityIndex
// 0-3: Good, 4-6: Medium, 7-8, Bad, >9: very Bad
let HCHOIndex = 0;
const value = message[row].hchr / 1000;
if (value >= 0 && value < 0.1) {
HCHOIndex = 0;
} else if (value >= 0.1 && value < 0.3) {
HCHOIndex = 1;
} else if (value >= 0.3 && value < 0.5) {
HCHOIndex = 2;
} else if (value >= 0.5) {
HCHOIndex = 3;
}
this.createOrExtendObject(
`${device.Serial}.Sensor.HCHOIndex`,
{
type: 'state',
common: {
name: 'HCHO QualityIndex. 0 - 0.099: Good, 0.100 - 0.299: Medium, 0.300 - 0.499, Bad, >0.500: very Bad',
read: true,
write: false,
role: 'value',
type: 'number',
states: {
0: 'Good',
1: 'Medium',
2: 'Bad',
3: 'very Bad',
4: 'extremely Bad',
5: 'worrying'
}
},
native: {}
},
HCHOIndex
);
this.subscribeStates(`${device.Serial}.Sensor.HCHOIndex`);
}
/**
* createVOC
*
* creates the data fields for the values itself and the index if the device has a VOC sensor
*
* @param {Object[]} message the received mqtt message
* @param {number} message[].va10
* @param {string} row the current data row
* @param {Object} device the device object the data is valid for
*/
createVOC(message, row, device) {