-
Notifications
You must be signed in to change notification settings - Fork 15
/
index.ts
2097 lines (1675 loc) · 73.6 KB
/
index.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
'use strict';
import 'source-map-support/register';
import debug from 'debug';
import * as dgram from 'dgram';
import { Socket } from 'dgram';
import { EventEmitter } from 'events';
import * as net from 'net';
import { setTimeout as setTimeoutSync } from 'timers';
import * as SLGateway from './messages/SLGatewayDataMessage';
import { BodyCommands, ChemCommands, ChlorCommands, CircuitCommands, ConnectionCommands, EquipmentCommands, OutboundGateway, PumpCommands, ScheduleCommands } from './messages/OutgoingMessages';
import { ConnectionMessage, SLVersionData } from './messages/ConnectionMessage';
import { EquipmentConfigurationMessage, SLCircuitNamesData, SLControllerConfigData, SLEquipmentConfigurationData, SLGetCustomNamesData, SLHistoryData, SLWeatherForecastData } from './messages/config/EquipmentConfig';
import { ChlorMessage, SLIntellichlorData } from './messages/state/ChlorMessage';
import { ChemMessage, SLChemData, SLChemHistory } from './messages/state/ChemMessage';
import { ScheduleMessage, SLScheduleData } from './messages/config/ScheduleMessage';
import { PumpMessage, SLPumpStatusData } from './messages/state/PumpMessage';
import { CircuitMessage } from './messages/config/CircuitMessage';
import { HeaterMessage } from './messages/config/HeaterMessage';
import { Inbound, SLMessage, SLSimpleBoolData, SLSimpleNumberData } from './messages/SLMessage';
import { EquipmentStateMessage, SLEquipmentStateData, SLSystemTimeData } from './messages/state/EquipmentState';
import { HLEncoder } from './utils/PasswordEncoder';
export * from './messages/config/ScheduleMessage';
export * from './messages/config/EquipmentConfig';
export * from './messages/config/CircuitMessage';
export * from './messages/config/HeaterMessage';
export * from './messages/state/ChemMessage';
export * from './messages/state/ChlorMessage';
export * from './messages/state/PumpMessage';
export * from './messages/state/EquipmentState';
export * from './messages/ConnectionMessage';
export * from './messages/OutgoingMessages';
export * from './messages/SLGatewayDataMessage';
export * from './messages/SLMessage';
const debugFind = debug('sl:find');
const debugRemote = debug('sl:remote');
const debugUnit = debug('sl:unit');
export class FindUnits extends EventEmitter {
constructor() {
super();
this.message = Buffer.alloc(8);
this.message[0] = 1;
this.finder = dgram.createSocket('udp4');
this.finder.on('listening', () => {
this.finder.setBroadcast(true);
this.finder.setMulticastTTL(128);
if (!this.bound) {
this.bound = true;
this.sendServerBroadcast();
}
}).on('message', (msg, remote) => {
this.foundServer(msg, remote);
}).on('close', () => {
debugFind('closed');
this.emit('close');
}).on('error', (e) => {
debugFind('error: %O', e);
this.emit('error', e);
});
}
private finder: Socket;
private bound: boolean;
private message: Buffer;
search() {
if (!this.bound) {
this.finder.bind();
} else {
this.sendServerBroadcast();
}
}
public async searchAsync(searchTimeMs?: number): Promise<LocalUnit[]> {
const p = new Promise((resolve) => {
try {
const units: LocalUnit[] = [];
debugFind('Screenlogic finder searching for local units...',);
setTimeoutSync(() => {
if (units.length === 0) {
debugFind('No units found searching locally.');
}
this.removeAllListeners();
resolve(units);
}, searchTimeMs ?? 5000);
this.on('serverFound', (unit) => {
debugFind(`Screenlogic found unit ${JSON.stringify(unit)}`);
units.push(unit);
});
} catch (error) {
debugFind(`Screenlogic caught searchAsync error ${error.message}, rethrowing...`);
throw error;
}
this.search();
});
return Promise.resolve(p) as Promise<LocalUnit[]>;
}
foundServer(msg: Buffer, remote: dgram.RemoteInfo) {
debugFind('found something');
if (msg.length >= 40) {
const server: LocalUnit = {
address: remote.address,
type: msg.readInt32LE(0),
port: msg.readInt16LE(8),
gatewayType: msg.readUInt8(10),
gatewaySubtype: msg.readUInt8(11),
gatewayName: msg.toString('utf8', 12, 29),
};
debugFind(' type: ' + server.type + ', host: ' + server.address + ':' + server.port + ', identified as ' + server.gatewayName);
if (server.type === 2) {
this.emit('serverFound', server);
}
} else {
debugFind(' unexpected message');
}
}
sendServerBroadcast() {
this.finder.send(this.message, 0, this.message.length, 1444, '255.255.255.255');
debugFind('Looking for ScreenLogic hosts...');
}
public close() {
this.finder.close();
}
}
export class RemoteLogin extends EventEmitter {
constructor(systemName: string) {
super();
this.systemName = systemName;
this._client = new net.Socket();
this._gateway = new OutboundGateway();
}
public systemName: string;
private _client: net.Socket;
private _gateway: OutboundGateway;
public async connectAsync(): Promise<SLGateway.SLGateWayData> {
return new Promise((resolve, reject) => {
debugRemote('connecting to dispatcher...');
this._client.on('data', (buf) => {
if (buf.length > 4) {
const message = new Inbound();
message.readFromBuffer(buf);
const msgType = buf.readInt16LE(2);
debugRemote(`received message of length ${buf.length} and messageId ${message.action}`);
switch (message.action) {
case ConnectionMessage.ResponseIDs.GatewayResponse:
debugRemote(' it is a gateway response');
if (typeof resolve !== 'undefined') {
const unit = new SLGateway.SLReceiveGatewayDataMessage(buf).get();
resolve(unit);
} else {
this.emit('gatewayFound', new SLGateway.SLReceiveGatewayDataMessage(buf));
}
break;
default:
debugRemote(' it is unknown. type: ' + msgType);
if (typeof reject !== 'undefined') {
reject(new Error(`Message on unknown type (${msgType}) received.`));
}
break;
}
} else {
debugRemote(' message of length <= 4 received and is not valid');
if (typeof reject !== 'undefined') {
reject(new Error('Message of length <= 4 is invalid.'));
}
}
this.closeAsync().catch((err: Error) => {
debugRemote(`Error with closeAsync: ${err.message};`);
});
}).on('close', (had_error) => {
debugRemote('Gateway server connection closed (close emit)');
this.emit('close', had_error);
}).on('error', (e) => {
debugRemote('error: %o', e);
if (typeof reject !== 'undefined') {
reject(e);
} else {
this.emit('error', e);
}
});
this._client.connect(500, 'screenlogicserver.pentair.com', () => {
debugRemote('connected to dispatcher');
this._client.write(this._gateway.createSendGatewayMessage(this.systemName));
});
});
}
public async closeAsync(): Promise<boolean> {
const p = new Promise((resolve) => {
debugRemote('Gateway request to close.');
this._client.end(() => {
debugRemote('Gateway closed');
resolve(true);
});
});
return Promise.resolve(p) as Promise<boolean>;
}
}
export class UnitConnection extends EventEmitter {
constructor() {
super();
this._buffer = Buffer.alloc(1024);
this._bufferIdx = 0;
}
public systemName: string;
private serverPort: number;
private serverAddress: string;
private password: string;
protected client: net.Socket;
private isConnected = false;
private _clientId: number;
public get clientId(): number { return this._clientId; }
public set clientId(val: number) { this._clientId = val; }
private _controllerId = 0;
public get controllerId(): number { return this._controllerId; }
public set controllerId(val: number) { this._controllerId = val; }
public static controllerType = 0; // for set equip message decode
public static expansionsCount = 0; // for set equip message decode
protected _isMock = false;
protected _hasAddedClient = false;
private _buffer: Buffer;
private _bufferIdx: number;
private _senderId = 0;
public get senderId(): number { return this._senderId; }
public set senderId(val: number) { this._senderId = val; }
public controller: Controller;
public netTimeout = 2500; // set back to 1s after testing
private _keepAliveDuration: number = 30 * 1000;
private _keepAliveTimer: NodeJS.Timeout;
private _expectedMsgLen: number;
public circuits: Circuit;
public equipment: Equipment;
public bodies: Body;
public chem: Chem;
public chlor: Chlor;
public schedule: Schedule;
public pump: Pump;
public reconnectAsync = async () => {
try {
debugUnit('Unit had an unexpected error/timeout/clientError - reconnecting.');
this.client.removeAllListeners();
await this.closeAsync();
await this.connectAsync();
} catch (err) {
debugUnit(`Error trying to reconnect: ${err.message}`);
}
};
public initMock(systemName: string, address: string, port: number, password: string, senderId?: number) {
this.systemName = systemName;
this.serverPort = port;
this.serverAddress = address;
this.password = password;
this.senderId = senderId ?? Math.min(Math.max(1, Math.trunc(Math.random() * 10000)), 10000);
this.clientId = Math.round(Math.random() * 100000);
this._initCommands();
this._isMock = true;
}
public init(systemName: string, address: string, port: number, password?: string, senderId?: number) {
this.systemName = systemName;
this.serverPort = port;
this.serverAddress = address;
this.password = password ?? '';
this.senderId = senderId ?? 0;
this.clientId = Math.round(Math.random() * 100000);
this._initCommands();
this._isMock = false;
this._keepAliveTimer = setTimeoutSync(() => {
this.keepAliveAsync();
}, this._keepAliveDuration || 30000);
}
public initUnit(server: LocalUnit) {
this.init(server.gatewayName, server.address, server.port);
}
private _initCommands() {
this.controller = {
circuits: new CircuitCommands(this),
connection: new ConnectionCommands(this),
equipment: new EquipmentCommands(this),
chlor: new ChlorCommands(this),
chem: new ChemCommands(this),
schedules: new ScheduleCommands(this),
pumps: new PumpCommands(this),
bodies: new BodyCommands(this)
};
this.circuits = new Circuit(this);
this.equipment = new Equipment(this);
this.bodies = new Body(this);
this.chem = new Chem(this);
this.chlor = new Chlor(this);
this.schedule = new Schedule(this);
this.pump = new Pump(this);
}
public write(bytes: Buffer | string) {
if (this._isMock) {
debugUnit('Skipping write because of mock port');
return;
}
try {
if (!this.client.writable) {
debugUnit('Socket not writeable.');
} else {
this.client.write(bytes);
this.emit('bytesWritten', this.client.bytesWritten);
}
} catch (err) {
debugUnit(`Error writing to net: ${err.message}`);
}
}
public readMockBytesAsString(hexStr: string) {
const bytes = [];
for (let i = 0; i < hexStr.length; i += 2) {
console.log(hexStr.length);
bytes.push(parseInt(hexStr.substring(i, i + 2), 16));
}
const buf = Buffer.from(bytes);
this.processData(buf);
}
public keepAliveAsync() {
try {
if (!this.isConnected) {
return;
}
if (typeof this._keepAliveTimer !== 'undefined' || this._keepAliveTimer) {
clearTimeout(this._keepAliveTimer);
}
this._keepAliveTimer = null;
this.pingServerAsync().catch(err => {
debugUnit(`Error pinging server: ${err.message}`);
});
} catch (error) {
debugUnit('ERROR pinging server');
} finally {
this._keepAliveTimer = setTimeoutSync(() => {
this.keepAliveAsync();
}, this._keepAliveDuration || 30000);
}
}
public processData(msg: Buffer) {
// ensure we can hold this message
if (this._buffer.length < msg.length + this._bufferIdx) {
this._buffer = Buffer.alloc(msg.length + this._buffer.length, this._buffer);
}
// if this is the start of a new message (as opposed to the continuation of a previous one)
// then store how long this message tells us it is
if (this._bufferIdx === 0) {
this._expectedMsgLen = msg.readInt32LE(4) + 8;
}
// if the expected message length is less than the message length, it means we have two messages
// packed into the same data
const toRead = Math.min(this._expectedMsgLen, msg.length);
msg.copy(this._buffer, this._bufferIdx, 0, toRead);
this._bufferIdx = this._bufferIdx + toRead;
// once we've read the expected length, we have a full message to handle
if (this._bufferIdx === this._expectedMsgLen) {
const b = this._buffer.slice(0, this._expectedMsgLen);
if (b.length > 4) {
const message = new Inbound(this.controllerId, this.senderId);
message.readFromBuffer(b);
this.toLogEmit(message, 'in');
this.onClientMessage(message);
}
this._bufferIdx = 0;
}
// finally check if there was more in the buffer than what we expected to receive.
// if so, there's another message (or more) left to be read
if (toRead < msg.length) {
this.processData(msg.slice(toRead, msg.length));
}
}
toLogEmit(message: SLMessage, direction: string) {
if (this._isMock) {
return;
}
const data = {
systemName: this.systemName,
action: message.action,
controllerId: message.controllerId,
clientId: this.clientId,
senderId: this.senderId,
serverAddress: this.serverAddress,
serverPort: this.serverPort,
payload: message.toBuffer().toJSON().data,
protocol: 'screenlogic',
dir: direction
};
this.emit('slLogMessage', data);
}
async closeAsync(): Promise<boolean> {
const p = new Promise((resolve) => {
try {
if (typeof this._keepAliveTimer !== 'undefined' || this._keepAliveTimer) {
clearTimeout(this._keepAliveTimer);
}
this._keepAliveTimer = null;
if (typeof this.client === 'undefined' || this.client.destroyed) {
resolve(true);
} else {
if (this.isConnected && this._hasAddedClient) {
const removeClient = this.removeClientAsync().catch(e => { throw e; });
debugUnit(`Removed client: ${removeClient}`);
}
this.client.setKeepAlive(false);
this.client.destroy();
this.isConnected = false;
this.client.removeAllListeners();
this.removeAllListeners();
this.client = undefined;
resolve(true);
}
} catch (error) {
debugUnit(`caught error in closeAsync ${error.message}... returning anwyay`);
resolve(true);
}
});
return Promise.resolve(p) as Promise<boolean>;
}
public async connectAsync(): Promise<boolean> {
if (this._isMock) {
return Promise.resolve(true);
}
const p = new Promise((resolve, reject) => {
try {
const opts = {
allowHalfOpen: false,
keepAlive: true,
keepAliveInitialDelay: 5
};
this.client = new net.Socket(opts);
this.client.setKeepAlive(true, 10 * 1000);
this.client.on('data', (msg) => {
this.emit('bytesRead', this.client.bytesRead);
this.processData(msg);
}).once('close', (had_error: boolean) => {
debugUnit(`closed. any error? ${had_error}`);
this.emit('close', had_error);
}).once('end', () => {
// often, during debugging, the socket will timeout
debugUnit('end event for unit');
this.emit('end');
}).once('error', async (e: Error) => {
// often, during debugging, the socket will timeout
debugUnit(`error event for unit: ${typeof e !== 'undefined' ? e.message : 'unknown unit'}`);
await this.reconnectAsync();
}).once('timeout', async () => {
// often, during debugging, the socket will timeout
debugUnit('timeout event for unit');
this.emit('timeout');
await this.reconnectAsync();
}).once('clientError', async (err, socket) => {
if (err.code === 'ECONNRESET' || !socket.writable) {
socket.end('HTTP/2 400 Bad Request\n');
}
debugUnit('client error\n', err);
await this.reconnectAsync();
});
debugUnit('connecting...');
this.client.once('ready', () => {
debugUnit('connected, sending init message...');
this.write('CONNECTSERVERHOST\r\n\r\n');
debugUnit('sending challenge message...');
const _timeout = setTimeoutSync(() => {
if (typeof reject === 'function') {
reject(new Error('timeout'));
}
}, this.netTimeout);
this.once('challengeString', async (challengeString) => {
debugUnit(' challenge string emit');
try {
await this.loginAsync(challengeString);
resolve(true);
} catch (error) {
reject(error);
} finally {
clearTimeout(_timeout);
}
});
const msg = this.controller.connection.sendChallengeMessage();
this.toLogEmit(msg, 'out');
});
this.client.connect(this.serverPort, this.serverAddress);
} catch (error) {
debugUnit(`Caught connectAsync error ${error.message}; rethrowing...`);
throw error;
}
});
return Promise.resolve(p) as Promise<boolean>;
}
async loginAsync(challengeString: string, senderId?: number) {
const p = new Promise((resolve, reject) => {
debugUnit('sending login message...');
const _timeout = setTimeoutSync(() => {
reject(new Error('time out waiting for challenge string'));
}, this.netTimeout);
this.once('loggedIn', () => {
debugUnit('received loggedIn event');
clearTimeout(_timeout);
this.isConnected = true;
resolve(true);
this.removeListener('loginFailed', () => { /* do nothing */ });
}).once('loginFailed', () => {
debugUnit('loginFailed');
clearTimeout(_timeout);
this.isConnected = false;
reject(new Error('Login Failed'));
});
const password = new HLEncoder(this.password.toString()).getEncryptedPassword(challengeString);
const msg = this.controller.connection.sendLoginMessage(password, senderId);
this.toLogEmit(msg, 'out');
});
return Promise.resolve(p);
}
public bytesRead() {
return this.client.bytesRead;
}
public bytesWritten() {
return this.client.bytesWritten;
}
public status() {
if (typeof this.client === 'undefined') {
return {
destroyed: true,
connecting: false,
// pending: this.client.pending, // should be here but isn't?
readyState: 'closed',
};
}
return {
destroyed: this.client.destroyed,
connecting: this.client.connecting,
// pending: this.client.pending, // should be here but isn't?
timeout: this.client.timeout,
readyState: this.client.readyState,
};
}
async getVersionAsync(senderId?: number): Promise<SLVersionData> {
const p = new Promise((resolve, reject) => {
debugUnit('[%d] sending version query...', senderId ?? this.senderId);
const _timeout = setTimeoutSync(() => {
reject(new Error('time out waiting for version'));
}, this.netTimeout);
this.once('version', (version) => {
debugUnit('received version event');
clearTimeout(_timeout);
resolve(version);
});
const msg = this.controller.connection.sendVersionMessage(senderId);
this.toLogEmit(msg, 'out');
});
return Promise.resolve(p) as Promise<SLVersionData>;
}
async addClientAsync(clientId?: number, senderId?: number): Promise<SLSimpleBoolData> {
if (this._isMock) {
return Promise.resolve({ senderId: senderId ?? 0, val: true });
}
const p = new Promise((resolve, reject) => {
debugUnit('[%d] sending add client command, clientId %d...', senderId ?? this.senderId, clientId ?? this.clientId);
const _timeout = setTimeoutSync(() => {
reject(new Error('time out waiting for add client response'));
}, this.netTimeout);
this.once('addClient', (clientAck) => {
debugUnit('received addClient event');
clearTimeout(_timeout);
this._hasAddedClient = true;
resolve(clientAck);
});
const msg = this.controller.connection.sendAddClientMessage(clientId, senderId);
this.toLogEmit(msg, 'out');
});
return Promise.resolve(p) as Promise<SLSimpleBoolData>;
}
async removeClientAsync(clientId?: number, senderId?: number): Promise<SLSimpleBoolData> {
if (this._isMock) {
return Promise.resolve({ senderId: senderId ?? 0, val: true });
}
const p = new Promise((resolve, reject) => {
try {
debugUnit(`[${senderId ?? this.senderId}] sending remove client command, clientId ${clientId ?? this.clientId}...`,);
const _timeout = setTimeoutSync(() => {
reject(new Error('time out waiting for remove client response'));
}, this.netTimeout);
this.once('removeClient', (clientAck) => {
debugUnit('received removeClient event');
clearTimeout(_timeout);
this._hasAddedClient = false;
resolve(clientAck);
});
const msg = this.controller.connection.sendRemoveClientMessage(clientId, senderId);
this.toLogEmit(msg, 'out');
} catch (error) {
debugUnit(`caught remove client error ${error.message}, rethrowing...`);
throw error;
}
});
return Promise.resolve(p) as Promise<SLSimpleBoolData>;
}
async pingServerAsync(senderId?: number): Promise<SLSimpleBoolData> {
const p = new Promise((resolve, reject) => {
debugUnit('[%d] pinging server', senderId ?? this.senderId);
const _timeout = setTimeoutSync(() => {
reject(new Error('time out waiting for ping server response'));
}, this.netTimeout);
this.once('pong', (pong) => {
debugUnit('received pong event');
clearTimeout(_timeout);
resolve(pong);
});
const msg = this.controller.connection.sendPingMessage(senderId);
this.toLogEmit(msg, 'out');
});
return Promise.resolve(p) as Promise<SLSimpleBoolData>;
}
onClientMessage(msg: Inbound) {
debugUnit(`received ${msg.action} message of length ${msg.length}`);
switch (msg.action) {
case ConnectionMessage.ResponseIDs.Challenge:
debugUnit(' it is a challenge response');
this.emit('challengeString', ConnectionMessage.decodeChallengeResponse(msg));
break;
case ConnectionMessage.ResponseIDs.Login:
debugUnit(' it is a login response');
this.emit('loggedIn');
break;
case ConnectionMessage.ResponseIDs.LoginFailure:
debugUnit(' it is a login failure');
this.emit('loginFailed');
break;
case EquipmentStateMessage.ResponseIDs.AsyncEquipmentState:
case EquipmentStateMessage.ResponseIDs.EquipmentState:
debugUnit(' it is pool status');
this.emit('equipmentState', EquipmentStateMessage.decodeEquipmentStateResponse(msg));
break;
case CircuitMessage.ResponseIDs.SetCircuitInfo:
debugUnit(' it is set circuit info');
this.emit('circuit', CircuitMessage.decodeSetCircuit(msg));
break;
case ConnectionMessage.ResponseIDs.Version:
debugUnit(' it is version');
this.emit('version', ConnectionMessage.decodeVersionResponse(msg));
break;
case ChlorMessage.ResponseIDs.GetIntellichlorConfig:
debugUnit(' it is salt cell config');
this.emit('intellichlorConfig', ChlorMessage.decodeIntellichlorConfig(msg));
break;
case EquipmentConfigurationMessage.ResponseIDs.GetCircuitDefinitions:
debugUnit(' it is a get circuit definitions answer');
this.emit('circuitDefinitions', EquipmentConfigurationMessage.decodeCircuitDefinitions(msg));
break;
case EquipmentConfigurationMessage.ResponseIDs.NumCircuitNames:
debugUnit(' it is get circuit names answer');
this.emit('nCircuitNames', EquipmentConfigurationMessage.decodeNCircuitNames(msg));
break;
case EquipmentConfigurationMessage.ResponseIDs.AsyncCircuitNames:
case EquipmentConfigurationMessage.ResponseIDs.GetCircuitNames:
debugUnit(' it is get circuit names answer');
this.emit('circuitNames', EquipmentConfigurationMessage.decodeCircuitNames(msg));
break;
case EquipmentConfigurationMessage.ResponseIDs.GetControllerConfig:
debugUnit(' it is controller configuration');
this.emit('controllerConfig', EquipmentConfigurationMessage.decodeControllerConfig(msg));
break;
case ChemMessage.ResponseIDs.AsyncChemicalData:
case ChemMessage.ResponseIDs.GetChemicalData:
debugUnit(' it is chem data');
this.emit('chemicalData', ChemMessage.decodeChemDataMessage(msg));
break;
case EquipmentStateMessage.ResponseIDs.SystemTime:
debugUnit(' it is system time');
this.emit('getSystemTime', EquipmentStateMessage.decodeSystemTime(msg));
break;
case ScheduleMessage.ResponseIDs.GetSchedule:
debugUnit(' it is schedule data');
this.emit('getScheduleData', ScheduleMessage.decodeGetScheduleMessage(msg));
break;
case EquipmentStateMessage.ResponseIDs.CancelDelay:
debugUnit(' it is a cancel delay ack');
this.emit('cancelDelay', EquipmentStateMessage.decodeCancelDelay(msg));
break;
case ConnectionMessage.ResponseIDs.AddClient:
debugUnit(' it is an add client ack');
this.emit('addClient', ConnectionMessage.decodeAddClient(msg));
break;
case ConnectionMessage.ResponseIDs.RemoveClient:
debugUnit(' it is a remove client ack');
this.emit('removeClient', ConnectionMessage.decodeRemoveClient(msg));
break;
case ConnectionMessage.ResponseIDs.Ping:
debugUnit(' it is a pong');
this.emit('pong', ConnectionMessage.decodePingClient(msg));
break;
case EquipmentConfigurationMessage.ResponseIDs.GetEquipmentConfiguration:
debugUnit(' it is a get equipment configuration');
this.emit('equipmentConfiguration', EquipmentConfigurationMessage.decodeGetEquipmentConfiguration(msg));
break;
case EquipmentConfigurationMessage.ResponseIDs.SetEquipmentConfiguration:
debugUnit(' it is a SET equipment configuration');
this.emit('setEquipmentConfiguration', EquipmentConfigurationMessage.decodeSetEquipmentConfiguration(msg));
break;
case EquipmentConfigurationMessage.ResponseIDs.SetEquipmentConfigurationAck:
debugUnit(' it is a SET equipment configuration ack');
this.emit('setEquipmentConfigurationAck', EquipmentConfigurationMessage.decodeSetEquipmentConfigurationAck(msg));
break;
case PumpMessage.ResponseIDs.PumpStatus:
debugUnit(' it is pump status');
this.emit('getPumpStatus', PumpMessage.decodePumpStatus(msg));
break;
case EquipmentConfigurationMessage.ResponseIDs.WeatherForecastAck:
debugUnit(' it is a weather forecast ack');
this.emit('weatherForecast', EquipmentConfigurationMessage.decodeWeatherMessage(msg));
break;
case CircuitMessage.ResponseIDs.SetCircuitState:
debugUnit(' it is circuit toggle ack');
this.emit('circuitStateChanged', CircuitMessage.decodeSetCircuitState(msg));
break;
case HeaterMessage.ResponseIDs.SetHeatSetPoint:
debugUnit(' it is a setpoint ack');
this.emit('setPointChanged', HeaterMessage.decodeSetHeatSetPoint(msg));
break;
case HeaterMessage.ResponseIDs.SetCoolSetPoint:
debugUnit(' it is a cool setpoint ack');
this.emit('coolSetPointChanged', HeaterMessage.decodeCoolSetHeatSetPoint(msg));
break;
case HeaterMessage.ResponseIDs.SetHeatMode:
debugUnit(' it is a heater mode ack');
this.emit('heatModeChanged', HeaterMessage.decodeSetHeatModePoint(msg));
break;
case CircuitMessage.ResponseIDs.SetLightState:
debugUnit(' it is a light control ack');
this.emit('sentLightCommand', CircuitMessage.decodeSetLight(msg));
break;
case CircuitMessage.ResponseIDs.LightSequence: // ~16-20s sequence intellibrite light theme
debugUnit(' it is a light sequence delay packet');
this.emit('intellibriteDelay', 1);
break;
case ChlorMessage.ResponseIDs.SetIntellichlorEnabled:
debugUnit(' it is a set salt cell isActive ack');
this.emit('intellichlorIsActive', ChlorMessage.decodeSetEnableIntellichlorConfig(msg));
break;
case ChlorMessage.ResponseIDs.SetIntellichlorConfig:
debugUnit(' it is a set salt cell config ack');
this.emit('setIntellichlorConfig', ChlorMessage.decodeSetIntellichlorConfig(msg));
break;
case ScheduleMessage.ResponseIDs.AddSchedule:
debugUnit(' it is a new schedule event ack');
this.emit('addNewScheduleEvent', ScheduleMessage.decodeAddSchedule(msg));
break;
case ScheduleMessage.ResponseIDs.DeleteSchedule:
debugUnit(' it is a delete schedule event ack');
this.emit('deleteScheduleEventById', ScheduleMessage.decodeDeleteSchedule(msg));
break;
case ScheduleMessage.ResponseIDs.SetSchedule:
debugUnit(' it is a set schedule event ack');
this.emit('setScheduleEventById', ScheduleMessage.decodeSetSchedule(msg));
break;
case CircuitMessage.ResponseIDs.SetCircuitRunTime:
debugUnit(' it is a set circuit runtime ack');
this.emit('setCircuitRuntimebyId', CircuitMessage.decodeSetCircuitRunTime(msg));
break;
case EquipmentConfigurationMessage.ResponseIDs.GetCustomNamesAck:
debugUnit(' it is a get custom names packet');
this.emit('getCustomNames', EquipmentConfigurationMessage.decodeCustomNames(msg));
break;
case EquipmentConfigurationMessage.ResponseIDs.SetCustomNameAck:
debugUnit(' it is a set custom names packet');
this.emit('setCustomName', EquipmentConfigurationMessage.decodeSetCustomNameAck(msg));
break;
case PumpMessage.ResponseIDs.SetPumpSpeed:
debugUnit(' it is a set pump flow ack');
this.emit('setPumpSpeed', PumpMessage.decodeSetPumpSpeed(msg));
break;
// ------------ ASYNC MESSAGES --------------- //
case EquipmentStateMessage.ResponseIDs.SetSystemTime:
debugUnit(' it is a set system time ack');
this.emit('setSystemTime', EquipmentStateMessage.decodeSetSystemTime(msg));
break;
case EquipmentConfigurationMessage.ResponseIDs.HistoryDataPending:
debugUnit(' it is a history data query ack');
this.emit('getHistoryDataPending');
break;
case EquipmentConfigurationMessage.ResponseIDs.GetHistoryData:
debugUnit(' it is a history data payload');
this.emit('getHistoryData', EquipmentConfigurationMessage.decodeGetHistory(msg));
break;
case ChemMessage.ResponseIDs.HistoryDataPending:
debugUnit(' it is a chem history data query ack');
this.emit('getChemHistoryDataPending');
break;
case ChemMessage.ResponseIDs.ChemicalHistoryData:
debugUnit(' it is a chem history data payload');
this.emit('getChemHistoryData', ChemMessage.decodecChemHistoryMessage(msg));
break;
// misc
case EquipmentConfigurationMessage.ResponseIDs.WeatherForecastChanged:
debugUnit(' it is a \'weather forecast changed\' notification');
this.emit('weatherForecastChanged');
break;
case ScheduleMessage.ResponseIDs.ScheduleChanged:
debugUnit(' it is a schedule changed notification');
this.emit('scheduleChanged');
break;
case ConnectionMessage.ResponseIDs.UnknownCommand:
debugUnit(' it is an unknown command.');
this.emit('unknownCommand');
break;
case ConnectionMessage.ResponseIDs.BadParameter:
debugUnit(' it is a parameter failure.');
this.emit('badParameter');
break;
default:
EquipmentStateMessage.decodeGeneric(msg);