-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.js
More file actions
1460 lines (1315 loc) · 51.2 KB
/
Copy pathmain.js
File metadata and controls
1460 lines (1315 loc) · 51.2 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
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
/* eslint-disable jsdoc/require-param */
'use strict';
const utils = require('@iobroker/adapter-core');
const GroheClient = require('./lib/groheClient');
const { GroheDeviceManagement } = require('./lib/device-manager');
const { sendNotification } = require('./lib/notificationManager');
const {
getNotificationMessage,
getLocalizedNotificationType,
getLocalizedCategoryName,
} = require('./lib/notificationMessages');
const { dumpApiStructure } = require('./lib/apiDump');
// Device type constants (same as GroheTypes in Python grohe package)
const GROHE_SENSE = 101;
const GROHE_SENSE_GUARD = 103;
const GROHE_BLUE_HOME = 104;
const GROHE_BLUE_PROFESSIONAL = 105;
class GroheSmarthome extends utils.Adapter {
/** @param {Partial<utils.AdapterOptions>} [options] Adapter options */
constructor(options) {
super({ ...options, name: 'grohe-smarthome' });
this.client = null;
this.deviceManagement = new GroheDeviceManagement(this);
this.pollTimer = null;
this.baseInterval = Math.max(60, Number(this.config.pollInterval) || 300);
/** Device registry – maps appliance_id to { locationId, roomId, applianceId, type, name } */
this.devices = new Map();
/**
* Poll cycle counter – used to reduce API calls for slowly changing data.
* - Dashboard: every poll (core sensor data)
* - Status (online/wifi/update): every 5th poll
* - Command (valve state): every 3rd poll
* - Pressure measurement: every 10th poll
*/
this.pollCount = 0;
/**
* Exponential backoff state for polling errors.
* On each consecutive failure the interval doubles (up to 1 hour).
* A successful poll resets it back to the configured interval.
*/
this.consecutiveErrors = 0;
this.currentPollInterval = 0; // set in onReady from config
/**
* Total consumption cache per Sense Guard.
* Maps applianceId -> { base: number, lastDay: string }
* base = cumulative from installation_date to yesterday (refreshed once/day).
* Mirrors HA guard_coordinator.py logic.
*/
this.totalConsumptionCache = new Map();
/**
* Tracks running background refresh-and-verify tasks for Blue devices.
* Maps applianceId -> true while a verify loop is in progress.
* Prevents multiple concurrent refresh tasks for the same device.
*/
this._blueRefreshRunning = new Map();
/**
* Tracks the timestamp of the last seen Grohe notification per device.
* Used to detect new notifications and avoid sending duplicates.
* Maps applianceId -> ISO timestamp string.
* Reset on adapter restart (any missed notifications during downtime are skipped).
*/
this._notifLastSeen = new Map();
/**
* Tracks the last known online status per device for change detection.
* Maps applianceId -> boolean (true = online, false = offline).
* Reset on adapter restart.
*/
this._deviceOnlineState = new Map();
/** ioBroker system language, read at startup from system.config */
this.systemLanguage = 'en';
this.on('ready', this.onReady.bind(this));
this.on('stateChange', this.onStateChange.bind(this));
this.on('unload', this.onUnload.bind(this));
this.on('message', this.onMessage.bind(this));
}
/* ================================================================== */
/* Startup */
/* ================================================================== */
async onReady() {
await this.setState('info.connection', { val: false, ack: true });
// Read ioBroker system language for localised notifications
try {
const sysConfig = await this.getForeignObjectAsync('system.config');
this.systemLanguage = sysConfig?.common?.language || 'en';
this.log.debug(`System language: ${this.systemLanguage}`);
} catch {
this.systemLanguage = 'en';
}
await this.setObjectNotExistsAsync('auth.refreshToken', {
type: 'state',
common: { name: 'Refresh Token (encrypted)', type: 'string', role: 'text', read: true, write: false },
native: {},
});
try {
this.client = new GroheClient(this.log, this.setTimeout.bind(this));
const email = (this.config.email || '').trim();
const password = this.config.password || '';
if (email) {
const parts = email.split('@');
const masked =
parts.length === 2 ? `${parts[0].substring(0, 2)}***@${parts[1]}` : `${email.substring(0, 3)}***`;
this.log.debug(`Using email: ${masked} (length: ${email.length})`);
}
this.log.debug(`Password present: ${password.length > 0}, length: ${password.length}`);
// Read refresh token from state (not config – writing config triggers restart!)
const savedRefresh = await this._readRefreshToken();
// 1) Try refresh token if present
if (savedRefresh) {
this.log.debug('Trying saved refresh token');
this.client.setRefreshToken(savedRefresh);
try {
await this.client.refresh();
this.log.info('Refresh token used successfully');
await this._persistRefreshToken(this.client.refreshToken);
} catch (err) {
this.log.warn(`Refresh with saved token failed: ${err.message}`);
this.client.auth.accessToken = null;
this.client.auth.refreshToken = null;
}
}
// 2) Full login if no valid access token yet
if (!this.client.accessToken) {
if (!email || !password) {
throw new Error('Please set email and password in the adapter settings.');
}
this.log.info('Starting login with username/password...');
const tokens = await this.client.login(email, password);
await this._persistRefreshToken(tokens.refresh_token);
}
await this.setState('info.connection', { val: true, ack: true });
// 3) Initial poll
await this.pollDevices();
// 4) Set up polling interval (minimum 60s)
const configuredInterval = this.config.pollInterval;
this.log.debug(`Config pollInterval: ${configuredInterval} (type: ${typeof configuredInterval})`);
this.baseInterval = Math.max(60, Number(configuredInterval) > 0 ? Number(configuredInterval) : 300);
this.currentPollInterval = this.baseInterval;
this._schedulePoll();
this.log.info(`Polling active: every ${this.baseInterval}s`);
} catch (err) {
await this.setState('info.connection', { val: false, ack: true });
this.log.warn(`Initialization failed: ${err.message}`);
}
}
/* ================================================================== */
/* Polling – Dashboard + Status + Command per device */
/* ================================================================== */
/**
* Schedule the next poll using the current (possibly backed-off) interval.
*/
_schedulePoll() {
if (this.pollTimer) {
this.clearTimeout(this.pollTimer);
}
this.pollTimer = this.setTimeout(async () => {
await this.pollDevices();
this._schedulePoll();
}, this.currentPollInterval * 1000);
}
async pollDevices() {
if (!this.client) {
return;
}
this.pollCount++;
// Determine which extra endpoints to fetch this cycle
const isFirstPoll = this.pollCount === 1;
const fetchStatus = isFirstPoll || this.pollCount % 5 === 0;
const fetchCommand = isFirstPoll || this.pollCount % 3 === 0;
const fetchPressure = isFirstPoll || this.pollCount % 10 === 0;
const fetchConsumption = isFirstPoll || this.pollCount % 5 === 0;
const fetchConfig = isFirstPoll || this.pollCount % 10 === 0;
this.log.debug(
`Poll cycle #${this.pollCount} (status=${fetchStatus}, command=${fetchCommand}, ` +
`pressure=${fetchPressure}, consumption=${fetchConsumption}, config=${fetchConfig})`,
);
try {
const dashboard = await this.client.getDashboard();
if (this.client.usingFallbackDiscovery && !this._fallbackLogged) {
this.log.info('Using fallback discovery mode because /dashboard is not available for this account');
this._fallbackLogged = true;
}
if (this.config.rawStates && !this._apiDumpScheduled) {
this._apiDumpScheduled = true;
this.log.info('Raw states enabled – scheduling API structure dump in 30 seconds');
this.setTimeout(async () => {
try {
await dumpApiStructure(this.client, this.log);
} catch (err) {
this.log.warn(`API structure dump failed: ${err.message}`);
}
}, 30000);
}
if (this.config.rawStates && this.pollCount >= 3) {
this.log.warn(
'Raw states mode: stopping after 3 polls. Disable "raw states" and restart the adapter for normal operation.',
);
if (this.pollTimer) {
this.clearTimeout(this.pollTimer);
this.pollTimer = null;
}
return;
}
await this.setState('info.connection', { val: true, ack: true });
// Successful poll – reset backoff to configured interval
if (this.consecutiveErrors > 0) {
this.log.info(
`Polling recovered after ${this.consecutiveErrors} error(s), interval reset to ${this.baseInterval}s`,
);
if (this.config.notifyEnabled && this.config.notifyOnConnError) {
await sendNotification(
this,
getNotificationMessage(this, 'pollingRecovered', { count: this.consecutiveErrors }),
);
}
this.consecutiveErrors = 0;
this.currentPollInterval = this.baseInterval;
}
const locations = dashboard?.locations || [];
for (const location of locations) {
const locationId = location.id;
const rooms = location.rooms || [];
for (const room of rooms) {
const roomId = room.id;
const appliances = room.appliances || [];
for (const appliance of appliances) {
if (appliance.registration_complete === false) {
this.log.debug(`Appliance ${appliance.appliance_id} not registered – skipped`);
continue;
}
await this._processAppliance(locationId, roomId, appliance, {
fetchStatus,
fetchCommand,
fetchPressure,
fetchConsumption,
fetchConfig,
});
}
}
}
} catch (err) {
await this.setState('info.connection', { val: false, ack: true });
// Exponential backoff: double the interval on each consecutive failure
this.consecutiveErrors++;
const MAX_BACKOFF = 3600; // 1 hour
const backoff = Math.min(MAX_BACKOFF, this.baseInterval * Math.pow(2, this.consecutiveErrors));
if (backoff >= MAX_BACKOFF) {
// After reaching 1h backoff: pause until 12:00 or 00:00
// This avoids further spam and gives the API a full rest period.
const now = new Date();
const target = new Date(now);
if (now.getHours() < 12) {
target.setHours(12, 0, 0, 0);
} else {
target.setDate(target.getDate() + 1);
target.setHours(0, 0, 0, 0);
}
this.currentPollInterval = Math.round((target.getTime() - now.getTime()) / 1000);
} else {
this.currentPollInterval = backoff;
}
const nextTryDate = new Date(Date.now() + this.currentPollInterval * 1000);
const nextTryStr = nextTryDate.toLocaleTimeString(this.systemLanguage || undefined, {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
});
const httpStatus = err?.response?.status;
const reason =
httpStatus === 403
? 'HTTP 403 (Forbidden). This may be caused by too frequent polling or the Grohe app/account may need checking'
: err.message;
this.log.warn(
`Polling failed: ${reason}. ` +
`Next try at ${nextTryStr} (interval: ${this.currentPollInterval}s, errors: ${this.consecutiveErrors})`,
);
// Send connection-error notification on every polling failure
if (this.config.notifyEnabled && this.config.notifyOnConnError) {
const notifReason =
httpStatus === 403 ? getNotificationMessage(this, 'reason403') : err.message || String(err);
const localReason = getNotificationMessage(this, 'pollingError', {
status: httpStatus || '?',
reason: notifReason,
});
const localRetry = getNotificationMessage(this, 'pollingRetry', {
time: nextTryStr,
interval: this.currentPollInterval,
errors: this.consecutiveErrors,
});
await sendNotification(this, `${localReason}\n${localRetry}`);
}
}
}
/* ================================================================== */
/* Process individual appliance from dashboard */
/* ================================================================== */
async _processAppliance(locationId, roomId, appliance, flags) {
const id = appliance.appliance_id;
const type = appliance.type;
const name = appliance.name || 'Grohe Device';
this.devices.set(id, { locationId, roomId, applianceId: id, type, name });
// Fetch status only every 5th poll (online/wifi/update change slowly)
let status = null;
if (flags.fetchStatus && this.client) {
try {
const statusArr = await this.client.getApplianceStatus(locationId, roomId, id);
status = this._parseStatusArray(statusArr);
} catch (err) {
this.log.warn(`Status query for ${id} failed: ${err.message}`);
}
}
switch (type) {
case GROHE_SENSE:
await this._updateSense(id, name, appliance, status);
break;
case GROHE_SENSE_GUARD:
await this._updateSenseGuard(id, name, appliance, locationId, roomId, status, flags);
break;
case GROHE_BLUE_HOME:
case GROHE_BLUE_PROFESSIONAL:
await this._updateBlue(id, name, appliance, type, status, locationId, roomId);
break;
default:
await this._ensureDevice(id, name, `UNKNOWN_${type}`);
this.log.debug(`Unknown device type ${type} for ${id}`);
}
}
/**
* Parse the status array from the API into a usable object.
* Status API returns: [{type: "update_available", value: false}, {type: "connection", value: true}, ...]
*/
_parseStatusArray(statusArr) {
const result = {};
if (!Array.isArray(statusArr)) {
return result;
}
for (const entry of statusArr) {
if (entry && entry.type) {
result[entry.type] = entry.value;
}
}
return result;
}
/* ================================================================== */
/* Sense (type 101) */
/* ================================================================== */
async _updateSense(id, name, appliance, status) {
await this._ensureDevice(id, `${name} (Sense)`, 'SENSE');
const m = appliance.data_latest?.measurement || {};
await this._setNum(id, 'temperature', 'Temperature', '°C', 'value.temperature', m.temperature);
await this._setNum(id, 'humidity', 'Humidity', '%', 'value.humidity', m.humidity);
await this._setNum(
id,
'battery',
'Battery',
'%',
'value.battery',
typeof m.battery === 'number' ? m.battery : undefined,
);
await this._setStr(id, 'lastMeasurement', 'Last measurement', 'date', m.timestamp);
// Status channel (from status API)
await this._updateStatusChannel(id, status);
// Notifications
await this._updateLatestNotification(id, appliance);
// Raw measurement data (optional)
}
/* ================================================================== */
/* Sense Guard (type 103) */
/* ================================================================== */
async _updateSenseGuard(id, name, appliance, locationId, roomId, status, flags) {
await this._ensureDevice(id, `${name} (Sense Guard)`, 'SENSE_GUARD');
const m = appliance.data_latest?.measurement || {};
const dl = appliance.data_latest || {};
// Temperature, flow, pressure (from dashboard – always available)
await this._setNum(id, 'temperature', 'Water temperature', '°C', 'value.temperature', m.temperature_guard);
await this._setNum(id, 'flowRate', 'Current flow rate', 'l/min', 'value', m.flowrate);
await this._setNum(id, 'pressure', 'Current pressure', 'bar', 'value.pressure', m.pressure);
await this._setStr(id, 'lastMeasurement', 'Last measurement', 'date', m.timestamp);
// Consumption channel (from dashboard – always available)
await this._ensureChannel(`${id}.consumption`, 'Consumption');
await this._setNum(`${id}.consumption`, 'daily', 'Daily consumption', 'l', 'value', dl.daily_consumption);
await this._setNum(
`${id}.consumption`,
'averageDaily',
'Average daily consumption',
'l',
'value',
dl.average_daily_consumption,
);
await this._setNum(
`${id}.consumption`,
'averageMonthly',
'Average monthly consumption',
'l',
'value',
dl.average_monthly_consumption,
);
// Total water consumption (calculated from /data/aggregated, like HA integration)
// Fetched every 5th poll – consumption changes slowly and uses extra API calls
if (flags.fetchConsumption) {
await this._updateTotalConsumption(id, locationId, roomId, appliance);
}
// Withdrawals (from dashboard – always available)
const w = dl.withdrawals || {};
await this._setNum(
`${id}.consumption`,
'lastWaterConsumption',
'Last water consumption',
'l',
'value',
w.waterconsumption,
);
await this._setNum(
`${id}.consumption`,
'lastMaxFlowRate',
'Last max flow rate',
'l/min',
'value',
w.maxflowrate,
);
// Valve state from command endpoint (every 3rd poll – rarely changes)
if (flags.fetchCommand && this.client) {
try {
const cmd = await this.client.getApplianceCommand(locationId, roomId, id);
const valveOpen = cmd?.command?.valve_open;
await this._setBool(id, 'valveOpen', 'Valve open', 'indicator', valveOpen);
} catch (err) {
this.log.warn(`Command query for ${id} failed: ${err.message}`);
}
// Snooze status (every 3rd poll – snooze is temporary, changes after start/stop)
try {
const snooze = await this.client.getSnooze(locationId, roomId, id);
const isActive = !!(snooze && (snooze.snooze_active || snooze.snooze_duration));
await this._setBool(`${id}.controls.snooze`, 'active', 'Snooze active', 'indicator', isActive);
} catch (err) {
if (err?.response?.status === 404) {
// 404 = no active snooze
await this._setBool(`${id}.controls.snooze`, 'active', 'Snooze active', 'indicator', false);
} else {
this.log.debug(`Snooze query for ${id} failed: ${err.message}`);
}
}
}
// Pressure measurement results (every 10th poll – only changes after manual trigger)
if (flags.fetchPressure && this.client) {
try {
const pm = await this.client.getAppliancePressureMeasurement(locationId, roomId, id);
const items = Array.isArray(pm) ? pm : pm?.items || pm?.data || [];
if (items.length > 0) {
const latest = items[0];
await this._ensureChannel(`${id}.pressureMeasurement`, 'Pressure measurement');
await this._setNum(
`${id}.pressureMeasurement`,
'dropOfPressure',
'Pressure drop',
'bar',
'value',
latest.drop_of_pressure,
);
await this._setBool(
`${id}.pressureMeasurement`,
'isLeakage',
'Leakage detected',
'indicator',
latest.leakage,
);
await this._setStr(
`${id}.pressureMeasurement`,
'leakageLevel',
'Leakage level',
'text',
latest.level,
);
await this._setStr(
`${id}.pressureMeasurement`,
'startTime',
'Measurement time',
'date',
latest.start_time,
);
}
} catch (err) {
if (err?.response?.status === 404) {
this.log.debug(`Pressure measurement not available for ${id} (HTTP 404 – no measurement data yet)`);
} else {
this.log.warn(`Pressure measurement for ${id} failed: ${err.message}`);
}
}
}
// Status channel
await this._updateStatusChannel(id, status);
// Notifications
await this._updateLatestNotification(id, appliance);
// Controls
await this._ensureChannel(`${id}.controls`, 'Controls');
await this._ensureWritableBool(`${id}.controls`, 'valveOpen', 'Open valve', 'button');
await this._ensureWritableBool(`${id}.controls`, 'valveClose', 'Close valve', 'button');
await this._ensureWritableBool(
`${id}.controls`,
'startPressureMeasurement',
'Start pressure measurement',
'button',
);
// Snooze sub-channel inside controls
await this._ensureChannel(`${id}.controls.snooze`, 'Snooze');
await this._ensureWritableNum(`${id}.controls.snooze`, 'duration', 'Snooze duration', 'value', 5, {
min: 1,
max: 240,
unit: 'min',
});
await this._ensureWritableBool(`${id}.controls.snooze`, 'start', 'Start snooze', 'button');
await this._ensureWritableBool(`${id}.controls.snooze`, 'stop', 'Stop snooze', 'button');
await this._ensureState(`${id}.controls.snooze.active`, {
name: 'Snooze active',
type: 'boolean',
role: 'indicator',
read: true,
write: false,
});
// Sprinkler sub-channel inside controls – states always present; values refreshed every 10th poll
const sprinklerDays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
await this._ensureChannel(`${id}.controls.sprinkler`, 'Sprinkler mode');
await this._ensureWritableNum(`${id}.controls.sprinkler`, 'startHour', 'Start time – hours', 'value', 0, {
min: 0,
max: 23,
unit: 'h',
});
await this._ensureWritableNum(`${id}.controls.sprinkler`, 'startMinute', 'Start time – minutes', 'value', 0, {
min: 0,
max: 59,
unit: 'min',
});
await this._ensureWritableNum(`${id}.controls.sprinkler`, 'stopHour', 'Stop time – hours', 'value', 23, {
min: 0,
max: 23,
unit: 'h',
});
await this._ensureWritableNum(`${id}.controls.sprinkler`, 'stopMinute', 'Stop time – minutes', 'value', 59, {
min: 0,
max: 59,
unit: 'min',
});
for (const day of sprinklerDays) {
const cap = day.charAt(0).toUpperCase() + day.slice(1);
await this._ensureWritableBool(`${id}.controls.sprinkler`, `active${cap}`, `Active on ${cap}`, 'switch');
}
await this._ensureWritableBool(`${id}.controls.sprinkler`, 'save', 'Save sprinkler settings', 'button');
await this._ensureWritableNum(
`${id}.controls`,
'withdrawalAmountLimit',
'Withdrawal amount limit',
'value',
300,
{ min: 0, max: 2000, unit: 'l' },
);
if (flags.fetchConfig && this.client) {
try {
const details = await this.client.getApplianceDetails(locationId, roomId, id);
const cfg = details?.config || {};
if (cfg.sprinkler_mode_start_time !== undefined) {
const totalMin = Number(cfg.sprinkler_mode_start_time);
await this.setState(`${id}.controls.sprinkler.startHour`, {
val: Math.floor(totalMin / 60),
ack: true,
});
await this.setState(`${id}.controls.sprinkler.startMinute`, {
val: totalMin % 60,
ack: true,
});
}
if (cfg.sprinkler_mode_stop_time !== undefined) {
const totalMin = Number(cfg.sprinkler_mode_stop_time);
await this.setState(`${id}.controls.sprinkler.stopHour`, {
val: Math.floor(totalMin / 60),
ack: true,
});
await this.setState(`${id}.controls.sprinkler.stopMinute`, {
val: totalMin % 60,
ack: true,
});
}
for (const day of sprinklerDays) {
const cap = day.charAt(0).toUpperCase() + day.slice(1);
const apiVal = cfg[`sprinkler_mode_active_${day}`];
if (apiVal !== undefined) {
await this.setState(`${id}.controls.sprinkler.active${cap}`, { val: !!apiVal, ack: true });
}
}
if (cfg.withdrawel_amount_limit !== undefined) {
await this.setState(`${id}.controls.withdrawalAmountLimit`, {
val: Number(cfg.withdrawel_amount_limit),
ack: true,
});
}
} catch (err) {
this.log.warn(`Config query for ${id} failed: ${err.message}`);
}
}
// Raw measurement data (optional)
}
/* ================================================================== */
/* Blue Home / Professional (type 104/105) */
/* ================================================================== */
async _updateBlue(id, name, appliance, type, status, locationId, roomId) {
const typeStr = type === GROHE_BLUE_HOME ? 'Blue Home' : 'Blue Professional';
await this._ensureDevice(id, `${name} (${typeStr})`, typeStr.toUpperCase().replace(' ', '_'));
// Use the measurement data supplied by /dashboard. The background verify
// loop (_startBlueVerify) fetches /details after get_current_measurement
// to pick up fresh readings; there is no need to call /details here too.
const m = appliance.data_latest?.measurement || {};
this.log.debug(`Blue ${id} /dashboard measurement: ${JSON.stringify(appliance.data_latest?.measurement)}`);
// Blue devices do NOT push measurements automatically – the device must
// be explicitly asked via get_current_measurement (the Grohe app does this too).
// Trigger a refresh every 3rd poll (including first poll after restart).
if (this.pollCount % 3 === 0 && locationId && roomId && this.client) {
const oldTimestamp = m.timestamp || null;
try {
await this.client.setApplianceCommand(locationId, roomId, id, {
get_current_measurement: true,
});
this.log.debug(`Triggered measurement refresh for Blue ${id}`);
// Start background verify loop to wait for fresh data from /details.
// The Grohe cloud needs time to process the measurement request.
// We poll /details up to 3 times (every 10s, max 30s).
this._startBlueVerify(id, locationId, roomId, oldTimestamp);
} catch (err) {
this.log.warn(`Measurement refresh for Blue ${id} failed: ${err.message}`);
}
}
await this._updateBlueStates(id, m, status, appliance);
}
/**
* Write all Blue device measurement states.
* Called both from the normal poll (/details data) and from the
* background verify loop when fresh data arrives after a measurement command.
*/
async _updateBlueStates(id, m, status, appliance) {
this.log.debug(
`Blue ${id} raw: remaining_filter=${m.remaining_filter}, remaining_filter_liters=${m.remaining_filter_liters}, ` +
`remaining_co2=${m.remaining_co2}, remaining_co2_liters=${m.remaining_co2_liters}, timestamp=${m.timestamp}`,
);
// CO2 & Filter
await this._setNum(id, 'remainingCo2', 'Remaining CO₂', '%', 'value.fill', m.remaining_co2);
await this._setNum(id, 'remainingFilter', 'Remaining filter', '%', 'value.fill', m.remaining_filter);
await this._setNum(
id,
'remainingCo2Liters',
'Remaining CO₂ (liters)',
'l',
'value.fill',
m.remaining_co2_liters,
);
await this._setNum(
id,
'remainingFilterLiters',
'Remaining filter (liters)',
'l',
'value.fill',
m.remaining_filter_liters,
);
// Cycles
await this._setNum(id, 'cyclesCarbonated', 'Cycles carbonated', '', 'value', m.open_close_cycles_carbonated);
await this._setNum(id, 'cyclesStill', 'Cycles still', '', 'value', m.open_close_cycles_still);
// Times
await this._setNum(id, 'operatingTime', 'Operating time', 'min', 'value', m.operating_time);
await this._setNum(id, 'pumpRunningTime', 'Pump running time', 'min', 'value', m.pump_running_time);
await this._setNum(id, 'maxIdleTime', 'Max idle time', 'min', 'value', m.max_idle_time);
await this._setNum(id, 'timeSinceRestart', 'Time since restart', 'min', 'value', m.time_since_restart);
// Water running times
await this._setNum(
id,
'waterRunningCarbonated',
'Water running carbonated',
'min',
'value',
m.water_running_time_carbonated,
);
await this._setNum(
id,
'waterRunningMedium',
'Water running medium',
'min',
'value',
m.water_running_time_medium,
);
await this._setNum(id, 'waterRunningStill', 'Water running still', 'min', 'value', m.water_running_time_still);
// Dates
await this._setStr(id, 'dateCleaning', 'Last cleaning', 'date', m.date_of_cleaning);
await this._setStr(id, 'dateCo2Replacement', 'Last CO₂ replacement', 'date', m.date_of_co2_replacement);
await this._setStr(
id,
'dateFilterReplacement',
'Last filter replacement',
'date',
m.date_of_filter_replacement,
);
await this._setStr(id, 'lastMeasurement', 'Last measurement', 'date', m.timestamp);
// Counts
await this._setNum(id, 'cleaningCount', 'Cleaning count', '', 'value', m.cleaning_count);
await this._setNum(id, 'filterChangeCount', 'Filter changes', '', 'value', m.filter_change_count);
await this._setNum(id, 'powerCutCount', 'Power cuts', '', 'value', m.power_cut_count);
await this._setNum(id, 'pumpCount', 'Pump cycles', '', 'value', m.pump_count);
// Status channel
if (status) {
await this._updateStatusChannel(id, status);
}
// Notifications
if (appliance) {
await this._updateLatestNotification(id, appliance);
}
// Controls
await this._ensureChannel(`${id}.controls`, 'Controls');
await this._ensureWritableNum(
`${id}.controls`,
'tapType',
'Tap type (1=still, 2=medium, 3=carbonated)',
'level',
1,
);
await this._ensureWritableNum(
`${id}.controls`,
'tapAmount',
'Amount in ml (50–2000, multiples of 50)',
'level',
250,
);
await this._ensureWritableBool(`${id}.controls`, 'dispenseTrigger', 'Dispense', 'button');
await this._ensureWritableBool(`${id}.controls`, 'resetCo2', 'Reset CO₂', 'button');
await this._ensureWritableBool(`${id}.controls`, 'resetFilter', 'Reset filter', 'button');
// Raw measurement data (optional)
}
/* ================================================================== */
/* Blue – Background refresh-and-verify */
/* ================================================================== */
/**
* Start a non-blocking background loop that polls the /details endpoint
* until a newer measurement timestamp appears (or gives up after 30s).
*
* This mirrors the HA ha-grohe_smarthome BlueHomeCoordinator pattern:
* after sending get_current_measurement, the Grohe cloud needs time to
* fetch data from the device. We poll /details every 10s up to 3 times.
*
* A guard flag prevents multiple concurrent verify loops for the same device.
*/
_startBlueVerify(applianceId, locationId, roomId, oldTimestamp) {
if (this._blueRefreshRunning.get(applianceId)) {
this.log.debug(`Blue verify already running for ${applianceId}, skipping`);
return;
}
this._blueRefreshRunning.set(applianceId, true);
const POLL_INTERVAL_MS = 10000; // 10 seconds between checks
const MAX_ATTEMPTS = 3; // total wait: up to 30s
let attempt = 0;
const poll = () => {
attempt++;
this.setTimeout(async () => {
try {
if (!this.client) {
this.log.debug(`Blue verify for ${applianceId}: client gone, aborting`);
this._blueRefreshRunning.delete(applianceId);
return;
}
const details = await this.client.getApplianceDetails(locationId, roomId, applianceId);
const newTimestamp = details?.data_latest?.measurement?.timestamp;
const newM = details?.data_latest?.measurement || {};
if (newTimestamp && newTimestamp !== oldTimestamp) {
this.log.info(
`Blue ${applianceId}: fresh data from /details ` +
`(old=${oldTimestamp}, new=${newTimestamp}, ` +
`remaining_filter=${newM.remaining_filter}, remaining_co2=${newM.remaining_co2})`,
);
await this._updateBlueStates(applianceId, newM, null, null);
this._blueRefreshRunning.delete(applianceId);
return;
}
if (attempt < MAX_ATTEMPTS) {
this.log.debug(
`Blue ${applianceId}: no new data yet (attempt ${attempt}/${MAX_ATTEMPTS}), retrying...`,
);
poll();
} else {
this.log.warn(
`Blue ${applianceId}: no new measurement found after ${MAX_ATTEMPTS * (POLL_INTERVAL_MS / 1000)}s ` +
`(timestamp still ${oldTimestamp || 'unknown'})`,
);
this._blueRefreshRunning.delete(applianceId);
}
} catch (err) {
this.log.warn(`Blue verify for ${applianceId} failed: ${err.message}`);
this._blueRefreshRunning.delete(applianceId);
}
}, POLL_INTERVAL_MS);
};
poll();
}
/* ================================================================== */
/* Status channel (all devices) */
/* ================================================================== */
async _updateStatusChannel(id, status) {
await this._ensureChannel(`${id}.status`, 'Status');
if (status) {
await this._setBool(`${id}.status`, 'online', 'Online', 'indicator.reachable', status.connection);
await this._setBool(
`${id}.status`,
'updateAvailable',
'Update available',
'indicator',
status.update_available,
);
if (status.wifi_quality !== undefined) {
await this._setNum(`${id}.status`, 'wifiQuality', 'WiFi quality', '', 'value', status.wifi_quality);
}
// Detect online/offline changes and send warning notifications
if (this.config.notifyEnabled && this.config.notifyOnWarnings && status.connection !== undefined) {
const prev = this._deviceOnlineState.get(id);
const cur = Boolean(status.connection);
if (prev !== undefined && prev !== cur) {
const dev = this.devices.get(id);
const devName = dev?.name || id;
const msgKey = cur ? 'deviceOnline' : 'deviceOffline';
await sendNotification(this, getNotificationMessage(this, msgKey, { device: devName }));
}
this._deviceOnlineState.set(id, cur);
}
}
}
/* ================================================================== */
/* Latest notification (all devices) */
/* ================================================================== */
async _updateLatestNotification(id, appliance) {
const notifications = appliance.notifications || [];
if (notifications.length === 0) {
return;
}
const latest = notifications[0];
const cat = latest.category;
const type = latest.type ?? latest.notification_type;
// Look up the human-readable notification text in the system language.
// The Grohe API does not return message text – all clients build it locally.
const typeText = getLocalizedNotificationType(this, cat, type);
const catName = getLocalizedCategoryName(this, cat);
this.log.debug(`Notification for ${id}: category=${cat}, type=${type}, text=${typeText}`);
await this._ensureChannel(`${id}.notifications`, 'Notifications');
await this._setStr(`${id}.notifications`, 'latestMessage', 'Latest notification message', 'text', typeText);
await this._setStr(`${id}.notifications`, 'latestTimestamp', 'Timestamp', 'date', latest.timestamp);
await this._setNum(`${id}.notifications`, 'latestCategory', 'Category', '', 'value', cat);
await this._setStr(`${id}.notifications`, 'latestCategoryName', 'Category name', 'text', catName);
await this._setNum(`${id}.notifications`, 'latestType', 'Notification type', '', 'value', type);
// Push notification for new Grohe alarms (30), warnings (20) and latestMessage changes (under warnings category)
if (this.config.notifyEnabled && latest.timestamp) {
const hadLastSeen = this._notifLastSeen.has(id);
const lastSeen = this._notifLastSeen.get(id);
if (lastSeen !== latest.timestamp) {
this._notifLastSeen.set(id, latest.timestamp);
// Skip startup baseline only on first poll to avoid flooding old notifications.
// If a device gets its first notification later, it will still trigger.
const shouldNotify = hadLastSeen || this.pollCount > 1;
if (shouldNotify) {
const dev = this.devices.get(id);
const devName = dev?.name || id;
if (cat === 30 && this.config.notifyOnAlarms) {
const prefix = getNotificationMessage(this, 'alarmPrefix');
await sendNotification(this, `${prefix} – ${devName}: ${typeText}`);
} else if (cat === 20 && this.config.notifyOnWarnings) {
const prefix = getNotificationMessage(this, 'warningPrefix');
await sendNotification(this, `${prefix} – ${devName}: ${typeText}`);
} else if (this.config.notifyOnWarnings) {
await sendNotification(
this,
getNotificationMessage(this, 'latestMessageChanged', {
device: devName,
message: typeText,
timestamp: latest.timestamp,
}),
);
}
}
}
}
}
/* ================================================================== */
/* State changes (write commands) */
/* ================================================================== */
async onStateChange(stateId, state) {
if (!state || state.ack || !this.client) {
return;