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