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