94ffc12a2481edca965765d1f669fff60902d9f4
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
1 import { PerformanceObserver, performance } from 'perf_hooks';
2
3 import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
4 import Configuration from '../utils/Configuration';
5 import Constants from '../utils/Constants.js';
6 import ElectricUtils from '../utils/ElectricUtils';
7 import { MeasurandValues } from '../types/MeasurandValues';
8 import OCPPError from './OcppError.js';
9 import Statistics from '../utils/Statistics';
10 import Utils from '../utils/Utils';
11 import WebSocket from 'ws';
12 import crypto from 'crypto';
13 import fs from 'fs';
14 import logger from '../utils/Logger';
15
16 export default class ChargingStation {
17 private _index: number;
18 private _stationTemplateFile: string;
19 private _stationInfo;
20 private _bootNotificationMessage;
21 private _connectors;
22 private _configuration;
23 private _connectorsConfigurationHash: string;
24 private _supervisionUrl;
25 private _wsConnectionUrl;
26 private _wsConnection: WebSocket;
27 private _isSocketRestart;
28 private _autoReconnectRetryCount: number;
29 private _autoReconnectMaxRetries: number;
30 private _autoReconnectTimeout: number;
31 private _requests;
32 private _messageQueue: any[];
33 private _automaticTransactionGeneration: AutomaticTransactionGenerator;
34 private _authorizedTags: string[];
35 private _heartbeatInterval: number;
36 private _heartbeatSetInterval;
37 private _statistics: Statistics;
38 private _performanceObserver: PerformanceObserver;
39
40 constructor(index: number, stationTemplateFile: string) {
41 this._index = index;
42 this._stationTemplateFile = stationTemplateFile;
43 this._connectors = {};
44 this._initialize();
45
46 this._isSocketRestart = false;
47 this._autoReconnectRetryCount = 0;
48 this._autoReconnectMaxRetries = Configuration.getAutoReconnectMaxRetries(); // -1 for unlimited
49 this._autoReconnectTimeout = Configuration.getAutoReconnectTimeout() * 1000; // Ms, zero for disabling
50
51 this._requests = {};
52 this._messageQueue = [];
53
54 this._authorizedTags = this._loadAndGetAuthorizedTags();
55 }
56
57 _getStationName(stationTemplate): string {
58 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + ('000000000' + this._index).substr(('000000000' + this._index).length - 4);
59 }
60
61 _buildStationInfo() {
62 let stationTemplateFromFile;
63 try {
64 // Load template file
65 const fileDescriptor = fs.openSync(this._stationTemplateFile, 'r');
66 stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8'));
67 fs.closeSync(fileDescriptor);
68 } catch (error) {
69 logger.error('Template file ' + this._stationTemplateFile + ' loading error: ' + error);
70 throw error;
71 }
72 const stationTemplate = stationTemplateFromFile || {};
73 if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
74 stationTemplate.maxPower = stationTemplateFromFile.power[Math.floor(Math.random() * stationTemplateFromFile.power.length)];
75 } else {
76 stationTemplate.maxPower = stationTemplateFromFile.power;
77 }
78 stationTemplate.name = this._getStationName(stationTemplateFromFile);
79 stationTemplate.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
80 return stationTemplate;
81 }
82
83 get stationInfo() {
84 return this._stationInfo;
85 }
86
87 _initialize(): void {
88 this._stationInfo = this._buildStationInfo();
89 this._bootNotificationMessage = {
90 chargePointModel: this._stationInfo.chargePointModel,
91 chargePointVendor: this._stationInfo.chargePointVendor,
92 ...!Utils.isUndefined(this._stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this._stationInfo.chargeBoxSerialNumberPrefix },
93 ...!Utils.isUndefined(this._stationInfo.firmwareVersion) && { firmwareVersion: this._stationInfo.firmwareVersion },
94 };
95 this._configuration = this._getConfiguration();
96 this._supervisionUrl = this._getSupervisionURL();
97 this._wsConnectionUrl = this._supervisionUrl + '/' + this._stationInfo.name;
98 // Build connectors if needed
99 const maxConnectors = this._getMaxNumberOfConnectors();
100 if (maxConnectors <= 0) {
101 logger.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with ${maxConnectors} connectors`);
102 }
103 const templateMaxConnectors = this._getTemplateMaxNumberOfConnectors();
104 if (templateMaxConnectors <= 0) {
105 logger.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with no connector configurations`);
106 }
107 // Sanity check
108 if (maxConnectors > (this._stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !Utils.convertToBoolean(this._stationInfo.randomConnectors)) {
109 logger.warn(`${this._logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this._stationTemplateFile}, forcing random connector configurations affectation`);
110 this._stationInfo.randomConnectors = true;
111 }
112 const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this._stationInfo.Connectors) + maxConnectors.toString()).digest('hex');
113 // FIXME: Handle shrinking the number of connectors
114 if (!this._connectors || (this._connectors && this._connectorsConfigurationHash !== connectorsConfigHash)) {
115 this._connectorsConfigurationHash = connectorsConfigHash;
116 // Add connector Id 0
117 let lastConnector = '0';
118 for (lastConnector in this._stationInfo.Connectors) {
119 if (Utils.convertToInt(lastConnector) === 0 && Utils.convertToBoolean(this._stationInfo.useConnectorId0) && this._stationInfo.Connectors[lastConnector]) {
120 this._connectors[lastConnector] = Utils.cloneObject(this._stationInfo.Connectors[lastConnector]);
121 }
122 }
123 // Generate all connectors
124 if ((this._stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
125 for (let index = 1; index <= maxConnectors; index++) {
126 const randConnectorID = Utils.convertToBoolean(this._stationInfo.randomConnectors) ? Utils.getRandomInt(Utils.convertToInt(lastConnector), 1) : index;
127 this._connectors[index] = Utils.cloneObject(this._stationInfo.Connectors[randConnectorID]);
128 }
129 }
130 }
131 // Avoid duplication of connectors related information
132 delete this._stationInfo.Connectors;
133 // Initialize transaction attributes on connectors
134 for (const connector in this._connectors) {
135 if (!this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
136 this._initTransactionOnConnector(connector);
137 }
138 }
139 // OCPP parameters
140 this._addConfigurationKey('NumberOfConnectors', this._getNumberOfConnectors(), true);
141 if (!this._getConfigurationKey('MeterValuesSampledData')) {
142 this._addConfigurationKey('MeterValuesSampledData', 'Energy.Active.Import.Register');
143 }
144 this._stationInfo.powerDivider = this._getPowerDivider();
145 if (this.getEnableStatistics()) {
146 this._statistics = Statistics.getInstance();
147 this._statistics.objName = this._stationInfo.name;
148 this._performanceObserver = new PerformanceObserver((list) => {
149 const entry = list.getEntries()[0];
150 this._statistics.logPerformance(entry, 'ChargingStation');
151 this._performanceObserver.disconnect();
152 });
153 }
154 }
155
156 get connectors() {
157 return this._connectors;
158 }
159
160 get statistics(): Statistics {
161 return this._statistics;
162 }
163
164 _logPrefix(): string {
165 return Utils.logPrefix(` ${this._stationInfo.name}:`);
166 }
167
168 _getConfiguration() {
169 return this._stationInfo.Configuration ? this._stationInfo.Configuration : {};
170 }
171
172 _getAuthorizationFile() {
173 return this._stationInfo.authorizationFile && this._stationInfo.authorizationFile;
174 }
175
176 _loadAndGetAuthorizedTags(): string[] {
177 let authorizedTags = [];
178 const authorizationFile = this._getAuthorizationFile();
179 if (authorizationFile) {
180 try {
181 // Load authorization file
182 const fileDescriptor = fs.openSync(authorizationFile, 'r');
183 authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8'));
184 fs.closeSync(fileDescriptor);
185 } catch (error) {
186 logger.error(this._logPrefix() + ' Authorization file ' + authorizationFile + ' loading error: ' + error);
187 throw error;
188 }
189 } else {
190 logger.info(this._logPrefix() + ' No authorization file given in template file ' + this._stationTemplateFile);
191 }
192 return authorizedTags;
193 }
194
195 getRandomTagId() {
196 const index = Math.floor(Math.random() * this._authorizedTags.length);
197 return this._authorizedTags[index];
198 }
199
200 hasAuthorizedTags() {
201 return !Utils.isEmptyArray(this._authorizedTags);
202 }
203
204 getEnableStatistics() {
205 return !Utils.isUndefined(this._stationInfo.enableStatistics) ? Utils.convertToBoolean(this._stationInfo.enableStatistics) : true;
206 }
207
208 _getNumberOfPhases(): number {
209 switch (this._getPowerOutType()) {
210 case 'AC':
211 return !Utils.isUndefined(this._stationInfo.numberOfPhases) ? Utils.convertToInt(this._stationInfo.numberOfPhases) : 3;
212 case 'DC':
213 return 0;
214 }
215 }
216
217 _getNumberOfRunningTransactions() {
218 let trxCount = 0;
219 for (const connector in this._connectors) {
220 if (this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
221 trxCount++;
222 }
223 }
224 return trxCount;
225 }
226
227 _getPowerDivider() {
228 let powerDivider = this._getNumberOfConnectors();
229 if (this._stationInfo.powerSharedByConnectors) {
230 powerDivider = this._getNumberOfRunningTransactions();
231 }
232 return powerDivider;
233 }
234
235 getConnector(id: number) {
236 return this._connectors[id];
237 }
238
239 _getTemplateMaxNumberOfConnectors() {
240 return Object.keys(this._stationInfo.Connectors).length;
241 }
242
243 _getMaxNumberOfConnectors() {
244 let maxConnectors = 0;
245 if (!Utils.isEmptyArray(this._stationInfo.numberOfConnectors)) {
246 // Distribute evenly the number of connectors
247 maxConnectors = this._stationInfo.numberOfConnectors[(this._index - 1) % this._stationInfo.numberOfConnectors.length];
248 } else if (!Utils.isUndefined(this._stationInfo.numberOfConnectors)) {
249 maxConnectors = this._stationInfo.numberOfConnectors;
250 } else {
251 maxConnectors = this._stationInfo.Connectors[0] ? this._getTemplateMaxNumberOfConnectors() - 1 : this._getTemplateMaxNumberOfConnectors();
252 }
253 return maxConnectors;
254 }
255
256 _getNumberOfConnectors(): number {
257 return this._connectors[0] ? Object.keys(this._connectors).length - 1 : Object.keys(this._connectors).length;
258 }
259
260 _getVoltageOut() {
261 const errMsg = `${this._logPrefix()} Unknown ${this._getPowerOutType()} powerOutType in template file ${this._stationTemplateFile}, cannot define default voltage out`;
262 let defaultVoltageOut;
263 switch (this._getPowerOutType()) {
264 case 'AC':
265 defaultVoltageOut = 230;
266 break;
267 case 'DC':
268 defaultVoltageOut = 400;
269 break;
270 default:
271 logger.error(errMsg);
272 throw Error(errMsg);
273 }
274 return !Utils.isUndefined(this._stationInfo.voltageOut) ? Utils.convertToInt(this._stationInfo.voltageOut) : defaultVoltageOut;
275 }
276
277 _getPowerOutType() {
278 return !Utils.isUndefined(this._stationInfo.powerOutType) ? this._stationInfo.powerOutType : 'AC';
279 }
280
281 _getSupervisionURL() {
282 const supervisionUrls = Utils.cloneObject(this._stationInfo.supervisionURL ? this._stationInfo.supervisionURL : Configuration.getSupervisionURLs());
283 let indexUrl = 0;
284 if (!Utils.isEmptyArray(supervisionUrls)) {
285 if (Configuration.getDistributeStationToTenantEqually()) {
286 indexUrl = this._index % supervisionUrls.length;
287 } else {
288 // Get a random url
289 indexUrl = Math.floor(Math.random() * supervisionUrls.length);
290 }
291 return supervisionUrls[indexUrl];
292 }
293 return supervisionUrls;
294 }
295
296 _getAuthorizeRemoteTxRequests() {
297 const authorizeRemoteTxRequests = this._getConfigurationKey('AuthorizeRemoteTxRequests');
298 return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false;
299 }
300
301 _getLocalAuthListEnabled() {
302 const localAuthListEnabled = this._getConfigurationKey('LocalAuthListEnabled');
303 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
304 }
305
306 _startMessageSequence(): void {
307 // Start heartbeat
308 this._startHeartbeat();
309 // Initialize connectors status
310 for (const connector in this._connectors) {
311 if (!this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
312 if (this.getConnector(Utils.convertToInt(connector)).bootStatus) {
313 this.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
314 } else {
315 this.sendStatusNotification(Utils.convertToInt(connector), 'Available');
316 }
317 } else {
318 this.sendStatusNotification(Utils.convertToInt(connector), 'Charging');
319 }
320 }
321 // Start the ATG
322 if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable)) {
323 if (!this._automaticTransactionGeneration) {
324 this._automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
325 }
326 if (this._automaticTransactionGeneration.timeToStop) {
327 this._automaticTransactionGeneration.start();
328 }
329 }
330 if (this.getEnableStatistics()) {
331 this._statistics.start();
332 }
333 }
334
335 async _stopMessageSequence(reason = ''): Promise<void> {
336 // Stop heartbeat
337 this._stopHeartbeat();
338 // Stop the ATG
339 if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable) &&
340 this._automaticTransactionGeneration &&
341 !this._automaticTransactionGeneration.timeToStop) {
342 await this._automaticTransactionGeneration.stop(reason);
343 } else {
344 for (const connector in this._connectors) {
345 if (this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
346 await this.sendStopTransaction(this.getConnector(Utils.convertToInt(connector)).transactionId, reason);
347 }
348 }
349 }
350 }
351
352 _startHeartbeat(): void {
353 if (this._heartbeatInterval && this._heartbeatInterval > 0 && !this._heartbeatSetInterval) {
354 this._heartbeatSetInterval = setInterval(() => {
355 this.sendHeartbeat();
356 }, this._heartbeatInterval);
357 logger.info(this._logPrefix() + ' Heartbeat started every ' + this._heartbeatInterval.toString() + 'ms');
358 } else {
359 logger.error(`${this._logPrefix()} Heartbeat interval set to ${this._heartbeatInterval}ms, not starting the heartbeat`);
360 }
361 }
362
363 _stopHeartbeat() {
364 if (this._heartbeatSetInterval) {
365 clearInterval(this._heartbeatSetInterval);
366 this._heartbeatSetInterval = null;
367 }
368 }
369
370 _startAuthorizationFileMonitoring() {
371 // eslint-disable-next-line no-unused-vars
372 fs.watchFile(this._getAuthorizationFile(), (current, previous) => {
373 try {
374 logger.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
375 // Initialize _authorizedTags
376 this._authorizedTags = this._loadAndGetAuthorizedTags();
377 } catch (error) {
378 logger.error(this._logPrefix() + ' Authorization file monitoring error: ' + error);
379 }
380 });
381 }
382
383 _startStationTemplateFileMonitoring() {
384 // eslint-disable-next-line no-unused-vars
385 fs.watchFile(this._stationTemplateFile, (current, previous) => {
386 try {
387 logger.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile + ' have changed, reload');
388 // Initialize
389 this._initialize();
390 if (!Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable) &&
391 this._automaticTransactionGeneration) {
392 this._automaticTransactionGeneration.stop().catch(() => {});
393 }
394 } catch (error) {
395 logger.error(this._logPrefix() + ' Charging station template file monitoring error: ' + error);
396 }
397 });
398 }
399
400 _startMeterValues(connectorId: number, interval: number): void {
401 if (!this.getConnector(connectorId).transactionStarted) {
402 logger.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
403 return;
404 } else if (this.getConnector(connectorId).transactionStarted && !this.getConnector(connectorId).transactionId) {
405 logger.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
406 return;
407 }
408 if (interval > 0) {
409 // eslint-disable-next-line @typescript-eslint/no-this-alias
410 const self = this;
411 this.getConnector(connectorId).transactionSetInterval = setInterval(async () => {
412 if (this.getEnableStatistics()) {
413 const sendMeterValues = performance.timerify(this.sendMeterValues);
414 this._performanceObserver.observe({
415 entryTypes: ['function'],
416 });
417 await sendMeterValues(connectorId, interval, self);
418 } else {
419 await this.sendMeterValues(connectorId, interval, self);
420 }
421 }, interval);
422 } else {
423 logger.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${interval}ms, not sending MeterValues`);
424 }
425 }
426
427 start() {
428 if (!this._wsConnectionUrl) {
429 this._wsConnectionUrl = this._supervisionUrl + '/' + this._stationInfo.name;
430 }
431 this._wsConnection = new WebSocket(this._wsConnectionUrl, 'ocpp' + Constants.OCPP_VERSION_16);
432 logger.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl);
433 // Monitor authorization file
434 this._startAuthorizationFileMonitoring();
435 // Monitor station template file
436 this._startStationTemplateFileMonitoring();
437 // Handle Socket incoming messages
438 this._wsConnection.on('message', this.onMessage.bind(this));
439 // Handle Socket error
440 this._wsConnection.on('error', this.onError.bind(this));
441 // Handle Socket close
442 this._wsConnection.on('close', this.onClose.bind(this));
443 // Handle Socket opening connection
444 this._wsConnection.on('open', this.onOpen.bind(this));
445 // Handle Socket ping
446 this._wsConnection.on('ping', this.onPing.bind(this));
447 }
448
449 async stop(reason = '') {
450 // Stop
451 await this._stopMessageSequence();
452 // eslint-disable-next-line guard-for-in
453 for (const connector in this._connectors) {
454 await this.sendStatusNotification(Utils.convertToInt(connector), 'Unavailable');
455 }
456 if (this._wsConnection && this._wsConnection.readyState === WebSocket.OPEN) {
457 await this._wsConnection.close();
458 }
459 }
460
461 _reconnect(error) {
462 logger.error(this._logPrefix() + ' Socket: abnormally closed', error);
463 // Stop the ATG if needed
464 if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable) &&
465 Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure) &&
466 this._automaticTransactionGeneration &&
467 !this._automaticTransactionGeneration.timeToStop) {
468 this._automaticTransactionGeneration.stop();
469 }
470 // Stop heartbeat
471 this._stopHeartbeat();
472 if (this._autoReconnectTimeout !== 0 &&
473 (this._autoReconnectRetryCount < this._autoReconnectMaxRetries || this._autoReconnectMaxRetries === -1)) {
474 logger.error(`${this._logPrefix()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
475 this._autoReconnectRetryCount++;
476 setTimeout(() => {
477 logger.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount);
478 this.start();
479 }, this._autoReconnectTimeout);
480 } else if (this._autoReconnectTimeout !== 0 || this._autoReconnectMaxRetries !== -1) {
481 logger.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
482 }
483 }
484
485 onOpen() {
486 logger.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
487 if (!this._isSocketRestart) {
488 // Send BootNotification
489 this.sendBootNotification();
490 }
491 if (this._isSocketRestart) {
492 this._startMessageSequence();
493 if (!Utils.isEmptyArray(this._messageQueue)) {
494 this._messageQueue.forEach((message) => {
495 if (this._wsConnection && this._wsConnection.readyState === WebSocket.OPEN) {
496 this._wsConnection.send(message);
497 }
498 });
499 }
500 }
501 this._autoReconnectRetryCount = 0;
502 this._isSocketRestart = false;
503 }
504
505 onError(error) {
506 switch (error) {
507 case 'ECONNREFUSED':
508 this._isSocketRestart = true;
509 this._reconnect(error);
510 break;
511 default:
512 logger.error(this._logPrefix() + ' Socket error: ' + error);
513 break;
514 }
515 }
516
517 onClose(error) {
518 switch (error) {
519 case 1000: // Normal close
520 case 1005:
521 logger.info(this._logPrefix() + ' Socket normally closed ' + error);
522 this._autoReconnectRetryCount = 0;
523 break;
524 default: // Abnormal close
525 this._isSocketRestart = true;
526 this._reconnect(error);
527 break;
528 }
529 }
530
531 onPing() {
532 logger.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
533 }
534
535 async onMessage(message) {
536 let [messageType, messageId, commandName, commandPayload, errorDetails] = [0, '', Constants.ENTITY_CHARGING_STATION, '', ''];
537 try {
538 // Parse the message
539 [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(message);
540
541 // Check the Type of message
542 switch (messageType) {
543 // Incoming Message
544 case Constants.OCPP_JSON_CALL_MESSAGE:
545 if (this.getEnableStatistics()) {
546 this._statistics.addMessage(commandName, messageType);
547 }
548 // Process the call
549 await this.handleRequest(messageId, commandName, commandPayload);
550 break;
551 // Outcome Message
552 case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
553 // Respond
554 // eslint-disable-next-line no-case-declarations
555 let responseCallback; let requestPayload;
556 if (Utils.isIterable(this._requests[messageId])) {
557 [responseCallback, , requestPayload] = this._requests[messageId];
558 } else {
559 throw new Error(`Response request for message id ${messageId} is not iterable`);
560 }
561 if (!responseCallback) {
562 // Error
563 throw new Error(`Response request for unknown message id ${messageId}`);
564 }
565 delete this._requests[messageId];
566 responseCallback(commandName, requestPayload);
567 break;
568 // Error Message
569 case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
570 if (!this._requests[messageId]) {
571 // Error
572 throw new Error(`Error request for unknown message id ${messageId}`);
573 }
574 // eslint-disable-next-line no-case-declarations
575 let rejectCallback;
576 if (Utils.isIterable(this._requests[messageId])) {
577 [, rejectCallback] = this._requests[messageId];
578 } else {
579 throw new Error(`Error request for message id ${messageId} is not iterable`);
580 }
581 delete this._requests[messageId];
582 rejectCallback(new OCPPError(commandName, commandPayload, errorDetails));
583 break;
584 // Error
585 default:
586 // eslint-disable-next-line no-case-declarations
587 const errMsg = `${this._logPrefix()} Wrong message type ${messageType}`;
588 logger.error(errMsg);
589 throw new Error(errMsg);
590 }
591 } catch (error) {
592 // Log
593 logger.error('%s Incoming message %j processing error %s on request content type %s', this._logPrefix(), message, error, this._requests[messageId]);
594 // Send error
595 await this.sendError(messageId, error, commandName);
596 }
597 }
598
599 sendHeartbeat() {
600 try {
601 const payload = {
602 currentTime: new Date().toISOString(),
603 };
604 this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'Heartbeat');
605 } catch (error) {
606 logger.error(this._logPrefix() + ' Send Heartbeat error: ' + error);
607 throw error;
608 }
609 }
610
611 sendBootNotification() {
612 try {
613 this.sendMessage(Utils.generateUUID(), this._bootNotificationMessage, Constants.OCPP_JSON_CALL_MESSAGE, 'BootNotification');
614 } catch (error) {
615 logger.error(this._logPrefix() + ' Send BootNotification error: ' + error);
616 throw error;
617 }
618 }
619
620 async sendStatusNotification(connectorId: number, status, errorCode = 'NoError') {
621 try {
622 const payload = {
623 connectorId,
624 errorCode,
625 status,
626 };
627 await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StatusNotification');
628 } catch (error) {
629 logger.error(this._logPrefix() + ' Send StatusNotification error: ' + error);
630 throw error;
631 }
632 }
633
634 async sendStartTransaction(connectorId: number, idTag?: string) {
635 try {
636 const payload = {
637 connectorId,
638 ...!Utils.isUndefined(idTag) ? { idTag } : { idTag: '' },
639 meterStart: 0,
640 timestamp: new Date().toISOString(),
641 };
642 return await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StartTransaction');
643 } catch (error) {
644 logger.error(this._logPrefix() + ' Send StartTransaction error: ' + error);
645 throw error;
646 }
647 }
648
649 async sendStopTransaction(transactionId, reason = ''): Promise<void> {
650 try {
651 const payload = {
652 transactionId,
653 meterStop: 0,
654 timestamp: new Date().toISOString(),
655 ...reason && { reason },
656 };
657 await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StopTransaction');
658 } catch (error) {
659 logger.error(this._logPrefix() + ' Send StopTransaction error: ' + error);
660 throw error;
661 }
662 }
663
664 // eslint-disable-next-line consistent-this
665 async sendMeterValues(connectorId: number, interval: number, self, debug = false): Promise<void> {
666 try {
667 const sampledValues = {
668 timestamp: new Date().toISOString(),
669 sampledValue: [],
670 };
671 const meterValuesTemplate = self.getConnector(connectorId).MeterValues;
672 for (let index = 0; index < meterValuesTemplate.length; index++) {
673 const connector = self.getConnector(connectorId);
674 // SoC measurand
675 if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === 'SoC' && self._getConfigurationKey('MeterValuesSampledData').value.includes('SoC')) {
676 sampledValues.sampledValue.push({
677 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'Percent' },
678 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
679 measurand: meterValuesTemplate[index].measurand,
680 ...!Utils.isUndefined(meterValuesTemplate[index].location) ? { location: meterValuesTemplate[index].location } : { location: 'EV' },
681 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: Utils.getRandomInt(100) },
682 });
683 const sampledValuesIndex = sampledValues.sampledValue.length - 1;
684 if (sampledValues.sampledValue[sampledValuesIndex].value > 100 || debug) {
685 logger.error(`${self._logPrefix()} MeterValues measurand ${sampledValues.sampledValue[sampledValuesIndex].measurand ? sampledValues.sampledValue[sampledValuesIndex].measurand : 'Energy.Active.Import.Register'}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValues.sampledValue[sampledValuesIndex].value}/100`);
686 }
687 // Voltage measurand
688 } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === 'Voltage' && self._getConfigurationKey('MeterValuesSampledData').value.includes('Voltage')) {
689 const voltageMeasurandValue = Utils.getRandomFloatRounded(self._getVoltageOut() + self._getVoltageOut() * 0.1, self._getVoltageOut() - self._getVoltageOut() * 0.1);
690 sampledValues.sampledValue.push({
691 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'V' },
692 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
693 measurand: meterValuesTemplate[index].measurand,
694 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
695 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: voltageMeasurandValue },
696 });
697 for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) {
698 const voltageValue = sampledValues.sampledValue[sampledValues.sampledValue.length - 1].value;
699 let phaseValue;
700 if (voltageValue >= 0 && voltageValue <= 250) {
701 phaseValue = `L${phase}-N`;
702 } else if (voltageValue > 250) {
703 phaseValue = `L${phase}-L${(phase + 1) % self._getNumberOfPhases() !== 0 ? (phase + 1) % self._getNumberOfPhases() : self._getNumberOfPhases()}`;
704 }
705 sampledValues.sampledValue.push({
706 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'V' },
707 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
708 measurand: meterValuesTemplate[index].measurand,
709 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
710 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: voltageMeasurandValue },
711 phase: phaseValue,
712 });
713 }
714 // Power.Active.Import measurand
715 } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === 'Power.Active.Import' && self._getConfigurationKey('MeterValuesSampledData').value.includes('Power.Active.Import')) {
716 // FIXME: factor out powerDivider checks
717 if (Utils.isUndefined(self._stationInfo.powerDivider)) {
718 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
719 logger.error(errMsg);
720 throw Error(errMsg);
721 } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) {
722 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`;
723 logger.error(errMsg);
724 throw Error(errMsg);
725 }
726 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: Unknown ${self._getPowerOutType()} powerOutType in template file ${self._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'} measurand value`;
727 const powerMeasurandValues = {} as MeasurandValues ;
728 const maxPower = Math.round(self._stationInfo.maxPower / self._stationInfo.powerDivider);
729 const maxPowerPerPhase = Math.round((self._stationInfo.maxPower / self._stationInfo.powerDivider) / self._getNumberOfPhases());
730 switch (self._getPowerOutType()) {
731 case 'AC':
732 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
733 powerMeasurandValues.L1 = Utils.getRandomFloatRounded(maxPowerPerPhase);
734 powerMeasurandValues.L2 = 0;
735 powerMeasurandValues.L3 = 0;
736 if (self._getNumberOfPhases() === 3) {
737 powerMeasurandValues.L2 = Utils.getRandomFloatRounded(maxPowerPerPhase);
738 powerMeasurandValues.L3 = Utils.getRandomFloatRounded(maxPowerPerPhase);
739 }
740 powerMeasurandValues.all = Utils.roundTo(powerMeasurandValues.L1 + powerMeasurandValues.L2 + powerMeasurandValues.L3, 2);
741 }
742 break;
743 case 'DC':
744 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
745 powerMeasurandValues.all = Utils.getRandomFloatRounded(maxPower);
746 }
747 break;
748 default:
749 logger.error(errMsg);
750 throw Error(errMsg);
751 }
752 sampledValues.sampledValue.push({
753 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'W' },
754 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
755 measurand: meterValuesTemplate[index].measurand,
756 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
757 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: powerMeasurandValues.all },
758 });
759 const sampledValuesIndex = sampledValues.sampledValue.length - 1;
760 if (sampledValues.sampledValue[sampledValuesIndex].value > maxPower || debug) {
761 logger.error(`${self._logPrefix()} MeterValues measurand ${sampledValues.sampledValue[sampledValuesIndex].measurand ? sampledValues.sampledValue[sampledValuesIndex].measurand : 'Energy.Active.Import.Register'}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValues.sampledValue[sampledValuesIndex].value}/${maxPower}`);
762 }
763 for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) {
764 const phaseValue = `L${phase}-N`;
765 sampledValues.sampledValue.push({
766 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'W' },
767 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
768 ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand },
769 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
770 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: powerMeasurandValues[`L${phase}`] },
771 phase: phaseValue,
772 });
773 }
774 // Current.Import measurand
775 } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === 'Current.Import' && self._getConfigurationKey('MeterValuesSampledData').value.includes('Current.Import')) {
776 // FIXME: factor out powerDivider checks
777 if (Utils.isUndefined(self._stationInfo.powerDivider)) {
778 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
779 logger.error(errMsg);
780 throw Error(errMsg);
781 } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) {
782 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`;
783 logger.error(errMsg);
784 throw Error(errMsg);
785 }
786 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: Unknown ${self._getPowerOutType()} powerOutType in template file ${self._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'} measurand value`;
787 const currentMeasurandValues = {} as MeasurandValues;
788 let maxAmperage;
789 switch (self._getPowerOutType()) {
790 case 'AC':
791 maxAmperage = ElectricUtils.ampPerPhaseFromPower(self._getNumberOfPhases(), self._stationInfo.maxPower / self._stationInfo.powerDivider, self._getVoltageOut());
792 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
793 currentMeasurandValues.L1 = Utils.getRandomFloatRounded(maxAmperage);
794 currentMeasurandValues.L2 = 0;
795 currentMeasurandValues.L3 = 0;
796 if (self._getNumberOfPhases() === 3) {
797 currentMeasurandValues.L2 = Utils.getRandomFloatRounded(maxAmperage);
798 currentMeasurandValues.L3 = Utils.getRandomFloatRounded(maxAmperage);
799 }
800 currentMeasurandValues.all = Utils.roundTo((currentMeasurandValues.L1 + currentMeasurandValues.L2 + currentMeasurandValues.L3) / self._getNumberOfPhases(), 2);
801 }
802 break;
803 case 'DC':
804 maxAmperage = ElectricUtils.ampTotalFromPower(self._stationInfo.maxPower / self._stationInfo.powerDivider, self._getVoltageOut());
805 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
806 currentMeasurandValues.all = Utils.getRandomFloatRounded(maxAmperage);
807 }
808 break;
809 default:
810 logger.error(errMsg);
811 throw Error(errMsg);
812 }
813 sampledValues.sampledValue.push({
814 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'A' },
815 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
816 measurand: meterValuesTemplate[index].measurand,
817 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
818 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: currentMeasurandValues.all },
819 });
820 const sampledValuesIndex = sampledValues.sampledValue.length - 1;
821 if (sampledValues.sampledValue[sampledValuesIndex].value > maxAmperage || debug) {
822 logger.error(`${self._logPrefix()} MeterValues measurand ${sampledValues.sampledValue[sampledValuesIndex].measurand ? sampledValues.sampledValue[sampledValuesIndex].measurand : 'Energy.Active.Import.Register'}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValues.sampledValue[sampledValuesIndex].value}/${maxAmperage}`);
823 }
824 for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) {
825 const phaseValue = `L${phase}`;
826 sampledValues.sampledValue.push({
827 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'A' },
828 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
829 ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand },
830 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
831 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: currentMeasurandValues[phaseValue] },
832 phase: phaseValue,
833 });
834 }
835 // Energy.Active.Import.Register measurand (default)
836 } else if (!meterValuesTemplate[index].measurand || meterValuesTemplate[index].measurand === 'Energy.Active.Import.Register') {
837 // FIXME: factor out powerDivider checks
838 if (Utils.isUndefined(self._stationInfo.powerDivider)) {
839 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
840 logger.error(errMsg);
841 throw Error(errMsg);
842 } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) {
843 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`;
844 logger.error(errMsg);
845 throw Error(errMsg);
846 }
847 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
848 const measurandValue = Utils.getRandomInt(self._stationInfo.maxPower / (self._stationInfo.powerDivider * 3600000) * interval);
849 // Persist previous value in connector
850 if (connector && !Utils.isNullOrUndefined(connector.lastEnergyActiveImportRegisterValue) && connector.lastEnergyActiveImportRegisterValue >= 0) {
851 connector.lastEnergyActiveImportRegisterValue += measurandValue;
852 } else {
853 connector.lastEnergyActiveImportRegisterValue = 0;
854 }
855 }
856 sampledValues.sampledValue.push({
857 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'Wh' },
858 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
859 ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand },
860 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
861 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: connector.lastEnergyActiveImportRegisterValue },
862 });
863 const sampledValuesIndex = sampledValues.sampledValue.length - 1;
864 const maxConsumption = Math.round(self._stationInfo.maxPower * 3600 / (self._stationInfo.powerDivider * interval));
865 if (sampledValues.sampledValue[sampledValuesIndex].value > maxConsumption || debug) {
866 logger.error(`${self._logPrefix()} MeterValues measurand ${sampledValues.sampledValue[sampledValuesIndex].measurand ? sampledValues.sampledValue[sampledValuesIndex].measurand : 'Energy.Active.Import.Register'}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValues.sampledValue[sampledValuesIndex].value}/${maxConsumption}`);
867 }
868 // Unsupported measurand
869 } else {
870 logger.info(`${self._logPrefix()} Unsupported MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'} on connectorId ${connectorId}`);
871 }
872 }
873
874 const payload = {
875 connectorId,
876 transactionId: self.getConnector(connectorId).transactionId,
877 meterValue: sampledValues,
878 };
879 await self.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'MeterValues');
880 } catch (error) {
881 logger.error(self._logPrefix() + ' Send MeterValues error: ' + error);
882 throw error;
883 }
884 }
885
886 sendError(messageId, err: Error|OCPPError, commandName) {
887 // Check exception type: only OCPP error are accepted
888 const error = err instanceof OCPPError ? err : new OCPPError(Constants.OCPP_ERROR_INTERNAL_ERROR, err.message, err.stack && err.stack);
889 // Send error
890 return this.sendMessage(messageId, error, Constants.OCPP_JSON_CALL_ERROR_MESSAGE, commandName);
891 }
892
893 sendMessage(messageId, commandParams, messageType = Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName: string) {
894 const self = this;
895 // Send a message through wsConnection
896 return new Promise((resolve, reject) => {
897 let messageToSend;
898 // Type of message
899 switch (messageType) {
900 // Request
901 case Constants.OCPP_JSON_CALL_MESSAGE:
902 // Build request
903 this._requests[messageId] = [responseCallback, rejectCallback, commandParams];
904 messageToSend = JSON.stringify([messageType, messageId, commandName, commandParams]);
905 break;
906 // Response
907 case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
908 // Build response
909 messageToSend = JSON.stringify([messageType, messageId, commandParams]);
910 break;
911 // Error Message
912 case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
913 // Build Error Message
914 messageToSend = JSON.stringify([messageType, messageId, commandParams.code ? commandParams.code : Constants.OCPP_ERROR_GENERIC_ERROR, commandParams.message ? commandParams.message : '', commandParams.details ? commandParams.details : {}]);
915 break;
916 }
917 // Check if wsConnection is ready
918 if (this._wsConnection && this._wsConnection.readyState === WebSocket.OPEN) {
919 if (this.getEnableStatistics()) {
920 this._statistics.addMessage(commandName, messageType);
921 }
922 // Yes: Send Message
923 this._wsConnection.send(messageToSend);
924 } else {
925 let dups = false;
926 // Handle dups in buffer
927 for (const message of this._messageQueue) {
928 // Same message
929 if (JSON.stringify(messageToSend) === JSON.stringify(message)) {
930 dups = true;
931 break;
932 }
933 }
934 if (!dups) {
935 // Buffer message
936 this._messageQueue.push(messageToSend);
937 }
938 // Reject it
939 return rejectCallback(new OCPPError(commandParams.code ? commandParams.code : Constants.OCPP_ERROR_GENERIC_ERROR, commandParams.message ? commandParams.message : `Web socket closed for message id '${messageId}' with content '${messageToSend}', message buffered`, commandParams.details ? commandParams.details : {}));
940 }
941 // Response?
942 if (messageType === Constants.OCPP_JSON_CALL_RESULT_MESSAGE) {
943 // Yes: send Ok
944 resolve();
945 } else if (messageType === Constants.OCPP_JSON_CALL_ERROR_MESSAGE) {
946 // Send timeout
947 setTimeout(() => rejectCallback(new OCPPError(commandParams.code ? commandParams.code : Constants.OCPP_ERROR_GENERIC_ERROR, commandParams.message ? commandParams.message : `Timeout for message id '${messageId}' with content '${messageToSend}'`, commandParams.details ? commandParams.details : {})), Constants.OCPP_SOCKET_TIMEOUT);
948 }
949
950 // Function that will receive the request's response
951 function responseCallback(payload, requestPayload): void {
952 if (self.getEnableStatistics()) {
953 self._statistics.addMessage(commandName, messageType);
954 }
955 // Send the response
956 self.handleResponse(commandName, payload, requestPayload);
957 resolve(payload);
958 }
959
960 // Function that will receive the request's rejection
961 function rejectCallback(error: OCPPError): void {
962 if (self.getEnableStatistics()) {
963 self._statistics.addMessage(commandName, messageType);
964 }
965 logger.debug(`${self._logPrefix()} Error %j occurred when calling command %s with parameters %j`, error, commandName, commandParams);
966 // Build Exception
967 // eslint-disable-next-line no-empty-function
968 self._requests[messageId] = [() => { }, () => { }, '']; // Properly format the request
969 // Send error
970 reject(error);
971 }
972 });
973 }
974
975 handleResponse(commandName: string, payload, requestPayload) {
976 const responseCallbackFn = 'handleResponse' + commandName;
977 if (typeof this[responseCallbackFn] === 'function') {
978 this[responseCallbackFn](payload, requestPayload);
979 } else {
980 logger.error(this._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn);
981 }
982 }
983
984 handleResponseBootNotification(payload, requestPayload) {
985 if (payload.status === 'Accepted') {
986 this._heartbeatInterval = payload.interval * 1000;
987 this._addConfigurationKey('HeartBeatInterval', Utils.convertToInt(payload.interval));
988 this._addConfigurationKey('HeartbeatInterval', Utils.convertToInt(payload.interval), false, false);
989 this._startMessageSequence();
990 } else if (payload.status === 'Pending') {
991 logger.info(this._logPrefix() + ' Charging station in pending state on the central server');
992 } else {
993 logger.info(this._logPrefix() + ' Charging station rejected by the central server');
994 }
995 }
996
997 _initTransactionOnConnector(connectorId) {
998 this.getConnector(connectorId).transactionStarted = false;
999 this.getConnector(connectorId).transactionId = null;
1000 this.getConnector(connectorId).idTag = null;
1001 this.getConnector(connectorId).lastEnergyActiveImportRegisterValue = -1;
1002 }
1003
1004 _resetTransactionOnConnector(connectorId) {
1005 this._initTransactionOnConnector(connectorId);
1006 if (this.getConnector(connectorId).transactionSetInterval) {
1007 clearInterval(this.getConnector(connectorId).transactionSetInterval);
1008 }
1009 }
1010
1011 handleResponseStartTransaction(payload, requestPayload) {
1012 if (this.getConnector(requestPayload.connectorId).transactionStarted) {
1013 logger.debug(this._logPrefix() + ' Try to start a transaction on an already used connector ' + requestPayload.connectorId + ': %s', this.getConnector(requestPayload.connectorId));
1014 return;
1015 }
1016
1017 let transactionConnectorId;
1018 for (const connector in this._connectors) {
1019 if (Utils.convertToInt(connector) === Utils.convertToInt(requestPayload.connectorId)) {
1020 transactionConnectorId = connector;
1021 break;
1022 }
1023 }
1024 if (!transactionConnectorId) {
1025 logger.error(this._logPrefix() + ' Try to start a transaction on a non existing connector Id ' + requestPayload.connectorId);
1026 return;
1027 }
1028 if (payload.idTagInfo && payload.idTagInfo.status === 'Accepted') {
1029 this.getConnector(requestPayload.connectorId).transactionStarted = true;
1030 this.getConnector(requestPayload.connectorId).transactionId = payload.transactionId;
1031 this.getConnector(requestPayload.connectorId).idTag = requestPayload.idTag;
1032 this.getConnector(requestPayload.connectorId).lastEnergyActiveImportRegisterValue = 0;
1033 this.sendStatusNotification(requestPayload.connectorId, 'Charging');
1034 logger.info(this._logPrefix() + ' Transaction ' + payload.transactionId + ' STARTED on ' + this._stationInfo.name + '#' + requestPayload.connectorId + ' for idTag ' + requestPayload.idTag);
1035 if (this._stationInfo.powerSharedByConnectors) {
1036 this._stationInfo.powerDivider++;
1037 }
1038 const configuredMeterValueSampleInterval = this._getConfigurationKey('MeterValueSampleInterval');
1039 this._startMeterValues(requestPayload.connectorId,
1040 configuredMeterValueSampleInterval ? configuredMeterValueSampleInterval.value * 1000 : 60000);
1041 } else {
1042 logger.error(this._logPrefix() + ' Starting transaction id ' + payload.transactionId + ' REJECTED with status ' + payload.idTagInfo.status + ', idTag ' + requestPayload.idTag);
1043 this._resetTransactionOnConnector(requestPayload.connectorId);
1044 this.sendStatusNotification(requestPayload.connectorId, 'Available');
1045 }
1046 }
1047
1048 handleResponseStopTransaction(payload, requestPayload) {
1049 let transactionConnectorId;
1050 for (const connector in this._connectors) {
1051 if (this.getConnector(Utils.convertToInt(connector)).transactionId === requestPayload.transactionId) {
1052 transactionConnectorId = connector;
1053 break;
1054 }
1055 }
1056 if (!transactionConnectorId) {
1057 logger.error(this._logPrefix() + ' Try to stop a non existing transaction ' + requestPayload.transactionId);
1058 return;
1059 }
1060 if (payload.idTagInfo && payload.idTagInfo.status === 'Accepted') {
1061 this.sendStatusNotification(transactionConnectorId, 'Available');
1062 if (this._stationInfo.powerSharedByConnectors) {
1063 this._stationInfo.powerDivider--;
1064 }
1065 logger.info(this._logPrefix() + ' Transaction ' + requestPayload.transactionId + ' STOPPED on ' + this._stationInfo.name + '#' + transactionConnectorId);
1066 this._resetTransactionOnConnector(transactionConnectorId);
1067 } else {
1068 logger.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload.transactionId + ' REJECTED with status ' + payload.idTagInfo.status);
1069 }
1070 }
1071
1072 handleResponseStatusNotification(payload, requestPayload) {
1073 logger.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload, requestPayload);
1074 }
1075
1076 handleResponseMeterValues(payload, requestPayload) {
1077 logger.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload, requestPayload);
1078 }
1079
1080 handleResponseHeartbeat(payload, requestPayload) {
1081 logger.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload, requestPayload);
1082 }
1083
1084 async handleRequest(messageId, commandName, commandPayload) {
1085 let response;
1086 // Call
1087 if (typeof this['handleRequest' + commandName] === 'function') {
1088 try {
1089 // Call the method to build the response
1090 response = await this['handleRequest' + commandName](commandPayload);
1091 } catch (error) {
1092 // Log
1093 logger.error(this._logPrefix() + ' Handle request error: ' + error);
1094 // Send back response to inform backend
1095 await this.sendError(messageId, error, commandName);
1096 throw error;
1097 }
1098 } else {
1099 // Throw exception
1100 await this.sendError(messageId, new OCPPError(Constants.OCPP_ERROR_NOT_IMPLEMENTED, `${commandName} not implemented`, {}), commandName);
1101 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
1102 }
1103 // Send response
1104 await this.sendMessage(messageId, response, Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName);
1105 }
1106
1107 // Simulate charging station restart
1108 async handleRequestReset(commandPayload) {
1109 setImmediate(async () => {
1110 await this.stop(commandPayload.type + 'Reset');
1111 await Utils.sleep(this._stationInfo.resetTime);
1112 await this.start();
1113 });
1114 logger.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${this._stationInfo.resetTime}ms`);
1115 return Constants.OCPP_RESPONSE_ACCEPTED;
1116 }
1117
1118 _getConfigurationKey(key) {
1119 return this._configuration.configurationKey.find((configElement) => configElement.key === key);
1120 }
1121
1122 _addConfigurationKey(key, value, readonly = false, visible = true, reboot = false) {
1123 const keyFound = this._getConfigurationKey(key);
1124 if (!keyFound) {
1125 this._configuration.configurationKey.push({
1126 key,
1127 readonly,
1128 value,
1129 visible,
1130 reboot,
1131 });
1132 }
1133 }
1134
1135 _setConfigurationKeyValue(key, value) {
1136 const keyFound = this._getConfigurationKey(key);
1137 if (keyFound) {
1138 const keyIndex = this._configuration.configurationKey.indexOf(keyFound);
1139 this._configuration.configurationKey[keyIndex].value = value;
1140 }
1141 }
1142
1143 async handleRequestGetConfiguration(commandPayload) {
1144 const configurationKey = [];
1145 const unknownKey = [];
1146 if (Utils.isEmptyArray(commandPayload.key)) {
1147 for (const configuration of this._configuration.configurationKey) {
1148 if (Utils.isUndefined(configuration.visible)) {
1149 configuration.visible = true;
1150 } else {
1151 configuration.visible = Utils.convertToBoolean(configuration.visible);
1152 }
1153 if (!configuration.visible) {
1154 continue;
1155 }
1156 configurationKey.push({
1157 key: configuration.key,
1158 readonly: configuration.readonly,
1159 value: configuration.value,
1160 });
1161 }
1162 } else {
1163 for (const configurationKey of commandPayload.key) {
1164 const keyFound = this._getConfigurationKey(configurationKey);
1165 if (keyFound) {
1166 if (Utils.isUndefined(keyFound.visible)) {
1167 keyFound.visible = true;
1168 } else {
1169 keyFound.visible = Utils.convertToBoolean(configurationKey.visible);
1170 }
1171 if (!keyFound.visible) {
1172 continue;
1173 }
1174 configurationKey.push({
1175 key: keyFound.key,
1176 readonly: keyFound.readonly,
1177 value: keyFound.value,
1178 });
1179 } else {
1180 unknownKey.push(configurationKey);
1181 }
1182 }
1183 }
1184 return {
1185 configurationKey,
1186 unknownKey,
1187 };
1188 }
1189
1190 async handleRequestChangeConfiguration(commandPayload) {
1191 const keyToChange = this._getConfigurationKey(commandPayload.key);
1192 if (!keyToChange) {
1193 return { status: Constants.OCPP_ERROR_NOT_SUPPORTED };
1194 } else if (keyToChange && Utils.convertToBoolean(keyToChange.readonly)) {
1195 return Constants.OCPP_RESPONSE_REJECTED;
1196 } else if (keyToChange && !Utils.convertToBoolean(keyToChange.readonly)) {
1197 const keyIndex = this._configuration.configurationKey.indexOf(keyToChange);
1198 this._configuration.configurationKey[keyIndex].value = commandPayload.value;
1199 let triggerHeartbeatRestart = false;
1200 if (keyToChange.key === 'HeartBeatInterval') {
1201 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload.value);
1202 triggerHeartbeatRestart = true;
1203 }
1204 if (keyToChange.key === 'HeartbeatInterval') {
1205 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload.value);
1206 triggerHeartbeatRestart = true;
1207 }
1208 if (triggerHeartbeatRestart) {
1209 this._heartbeatInterval = Utils.convertToInt(commandPayload.value) * 1000;
1210 // Stop heartbeat
1211 this._stopHeartbeat();
1212 // Start heartbeat
1213 this._startHeartbeat();
1214 }
1215 if (Utils.convertToBoolean(keyToChange.reboot)) {
1216 return Constants.OCPP_RESPONSE_REBOOT_REQUIRED;
1217 }
1218 return Constants.OCPP_RESPONSE_ACCEPTED;
1219 }
1220 }
1221
1222 async handleRequestRemoteStartTransaction(commandPayload) {
1223 const transactionConnectorID = commandPayload.connectorId ? commandPayload.connectorId : '1';
1224 if (this._getAuthorizeRemoteTxRequests() && this._getLocalAuthListEnabled() && this.hasAuthorizedTags()) {
1225 // Check if authorized
1226 if (this._authorizedTags.find((value) => value === commandPayload.idTag)) {
1227 // Authorization successful start transaction
1228 this.sendStartTransaction(transactionConnectorID, commandPayload.idTag);
1229 logger.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID + ' for idTag ' + commandPayload.idTag);
1230 return Constants.OCPP_RESPONSE_ACCEPTED;
1231 }
1232 logger.error(this._logPrefix() + ' Remote starting transaction REJECTED with status ' + commandPayload.idTagInfo.status + ', idTag ' + commandPayload.idTag);
1233 return Constants.OCPP_RESPONSE_REJECTED;
1234 }
1235 // No local authorization check required => start transaction
1236 this.sendStartTransaction(transactionConnectorID, commandPayload.idTag);
1237 logger.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID + ' for idTag ' + commandPayload.idTag);
1238 return Constants.OCPP_RESPONSE_ACCEPTED;
1239 }
1240
1241 async handleRequestRemoteStopTransaction(commandPayload) {
1242 for (const connector in this._connectors) {
1243 if (this.getConnector(Utils.convertToInt(connector)).transactionId === commandPayload.transactionId) {
1244 this.sendStopTransaction(commandPayload.transactionId);
1245 return Constants.OCPP_RESPONSE_ACCEPTED;
1246 }
1247 }
1248 logger.info(this._logPrefix() + ' Try to stop remotely a non existing transaction ' + commandPayload.transactionId);
1249 return Constants.OCPP_RESPONSE_REJECTED;
1250 }
1251 }
1252