nodejs-poolcontroller 8.3.0 → 8.4.1

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 (107) 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 -63
  7. package/.github/workflows/ghcr-publish.yml +67 -67
  8. package/157_issues.md +101 -0
  9. package/AGENTS.md +613 -0
  10. package/CONTRIBUTING.md +74 -74
  11. package/Changelog +292 -284
  12. package/Dockerfile +62 -62
  13. package/Gruntfile.js +40 -40
  14. package/LICENSE +661 -661
  15. package/README.md +329 -309
  16. package/anslq25/MessagesMock.ts +221 -221
  17. package/anslq25/boards/MockBoardFactory.ts +49 -49
  18. package/anslq25/boards/MockEasyTouchBoard.ts +696 -696
  19. package/anslq25/boards/MockSystemBoard.ts +216 -216
  20. package/anslq25/chemistry/MockChlorinator.ts +98 -98
  21. package/anslq25/pumps/MockPump.ts +83 -83
  22. package/app.ts +115 -115
  23. package/config/Config.ts +0 -0
  24. package/config/VersionCheck.ts +0 -0
  25. package/controller/Constants.ts +809 -805
  26. package/controller/Equipment.ts +2737 -2664
  27. package/controller/Errors.ts +181 -181
  28. package/controller/Lockouts.ts +549 -549
  29. package/controller/State.ts +3746 -3701
  30. package/controller/boards/AquaLinkBoard.ts +1175 -1003
  31. package/controller/boards/BoardFactory.ts +53 -53
  32. package/controller/boards/EasyTouchBoard.ts +3246 -3202
  33. package/controller/boards/IntelliCenterBoard.ts +4581 -3899
  34. package/controller/boards/IntelliComBoard.ts +69 -69
  35. package/controller/boards/IntelliTouchBoard.ts +382 -382
  36. package/controller/boards/NixieBoard.ts +1947 -1944
  37. package/controller/boards/SunTouchBoard.ts +401 -400
  38. package/controller/boards/SystemBoard.ts +5303 -5268
  39. package/controller/comms/Comms.ts +1278 -1255
  40. package/controller/comms/ScreenLogic.ts +1665 -1665
  41. package/controller/comms/messages/Messages.ts +1627 -1406
  42. package/controller/comms/messages/config/ChlorinatorMessage.ts +5 -0
  43. package/controller/comms/messages/config/CircuitGroupMessage.ts +0 -0
  44. package/controller/comms/messages/config/CircuitMessage.ts +0 -0
  45. package/controller/comms/messages/config/ConfigMessage.ts +6 -0
  46. package/controller/comms/messages/config/CoverMessage.ts +0 -0
  47. package/controller/comms/messages/config/CustomNameMessage.ts +31 -31
  48. package/controller/comms/messages/config/EquipmentMessage.ts +250 -210
  49. package/controller/comms/messages/config/ExternalMessage.ts +1051 -903
  50. package/controller/comms/messages/config/FeatureMessage.ts +0 -0
  51. package/controller/comms/messages/config/GeneralMessage.ts +65 -0
  52. package/controller/comms/messages/config/HeaterMessage.ts +0 -0
  53. package/controller/comms/messages/config/IntellichemMessage.ts +0 -0
  54. package/controller/comms/messages/config/OptionsMessage.ts +207 -174
  55. package/controller/comms/messages/config/PumpMessage.ts +427 -421
  56. package/controller/comms/messages/config/RemoteMessage.ts +0 -0
  57. package/controller/comms/messages/config/ScheduleMessage.ts +401 -390
  58. package/controller/comms/messages/config/SecurityMessage.ts +37 -13
  59. package/controller/comms/messages/config/ValveMessage.ts +0 -0
  60. package/controller/comms/messages/status/ChlorinatorStateMessage.ts +0 -0
  61. package/controller/comms/messages/status/EquipmentStateMessage.ts +940 -822
  62. package/controller/comms/messages/status/HeaterStateMessage.ts +147 -135
  63. package/controller/comms/messages/status/IntelliChemStateMessage.ts +448 -448
  64. package/controller/comms/messages/status/IntelliValveStateMessage.ts +36 -36
  65. package/controller/comms/messages/status/NeptuneModbusStateMessage.ts +217 -0
  66. package/controller/comms/messages/status/PumpStateMessage.ts +0 -0
  67. package/controller/comms/messages/status/RegalModbusStateMessage.ts +410 -410
  68. package/controller/comms/messages/status/VersionMessage.ts +152 -41
  69. package/controller/nixie/Nixie.ts +173 -173
  70. package/controller/nixie/NixieEquipment.ts +104 -104
  71. package/controller/nixie/bodies/Body.ts +120 -120
  72. package/controller/nixie/bodies/Filter.ts +135 -135
  73. package/controller/nixie/chemistry/ChemController.ts +2756 -2724
  74. package/controller/nixie/chemistry/ChemDoser.ts +806 -806
  75. package/controller/nixie/chemistry/Chlorinator.ts +367 -367
  76. package/controller/nixie/circuits/Circuit.ts +478 -478
  77. package/controller/nixie/heaters/Heater.ts +843 -834
  78. package/controller/nixie/pumps/Pump.ts +1336 -1193
  79. package/controller/nixie/schedules/Schedule.ts +401 -401
  80. package/controller/nixie/valves/Valve.ts +170 -170
  81. package/defaultConfig.json +352 -352
  82. package/docker-compose.yml +32 -31
  83. package/logger/DataLogger.ts +448 -448
  84. package/logger/Logger.ts +459 -436
  85. package/package.json +58 -58
  86. package/sendSocket.js +32 -32
  87. package/tsconfig.json +26 -25
  88. package/types/express-multer.d.ts +32 -32
  89. package/web/Server.ts +1939 -1927
  90. package/web/bindings/aqualinkD.json +559 -559
  91. package/web/bindings/influxDB.json +1066 -1066
  92. package/web/bindings/mqtt.json +721 -721
  93. package/web/bindings/mqttAlt.json +746 -746
  94. package/web/bindings/rulesManager.json +54 -54
  95. package/web/bindings/smartThings-Hubitat.json +31 -31
  96. package/web/bindings/valveRelays.json +20 -20
  97. package/web/bindings/vera.json +25 -25
  98. package/web/interfaces/baseInterface.ts +188 -188
  99. package/web/interfaces/httpInterface.ts +148 -148
  100. package/web/interfaces/influxInterface.ts +283 -283
  101. package/web/interfaces/mqttInterface.ts +695 -695
  102. package/web/interfaces/ruleInterface.ts +101 -87
  103. package/web/services/config/Config.ts +1212 -1053
  104. package/web/services/config/ConfigSocket.ts +0 -0
  105. package/web/services/state/State.ts +21 -0
  106. package/web/services/state/StateSocket.ts +28 -0
  107. package/web/services/utilities/Utilities.ts +233 -233
