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