nodejs-poolcontroller 8.1.2 → 8.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/.eslintrc.json +36 -36
  2. package/.github/ISSUE_TEMPLATE/1-bug-report.yml +84 -84
  3. package/.github/ISSUE_TEMPLATE/2-docs.md +12 -12
  4. package/.github/ISSUE_TEMPLATE/3-proposal.md +28 -28
  5. package/.github/ISSUE_TEMPLATE/config.yml +8 -8
  6. package/.github/copilot-instructions.md +63 -0
  7. package/.github/workflows/ghcr-publish.yml +67 -0
  8. package/AGENTS.md +597 -0
  9. package/CONTRIBUTING.md +74 -74
  10. package/Changelog +292 -257
  11. package/Dockerfile +62 -19
  12. package/Gruntfile.js +40 -40
  13. package/LICENSE +661 -661
  14. package/README.md +318 -191
  15. package/anslq25/MessagesMock.ts +221 -221
  16. package/anslq25/boards/MockBoardFactory.ts +49 -49
  17. package/anslq25/boards/MockEasyTouchBoard.ts +696 -696
  18. package/anslq25/boards/MockSystemBoard.ts +216 -216
  19. package/anslq25/chemistry/MockChlorinator.ts +98 -98
  20. package/anslq25/pumps/MockPump.ts +83 -83
  21. package/app.ts +115 -115
  22. package/config/Config.ts +57 -7
  23. package/config/VersionCheck.ts +63 -35
  24. package/controller/Constants.ts +809 -805
  25. package/controller/Equipment.ts +2688 -2664
  26. package/controller/Errors.ts +181 -181
  27. package/controller/Lockouts.ts +549 -549
  28. package/controller/State.ts +3738 -3690
  29. package/controller/boards/AquaLinkBoard.ts +1003 -1003
  30. package/controller/boards/BoardFactory.ts +53 -53
  31. package/controller/boards/EasyTouchBoard.ts +3202 -3202
  32. package/controller/boards/IntelliCenterBoard.ts +4393 -3899
  33. package/controller/boards/IntelliComBoard.ts +69 -69
  34. package/controller/boards/IntelliTouchBoard.ts +382 -382
  35. package/controller/boards/NixieBoard.ts +1944 -1929
  36. package/controller/boards/SunTouchBoard.ts +400 -400
  37. package/controller/boards/SystemBoard.ts +5268 -5268
  38. package/controller/comms/Comms.ts +1272 -1214
  39. package/controller/comms/ScreenLogic.ts +1665 -1665
  40. package/controller/comms/messages/Messages.ts +1433 -1243
  41. package/controller/comms/messages/config/ChlorinatorMessage.ts +5 -0
  42. package/controller/comms/messages/config/CircuitGroupMessage.ts +0 -0
  43. package/controller/comms/messages/config/CircuitMessage.ts +0 -0
  44. package/controller/comms/messages/config/ConfigMessage.ts +6 -0
  45. package/controller/comms/messages/config/CoverMessage.ts +0 -0
  46. package/controller/comms/messages/config/CustomNameMessage.ts +31 -31
  47. package/controller/comms/messages/config/EquipmentMessage.ts +216 -210
  48. package/controller/comms/messages/config/ExternalMessage.ts +96 -10
  49. package/controller/comms/messages/config/FeatureMessage.ts +0 -0
  50. package/controller/comms/messages/config/GeneralMessage.ts +0 -0
  51. package/controller/comms/messages/config/HeaterMessage.ts +0 -0
  52. package/controller/comms/messages/config/IntellichemMessage.ts +0 -0
  53. package/controller/comms/messages/config/OptionsMessage.ts +194 -174
  54. package/controller/comms/messages/config/PumpMessage.ts +0 -0
  55. package/controller/comms/messages/config/RemoteMessage.ts +0 -0
  56. package/controller/comms/messages/config/ScheduleMessage.ts +401 -390
  57. package/controller/comms/messages/config/SecurityMessage.ts +0 -0
  58. package/controller/comms/messages/config/ValveMessage.ts +0 -0
  59. package/controller/comms/messages/status/ChlorinatorStateMessage.ts +0 -0
  60. package/controller/comms/messages/status/EquipmentStateMessage.ts +1158 -822
  61. package/controller/comms/messages/status/HeaterStateMessage.ts +135 -135
  62. package/controller/comms/messages/status/IntelliChemStateMessage.ts +448 -448
  63. package/controller/comms/messages/status/IntelliValveStateMessage.ts +36 -36
  64. package/controller/comms/messages/status/PumpStateMessage.ts +0 -0
  65. package/controller/comms/messages/status/RegalModbusStateMessage.ts +411 -0
  66. package/controller/comms/messages/status/VersionMessage.ts +103 -41
  67. package/controller/nixie/Nixie.ts +173 -173
  68. package/controller/nixie/NixieEquipment.ts +104 -104
  69. package/controller/nixie/bodies/Body.ts +120 -120
  70. package/controller/nixie/bodies/Filter.ts +135 -135
  71. package/controller/nixie/chemistry/ChemController.ts +2724 -2724
  72. package/controller/nixie/chemistry/ChemDoser.ts +806 -806
  73. package/controller/nixie/chemistry/Chlorinator.ts +367 -367
  74. package/controller/nixie/circuits/Circuit.ts +478 -478
  75. package/controller/nixie/heaters/Heater.ts +834 -834
  76. package/controller/nixie/pumps/Pump.ts +1194 -996
  77. package/controller/nixie/schedules/Schedule.ts +401 -401
  78. package/controller/nixie/valves/Valve.ts +170 -170
  79. package/defaultConfig.json +352 -347
  80. package/docker-compose.yml +32 -0
  81. package/logger/DataLogger.ts +448 -448
  82. package/logger/Logger.ts +448 -436
  83. package/package.json +58 -60
  84. package/sendSocket.js +32 -32
  85. package/tsconfig.json +25 -25
  86. package/types/express-multer.d.ts +32 -0
  87. package/web/Server.ts +1937 -1927
  88. package/web/bindings/aqualinkD.json +559 -559
  89. package/web/bindings/influxDB.json +1066 -1066
  90. package/web/bindings/mqtt.json +721 -721
  91. package/web/bindings/mqttAlt.json +746 -746
  92. package/web/bindings/rulesManager.json +54 -54
  93. package/web/bindings/smartThings-Hubitat.json +31 -31
  94. package/web/bindings/valveRelays.json +20 -20
  95. package/web/bindings/vera.json +25 -25
  96. package/web/interfaces/baseInterface.ts +188 -188
  97. package/web/interfaces/httpInterface.ts +148 -148
  98. package/web/interfaces/influxInterface.ts +283 -283
  99. package/web/interfaces/mqttInterface.ts +695 -695
  100. package/web/interfaces/ruleInterface.ts +101 -87
  101. package/web/services/config/Config.ts +1063 -1053
  102. package/web/services/config/ConfigSocket.ts +0 -0
  103. package/web/services/state/State.ts +0 -0
  104. package/web/services/state/StateSocket.ts +0 -0
  105. package/web/services/utilities/Utilities.ts +233 -233
  106. package/.github/workflows/docker-publish-njsPC-linux.yml +0 -50
