nodejs-poolcontroller 7.6.1 → 7.7.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 (91) hide show
  1. package/.eslintrc.json +44 -44
  2. package/.github/ISSUE_TEMPLATE/1-bug-report.yml +84 -0
  3. package/.github/ISSUE_TEMPLATE/2-docs.md +12 -0
  4. package/.github/ISSUE_TEMPLATE/3-proposal.md +28 -0
  5. package/.github/ISSUE_TEMPLATE/config.yml +8 -0
  6. package/CONTRIBUTING.md +74 -74
  7. package/Changelog +220 -215
  8. package/Dockerfile +17 -17
  9. package/Gruntfile.js +40 -40
  10. package/LICENSE +661 -661
  11. package/README.md +191 -191
  12. package/app.ts +1 -1
  13. package/config/Config.ts +14 -0
  14. package/config/VersionCheck.ts +2 -2
  15. package/controller/Constants.ts +2 -1
  16. package/controller/Equipment.ts +2484 -2459
  17. package/controller/Errors.ts +180 -180
  18. package/controller/Lockouts.ts +502 -436
  19. package/controller/State.ts +106 -30
  20. package/controller/boards/AquaLinkBoard.ts +1000 -0
  21. package/controller/boards/BoardFactory.ts +49 -45
  22. package/controller/boards/EasyTouchBoard.ts +2859 -2653
  23. package/controller/boards/IntelliCenterBoard.ts +4198 -4230
  24. package/controller/boards/IntelliComBoard.ts +63 -63
  25. package/controller/boards/IntelliTouchBoard.ts +273 -241
  26. package/controller/boards/NixieBoard.ts +1728 -1675
  27. package/controller/boards/SystemBoard.ts +4925 -4697
  28. package/controller/comms/Comms.ts +442 -479
  29. package/controller/comms/messages/Messages.ts +171 -25
  30. package/controller/comms/messages/config/ChlorinatorMessage.ts +5 -2
  31. package/controller/comms/messages/config/CircuitGroupMessage.ts +0 -0
  32. package/controller/comms/messages/config/CircuitMessage.ts +1 -0
  33. package/controller/comms/messages/config/ConfigMessage.ts +0 -0
  34. package/controller/comms/messages/config/CoverMessage.ts +0 -0
  35. package/controller/comms/messages/config/CustomNameMessage.ts +30 -30
  36. package/controller/comms/messages/config/EquipmentMessage.ts +0 -0
  37. package/controller/comms/messages/config/ExternalMessage.ts +0 -0
  38. package/controller/comms/messages/config/FeatureMessage.ts +0 -0
  39. package/controller/comms/messages/config/GeneralMessage.ts +0 -0
  40. package/controller/comms/messages/config/HeaterMessage.ts +142 -10
  41. package/controller/comms/messages/config/IntellichemMessage.ts +0 -0
  42. package/controller/comms/messages/config/OptionsMessage.ts +4 -21
  43. package/controller/comms/messages/config/PumpMessage.ts +53 -35
  44. package/controller/comms/messages/config/RemoteMessage.ts +0 -0
  45. package/controller/comms/messages/config/ScheduleMessage.ts +350 -347
  46. package/controller/comms/messages/config/SecurityMessage.ts +0 -0
  47. package/controller/comms/messages/config/ValveMessage.ts +1 -1
  48. package/controller/comms/messages/status/ChlorinatorStateMessage.ts +38 -86
  49. package/controller/comms/messages/status/EquipmentStateMessage.ts +58 -22
  50. package/controller/comms/messages/status/HeaterStateMessage.ts +116 -86
  51. package/controller/comms/messages/status/IntelliChemStateMessage.ts +445 -445
  52. package/controller/comms/messages/status/IntelliValveStateMessage.ts +35 -35
  53. package/controller/comms/messages/status/PumpStateMessage.ts +23 -1
  54. package/controller/comms/messages/status/VersionMessage.ts +0 -0
  55. package/controller/nixie/Nixie.ts +162 -162
  56. package/controller/nixie/NixieEquipment.ts +103 -103
  57. package/controller/nixie/bodies/Body.ts +120 -120
  58. package/controller/nixie/bodies/Filter.ts +135 -135
  59. package/controller/nixie/chemistry/ChemController.ts +2511 -2498
  60. package/controller/nixie/chemistry/Chlorinator.ts +363 -314
  61. package/controller/nixie/circuits/Circuit.ts +261 -248
  62. package/controller/nixie/heaters/Heater.ts +650 -648
  63. package/controller/nixie/pumps/Pump.ts +906 -661
  64. package/controller/nixie/schedules/Schedule.ts +313 -257
  65. package/controller/nixie/valves/Valve.ts +170 -170
  66. package/defaultConfig.json +306 -286
  67. package/logger/DataLogger.ts +448 -448
  68. package/logger/Logger.ts +0 -0
  69. package/package.json +56 -56
  70. package/tsconfig.json +25 -25
  71. package/web/Server.ts +92 -47
  72. package/web/bindings/aqualinkD.json +505 -0
  73. package/web/bindings/influxDB.json +1051 -1021
  74. package/web/bindings/mqtt.json +702 -654
  75. package/web/bindings/mqttAlt.json +731 -684
  76. package/web/bindings/rulesManager.json +54 -54
  77. package/web/bindings/smartThings-Hubitat.json +31 -31
  78. package/web/bindings/valveRelays.json +20 -20
  79. package/web/bindings/vera.json +25 -25
  80. package/web/interfaces/baseInterface.ts +137 -136
  81. package/web/interfaces/httpInterface.ts +145 -124
  82. package/web/interfaces/influxInterface.ts +276 -245
  83. package/web/interfaces/mqttInterface.ts +535 -475
  84. package/web/services/config/Config.ts +39 -18
  85. package/web/services/config/ConfigSocket.ts +0 -0
  86. package/web/services/state/State.ts +10 -0
  87. package/web/services/state/StateSocket.ts +4 -4
  88. package/web/services/utilities/Utilities.ts +44 -42
  89. package/.github/ISSUE_TEMPLATE/bug_report.md +0 -52
  90. package/config copy.json +0 -300
  91. package/issue_template.md +0 -52
