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
package/logger/Logger.ts CHANGED
@@ -1,436 +1,448 @@
1
- /* nodejs-poolController. An application to control pool equipment.
2
- Copyright (C) 2016, 2017, 2018, 2019, 2020, 2021, 2022.
3
- Russell Goldin, tagyoureit. russ.goldin@gmail.com
4
-
5
- This program is free software: you can redistribute it and/or modify
6
- it under the terms of the GNU Affero General Public License as
7
- published by the Free Software Foundation, either version 3 of the
8
- License, or (at your option) any later version.
9
-
10
- This program is distributed in the hope that it will be useful,
11
- but WITHOUT ANY WARRANTY; without even the implied warranty of
12
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
- GNU Affero General Public License for more details.
14
-
15
- You should have received a copy of the GNU Affero General Public License
16
- along with this program. If not, see <http://www.gnu.org/licenses/>.
17
- */
18
- import * as path from 'path';
19
- import * as fs from 'fs';
20
- import * as winston from 'winston';
21
- import * as os from 'os';
22
- import { utils } from "../controller/Constants";
23
- import { Message } from '../controller/comms/messages/Messages';
24
- import { config } from '../config/Config';
25
- import { webApp } from '../web/Server';
26
- import { sl } from '../controller/comms/ScreenLogic';
27
-
28
- const extend = require("extend");
29
-
30
- class Logger {
31
- constructor() {
32
- if (!fs.existsSync(path.join(process.cwd(), '/logs'))) fs.mkdirSync(path.join(process.cwd(), '/logs'));
33
- this.pktPath = path.join(process.cwd(), '/logs', this.getPacketPath());
34
- this.captureForReplayBaseDir = path.join(process.cwd(), '/logs/', this.getLogTimestamp());
35
- /* this.captureForReplayPath = path.join(this.captureForReplayBaseDir, '/packetCapture.json'); */
36
- this.pkts = [];
37
- this.slMessages = [];
38
- }
39
- private cfg;
40
- private pkts: Message[];
41
- private slMessages: any[];
42
- private pktPath: string;
43
- private consoleToFilePath: string;
44
- private transports: { console: winston.transports.ConsoleTransportInstance, file?: winston.transports.FileTransportInstance, consoleFile?: winston.transports.FileTransportInstance } = {
45
- console: new winston.transports.Console({ level: 'silly' })
46
- };
47
- private captureForReplayBaseDir: string;
48
- private captureForReplayPath: string;
49
- private pktTimer: NodeJS.Timeout;
50
- private currentTimestamp: string;
51
- private getPacketPath(): string {
52
- // changed this to remove spaces from the name
53
- return 'packetLog(' + this.getLogTimestamp() + ').log';
54
- }
55
- private getConsoleToFilePath(): string {
56
- return 'consoleLog(' + this.getLogTimestamp() + ').log';
57
- }
58
- public getLogTimestamp(bNew: boolean = false): string {
59
- if (!bNew && typeof this.currentTimestamp !== 'undefined') { return this.currentTimestamp; }
60
- var ts = new Date();
61
- function pad(n) { return (n < 10 ? '0' : '') + n; }
62
- this.currentTimestamp = ts.getFullYear() + '-' + pad(ts.getMonth() + 1) + '-' + pad(ts.getDate()) + '_' + pad(ts.getHours()) + '-' + pad(ts.getMinutes()) + '-' + pad(ts.getSeconds());
63
- return this.currentTimestamp;
64
- }
65
-
66
- private myFormat = winston.format.printf(({ level, message, label }) => {
67
- return `[${new Date().toLocaleString()}] ${level}: ${message}`;
68
- });
69
-
70
- private _logger: winston.Logger;
71
- public init() {
72
- this.cfg = config.getSection('log');
73
- logger._logger = winston.createLogger({
74
- format: winston.format.combine(winston.format.timestamp({format: 'MMMM DD YYYY'}), winston.format.colorize(), winston.format.splat(), this.myFormat),
75
- transports: [this.transports.console]
76
- });
77
- this.transports.console.level = this.cfg.app.level;
78
- if (this.cfg.app.captureForReplay) this.startCaptureForReplay(false);
79
- if (this.cfg.app.logToFile) {
80
- this.transports.consoleFile = new winston.transports.File({
81
- filename: path.join(process.cwd(), '/logs', this.getConsoleToFilePath()),
82
- level: 'silly',
83
- format: winston.format.combine(winston.format.splat(), winston.format.uncolorize(), this.myFormat)
84
- });
85
- this.transports.consoleFile.level = this.cfg.app.level;
86
- this._logger.add(this.transports.consoleFile);
87
- }
88
- }
89
- public async stopAsync() {
90
- try {
91
- this.info(`Stopping logger Process.`);
92
- if (this.cfg.app.captureForReplay) {
93
- return await this.stopCaptureForReplayAsync();
94
- }
95
- // Free up the file handles. This is yet another goofiness with winston. Not sure why they
96
- // need to exclusively lock the file handles when the process always appends. Just stupid.
97
- if (typeof this.transports.consoleFile !== 'undefined') {
98
- this._logger.remove(this.transports.consoleFile);
99
- this.transports.consoleFile.close();
100
- this.transports.consoleFile = undefined;
101
- }
102
- console.log(`Logger Process Stopped`);
103
- } catch (err) { console.log(`Error shutting down logger: ${err.message}`); }
104
- }
105
- public get options(): any { return this.cfg; }
106
- public info(...args: any[]) { logger._logger.info.apply(logger._logger, arguments); }
107
- public debug(...args: any[]) { logger._logger.debug.apply(logger._logger, arguments); }
108
- public warn(...args: any[]) { logger._logger.warn.apply(logger._logger, arguments); }
109
- public verbose(...args: any[]) { logger._logger.verbose.apply(logger._logger, arguments); }
110
- public error(...args: any[]): Error { logger._logger.error.apply(logger._logger, arguments); return new Error(arguments[0]); }
111
- public silly(...args: any[]) { logger._logger.silly.apply(logger._logger, arguments); }
112
- public reject(sError: string): Promise<Error> {
113
- logger.error(sError);
114
- return Promise.reject(new Error(sError));
115
- }
116
- private isIncluded(byte: number, arr: number[]): boolean {
117
- if (typeof (arr) === "undefined" || !arr || arr.length === 0) return true;
118
- if (arr.indexOf(byte) !== -1) return true;
119
- return false;
120
- }
121
- private isExcluded(byte: number, arr: number[]): boolean {
122
- if (typeof (arr) === "undefined" || !arr) return false;
123
- if (arr && arr.length === 0) return false;
124
- if (arr.indexOf(byte) !== -1) return true;
125
- return false;
126
- }
127
- public packet(msg: Message) {
128
- if (logger.cfg.packet.enabled || logger.cfg.app.captureForReplay) {
129
- // Filter out the messages we do not want.
130
- var bLog: boolean = true;
131
- // A random packet may actually find its way into the throws should the bytes get messed up
132
- // in a fashion where the header byte is 255, 0, 255 but we have not identified the channel.
133
- // Thus far we have seen 165 and 166.
134
- var cfgPacket = logger.cfg.packet[msg.protocol] || logger.cfg.packet['unidentified'];
135
- if (!logger.cfg.app.captureForReplay) {
136
- // Log invalid messages no matter what if the user has selected invalid message logging.
137
- if (bLog && !msg.isValid) {
138
- if (!logger.cfg.packet.invalid) bLog = false;
139
- }
140
- else {
141
- if (bLog && !cfgPacket.enabled) bLog = false;
142
- if (bLog && !logger.isIncluded(msg.source, cfgPacket.includeSouce)) bLog = false;
143
- if (bLog && !logger.isIncluded(msg.dest, cfgPacket.includeDest)) bLog = false;
144
- if (bLog && !logger.isIncluded(msg.action, cfgPacket.includeActions)) bLog = false;
145
- if (bLog && logger.isExcluded(msg.source, cfgPacket.excludeSource)) bLog = false;
146
- if (bLog && logger.isExcluded(msg.dest, cfgPacket.excludeDest)) bLog = false;
147
- if (bLog && logger.isExcluded(msg.action, cfgPacket.excludeActions)) bLog = false;
148
- }
149
- }
150
-
151
- if (bLog) {
152
- if (logger.cfg.packet.logToFile) {
153
- logger.pkts.push(msg);
154
- if (logger.pkts.length > 5)
155
- logger.flushLogs();
156
- else {
157
- // Attempt to ease up on the writes if we are logging a bunch of packets.
158
- if (logger.pktTimer) clearTimeout(logger.pktTimer);
159
- logger.pktTimer = setTimeout(logger.flushLogs, 1000);
160
- }
161
- }
162
- webApp.emitToChannel('msgLogger', 'logMessage', msg);
163
- }
164
- }
165
- if (logger.cfg.packet.logToConsole) {
166
- if (msg.isValid && bLog) logger._logger.info(msg.toLog());
167
- else if (!msg.isValid) logger._logger.warn(msg.toLog());
168
- }
169
- }
170
- public screenlogic(data: any){
171
- if (logger.cfg.screenlogic.enabled || logger.cfg.app.captureForReplay){
172
- if (logger.cfg.screenlogic.logToFile) {
173
- logger.slMessages.push(data);
174
- if (logger.slMessages.length > 5)
175
- logger.flushSLLogs();
176
- else {
177
- // Attempt to ease up on the writes if we are logging a bunch of packets.
178
- if (logger.pktTimer) clearTimeout(logger.pktTimer);
179
- logger.pktTimer = setTimeout(logger.flushSLLogs, 1000);
180
- }
181
- }
182
- webApp.emitToChannel('msgLogger', 'logMessage', data);
183
-
184
- }
185
- if (logger.cfg.screenlogic.logToConsole){
186
- logger._logger.info(sl.toLog(data));
187
- }
188
- }
189
- public logAPI(apiReq:string){
190
- if (logger.cfg.app.captureForReplay){
191
- // TODO: buffer this
192
- fs.appendFile(logger.pktPath, apiReq, function(err) {
193
- if (err) logger.error('Error writing packet to %s: %s', logger.pktPath, err);
194
- });
195
- }
196
-
197
- }
198
- public clearMessages() {
199
- if (fs.existsSync(logger.pktPath)) {
200
- logger.info(`Clearing message log: ${ logger.pktPath }`);
201
- fs.truncateSync(logger.pktPath, 0);
202
- }
203
- }
204
- public flushLogs() {
205
- var p: Message[] = logger.pkts.splice(0, logger.pkts.length);
206
- var buf: string = '';
207
- if (logger.cfg.packet.enabled) {
208
- for (let i = 0; i < p.length; i++) {
209
-
210
- buf += (p[i].toLog() + os.EOL);
211
- }
212
- fs.appendFile(logger.pktPath, buf, function(err) {
213
- if (err) logger.error('Error writing packet to %s: %s', logger.pktPath, err);
214
- });
215
- }
216
- buf = '';
217
- }
218
- public flushSLLogs() {
219
- var p: any[] = logger.slMessages.splice(0, logger.slMessages.length);
220
- var buf: string = '';
221
-
222
- for (let i = 0; i < p.length; i++) {
223
- buf += (p[i] + os.EOL);
224
- }
225
- fs.appendFile(logger.pktPath, buf, function(err) {
226
- if (err) logger.error(`Error writing screenlogic message to ${logger.pktPath}: ${err.message}`);
227
- });
228
-
229
- buf = '';
230
- }
231
- public setOptions(opts, c?: any) {
232
- c = typeof c === 'undefined' ? this.cfg : c;
233
- for (let prop in opts) {
234
- let o = opts[prop];
235
- if (o instanceof Array) {
236
- //console.log({ o: o, c: c, prop: prop });
237
- c[prop] = o; // Stop here we are replacing the array.
238
- }
239
- else if (typeof o === 'object') {
240
- if (typeof c[prop] === 'undefined') c[prop] = {};
241
- this.setOptions(o, c[prop]); // Use recursion here. Harder to follow but much less code.
242
- }
243
- else
244
- c[prop] = opts[prop];
245
- }
246
- config.setSection('log', this.cfg);
247
- if (utils.makeBool(this.cfg.app.logToFile)) {
248
- if (typeof this.transports.consoleFile === 'undefined') {
249
- this.transports.consoleFile = new winston.transports.File({
250
- filename: path.join(process.cwd(), '/logs', this.getConsoleToFilePath()),
251
- level: 'silly',
252
- format: winston.format.combine(winston.format.splat(), winston.format.uncolorize(), this.myFormat)
253
- });
254
- this._logger.add(this.transports.consoleFile);
255
- }
256
- }
257
- else {
258
- if (typeof this.transports.consoleFile !== 'undefined') {
259
- this._logger.remove(this.transports.consoleFile);
260
- this.transports.consoleFile.close();
261
- this.transports.consoleFile = undefined;
262
- }
263
- }
264
- for (let [key, transport] of Object.entries(this.transports)) {
265
- if(typeof transport !== 'undefined') transport.level = this.cfg.app.level;
266
- }
267
- }
268
- public startCaptureForReplay(bResetLogs:boolean) {
269
- logger.info(`Starting Replay Capture.`);
270
- // start new replay directory
271
-
272
- if (!fs.existsSync(this.captureForReplayPath)) fs.mkdirSync(this.captureForReplayBaseDir, { recursive: true });
273
-
274
- // Create logs subdirectory for additional log files
275
- let logsSubDir = path.join(this.captureForReplayBaseDir, 'logs');
276
- if (!fs.existsSync(logsSubDir)) fs.mkdirSync(logsSubDir, { recursive: true });
277
- if (bResetLogs){
278
- if (fs.existsSync(path.join(process.cwd(), 'data/poolConfig.json'))) {
279
- fs.copyFileSync(path.join(process.cwd(), 'data/poolConfig.json'), path.join(process.cwd(),'data/', `poolConfig-${this.getLogTimestamp()}.json`));
280
- fs.unlinkSync((path.join(process.cwd(), 'data/poolConfig.json')));
281
- }
282
- if (fs.existsSync(path.join(process.cwd(), 'data/poolState.json'))) {
283
- fs.copyFileSync(path.join(process.cwd(), 'data/poolState.json'), path.join(process.cwd(),'data/', `poolState-${this.getLogTimestamp()}.json`));
284
- fs.unlinkSync((path.join(process.cwd(), 'data/poolState.json')));
285
- }
286
- this.clearMessages();
287
- }
288
- logger.cfg = extend(true, {}, logger.cfg, {
289
- "packet": {
290
- "enabled": true,
291
- "logToConsole": true,
292
- "logToFile": true,
293
- "invalid": true,
294
- "broadcast": {
295
- "enabled": true,
296
- "includeActions": [],
297
- "includeSource": [],
298
- "includeDest": [],
299
- "excludeActions": [],
300
- "excludeSource": [],
301
- "excludeDest": []
302
- },
303
- "pump": {
304
- "enabled": true,
305
- "includeActions": [],
306
- "includeSource": [],
307
- "includeDest": [],
308
- "excludeActions": [],
309
- "excludeSource": [],
310
- "excludeDest": []
311
- },
312
- "chlorinator": {
313
- "enabled": true,
314
- "includeSource": [],
315
- "includeDest": [],
316
- "excludeSource": [],
317
- "excludeDest": []
318
- },
319
- "intellichem": {
320
- "enabled": true,
321
- "includeActions": [],
322
- "exclueActions": [],
323
- "includeSource": [],
324
- "includeDest": [],
325
- "excludeSource": [],
326
- "excludeDest": []
327
- },
328
- "intellivalve": {
329
- "enabled": true,
330
- "includeActions": [],
331
- "exclueActions": [],
332
- "includeSource": [],
333
- "includeDest": [],
334
- "excludeSource": [],
335
- "excludeDest": []
336
- },
337
- "unidentified": {
338
- "enabled": true,
339
- "includeSource": [],
340
- "includeDest": [],
341
- "excludeSource": [],
342
- "excludeDest": []
343
- },
344
- "unknown": {
345
- "enabled": true,
346
- "includeSource": [],
347
- "includeDest": [],
348
- "excludeSource": [],
349
- "excludeDest": []
350
- }
351
- },
352
- "app": {
353
- "enabled": true,
354
- "level": "silly",
355
- "captureForReplay": true
356
- }
357
- });
358
- this.consoleToFilePath = path.join(this.captureForReplayBaseDir, this.getConsoleToFilePath());
359
- this.transports.file = new winston.transports.File({
360
- filename: this.consoleToFilePath,
361
- level: 'silly',
362
- format: winston.format.combine(winston.format.splat(), winston.format.uncolorize(), this.myFormat)
363
- });
364
- logger._logger.add(this.transports.file);
365
- this.transports.console.level = 'silly';
366
- }
367
- public async stopCaptureForReplayAsync(remLogs?: any[]):Promise<string> {
368
- return new Promise<string>(async (resolve, reject) => {
369
- try {
370
- // Get REM server configurations from config
371
- let configData = config.getSection();
372
- let remServers = [];
373
- if (configData.web && configData.web.interfaces) {
374
- for (let interfaceName in configData.web.interfaces) {
375
- let interfaceConfig = configData.web.interfaces[interfaceName];
376
- if (interfaceConfig.type === 'rem' && interfaceConfig.enabled) {
377
- remServers.push({
378
- name: interfaceConfig.name || interfaceName,
379
- uuid: interfaceConfig.uuid,
380
- host: interfaceConfig.options?.host || '',
381
- backup: true
382
- });
383
- }
384
- }
385
- }
386
-
387
- // Use the existing backup logic to create the base backup
388
- let backupOptions = {
389
- njsPC: true,
390
- servers: remServers,
391
- name: `Packet Capture ${this.currentTimestamp}`,
392
- automatic: false
393
- };
394
-
395
- let backupFile = await webApp.backupServer(backupOptions);
396
-
397
- // Add packet capture logs to the existing backup zip
398
- let jszip = require("jszip");
399
- let zip = await jszip.loadAsync(fs.readFileSync(backupFile.filePath));
400
-
401
- // Add packet capture logs to the njsPC/logs directory
402
- zip.file(`njsPC/logs/${this.getPacketPath()}`, fs.readFileSync(logger.pktPath));
403
- zip.file(`njsPC/logs/${this.getConsoleToFilePath()}`, fs.readFileSync(this.consoleToFilePath));
404
-
405
- // Add REM server logs if provided
406
- if (remLogs && remLogs.length > 0) {
407
- logger.info(`Adding ${remLogs.length} REM logs to backup`);
408
- for (let remLog of remLogs) {
409
- // Create logs directory for the REM server using the hardcoded name
410
- let logPath = `Relay Equipment Manager/logs/${remLog.logFileName}`;
411
- logger.info(`Adding REM log to backup: ${logPath} (size: ${remLog.logData.length} characters)`);
412
- zip.file(logPath, remLog.logData);
413
- }
414
- } else {
415
- logger.info(`No REM logs provided to add to backup`);
416
- }
417
-
418
- // Generate the updated zip
419
- await zip.generateAsync({type:'nodebuffer'}).then(content => {
420
- fs.writeFileSync(backupFile.filePath, content);
421
- });
422
-
423
- // Restore original logging configuration
424
- this.cfg = config.getSection('log');
425
- logger._logger.remove(this.transports.file);
426
- this.transports.console.level = this.cfg.app.level;
427
-
428
- resolve(backupFile.filePath);
429
- }
430
- catch (err) {
431
- reject(err.message);
432
- }
433
- });
434
- }
435
- }
436
- export var logger = new Logger();
1
+ /* nodejs-poolController. An application to control pool equipment.
2
+ Copyright (C) 2016, 2017, 2018, 2019, 2020, 2021, 2022.
3
+ Russell Goldin, tagyoureit. russ.goldin@gmail.com
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or (at your option) any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+ import * as path from 'path';
19
+ import * as fs from 'fs';
20
+ import * as winston from 'winston';
21
+ import * as os from 'os';
22
+ import { utils } from "../controller/Constants";
23
+ import { Message } from '../controller/comms/messages/Messages';
24
+ import { config } from '../config/Config';
25
+ import { webApp } from '../web/Server';
26
+ import { sl } from '../controller/comms/ScreenLogic';
27
+
28
+ const extend = require("extend");
29
+
30
+ class Logger {
31
+ constructor() {
32
+ if (!fs.existsSync(path.join(process.cwd(), '/logs'))) fs.mkdirSync(path.join(process.cwd(), '/logs'));
33
+ this.pktPath = path.join(process.cwd(), '/logs', this.getPacketPath());
34
+ this.captureForReplayBaseDir = path.join(process.cwd(), '/logs/', this.getLogTimestamp());
35
+ /* this.captureForReplayPath = path.join(this.captureForReplayBaseDir, '/packetCapture.json'); */
36
+ this.pkts = [];
37
+ this.slMessages = [];
38
+ }
39
+ private cfg;
40
+ private pkts: Message[];
41
+ private slMessages: any[];
42
+ private pktPath: string;
43
+ private consoleToFilePath: string;
44
+ private transports: { console: winston.transports.ConsoleTransportInstance, file?: winston.transports.FileTransportInstance, consoleFile?: winston.transports.FileTransportInstance } = {
45
+ console: new winston.transports.Console({ level: 'silly' })
46
+ };
47
+ private captureForReplayBaseDir: string;
48
+ private captureForReplayPath: string;
49
+ private pktTimer: NodeJS.Timeout;
50
+ private currentTimestamp: string;
51
+ private _captureInProgress: boolean = false;
52
+ private getPacketPath(): string {
53
+ // changed this to remove spaces from the name
54
+ return 'packetLog(' + this.getLogTimestamp() + ').log';
55
+ }
56
+ private getConsoleToFilePath(): string {
57
+ return 'consoleLog(' + this.getLogTimestamp() + ').log';
58
+ }
59
+ public getLogTimestamp(bNew: boolean = false): string {
60
+ if (!bNew && typeof this.currentTimestamp !== 'undefined') { return this.currentTimestamp; }
61
+ var ts = new Date();
62
+ function pad(n) { return (n < 10 ? '0' : '') + n; }
63
+ this.currentTimestamp = ts.getFullYear() + '-' + pad(ts.getMonth() + 1) + '-' + pad(ts.getDate()) + '_' + pad(ts.getHours()) + '-' + pad(ts.getMinutes()) + '-' + pad(ts.getSeconds());
64
+ return this.currentTimestamp;
65
+ }
66
+
67
+ private myFormat = winston.format.printf(({ level, message, label }) => {
68
+ return `[${new Date().toLocaleString()}] ${level}: ${message}`;
69
+ });
70
+
71
+ private _logger: winston.Logger;
72
+ public init() {
73
+ this.cfg = config.getSection('log');
74
+ logger._logger = winston.createLogger({
75
+ format: winston.format.combine(winston.format.timestamp({format: 'MMMM DD YYYY'}), winston.format.colorize(), winston.format.splat(), this.myFormat),
76
+ transports: [this.transports.console]
77
+ });
78
+ this.transports.console.level = this.cfg.app.level;
79
+ // Only start capture if not already capturing (prevents duplicate transports when config watcher triggers init())
80
+ if (this.cfg.app.captureForReplay && !this._captureInProgress) {
81
+ this.startCaptureForReplay(false);
82
+ }
83
+ if (this.cfg.app.logToFile) {
84
+ this.transports.consoleFile = new winston.transports.File({
85
+ filename: path.join(process.cwd(), '/logs', this.getConsoleToFilePath()),
86
+ level: 'silly',
87
+ format: winston.format.combine(winston.format.splat(), winston.format.uncolorize(), this.myFormat)
88
+ });
89
+ this.transports.consoleFile.level = this.cfg.app.level;
90
+ this._logger.add(this.transports.consoleFile);
91
+ }
92
+ }
93
+ public async stopAsync() {
94
+ try {
95
+ this.info(`Stopping logger Process.`);
96
+ if (this.cfg.app.captureForReplay) {
97
+ return await this.stopCaptureForReplayAsync();
98
+ }
99
+ // Free up the file handles. This is yet another goofiness with winston. Not sure why they
100
+ // need to exclusively lock the file handles when the process always appends. Just stupid.
101
+ if (typeof this.transports.consoleFile !== 'undefined') {
102
+ this._logger.remove(this.transports.consoleFile);
103
+ this.transports.consoleFile.close();
104
+ this.transports.consoleFile = undefined;
105
+ }
106
+ console.log(`Logger Process Stopped`);
107
+ } catch (err) { console.log(`Error shutting down logger: ${err.message}`); }
108
+ }
109
+ public get options(): any { return this.cfg; }
110
+ public info(...args: any[]) { logger._logger.info.apply(logger._logger, arguments); }
111
+ public debug(...args: any[]) { logger._logger.debug.apply(logger._logger, arguments); }
112
+ public warn(...args: any[]) { logger._logger.warn.apply(logger._logger, arguments); }
113
+ public verbose(...args: any[]) { logger._logger.verbose.apply(logger._logger, arguments); }
114
+ public error(...args: any[]): Error { logger._logger.error.apply(logger._logger, arguments); return new Error(arguments[0]); }
115
+ public silly(...args: any[]) { logger._logger.silly.apply(logger._logger, arguments); }
116
+ public reject(sError: string): Promise<Error> {
117
+ logger.error(sError);
118
+ return Promise.reject(new Error(sError));
119
+ }
120
+ private isIncluded(byte: number, arr: number[]): boolean {
121
+ if (typeof (arr) === "undefined" || !arr || arr.length === 0) return true;
122
+ if (arr.indexOf(byte) !== -1) return true;
123
+ return false;
124
+ }
125
+ private isExcluded(byte: number, arr: number[]): boolean {
126
+ if (typeof (arr) === "undefined" || !arr) return false;
127
+ if (arr && arr.length === 0) return false;
128
+ if (arr.indexOf(byte) !== -1) return true;
129
+ return false;
130
+ }
131
+ public packet(msg: Message) {
132
+ // Emits to clients should not be gated by logging settings.
133
+ // Logging-to-file/console remains gated by packet config and filters.
134
+ webApp.emitToChannel('msgLogger', 'logMessage', msg);
135
+
136
+ // Filter out the messages we do not want to *log*.
137
+ let bLog: boolean = true;
138
+ if (logger.cfg.packet.enabled || logger.cfg.app.captureForReplay) {
139
+ // A random packet may actually find its way into the throws should the bytes get messed up
140
+ // in a fashion where the header byte is 255, 0, 255 but we have not identified the channel.
141
+ // Thus far we have seen 165 and 166.
142
+ const cfgPacket = logger.cfg.packet[msg.protocol] || logger.cfg.packet['unidentified'];
143
+ if (!logger.cfg.app.captureForReplay) {
144
+ // Log invalid messages no matter what if the user has selected invalid message logging.
145
+ if (bLog && !msg.isValid) {
146
+ if (!logger.cfg.packet.invalid) bLog = false;
147
+ }
148
+ else {
149
+ if (bLog && !cfgPacket.enabled) bLog = false;
150
+ if (bLog && !logger.isIncluded(msg.source, cfgPacket.includeSouce)) bLog = false;
151
+ if (bLog && !logger.isIncluded(msg.dest, cfgPacket.includeDest)) bLog = false;
152
+ if (bLog && !logger.isIncluded(msg.action, cfgPacket.includeActions)) bLog = false;
153
+ if (bLog && logger.isExcluded(msg.source, cfgPacket.excludeSource)) bLog = false;
154
+ if (bLog && logger.isExcluded(msg.dest, cfgPacket.excludeDest)) bLog = false;
155
+ if (bLog && logger.isExcluded(msg.action, cfgPacket.excludeActions)) bLog = false;
156
+ }
157
+ }
158
+
159
+ if (bLog && logger.cfg.packet.logToFile) {
160
+ logger.pkts.push(msg);
161
+ if (logger.pkts.length > 5)
162
+ logger.flushLogs();
163
+ else {
164
+ // Attempt to ease up on the writes if we are logging a bunch of packets.
165
+ if (logger.pktTimer) clearTimeout(logger.pktTimer);
166
+ logger.pktTimer = setTimeout(logger.flushLogs, 1000);
167
+ }
168
+ }
169
+ }
170
+ else {
171
+ bLog = false;
172
+ }
173
+
174
+ if (logger.cfg.packet.logToConsole && bLog) {
175
+ if (msg.isValid) logger._logger.info(msg.toLog());
176
+ else logger._logger.warn(msg.toLog());
177
+ }
178
+ }
179
+ public screenlogic(data: any){
180
+ if (logger.cfg.screenlogic.enabled || logger.cfg.app.captureForReplay){
181
+ if (logger.cfg.screenlogic.logToFile) {
182
+ logger.slMessages.push(data);
183
+ if (logger.slMessages.length > 5)
184
+ logger.flushSLLogs();
185
+ else {
186
+ // Attempt to ease up on the writes if we are logging a bunch of packets.
187
+ if (logger.pktTimer) clearTimeout(logger.pktTimer);
188
+ logger.pktTimer = setTimeout(logger.flushSLLogs, 1000);
189
+ }
190
+ }
191
+ webApp.emitToChannel('msgLogger', 'logMessage', data);
192
+
193
+ }
194
+ if (logger.cfg.screenlogic.logToConsole){
195
+ logger._logger.info(sl.toLog(data));
196
+ }
197
+ }
198
+ public logAPI(apiReq:string){
199
+ if (logger.cfg.app.captureForReplay){
200
+ // TODO: buffer this
201
+ fs.appendFile(logger.pktPath, apiReq, function(err) {
202
+ if (err) logger.error('Error writing packet to %s: %s', logger.pktPath, err);
203
+ });
204
+ }
205
+
206
+ }
207
+ public clearMessages() {
208
+ if (fs.existsSync(logger.pktPath)) {
209
+ logger.info(`Clearing message log: ${ logger.pktPath }`);
210
+ fs.truncateSync(logger.pktPath, 0);
211
+ }
212
+ }
213
+ public flushLogs() {
214
+ var p: Message[] = logger.pkts.splice(0, logger.pkts.length);
215
+ var buf: string = '';
216
+ if (logger.cfg.packet.enabled) {
217
+ for (let i = 0; i < p.length; i++) {
218
+
219
+ buf += (p[i].toLog() + os.EOL);
220
+ }
221
+ fs.appendFile(logger.pktPath, buf, function(err) {
222
+ if (err) logger.error('Error writing packet to %s: %s', logger.pktPath, err);
223
+ });
224
+ }
225
+ buf = '';
226
+ }
227
+ public flushSLLogs() {
228
+ var p: any[] = logger.slMessages.splice(0, logger.slMessages.length);
229
+ var buf: string = '';
230
+
231
+ for (let i = 0; i < p.length; i++) {
232
+ buf += (p[i] + os.EOL);
233
+ }
234
+ fs.appendFile(logger.pktPath, buf, function(err) {
235
+ if (err) logger.error(`Error writing screenlogic message to ${logger.pktPath}: ${err.message}`);
236
+ });
237
+
238
+ buf = '';
239
+ }
240
+ public setOptions(opts, c?: any) {
241
+ c = typeof c === 'undefined' ? this.cfg : c;
242
+ for (let prop in opts) {
243
+ let o = opts[prop];
244
+ if (o instanceof Array) {
245
+ //console.log({ o: o, c: c, prop: prop });
246
+ c[prop] = o; // Stop here we are replacing the array.
247
+ }
248
+ else if (typeof o === 'object') {
249
+ if (typeof c[prop] === 'undefined') c[prop] = {};
250
+ this.setOptions(o, c[prop]); // Use recursion here. Harder to follow but much less code.
251
+ }
252
+ else
253
+ c[prop] = opts[prop];
254
+ }
255
+ config.setSection('log', this.cfg);
256
+ if (utils.makeBool(this.cfg.app.logToFile)) {
257
+ if (typeof this.transports.consoleFile === 'undefined') {
258
+ this.transports.consoleFile = new winston.transports.File({
259
+ filename: path.join(process.cwd(), '/logs', this.getConsoleToFilePath()),
260
+ level: 'silly',
261
+ format: winston.format.combine(winston.format.splat(), winston.format.uncolorize(), this.myFormat)
262
+ });
263
+ this._logger.add(this.transports.consoleFile);
264
+ }
265
+ }
266
+ else {
267
+ if (typeof this.transports.consoleFile !== 'undefined') {
268
+ this._logger.remove(this.transports.consoleFile);
269
+ this.transports.consoleFile.close();
270
+ this.transports.consoleFile = undefined;
271
+ }
272
+ }
273
+ for (let [key, transport] of Object.entries(this.transports)) {
274
+ if(typeof transport !== 'undefined') transport.level = this.cfg.app.level;
275
+ }
276
+ }
277
+ public startCaptureForReplay(bResetLogs:boolean) {
278
+ this._captureInProgress = true;
279
+ logger.info(`Starting Replay Capture.`);
280
+ // start new replay directory
281
+
282
+ if (!fs.existsSync(this.captureForReplayPath)) fs.mkdirSync(this.captureForReplayBaseDir, { recursive: true });
283
+
284
+ // Create logs subdirectory for additional log files
285
+ let logsSubDir = path.join(this.captureForReplayBaseDir, 'logs');
286
+ if (!fs.existsSync(logsSubDir)) fs.mkdirSync(logsSubDir, { recursive: true });
287
+ if (bResetLogs){
288
+ if (fs.existsSync(path.join(process.cwd(), 'data/poolConfig.json'))) {
289
+ fs.copyFileSync(path.join(process.cwd(), 'data/poolConfig.json'), path.join(process.cwd(),'data/', `poolConfig-${this.getLogTimestamp()}.json`));
290
+ fs.unlinkSync((path.join(process.cwd(), 'data/poolConfig.json')));
291
+ }
292
+ if (fs.existsSync(path.join(process.cwd(), 'data/poolState.json'))) {
293
+ fs.copyFileSync(path.join(process.cwd(), 'data/poolState.json'), path.join(process.cwd(),'data/', `poolState-${this.getLogTimestamp()}.json`));
294
+ fs.unlinkSync((path.join(process.cwd(), 'data/poolState.json')));
295
+ }
296
+ this.clearMessages();
297
+ }
298
+ logger.cfg = extend(true, {}, logger.cfg, {
299
+ "packet": {
300
+ "enabled": true,
301
+ "logToConsole": true,
302
+ "logToFile": true,
303
+ "invalid": true,
304
+ "broadcast": {
305
+ "enabled": true,
306
+ "includeActions": [],
307
+ "includeSource": [],
308
+ "includeDest": [],
309
+ "excludeActions": [],
310
+ "excludeSource": [],
311
+ "excludeDest": []
312
+ },
313
+ "pump": {
314
+ "enabled": true,
315
+ "includeActions": [],
316
+ "includeSource": [],
317
+ "includeDest": [],
318
+ "excludeActions": [],
319
+ "excludeSource": [],
320
+ "excludeDest": []
321
+ },
322
+ "chlorinator": {
323
+ "enabled": true,
324
+ "includeSource": [],
325
+ "includeDest": [],
326
+ "excludeSource": [],
327
+ "excludeDest": []
328
+ },
329
+ "intellichem": {
330
+ "enabled": true,
331
+ "includeActions": [],
332
+ "exclueActions": [],
333
+ "includeSource": [],
334
+ "includeDest": [],
335
+ "excludeSource": [],
336
+ "excludeDest": []
337
+ },
338
+ "intellivalve": {
339
+ "enabled": true,
340
+ "includeActions": [],
341
+ "exclueActions": [],
342
+ "includeSource": [],
343
+ "includeDest": [],
344
+ "excludeSource": [],
345
+ "excludeDest": []
346
+ },
347
+ "unidentified": {
348
+ "enabled": true,
349
+ "includeSource": [],
350
+ "includeDest": [],
351
+ "excludeSource": [],
352
+ "excludeDest": []
353
+ },
354
+ "unknown": {
355
+ "enabled": true,
356
+ "includeSource": [],
357
+ "includeDest": [],
358
+ "excludeSource": [],
359
+ "excludeDest": []
360
+ }
361
+ },
362
+ "app": {
363
+ "enabled": true,
364
+ "level": "silly",
365
+ "captureForReplay": true
366
+ }
367
+ });
368
+ this.consoleToFilePath = path.join(this.captureForReplayBaseDir, this.getConsoleToFilePath());
369
+ this.transports.file = new winston.transports.File({
370
+ filename: this.consoleToFilePath,
371
+ level: 'silly',
372
+ format: winston.format.combine(winston.format.splat(), winston.format.uncolorize(), this.myFormat)
373
+ });
374
+ logger._logger.add(this.transports.file);
375
+ this.transports.console.level = 'silly';
376
+ }
377
+ public async stopCaptureForReplayAsync(remLogs?: any[]):Promise<string> {
378
+ return new Promise<string>(async (resolve, reject) => {
379
+ try {
380
+ // Get REM server configurations from config
381
+ let configData = config.getSection();
382
+ let remServers = [];
383
+ if (configData.web && configData.web.interfaces) {
384
+ for (let interfaceName in configData.web.interfaces) {
385
+ let interfaceConfig = configData.web.interfaces[interfaceName];
386
+ if (interfaceConfig.type === 'rem' && interfaceConfig.enabled) {
387
+ remServers.push({
388
+ name: interfaceConfig.name || interfaceName,
389
+ uuid: interfaceConfig.uuid,
390
+ host: interfaceConfig.options?.host || '',
391
+ backup: true
392
+ });
393
+ }
394
+ }
395
+ }
396
+
397
+ // Use the existing backup logic to create the base backup
398
+ let backupOptions = {
399
+ njsPC: true,
400
+ servers: remServers,
401
+ name: `Packet Capture ${this.currentTimestamp}`,
402
+ automatic: false
403
+ };
404
+
405
+ let backupFile = await webApp.backupServer(backupOptions);
406
+
407
+ // Add packet capture logs to the existing backup zip
408
+ let jszip = require("jszip");
409
+ let zip = await jszip.loadAsync(fs.readFileSync(backupFile.filePath));
410
+
411
+ // Add packet capture logs to the njsPC/logs directory
412
+ zip.file(`njsPC/logs/${this.getPacketPath()}`, fs.readFileSync(logger.pktPath));
413
+ zip.file(`njsPC/logs/${this.getConsoleToFilePath()}`, fs.readFileSync(this.consoleToFilePath));
414
+
415
+ // Add REM server logs if provided
416
+ if (remLogs && remLogs.length > 0) {
417
+ logger.info(`Adding ${remLogs.length} REM logs to backup`);
418
+ for (let remLog of remLogs) {
419
+ // Create logs directory for the REM server using the hardcoded name
420
+ let logPath = `Relay Equipment Manager/logs/${remLog.logFileName}`;
421
+ logger.info(`Adding REM log to backup: ${logPath} (size: ${remLog.logData.length} characters)`);
422
+ zip.file(logPath, remLog.logData);
423
+ }
424
+ } else {
425
+ logger.info(`No REM logs provided to add to backup`);
426
+ }
427
+
428
+ // Generate the updated zip
429
+ await zip.generateAsync({type:'nodebuffer'}).then(content => {
430
+ fs.writeFileSync(backupFile.filePath, content);
431
+ });
432
+
433
+ // Restore original logging configuration
434
+ this.cfg = config.getSection('log');
435
+ logger._logger.remove(this.transports.file);
436
+ this.transports.console.level = this.cfg.app.level;
437
+ this._captureInProgress = false;
438
+
439
+ resolve(backupFile.filePath);
440
+ }
441
+ catch (err) {
442
+ this._captureInProgress = false;
443
+ reject(err.message);
444
+ }
445
+ });
446
+ }
447
+ }
448
+ export var logger = new Logger();