-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
1097 lines (1044 loc) · 34.9 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
"use strict";
const {
poolSpaInfo,
bodyMap,
heaterModes,
clientInt,
commonCircuitMap,
heaterStatus,
rawObjects,
scheduleTypeMap,
pumpsSenderBase,
schedulesSenderBase,
} = require("./constants");
const express = require("express");
const app = express();
// const bodyParser = require('body-parser');
const expressPort = process.env.PORT || 3000;
const ScreenLogic = require("node-screenlogic");
const predictSchedId = require("./predictSchedIds");
const nextSchedId = predictSchedId.predictSchedId;
const cors = require("cors");
app.use(cors());
// app.use(express.json());
// defaulting to 5 second poll intervals.
// Override with POLL_INTERVAL environment variable.
// This is now deprecated as I am using the addClient API.
// const pollInterval = process.env.POLL_INTERVAL || 5000; //5000 = 5 sec
var activeScheduleIds = new Set();
var scheduleIdDeleteQueue = new Set();
var scheduleIdAddQueue = new Set();
// New poll skipping mechanism is in place, but we want to only allow a max number to be skipped...
// Override with MAX_POLL_SKIP environment variable.
const baseApiPath = process.env.BASE_PATH || "/api";
// Read other Configs from the Environment
let slIpAddress = process.env.SL_IP_ADDRESS || null;
let slPort = process.env.SL_PORT || 80;
let slName = process.env.SL_NAME || null;
const featuresInterface = process.env.FEATURES_LOCATION || "features";
function findScreenLogic() {
if (slIpAddress && slPort) {
// console.log(server)
// console.log(connection);
console.log("Got Screenlogic IP address and Port from the Environment.");
poolSpaInfo.meta.server = {
ipAddress: slIpAddress,
port: slPort,
name: slName,
};
if (slName) {
poolSpaInfo.meta.server.name = slName;
}
} else {
const finder = new ScreenLogic.FindUnits();
finder.search();
finder.on("serverFound", function (server) {
console.log(
"Found ScreenLogic unit at: " + server.address + ":" + server.port
);
slIpAddress = server.address;
slPort = server.port;
slName = server.gatewayName;
poolSpaInfo.meta.server = {
ipAddress: server.address,
port: server.port,
name: server.gatewayName,
};
finder.close();
});
}
}
function getSlClient(port = slPort, ipAddress = slIpAddress) {
return new ScreenLogic.UnitConnection(port, ipAddress);
}
function setHeatMode(body, heatMode) {
// Body: pool = 0; spa = 1
// heatMode: 0: "Off", 1: "Solar", 2 : "Solar Preferred", 3 : "Heat Pump", 4: "Don't Change"
const client = getSlClient();
const heatBody = bodyMap[body];
client
.on("loggedIn", function () {
console.log(
"Logged in, setting heater state for " +
heatBody +
" to " +
heaterModes[heatMode]
);
this.setHeatMode(clientInt, body, heatMode);
})
.on("heatModeChanged", function () {
console.log(
"Changed " + heatBody + " heater state to " + heaterModes[heatMode]
);
client.close();
// setTimeout(function () {
// // getAllPoolSpaInfo();
// }, 10000);
})
.on("loginFailed", function () {
console.log("Unable to login... refreshing client.");
client.close();
});
client.connect();
}
function setHeatSetPoint(body, temp) {
const client = getSlClient();
const heatBody = bodyMap[body];
console.log(
"Setting heater setpoint for " + heatBody + " to " + temp + " degrees."
);
client
.on("loggedIn", function () {
console.log("Logged in...");
this.setSetPoint(clientInt, body, temp);
})
.on("setPointChanged", function () {
console.log(heatBody + " setpoint Successfully changed to " + temp);
client.close();
setTimeout(function () {
// getAllPoolSpaInfo();
}, 10000);
})
.on("loginFailed", function () {
console.log("Unable to login...");
client.close();
});
client.connect();
}
function setNewCircuitState(circuitId, state) {
const client = getSlClient();
console.log(
"Invoking change state with state = " +
state +
" and circuit ID = " +
circuitId
);
client
.on("loggedIn", function () {
console.log(
"Logged in, sending state " + state + " to circuit ID " + circuitId
);
this.setCircuitState(clientInt, circuitId, state);
})
.on("circuitStateChanged", function () {
const newState = state === 0 ? "off" : "on";
console.log(`Circuit ${circuitId} set to ${newState}.`);
client.close();
// setTimeout(function() {
// getAllPoolSpaInfo();
// }, 10000);
})
.on("loginFailed", function () {
console.log("Unable to login...refreshing client.");
client.close();
findScreenLogic();
});
client.connect();
}
function getAllPoolSpaInfo() {
const client = getSlClient();
const pollTime = Date.now();
console.log("Poll for full ScreenLogic update at " + pollTime);
client
.on("loggedIn", function () {
console.log("Logged In...");
if (!poolSpaInfo.meta.server.name) {
poolSpaInfo.meta.server.name =
"Pentair: " + client.challengeString.substr(9);
}
this.getVersion();
this.getPoolStatus();
this.getSaltCellConfig();
this.getControllerConfig();
var i;
for (i = 0; i < 8; i++) {
console.log("Pump ID: " + i);
var pumpSid = pumpsSenderBase + i;
console.log("Pump SenderID: " + pumpSid);
this.getPumpStatus(i, pumpSid);
}
for (i = 0; i < 2; i++) {
var scheduleSid = schedulesSenderBase + i;
console.log("Requesting Schedule Type: " + scheduleTypeMap[i]);
console.log("Schedule SenderID: " + scheduleSid);
this.getScheduleData(i, scheduleSid);
}
this.getChemicalData();
})
.on("version", function (version) {
console.log("Got Version " + version);
poolSpaInfo.firmware = {
version: version.version,
};
// console.log(' version=' + version.version);
})
.on("poolStatus", function (status) {
poolSpaInfo.meta.airTemp = status.airTemp;
poolSpaInfo.meta.activeAlarms = status.alarms;
poolSpaInfo.meta.serviceMode = status.isDeviceServiceMode();
poolSpaInfo.meta.freezeMode = status.freezeMode;
poolSpaInfo.meta.cleanerDelay = status.cleanerDelay;
poolSpaInfo.meta.heaterActive = status.heatStatus[0] > 0 || status.heatStatus[1] > 0
let poolActive = false;
try {
poolActive = status.isPoolActive();
} catch (e) {
// ignore
}
let spaActive = false;
try {
spaActive = status.isSpaActive();
} catch (e) {
// ignore
}
poolSpaInfo.status = {
bodies: [
{
name: "pool",
circuitId: commonCircuitMap.pool,
interfaceId: 0,
altInterfaceId: featuresInterface.toLowerCase() === "pool" ? 2 : 0,
waterTemp: status.currentTemp[0],
active: poolActive,
airTemp: status.airTemp,
heater: {
equipPresent: {},
modeCode: status.heatMode[0],
mode: heaterModes[status.heatMode[0]],
active: status.heatStatus[0] > 0,
activeCode: status.heatStatus[0],
activeType: heaterStatus[status.heatStatus[0]],
setpoint: {
current: status.setPoint[0],
},
},
},
{
name: "spa",
circuitId: commonCircuitMap.spa,
interfaceId: 1,
altInterfaceId: featuresInterface.toLowerCase() === "spa" ? 2 : 1,
waterTemp: status.currentTemp[1],
active: spaActive,
airTemp: status.airTemp,
heater: {
equipPresent: {},
modeCode: status.heatMode[1],
mode: heaterModes[status.heatMode[1]],
active: status.heatStatus[1] > 0,
activeCode: status.heatStatus[1],
activeType: heaterStatus[status.heatStatus[1]],
setpoint: {
current: status.setPoint[1],
},
},
},
],
device: {
currentStatus: status.ok,
ready: status.isDeviceReady(),
sync: status.isDeviceSync(),
activeAlarms: status.alarms,
serviceMode: status.isDeviceServiceMode(),
freezeMode: status.freezeMode,
},
chemistry: {
saltPPM: status.saltPPM,
ph: status.pH,
calciumSaturation: status.saturation,
},
circuits: status.circuitArray,
};
rawObjects.status = status;
})
.on("saltCellConfig", function (saltCellConfig) {
poolSpaInfo.saltCell = {
installed: saltCellConfig.installed,
status: saltCellConfig.status,
saltLevel: saltCellConfig.salt,
};
rawObjects.saltCellConfig = saltCellConfig;
})
.on("controllerConfig", function (config) {
poolSpaInfo.meta.tempInCelcius = config.degC;
poolSpaInfo.controllerConfig = {
tempInCelcius: config.degC,
tempScale: config.degC ? "C" : "F",
pumps: config.pumpCircArray,
bodyArray: config.bodyArray,
controllerId: config.controllerId,
poolMinSetPoint: config.minSetPoint[0],
poolMaxSetPoint: config.maxSetPoint[0],
spaMinSetPoint: config.minSetPoint[1],
spaMaxSetPoint: config.maxSetPoint[1],
interfaceTabFlags: config.interfaceTabFlags,
equipFlags: config.equipFlags,
};
poolSpaInfo.controllerConfig.equipPresent = {
heater: true,
solar: config.hasSolar(),
solarisheater: config.hasSolarAsHeatpump(),
chlorinator: config.hasChlorinator(),
cooler: config.hasCooling(),
intellichem: config.hasIntellichem(),
isEasyTouch: config.isEasyTouch(),
isIntelliTouch: config.isIntelliTouch(),
isEasyTouchLite: config.isEasyTouchLite(),
isDualBody: config.isDualBody(),
isChem2: config.isChem2()
}
poolSpaInfo.chemistry.intellichemInstalled = config.hasIntellichem();
poolSpaInfo.status.bodies.forEach(function (v, i) {
v.heater.equipPresent.heater =
poolSpaInfo.controllerConfig.equipPresent.heater;
v.heater.equipPresent.solar =
poolSpaInfo.controllerConfig.equipPresent.solar;
v.heater.equipPresent.solarisheater =
poolSpaInfo.controllerConfig.equipPresent.solarisheater;
v.heater.equipPresent.cooler =
poolSpaInfo.controllerConfig.equipPresent.cooler;
v.tempScale = config.degC ? "C" : "F";
v.heater.setpoint.min = config.minSetPoint[i];
v.heater.setpoint.max = config.maxSetPoint[i];
});
poolSpaInfo.meta.tempScale = config.degC ? "C" : "F";
rawObjects.config = config;
poolSpaInfo.controllerConfig.bodyArray.forEach((c) => {
poolSpaInfo.status.circuits.forEach((z) => {
if (c.circuitId === z.id) {
// console.log(c.circuitId)
c.state = z.state;
c.delay = z.delay;
if (z.state === 0) {
c.active = false;
} else if (z.state === 1) {
c.active = true;
}
}
});
if (c.name === "Lights") {
// console.log(c.name)
// console.log(Object.keys(c))
poolSpaInfo.meta.lightsOn = c.active;
}
});
})
.on("getPumpStatus", function (pumpData) {
var pumpId = pumpData.senderId - pumpsSenderBase;
console.log("Got Pump Status for senderID " + pumpData.senderId);
var pumpTypeName = "Unknown Pump Type";
if (pumpData.pumpType === ScreenLogic.PUMP_TYPE_INTELLIFLOVF) {
pumpTypeName = "IntelliFlo VF";
} else if (pumpData.pumpType === ScreenLogic.PUMP_TYPE_INTELLIFLOVS) {
pumpTypeName = "IntelliFlo VFS";
} else if (pumpData.pumpType === ScreenLogic.PUMP_TYPE_INTELLIFLOVSF) {
pumpTypeName = "IntelliFlo VS";
}
console.log(pumpTypeName);
rawObjects.pumps = {
[pumpId]: pumpData,
};
var pumpApiData = {
pumpSetting: pumpData.pumpSetting,
pumpType: pumpData.pumpType,
isRunning: pumpData.isRunning,
pumpTypeName: pumpTypeName,
pumpWatts: pumpData.pumpWatts,
pumpRPMs: pumpData.pumpRPMs,
pumpGPMs: pumpData.pumpGPMS,
pumpUnknown1: pumpData.pumpUnknown1,
pumpUnknown2: pumpData.pumpUnknown2,
};
poolSpaInfo.status.pumps = {
[pumpId.toString()]: pumpApiData,
};
})
.on("getScheduleData", function (schedules) {
console.log("Schedule return SenderID: " + schedules.senderId);
var scheduleType = schedules.senderId - schedulesSenderBase;
console.log(scheduleType);
var scheduleTypeName = scheduleTypeMap[scheduleType];
console.log(scheduleTypeName);
poolSpaInfo.schedules[scheduleTypeName] = schedules.events;
aggregateScheduleIds();
})
.on("chemicalData", function (chemData) {
poolSpaInfo.chemistry = {
info: "This data only valid if IntelliChem in installed",
isValid: chemData.isValid,
error: chemData.error,
calciumLSI: chemData.calcium,
cyanuric: chemData.cyanuricAcid,
alkalinity: chemData.alkalinity,
};
rawObjects.chemData = chemData;
poolSpaInfo.meta.lastUpdated = pollTime;
rawObjects.meta.lastUpdated = pollTime;
//connection cleanup
if (!poolSpaInfo.meta.successfulPolling) {
console.log("Initial State Data loaded from ScreenLogic.");
// console.log('\n')
// console.log(poolSpaInfo)
// console.log('\n')
}
poolSpaInfo.meta.successfulPolling = true;
// console.log('Info Refreshed')
client.close();
})
.on("loginFailed", function () {
//Handle login failure
console.log("Unable to login...refreshing client.");
client.close();
findScreenLogic();
});
client.connect();
// getAllSchedules(client);
}
// exports.poolSpaInfo = poolSpaInfo;
function poolSpaChangeListener() {
const client = getSlClient();
client
.on("loggedIn", function () {
console.log("Listener logged In...");
//set up Listeners...
this.addClient(1234);
this.getPoolStatus();
})
.on("poolStatus", function (status) {
console.log("Got async poolStatus event...");
// console.log(status);
// console.log('Service Mode?');
// console.log(status.isDeviceServiceMode());
poolSpaInfo.meta.airTemp = status.airTemp;
poolSpaInfo.meta.activeAlarms = status.alarms;
poolSpaInfo.meta.serviceMode = status.isDeviceServiceMode();
poolSpaInfo.meta.freezeMode = status.freezeMode;
poolSpaInfo.meta.cleanerDelay = status.cleanerDelay;
let poolActive = false;
try {
poolActive = status.isPoolActive();
} catch (e) {
// ignore
}
let spaActive = false;
try {
spaActive = status.isSpaActive();
} catch (e) {
// ignore
}
// update pool info...
poolSpaInfo.status.bodies[0].waterTemp = status.currentTemp[0];
poolSpaInfo.status.bodies[0].active = poolActive;
poolSpaInfo.status.bodies[0].airTemp = status.airTemp;
poolSpaInfo.status.bodies[0].heater.modeCode = status.heatMode[0];
poolSpaInfo.status.bodies[0].heater.mode =
heaterModes[status.heatMode[0]];
poolSpaInfo.status.bodies[0].heater.active = status.heatStatus[0] > 0;
poolSpaInfo.status.bodies[0].heater.activeCode = status.heatStatus[0];
poolSpaInfo.status.bodies[0].heater.activeType =
heaterStatus[status.heatStatus[0]];
poolSpaInfo.status.bodies[0].heater.setpoint.current = status.setPoint[0];
// update spa info
poolSpaInfo.status.bodies[1].waterTemp = status.currentTemp[1];
poolSpaInfo.status.bodies[1].active = spaActive;
poolSpaInfo.status.bodies[1].airTemp = status.airTemp;
poolSpaInfo.status.bodies[1].heater.modeCode = status.heatMode[1];
poolSpaInfo.status.bodies[1].heater.mode =
heaterModes[status.heatMode[1]];
poolSpaInfo.status.bodies[1].heater.active = status.heatStatus[1] > 0;
poolSpaInfo.status.bodies[1].heater.activeCode = status.heatStatus[1];
poolSpaInfo.status.bodies[1].heater.activeType =
heaterStatus[status.heatStatus[1]];
poolSpaInfo.status.bodies[1].heater.setpoint.current = status.setPoint[1];
//update device status
poolSpaInfo.status.device.currentStatus = status.ok;
poolSpaInfo.status.device.ready = status.isDeviceReady();
poolSpaInfo.status.device.sync = status.isDeviceSync();
poolSpaInfo.status.device.activeAlarms = status.alarms;
poolSpaInfo.status.device.serviceMode = status.isDeviceServiceMode();
poolSpaInfo.status.device.freezeMode = status.freezeMode;
// update chemistry
poolSpaInfo.status.chemistry.saltPPM = status.saltPPM;
poolSpaInfo.status.chemistry.ph = status.pH;
poolSpaInfo.status.chemistry.calciumSaturation = status.saturation;
})
.on("loginFailed", function () {
//Handle login failure
console.log("Unable to login...refreshing client.");
client.close();
findScreenLogic();
// poolSpaChangeListener();
});
client.connect();
// getAllSchedules(client);
}
function setPoolModeOn() {
setNewCircuitState(505, 1);
}
function setPoolModeOff() {
setNewCircuitState(505, 0);
}
function setSpaModeOn() {
setNewCircuitState(500, 1);
}
function setSpaModeOff() {
setNewCircuitState(500, 0);
}
function lightFunction(message) {
const client = getSlClient();
client
.on("loggedIn", function () {
console.log("Logged in");
this.sendLightCommand(clientInt, message);
console.log("Light Command sent");
})
.on("sentLightCommand", function () {
console.log("Light Command Acknowledged");
client.close();
// setTimeout(function () {
// getAllPoolSpaInfo();
// }, 10000);
})
.on("loginFailed", function () {
console.log("Unable to login... refreshing client.");
client.close();
// findScreenLogic();
});
client.connect();
}
// Pump Info
// function getPumpStatus(pumpId, initial = true){
// // const pumps = poolSpaInfo.controllerConfig.pumps
// // console.log(pumpId)
// const client = getSlClient();
// client.on("loggedIn", function (){
// if(!initial){
// this.addClient(1240 + pumpId);
// }
// console.log('Pump Status Poll...')
// this.getPumpStatus(pumpId);
// })
// .on('getPumpStatus', function(pumpData){
// console.log('Got Pump Status')
// var pumpTypeName = "Unknown Pump Type";
// if(pumpData.pumpType === ScreenLogic.PUMP_TYPE_INTELLIFLOVF){
// pumpTypeName = "IntelliFlo VF"
// } else if (pumpData.pumpType === ScreenLogic.PUMP_TYPE_INTELLIFLOVS){
// pumpTypeName = "IntelliFlo VFS"
// } else if (pumpData.pumpType === ScreenLogic.PUMP_TYPE_INTELLIFLOVSF){
// pumpTypeName = "IntelliFlo VS"
// };
// console.log(pumpTypeName);
// rawObjects.pumps = {
// [pumpId] : pumpData
// };
// poolSpaInfo.status.pumps = {
// [pumpId] : {
// pumpSetting : pumpData.pumpSetting,
// pumpType: pumpData.pumpType,
// isRunning: pumpData.isRunning,
// pumpTypeName: pumpTypeName,
// pumpWatts: pumpData.pumpWatts,
// pumpRPMs: pumpData.pumpRPMs,
// pumpGPMs: pumpData.pumpGPMS,
// pumpUnknown1: pumpData.pumpUnknown1,
// pumpUnknown2: pumpData.pumpUnknown2
// }
// };
// // console.log(poolSpaInfo.status.pumps);
// if(initial){
// client.close();
// }
// })
// client.connect();
// }
// Schedule support
// At some point in the future, when I get good at node.js, I'll refactor...
// function getAllSchedules(scheduleType, initial = true) {
// const client = getSlClient();
// var scheduleTypeName = scheduleTypeMap[scheduleType];
// client
// .on("loggedIn", function () {
// if(!initial){
// this.addClient(1300 + scheduleType);
// }
// this.getScheduleData(scheduleType);
// if(initial){
// console.log('Poll for ' + scheduleTypeName)
// }
// })
// .on("getScheduleData", function (schedules) {
// console.log("Getting schedule info...");
// poolSpaInfo.schedules[scheduleTypeName] = schedules.events;
// aggregateScheduleIds();
// if(initial){
// client.close();
// }
// })
// .on("loginFailed", function () {
// console.log("Unable to login...");
// client.close();
// });
// client.connect();
// };
function aggregateScheduleIds() {
const schedulesKeys = ["daily", "runOnce"];
var currentSchedIds = new Set();
schedulesKeys.forEach(function (key, i) {
poolSpaInfo.schedules[key].forEach(function (e, i) {
if (e.scheduleId) {
currentSchedIds.add(e.scheduleId);
}
});
});
activeScheduleIds = currentSchedIds;
poolSpaInfo.schedules.eventIds = Array.from(activeScheduleIds);
console.log("Active Schedule IDS: ");
console.log(activeScheduleIds);
// return;
}
// Express.js endpoint logic below this line
// --------------------------------
const error503Object = {
code: "503",
message:
"Server has not completed its initial data load... please try again in a moment.",
};
app.listen(expressPort, function () {
if (slIpAddress && slPort) {
console.log(
"Connecting to ScreenLogic at " +
slIpAddress +
" on port " +
slPort +
"..."
);
} else {
console.log("Finding Screenlogic Units...");
}
findScreenLogic();
// console.log(
// "Pool data update interval is " + pollInterval / 1000 + " seconds."
// );
//This fixes the startup, but a one second delay is silly, this should be event driven...
//Initial Call
setTimeout(function () {
getAllPoolSpaInfo();
}, 1000);
setTimeout(function () {
poolSpaChangeListener();
}, 5000);
setInterval(function () {
getAllPoolSpaInfo();
// poolSpaChangeListener();
}, 60000);
// aggregateScheduleIds();
// setInterval(function () {
// console.log('Polling...')
// poolSpaInfo.meta.skippedPolls = 0;
// } else {
// console.log('Poll already Scheduled...skipping this polling loop.')
// poolSpaInfo.meta.skippedPolls++;
// console.log("Skipped " + poolSpaInfo.meta.skippedPolls + " polling loops...")
// if(poolSpaInfo.meta.skippedPolls >= maxPollSkip){
// console.log('Max Skipped polls reached, forcing poll on next cycle...')
// poolSpaInfo.meta.skippedPolls = 0;
// }
// }
// }, pollInterval);
console.log("Express server listening on port " + expressPort);
});
app.get("/health", function (req, res) {
const response = {
healthy: poolSpaInfo.meta.successfulPolling,
};
res.json(response);
console.log("Returned " + req.method + " " + req.route.path);
});
app.get(baseApiPath + "/all", function (req, res) {
if (poolSpaInfo.meta.successfulPolling) {
res.json(poolSpaInfo);
console.log("Returned " + req.method + " " + req.route.path);
} else {
res.json(error503Object);
}
});
app.get(baseApiPath + "/raw", function (req, res) {
console.log(req.ip);
// console.log('All Pool Info: ' + poolSpaInfo);
res.json(rawObjects);
console.log("Returned " + req.method + " " + req.route.path);
});
app.put(baseApiPath + "/pool/on", function (req, res) {
console.log(req.ip);
setPoolModeOn();
const response = {
body: "pool",
action: "turn on",
sent: true,
};
console.log("Sent poolOn to ScreenLogic");
res.json(response);
console.log("Returned " + req.method + " " + req.route.path);
});
app.put(baseApiPath + "/pool/off", function (req, res) {
console.log(req.ip);
setPoolModeOff();
var response = {
body: "pool",
action: "off",
sent: true,
};
console.log("Sent poolOff to ScreenLogic");
res.json(response);
console.log("Returned " + req.method + " " + req.route.path);
});
app.put(baseApiPath + "/spa/on", function (req, res) {
console.log(req.ip);
setSpaModeOn();
var response = {
body: "spa",
action: "on",
sent: true,
};
console.log("Sent spaOn to ScreenLogic");
res.json(response);
console.log("Returned " + req.method + " " + req.route.path);
return;
});
app.put(baseApiPath + "/spa/off", function (req, res) {
console.log(req.ip);
setSpaModeOff();
const response = {
body: "spa",
action: "off",
sent: true,
};
console.log("Sent spaOff to ScreenLogic");
res.json(response);
console.log("Returned " + req.method + " " + req.route.path);
});
app.put(baseApiPath + "/lights/:command", function (req, res) {
// console.log(req.params.command)
console.log('Got PUT command for lights: ' + req.params.command)
if(!req.params.command || req.params.command < 0 || req.params.command > 17){
res
.status(406)
.send(
'{"Error" : "The format of this request is ../lights/<command>. Command should be an integer between 0 and and 17, which corresponds to the various light commands available. Please see documentation for lights."}'
);
return;
}
lightFunction(req.params.command);
const response = {
lightCommand: req.params.command,
};
res.status(200).send(response);
});
app.put(baseApiPath + "/circuit/:circuit/:state", function (req, res) {
console.log(req.ip);
console.log(req.params);
const changeCircuit = parseInt(req.params.circuit);
let stateInt = null;
if (!req.params.circuit || !req.params.state) {
res
.status(406)
.send(
'{"Error" : "The format of this request is /api/v1/circuit/<circuitNumber>/<state>. Circuit should be the number of the circuit, an integer between 500 and 600. State should be 0 (off) or 1 (on)."}'
);
return;
}
if (req.params.state.toUpperCase() === "ON" || req.params.state === "1") {
stateInt = 1;
} else if (
req.params.state.toUpperCase() === "OFF" ||
req.params.state === "0"
) {
stateInt = 0;
} else {
res.status(418).send('{"Error" : "State should be 0 (off) or 1(on)."}');
return;
}
if (req.params.circuit < 500 || req.params.circuit > 599) {
res
.status(418)
.send('{"Error" : "Circuit should be an integer between 500 and 600"}');
return;
}
setNewCircuitState(changeCircuit, stateInt);
const response = {
circuit: changeCircuit,
newState: stateInt,
};
res.status(200).send(response);
console.log("Returned " + req.method + " " + req.route.path);
});
const bodyTypeError = {
code: 418,
message: "Invalid target body",
info: "Valid target bodies are 'pool' or 'spa'",
};
app.put(baseApiPath + "/:body/heater/setpoint/:temp", function (req, res) {
console.log(req.toString());
console.log(req.params);
res.send(req.params);
if (poolSpaInfo.meta.successfulPolling) {
if (req.params.body === "spa" || req.params.body === "pool") {
const targetBody = bodyMap[req.params.body];
const targetTemp = parseInt(req.params.temp);
const maxTemp = parseInt(poolSpaInfo.controllerConfig.spaMaxSetPoint);
const minTemp = parseInt(poolSpaInfo.controllerConfig.spaMinSetPoint);
if (minTemp <= targetTemp && maxTemp >= targetTemp) {
console.log("Valid Setpoint Temperature");
setHeatSetPoint(targetBody, targetTemp);
const response = {
body: req.params.body,
newSetpoint: targetTemp,
success: true,
};
res.json(response);
console.log("Returned " + req.method + " " + req.route.path);
} else {
console.log("Invalid Setpoint Temperature");
var setPointError = {
code: "418",
message: "Setpoint should be between " + minTemp + " and " + maxTemp,
};
res.status(418).send(setPointError);
}
} else {
res.status(418).send(bodyTypeError);
}
} else {
res.status(503).send(error503Object);
}
});
app.put(baseApiPath + "/:body/heater/mode/:mode", function (req, res) {
// heatMode: 0: "Off", 1: "Solar", 2 : "Solar Preferred", 3 : "Heat Pump", 4: "Don't Change"
console.log(req.params);
if (poolSpaInfo.meta.successfulPolling) {
if (req.params.body === "spa" || req.params.body === "pool") {
const targetBody = bodyMap[req.params.body];
const targetHeatMode = parseInt(req.params.mode);
if (targetHeatMode >= 0 && targetHeatMode <= 4) {
setHeatMode(targetBody, targetHeatMode);
const response = {
targetBody: req.params.body,
newHeaterMode: targetHeatMode,
newHeaterModeMeaning: heaterModes[targetHeatMode],
success: true,
};
res.json(response);
console.log("Returned " + req.method + " " + req.route.path);
} else {
const heatModeError = {
code: "418",
message: "Invalid Heat Mode",
"Valid Heat Modes": heaterModes,
};
res.status(418).send(heatModeError);
}
} else {
res.status(418).send(bodyTypeError);
}
} else {
res.status(503).send(error503Object);
}
});
app.get("/connection", function (req, res) {
findScreenLogic();
const slConnection = getSlClient();
res.status(200).json(slConnection);
console.log("Returned " + req.method + " " + req.route.path);
});
// Schedules!
// Need to differentiate between events and run-once events
app.get(baseApiPath + "/schedules", function (req, res) {
console.log("GET /schedules");
// console.log(poolSpaInfo.schedules)
if (poolSpaInfo.meta.successfulPolling) {
res.json(poolSpaInfo.schedules);
console.log("Returned " + req.method + " " + req.route.path);
} else {
res.status(503).send(error503Object);
}
});
app.post(baseApiPath + "/schedules/:type", function (req, res) {
// Schedule Types: 0 = Normal, 1 = Run Once
console.log(req.params);
const newSchedId = nextSchedId(activeScheduleIds);
const newScheduleReturn = {
status: "unknown",
scheduleId: newSchedId,
};
if (poolSpaInfo.meta.successfulPolling) {
if (req.params.type === "0" || req.params.type === "1") {
var scheduleType = parseInt(req.params.type);
const client = getSlClient();
client
.on("loggedIn", function () {
console.log("Logged in...");
setTimeout(function () {
client.addNewScheduleEvent(scheduleType);
}, 5000);
console.log("Sending new event data...");
// client.close();
})
.on("addNewScheduleEvent", function (newScheduleObj) {
client.close();
// getAllPoolSpaInfo();
console.log(newScheduleObj);
newScheduleReturn.status = "success";
newScheduleReturn.scheduleId = newScheduleObj.scheduleId;
console.log("New Schedule Event ID is " + newScheduleObj.scheduleId);
res.status(200).json(newScheduleReturn);
activeScheduleIds.add(newScheduleObj.scheduleId);
});
client.connect();
// newScheduleReturn.status = "success";
// newScheduleReturn.scheduleId = 'poll for new schedule ID';
// res.status(200).json(newScheduleReturn);
// getAllSchedules(0);
// getAllSchedules(1);
// aggregateScheduleIds();
} else {
var invalidSchedTypeRes = {
code: 418,
message: "Invalid Schedule Type",
info: "Valid Schedule types are 0 (Daily) or 1 (Run Once)",
};
res.status(418).send(invalidSchedTypeRes);
}
} else {
res.status(503).send(error503Object);
}
return;
});
//Delete a Schedule
//ToDo: Implement delete queue, as SL cannot be relied on to delete in a timely manner.
app.delete(baseApiPath + "/schedules/:id", function (req, res) {
console.log(req.params);
var scheduleId = Number(req.params.id);
//Check to make sure the schedule ID exists...
if (poolSpaInfo.meta.successfulPolling) {
if (activeScheduleIds.has(scheduleId)) {
scheduleIdDeleteQueue.add(scheduleId);
const client = getSlClient();
client.on("loggedIn", function () {
console.log("Logged in...");