@@ -1,84 +1,84 @@
1
- import { sys } from "../../controller/Equipment";
2
- import { PumpState, state } from "../../controller/State";
3
- import { Outbound } from "../../controller/comms/messages/Messages";
4
- import { conn } from "controller/comms/Comms";
5
-
6
- export class MockPump {
7
- constructor(){}
8
-
9
- public process(outboundMsg: Outbound){
10
- let response: Outbound = Outbound.create({
11
- portId: outboundMsg.portId,
12
- protocol: outboundMsg.protocol
13
- });
14
-
15
- switch (outboundMsg.action){
16
- case 7:
17
- this.pumpStatus(outboundMsg, response);
18
- default:
19
- this.pumpAck(outboundMsg, response);
20
- }
21
- }
22
-
23
- public pumpStatus(outboundMsg: Outbound, response: Outbound){
24
- let pState:PumpState = state.pumps.getItemById(outboundMsg.dest - 96);
25
- let pt = sys.board.valueMaps.pumpTypes.get(pState.type);
26
- response.action = 7;
27
- response.source = outboundMsg.dest;
28
- response.dest = outboundMsg.source;
29
- response.appendPayloadBytes(0, 15);
30
- response.setPayloadByte(0, pState.command, 2);
31
- response.setPayloadByte(1, pState.mode, 0);
32
- response.setPayloadByte(2, pState.driveState, 2);
33
- let watts = 0;
34
- if (Math.max(pState.rpm, pState.flow) > 0){
35
- if (pState.rpm > 0) watts = pState.rpm/pt.maxSpeed * 2000 + this.random(100);
36
- else if (pState.flow > 0) watts = pState.flow/pt.maxFlow * 2000 + this.random(100);
37
- else //ss, ds, etc
38
- watts = 2000 + this.random(250);
39
- }
40
- response.setPayloadByte(3, Math.floor(watts / 256), 0);
41
- response.setPayloadByte(4, watts % 256, 0);
42
- response.setPayloadByte(5, Math.floor(pState.rpm / 256), 0);
43
- response.setPayloadByte(6, pState.rpm % 256, 0);
44
- response.setPayloadByte(7, pState.flow, 0);
45
- response.setPayloadByte(8, pState.ppc, 0);
46
- // 9, 10 = unknown
47
- // 11, 12 = Status code;
48
- response.setPayloadByte(11, Math.floor(pState.status / 256), 0);
49
- response.setPayloadByte(12, pState.status % 256, 1);
50
- let time = new Date();
51
- response.setPayloadByte(13, time.getHours() * 60);
52
- response.setPayloadByte(14, time.getMinutes());
53
-
54
- conn.queueSendMessage(response);
55
- }
56
-
57
- public pumpAck(outboundMsg: Outbound, response: Outbound){
58
- response.action = outboundMsg.action;
59
- response.source = outboundMsg.dest;
60
- response.dest = outboundMsg.source;
61
- switch (outboundMsg.action){
62
- case 1:
63
- case 10: {
64
- response.appendPayloadByte(outboundMsg.payload[2]);
65
- response.appendPayloadByte(outboundMsg.payload[3]);
66
- break;
67
- }
68
- default:
69
- response.appendPayloadByte(outboundMsg.payload[0]);
70
- }
71
- conn.queueSendMessage(response);
72
- }
73
-
74
- private random(bounds: number, onlyPositive: boolean = false){
75
- let rand = Math.random() * bounds;
76
- if (!onlyPositive) {
77
- if (Math.random()<=.5) rand = rand * -1;
78
- }
79
- return rand;
80
- }
81
-
82
- }
83
-
1
+ import { sys } from "../../controller/Equipment";
2
+ import { PumpState, state } from "../../controller/State";
3
+ import { Outbound } from "../../controller/comms/messages/Messages";
4
+ import { conn } from "controller/comms/Comms";
5
+
6
+ export class MockPump {
7
+ constructor(){}
8
+
9
+ public process(outboundMsg: Outbound){
10
+ let response: Outbound = Outbound.create({
11
+ portId: outboundMsg.portId,
12
+ protocol: outboundMsg.protocol
13
+ });
14
+
15
+ switch (outboundMsg.action){
16
+ case 7:
17
+ this.pumpStatus(outboundMsg, response);
18
+ default:
19
+ this.pumpAck(outboundMsg, response);
20
+ }
21
+ }
22
+
23
+ public pumpStatus(outboundMsg: Outbound, response: Outbound){
24
+ let pState:PumpState = state.pumps.getItemById(outboundMsg.dest - 96);
25
+ let pt = sys.board.valueMaps.pumpTypes.get(pState.type);
26
+ response.action = 7;
27
+ response.source = outboundMsg.dest;
28
+ response.dest = outboundMsg.source;
29
+ response.appendPayloadBytes(0, 15);
30
+ response.setPayloadByte(0, pState.command, 2);
31
+ response.setPayloadByte(1, pState.mode, 0);
32
+ response.setPayloadByte(2, pState.driveState, 2);
33
+ let watts = 0;
34
+ if (Math.max(pState.rpm, pState.flow) > 0){
35
+ if (pState.rpm > 0) watts = pState.rpm/pt.maxSpeed * 2000 + this.random(100);
36
+ else if (pState.flow > 0) watts = pState.flow/pt.maxFlow * 2000 + this.random(100);
37
+ else //ss, ds, etc
38
+ watts = 2000 + this.random(250);
39
+ }
40
+ response.setPayloadByte(3, Math.floor(watts / 256), 0);
41
+ response.setPayloadByte(4, watts % 256, 0);
42
+ response.setPayloadByte(5, Math.floor(pState.rpm / 256), 0);
43
+ response.setPayloadByte(6, pState.rpm % 256, 0);
44
+ response.setPayloadByte(7, pState.flow, 0);
45
+ response.setPayloadByte(8, pState.ppc, 0);
46
+ // 9, 10 = unknown
47
+ // 11, 12 = Status code;
48
+ response.setPayloadByte(11, Math.floor(pState.status / 256), 0);
49
+ response.setPayloadByte(12, pState.status % 256, 1);
50
+ let time = new Date();
51
+ response.setPayloadByte(13, time.getHours() * 60);
52
+ response.setPayloadByte(14, time.getMinutes());
53
+
54
+ conn.queueSendMessage(response);
55
+ }
56
+
57
+ public pumpAck(outboundMsg: Outbound, response: Outbound){
58
+ response.action = outboundMsg.action;
59
+ response.source = outboundMsg.dest;
60
+ response.dest = outboundMsg.source;
61
+ switch (outboundMsg.action){
62
+ case 1:
63
+ case 10: {
64
+ response.appendPayloadByte(outboundMsg.payload[2]);
65
+ response.appendPayloadByte(outboundMsg.payload[3]);
66
+ break;
67
+ }
68
+ default:
69
+ response.appendPayloadByte(outboundMsg.payload[0]);
70
+ }
71
+ conn.queueSendMessage(response);
72
+ }
73
+
74
+ private random(bounds: number, onlyPositive: boolean = false){
75
+ let rand = Math.random() * bounds;
76
+ if (!onlyPositive) {
77
+ if (Math.random()<=.5) rand = rand * -1;
78
+ }
79
+ return rand;
80
+ }
81
+
82
+ }
83
+
84
84
  export var mockPump: MockPump = new MockPump();
