nodejs-poolcontroller 8.3.0 → 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 (105) hide show
  1. package/.eslintrc.json +36 -36
  2. package/.github/ISSUE_TEMPLATE/1-bug-report.yml +84 -84
  3. package/.github/ISSUE_TEMPLATE/2-docs.md +12 -12
  4. package/.github/ISSUE_TEMPLATE/3-proposal.md +28 -28
  5. package/.github/ISSUE_TEMPLATE/config.yml +8 -8
  6. package/.github/copilot-instructions.md +63 -63
  7. package/.github/workflows/ghcr-publish.yml +67 -67
  8. package/AGENTS.md +597 -0
  9. package/CONTRIBUTING.md +74 -74
  10. package/Changelog +292 -284
  11. package/Dockerfile +62 -62
  12. package/Gruntfile.js +40 -40
  13. package/LICENSE +661 -661
  14. package/README.md +318 -309
  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 +0 -0
  23. package/config/VersionCheck.ts +0 -0
  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 -3701
  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 -1944
  36. package/controller/boards/SunTouchBoard.ts +400 -400
  37. package/controller/boards/SystemBoard.ts +5268 -5268
  38. package/controller/comms/Comms.ts +1272 -1255
  39. package/controller/comms/ScreenLogic.ts +1665 -1665
  40. package/controller/comms/messages/Messages.ts +1433 -1406
  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 +410 -410
  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 +1193 -1193
  77. package/controller/nixie/schedules/Schedule.ts +401 -401
  78. package/controller/nixie/valves/Valve.ts +170 -170
  79. package/defaultConfig.json +352 -352
  80. package/docker-compose.yml +31 -31
  81. package/logger/DataLogger.ts +448 -448
  82. package/logger/Logger.ts +448 -436
  83. package/package.json +58 -58
  84. package/sendSocket.js +32 -32
  85. package/tsconfig.json +25 -25
  86. package/types/express-multer.d.ts +32 -32
  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
