Spell fix.
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.js
CommitLineData
7dde0b73
JB
1const Configuration = require('../utils/Configuration');
2const logger = require('../utils/Logger');
3const WebSocket = require('ws');
f7869514 4const Constants = require('../utils/Constants');
7dde0b73
JB
5const Utils = require('../utils/Utils');
6const OCPPError = require('./OcppError');
7dde0b73
JB
7const AutomaticTransactionGenerator = require('./AutomaticTransactionGenerator');
8const Statistics = require('../utils/Statistics');
9const fs = require('fs');
de1f5008 10const crypto = require('crypto');
7dde0b73
JB
11const {performance, PerformanceObserver} = require('perf_hooks');
12
13class ChargingStation {
2e6f5966
JB
14 constructor(index, stationTemplateFile) {
15 this._index = index;
16 this._stationTemplateFile = stationTemplateFile;
fa9bcef2 17 this._connectors = {};
2e6f5966
JB
18 this._initialize();
19
0a60c33c 20 this._isSocketRestart = false;
7dde0b73
JB
21 this._autoReconnectRetryCount = 0;
22 this._autoReconnectMaxRetries = Configuration.getAutoReconnectMaxRetries(); // -1 for unlimited
23 this._autoReconnectTimeout = Configuration.getAutoReconnectTimeout() * 1000; // ms, zero for disabling
2e6f5966
JB
24
25 this._requests = {};
26 this._messageQueue = [];
27
83045896 28 this._authorizedTags = this._loadAndGetAuthorizedTags();
2e6f5966
JB
29 }
30
5ad8570f
JB
31 _getStationName(stationTemplate) {
32 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + ('000000000' + this._index).substr(('000000000' + this._index).length - 4);
33 }
34
35 _buildStationInfo() {
36 let stationTemplateFromFile;
37 try {
38 // Load template file
39 const fileDescriptor = fs.openSync(this._stationTemplateFile, 'r');
40 stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8'));
41 fs.closeSync(fileDescriptor);
42 } catch (error) {
ead548f2 43 logger.error(this._logPrefix() + ' Template file loading error: ' + error);
5ad8570f
JB
44 }
45 const stationTemplate = stationTemplateFromFile || {};
0a60c33c 46 if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
5ad8570f
JB
47 stationTemplate.maxPower = stationTemplateFromFile.power[Math.floor(Math.random() * stationTemplateFromFile.power.length)];
48 } else {
49 stationTemplate.maxPower = stationTemplateFromFile.power;
50 }
51 stationTemplate.name = this._getStationName(stationTemplateFromFile);
0a60c33c 52 stationTemplate.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
5ad8570f
JB
53 return stationTemplate;
54 }
55
2e6f5966
JB
56 _initialize() {
57 this._stationInfo = this._buildStationInfo();
58 this._bootNotificationMessage = {
59 chargePointModel: this._stationInfo.chargePointModel,
60 chargePointVendor: this._stationInfo.chargePointVendor,
6958152c 61 chargePointSerialNumber: this._stationInfo.chargePointSerialNumberPrefix ? this._stationInfo.chargePointSerialNumberPrefix : '',
34dcb3b5 62 firmwareVersion: this._stationInfo.firmwareVersion ? this._stationInfo.firmwareVersion : '',
2e6f5966
JB
63 };
64 this._configuration = this._getConfiguration();
2e6f5966 65 this._supervisionUrl = this._getSupervisionURL();
0a60c33c
JB
66 this._wsConnectionUrl = this._supervisionUrl + '/' + this._stationInfo.name;
67 // Build connectors if needed
6ecb15e4
JB
68 const maxConnectors = this._getMaxNumberOfConnectors();
69 if (maxConnectors <= 0) {
70 const errMsg = `${this._logPrefix()} Charging station template with no connectors`;
71 logger.error(errMsg);
72 throw Error(errMsg);
73 }
0a60c33c 74 const connectorsConfig = Utils.cloneJSonDocument(this._stationInfo.Connectors);
de1f5008
JB
75 const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(connectorsConfig) + maxConnectors.toString()).digest('hex');
76 // FIXME: Handle shrinking the number of connectors
77 if (!this._connectors || (this._connectors && this._connectorsConfigurationHash !== connectorsConfigHash)) {
78 this._connectorsConfigurationHash = connectorsConfigHash;
0a60c33c
JB
79 // Determine number of customized connectors
80 let lastConnector;
81 for (lastConnector in connectorsConfig) {
6ecb15e4 82 // Add connector Id 0
0a60c33c
JB
83 if (Utils.convertToInt(lastConnector) === 0 && Utils.convertToBoolean(this._stationInfo.useConnectorId0) &&
84 connectorsConfig[lastConnector]) {
85 this._connectors[lastConnector] = connectorsConfig[lastConnector];
86 }
87 }
88 this._addConfigurationKey('NumberOfConnectors', maxConnectors, true);
6ecb15e4
JB
89 if (!this._getConfigurationKey('MeterValuesSampledData')) {
90 this._addConfigurationKey('MeterValuesSampledData', 'Energy.Active.Import.Register');
91 }
0a60c33c
JB
92 // Generate all connectors
93 for (let index = 1; index <= maxConnectors; index++) {
94 const randConnectorID = Utils.convertToBoolean(this._stationInfo.randomConnectors) ? Utils.getRandomInt(lastConnector, 1) : index;
95 this._connectors[index] = connectorsConfig[randConnectorID];
96 }
97 }
d4a73fb7
JB
98 // Avoid duplication of connectors related information
99 delete this._stationInfo.Connectors;
0a60c33c
JB
100 // Initialize transaction attributes on connectors
101 for (const connector in this._connectors) {
102 if (!this._connectors[connector].transactionStarted) {
103 this._initTransactionOnConnector(connector);
104 }
105 }
6ecb15e4 106 this._stationInfo.powerDivider = this._getPowerDivider();
13b4eba0 107 // FIXME: Conditionally initialize or use singleton design pattern per charging station
7dde0b73
JB
108 this._statistics = new Statistics(this._stationInfo.name);
109 this._performanceObserver = new PerformanceObserver((list) => {
110 const entry = list.getEntries()[0];
111 this._statistics.logPerformance(entry, 'ChargingStation');
112 this._performanceObserver.disconnect();
113 });
7dde0b73
JB
114 }
115
ead548f2
JB
116 _logPrefix() {
117 return Utils.logPrefix(` ${this._stationInfo.name}:`);
7dde0b73
JB
118 }
119
2e6f5966
JB
120 _getConfiguration() {
121 return this._stationInfo.Configuration ? this._stationInfo.Configuration : {};
7dde0b73
JB
122 }
123
2e6f5966
JB
124 _getAuthorizationFile() {
125 return this._stationInfo.authorizationFile ? this._stationInfo.authorizationFile : '';
7dde0b73
JB
126 }
127
83045896 128 _loadAndGetAuthorizedTags() {
2e6f5966
JB
129 let authorizedTags = [];
130 const authorizationFile = this._getAuthorizationFile();
131 if (authorizationFile) {
132 try {
133 // Load authorization file
134 const fileDescriptor = fs.openSync(authorizationFile, 'r');
135 authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8'));
136 fs.closeSync(fileDescriptor);
137 } catch (error) {
ead548f2 138 logger.error(this._logPrefix() + ' Authorization file loading error: ' + error);
2e6f5966
JB
139 }
140 } else {
ead548f2 141 logger.info(this._logPrefix() + ' No authorization file given in template file ' + this._stationTemplateFile);
2e6f5966
JB
142 }
143 return authorizedTags;
144 }
145
5ad8570f
JB
146 getRandomTagId() {
147 const index = Math.floor(Math.random() * this._authorizedTags.length);
148 return this._authorizedTags[index];
2e6f5966
JB
149 }
150
5ad8570f
JB
151 hasAuthorizedTags() {
152 return !Utils.isEmptyArray(this._authorizedTags);
153 }
154
6ecb15e4
JB
155 _getNumberOfRunningTransactions() {
156 let trxCount = 0;
157 for (const connector in this._connectors) {
158 if (this._getConnector(connector).transactionStarted) {
159 trxCount++;
160 }
161 }
162 return trxCount;
163 }
164
165 _getPowerDivider() {
166 let powerDivider = this._getNumberOfConnectors();
167 if (this._stationInfo.powerSharedByConnectors) {
168 powerDivider = this._getNumberOfRunningTransactions();
169 }
170 return powerDivider;
171 }
172
6ecb15e4
JB
173 _getConnector(number) {
174 return this._connectors[number];
175 }
176
177 _getMaxNumberOfConnectors() {
5ad8570f 178 let maxConnectors = 0;
0a60c33c 179 if (!Utils.isEmptyArray(this._stationInfo.numberOfConnectors)) {
6ecb15e4 180 // Distribute evenly the number of connectors
5ad8570f
JB
181 maxConnectors = this._stationInfo.numberOfConnectors[(this._index - 1) % this._stationInfo.numberOfConnectors.length];
182 } else {
183 maxConnectors = this._stationInfo.numberOfConnectors;
184 }
185 return maxConnectors;
2e6f5966
JB
186 }
187
6ecb15e4
JB
188 _getNumberOfConnectors() {
189 return Utils.convertToBoolean(this._stationInfo.useConnectorId0) ? Object.keys(this._connectors).length - 1 : Object.keys(this._connectors).length;
190 }
191
2e6f5966
JB
192 _getSupervisionURL() {
193 const supervisionUrls = Utils.cloneJSonDocument(this._stationInfo.supervisionURL ? this._stationInfo.supervisionURL : Configuration.getSupervisionURLs());
7dde0b73 194 let indexUrl = 0;
0a60c33c 195 if (!Utils.isEmptyArray(supervisionUrls)) {
2e6f5966
JB
196 if (Configuration.getDistributeStationToTenantEqually()) {
197 indexUrl = this._index % supervisionUrls.length;
7dde0b73
JB
198 } else {
199 // Get a random url
200 indexUrl = Math.floor(Math.random() * supervisionUrls.length);
201 }
202 return supervisionUrls[indexUrl];
203 }
204 return supervisionUrls;
205 }
206
7dde0b73 207 _getAuthorizeRemoteTxRequests() {
61c2e33d 208 const authorizeRemoteTxRequests = this._getConfigurationKey('AuthorizeRemoteTxRequests');
a6e68f34 209 return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false;
7dde0b73
JB
210 }
211
def3d48e 212 _getLocalAuthListEnabled() {
61c2e33d 213 const localAuthListEnabled = this._getConfigurationKey('LocalAuthListEnabled');
def3d48e
JB
214 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
215 }
216
5ad8570f
JB
217 async _basicStartMessageSequence() {
218 // Start heartbeat
219 this._startHeartbeat(this);
0a60c33c 220 // Initialize connectors status
5ad8570f
JB
221 for (const connector in this._connectors) {
222 if (!this._connectors[connector].transactionStarted) {
223 if (this._connectors[connector].bootStatus) {
224 this.sendStatusNotificationWithTimeout(connector, this._connectors[connector].bootStatus);
225 } else {
226 this.sendStatusNotificationWithTimeout(connector, 'Available');
227 }
228 } else {
229 this.sendStatusNotificationWithTimeout(connector, 'Charging');
230 }
231 }
0a60c33c 232 // Start the ATG
5ad8570f
JB
233 if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable)) {
234 if (!this._automaticTransactionGeneration) {
235 this._automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
236 }
237 if (this._automaticTransactionGeneration.timeToStop) {
238 this._automaticTransactionGeneration.start();
239 }
240 }
241 this._statistics.start();
242 }
243
244 // eslint-disable-next-line class-methods-use-this
245 async _startHeartbeat(self) {
0a60c33c 246 if (self._heartbeatInterval && self._heartbeatInterval > 0 && !self._heartbeatSetInterval) {
5ad8570f 247 self._heartbeatSetInterval = setInterval(() => {
0a60c33c 248 this.sendHeartbeat();
5ad8570f 249 }, self._heartbeatInterval);
ead548f2 250 logger.info(self._logPrefix() + ' Heartbeat started every ' + self._heartbeatInterval + 'ms');
7dde0b73 251 } else {
ead548f2 252 logger.error(`${self._logPrefix()} Heartbeat interval set to ${self._heartbeatInterval}, not starting the heartbeat`);
0a60c33c
JB
253 }
254 }
255
256 async _stopHeartbeat() {
257 if (this._heartbeatSetInterval) {
258 clearInterval(this._heartbeatSetInterval);
259 this._heartbeatSetInterval = null;
7dde0b73 260 }
5ad8570f
JB
261 }
262
263 _startAuthorizationFileMonitoring() {
264 // eslint-disable-next-line no-unused-vars
265 fs.watchFile(this._getAuthorizationFile(), (current, previous) => {
266 try {
ead548f2 267 logger.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
5ad8570f
JB
268 // Initialize _authorizedTags
269 this._authorizedTags = this._loadAndGetAuthorizedTags();
270 } catch (error) {
ead548f2 271 logger.error(this._logPrefix() + ' Authorization file monitoring error: ' + error);
5ad8570f
JB
272 }
273 });
274 }
275
276 _startStationTemplateFileMonitoring() {
277 // eslint-disable-next-line no-unused-vars
278 fs.watchFile(this._stationTemplateFile, (current, previous) => {
279 try {
ead548f2 280 logger.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile + ' have changed, reload');
5ad8570f
JB
281 // Initialize
282 this._initialize();
283 this._addConfigurationKey('HeartBeatInterval', Utils.convertToInt(this._heartbeatInterval ? this._heartbeatInterval / 1000 : 0));
284 this._addConfigurationKey('HeartbeatInterval', Utils.convertToInt(this._heartbeatInterval ? this._heartbeatInterval / 1000 : 0), false, false);
5ad8570f 285 } catch (error) {
ead548f2 286 logger.error(this._logPrefix() + ' Charging station template file monitoring error: ' + error);
5ad8570f
JB
287 }
288 });
289 }
290
bec64e8b
JB
291 async _startMeterValues(connectorId, interval) {
292 if (!this._connectors[connectorId].transactionStarted) {
6ecb15e4 293 logger.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
5ad8570f 294 return;
bec64e8b 295 } else if (this._connectors[connectorId].transactionStarted && !this._connectors[connectorId].transactionId) {
6ecb15e4 296 logger.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
5ad8570f
JB
297 return;
298 }
0a60c33c 299 if (interval > 0) {
bec64e8b 300 this._connectors[connectorId].transactionSetInterval = setInterval(async () => {
0a60c33c
JB
301 const sendMeterValues = performance.timerify(this.sendMeterValues);
302 this._performanceObserver.observe({
303 entryTypes: ['function'],
304 });
bec64e8b 305 await sendMeterValues(connectorId, interval, this);
0a60c33c
JB
306 }, interval);
307 } else {
ead548f2 308 logger.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${interval}ms, not sending MeterValues`);
0a60c33c 309 }
7dde0b73
JB
310 }
311
312 async start() {
0a60c33c
JB
313 if (!this._wsConnectionUrl) {
314 this._wsConnectionUrl = this._supervisionUrl + '/' + this._stationInfo.name;
5ad8570f 315 }
0a60c33c 316 this._wsConnection = new WebSocket(this._wsConnectionUrl, 'ocpp' + Constants.OCPP_VERSION_16);
ead548f2 317 logger.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl);
2e6f5966
JB
318 // Monitor authorization file
319 this._startAuthorizationFileMonitoring();
320 // Monitor station template file
321 this._startStationTemplateFileMonitoring();
7dde0b73
JB
322 // Handle Socket incoming messages
323 this._wsConnection.on('message', this.onMessage.bind(this));
324 // Handle Socket error
325 this._wsConnection.on('error', this.onError.bind(this));
326 // Handle Socket close
327 this._wsConnection.on('close', this.onClose.bind(this));
328 // Handle Socket opening connection
329 this._wsConnection.on('open', this.onOpen.bind(this));
330 // Handle Socket ping
331 this._wsConnection.on('ping', this.onPing.bind(this));
332 }
333
2d0e26f5 334 async stop(reason = '') {
5ad8570f 335 // Stop heartbeat
0a60c33c 336 await this._stopHeartbeat();
5ad8570f
JB
337 // Stop the ATG
338 if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable) &&
339 this._automaticTransactionGeneration &&
340 !this._automaticTransactionGeneration.timeToStop) {
2d0e26f5 341 await this._automaticTransactionGeneration.stop(reason);
5ad8570f
JB
342 } else {
343 for (const connector in this._connectors) {
344 if (this._connectors[connector].transactionStarted) {
2d0e26f5 345 await this.sendStopTransaction(this._connectors[connector].transactionId, reason);
5ad8570f
JB
346 }
347 }
348 }
349 // eslint-disable-next-line guard-for-in
350 for (const connector in this._connectors) {
351 await this.sendStatusNotification(connector, 'Unavailable');
352 }
0a60c33c 353 if (this._wsConnection && this._wsConnection.readyState === WebSocket.OPEN) {
5ad8570f
JB
354 await this._wsConnection.close();
355 }
356 }
357
358 _reconnect(error) {
ead548f2 359 logger.error(this._logPrefix() + ' Socket: abnormally closed', error);
5ad8570f
JB
360 // Stop the ATG if needed
361 if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable) &&
362 Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure) &&
363 this._automaticTransactionGeneration &&
364 !this._automaticTransactionGeneration.timeToStop) {
365 this._automaticTransactionGeneration.stop();
366 }
367 // Stop heartbeat
0a60c33c 368 this._stopHeartbeat();
5ad8570f
JB
369 if (this._autoReconnectTimeout !== 0 &&
370 (this._autoReconnectRetryCount < this._autoReconnectMaxRetries || this._autoReconnectMaxRetries === -1)) {
ead548f2 371 logger.error(`${this._logPrefix()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
5ad8570f
JB
372 this._autoReconnectRetryCount++;
373 setTimeout(() => {
ead548f2 374 logger.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount);
5ad8570f
JB
375 this.start();
376 }, this._autoReconnectTimeout);
377 } else if (this._autoReconnectTimeout !== 0 || this._autoReconnectMaxRetries !== -1) {
ead548f2 378 logger.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
5ad8570f
JB
379 }
380 }
381
7dde0b73 382 onOpen() {
ead548f2 383 logger.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
5ad8570f 384 if (!this._isSocketRestart) {
0bbcb3dc 385 // Send BootNotification
0a60c33c 386 this.sendBootNotification();
0bbcb3dc 387 }
7dde0b73 388 if (this._isSocketRestart) {
027b409a 389 this._basicStartMessageSequence();
546dec0f 390 if (!Utils.isEmptyArray(this._messageQueue)) {
7dde0b73 391 this._messageQueue.forEach((message) => {
0a60c33c 392 if (this._wsConnection && this._wsConnection.readyState === WebSocket.OPEN) {
7dde0b73
JB
393 this._wsConnection.send(message);
394 }
395 });
396 }
7dde0b73
JB
397 }
398 this._autoReconnectRetryCount = 0;
399 this._isSocketRestart = false;
400 }
401
402 onError(error) {
403 switch (error) {
404 case 'ECONNREFUSED':
405 this._isSocketRestart = true;
406 this._reconnect(error);
407 break;
408 default:
ead548f2 409 logger.error(this._logPrefix() + ' Socket error: ' + error);
7dde0b73
JB
410 break;
411 }
412 }
413
414 onClose(error) {
415 switch (error) {
416 case 1000: // Normal close
417 case 1005:
ead548f2 418 logger.info(this._logPrefix() + ' Socket normally closed ' + error);
7dde0b73
JB
419 this._autoReconnectRetryCount = 0;
420 break;
421 default: // Abnormal close
422 this._isSocketRestart = true;
423 this._reconnect(error);
424 break;
425 }
426 }
427
428 onPing() {
ead548f2 429 logger.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
7dde0b73
JB
430 }
431
432 async onMessage(message) {
2d8cee5a 433 let [messageType, messageId, commandName, commandPayload, errorDetails] = [0, '', Constants.ENTITY_CHARGING_STATION, '', ''];
7dde0b73 434 try {
2d8cee5a
JB
435 // Parse the message
436 [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(message);
437
7dde0b73
JB
438 // Check the Type of message
439 switch (messageType) {
440 // Incoming Message
f7869514 441 case Constants.OCPP_JSON_CALL_MESSAGE:
7dde0b73 442 // Process the call
7dde0b73
JB
443 await this.handleRequest(messageId, commandName, commandPayload);
444 break;
445 // Outcome Message
f7869514 446 case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
7dde0b73
JB
447 // Respond
448 // eslint-disable-next-line no-case-declarations
449 let responseCallback; let requestPayload;
450 if (Utils.isIterable(this._requests[messageId])) {
451 [responseCallback, , requestPayload] = this._requests[messageId];
452 } else {
453 throw new Error(`Response request for unknown message id ${messageId} is not iterable`);
454 }
455 if (!responseCallback) {
456 // Error
457 throw new Error(`Response for unknown message id ${messageId}`);
458 }
459 delete this._requests[messageId];
7dde0b73
JB
460 responseCallback(commandName, requestPayload);
461 break;
462 // Error Message
f7869514 463 case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
7dde0b73
JB
464 if (!this._requests[messageId]) {
465 // Error
466 throw new Error(`Error for unknown message id ${messageId}`);
467 }
468 // eslint-disable-next-line no-case-declarations
469 let rejectCallback;
470 if (Utils.isIterable(this._requests[messageId])) {
471 [, rejectCallback] = this._requests[messageId];
472 } else {
473 throw new Error(`Error request for unknown message id ${messageId} is not iterable`);
474 }
475 delete this._requests[messageId];
476 rejectCallback(new OCPPError(commandName, commandPayload, errorDetails));
477 break;
478 // Error
479 default:
480 throw new Error(`Wrong message type ${messageType}`);
481 }
482 } catch (error) {
483 // Log
ead548f2 484 logger.error('%s Incoming message %j processing error %s on request content %s', this._logPrefix(), message, error, this._requests[messageId]);
7dde0b73
JB
485 // Send error
486 // await this.sendError(messageId, error);
487 }
488 }
489
0a60c33c
JB
490 sendHeartbeat() {
491 try {
492 const payload = {
493 currentTime: new Date().toISOString(),
494 };
495 this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'Heartbeat');
496 } catch (error) {
ead548f2 497 logger.error(this._logPrefix() + ' Send Heartbeat error: ' + error);
0a60c33c
JB
498 throw error;
499 }
500 }
501
502 sendBootNotification() {
503 try {
504 this.sendMessage(Utils.generateUUID(), this._bootNotificationMessage, Constants.OCPP_JSON_CALL_MESSAGE, 'BootNotification');
505 } catch (error) {
ead548f2 506 logger.error(this._logPrefix() + ' Send BootNotification error: ' + error);
0a60c33c
JB
507 throw error;
508 }
509 }
510
5ad8570f
JB
511 async sendStatusNotification(connectorId, status, errorCode = 'NoError') {
512 try {
513 const payload = {
514 connectorId,
515 errorCode,
516 status,
517 };
518 await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StatusNotification');
519 } catch (error) {
ead548f2 520 logger.error(this._logPrefix() + ' Send StatusNotification error: ' + error);
5ad8570f 521 throw error;
027b409a
JB
522 }
523 }
524
5ad8570f
JB
525 sendStatusNotificationWithTimeout(connectorId, status, errorCode = 'NoError', timeout = Constants.STATUS_NOTIFICATION_TIMEOUT) {
526 setTimeout(() => this.sendStatusNotification(connectorId, status, errorCode), timeout);
527 }
528
bec64e8b 529 async sendStartTransaction(connectorId, idTag) {
5ad8570f
JB
530 try {
531 const payload = {
bec64e8b 532 connectorId,
5ad8570f
JB
533 idTag,
534 meterStart: 0,
535 timestamp: new Date().toISOString(),
536 };
537 return await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StartTransaction');
538 } catch (error) {
ead548f2 539 logger.error(this._logPrefix() + ' Send StartTransaction error: ' + error);
5ad8570f 540 throw error;
7dde0b73
JB
541 }
542 }
543
bec64e8b
JB
544 sendStartTransactionWithTimeout(connectorId, idTag, timeout) {
545 setTimeout(() => this.sendStartTransaction(connectorId, idTag), timeout);
7dde0b73
JB
546 }
547
5ad8570f 548 async sendStopTransaction(transactionId, reason = '') {
027b409a 549 try {
bec64e8b 550 let payload;
2d0e26f5
JB
551 if (reason) {
552 payload = {
553 transactionId,
554 meterStop: 0,
555 timestamp: new Date().toISOString(),
556 reason,
557 };
558 } else {
559 payload = {
560 transactionId,
561 meterStop: 0,
562 timestamp: new Date().toISOString(),
563 };
564 }
5ad8570f 565 await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StopTransaction');
027b409a 566 } catch (error) {
ead548f2 567 logger.error(this._logPrefix() + ' Send StopTransaction error: ' + error);
5ad8570f 568 throw error;
027b409a
JB
569 }
570 }
571
5ad8570f 572 // eslint-disable-next-line class-methods-use-this
bec64e8b 573 async sendMeterValues(connectorId, interval, self, debug = false) {
5ad8570f
JB
574 try {
575 const sampledValueLcl = {
576 timestamp: new Date().toISOString(),
577 };
bec64e8b 578 const meterValuesClone = Utils.cloneJSonDocument(self._getConnector(connectorId).MeterValues);
0a60c33c 579 if (!Utils.isEmptyArray(meterValuesClone)) {
5ad8570f
JB
580 sampledValueLcl.sampledValue = meterValuesClone;
581 } else {
582 sampledValueLcl.sampledValue = [meterValuesClone];
583 }
584 for (let index = 0; index < sampledValueLcl.sampledValue.length; index++) {
bec64e8b 585 const connector = self._connectors[connectorId];
0a60c33c 586 // SoC measurand
6ecb15e4 587 if (sampledValueLcl.sampledValue[index].measurand && sampledValueLcl.sampledValue[index].measurand === 'SoC' && self._getConfigurationKey('MeterValuesSampledData').value.includes('SoC')) {
5c389abe 588 sampledValueLcl.sampledValue[index].value = !Utils.isUndefined(sampledValueLcl.sampledValue[index].value) ?
9b25a525
JB
589 sampledValueLcl.sampledValue[index].value :
590 sampledValueLcl.sampledValue[index].value = Utils.getRandomInt(100);
5ad8570f 591 if (sampledValueLcl.sampledValue[index].value > 100 || debug) {
ead548f2 592 logger.error(`${self._logPrefix()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValueLcl.sampledValue[index].value}`);
5ad8570f 593 }
0a60c33c 594 // Voltage measurand
6ecb15e4 595 } else if (sampledValueLcl.sampledValue[index].measurand && sampledValueLcl.sampledValue[index].measurand === 'Voltage' && self._getConfigurationKey('MeterValuesSampledData').value.includes('Voltage')) {
5c389abe 596 sampledValueLcl.sampledValue[index].value = !Utils.isUndefined(sampledValueLcl.sampledValue[index].value) ? sampledValueLcl.sampledValue[index].value : 230;
0a60c33c
JB
597 // Energy.Active.Import.Register measurand (default)
598 } else if (!sampledValueLcl.sampledValue[index].measurand || sampledValueLcl.sampledValue[index].measurand === 'Energy.Active.Import.Register') {
6ecb15e4
JB
599 if (Utils.isUndefined(self._stationInfo.powerDivider)) {
600 const errMsg = `${self._logPrefix()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
601 logger.error(errMsg);
602 throw Error(errMsg);
603 } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) {
604 const errMsg = `${self._logPrefix()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`;
605 logger.error(errMsg);
606 throw Error(errMsg);
607 }
5c389abe 608 if (Utils.isUndefined(sampledValueLcl.sampledValue[index].value)) {
6ecb15e4 609 const measurandValue = Utils.getRandomInt(self._stationInfo.maxPower / (self._stationInfo.powerDivider * 3600000) * interval);
9b25a525
JB
610 // Persist previous value in connector
611 if (connector && connector.lastEnergyActiveImportRegisterValue >= 0) {
612 connector.lastEnergyActiveImportRegisterValue += measurandValue;
613 } else {
614 connector.lastEnergyActiveImportRegisterValue = 0;
615 }
616 sampledValueLcl.sampledValue[index].value = connector.lastEnergyActiveImportRegisterValue;
5ad8570f 617 }
ead548f2 618 logger.info(`${self._logPrefix()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: connectorId ${connectorId}, transaction ${connector.transactionId}, value ${sampledValueLcl.sampledValue[index].value}`);
6ecb15e4 619 const maxConsumption = self._stationInfo.maxPower * 3600 / (self._stationInfo.powerDivider * interval);
5ad8570f 620 if (sampledValueLcl.sampledValue[index].value > maxConsumption || debug) {
ead548f2 621 logger.error(`${self._logPrefix()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValueLcl.sampledValue[index].value}/${maxConsumption}`);
5ad8570f 622 }
0a60c33c
JB
623 // Unsupported measurand
624 } else {
ead548f2 625 logger.info(`${self._logPrefix()} Unsupported MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'} on connectorId ${connectorId}`);
5ad8570f
JB
626 }
627 }
628
629 const payload = {
bec64e8b
JB
630 connectorId,
631 transactionId: self._connectors[connectorId].transactionId,
5ad8570f
JB
632 meterValue: [sampledValueLcl],
633 };
634 await self.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'MeterValues');
635 } catch (error) {
ead548f2 636 logger.error(self._logPrefix() + ' Send MeterValues error: ' + error);
0a60c33c 637 throw error;
5ad8570f
JB
638 }
639 }
640
641 sendError(messageId, err) {
642 // Check exception: only OCPP error are accepted
643 const error = err instanceof OCPPError ? err : new OCPPError(Constants.OCPP_ERROR_INTERNAL_ERROR, err.message);
644 // Send error
645 return this.sendMessage(messageId, error, Constants.OCPP_JSON_CALL_ERROR_MESSAGE);
027b409a
JB
646 }
647
f7869514 648 sendMessage(messageId, command, messageType = Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName = '') {
7dde0b73
JB
649 // Send a message through wsConnection
650 const self = this;
651 // Create a promise
652 return new Promise((resolve, reject) => {
653 let messageToSend;
654 // Type of message
655 switch (messageType) {
656 // Request
f7869514 657 case Constants.OCPP_JSON_CALL_MESSAGE:
7dde0b73
JB
658 this._statistics.addMessage(commandName);
659 // Build request
660 this._requests[messageId] = [responseCallback, rejectCallback, command];
661 messageToSend = JSON.stringify([messageType, messageId, commandName, command]);
662 break;
663 // Response
f7869514 664 case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
d3a7883e 665 this._statistics.addMessage(commandName);
7dde0b73
JB
666 // Build response
667 messageToSend = JSON.stringify([messageType, messageId, command]);
668 break;
669 // Error Message
f7869514 670 case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
7dde0b73 671 // Build Message
52f96caf 672 this._statistics.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`);
894a1780 673 messageToSend = JSON.stringify([messageType, messageId, command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR, command.message ? command.message : '', command.details ? command.details : {}]);
7dde0b73
JB
674 break;
675 }
2e6f5966 676 // Check if wsConnection is ready
0a60c33c 677 if (this._wsConnection && this._wsConnection.readyState === WebSocket.OPEN) {
7dde0b73
JB
678 // Yes: Send Message
679 this._wsConnection.send(messageToSend);
680 } else {
681 // Buffer message until connection is back
682 this._messageQueue.push(messageToSend);
683 }
684 // Request?
f7869514 685 if (messageType !== Constants.OCPP_JSON_CALL_MESSAGE) {
7dde0b73
JB
686 // Yes: send Ok
687 resolve();
0a60c33c 688 } else if (this._wsConnection && this._wsConnection.readyState === WebSocket.OPEN) {
7dde0b73
JB
689 // Send timeout in case connection is open otherwise wait for ever
690 // FIXME: Handle message on timeout
f7869514 691 setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants.OCPP_SOCKET_TIMEOUT);
7dde0b73
JB
692 }
693
694 // Function that will receive the request's response
695 function responseCallback(payload, requestPayload) {
696 self._statistics.addMessage(commandName, true);
697 const responseCallbackFn = 'handleResponse' + commandName;
698 if (typeof self[responseCallbackFn] === 'function') {
699 self[responseCallbackFn](payload, requestPayload, self);
700 } else {
ead548f2 701 logger.debug(self._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn);
7dde0b73
JB
702 }
703 // Send the response
704 resolve(payload);
705 }
706
707 // Function that will receive the request's rejection
708 function rejectCallback(reason) {
52f96caf 709 self._statistics.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`, true);
7dde0b73
JB
710 // Build Exception
711 // eslint-disable-next-line no-empty-function
712 self._requests[messageId] = [() => { }, () => { }, '']; // Properly format the request
713 const error = reason instanceof OCPPError ? reason : new Error(reason);
714 // Send error
715 reject(error);
716 }
717 });
718 }
719
5ad8570f
JB
720 handleResponseBootNotification(payload) {
721 if (payload.status === 'Accepted') {
722 this._heartbeatInterval = payload.interval * 1000;
723 this._addConfigurationKey('HeartBeatInterval', Utils.convertToInt(payload.interval));
724 this._addConfigurationKey('HeartbeatInterval', Utils.convertToInt(payload.interval), false, false);
725 this._basicStartMessageSequence();
0a60c33c 726 } else if (payload.status === 'Pending') {
ead548f2 727 logger.info(this._logPrefix() + ' Charging station pending on the central server');
5ad8570f 728 } else {
ead548f2 729 logger.info(this._logPrefix() + ' Charging station rejected by the central server');
7dde0b73 730 }
7dde0b73
JB
731 }
732
bec64e8b
JB
733 _initTransactionOnConnector(connectorId) {
734 this._connectors[connectorId].transactionStarted = false;
735 this._connectors[connectorId].transactionId = null;
736 this._connectors[connectorId].idTag = null;
737 this._connectors[connectorId].lastEnergyActiveImportRegisterValue = -1;
0a60c33c
JB
738 }
739
bec64e8b
JB
740 _resetTransactionOnConnector(connectorId) {
741 this._initTransactionOnConnector(connectorId);
742 if (this._connectors[connectorId].transactionSetInterval) {
743 clearInterval(this._connectors[connectorId].transactionSetInterval);
027b409a
JB
744 }
745 }
746
7dde0b73 747 handleResponseStartTransaction(payload, requestPayload) {
d3a7883e 748 if (this._connectors[requestPayload.connectorId].transactionStarted) {
ead548f2 749 logger.debug(this._logPrefix() + ' Try to start a transaction on an already used connector ' + requestPayload.connectorId + ': %s', this._connectors[requestPayload.connectorId]);
2d0e26f5 750 return;
d3a7883e 751 }
84393381 752
7de604f9
JB
753 let transactionConnectorId;
754 for (const connector in this._connectors) {
755 if (Utils.convertToInt(connector) === Utils.convertToInt(requestPayload.connectorId)) {
756 transactionConnectorId = connector;
757 break;
7dde0b73 758 }
7de604f9
JB
759 }
760 if (!transactionConnectorId) {
ead548f2 761 logger.error(this._logPrefix() + ' Try to start a transaction on a non existing connector Id ' + requestPayload.connectorId);
7de604f9
JB
762 return;
763 }
764 if (payload.idTagInfo && payload.idTagInfo.status === 'Accepted') {
765 this._connectors[transactionConnectorId].transactionStarted = true;
766 this._connectors[transactionConnectorId].transactionId = payload.transactionId;
767 this._connectors[transactionConnectorId].idTag = requestPayload.idTag;
9b25a525 768 this._connectors[transactionConnectorId].lastEnergyActiveImportRegisterValue = 0;
7de604f9 769 this.sendStatusNotification(requestPayload.connectorId, 'Charging');
ead548f2 770 logger.info(this._logPrefix() + ' Transaction ' + payload.transactionId + ' STARTED on ' + this._stationInfo.name + '#' + requestPayload.connectorId + ' for idTag ' + requestPayload.idTag);
6ecb15e4
JB
771 if (this._stationInfo.powerSharedByConnectors) {
772 this._stationInfo.powerDivider++;
773 }
7de604f9 774 const configuredMeterValueSampleInterval = this._getConfigurationKey('MeterValueSampleInterval');
5ad8570f 775 this._startMeterValues(requestPayload.connectorId,
7de604f9 776 configuredMeterValueSampleInterval ? configuredMeterValueSampleInterval.value * 1000 : 60000);
7dde0b73 777 } else {
ead548f2 778 logger.error(this._logPrefix() + ' Starting transaction id ' + payload.transactionId + ' REJECTED with status ' + payload.idTagInfo.status + ', idTag ' + requestPayload.idTag);
7de604f9 779 this._resetTransactionOnConnector(transactionConnectorId);
7dde0b73
JB
780 this.sendStatusNotification(requestPayload.connectorId, 'Available');
781 }
782 }
783
34dcb3b5 784 handleResponseStopTransaction(payload, requestPayload) {
d3a7883e
JB
785 let transactionConnectorId;
786 for (const connector in this._connectors) {
787 if (this._connectors[connector].transactionId === requestPayload.transactionId) {
788 transactionConnectorId = connector;
789 break;
790 }
791 }
792 if (!transactionConnectorId) {
ead548f2 793 logger.error(this._logPrefix() + ' Try to stop a non existing transaction ' + requestPayload.transactionId);
7de604f9 794 return;
d3a7883e
JB
795 }
796 if (payload.idTagInfo && payload.idTagInfo.status === 'Accepted') {
797 this.sendStatusNotification(transactionConnectorId, 'Available');
6ecb15e4
JB
798 if (this._stationInfo.powerSharedByConnectors) {
799 this._stationInfo.powerDivider--;
800 }
ead548f2 801 logger.info(this._logPrefix() + ' Transaction ' + requestPayload.transactionId + ' STOPPED on ' + this._stationInfo.name + '#' + transactionConnectorId);
d3a7883e 802 this._resetTransactionOnConnector(transactionConnectorId);
34dcb3b5 803 } else {
ead548f2 804 logger.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload.transactionId + ' REJECTED with status ' + payload.idTagInfo.status);
34dcb3b5
JB
805 }
806 }
807
facd8ebd 808 handleResponseStatusNotification(payload, requestPayload) {
ead548f2 809 logger.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload, requestPayload);
7dde0b73
JB
810 }
811
facd8ebd 812 handleResponseMeterValues(payload, requestPayload) {
ead548f2 813 logger.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload, requestPayload);
027b409a
JB
814 }
815
facd8ebd 816 handleResponseHeartbeat(payload, requestPayload) {
ead548f2 817 logger.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload, requestPayload);
7dde0b73
JB
818 }
819
820 async handleRequest(messageId, commandName, commandPayload) {
821 let result;
822 this._statistics.addMessage(commandName, true);
823 // Call
824 if (typeof this['handle' + commandName] === 'function') {
825 try {
826 // Call the method
827 result = await this['handle' + commandName](commandPayload);
828 } catch (error) {
829 // Log
ead548f2 830 logger.error(this._logPrefix() + ' Handle request error: ' + error);
facd8ebd 831 // Send back response to inform backend
7dde0b73
JB
832 await this.sendError(messageId, error);
833 }
834 } else {
84393381 835 // Throw exception
f7869514 836 await this.sendError(messageId, new OCPPError(Constants.OCPP_ERROR_NOT_IMPLEMENTED, 'Not implemented', {}));
7dde0b73
JB
837 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
838 }
84393381 839 // Send response
f7869514 840 await this.sendMessage(messageId, result, Constants.OCPP_JSON_CALL_RESULT_MESSAGE);
7dde0b73
JB
841 }
842
5ad8570f 843 async handleReset(commandPayload) {
5ad8570f
JB
844 // Simulate charging station restart
845 setImmediate(async () => {
2d0e26f5 846 await this.stop(commandPayload.type + 'Reset');
0a60c33c 847 await Utils.sleep(this._stationInfo.resetTime);
5ad8570f
JB
848 await this.start();
849 });
ead548f2 850 logger.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${this._stationInfo.resetTime}ms`);
5ad8570f
JB
851 return Constants.OCPP_RESPONSE_ACCEPTED;
852 }
853
61c2e33d
JB
854 _getConfigurationKey(key) {
855 return this._configuration.configurationKey.find((configElement) => configElement.key === key);
856 }
857
3497da01 858 _addConfigurationKey(key, value, readonly = false, visible = true, reboot = false) {
61c2e33d
JB
859 const keyFound = this._getConfigurationKey(key);
860 if (!keyFound) {
861 this._configuration.configurationKey.push({
862 key,
863 readonly,
864 value,
865 visible,
3497da01 866 reboot,
61c2e33d
JB
867 });
868 }
869 }
870
871 _setConfigurationKeyValue(key, value) {
872 const keyFound = this._getConfigurationKey(key);
873 if (keyFound) {
d3a7883e
JB
874 const keyIndex = this._configuration.configurationKey.indexOf(keyFound);
875 this._configuration.configurationKey[keyIndex].value = value;
61c2e33d
JB
876 }
877 }
878
34dcb3b5 879 async handleGetConfiguration(commandPayload) {
facd8ebd
JB
880 const configurationKey = [];
881 const unknownKey = [];
61c2e33d
JB
882 if (Utils.isEmptyArray(commandPayload.key)) {
883 for (const configuration of this._configuration.configurationKey) {
884 if (Utils.isUndefined(configuration.visible)) {
885 configuration.visible = true;
886 } else {
887 configuration.visible = Utils.convertToBoolean(configuration.visible);
888 }
889 if (!configuration.visible) {
890 continue;
891 }
892 configurationKey.push({
893 key: configuration.key,
894 readonly: configuration.readonly,
895 value: configuration.value,
896 });
facd8ebd 897 }
61c2e33d 898 } else {
d20c21a0
JB
899 for (const configurationKey of commandPayload.key) {
900 const keyFound = this._getConfigurationKey(configurationKey);
61c2e33d
JB
901 if (keyFound) {
902 if (Utils.isUndefined(keyFound.visible)) {
903 keyFound.visible = true;
904 } else {
d20c21a0 905 keyFound.visible = Utils.convertToBoolean(configurationKey.visible);
61c2e33d
JB
906 }
907 if (!keyFound.visible) {
908 continue;
909 }
910 configurationKey.push({
911 key: keyFound.key,
912 readonly: keyFound.readonly,
913 value: keyFound.value,
914 });
915 } else {
d20c21a0 916 unknownKey.push(configurationKey);
61c2e33d 917 }
facd8ebd 918 }
facd8ebd
JB
919 }
920 return {
921 configurationKey,
922 unknownKey,
923 };
7dde0b73
JB
924 }
925
926 async handleChangeConfiguration(commandPayload) {
61c2e33d 927 const keyToChange = this._getConfigurationKey(commandPayload.key);
7d887a1b
JB
928 if (!keyToChange) {
929 return {status: Constants.OCPP_ERROR_NOT_SUPPORTED};
930 } else if (keyToChange && Utils.convertToBoolean(keyToChange.readonly)) {
931 return Constants.OCPP_RESPONSE_REJECTED;
932 } else if (keyToChange && !Utils.convertToBoolean(keyToChange.readonly)) {
a6e68f34
JB
933 const keyIndex = this._configuration.configurationKey.indexOf(keyToChange);
934 this._configuration.configurationKey[keyIndex].value = commandPayload.value;
d3a7883e
JB
935 let triggerHeartbeatRestart = false;
936 if (keyToChange.key === 'HeartBeatInterval') {
937 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload.value);
938 triggerHeartbeatRestart = true;
939 }
940 if (keyToChange.key === 'HeartbeatInterval') {
941 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload.value);
942 triggerHeartbeatRestart = true;
943 }
944 if (triggerHeartbeatRestart) {
5c68da4d
JB
945 this._heartbeatInterval = Utils.convertToInt(commandPayload.value) * 1000;
946 // Stop heartbeat
0a60c33c 947 this._stopHeartbeat();
5c68da4d
JB
948 // Start heartbeat
949 this._startHeartbeat(this);
950 }
7d887a1b
JB
951 if (Utils.convertToBoolean(keyToChange.reboot)) {
952 return Constants.OCPP_RESPONSE_REBOOT_REQUIRED;
953 }
dcab13bd 954 return Constants.OCPP_RESPONSE_ACCEPTED;
7dde0b73 955 }
7dde0b73
JB
956 }
957
958 async handleRemoteStartTransaction(commandPayload) {
72766a82 959 const transactionConnectorID = commandPayload.connectorId ? commandPayload.connectorId : '1';
2e6f5966 960 if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
dcab13bd 961 // Check if authorized
2e6f5966 962 if (this._authorizedTags.find((value) => value === commandPayload.idTag)) {
7dde0b73 963 // Authorization successful start transaction
61c2e33d 964 this.sendStartTransactionWithTimeout(transactionConnectorID, commandPayload.idTag, Constants.START_TRANSACTION_TIMEOUT);
ead548f2 965 logger.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID + ' for idTag ' + commandPayload.idTag);
dcab13bd 966 return Constants.OCPP_RESPONSE_ACCEPTED;
7dde0b73 967 }
ead548f2 968 logger.error(this._logPrefix() + ' Remote starting transaction REJECTED with status ' + commandPayload.idTagInfo.status + ', idTag ' + commandPayload.idTag);
dcab13bd 969 return Constants.OCPP_RESPONSE_REJECTED;
7dde0b73 970 }
dcab13bd 971 // No local authorization check required => start transaction
61c2e33d 972 this.sendStartTransactionWithTimeout(transactionConnectorID, commandPayload.idTag, Constants.START_TRANSACTION_TIMEOUT);
ead548f2 973 logger.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID + ' for idTag ' + commandPayload.idTag);
027b409a
JB
974 return Constants.OCPP_RESPONSE_ACCEPTED;
975 }
976
977 async handleRemoteStopTransaction(commandPayload) {
978 for (const connector in this._connectors) {
979 if (this._connectors[connector].transactionId === commandPayload.transactionId) {
d3a7883e
JB
980 this.sendStopTransaction(commandPayload.transactionId);
981 return Constants.OCPP_RESPONSE_ACCEPTED;
027b409a
JB
982 }
983 }
ead548f2 984 logger.info(this._logPrefix() + ' Try to stop remotely a non existing transaction ' + commandPayload.transactionId);
d3a7883e 985 return Constants.OCPP_RESPONSE_REJECTED;
7dde0b73 986 }
7dde0b73
JB
987}
988
989module.exports = ChargingStation;