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