@@ -1,695 +1,695 @@
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, InterfaceContext, IInterfaceEvent } 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 { Timestamp, Utils, 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
- public 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 = () => { (async () => { await this.initAsync(); })(); }
44
- public async initAsync() {
45
- try {
46
- if (this.client) await this.stopAsync();
47
- logger.info(`Initializing MQTT client ${this.cfg.name}`);
48
- let baseOpts = extend(true, { headers: {} }, this.cfg.options, this.context.options);
49
- if ((typeof baseOpts.hostname === 'undefined' || !baseOpts.hostname) && (typeof baseOpts.host === 'undefined' || !baseOpts.host || baseOpts.host === '*')) {
50
- logger.warn(`Interface: ${this.cfg.name} has not resolved to a valid host.`);
51
- return;
52
- }
53
- const url = `${baseOpts.protocol || 'mqtt://'}${baseOpts.host}:${baseOpts.port || 1883}`;
54
- let toks = {};
55
- const opts = {
56
- clientId: this.tokensReplacer(baseOpts.clientId, undefined, toks, { vars: {} } as any, {}),
57
- username: baseOpts.username,
58
- password: baseOpts.password,
59
- rejectUnauthorized: !baseOpts.selfSignedCertificate,
60
- url
61
- }
62
- this.setWillOptions(opts);
63
- this.client = connect(url, opts);
64
- this.client.on('connect', async () => {
65
- try {
66
- logger.info(`MQTT connected to ${url}`);
67
- await this.subscribe();
68
- // make sure status is up to date immediately
69
- // especially in the case of a re-connect
70
- this.bindEvent("controller", state.controllerState);
71
- } catch (err) { logger.error(`Error connecting to MQTT Broker ${this.cfg.name} ${err.message}`); }
72
- });
73
- this.client.on('reconnect', () => {
74
- try {
75
- logger.info(`Re-connecting to MQTT broker ${this.cfg.name}`);
76
- } catch (err) { logger.error(`Error reconnecting to MQTT Brokder ${this.cfg.name} ${err.message}`); }
77
-
78
- });
79
- this.client.on('error', (error) => {
80
- logger.error(`MQTT error ${error}`)
81
- this.clearWillState();
82
- });
83
- } catch (err) { logger.error(`Error initializing MQTT client ${this.cfg.name}: ${err}`); }
84
- }
85
- public async stopAsync() {
86
- try {
87
- if (typeof this.client !== 'undefined') {
88
- await this.unsubscribe();
89
- await new Promise<boolean>((resolve, reject) => {
90
- this.client.end(true, { reasonCode: 0, reasonString: `Shutting down MQTT Client` }, () => {
91
- resolve(true);
92
- logger.info(`Successfully shut down MQTT Client`);
93
- });
94
- });
95
- if (this.client) this.client.removeAllListeners();
96
- this.client = null;
97
- }
98
- } catch (err) { logger.error(`Error stopping MQTT Client: ${err.message}`); }
99
- }
100
- public async reload(data) {
101
- try {
102
- await this.unsubscribe();
103
- this.context = Object.assign<InterfaceContext, any>(new InterfaceContext(), data.context);
104
- this.events = Object.assign<MqttInterfaceEvent[], any>([], data.events);
105
- this.subscriptions = Object.assign<MqttTopicSubscription[], any>([], data.subscriptions);
106
- await this.subscribe();
107
- } catch (err) { logger.error(`Error reloading MQTT bindings`); }
108
- }
109
- private async unsubscribe() {
110
- try {
111
- this.client.off('message', this.messageHandler);
112
- while (this.topics.length > 0) {
113
- let topic = this.topics.pop();
114
- if (typeof topic !== 'undefined') {
115
- await new Promise<boolean>((resolve, reject) => {
116
- this.client.unsubscribe(topic.topicPath, (err, packet) => {
117
- if (err) {
118
- logger.error(`Error unsubscribing from MQTT topic ${topic.topicPath}: ${err}`);
119
- resolve(false);
120
- }
121
- else {
122
- logger.debug(`Unsubscribed from MQTT topic ${topic.topicPath}`);
123
- resolve(true);
124
- }
125
- });
126
- });
127
- }
128
- }
129
- this.subscribed = false;
130
- } catch (err) { logger.error(`Error unsubcribing to MQTT topic: ${err.message}`); }
131
- }
132
- protected async subscribe() {
133
- if (this.topics.length > 0) await this.unsubscribe();
134
- let root = this.rootTopic();
135
- if (typeof this.subscriptions !== 'undefined') {
136
- for (let i = 0; i < this.subscriptions.length; i++) {
137
- let sub = this.subscriptions[i];
138
- if(sub.enabled !== false) this.topics.push(new MqttTopicSubscription(root, sub));
139
- }
140
- }
141
- else if (typeof root !== 'undefined') {
142
- let arrTopics = [
143
- `state/+/setState`,
144
- `state/+/setstate`,
145
- `state/+/toggleState`,
146
- `state/+/togglestate`,
147
- `state/body/setPoint`,
148
- `state/body/setpoint`,
149
- `state/body/heatSetpoint`,
150
- `state/body/coolSetpoint`,
151
- `state/body/heatMode`,
152
- `state/body/heatmode`,
153
- `state/+/setTheme`,
154
- `state/+/settheme`,
155
- `state/temps`,
156
- `config/tempSensors`,
157
- `config/chemController`,
158
- `state/chemController`,
159
- `config/chlorinator`,
160
- `state/chlorinator`];
161
- for (let i = 0; i < arrTopics.length; i++) {
162
- this.topics.push(new MqttTopicSubscription(root, { topic: arrTopics[i] }));
163
- }
164
- }
165
- for (let i = 0; i < this.topics.length; i++) {
166
- let topic = this.topics[i];
167
- this.client.subscribe(topic.topicPath, (err, granted) => {
168
- if (!err) logger.verbose(`MQTT subscribed to ${JSON.stringify(granted)}`);
169
- else logger.error(`MQTT Subscribe: ${err}`);
170
- });
171
- }
172
- this.client.on('message', this.messageHandler);
173
- this.subscribed = true;
174
- }
175
- // this will take in the MQTT Formatter options and format each token that is bound
176
- // otherwise, it's the same as the base buildTokens fn.
177
- // This could be combined into one fn but for now it's specific to MQTT formatting of topics
178
- protected buildTokensWithFormatter(input: string, eventName: string, toks: any, e: InterfaceEvent, data, formatter: any): any {
179
- toks = toks || [];
180
- let s = input;
181
- let regx = /(?<=@bind\=\s*).*?(?=\;)/g;
182
- let match;
183
- let sys = sysAlias;
184
- let state = stateAlias;
185
- let webApp = webAppAlias;
186
- let vars = this.bindVarTokens(e, eventName, data);
187
- // Map all the returns to the token list. We are being very basic
188
- // here an the object graph is simply based upon the first object occurrence.
189
- // We simply want to eval against that object reference.
190
-
191
- while (match = regx.exec(s)) {
192
- let bind = match[0];
193
- if (typeof toks[bind] !== 'undefined') continue;
194
- let tok: any = {};
195
- toks[bind] = tok;
196
- try {
197
- // we may error out if data can't be found (eg during init)
198
- tok.reg = new RegExp("@bind=" + this.escapeRegex(bind) + ";", "g");
199
- tok.value = eval(bind);
200
- if (typeof formatter !== 'undefined') {
201
- formatter.forEach(entry => {
202
- if (typeof entry.transform !== 'undefined') {
203
- let transform = `('${tok.value}')${entry.transform}`;
204
- tok.value = eval(transform);
205
- }
206
- else if (typeof entry === 'object') {
207
- let rexp = new RegExp(entry.regexkey, 'g')
208
- tok.value = tok.value.replace(rexp, entry.replace);
209
- }
210
- })
211
- }
212
- }
213
- catch (err) {
214
- // leave value undefined so it isn't sent to bindings
215
- tok[bind] = null;
216
- }
217
- }
218
- return toks;
219
- }
220
- private setWillOptions = (connectOpts) => {
221
- const baseOpts = extend(true, { headers: {} }, this.cfg.options, this.context.options);
222
-
223
- if (baseOpts.willTopic !== 'undefined') {
224
- const rootTopic = this.rootTopic();
225
- const topic = `${rootTopic}/${baseOpts.willTopic}`;
226
- const publishOptions = {
227
- retain: typeof baseOpts.retain !== 'undefined' ? baseOpts.retain : true,
228
- qos: typeof baseOpts.qos !== 'undefined' ? baseOpts.qos : 2
229
- };
230
-
231
- connectOpts.will = {
232
- topic: topic,
233
- payload: baseOpts.willPayload,
234
- retain: publishOptions.retain,
235
- qos: publishOptions.qos
236
- };
237
- }
238
- }
239
- private clearWillState() {
240
- if (typeof this.client.options.will === 'undefined') return;
241
- let willTopic = this.client.options.will.topic;
242
- let willPayload = this.client.options.will.payload;
243
-
244
- if (typeof this.events !== 'undefined') this.events.forEach(evt => {
245
- if (typeof evt.topics !== 'undefined') evt.topics.forEach(t => {
246
- if (typeof t.lastSent !== 'undefined') {
247
- let lm = t.lastSent.find(elem => elem.topic === willTopic);
248
- if (typeof lm !== 'undefined') {
249
- lm.message = willPayload.toString();
250
- }
251
- }
252
- });
253
- });
254
- }
255
- public rootTopic = () => {
256
- let toks = {};
257
- let baseOpts = extend(true, { headers: {} }, this.cfg.options, this.context.options);
258
- let topic = '';
259
- this.buildTokensWithFormatter(baseOpts.rootTopic, undefined, toks, undefined, undefined, baseOpts.formatter);
260
- topic = this.replaceTokens(baseOpts.rootTopic, toks);
261
- return topic;
262
- }
263
- public bindEvent(evt: string, ...data: any) {
264
- try {
265
- if (!this.sentInitialMessages && evt === 'controller' && data[0].status.val === 1) {
266
- // Emitting all the equipment messages
267
- state.emitAllEquipmentChanges();
268
- this.sentInitialMessages = true;
269
- }
270
- // Find the binding by first looking for the specific event name.
271
- // If that doesn't exist then look for the "*" (all events).
272
- if (typeof this.events !== 'undefined') {
273
- if (typeof this.client === 'undefined') this.init();
274
- let evts = this.events.filter(elem => elem.name === evt);
275
- // If we don't have an explicitly defined event then see if there is a default.
276
- if (evts.length === 0) {
277
- let e = this.events.find(elem => elem.name === '*');
278
- evts = e ? [e] : [];
279
- }
280
-
281
- if (evts.length > 0) {
282
- let toks = {};
283
- let replacer = '';
284
- for (let i = 0; i < evts.length; i++) {
285
- let e = evts[i];
286
- if (typeof e.enabled !== 'undefined' && !e.enabled) continue;
287
- let baseOpts = extend(true, { headers: {} }, this.cfg.options, this.context.options);
288
- let opts = extend(true, baseOpts, e.options);
289
- // Figure out whether we need to check the filter.
290
- if (typeof e.filter !== 'undefined') {
291
- this.buildTokens(e.filter, evt, toks, e, data[0]);
292
- if (eval(this.replaceTokens(e.filter, toks)) === false) continue;
293
- }
294
-
295
- let rootTopic = this.rootTopic();
296
- if (typeof opts.replacer !== 'undefined') replacer = opts.replacer;
297
- if (typeof e.topics !== 'undefined') e.topics.forEach(t => {
298
- let topicToks = {};
299
- if (typeof t.enabled !== 'undefined' && !t.enabled) return;
300
- if (typeof t.filter !== 'undefined') {
301
- this.buildTokens(t.filter, evt, topicToks, e, data[0]);
302
- if (eval(this.replaceTokens(t.filter, topicToks)) === false) return;
303
- }
304
- let topicFormatter = t.formatter || opts.formatter;
305
- let topic = '';
306
- let message: any;
307
- // build tokens for Topic
308
- // we need to keep separated topic tokens because otherwise
309
- // a value like @bind=data.name; would be eval'd the same
310
- // across all topics
311
- this.buildTokensWithFormatter(t.topic, evt, topicToks, e, data[0], topicFormatter);
312
- topic = this.replaceTokens(t.topic, topicToks);
313
- if (t.useRootTopic !== false) topic = `${rootTopic}/${topic}`;
314
- // Filter out any topics where there may be undefined in it. We don't want any of this if that is the case.
315
- if (topic.endsWith('/undefined') || topic.indexOf('/undefined/') !== -1 || topic.startsWith('null/') || topic.indexOf('/null') !== -1) return;
316
- let publishOptions: IClientPublishOptions = { retain: typeof baseOpts.retain !== 'undefined' ? baseOpts.retain : true, qos: typeof baseOpts.qos !== 'undefined' ? baseOpts.qos : 2 };
317
- let changesOnly = typeof baseOpts.changesOnly !== 'undefined' ? baseOpts.changesOnly : true;
318
- if (typeof e.options !== 'undefined') {
319
- if (typeof e.options.retain !== 'undefined') publishOptions.retain = e.options.retain;
320
- if (typeof e.options.qos !== 'undefined') publishOptions.retain = e.options.qos;
321
- if (typeof e.options.changesOnly !== 'undefined') changesOnly = e.options.changesOnly;
322
- }
323
- if (typeof t.options !== 'undefined') {
324
- if (typeof t.options.retain !== 'undefined') publishOptions.retain = t.options.retain;
325
- if (typeof t.options.qos !== 'undefined') publishOptions.qos = t.options.qos;
326
- if (typeof t.options.changeOnly !== 'undefined') changesOnly = t.options.changesOnly;
327
- }
328
-
329
- if (typeof t.processor !== 'undefined') {
330
- if (t.ignoreProcessor) message = "err";
331
- else {
332
- if (typeof t._fnProcessor !== 'function') {
333
- let fnBody = Array.isArray(t.processor) ? t.processor.join('\n') : t.processor;
334
- try {
335
- // Try to compile it.
336
- t._fnProcessor = new Function('ctx', 'pub', 'sys', 'state', 'data', fnBody) as (ctx: any, pub: MQTTPublishTopic, sys: PoolSystem, state: State, data: any) => any;
337
- } catch (err) { logger.error(`Error compiling subscription processor: ${err} -- ${fnBody}`); t.ignoreProcessor = true; }
338
- }
339
- if (typeof t._fnProcessor === 'function') {
340
- let vars = this.bindVarTokens(e, evt, data);
341
- let ctx = { util: utils, rootTopic: rootTopic, topic: topic, opts: opts, vars: vars }
342
- try {
343
- message = t._fnProcessor(ctx, t, sys, state, data[0]).toString();
344
- topic = ctx.topic;
345
- } catch (err) { logger.error(`Error publishing MQTT data for topic ${t.topic}: ${err.message}`); message = "err"; }
346
- }
347
- }
348
- }
349
- else {
350
- this.buildTokens(t.message, evt, topicToks, e, data[0]);
351
- message = this.tokensReplacer(t.message, evt, topicToks, e, data[0]);
352
- }
353
-
354
- if (changesOnly) {
355
- if (typeof t.lastSent === 'undefined') t.lastSent = [];
356
- let lm = t.lastSent.find(elem => elem.topic === topic);
357
- if (typeof lm === 'undefined' || lm.message !== message) {
358
- setImmediate(() => { this.client.publish(topic, message, publishOptions); });
359
- logger.silly(`MQTT send:\ntopic: ${topic}\nmessage: ${message}\nopts:${JSON.stringify(publishOptions)}`);
360
- }
361
- if (typeof lm === 'undefined') t.lastSent.push({ topic: topic, message: message });
362
- else lm.message = message;
363
-
364
- }
365
- else {
366
- logger.silly(`MQTT send:\ntopic: ${topic}\nmessage: ${message}\nopts:${JSON.stringify(publishOptions)}`);
367
- setImmediate(() => { this.client.publish(topic, message, publishOptions); });
368
- if (typeof t.lastSent !== 'undefined') t.lastSent = undefined;
369
- }
370
-
371
- })
372
- }
373
- }
374
- }
375
- }
376
- catch (err) {
377
- logger.error(`Error binding MQTT event ${evt}: ${err.message}`);
378
- }
379
- }
380
- // This needed to be refactored so we could extract it from an anonymous function. We want to be able to unbind
381
- // from it
382
- private messageHandler = (topic, message) => { (async () => { await this.processMessage(topic, message); })(); }
383
- private processMessage = async (topic, message) => {
384
- try {
385
- if (!state.isInitialized){
386
- logger.info(`MQTT: **TOPIC IGNORED, SYSTEM NOT READY** Inbound ${topic}: ${message.toString()}`);
387
- return;
388
- }
389
- let msg = message.toString();
390
- if (msg[0] === '{') msg = JSON.parse(msg);
391
-
392
- let sub: MqttTopicSubscription = this.topics.find(elem => topic === elem.topicPath);
393
- if (typeof sub !== 'undefined') {
394
- logger.debug(`MQTT: Inbound ${topic} ${message.toString()}`);
395
- // Alright so now lets process our results.
396
- if (typeof sub.fnProcessor === 'function') {
397
- sub.executeProcessor(this, msg);
398
- return;
399
- }
400
- }
401
- const topics = topic.split('/');
402
- if (topic.startsWith(this.rootTopic() + '/') && typeof msg === 'object') {
403
- // RKS: Not sure why there is no processing of state vs config here. Right now the topics are unique
404
- // between them so it doesn't matter but it will become an issue.
405
- switch (topics[topics.length - 1].toLowerCase()) {
406
- case 'setstate': {
407
- let id = parseInt(msg.id, 10);
408
- if (typeof id !== 'undefined' && isNaN(id)) {
409
- logger.error(`Inbound MQTT ${topics} has an invalid id (${id}) in the message (${msg}).`)
410
- };
411
- let isOn = typeof msg.isOn !== 'undefined' ? utils.makeBool(msg.isOn) : typeof msg.state !== 'undefined' ? utils.makeBool(msg.state) : undefined;
412
- switch (topics[topics.length - 2].toLowerCase()) {
413
- case 'circuits':
414
- case 'circuit': {
415
- try {
416
- if(typeof isOn !== 'undefined') await sys.board.circuits.setCircuitStateAsync(id, isOn);
417
- }
418
- catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
419
- break;
420
- }
421
- case 'features':
422
- case 'feature': {
423
- try {
424
- if (typeof isOn !== 'undefined') await sys.board.features.setFeatureStateAsync(id, isOn);
425
- }
426
- catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
427
- break;
428
- }
429
- case 'lightgroups':
430
- case 'lightgroup': {
431
- try {
432
- if (typeof isOn !== 'undefined') await sys.board.circuits.setLightGroupStateAsync(id, isOn);
433
- }
434
- catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
435
- break;
436
- }
437
- case 'circuitgroups':
438
- case 'circuitgroup': {
439
- try {
440
- if (typeof isOn !== 'undefined') await sys.board.circuits.setCircuitGroupStateAsync(id, isOn);
441
- }
442
- catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
443
- break;
444
- }
445
- default:
446
- logger.warn(`MQTT: Inbound topic ${topics[topics.length - 1]} not matched to event ${topics[topics.length - 2].toLowerCase()}. Message ${msg} `)
447
- }
448
- break;
449
- }
450
- case 'togglestate':
451
- {
452
- let id = parseInt(msg.id, 10);
453
- if (typeof id !== 'undefined' && isNaN(id)) {
454
- logger.error(`Inbound MQTT ${topics} has an invalid id (${id}) in the message (${msg}).`)
455
- };
456
- switch (topics[topics.length - 2].toLowerCase()) {
457
- case 'circuits':
458
- case 'circuit':
459
- try {
460
- await sys.board.circuits.toggleCircuitStateAsync(id);
461
- }
462
- catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
463
- break;
464
- case 'features':
465
- case 'feature':
466
- try {
467
- await sys.board.features.toggleFeatureStateAsync(id);
468
- }
469
- catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
470
- break;
471
- default:
472
- logger.warn(`MQTT: Inbound topic ${topics[topics.length - 1]} not matched to event ${topics[topics.length - 2].toLowerCase()}. Message ${msg} `)
473
- }
474
- break;
475
- }
476
- case 'heatsetpoint':
477
- try {
478
- let body = sys.bodies.findByObject(msg);
479
- if (topics[topics.length - 2].toLowerCase() === 'body') {
480
- if (typeof body === 'undefined') {
481
- logger.error(new ServiceParameterError(`Cannot set body heatSetpoint. You must supply a valid id, circuit, name, or type for the body`, 'body', 'id', msg.id));
482
- return;
483
- }
484
- if (typeof msg.setPoint !== 'undefined' || typeof msg.heatSetpoint !== 'undefined') {
485
- let setPoint = parseInt(msg.setPoint, 10) || parseInt(msg.heatSetpoint, 10);
486
- if (!isNaN(setPoint)) {
487
- await sys.board.bodies.setHeatSetpointAsync(body, setPoint);
488
- }
489
- }
490
- }
491
- }
492
- catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
493
- break;
494
- case 'coolsetpoint':
495
- try {
496
- let body = sys.bodies.findByObject(msg);
497
- if (topics[topics.length - 2].toLowerCase() === 'body') {
498
- if (typeof body === 'undefined') {
499
- logger.error(new ServiceParameterError(`Cannot set body coolSetpoint. You must supply a valid id, circuit, name, or type for the body`, 'body', 'id', msg.id));
500
- return;
501
- }
502
- if (typeof msg.setPoint !== 'undefined' || typeof msg.coolSetpoint !== 'undefined') {
503
- let setPoint = parseInt(msg.coolSetpoint, 10) || parseInt(msg.coolSetpoint, 10);
504
- if (!isNaN(setPoint)) {
505
- await sys.board.bodies.setCoolSetpointAsync(body, setPoint);
506
- }
507
- }
508
- }
509
- } catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
510
- break;
511
- case 'setpoint':
512
- try {
513
- let body = sys.bodies.findByObject(msg);
514
- if (topics[topics.length - 2].toLowerCase() === 'body') {
515
- if (typeof body === 'undefined') {
516
- 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));
517
- return;
518
- }
519
- if (typeof msg.setPoint !== 'undefined' || typeof msg.heatSetpoint !== 'undefined') {
520
- let setPoint = parseInt(msg.setPoint, 10) || parseInt(msg.heatSetpoint, 10);
521
- if (!isNaN(setPoint)) {
522
- await sys.board.bodies.setHeatSetpointAsync(body, setPoint);
523
- }
524
- }
525
- if (typeof msg.coolSetpoint !== 'undefined') {
526
- let setPoint = parseInt(msg.coolSetpoint, 10);
527
- if (!isNaN(setPoint)) {
528
- await sys.board.bodies.setCoolSetpointAsync(body, setPoint);
529
- }
530
- }
531
- }
532
- }
533
- catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
534
- break;
535
- case 'heatmode':
536
- try {
537
- if (topics[topics.length - 2].toLowerCase() !== 'body') return;
538
- // Map the mode that was passed in. This should accept the text based name or the ordinal id value.
539
- let mode = parseInt(msg.mode, 10);
540
- let val;
541
- if (isNaN(mode)) mode = parseInt(msg.heatMode, 10);
542
- if (!isNaN(mode)) val = sys.board.valueMaps.heatModes.transform(mode);
543
- else val = sys.board.valueMaps.heatModes.transformByName(msg.mode || msg.heatMode);
544
- if (typeof val.val === 'undefined') {
545
- logger.error(new ServiceParameterError(`Invalid value for heatMode: ${msg.mode}`, 'body', 'heatMode', mode));
546
- return;
547
- }
548
- mode = val.val;
549
- let body = sys.bodies.findByObject(msg);
550
- if (typeof body === 'undefined') {
551
- 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));
552
- return;
553
- }
554
- let tbody = await sys.board.bodies.setHeatModeAsync(body, mode);
555
- }
556
- catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
557
- break;
558
- case 'chlorinator':
559
- try {
560
- let schlor = await sys.board.chlorinator.setChlorAsync(msg);
561
- }
562
- catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
563
- break;
564
- case 'chemcontroller':
565
- try {
566
- await sys.board.chemControllers.setChemControllerAsync(msg);
567
- }
568
- catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
569
- break;
570
- case 'settheme':
571
- try {
572
- let theme = await state.circuits.setLightThemeAsync(parseInt(msg.id, 10), sys.board.valueMaps.lightThemes.encode(msg.theme));
573
- }
574
- catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
575
- break;
576
- case 'temp':
577
- case 'temps':
578
- try {
579
- await sys.board.system.setTempsAsync(msg);
580
- }
581
- catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
582
- break;
583
- case 'tempsensor':
584
- case 'tempsensors':
585
- try {
586
- await sys.board.system.setTempSensorsAsync(msg);
587
- }
588
- catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
589
- break;
590
- default:
591
- logger.silly(`MQTT: Inbound MQTT topic not matched: ${topic}: ${message.toString()}`)
592
- break;
593
- }
594
- }
595
- }
596
- catch (err) {
597
- logger.error(`Error processing MQTT request ${topic}: ${err}. ${message}`)
598
- }
599
- }
600
- }
601
- class MqttInterfaceEvent extends InterfaceEvent {
602
- public topics: MQTTPublishTopic[]
603
- }
604
- export class MQTTPublishTopic {
605
- topic: string;
606
- useRootTopic: boolean;
607
- message: string;
608
- description: string;
609
- formatter: any[];
610
- qos: string;
611
- retain: boolean;
612
- enabled?: boolean;
613
- filter?: string;
614
- lastSent: MQTTMessage[];
615
- options: any;
616
- processor?: string[];
617
- ignoreProcessor: boolean = false;
618
- _fnProcessor: (ctx: any, pub: MQTTPublishTopic, sys: PoolSystem, state: State, data: any) => any
619
- }
620
- class MQTTMessage {
621
- topic: string;
622
- message: string;
623
- }
624
-
625
- class MqttSubscriptions {
626
- public subscriptions: IMQTTSubscription[]
627
- }
628
- class MqttTopicSubscription implements IInterfaceEvent {
629
- root: string;
630
- topic: string;
631
- enabled: boolean;
632
- fnProcessor: (ctx: any, sub: MqttTopicSubscription, sys: PoolSystem, state: State, value: any) => void;
633
- options: any = {};
634
- constructor(root: string, sub: any) {
635
- this.root = sub.root || root;
636
- this.topic = sub.topic;
637
- if (typeof sub.processor !== 'undefined') {
638
- let fnBody = Array.isArray(sub.processor) ? sub.processor.join('\n') : sub.processor;
639
- try {
640
- this.fnProcessor = new Function('ctx', 'sub', 'sys', 'state', 'value', fnBody) as (ctx: any, sub: MqttTopicSubscription, sys: PoolSystem, state: State, value: any) => void;
641
- } catch (err) { logger.error(`Error compiling subscription processor: ${err} -- ${fnBody}`); }
642
- }
643
- }
644
- public get topicPath(): string { return `${this.root}/${this.topic}` };
645
- public executeProcessor(bindings: MqttInterfaceBindings, value: any) {
646
- let baseOpts = extend(true, { headers: {} }, bindings.cfg.options, bindings.context.options);
647
- let opts = extend(true, baseOpts, this.options);
648
- let vars = bindings.bindVarTokens(this, this.topic, value);
649
-
650
- let ctx = {
651
- util: utils,
652
- client: bindings.client,
653
- vars: vars || {},
654
- publish: (topic: string, message: any, options?: any) => {
655
- try {
656
- let msg: string;
657
- if (typeof message === 'undefined') msg = '';
658
- else if (typeof message === 'string') msg = message;
659
- else if (typeof message === 'boolean') msg = message ? 'true' : 'false';
660
- else if (message instanceof Timestamp) (message as Timestamp).format();
661
- else if (typeof message.getTime === 'function') msg = Timestamp.toISOLocal(message);
662
- else {
663
- msg = Utils.stringifyJSON(message);
664
- }
665
- let baseOpts = extend(true, { headers: {} }, bindings.cfg.options, bindings.context.options);
666
- let pubOpts: IClientPublishOptions = { retain: typeof baseOpts.retain !== 'undefined' ? baseOpts.retain : true, qos: typeof baseOpts.qos !== 'undefined' ? baseOpts.qos : 2 };
667
- if (typeof options !== 'undefined') {
668
- if (typeof options.retain !== 'undefined') pubOpts.retain = options.retain;
669
- if (typeof options.qos !== 'undefined') pubOpts.qos = options.qos;
670
- if (typeof options.headers !== 'undefined') pubOpts.properties = extend(true, {}, baseOpts.properties, options.properties);
671
- }
672
- let top = `${this.root}`;
673
- if (!top.endsWith('/') && !topic.startsWith('/')) top += '/';
674
- top += topic;
675
- logger.silly(`Publishing ${top}-${msg}`);
676
- // Now we should be able to send this to the broker.
677
- bindings.client.publish(top, msg, pubOpts, (err) => {
678
- if (err) {
679
- logger.error(`Error publishing topic ${top}-${msg} : ${err}`);
680
- }
681
- });
682
- } catch (err) { logger.error(`Error publishing ${topic} to server ${bindings.cfg.name} from ${this.topic}`); }
683
- }
684
- };
685
-
686
- this.fnProcessor(ctx, this, sys, state, value);
687
- state.emitEquipmentChanges();
688
- }
689
- }
690
- export interface IMQTTSubscription {
691
- topic: string,
692
- description: string,
693
- processor?: string,
694
- enabled?: boolean
695
- }
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, InterfaceContext, IInterfaceEvent } 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 { Timestamp, Utils, 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
+ public 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 = () => { (async () => { await this.initAsync(); })(); }
44
+ public async initAsync() {
45
+ try {
46
+ if (this.client) await this.stopAsync();
47
+ logger.info(`Initializing MQTT client ${this.cfg.name}`);
48
+ let baseOpts = extend(true, { headers: {} }, this.cfg.options, this.context.options);
49
+ if ((typeof baseOpts.hostname === 'undefined' || !baseOpts.hostname) && (typeof baseOpts.host === 'undefined' || !baseOpts.host || baseOpts.host === '*')) {
50
+ logger.warn(`Interface: ${this.cfg.name} has not resolved to a valid host.`);
51
+ return;
52
+ }
53
+ const url = `${baseOpts.protocol || 'mqtt://'}${baseOpts.host}:${baseOpts.port || 1883}`;
54
+ let toks = {};
55
+ const opts = {
56
+ clientId: this.tokensReplacer(baseOpts.clientId, undefined, toks, { vars: {} } as any, {}),
57
+ username: baseOpts.username,
58
+ password: baseOpts.password,
59
+ rejectUnauthorized: !baseOpts.selfSignedCertificate,
60
+ url
61
+ }
62
+ this.setWillOptions(opts);
63
+ this.client = connect(url, opts);
64
+ this.client.on('connect', async () => {
65
+ try {
66
+ logger.info(`MQTT connected to ${url}`);
67
+ await this.subscribe();
68
+ // make sure status is up to date immediately
69
+ // especially in the case of a re-connect
70
+ this.bindEvent("controller", state.controllerState);
71
+ } catch (err) { logger.error(`Error connecting to MQTT Broker ${this.cfg.name} ${err.message}`); }
72
+ });
73
+ this.client.on('reconnect', () => {
74
+ try {
75
+ logger.info(`Re-connecting to MQTT broker ${this.cfg.name}`);
76
+ } catch (err) { logger.error(`Error reconnecting to MQTT Brokder ${this.cfg.name} ${err.message}`); }
77
+
78
+ });
79
+ this.client.on('error', (error) => {
80
+ logger.error(`MQTT error ${error}`)
81
+ this.clearWillState();
82
+ });
83
+ } catch (err) { logger.error(`Error initializing MQTT client ${this.cfg.name}: ${err}`); }
84
+ }
85
+ public async stopAsync() {
86
+ try {
87
+ if (typeof this.client !== 'undefined') {
88
+ await this.unsubscribe();
89
+ await new Promise<boolean>((resolve, reject) => {
90
+ this.client.end(true, { reasonCode: 0, reasonString: `Shutting down MQTT Client` }, () => {
91
+ resolve(true);
92
+ logger.info(`Successfully shut down MQTT Client`);
93
+ });
94
+ });
95
+ if (this.client) this.client.removeAllListeners();
96
+ this.client = null;
97
+ }
98
+ } catch (err) { logger.error(`Error stopping MQTT Client: ${err.message}`); }
99
+ }
100
+ public async reload(data) {
101
+ try {
102
+ await this.unsubscribe();
103
+ this.context = Object.assign<InterfaceContext, any>(new InterfaceContext(), data.context);
104
+ this.events = Object.assign<MqttInterfaceEvent[], any>([], data.events);
105
+ this.subscriptions = Object.assign<MqttTopicSubscription[], any>([], data.subscriptions);
106
+ await this.subscribe();
107
+ } catch (err) { logger.error(`Error reloading MQTT bindings`); }
108
+ }
109
+ private async unsubscribe() {
110
+ try {
111
+ this.client.off('message', this.messageHandler);
112
+ while (this.topics.length > 0) {
113
+ let topic = this.topics.pop();
114
+ if (typeof topic !== 'undefined') {
115
+ await new Promise<boolean>((resolve, reject) => {
116
+ this.client.unsubscribe(topic.topicPath, (err, packet) => {
117
+ if (err) {
118
+ logger.error(`Error unsubscribing from MQTT topic ${topic.topicPath}: ${err}`);
119
+ resolve(false);
120
+ }
121
+ else {
122
+ logger.debug(`Unsubscribed from MQTT topic ${topic.topicPath}`);
123
+ resolve(true);
124
+ }
125
+ });
126
+ });
127
+ }
128
+ }
129
+ this.subscribed = false;
130
+ } catch (err) { logger.error(`Error unsubcribing to MQTT topic: ${err.message}`); }
131
+ }
132
+ protected async subscribe() {
133
+ if (this.topics.length > 0) await this.unsubscribe();
134
+ let root = this.rootTopic();
135
+ if (typeof this.subscriptions !== 'undefined') {
136
+ for (let i = 0; i < this.subscriptions.length; i++) {
137
+ let sub = this.subscriptions[i];
138
+ if(sub.enabled !== false) this.topics.push(new MqttTopicSubscription(root, sub));
139
+ }
140
+ }
141
+ else if (typeof root !== 'undefined') {
142
+ let arrTopics = [
143
+ `state/+/setState`,
144
+ `state/+/setstate`,
145
+ `state/+/toggleState`,
146
+ `state/+/togglestate`,
147
+ `state/body/setPoint`,
148
+ `state/body/setpoint`,
149
+ `state/body/heatSetpoint`,
150
+ `state/body/coolSetpoint`,
151
+ `state/body/heatMode`,
152
+ `state/body/heatmode`,
153
+ `state/+/setTheme`,
154
+ `state/+/settheme`,
155
+ `state/temps`,
156
+ `config/tempSensors`,
157
+ `config/chemController`,
158
+ `state/chemController`,
159
+ `config/chlorinator`,
160
+ `state/chlorinator`];
161
+ for (let i = 0; i < arrTopics.length; i++) {
162
+ this.topics.push(new MqttTopicSubscription(root, { topic: arrTopics[i] }));
163
+ }
164
+ }
165
+ for (let i = 0; i < this.topics.length; i++) {
166
+ let topic = this.topics[i];
167
+ this.client.subscribe(topic.topicPath, (err, granted) => {
168
+ if (!err) logger.verbose(`MQTT subscribed to ${JSON.stringify(granted)}`);
169
+ else logger.error(`MQTT Subscribe: ${err}`);
170
+ });
171
+ }
172
+ this.client.on('message', this.messageHandler);
173
+ this.subscribed = true;
174
+ }
175
+ // this will take in the MQTT Formatter options and format each token that is bound
176
+ // otherwise, it's the same as the base buildTokens fn.
177
+ // This could be combined into one fn but for now it's specific to MQTT formatting of topics
178
+ protected buildTokensWithFormatter(input: string, eventName: string, toks: any, e: InterfaceEvent, data, formatter: any): any {
179
+ toks = toks || [];
180
+ let s = input;
181
+ let regx = /(?<=@bind\=\s*).*?(?=\;)/g;
182
+ let match;
183
+ let sys = sysAlias;
184
+ let state = stateAlias;
185
+ let webApp = webAppAlias;
186
+ let vars = this.bindVarTokens(e, eventName, data);
187
+ // Map all the returns to the token list. We are being very basic
188
+ // here an the object graph is simply based upon the first object occurrence.
189
+ // We simply want to eval against that object reference.
190
+
191
+ while (match = regx.exec(s)) {
192
+ let bind = match[0];
193
+ if (typeof toks[bind] !== 'undefined') continue;
194
+ let tok: any = {};
195
+ toks[bind] = tok;
196
+ try {
197
+ // we may error out if data can't be found (eg during init)
198
+ tok.reg = new RegExp("@bind=" + this.escapeRegex(bind) + ";", "g");
199
+ tok.value = eval(bind);
200
+ if (typeof formatter !== 'undefined') {
201
+ formatter.forEach(entry => {
202
+ if (typeof entry.transform !== 'undefined') {
203
+ let transform = `('${tok.value}')${entry.transform}`;
204
+ tok.value = eval(transform);
205
+ }
206
+ else if (typeof entry === 'object') {
207
+ let rexp = new RegExp(entry.regexkey, 'g')
208
+ tok.value = tok.value.replace(rexp, entry.replace);
209
+ }
210
+ })
211
+ }
212
+ }
213
+ catch (err) {
214
+ // leave value undefined so it isn't sent to bindings
215
+ tok[bind] = null;
216
+ }
217
+ }
218
+ return toks;
219
+ }
220
+ private setWillOptions = (connectOpts) => {
221
+ const baseOpts = extend(true, { headers: {} }, this.cfg.options, this.context.options);
222
+
223
+ if (baseOpts.willTopic !== 'undefined') {
224
+ const rootTopic = this.rootTopic();
225
+ const topic = `${rootTopic}/${baseOpts.willTopic}`;
226
+ const publishOptions = {
227
+ retain: typeof baseOpts.retain !== 'undefined' ? baseOpts.retain : true,
228
+ qos: typeof baseOpts.qos !== 'undefined' ? baseOpts.qos : 2
229
+ };
230
+
231
+ connectOpts.will = {
232
+ topic: topic,
233
+ payload: baseOpts.willPayload,
234
+ retain: publishOptions.retain,
235
+ qos: publishOptions.qos
236
+ };
237
+ }
238
+ }
239
+ private clearWillState() {
240
+ if (typeof this.client.options.will === 'undefined') return;
241
+ let willTopic = this.client.options.will.topic;
242
+ let willPayload = this.client.options.will.payload;
243
+
244
+ if (typeof this.events !== 'undefined') this.events.forEach(evt => {
245
+ if (typeof evt.topics !== 'undefined') evt.topics.forEach(t => {
246
+ if (typeof t.lastSent !== 'undefined') {
247
+ let lm = t.lastSent.find(elem => elem.topic === willTopic);
248
+ if (typeof lm !== 'undefined') {
249
+ lm.message = willPayload.toString();
250
+ }
251
+ }
252
+ });
253
+ });
254
+ }
255
+ public rootTopic = () => {
256
+ let toks = {};
257
+ let baseOpts = extend(true, { headers: {} }, this.cfg.options, this.context.options);
258
+ let topic = '';
259
+ this.buildTokensWithFormatter(baseOpts.rootTopic, undefined, toks, undefined, undefined, baseOpts.formatter);
260
+ topic = this.replaceTokens(baseOpts.rootTopic, toks);
261
+ return topic;
262
+ }
263
+ public bindEvent(evt: string, ...data: any) {
264
+ try {
265
+ if (!this.sentInitialMessages && evt === 'controller' && data[0].status.val === 1) {
266
+ // Emitting all the equipment messages
267
+ state.emitAllEquipmentChanges();
268
+ this.sentInitialMessages = true;
269
+ }
270
+ // Find the binding by first looking for the specific event name.
271
+ // If that doesn't exist then look for the "*" (all events).
272
+ if (typeof this.events !== 'undefined') {
273
+ if (typeof this.client === 'undefined') this.init();
274
+ let evts = this.events.filter(elem => elem.name === evt);
275
+ // If we don't have an explicitly defined event then see if there is a default.
276
+ if (evts.length === 0) {
277
+ let e = this.events.find(elem => elem.name === '*');
278
+ evts = e ? [e] : [];
279
+ }
280
+
281
+ if (evts.length > 0) {
282
+ let toks = {};
283
+ let replacer = '';
284
+ for (let i = 0; i < evts.length; i++) {
285
+ let e = evts[i];
286
+ if (typeof e.enabled !== 'undefined' && !e.enabled) continue;
287
+ let baseOpts = extend(true, { headers: {} }, this.cfg.options, this.context.options);
288
+ let opts = extend(true, baseOpts, e.options);
289
+ // Figure out whether we need to check the filter.
290
+ if (typeof e.filter !== 'undefined') {
291
+ this.buildTokens(e.filter, evt, toks, e, data[0]);
292
+ if (eval(this.replaceTokens(e.filter, toks)) === false) continue;
293
+ }
294
+
295
+ let rootTopic = this.rootTopic();
296
+ if (typeof opts.replacer !== 'undefined') replacer = opts.replacer;
297
+ if (typeof e.topics !== 'undefined') e.topics.forEach(t => {
298
+ let topicToks = {};
299
+ if (typeof t.enabled !== 'undefined' && !t.enabled) return;
300
+ if (typeof t.filter !== 'undefined') {
301
+ this.buildTokens(t.filter, evt, topicToks, e, data[0]);
302
+ if (eval(this.replaceTokens(t.filter, topicToks)) === false) return;
303
+ }
304
+ let topicFormatter = t.formatter || opts.formatter;
305
+ let topic = '';
306
+ let message: any;
307
+ // build tokens for Topic
308
+ // we need to keep separated topic tokens because otherwise
309
+ // a value like @bind=data.name; would be eval'd the same
310
+ // across all topics
311
+ this.buildTokensWithFormatter(t.topic, evt, topicToks, e, data[0], topicFormatter);
312
+ topic = this.replaceTokens(t.topic, topicToks);
313
+ if (t.useRootTopic !== false) topic = `${rootTopic}/${topic}`;
314
+ // Filter out any topics where there may be undefined in it. We don't want any of this if that is the case.
315
+ if (topic.endsWith('/undefined') || topic.indexOf('/undefined/') !== -1 || topic.startsWith('null/') || topic.indexOf('/null') !== -1) return;
316
+ let publishOptions: IClientPublishOptions = { retain: typeof baseOpts.retain !== 'undefined' ? baseOpts.retain : true, qos: typeof baseOpts.qos !== 'undefined' ? baseOpts.qos : 2 };
317
+ let changesOnly = typeof baseOpts.changesOnly !== 'undefined' ? baseOpts.changesOnly : true;
318
+ if (typeof e.options !== 'undefined') {
319
+ if (typeof e.options.retain !== 'undefined') publishOptions.retain = e.options.retain;
320
+ if (typeof e.options.qos !== 'undefined') publishOptions.retain = e.options.qos;
321
+ if (typeof e.options.changesOnly !== 'undefined') changesOnly = e.options.changesOnly;
322
+ }
323
+ if (typeof t.options !== 'undefined') {
324
+ if (typeof t.options.retain !== 'undefined') publishOptions.retain = t.options.retain;
325
+ if (typeof t.options.qos !== 'undefined') publishOptions.qos = t.options.qos;
326
+ if (typeof t.options.changeOnly !== 'undefined') changesOnly = t.options.changesOnly;
327
+ }
328
+
329
+ if (typeof t.processor !== 'undefined') {
330
+ if (t.ignoreProcessor) message = "err";
331
+ else {
332
+ if (typeof t._fnProcessor !== 'function') {
333
+ let fnBody = Array.isArray(t.processor) ? t.processor.join('\n') : t.processor;
334
+ try {
335
+ // Try to compile it.
336
+ t._fnProcessor = new Function('ctx', 'pub', 'sys', 'state', 'data', fnBody) as (ctx: any, pub: MQTTPublishTopic, sys: PoolSystem, state: State, data: any) => any;
337
+ } catch (err) { logger.error(`Error compiling subscription processor: ${err} -- ${fnBody}`); t.ignoreProcessor = true; }
338
+ }
339
+ if (typeof t._fnProcessor === 'function') {
340
+ let vars = this.bindVarTokens(e, evt, data);
341
+ let ctx = { util: utils, rootTopic: rootTopic, topic: topic, opts: opts, vars: vars }
342
+ try {
343
+ message = t._fnProcessor(ctx, t, sys, state, data[0]).toString();
344
+ topic = ctx.topic;
345
+ } catch (err) { logger.error(`Error publishing MQTT data for topic ${t.topic}: ${err.message}`); message = "err"; }
346
+ }
347
+ }
348
+ }
349
+ else {
350
+ this.buildTokens(t.message, evt, topicToks, e, data[0]);
351
+ message = this.tokensReplacer(t.message, evt, topicToks, e, data[0]);
352
+ }
353
+
354
+ if (changesOnly) {
355
+ if (typeof t.lastSent === 'undefined') t.lastSent = [];
356
+ let lm = t.lastSent.find(elem => elem.topic === topic);
357
+ if (typeof lm === 'undefined' || lm.message !== message) {
358
+ setImmediate(() => { this.client.publish(topic, message, publishOptions); });
359
+ logger.silly(`MQTT send:\ntopic: ${topic}\nmessage: ${message}\nopts:${JSON.stringify(publishOptions)}`);
360
+ }
361
+ if (typeof lm === 'undefined') t.lastSent.push({ topic: topic, message: message });
362
+ else lm.message = message;
363
+
364
+ }
365
+ else {
366
+ logger.silly(`MQTT send:\ntopic: ${topic}\nmessage: ${message}\nopts:${JSON.stringify(publishOptions)}`);
367
+ setImmediate(() => { this.client.publish(topic, message, publishOptions); });
368
+ if (typeof t.lastSent !== 'undefined') t.lastSent = undefined;
369
+ }
370
+
371
+ })
372
+ }
373
+ }
374
+ }
375
+ }
376
+ catch (err) {
377
+ logger.error(`Error binding MQTT event ${evt}: ${err.message}`);
378
+ }
379
+ }
380
+ // This needed to be refactored so we could extract it from an anonymous function. We want to be able to unbind
381
+ // from it
382
+ private messageHandler = (topic, message) => { (async () => { await this.processMessage(topic, message); })(); }
383
+ private processMessage = async (topic, message) => {
384
+ try {
385
+ if (!state.isInitialized){
386
+ logger.info(`MQTT: **TOPIC IGNORED, SYSTEM NOT READY** Inbound ${topic}: ${message.toString()}`);
387
+ return;
388
+ }
389
+ let msg = message.toString();
390
+ if (msg[0] === '{') msg = JSON.parse(msg);
391
+
392
+ let sub: MqttTopicSubscription = this.topics.find(elem => topic === elem.topicPath);
393
+ if (typeof sub !== 'undefined') {
394
+ logger.debug(`MQTT: Inbound ${topic} ${message.toString()}`);
395
+ // Alright so now lets process our results.
396
+ if (typeof sub.fnProcessor === 'function') {
397
+ sub.executeProcessor(this, msg);
398
+ return;
399
+ }
400
+ }
401
+ const topics = topic.split('/');
402
+ if (topic.startsWith(this.rootTopic() + '/') && typeof msg === 'object') {
403
+ // RKS: Not sure why there is no processing of state vs config here. Right now the topics are unique
404
+ // between them so it doesn't matter but it will become an issue.
405
+ switch (topics[topics.length - 1].toLowerCase()) {
406
+ case 'setstate': {
407
+ let id = parseInt(msg.id, 10);
408
+ if (typeof id !== 'undefined' && isNaN(id)) {
409
+ logger.error(`Inbound MQTT ${topics} has an invalid id (${id}) in the message (${msg}).`)
410
+ };
411
+ let isOn = typeof msg.isOn !== 'undefined' ? utils.makeBool(msg.isOn) : typeof msg.state !== 'undefined' ? utils.makeBool(msg.state) : undefined;
412
+ switch (topics[topics.length - 2].toLowerCase()) {
413
+ case 'circuits':
414
+ case 'circuit': {
415
+ try {
416
+ if(typeof isOn !== 'undefined') await sys.board.circuits.setCircuitStateAsync(id, isOn);
417
+ }
418
+ catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
419
+ break;
420
+ }
421
+ case 'features':
422
+ case 'feature': {
423
+ try {
424
+ if (typeof isOn !== 'undefined') await sys.board.features.setFeatureStateAsync(id, isOn);
425
+ }
426
+ catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
427
+ break;
428
+ }
429
+ case 'lightgroups':
430
+ case 'lightgroup': {
431
+ try {
432
+ if (typeof isOn !== 'undefined') await sys.board.circuits.setLightGroupStateAsync(id, isOn);
433
+ }
434
+ catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
435
+ break;
436
+ }
437
+ case 'circuitgroups':
438
+ case 'circuitgroup': {
439
+ try {
440
+ if (typeof isOn !== 'undefined') await sys.board.circuits.setCircuitGroupStateAsync(id, isOn);
441
+ }
442
+ catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
443
+ break;
444
+ }
445
+ default:
446
+ logger.warn(`MQTT: Inbound topic ${topics[topics.length - 1]} not matched to event ${topics[topics.length - 2].toLowerCase()}. Message ${msg} `)
447
+ }
448
+ break;
449
+ }
450
+ case 'togglestate':
451
+ {
452
+ let id = parseInt(msg.id, 10);
453
+ if (typeof id !== 'undefined' && isNaN(id)) {
454
+ logger.error(`Inbound MQTT ${topics} has an invalid id (${id}) in the message (${msg}).`)
455
+ };
456
+ switch (topics[topics.length - 2].toLowerCase()) {
457
+ case 'circuits':
458
+ case 'circuit':
459
+ try {
460
+ await sys.board.circuits.toggleCircuitStateAsync(id);
461
+ }
462
+ catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
463
+ break;
464
+ case 'features':
465
+ case 'feature':
466
+ try {
467
+ await sys.board.features.toggleFeatureStateAsync(id);
468
+ }
469
+ catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
470
+ break;
471
+ default:
472
+ logger.warn(`MQTT: Inbound topic ${topics[topics.length - 1]} not matched to event ${topics[topics.length - 2].toLowerCase()}. Message ${msg} `)
473
+ }
474
+ break;
475
+ }
476
+ case 'heatsetpoint':
477
+ try {
478
+ let body = sys.bodies.findByObject(msg);
479
+ if (topics[topics.length - 2].toLowerCase() === 'body') {
480
+ if (typeof body === 'undefined') {
481
+ logger.error(new ServiceParameterError(`Cannot set body heatSetpoint. You must supply a valid id, circuit, name, or type for the body`, 'body', 'id', msg.id));
482
+ return;
483
+ }
484
+ if (typeof msg.setPoint !== 'undefined' || typeof msg.heatSetpoint !== 'undefined') {
485
+ let setPoint = parseInt(msg.setPoint, 10) || parseInt(msg.heatSetpoint, 10);
486
+ if (!isNaN(setPoint)) {
487
+ await sys.board.bodies.setHeatSetpointAsync(body, setPoint);
488
+ }
489
+ }
490
+ }
491
+ }
492
+ catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
493
+ break;
494
+ case 'coolsetpoint':
495
+ try {
496
+ let body = sys.bodies.findByObject(msg);
497
+ if (topics[topics.length - 2].toLowerCase() === 'body') {
498
+ if (typeof body === 'undefined') {
499
+ logger.error(new ServiceParameterError(`Cannot set body coolSetpoint. You must supply a valid id, circuit, name, or type for the body`, 'body', 'id', msg.id));
500
+ return;
501
+ }
502
+ if (typeof msg.setPoint !== 'undefined' || typeof msg.coolSetpoint !== 'undefined') {
503
+ let setPoint = parseInt(msg.coolSetpoint, 10) || parseInt(msg.coolSetpoint, 10);
504
+ if (!isNaN(setPoint)) {
505
+ await sys.board.bodies.setCoolSetpointAsync(body, setPoint);
506
+ }
507
+ }
508
+ }
509
+ } catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
510
+ break;
511
+ case 'setpoint':
512
+ try {
513
+ let body = sys.bodies.findByObject(msg);
514
+ if (topics[topics.length - 2].toLowerCase() === 'body') {
515
+ if (typeof body === 'undefined') {
516
+ 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));
517
+ return;
518
+ }
519
+ if (typeof msg.setPoint !== 'undefined' || typeof msg.heatSetpoint !== 'undefined') {
520
+ let setPoint = parseInt(msg.setPoint, 10) || parseInt(msg.heatSetpoint, 10);
521
+ if (!isNaN(setPoint)) {
522
+ await sys.board.bodies.setHeatSetpointAsync(body, setPoint);
523
+ }
524
+ }
525
+ if (typeof msg.coolSetpoint !== 'undefined') {
526
+ let setPoint = parseInt(msg.coolSetpoint, 10);
527
+ if (!isNaN(setPoint)) {
528
+ await sys.board.bodies.setCoolSetpointAsync(body, setPoint);
529
+ }
530
+ }
531
+ }
532
+ }
533
+ catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
534
+ break;
535
+ case 'heatmode':
536
+ try {
537
+ if (topics[topics.length - 2].toLowerCase() !== 'body') return;
538
+ // Map the mode that was passed in. This should accept the text based name or the ordinal id value.
539
+ let mode = parseInt(msg.mode, 10);
540
+ let val;
541
+ if (isNaN(mode)) mode = parseInt(msg.heatMode, 10);
542
+ if (!isNaN(mode)) val = sys.board.valueMaps.heatModes.transform(mode);
543
+ else val = sys.board.valueMaps.heatModes.transformByName(msg.mode || msg.heatMode);
544
+ if (typeof val.val === 'undefined') {
545
+ logger.error(new ServiceParameterError(`Invalid value for heatMode: ${msg.mode}`, 'body', 'heatMode', mode));
546
+ return;
547
+ }
548
+ mode = val.val;
549
+ let body = sys.bodies.findByObject(msg);
550
+ if (typeof body === 'undefined') {
551
+ 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));
552
+ return;
553
+ }
554
+ let tbody = await sys.board.bodies.setHeatModeAsync(body, mode);
555
+ }
556
+ catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
557
+ break;
558
+ case 'chlorinator':
559
+ try {
560
+ let schlor = await sys.board.chlorinator.setChlorAsync(msg);
561
+ }
562
+ catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
563
+ break;
564
+ case 'chemcontroller':
565
+ try {
566
+ await sys.board.chemControllers.setChemControllerAsync(msg);
567
+ }
568
+ catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
569
+ break;
570
+ case 'settheme':
571
+ try {
572
+ let theme = await state.circuits.setLightThemeAsync(parseInt(msg.id, 10), sys.board.valueMaps.lightThemes.encode(msg.theme));
573
+ }
574
+ catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
575
+ break;
576
+ case 'temp':
577
+ case 'temps':
578
+ try {
579
+ await sys.board.system.setTempsAsync(msg);
580
+ }
581
+ catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
582
+ break;
583
+ case 'tempsensor':
584
+ case 'tempsensors':
585
+ try {
586
+ await sys.board.system.setTempSensorsAsync(msg);
587
+ }
588
+ catch (err) { logger.error(`Error processing MQTT topic ${topics[topics.length - 2]}: ${err.message}`); }
589
+ break;
590
+ default:
591
+ logger.silly(`MQTT: Inbound MQTT topic not matched: ${topic}: ${message.toString()}`)
592
+ break;
593
+ }
594
+ }
595
+ }
596
+ catch (err) {
597
+ logger.error(`Error processing MQTT request ${topic}: ${err}. ${message}`)
598
+ }
599
+ }
600
+ }
601
+ class MqttInterfaceEvent extends InterfaceEvent {
602
+ public topics: MQTTPublishTopic[]
603
+ }
604
+ export class MQTTPublishTopic {
605
+ topic: string;
606
+ useRootTopic: boolean;
607
+ message: string;
608
+ description: string;
609
+ formatter: any[];
610
+ qos: string;
611
+ retain: boolean;
612
+ enabled?: boolean;
613
+ filter?: string;
614
+ lastSent: MQTTMessage[];
615
+ options: any;
616
+ processor?: string[];
617
+ ignoreProcessor: boolean = false;
618
+ _fnProcessor: (ctx: any, pub: MQTTPublishTopic, sys: PoolSystem, state: State, data: any) => any
619
+ }
620
+ class MQTTMessage {
621
+ topic: string;
622
+ message: string;
623
+ }
624
+
625
+ class MqttSubscriptions {
626
+ public subscriptions: IMQTTSubscription[]
627
+ }
628
+ class MqttTopicSubscription implements IInterfaceEvent {
629
+ root: string;
630
+ topic: string;
631
+ enabled: boolean;
632
+ fnProcessor: (ctx: any, sub: MqttTopicSubscription, sys: PoolSystem, state: State, value: any) => void;
633
+ options: any = {};
634
+ constructor(root: string, sub: any) {
635
+ this.root = sub.root || root;
636
+ this.topic = sub.topic;
637
+ if (typeof sub.processor !== 'undefined') {
638
+ let fnBody = Array.isArray(sub.processor) ? sub.processor.join('\n') : sub.processor;
639
+ try {
640
+ this.fnProcessor = new Function('ctx', 'sub', 'sys', 'state', 'value', fnBody) as (ctx: any, sub: MqttTopicSubscription, sys: PoolSystem, state: State, value: any) => void;
641
+ } catch (err) { logger.error(`Error compiling subscription processor: ${err} -- ${fnBody}`); }
642
+ }
643
+ }
644
+ public get topicPath(): string { return `${this.root}/${this.topic}` };
645
+ public executeProcessor(bindings: MqttInterfaceBindings, value: any) {
646
+ let baseOpts = extend(true, { headers: {} }, bindings.cfg.options, bindings.context.options);
647
+ let opts = extend(true, baseOpts, this.options);
648
+ let vars = bindings.bindVarTokens(this, this.topic, value);
649
+
650
+ let ctx = {
651
+ util: utils,
652
+ client: bindings.client,
653
+ vars: vars || {},
654
+ publish: (topic: string, message: any, options?: any) => {
655
+ try {
656
+ let msg: string;
657
+ if (typeof message === 'undefined') msg = '';
658
+ else if (typeof message === 'string') msg = message;
659
+ else if (typeof message === 'boolean') msg = message ? 'true' : 'false';
660
+ else if (message instanceof Timestamp) (message as Timestamp).format();
661
+ else if (typeof message.getTime === 'function') msg = Timestamp.toISOLocal(message);
662
+ else {
663
+ msg = Utils.stringifyJSON(message);
664
+ }
665
+ let baseOpts = extend(true, { headers: {} }, bindings.cfg.options, bindings.context.options);
666
+ let pubOpts: IClientPublishOptions = { retain: typeof baseOpts.retain !== 'undefined' ? baseOpts.retain : true, qos: typeof baseOpts.qos !== 'undefined' ? baseOpts.qos : 2 };
667
+ if (typeof options !== 'undefined') {
668
+ if (typeof options.retain !== 'undefined') pubOpts.retain = options.retain;
669
+ if (typeof options.qos !== 'undefined') pubOpts.qos = options.qos;
670
+ if (typeof options.headers !== 'undefined') pubOpts.properties = extend(true, {}, baseOpts.properties, options.properties);
671
+ }
672
+ let top = `${this.root}`;
673
+ if (!top.endsWith('/') && !topic.startsWith('/')) top += '/';
674
+ top += topic;
675
+ logger.silly(`Publishing ${top}-${msg}`);
676
+ // Now we should be able to send this to the broker.
677
+ bindings.client.publish(top, msg, pubOpts, (err) => {
678
+ if (err) {
679
+ logger.error(`Error publishing topic ${top}-${msg} : ${err}`);
680
+ }
681
+ });
682
+ } catch (err) { logger.error(`Error publishing ${topic} to server ${bindings.cfg.name} from ${this.topic}`); }
683
+ }
684
+ };
685
+
686
+ this.fnProcessor(ctx, this, sys, state, value);
687
+ state.emitEquipmentChanges();
688
+ }
689
+ }
690
+ export interface IMQTTSubscription {
691
+ topic: string,
692
+ description: string,
693
+ processor?: string,
694
+ enabled?: boolean
695
+ }