nodejs-poolcontroller 8.3.0 → 8.4.1

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 (107) 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/157_issues.md +101 -0
  9. package/AGENTS.md +613 -0
  10. package/CONTRIBUTING.md +74 -74
  11. package/Changelog +292 -284
  12. package/Dockerfile +62 -62
  13. package/Gruntfile.js +40 -40
  14. package/LICENSE +661 -661
  15. package/README.md +329 -309
  16. package/anslq25/MessagesMock.ts +221 -221
  17. package/anslq25/boards/MockBoardFactory.ts +49 -49
  18. package/anslq25/boards/MockEasyTouchBoard.ts +696 -696
  19. package/anslq25/boards/MockSystemBoard.ts +216 -216
  20. package/anslq25/chemistry/MockChlorinator.ts +98 -98
  21. package/anslq25/pumps/MockPump.ts +83 -83
  22. package/app.ts +115 -115
  23. package/config/Config.ts +0 -0
  24. package/config/VersionCheck.ts +0 -0
  25. package/controller/Constants.ts +809 -805
  26. package/controller/Equipment.ts +2737 -2664
  27. package/controller/Errors.ts +181 -181
  28. package/controller/Lockouts.ts +549 -549
  29. package/controller/State.ts +3746 -3701
  30. package/controller/boards/AquaLinkBoard.ts +1175 -1003
  31. package/controller/boards/BoardFactory.ts +53 -53
  32. package/controller/boards/EasyTouchBoard.ts +3246 -3202
  33. package/controller/boards/IntelliCenterBoard.ts +4581 -3899
  34. package/controller/boards/IntelliComBoard.ts +69 -69
  35. package/controller/boards/IntelliTouchBoard.ts +382 -382
  36. package/controller/boards/NixieBoard.ts +1947 -1944
  37. package/controller/boards/SunTouchBoard.ts +401 -400
  38. package/controller/boards/SystemBoard.ts +5303 -5268
  39. package/controller/comms/Comms.ts +1278 -1255
  40. package/controller/comms/ScreenLogic.ts +1665 -1665
  41. package/controller/comms/messages/Messages.ts +1627 -1406
  42. package/controller/comms/messages/config/ChlorinatorMessage.ts +5 -0
  43. package/controller/comms/messages/config/CircuitGroupMessage.ts +0 -0
  44. package/controller/comms/messages/config/CircuitMessage.ts +0 -0
  45. package/controller/comms/messages/config/ConfigMessage.ts +6 -0
  46. package/controller/comms/messages/config/CoverMessage.ts +0 -0
  47. package/controller/comms/messages/config/CustomNameMessage.ts +31 -31
  48. package/controller/comms/messages/config/EquipmentMessage.ts +250 -210
  49. package/controller/comms/messages/config/ExternalMessage.ts +1051 -903
  50. package/controller/comms/messages/config/FeatureMessage.ts +0 -0
  51. package/controller/comms/messages/config/GeneralMessage.ts +65 -0
  52. package/controller/comms/messages/config/HeaterMessage.ts +0 -0
  53. package/controller/comms/messages/config/IntellichemMessage.ts +0 -0
  54. package/controller/comms/messages/config/OptionsMessage.ts +207 -174
  55. package/controller/comms/messages/config/PumpMessage.ts +427 -421
  56. package/controller/comms/messages/config/RemoteMessage.ts +0 -0
  57. package/controller/comms/messages/config/ScheduleMessage.ts +401 -390
  58. package/controller/comms/messages/config/SecurityMessage.ts +37 -13
  59. package/controller/comms/messages/config/ValveMessage.ts +0 -0
  60. package/controller/comms/messages/status/ChlorinatorStateMessage.ts +0 -0
  61. package/controller/comms/messages/status/EquipmentStateMessage.ts +940 -822
  62. package/controller/comms/messages/status/HeaterStateMessage.ts +147 -135
  63. package/controller/comms/messages/status/IntelliChemStateMessage.ts +448 -448
  64. package/controller/comms/messages/status/IntelliValveStateMessage.ts +36 -36
  65. package/controller/comms/messages/status/NeptuneModbusStateMessage.ts +217 -0
  66. package/controller/comms/messages/status/PumpStateMessage.ts +0 -0
  67. package/controller/comms/messages/status/RegalModbusStateMessage.ts +410 -410
  68. package/controller/comms/messages/status/VersionMessage.ts +152 -41
  69. package/controller/nixie/Nixie.ts +173 -173
  70. package/controller/nixie/NixieEquipment.ts +104 -104
  71. package/controller/nixie/bodies/Body.ts +120 -120
  72. package/controller/nixie/bodies/Filter.ts +135 -135
  73. package/controller/nixie/chemistry/ChemController.ts +2756 -2724
  74. package/controller/nixie/chemistry/ChemDoser.ts +806 -806
  75. package/controller/nixie/chemistry/Chlorinator.ts +367 -367
  76. package/controller/nixie/circuits/Circuit.ts +478 -478
  77. package/controller/nixie/heaters/Heater.ts +843 -834
  78. package/controller/nixie/pumps/Pump.ts +1336 -1193
  79. package/controller/nixie/schedules/Schedule.ts +401 -401
  80. package/controller/nixie/valves/Valve.ts +170 -170
  81. package/defaultConfig.json +352 -352
  82. package/docker-compose.yml +32 -31
  83. package/logger/DataLogger.ts +448 -448
  84. package/logger/Logger.ts +459 -436
  85. package/package.json +58 -58
  86. package/sendSocket.js +32 -32
  87. package/tsconfig.json +26 -25
  88. package/types/express-multer.d.ts +32 -32
  89. package/web/Server.ts +1939 -1927
  90. package/web/bindings/aqualinkD.json +559 -559
  91. package/web/bindings/influxDB.json +1066 -1066
  92. package/web/bindings/mqtt.json +721 -721
  93. package/web/bindings/mqttAlt.json +746 -746
  94. package/web/bindings/rulesManager.json +54 -54
  95. package/web/bindings/smartThings-Hubitat.json +31 -31
  96. package/web/bindings/valveRelays.json +20 -20
  97. package/web/bindings/vera.json +25 -25
  98. package/web/interfaces/baseInterface.ts +188 -188
  99. package/web/interfaces/httpInterface.ts +148 -148
  100. package/web/interfaces/influxInterface.ts +283 -283
  101. package/web/interfaces/mqttInterface.ts +695 -695
  102. package/web/interfaces/ruleInterface.ts +101 -87
  103. package/web/services/config/Config.ts +1212 -1053
  104. package/web/services/config/ConfigSocket.ts +0 -0
  105. package/web/services/state/State.ts +21 -0
  106. package/web/services/state/StateSocket.ts +28 -0
  107. package/web/services/utilities/Utilities.ts +233 -233
