forked from UniversalDevicesInc/tesla-nodeserver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnodeserver.js
286 lines (235 loc) · 8.97 KB
/
nodeserver.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
'use strict';
trapUncaughExceptions();
const fs = require('fs');
const markdown = require('markdown').markdown;
const AsyncLock = require('async-lock');
// Loads the appropriate Polyglot interface module.
const Polyglot = useCloud() ?
require('pgc_interface') : // Cloud Polyglot
require('polyinterface'); // Polyglot V2 module (On-Premise)
const logger = Polyglot.logger;
const lock = new AsyncLock({ timeout: 500 });
const ControllerNode = require('./Nodes/ControllerNode.js')(Polyglot);
const Vehicle = require('./Nodes/Vehicle.js')(Polyglot);
const VehicleSecurity = require('./Nodes/VehicleSecurity.js')(Polyglot);
const VehicleClimate = require('./Nodes/VehicleClimate.js')(Polyglot);
const VehicleConditioning = require('./Nodes/VehicleConditioning.js')(Polyglot);
const VehicleWakeMode = require('./Nodes/VehicleWakeMode.js')(Polyglot);
// Must be the same as in tesla.js
const emailParam = 'Tesla account email';
const pwParam = 'Tesla account password';
// Must be the same in VehicleSecurity.js
const enableSecurityCommandsParam = 'Enable Security Commands';
const homeLatLon = 'Home Lat Lon';
// Must be the same in Vehicle.js
const customLoggingLevel = 'Custom Logging Level';
// UI customParams (param:defaultValue)
const defaultParams = {
[emailParam]: 'Tesla email',
[pwParam]: 'password',
[enableSecurityCommandsParam]: 'false',
[homeLatLon]: '',
[customLoggingLevel]: 'info',
};
const controllerAddress = 'controller';
logger.info('-------------------------------------------------------');
logger.info('Starting Tesla Node Server');
// Create an instance of the Polyglot interface. We need pass all the node
// classes that we will be using.
const poly = new Polyglot.Interface([ControllerNode, Vehicle, VehicleSecurity, VehicleClimate, VehicleConditioning, VehicleWakeMode]);
// Tesla API interface module
// const tesla = require('./lib/tesla.js')(Polyglot, poly);
// Connected to MQTT, but config has not yet arrived.
poly.on('mqttConnected', function() {
logger.info('MQTT Connection started');
});
// Config has been received
poly.on('config', function(config) {
const nodesCount = Object.keys(config.nodes).length;
logger.info('Config received has %d nodes', nodesCount);
// logger.info('Received config: %o',
// Object.assign({}, config, { nodes: '<nodes>' }));
// Important config options:
// config.nodes: Our nodes, with the node class applied
// config.customParams: Configuration parameters from the UI
// config.newParamsDetected: Flag which tells us that customParams changed
// If this is the first config after a node server restart
if (config.isInitialConfig) {
// Removes all existing notices on startup.
poly.removeNoticesAll();
// Uses options specific to Polyglot-V2 vs PGC
if (poly.isCloud) {
logger.info('Running nodeserver in the cloud');
if (!nodesCount) {
// Only required if using PGC
logger.info('Sending profile files to ISY.');
poly.updateProfile();
}
} else {
logger.info('Running nodeserver on-premises');
// Sets the configuration doc shown in the UI
// Available in Polyglot V2 only
const md = fs.readFileSync('./configdoc.md');
poly.setCustomParamsDoc(markdown.toHTML(md.toString()));
}
// Sets the configuration fields in the UI
initializeCustomParams(config.customParams);
// If we have no nodes yet, we add the first node: a controller node which
// holds the node server status and control buttons.
if (!nodesCount) {
// When Nodeserver is started for the first time, creation of the
// controller fails if done too early.
const createDelay = 5000;
logger.info('Auto-creating controller in %s seconds', createDelay / 1000);
setTimeout(function() {
try {
logger.info('Auto-creating controller');
callAsync(autoCreateController());
} catch (err) {
logger.error('Error while auto-creating controller node:', err);
}
}, createDelay);
} else {
// Test code to remove the first node found
// try {
// logger.info('Auto-deleting controller');
// callAsync(autoDeleteNode(config.nodes[Object.keys(config.nodes)[0]]));
// } catch (err) {
// logger.error('Error while auto-deleting controller node');
// }
}
} else {
if (config.newParamsDetected) {
logger.info('New parameters detected');
const controllerNode = poly.getNode(controllerAddress);
// Automatically try to discover vehicles if user changed his creds
if (controllerNode &&
nodesCount === 1 &&
config.customParams[emailParam] &&
/[^@]+@[^\.]+\..+/.test(config.customParams[emailParam]) &&
config.customParams[emailParam] !== defaultParams [emailParam] &&
config.customParams[pwParam] &&
config.customParams[pwParam].length > 1 &&
config.customParams[pwParam] !== defaultParams [pwParam]
) {
controllerNode.onDiscover();
}
}
}
});
// This is triggered every x seconds. Frequency is configured in the UI.
poly.on('poll', function(longPoll) {
callAsync(doPoll(longPoll));
});
// Received a 'stop' message from Polyglot. This NodeServer is shutting down
poly.on('stop', async function() {
logger.info('Graceful stop');
// Make a last short poll and long poll
await doPoll(false);
// await doPoll(true); Long poll is not used.
// Tell Interface we are stopping (Our polling is now finished)
poly.stop();
});
// Received a 'delete' message from Polyglot. This NodeServer is being removed
poly.on('delete', function() {
logger.info('Nodeserver is being deleted');
// We can do some cleanup, then stop.
poly.stop();
});
// MQTT connection ended
poly.on('mqttEnd', function() {
logger.info('MQTT connection ended.'); // May be graceful or not.
});
// Triggered for every message received from polyglot.
// Can be used for troubleshooting.
poly.on('messageReceived', function(message) {
// Only display messages other than config
// if (!message['config']) {
// logger.debug('Message: %o', message);
// }
});
// Triggered for every message received from polyglot.
// Can be used for troubleshooting.
// poly.on('messageSent', function(message) {
// logger.debug('Message sent: %o', message);
// });
// This is being triggered based on the short and long poll parameters in the UI
async function doPoll(longPoll) {
// Prevents polling logic reentry if an existing poll is underway
try {
await lock.acquire('poll', function() {
logger.info('%s', longPoll ? 'Long poll' : 'Short poll');
const nodes = poly.getNodes();
Object.keys(nodes).forEach(function(address) {
if ('query' in nodes[address]) {
nodes[address].query(longPoll);
}
});
});
} catch (err) {
logger.error('Error while polling: %s', err.message);
}
}
// Creates the controller node
async function autoCreateController() {
try {
await poly.addNode(
new ControllerNode(poly,
controllerAddress, controllerAddress, 'Tesla NodeServer')
);
// Add a notice in the UI
poly.addNoticeTemp('newController', 'Controller node initialized', 5);
} catch (err) {
logger.error('Error creating controller node');
// Add a notice in the UI, and leave it there
poly.addNotice('newController', 'Error creating controller node');
}
}
// Sets the custom params as we want them. Keeps existing params values.
function initializeCustomParams(currentParams) {
const defaultParamKeys = Object.keys(defaultParams);
const currentParamKeys = Object.keys(currentParams);
// Get orphan keys from either currentParams or defaultParams
const differentKeys = defaultParamKeys.concat(currentParamKeys)
.filter(function(key) {
return !(key in defaultParams) || !(key in currentParams);
});
if (differentKeys.length) {
let customParams = {};
// Only keeps params that exists in defaultParams
// Sets the params to the existing value, or default value.
defaultParamKeys.forEach(function(key) {
customParams[key] = currentParams[key] ?
currentParams[key] : defaultParams[key];
});
poly.saveCustomParams(customParams);
}
}
// Call Async function from a non-async function without waiting for result
// and log the error if it fails
function callAsync(promise) {
(async function() {
try {
await promise;
} catch (err) {
logger.error('Error with async function: %s',
err.stack ? err.stack : err.message);
}
})();
}
function trapUncaughExceptions() {
// If we get an uncaugthException...
process.on('uncaughtException', function(err) {
// Used in dev. Useful when logger is not yet defined.
console.log('err', err);
// avoid the edge case where an exception is thrown before the logger is available
if ( !(typeof myval === 'undefined')) {
logger.error(`uncaughtException REPORT THIS!: ${err.stack}`);
}
});
}
function useCloud() {
return process.env.MQTTENDPOINT && process.env.STAGE;
}
// Starts the NodeServer!
poly.start();