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