@@ -1,475 +1,535 @@
1
- /* nodejs-poolController. An application to control pool equipment.
2
- Copyright (C) 2016, 2017. Russell Goldin, tagyoureit. russ.goldin@gmail.com
3
-
4
- This program is free software: you can redistribute it and/or modify
5
- it under the terms of the GNU Affero General Public License as
6
- published by the Free Software Foundation, either version 3 of the
7
- License, or (at your option) any later version.
8
-
9
- This program is distributed in the hope that it will be useful,
10
- but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- GNU Affero General Public License for more details.
13
-
14
- You should have received a copy of the GNU Affero General Public License
15
- along with this program. If not, see <http://www.gnu.org/licenses/>.
16
- */
17
- import { connect, MqttClient, Client, IClientPublishOptions, CloseCallback } from 'mqtt';
18
- import * as http2 from "http2";
19
- import * as http from "http";
20
- import * as https from "https";
21
- import extend = require("extend");
22
- import { logger } from "../../logger/Logger";
23
- import { sys } from "../../controller/Equipment";
24
- import { state } from "../../controller/State";
25
- import { InterfaceEvent, BaseInterfaceBindings } from "./baseInterface";
26
- import { sys as sysAlias } from "../../controller/Equipment";
27
- import { state as stateAlias } from "../../controller/State";
28
- import { webApp as webAppAlias } from '../Server';
29
- import { utils } from "../../controller/Constants";
30
- import { ServiceParameterError } from '../../controller/Errors';
31
-
32
- export class MqttInterfaceBindings extends BaseInterfaceBindings {
33
- constructor(cfg) {
34
- super(cfg);
35
- this.subscribed = false;
36
- }
37
- private client: MqttClient;
38
- private topics: string[] = [];
39
- declare events: MqttInterfaceEvent[];
40
- private subscribed: boolean; // subscribed to events or not
41
- private sentInitialMessages = false;
42
- private init = () => {
43
- let baseOpts = extend(true, { headers: {} }, this.cfg.options, this.context.options);
44
- if ((typeof baseOpts.hostname === 'undefined' || !baseOpts.hostname) && (typeof baseOpts.host === 'undefined' || !baseOpts.host || baseOpts.host === '*')) {
45
- logger.warn(`Interface: ${this.cfg.name} has not resolved to a valid host.`);
46
- return;
47
- }
48
- const url = `${baseOpts.protocol || 'mqtt://'}${baseOpts.host}:${baseOpts.port || 1883}`;
49
- let toks = {};
50
- const opts = {
51
- clientId: this.tokensReplacer(baseOpts.clientId, undefined, toks, { vars: {} } as any, {}),
52
- username: baseOpts.username,
53
- password: baseOpts.password,
54
- rejectUnauthorized: !baseOpts.selfSignedCertificate,
55
- url
56
- }
57
- this.client = connect(url, opts);
58
-
59
- this.client.on('connect', () => {
60
- try {
61
- logger.info(`MQTT connected to ${url}`);
62
- this.subscribe();
63
- } catch (err) { logger.error(err); }
64
- });
65
-
66
- this.client.on('error', (error) => {
67
- logger.error(`MQTT error ${error}`)
68
- });
69
- }
70
- public async stopAsync() {
71
- try {
72
- if (typeof this.client !== 'undefined') {
73
- this.unsubscribe();
74
- this.client.end(true, { reasonCode: 0, reasonString: `Shutting down MQTT Client` }, () => {
75
- logger.info(`Successfully shut down MQTT Client`);
76
- });
77
- }
78
- } catch (err) { logger.error(`Error stopping MQTT Client: ${err.message}`); }
79
- }
80
- private async unsubscribe() {
81
- try {
82
- while (this.topics.length > 0) {
83
- let topic = this.topics.pop();
84
- if (typeof topic !== 'undefined') {
85
- this.client.unsubscribe(topic, (err, packet) => {
86
- if (err) logger.error(`Error unsubscribing from MQTT topic ${topic}`);
87
- else {
88
- logger.debug(`Unsubscribed from MQTT topic ${topic}`);
89
- }
90
- });
91
- }
92
- }
93
- } catch (err) { logger.error(`Error unsubcribing to MQTT topic: ${err.message}`); }
94
- }
95
- private subscribe() {
96
- try {
97
- if (this.topics.length > 0) this.unsubscribe();
98
- let root = this.rootTopic();
99
- this.topics.push(`${root}/state/+/setState`,
100
- `${root}/state/+/setstate`,
101
- `${root}/state/+/toggleState`,
102
- `${root}/state/+/togglestate`,
103
- `${root}/state/body/setPoint`,
104
- `${root}/state/body/setpoint`,
105
- `${root}/state/body/heatMode`,
106
- `${root}/state/body/heatmode`,
107
- `${root}/state/+/setTheme`,
108
- `${root}/state/+/settheme`,
109
- `${root}/state/temps`,
110
- `${root}/config/tempSensors`,
111
- `${root}/config/chemController`,
112
- `${root}/state/chemController`,
113
- `${root}/config/chlorinator`,
114
- `${root}/state/chlorinator`);
115
- for (let i = 0; i < this.topics.length; i++) {
116
- let topic = this.topics[i];
117
- // await new Promise<void>((resolve, reject) => {
118
- this.client.subscribe(topic, (err, granted) => {
119
- if (!err) {
120
- logger.debug(`MQTT subscribed to ${JSON.stringify(granted)}`);
121
- // resolve();
122
- }
123
- else {
124
- logger.error(`MQTT Subscribe: ${err}`);
125
- // reject(err);
126
- }
127
- });
128
- // });
129
-
130
- }
131
- this.client.on('message', async (topic, msg) => { try { await this.messageHandler(topic, msg) } catch (err) { logger.error(`Error processing MQTT request ${err}.`) }; })
132
- this.subscribed = true;
133
- } catch (err) { logger.error(`Error subcribing to MQTT topics`); }
134
- }
135
-
136
- // this will take in the MQTT Formatter options and format each token that is bound
137
- // otherwise, it's the same as the base buildTokens fn.
138
- // This could be combined into one fn but for now it's specific to MQTT formatting of topics
139
- protected buildTokensWithFormatter(input: string, eventName: string, toks: any, e: InterfaceEvent, data, formatter: any): any {
140
- toks = toks || [];
141
- let s = input;
142
- let regx = /(?<=@bind\=\s*).*?(?=\;)/g;
143
- let match;
144
- let vars = extend(true, {}, this.cfg.vars, this.context.vars, typeof e !== 'undefined' && e.vars);
145
- let sys = sysAlias;
146
- let state = stateAlias;
147
- let webApp = webAppAlias;
148
- // Map all the returns to the token list. We are being very basic
149
- // here an the object graph is simply based upon the first object occurrence.
150
- // We simply want to eval against that object reference.
151
-
152
- while (match = regx.exec(s)) {
153
- let bind = match[0];
154
- if (typeof toks[bind] !== 'undefined') continue;
155
- let tok: any = {};
156
- toks[bind] = tok;
157
- try {
158
- // we may error out if data can't be found (eg during init)
159
- tok.reg = new RegExp("@bind=" + this.escapeRegex(bind) + ";", "g");
160
- tok.value = eval(bind);
161
- if (typeof formatter !== 'undefined') {
162
- formatter.forEach(entry => {
163
- if (typeof entry.transform !== 'undefined') {
164
- let transform = `('${tok.value}')${entry.transform}`;
165
- tok.value = eval(transform);
166
- }
167
- else if (typeof entry === 'object') {
168
- let rexp = new RegExp(entry.regexkey, 'g')
169
- tok.value = tok.value.replace(rexp, entry.replace);
170
- }
171
- })
172
- }
173
- }
174
- catch (err) {
175
- // leave value undefined so it isn't sent to bindings
176
- tok[bind] = null;
177
- }
178
- }
179
- return toks;
180
- }
181
-
182
- private rootTopic = () => {
183
- let toks = {};
184
- let baseOpts = extend(true, { headers: {} }, this.cfg.options, this.context.options);
185
- let topic = '';
186
- this.buildTokensWithFormatter(baseOpts.rootTopic, undefined, toks, undefined, undefined, baseOpts.formatter);
187
- topic = this.replaceTokens(baseOpts.rootTopic, toks);
188
- return topic;
189
- }
190
-
191
- public bindEvent(evt: string, ...data: any) {
192
- try {
193
- if (!this.sentInitialMessages && evt === 'controller' && data[0].status.val === 1) {
194
- state.emitAllEquipmentChanges();
195
- this.sentInitialMessages = true;
196
- }
197
- // Find the binding by first looking for the specific event name.
198
- // If that doesn't exist then look for the "*" (all events).
199
- if (typeof this.events !== 'undefined') {
200
- if (typeof this.client === 'undefined') this.init();
201
- let evts = this.events.filter(elem => elem.name === evt);
202
- // If we don't have an explicitly defined event then see if there is a default.
203
- if (evts.length === 0) {
204
- let e = this.events.find(elem => elem.name === '*');
205
- evts = e ? [e] : [];
206
- }
207
-
208
- if (evts.length > 0) {
209
- let toks = {};
210
- let replacer = '';
211
- for (let i = 0; i < evts.length; i++) {
212
- let e = evts[i];
213
- if (typeof e.enabled !== 'undefined' && !e.enabled) continue;
214
- let baseOpts = extend(true, { headers: {} }, this.cfg.options, this.context.options);
215
- let opts = extend(true, baseOpts, e.options);
216
- // Figure out whether we need to check the filter.
217
- if (typeof e.filter !== 'undefined') {
218
- this.buildTokens(e.filter, evt, toks, e, data[0]);
219
- if (eval(this.replaceTokens(e.filter, toks)) === false) continue;
220
- }
221
-
222
- let rootTopic = this.rootTopic();
223
- if (typeof opts.replacer !== 'undefined') replacer = opts.replacer;
224
- if (typeof e.topics !== 'undefined') e.topics.forEach(t => {
225
- let topicToks = {};
226
- if (typeof t.enabled !== 'undefined' && !t.enabled) return;
227
- if (typeof t.filter !== 'undefined') {
228
- this.buildTokens(t.filter, evt, topicToks, e, data[0]);
229
- if (eval(this.replaceTokens(t.filter, topicToks)) === false) return;
230
- }
231
- let topicFormatter = t.formatter || opts.formatter;
232
- let topic = '';
233
- let message: any;
234
- // build tokens for Topic
235
- // we need to keep separated topic tokens because otherwise
236
- // a value like @bind=data.name; would be eval'd the same
237
- // across all topics
238
- this.buildTokensWithFormatter(t.topic, evt, topicToks, e, data[0], topicFormatter);
239
- topic = `${rootTopic}/${this.replaceTokens(t.topic, topicToks)}`;
240
- // Filter out any topics where there may be undefined in it. We don't want any of this if that is the case.
241
- if (topic.endsWith('/undefined') || topic.indexOf('/undefined/') !== -1 || topic.startsWith('null/') || topic.indexOf('/null') !== -1) return;
242
-
243
-
244
- this.buildTokens(t.message, evt, topicToks, e, data[0]);
245
- message = this.tokensReplacer(t.message, evt, topicToks, e, data[0]);
246
-
247
- let publishOptions: IClientPublishOptions = { retain: typeof baseOpts.retain !== 'undefined' ? baseOpts.retain : true, qos: typeof baseOpts.qos !== 'undefined' ? baseOpts.qos : 2 };
248
- let changesOnly = typeof baseOpts.changesOnly !== 'undefined' ? baseOpts.changesOnly : true;
249
- if (typeof e.options !== 'undefined') {
250
- if (typeof e.options.retain !== 'undefined') publishOptions.retain = e.options.retain;
251
- if (typeof e.options.qos !== 'undefined') publishOptions.retain = e.options.qos;
252
- if (typeof e.options.changesOnly !== 'undefined') changesOnly = e.options.changesOnly;
253
- }
254
- if (typeof t.options !== 'undefined') {
255
- if (typeof t.options.retain !== 'undefined') publishOptions.retain = t.options.retain;
256
- if (typeof t.options.qos !== 'undefined') publishOptions.qos = t.options.qos;
257
- if (typeof t.options.changeOnly !== 'undefined') changesOnly = t.options.changesOnly;
258
- }
259
- if (changesOnly) {
260
- if (typeof t.lastSent === 'undefined') t.lastSent = [];
261
- let lm = t.lastSent.find(elem => elem.topic === topic);
262
- if (typeof lm === 'undefined' || lm.message !== message) {
263
- setImmediate(() => { this.client.publish(topic, message, publishOptions); });
264
- logger.silly(`MQTT send:\ntopic: ${topic}\nmessage: ${message}\nopts:${JSON.stringify(publishOptions)}`);
265
- }
266
- if (typeof lm === 'undefined') t.lastSent.push({ topic: topic, message: message });
267
- else lm.message = message;
268
-
269
- }
270
- else {
271
- logger.silly(`MQTT send:\ntopic: ${topic}\nmessage: ${message}\nopts:${JSON.stringify(publishOptions)}`);
272
- setImmediate(() => { this.client.publish(topic, message, publishOptions); });
273
- if (typeof t.lastSent !== 'undefined') t.lastSent = undefined;
274
- }
275
-
276
- })
277
- }
278
- }
279
- }
280
- }
281
- catch (err) {
282
- logger.error(err);
283
- }
284
- }
285
- private messageHandler = async (topic, message) => {
286
- try {
287
- let msg = message.toString();
288
- if (msg[0] === '{') msg = JSON.parse(msg);
289
- const topics = topic.split('/');
290
- logger.debug(`MQTT: Inbound ${topic}: ${message.toString()}`);
291
- if (topic.startsWith(this.rootTopic() + '/') && typeof msg === 'object') {
292
- // RKS: Not sure why there is no processing of state vs config here. Right now the topics are unique
293
- // between them so it doesn't matter but it will become an issue.
294
- switch (topics[topics.length - 1].toLowerCase()) {
295
- case 'setstate': {
296
- let id = parseInt(msg.id, 10);
297
- if (typeof id !== 'undefined' && isNaN(id)) {
298
- logger.error(`Inbound MQTT ${topics} has an invalid id (${id}) in the message (${msg}).`)
299
- };
300
- let isOn = utils.makeBool(msg.isOn);
301
- switch (topics[topics.length - 2].toLowerCase()) {
302
- case 'circuits':
303
- case 'circuit': {
304
- try {
305
- if (msg.isOn !== 'undefined') await sys.board.circuits.setCircuitStateAsync(id, isOn);
306
- }
307
- catch (err) { logger.error(err); }
308
- break;
309
- }
310
- case 'features':
311
- case 'feature': {
312
- try {
313
- if (msg.isOn !== 'undefined') await sys.board.features.setFeatureStateAsync(id, isOn);
314
- }
315
- catch (err) { logger.error(err); }
316
- break;
317
- }
318
- case 'lightgroups':
319
- case 'lightgroup': {
320
- try {
321
- await sys.board.circuits.setLightGroupStateAsync(id, isOn);
322
- }
323
- catch (err) { logger.error(err); }
324
- break;
325
- }
326
- case 'circuitgroups':
327
- case 'circuitgroup': {
328
- try {
329
- await sys.board.circuits.setCircuitGroupStateAsync(id, isOn);
330
- }
331
- catch (err) { logger.error(err); }
332
- break;
333
- }
334
- default:
335
- logger.warn(`MQTT: Inbound topic ${topics[topics.length - 1]} not matched to event ${topics[topics.length - 2].toLowerCase()}. Message ${msg} `)
336
- }
337
- break;
338
- }
339
- case 'togglestate':
340
- {
341
- let id = parseInt(msg.id, 10);
342
- if (typeof id !== 'undefined' && isNaN(id)) {
343
- logger.error(`Inbound MQTT ${topics} has an invalid id (${id}) in the message (${msg}).`)
344
- };
345
- switch (topics[topics.length - 2].toLowerCase()) {
346
- case 'circuits':
347
- case 'circuit':
348
- try {
349
- await sys.board.circuits.toggleCircuitStateAsync(id);
350
- }
351
- catch (err) { logger.error(err); }
352
- break;
353
- case 'features':
354
- case 'feature':
355
- try {
356
- await sys.board.features.toggleFeatureStateAsync(id);
357
- }
358
- catch (err) { logger.error(err); }
359
- break;
360
- default:
361
- logger.warn(`MQTT: Inbound topic ${topics[topics.length - 1]} not matched to event ${topics[topics.length - 2].toLowerCase()}. Message ${msg} `)
362
- }
363
- break;
364
- }
365
- case 'setpoint':
366
- try {
367
- let body = sys.bodies.findByObject(msg);
368
- if (topics[topics.length - 2].toLowerCase() === 'body') {
369
- if (typeof body === 'undefined') {
370
- logger.error(new ServiceParameterError(`Cannot set body setPoint. You must supply a valid id, circuit, name, or type for the body`, 'body', 'id', msg.id));
371
- return;
372
- }
373
- if (typeof msg.setPoint !== 'undefined' || typeof msg.heatSetpoint !== 'undefined') {
374
- let setPoint = parseInt(msg.setPoint, 10) || parseInt(msg.heatSetpoint, 10);
375
- if (!isNaN(setPoint)) {
376
- await sys.board.bodies.setHeatSetpointAsync(body, setPoint);
377
- }
378
- }
379
- if (typeof msg.coolSetpoint !== 'undefined') {
380
- let setPoint = parseInt(msg.coolSetpoint, 10);
381
- if (!isNaN(setPoint)) {
382
- await sys.board.bodies.setCoolSetpointAsync(body, setPoint);
383
- }
384
- }
385
- }
386
- }
387
- catch (err) { logger.error(err); }
388
- break;
389
- case 'heatmode':
390
- try {
391
- if (topics[topics.length - 2].toLowerCase() !== 'body') return;
392
- // Map the mode that was passed in. This should accept the text based name or the ordinal id value.
393
- let mode = parseInt(msg.mode, 10);
394
- let val;
395
- if (isNaN(mode)) mode = parseInt(msg.heatMode, 10);
396
- if (!isNaN(mode)) val = sys.board.valueMaps.heatModes.transform(mode);
397
- else val = sys.board.valueMaps.heatModes.transformByName(msg.mode || msg.heatMode);
398
- if (typeof val.val === 'undefined') {
399
- logger.error(new ServiceParameterError(`Invalid value for heatMode: ${msg.mode}`, 'body', 'heatMode', mode));
400
- return;
401
- }
402
- mode = val.val;
403
- let body = sys.bodies.findByObject(msg);
404
- if (typeof body === 'undefined') {
405
- logger.error(new ServiceParameterError(`Cannot set body heatMode. You must supply a valid id, circuit, name, or type for the body`, 'body', 'id', msg.id));
406
- return;
407
- }
408
- let tbody = await sys.board.bodies.setHeatModeAsync(body, mode);
409
- }
410
- catch (err) { logger.error(err); }
411
- break;
412
- case 'chlorinator':
413
- try {
414
- let schlor = await sys.board.chlorinator.setChlorAsync(msg);
415
- }
416
- catch (err) { logger.error(err); }
417
- break;
418
- case 'chemcontroller':
419
- try {
420
- await sys.board.chemControllers.setChemControllerAsync(msg);
421
- }
422
- catch (err) { logger.error(err); }
423
- break;
424
- case 'settheme':
425
- try {
426
- let theme = await state.circuits.setLightThemeAsync(parseInt(msg.id, 10), sys.board.valueMaps.lightThemes.encode(msg.theme));
427
- }
428
- catch (err) { logger.error(err); }
429
- break;
430
- case 'temp':
431
- case 'temps':
432
- try {
433
- await sys.board.system.setTempsAsync(msg);
434
- }
435
- catch (err) { logger.error(err); }
436
- break;
437
- case 'tempsensor':
438
- case 'tempsensors':
439
- try {
440
- await sys.board.system.setTempSensorsAsync(msg);
441
- }
442
- catch (err) { logger.error(err); }
443
- break;
444
- default:
445
- logger.silly(`MQTT: Inbound MQTT topic not matched: ${topic}: ${message.toString()}`)
446
- break;
447
- }
448
- }
449
- }
450
- catch (err) {
451
- logger.error(`Error processing MQTT request ${topic}: ${err}. ${message}`)
452
- }
453
- }
454
- }
455
-
456
- class MqttInterfaceEvent extends InterfaceEvent {
457
- public topics: IMQTT[]
458
- }
459
-
460
- export interface IMQTT {
461
- topic: string;
462
- message: string;
463
- description: string;
464
- formatter: any[];
465
- qos: string;
466
- retain: boolean;
467
- enabled?: boolean;
468
- filter?: string;
469
- lastSent: MQTTMessage[];
470
- options: any;
471
- }
472
- class MQTTMessage {
473
- topic: string;
474
- message: string;
475
- }
1
+ /* nodejs-poolController. An application to control pool equipment.
2
+ Copyright (C) 2016, 2017. Russell Goldin, tagyoureit. russ.goldin@gmail.com
3
+
4
+ This program is free software: you can redistribute it and/or modify
5
+ it under the terms of the GNU Affero General Public License as
6
+ published by the Free Software Foundation, either version 3 of the
7
+ License, or (at your option) any later version.
8
+
9
+ This program is distributed in the hope that it will be useful,
10
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ GNU Affero General Public License for more details.
13
+
14
+ You should have received a copy of the GNU Affero General Public License
15
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
16
+ */
17
+ import { connect, MqttClient, Client, IClientPublishOptions, CloseCallback } from 'mqtt';
18
+ import * as http2 from "http2";
19
+ import * as http from "http";
20
+ import * as https from "https";
21
+ import extend = require("extend");
22
+ import { logger } from "../../logger/Logger";
23
+ import { PoolSystem, sys } from "../../controller/Equipment";
24
+ import { State, state } from "../../controller/State";
25
+ import { InterfaceEvent, BaseInterfaceBindings } from "./baseInterface";
26
+ import { sys as sysAlias } from "../../controller/Equipment";
27
+ import { state as stateAlias } from "../../controller/State";
28
+ import { webApp as webAppAlias } from '../Server';
29
+ import { utils } from "../../controller/Constants";
30
+ import { ServiceParameterError } from '../../controller/Errors';
31
+
32
+ export class MqttInterfaceBindings extends BaseInterfaceBindings {
33
+ constructor(cfg) {
34
+ super(cfg);
35
+ this.subscribed = false;
36
+ }
37
+ private client: MqttClient;
38
+ private topics: MqttTopicSubscription[] = [];
39
+ declare events: MqttInterfaceEvent[];
40
+ declare subscriptions: MqttTopicSubscription[];
41
+ private subscribed: boolean; // subscribed to events or not
42
+ private sentInitialMessages = false;
43
+ private init = () => {
44
+ let baseOpts = extend(true, { headers: {} }, this.cfg.options, this.context.options);
45
+ if ((typeof baseOpts.hostname === 'undefined' || !baseOpts.hostname) && (typeof baseOpts.host === 'undefined' || !baseOpts.host || baseOpts.host === '*')) {
46
+ logger.warn(`Interface: ${this.cfg.name} has not resolved to a valid host.`);
47
+ return;
48
+ }
49
+ const url = `${baseOpts.protocol || 'mqtt://'}${baseOpts.host}:${baseOpts.port || 1883}`;
50
+ let toks = {};
51
+ const opts = {
52
+ clientId: this.tokensReplacer(baseOpts.clientId, undefined, toks, { vars: {} } as any, {}),
53
+ username: baseOpts.username,
54
+ password: baseOpts.password,
55
+ rejectUnauthorized: !baseOpts.selfSignedCertificate,
56
+ url
57
+ }
58
+ this.client = connect(url, opts);
59
+ this.client.on('connect', () => {
60
+ try {
61
+ logger.info(`MQTT connected to ${url}`);
62
+ this.subscribe();
63
+ } catch (err) { logger.error(err); }
64
+ });
65
+
66
+ this.client.on('error', (error) => {
67
+ logger.error(`MQTT error ${error}`)
68
+ });
69
+ }
70
+ public async stopAsync() {
71
+ try {
72
+ if (typeof this.client !== 'undefined') {
73
+ this.unsubscribe();
74
+ this.client.end(true, { reasonCode: 0, reasonString: `Shutting down MQTT Client` }, () => {
75
+ logger.info(`Successfully shut down MQTT Client`);
76
+ });
77
+ }
78
+ } catch (err) { logger.error(`Error stopping MQTT Client: ${err.message}`); }
79
+ }
80
+ private async unsubscribe() {
81
+ try {
82
+ while (this.topics.length > 0) {
83
+ let topic = this.topics.pop();
84
+ if (typeof topic !== 'undefined') {
85
+ this.client.unsubscribe(topic.topicPath, (err, packet) => {
86
+ if (err) logger.error(`Error unsubscribing from MQTT topic ${topic}`);
87
+ else {
88
+ logger.debug(`Unsubscribed from MQTT topic ${topic}`);
89
+ }
90
+ });
91
+ }
92
+ }
93
+ } catch (err) { logger.error(`Error unsubcribing to MQTT topic: ${err.message}`); }
94
+ }
95
+ protected subscribe() {
96
+ if (this.topics.length > 0) this.unsubscribe();
97
+ let root = this.rootTopic();
98
+ if (typeof this.subscriptions !== 'undefined') {
99
+ for (let i = 0; i < this.subscriptions.length; i++) {
100
+ let sub = this.subscriptions[i];
101
+ if(sub.enabled !== false) this.topics.push(new MqttTopicSubscription(root, sub));
102
+ }
103
+ }
104
+ else {
105
+ let arrTopics = [
106
+ `state/+/setState`,
107
+ `state/+/setstate`,
108
+ `state/+/toggleState`,
109
+ `state/+/togglestate`,
110
+ `state/body/setPoint`,
111
+ `state/body/setpoint`,
112
+ `state/body/heatMode`,
113
+ `state/body/heatmode`,
114
+ `state/+/setTheme`,
115
+ `state/+/settheme`,
116
+ `state/temps`,
117
+ `config/tempSensors`,
118
+ `config/chemController`,
119
+ `state/chemController`,
120
+ `config/chlorinator`,
121
+ `state/chlorinator`];
122
+ for (let i = 0; i < arrTopics.length; i++) {
123
+ this.topics.push(new MqttTopicSubscription(root, { topic: arrTopics[i] }));
124
+ }
125
+ }
126
+ for (let i = 0; i < this.topics.length; i++) {
127
+ let topic = this.topics[i];
128
+ this.client.subscribe(topic.topicPath, (err, granted) => {
129
+ if (!err) logger.debug(`MQTT subscribed to ${JSON.stringify(granted)}`);
130
+ else logger.error(`MQTT Subscribe: ${err}`);
131
+ });
132
+ }
133
+ this.client.on('message', async (topic, msg) => { try { await this.messageHandler(topic, msg) } catch (err) { logger.error(`Error processing MQTT request ${err}.`) }; })
134
+ this.subscribed = true;
135
+ }
136
+ // this will take in the MQTT Formatter options and format each token that is bound
137
+ // otherwise, it's the same as the base buildTokens fn.
138
+ // This could be combined into one fn but for now it's specific to MQTT formatting of topics
139
+ protected buildTokensWithFormatter(input: string, eventName: string, toks: any, e: InterfaceEvent, data, formatter: any): any {
140
+ toks = toks || [];
141
+ let s = input;
142
+ let regx = /(?<=@bind\=\s*).*?(?=\;)/g;
143
+ let match;
144
+ let vars = extend(true, {}, this.cfg.vars, this.context.vars, typeof e !== 'undefined' && e.vars);
145
+ let sys = sysAlias;
146
+ let state = stateAlias;
147
+ let webApp = webAppAlias;
148
+ // Map all the returns to the token list. We are being very basic
149
+ // here an the object graph is simply based upon the first object occurrence.
150
+ // We simply want to eval against that object reference.
151
+
152
+ while (match = regx.exec(s)) {
153
+ let bind = match[0];
154
+ if (typeof toks[bind] !== 'undefined') continue;
155
+ let tok: any = {};
156
+ toks[bind] = tok;
157
+ try {
158
+ // we may error out if data can't be found (eg during init)
159
+ tok.reg = new RegExp("@bind=" + this.escapeRegex(bind) + ";", "g");
160
+ tok.value = eval(bind);
161
+ if (typeof formatter !== 'undefined') {
162
+ formatter.forEach(entry => {
163
+ if (typeof entry.transform !== 'undefined') {
164
+ let transform = `('${tok.value}')${entry.transform}`;
165
+ tok.value = eval(transform);
166
+ }
167
+ else if (typeof entry === 'object') {
168
+ let rexp = new RegExp(entry.regexkey, 'g')
169
+ tok.value = tok.value.replace(rexp, entry.replace);
170
+ }
171
+ })
172
+ }
173
+ }
174
+ catch (err) {
175
+ // leave value undefined so it isn't sent to bindings
176
+ tok[bind] = null;
177
+ }
178
+ }
179
+ return toks;
180
+ }
181
+ private rootTopic = () => {
182
+ let toks = {};
183
+ let baseOpts = extend(true, { headers: {} }, this.cfg.options, this.context.options);
184
+ let topic = '';
185
+ this.buildTokensWithFormatter(baseOpts.rootTopic, undefined, toks, undefined, undefined, baseOpts.formatter);
186
+ topic = this.replaceTokens(baseOpts.rootTopic, toks);
187
+ return topic;
188
+ }
189
+ public bindEvent(evt: string, ...data: any) {
190
+ try {
191
+ if (!this.sentInitialMessages && evt === 'controller' && data[0].status.val === 1) {
192
+ state.emitAllEquipmentChanges();
193
+ this.sentInitialMessages = true;
194
+ }
195
+ // Find the binding by first looking for the specific event name.
196
+ // If that doesn't exist then look for the "*" (all events).
197
+ if (typeof this.events !== 'undefined') {
198
+ if (typeof this.client === 'undefined') this.init();
199
+ let evts = this.events.filter(elem => elem.name === evt);
200
+ // If we don't have an explicitly defined event then see if there is a default.
201
+ if (evts.length === 0) {
202
+ let e = this.events.find(elem => elem.name === '*');
203
+ evts = e ? [e] : [];
204
+ }
205
+
206
+ if (evts.length > 0) {
207
+ let toks = {};
208
+ let replacer = '';
209
+ for (let i = 0; i < evts.length; i++) {
210
+ let e = evts[i];
211
+ if (typeof e.enabled !== 'undefined' && !e.enabled) continue;
212
+ let baseOpts = extend(true, { headers: {} }, this.cfg.options, this.context.options);
213
+ let opts = extend(true, baseOpts, e.options);
214
+ // Figure out whether we need to check the filter.
215
+ if (typeof e.filter !== 'undefined') {
216
+ this.buildTokens(e.filter, evt, toks, e, data[0]);
217
+ if (eval(this.replaceTokens(e.filter, toks)) === false) continue;
218
+ }
219
+
220
+ let rootTopic = this.rootTopic();
221
+ if (typeof opts.replacer !== 'undefined') replacer = opts.replacer;
222
+ if (typeof e.topics !== 'undefined') e.topics.forEach(t => {
223
+ let topicToks = {};
224
+ if (typeof t.enabled !== 'undefined' && !t.enabled) return;
225
+ if (typeof t.filter !== 'undefined') {
226
+ this.buildTokens(t.filter, evt, topicToks, e, data[0]);
227
+ if (eval(this.replaceTokens(t.filter, topicToks)) === false) return;
228
+ }
229
+ let topicFormatter = t.formatter || opts.formatter;
230
+ let topic = '';
231
+ let message: any;
232
+ // build tokens for Topic
233
+ // we need to keep separated topic tokens because otherwise
234
+ // a value like @bind=data.name; would be eval'd the same
235
+ // across all topics
236
+ this.buildTokensWithFormatter(t.topic, evt, topicToks, e, data[0], topicFormatter);
237
+ topic = `${rootTopic}/${this.replaceTokens(t.topic, topicToks)}`;
238
+ // Filter out any topics where there may be undefined in it. We don't want any of this if that is the case.
239
+ if (topic.endsWith('/undefined') || topic.indexOf('/undefined/') !== -1 || topic.startsWith('null/') || topic.indexOf('/null') !== -1) return;
240
+ if (typeof t.processor !== 'undefined') {
241
+ if (t.ignoreProcessor) message = "err";
242
+ else {
243
+ if (typeof t._fnProcessor !== 'function') {
244
+ let fnBody = Array.isArray(t.processor) ? t.processor.join('\n') : t.processor;
245
+ try {
246
+ // Try to compile it.
247
+ t._fnProcessor = new Function('ctx', 'pub', 'sys', 'state', 'data', fnBody) as (ctx: any, pub: MQTTPublishTopic, sys: PoolSystem, state: State, data: any) => any;
248
+ } catch (err) { logger.error(`Error compiling subscription processor: ${err} -- ${fnBody}`); t.ignoreProcessor = true; }
249
+ }
250
+ if (typeof t._fnProcessor === 'function') {
251
+ let ctx = { util: utils }
252
+ try {
253
+ message = t._fnProcessor(ctx, t, sys, state, data[0]).toString();
254
+ } catch (err) { logger.error(`Error publishing MQTT data for topic ${t.topic}: ${err.message}`); message = "err"; }
255
+ }
256
+ }
257
+ }
258
+ else {
259
+ this.buildTokens(t.message, evt, topicToks, e, data[0]);
260
+ message = this.tokensReplacer(t.message, evt, topicToks, e, data[0]);
261
+ }
262
+
263
+ let publishOptions: IClientPublishOptions = { retain: typeof baseOpts.retain !== 'undefined' ? baseOpts.retain : true, qos: typeof baseOpts.qos !== 'undefined' ? baseOpts.qos : 2 };
264
+ let changesOnly = typeof baseOpts.changesOnly !== 'undefined' ? baseOpts.changesOnly : true;
265
+ if (typeof e.options !== 'undefined') {
266
+ if (typeof e.options.retain !== 'undefined') publishOptions.retain = e.options.retain;
267
+ if (typeof e.options.qos !== 'undefined') publishOptions.retain = e.options.qos;
268
+ if (typeof e.options.changesOnly !== 'undefined') changesOnly = e.options.changesOnly;
269
+ }
270
+ if (typeof t.options !== 'undefined') {
271
+ if (typeof t.options.retain !== 'undefined') publishOptions.retain = t.options.retain;
272
+ if (typeof t.options.qos !== 'undefined') publishOptions.qos = t.options.qos;
273
+ if (typeof t.options.changeOnly !== 'undefined') changesOnly = t.options.changesOnly;
274
+ }
275
+ if (changesOnly) {
276
+ if (typeof t.lastSent === 'undefined') t.lastSent = [];
277
+ let lm = t.lastSent.find(elem => elem.topic === topic);
278
+ if (typeof lm === 'undefined' || lm.message !== message) {
279
+ setImmediate(() => { this.client.publish(topic, message, publishOptions); });
280
+ logger.silly(`MQTT send:\ntopic: ${topic}\nmessage: ${message}\nopts:${JSON.stringify(publishOptions)}`);
281
+ }
282
+ if (typeof lm === 'undefined') t.lastSent.push({ topic: topic, message: message });
283
+ else lm.message = message;
284
+
285
+ }
286
+ else {
287
+ logger.silly(`MQTT send:\ntopic: ${topic}\nmessage: ${message}\nopts:${JSON.stringify(publishOptions)}`);
288
+ setImmediate(() => { this.client.publish(topic, message, publishOptions); });
289
+ if (typeof t.lastSent !== 'undefined') t.lastSent = undefined;
290
+ }
291
+
292
+ })
293
+ }
294
+ }
295
+ }
296
+ }
297
+ catch (err) {
298
+ logger.error(err);
299
+ }
300
+ }
301
+ private messageHandler = async (topic, message) => {
302
+ try {
303
+ let msg = message.toString();
304
+ if (msg[0] === '{') msg = JSON.parse(msg);
305
+
306
+ let sub: MqttTopicSubscription = this.topics.find(elem => topic === elem.topicPath);
307
+ if (typeof sub !== 'undefined') {
308
+ logger.debug(`Topic not found ${topic}`)
309
+ // Alright so now lets process our results.
310
+ if (typeof sub.processor === 'function') {
311
+ sub.executeProcessor(msg);
312
+ return;
313
+ }
314
+ }
315
+ const topics = topic.split('/');
316
+ logger.debug(`MQTT: Inbound ${topic}: ${message.toString()}`);
317
+ if (topic.startsWith(this.rootTopic() + '/') && typeof msg === 'object') {
318
+ // RKS: Not sure why there is no processing of state vs config here. Right now the topics are unique
319
+ // between them so it doesn't matter but it will become an issue.
320
+ switch (topics[topics.length - 1].toLowerCase()) {
321
+ case 'setstate': {
322
+ let id = parseInt(msg.id, 10);
323
+ if (typeof id !== 'undefined' && isNaN(id)) {
324
+ logger.error(`Inbound MQTT ${topics} has an invalid id (${id}) in the message (${msg}).`)
325
+ };
326
+ let isOn = utils.makeBool(msg.isOn);
327
+ switch (topics[topics.length - 2].toLowerCase()) {
328
+ case 'circuits':
329
+ case 'circuit': {
330
+ try {
331
+ if (msg.isOn !== 'undefined') await sys.board.circuits.setCircuitStateAsync(id, isOn);
332
+ }
333
+ catch (err) { logger.error(err); }
334
+ break;
335
+ }
336
+ case 'features':
337
+ case 'feature': {
338
+ try {
339
+ if (msg.isOn !== 'undefined') await sys.board.features.setFeatureStateAsync(id, isOn);
340
+ }
341
+ catch (err) { logger.error(err); }
342
+ break;
343
+ }
344
+ case 'lightgroups':
345
+ case 'lightgroup': {
346
+ try {
347
+ await sys.board.circuits.setLightGroupStateAsync(id, isOn);
348
+ }
349
+ catch (err) { logger.error(err); }
350
+ break;
351
+ }
352
+ case 'circuitgroups':
353
+ case 'circuitgroup': {
354
+ try {
355
+ await sys.board.circuits.setCircuitGroupStateAsync(id, isOn);
356
+ }
357
+ catch (err) { logger.error(err); }
358
+ break;
359
+ }
360
+ default:
361
+ logger.warn(`MQTT: Inbound topic ${topics[topics.length - 1]} not matched to event ${topics[topics.length - 2].toLowerCase()}. Message ${msg} `)
362
+ }
363
+ break;
364
+ }
365
+ case 'togglestate':
366
+ {
367
+ let id = parseInt(msg.id, 10);
368
+ if (typeof id !== 'undefined' && isNaN(id)) {
369
+ logger.error(`Inbound MQTT ${topics} has an invalid id (${id}) in the message (${msg}).`)
370
+ };
371
+ switch (topics[topics.length - 2].toLowerCase()) {
372
+ case 'circuits':
373
+ case 'circuit':
374
+ try {
375
+ await sys.board.circuits.toggleCircuitStateAsync(id);
376
+ }
377
+ catch (err) { logger.error(err); }
378
+ break;
379
+ case 'features':
380
+ case 'feature':
381
+ try {
382
+ await sys.board.features.toggleFeatureStateAsync(id);
383
+ }
384
+ catch (err) { logger.error(err); }
385
+ break;
386
+ default:
387
+ logger.warn(`MQTT: Inbound topic ${topics[topics.length - 1]} not matched to event ${topics[topics.length - 2].toLowerCase()}. Message ${msg} `)
388
+ }
389
+ break;
390
+ }
391
+ case 'setpoint':
392
+ try {
393
+ let body = sys.bodies.findByObject(msg);
394
+ if (topics[topics.length - 2].toLowerCase() === 'body') {
395
+ if (typeof body === 'undefined') {
396
+ logger.error(new ServiceParameterError(`Cannot set body setPoint. You must supply a valid id, circuit, name, or type for the body`, 'body', 'id', msg.id));
397
+ return;
398
+ }
399
+ if (typeof msg.setPoint !== 'undefined' || typeof msg.heatSetpoint !== 'undefined') {
400
+ let setPoint = parseInt(msg.setPoint, 10) || parseInt(msg.heatSetpoint, 10);
401
+ if (!isNaN(setPoint)) {
402
+ await sys.board.bodies.setHeatSetpointAsync(body, setPoint);
403
+ }
404
+ }
405
+ if (typeof msg.coolSetpoint !== 'undefined') {
406
+ let setPoint = parseInt(msg.coolSetpoint, 10);
407
+ if (!isNaN(setPoint)) {
408
+ await sys.board.bodies.setCoolSetpointAsync(body, setPoint);
409
+ }
410
+ }
411
+ }
412
+ }
413
+ catch (err) { logger.error(err); }
414
+ break;
415
+ case 'heatmode':
416
+ try {
417
+ if (topics[topics.length - 2].toLowerCase() !== 'body') return;
418
+ // Map the mode that was passed in. This should accept the text based name or the ordinal id value.
419
+ let mode = parseInt(msg.mode, 10);
420
+ let val;
421
+ if (isNaN(mode)) mode = parseInt(msg.heatMode, 10);
422
+ if (!isNaN(mode)) val = sys.board.valueMaps.heatModes.transform(mode);
423
+ else val = sys.board.valueMaps.heatModes.transformByName(msg.mode || msg.heatMode);
424
+ if (typeof val.val === 'undefined') {
425
+ logger.error(new ServiceParameterError(`Invalid value for heatMode: ${msg.mode}`, 'body', 'heatMode', mode));
426
+ return;
427
+ }
428
+ mode = val.val;
429
+ let body = sys.bodies.findByObject(msg);
430
+ if (typeof body === 'undefined') {
431
+ logger.error(new ServiceParameterError(`Cannot set body heatMode. You must supply a valid id, circuit, name, or type for the body`, 'body', 'id', msg.id));
432
+ return;
433
+ }
434
+ let tbody = await sys.board.bodies.setHeatModeAsync(body, mode);
435
+ }
436
+ catch (err) { logger.error(err); }
437
+ break;
438
+ case 'chlorinator':
439
+ try {
440
+ let schlor = await sys.board.chlorinator.setChlorAsync(msg);
441
+ }
442
+ catch (err) { logger.error(err); }
443
+ break;
444
+ case 'chemcontroller':
445
+ try {
446
+ await sys.board.chemControllers.setChemControllerAsync(msg);
447
+ }
448
+ catch (err) { logger.error(err); }
449
+ break;
450
+ case 'settheme':
451
+ try {
452
+ let theme = await state.circuits.setLightThemeAsync(parseInt(msg.id, 10), sys.board.valueMaps.lightThemes.encode(msg.theme));
453
+ }
454
+ catch (err) { logger.error(err); }
455
+ break;
456
+ case 'temp':
457
+ case 'temps':
458
+ try {
459
+ await sys.board.system.setTempsAsync(msg);
460
+ }
461
+ catch (err) { logger.error(err); }
462
+ break;
463
+ case 'tempsensor':
464
+ case 'tempsensors':
465
+ try {
466
+ await sys.board.system.setTempSensorsAsync(msg);
467
+ }
468
+ catch (err) { logger.error(err); }
469
+ break;
470
+ default:
471
+ logger.silly(`MQTT: Inbound MQTT topic not matched: ${topic}: ${message.toString()}`)
472
+ break;
473
+ }
474
+ }
475
+ }
476
+ catch (err) {
477
+ logger.error(`Error processing MQTT request ${topic}: ${err}. ${message}`)
478
+ }
479
+ }
480
+ }
481
+ class MqttInterfaceEvent extends InterfaceEvent {
482
+ public topics: MQTTPublishTopic[]
483
+ }
484
+ export class MQTTPublishTopic {
485
+ topic: string;
486
+ message: string;
487
+ description: string;
488
+ formatter: any[];
489
+ qos: string;
490
+ retain: boolean;
491
+ enabled?: boolean;
492
+ filter?: string;
493
+ lastSent: MQTTMessage[];
494
+ options: any;
495
+ processor?: string[];
496
+ ignoreProcessor: boolean = false;
497
+ _fnProcessor: (ctx: any, pub: MQTTPublishTopic, sys: PoolSystem, state: State, data: any) => any
498
+ }
499
+ class MQTTMessage {
500
+ topic: string;
501
+ message: string;
502
+ }
503
+
504
+ class MqttSubscriptions {
505
+ public subscriptions: IMQTTSubscription[]
506
+ }
507
+ class MqttTopicSubscription {
508
+ root: string;
509
+ topic: string;
510
+ enabled: boolean;
511
+ processor: (ctx: any, sub: MqttTopicSubscription, sys: PoolSystem, state: State, value: any) => void;
512
+ constructor(root: string, sub: any) {
513
+ this.root = sub.root || root;
514
+ this.topic = sub.topic;
515
+ if (typeof sub.processor !== 'undefined') {
516
+ let fnBody = Array.isArray(sub.processor) ? sub.processor.join('\n') : sub.processor;
517
+ try {
518
+ this.processor = new Function('ctx', 'sub', 'sys', 'state', 'value', fnBody) as (ctx: any, sub: MqttTopicSubscription, sys: PoolSystem, state: State, value: any) => void;
519
+ } catch (err) { logger.error(`Error compiling subscription processor: ${err} -- ${fnBody}`); }
520
+ }
521
+ }
522
+ public get topicPath(): string { return `${this.root}/${this.topic}` };
523
+ public executeProcessor(value: any) {
524
+ let ctx = { util:utils }
525
+ this.processor(ctx, this, sys, state, value);
526
+ state.emitEquipmentChanges();
527
+ }
528
+
529
+ }
530
+ export interface IMQTTSubscription {
531
+ topic: string,
532
+ description: string,
533
+ processor?: string,
534
+ enabled?: boolean
535
+ }