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,996 +1,1194 @@
1
- import { EquipmentNotFoundError, InvalidEquipmentDataError, InvalidEquipmentIdError, ParameterOutOfRangeError } from '../../Errors';
2
- import { utils, Timestamp } from '../../Constants';
3
- import { logger } from '../../../logger/Logger';
4
-
5
- import { NixieEquipment, NixieChildEquipment, NixieEquipmentCollection, INixieControlPanel } from "../NixieEquipment";
6
- import { Pump, PumpCircuit, PumpCollection, PumpRelay, sys } from "../../../controller/Equipment";
7
- import { CircuitState, PumpState, state, } from "../../State";
8
- import { setTimeout as setTimeoutSync, clearTimeout } from 'timers';
9
- import { NixieControlPanel } from '../Nixie';
10
- import { webApp, InterfaceServerResponse } from "../../../web/Server";
11
- import { Outbound, Protocol, Response } from '../../comms/messages/Messages';
12
- import { conn } from '../../comms/Comms';
13
- import { setTimeout } from 'timers/promises';
14
-
15
- export class NixiePumpCollection extends NixieEquipmentCollection<NixiePump> {
16
- public async deletePumpAsync(id: number) {
17
- try {
18
- for (let i = this.length - 1; i >= 0; i--) {
19
- let pump = this[i];
20
- if (pump.id === id) {
21
- await pump.closeAsync();
22
- this.splice(i, 1);
23
- }
24
- }
25
- } catch (err) { logger.error(`Nixie Control Panel deletePumpAsync ${err.message}`); }
26
- }
27
- public async setPumpStateAsync(pstate: PumpState) {
28
- try {
29
- let pump: NixiePump = this.find(elem => elem.id === pstate.id) as NixiePump;
30
- if (typeof pump === 'undefined') {
31
- return logger.error(`Nixie Control Panel Error setPumpState could not find pump ${pstate.id}-${pstate.name}`);
32
- }
33
- await pump.setPumpStateAsync(pstate);
34
- } catch (err) { logger.error(`Nixie Error setting pump state ${pstate.id}-${pstate.name}: ${err.message}`); return Promise.reject(err); }
35
- }
36
- public async setPumpAsync(pump: Pump, data: any) {
37
- // By the time we get here we know that we are in control and this is a Nixie pump.
38
- try {
39
- let c: NixiePump = this.find(elem => elem.id === pump.id) as NixiePump;
40
- if (typeof c === 'undefined') {
41
- pump.master = 1;
42
- if (typeof data.type !== 'undefined') pump.type = data.type; // needed for init of correct type
43
- if (typeof pump.type === 'undefined') return Promise.reject(new InvalidEquipmentIdError(`Invalid pump type for ${pump.name}`, data.id, 'Pump'));
44
- c = this.pumpFactory(pump);
45
- // c = new NixiePump(this.controlPanel, pump);
46
- this.push(c);
47
- logger.info(`A pump was not found for id #${pump.id} creating pump`);
48
- return await c.setPumpAsync(data);
49
- }
50
- else {
51
- if (typeof data.type !== 'undefined' && c.pump.type !== data.type) {
52
- // pump exists, changing type
53
- await c.closeAsync();
54
- pump.type = data.type; // needed for init of correct type
55
- if (typeof pump.type === 'undefined') return Promise.reject(new InvalidEquipmentIdError(`Invalid pump type for ${pump.name}`, data.id, 'Pump'));
56
- c = this.pumpFactory(pump);
57
- }
58
- return await c.setPumpAsync(data);
59
- }
60
- }
61
- catch (err) { logger.error(`setPumpAsync: ${err.message}`); return Promise.reject(err); }
62
- }
63
- public async initAsync(pumps: PumpCollection) {
64
- try {
65
- for (let i = 0; i < pumps.length; i++) {
66
- let pump = pumps.getItemByIndex(i);
67
- if (pump.master === 1) {
68
- let p: NixiePump = this.find(elem => elem.id === pump.id) as NixiePump;
69
- if (typeof p === 'undefined') {
70
- let type = sys.board.valueMaps.pumpTypes.getName(pump.type);
71
- let npump = this.pumpFactory(pump);
72
- logger.info(`Initializing Nixie Pump ${npump.id}-${pump.name}`);
73
- this.push(npump);
74
- await npump.initAsync();
75
- }
76
- }
77
- }
78
- }
79
- catch (err) { logger.error(`Nixie Pump initAsync Error: ${err.message}`); return Promise.reject(err); }
80
- }
81
- public async closeAsync() {
82
- try {
83
- for (let i = this.length - 1; i >= 0; i--) {
84
- try {
85
- try {
86
- await this[i].closeAsync();
87
- } catch (err) { logger.error(`Error attempting to close pump ${this[i].id}`); }
88
- this.splice(i, 1);
89
- } catch (err) { logger.error(`Error stopping Nixie Pump ${err}`); }
90
- }
91
- } catch (err) { } // Don't bail if we have an errror.
92
- }
93
- public async setServiceModeAsync() {
94
- try {
95
- for (let i = this.length - 1; i >= 0; i--) {
96
- try {
97
- let p = this[i] as NixiePump;
98
- await p.setServiceModeAsync();
99
- } catch (err) { logger.error(`Error setting service mode for Nixie Pump ${err}`); }
100
- }
101
- } catch (err) { } // Don't bail if we have an errror.
102
- }
103
- public async initPumpAsync(pump: Pump): Promise<NixiePump> {
104
- try {
105
- let c: NixiePump = this.find(elem => elem.id === pump.id) as NixiePump;
106
- if (pump.master === 1) {
107
- // if pump exists, close it so we can re-init
108
- // (EG if pump type changes, we need to setup a new instance of the pump)
109
- if (typeof c !== 'undefined' && c.pump.type !== pump.type) {
110
- await c.closeAsync();
111
- await this.deletePumpAsync(pump.id);
112
- c = this.pumpFactory(pump);
113
- this.push(c);
114
- }
115
- logger.info(`Initializing Existing Nixie Pump ${c.id}-${pump.name}`);
116
-
117
- }
118
- return c;
119
- } catch (err) { return Promise.reject(logger.error(`Nixie Controller: initPumpAsync Error: ${err.message}`)); }
120
- }
121
- private pumpFactory(pump: Pump) {
122
- let type = sys.board.valueMaps.pumpTypes.getName(pump.type);
123
- switch (type) {
124
- case 'ss':
125
- return new NixiePumpSS(this.controlPanel, pump);
126
- case 'ds':
127
- return new NixiePumpDS(this.controlPanel, pump);
128
- case 'vsf':
129
- return new NixiePumpVSF(this.controlPanel, pump);
130
- case 'vf':
131
- return new NixiePumpVF(this.controlPanel, pump);
132
- case 'sf':
133
- return new NixiePumpSF(this.controlPanel, pump);
134
- case 'vs':
135
- return new NixiePumpVS(this.controlPanel, pump);
136
- case 'hwvs':
137
- return new NixiePumpHWVS(this.controlPanel, pump);
138
- case 'hwrly':
139
- return new NixiePumpHWRLY(this.controlPanel, pump);
140
- default:
141
- throw new EquipmentNotFoundError(`NCP: Cannot create pump ${pump.name}.`, type);
142
- }
143
- }
144
- public syncPumpStates() {
145
- // loop through all pumps and update rates based on circuit changes
146
- // this would happen in <2s anyway based on pollAsync but this is immediate.
147
- for (let i = this.length - 1; i >= 0; i--) {
148
- let pump = this[i] as NixiePump;
149
- if (!pump.suspendPolling) setTimeoutSync(async () => { await pump.pollEquipmentAsync(); }, 100);
150
- else {
151
- pump.setTargetSpeed(state.pumps.getItemById(pump.id));
152
- }
153
- // RKS: 05-16-23 - Below backs up the processing.
154
- /*
155
-
156
- setTimeoutSync(async () => {
157
- let pump = this[i] as NixiePump;
158
- try {
159
- if (!pump.closing) await pump.pollEquipmentAsync();
160
- } catch (err) { }
161
- }, 100);
162
- */
163
- }
164
- }
165
- }
166
- export class NixiePump extends NixieEquipment {
167
- public pollingInterval: number = 2000;
168
- protected _pollTimer: NodeJS.Timeout = null;
169
- public pump: Pump;
170
- protected _targetSpeed: number;
171
- protected _suspendPolling = 0;
172
- public get suspendPolling(): boolean { return this._suspendPolling > 0; }
173
- public set suspendPolling(val: boolean) {
174
- this._suspendPolling = Math.max(0, this._suspendPolling + (val ? 1 : -1));
175
- if (this._suspendPolling > 1) console.log(`Suspend Polling ${this._suspendPolling}`);
176
- }
177
- public closing = false;
178
- public async setServiceModeAsync() {
179
- let pstate = state.pumps.getItemById(this.pump.id);
180
- await this.setPumpStateAsync(pstate);
181
- }
182
- /*
183
- _targetSpeed will hold values as follows:
184
- vs/vsf/vf: rpm/gpm;
185
- ss: 0=off, 1=on;
186
- ds/sf: bit shift 1-4 = values 1/2/4/8 for relays 1/2/3/4
187
- */
188
- constructor(ncp: INixieControlPanel, pump: Pump) {
189
- super(ncp);
190
- this.pump = pump;
191
- this._targetSpeed = 0;
192
- }
193
- public async initAsync() {
194
- if (this._pollTimer) {
195
- clearTimeout(this._pollTimer);
196
- this._pollTimer = undefined;
197
- }
198
- this.closing = false;
199
- this._suspendPolling = 0;
200
- this.pollEquipmentAsync();
201
- }
202
- public get id(): number { return typeof this.pump !== 'undefined' ? this.pump.id : -1; }
203
- public async setPumpStateAsync(pstate: PumpState) {
204
- try {
205
- // Here we go we need to set the pump state.
206
- return new InterfaceServerResponse(200, 'Ok');
207
- } catch (err) { return Promise.reject(`Nixie Error setting pump state ${pstate.id}-${pstate.name}: ${err.message}`); }
208
- }
209
- public async setPumpAsync(data: any): Promise<InterfaceServerResponse> {
210
- try {
211
- this.pump.master = 1;
212
- // if (typeof data.isVirtual !== 'undefined') this.pump.isVirtual = data.isVirtual;
213
- this.pump.isActive = true;
214
- // if (typeof data.type !== 'undefined' && data.type !== this.pump.type) {
215
- // sys.board.pumps.setType(this.pump, data.type);
216
- // this.pump = sys.pumps.getItemById(id, true);
217
- // spump = state.pumps.getItemById(id, true);
218
- // }
219
- let type = sys.board.valueMaps.pumpTypes.transform(this.pump.type);
220
- this.pump.name = data.name || this.pump.name || type.desc;
221
- if (typeof type.maxCircuits !== 'undefined' && type.maxCircuits > 0 && typeof data.circuits !== 'undefined') { // This pump type supports circuits
222
- for (let i = 1; i <= data.circuits.length && i <= type.maxCircuits; i++) {
223
- let c = data.circuits[i - 1];
224
- c.id = i;
225
- let circuit = parseInt(c.circuit, 10);
226
- let cd = this.pump.circuits.find(elem => elem.circuit === circuit);
227
- let speed = parseInt(c.speed, 10);
228
- let relay = parseInt(c.relay, 10);
229
- let flow = parseInt(c.flow, 10);
230
- let units = typeof c.units !== 'undefined' ? sys.board.valueMaps.pumpUnits.encode(c.units) : undefined;
231
- switch (type.name) {
232
- case 'vf':
233
- units = sys.board.valueMaps.pumpUnits.getValue('gpm');
234
- break;
235
- case 'hwvs':
236
- case 'vssvrs':
237
- case 'vs':
238
- c.units = sys.board.valueMaps.pumpUnits.getValue('rpm');
239
- break;
240
- case 'ss':
241
- case 'ds':
242
- case 'sf':
243
- case 'hwrly':
244
- c.units = undefined;
245
- break;
246
- }
247
- if (isNaN(units)) units = typeof cd !== 'undefined' ? cd.units : sys.board.valueMaps.pumpUnits.getValue('rpm');
248
- if (isNaN(speed)) speed = type.minSpeed;
249
- if (isNaN(flow)) flow = type.minFlow;
250
- if (isNaN(relay)) relay = 1;
251
- c.units = units;
252
- //c.units = parseInt(c.units, 10) || type.name === 'vf' ? sys.board.valueMaps.pumpUnits.getValue('gpm') : sys.board.valueMaps.pumpUnits.getValue('rpm');
253
- if (typeof type.minSpeed !== 'undefined' && c.units === sys.board.valueMaps.pumpUnits.getValue('rpm')) {
254
- c.speed = speed;
255
- }
256
- else if (typeof type.minFlow !== 'undefined' && c.units === sys.board.valueMaps.pumpUnits.getValue('gpm')) {
257
- c.flow = flow;
258
- }
259
- else if (type.maxRelays > 0)
260
- c.relay = relay;
261
- }
262
- }
263
- else data.circuits = [];
264
- this.pump.set(data); // Sets all the data back to the pump. This also sets the relays should it exist on the data.
265
- let spump = state.pumps.getItemById(this.pump.id, true);
266
- spump.name = this.pump.name;
267
- spump.address = this.pump.address;
268
- spump.type = this.pump.type;
269
- sys.pumps.sortById();
270
- state.pumps.sortById();
271
- this.pump.hasChanged = true;
272
- this.pollEquipmentAsync();
273
- return Promise.resolve(new InterfaceServerResponse(200, 'Ok'));
274
- }
275
- catch (err) { logger.error(`Nixie setPumpAsync: ${err.message}`); return Promise.reject(err); }
276
- }
277
- public async pollEquipmentAsync() {
278
- let self = this;
279
- try {
280
- // RSG 8-2022. Refactored to add initasync. With this.pollEquipmentAsync inside the
281
- // constructor we could get here before the pump is initialized. The added check
282
- // for the 112 address prevented that previously, but now is just a final fail safe.
283
- if (typeof this._pollTimer !== 'undefined' || this._pollTimer) clearTimeout(this._pollTimer);
284
- this._pollTimer = null;
285
- if (this.suspendPolling || this.closing || this.pump.address > 112) {
286
- if (this.suspendPolling) logger.info(`Pump ${this.id} Polling Suspended`);
287
- if (this.closing) logger.info(`Pump ${this.id} is closing`);
288
- return;
289
- }
290
- let pstate = state.pumps.getItemById(this.pump.id);
291
- this.setTargetSpeed(pstate);
292
- await this.setPumpStateAsync(pstate);
293
- }
294
- catch (err) { logger.error(`Nixie Error running pump sequence - ${err}`); }
295
- finally { if (!self.closing) this._pollTimer = setTimeoutSync(async () => await self.pollEquipmentAsync(), self.pollingInterval || 2000); }
296
- }
297
- private async checkHardwareStatusAsync(connectionId: string, deviceBinding: string) {
298
- try {
299
- let dev = await NixieEquipment.getDeviceService(connectionId, `/status/device/${deviceBinding}`);
300
- return dev;
301
- } catch (err) { logger.error(`Nixie Pump checkHardwareStatusAsync: ${err.message}`); return { hasFault: true } }
302
- }
303
- public async validateSetupAsync(pump: Pump, pstate: PumpState) {
304
- try {
305
- } catch (err) { logger.error(`Nixie Error checking Pump Hardware ${this.pump.name}: ${err.message}`); return Promise.reject(err); }
306
- }
307
- public async closeAsync() {
308
- try {
309
- logger.info(`Nixie Pump closing ${this.pump.name}.`)
310
- if (typeof this._pollTimer !== 'undefined' || this._pollTimer) clearTimeout(this._pollTimer);
311
- this._pollTimer = null;
312
- this._targetSpeed = 0;
313
- let pstate = state.pumps.getItemById(this.pump.id);
314
- try {
315
- await this.setPumpStateAsync(pstate);
316
- // Since we are closing we need to not reject.
317
- } catch (err) { logger.error(`Nixie Closing pump closeAsync: ${err.message}`); }
318
- // This will make sure the timer is dead and we are completely closed.
319
- this.closing = true;
320
- if (typeof this._pollTimer !== 'undefined' || this._pollTimer) clearTimeout(this._pollTimer);
321
- pstate.emitEquipmentChange();
322
- }
323
- catch (err) { logger.error(`Nixie Pump closeAsync: ${err.message}`); return Promise.reject(err); }
324
- }
325
- public logData(filename: string, data: any) { this.controlPanel.logData(filename, data); }
326
- public setTargetSpeed(pstate: PumpState) { };
327
- protected isBodyOn(bodyCode: number) {
328
- let assoc = sys.board.valueMaps.pumpBodies.transform(bodyCode);
329
- switch (assoc.name) {
330
- case 'body1':
331
- case 'pool':
332
- return state.temps.bodies.getItemById(1).isOn;
333
- case 'body2':
334
- case 'spa':
335
- return state.temps.bodies.getItemById(2).isOn;
336
- case 'body3':
337
- return state.temps.bodies.getItemById(3).isOn;
338
- case 'body4':
339
- return state.temps.bodies.getItemById(4).isOn;
340
- case 'poolspa':
341
- if (sys.equipment.shared && sys.equipment.maxBodies >= 2) {
342
- return state.temps.bodies.getItemById(1).isOn === true || state.temps.bodies.getItemById(2).isOn === true;
343
- }
344
- else
345
- return state.temps.bodies.getItemById(1).isOn;
346
- }
347
- return false;
348
- }
349
- }
350
- export class NixiePumpSS extends NixiePump {
351
- public setTargetSpeed(pState: PumpState) {
352
- // Turn on ss pumps.
353
- let _newSpeed = 0;
354
- if (!pState.pumpOnDelay) {
355
- let pt = sys.board.valueMaps.pumpTypes.get(this.pump.type);
356
- if (pt.maxCircuits === 0 || pt.hasBody) {
357
- _newSpeed = this.isBodyOn(this.pump.body) ? 1 : 0;
358
- //console.log(`BODY: ${sys.board.bodies.isBodyOn(this.pump.body)} CODE: ${this.pump.body}`);
359
- }
360
- else if (!pState.pumpOnDelay) {
361
- let pumpCircuits: PumpCircuit[] = this.pump.circuits.get();
362
- if (!pState.pumpOnDelay) {
363
- for (let i = 0; i < pumpCircuits.length; i++) {
364
- let circ = state.circuits.getInterfaceById(pumpCircuits[i].circuit);
365
- if (circ.isOn) _newSpeed = 1;
366
- }
367
- }
368
- }
369
- }
370
- if (this._targetSpeed !== _newSpeed) logger.info(`NCP: Setting Pump ${this.pump.name} to ${_newSpeed > 0 ? 'on' : 'off'}. ${sys.board.bodies.isBodyOn(this.pump.body)}`);
371
- if (isNaN(_newSpeed)) _newSpeed = 0;
372
- this._targetSpeed = _newSpeed;
373
- }
374
- public async setServiceModeAsync() {
375
- let pstate = state.pumps.getItemById(this.pump.id);
376
- pstate.targetSpeed = this._targetSpeed = 0;
377
- await this.setPumpStateAsync(pstate);
378
- }
379
- public async setPumpStateAsync(pstate: PumpState) {
380
- let relays: PumpRelay[] = this.pump.relays.get();
381
- let relayState = 0;
382
- for (let i = 0; i < relays.length; i++) {
383
- let pr = relays[i];
384
- if (typeof pr.id === 'undefined') pr.id = i + 1; // remove when id is added to dP relays upon save.
385
- let isOn = this._targetSpeed >> pr.id - 1 & 1;
386
- if (utils.isNullOrEmpty(pr.connectionId) || utils.isNullOrEmpty(pr.deviceBinding)) {
387
- // If they haven't set a program for the relay bugger out.
388
- if (isOn) relayState |= (1 << pr.id - 1);
389
- }
390
- else {
391
- try {
392
- let res = await NixieEquipment.putDeviceService(pr.connectionId, `/state/device/${pr.deviceBinding}`, { isOn, latch: isOn ? 5000 : undefined });
393
- if (res.status.code === 200) {
394
- if (isOn) relayState |= (1 << pr.id - 1);
395
- }
396
- else pstate.status = 16;
397
- }
398
- catch (err) {
399
- logger.error(`NCP: Error setting pump ${this.pump.name} relay ${pr.id} to ${isOn ? 'on' : 'off'}. Error ${err.message}}`);
400
- pstate.status = 16;
401
- }
402
- }
403
- }
404
- if (pstate.targetSpeed === 0) {
405
- pstate.status = 0;
406
- pstate.driveState = 0; // We need to set this if it is a priming cycle but it might not matter for our relay based pumps.
407
- pstate.command = 0;
408
- }
409
- else if (relayState === pstate.targetSpeed) {
410
- pstate.status = 1;
411
- pstate.driveState = 2;
412
- pstate.command = 4;
413
- }
414
- pstate.relay = relayState;
415
- return new InterfaceServerResponse(200, 'Success');
416
- }
417
- }
418
- export class NixiePumpDS extends NixiePumpSS {
419
- public setTargetSpeed(pState: PumpState) {
420
- // Turn on sf pumps. The new speed will be the relays associated with the pump. I believe when this comes out in the final
421
- // wash it should engage all the relays for all speeds associated with the pump. The pump logic will determine which program is
422
- // the one to engage.
423
- let _newSpeed = 0;
424
- if (!pState.pumpOnDelay) {
425
- let pumpCircuits: PumpCircuit[] = this.pump.circuits.get();
426
- if (!pState.pumpOnDelay) {
427
- for (let i = 0; i < pumpCircuits.length; i++) {
428
- let circ = state.circuits.getInterfaceById(pumpCircuits[i].circuit);
429
- // relay speeds are bit-shifted 'or' based on 1,2,4,8
430
- if (circ.isOn) _newSpeed |= (1 << pumpCircuits[i].relay - 1);
431
- }
432
- }
433
- }
434
- if (isNaN(_newSpeed)) _newSpeed = 0;
435
- this.logSpeed(_newSpeed);
436
- this._targetSpeed = _newSpeed;
437
- }
438
- public logSpeed(_newSpeed: number) {
439
- if (this._targetSpeed !== _newSpeed) logger.info(`NCP: Setting Pump ${this.pump.name} relays to Relay 1: ${_newSpeed & 1 ? 'on' : 'off'}, Relay 2: ${_newSpeed & 2 ? 'on' : 'off'}.`);
440
- }
441
- }
442
- export class NixiePumpSF extends NixiePumpDS {
443
- // effectively operates the same way as a DS pump since we removed the body association on DS.
444
- // only logger msg is different
445
- public logSpeed(_newSpeed: number) {
446
- if (this._targetSpeed !== _newSpeed) logger.info(`NCP: Setting Pump ${this.pump.name} relays to Relay 1: ${_newSpeed & 1 ? 'on' : 'off'}, Relay 2: ${_newSpeed & 2 ? 'on' : 'off'}, Relay 3: ${_newSpeed & 4 ? 'on' : 'off'}, and Relay 4: ${_newSpeed & 8 ? 'on' : 'off'}.`);
447
- }
448
- }
449
- export class NixiePumpHWRLY extends NixiePumpDS {
450
- // This operates as a relay pump with up to 8 speeds. The speeds are defined as follows. The override
451
- // relay should be defined as being normally closed. When it opens then the pump will turn on to the speed.
452
- // +-------+---------+---------+---------+---------+
453
- // + Speed | Relay 1 | Relay 2 | Relay 3 | OVRD |
454
- // +-------+---------+---------+---------+---------+
455
- // | OFF | OFF | OFF | OFF | OFF |
456
- // +-------+---------+---------+---------+---------+
457
- // | 1 | OFF | OFF | OFF | ON |
458
- // +-------+---------+---------+---------+---------+
459
- // | 2 | ON | OFF | OFF | ON |
460
- // +-------+---------+---------+---------+---------+
461
- // | 3 | OFF | ON | OFF | ON |
462
- // +-------+---------+---------+---------+---------+
463
- // | 4 | ON | ON | OFF | ON |
464
- // +-------+---------+---------+---------+---------+
465
- // | 5 | OFF | OFF | ON | ON |
466
- // +-------+---------+---------+---------+---------+
467
- // | 6 | ON | OFF | ON | ON |
468
- // +-------+---------+---------+---------+---------+
469
- // | 7 | OFF | ON | ON | ON |
470
- // +-------+---------+---------+---------+---------+
471
- // | 8 | ON | ON | ON | ON |
472
- // +-------+---------+---------+---------+---------+
473
-
474
- public setTargetSpeed(pState: PumpState) {
475
- let _newSpeed = 0;
476
- if (!pState.pumpOnDelay) {
477
- let pumpCircuits = this.pump.circuits.get();
478
- for (let i = 0; i < pumpCircuits.length; i++) {
479
- let circ = state.circuits.getInterfaceById(pumpCircuits[i].circuit);
480
- let pc = pumpCircuits[i];
481
- if (circ.isOn) {
482
- _newSpeed = Math.max(_newSpeed, pc.relay);
483
- }
484
- }
485
- }
486
- if (isNaN(_newSpeed)) _newSpeed = 0;
487
- this._targetSpeed = _newSpeed;
488
- if (this._targetSpeed !== 0) Math.min(Math.max(this.pump.minSpeed, this._targetSpeed), this.pump.maxSpeed);
489
- if (this._targetSpeed !== _newSpeed) logger.info(`NCP: Setting Pump ${this.pump.name} to ${_newSpeed}.`);
490
- }
491
- public async setPumpStateAsync(pstate: PumpState) {
492
- // Don't poll while we are seting the state.
493
- this.suspendPolling = true;
494
- try {
495
- let relays: PumpRelay[] = this.pump.relays.get();
496
- let relayState = 0;
497
- let targetState = 0;
498
- for (let i = 0; i < relays.length; i++) {
499
- let pr = relays[i];
500
- if (typeof pr.id === 'undefined') pr.id = i + 1; // remove when id is added to dP relays upon save.
501
- // If we are turning on the pump relay #4 needs to be on. NOTE: It is expected that the OVRD relay is hooked up in a normally closed
502
- // configuration so that whenever the pump is off the relay terminals are closed.
503
- let isOn = this._targetSpeed > 0 ? i === 3 ? true : (this._targetSpeed - 1 & (1 << i)) > 0 : false;
504
- let bit = isOn ? (1 << i) : 0;
505
- targetState |= bit;
506
- if (utils.isNullOrEmpty(pr.connectionId) || utils.isNullOrEmpty(pr.deviceBinding)) {
507
- // Determine whether the relay should be on.
508
- relayState |= bit;
509
- }
510
- else {
511
- try {
512
- let res = await NixieEquipment.putDeviceService(pr.connectionId, `/state/device/${pr.deviceBinding}`, { isOn, latch: isOn ? 5000 : undefined });
513
- if (res.status.code === 200) {
514
- relayState |= bit;
515
- }
516
- else pstate.status = 16;
517
- }
518
- catch (err) {
519
- logger.error(`NCP: Error setting pump ${this.pump.name} relay ${pr.id} to ${isOn ? 'on' : 'off'}. Error ${err.message}}`);
520
- pstate.status = 16;
521
- }
522
- }
523
- }
524
- pstate.command = this._targetSpeed;
525
- if (targetState === relayState) {
526
- pstate.status = relayState > 0 ? 1 : 0;
527
- pstate.driveState = relayState > 0 ? 2 : 0;
528
- pstate.relay = relayState;
529
- }
530
- else {
531
- pstate.driveState = 0;
532
- }
533
- return new InterfaceServerResponse(200, 'Success');
534
- }
535
- catch (err) {
536
- logger.error(`Error running pump sequence for ${this.pump.name}: ${err.message}`);
537
- return Promise.reject(err);
538
- }
539
- finally { this.suspendPolling = false; }
540
- };
541
-
542
- }
543
- export class NixiePumpRS485 extends NixiePump {
544
- public async setServiceModeAsync() {
545
- this._targetSpeed = 0;
546
- await this.setDriveStateAsync(false);
547
- await this.setPumpToRemoteControlAsync(false);
548
- }
549
- public async setPumpStateAsync(pstate: PumpState) {
550
- // Don't poll while we are seting the state.
551
- this.suspendPolling = true;
552
- try {
553
- let pt = sys.board.valueMaps.pumpTypes.get(this.pump.type);
554
- if (state.mode === 0) {
555
- // Since these process are async the closing flag can be set
556
- // between calls. We need to check it in between each call.
557
- if (!this.closing) await this.setDriveStateAsync();
558
- if (!this.closing) {
559
- if (this._targetSpeed >= pt.minFlow && this._targetSpeed <= pt.maxFlow) await this.setPumpGPMAsync();
560
- else if (this._targetSpeed >= pt.minSpeed && this._targetSpeed <= pt.maxSpeed) await this.setPumpRPMAsync();
561
- }
562
- ;
563
- if (!this.closing && pt.name !== 'vsf' && pt.name !== 'vs') await this.setPumpFeatureAsync(6);;
564
- if (!this.closing) await setTimeout(1000);;
565
- if (!this.closing) await this.requestPumpStatusAsync();;
566
- if (!this.closing) await this.setPumpToRemoteControlAsync();;
567
- }
568
- return new InterfaceServerResponse(200, 'Success');
569
- }
570
- catch (err) {
571
- logger.error(`Error running pump sequence for ${this.pump.name}: ${err.message}`);
572
- return Promise.reject(err);
573
- }
574
- finally { this.suspendPolling = false; }
575
- };
576
- protected async setDriveStateAsync(running: boolean = true) {
577
- try {
578
- if (conn.isPortEnabled(this.pump.portId || 0)) {
579
- let out = Outbound.create({
580
- portId: this.pump.portId || 0,
581
- protocol: Protocol.Pump,
582
- dest: this.pump.address,
583
- action: 6,
584
- payload: running && this._targetSpeed > 0 ? [10] : [4],
585
- retries: 1,
586
- response: true
587
- });
588
- try {
589
- await out.sendAsync();
590
- }
591
- catch (err) {
592
- logger.error(`Error sending setDriveState for ${this.pump.name}: ${err.message}`);
593
- }
594
- }
595
- else {
596
- let pstate = state.pumps.getItemById(this.pump.id);
597
- pstate.command = pstate.rpm > 0 || pstate.flow > 0 ? 10 : 0;
598
- }
599
- } catch (err) { logger.error(`Error setting driveState for ${this.pump.name}: ${err.message}`); }
600
- };
601
- protected async requestPumpStatusAsync() {
602
- if (conn.isPortEnabled(this.pump.portId || 0)) {
603
- let out = Outbound.create({
604
- portId: this.pump.portId || 0,
605
- protocol: Protocol.Pump,
606
- dest: this.pump.address,
607
- action: 7,
608
- payload: [],
609
- retries: 2,
610
- response: true,
611
- });
612
- try {
613
- await out.sendAsync();
614
- }
615
- catch (err) {
616
- logger.error(`Error sending requestPumpStatus for ${this.pump.name}: ${err.message}`);
617
- }
618
- }
619
- };
620
- protected async setPumpToRemoteControlAsync(running: boolean = true) {
621
- try {
622
- if (conn.isPortEnabled(this.pump.portId || 0)) {
623
- let out = Outbound.create({
624
- portId: this.pump.portId || 0,
625
- protocol: Protocol.Pump,
626
- dest: this.pump.address,
627
- action: 4,
628
- payload: running ? [255] : [0], // when stopAsync is called, pass false to return control to pump panel
629
- retries: 1,
630
- response: true
631
- });
632
- try {
633
- await out.sendAsync();
634
- }
635
- catch (err) {
636
- logger.error(`Error sending setPumpToRemoteControl for ${this.pump.name}: ${err.message}`);
637
- }
638
- }
639
- } catch (err) { logger.error(`Error setting pump to Remote Control for ${this.pump.name}: ${err.message}`); }
640
- }
641
- protected async setPumpFeatureAsync(feature?: number) {
642
- // empty payload (possibly 0?, too) is no feature
643
- // 6: Feature 1
644
- try {
645
- if (conn.isPortEnabled(this.pump.portId || 0)) {
646
- let out = Outbound.create({
647
- portId: this.pump.portId || 0,
648
- protocol: Protocol.Pump,
649
- dest: this.pump.address,
650
- action: 5,
651
- payload: typeof feature === 'undefined' ? [] : [feature],
652
- retries: 2,
653
- response: true
654
- });
655
- try {
656
- await out.sendAsync();
657
- }
658
- catch (err) {
659
- logger.error(`Error sending setPumpFeature for ${this.pump.name}: ${err.message}`);
660
- }
661
- }
662
- } catch (err) { logger.error(`Error setting pump feature for ${this.pump.name}: ${err.message}`); }
663
- };
664
- protected async setPumpRPMAsync() {
665
- if (conn.isPortEnabled(this.pump.portId || 0)) {
666
- let out = Outbound.create({
667
- portId: this.pump.portId || 0,
668
- protocol: Protocol.Pump,
669
- dest: this.pump.address,
670
- action: 1,
671
- payload: [2, 196, Math.floor(this._targetSpeed / 256), this._targetSpeed % 256],
672
- retries: 1,
673
- // timeout: 250,
674
- response: true
675
- });
676
- try {
677
- await out.sendAsync();
678
- }
679
- catch (err) {
680
- logger.error(`Error sending setPumpRPMAsync for ${this.pump.name}: ${err.message}`);
681
- }
682
- }
683
- };
684
- protected async setPumpGPMAsync() {
685
- // packet for vf; vsf will override
686
- if (conn.isPortEnabled(this.pump.portId || 0)) {
687
- let out = Outbound.create({
688
- portId: this.pump.portId || 0,
689
- protocol: Protocol.Pump,
690
- dest: this.pump.address,
691
- action: 1,
692
- payload: [2, 228, 0, this._targetSpeed],
693
- retries: 1,
694
- response: true
695
- });
696
- try {
697
- await out.sendAsync();
698
- }
699
- catch (err) {
700
- logger.error(`Error sending setPumpGPMAsync for ${this.pump.name}: ${err.message}`);
701
- }
702
- }
703
- };
704
- public async closeAsync() {
705
- try {
706
- this.suspendPolling = true;
707
- logger.info(`Nixie Pump closing ${this.pump.name}.`)
708
- if (typeof this._pollTimer !== 'undefined' || this._pollTimer) clearTimeout(this._pollTimer);
709
- this._pollTimer = null;
710
- this.closing = true;
711
- let pt = sys.board.valueMaps.pumpTypes.get(this.pump.type);
712
- let pstate = state.pumps.getItemById(this.pump.id);
713
- this._targetSpeed = 0;
714
- await this.setDriveStateAsync(false);
715
- if (!this.closing && pt.name !== 'vsf' && pt.name !== 'vs') await this.setPumpFeatureAsync();
716
- //await this.setPumpFeature();
717
- //await this.setDriveStateAsync(false);
718
- await this.setPumpToRemoteControlAsync(false);
719
- // Make sure the polling timer is dead after we have closed this all off. That way we do not
720
- // have another process that revives it from the dead.
721
- if (typeof this._pollTimer !== 'undefined' || this._pollTimer) clearTimeout(this._pollTimer);
722
- this._pollTimer = null;
723
- pstate.emitEquipmentChange();
724
- }
725
- catch (err) { logger.error(`Nixie Pump closeAsync: ${err.message}`); return Promise.reject(err); }
726
- finally { this.suspendPolling = false; }
727
- }
728
- }
729
- export class NixiePumpVS extends NixiePumpRS485 {
730
- public setTargetSpeed(pState: PumpState) {
731
- let _newSpeed = 0;
732
- if (!pState.pumpOnDelay) {
733
- let pumpCircuits = this.pump.circuits.get();
734
-
735
- for (let i = 0; i < pumpCircuits.length; i++) {
736
- let circ = state.circuits.getInterfaceById(pumpCircuits[i].circuit);
737
- let pc = pumpCircuits[i];
738
- if (circ.isOn) _newSpeed = Math.max(_newSpeed, pc.speed);
739
- }
740
- }
741
- if (isNaN(_newSpeed)) _newSpeed = 0;
742
- this._targetSpeed = _newSpeed;
743
- if (this._targetSpeed !== 0) Math.min(Math.max(this.pump.minSpeed, this._targetSpeed), this.pump.maxSpeed);
744
- if (this._targetSpeed !== _newSpeed) logger.info(`NCP: Setting Pump ${this.pump.name} to ${_newSpeed} RPM.`);
745
- }
746
- }
747
- export class NixiePumpVF extends NixiePumpRS485 {
748
- public setTargetSpeed(pState: PumpState) {
749
- let _newSpeed = 0;
750
- if (!pState.pumpOnDelay) {
751
- let pumpCircuits = this.pump.circuits.get();
752
- for (let i = 0; i < pumpCircuits.length; i++) {
753
- let circ = state.circuits.getInterfaceById(pumpCircuits[i].circuit);
754
- let pc = pumpCircuits[i];
755
- if (circ.isOn) _newSpeed = Math.max(_newSpeed, pc.flow);
756
- }
757
- }
758
- if (isNaN(_newSpeed)) _newSpeed = 0;
759
- this._targetSpeed = _newSpeed;
760
- if (this._targetSpeed !== 0) Math.min(Math.max(this.pump.minFlow, this._targetSpeed), this.pump.maxFlow);
761
- if (this._targetSpeed !== _newSpeed) logger.info(`NCP: Setting Pump ${this.pump.name} to ${_newSpeed} GPM.`);
762
- }
763
- public async setPumpStateAsync(pstate: PumpState) {
764
- // Don't poll while we are seting the state.
765
- this.suspendPolling = true;
766
- try {
767
- let pt = sys.board.valueMaps.pumpTypes.get(this.pump.type);
768
- if (state.mode === 0) {
769
- // Since these process are async the closing flag can be set
770
- // between calls. We need to check it in between each call. // 4, 6, 5, 7
771
- // When we are 0 then it sends 4[255], 6[4], 5[6]
772
- // When we are not 0 then it sends 4[255], 6[10], 5[6], 1[flow]
773
- if (!this.closing) await this.setPumpToRemoteControlAsync(); // Action 4
774
- if (!this.closing && this._targetSpeed > 0) await this.setPumpGPMAsync(); // Action 1
775
- if (!this.closing && this._targetSpeed > 0) await this.setPumpFeatureAsync(6); // Action 5
776
- // RKS: 07-21-24 - This used to send an empty payload when the pump should be off. For VF pumps it
777
- // appears that not setting the feature or target flow will set the pump off when it gets to
778
- // the drive state.
779
- //if (!this.closing) await this.setPumpFeatureAsync(this._targetSpeed > 0 ? 6 : undefined); // Action 5
780
- if (!this.closing) await this.setDriveStateAsync(); // Action 6
781
- if (!this.closing) await setTimeout(200);
782
- if (!this.closing) await this.requestPumpStatusAsync(); // Action 7
783
- }
784
- return new InterfaceServerResponse(200, 'Success');
785
- }
786
- catch (err) {
787
- logger.error(`Error running pump sequence for ${this.pump.name}: ${err.message}`);
788
- return Promise.reject(err);
789
- }
790
- finally { this.suspendPolling = false; }
791
- };
792
- }
793
- export class NixiePumpVSF extends NixiePumpRS485 {
794
- public setTargetSpeed(pState: PumpState) {
795
- let _newSpeed = 0;
796
- let maxRPM = 0;
797
- let maxGPM = 0;
798
- let useFlow = false;
799
- if (!pState.pumpOnDelay) {
800
- let pumpCircuits = this.pump.circuits.get();
801
- let pt = sys.board.valueMaps.pumpTypes.get(this.pump.type);
802
- // VSF pumps present a problem. In fact they do not currently operate properly on Touch panels. On touch these need to either be all in RPM or GPM
803
- // if there is a mix in the circuit array then they will not work. In IntelliCenter if there is an RPM setting in the mix it will use RPM by converting
804
- // the GPM to RPM but if there is none then it will use GPM.
805
- let toRPM = (flowRate: number, minSpeed: number = 450, maxSpeed: number = 3450) => {
806
- // eff = 114.4365
807
- // gpm = 80
808
- // speed = 2412
809
- let eff = .03317 * maxSpeed;
810
- let rpm = Math.min(Math.round((flowRate * maxSpeed) / eff), maxSpeed);
811
- return rpm > 0 ? Math.max(rpm, minSpeed) : 0;
812
- };
813
- let toGPM = (speed: number, maxSpeed: number = 3450, minFlow: number = 15, maxFlow: number = 140) => {
814
- // eff = 114.4365
815
- // speed = 1100
816
- // gpm = (114.4365 * 1100)/3450 = 36
817
- let eff = .03317 * maxSpeed;
818
- let gpm = Math.min(Math.round((eff * speed) / maxSpeed), maxFlow);
819
- return gpm > 0 ? Math.max(gpm, minFlow) : 0;
820
- }
821
- for (let i = 0; i < pumpCircuits.length; i++) {
822
- let circ = state.circuits.getInterfaceById(pumpCircuits[i].circuit);
823
- let pc = pumpCircuits[i];
824
- if (circ.isOn) {
825
- if (pc.units > 0) {
826
- let rpm = toRPM(pc.flow, pt.minSpeed, pt.MaxSpeed);
827
- if (rpm > maxRPM) useFlow = true;
828
- maxGPM = Math.max(maxGPM, pc.flow);
829
- rpm = Math.max(maxRPM, rpm);
830
- }
831
- else {
832
- let gpm = toGPM(pc.speed, pt.maxSpeed, pt.minFlow, pt.maxFlow);
833
- if (gpm > maxGPM) useFlow = false;
834
- maxRPM = Math.max(maxRPM, pc.speed);
835
- maxGPM = Math.max(maxGPM, gpm);
836
- }
837
- }
838
- }
839
- _newSpeed = useFlow ? maxGPM : maxRPM;
840
- }
841
- if (isNaN(_newSpeed)) _newSpeed = 0;
842
- // Send the flow message if it is flow and the rpm message if it is rpm.
843
- if (this._targetSpeed !== _newSpeed) logger.info(`NCP: Setting Pump ${this.pump.name} to ${_newSpeed} ${useFlow ? 'GPM' : 'RPM'}.`);
844
- this._targetSpeed = _newSpeed;
845
- }
846
- protected async setPumpRPMAsync() {
847
- // vsf action is 10 for rpm
848
- if (conn.isPortEnabled(this.pump.portId || 0)) {
849
- let out = Outbound.create({
850
- portId: this.pump.portId || 0,
851
- protocol: Protocol.Pump,
852
- dest: this.pump.address,
853
- action: 10,
854
- payload: [2, 196, Math.floor(this._targetSpeed / 256), this._targetSpeed % 256],
855
- retries: 1,
856
- // timeout: 250,
857
- response: true
858
- });
859
- try {
860
- await out.sendAsync();
861
- }
862
- catch (err) {
863
- logger.error(`Error sending setPumpRPMAsync for ${this.pump.name}: ${err.message}`);
864
- }
865
- }
866
- };
867
- protected async setPumpGPMAsync() {
868
- // vsf payload; different from vf payload
869
- if (conn.isPortEnabled(this.pump.portId || 0)) {
870
- let out = Outbound.create({
871
- portId: this.pump.portId || 0,
872
- protocol: Protocol.Pump,
873
- dest: this.pump.address,
874
- action: 9,
875
- payload: [2, 196, 0, this._targetSpeed],
876
- retries: 1,
877
- response: true
878
- });
879
- try {
880
- await out.sendAsync();
881
- }
882
- catch (err) {
883
- logger.error(`Error sending setPumpGPMAsync for ${this.pump.name}: ${err.message}`);
884
- }
885
- }
886
- };
887
- };
888
- export class NixiePumpHWVS extends NixiePumpRS485 {
889
- public setTargetSpeed(pState: PumpState) {
890
- let _newSpeed = 0;
891
- if (!pState.pumpOnDelay) {
892
- let pumpCircuits = this.pump.circuits.get();
893
-
894
- for (let i = 0; i < pumpCircuits.length; i++) {
895
- let circ = state.circuits.getInterfaceById(pumpCircuits[i].circuit);
896
- let pc = pumpCircuits[i];
897
- if (circ.isOn) _newSpeed = Math.max(_newSpeed, pc.speed);
898
- }
899
- }
900
- if (isNaN(_newSpeed)) _newSpeed = 0;
901
- this._targetSpeed = _newSpeed;
902
- if (this._targetSpeed !== 0) Math.min(Math.max(this.pump.minSpeed, this._targetSpeed), this.pump.maxSpeed);
903
- if (this._targetSpeed !== _newSpeed) logger.info(`NCP: Setting Pump ${this.pump.name} to ${_newSpeed} RPM.`);
904
- }
905
- public async setServiceModeAsync() {
906
- this._targetSpeed = 0;
907
- await this.setPumpRPMAsync();
908
- }
909
- public async setDriveStateAsync(running: boolean = false) { return Promise.resolve(); }
910
- public async setPumpStateAsync(pstate: PumpState) {
911
- // Don't poll while we are seting the state.
912
- this.suspendPolling = true;
913
- try {
914
- // Since these process are async the closing flag can be set
915
- // between calls. We need to check it in between each call.
916
- if (!this.closing) { await this.setPumpRPMAsync(); }
917
- return new InterfaceServerResponse(200, 'Success');
918
- }
919
- catch (err) {
920
- logger.error(`Error running pump sequence for ${this.pump.name}: ${err.message}`);
921
- return Promise.reject(err);
922
- }
923
- finally { this.suspendPolling = false; }
924
- };
925
- protected async requestPumpStatusAsync() { return Promise.resolve(); };
926
- protected setPumpFeatureAsync(feature?: number) { return Promise.resolve(); }
927
- protected async setPumpToRemoteControlAsync(running: boolean = true) {
928
- try {
929
- // We do nothing on this pump to set it to remote control. That is unless we are turning it off.
930
- if (conn.isPortEnabled(this.pump.portId || 0)) {
931
- if (!running) {
932
- let out = Outbound.create({
933
- portId: this.pump.portId || 0,
934
- protocol: Protocol.Hayward,
935
- source: 12, // Use the broadcast address
936
- dest: this.pump.address,
937
- action: 1,
938
- payload: [0], // when stopAsync is called, pass false to return control to pump panel
939
- // payload: spump.virtualControllerStatus === sys.board.valueMaps.virtualControllerStatus.getValue('running') ? [255] : [0],
940
- retries: 1,
941
- response: Response.create({ protocol: Protocol.Hayward, action: 12, source: this.pump.address - 96 })
942
- });
943
- try {
944
- await out.sendAsync();
945
- }
946
- catch (err) {
947
- logger.error(`Error sending setPumpToRemoteControl for ${this.pump.name}: ${err.message}`);
948
-
949
- }
950
- }
951
- }
952
- } catch(err) { `Error sending setPumpToRemoteControl message for ${this.pump.name}: ${err.message}` };
953
- }
954
- protected async setPumpRPMAsync() {
955
- // Address 1
956
- //[][16, 2, 12, 1, 0][41][0, 72, 16, 3] out
957
- //[][16, 2, 0, 12, 0][0, 41, 0, 135][0, 206, 16, 3] In
958
- // Address 2
959
- //[][16, 2, 12, 1, 1][100][0, 132, 16, 3] out
960
- //[][16, 2, 0, 12, 1][0, 96, 21, 64][0, 212, 16, 3] in
961
- // Note that action 12 is in a different position for the outbound than the inbound. The source and destination are kind
962
- // of a misnomer in that it identifies the equipment address in byte(4) of the header and flips the command address around.
963
- // So in essence for equipment item 0-16 (pump addresses) the outbound is really a broadcast on 12 (broadcast) from 1 and the inbound is
964
- // broadcast from the equipment item to 0 (anybody).
965
- if (conn.isPortEnabled(this.pump.portId || 0)) {
966
- let pt = sys.board.valueMaps.pumpTypes.get(this.pump.type);
967
- let out = Outbound.create({
968
- portId: this.pump.portId || 0,
969
- protocol: Protocol.Hayward,
970
- source: 1, // Use the broadcast address
971
- dest: this.pump.address - 96,
972
- action: 12,
973
- payload: [Math.min(Math.round((this._targetSpeed / pt.maxSpeed) * 100), 100)], // when stopAsync is called, pass false to return control to pump panel
974
- retries: 1,
975
- response: Response.create({ protocol: Protocol.Hayward, action: 12, source: this.pump.address - 96 })
976
- });
977
- try {
978
- await out.sendAsync();
979
- }
980
- catch (err) {
981
- logger.error(`Error sending setPumpRPM for ${this.pump.name}: ${err.message}`);
982
- let pstate = state.pumps.getItemById(this.pump.id);
983
- pstate.command = 0;
984
- pstate.rpm = 0;
985
- pstate.watts = 0;
986
- }
987
- }
988
- else {
989
- let pstate = state.pumps.getItemById(this.pump.id);
990
- pstate.command = 0;
991
- pstate.rpm = 0;
992
- pstate.watts = 0;
993
- }
994
-
995
- };
996
- }
1
+ import { EquipmentNotFoundError, InvalidEquipmentDataError, InvalidEquipmentIdError, ParameterOutOfRangeError } from '../../Errors';
2
+ import { utils, Timestamp } from '../../Constants';
3
+ import { logger } from '../../../logger/Logger';
4
+
5
+ import { NixieEquipment, NixieChildEquipment, NixieEquipmentCollection, INixieControlPanel } from "../NixieEquipment";
6
+ import { Pump, PumpCircuit, PumpCollection, PumpRelay, sys } from "../../../controller/Equipment";
7
+ import { CircuitState, PumpState, state, } from "../../State";
8
+ import { setTimeout as setTimeoutSync, clearTimeout } from 'timers';
9
+ import { NixieControlPanel } from '../Nixie';
10
+ import { webApp, InterfaceServerResponse } from "../../../web/Server";
11
+ import { Outbound, Protocol, Response } from '../../comms/messages/Messages';
12
+ import { conn } from '../../comms/Comms';
13
+ import { setTimeout } from 'timers/promises';
14
+
15
+ export class NixiePumpCollection extends NixieEquipmentCollection<NixiePump> {
16
+ public async deletePumpAsync(id: number) {
17
+ try {
18
+ for (let i = this.length - 1; i >= 0; i--) {
19
+ let pump = this[i];
20
+ if (pump.id === id) {
21
+ await pump.closeAsync();
22
+ this.splice(i, 1);
23
+ }
24
+ }
25
+ } catch (err) { logger.error(`Nixie Control Panel deletePumpAsync ${err.message}`); }
26
+ }
27
+ public async setPumpStateAsync(pstate: PumpState) {
28
+ try {
29
+ let pump: NixiePump = this.find(elem => elem.id === pstate.id) as NixiePump;
30
+ if (typeof pump === 'undefined') {
31
+ return logger.error(`Nixie Control Panel Error setPumpState could not find pump ${pstate.id}-${pstate.name}`);
32
+ }
33
+ await pump.setPumpStateAsync(pstate);
34
+ } catch (err) { logger.error(`Nixie Error setting pump state ${pstate.id}-${pstate.name}: ${err.message}`); return Promise.reject(err); }
35
+ }
36
+ public async setPumpAsync(pump: Pump, data: any) {
37
+ // By the time we get here we know that we are in control and this is a Nixie pump.
38
+ try {
39
+ let c: NixiePump = this.find(elem => elem.id === pump.id) as NixiePump;
40
+ if (typeof c === 'undefined') {
41
+ pump.master = 1;
42
+ if (typeof data.type !== 'undefined') pump.type = data.type; // needed for init of correct type
43
+ if (typeof pump.type === 'undefined') return Promise.reject(new InvalidEquipmentIdError(`Invalid pump type for ${pump.name}`, data.id, 'Pump'));
44
+ c = this.pumpFactory(pump);
45
+ // c = new NixiePump(this.controlPanel, pump);
46
+ this.push(c);
47
+ logger.info(`A pump was not found for id #${pump.id} creating pump`);
48
+ return await c.setPumpAsync(data);
49
+ }
50
+ else {
51
+ if (typeof data.type !== 'undefined' && c.pump.type !== data.type) {
52
+ // pump exists, changing type
53
+ await c.closeAsync();
54
+ pump.type = data.type; // needed for init of correct type
55
+ if (typeof pump.type === 'undefined') return Promise.reject(new InvalidEquipmentIdError(`Invalid pump type for ${pump.name}`, data.id, 'Pump'));
56
+ c = this.pumpFactory(pump);
57
+ }
58
+ return await c.setPumpAsync(data);
59
+ }
60
+ }
61
+ catch (err) { logger.error(`setPumpAsync: ${err.message}`); return Promise.reject(err); }
62
+ }
63
+ public async initAsync(pumps: PumpCollection) {
64
+ try {
65
+ for (let i = 0; i < pumps.length; i++) {
66
+ let pump = pumps.getItemByIndex(i);
67
+ if (pump.master === 1) {
68
+ let p: NixiePump = this.find(elem => elem.id === pump.id) as NixiePump;
69
+ if (typeof p === 'undefined') {
70
+ let type = sys.board.valueMaps.pumpTypes.getName(pump.type);
71
+ let npump = this.pumpFactory(pump);
72
+ logger.info(`Initializing Nixie Pump ${npump.id}-${pump.name}`);
73
+ this.push(npump);
74
+ await npump.initAsync();
75
+ }
76
+ }
77
+ }
78
+ }
79
+ catch (err) { logger.error(`Nixie Pump initAsync Error: ${err.message}`); return Promise.reject(err); }
80
+ }
81
+ public async closeAsync() {
82
+ try {
83
+ for (let i = this.length - 1; i >= 0; i--) {
84
+ try {
85
+ try {
86
+ await this[i].closeAsync();
87
+ } catch (err) { logger.error(`Error attempting to close pump ${this[i].id}`); }
88
+ this.splice(i, 1);
89
+ } catch (err) { logger.error(`Error stopping Nixie Pump ${err}`); }
90
+ }
91
+ } catch (err) { } // Don't bail if we have an errror.
92
+ }
93
+ public async setServiceModeAsync() {
94
+ try {
95
+ for (let i = this.length - 1; i >= 0; i--) {
96
+ try {
97
+ let p = this[i] as NixiePump;
98
+ await p.setServiceModeAsync();
99
+ } catch (err) { logger.error(`Error setting service mode for Nixie Pump ${err}`); }
100
+ }
101
+ } catch (err) { } // Don't bail if we have an errror.
102
+ }
103
+ public async initPumpAsync(pump: Pump): Promise<NixiePump> {
104
+ try {
105
+ let c: NixiePump = this.find(elem => elem.id === pump.id) as NixiePump;
106
+ if (pump.master === 1) {
107
+ // if pump exists, close it so we can re-init
108
+ // (EG if pump type changes, we need to setup a new instance of the pump)
109
+ if (typeof c !== 'undefined' && c.pump.type !== pump.type) {
110
+ await c.closeAsync();
111
+ await this.deletePumpAsync(pump.id);
112
+ c = this.pumpFactory(pump);
113
+ this.push(c);
114
+ }
115
+ logger.info(`Initializing Existing Nixie Pump ${c.id}-${pump.name}`);
116
+
117
+ }
118
+ return c;
119
+ } catch (err) { return Promise.reject(logger.error(`Nixie Controller: initPumpAsync Error: ${err.message}`)); }
120
+ }
121
+ private pumpFactory(pump: Pump) {
122
+ let type = sys.board.valueMaps.pumpTypes.getName(pump.type);
123
+ switch (type) {
124
+ case 'ss':
125
+ return new NixiePumpSS(this.controlPanel, pump);
126
+ case 'ds':
127
+ return new NixiePumpDS(this.controlPanel, pump);
128
+ case 'vsf':
129
+ return new NixiePumpVSF(this.controlPanel, pump);
130
+ case 'vf':
131
+ return new NixiePumpVF(this.controlPanel, pump);
132
+ case 'sf':
133
+ return new NixiePumpSF(this.controlPanel, pump);
134
+ case 'vs':
135
+ return new NixiePumpVS(this.controlPanel, pump);
136
+ case 'hwvs':
137
+ return new NixiePumpHWVS(this.controlPanel, pump);
138
+ case 'hwrly':
139
+ return new NixiePumpHWRLY(this.controlPanel, pump);
140
+ case 'regalmodbus':
141
+ return new NixiePumpRegalModbus(this.controlPanel, pump);
142
+ default:
143
+ throw new EquipmentNotFoundError(`NCP: Cannot create pump ${pump.name}.`, type);
144
+ }
145
+ }
146
+ public syncPumpStates() {
147
+ // loop through all pumps and update rates based on circuit changes
148
+ // this would happen in <2s anyway based on pollAsync but this is immediate.
149
+ for (let i = this.length - 1; i >= 0; i--) {
150
+ let pump = this[i] as NixiePump;
151
+ if (!pump.suspendPolling) setTimeoutSync(async () => { await pump.pollEquipmentAsync(); }, 100);
152
+ else {
153
+ pump.setTargetSpeed(state.pumps.getItemById(pump.id));
154
+ }
155
+ // RKS: 05-16-23 - Below backs up the processing.
156
+ /*
157
+
158
+ setTimeoutSync(async () => {
159
+ let pump = this[i] as NixiePump;
160
+ try {
161
+ if (!pump.closing) await pump.pollEquipmentAsync();
162
+ } catch (err) { }
163
+ }, 100);
164
+ */
165
+ }
166
+ }
167
+ }
168
+ export class NixiePump extends NixieEquipment {
169
+ public pollingInterval: number = 2000;
170
+ protected _pollTimer: NodeJS.Timeout = null;
171
+ public pump: Pump;
172
+ protected _targetSpeed: number;
173
+ protected _suspendPolling = 0;
174
+ public get suspendPolling(): boolean { return this._suspendPolling > 0; }
175
+ public set suspendPolling(val: boolean) {
176
+ this._suspendPolling = Math.max(0, this._suspendPolling + (val ? 1 : -1));
177
+ if (this._suspendPolling > 1) console.log(`Suspend Polling ${this._suspendPolling}`);
178
+ }
179
+ public closing = false;
180
+ public async setServiceModeAsync() {
181
+ let pstate = state.pumps.getItemById(this.pump.id);
182
+ await this.setPumpStateAsync(pstate);
183
+ }
184
+ /*
185
+ _targetSpeed will hold values as follows:
186
+ vs/vsf/vf: rpm/gpm;
187
+ ss: 0=off, 1=on;
188
+ ds/sf: bit shift 1-4 = values 1/2/4/8 for relays 1/2/3/4
189
+ */
190
+ constructor(ncp: INixieControlPanel, pump: Pump) {
191
+ super(ncp);
192
+ this.pump = pump;
193
+ this._targetSpeed = 0;
194
+ }
195
+ public async initAsync() {
196
+ if (this._pollTimer) {
197
+ clearTimeout(this._pollTimer);
198
+ this._pollTimer = undefined;
199
+ }
200
+ this.closing = false;
201
+ this._suspendPolling = 0;
202
+ this.pollEquipmentAsync();
203
+ }
204
+ public get id(): number { return typeof this.pump !== 'undefined' ? this.pump.id : -1; }
205
+ public async setPumpStateAsync(pstate: PumpState) {
206
+ try {
207
+ // Here we go we need to set the pump state.
208
+ return new InterfaceServerResponse(200, 'Ok');
209
+ } catch (err) { return Promise.reject(`Nixie Error setting pump state ${pstate.id}-${pstate.name}: ${err.message}`); }
210
+ }
211
+ public async setPumpAsync(data: any): Promise<InterfaceServerResponse> {
212
+ try {
213
+ this.pump.master = 1;
214
+ // if (typeof data.isVirtual !== 'undefined') this.pump.isVirtual = data.isVirtual;
215
+ this.pump.isActive = true;
216
+ // if (typeof data.type !== 'undefined' && data.type !== this.pump.type) {
217
+ // sys.board.pumps.setType(this.pump, data.type);
218
+ // this.pump = sys.pumps.getItemById(id, true);
219
+ // spump = state.pumps.getItemById(id, true);
220
+ // }
221
+ let type = sys.board.valueMaps.pumpTypes.transform(this.pump.type);
222
+ this.pump.name = data.name || this.pump.name || type.desc;
223
+ if (typeof type.maxCircuits !== 'undefined' && type.maxCircuits > 0 && typeof data.circuits !== 'undefined') { // This pump type supports circuits
224
+ for (let i = 1; i <= data.circuits.length && i <= type.maxCircuits; i++) {
225
+ let c = data.circuits[i - 1];
226
+ c.id = i;
227
+ let circuit = parseInt(c.circuit, 10);
228
+ let cd = this.pump.circuits.find(elem => elem.circuit === circuit);
229
+ let speed = parseInt(c.speed, 10);
230
+ let relay = parseInt(c.relay, 10);
231
+ let flow = parseInt(c.flow, 10);
232
+ let units = typeof c.units !== 'undefined' ? sys.board.valueMaps.pumpUnits.encode(c.units) : undefined;
233
+ switch (type.name) {
234
+ case 'vf':
235
+ units = sys.board.valueMaps.pumpUnits.getValue('gpm');
236
+ break;
237
+ case 'hwvs':
238
+ case 'vssvrs':
239
+ case 'vs':
240
+ case 'regalmodbus':
241
+ c.units = sys.board.valueMaps.pumpUnits.getValue('rpm');
242
+ break;
243
+ case 'ss':
244
+ case 'ds':
245
+ case 'sf':
246
+ case 'hwrly':
247
+ c.units = undefined;
248
+ break;
249
+ }
250
+ if (isNaN(units)) units = typeof cd !== 'undefined' ? cd.units : sys.board.valueMaps.pumpUnits.getValue('rpm');
251
+ if (isNaN(speed)) speed = type.minSpeed;
252
+ if (isNaN(flow)) flow = type.minFlow;
253
+ if (isNaN(relay)) relay = 1;
254
+ c.units = units;
255
+ //c.units = parseInt(c.units, 10) || type.name === 'vf' ? sys.board.valueMaps.pumpUnits.getValue('gpm') : sys.board.valueMaps.pumpUnits.getValue('rpm');
256
+ if (typeof type.minSpeed !== 'undefined' && c.units === sys.board.valueMaps.pumpUnits.getValue('rpm')) {
257
+ c.speed = speed;
258
+ }
259
+ else if (typeof type.minFlow !== 'undefined' && c.units === sys.board.valueMaps.pumpUnits.getValue('gpm')) {
260
+ c.flow = flow;
261
+ }
262
+ else if (type.maxRelays > 0)
263
+ c.relay = relay;
264
+ }
265
+ }
266
+ else data.circuits = [];
267
+ this.pump.set(data); // Sets all the data back to the pump. This also sets the relays should it exist on the data.
268
+ let spump = state.pumps.getItemById(this.pump.id, true);
269
+ spump.name = this.pump.name;
270
+ spump.address = this.pump.address;
271
+ spump.type = this.pump.type;
272
+ sys.pumps.sortById();
273
+ state.pumps.sortById();
274
+ this.pump.hasChanged = true;
275
+ this.pollEquipmentAsync();
276
+ return Promise.resolve(new InterfaceServerResponse(200, 'Ok'));
277
+ }
278
+ catch (err) { logger.error(`Nixie setPumpAsync: ${err.message}`); return Promise.reject(err); }
279
+ }
280
+ public async pollEquipmentAsync() {
281
+ let self = this;
282
+ try {
283
+ // RSG 8-2022. Refactored to add initasync. With this.pollEquipmentAsync inside the
284
+ // constructor we could get here before the pump is initialized. The added check
285
+ // for the 112 address prevented that previously, but now is just a final fail safe.
286
+ if (typeof this._pollTimer !== 'undefined' || this._pollTimer) clearTimeout(this._pollTimer);
287
+ this._pollTimer = null;
288
+ if (this.suspendPolling || this.closing || this.pump.address > 112) {
289
+ if (this.suspendPolling) logger.info(`Pump ${this.id} Polling Suspended`);
290
+ if (this.closing) logger.info(`Pump ${this.id} is closing`);
291
+ return;
292
+ }
293
+ let pstate = state.pumps.getItemById(this.pump.id);
294
+ this.setTargetSpeed(pstate);
295
+ await this.setPumpStateAsync(pstate);
296
+ }
297
+ catch (err) { logger.error(`Nixie Error running pump sequence - ${err}`); }
298
+ finally { if (!self.closing) this._pollTimer = setTimeoutSync(async () => await self.pollEquipmentAsync(), self.pollingInterval || 2000); }
299
+ }
300
+ private async checkHardwareStatusAsync(connectionId: string, deviceBinding: string) {
301
+ try {
302
+ let dev = await NixieEquipment.getDeviceService(connectionId, `/status/device/${deviceBinding}`);
303
+ return dev;
304
+ } catch (err) { logger.error(`Nixie Pump checkHardwareStatusAsync: ${err.message}`); return { hasFault: true } }
305
+ }
306
+ public async validateSetupAsync(pump: Pump, pstate: PumpState) {
307
+ try {
308
+ } catch (err) { logger.error(`Nixie Error checking Pump Hardware ${this.pump.name}: ${err.message}`); return Promise.reject(err); }
309
+ }
310
+ public async closeAsync() {
311
+ try {
312
+ logger.info(`Nixie Pump closing ${this.pump.name}.`)
313
+ if (typeof this._pollTimer !== 'undefined' || this._pollTimer) clearTimeout(this._pollTimer);
314
+ this._pollTimer = null;
315
+ this._targetSpeed = 0;
316
+ let pstate = state.pumps.getItemById(this.pump.id);
317
+ try {
318
+ await this.setPumpStateAsync(pstate);
319
+ // Since we are closing we need to not reject.
320
+ } catch (err) { logger.error(`Nixie Closing pump closeAsync: ${err.message}`); }
321
+ // This will make sure the timer is dead and we are completely closed.
322
+ this.closing = true;
323
+ if (typeof this._pollTimer !== 'undefined' || this._pollTimer) clearTimeout(this._pollTimer);
324
+ pstate.emitEquipmentChange();
325
+ }
326
+ catch (err) { logger.error(`Nixie Pump closeAsync: ${err.message}`); return Promise.reject(err); }
327
+ }
328
+ public logData(filename: string, data: any) { this.controlPanel.logData(filename, data); }
329
+ public setTargetSpeed(pstate: PumpState) { };
330
+ protected isBodyOn(bodyCode: number) {
331
+ let assoc = sys.board.valueMaps.pumpBodies.transform(bodyCode);
332
+ switch (assoc.name) {
333
+ case 'body1':
334
+ case 'pool':
335
+ return state.temps.bodies.getItemById(1).isOn;
336
+ case 'body2':
337
+ case 'spa':
338
+ return state.temps.bodies.getItemById(2).isOn;
339
+ case 'body3':
340
+ return state.temps.bodies.getItemById(3).isOn;
341
+ case 'body4':
342
+ return state.temps.bodies.getItemById(4).isOn;
343
+ case 'poolspa':
344
+ if (sys.equipment.shared && sys.equipment.maxBodies >= 2) {
345
+ return state.temps.bodies.getItemById(1).isOn === true || state.temps.bodies.getItemById(2).isOn === true;
346
+ }
347
+ else
348
+ return state.temps.bodies.getItemById(1).isOn;
349
+ }
350
+ return false;
351
+ }
352
+ }
353
+ export class NixiePumpSS extends NixiePump {
354
+ public setTargetSpeed(pState: PumpState) {
355
+ // Turn on ss pumps.
356
+ let _newSpeed = 0;
357
+ if (!pState.pumpOnDelay) {
358
+ let pt = sys.board.valueMaps.pumpTypes.get(this.pump.type);
359
+ if (pt.maxCircuits === 0 || pt.hasBody) {
360
+ _newSpeed = this.isBodyOn(this.pump.body) ? 1 : 0;
361
+ //console.log(`BODY: ${sys.board.bodies.isBodyOn(this.pump.body)} CODE: ${this.pump.body}`);
362
+ }
363
+ else if (!pState.pumpOnDelay) {
364
+ let pumpCircuits: PumpCircuit[] = this.pump.circuits.get();
365
+ if (!pState.pumpOnDelay) {
366
+ for (let i = 0; i < pumpCircuits.length; i++) {
367
+ let circ = state.circuits.getInterfaceById(pumpCircuits[i].circuit);
368
+ if (circ.isOn) _newSpeed = 1;
369
+ }
370
+ }
371
+ }
372
+ }
373
+ if (this._targetSpeed !== _newSpeed) logger.info(`NCP: Setting Pump ${this.pump.name} to ${_newSpeed > 0 ? 'on' : 'off'}. ${sys.board.bodies.isBodyOn(this.pump.body)}`);
374
+ if (isNaN(_newSpeed)) _newSpeed = 0;
375
+ this._targetSpeed = _newSpeed;
376
+ }
377
+ public async setServiceModeAsync() {
378
+ let pstate = state.pumps.getItemById(this.pump.id);
379
+ pstate.targetSpeed = this._targetSpeed = 0;
380
+ await this.setPumpStateAsync(pstate);
381
+ }
382
+ public async setPumpStateAsync(pstate: PumpState) {
383
+ let relays: PumpRelay[] = this.pump.relays.get();
384
+ let relayState = 0;
385
+ for (let i = 0; i < relays.length; i++) {
386
+ let pr = relays[i];
387
+ if (typeof pr.id === 'undefined') pr.id = i + 1; // remove when id is added to dP relays upon save.
388
+ let isOn = this._targetSpeed >> pr.id - 1 & 1;
389
+ if (utils.isNullOrEmpty(pr.connectionId) || utils.isNullOrEmpty(pr.deviceBinding)) {
390
+ // If they haven't set a program for the relay bugger out.
391
+ if (isOn) relayState |= (1 << pr.id - 1);
392
+ }
393
+ else {
394
+ try {
395
+ let res = await NixieEquipment.putDeviceService(pr.connectionId, `/state/device/${pr.deviceBinding}`, { isOn, latch: isOn ? 5000 : undefined });
396
+ if (res.status.code === 200) {
397
+ if (isOn) relayState |= (1 << pr.id - 1);
398
+ }
399
+ else pstate.status = 16;
400
+ }
401
+ catch (err) {
402
+ logger.error(`NCP: Error setting pump ${this.pump.name} relay ${pr.id} to ${isOn ? 'on' : 'off'}. Error ${err.message}}`);
403
+ pstate.status = 16;
404
+ }
405
+ }
406
+ }
407
+ if (pstate.targetSpeed === 0) {
408
+ pstate.status = 0;
409
+ pstate.driveState = 0; // We need to set this if it is a priming cycle but it might not matter for our relay based pumps.
410
+ pstate.command = 0;
411
+ }
412
+ else if (relayState === pstate.targetSpeed) {
413
+ pstate.status = 1;
414
+ pstate.driveState = 2;
415
+ pstate.command = 4;
416
+ }
417
+ pstate.relay = relayState;
418
+ return new InterfaceServerResponse(200, 'Success');
419
+ }
420
+ }
421
+ export class NixiePumpDS extends NixiePumpSS {
422
+ public setTargetSpeed(pState: PumpState) {
423
+ // Turn on sf pumps. The new speed will be the relays associated with the pump. I believe when this comes out in the final
424
+ // wash it should engage all the relays for all speeds associated with the pump. The pump logic will determine which program is
425
+ // the one to engage.
426
+ let _newSpeed = 0;
427
+ if (!pState.pumpOnDelay) {
428
+ let pumpCircuits: PumpCircuit[] = this.pump.circuits.get();
429
+ if (!pState.pumpOnDelay) {
430
+ for (let i = 0; i < pumpCircuits.length; i++) {
431
+ let circ = state.circuits.getInterfaceById(pumpCircuits[i].circuit);
432
+ // relay speeds are bit-shifted 'or' based on 1,2,4,8
433
+ if (circ.isOn) _newSpeed |= (1 << pumpCircuits[i].relay - 1);
434
+ }
435
+ }
436
+ }
437
+ if (isNaN(_newSpeed)) _newSpeed = 0;
438
+ this.logSpeed(_newSpeed);
439
+ this._targetSpeed = _newSpeed;
440
+ }
441
+ public logSpeed(_newSpeed: number) {
442
+ if (this._targetSpeed !== _newSpeed) logger.info(`NCP: Setting Pump ${this.pump.name} relays to Relay 1: ${_newSpeed & 1 ? 'on' : 'off'}, Relay 2: ${_newSpeed & 2 ? 'on' : 'off'}.`);
443
+ }
444
+ }
445
+ export class NixiePumpSF extends NixiePumpDS {
446
+ // effectively operates the same way as a DS pump since we removed the body association on DS.
447
+ // only logger msg is different
448
+ public logSpeed(_newSpeed: number) {
449
+ if (this._targetSpeed !== _newSpeed) logger.info(`NCP: Setting Pump ${this.pump.name} relays to Relay 1: ${_newSpeed & 1 ? 'on' : 'off'}, Relay 2: ${_newSpeed & 2 ? 'on' : 'off'}, Relay 3: ${_newSpeed & 4 ? 'on' : 'off'}, and Relay 4: ${_newSpeed & 8 ? 'on' : 'off'}.`);
450
+ }
451
+ }
452
+ export class NixiePumpHWRLY extends NixiePumpDS {
453
+ // This operates as a relay pump with up to 8 speeds. The speeds are defined as follows. The override
454
+ // relay should be defined as being normally closed. When it opens then the pump will turn on to the speed.
455
+ // +-------+---------+---------+---------+---------+
456
+ // + Speed | Relay 1 | Relay 2 | Relay 3 | OVRD |
457
+ // +-------+---------+---------+---------+---------+
458
+ // | OFF | OFF | OFF | OFF | OFF |
459
+ // +-------+---------+---------+---------+---------+
460
+ // | 1 | OFF | OFF | OFF | ON |
461
+ // +-------+---------+---------+---------+---------+
462
+ // | 2 | ON | OFF | OFF | ON |
463
+ // +-------+---------+---------+---------+---------+
464
+ // | 3 | OFF | ON | OFF | ON |
465
+ // +-------+---------+---------+---------+---------+
466
+ // | 4 | ON | ON | OFF | ON |
467
+ // +-------+---------+---------+---------+---------+
468
+ // | 5 | OFF | OFF | ON | ON |
469
+ // +-------+---------+---------+---------+---------+
470
+ // | 6 | ON | OFF | ON | ON |
471
+ // +-------+---------+---------+---------+---------+
472
+ // | 7 | OFF | ON | ON | ON |
473
+ // +-------+---------+---------+---------+---------+
474
+ // | 8 | ON | ON | ON | ON |
475
+ // +-------+---------+---------+---------+---------+
476
+
477
+ public setTargetSpeed(pState: PumpState) {
478
+ let _newSpeed = 0;
479
+ if (!pState.pumpOnDelay) {
480
+ let pumpCircuits = this.pump.circuits.get();
481
+ for (let i = 0; i < pumpCircuits.length; i++) {
482
+ let circ = state.circuits.getInterfaceById(pumpCircuits[i].circuit);
483
+ let pc = pumpCircuits[i];
484
+ if (circ.isOn) {
485
+ _newSpeed = Math.max(_newSpeed, pc.relay);
486
+ }
487
+ }
488
+ }
489
+ if (isNaN(_newSpeed)) _newSpeed = 0;
490
+ this._targetSpeed = _newSpeed;
491
+ if (this._targetSpeed !== 0) Math.min(Math.max(this.pump.minSpeed, this._targetSpeed), this.pump.maxSpeed);
492
+ if (this._targetSpeed !== _newSpeed) logger.info(`NCP: Setting Pump ${this.pump.name} to ${_newSpeed}.`);
493
+ }
494
+ public async setPumpStateAsync(pstate: PumpState) {
495
+ // Don't poll while we are seting the state.
496
+ this.suspendPolling = true;
497
+ try {
498
+ let relays: PumpRelay[] = this.pump.relays.get();
499
+ let relayState = 0;
500
+ let targetState = 0;
501
+ for (let i = 0; i < relays.length; i++) {
502
+ let pr = relays[i];
503
+ if (typeof pr.id === 'undefined') pr.id = i + 1; // remove when id is added to dP relays upon save.
504
+ // If we are turning on the pump relay #4 needs to be on. NOTE: It is expected that the OVRD relay is hooked up in a normally closed
505
+ // configuration so that whenever the pump is off the relay terminals are closed.
506
+ let isOn = this._targetSpeed > 0 ? i === 3 ? true : (this._targetSpeed - 1 & (1 << i)) > 0 : false;
507
+ let bit = isOn ? (1 << i) : 0;
508
+ targetState |= bit;
509
+ if (utils.isNullOrEmpty(pr.connectionId) || utils.isNullOrEmpty(pr.deviceBinding)) {
510
+ // Determine whether the relay should be on.
511
+ relayState |= bit;
512
+ }
513
+ else {
514
+ try {
515
+ let res = await NixieEquipment.putDeviceService(pr.connectionId, `/state/device/${pr.deviceBinding}`, { isOn, latch: isOn ? 5000 : undefined });
516
+ if (res.status.code === 200) {
517
+ relayState |= bit;
518
+ }
519
+ else pstate.status = 16;
520
+ }
521
+ catch (err) {
522
+ logger.error(`NCP: Error setting pump ${this.pump.name} relay ${pr.id} to ${isOn ? 'on' : 'off'}. Error ${err.message}}`);
523
+ pstate.status = 16;
524
+ }
525
+ }
526
+ }
527
+ pstate.command = this._targetSpeed;
528
+ if (targetState === relayState) {
529
+ pstate.status = relayState > 0 ? 1 : 0;
530
+ pstate.driveState = relayState > 0 ? 2 : 0;
531
+ pstate.relay = relayState;
532
+ }
533
+ else {
534
+ pstate.driveState = 0;
535
+ }
536
+ return new InterfaceServerResponse(200, 'Success');
537
+ }
538
+ catch (err) {
539
+ logger.error(`Error running pump sequence for ${this.pump.name}: ${err.message}`);
540
+ return Promise.reject(err);
541
+ }
542
+ finally { this.suspendPolling = false; }
543
+ };
544
+
545
+ }
546
+ export class NixiePumpRS485 extends NixiePump {
547
+ public async setServiceModeAsync() {
548
+ this._targetSpeed = 0;
549
+ await this.setDriveStateAsync(false);
550
+ await this.setPumpToRemoteControlAsync(false);
551
+ }
552
+ public async setPumpStateAsync(pstate: PumpState) {
553
+ // Don't poll while we are seting the state.
554
+ this.suspendPolling = true;
555
+ try {
556
+ let pt = sys.board.valueMaps.pumpTypes.get(this.pump.type);
557
+ if (state.mode === 0) {
558
+ // Since these process are async the closing flag can be set
559
+ // between calls. We need to check it in between each call.
560
+ if (!this.closing) await this.setDriveStateAsync();
561
+ if (!this.closing) {
562
+ if (this._targetSpeed >= pt.minFlow && this._targetSpeed <= pt.maxFlow) await this.setPumpGPMAsync();
563
+ else if (this._targetSpeed >= pt.minSpeed && this._targetSpeed <= pt.maxSpeed) await this.setPumpRPMAsync();
564
+ }
565
+ ;
566
+ if (!this.closing && pt.name !== 'vsf' && pt.name !== 'vs') await this.setPumpFeatureAsync(6);;
567
+ if (!this.closing) await setTimeout(1000);;
568
+ if (!this.closing) await this.requestPumpStatusAsync();;
569
+ if (!this.closing) await this.setPumpToRemoteControlAsync();;
570
+ }
571
+ return new InterfaceServerResponse(200, 'Success');
572
+ }
573
+ catch (err) {
574
+ logger.error(`Error running pump sequence for ${this.pump.name}: ${err.message}`);
575
+ return Promise.reject(err);
576
+ }
577
+ finally { this.suspendPolling = false; }
578
+ };
579
+ protected async setDriveStateAsync(running: boolean = true) {
580
+ try {
581
+ if (conn.isPortEnabled(this.pump.portId || 0)) {
582
+ let out = Outbound.create({
583
+ portId: this.pump.portId || 0,
584
+ protocol: Protocol.Pump,
585
+ dest: this.pump.address,
586
+ action: 6,
587
+ payload: running && this._targetSpeed > 0 ? [10] : [4],
588
+ retries: 1,
589
+ response: true
590
+ });
591
+ try {
592
+ await out.sendAsync();
593
+ }
594
+ catch (err) {
595
+ logger.error(`Error sending setDriveState for ${this.pump.name}: ${err.message}`);
596
+ }
597
+ }
598
+ else {
599
+ let pstate = state.pumps.getItemById(this.pump.id);
600
+ pstate.command = pstate.rpm > 0 || pstate.flow > 0 ? 10 : 0;
601
+ }
602
+ } catch (err) { logger.error(`Error setting driveState for ${this.pump.name}: ${err.message}`); }
603
+ };
604
+ protected async requestPumpStatusAsync() {
605
+ if (conn.isPortEnabled(this.pump.portId || 0)) {
606
+ let out = Outbound.create({
607
+ portId: this.pump.portId || 0,
608
+ protocol: Protocol.Pump,
609
+ dest: this.pump.address,
610
+ action: 7,
611
+ payload: [],
612
+ retries: 2,
613
+ response: true,
614
+ });
615
+ try {
616
+ await out.sendAsync();
617
+ }
618
+ catch (err) {
619
+ logger.error(`Error sending requestPumpStatus for ${this.pump.name}: ${err.message}`);
620
+ }
621
+ }
622
+ };
623
+ protected async setPumpToRemoteControlAsync(running: boolean = true) {
624
+ try {
625
+ if (conn.isPortEnabled(this.pump.portId || 0)) {
626
+ let out = Outbound.create({
627
+ portId: this.pump.portId || 0,
628
+ protocol: Protocol.Pump,
629
+ dest: this.pump.address,
630
+ action: 4,
631
+ payload: running ? [255] : [0], // when stopAsync is called, pass false to return control to pump panel
632
+ retries: 1,
633
+ response: true
634
+ });
635
+ try {
636
+ await out.sendAsync();
637
+ }
638
+ catch (err) {
639
+ logger.error(`Error sending setPumpToRemoteControl for ${this.pump.name}: ${err.message}`);
640
+ }
641
+ }
642
+ } catch (err) { logger.error(`Error setting pump to Remote Control for ${this.pump.name}: ${err.message}`); }
643
+ }
644
+ protected async setPumpFeatureAsync(feature?: number) {
645
+ // empty payload (possibly 0?, too) is no feature
646
+ // 6: Feature 1
647
+ try {
648
+ if (conn.isPortEnabled(this.pump.portId || 0)) {
649
+ let out = Outbound.create({
650
+ portId: this.pump.portId || 0,
651
+ protocol: Protocol.Pump,
652
+ dest: this.pump.address,
653
+ action: 5,
654
+ payload: typeof feature === 'undefined' ? [] : [feature],
655
+ retries: 2,
656
+ response: true
657
+ });
658
+ try {
659
+ await out.sendAsync();
660
+ }
661
+ catch (err) {
662
+ logger.error(`Error sending setPumpFeature for ${this.pump.name}: ${err.message}`);
663
+ }
664
+ }
665
+ } catch (err) { logger.error(`Error setting pump feature for ${this.pump.name}: ${err.message}`); }
666
+ };
667
+ protected async setPumpRPMAsync() {
668
+ if (conn.isPortEnabled(this.pump.portId || 0)) {
669
+ let out = Outbound.create({
670
+ portId: this.pump.portId || 0,
671
+ protocol: Protocol.Pump,
672
+ dest: this.pump.address,
673
+ action: 1,
674
+ payload: [2, 196, Math.floor(this._targetSpeed / 256), this._targetSpeed % 256],
675
+ retries: 1,
676
+ // timeout: 250,
677
+ response: true
678
+ });
679
+ try {
680
+ await out.sendAsync();
681
+ }
682
+ catch (err) {
683
+ logger.error(`Error sending setPumpRPMAsync for ${this.pump.name}: ${err.message}`);
684
+ }
685
+ }
686
+ };
687
+ protected async setPumpGPMAsync() {
688
+ // packet for vf; vsf will override
689
+ if (conn.isPortEnabled(this.pump.portId || 0)) {
690
+ let out = Outbound.create({
691
+ portId: this.pump.portId || 0,
692
+ protocol: Protocol.Pump,
693
+ dest: this.pump.address,
694
+ action: 1,
695
+ payload: [2, 228, 0, this._targetSpeed],
696
+ retries: 1,
697
+ response: true
698
+ });
699
+ try {
700
+ await out.sendAsync();
701
+ }
702
+ catch (err) {
703
+ logger.error(`Error sending setPumpGPMAsync for ${this.pump.name}: ${err.message}`);
704
+ }
705
+ }
706
+ };
707
+ public async closeAsync() {
708
+ try {
709
+ this.suspendPolling = true;
710
+ logger.info(`Nixie Pump closing ${this.pump.name}.`)
711
+ if (typeof this._pollTimer !== 'undefined' || this._pollTimer) clearTimeout(this._pollTimer);
712
+ this._pollTimer = null;
713
+ this.closing = true;
714
+ let pt = sys.board.valueMaps.pumpTypes.get(this.pump.type);
715
+ let pstate = state.pumps.getItemById(this.pump.id);
716
+ this._targetSpeed = 0;
717
+ await this.setDriveStateAsync(false);
718
+ if (!this.closing && pt.name !== 'vsf' && pt.name !== 'vs') await this.setPumpFeatureAsync();
719
+ //await this.setPumpFeature();
720
+ //await this.setDriveStateAsync(false);
721
+ await this.setPumpToRemoteControlAsync(false);
722
+ // Make sure the polling timer is dead after we have closed this all off. That way we do not
723
+ // have another process that revives it from the dead.
724
+ if (typeof this._pollTimer !== 'undefined' || this._pollTimer) clearTimeout(this._pollTimer);
725
+ this._pollTimer = null;
726
+ pstate.emitEquipmentChange();
727
+ }
728
+ catch (err) { logger.error(`Nixie Pump closeAsync: ${err.message}`); return Promise.reject(err); }
729
+ finally { this.suspendPolling = false; }
730
+ }
731
+ }
732
+ export class NixiePumpVS extends NixiePumpRS485 {
733
+ public setTargetSpeed(pState: PumpState) {
734
+ let _newSpeed = 0;
735
+ if (!pState.pumpOnDelay) {
736
+ let pumpCircuits = this.pump.circuits.get();
737
+
738
+ for (let i = 0; i < pumpCircuits.length; i++) {
739
+ let circ = state.circuits.getInterfaceById(pumpCircuits[i].circuit);
740
+ let pc = pumpCircuits[i];
741
+ if (circ.isOn) _newSpeed = Math.max(_newSpeed, pc.speed);
742
+ }
743
+ }
744
+ if (isNaN(_newSpeed)) _newSpeed = 0;
745
+ this._targetSpeed = _newSpeed;
746
+ if (this._targetSpeed !== 0) Math.min(Math.max(this.pump.minSpeed, this._targetSpeed), this.pump.maxSpeed);
747
+ if (this._targetSpeed !== _newSpeed) logger.info(`NCP: Setting Pump ${this.pump.name} to ${_newSpeed} RPM.`);
748
+ }
749
+ }
750
+ export class NixiePumpVF extends NixiePumpRS485 {
751
+ public setTargetSpeed(pState: PumpState) {
752
+ let _newSpeed = 0;
753
+ if (!pState.pumpOnDelay) {
754
+ let pumpCircuits = this.pump.circuits.get();
755
+ for (let i = 0; i < pumpCircuits.length; i++) {
756
+ let circ = state.circuits.getInterfaceById(pumpCircuits[i].circuit);
757
+ let pc = pumpCircuits[i];
758
+ if (circ.isOn) _newSpeed = Math.max(_newSpeed, pc.flow);
759
+ }
760
+ }
761
+ if (isNaN(_newSpeed)) _newSpeed = 0;
762
+ this._targetSpeed = _newSpeed;
763
+ if (this._targetSpeed !== 0) Math.min(Math.max(this.pump.minFlow, this._targetSpeed), this.pump.maxFlow);
764
+ if (this._targetSpeed !== _newSpeed) logger.info(`NCP: Setting Pump ${this.pump.name} to ${_newSpeed} GPM.`);
765
+ }
766
+ public async setPumpStateAsync(pstate: PumpState) {
767
+ // Don't poll while we are seting the state.
768
+ this.suspendPolling = true;
769
+ try {
770
+ let pt = sys.board.valueMaps.pumpTypes.get(this.pump.type);
771
+ if (state.mode === 0) {
772
+ // Since these process are async the closing flag can be set
773
+ // between calls. We need to check it in between each call. // 4, 6, 5, 7
774
+ // When we are 0 then it sends 4[255], 6[4], 5[6]
775
+ // When we are not 0 then it sends 4[255], 6[10], 5[6], 1[flow]
776
+ if (!this.closing) await this.setPumpToRemoteControlAsync(); // Action 4
777
+ if (!this.closing && this._targetSpeed > 0) await this.setPumpGPMAsync(); // Action 1
778
+ if (!this.closing && this._targetSpeed > 0) await this.setPumpFeatureAsync(6); // Action 5
779
+ // RKS: 07-21-24 - This used to send an empty payload when the pump should be off. For VF pumps it
780
+ // appears that not setting the feature or target flow will set the pump off when it gets to
781
+ // the drive state.
782
+ //if (!this.closing) await this.setPumpFeatureAsync(this._targetSpeed > 0 ? 6 : undefined); // Action 5
783
+ if (!this.closing) await this.setDriveStateAsync(); // Action 6
784
+ if (!this.closing) await setTimeout(200);
785
+ if (!this.closing) await this.requestPumpStatusAsync(); // Action 7
786
+ }
787
+ return new InterfaceServerResponse(200, 'Success');
788
+ }
789
+ catch (err) {
790
+ logger.error(`Error running pump sequence for ${this.pump.name}: ${err.message}`);
791
+ return Promise.reject(err);
792
+ }
793
+ finally { this.suspendPolling = false; }
794
+ };
795
+ }
796
+ export class NixiePumpVSF extends NixiePumpRS485 {
797
+ public setTargetSpeed(pState: PumpState) {
798
+ let _newSpeed = 0;
799
+ let maxRPM = 0;
800
+ let maxGPM = 0;
801
+ let useFlow = false;
802
+ if (!pState.pumpOnDelay) {
803
+ let pumpCircuits = this.pump.circuits.get();
804
+ let pt = sys.board.valueMaps.pumpTypes.get(this.pump.type);
805
+ // VSF pumps present a problem. In fact they do not currently operate properly on Touch panels. On touch these need to either be all in RPM or GPM
806
+ // if there is a mix in the circuit array then they will not work. In IntelliCenter if there is an RPM setting in the mix it will use RPM by converting
807
+ // the GPM to RPM but if there is none then it will use GPM.
808
+ let toRPM = (flowRate: number, minSpeed: number = 450, maxSpeed: number = 3450) => {
809
+ // eff = 114.4365
810
+ // gpm = 80
811
+ // speed = 2412
812
+ let eff = .03317 * maxSpeed;
813
+ let rpm = Math.min(Math.round((flowRate * maxSpeed) / eff), maxSpeed);
814
+ return rpm > 0 ? Math.max(rpm, minSpeed) : 0;
815
+ };
816
+ let toGPM = (speed: number, maxSpeed: number = 3450, minFlow: number = 15, maxFlow: number = 140) => {
817
+ // eff = 114.4365
818
+ // speed = 1100
819
+ // gpm = (114.4365 * 1100)/3450 = 36
820
+ let eff = .03317 * maxSpeed;
821
+ let gpm = Math.min(Math.round((eff * speed) / maxSpeed), maxFlow);
822
+ return gpm > 0 ? Math.max(gpm, minFlow) : 0;
823
+ }
824
+ for (let i = 0; i < pumpCircuits.length; i++) {
825
+ let circ = state.circuits.getInterfaceById(pumpCircuits[i].circuit);
826
+ let pc = pumpCircuits[i];
827
+ if (circ.isOn) {
828
+ if (pc.units > 0) {
829
+ let rpm = toRPM(pc.flow, pt.minSpeed, pt.MaxSpeed);
830
+ if (rpm > maxRPM) useFlow = true;
831
+ maxGPM = Math.max(maxGPM, pc.flow);
832
+ rpm = Math.max(maxRPM, rpm);
833
+ }
834
+ else {
835
+ let gpm = toGPM(pc.speed, pt.maxSpeed, pt.minFlow, pt.maxFlow);
836
+ if (gpm > maxGPM) useFlow = false;
837
+ maxRPM = Math.max(maxRPM, pc.speed);
838
+ maxGPM = Math.max(maxGPM, gpm);
839
+ }
840
+ }
841
+ }
842
+ _newSpeed = useFlow ? maxGPM : maxRPM;
843
+ }
844
+ if (isNaN(_newSpeed)) _newSpeed = 0;
845
+ // Send the flow message if it is flow and the rpm message if it is rpm.
846
+ if (this._targetSpeed !== _newSpeed) logger.info(`NCP: Setting Pump ${this.pump.name} to ${_newSpeed} ${useFlow ? 'GPM' : 'RPM'}.`);
847
+ this._targetSpeed = _newSpeed;
848
+ }
849
+ protected async setPumpRPMAsync() {
850
+ // vsf action is 10 for rpm
851
+ if (conn.isPortEnabled(this.pump.portId || 0)) {
852
+ let out = Outbound.create({
853
+ portId: this.pump.portId || 0,
854
+ protocol: Protocol.Pump,
855
+ dest: this.pump.address,
856
+ action: 10,
857
+ payload: [2, 196, Math.floor(this._targetSpeed / 256), this._targetSpeed % 256],
858
+ retries: 1,
859
+ // timeout: 250,
860
+ response: true
861
+ });
862
+ try {
863
+ await out.sendAsync();
864
+ }
865
+ catch (err) {
866
+ logger.error(`Error sending setPumpRPMAsync for ${this.pump.name}: ${err.message}`);
867
+ }
868
+ }
869
+ };
870
+ protected async setPumpGPMAsync() {
871
+ // vsf payload; different from vf payload
872
+ if (conn.isPortEnabled(this.pump.portId || 0)) {
873
+ let out = Outbound.create({
874
+ portId: this.pump.portId || 0,
875
+ protocol: Protocol.Pump,
876
+ dest: this.pump.address,
877
+ action: 9,
878
+ payload: [2, 196, 0, this._targetSpeed],
879
+ retries: 1,
880
+ response: true
881
+ });
882
+ try {
883
+ await out.sendAsync();
884
+ }
885
+ catch (err) {
886
+ logger.error(`Error sending setPumpGPMAsync for ${this.pump.name}: ${err.message}`);
887
+ }
888
+ }
889
+ };
890
+ };
891
+ export class NixiePumpHWVS extends NixiePumpRS485 {
892
+ public setTargetSpeed(pState: PumpState) {
893
+ let _newSpeed = 0;
894
+ if (!pState.pumpOnDelay) {
895
+ let pumpCircuits = this.pump.circuits.get();
896
+
897
+ for (let i = 0; i < pumpCircuits.length; i++) {
898
+ let circ = state.circuits.getInterfaceById(pumpCircuits[i].circuit);
899
+ let pc = pumpCircuits[i];
900
+ if (circ.isOn) _newSpeed = Math.max(_newSpeed, pc.speed);
901
+ }
902
+ }
903
+ if (isNaN(_newSpeed)) _newSpeed = 0;
904
+ this._targetSpeed = _newSpeed;
905
+ if (this._targetSpeed !== 0) Math.min(Math.max(this.pump.minSpeed, this._targetSpeed), this.pump.maxSpeed);
906
+ if (this._targetSpeed !== _newSpeed) logger.info(`NCP: Setting Pump ${this.pump.name} to ${_newSpeed} RPM.`);
907
+ }
908
+ public async setServiceModeAsync() {
909
+ this._targetSpeed = 0;
910
+ await this.setPumpRPMAsync();
911
+ }
912
+ public async setDriveStateAsync(running: boolean = false) { return Promise.resolve(); }
913
+ public async setPumpStateAsync(pstate: PumpState) {
914
+ // Don't poll while we are seting the state.
915
+ this.suspendPolling = true;
916
+ try {
917
+ // Since these process are async the closing flag can be set
918
+ // between calls. We need to check it in between each call.
919
+ if (!this.closing) { await this.setPumpRPMAsync(); }
920
+ return new InterfaceServerResponse(200, 'Success');
921
+ }
922
+ catch (err) {
923
+ logger.error(`Error running pump sequence for ${this.pump.name}: ${err.message}`);
924
+ return Promise.reject(err);
925
+ }
926
+ finally { this.suspendPolling = false; }
927
+ };
928
+ protected async requestPumpStatusAsync() { return Promise.resolve(); };
929
+ protected setPumpFeatureAsync(feature?: number) { return Promise.resolve(); }
930
+ protected async setPumpToRemoteControlAsync(running: boolean = true) {
931
+ try {
932
+ // We do nothing on this pump to set it to remote control. That is unless we are turning it off.
933
+ if (conn.isPortEnabled(this.pump.portId || 0)) {
934
+ if (!running) {
935
+ let out = Outbound.create({
936
+ portId: this.pump.portId || 0,
937
+ protocol: Protocol.Hayward,
938
+ source: 12, // Use the broadcast address
939
+ dest: this.pump.address,
940
+ action: 1,
941
+ payload: [0], // when stopAsync is called, pass false to return control to pump panel
942
+ // payload: spump.virtualControllerStatus === sys.board.valueMaps.virtualControllerStatus.getValue('running') ? [255] : [0],
943
+ retries: 1,
944
+ response: Response.create({ protocol: Protocol.Hayward, action: 12, source: this.pump.address - 96 })
945
+ });
946
+ try {
947
+ await out.sendAsync();
948
+ }
949
+ catch (err) {
950
+ logger.error(`Error sending setPumpToRemoteControl for ${this.pump.name}: ${err.message}`);
951
+
952
+ }
953
+ }
954
+ }
955
+ } catch(err) { `Error sending setPumpToRemoteControl message for ${this.pump.name}: ${err.message}` };
956
+ }
957
+ protected async setPumpRPMAsync() {
958
+ // Address 1
959
+ //[][16, 2, 12, 1, 0][41][0, 72, 16, 3] out
960
+ //[][16, 2, 0, 12, 0][0, 41, 0, 135][0, 206, 16, 3] In
961
+ // Address 2
962
+ //[][16, 2, 12, 1, 1][100][0, 132, 16, 3] out
963
+ //[][16, 2, 0, 12, 1][0, 96, 21, 64][0, 212, 16, 3] in
964
+ // Note that action 12 is in a different position for the outbound than the inbound. The source and destination are kind
965
+ // of a misnomer in that it identifies the equipment address in byte(4) of the header and flips the command address around.
966
+ // So in essence for equipment item 0-16 (pump addresses) the outbound is really a broadcast on 12 (broadcast) from 1 and the inbound is
967
+ // broadcast from the equipment item to 0 (anybody).
968
+ if (conn.isPortEnabled(this.pump.portId || 0)) {
969
+ let pt = sys.board.valueMaps.pumpTypes.get(this.pump.type);
970
+ let out = Outbound.create({
971
+ portId: this.pump.portId || 0,
972
+ protocol: Protocol.Hayward,
973
+ source: 1, // Use the broadcast address
974
+ dest: this.pump.address - 96,
975
+ action: 12,
976
+ payload: [Math.min(Math.round((this._targetSpeed / pt.maxSpeed) * 100), 100)], // when stopAsync is called, pass false to return control to pump panel
977
+ retries: 1,
978
+ response: Response.create({ protocol: Protocol.Hayward, action: 12, source: this.pump.address - 96 })
979
+ });
980
+ try {
981
+ await out.sendAsync();
982
+ }
983
+ catch (err) {
984
+ logger.error(`Error sending setPumpRPM for ${this.pump.name}: ${err.message}`);
985
+ let pstate = state.pumps.getItemById(this.pump.id);
986
+ pstate.command = 0;
987
+ pstate.rpm = 0;
988
+ pstate.watts = 0;
989
+ }
990
+ }
991
+ else {
992
+ let pstate = state.pumps.getItemById(this.pump.id);
993
+ pstate.command = 0;
994
+ pstate.rpm = 0;
995
+ pstate.watts = 0;
996
+ }
997
+
998
+ };
999
+ }
1000
+
1001
+ export class NixiePumpRegalModbus extends NixiePump {
1002
+
1003
+ constructor(ncp: INixieControlPanel, pump: Pump) {
1004
+ super(ncp, pump);
1005
+ // this.pump = pump;
1006
+ // this._targetSpeed = 0;
1007
+ }
1008
+
1009
+ public setTargetSpeed(pumpState: PumpState) {
1010
+ let newSpeed = 0;
1011
+ if (!pumpState.pumpOnDelay) {
1012
+ let circuitConfigs = this.pump.circuits.get();
1013
+ for (let i = 0; i < circuitConfigs.length; i++) {
1014
+ let circuitConfig = circuitConfigs[i];
1015
+ let circ = state.circuits.getInterfaceById(circuitConfig.circuit);
1016
+ if (circ.isOn) newSpeed = Math.max(newSpeed, circuitConfig.speed);
1017
+ }
1018
+ }
1019
+ if (isNaN(newSpeed)) newSpeed = 0;
1020
+ this._targetSpeed = newSpeed;
1021
+ if (this._targetSpeed !== 0) Math.min(Math.max(this.pump.minSpeed, this._targetSpeed), this.pump.maxSpeed);
1022
+ if (this._targetSpeed !== newSpeed) logger.info(`NCP: Setting Pump ${this.pump.name} to ${newSpeed} RPM.`);
1023
+ }
1024
+
1025
+ public async setServiceModeAsync() {
1026
+ this._targetSpeed = 0;
1027
+ await this.setDriveStateAsync(false);
1028
+ // await this.setPumpToRemoteControlAsync(false);
1029
+ }
1030
+
1031
+ public async setPumpStateAsync(pstate: PumpState) {
1032
+ // Don't poll while we are seting the state.
1033
+ this.suspendPolling = true;
1034
+ try {
1035
+ let pt = sys.board.valueMaps.pumpTypes.get(this.pump.type);
1036
+ if (state.mode === 0) {
1037
+ // Since these process are async the closing flag can be set
1038
+ // between calls. We need to check it in between each call.
1039
+ if (!this.closing) {
1040
+ if (this._targetSpeed >= pt.minSpeed && this._targetSpeed <= pt.maxSpeed) await this.setPumpRPMAsync();
1041
+ }
1042
+ if (!this.closing) await this.setDriveStateAsync();
1043
+ ;
1044
+ // if (!this.closing && pt.name !== 'vsf' && pt.name !== 'vs') await this.setPumpFeatureAsync(6);;
1045
+ if (!this.closing) await setTimeout(1000);;
1046
+ if (!this.closing) await this.requestPumpStatusAsync();;
1047
+ // if (!this.closing) await this.setPumpToRemoteControlAsync();;
1048
+ }
1049
+ return new InterfaceServerResponse(200, 'Success');
1050
+ }
1051
+ catch (err) {
1052
+ logger.error(`Error running pump sequence for ${this.pump.name}: ${err.message}`);
1053
+ return Promise.reject(err);
1054
+ }
1055
+ finally { this.suspendPolling = false; }
1056
+ };
1057
+ protected async setDriveStateAsync(isRunning: boolean = true) {
1058
+ let functionCode = this._targetSpeed > 0 ? 0x41 : 0x42;
1059
+ logger.debug(`NixiePumpRegalModbus: setDriveStateAsync ${this.pump.name} ${functionCode == 0x41 ? 'RUN' : functionCode == 0x42 ? 'STOP' : 'UNKNOWN'}`);
1060
+ try {
1061
+ if (conn.isPortEnabled(this.pump.portId || 0)) {
1062
+ let functionCode = this._targetSpeed > 0 ? 0x41 : 0x42;
1063
+ let out = Outbound.create({
1064
+ portId: this.pump.portId || 0,
1065
+ protocol: Protocol.RegalModbus,
1066
+ dest: this.pump.address,
1067
+ action: functionCode,
1068
+ payload: [],
1069
+ retries: 1,
1070
+ response: true
1071
+ });
1072
+ try {
1073
+ await out.sendAsync();
1074
+ }
1075
+ catch (err) {
1076
+ logger.error(`Error sending setDriveState for ${this.pump.name}: ${err.message}`);
1077
+ }
1078
+ }
1079
+ else {
1080
+ let pumpState = state.pumps.getItemById(this.pump.id);
1081
+ pumpState.command = pumpState.rpm > 0 || pumpState.flow > 0 ? 10 : 0; // dashPanel needs this to be set to 10 for running.
1082
+ }
1083
+ } catch (err) { logger.error(`Error setting driveState for ${this.pump.name}: ${err.message}`); }
1084
+ };
1085
+
1086
+ protected async requestPumpDriveStateAsync() {
1087
+ if (conn.isPortEnabled(this.pump.portId || 0)) {
1088
+ let out = Outbound.create({
1089
+ portId: this.pump.portId || 0,
1090
+ protocol: Protocol.RegalModbus,
1091
+ dest: this.pump.address,
1092
+ action: 0x43,
1093
+ payload: [],
1094
+ retries: 2,
1095
+ response: true,
1096
+ });
1097
+ try {
1098
+ await out.sendAsync();
1099
+ }
1100
+ catch (err) {
1101
+ logger.error(`Error sending requestPumpDriveState for ${this.pump.name}: ${err.message}`);
1102
+ }
1103
+ }
1104
+ }
1105
+
1106
+ protected async requestSensorAsync(page: number, sensorAddr: number, retries: number = 2) {
1107
+ if (conn.isPortEnabled(this.pump.portId || 0)) {
1108
+ let out = Outbound.create({
1109
+ portId: this.pump.portId || 0,
1110
+ protocol: Protocol.RegalModbus,
1111
+ dest: this.pump.address,
1112
+ action: 0x45,
1113
+ payload: [page, sensorAddr],
1114
+ retries: retries,
1115
+ response: true,
1116
+ });
1117
+ try {
1118
+ await out.sendAsync();
1119
+ }
1120
+ catch (err) {
1121
+ logger.error(`Error sending requestSensor for ${this.pump.name} page ${page} sensor ${sensorAddr}: ${err.message}`);
1122
+ }
1123
+ }
1124
+ }
1125
+
1126
+ protected async requestPumpStatusAsync() {
1127
+
1128
+ await this.requestPumpDriveStateAsync();
1129
+ await this.requestSensorAsync(0, 0x00); // motor speed
1130
+ // await this.requestSensorAsync(0, 0x01); // motor current
1131
+ // await this.requestSensorAsync(0, 0x04); // torque
1132
+ // await this.requestSensorAsync(0, 0x05); // inverter input power
1133
+ // await this.requestSensorAsync(0, 0x06); // DC bus voltage
1134
+ // await this.requestSensorAsync(0, 0x07); // ambient temperature
1135
+ await this.requestSensorAsync(0, 0x0A); // output power
1136
+ // await this.requestSensorAsync(0, 0x0D); // motor line voltage
1137
+ // await this.requestSensorAsync(0, 0x0E); // ramp status
1138
+ // await this.requestSensorAsync(0, 0x0F); // no of total fault
1139
+ // await this.requestSensorAsync(0, 0x10); // prime status
1140
+ // await this.requestSensorAsync(0, 0x11); // motor input power
1141
+ // await this.requestSensorAsync(0, 0x12); // IGBT temperature
1142
+ // await this.requestSensorAsync(0, 0x13); // PCB temperature
1143
+ };
1144
+
1145
+ protected async setPumpRPMAsync() {
1146
+ logger.debug(`NixiePumpRegalModbus: setPumpRPMAsync ${this.pump.name} ${this._targetSpeed}`);
1147
+ if (conn.isPortEnabled(this.pump.portId || 0)) {
1148
+ // get demand bytes from rpm
1149
+ const mode = 0x00; // 0x00 for speed control mode
1150
+ const demandLo = Math.round(this._targetSpeed * 4) & 0xFF;
1151
+ const demandHi = (Math.round(this._targetSpeed * 4) >> 8) & 0xFF;
1152
+ let out = Outbound.create({
1153
+ portId: this.pump.portId || 0,
1154
+ protocol: Protocol.RegalModbus,
1155
+ dest: this.pump.address,
1156
+ action: 0x44,
1157
+ payload: [mode, demandLo, demandHi],
1158
+ retries: 1,
1159
+ // timeout: 250,
1160
+ response: true
1161
+ });
1162
+ try {
1163
+ await out.sendAsync();
1164
+ }
1165
+ catch (err) {
1166
+ logger.error(`Error sending setPumpRPMAsync for ${this.pump.name}: ${err.message}`);
1167
+ }
1168
+ }
1169
+ };
1170
+ public async closeAsync() {
1171
+ try {
1172
+ this.suspendPolling = true;
1173
+ logger.info(`Nixie Pump closing ${this.pump.name}.`)
1174
+ if (typeof this._pollTimer !== 'undefined' || this._pollTimer) clearTimeout(this._pollTimer);
1175
+ this._pollTimer = null;
1176
+ this.closing = true;
1177
+ let pumpType = sys.board.valueMaps.pumpTypes.get(this.pump.type);
1178
+ let pumpState = state.pumps.getItemById(this.pump.id);
1179
+ this._targetSpeed = 0;
1180
+ await this.setDriveStateAsync(false);
1181
+ // if (!this.closing && pt.name !== 'vsf' && pt.name !== 'vs') await this.setPumpFeatureAsync();
1182
+ //await this.setPumpFeature();
1183
+ //await this.setDriveStateAsync(false);
1184
+ // await this.setPumpToRemoteControlAsync(false);
1185
+ // Make sure the polling timer is dead after we have closed this all off. That way we do not
1186
+ // have another process that revives it from the dead.
1187
+ if (typeof this._pollTimer !== 'undefined' || this._pollTimer) clearTimeout(this._pollTimer);
1188
+ this._pollTimer = null;
1189
+ pumpState.emitEquipmentChange();
1190
+ }
1191
+ catch (err) { logger.error(`Nixie Pump closeAsync: ${err.message}`); return Promise.reject(err); }
1192
+ finally { this.suspendPolling = false; }
1193
+ }
1194
+ }