@@ -1,42 +1,153 @@
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
- import { Inbound } from "../Messages";
19
- import { sys, ConfigVersion } from "../../../Equipment";
20
- export class VersionMessage {
21
- public static process(msg: Inbound): void {
22
- var ver: ConfigVersion = new ConfigVersion({});
23
- ver.options = msg.extractPayloadInt(6);
24
- ver.circuits = msg.extractPayloadInt(8);
25
- ver.features = msg.extractPayloadInt(10);
26
- ver.schedules = msg.extractPayloadInt(12);
27
- ver.pumps = msg.extractPayloadInt(14);
28
- ver.remotes = msg.extractPayloadInt(16);
29
- ver.circuitGroups = msg.extractPayloadInt(18);
30
- ver.chlorinators = msg.extractPayloadInt(20);
31
- ver.intellichem = msg.extractPayloadInt(22);
32
- ver.valves = msg.extractPayloadInt(24);
33
- ver.heaters = msg.extractPayloadInt(26);
34
- ver.security = msg.extractPayloadInt(28);
35
- ver.general = msg.extractPayloadInt(30);
36
- ver.equipment = msg.extractPayloadInt(32);
37
- ver.covers = msg.extractPayloadInt(34);
38
- ver.systemState = msg.extractPayloadInt(36);
39
- sys.processVersionChanges(ver);
40
- msg.isProcessed = true;
41
- }
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
+ import { Inbound, Message, Outbound, Response } from "../Messages";
19
+ import { sys, ConfigVersion } from "../../../Equipment";
20
+ import { logger } from "../../../../logger/Logger";
21
+
22
+ export class VersionMessage {
23
+ // Debounce config refresh requests to avoid duplicate requests from overlapping triggers
24
+ private static lastConfigRefreshTime: number = 0;
25
+ private static readonly CONFIG_REFRESH_DEBOUNCE_MS = 2000; // 2 seconds
26
+ private static pendingConfigRefreshTimer?: NodeJS.Timeout;
27
+ private static pendingConfigRefreshSource?: string;
28
+ private static scheduleConfigRefresh(delayMs: number, source: string, reason: string): void {
29
+ this.pendingConfigRefreshSource = source;
30
+ if (!this.pendingConfigRefreshTimer) {
31
+ this.pendingConfigRefreshTimer = setTimeout(() => {
32
+ this.pendingConfigRefreshTimer = undefined;
33
+ const src = this.pendingConfigRefreshSource ? `${this.pendingConfigRefreshSource} (trailing)` : 'Trailing';
34
+ this.pendingConfigRefreshSource = undefined;
35
+ this.triggerConfigRefresh(src);
36
+ }, delayMs);
37
+ }
38
+ logger.silly(`v3.004+ ${source}: Deferring config refresh (${reason}, retry in ${delayMs}ms)`);
39
+ }
40
+
41
+ /**
42
+ * Shared method to trigger a config refresh with debouncing.
43
+ * Prevents duplicate requests when multiple triggers fire in quick succession.
44
+ */
45
+ private static triggerConfigRefresh(source: string): void {
46
+ const now = Date.now();
47
+ const elapsed = now - this.lastConfigRefreshTime;
48
+ if (elapsed < this.CONFIG_REFRESH_DEBOUNCE_MS) {
49
+ // Throttle-with-trailing: don't lose rapid toggle updates; schedule one refresh at end of window.
50
+ const remainingMs = Math.max(0, this.CONFIG_REFRESH_DEBOUNCE_MS - elapsed);
51
+ this.scheduleConfigRefresh(remainingMs, source, `debounced (last send ${elapsed}ms ago)`);
52
+ return;
53
+ }
54
+ (sys.board as any).needsConfigChanges = true;
55
+ // Invalidate cached options version so queueChanges() will request category 0.
56
+ // OCP doesn't increment options version when heat mode/setpoints change,
57
+ // so we force a refresh by clearing our cached version.
58
+ sys.configVersion.options = 0;
59
+ // v3.004+: OCP does NOT reliably increment systemState when features toggle (esp. rapid OFF/ON sequences).
60
+ // Force a systemState refresh so queueChanges() will request category 15 (systemState), option [0] => Action 222 [15,0].
61
+ sys.configVersion.systemState = 0;
62
+ // v3.004+: OCP does NOT increment pumps version when pump config changes via WCP (Action 168 type 4).
63
+ // Force a pumps refresh so queueChanges() will request category 4 (pumps).
64
+ sys.configVersion.pumps = 0;
65
+ // v3.x: personal-information updates (Action 168 type 12) are not always reflected by
66
+ // version deltas in the field; force a general refresh so category 12 is re-polled.
67
+ sys.configVersion.general = 0;
68
+
69
+ // If a config queue run is already active, coalesce this refresh and retry after a short delay.
70
+ // This avoids extra 228/164 churn in the middle of an in-flight loading pass.
71
+ if (typeof (sys.board as any).isConfigQueueProcessing === 'function' &&
72
+ (sys.board as any).isConfigQueueProcessing()) {
73
+ this.scheduleConfigRefresh(this.CONFIG_REFRESH_DEBOUNCE_MS, source, 'config queue already processing');
74
+ return;
75
+ }
76
+
77
+ this.lastConfigRefreshTime = now;
78
+ logger.silly(`v3.004+ ${source}: Sending Action 228`);
79
+ Outbound.create({
80
+ dest: 16, action: 228, payload: [0], retries: 2,
81
+ scope: 'v3RefreshTrigger',
82
+ // v3.004+: require 164 addressed to us (not to Wireless).
83
+ response: Response.create({ dest: Message.pluginAddress, action: 164 })
84
+ }).sendAsync();
85
+ }
86
+
87
+ /**
88
+ * v3.004+ Piggyback: When another device sends Action 228 to OCP,
89
+ * send our own to catch config changes. See .plan/202-intellicenter-bodies-temps.md
90
+ */
91
+ public static processVersionRequest(msg: Inbound): void {
92
+ if (sys.equipment.isIntellicenterV3 &&
93
+ msg.source !== Message.pluginAddress && // Not from us
94
+ msg.dest === 16) { // Directed to OCP
95
+ this.triggerConfigRefresh('Piggyback');
96
+ }
97
+ msg.isProcessed = true;
98
+ }
99
+
100
+ /**
101
+ * v3.004+ ACK Trigger (single entrypoint):
102
+ * When OCP ACKs a Wireless/other device's Action 168 or 184, trigger a debounced config refresh.
103
+ *
104
+ * Intended call-site: `Messages.ts` should gate on ACK payload[0] (168/184) and then call this method once.
105
+ */
106
+ public static processActionAck(msg: Inbound): void {
107
+ // Gate: only v3.004+
108
+ if (!sys.equipment.isIntellicenterV3) {
109
+ msg.isProcessed = true;
110
+ return;
111
+ }
112
+ // Gate: only when ACK originates from OCP (src=16) to some other device (not us, not OCP).
113
+ if (msg.source !== 16 || msg.dest === Message.pluginAddress || msg.dest === 16) {
114
+ msg.isProcessed = true;
115
+ return;
116
+ }
117
+ // Gate: only ACKing Action 168 or 184 (caller should gate, but keep defensive checks here too).
118
+ const ackedAction = msg.payload.length > 0 ? msg.payload[0] : undefined;
119
+ if (ackedAction !== 168 && ackedAction !== 184) {
120
+ msg.isProcessed = true;
121
+ return;
122
+ }
123
+
124
+ const label =
125
+ ackedAction === 168
126
+ ? `ACK(168) Trigger (device ${msg.dest})`
127
+ : `ACK(184) Trigger (device ${msg.dest})`;
128
+ this.triggerConfigRefresh(label);
129
+ msg.isProcessed = true;
130
+ }
131
+
132
+ public static process(msg: Inbound): void {
133
+ var ver: ConfigVersion = new ConfigVersion({});
134
+ ver.options = msg.extractPayloadInt(6);
135
+ ver.circuits = msg.extractPayloadInt(8);
136
+ ver.features = msg.extractPayloadInt(10);
137
+ ver.schedules = msg.extractPayloadInt(12);
138
+ ver.pumps = msg.extractPayloadInt(14);
139
+ ver.remotes = msg.extractPayloadInt(16);
140
+ ver.circuitGroups = msg.extractPayloadInt(18);
141
+ ver.chlorinators = msg.extractPayloadInt(20);
142
+ ver.intellichem = msg.extractPayloadInt(22);
143
+ ver.valves = msg.extractPayloadInt(24);
144
+ ver.heaters = msg.extractPayloadInt(26);
145
+ ver.security = msg.extractPayloadInt(28);
146
+ ver.general = msg.extractPayloadInt(30);
147
+ ver.equipment = msg.extractPayloadInt(32);
148
+ ver.covers = msg.extractPayloadInt(34);
149
+ ver.systemState = msg.extractPayloadInt(36);
150
+ sys.processVersionChanges(ver);
151
+ msg.isProcessed = true;
152
+ }
42
153
  }
@@ -1,174 +1,174 @@
1
- import * as path from 'path';
2
- import * as fs from 'fs';
3
- import * as os from 'os';
4
- import { webApp } from "../../web/Server";
5
- import { logger } from "../../logger/Logger";
6
- import { INixieControlPanel } from "./NixieEquipment";
7
- import { NixieChemControllerCollection } from "./chemistry/ChemController";
8
- import { NixieChemDoserCollection } from "./chemistry/ChemDoser";
9
-
10
- import { sys, PoolSystem } from "../../controller/Equipment";
11
- import { NixieCircuitCollection } from './circuits/Circuit';
12
- import { NixieBodyCollection } from './bodies/Body';
13
- import { NixieValveCollection } from './valves/Valve';
14
- import { NixieHeaterCollection } from './heaters/Heater';
15
- import { config } from '../../config/Config';
16
- import { NixieFilterCollection } from './bodies/Filter';
17
- import { NixieChlorinatorCollection } from './chemistry/Chlorinator';
18
- import { NixiePump, NixiePumpCollection } from './pumps/Pump';
19
- import { NixieScheduleCollection } from './schedules/Schedule';
20
-
21
- /************************************************************************
22
- * Nixie: Nixie is a control panel that controls devices as a master. It
23
- * can extend an existing *Touch or Center control panel. Or it can run
24
- * standalone as a master controller. The NixieControlPanel will always
25
- * be instantiated to control equipment when that equipment is not
26
- * supported or controlled by a traditional OCP. However, if a traditional
27
- * OCP exists, it will be subordinate to that OCP in regard to controlling
28
- * pool bodies.
29
- *
30
- * Equipment: Equipment identified as ncp (Nixie Control Panel) will be
31
- * managed by the Nixie controller. It works hand-in-glove with the REM
32
- * (Relay Equipment Manager) to provide low level hardware support.
33
- *
34
- * RS485: RS485 occurs directly within nixie through the standard RS485
35
- * bus identified for njspc and does not route through REM. This is an
36
- * important distinction to provide robust hardware level communication.
37
- * Items Controlled on this channel include: Pumps, Chlorinators, and
38
- * IntelliChem controllers. When and if IntelliValve functions become
39
- * available these too will be performed through the njspc RS485 bus.
40
- *
41
- * Configuration and State Management:
42
- * Nixie uses the underlying njspc configuration structures. The intent
43
- * is not to replace these rather the intention is to extend them with
44
- * low level control. For this reason, only when a Nixie is the only
45
- * master controller on the pool do commands get routed through NixieBoard.
46
- * this mode is identified at startup. When a particular piece of equipment
47
- * is identified to be controlled by Nixie as a master then the command
48
- * will eventually be marshalled to the NixieControlPanel. Any connected
49
- * OCP will get first crack at it.
50
- *
51
- * LifeCycle: The Nixie controller does not persist data outside of
52
- * the PoolConfig.json and PoolState.json files. It is initialized
53
- * at startup and torn down when the application is stopped.
54
- * */
55
- export class NixieControlPanel implements INixieControlPanel {
56
- // Only equipment controlled by Nixie is represented on the controller. If interaction with
57
- // other equipment is required this should be sent back through the original controller.
58
- // Command sequence is <OCP>Board -> SystemBoard -> NixieController whenever the master is not identified as Nixie.
59
- chemDosers: NixieChemDoserCollection = new NixieChemDoserCollection(this);
60
- chemControllers: NixieChemControllerCollection = new NixieChemControllerCollection(this);
61
- chlorinators: NixieChlorinatorCollection = new NixieChlorinatorCollection(this);
62
- circuits: NixieCircuitCollection = new NixieCircuitCollection(this);
63
- bodies: NixieBodyCollection = new NixieBodyCollection(this);
64
- filters: NixieFilterCollection = new NixieFilterCollection(this);
65
- valves: NixieValveCollection = new NixieValveCollection(this);
66
- heaters: NixieHeaterCollection = new NixieHeaterCollection(this);
67
- pumps: NixiePumpCollection = new NixiePumpCollection(this);
68
- schedules: NixieScheduleCollection = new NixieScheduleCollection(this);
69
- public async setServiceModeAsync() {
70
- await this.circuits.setServiceModeAsync();
71
- await this.heaters.setServiceModeAsync();
72
- await this.chlorinators.setServiceModeAsync();
73
- await this.chemControllers.setServiceModeAsync();
74
- await this.chemDosers.setServiceModeAsync();
75
- await this.pumps.setServiceModeAsync();
76
- }
77
- public async initAsync(equipment: PoolSystem) {
78
- try {
79
-
80
- // We need to tell Nixie what her place is. If there is an existing OCP she needs to be a partner. However, if
81
- // she is the only master then she needs to step up and take command. The way we will signify this is
82
- // by using settings in config.json.
83
- // The controller types define the number of bodies and whether they are shared.
84
- logger.info(`Initializing Nixie Controller`);
85
- await this.bodies.initAsync(equipment.bodies);
86
- await this.filters.initAsync(equipment.filters);
87
- await this.circuits.initAsync(equipment.circuits);
88
- await this.valves.initAsync(equipment.valves);
89
- await this.heaters.initAsync(equipment.heaters);
90
- await this.chlorinators.initAsync(equipment.chlorinators);
91
- await this.chemControllers.initAsync(equipment.chemControllers);
92
- await this.chemDosers.initAsync(equipment.chemDosers);
93
- await this.pumps.initAsync(equipment.pumps);
94
- await this.schedules.initAsync(equipment.schedules);
95
- logger.info(`Nixie Controller Initialized`)
96
- }
97
- catch (err) { return Promise.reject(err); }
98
- }
99
- public async readLogFile(logFile: string): Promise<string[]> {
100
- try {
101
- let logPath = path.join(process.cwd(), '/logs');
102
- if (!fs.existsSync(logPath)) fs.mkdirSync(logPath);
103
- logPath += (`/${logFile}`);
104
- let lines = [];
105
- if (fs.existsSync(logPath)) {
106
- let buff = fs.readFileSync(logPath);
107
- lines = buff.toString().split('\n');
108
- }
109
- return lines;
110
- } catch (err) { logger.error(`Error reading log file ${logFile}: ${err.message}`); }
111
- }
112
- public async logData(logFile: string, data: any) {
113
- try {
114
- let logPath = path.join(process.cwd(), '/logs');
115
- if (!fs.existsSync(logPath)) fs.mkdirSync(logPath);
116
- logPath += (`/${logFile}`);
117
- let lines = [];
118
- if (fs.existsSync(logPath)) {
119
- let buff = fs.readFileSync(logPath);
120
- lines = buff.toString().split('\n');
121
- }
122
- if (typeof data === 'object')
123
- lines.unshift(JSON.stringify(data));
124
- else
125
- lines.unshift(data.toString());
126
- fs.writeFileSync(logPath, lines.join('\n'));
127
- } catch (err) { logger.error(`Error logging to ${logFile}: ${err.message}`); }
128
- }
129
- public async closeAsync() {
130
- // Close all the associated equipment.
131
- await this.chemDosers.closeAsync();
132
- await this.chemControllers.closeAsync();
133
- await this.chlorinators.closeAsync();
134
- await this.heaters.closeAsync();
135
- await this.circuits.closeAsync();
136
- await this.pumps.closeAsync();
137
- await this.filters.closeAsync();
138
- await this.bodies.closeAsync();
139
- await this.valves.closeAsync();
140
- }
141
- /*
142
- * This method is used to obtain a list of existing REM servers for configuration. This returns all servers and
143
- * their potential devices and is not designed to be used at run-time or to detect failure.
144
- *
145
- */
146
- public async getREMServers() {
147
- try {
148
- let srv = [];
149
- let servers = webApp.findServersByType('rem');
150
- if (typeof servers !== 'undefined') {
151
- for (let i = 0; i < servers.length; i++) {
152
- let server = servers[i];
153
- // Sometimes I hate type safety.
154
- let devices = typeof server['getDevices'] === 'function' ? await server['getDevices']() : [];
155
- let int = config.getInterfaceByUuid(servers[i].uuid);
156
- srv.push({
157
- uuid: servers[i].uuid,
158
- name: servers[i].name,
159
- type: servers[i].type,
160
- isRunning: servers[i].isRunning,
161
- isConnected: servers[i].isConnected,
162
- devices: devices,
163
- remoteConnectionId: servers[i].remoteConnectionId,
164
- interface: int
165
- });
166
- }
167
- await ncp.chemControllers.syncRemoteREMFeeds(srv);
168
- }
169
- return srv;
170
- } catch (err) { logger.error(`Error gettting REM Servers: ${err.message}`); }
171
- }
172
- }
173
-
1
+ import * as path from 'path';
2
+ import * as fs from 'fs';
3
+ import * as os from 'os';
4
+ import { webApp } from "../../web/Server";
5
+ import { logger } from "../../logger/Logger";
6
+ import { INixieControlPanel } from "./NixieEquipment";
7
+ import { NixieChemControllerCollection } from "./chemistry/ChemController";
8
+ import { NixieChemDoserCollection } from "./chemistry/ChemDoser";
9
+
10
+ import { sys, PoolSystem } from "../../controller/Equipment";
11
+ import { NixieCircuitCollection } from './circuits/Circuit';
12
+ import { NixieBodyCollection } from './bodies/Body';
13
+ import { NixieValveCollection } from './valves/Valve';
14
+ import { NixieHeaterCollection } from './heaters/Heater';
15
+ import { config } from '../../config/Config';
16
+ import { NixieFilterCollection } from './bodies/Filter';
17
+ import { NixieChlorinatorCollection } from './chemistry/Chlorinator';
18
+ import { NixiePump, NixiePumpCollection } from './pumps/Pump';
19
+ import { NixieScheduleCollection } from './schedules/Schedule';
20
+
21
+ /************************************************************************
22
+ * Nixie: Nixie is a control panel that controls devices as a master. It
23
+ * can extend an existing *Touch or Center control panel. Or it can run
24
+ * standalone as a master controller. The NixieControlPanel will always
25
+ * be instantiated to control equipment when that equipment is not
26
+ * supported or controlled by a traditional OCP. However, if a traditional
27
+ * OCP exists, it will be subordinate to that OCP in regard to controlling
28
+ * pool bodies.
29
+ *
30
+ * Equipment: Equipment identified as ncp (Nixie Control Panel) will be
31
+ * managed by the Nixie controller. It works hand-in-glove with the REM
32
+ * (Relay Equipment Manager) to provide low level hardware support.
33
+ *
34
+ * RS485: RS485 occurs directly within nixie through the standard RS485
35
+ * bus identified for njspc and does not route through REM. This is an
36
+ * important distinction to provide robust hardware level communication.
37
+ * Items Controlled on this channel include: Pumps, Chlorinators, and
38
+ * IntelliChem controllers. When and if IntelliValve functions become
39
+ * available these too will be performed through the njspc RS485 bus.
40
+ *
41
+ * Configuration and State Management:
42
+ * Nixie uses the underlying njspc configuration structures. The intent
43
+ * is not to replace these rather the intention is to extend them with
44
+ * low level control. For this reason, only when a Nixie is the only
45
+ * master controller on the pool do commands get routed through NixieBoard.
46
+ * this mode is identified at startup. When a particular piece of equipment
47
+ * is identified to be controlled by Nixie as a master then the command
48
+ * will eventually be marshalled to the NixieControlPanel. Any connected
49
+ * OCP will get first crack at it.
50
+ *
51
+ * LifeCycle: The Nixie controller does not persist data outside of
52
+ * the PoolConfig.json and PoolState.json files. It is initialized
53
+ * at startup and torn down when the application is stopped.
54
+ * */
55
+ export class NixieControlPanel implements INixieControlPanel {
56
+ // Only equipment controlled by Nixie is represented on the controller. If interaction with
57
+ // other equipment is required this should be sent back through the original controller.
58
+ // Command sequence is <OCP>Board -> SystemBoard -> NixieController whenever the master is not identified as Nixie.
59
+ chemDosers: NixieChemDoserCollection = new NixieChemDoserCollection(this);
60
+ chemControllers: NixieChemControllerCollection = new NixieChemControllerCollection(this);
61
+ chlorinators: NixieChlorinatorCollection = new NixieChlorinatorCollection(this);
62
+ circuits: NixieCircuitCollection = new NixieCircuitCollection(this);
63
+ bodies: NixieBodyCollection = new NixieBodyCollection(this);
64
+ filters: NixieFilterCollection = new NixieFilterCollection(this);
65
+ valves: NixieValveCollection = new NixieValveCollection(this);
66
+ heaters: NixieHeaterCollection = new NixieHeaterCollection(this);
67
+ pumps: NixiePumpCollection = new NixiePumpCollection(this);
68
+ schedules: NixieScheduleCollection = new NixieScheduleCollection(this);
69
+ public async setServiceModeAsync() {
70
+ await this.circuits.setServiceModeAsync();
71
+ await this.heaters.setServiceModeAsync();
72
+ await this.chlorinators.setServiceModeAsync();
73
+ await this.chemControllers.setServiceModeAsync();
74
+ await this.chemDosers.setServiceModeAsync();
75
+ await this.pumps.setServiceModeAsync();
76
+ }
77
+ public async initAsync(equipment: PoolSystem) {
78
+ try {
79
+
80
+ // We need to tell Nixie what her place is. If there is an existing OCP she needs to be a partner. However, if
81
+ // she is the only master then she needs to step up and take command. The way we will signify this is
82
+ // by using settings in config.json.
83
+ // The controller types define the number of bodies and whether they are shared.
84
+ logger.info(`Initializing Nixie Controller`);
85
+ await this.bodies.initAsync(equipment.bodies);
86
+ await this.filters.initAsync(equipment.filters);
87
+ await this.circuits.initAsync(equipment.circuits);
88
+ await this.valves.initAsync(equipment.valves);
89
+ await this.heaters.initAsync(equipment.heaters);
90
+ await this.chlorinators.initAsync(equipment.chlorinators);
91
+ await this.chemControllers.initAsync(equipment.chemControllers);
92
+ await this.chemDosers.initAsync(equipment.chemDosers);
93
+ await this.pumps.initAsync(equipment.pumps);
94
+ await this.schedules.initAsync(equipment.schedules);
95
+ logger.info(`Nixie Controller Initialized`)
96
+ }
97
+ catch (err) { return Promise.reject(err); }
98
+ }
99
+ public async readLogFile(logFile: string): Promise<string[]> {
100
+ try {
101
+ let logPath = path.join(process.cwd(), '/logs');
102
+ if (!fs.existsSync(logPath)) fs.mkdirSync(logPath);
103
+ logPath += (`/${logFile}`);
104
+ let lines = [];
105
+ if (fs.existsSync(logPath)) {
106
+ let buff = fs.readFileSync(logPath);
107
+ lines = buff.toString().split('\n');
108
+ }
109
+ return lines;
110
+ } catch (err) { logger.error(`Error reading log file ${logFile}: ${err.message}`); }
111
+ }
112
+ public async logData(logFile: string, data: any) {
113
+ try {
114
+ let logPath = path.join(process.cwd(), '/logs');
115
+ if (!fs.existsSync(logPath)) fs.mkdirSync(logPath);
116
+ logPath += (`/${logFile}`);
117
+ let lines = [];
118
+ if (fs.existsSync(logPath)) {
119
+ let buff = fs.readFileSync(logPath);
120
+ lines = buff.toString().split('\n');
121
+ }
122
+ if (typeof data === 'object')
123
+ lines.unshift(JSON.stringify(data));
124
+ else
125
+ lines.unshift(data.toString());
126
+ fs.writeFileSync(logPath, lines.join('\n'));
127
+ } catch (err) { logger.error(`Error logging to ${logFile}: ${err.message}`); }
128
+ }
129
+ public async closeAsync() {
130
+ // Close all the associated equipment.
131
+ await this.chemDosers.closeAsync();
132
+ await this.chemControllers.closeAsync();
133
+ await this.chlorinators.closeAsync();
134
+ await this.heaters.closeAsync();
135
+ await this.circuits.closeAsync();
136
+ await this.pumps.closeAsync();
137
+ await this.filters.closeAsync();
138
+ await this.bodies.closeAsync();
139
+ await this.valves.closeAsync();
140
+ }
141
+ /*
142
+ * This method is used to obtain a list of existing REM servers for configuration. This returns all servers and
143
+ * their potential devices and is not designed to be used at run-time or to detect failure.
144
+ *
145
+ */
146
+ public async getREMServers() {
147
+ try {
148
+ let srv = [];
149
+ let servers = webApp.findServersByType('rem');
150
+ if (typeof servers !== 'undefined') {
151
+ for (let i = 0; i < servers.length; i++) {
152
+ let server = servers[i];
153
+ // Sometimes I hate type safety.
154
+ let devices = typeof server['getDevices'] === 'function' ? await server['getDevices']() : [];
155
+ let int = config.getInterfaceByUuid(servers[i].uuid);
156
+ srv.push({
157
+ uuid: servers[i].uuid,
158
+ name: servers[i].name,
159
+ type: servers[i].type,
160
+ isRunning: servers[i].isRunning,
161
+ isConnected: servers[i].isConnected,
162
+ devices: devices,
163
+ remoteConnectionId: servers[i].remoteConnectionId,
164
+ interface: int
165
+ });
166
+ }
167
+ await ncp.chemControllers.syncRemoteREMFeeds(srv);
168
+ }
169
+ return srv;
170
+ } catch (err) { logger.error(`Error gettting REM Servers: ${err.message}`); }
171
+ }
172
+ }
173
+
174
174
  export let ncp = new NixieControlPanel();