Fix heartbeat initialization
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.js
1 const Configuration = require('../utils/Configuration');
2 const logger = require('../utils/Logger');
3 const WebSocket = require('ws');
4 const Constants = require('../utils/Constants');
5 const Utils = require('../utils/Utils');
6 const OCPPError = require('./OcppError');
7 const AutomaticTransactionGenerator = require('./AutomaticTransactionGenerator');
8 const Statistics = require('../utils/Statistics');
9 const fs = require('fs');
10 const {performance, PerformanceObserver} = require('perf_hooks');
11
12 class ChargingStation {
13 constructor(index, stationTemplateFile) {
14 this._index = index;
15 this._stationTemplateFile = stationTemplateFile;
16 this._initialize();
17
18 this._autoReconnectRetryCount = 0;
19 this._autoReconnectMaxRetries = Configuration.getAutoReconnectMaxRetries(); // -1 for unlimited
20 this._autoReconnectTimeout = Configuration.getAutoReconnectTimeout() * 1000; // ms, zero for disabling
21
22 this._requests = {};
23 this._messageQueue = [];
24
25 this._isSocketRestart = false;
26
27 this._authorizedTags = this._getAuthorizedTags();
28 }
29
30 _initialize() {
31 this._stationInfo = this._buildStationInfo();
32 this._bootNotificationMessage = {
33 chargePointModel: this._stationInfo.chargePointModel,
34 chargePointVendor: this._stationInfo.chargePointVendor,
35 // chargePointSerialNumber: this._stationInfo.chargePointSerialNumber,
36 firmwareVersion: this._stationInfo.firmwareVersion ? this._stationInfo.firmwareVersion : '',
37 };
38 this._configuration = this._getConfiguration();
39 this._supervisionUrl = this._getSupervisionURL();
40 this._statistics = new Statistics(this._stationInfo.name);
41 this._performanceObserver = new PerformanceObserver((list) => {
42 const entry = list.getEntries()[0];
43 this._statistics.logPerformance(entry, 'ChargingStation');
44 this._performanceObserver.disconnect();
45 });
46 }
47
48 _basicFormatLog() {
49 return Utils.basicFormatLog(` ${this._stationInfo.name}:`);
50 }
51
52 _getConfiguration() {
53 return this._stationInfo.Configuration ? this._stationInfo.Configuration : {};
54 }
55
56 _getAuthorizationFile() {
57 return this._stationInfo.authorizationFile ? this._stationInfo.authorizationFile : '';
58 }
59
60 _getAuthorizedTags() {
61 let authorizedTags = [];
62 const authorizationFile = this._getAuthorizationFile();
63 if (authorizationFile) {
64 try {
65 // Load authorization file
66 const fileDescriptor = fs.openSync(authorizationFile, 'r');
67 authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8'));
68 fs.closeSync(fileDescriptor);
69 } catch (error) {
70 logger.error(this._basicFormatLog() + ' Authorization file loading error: ' + error);
71 }
72 } else {
73 logger.info(this._basicFormatLog() + ' No authorization file given in template file ' + this._stationTemplateFile);
74 }
75 return authorizedTags;
76 }
77
78 _startAuthorizationFileMonitoring() {
79 // eslint-disable-next-line no-unused-vars
80 fs.watchFile(this._getAuthorizationFile(), (current, previous) => {
81 try {
82 logger.debug(this._basicFormatLog() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
83 // Initialize _authorizedTags
84 this._authorizedTags = this._getAuthorizedTags();
85 } catch (error) {
86 logger.error(this._basicFormatLog() + ' Authorization file monitoring error: ' + error);
87 }
88 });
89 }
90
91 _startStationTemplateFileMonitoring() {
92 // eslint-disable-next-line no-unused-vars
93 fs.watchFile(this._stationTemplateFile, (current, previous) => {
94 try {
95 logger.debug(this._basicFormatLog() + ' Template file ' + this._stationTemplateFile + ' have changed, reload');
96 // Initialize
97 this._initialize();
98 } catch (error) {
99 logger.error(this._basicFormatLog() + ' Charging station template file monitoring error: ' + error);
100 }
101 });
102 }
103
104 _getSupervisionURL() {
105 const supervisionUrls = Utils.cloneJSonDocument(this._stationInfo.supervisionURL ? this._stationInfo.supervisionURL : Configuration.getSupervisionURLs());
106 let indexUrl = 0;
107 if (Array.isArray(supervisionUrls)) {
108 if (Configuration.getDistributeStationToTenantEqually()) {
109 indexUrl = this._index % supervisionUrls.length;
110 } else {
111 // Get a random url
112 indexUrl = Math.floor(Math.random() * supervisionUrls.length);
113 }
114 return supervisionUrls[indexUrl];
115 }
116 return supervisionUrls;
117 }
118
119 _getStationName(stationTemplate) {
120 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + ('000000000' + this._index).substr(('000000000' + this._index).length - 4);
121 }
122
123 _getAuthorizeRemoteTxRequests() {
124 const authorizeRemoteTxRequests = this._configuration.configurationKey.find((configElement) => configElement.key === 'AuthorizeRemoteTxRequests');
125 return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false;
126 }
127
128 _getLocalAuthListEnabled() {
129 const localAuthListEnabled = this._configuration.configurationKey.find((configElement) => configElement.key === 'LocalAuthListEnabled');
130 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
131 }
132
133 _buildStationInfo() {
134 let stationTemplateFromFile;
135 try {
136 // Load template file
137 const fileDescriptor = fs.openSync(this._stationTemplateFile, 'r');
138 stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8'));
139 fs.closeSync(fileDescriptor);
140 } catch (error) {
141 logger.error(this._basicFormatLog() + ' Template file loading error: ' + error);
142 }
143 const stationTemplate = stationTemplateFromFile || {};
144 if (Array.isArray(stationTemplateFromFile.power)) {
145 stationTemplate.maxPower = stationTemplateFromFile.power[Math.floor(Math.random() * stationTemplateFromFile.power.length)];
146 } else {
147 stationTemplate.maxPower = stationTemplateFromFile.power;
148 }
149 stationTemplate.name = this._getStationName(stationTemplateFromFile);
150 return stationTemplate;
151 }
152
153 async start() {
154 this._url = this._supervisionUrl + '/' + this._stationInfo.name;
155 this._wsConnection = new WebSocket(this._url, 'ocpp1.6');
156 logger.info(this._basicFormatLog() + ' Will communicate with ' + this._supervisionUrl);
157 // Monitor authorization file
158 this._startAuthorizationFileMonitoring();
159 // Monitor station template file
160 this._startStationTemplateFileMonitoring();
161 // Handle Socket incoming messages
162 this._wsConnection.on('message', this.onMessage.bind(this));
163 // Handle Socket error
164 this._wsConnection.on('error', this.onError.bind(this));
165 // Handle Socket close
166 this._wsConnection.on('close', this.onClose.bind(this));
167 // Handle Socket opening connection
168 this._wsConnection.on('open', this.onOpen.bind(this));
169 // Handle Socket ping
170 this._wsConnection.on('ping', this.onPing.bind(this));
171 }
172
173 onOpen() {
174 logger.info(`${this._basicFormatLog()} Is connected to server through ${this._url}`);
175 if (!this._heartbeatInterval) {
176 // Send BootNotification
177 try {
178 this.sendMessage(Utils.generateUUID(), this._bootNotificationMessage, Constants.OCPP_JSON_CALL_MESSAGE, 'BootNotification');
179 } catch (error) {
180 logger.error(this._basicFormatLog() + ' Send boot notification error: ' + error);
181 }
182 }
183 if (this._isSocketRestart) {
184 this._basicStartMessageSequence();
185 if (this._messageQueue.length > 0) {
186 this._messageQueue.forEach((message) => {
187 if (this._wsConnection.readyState === WebSocket.OPEN) {
188 this._wsConnection.send(message);
189 }
190 });
191 }
192 }
193 this._autoReconnectRetryCount = 0;
194 this._isSocketRestart = false;
195 }
196
197 onError(error) {
198 switch (error) {
199 case 'ECONNREFUSED':
200 this._isSocketRestart = true;
201 this._reconnect(error);
202 break;
203 default:
204 logger.error(this._basicFormatLog() + ' Socket error: ' + error);
205 break;
206 }
207 }
208
209 onClose(error) {
210 switch (error) {
211 case 1000: // Normal close
212 case 1005:
213 logger.info(this._basicFormatLog() + ' Socket normally closed ' + error);
214 this._autoReconnectRetryCount = 0;
215 break;
216 default: // Abnormal close
217 this._isSocketRestart = true;
218 this._reconnect(error);
219 break;
220 }
221 }
222
223 onPing() {
224 logger.debug(this._basicFormatLog() + ' Has received a WS ping (rfc6455) from the server');
225 }
226
227 async onMessage(message) {
228 let [messageType, messageId, commandName, commandPayload, errorDetails] = [0, '', Constants.ENTITY_CHARGING_STATION, '', ''];
229 try {
230 // Parse the message
231 [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(message);
232
233 // Check the Type of message
234 switch (messageType) {
235 // Incoming Message
236 case Constants.OCPP_JSON_CALL_MESSAGE:
237 // Process the call
238 this._statistics.addMessage(commandName);
239 await this.handleRequest(messageId, commandName, commandPayload);
240 break;
241 // Outcome Message
242 case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
243 // Respond
244 // eslint-disable-next-line no-case-declarations
245 let responseCallback; let requestPayload;
246 if (Utils.isIterable(this._requests[messageId])) {
247 [responseCallback, , requestPayload] = this._requests[messageId];
248 } else {
249 throw new Error(`Response request for unknown message id ${messageId} is not iterable`);
250 }
251 if (!responseCallback) {
252 // Error
253 throw new Error(`Response for unknown message id ${messageId}`);
254 }
255 delete this._requests[messageId];
256 // this._statistics.addMessage(commandName)
257 responseCallback(commandName, requestPayload);
258 break;
259 // Error Message
260 case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
261 if (!this._requests[messageId]) {
262 // Error
263 throw new Error(`Error for unknown message id ${messageId}`);
264 }
265 // eslint-disable-next-line no-case-declarations
266 let rejectCallback;
267 if (Utils.isIterable(this._requests[messageId])) {
268 [, rejectCallback] = this._requests[messageId];
269 } else {
270 throw new Error(`Error request for unknown message id ${messageId} is not iterable`);
271 }
272 delete this._requests[messageId];
273 rejectCallback(new OCPPError(commandName, commandPayload, errorDetails));
274 break;
275 // Error
276 default:
277 throw new Error(`Wrong message type ${messageType}`);
278 }
279 } catch (error) {
280 // Log
281 logger.error('%s Incoming message %j processing error %s on request content %s', this._basicFormatLog(), message, error, this._requests[messageId]);
282 // Send error
283 // await this.sendError(messageId, error);
284 }
285 }
286
287 // eslint-disable-next-line class-methods-use-this
288 async _startHeartbeat(self) {
289 if (self._heartbeatInterval && !self._heartbeatSetInterval) {
290 self._heartbeatSetInterval = setInterval(() => {
291 try {
292 const payload = {
293 currentTime: new Date().toISOString(),
294 };
295 self.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'Heartbeat');
296 } catch (error) {
297 logger.error(self._basicFormatLog() + ' Send heartbeat error: ' + error);
298 }
299 }, self._heartbeatInterval);
300 logger.info(self._basicFormatLog() + ' Heartbeat started every ' + self._heartbeatInterval + 'ms');
301 } else {
302 logger.error(self._basicFormatLog() + ' Heartbeat interval undefined, not starting the heartbeat');
303 }
304 }
305
306 _reconnect(error) {
307 logger.error(this._basicFormatLog() + ' Socket: abnormally closed', error);
308 // Stop heartbeat interval
309 if (this._heartbeatSetInterval) {
310 clearInterval(this._heartbeatSetInterval);
311 this._heartbeatSetInterval = null;
312 }
313 // Stop the ATG if needed
314 if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable) &&
315 Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure) &&
316 this._automaticTransactionGeneration &&
317 !this._automaticTransactionGeneration.timeToStop) {
318 this._automaticTransactionGeneration.stop();
319 }
320 if (this._autoReconnectTimeout !== 0 &&
321 (this._autoReconnectRetryCount < this._autoReconnectMaxRetries || this._autoReconnectMaxRetries === -1)) {
322 logger.error(`${this._basicFormatLog()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
323 this._autoReconnectRetryCount++;
324 setTimeout(() => {
325 logger.error(this._basicFormatLog() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount);
326 this.start();
327 }, this._autoReconnectTimeout);
328 } else if (this._autoReconnectTimeout !== 0 || this._autoReconnectMaxRetries !== -1) {
329 logger.error(`${this._basicFormatLog()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
330 }
331 }
332
333 send(command, messageType = Constants.OCPP_JSON_CALL_MESSAGE) {
334 // Send Message
335 return this.sendMessage(Utils.generateUUID(), command, messageType);
336 }
337
338 sendError(messageId, err) {
339 // Check exception: only OCPP error are accepted
340 const error = err instanceof OCPPError ? err : new OCPPError(Constants.OCPP_ERROR_INTERNAL_ERROR, err.message);
341 // Send error
342 return this.sendMessage(messageId, error, Constants.OCPP_JSON_CALL_ERROR_MESSAGE);
343 }
344
345 async sendStatusNotification(connectorId, status, errorCode = 'NoError') {
346 try {
347 const payload = {
348 connectorId,
349 errorCode,
350 status,
351 };
352 await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StatusNotification');
353 } catch (error) {
354 logger.error(this._basicFormatLog() + ' Send status error: ' + error);
355 }
356 }
357
358 async sendStatusNotificationWithTimeout(connectorId, status, errorCode = 'NoError', timeout = Constants.STATUS_NOTIFICATION_TIMEOUT) {
359 setTimeout(() => this.sendStatusNotification(connectorId, status, errorCode), timeout);
360 }
361
362 sendMessage(messageId, command, messageType = Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName = '') {
363 // Send a message through wsConnection
364 const self = this;
365 // Create a promise
366 return new Promise((resolve, reject) => {
367 let messageToSend;
368 // Type of message
369 switch (messageType) {
370 // Request
371 case Constants.OCPP_JSON_CALL_MESSAGE:
372 this._statistics.addMessage(commandName);
373 // Build request
374 this._requests[messageId] = [responseCallback, rejectCallback, command];
375 messageToSend = JSON.stringify([messageType, messageId, commandName, command]);
376 break;
377 // Response
378 case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
379 // Build response
380 messageToSend = JSON.stringify([messageType, messageId, command]);
381 break;
382 // Error Message
383 case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
384 // Build Message
385 this._statistics.addMessage(`Error ${command.code}`);
386 messageToSend = JSON.stringify([messageType, messageId, command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR, command.message ? command.message : '', command.details ? command.details : {}]);
387 break;
388 }
389 // Check if wsConnection is ready
390 if (this._wsConnection.readyState === WebSocket.OPEN) {
391 // Yes: Send Message
392 this._wsConnection.send(messageToSend);
393 } else {
394 // Buffer message until connection is back
395 this._messageQueue.push(messageToSend);
396 }
397 // Request?
398 if (messageType !== Constants.OCPP_JSON_CALL_MESSAGE) {
399 // Yes: send Ok
400 resolve();
401 } else if (this._wsConnection.readyState === WebSocket.OPEN) {
402 // Send timeout in case connection is open otherwise wait for ever
403 // FIXME: Handle message on timeout
404 setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants.OCPP_SOCKET_TIMEOUT);
405 }
406
407 // Function that will receive the request's response
408 function responseCallback(payload, requestPayload) {
409 self._statistics.addMessage(commandName, true);
410 const responseCallbackFn = 'handleResponse' + commandName;
411 if (typeof self[responseCallbackFn] === 'function') {
412 self[responseCallbackFn](payload, requestPayload, self);
413 } else {
414 logger.debug(self._basicFormatLog() + ' Trying to call an undefined callback function: ' + responseCallbackFn);
415 }
416 // Send the response
417 resolve(payload);
418 }
419
420 // Function that will receive the request's rejection
421 function rejectCallback(reason) {
422 // Build Exception
423 // eslint-disable-next-line no-empty-function
424 self._requests[messageId] = [() => { }, () => { }, '']; // Properly format the request
425 const error = reason instanceof OCPPError ? reason : new Error(reason);
426 // Send error
427 reject(error);
428 }
429 });
430 }
431
432 async _basicStartMessageSequence() {
433 this._startHeartbeat(this);
434 // build connectors
435 if (!this._connectors) {
436 this._connectors = {};
437 const connectorsConfig = Utils.cloneJSonDocument(this._stationInfo.Connectors);
438 // determine number of customized connectors
439 let lastConnector;
440 for (lastConnector in connectorsConfig) {
441 // add connector 0, OCPP specification violation that for example KEBA have
442 if (Utils.convertToInt(lastConnector) === 0 && Utils.convertToBoolean(this._stationInfo.useConnectorId0)) {
443 this._connectors[lastConnector] = connectorsConfig[lastConnector];
444 }
445 }
446 let maxConnectors = 0;
447 if (Array.isArray(this._stationInfo.numberOfConnectors)) {
448 // generate some connectors
449 maxConnectors = this._stationInfo.numberOfConnectors[(this._index - 1) % this._stationInfo.numberOfConnectors.length];
450 } else {
451 maxConnectors = this._stationInfo.numberOfConnectors;
452 }
453 // generate all connectors
454 for (let index = 1; index <= maxConnectors; index++) {
455 const randConnectorID = Utils.convertToBoolean(this._stationInfo.randomConnectors) ? Utils.getRandomInt(lastConnector, 1) : index;
456 this._connectors[index] = connectorsConfig[randConnectorID];
457 }
458 }
459
460 for (const connector in this._connectors) {
461 if (!this._connectors[connector].transactionStarted) {
462 if (this._connectors[connector].bootStatus) {
463 this.sendStatusNotificationWithTimeout(connector, this._connectors[connector].bootStatus);
464 } else {
465 this.sendStatusNotificationWithTimeout(connector, 'Available');
466 }
467 } else {
468 this.sendStatusNotificationWithTimeout(connector, 'Charging');
469 }
470 }
471
472 if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable)) {
473 if (!this._automaticTransactionGeneration) {
474 this._automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
475 }
476 if (this._automaticTransactionGeneration.timeToStop) {
477 this._automaticTransactionGeneration.start();
478 }
479 }
480 this._statistics.start();
481 }
482
483 _resetTransactionOnConnector(connectorID) {
484 this._connectors[connectorID].transactionStarted = false;
485 this._connectors[connectorID].transactionId = null;
486 this._connectors[connectorID].lastConsumptionValue = -1;
487 this._connectors[connectorID].lastSoC = -1;
488 if (this._connectors[connectorID].transactionInterval) {
489 clearInterval(this._connectors[connectorID].transactionInterval);
490 }
491 }
492
493 handleResponseBootNotification(payload) {
494 if (payload.status === 'Accepted') {
495 this._heartbeatInterval = payload.interval * 1000;
496 this._basicStartMessageSequence();
497 } else {
498 logger.info(this._basicFormatLog() + ' Boot Notification rejected');
499 }
500 }
501
502 handleResponseStartTransaction(payload, requestPayload) {
503 // Set connector transaction related attributes
504 this._connectors[requestPayload.connectorId].transactionStarted = false;
505 this._connectors[requestPayload.connectorId].idTag = requestPayload.idTag;
506
507 if (payload.idTagInfo.status === 'Accepted') {
508 for (const connector in this._connectors) {
509 if (Utils.convertToInt(connector) === Utils.convertToInt(requestPayload.connectorId)) {
510 this._connectors[connector].transactionStarted = true;
511 this._connectors[connector].transactionId = payload.transactionId;
512 this._connectors[connector].lastConsumptionValue = 0;
513 this._connectors[connector].lastSoC = 0;
514 logger.info(this._basicFormatLog() + ' Transaction ' + this._connectors[connector].transactionId + ' STARTED on ' + this._stationInfo.name + '#' + requestPayload.connectorId + ' for idTag ' + requestPayload.idTag);
515 this.sendStatusNotification(requestPayload.connectorId, 'Charging');
516 const configuredMeterValueSampleInterval = this._configuration.configurationKey.find((value) => value.key === 'MeterValueSampleInterval');
517 this.startMeterValues(requestPayload.connectorId,
518 configuredMeterValueSampleInterval ? configuredMeterValueSampleInterval.value * 1000 : 60000,
519 this);
520 }
521 }
522 } else {
523 logger.error(this._basicFormatLog() + ' Starting transaction id ' + payload.transactionId + ' REJECTED with status ' + payload.idTagInfo.status + ', idTag ' + requestPayload.idTag);
524 for (const connector in this._connectors) {
525 if (Utils.convertToInt(connector) === Utils.convertToInt(requestPayload.connectorId)) {
526 this._resetTransactionOnConnector(connector);
527 }
528 }
529 this.sendStatusNotification(requestPayload.connectorId, 'Available');
530 }
531 }
532
533 handleResponseStopTransaction(payload, requestPayload) {
534 if (payload.idTagInfo && payload.idTagInfo.status) {
535 logger.debug(this._basicFormatLog() + ' Stop transaction ' + requestPayload.transactionId + ' response status: ' + payload.idTagInfo.status);
536 } else {
537 logger.debug(this._basicFormatLog() + ' Stop transaction ' + requestPayload.transactionId + ' response status: Unknown');
538 }
539 }
540
541 handleResponseStatusNotification(payload, requestPayload) {
542 logger.debug(this._basicFormatLog() + ' Status notification response received: %j to status notification request: %j', payload, requestPayload);
543 }
544
545 handleResponseMeterValues(payload, requestPayload) {
546 logger.debug(this._basicFormatLog() + ' MeterValues response received: %j to MeterValues request: %j', payload, requestPayload);
547 }
548
549 handleResponseHeartbeat(payload, requestPayload) {
550 logger.debug(this._basicFormatLog() + ' Heartbeat response received: %j to Heartbeat request: %j', payload, requestPayload);
551 }
552
553 async handleRequest(messageId, commandName, commandPayload) {
554 let result;
555 this._statistics.addMessage(commandName, true);
556 // Call
557 if (typeof this['handle' + commandName] === 'function') {
558 try {
559 // Call the method
560 result = await this['handle' + commandName](commandPayload);
561 } catch (error) {
562 // Log
563 logger.error(this._basicFormatLog() + ' Handle request error: ' + error);
564 // Send back response to inform backend
565 await this.sendError(messageId, error);
566 }
567 } else {
568 // Throw exception
569 await this.sendError(messageId, new OCPPError(Constants.OCPP_ERROR_NOT_IMPLEMENTED, 'Not implemented', {}));
570 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
571 }
572 // Send response
573 await this.sendMessage(messageId, result, Constants.OCPP_JSON_CALL_RESULT_MESSAGE);
574 }
575
576 async handleGetConfiguration(commandPayload) {
577 const configurationKey = [];
578 const unknownKey = [];
579 for (const configuration of this._configuration.configurationKey) {
580 if (Utils.isUndefined(configuration.visible)) {
581 configuration.visible = true;
582 } else {
583 configuration.visible = Utils.convertToBoolean(configuration.visible);
584 }
585 if (!configuration.visible) {
586 continue;
587 }
588 configurationKey.push({
589 key: configuration.key,
590 readonly: configuration.readonly,
591 value: configuration.value,
592 });
593 }
594 return {
595 configurationKey,
596 unknownKey,
597 };
598 }
599
600 async handleChangeConfiguration(commandPayload) {
601 const keyToChange = this._configuration.configurationKey.find((element) => element.key === commandPayload.key);
602 if (keyToChange && !Utils.convertToBoolean(keyToChange.readonly)) {
603 const keyIndex = this._configuration.configurationKey.indexOf(keyToChange);
604 this._configuration.configurationKey[keyIndex].value = commandPayload.value;
605 return Constants.OCPP_RESPONSE_ACCEPTED;
606 }
607 return Constants.OCPP_RESPONSE_REJECTED;
608 }
609
610 async handleRemoteStartTransaction(commandPayload) {
611 const transactionConnectorID = commandPayload.connectorId ? commandPayload.connectorId : '1';
612 if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
613 // Check if authorized
614 if (this._authorizedTags.find((value) => value === commandPayload.idTag)) {
615 // Authorization successful start transaction
616 setTimeout(() => this.sendStartTransaction(transactionConnectorID, commandPayload.idTag), Constants.START_TRANSACTION_TIMEOUT);
617 logger.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID + ' for idTag ' + commandPayload.idTag);
618 return Constants.OCPP_RESPONSE_ACCEPTED;
619 }
620 logger.error(this._basicFormatLog() + ' Remote starting transaction REJECTED with status ' + commandPayload.idTagInfo.status + ', idTag ' + commandPayload.idTag);
621 return Constants.OCPP_RESPONSE_REJECTED;
622 }
623 // No local authorization check required => start transaction
624 setTimeout(() => this.sendStartTransaction(transactionConnectorID, commandPayload.idTag), Constants.START_TRANSACTION_TIMEOUT);
625 logger.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID + ' for idTag ' + commandPayload.idTag);
626 return Constants.OCPP_RESPONSE_ACCEPTED;
627 }
628
629 async handleRemoteStopTransaction(commandPayload) {
630 for (const connector in this._connectors) {
631 if (this._connectors[connector].transactionId === commandPayload.transactionId) {
632 this.sendStopTransaction(commandPayload.transactionId, connector);
633 }
634 }
635 return Constants.OCPP_RESPONSE_ACCEPTED;
636 }
637
638 async sendStartTransaction(connectorID, idTag) {
639 try {
640 const payload = {
641 connectorId: connectorID,
642 idTag,
643 meterStart: 0,
644 timestamp: new Date().toISOString(),
645 };
646 return await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StartTransaction');
647 } catch (error) {
648 logger.error(this._basicFormatLog() + ' Send start transaction error: ' + error);
649 this._resetTransactionOnConnector(connectorID);
650 throw error;
651 }
652 }
653
654 async sendStopTransaction(transactionId, connectorID) {
655 try {
656 const payload = {
657 transactionId,
658 meterStop: 0,
659 timestamp: new Date().toISOString(),
660 };
661 await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StopTransaction');
662 logger.info(this._basicFormatLog() + ' Transaction ' + this._connectors[connectorID].transactionId + ' STOPPED on ' + this._stationInfo.name + '#' + connectorID);
663 this.sendStatusNotification(connectorID, 'Available');
664 } catch (error) {
665 logger.error(this._basicFormatLog() + ' Send stop transaction error: ' + error);
666 throw error;
667 } finally {
668 this._resetTransactionOnConnector(connectorID);
669 }
670 }
671
672 // eslint-disable-next-line class-methods-use-this
673 async sendMeterValues(connectorID, interval, self) {
674 try {
675 const sampledValueLcl = {
676 timestamp: new Date().toISOString(),
677 };
678 const meterValuesClone = Utils.cloneJSonDocument(self._getConnector(connectorID).MeterValues);
679 if (Array.isArray(meterValuesClone)) {
680 sampledValueLcl.sampledValue = meterValuesClone;
681 } else {
682 sampledValueLcl.sampledValue = [meterValuesClone];
683 }
684 for (let index = 0; index < sampledValueLcl.sampledValue.length; index++) {
685 if (sampledValueLcl.sampledValue[index].measurand && sampledValueLcl.sampledValue[index].measurand === 'SoC') {
686 sampledValueLcl.sampledValue[index].value = Math.floor(Math.random() * 100) + 1;
687 if (sampledValueLcl.sampledValue[index].value > 100) {
688 logger.info(self._basicFormatLog() + ' MeterValues measurand: ' +
689 sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register' +
690 ', value: ' + sampledValueLcl.sampledValue[index].value);
691 }
692 } else {
693 // Persist previous value in connector
694 const connector = self._connectors[connectorID];
695 let consumption;
696 consumption = Utils.getRandomInt(self._stationInfo.maxPower / 3600000 * interval, 4);
697 if (connector && connector.lastConsumptionValue >= 0) {
698 connector.lastConsumptionValue += consumption;
699 } else {
700 connector.lastConsumptionValue = 0;
701 }
702 consumption = Math.round(connector.lastConsumptionValue * 3600 / interval);
703 logger.info(self._basicFormatLog() + ' MeterValues: connectorID ' + connectorID + ', transaction ' + connector.transactionId + ', value ' + connector.lastConsumptionValue);
704 sampledValueLcl.sampledValue[index].value = connector.lastConsumptionValue;
705 if (sampledValueLcl.sampledValue[index].value > (self._stationInfo.maxPower * 3600 / interval) || sampledValueLcl.sampledValue[index].value < 500) {
706 logger.info(self._basicFormatLog() + ' MeterValues measurand: ' +
707 sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register' +
708 ', value: ' + sampledValueLcl.sampledValue[index].value + '/' + (self._stationInfo.maxPower * 3600 / interval));
709 }
710 }
711 }
712
713 const payload = {
714 connectorId: connectorID,
715 transactionId: self._connectors[connectorID].transactionId,
716 meterValue: [sampledValueLcl],
717 };
718 await self.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'MeterValues');
719 } catch (error) {
720 logger.error(self._basicFormatLog() + ' Send MeterValues error: ' + error);
721 }
722 }
723
724 async startMeterValues(connectorID, interval, self) {
725 if (!this._connectors[connectorID].transactionStarted) {
726 logger.debug(`${self._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction started`);
727 } else if (this._connectors[connectorID].transactionStarted && !this._connectors[connectorID].transactionId) {
728 logger.debug(`${self._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction id`);
729 }
730 this._connectors[connectorID].transactionInterval = setInterval(async () => {
731 const sendMeterValues = performance.timerify(this.sendMeterValues);
732 this._performanceObserver.observe({
733 entryTypes: ['function'],
734 });
735 await sendMeterValues(connectorID, interval, self);
736 }, interval);
737 }
738
739 hasAuthorizedTags() {
740 return Array.isArray(this._authorizedTags) && this._authorizedTags.length > 0;
741 }
742
743 getRandomTagId() {
744 const index = Math.round(Math.floor(Math.random() * this._authorizedTags.length - 1));
745 return this._authorizedTags[index];
746 }
747
748 _getConnector(number) {
749 return this._stationInfo.Connectors[number];
750 }
751 }
752
753 module.exports = ChargingStation;