Update README.md
[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._loadAndGetAuthorizedTags();
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.chargePointSerialNumberPrefix ? this._stationInfo.chargePointSerialNumberPrefix : '',
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 _loadAndGetAuthorizedTags() {
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._loadAndGetAuthorizedTags();
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 this._addConfigurationKey('HeartBeatInterval', Utils.convertToInt(this._heartbeatInterval ? this._heartbeatInterval : 0));
99 this._addConfigurationKey('HeartbeatInterval', Utils.convertToInt(this._heartbeatInterval ? this._heartbeatInterval : 0), false, false);
100 this._addConfigurationKey('NumberOfConnectors', this._getMaxConnectors(), true);
101 } catch (error) {
102 logger.error(this._basicFormatLog() + ' Charging station template file monitoring error: ' + error);
103 }
104 });
105 }
106
107 _getSupervisionURL() {
108 const supervisionUrls = Utils.cloneJSonDocument(this._stationInfo.supervisionURL ? this._stationInfo.supervisionURL : Configuration.getSupervisionURLs());
109 let indexUrl = 0;
110 if (Array.isArray(supervisionUrls)) {
111 if (Configuration.getDistributeStationToTenantEqually()) {
112 indexUrl = this._index % supervisionUrls.length;
113 } else {
114 // Get a random url
115 indexUrl = Math.floor(Math.random() * supervisionUrls.length);
116 }
117 return supervisionUrls[indexUrl];
118 }
119 return supervisionUrls;
120 }
121
122 _getStationName(stationTemplate) {
123 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + ('000000000' + this._index).substr(('000000000' + this._index).length - 4);
124 }
125
126 _getAuthorizeRemoteTxRequests() {
127 const authorizeRemoteTxRequests = this._getConfigurationKey('AuthorizeRemoteTxRequests');
128 return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false;
129 }
130
131 _getLocalAuthListEnabled() {
132 const localAuthListEnabled = this._getConfigurationKey('LocalAuthListEnabled');
133 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
134 }
135
136 _buildStationInfo() {
137 let stationTemplateFromFile;
138 try {
139 // Load template file
140 const fileDescriptor = fs.openSync(this._stationTemplateFile, 'r');
141 stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8'));
142 fs.closeSync(fileDescriptor);
143 } catch (error) {
144 logger.error(this._basicFormatLog() + ' Template file loading error: ' + error);
145 }
146 const stationTemplate = stationTemplateFromFile || {};
147 if (Array.isArray(stationTemplateFromFile.power)) {
148 stationTemplate.maxPower = stationTemplateFromFile.power[Math.floor(Math.random() * stationTemplateFromFile.power.length)];
149 } else {
150 stationTemplate.maxPower = stationTemplateFromFile.power;
151 }
152 stationTemplate.name = this._getStationName(stationTemplateFromFile);
153 return stationTemplate;
154 }
155
156 async start() {
157 this._url = this._supervisionUrl + '/' + this._stationInfo.name;
158 this._wsConnection = new WebSocket(this._url, 'ocpp1.6');
159 logger.info(this._basicFormatLog() + ' Will communicate with ' + this._supervisionUrl);
160 // Monitor authorization file
161 this._startAuthorizationFileMonitoring();
162 // Monitor station template file
163 this._startStationTemplateFileMonitoring();
164 // Handle Socket incoming messages
165 this._wsConnection.on('message', this.onMessage.bind(this));
166 // Handle Socket error
167 this._wsConnection.on('error', this.onError.bind(this));
168 // Handle Socket close
169 this._wsConnection.on('close', this.onClose.bind(this));
170 // Handle Socket opening connection
171 this._wsConnection.on('open', this.onOpen.bind(this));
172 // Handle Socket ping
173 this._wsConnection.on('ping', this.onPing.bind(this));
174 }
175
176 onOpen() {
177 logger.info(`${this._basicFormatLog()} Is connected to server through ${this._url}`);
178 if (!this._heartbeatInterval) {
179 // Send BootNotification
180 try {
181 this.sendMessage(Utils.generateUUID(), this._bootNotificationMessage, Constants.OCPP_JSON_CALL_MESSAGE, 'BootNotification');
182 } catch (error) {
183 logger.error(this._basicFormatLog() + ' Send boot notification error: ' + error);
184 }
185 }
186 if (this._isSocketRestart) {
187 this._basicStartMessageSequence();
188 if (this._messageQueue.length > 0) {
189 this._messageQueue.forEach((message) => {
190 if (this._wsConnection.readyState === WebSocket.OPEN) {
191 this._wsConnection.send(message);
192 }
193 });
194 }
195 }
196 this._autoReconnectRetryCount = 0;
197 this._isSocketRestart = false;
198 }
199
200 onError(error) {
201 switch (error) {
202 case 'ECONNREFUSED':
203 this._isSocketRestart = true;
204 this._reconnect(error);
205 break;
206 default:
207 logger.error(this._basicFormatLog() + ' Socket error: ' + error);
208 break;
209 }
210 }
211
212 onClose(error) {
213 switch (error) {
214 case 1000: // Normal close
215 case 1005:
216 logger.info(this._basicFormatLog() + ' Socket normally closed ' + error);
217 this._autoReconnectRetryCount = 0;
218 break;
219 default: // Abnormal close
220 this._isSocketRestart = true;
221 this._reconnect(error);
222 break;
223 }
224 }
225
226 onPing() {
227 logger.debug(this._basicFormatLog() + ' Has received a WS ping (rfc6455) from the server');
228 }
229
230 async onMessage(message) {
231 let [messageType, messageId, commandName, commandPayload, errorDetails] = [0, '', Constants.ENTITY_CHARGING_STATION, '', ''];
232 try {
233 // Parse the message
234 [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(message);
235
236 // Check the Type of message
237 switch (messageType) {
238 // Incoming Message
239 case Constants.OCPP_JSON_CALL_MESSAGE:
240 // Process the call
241 await this.handleRequest(messageId, commandName, commandPayload);
242 break;
243 // Outcome Message
244 case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
245 // Respond
246 // eslint-disable-next-line no-case-declarations
247 let responseCallback; let requestPayload;
248 if (Utils.isIterable(this._requests[messageId])) {
249 [responseCallback, , requestPayload] = this._requests[messageId];
250 } else {
251 throw new Error(`Response request for unknown message id ${messageId} is not iterable`);
252 }
253 if (!responseCallback) {
254 // Error
255 throw new Error(`Response for unknown message id ${messageId}`);
256 }
257 delete this._requests[messageId];
258 responseCallback(commandName, requestPayload);
259 break;
260 // Error Message
261 case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
262 if (!this._requests[messageId]) {
263 // Error
264 throw new Error(`Error for unknown message id ${messageId}`);
265 }
266 // eslint-disable-next-line no-case-declarations
267 let rejectCallback;
268 if (Utils.isIterable(this._requests[messageId])) {
269 [, rejectCallback] = this._requests[messageId];
270 } else {
271 throw new Error(`Error request for unknown message id ${messageId} is not iterable`);
272 }
273 delete this._requests[messageId];
274 rejectCallback(new OCPPError(commandName, commandPayload, errorDetails));
275 break;
276 // Error
277 default:
278 throw new Error(`Wrong message type ${messageType}`);
279 }
280 } catch (error) {
281 // Log
282 logger.error('%s Incoming message %j processing error %s on request content %s', this._basicFormatLog(), message, error, this._requests[messageId]);
283 // Send error
284 // await this.sendError(messageId, error);
285 }
286 }
287
288 // eslint-disable-next-line class-methods-use-this
289 async _startHeartbeat(self) {
290 if (self._heartbeatInterval && !self._heartbeatSetInterval) {
291 self._heartbeatSetInterval = setInterval(() => {
292 try {
293 const payload = {
294 currentTime: new Date().toISOString(),
295 };
296 self.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'Heartbeat');
297 } catch (error) {
298 logger.error(self._basicFormatLog() + ' Send heartbeat error: ' + error);
299 }
300 }, self._heartbeatInterval);
301 logger.info(self._basicFormatLog() + ' Heartbeat started every ' + self._heartbeatInterval + 'ms');
302 } else {
303 logger.error(self._basicFormatLog() + ' Heartbeat interval undefined, not starting the heartbeat');
304 }
305 }
306
307 _reconnect(error) {
308 logger.error(this._basicFormatLog() + ' Socket: abnormally closed', error);
309 // Stop heartbeat
310 if (this._heartbeatSetInterval) {
311 clearInterval(this._heartbeatSetInterval);
312 this._heartbeatSetInterval = null;
313 }
314 // Stop the ATG if needed
315 if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable) &&
316 Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure) &&
317 this._automaticTransactionGeneration &&
318 !this._automaticTransactionGeneration.timeToStop) {
319 this._automaticTransactionGeneration.stop();
320 }
321 if (this._autoReconnectTimeout !== 0 &&
322 (this._autoReconnectRetryCount < this._autoReconnectMaxRetries || this._autoReconnectMaxRetries === -1)) {
323 logger.error(`${this._basicFormatLog()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
324 this._autoReconnectRetryCount++;
325 setTimeout(() => {
326 logger.error(this._basicFormatLog() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount);
327 this.start();
328 }, this._autoReconnectTimeout);
329 } else if (this._autoReconnectTimeout !== 0 || this._autoReconnectMaxRetries !== -1) {
330 logger.error(`${this._basicFormatLog()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
331 }
332 }
333
334 sendError(messageId, err) {
335 // Check exception: only OCPP error are accepted
336 const error = err instanceof OCPPError ? err : new OCPPError(Constants.OCPP_ERROR_INTERNAL_ERROR, err.message);
337 // Send error
338 return this.sendMessage(messageId, error, Constants.OCPP_JSON_CALL_ERROR_MESSAGE);
339 }
340
341 async sendStatusNotification(connectorId, status, errorCode = 'NoError') {
342 try {
343 const payload = {
344 connectorId,
345 errorCode,
346 status,
347 };
348 await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StatusNotification');
349 } catch (error) {
350 logger.error(this._basicFormatLog() + ' Send status error: ' + error);
351 }
352 }
353
354 async sendStatusNotificationWithTimeout(connectorId, status, errorCode = 'NoError', timeout = Constants.STATUS_NOTIFICATION_TIMEOUT) {
355 setTimeout(() => this.sendStatusNotification(connectorId, status, errorCode), timeout);
356 }
357
358 sendMessage(messageId, command, messageType = Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName = '') {
359 // Send a message through wsConnection
360 const self = this;
361 // Create a promise
362 return new Promise((resolve, reject) => {
363 let messageToSend;
364 // Type of message
365 switch (messageType) {
366 // Request
367 case Constants.OCPP_JSON_CALL_MESSAGE:
368 this._statistics.addMessage(commandName);
369 // Build request
370 this._requests[messageId] = [responseCallback, rejectCallback, command];
371 messageToSend = JSON.stringify([messageType, messageId, commandName, command]);
372 break;
373 // Response
374 case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
375 this._statistics.addMessage(commandName);
376 // Build response
377 messageToSend = JSON.stringify([messageType, messageId, command]);
378 break;
379 // Error Message
380 case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
381 // Build Message
382 this._statistics.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName || ''}`);
383 messageToSend = JSON.stringify([messageType, messageId, command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR, command.message ? command.message : '', command.details ? command.details : {}]);
384 break;
385 }
386 // Check if wsConnection is ready
387 if (this._wsConnection.readyState === WebSocket.OPEN) {
388 // Yes: Send Message
389 this._wsConnection.send(messageToSend);
390 } else {
391 // Buffer message until connection is back
392 this._messageQueue.push(messageToSend);
393 }
394 // Request?
395 if (messageType !== Constants.OCPP_JSON_CALL_MESSAGE) {
396 // Yes: send Ok
397 resolve();
398 } else if (this._wsConnection.readyState === WebSocket.OPEN) {
399 // Send timeout in case connection is open otherwise wait for ever
400 // FIXME: Handle message on timeout
401 setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants.OCPP_SOCKET_TIMEOUT);
402 }
403
404 // Function that will receive the request's response
405 function responseCallback(payload, requestPayload) {
406 self._statistics.addMessage(commandName, true);
407 const responseCallbackFn = 'handleResponse' + commandName;
408 if (typeof self[responseCallbackFn] === 'function') {
409 self[responseCallbackFn](payload, requestPayload, self);
410 } else {
411 logger.debug(self._basicFormatLog() + ' Trying to call an undefined response callback function: ' + responseCallbackFn);
412 }
413 // Send the response
414 resolve(payload);
415 }
416
417 // Function that will receive the request's rejection
418 function rejectCallback(reason) {
419 self._statistics.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName || ''}`, true);
420 // Build Exception
421 // eslint-disable-next-line no-empty-function
422 self._requests[messageId] = [() => { }, () => { }, '']; // Properly format the request
423 const error = reason instanceof OCPPError ? reason : new Error(reason);
424 // Send error
425 reject(error);
426 }
427 });
428 }
429
430 async _basicStartMessageSequence() {
431 // Start heartbeat
432 this._startHeartbeat(this);
433 // Build connectors
434 if (!this._connectors) {
435 this._connectors = {};
436 const connectorsConfig = Utils.cloneJSonDocument(this._stationInfo.Connectors);
437 // Determine number of customized connectors
438 let lastConnector;
439 for (lastConnector in connectorsConfig) {
440 // Add connector 0, OCPP specification violation that for example KEBA have
441 if (Utils.convertToInt(lastConnector) === 0 && Utils.convertToBoolean(this._stationInfo.useConnectorId0) &&
442 connectorsConfig[lastConnector]) {
443 this._connectors[lastConnector] = connectorsConfig[lastConnector];
444 }
445 }
446 const maxConnectors = this._getMaxConnectors();
447 this._addConfigurationKey('NumberOfConnectors', maxConnectors, true);
448 // Generate all connectors
449 for (let index = 1; index <= maxConnectors; index++) {
450 const randConnectorID = Utils.convertToBoolean(this._stationInfo.randomConnectors) ? Utils.getRandomInt(lastConnector, 1) : index;
451 this._connectors[index] = connectorsConfig[randConnectorID];
452 }
453 }
454
455 for (const connector in this._connectors) {
456 if (!this._connectors[connector].transactionStarted) {
457 if (this._connectors[connector].bootStatus) {
458 this.sendStatusNotificationWithTimeout(connector, this._connectors[connector].bootStatus);
459 } else {
460 this.sendStatusNotificationWithTimeout(connector, 'Available');
461 }
462 } else {
463 this.sendStatusNotificationWithTimeout(connector, 'Charging');
464 }
465 }
466
467 if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable)) {
468 if (!this._automaticTransactionGeneration) {
469 this._automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
470 }
471 if (this._automaticTransactionGeneration.timeToStop) {
472 this._automaticTransactionGeneration.start();
473 }
474 }
475 this._statistics.start();
476 }
477
478 _resetTransactionOnConnector(connectorID) {
479 this._connectors[connectorID].transactionStarted = false;
480 this._connectors[connectorID].transactionId = null;
481 this._connectors[connectorID].idTag = null;
482 this._connectors[connectorID].lastConsumptionValue = -1;
483 this._connectors[connectorID].lastSoC = -1;
484 if (this._connectors[connectorID].transactionSetInterval) {
485 clearInterval(this._connectors[connectorID].transactionSetInterval);
486 }
487 }
488
489 handleResponseBootNotification(payload) {
490 if (payload.status === 'Accepted') {
491 this._heartbeatInterval = payload.interval * 1000;
492 this._addConfigurationKey('HeartBeatInterval', Utils.convertToInt(payload.interval));
493 this._addConfigurationKey('HeartbeatInterval', Utils.convertToInt(payload.interval), false, false);
494 this._basicStartMessageSequence();
495 } else {
496 logger.info(this._basicFormatLog() + ' Boot Notification rejected');
497 }
498 }
499
500 handleResponseStartTransaction(payload, requestPayload) {
501 if (this._connectors[requestPayload.connectorId].transactionStarted) {
502 logger.debug(this._basicFormatLog() + ' Try to start a transaction on an already used connector ' + requestPayload.connectorId + ' by transaction ' + this._connectors[requestPayload.connectorId].transactionId);
503 }
504
505 let transactionConnectorId;
506 for (const connector in this._connectors) {
507 if (Utils.convertToInt(connector) === Utils.convertToInt(requestPayload.connectorId)) {
508 transactionConnectorId = connector;
509 break;
510 }
511 }
512 if (!transactionConnectorId) {
513 logger.error(this._basicFormatLog() + ' Try to start a transaction on a non existing connector Id ' + requestPayload.connectorId);
514 return;
515 }
516 if (payload.idTagInfo && payload.idTagInfo.status === 'Accepted') {
517 this._connectors[transactionConnectorId].transactionStarted = true;
518 this._connectors[transactionConnectorId].transactionId = payload.transactionId;
519 this._connectors[transactionConnectorId].idTag = requestPayload.idTag;
520 this._connectors[transactionConnectorId].lastConsumptionValue = 0;
521 this._connectors[transactionConnectorId].lastSoC = 0;
522 this.sendStatusNotification(requestPayload.connectorId, 'Charging');
523 logger.info(this._basicFormatLog() + ' Transaction ' + this._connectors[transactionConnectorId].transactionId + ' STARTED on ' + this._stationInfo.name + '#' + requestPayload.connectorId + ' for idTag ' + requestPayload.idTag);
524 const configuredMeterValueSampleInterval = this._getConfigurationKey('MeterValueSampleInterval');
525 this.startMeterValues(requestPayload.connectorId,
526 configuredMeterValueSampleInterval ? configuredMeterValueSampleInterval.value * 1000 : 60000);
527 } else {
528 logger.error(this._basicFormatLog() + ' Starting transaction id ' + payload.transactionId + ' REJECTED with status ' + payload.idTagInfo.status + ', idTag ' + requestPayload.idTag);
529 this._resetTransactionOnConnector(transactionConnectorId);
530 this.sendStatusNotification(requestPayload.connectorId, 'Available');
531 }
532 }
533
534 handleResponseStopTransaction(payload, requestPayload) {
535 let transactionConnectorId;
536 for (const connector in this._connectors) {
537 if (this._connectors[connector].transactionId === requestPayload.transactionId) {
538 transactionConnectorId = connector;
539 break;
540 }
541 }
542 if (!transactionConnectorId) {
543 logger.error(this._basicFormatLog() + ' Try to stop a non existing transaction ' + requestPayload.transactionId);
544 return;
545 }
546 if (payload.idTagInfo && payload.idTagInfo.status === 'Accepted') {
547 this.sendStatusNotification(transactionConnectorId, 'Available');
548 logger.info(this._basicFormatLog() + ' Transaction ' + this._connectors[transactionConnectorId].transactionId + ' STOPPED on ' + this._stationInfo.name + '#' + transactionConnectorId);
549 this._resetTransactionOnConnector(transactionConnectorId);
550 } else {
551 logger.error(this._basicFormatLog() + ' Stopping transaction id ' + this._connectors[transactionConnectorId].transactionId + ' REJECTED with status ' + payload.idTagInfo.status);
552 }
553 }
554
555 handleResponseStatusNotification(payload, requestPayload) {
556 logger.debug(this._basicFormatLog() + ' Status notification response received: %j to status notification request: %j', payload, requestPayload);
557 }
558
559 handleResponseMeterValues(payload, requestPayload) {
560 logger.debug(this._basicFormatLog() + ' MeterValues response received: %j to MeterValues request: %j', payload, requestPayload);
561 }
562
563 handleResponseHeartbeat(payload, requestPayload) {
564 logger.debug(this._basicFormatLog() + ' Heartbeat response received: %j to Heartbeat request: %j', payload, requestPayload);
565 }
566
567 async handleRequest(messageId, commandName, commandPayload) {
568 let result;
569 this._statistics.addMessage(commandName, true);
570 // Call
571 if (typeof this['handle' + commandName] === 'function') {
572 try {
573 // Call the method
574 result = await this['handle' + commandName](commandPayload);
575 } catch (error) {
576 // Log
577 logger.error(this._basicFormatLog() + ' Handle request error: ' + error);
578 // Send back response to inform backend
579 await this.sendError(messageId, error);
580 }
581 } else {
582 // Throw exception
583 await this.sendError(messageId, new OCPPError(Constants.OCPP_ERROR_NOT_IMPLEMENTED, 'Not implemented', {}));
584 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
585 }
586 // Send response
587 await this.sendMessage(messageId, result, Constants.OCPP_JSON_CALL_RESULT_MESSAGE);
588 }
589
590 _getConfigurationKey(key) {
591 return this._configuration.configurationKey.find((configElement) => configElement.key === key);
592 }
593
594 _addConfigurationKey(key, value, readonly = false, visible = true, reboot = false) {
595 const keyFound = this._getConfigurationKey(key);
596 if (!keyFound) {
597 this._configuration.configurationKey.push({
598 key,
599 readonly,
600 value,
601 visible,
602 reboot,
603 });
604 }
605 }
606
607 _setConfigurationKeyValue(key, value) {
608 const keyFound = this._getConfigurationKey(key);
609 if (keyFound) {
610 const keyIndex = this._configuration.configurationKey.indexOf(keyFound);
611 this._configuration.configurationKey[keyIndex].value = value;
612 }
613 }
614
615 async handleGetConfiguration(commandPayload) {
616 const configurationKey = [];
617 const unknownKey = [];
618 if (Utils.isEmptyArray(commandPayload.key)) {
619 for (const configuration of this._configuration.configurationKey) {
620 if (Utils.isUndefined(configuration.visible)) {
621 configuration.visible = true;
622 } else {
623 configuration.visible = Utils.convertToBoolean(configuration.visible);
624 }
625 if (!configuration.visible) {
626 continue;
627 }
628 configurationKey.push({
629 key: configuration.key,
630 readonly: configuration.readonly,
631 value: configuration.value,
632 });
633 }
634 } else {
635 for (const configurationKey of commandPayload.key) {
636 const keyFound = this._getConfigurationKey(configurationKey);
637 if (keyFound) {
638 if (Utils.isUndefined(keyFound.visible)) {
639 keyFound.visible = true;
640 } else {
641 keyFound.visible = Utils.convertToBoolean(configurationKey.visible);
642 }
643 if (!keyFound.visible) {
644 continue;
645 }
646 configurationKey.push({
647 key: keyFound.key,
648 readonly: keyFound.readonly,
649 value: keyFound.value,
650 });
651 } else {
652 unknownKey.push(configurationKey);
653 }
654 }
655 }
656 return {
657 configurationKey,
658 unknownKey,
659 };
660 }
661
662 async handleChangeConfiguration(commandPayload) {
663 const keyToChange = this._getConfigurationKey(commandPayload.key);
664 if (!keyToChange) {
665 return {status: Constants.OCPP_ERROR_NOT_SUPPORTED};
666 } else if (keyToChange && Utils.convertToBoolean(keyToChange.readonly)) {
667 return Constants.OCPP_RESPONSE_REJECTED;
668 } else if (keyToChange && !Utils.convertToBoolean(keyToChange.readonly)) {
669 const keyIndex = this._configuration.configurationKey.indexOf(keyToChange);
670 this._configuration.configurationKey[keyIndex].value = commandPayload.value;
671 let triggerHeartbeatRestart = false;
672 if (keyToChange.key === 'HeartBeatInterval') {
673 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload.value);
674 triggerHeartbeatRestart = true;
675 }
676 if (keyToChange.key === 'HeartbeatInterval') {
677 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload.value);
678 triggerHeartbeatRestart = true;
679 }
680 if (triggerHeartbeatRestart) {
681 this._heartbeatInterval = Utils.convertToInt(commandPayload.value) * 1000;
682 // Stop heartbeat
683 if (this._heartbeatSetInterval) {
684 clearInterval(this._heartbeatSetInterval);
685 this._heartbeatSetInterval = null;
686 }
687 // Start heartbeat
688 this._startHeartbeat(this);
689 }
690 if (Utils.convertToBoolean(keyToChange.reboot)) {
691 return Constants.OCPP_RESPONSE_REBOOT_REQUIRED;
692 }
693 return Constants.OCPP_RESPONSE_ACCEPTED;
694 }
695 }
696
697 async handleRemoteStartTransaction(commandPayload) {
698 const transactionConnectorID = commandPayload.connectorId ? commandPayload.connectorId : '1';
699 if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
700 // Check if authorized
701 if (this._authorizedTags.find((value) => value === commandPayload.idTag)) {
702 // Authorization successful start transaction
703 this.sendStartTransactionWithTimeout(transactionConnectorID, commandPayload.idTag, Constants.START_TRANSACTION_TIMEOUT);
704 logger.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID + ' for idTag ' + commandPayload.idTag);
705 return Constants.OCPP_RESPONSE_ACCEPTED;
706 }
707 logger.error(this._basicFormatLog() + ' Remote starting transaction REJECTED with status ' + commandPayload.idTagInfo.status + ', idTag ' + commandPayload.idTag);
708 return Constants.OCPP_RESPONSE_REJECTED;
709 }
710 // No local authorization check required => start transaction
711 this.sendStartTransactionWithTimeout(transactionConnectorID, commandPayload.idTag, Constants.START_TRANSACTION_TIMEOUT);
712 logger.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID + ' for idTag ' + commandPayload.idTag);
713 return Constants.OCPP_RESPONSE_ACCEPTED;
714 }
715
716 async handleRemoteStopTransaction(commandPayload) {
717 for (const connector in this._connectors) {
718 if (this._connectors[connector].transactionId === commandPayload.transactionId) {
719 this.sendStopTransaction(commandPayload.transactionId);
720 return Constants.OCPP_RESPONSE_ACCEPTED;
721 }
722 }
723 logger.info(this._basicFormatLog() + ' Try to stop remotely a non existing transaction ' + commandPayload.transactionId);
724 return Constants.OCPP_RESPONSE_REJECTED;
725 }
726
727 async sendStartTransaction(connectorID, idTag) {
728 try {
729 const payload = {
730 connectorId: connectorID,
731 idTag,
732 meterStart: 0,
733 timestamp: new Date().toISOString(),
734 };
735 return await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StartTransaction');
736 } catch (error) {
737 logger.error(this._basicFormatLog() + ' Send start transaction error: ' + error);
738 throw error;
739 }
740 }
741 async sendStartTransactionWithTimeout(connectorID, idTag, timeout) {
742 setTimeout(() => this.sendStartTransaction(connectorID, idTag), timeout);
743 }
744
745 async sendStopTransaction(transactionId) {
746 try {
747 const payload = {
748 transactionId,
749 meterStop: 0,
750 timestamp: new Date().toISOString(),
751 };
752 await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StopTransaction');
753 } catch (error) {
754 logger.error(this._basicFormatLog() + ' Send stop transaction error: ' + error);
755 throw error;
756 }
757 }
758
759 // eslint-disable-next-line class-methods-use-this
760 async sendMeterValues(connectorID, interval, self, debug = false) {
761 try {
762 const sampledValueLcl = {
763 timestamp: new Date().toISOString(),
764 };
765 const meterValuesClone = Utils.cloneJSonDocument(self._getConnector(connectorID).MeterValues);
766 if (Array.isArray(meterValuesClone)) {
767 sampledValueLcl.sampledValue = meterValuesClone;
768 } else {
769 sampledValueLcl.sampledValue = [meterValuesClone];
770 }
771 for (let index = 0; index < sampledValueLcl.sampledValue.length; index++) {
772 const connector = self._connectors[connectorID];
773 if (sampledValueLcl.sampledValue[index].measurand && sampledValueLcl.sampledValue[index].measurand === 'SoC') {
774 sampledValueLcl.sampledValue[index].value = Utils.getRandomInt(100);
775 if (sampledValueLcl.sampledValue[index].value > 100 || debug) {
776 logger.error(`${self._basicFormatLog()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: connectorID ${connectorID}, transaction ${connector.transactionId}, value: ${sampledValueLcl.sampledValue[index].value}`);
777 }
778 } else {
779 // Persist previous value in connector
780 const consumption = Utils.getRandomInt(self._stationInfo.maxPower / 3600000 * interval);
781 if (connector && connector.lastConsumptionValue >= 0) {
782 connector.lastConsumptionValue += consumption;
783 } else {
784 connector.lastConsumptionValue = 0;
785 }
786 const maxConsumption = self._stationInfo.maxPower * 3600 / interval;
787 logger.info(`${self._basicFormatLog()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: connectorID ${connectorID}, transaction ${connector.transactionId}, value ${connector.lastConsumptionValue}`);
788 sampledValueLcl.sampledValue[index].value = connector.lastConsumptionValue;
789 if (sampledValueLcl.sampledValue[index].value > maxConsumption || debug) {
790 logger.error(`${self._basicFormatLog()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: connectorID ${connectorID}, transaction ${connector.transactionId}, value: ${sampledValueLcl.sampledValue[index].value}/${maxConsumption}`);
791 }
792 }
793 }
794
795 const payload = {
796 connectorId: connectorID,
797 transactionId: self._connectors[connectorID].transactionId,
798 meterValue: [sampledValueLcl],
799 };
800 await self.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'MeterValues');
801 } catch (error) {
802 logger.error(self._basicFormatLog() + ' Send MeterValues error: ' + error);
803 }
804 }
805
806 async startMeterValues(connectorID, interval) {
807 if (!this._connectors[connectorID].transactionStarted) {
808 logger.error(`${this._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction started`);
809 return;
810 } else if (this._connectors[connectorID].transactionStarted && !this._connectors[connectorID].transactionId) {
811 logger.error(`${this._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction id`);
812 return;
813 }
814 this._connectors[connectorID].transactionSetInterval = setInterval(async () => {
815 const sendMeterValues = performance.timerify(this.sendMeterValues);
816 this._performanceObserver.observe({
817 entryTypes: ['function'],
818 });
819 await sendMeterValues(connectorID, interval, this);
820 }, interval);
821 }
822
823 hasAuthorizedTags() {
824 return !Utils.isEmptyArray(this._authorizedTags);
825 }
826
827 getRandomTagId() {
828 const index = Math.floor(Math.random() * this._authorizedTags.length);
829 return this._authorizedTags[index];
830 }
831
832 _getConnector(number) {
833 return this._stationInfo.Connectors[number];
834 }
835
836 _getMaxConnectors() {
837 let maxConnectors = 0;
838 if (Array.isArray(this._stationInfo.numberOfConnectors)) {
839 // Generate some connectors
840 maxConnectors = this._stationInfo.numberOfConnectors[(this._index - 1) % this._stationInfo.numberOfConnectors.length];
841 } else {
842 maxConnectors = this._stationInfo.numberOfConnectors;
843 }
844 return maxConnectors;
845 }
846 }
847
848 module.exports = ChargingStation;