package/app.ts CHANGED
@@ -1,116 +1,116 @@
1
- /* nodejs-poolController. An application to control pool equipment.
2
- Copyright (C) 2016, 2017, 2018, 2019, 2020, 2021, 2022.
3
- Russell Goldin, tagyoureit. russ.goldin@gmail.com
4
-
5
- This program is free software: you can redistribute it and/or modify
6
- it under the terms of the GNU Affero General Public License as
7
- published by the Free Software Foundation, either version 3 of the
8
- License, or (at your option) any later version.
9
-
10
- This program is distributed in the hope that it will be useful,
11
- but WITHOUT ANY WARRANTY; without even the implied warranty of
12
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
- GNU Affero General Public License for more details.
14
-
15
- You should have received a copy of the GNU Affero General Public License
16
- along with this program. If not, see <http://www.gnu.org/licenses/>.
17
- */
18
- // add source map support for .js to .ts files
19
- //require('source-map-support').install();
20
- import 'source-map-support/register';
21
-
22
- import { logger } from "./logger/Logger";
23
- import { config } from "./config/Config";
24
- import { conn } from "./controller/comms/Comms";
25
- import { sys } from "./controller/Equipment";
26
-
27
- import { state } from "./controller/State";
28
- import { webApp, REMInterfaceServer } from "./web/Server";
29
- import * as readline from 'readline';
30
- import { sl } from './controller/comms/ScreenLogic'
31
-
32
- export async function initAsync() {
33
- try {
34
- await config.init();
35
- await logger.init();
36
- await sys.init();
37
- await state.init();
38
- await webApp.init();
39
- await conn.initAsync();
40
- await sys.start();
41
- await webApp.initAutoBackup();
42
- await sl.openAsync();
43
- } catch (err) { console.log(`Error Initializing nodejs-PoolController ${err.message}`); }
44
- }
45
-
46
- export async function startPacketCapture(bResetLogs: boolean) {
47
- try {
48
- let log = config.getSection('log');
49
- log.app.captureForReplay = true;
50
- config.setSection('log', log);
51
- logger.startCaptureForReplay(bResetLogs);
52
- if (bResetLogs){
53
- sys.resetSystem();
54
- }
55
-
56
- // Start packet capture on the REM server
57
- await REMInterfaceServer.startPacketCaptureOnRemServer();
58
- }
59
- catch (err) {
60
- console.error(`Error starting replay: ${ err.message }`);
61
- }
62
- }
63
- export async function stopPacketCaptureAsync() {
64
- let log = config.getSection('log');
65
- log.app.captureForReplay = false;
66
- config.setSection('log', log);
67
-
68
- // Stop packet capture on the REM server and collect its logs
69
- let remLogs = await REMInterfaceServer.stopPacketCaptureOnRemServer();
70
-
71
- // Pass REM logs to the logger for inclusion in the backup
72
- return logger.stopCaptureForReplayAsync(remLogs);
73
- }
74
- export async function stopAsync(): Promise<void> {
75
- try {
76
- console.log('Shutting down open processes');
77
- await webApp.stopAutoBackup();
78
- await sys.stopAsync();
79
- await state.stopAsync();
80
- await conn.stopAsync();
81
- await sl.closeAsync();
82
- await webApp.stopAsync();
83
- await config.updateAsync();
84
- await logger.stopAsync();
85
- // RKS: Uncomment below to see the shutdown process
86
- //await new Promise<void>((resolve, reject) => { setTimeout(() => { resolve(); }, 20000); });
87
- }
88
- catch (err) {
89
- console.error(`Error stopping processes: ${ err.message }`);
90
- }
91
- finally {
92
- process.exit();
93
- }
94
- }
95
- if (process.platform === 'win32') {
96
- let rl = readline.createInterface({ input: process.stdin, output: process.stdout });
97
- rl.on('SIGINT', async function () {
98
- try { await stopAsync(); } catch (err) { console.log(`Error shutting down processes ${err.message}`); }
99
- });
100
- }
101
- else {
102
- process.stdin.resume();
103
- process.on('SIGINT', async function () {
104
- try { return await stopAsync(); } catch (err) { console.log(`Error shutting down processes ${err.message}`); }
105
- });
106
- }
107
- if (typeof process === 'object') {
108
- process.on('unhandledRejection', (error: Error, promise) => {
109
- console.group('unhandled rejection');
110
- console.error("== Node detected an unhandled rejection! ==");
111
- console.error(error.message);
112
- console.error(error.stack);
113
- console.groupEnd();
114
- });
115
- }
1
+ /* nodejs-poolController. An application to control pool equipment.
2
+ Copyright (C) 2016, 2017, 2018, 2019, 2020, 2021, 2022.
3
+ Russell Goldin, tagyoureit. russ.goldin@gmail.com
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or (at your option) any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+ // add source map support for .js to .ts files
19
+ //require('source-map-support').install();
20
+ import 'source-map-support/register';
21
+
22
+ import { logger } from "./logger/Logger";
23
+ import { config } from "./config/Config";
24
+ import { conn } from "./controller/comms/Comms";
25
+ import { sys } from "./controller/Equipment";
26
+
27
+ import { state } from "./controller/State";
28
+ import { webApp, REMInterfaceServer } from "./web/Server";
29
+ import * as readline from 'readline';
30
+ import { sl } from './controller/comms/ScreenLogic'
31
+
32
+ export async function initAsync() {
33
+ try {
34
+ await config.init();
35
+ await logger.init();
36
+ await sys.init();
37
+ await state.init();
38
+ await webApp.init();
39
+ await conn.initAsync();
40
+ await sys.start();
41
+ await webApp.initAutoBackup();
42
+ await sl.openAsync();
43
+ } catch (err) { console.log(`Error Initializing nodejs-PoolController ${err.message}`); }
44
+ }
45
+
46
+ export async function startPacketCapture(bResetLogs: boolean) {
47
+ try {
48
+ let log = config.getSection('log');
49
+ log.app.captureForReplay = true;
50
+ config.setSection('log', log);
51
+ logger.startCaptureForReplay(bResetLogs);
52
+ if (bResetLogs){
53
+ await sys.resetSystemAsync();
54
+ }
55
+
56
+ // Start packet capture on the REM server
57
+ await REMInterfaceServer.startPacketCaptureOnRemServer();
58
+ }
59
+ catch (err) {
60
+ console.error(`Error starting replay: ${ err.message }`);
61
+ }
62
+ }
63
+ export async function stopPacketCaptureAsync() {
64
+ let log = config.getSection('log');
65
+ log.app.captureForReplay = false;
66
+ config.setSection('log', log);
67
+
68
+ // Stop packet capture on the REM server and collect its logs
69
+ let remLogs = await REMInterfaceServer.stopPacketCaptureOnRemServer();
70
+
71
+ // Pass REM logs to the logger for inclusion in the backup
72
+ return logger.stopCaptureForReplayAsync(remLogs);
73
+ }
74
+ export async function stopAsync(): Promise<void> {
75
+ try {
76
+ console.log('Shutting down open processes');
77
+ await webApp.stopAutoBackup();
78
+ await sys.stopAsync();
79
+ await state.stopAsync();
80
+ await conn.stopAsync();
81
+ await sl.closeAsync();
82
+ await webApp.stopAsync();
83
+ await config.updateAsync();
84
+ await logger.stopAsync();
85
+ // RKS: Uncomment below to see the shutdown process
86
+ //await new Promise<void>((resolve, reject) => { setTimeout(() => { resolve(); }, 20000); });
87
+ }
88
+ catch (err) {
89
+ console.error(`Error stopping processes: ${ err.message }`);
90
+ }
91
+ finally {
92
+ process.exit();
93
+ }
94
+ }
95
+ if (process.platform === 'win32') {
96
+ let rl = readline.createInterface({ input: process.stdin, output: process.stdout });
97
+ rl.on('SIGINT', async function () {
98
+ try { await stopAsync(); } catch (err) { console.log(`Error shutting down processes ${err.message}`); }
99
+ });
100
+ }
101
+ else {
102
+ process.stdin.resume();
103
+ process.on('SIGINT', async function () {
104
+ try { return await stopAsync(); } catch (err) { console.log(`Error shutting down processes ${err.message}`); }
105
+ });
106
+ }
107
+ if (typeof process === 'object') {
108
+ process.on('unhandledRejection', (error: Error, promise) => {
109
+ console.group('unhandled rejection');
110
+ console.error("== Node detected an unhandled rejection! ==");
111
+ console.error(error.message);
112
+ console.error(error.stack);
113
+ console.groupEnd();
114
+ });
115
+ }
116
116
  ( async () => { await initAsync() })();
package/config/Config.ts CHANGED
@@ -36,21 +36,52 @@ class Config {
36
36
  // RKS 05-18-20: This originally had multiple points of failure where it was not in the try/catch.
37
37
  try {
38
38
  this._isLoading = true;
39
- this._cfg = fs.existsSync(this.cfgPath) ? JSON.parse(fs.readFileSync(this.cfgPath, "utf8").trim()) : {};
39
+ // Read user config (if present) with graceful handling of empty or invalid JSON.
40
+ let userCfg: any = {};
41
+ if (fs.existsSync(this.cfgPath)) {
42
+ try {
43
+ const raw = fs.readFileSync(this.cfgPath, "utf8");
44
+ const trimmed = raw.trim();
45
+ if (trimmed.length > 0) userCfg = JSON.parse(trimmed);
46
+ else {
47
+ console.log(`Config file '${ this.cfgPath }' is empty. Populating with defaults.`);
48
+ }
49
+ } catch (parseErr: any) {
50
+ // Backup corrupt file then continue with defaults.
51
+ try {
52
+ const backupName = this.cfgPath.replace(/\.json$/i, `.corrupt-${ Date.now() }.json`);
53
+ fs.copyFileSync(this.cfgPath, backupName);
54
+ console.log(`Config file '${ this.cfgPath }' contained invalid JSON and was backed up to '${ backupName }'. Using defaults.`);
55
+ } catch (backupErr: any) {
56
+ console.log(`Failed to backup corrupt config file '${ this.cfgPath }': ${ backupErr.message }`);
57
+ }
58
+ userCfg = {};
59
+ }
60
+ }
40
61
  const def = JSON.parse(fs.readFileSync(path.join(process.cwd(), "/defaultConfig.json"), "utf8").trim());
41
62
  const packageJson = JSON.parse(fs.readFileSync(path.join(process.cwd(), "/package.json"), "utf8").trim());
42
- this._cfg = extend(true, {}, def, this._cfg, { appVersion: packageJson.version });
63
+ this._cfg = extend(true, {}, def, userCfg, { appVersion: packageJson.version });
43
64
  this._isInitialized = true;
44
65
  this.updateAsync((err) => {
45
66
  if (typeof err === 'undefined') {
46
67
  fs.watch(this.cfgPath, (event, fileName) => {
47
68
  if (fileName && event === 'change') {
48
- if (self._isLoading) return; // Need a debounce here. We will use a semaphore to cause it not to load more than once.
69
+ if (self._isLoading) return; // Debounce via semaphore.
49
70
  console.log('Updating config file');
50
71
  const stats = fs.statSync(self.cfgPath);
51
72
  if (stats.mtime.valueOf() === self._fileTime.valueOf()) return;
52
- this._cfg = fs.existsSync(this.cfgPath) ? JSON.parse(fs.readFileSync(this.cfgPath, "utf8")) : {};
53
- this._cfg = extend(true, {}, def, this._cfg, { appVersion: packageJson.version });
73
+ let changedCfg: any = {};
74
+ if (fs.existsSync(self.cfgPath)) {
75
+ try {
76
+ const raw2 = fs.readFileSync(self.cfgPath, "utf8");
77
+ const trimmed2 = raw2.trim();
78
+ if (trimmed2.length > 0) changedCfg = JSON.parse(trimmed2);
79
+ else console.log(`Watched config file is empty; continuing with defaults + existing overrides.`);
80
+ } catch (e: any) {
81
+ console.log(`Error parsing updated config file. Retaining existing configuration. Error: ${ e.message }`);
82
+ }
83
+ }
84
+ this._cfg = extend(true, {}, def, changedCfg, { appVersion: packageJson.version });
54
85
  logger.init(); // only reload logger for now; possibly expand to other areas of app
55
86
  logger.info(`Reloading app config: ${fileName}`);
56
87
  this.emitter.emit('reloaded', this._cfg);
@@ -63,8 +94,7 @@ class Config {
63
94
  this.getEnvVariables();
64
95
  } catch (err) {
65
96
  console.log(`Error reading configuration information. Aborting startup: ${ err }`);
66
- // Rethrow this error so we exit the app with the appropriate pause in the console.
67
- throw err;
97
+ throw err; // Only throw if defaults/package.json could not be read.
68
98
  }
69
99
  }
70
100
  public async updateAsync(callback?: (err?) => void) {
@@ -189,6 +219,26 @@ class Config {
189
219
  this._cfg.controller.comms.netPort = env.POOL_NET_PORT;
190
220
  bUpdate = true;
191
221
  }
222
+ // Allow overriding location coordinates for heliotrope calculations
223
+ if (typeof env.POOL_LATITUDE !== 'undefined') {
224
+ const lat = parseFloat(env.POOL_LATITUDE as any);
225
+ if (!isNaN(lat) && (!this._cfg.controller?.general?.location || this._cfg.controller.general.location.latitude !== lat)) {
226
+ // Ensure nested objects exist
227
+ this._cfg.controller.general = this._cfg.controller.general || {};
228
+ this._cfg.controller.general.location = this._cfg.controller.general.location || {};
229
+ this._cfg.controller.general.location.latitude = lat;
230
+ bUpdate = true;
231
+ }
232
+ }
233
+ if (typeof env.POOL_LONGITUDE !== 'undefined') {
234
+ const lon = parseFloat(env.POOL_LONGITUDE as any);
235
+ if (!isNaN(lon) && (!this._cfg.controller?.general?.location || this._cfg.controller.general.location.longitude !== lon)) {
236
+ this._cfg.controller.general = this._cfg.controller.general || {};
237
+ this._cfg.controller.general.location = this._cfg.controller.general.location || {};
238
+ this._cfg.controller.general.location.longitude = lon;
239
+ bUpdate = true;
240
+ }
241
+ }
192
242
  if (bUpdate) this.updateAsync();
193
243
  }
194
244
  }
@@ -28,10 +28,24 @@ class VersionCheck {
28
28
  private gitApiHost: string;
29
29
  private gitLatestReleaseJSONPath: string;
30
30
  private redirects: number;
31
+ private gitAvailable: boolean;
32
+ private warnedBranch: boolean = false;
33
+ private warnedCommit: boolean = false;
31
34
  constructor() {
32
35
  this.userAgent = 'tagyoureit-nodejs-poolController-app';
33
36
  this.gitApiHost = 'api.github.com';
34
37
  this.gitLatestReleaseJSONPath = '/repos/tagyoureit/nodejs-poolController/releases/latest';
38
+ this.gitAvailable = this.detectGit();
39
+ // NOTE:
40
+ // * SOURCE_BRANCH / SOURCE_COMMIT env vars (if present) override git commands. These are expected in container builds where .git may be absent.
41
+ // * If git is not available (no binary or not a repo) we suppress repeated warnings after the first occurrence.
42
+ // * Version comparison is rate-limited via nextCheckTime (every 2 days) to avoid Github API throttling.
43
+ }
44
+ private detectGit(): boolean {
45
+ try {
46
+ execSync('git --version', { stdio: 'ignore' });
47
+ return true;
48
+ } catch { return false; }
35
49
  }
36
50
 
37
51
  public checkGitRemote() {
@@ -40,43 +54,46 @@ class VersionCheck {
40
54
  if (typeof state.appVersion.nextCheckTime === 'undefined' || new Date() > new Date(state.appVersion.nextCheckTime)) setTimeout(() => { this.checkAll(); }, 100);
41
55
  }
42
56
  public checkGitLocal() {
43
- let env = process.env;
44
- // check local git version
57
+ const env = process.env;
58
+ // Branch
45
59
  try {
46
60
  let out: string;
47
- if (typeof env.SOURCE_BRANCH !== 'undefined')
48
- {
49
- out = env.SOURCE_BRANCH // check for docker variable
50
- }
51
- else {
52
- let res = execSync('git rev-parse --abbrev-ref HEAD', { stdio: 'pipe' });
61
+ if (typeof env.SOURCE_BRANCH !== 'undefined') {
62
+ out = env.SOURCE_BRANCH;
63
+ } else if (this.gitAvailable) {
64
+ const res = execSync('git rev-parse --abbrev-ref HEAD', { stdio: 'pipe' });
53
65
  out = res.toString().trim();
66
+ } else {
67
+ out = '--';
54
68
  }
55
- logger.info(`The current git branch output is ${out}`);
69
+ if (out !== '--') logger.info(`The current git branch output is ${out}`);
56
70
  switch (out) {
57
- case 'fatal':
58
- case 'command':
59
- state.appVersion.gitLocalBranch = '--';
60
- break;
61
- default:
62
- state.appVersion.gitLocalBranch = out;
63
- }
64
- }
65
- catch (err) {
71
+ case 'fatal':
72
+ case 'command':
73
+ state.appVersion.gitLocalBranch = '--';
74
+ break;
75
+ default:
76
+ state.appVersion.gitLocalBranch = out;
77
+ }
78
+ } catch (err) {
66
79
  state.appVersion.gitLocalBranch = '--';
67
- logger.warn(`Unable to retrieve local git branch. ${err}`);
80
+ if (!this.warnedBranch) {
81
+ logger.warn(`Unable to retrieve local git branch (git missing or not a repo). Further branch warnings suppressed.`);
82
+ this.warnedBranch = true;
83
+ }
68
84
  }
85
+ // Commit
69
86
  try {
70
87
  let out: string;
71
- if (typeof env.SOURCE_COMMIT !== 'undefined')
72
- {
73
- out = env.SOURCE_COMMIT; // check for docker variable
74
- }
75
- else {
76
- let res = execSync('git rev-parse HEAD', { stdio: 'pipe' });
88
+ if (typeof env.SOURCE_COMMIT !== 'undefined') {
89
+ out = env.SOURCE_COMMIT;
90
+ } else if (this.gitAvailable) {
91
+ const res = execSync('git rev-parse HEAD', { stdio: 'pipe' });
77
92
  out = res.toString().trim();
93
+ } else {
94
+ out = '--';
78
95
  }
79
- logger.info(`The current git commit output is ${out}`);
96
+ if (out !== '--') logger.info(`The current git commit output is ${out}`);
80
97
  switch (out) {
81
98
  case 'fatal':
82
99
  case 'command':
@@ -85,10 +102,12 @@ class VersionCheck {
85
102
  default:
86
103
  state.appVersion.gitLocalCommit = out;
87
104
  }
88
- }
89
- catch (err) {
105
+ } catch (err) {
90
106
  state.appVersion.gitLocalCommit = '--';
91
- logger.warn(`Unable to retrieve local git commit. ${err}`);
107
+ if (!this.warnedCommit) {
108
+ logger.warn(`Unable to retrieve local git commit (git missing or not a repo). Further commit warnings suppressed.`);
109
+ this.warnedCommit = true;
110
+ }
92
111
  }
93
112
  }
94
113
  private checkAll() {
@@ -126,15 +145,24 @@ class VersionCheck {
126
145
  return new Promise<string>((resolve, reject) => {
127
146
  try {
128
147
  let req = https.request(url, options, async res => {
129
- if (res.statusCode > 300 && res.statusCode < 400 && res.headers.location) await this.getLatestRelease(res.headers.location);
148
+ if (res.statusCode > 300 && res.statusCode < 400 && res.headers.location) {
149
+ try {
150
+ const redirected = await this.getLatestRelease(res.headers.location);
151
+ return resolve(redirected);
152
+ } catch (e) { return reject(e); }
153
+ }
130
154
  let data = '';
131
155
  res.on('data', d => { data += d; });
132
156
  res.on('end', () => {
133
- let jdata = JSON.parse(data);
134
- if (typeof jdata.tag_name !== 'undefined')
135
- resolve(jdata.tag_name.replace('v', ''));
136
- else
137
- reject(`No data returned.`)
157
+ try {
158
+ let jdata = JSON.parse(data);
159
+ if (typeof jdata.tag_name !== 'undefined')
160
+ resolve(jdata.tag_name.replace('v', ''));
161
+ else
162
+ reject(`No data returned.`)
163
+ } catch(parseErr: any){
164
+ reject(`Error parsing Github response: ${ parseErr.message }`);
165
+ }
138
166
  })
139
167
  })
140
168
  .end();