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