Fix unit conversion.
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.js
CommitLineData
7dde0b73
JB
1const Configuration = require('../utils/Configuration');
2const logger = require('../utils/Logger');
3const WebSocket = require('ws');
f7869514 4const Constants = require('../utils/Constants');
7dde0b73
JB
5const Utils = require('../utils/Utils');
6const OCPPError = require('./OcppError');
7dde0b73
JB
7const AutomaticTransactionGenerator = require('./AutomaticTransactionGenerator');
8const Statistics = require('../utils/Statistics');
9const fs = require('fs');
10const {performance, PerformanceObserver} = require('perf_hooks');
11
12class ChargingStation {
2e6f5966
JB
13 constructor(index, stationTemplateFile) {
14 this._index = index;
15 this._stationTemplateFile = stationTemplateFile;
16 this._initialize();
17
7dde0b73
JB
18 this._autoReconnectRetryCount = 0;
19 this._autoReconnectMaxRetries = Configuration.getAutoReconnectMaxRetries(); // -1 for unlimited
20 this._autoReconnectTimeout = Configuration.getAutoReconnectTimeout() * 1000; // ms, zero for disabling
2e6f5966
JB
21
22 this._requests = {};
23 this._messageQueue = [];
24
7dde0b73 25 this._isSocketRestart = false;
34dcb3b5 26
83045896 27 this._authorizedTags = this._loadAndGetAuthorizedTags();
2e6f5966
JB
28 }
29
30 _initialize() {
31 this._stationInfo = this._buildStationInfo();
32 this._bootNotificationMessage = {
33 chargePointModel: this._stationInfo.chargePointModel,
34 chargePointVendor: this._stationInfo.chargePointVendor,
6958152c 35 chargePointSerialNumber: this._stationInfo.chargePointSerialNumberPrefix ? this._stationInfo.chargePointSerialNumberPrefix : '',
34dcb3b5 36 firmwareVersion: this._stationInfo.firmwareVersion ? this._stationInfo.firmwareVersion : '',
2e6f5966
JB
37 };
38 this._configuration = this._getConfiguration();
2e6f5966 39 this._supervisionUrl = this._getSupervisionURL();
7dde0b73
JB
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 });
7dde0b73
JB
46 }
47
48 _basicFormatLog() {
49 return Utils.basicFormatLog(` ${this._stationInfo.name}:`);
50 }
51
2e6f5966
JB
52 _getConfiguration() {
53 return this._stationInfo.Configuration ? this._stationInfo.Configuration : {};
7dde0b73
JB
54 }
55
2e6f5966
JB
56 _getAuthorizationFile() {
57 return this._stationInfo.authorizationFile ? this._stationInfo.authorizationFile : '';
7dde0b73
JB
58 }
59
83045896 60 _loadAndGetAuthorizedTags() {
2e6f5966
JB
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
83045896 84 this._authorizedTags = this._loadAndGetAuthorizedTags();
2e6f5966
JB
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();
35f9a031
JB
98 this._addConfigurationKey('HeartBeatInterval', Utils.convertToInt(this._heartbeatInterval ? this._heartbeatInterval / 1000 : 0));
99 this._addConfigurationKey('HeartbeatInterval', Utils.convertToInt(this._heartbeatInterval ? this._heartbeatInterval / 1000 : 0), false, false);
adf3e648 100 this._addConfigurationKey('NumberOfConnectors', this._getMaxConnectors(), true);
2e6f5966
JB
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());
7dde0b73
JB
109 let indexUrl = 0;
110 if (Array.isArray(supervisionUrls)) {
2e6f5966
JB
111 if (Configuration.getDistributeStationToTenantEqually()) {
112 indexUrl = this._index % supervisionUrls.length;
7dde0b73
JB
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
2e6f5966
JB
122 _getStationName(stationTemplate) {
123 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + ('000000000' + this._index).substr(('000000000' + this._index).length - 4);
7dde0b73
JB
124 }
125
126 _getAuthorizeRemoteTxRequests() {
61c2e33d 127 const authorizeRemoteTxRequests = this._getConfigurationKey('AuthorizeRemoteTxRequests');
a6e68f34 128 return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false;
7dde0b73
JB
129 }
130
def3d48e 131 _getLocalAuthListEnabled() {
61c2e33d 132 const localAuthListEnabled = this._getConfigurationKey('LocalAuthListEnabled');
def3d48e
JB
133 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
134 }
135
2e6f5966
JB
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)];
7dde0b73 149 } else {
2e6f5966 150 stationTemplate.maxPower = stationTemplateFromFile.power;
7dde0b73 151 }
2e6f5966 152 stationTemplate.name = this._getStationName(stationTemplateFromFile);
7dde0b73
JB
153 return stationTemplate;
154 }
155
156 async start() {
34dcb3b5
JB
157 this._url = this._supervisionUrl + '/' + this._stationInfo.name;
158 this._wsConnection = new WebSocket(this._url, 'ocpp1.6');
7dde0b73 159 logger.info(this._basicFormatLog() + ' Will communicate with ' + this._supervisionUrl);
2e6f5966
JB
160 // Monitor authorization file
161 this._startAuthorizationFileMonitoring();
162 // Monitor station template file
163 this._startStationTemplateFileMonitoring();
7dde0b73
JB
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}`);
0bbcb3dc
JB
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 }
7dde0b73 186 if (this._isSocketRestart) {
027b409a 187 this._basicStartMessageSequence();
7dde0b73
JB
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 }
7dde0b73
JB
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() {
027b409a 227 logger.debug(this._basicFormatLog() + ' Has received a WS ping (rfc6455) from the server');
7dde0b73
JB
228 }
229
230 async onMessage(message) {
2d8cee5a 231 let [messageType, messageId, commandName, commandPayload, errorDetails] = [0, '', Constants.ENTITY_CHARGING_STATION, '', ''];
7dde0b73 232 try {
2d8cee5a
JB
233 // Parse the message
234 [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(message);
235
7dde0b73
JB
236 // Check the Type of message
237 switch (messageType) {
238 // Incoming Message
f7869514 239 case Constants.OCPP_JSON_CALL_MESSAGE:
7dde0b73 240 // Process the call
7dde0b73
JB
241 await this.handleRequest(messageId, commandName, commandPayload);
242 break;
243 // Outcome Message
f7869514 244 case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
7dde0b73
JB
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];
7dde0b73
JB
258 responseCallback(commandName, requestPayload);
259 break;
260 // Error Message
f7869514 261 case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
7dde0b73
JB
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
027b409a
JB
288 // eslint-disable-next-line class-methods-use-this
289 async _startHeartbeat(self) {
290 if (self._heartbeatInterval && !self._heartbeatSetInterval) {
027b409a
JB
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);
0bbcb3dc 301 logger.info(self._basicFormatLog() + ' Heartbeat started every ' + self._heartbeatInterval + 'ms');
027b409a
JB
302 } else {
303 logger.error(self._basicFormatLog() + ' Heartbeat interval undefined, not starting the heartbeat');
304 }
305 }
306
7dde0b73
JB
307 _reconnect(error) {
308 logger.error(this._basicFormatLog() + ' Socket: abnormally closed', error);
5c68da4d 309 // Stop heartbeat
7dde0b73
JB
310 if (this._heartbeatSetInterval) {
311 clearInterval(this._heartbeatSetInterval);
312 this._heartbeatSetInterval = null;
313 }
34dcb3b5
JB
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) {
7dde0b73
JB
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
7dde0b73
JB
334 sendError(messageId, err) {
335 // Check exception: only OCPP error are accepted
72766a82 336 const error = err instanceof OCPPError ? err : new OCPPError(Constants.OCPP_ERROR_INTERNAL_ERROR, err.message);
7dde0b73 337 // Send error
f7869514 338 return this.sendMessage(messageId, error, Constants.OCPP_JSON_CALL_ERROR_MESSAGE);
7dde0b73
JB
339 }
340
027b409a
JB
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
f7869514 358 sendMessage(messageId, command, messageType = Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName = '') {
7dde0b73
JB
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
f7869514 367 case Constants.OCPP_JSON_CALL_MESSAGE:
7dde0b73
JB
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
f7869514 374 case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
d3a7883e 375 this._statistics.addMessage(commandName);
7dde0b73
JB
376 // Build response
377 messageToSend = JSON.stringify([messageType, messageId, command]);
378 break;
379 // Error Message
f7869514 380 case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
7dde0b73 381 // Build Message
7de604f9 382 this._statistics.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName || ''}`);
894a1780 383 messageToSend = JSON.stringify([messageType, messageId, command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR, command.message ? command.message : '', command.details ? command.details : {}]);
7dde0b73
JB
384 break;
385 }
2e6f5966 386 // Check if wsConnection is ready
7dde0b73
JB
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?
f7869514 395 if (messageType !== Constants.OCPP_JSON_CALL_MESSAGE) {
7dde0b73
JB
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
f7869514 401 setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants.OCPP_SOCKET_TIMEOUT);
7dde0b73
JB
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 {
61c2e33d 411 logger.debug(self._basicFormatLog() + ' Trying to call an undefined response callback function: ' + responseCallbackFn);
7dde0b73
JB
412 }
413 // Send the response
414 resolve(payload);
415 }
416
417 // Function that will receive the request's rejection
418 function rejectCallback(reason) {
7de604f9 419 self._statistics.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName || ''}`, true);
7dde0b73
JB
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
027b409a 430 async _basicStartMessageSequence() {
5c68da4d 431 // Start heartbeat
7dde0b73 432 this._startHeartbeat(this);
61c2e33d 433 // Build connectors
2e6f5966 434 if (!this._connectors) {
7dde0b73 435 this._connectors = {};
2e6f5966 436 const connectorsConfig = Utils.cloneJSonDocument(this._stationInfo.Connectors);
61c2e33d 437 // Determine number of customized connectors
7dde0b73
JB
438 let lastConnector;
439 for (lastConnector in connectorsConfig) {
61c2e33d
JB
440 // Add connector 0, OCPP specification violation that for example KEBA have
441 if (Utils.convertToInt(lastConnector) === 0 && Utils.convertToBoolean(this._stationInfo.useConnectorId0) &&
d3a7883e 442 connectorsConfig[lastConnector]) {
7dde0b73
JB
443 this._connectors[lastConnector] = connectorsConfig[lastConnector];
444 }
445 }
adf3e648 446 const maxConnectors = this._getMaxConnectors();
61c2e33d
JB
447 this._addConfigurationKey('NumberOfConnectors', maxConnectors, true);
448 // Generate all connectors
7dde0b73 449 for (let index = 1; index <= maxConnectors; index++) {
34dcb3b5 450 const randConnectorID = Utils.convertToBoolean(this._stationInfo.randomConnectors) ? Utils.getRandomInt(lastConnector, 1) : index;
7dde0b73
JB
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) {
027b409a 458 this.sendStatusNotificationWithTimeout(connector, this._connectors[connector].bootStatus);
7dde0b73 459 } else {
027b409a 460 this.sendStatusNotificationWithTimeout(connector, 'Available');
7dde0b73
JB
461 }
462 } else {
027b409a 463 this.sendStatusNotificationWithTimeout(connector, 'Charging');
7dde0b73
JB
464 }
465 }
466
34dcb3b5 467 if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable)) {
7dde0b73
JB
468 if (!this._automaticTransactionGeneration) {
469 this._automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
470 }
34dcb3b5
JB
471 if (this._automaticTransactionGeneration.timeToStop) {
472 this._automaticTransactionGeneration.start();
473 }
7dde0b73
JB
474 }
475 this._statistics.start();
476 }
477
027b409a
JB
478 _resetTransactionOnConnector(connectorID) {
479 this._connectors[connectorID].transactionStarted = false;
480 this._connectors[connectorID].transactionId = null;
d3a7883e 481 this._connectors[connectorID].idTag = null;
027b409a
JB
482 this._connectors[connectorID].lastConsumptionValue = -1;
483 this._connectors[connectorID].lastSoC = -1;
d3a7883e
JB
484 if (this._connectors[connectorID].transactionSetInterval) {
485 clearInterval(this._connectors[connectorID].transactionSetInterval);
027b409a
JB
486 }
487 }
488
489 handleResponseBootNotification(payload) {
490 if (payload.status === 'Accepted') {
491 this._heartbeatInterval = payload.interval * 1000;
5c68da4d
JB
492 this._addConfigurationKey('HeartBeatInterval', Utils.convertToInt(payload.interval));
493 this._addConfigurationKey('HeartbeatInterval', Utils.convertToInt(payload.interval), false, false);
027b409a
JB
494 this._basicStartMessageSequence();
495 } else {
496 logger.info(this._basicFormatLog() + ' Boot Notification rejected');
497 }
498 }
499
7dde0b73 500 handleResponseStartTransaction(payload, requestPayload) {
d3a7883e
JB
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 }
84393381 504
7de604f9
JB
505 let transactionConnectorId;
506 for (const connector in this._connectors) {
507 if (Utils.convertToInt(connector) === Utils.convertToInt(requestPayload.connectorId)) {
508 transactionConnectorId = connector;
509 break;
7dde0b73 510 }
7de604f9
JB
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);
7dde0b73
JB
527 } else {
528 logger.error(this._basicFormatLog() + ' Starting transaction id ' + payload.transactionId + ' REJECTED with status ' + payload.idTagInfo.status + ', idTag ' + requestPayload.idTag);
7de604f9 529 this._resetTransactionOnConnector(transactionConnectorId);
7dde0b73
JB
530 this.sendStatusNotification(requestPayload.connectorId, 'Available');
531 }
532 }
533
34dcb3b5 534 handleResponseStopTransaction(payload, requestPayload) {
d3a7883e
JB
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) {
7de604f9
JB
543 logger.error(this._basicFormatLog() + ' Try to stop a non existing transaction ' + requestPayload.transactionId);
544 return;
d3a7883e
JB
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);
34dcb3b5 550 } else {
d3a7883e 551 logger.error(this._basicFormatLog() + ' Stopping transaction id ' + this._connectors[transactionConnectorId].transactionId + ' REJECTED with status ' + payload.idTagInfo.status);
34dcb3b5
JB
552 }
553 }
554
facd8ebd
JB
555 handleResponseStatusNotification(payload, requestPayload) {
556 logger.debug(this._basicFormatLog() + ' Status notification response received: %j to status notification request: %j', payload, requestPayload);
7dde0b73
JB
557 }
558
facd8ebd
JB
559 handleResponseMeterValues(payload, requestPayload) {
560 logger.debug(this._basicFormatLog() + ' MeterValues response received: %j to MeterValues request: %j', payload, requestPayload);
027b409a
JB
561 }
562
facd8ebd
JB
563 handleResponseHeartbeat(payload, requestPayload) {
564 logger.debug(this._basicFormatLog() + ' Heartbeat response received: %j to Heartbeat request: %j', payload, requestPayload);
7dde0b73
JB
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);
facd8ebd 578 // Send back response to inform backend
7dde0b73
JB
579 await this.sendError(messageId, error);
580 }
581 } else {
84393381 582 // Throw exception
f7869514 583 await this.sendError(messageId, new OCPPError(Constants.OCPP_ERROR_NOT_IMPLEMENTED, 'Not implemented', {}));
7dde0b73
JB
584 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
585 }
84393381 586 // Send response
f7869514 587 await this.sendMessage(messageId, result, Constants.OCPP_JSON_CALL_RESULT_MESSAGE);
7dde0b73
JB
588 }
589
61c2e33d
JB
590 _getConfigurationKey(key) {
591 return this._configuration.configurationKey.find((configElement) => configElement.key === key);
592 }
593
3497da01 594 _addConfigurationKey(key, value, readonly = false, visible = true, reboot = false) {
61c2e33d
JB
595 const keyFound = this._getConfigurationKey(key);
596 if (!keyFound) {
597 this._configuration.configurationKey.push({
598 key,
599 readonly,
600 value,
601 visible,
3497da01 602 reboot,
61c2e33d
JB
603 });
604 }
605 }
606
607 _setConfigurationKeyValue(key, value) {
608 const keyFound = this._getConfigurationKey(key);
609 if (keyFound) {
d3a7883e
JB
610 const keyIndex = this._configuration.configurationKey.indexOf(keyFound);
611 this._configuration.configurationKey[keyIndex].value = value;
61c2e33d
JB
612 }
613 }
614
34dcb3b5 615 async handleGetConfiguration(commandPayload) {
facd8ebd
JB
616 const configurationKey = [];
617 const unknownKey = [];
61c2e33d
JB
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 });
facd8ebd 633 }
61c2e33d 634 } else {
d20c21a0
JB
635 for (const configurationKey of commandPayload.key) {
636 const keyFound = this._getConfigurationKey(configurationKey);
61c2e33d
JB
637 if (keyFound) {
638 if (Utils.isUndefined(keyFound.visible)) {
639 keyFound.visible = true;
640 } else {
d20c21a0 641 keyFound.visible = Utils.convertToBoolean(configurationKey.visible);
61c2e33d
JB
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 {
d20c21a0 652 unknownKey.push(configurationKey);
61c2e33d 653 }
facd8ebd 654 }
facd8ebd
JB
655 }
656 return {
657 configurationKey,
658 unknownKey,
659 };
7dde0b73
JB
660 }
661
662 async handleChangeConfiguration(commandPayload) {
61c2e33d 663 const keyToChange = this._getConfigurationKey(commandPayload.key);
7d887a1b
JB
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)) {
a6e68f34
JB
669 const keyIndex = this._configuration.configurationKey.indexOf(keyToChange);
670 this._configuration.configurationKey[keyIndex].value = commandPayload.value;
d3a7883e
JB
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) {
5c68da4d
JB
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 }
7d887a1b
JB
690 if (Utils.convertToBoolean(keyToChange.reboot)) {
691 return Constants.OCPP_RESPONSE_REBOOT_REQUIRED;
692 }
dcab13bd 693 return Constants.OCPP_RESPONSE_ACCEPTED;
7dde0b73 694 }
7dde0b73
JB
695 }
696
697 async handleRemoteStartTransaction(commandPayload) {
72766a82 698 const transactionConnectorID = commandPayload.connectorId ? commandPayload.connectorId : '1';
2e6f5966 699 if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
dcab13bd 700 // Check if authorized
2e6f5966 701 if (this._authorizedTags.find((value) => value === commandPayload.idTag)) {
7dde0b73 702 // Authorization successful start transaction
61c2e33d 703 this.sendStartTransactionWithTimeout(transactionConnectorID, commandPayload.idTag, Constants.START_TRANSACTION_TIMEOUT);
027b409a 704 logger.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID + ' for idTag ' + commandPayload.idTag);
dcab13bd 705 return Constants.OCPP_RESPONSE_ACCEPTED;
7dde0b73 706 }
84393381 707 logger.error(this._basicFormatLog() + ' Remote starting transaction REJECTED with status ' + commandPayload.idTagInfo.status + ', idTag ' + commandPayload.idTag);
dcab13bd 708 return Constants.OCPP_RESPONSE_REJECTED;
7dde0b73 709 }
dcab13bd 710 // No local authorization check required => start transaction
61c2e33d 711 this.sendStartTransactionWithTimeout(transactionConnectorID, commandPayload.idTag, Constants.START_TRANSACTION_TIMEOUT);
027b409a
JB
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) {
d3a7883e
JB
719 this.sendStopTransaction(commandPayload.transactionId);
720 return Constants.OCPP_RESPONSE_ACCEPTED;
027b409a
JB
721 }
722 }
d3a7883e
JB
723 logger.info(this._basicFormatLog() + ' Try to stop remotely a non existing transaction ' + commandPayload.transactionId);
724 return Constants.OCPP_RESPONSE_REJECTED;
7dde0b73
JB
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 };
027b409a 735 return await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StartTransaction');
7dde0b73
JB
736 } catch (error) {
737 logger.error(this._basicFormatLog() + ' Send start transaction error: ' + error);
7dde0b73
JB
738 throw error;
739 }
740 }
61c2e33d
JB
741 async sendStartTransactionWithTimeout(connectorID, idTag, timeout) {
742 setTimeout(() => this.sendStartTransaction(connectorID, idTag), timeout);
743 }
7dde0b73 744
d3a7883e 745 async sendStopTransaction(transactionId) {
7dde0b73
JB
746 try {
747 const payload = {
748 transactionId,
749 meterStop: 0,
750 timestamp: new Date().toISOString(),
751 };
027b409a 752 await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StopTransaction');
7dde0b73
JB
753 } catch (error) {
754 logger.error(this._basicFormatLog() + ' Send stop transaction error: ' + error);
755 throw error;
7dde0b73
JB
756 }
757 }
758
7dde0b73 759 // eslint-disable-next-line class-methods-use-this
7de604f9 760 async sendMeterValues(connectorID, interval, self, debug = false) {
7dde0b73
JB
761 try {
762 const sampledValueLcl = {
763 timestamp: new Date().toISOString(),
764 };
2e6f5966 765 const meterValuesClone = Utils.cloneJSonDocument(self._getConnector(connectorID).MeterValues);
7dde0b73
JB
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++) {
7de604f9 772 const connector = self._connectors[connectorID];
7dde0b73 773 if (sampledValueLcl.sampledValue[index].measurand && sampledValueLcl.sampledValue[index].measurand === 'SoC') {
61c2e33d 774 sampledValueLcl.sampledValue[index].value = Utils.getRandomInt(100);
7de604f9
JB
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}`);
7dde0b73
JB
777 }
778 } else {
779 // Persist previous value in connector
7de604f9 780 const consumption = Utils.getRandomInt(self._stationInfo.maxPower / 3600000 * interval);
7dde0b73
JB
781 if (connector && connector.lastConsumptionValue >= 0) {
782 connector.lastConsumptionValue += consumption;
783 } else {
784 connector.lastConsumptionValue = 0;
785 }
7de604f9
JB
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}`);
7dde0b73 788 sampledValueLcl.sampledValue[index].value = connector.lastConsumptionValue;
7de604f9
JB
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}`);
7dde0b73
JB
791 }
792 }
793 }
794
795 const payload = {
796 connectorId: connectorID,
797 transactionId: self._connectors[connectorID].transactionId,
798 meterValue: [sampledValueLcl],
799 };
027b409a 800 await self.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'MeterValues');
7dde0b73 801 } catch (error) {
34dcb3b5 802 logger.error(self._basicFormatLog() + ' Send MeterValues error: ' + error);
7dde0b73
JB
803 }
804 }
805
7de604f9 806 async startMeterValues(connectorID, interval) {
84393381 807 if (!this._connectors[connectorID].transactionStarted) {
7de604f9
JB
808 logger.error(`${this._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction started`);
809 return;
84393381 810 } else if (this._connectors[connectorID].transactionStarted && !this._connectors[connectorID].transactionId) {
7de604f9
JB
811 logger.error(`${this._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction id`);
812 return;
84393381 813 }
d3a7883e 814 this._connectors[connectorID].transactionSetInterval = setInterval(async () => {
7dde0b73
JB
815 const sendMeterValues = performance.timerify(this.sendMeterValues);
816 this._performanceObserver.observe({
817 entryTypes: ['function'],
818 });
7de604f9 819 await sendMeterValues(connectorID, interval, this);
7dde0b73
JB
820 }, interval);
821 }
822
2e6f5966 823 hasAuthorizedTags() {
4a56deef 824 return !Utils.isEmptyArray(this._authorizedTags);
7dde0b73
JB
825 }
826
827 getRandomTagId() {
61c2e33d 828 const index = Math.floor(Math.random() * this._authorizedTags.length);
2e6f5966 829 return this._authorizedTags[index];
7dde0b73
JB
830 }
831
832 _getConnector(number) {
833 return this._stationInfo.Connectors[number];
834 }
adf3e648
JB
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 }
7dde0b73
JB
846}
847
848module.exports = ChargingStation;