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,283 +1,283 @@
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
-
19
- import extend = require("extend");
20
- import { ClientOptions, DEFAULT_WriteOptions, InfluxDB, Point, WriteApi, WriteOptions, WritePrecisionType } from '@influxdata/influxdb-client';
21
- import { utils, Timestamp } from '../../controller/Constants';
22
- import { logger } from "../../logger/Logger";
23
- import { BaseInterfaceBindings, InterfaceContext, InterfaceEvent } from "./baseInterface";
24
- export class InfluxInterfaceBindings extends BaseInterfaceBindings {
25
- constructor(cfg) {
26
- super(cfg);
27
- }
28
- private writeApi: WriteApi;
29
- declare context: InterfaceContext;
30
- declare cfg;
31
- declare events: InfluxInterfaceEvent[];
32
- private init = () => {
33
- let baseOpts = extend(true, this.cfg.options, this.context.options);
34
- let url = 'http://';
35
- if (typeof baseOpts.protocol !== 'undefined' && baseOpts.protocol) url = baseOpts.protocol;
36
- if (!url.endsWith('://')) url += '://';
37
- url = `${url}${baseOpts.host}`;
38
- if(typeof baseOpts.port !== 'undefined' && baseOpts.port !== null && !isNaN(baseOpts.port)) url = `${url}:${baseOpts.port}`;
39
- let influxDB: InfluxDB;
40
- let bucket;
41
- let org;
42
- if (typeof baseOpts.host === 'undefined' || !baseOpts.host) {
43
- logger.warn(`Interface: ${this.cfg.name} has not resolved to a valid host.`);
44
- return;
45
- }
46
- if (baseOpts.version === 1) {
47
- if (typeof baseOpts.database === 'undefined' || !baseOpts.database) {
48
- logger.warn(`Interface: ${this.cfg.name} has not resolved to a valid database.`);
49
- return;
50
- }
51
- bucket = `${baseOpts.database}/${baseOpts.retentionPolicy}`;
52
- const clientOptions: ClientOptions = {
53
- url,
54
- token: `${baseOpts.username}:${baseOpts.password}`,
55
- }
56
- influxDB = new InfluxDB(clientOptions);
57
- }
58
- else if (baseOpts.version === 2) {
59
- org = baseOpts.org;
60
- bucket = baseOpts.bucket;
61
- const clientOptions: ClientOptions = {
62
- url,
63
- token: baseOpts.token,
64
- }
65
- influxDB = new InfluxDB(clientOptions);
66
- }
67
- // set global tags from context
68
- let baseTags = {}
69
- baseOpts.tags.forEach(tag => {
70
- let toks = {};
71
- let sname = this.tokensReplacer(tag.name, undefined, toks, undefined, {})
72
- let svalue = this.tokensReplacer(tag.value, undefined, toks, { vars: {} } as any, {});
73
- if (typeof sname !== 'undefined' && typeof svalue !== 'undefined' && !sname.includes('@bind') && !svalue.includes('@bind'))
74
- baseTags[sname] = svalue;
75
- })
76
- //this.writeApi.useDefaultTags(baseTags);
77
- const writeOptions:WriteOptions = {
78
- /* the maximum points/line to send in a single batch to InfluxDB server */
79
- batchSize: baseOpts.batchSize || 100,
80
- /* default tags to add to every point */
81
- defaultTags: baseTags,
82
- /* maximum time in millis to keep points in an unflushed batch, 0 means don't periodically flush */
83
- flushInterval: DEFAULT_WriteOptions.flushInterval,
84
- /* maximum size of the retry buffer - it contains items that could not be sent for the first time */
85
- maxBufferLines: DEFAULT_WriteOptions.maxBufferLines,
86
- /* the count of retries, the delays between retries follow an exponential backoff strategy if there is no Retry-After HTTP header */
87
- maxRetries: DEFAULT_WriteOptions.maxRetries,
88
- /* maximum delay between retries in milliseconds */
89
- maxRetryDelay: DEFAULT_WriteOptions.maxRetryDelay,
90
- /* minimum delay between retries in milliseconds */
91
- minRetryDelay: DEFAULT_WriteOptions.minRetryDelay, // minimum delay between retries
92
- /* a random value of up to retryJitter is added when scheduling next retry */
93
- retryJitter: DEFAULT_WriteOptions.retryJitter,
94
- // ... or you can customize what to do on write failures when using a writeFailed fn, see the API docs for details
95
- writeFailed: function(error, lines, failedAttempts){
96
- /** return promise or void */
97
- logger.error(`InfluxDB batch write failed writing ${lines.length} lines with ${failedAttempts} failed attempts. ${error.message}`);
98
- //console.log(lines);
99
- },
100
- writeSuccess: function(lines){
101
- logger.silly(`InfluxDB successfully wrote ${lines.length} lines.`)
102
- },
103
- writeRetrySkipped: function(entry){
104
- logger.silly(`Influx write retry skipped ${JSON.stringify(entry)}`);
105
- },
106
- maxRetryTime: DEFAULT_WriteOptions.maxRetryTime,
107
- exponentialBase: DEFAULT_WriteOptions.exponentialBase,
108
- randomRetry: DEFAULT_WriteOptions.randomRetry,
109
- maxBatchBytes: 4096
110
-
111
- }
112
- this.writeApi = influxDB.getWriteApi(org, bucket, 'ms', writeOptions);
113
-
114
-
115
-
116
- }
117
- public bindEvent(evt: string, ...data: any) {
118
-
119
- // if (state.status.value !== sys.board.valueMaps.controllerStatus.getValue('ready')) return; // miss values? or show errors? or?
120
- if (typeof this.events !== 'undefined') {
121
- if (typeof this.writeApi === 'undefined') this.init();
122
- let evts = this.events.filter(elem => elem.name === evt);
123
- if (evts.length > 0) {
124
- let toks = {};
125
- for (let i = 0; i < evts.length; i++) {
126
- let e = evts[i];
127
- if (typeof e.enabled !== 'undefined' && !e.enabled) continue;
128
- // Figure out whether we need to check the filter.
129
- if (typeof e.filter !== 'undefined') {
130
- this.buildTokens(e.filter, evt, toks, e, data[0]);
131
- if (eval(this.replaceTokens(e.filter, toks)) === false) continue;
132
- }
133
- for (let j = 0; j < e.points.length; j++) {
134
- let _point = e.points[j];
135
- // Figure out whether we need to check the filter for each point.
136
- if (typeof _point.filter !== 'undefined') {
137
- this.buildTokens(_point.filter, evt, toks, e, data[0]);
138
- if (eval(this.replaceTokens(_point.filter, toks)) === false) continue;
139
- }
140
- // iterate through points array
141
- let point = new Point(_point.measurement)
142
- let point2 = new Point(_point.measurement);
143
- _point.tags.forEach(_tag => {
144
- let sname = _tag.name;
145
- this.buildTokens(sname, evt, toks, e, data[0]);
146
- sname = this.replaceTokens(sname, toks);
147
- let svalue = _tag.value;
148
- this.buildTokens(svalue, evt, toks, e, data[0]);
149
- svalue = this.replaceTokens(svalue, toks);
150
- if (typeof sname !== 'undefined' && typeof svalue !== 'undefined' && !sname.includes('@bind') && !svalue.includes('@bind') && svalue !== null) {
151
- point.tag(sname, svalue);
152
- if (typeof _point.storePrevState !== 'undefined' && _point.storePrevState) point2.tag(sname, svalue);
153
- }
154
- else {
155
- logger.error(`InfluxDB tag binding failure on ${evt}:${_tag.name}/${_tag.value} --> ${svalue || 'undefined'} ${JSON.stringify(data[0])}`);
156
- if (typeof sname === 'undefined') logger.error(`InfluxDB tag name is undefined`);
157
- if (typeof svalue === 'undefined') logger.error(`InfluxDB value is undefined`);
158
- if (svalue.includes('@bind')) logger.error(`InfluxDB value not bound`);
159
- if (svalue === null) logger.error(`InfluxDB value is null`);
160
- }
161
- })
162
- _point.fields.forEach(_field => {
163
- try {
164
- let sname = _field.name;
165
- this.buildTokens(sname, evt, toks, e, data[0]);
166
- //console.log(toks);
167
- sname = this.replaceTokens(sname, toks);
168
- let svalue = _field.value;
169
- this.buildTokens(svalue, evt, toks, e, data[0]);
170
- svalue = this.replaceTokens(svalue, toks);
171
- if (typeof sname !== 'undefined' && typeof svalue !== 'undefined' && !sname.includes('@bind') && !svalue.includes('@bind') && svalue !== null)
172
- switch (_field.type) {
173
- case 'int':
174
- case 'integer':
175
- let int = parseInt(svalue, 10);
176
- if (!isNaN(int)) point.intField(sname, int);
177
- // if (!isNaN(int) && typeof _point.storePrevState !== 'undefined' && _point.storePrevState) point2.intField(sname, int);
178
- break;
179
- case 'string':
180
- point.stringField(sname, svalue);
181
- // if (typeof _point.storePrevState !== 'undefined' && _point.storePrevState) point2.stringField(sname, svalue);
182
- break;
183
- case 'boolean':
184
- point.booleanField(sname, utils.makeBool(svalue));
185
- if (typeof _point.storePrevState !== 'undefined' && _point.storePrevState) point2.booleanField(sname, !utils.makeBool(svalue));
186
- break;
187
- case 'float':
188
- let float = parseFloat(svalue);
189
- if (!isNaN(float)) point.floatField(sname, float);
190
- // if (!isNaN(float) && typeof _point.storePrevState !== 'undefined' && _point.storePrevState) point2.intField(sname, int);
191
- break;
192
- case 'timestamp':
193
- case 'datetime':
194
- case 'date':
195
- //let dt = Date.parse(svalue.replace(/^["'](.+(?=["']$))["']$/, '$1'));
196
- // RKS: 07-06-21 - I think this is missing the eval function around all of this. The strings still have the quotes around them. I think
197
- // maybe we need to create a closure and execute it as a code segment for variable data.
198
- let sdt = eval(svalue);
199
- if (sdt !== null && typeof sdt !== 'undefined') {
200
- let dt = Date.parse(sdt);
201
- if (!isNaN(dt)) point.intField(sname, dt);
202
- else if (svalue !== '') logger.warn(`Influx error parsing date from ${sname}: ${svalue}`);
203
- }
204
- break;
205
- }
206
- else {
207
- logger.error(`InfluxDB point binding failure on ${evt}:${_field.name}/${_field.value} --> ${svalue || 'undefined'}`);
208
- }
209
- } catch (err) { logger.error(`Error binding InfluxDB point fields ${err.message}`); }
210
- });
211
- if (typeof _point.series !== 'undefined') {
212
- try {
213
- this.buildTokens(_point.series.value, evt, toks, e, data[0]);
214
- let ser = eval(this.replaceTokens(_point.series.value, toks));
215
- let ts = Date.parse(ser);
216
- if (isNaN(ts)) {
217
- logger.error(`Influx series timestamp is invalid ${ser}`);
218
- }
219
- else
220
- point.timestamp(new Date(ts));
221
- } catch (err) { logger.error(`Error parsing Influx point series for ${evt} - ${_point.series.value}`); }
222
- }
223
- else
224
- point.timestamp(new Date());
225
- try {
226
-
227
- if (typeof _point.storePrevState !== 'undefined' && _point.storePrevState) {
228
- // copy the point and subtract a second and keep inverse value
229
- let ts = new Date();
230
- let sec = ts.getSeconds() - 1;
231
- ts.setSeconds(sec);
232
- point2.timestamp(ts);
233
- logger.silly(`Batching influx ${e.name} inverse data point ${point2.toString()})`)
234
- this.writeApi.writePoint(point2);
235
- }
236
- if (typeof point.toLineProtocol() !== 'undefined') {
237
- logger.silly(`Batching influx ${e.name} data point ${point.toString()}`)
238
- this.writeApi.writePoint(point);
239
- // this.writeApi.flush()
240
- // .catch(error => { logger.error(`Error flushing Influx data point ${point.toString()} ${error}`); });
241
- //logger.info(`INFLUX: ${point.toLineProtocol()}`)
242
- }
243
- else {
244
- logger.silly(`Skipping INFLUX write because some data is missing with ${e.name} event on measurement ${_point.measurement}.`)
245
- }
246
- }
247
- catch (err) {
248
- logger.error(`Error writing to Influx: ${err.message}`)
249
- }
250
- }
251
- }
252
- }
253
- }
254
- }
255
- public close = () => {
256
-
257
- }
258
- }
259
-
260
- class InfluxInterfaceEvent extends InterfaceEvent {
261
- public points: IPoint[];
262
- }
263
-
264
- export interface IPoint {
265
- measurement: string;
266
- series?: ISeries;
267
- tags: ITag[];
268
- fields: IFields[];
269
- storePrevState?: boolean;
270
- filter?: any;
271
- }
272
- export interface ITag {
273
- name: string;
274
- value: string;
275
- }
276
- export interface IFields {
277
- name: string;
278
- value: string;
279
- type: string;
280
- }
281
- export interface ISeries {
282
- value: string;
283
- }
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
+
19
+ import extend = require("extend");
20
+ import { ClientOptions, DEFAULT_WriteOptions, InfluxDB, Point, WriteApi, WriteOptions, WritePrecisionType } from '@influxdata/influxdb-client';
21
+ import { utils, Timestamp } from '../../controller/Constants';
22
+ import { logger } from "../../logger/Logger";
23
+ import { BaseInterfaceBindings, InterfaceContext, InterfaceEvent } from "./baseInterface";
24
+ export class InfluxInterfaceBindings extends BaseInterfaceBindings {
25
+ constructor(cfg) {
26
+ super(cfg);
27
+ }
28
+ private writeApi: WriteApi;
29
+ declare context: InterfaceContext;
30
+ declare cfg;
31
+ declare events: InfluxInterfaceEvent[];
32
+ private init = () => {
33
+ let baseOpts = extend(true, this.cfg.options, this.context.options);
34
+ let url = 'http://';
35
+ if (typeof baseOpts.protocol !== 'undefined' && baseOpts.protocol) url = baseOpts.protocol;
36
+ if (!url.endsWith('://')) url += '://';
37
+ url = `${url}${baseOpts.host}`;
38
+ if(typeof baseOpts.port !== 'undefined' && baseOpts.port !== null && !isNaN(baseOpts.port)) url = `${url}:${baseOpts.port}`;
39
+ let influxDB: InfluxDB;
40
+ let bucket;
41
+ let org;
42
+ if (typeof baseOpts.host === 'undefined' || !baseOpts.host) {
43
+ logger.warn(`Interface: ${this.cfg.name} has not resolved to a valid host.`);
44
+ return;
45
+ }
46
+ if (baseOpts.version === 1) {
47
+ if (typeof baseOpts.database === 'undefined' || !baseOpts.database) {
48
+ logger.warn(`Interface: ${this.cfg.name} has not resolved to a valid database.`);
49
+ return;
50
+ }
51
+ bucket = `${baseOpts.database}/${baseOpts.retentionPolicy}`;
52
+ const clientOptions: ClientOptions = {
53
+ url,
54
+ token: `${baseOpts.username}:${baseOpts.password}`,
55
+ }
56
+ influxDB = new InfluxDB(clientOptions);
57
+ }
58
+ else if (baseOpts.version === 2) {
59
+ org = baseOpts.org;
60
+ bucket = baseOpts.bucket;
61
+ const clientOptions: ClientOptions = {
62
+ url,
63
+ token: baseOpts.token,
64
+ }
65
+ influxDB = new InfluxDB(clientOptions);
66
+ }
67
+ // set global tags from context
68
+ let baseTags = {}
69
+ baseOpts.tags.forEach(tag => {
70
+ let toks = {};
71
+ let sname = this.tokensReplacer(tag.name, undefined, toks, undefined, {})
72
+ let svalue = this.tokensReplacer(tag.value, undefined, toks, { vars: {} } as any, {});
73
+ if (typeof sname !== 'undefined' && typeof svalue !== 'undefined' && !sname.includes('@bind') && !svalue.includes('@bind'))
74
+ baseTags[sname] = svalue;
75
+ })
76
+ //this.writeApi.useDefaultTags(baseTags);
77
+ const writeOptions:WriteOptions = {
78
+ /* the maximum points/line to send in a single batch to InfluxDB server */
79
+ batchSize: baseOpts.batchSize || 100,
80
+ /* default tags to add to every point */
81
+ defaultTags: baseTags,
82
+ /* maximum time in millis to keep points in an unflushed batch, 0 means don't periodically flush */
83
+ flushInterval: DEFAULT_WriteOptions.flushInterval,
84
+ /* maximum size of the retry buffer - it contains items that could not be sent for the first time */
85
+ maxBufferLines: DEFAULT_WriteOptions.maxBufferLines,
86
+ /* the count of retries, the delays between retries follow an exponential backoff strategy if there is no Retry-After HTTP header */
87
+ maxRetries: DEFAULT_WriteOptions.maxRetries,
88
+ /* maximum delay between retries in milliseconds */
89
+ maxRetryDelay: DEFAULT_WriteOptions.maxRetryDelay,
90
+ /* minimum delay between retries in milliseconds */
91
+ minRetryDelay: DEFAULT_WriteOptions.minRetryDelay, // minimum delay between retries
92
+ /* a random value of up to retryJitter is added when scheduling next retry */
93
+ retryJitter: DEFAULT_WriteOptions.retryJitter,
94
+ // ... or you can customize what to do on write failures when using a writeFailed fn, see the API docs for details
95
+ writeFailed: function(error, lines, failedAttempts){
96
+ /** return promise or void */
97
+ logger.error(`InfluxDB batch write failed writing ${lines.length} lines with ${failedAttempts} failed attempts. ${error.message}`);
98
+ //console.log(lines);
99
+ },
100
+ writeSuccess: function(lines){
101
+ logger.silly(`InfluxDB successfully wrote ${lines.length} lines.`)
102
+ },
103
+ writeRetrySkipped: function(entry){
104
+ logger.silly(`Influx write retry skipped ${JSON.stringify(entry)}`);
105
+ },
106
+ maxRetryTime: DEFAULT_WriteOptions.maxRetryTime,
107
+ exponentialBase: DEFAULT_WriteOptions.exponentialBase,
108
+ randomRetry: DEFAULT_WriteOptions.randomRetry,
109
+ maxBatchBytes: 4096
110
+
111
+ }
112
+ this.writeApi = influxDB.getWriteApi(org, bucket, 'ms', writeOptions);
113
+
114
+
115
+
116
+ }
117
+ public bindEvent(evt: string, ...data: any) {
118
+
119
+ // if (state.status.value !== sys.board.valueMaps.controllerStatus.getValue('ready')) return; // miss values? or show errors? or?
120
+ if (typeof this.events !== 'undefined') {
121
+ if (typeof this.writeApi === 'undefined') this.init();
122
+ let evts = this.events.filter(elem => elem.name === evt);
123
+ if (evts.length > 0) {
124
+ let toks = {};
125
+ for (let i = 0; i < evts.length; i++) {
126
+ let e = evts[i];
127
+ if (typeof e.enabled !== 'undefined' && !e.enabled) continue;
128
+ // Figure out whether we need to check the filter.
129
+ if (typeof e.filter !== 'undefined') {
130
+ this.buildTokens(e.filter, evt, toks, e, data[0]);
131
+ if (eval(this.replaceTokens(e.filter, toks)) === false) continue;
132
+ }
133
+ for (let j = 0; j < e.points.length; j++) {
134
+ let _point = e.points[j];
135
+ // Figure out whether we need to check the filter for each point.
136
+ if (typeof _point.filter !== 'undefined') {
137
+ this.buildTokens(_point.filter, evt, toks, e, data[0]);
138
+ if (eval(this.replaceTokens(_point.filter, toks)) === false) continue;
139
+ }
140
+ // iterate through points array
141
+ let point = new Point(_point.measurement)
142
+ let point2 = new Point(_point.measurement);
143
+ _point.tags.forEach(_tag => {
144
+ let sname = _tag.name;
145
+ this.buildTokens(sname, evt, toks, e, data[0]);
146
+ sname = this.replaceTokens(sname, toks);
147
+ let svalue = _tag.value;
148
+ this.buildTokens(svalue, evt, toks, e, data[0]);
149
+ svalue = this.replaceTokens(svalue, toks);
150
+ if (typeof sname !== 'undefined' && typeof svalue !== 'undefined' && !sname.includes('@bind') && !svalue.includes('@bind') && svalue !== null) {
151
+ point.tag(sname, svalue);
152
+ if (typeof _point.storePrevState !== 'undefined' && _point.storePrevState) point2.tag(sname, svalue);
153
+ }
154
+ else {
155
+ logger.error(`InfluxDB tag binding failure on ${evt}:${_tag.name}/${_tag.value} --> ${svalue || 'undefined'} ${JSON.stringify(data[0])}`);
156
+ if (typeof sname === 'undefined') logger.error(`InfluxDB tag name is undefined`);
157
+ if (typeof svalue === 'undefined') logger.error(`InfluxDB value is undefined`);
158
+ if (svalue.includes('@bind')) logger.error(`InfluxDB value not bound`);
159
+ if (svalue === null) logger.error(`InfluxDB value is null`);
160
+ }
161
+ })
162
+ _point.fields.forEach(_field => {
163
+ try {
164
+ let sname = _field.name;
165
+ this.buildTokens(sname, evt, toks, e, data[0]);
166
+ //console.log(toks);
167
+ sname = this.replaceTokens(sname, toks);
168
+ let svalue = _field.value;
169
+ this.buildTokens(svalue, evt, toks, e, data[0]);
170
+ svalue = this.replaceTokens(svalue, toks);
171
+ if (typeof sname !== 'undefined' && typeof svalue !== 'undefined' && !sname.includes('@bind') && !svalue.includes('@bind') && svalue !== null)
172
+ switch (_field.type) {
173
+ case 'int':
174
+ case 'integer':
175
+ let int = parseInt(svalue, 10);
176
+ if (!isNaN(int)) point.intField(sname, int);
177
+ // if (!isNaN(int) && typeof _point.storePrevState !== 'undefined' && _point.storePrevState) point2.intField(sname, int);
178
+ break;
179
+ case 'string':
180
+ point.stringField(sname, svalue);
181
+ // if (typeof _point.storePrevState !== 'undefined' && _point.storePrevState) point2.stringField(sname, svalue);
182
+ break;
183
+ case 'boolean':
184
+ point.booleanField(sname, utils.makeBool(svalue));
185
+ if (typeof _point.storePrevState !== 'undefined' && _point.storePrevState) point2.booleanField(sname, !utils.makeBool(svalue));
186
+ break;
187
+ case 'float':
188
+ let float = parseFloat(svalue);
189
+ if (!isNaN(float)) point.floatField(sname, float);
190
+ // if (!isNaN(float) && typeof _point.storePrevState !== 'undefined' && _point.storePrevState) point2.intField(sname, int);
191
+ break;
192
+ case 'timestamp':
193
+ case 'datetime':
194
+ case 'date':
195
+ //let dt = Date.parse(svalue.replace(/^["'](.+(?=["']$))["']$/, '$1'));
196
+ // RKS: 07-06-21 - I think this is missing the eval function around all of this. The strings still have the quotes around them. I think
197
+ // maybe we need to create a closure and execute it as a code segment for variable data.
198
+ let sdt = eval(svalue);
199
+ if (sdt !== null && typeof sdt !== 'undefined') {
200
+ let dt = Date.parse(sdt);
201
+ if (!isNaN(dt)) point.intField(sname, dt);
202
+ else if (svalue !== '') logger.warn(`Influx error parsing date from ${sname}: ${svalue}`);
203
+ }
204
+ break;
205
+ }
206
+ else {
207
+ logger.error(`InfluxDB point binding failure on ${evt}:${_field.name}/${_field.value} --> ${svalue || 'undefined'}`);
208
+ }
209
+ } catch (err) { logger.error(`Error binding InfluxDB point fields ${err.message}`); }
210
+ });
211
+ if (typeof _point.series !== 'undefined') {
212
+ try {
213
+ this.buildTokens(_point.series.value, evt, toks, e, data[0]);
214
+ let ser = eval(this.replaceTokens(_point.series.value, toks));
215
+ let ts = Date.parse(ser);
216
+ if (isNaN(ts)) {
217
+ logger.error(`Influx series timestamp is invalid ${ser}`);
218
+ }
219
+ else
220
+ point.timestamp(new Date(ts));
221
+ } catch (err) { logger.error(`Error parsing Influx point series for ${evt} - ${_point.series.value}`); }
222
+ }
223
+ else
224
+ point.timestamp(new Date());
225
+ try {
226
+
227
+ if (typeof _point.storePrevState !== 'undefined' && _point.storePrevState) {
228
+ // copy the point and subtract a second and keep inverse value
229
+ let ts = new Date();
230
+ let sec = ts.getSeconds() - 1;
231
+ ts.setSeconds(sec);
232
+ point2.timestamp(ts);
233
+ logger.silly(`Batching influx ${e.name} inverse data point ${point2.toString()})`)
234
+ this.writeApi.writePoint(point2);
235
+ }
236
+ if (typeof point.toLineProtocol() !== 'undefined') {
237
+ logger.silly(`Batching influx ${e.name} data point ${point.toString()}`)
238
+ this.writeApi.writePoint(point);
239
+ // this.writeApi.flush()
240
+ // .catch(error => { logger.error(`Error flushing Influx data point ${point.toString()} ${error}`); });
241
+ //logger.info(`INFLUX: ${point.toLineProtocol()}`)
242
+ }
243
+ else {
244
+ logger.silly(`Skipping INFLUX write because some data is missing with ${e.name} event on measurement ${_point.measurement}.`)
245
+ }
246
+ }
247
+ catch (err) {
248
+ logger.error(`Error writing to Influx: ${err.message}`)
249
+ }
250
+ }
251
+ }
252
+ }
253
+ }
254
+ }
255
+ public close = () => {
256
+
257
+ }
258
+ }
259
+
260
+ class InfluxInterfaceEvent extends InterfaceEvent {
261
+ public points: IPoint[];
262
+ }
263
+
264
+ export interface IPoint {
265
+ measurement: string;
266
+ series?: ISeries;
267
+ tags: ITag[];
268
+ fields: IFields[];
269
+ storePrevState?: boolean;
270
+ filter?: any;
271
+ }
272
+ export interface ITag {
273
+ name: string;
274
+ value: string;
275
+ }
276
+ export interface IFields {
277
+ name: string;
278
+ value: string;
279
+ type: string;
280
+ }
281
+ export interface ISeries {
282
+ value: string;
283
+ }