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