@@ -1,55 +1,55 @@
1
- {
2
- "context": {
3
- "name": "Rules Manager",
4
- "vars": {},
5
- "options": {
6
- "method": "PUT",
7
- "headers": {
8
- "CONTENT-TYPE": "application/json"
9
- }
10
- }
11
- },
12
- "events": [
13
- {
14
- "name": "controller",
15
- "description": "Turn on needsCleaning flag for filter. Evaluate on a controller socket emit. True when the pool is on, pump is not priming, and filter psi > 15",
16
- "enabled": true,
17
- "filter": "@bind=data.id;===1 && @bind=state.filters.getItemById(1).psi;>15 && @bind=data.status.name;!=='priming'",
18
- "options": {
19
- "path": "/config/filter"
20
- },
21
- "body": {"needsCleaning":true}
22
- },
23
- {
24
- "name": "controller",
25
- "description": "Turn on needsCleaning flag for filter. Evaluate on a controller/time socket emit. Eval on the first day of every 3rd month when psi is >15 at any point",
26
- "enabled": true,
27
- "filter": "@bind=(new Date(data.time)).getMonth()%3;===0 && @bind=(new Date(data.time)).getDate();===1 && @bind=state.filters.getItemById(1).psi;>15",
28
- "options": {
29
- "path": "/config/filter"
30
- },
31
- "body": {"needsCleaning":true}
32
- },
33
- {
34
- "name": "chemController",
35
- "description": "Sets chlorinator to 50% if ORP is low",
36
- "enabled": true,
37
- "filter": "@bind=data.orpLevel; < @bind=sys.chemControllers.getItemById(1).orpSetpoint;",
38
- "options": {
39
- "path": "/config/chlorinator"
40
- },
41
- "body": {"id":1, "poolSetpoint":50}
42
- },
43
- {
44
- "name": "chemController",
45
- "description": "Sets chlorinator to 5% if ORP is in range",
46
- "enabled": true,
47
- "filter": "@bind=data.orpLevel; > @bind=sys.chemControllers.getItemById(1).orpSetpoint;",
48
- "options": {
49
- "path": "/config/chlorinator"
50
- },
51
- "body": {"id":1, "poolSetpoint":5}
52
- }
53
-
54
- ]
1
+ {
2
+ "context": {
3
+ "name": "Rules Manager",
4
+ "vars": {},
5
+ "options": {
6
+ "method": "PUT",
7
+ "headers": {
8
+ "CONTENT-TYPE": "application/json"
9
+ }
10
+ }
11
+ },
12
+ "events": [
13
+ {
14
+ "name": "controller",
15
+ "description": "Turn on needsCleaning flag for filter. Evaluate on a controller socket emit. True when the pool is on, pump is not priming, and filter psi > 15",
16
+ "enabled": true,
17
+ "filter": "@bind=data.id;===1 && @bind=state.filters.getItemById(1).psi;>15 && @bind=data.status.name;!=='priming'",
18
+ "options": {
19
+ "path": "/config/filter"
20
+ },
21
+ "body": {"needsCleaning":true}
22
+ },
23
+ {
24
+ "name": "controller",
25
+ "description": "Turn on needsCleaning flag for filter. Evaluate on a controller/time socket emit. Eval on the first day of every 3rd month when psi is >15 at any point",
26
+ "enabled": true,
27
+ "filter": "@bind=(new Date(data.time)).getMonth()%3;===0 && @bind=(new Date(data.time)).getDate();===1 && @bind=state.filters.getItemById(1).psi;>15",
28
+ "options": {
29
+ "path": "/config/filter"
30
+ },
31
+ "body": {"needsCleaning":true}
32
+ },
33
+ {
34
+ "name": "chemController",
35
+ "description": "Sets chlorinator to 50% if ORP is low",
36
+ "enabled": true,
37
+ "filter": "@bind=data.orpLevel; < @bind=sys.chemControllers.getItemById(1).orpSetpoint;",
38
+ "options": {
39
+ "path": "/config/chlorinator"
40
+ },
41
+ "body": {"id":1, "poolSetpoint":50}
42
+ },
43
+ {
44
+ "name": "chemController",
45
+ "description": "Sets chlorinator to 5% if ORP is in range",
46
+ "enabled": true,
47
+ "filter": "@bind=data.orpLevel; > @bind=sys.chemControllers.getItemById(1).orpSetpoint;",
48
+ "options": {
49
+ "path": "/config/chlorinator"
50
+ },
51
+ "body": {"id":1, "poolSetpoint":5}
52
+ }
53
+
54
+ ]
55
55
  }
@@ -1,32 +1,32 @@
1
- {
2
- "context": {
3
- "name": "SmartThings",
4
- "vars": {},
5
- "options": {
6
- "method": "NOTIFY",
7
- "path": "/notify",
8
- "headers": {
9
- "CONTENT-TYPE": "application/json",
10
- "X-EVENT-TYPE": "@bind=eventName;"
11
- }
12
- }
13
- },
14
- "events": [
15
- {
16
- "name": "justAnExample",
17
- "description": "Shows how the binding can be used to send variable data to SmartThings. This can be any combination of data.",
18
- "body": "{\"air\":\"@bind=data.air;@bind=data.units.name.substring(0, 1);\", \"total\":@bind=data.solar + data.waterSensor1;, \"status\":\"@bind=state.equipment.model;\"}",
19
- "options": {
20
- "headers": {
21
- "X-EVENT2": ""
22
- }
23
- }
24
- },
25
- {
26
- "name": "config",
27
- "description": "Not used for updates",
28
- "enabled": false
29
- },
30
- { "name": "*", "description": "All events that are not trapped by other event names. Sends the entire emitted response.", "body": "@bind=data;" }
31
- ]
1
+ {
2
+ "context": {
3
+ "name": "SmartThings",
4
+ "vars": {},
5
+ "options": {
6
+ "method": "NOTIFY",
7
+ "path": "/notify",
8
+ "headers": {
9
+ "CONTENT-TYPE": "application/json",
10
+ "X-EVENT-TYPE": "@bind=eventName;"
11
+ }
12
+ }
13
+ },
14
+ "events": [
15
+ {
16
+ "name": "justAnExample",
17
+ "description": "Shows how the binding can be used to send variable data to SmartThings. This can be any combination of data.",
18
+ "body": "{\"air\":\"@bind=data.air;@bind=data.units.name.substring(0, 1);\", \"total\":@bind=data.solar + data.waterSensor1;, \"status\":\"@bind=state.equipment.model;\"}",
19
+ "options": {
20
+ "headers": {
21
+ "X-EVENT2": ""
22
+ }
23
+ }
24
+ },
25
+ {
26
+ "name": "config",
27
+ "description": "Not used for updates",
28
+ "enabled": false
29
+ },
30
+ { "name": "*", "description": "All events that are not trapped by other event names. Sends the entire emitted response.", "body": "@bind=data;" }
31
+ ]
32
32
  }
@@ -1,20 +1,20 @@
1
- {
2
- "context": {
3
- "name": "valveRelay",
4
- "options": {
5
- "method": "GET",
6
- "path": "/@bind=data.pinId;/@bind=data.isDiverted ? 'on' : 'off';",
7
- "headers": {
8
- "CONTENT-TYPE": "application/json"
9
- }
10
- },
11
- "vars": {}
12
- },
13
- "events": [
14
- {
15
- "name": "valve",
16
- "filter": "@bind=data.isVirtual;",
17
- "description": "Send commands to turn on or off the valve relay based upon the valve emit."
18
- }
19
- ]
20
- }
1
+ {
2
+ "context": {
3
+ "name": "valveRelay",
4
+ "options": {
5
+ "method": "GET",
6
+ "path": "/@bind=data.pinId;/@bind=data.isDiverted ? 'on' : 'off';",
7
+ "headers": {
8
+ "CONTENT-TYPE": "application/json"
9
+ }
10
+ },
11
+ "vars": {}
12
+ },
13
+ "events": [
14
+ {
15
+ "name": "valve",
16
+ "filter": "@bind=data.isVirtual;",
17
+ "description": "Send commands to turn on or off the valve relay based upon the valve emit."
18
+ }
19
+ ]
20
+ }
@@ -1,25 +1,25 @@
1
- {
2
- "context": {
3
- "name": "Vera",
4
- "options": {
5
- "method": "POST",
6
- "path": "/data_request?id=action&DeviceNum=@bind=vars.deviceId;&serviceId=urn:rstrouse-com:serviceId:PoolController1&action=SetEventData&targetData=@bind=eventName;",
7
- "headers": {
8
- "CONTENT-TYPE": "application/json"
9
- }
10
- },
11
- "vars": {}
12
- },
13
- "events": [
14
- {
15
- "name": "config",
16
- "description": "Vera doesn't use this payload.",
17
- "enabled": false
18
- },
19
- {
20
- "name": "*",
21
- "description": "This will be the UPnP version when I get the services built in Vera and the only binding required. Sends the entire emitted response.",
22
- "body": "@bind=data;"
23
- }
24
- ]
25
- }
1
+ {
2
+ "context": {
3
+ "name": "Vera",
4
+ "options": {
5
+ "method": "POST",
6
+ "path": "/data_request?id=action&DeviceNum=@bind=vars.deviceId;&serviceId=urn:rstrouse-com:serviceId:PoolController1&action=SetEventData&targetData=@bind=eventName;",
7
+ "headers": {
8
+ "CONTENT-TYPE": "application/json"
9
+ }
10
+ },
11
+ "vars": {}
12
+ },
13
+ "events": [
14
+ {
15
+ "name": "config",
16
+ "description": "Vera doesn't use this payload.",
17
+ "enabled": false
18
+ },
19
+ {
20
+ "name": "*",
21
+ "description": "This will be the UPnP version when I get the services built in Vera and the only binding required. Sends the entire emitted response.",
22
+ "body": "@bind=data;"
23
+ }
24
+ ]
25
+ }
@@ -1,188 +1,188 @@
1
- import * as fs from "fs";
2
- import * as path from "path";
3
- import extend = require("extend");
4
- import { logger } from "../../logger/Logger";
5
- import { sys as sysAlias } from "../../controller/Equipment";
6
- import { state as stateAlias} from "../../controller/State";
7
- import { webApp as webAppAlias } from '../Server';
8
- import { config } from "../../config/Config";
9
- export class BindingsFile {
10
- public static async fromBuffer(filename: string, buff: Buffer) {
11
- try {
12
- let bf = new BindingsFile();
13
- bf.filename = filename;
14
- bf.filePath = path.join(process.cwd(), 'web/bindings/custom', bf.filename);
15
- bf.options = await bf.extractBindingOptions(buff);
16
- return typeof bf.options !== 'undefined' ? bf : undefined;
17
- } catch (err) { logger.error(`Error creating buffered backup file: ${filename}`); }
18
- }
19
- public static async fromFile(pathName: string, fileName: string) {
20
- try {
21
- let bf = new BindingsFile();
22
- bf.filePath = path.posix.join(pathName, fileName);
23
- bf.filename = fileName;
24
- bf.options = await bf.extractBindingOptions(bf.filePath);
25
- return typeof bf.options !== 'undefined' ? bf : undefined;
26
- } catch (err) { logger.error(`Error creating bindings file from file ${pathName}${fileName}`); }
27
- }
28
- public filename: string;
29
- public filePath: string;
30
- public options: any;
31
- protected async extractBindingOptions(file: string | Buffer) {
32
- try {
33
- let buff = Buffer.isBuffer(file) ? file.toString() : fs.readFileSync(file, 'utf8');
34
- let bindings = JSON.parse(buff);
35
- let interfaces = config.getSection('web.interfaces');
36
- let ass = [];
37
- for (let ifname in interfaces) {
38
- let iface = interfaces[ifname]
39
- if (typeof iface !== 'undefined' && typeof iface.fileName !== 'undefined')
40
- if (iface.fileName.endsWith(`custom/${this.filename}`)) ass.push(ifname);
41
- }
42
- if (typeof bindings.context !== 'undefined')
43
- return {
44
- filename: this.filename, filepath: this.filePath, name: bindings.context.name || name, type: bindings.context.type || undefined, assoc: ass
45
- };
46
- return this.options;
47
- } catch (err) { logger.error(`Error extracting binding options from ${Buffer.isBuffer(file) ? 'Buffer' : file}: ${err.message}`); }
48
- }
49
- }
50
-
51
- export class BaseInterfaceBindings {
52
- constructor(cfg) {
53
- this.cfg = cfg;
54
- }
55
- public context: InterfaceContext;
56
- public cfg;
57
- public events: InterfaceEvent[];
58
- public bindEvent(evt: string, ...data: any) { };
59
- public bindVarTokens(e: IInterfaceEvent, evt: string, ...data: any) {
60
- let v = {};
61
- let toks = {};
62
- let vars = extend(true, {}, this.context.vars, typeof e !== 'undefined' && e.vars ? e.vars : {}, this.cfg.vars || {});
63
- for (var s in vars) {
64
- let ovalue = vars[s];
65
- if (typeof ovalue === 'string') {
66
- if (ovalue.includes('@bind')) {
67
- this.matchTokens(ovalue, evt, toks, e, data[0], vars);
68
- v[s] = toks;
69
- ovalue = this.evalTokens(ovalue, toks);
70
- }
71
- }
72
- v[s] = ovalue;
73
- }
74
- //console.log(...data);
75
- //console.log(v);
76
- return v;
77
- }
78
- protected matchTokens(input: string, eventName: string, toks: any, e: IInterfaceEvent, data, vars): any {
79
- toks = toks || [];
80
- let s = input;
81
- let regx = /(?<=@bind\=\s*).*?(?=\;)/g;
82
- let match;
83
- let sys = sysAlias;
84
- let state = stateAlias;
85
- let webApp = webAppAlias;
86
- while (match = regx.exec(s)) {
87
- let bind = match[0];
88
- if (typeof toks[bind] !== 'undefined') continue;
89
- let tok: any = {};
90
- toks[bind] = tok;
91
- try {
92
- // we may error out if data can't be found (eg during init)
93
- tok.reg = new RegExp("@bind=" + this.escapeRegex(bind) + ";", "g");
94
- tok.value = eval(bind);
95
- }
96
- catch (err) {
97
- // leave value undefined so it isn't sent to bindings
98
- toks[bind] = null;
99
- }
100
- }
101
- return toks;
102
-
103
- }
104
- protected buildTokens(input: string, eventName: string, toks: any, e: IInterfaceEvent, data): any {
105
- toks = toks || [];
106
- let s = input;
107
- let regx = /(?<=@bind\=\s*).*?(?=\;)/g;
108
- let match;
109
- let vars = this.bindVarTokens(e, eventName, data);
110
- let sys = sysAlias;
111
- let state = stateAlias;
112
- let webApp = webAppAlias;
113
- // Map all the returns to the token list. We are being very basic
114
- // here an the object graph is simply based upon the first object occurrence.
115
- // We simply want to eval against that object reference.
116
-
117
- while (match = regx.exec(s)) {
118
- let bind = match[0];
119
- if (typeof toks[bind] !== 'undefined') continue;
120
- let tok: any = {};
121
- toks[bind] = tok;
122
- try {
123
- // we may error out if data can't be found (eg during init)
124
- tok.reg = new RegExp("@bind=" + this.escapeRegex(bind) + ";", "g");
125
- tok.value = eval(bind);
126
- }
127
- catch (err) {
128
- // leave value undefined so it isn't sent to bindings
129
- toks[bind] = null;
130
- }
131
- }
132
- return toks;
133
- }
134
- protected escapeRegex(reg: string) { return reg.replace(/[-[\]{}()*+?.|,\\^$]/g, '\\$&'); }
135
- protected replaceTokens(input: string, toks: any) {
136
- let s = input;
137
- for (let exp in toks) {
138
- let tok = toks[exp];
139
- if (!tok || typeof tok.reg === 'undefined') continue;
140
- tok.reg.lastIndex = 0; // Start over if we used this before.
141
- if (typeof tok.value === 'string') s = s.replace(tok.reg, tok.value);
142
- else if (typeof tok.value === 'undefined') s = s.replace(tok.reg, 'null');
143
- else s = s.replace(tok.reg, JSON.stringify(tok.value));
144
- }
145
- return s;
146
- }
147
- protected evalTokens(input: string, toks: any) {
148
- let s = input;
149
- for (let exp in toks) {
150
- let tok = toks[exp];
151
- if (!tok || typeof tok.reg === 'undefined') continue;
152
- tok.reg.lastIndex = 0; // Start over if we used this before.
153
- if (typeof tok.value === 'string') s = s.replace(tok.reg, tok.value);
154
- else if (typeof tok.value === 'undefined') s = s.replace(tok.reg, 'null');
155
- else return tok.value;
156
- }
157
- return s;
158
- }
159
- protected tokensReplacer(input: string, eventName: string, toks: any, e: InterfaceEvent, data): any{
160
- this.buildTokens(input, eventName, toks, e, data);
161
- return this.replaceTokens(input, toks);
162
- }
163
- public async stopAsync() { }
164
- }
165
- export interface IInterfaceEvent {
166
- enabled: boolean;
167
- filter?: string;
168
- options?: any;
169
- body?: any;
170
- vars?: any;
171
- processor?: string[]
172
- }
173
- export class InterfaceEvent implements IInterfaceEvent {
174
- public name: string;
175
- public enabled: boolean = true;
176
- public filter: string;
177
- public options: any = {};
178
- public body: any = {};
179
- public vars: any = {};
180
- public processor?: string[]
181
- }
182
- export class InterfaceContext {
183
- public name: string;
184
- public mdnsDiscovery: any;
185
- public upnpDevice: any;
186
- public options: any = {};
187
- public vars: any = {};
188
- }
1
+ import * as fs from "fs";
2
+ import * as path from "path";
3
+ import extend = require("extend");
4
+ import { logger } from "../../logger/Logger";
5
+ import { sys as sysAlias } from "../../controller/Equipment";
6
+ import { state as stateAlias} from "../../controller/State";
7
+ import { webApp as webAppAlias } from '../Server';
8
+ import { config } from "../../config/Config";
9
+ export class BindingsFile {
10
+ public static async fromBuffer(filename: string, buff: Buffer) {
11
+ try {
12
+ let bf = new BindingsFile();
13
+ bf.filename = filename;
14
+ bf.filePath = path.join(process.cwd(), 'web/bindings/custom', bf.filename);
15
+ bf.options = await bf.extractBindingOptions(buff);
16
+ return typeof bf.options !== 'undefined' ? bf : undefined;
17
+ } catch (err) { logger.error(`Error creating buffered backup file: ${filename}`); }
18
+ }
19
+ public static async fromFile(pathName: string, fileName: string) {
20
+ try {
21
+ let bf = new BindingsFile();
22
+ bf.filePath = path.posix.join(pathName, fileName);
23
+ bf.filename = fileName;
24
+ bf.options = await bf.extractBindingOptions(bf.filePath);
25
+ return typeof bf.options !== 'undefined' ? bf : undefined;
26
+ } catch (err) { logger.error(`Error creating bindings file from file ${pathName}${fileName}`); }
27
+ }
28
+ public filename: string;
29
+ public filePath: string;
30
+ public options: any;
31
+ protected async extractBindingOptions(file: string | Buffer) {
32
+ try {
33
+ let buff = Buffer.isBuffer(file) ? file.toString() : fs.readFileSync(file, 'utf8');
34
+ let bindings = JSON.parse(buff);
35
+ let interfaces = config.getSection('web.interfaces');
36
+ let ass = [];
37
+ for (let ifname in interfaces) {
38
+ let iface = interfaces[ifname]
39
+ if (typeof iface !== 'undefined' && typeof iface.fileName !== 'undefined')
40
+ if (iface.fileName.endsWith(`custom/${this.filename}`)) ass.push(ifname);
41
+ }
42
+ if (typeof bindings.context !== 'undefined')
43
+ return {
44
+ filename: this.filename, filepath: this.filePath, name: bindings.context.name || name, type: bindings.context.type || undefined, assoc: ass
45
+ };
46
+ return this.options;
47
+ } catch (err) { logger.error(`Error extracting binding options from ${Buffer.isBuffer(file) ? 'Buffer' : file}: ${err.message}`); }
48
+ }
49
+ }
50
+
51
+ export class BaseInterfaceBindings {
52
+ constructor(cfg) {
53
+ this.cfg = cfg;
54
+ }
55
+ public context: InterfaceContext;
56
+ public cfg;
57
+ public events: InterfaceEvent[];
58
+ public bindEvent(evt: string, ...data: any) { };
59
+ public bindVarTokens(e: IInterfaceEvent, evt: string, ...data: any) {
60
+ let v = {};
61
+ let toks = {};
62
+ let vars = extend(true, {}, this.context.vars, typeof e !== 'undefined' && e.vars ? e.vars : {}, this.cfg.vars || {});
63
+ for (var s in vars) {
64
+ let ovalue = vars[s];
65
+ if (typeof ovalue === 'string') {
66
+ if (ovalue.includes('@bind')) {
67
+ this.matchTokens(ovalue, evt, toks, e, data[0], vars);
68
+ v[s] = toks;
69
+ ovalue = this.evalTokens(ovalue, toks);
70
+ }
71
+ }
72
+ v[s] = ovalue;
73
+ }
74
+ //console.log(...data);
75
+ //console.log(v);
76
+ return v;
77
+ }
78
+ protected matchTokens(input: string, eventName: string, toks: any, e: IInterfaceEvent, data, vars): any {
79
+ toks = toks || [];
80
+ let s = input;
81
+ let regx = /(?<=@bind\=\s*).*?(?=\;)/g;
82
+ let match;
83
+ let sys = sysAlias;
84
+ let state = stateAlias;
85
+ let webApp = webAppAlias;
86
+ while (match = regx.exec(s)) {
87
+ let bind = match[0];
88
+ if (typeof toks[bind] !== 'undefined') continue;
89
+ let tok: any = {};
90
+ toks[bind] = tok;
91
+ try {
92
+ // we may error out if data can't be found (eg during init)
93
+ tok.reg = new RegExp("@bind=" + this.escapeRegex(bind) + ";", "g");
94
+ tok.value = eval(bind);
95
+ }
96
+ catch (err) {
97
+ // leave value undefined so it isn't sent to bindings
98
+ toks[bind] = null;
99
+ }
100
+ }
101
+ return toks;
102
+
103
+ }
104
+ protected buildTokens(input: string, eventName: string, toks: any, e: IInterfaceEvent, data): any {
105
+ toks = toks || [];
106
+ let s = input;
107
+ let regx = /(?<=@bind\=\s*).*?(?=\;)/g;
108
+ let match;
109
+ let vars = this.bindVarTokens(e, eventName, data);
110
+ let sys = sysAlias;
111
+ let state = stateAlias;
112
+ let webApp = webAppAlias;
113
+ // Map all the returns to the token list. We are being very basic
114
+ // here an the object graph is simply based upon the first object occurrence.
115
+ // We simply want to eval against that object reference.
116
+
117
+ while (match = regx.exec(s)) {
118
+ let bind = match[0];
119
+ if (typeof toks[bind] !== 'undefined') continue;
120
+ let tok: any = {};
121
+ toks[bind] = tok;
122
+ try {
123
+ // we may error out if data can't be found (eg during init)
124
+ tok.reg = new RegExp("@bind=" + this.escapeRegex(bind) + ";", "g");
125
+ tok.value = eval(bind);
126
+ }
127
+ catch (err) {
128
+ // leave value undefined so it isn't sent to bindings
129
+ toks[bind] = null;
130
+ }
131
+ }
132
+ return toks;
133
+ }
134
+ protected escapeRegex(reg: string) { return reg.replace(/[-[\]{}()*+?.|,\\^$]/g, '\\$&'); }
135
+ protected replaceTokens(input: string, toks: any) {
136
+ let s = input;
137
+ for (let exp in toks) {
138
+ let tok = toks[exp];
139
+ if (!tok || typeof tok.reg === 'undefined') continue;
140
+ tok.reg.lastIndex = 0; // Start over if we used this before.
141
+ if (typeof tok.value === 'string') s = s.replace(tok.reg, tok.value);
142
+ else if (typeof tok.value === 'undefined') s = s.replace(tok.reg, 'null');
143
+ else s = s.replace(tok.reg, JSON.stringify(tok.value));
144
+ }
145
+ return s;
146
+ }
147
+ protected evalTokens(input: string, toks: any) {
148
+ let s = input;
149
+ for (let exp in toks) {
150
+ let tok = toks[exp];
151
+ if (!tok || typeof tok.reg === 'undefined') continue;
152
+ tok.reg.lastIndex = 0; // Start over if we used this before.
153
+ if (typeof tok.value === 'string') s = s.replace(tok.reg, tok.value);
154
+ else if (typeof tok.value === 'undefined') s = s.replace(tok.reg, 'null');
155
+ else return tok.value;
156
+ }
157
+ return s;
158
+ }
159
+ protected tokensReplacer(input: string, eventName: string, toks: any, e: InterfaceEvent, data): any{
160
+ this.buildTokens(input, eventName, toks, e, data);
161
+ return this.replaceTokens(input, toks);
162
+ }
163
+ public async stopAsync() { }
164
+ }
165
+ export interface IInterfaceEvent {
166
+ enabled: boolean;
167
+ filter?: string;
168
+ options?: any;
169
+ body?: any;
170
+ vars?: any;
171
+ processor?: string[]
172
+ }
173
+ export class InterfaceEvent implements IInterfaceEvent {
174
+ public name: string;
175
+ public enabled: boolean = true;
176
+ public filter: string;
177
+ public options: any = {};
178
+ public body: any = {};
179
+ public vars: any = {};
180
+ public processor?: string[]
181
+ }
182
+ export class InterfaceContext {
183
+ public name: string;
184
+ public mdnsDiscovery: any;
185
+ public upnpDevice: any;
186
+ public options: any = {};
187
+ public vars: any = {};
188
+ }