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