generated from homebridge/homebridge-plugin-template
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathspaClient.ts
1396 lines (1283 loc) · 60.7 KB
/
spaClient.ts
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
import * as crc from "crc";
import type { Logger } from 'homebridge';
import * as net from "net";
export const FLOW_GOOD = "Good";
export const FLOW_LOW = "Low";
export const FLOW_FAILED = "Failed";
export const FLOW_STATES = [FLOW_GOOD, FLOW_LOW, FLOW_FAILED];
const FILTERSTATES = ['Off', 'Cycle 1', 'Cycle 2', 'Cycle 1 and 2'];
const HEATINGMODES = ['Ready', 'Rest', 'Ready in Rest'];
const CELSIUS = 'Celsius';
const FAHRENHEIT = 'Fahrenheit';
const PrimaryRequest = new Uint8Array([0x0a, 0xbf, 0x22]);
const GetFaultsMessageContents = new Uint8Array([0x20, 0xff, 0x00]);
const GetFaultsReply = new Uint8Array([0x0a,0xbf,0x28]);
// These will tell us how many pumps, lights, etc the Spa has
const ControlTypesMessageContents = new Uint8Array([0x00, 0x00, 0x01]);
const ControlTypesReply = new Uint8Array([0x0a,0xbf,0x2e]);
// This one is sent to us automatically every second - no need to request it
const StateReply = new Uint8Array([0xff,0xaf,0x13]);
// Sent if the user sets the spa time from the Balboa app
const PreferencesReply = new Uint8Array([0xff,0xaf,0x26]);
// These three either don't have a reply or we don't care about it.
const ToggleItemRequest = new Uint8Array([0x0a, 0xbf, 0x11]);
const LockPanelRequest = new Uint8Array([0x0a, 0xbf, 0x2d]);
const SetTimeOfDayRequest = new Uint8Array([0x0a, 0xbf, 0x21]);
const SetTargetTempRequest = new Uint8Array([0x0a, 0xbf, 0x20]);
// These we send once, but don't actually currently make use of the results
// Need to investigate how to interpret them.
const ConfigRequest = new Uint8Array([0x0a, 0xbf, 0x04]);
const ConfigReply = new Uint8Array([0x0a,0xbf,0x94]);
// Four different request message contents and their reply codes. Unclear of the
// purpose/value of all of them yet. Again we send each once.
const ControlPanelRequest : Uint8Array[][] = [
[new Uint8Array([0x01,0x00,0x00]), new Uint8Array([0x0a,0xbf,0x23])],
[new Uint8Array([0x02,0x00,0x00]), new Uint8Array([0x0a,0xbf,0x24])],
[new Uint8Array([0x04,0x00,0x00]), new Uint8Array([0x0a,0xbf,0x25])],
[new Uint8Array([0x08,0x00,0x00]), new Uint8Array([0x0a,0xbf,0x26])]
];
// Perhaps something to do with ChromaZone
const KnownUnknownReply = new Uint8Array([0xff,0xaf,0x32]);
export class SpaClient {
socket?: net.Socket;
// undefined means the light doesn't exist on the spa
lightIsOn: (boolean | undefined)[];
// takes values from 0 to pumpsSpeedRange[thisPump]
pumpsCurrentSpeed: number[];
// 0 means doesn't exist, else 1 or 2 indicates number of speeds for this pump
pumpsSpeedRange: number[];
// undefined if not on the spa, else 0-3
blowerCurrentSpeed: (number|undefined);
// 0 means doesn't exist, else 1-3 indicates number of speeds for the blower
blowerSpeedRange: number;
// undefined means the aux doesn't exist on the spa
auxIsOn: (boolean | undefined)[];
// undefined means the mister doesn't exist on the spa
misterIsOn: (boolean | undefined);
// Is Spa set to operate in FAHRENHEIT or CELSIUS
temp_CorF: string;
// If temp_CorF is FAHRENHEIT, temperatures are all stored as degrees F, integers
// (so the resolution is 1 degree F).
// If temp_CorF is CELSIUS, temperatures are all stored as 2x degrees C, integers
// (so the resolution is 0.5 degrees C).
currentTemp?: number;
// When spa is in 'high' mode, what is the target temperature
targetTempModeHigh?: number;
// When spa is in 'low' mode, what is the target temperature
targetTempModeLow?: number;
// Is spa in low or high mode.
tempRangeIsHigh: boolean;
// Time of day, based on the last message we've received, according to the Spa
// (sync it with the Balboa mobile app if you wish)
hour: number;
minute: number;
// ready, ready at rest, etc.
heatingMode: string;
priming: boolean;
time_12or24: string;
isHeatingNow: boolean;
hasCirculationPump: boolean;
circulationPumpIsOn: boolean;
filtering: number;
lockTheSettings: boolean;
lockTheEntirePanel: boolean;
hold: boolean;
receivedStateUpdate: boolean;
autoSetSpaClock: boolean = true;
// Takes values from FLOW_STATES
flow: string;
// Once the Spa has told us what accessories it really has. Only need to do this once.
accurateConfigReadFromSpa: boolean;
// Should be true for almost all of the time, but occasionally the Spa's connection drops
// and we must reconnect.
private isCurrentlyConnectedToSpa: boolean;
numberOfConnectionsSoFar: number = 0;
liveSinceDate: Date;
// Stored so that we can cancel intervals if needed
faultCheckIntervalId: any;
stateUpdateCheckIntervalId: any;
// Can be set in the overall config to provide more detailed logging
devMode: boolean;
lastStateBytes = new Uint8Array();
lastFaultBytes = new Uint8Array();
temperatureHistory : (number|undefined)[] = new Array();
constructor(public readonly log: Logger, public readonly host: string,
public readonly spaConfigurationKnownCallback: () => void,
public readonly changesCallback: () => void,
public readonly reconnectedCallback: () => void, devMode?: boolean) {
this.accurateConfigReadFromSpa = false;
this.isCurrentlyConnectedToSpa = false;
this.devMode = (devMode ? devMode : false);
// Be generous to start. Once we've read the config we will reduce the number of lights
// if needed.
this.lightIsOn = [false,false];
this.auxIsOn = [false, false];
this.misterIsOn = false;
// Be generous to start. Once we've read the config, we'll set reduce
// the number of pumps and their number of speeds correctly
this.pumpsCurrentSpeed = [0,0,0,0,0,0];
this.pumpsSpeedRange = [2,2,2,2,2,2];
this.blowerCurrentSpeed = 0;
this.blowerSpeedRange = 0;
// All of these will be set by the Spa as soon as we get the first status update
this.currentTemp = undefined;
this.hour = 12;
this.minute = 0;
this.heatingMode = "";
this.temp_CorF = "";
this.tempRangeIsHigh = true;
this.targetTempModeLow = undefined;
this.targetTempModeHigh = undefined;
this.priming = false;
this.time_12or24 = "12 Hr";
this.isHeatingNow = false;
this.hasCirculationPump = false;
this.circulationPumpIsOn = false;
this.filtering = 0;
this.lockTheSettings = false;
this.lockTheEntirePanel = false;
this.hold = false;
this.receivedStateUpdate = true;
// This isn't updated as frequently as the above
this.flow = FLOW_GOOD;
this.liveSinceDate = new Date();
// Our communications channel with the spa
this.socket = this.get_socket(host);
// Record temperature history - every 30 minutes
setInterval(() => {
this.recordTemperatureHistory();
}, 30 * 60 * 1000);
}
get_socket(host: string) {
if (this.isCurrentlyConnectedToSpa) {
this.log.error("Already connected, should not be trying again.");
}
this.log.debug("Connecting to Spa at", host, "on port 4257");
this.socket = net.connect({
port: 4257,
host: host
}, () => {
this.numberOfConnectionsSoFar++;
this.liveSinceDate.getUTCDay
const diff = Math.abs(this.liveSinceDate.getTime() - new Date().getTime());
const diffDays = Math.ceil(diff / (1000 * 3600 * 24));
this.log.info('Successfully connected to Spa at', host,
'on port 4257. This is connection number', this.numberOfConnectionsSoFar,
'in', diffDays, 'days');
this.successfullyConnectedToSpa();
});
this.socket?.on('end', () => {
this.log.debug("SpaClient: disconnected:");
});
// If we get an error, then retry
this.socket?.on('error', (error: any) => {
this.log.debug(error);
this.log.info("Had error - closing old socket, retrying in 20s");
this.shutdownSpaConnection();
this.reconnect(host);
});
return this.socket;
}
successfullyConnectedToSpa() {
this.isCurrentlyConnectedToSpa = true;
// Reset our knowledge of the state, since it will
// almost certainly be out of date.
this.resetRecentState();
// Update homekit right away, and then again once some data comes in.
// this.changesCallback();
// listen for new messages from the spa. These can be replies to messages
// We have sent, or can be the standard sending of status that the spa
// seems to do every second.
this.socket?.on('data', (data: any) => {
const bufView = new Uint8Array(data);
this.readAndActOnSocketContents(bufView);
});
// No need to do this once we already have all the config information once.
if (!this.accurateConfigReadFromSpa) {
// Get the Spa's primary configuration of accessories right away
this.sendControlTypesRequest();
// Some testing things. Not yet sure of their use.
// Note: must use 'let' here so id is bound separately each time.
for (let id=0;id<4;id++) {
setTimeout(() => {
this.sendControlPanelRequest(id);
}, 1000*(id+1));
}
setTimeout(() => {
this.send_config_request();
}, 15000);
}
// Wait 5 seconds after startup to send a request to check for any faults
setTimeout(() => {
if (this.isCurrentlyConnectedToSpa) {
this.send_request_for_faults_log();
}
if (this.faultCheckIntervalId) {
this.log.error("Shouldn't ever already have a fault check interval running here.");
}
// And then request again once every 10 minutes.
this.faultCheckIntervalId = setInterval(() => {
if (this.isCurrentlyConnectedToSpa) {
this.send_request_for_faults_log();
}
}, 10 * 60 * 1000);
}, 5000);
// Every 15 minutes, make sure we update the log. And if we haven't
// received a state update, then message the spa so it starts sending
// us messages again.
if (this.stateUpdateCheckIntervalId) {
this.log.error("Shouldn't ever already have a state update check interval running here.");
}
this.stateUpdateCheckIntervalId = setInterval(() => {
if (this.isCurrentlyConnectedToSpa) {
this.checkWeHaveReceivedStateUpdate();
}
}, 15 * 60 * 1000)
// Call to ensure we catch up on anything that happened while we
// were disconnected.
this.reconnectedCallback();
}
lastIncompleteChunk: (Uint8Array|undefined) = undefined;
lastChunkTimestamp: (Date|undefined) = undefined;
/**
* We got some data from the Spa. Often one "chunk" exactly equals one message.
* But sometimes a single chunk will contain multiple messages back to back, and
* so we need to process each in turn. And sometimes a chunk will not contain a full
* message - it is incomplete - and we should store it and wait for the rest to
* arrive (or discard it if the rest doesn't arrive).
*
* @param chunk
*/
readAndActOnSocketContents(chunk: Uint8Array) {
// If we have a lastIncompleteChunk, then it may be the new chunk is just what is needed to
// complete that.
if (this.lastIncompleteChunk) {
const diff = Math.abs(this.lastChunkTimestamp!.getTime() - new Date().getTime());
if (diff < 1000) {
// Merge the messages, if timestamp difference less than 1 second
chunk = this.concat(this.lastIncompleteChunk, chunk);
this.log.debug("Merging messages of length", this.lastIncompleteChunk.length, "and", chunk.length);
} else {
this.log.warn("Discarding old, incomplete message", this.prettify(this.lastIncompleteChunk));
}
this.lastIncompleteChunk = undefined;
this.lastChunkTimestamp = undefined;
}
let messagesProcessed = 0;
while (chunk.length > 0) {
if (chunk.length < 2) {
this.log.error("Very short message received (ignored)", this.prettify(chunk));
break;
}
// Length is the length of the message, which excludes the checksum and 0x7e end.
const msgLength = chunk[1];
if (msgLength > (chunk.length-2)) {
// Cache this because more contents is coming in the next packet, hopefully
this.lastIncompleteChunk = chunk;
this.lastChunkTimestamp = new Date();
this.log.debug("Incomplete message received (awaiting more data)", this.prettify(chunk),
"missing", (msgLength - chunk.length +2), "bytes");
break;
}
// We appear to have a full message, perhaps more than one.
if (chunk[0] == 0x7e && chunk[msgLength+1] == 0x7e) {
// All spa messages start and end with 0x7e
if (msgLength > 0) {
const thisMsg = chunk.slice(0, msgLength+2);
const checksum = thisMsg[msgLength];
// Seems like a good message. Check the checksum is ok
if (checksum != this.compute_checksum(new Uint8Array([msgLength]), thisMsg.slice(2,msgLength))) {
this.log.error("Bad checksum", checksum, "for", this.prettify(thisMsg));
} else {
const somethingChanged = this.readAndActOnMessage(msgLength, checksum, thisMsg);
if (somethingChanged) {
// Only log state when something has changed.
this.log.debug("State change:", this.stateToString());
// Call whoever has registered with us - this is our homekit platform plugin
// which will arrange to go through each accessory and check if the state of
// it has changed. There are 3 cases here to be aware of:
// 1) The user adjusted something in Home and therefore this callback is completely
// unnecessary, since Home is already aware.
// 2) The user adjusted something in Home, but that change could not actually take
// effect - for example the user tried to turn off the primary filter pump during
// a filtration cycle, and the Spa will ignore such a change. In this case this
// callback is essential for the Home app to reflect reality
// 3) The user adjusted something using the physical spa controls (or the Balboa app),
// and again this callback is essential for Home to be in sync with those changes.
//
// Theoretically we could be cleverer and not call this for the unnecessary cases, but
// that seems like a lot of complex work for little benefit. Also theoretically we
// could specify just the controls that have changed, and hence reduce the amount of
// activity. But again little genuine benefit really from that, versus the code complexity
// it would require.
this.changesCallback();
}
}
} else {
// Message length zero means there is no content at all. Not sure if this ever happens,
// but no harm in just ignoring it.
}
messagesProcessed++;
} else {
// Message didn't start/end correctly
this.log.error("Message with bad terminations encountered:", this.prettify(chunk));
}
// Process rest of the chunk, as needed (go round the while loop).
// It might contain more messages
chunk = chunk.slice(msgLength+2);
}
return messagesProcessed;
}
checkWeHaveReceivedStateUpdate() {
if (this.receivedStateUpdate) {
// All good - reset for next time
this.log.info('Latest spa state', this.stateToString());
this.receivedStateUpdate = false;
// We use this periodic occasion to see if we should correct the Spa's clock
this.checkAndSetTimeOfDay();
} else {
this.log.error('No spa state update received for some time. Last state was',
this.stateToString());
// TODO - it would be nice if there was a softer way of getting the spa
// to start sending the status updates again then a full disconnect, reconnect.
// For example, perhaps there is a simple message we send which will trigger that
this.socket?.emit("error", Error("no spa update"));
}
}
reconnecting: boolean = false;
reconnect(host: string) {
if (!this.reconnecting) {
this.reconnecting = true;
setTimeout(() => {
this.socket = this.get_socket(host);
this.reconnecting = false;
}, 20000);
}
}
// Used if we get an error on the socket, as well as during shutdown.
// If we got an error, after this the code will retry to recreate the
// connection (elsewhere).
shutdownSpaConnection() {
// Might already be disconnected, if we're in a repeat error situation.
this.isCurrentlyConnectedToSpa = false;
this.log.debug("Shutting down Spa socket");
if (this.faultCheckIntervalId) {
clearInterval(this.faultCheckIntervalId);
this.faultCheckIntervalId = undefined;
}
if (this.stateUpdateCheckIntervalId) {
clearInterval(this.stateUpdateCheckIntervalId);
this.stateUpdateCheckIntervalId = undefined;
}
// Not sure I understand enough about these sockets to be sure
// of best way to clean them up.
if (this.socket != undefined) {
this.socket.end();
this.socket.destroy();
this.socket = undefined;
}
}
hasGoodSpaConnection() {
return this.isCurrentlyConnectedToSpa;
}
// Called every half hour
recordTemperatureHistory() {
this.temperatureHistory.push(this.getCurrentTemp());
if (this.temperatureHistory.length == 48) {
this.log.info("Temperature for last day (half hour intervals):", this.temperatureHistory.toString());
this.temperatureHistory = new Array();
}
}
/**
* Message starts and ends with 0x7e. Needs a checksum.
* @param purpose purely for logging clarity
* @param type
* @param payload
*/
sendMessageToSpa(purpose: string, type: Uint8Array, payload: Uint8Array) {
const length = (5 + payload.length);
const typepayload = this.concat(type, payload);
const checksum = this.compute_checksum(new Uint8Array([length]), typepayload);
const prefixSuffix = new Uint8Array([0x7e]);
let message = this.concat(prefixSuffix, new Uint8Array([length]));
message = this.concat(message, typepayload);
message = this.concat(message, new Uint8Array([checksum]));
message = this.concat(message, prefixSuffix);
if (this.devMode) {
this.log.info("DEV Sending (" + purpose + "):" + this.prettify(message));
} else {
this.log.debug("Sending (" + purpose + "):" + this.prettify(message));
}
this.socket?.write(message);
}
/**
* Turn the bytes into a nice hex, comma-separated string like '0a,bf,2e'
* @param message the bytes
*/
prettify(message: Uint8Array) {
return Buffer.from(message).toString('hex').match(/.{1,2}/g);
}
getTargetTemp() {
return this.convertSpaTemperatureToExternal(this.tempRangeIsHigh
? this.targetTempModeHigh! : this.targetTempModeLow!);
}
getTempIsCorF() {
return this.temp_CorF;
}
convertTempToC(temp: number) {
if (temp == undefined) return undefined;
if (this.getTempIsCorF() === CELSIUS) {
return temp;
} else {
return (temp-32.0)*5/9;
}
}
convertTempFromC(temp: number) {
if (temp == undefined) return undefined;
if (this.getTempIsCorF() === CELSIUS) {
return temp;
} else {
return (temp*9/5.0)+32.0;
}
}
getTempRangeIsHigh() {
return this.tempRangeIsHigh;
}
timeToString(hour: number, minute: number) {
return hour.toString().padStart(2, '0') + ":" + minute.toString().padStart(2, '0');
}
getIsLightOn(index: number) {
// Lights are numbered 1,2 by Balboa
index--;
return this.lightIsOn[index];
}
setMisterState(value: boolean) {
if ((this.misterIsOn === value)) {
return;
}
if (this.misterIsOn == undefined) {
this.log.error("Trying to set state of mister which doesn't exist");
return;
}
if (!this.isCurrentlyConnectedToSpa) {
// Should we throw an error, or how do we handle this?
}
const id = 0x0e;
this.send_toggle_message('Mister', id);
this.misterIsOn = value;
}
getIsMisterOn() {
return this.misterIsOn;
}
setAuxState(index: number, value: boolean) {
// Aux are numbered 1,2 by Balboa
index--;
if ((this.auxIsOn[index] === value)) {
return;
}
if (this.auxIsOn[index] == undefined) {
this.log.error("Trying to set state of aux",(index+1),"which doesn't exist");
return;
}
if (!this.isCurrentlyConnectedToSpa) {
// Should we throw an error, or how do we handle this?
}
const id = 0x16+index;
this.send_toggle_message('Aux'+(index+1), id);
this.auxIsOn[index] = value;
}
getIsAuxOn(index: number) {
index--;
return this.auxIsOn[index];
}
getIsHold() {
return this.hold;
}
setIsHold(value: boolean) {
if (this.hold == value) return;
this.send_toggle_message('Hold', 0x3c);
this.hold = value;
}
getIsLocked(entirePanel: boolean) {
return entirePanel ? this.lockTheEntirePanel : this.lockTheSettings;
}
setIsLocked(entirePanel: boolean, value: boolean) {
if (this.getIsLocked(entirePanel) == value) return;
this.send_lock_settings(entirePanel, value);
if (entirePanel) {
this.lockTheEntirePanel = value;
} else {
this.lockTheSettings = value;
}
}
getIsHeatingNow() {
return this.isHeatingNow;
}
// Three-state: ready, rest, ready-at-rest (the latter indicating it is in 'rest' mode and a
// pump has been turned on so the spa will heat if necessary). This is what is shown in
// the spa display.
getHeatingMode() {
return this.heatingMode;
}
// See below
isHeatingModeAlwaysReady() {
return (this.heatingMode == 'Ready');
}
/**
* Boolean either
* - 'ready' (always heating if needed) or
* - 'rest' (only heating when a pump is running)
*
* In winter it is advisable to keep the spa in ready mode (at a low temperature if preferred)
* to avoid freezing.
*/
setHeatingModeAlwaysReady(isAlwaysReady: boolean) {
const isSetToAlwaysReady = (this.heatingMode == 'Ready');
if (isSetToAlwaysReady == isAlwaysReady) {
// Already set correctly
return;
}
this.send_toggle_message('Heating Mode', 0x51);
this.heatingMode = HEATINGMODES[isAlwaysReady? 0 : 1];
}
/**
* Returns in C or F depending on what the user has defined in the Spa
* control panel.
*/
getCurrentTemp() {
if (this.currentTemp == undefined) {
return undefined;
} else {
return this.convertSpaTemperatureToExternal(this.currentTemp);
}
}
setLightState(index: number, value: boolean) {
// Lights are numbered 1,2 by Balboa
index--;
if ((this.lightIsOn[index] === value)) {
return;
}
if (this.lightIsOn[index] == undefined) {
this.log.error("Trying to set state of light",(index+1),"which doesn't exist");
return;
}
if (!this.isCurrentlyConnectedToSpa) {
// Should we throw an error, or how do we handle this?
}
const id = 0x11+index;
this.send_toggle_message('Light'+(index+1), id);
this.lightIsOn[index] = value;
}
setTempRangeIsHigh(isHigh: boolean) {
if ((this.tempRangeIsHigh === isHigh)) {
return;
}
this.send_toggle_message('TempHighLowRange', 0x50);
this.tempRangeIsHigh = isHigh;
}
getFlowState() {
return this.flow;
}
getPumpSpeedRange(index: number) {
if (index == 0) {
return (this.hasCirculationPump ? 1 : 0);
} else {
return this.pumpsSpeedRange[index-1];
}
}
static getSpeedAsString(range: number, speed: number) {
if (range == 1) {
return ["Off", "High"][speed];
} else if (range == 2) {
return ["Off", "Low", "High"][speed];
} else if (range == 3) {
return ["Off", "Low", "Medium", "High"][speed];
} else {
return undefined;
}
}
getPumpSpeed(index: number) {
if (index == 0) {
if (this.hasCirculationPump) {
return this.circulationPumpIsOn ? 1 : 0;
} else {
this.log.error("Trying to get speed of circulation pump which doesn't exist");
return 0;
}
}
// Pumps are numbered 1,2,3,... by Balboa
index--;
if (this.pumpsSpeedRange[index] == 0) {
this.log.error("Trying to get speed of pump",(index+1),"which doesn't exist");
return 0;
}
return this.pumpsCurrentSpeed[index];
}
getBlowerSpeedRange() {
return this.blowerSpeedRange;
}
getBlowerSpeed() {
if (this.blowerCurrentSpeed === undefined) {
this.log.error("Trying to get speed of blower, which doesn't exist");
return 0;
}
return this.blowerCurrentSpeed!;
}
setBlowerSpeed(desiredSpeed: number) {
if (this.blowerCurrentSpeed === undefined) {
this.log.error("Trying to set speed of blower, which doesn't exist");
return;
}
const numberOfStates = 4;
const oldIdx = this.blowerCurrentSpeed!;
let toggleCount = (numberOfStates + desiredSpeed - oldIdx) % numberOfStates;
// Anything from 0 to 3 toggles needed.
while (toggleCount > 0) {
this.send_toggle_message('Blower', 0x0c);
toggleCount--;
}
this.blowerCurrentSpeed = desiredSpeed;
}
/**
* A complication here is that, during filtration cycles, a pump might be locked into an "on"
* state. For example on my Spa, pump 1 goes into "low" state, and I can switch it to "high", but
* a toggle from "high" does not switch it off, but rather switches it straight to "low" again.
* With single-speed pumps this isn't such an issue, but with 2-speed pumps, this behaviour causes
* problems for the easiest approach to setting the pump to a particular speed. When we calculate that
* two 'toggles' are needed, the reality is that sometimes it might just be one, and hence two
* toggles will end us in the wrong pump speed. There are really just two specific case that are
* annoying as a user:
*
* 1) the pump is "High". Desired speed is "Low". Hence we deduce the need for
* two toggles. But, since "Off" is skipped, we end up back where we started in "High".
*
* 2) we're trying to turn the pump off, but it can't be turned off. We need to make sure
* the ending state is correctly reflected in Home.
*
* @param index pump number (1-6) convert to index lookup (0-5) convert to Balboa message id (4-9)
* @param desiredSpeed 0...pumpsSpeedRange[index] depending on speed range of the pump
*/
setPumpSpeed(index: number, desiredSpeed: number) {
// Pump 0 is the circulation pump, whose state cannot be set
if (index == 0) {
if (desiredSpeed == 0) {
// Anytime we turn a pump off, ensure that all remembered state information
// is forgotten, so the next information from the Spa will tell us what is
// actually going on, and we'll update Home if necessary.
this.resetRecentState();
}
return;
}
const pumpName = 'Pump' + index;
// Pumps are numbered 1,2,3,... by Balboa
index--;
if (this.pumpsCurrentSpeed[index] === desiredSpeed) {
// No action needed if pump already at the desired speed
return;
}
if (this.pumpsSpeedRange[index] == 0) {
this.log.error("Trying to set speed of", pumpName, "which doesn't exist");
return;
}
if (desiredSpeed > this.pumpsSpeedRange[index]) {
this.log.error("Trying to set speed of", pumpName, " faster (",desiredSpeed,
") than the pump supports (",this.pumpsSpeedRange[index] ,").");
return;
}
// Toggle Pump1 = toggle '4', Pump2 = toggle '5', etc.
const balboaPumpId = index+4;
if (this.pumpsSpeedRange[index] == 1) {
// It is a 1-speed pump
// Any change requires just one toggle. It's either from off to high or high to off
this.send_toggle_message(pumpName, balboaPumpId);
this.pumpsCurrentSpeed[index] = desiredSpeed;
} else {
// How many toggles do we need to get from the current speed
// to the desired speed? For a 2-speed pump, allowed speeds are 0,1,2.
// This code (but not other code in this class) should actually
// work as-is for 3-speed pumps if they exist.
const numberOfStates = this.pumpsSpeedRange[index]+1;
const oldIdx = this.pumpsCurrentSpeed[index];
const newIdx = desiredSpeed;
// For a 2-speed pump, we'll need to toggle either 1 or 2 times.
let toggleCount = (numberOfStates + newIdx - oldIdx) % numberOfStates;
if (toggleCount == 2 && desiredSpeed === 1) {
// Deal with the edge-case complication remarked on above.
// Send one toggle message
this.send_toggle_message(pumpName, balboaPumpId);
this.pumpsCurrentSpeed[index] = 0;
// Then wait a little bit to check what state the pump is in, before
// continuing - either we need to do nothing, or we need to do one more
// toggle.
if (this.devMode) {
this.log.info("DEV Edge case triggered on", pumpName);
}
// TODO: is this the right amount of waiting? Should we try to explicitly
// synchronise this with the next status update message?
setTimeout(() => {
if (this.pumpsCurrentSpeed[index] === 0) {
// This is the normal case. We still have one more toggle to do.
this.send_toggle_message(pumpName, balboaPumpId);
this.pumpsCurrentSpeed[index] = 1;
} else {
// Spa is in filter mode where this specific pump is not
// allowed to turn off. It's already in the right state.
if (this.devMode) {
this.log.info("DEV Pump already in correct state");
}
}
}, 500);
} else {
while (toggleCount > 0) {
this.send_toggle_message(pumpName, balboaPumpId);
toggleCount--;
}
this.pumpsCurrentSpeed[index] = desiredSpeed;
}
}
// The other edge case where we try to turn a pump off
// that cannot currently be turned off (scheduled filtering).
if (desiredSpeed == 0) {
// Anytime we turn a pump off, ensure that all remembered state information
// is forgotten, so the next information from the Spa will tell us what is
// actually going on, and we'll update Home if necessary.
this.resetRecentState();
}
}
compute_checksum(length: Uint8Array, bytes: Uint8Array) {
const checksum = crc.crc8(Buffer.from(this.concat(length, bytes)), 0x02);
return checksum ^ 0x02;
}
concat(a: Uint8Array, b: Uint8Array) {
const c = new Uint8Array(a.length + b.length);
c.set(a);
c.set(b, a.length);
return c;
}
// Temperatures which are out of certain bounds will be rejected by the spa.
// We don't do bounds-checking ourselves.
setTargetTemperature(temp: number) {
let sendTemp;
if (this.tempRangeIsHigh) {
this.targetTempModeHigh = this.convertExternalTemperatureToSpa(temp);
sendTemp = this.targetTempModeHigh;
} else {
this.targetTempModeLow = this.convertExternalTemperatureToSpa(temp);
sendTemp = this.targetTempModeLow;
}
this.sendMessageToSpa("SetTargetTempRequest", SetTargetTempRequest, new Uint8Array([sendTemp]));
}
checkAndSetTimeOfDay() {
const date = new Date();
const hr = date.getHours();
const min = date.getMinutes();
if (Math.abs((hr*60+min) - (this.hour * 60 + this.minute)) > 10) {
// Spa's time seems to be different to my time. We trust that the computer we are
// running this code on is more likely to have the correct time than the Spa.
// So we change the Spa's time.
if (this.autoSetSpaClock) {
this.sendMessageToSpa("SetSpaTimeOfDay", SetTimeOfDayRequest, new Uint8Array([hr, min]));
}
}
}
send_config_request() {
this.sendMessageToSpa("ConfigRequest", ConfigRequest, new Uint8Array());
}
sendControlTypesRequest() {
this.sendMessageToSpa("ControlTypesRequest", PrimaryRequest, ControlTypesMessageContents);
}
sendControlPanelRequest(id : number) {
// 4 messages from [0x01,0x00,0x00] through 2,4,8
this.sendMessageToSpa("ControlPanelRequest"+(id+1), PrimaryRequest, ControlPanelRequest[id][0]);
}
send_request_for_faults_log() {
this.sendMessageToSpa("Checking for any Spa faults", PrimaryRequest, GetFaultsMessageContents);
}
/**
* Most of the Spa's controls are "toggles" - i.e. we don't set a pump to a specific
* speed, or turn a light on, but rather we increment or toggle the state of a device,
* so the same action turns a light on as off, and to get a 2-speed pump from off to high
* we need to toggle it twice. Here are the known codes:
* - 0x04 to 0x09 - pumps 1-6
* - 0x11-0x12 - lights 1-2
* - 0x3c - hold. Hold mode is used to disable the pumps during service
* functions like cleaning or replacing the filter. Hold mode will last for 1 hour
* unless the mode is exited manually.
* - 0x50 - temperature range (high or low)
* - 0x0c - blower
* - 0x0e - mister
* - 0x16 - aux1
* - 0x17 - aux2
* - 0x51 - heating mode (ready = always trying to maintain temperature, rest = only
* heat when pumps are running)
*
* The spa may also have two "lock" settings - locking the control panel completely, or
* just locking the settings (but allowing jets and lights, say, to still be used). Those
* are set below in 'send_lock_settings' and do not use the toggle mechanism.
*/
send_toggle_message(itemName: string, code: number) {
if (code > 255) {
this.log.error("Toggle only a single byte; had " + code);
return;
}
// All of these codes form a 2-byte message - the code and zero.
// (no idea why, nor if making that zero something else will change the
// outcome).
this.sendMessageToSpa("Toggle " + itemName + ", using code:"+ code,
ToggleItemRequest, new Uint8Array([code, 0x00]));
}
// See https://github.com/ccutrer/balboa_worldwide_app/wiki#lock-request
// 1 = lock settings, 2 = lock panel, 3 = unlock settings, 4 = unlock panel
send_lock_settings(entirePanel: boolean, lock: boolean) {
const value = (entirePanel ? 1 : 0) + (lock ? 1 : 3);
this.sendMessageToSpa("Lock", LockPanelRequest, new Uint8Array([value]));
}
// Celsius temperatures are stored/communicated by the Spa in half degrees.
// So '80' stored/sent by the Spa means 40.0 degrees celsius, IF the spa
// is operating in Celsius. If in Fahrenheit then no conversions needed.
convertSpaTemperatureToExternal(temperature : number) {
if (this.temp_CorF === FAHRENHEIT) return temperature;
// It's a celsius value which needs either dividing or multiplying by 2
return temperature/2.0;
}
// Celsius temperatures are stored/communicated by the Spa in half degrees.
// So '80' stored/sent by the Spa means 40.0 degrees celsius, IF the spa
// is operating in Celsius. If in Fahrenheit then no conversions needed.
convertExternalTemperatureToSpa(temperature : number) {
if (this.temp_CorF === FAHRENHEIT) return temperature;
return Math.round(temperature * 2.0);
}
internalTemperatureToString(temperature? : number) {
if (temperature == undefined) return "Unknown";
if (this.temp_CorF === FAHRENHEIT) return temperature.toString() + "F";
return this.convertSpaTemperatureToExternal(temperature).toFixed(1).toString() + "C";
}
stateToString() {
let pumpDesc = '[';
for (let i = 0; i<6;i++) {
if (this.pumpsSpeedRange[i] > 0) {
pumpDesc += SpaClient.getSpeedAsString(this.pumpsSpeedRange[i],this.pumpsCurrentSpeed[i]) + ' ';
}
}
pumpDesc += ']';
const s = "Temp: " + this.internalTemperatureToString(this.currentTemp)
+ ", Temp Range: " + (this.tempRangeIsHigh ? "High" : "Low")
+ ", Target Temp(H): " + this.internalTemperatureToString(this.targetTempModeHigh)
+ ", Target Temp(L): " + this.internalTemperatureToString(this.targetTempModeLow)
+ ", Time: " + this.timeToString(this.hour, this.minute)
+ ", Priming: " + this.priming.toString()
+ ", Heating Mode: " + this.heatingMode
+ ", Temp Scale: " + this.temp_CorF
+ ", Time Scale: " + this.time_12or24
+ ", Heating: " + this.isHeatingNow
+ ", Pumps: " + pumpDesc
+ (this.hasCirculationPump ? ", Circ Pump: " + (this.circulationPumpIsOn ? "On" : "Off") : "")
+ ", Filtering: " + FILTERSTATES[this.filtering]
+ ", Lights: [" + this.lightIsOn + "]"
+ (this.blowerCurrentSpeed != undefined ? ", Blower: " + this.blowerCurrentSpeed : "")
+ (this.misterIsOn != undefined ? ", Mister: " + this.misterIsOn : "")
+ ", Aux: [" + this.auxIsOn + "]"
+ (this.lockTheEntirePanel ? ", Panel locked" : "")
+ (this.lockTheSettings ? ", Settings locked" : "")
+ (this.hold ? ", Hold mode activated" : "")
return s;
}
/**
* Return true if anything in the state has changed as a result of the message
* received.
*
* @param length
* @param checksum
* @param chunk - first and last bytes are 0x7e. Second byte is message length.
* Second-last byte is the checksum. Then bytes 3,4,5 are the message type.
* Everything in between is the content.
*/
readAndActOnMessage(length: number, checksum: number, chunk: Uint8Array) {
if (chunk[0] != 0x7e || chunk[1] != length || chunk[length] != checksum || chunk[length+1] != 0x7e || chunk.length != (length+2)) {
this.log.error("Bad internal data in message handling. Please report a bug:",
length, checksum, this.prettify(chunk));
return false;
}
const contents = chunk.slice(5, length);
const msgType = chunk.slice(2,5);
let stateChanged : boolean;
let avoidHighFreqDevMessage : boolean = true;
if (this.equal(msgType,StateReply)) {
stateChanged = this.readStateFromBytes(contents);
avoidHighFreqDevMessage = stateChanged;
} else if (this.equal(msgType, GetFaultsReply)) {
stateChanged = this.readFaults(contents);
} else if (this.equal(msgType, ControlTypesReply)) {
this.log.info("Control types reply(" + this.prettify(msgType)
+ "):"+ this.prettify(contents));
stateChanged = this.interpretControlTypesReply(contents);