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