CF: include TS sources.
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
... / ...
CommitLineData
1import { PerformanceObserver, performance } from 'perf_hooks';
2
3import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
4import Configuration from '../utils/Configuration';
5import Constants from '../utils/Constants.js';
6import ElectricUtils from '../utils/ElectricUtils';
7import { MeasurandValues } from '../types/MeasurandValues';
8import OCPPError from './OcppError.js';
9import Statistics from '../utils/Statistics';
10import Utils from '../utils/Utils';
11import WebSocket from 'ws';
12import crypto from 'crypto';
13import fs from 'fs';
14import logger from '../utils/Logger';
15
16export 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() : string {
173 return this._stationInfo.authorizationFile && this._stationInfo.authorizationFile;
174 }
175
176 _loadAndGetAuthorizedTags(): string[] {
177 let authorizedTags: string[] = [];
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(): string {
196 const index = Math.floor(Math.random() * this._authorizedTags.length);
197 return this._authorizedTags[index];
198 }
199
200 hasAuthorizedTags(): boolean {
201 return !Utils.isEmptyArray(this._authorizedTags);
202 }
203
204 getEnableStatistics(): boolean {
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(): number {
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(): number {
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(): number {
240 return Object.keys(this._stationInfo.Connectors).length;
241 }
242
243 _getMaxNumberOfConnectors(): number {
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(): number {
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(): string {
278 return !Utils.isUndefined(this._stationInfo.powerOutType) ? this._stationInfo.powerOutType : 'AC';
279 }
280
281 _getSupervisionURL(): string {
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(): boolean {
297 const authorizeRemoteTxRequests = this._getConfigurationKey('AuthorizeRemoteTxRequests');
298 return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false;
299 }
300
301 _getLocalAuthListEnabled(): boolean {
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(): void {
364 if (this._heartbeatSetInterval) {
365 clearInterval(this._heartbeatSetInterval);
366 this._heartbeatSetInterval = null;
367 }
368 }
369
370 _startAuthorizationFileMonitoring(): void {
371 // eslint-disable-next-line @typescript-eslint/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(): void {
384 // eslint-disable-next-line @typescript-eslint/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 this.getConnector(connectorId).transactionSetInterval = setInterval(async (): Promise<void> => {
410 if (this.getEnableStatistics()) {
411 const sendMeterValues = performance.timerify(this.sendMeterValues);
412 this._performanceObserver.observe({
413 entryTypes: ['function'],
414 });
415 await sendMeterValues(connectorId, interval, this);
416 } else {
417 await this.sendMeterValues(connectorId, interval, this);
418 }
419 }, interval);
420 } else {
421 logger.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${interval}ms, not sending MeterValues`);
422 }
423 }
424
425 start(): void {
426 if (!this._wsConnectionUrl) {
427 this._wsConnectionUrl = this._supervisionUrl + '/' + this._stationInfo.name;
428 }
429 this._wsConnection = new WebSocket(this._wsConnectionUrl, 'ocpp' + Constants.OCPP_VERSION_16);
430 logger.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl);
431 // Monitor authorization file
432 this._startAuthorizationFileMonitoring();
433 // Monitor station template file
434 this._startStationTemplateFileMonitoring();
435 // Handle Socket incoming messages
436 this._wsConnection.on('message', this.onMessage.bind(this));
437 // Handle Socket error
438 this._wsConnection.on('error', this.onError.bind(this));
439 // Handle Socket close
440 this._wsConnection.on('close', this.onClose.bind(this));
441 // Handle Socket opening connection
442 this._wsConnection.on('open', this.onOpen.bind(this));
443 // Handle Socket ping
444 this._wsConnection.on('ping', this.onPing.bind(this));
445 }
446
447 async stop(reason = ''): Promise<void> {
448 // Stop
449 await this._stopMessageSequence();
450 // eslint-disable-next-line guard-for-in
451 for (const connector in this._connectors) {
452 await this.sendStatusNotification(Utils.convertToInt(connector), 'Unavailable');
453 }
454 if (this._wsConnection && this._wsConnection.readyState === WebSocket.OPEN) {
455 this._wsConnection.close();
456 }
457 }
458
459 _reconnect(error): void {
460 logger.error(this._logPrefix() + ' Socket: abnormally closed', error);
461 // Stop the ATG if needed
462 if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable) &&
463 Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure) &&
464 this._automaticTransactionGeneration &&
465 !this._automaticTransactionGeneration.timeToStop) {
466 this._automaticTransactionGeneration.stop();
467 }
468 // Stop heartbeat
469 this._stopHeartbeat();
470 if (this._autoReconnectTimeout !== 0 &&
471 (this._autoReconnectRetryCount < this._autoReconnectMaxRetries || this._autoReconnectMaxRetries === -1)) {
472 logger.error(`${this._logPrefix()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
473 this._autoReconnectRetryCount++;
474 setTimeout(() => {
475 logger.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount);
476 this.start();
477 }, this._autoReconnectTimeout);
478 } else if (this._autoReconnectTimeout !== 0 || this._autoReconnectMaxRetries !== -1) {
479 logger.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
480 }
481 }
482
483 onOpen() {
484 logger.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
485 if (!this._isSocketRestart) {
486 // Send BootNotification
487 this.sendBootNotification();
488 }
489 if (this._isSocketRestart) {
490 this._startMessageSequence();
491 if (!Utils.isEmptyArray(this._messageQueue)) {
492 this._messageQueue.forEach((message) => {
493 if (this._wsConnection && this._wsConnection.readyState === WebSocket.OPEN) {
494 this._wsConnection.send(message);
495 }
496 });
497 }
498 }
499 this._autoReconnectRetryCount = 0;
500 this._isSocketRestart = false;
501 }
502
503 onError(error) {
504 switch (error) {
505 case 'ECONNREFUSED':
506 this._isSocketRestart = true;
507 this._reconnect(error);
508 break;
509 default:
510 logger.error(this._logPrefix() + ' Socket error: ' + error);
511 break;
512 }
513 }
514
515 onClose(error) {
516 switch (error) {
517 case 1000: // Normal close
518 case 1005:
519 logger.info(this._logPrefix() + ' Socket normally closed ' + error);
520 this._autoReconnectRetryCount = 0;
521 break;
522 default: // Abnormal close
523 this._isSocketRestart = true;
524 this._reconnect(error);
525 break;
526 }
527 }
528
529 onPing() {
530 logger.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
531 }
532
533 async onMessage(message) {
534 let [messageType, messageId, commandName, commandPayload, errorDetails] = [0, '', Constants.ENTITY_CHARGING_STATION, '', ''];
535 try {
536 // Parse the message
537 [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(message);
538
539 // Check the Type of message
540 switch (messageType) {
541 // Incoming Message
542 case Constants.OCPP_JSON_CALL_MESSAGE:
543 if (this.getEnableStatistics()) {
544 this._statistics.addMessage(commandName, messageType);
545 }
546 // Process the call
547 await this.handleRequest(messageId, commandName, commandPayload);
548 break;
549 // Outcome Message
550 case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
551 // Respond
552 // eslint-disable-next-line no-case-declarations
553 let responseCallback; let requestPayload;
554 if (Utils.isIterable(this._requests[messageId])) {
555 [responseCallback, , requestPayload] = this._requests[messageId];
556 } else {
557 throw new Error(`Response request for message id ${messageId} is not iterable`);
558 }
559 if (!responseCallback) {
560 // Error
561 throw new Error(`Response request for unknown message id ${messageId}`);
562 }
563 delete this._requests[messageId];
564 responseCallback(commandName, requestPayload);
565 break;
566 // Error Message
567 case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
568 if (!this._requests[messageId]) {
569 // Error
570 throw new Error(`Error request for unknown message id ${messageId}`);
571 }
572 // eslint-disable-next-line no-case-declarations
573 let rejectCallback;
574 if (Utils.isIterable(this._requests[messageId])) {
575 [, rejectCallback] = this._requests[messageId];
576 } else {
577 throw new Error(`Error request for message id ${messageId} is not iterable`);
578 }
579 delete this._requests[messageId];
580 rejectCallback(new OCPPError(commandName, commandPayload, errorDetails));
581 break;
582 // Error
583 default:
584 // eslint-disable-next-line no-case-declarations
585 const errMsg = `${this._logPrefix()} Wrong message type ${messageType}`;
586 logger.error(errMsg);
587 throw new Error(errMsg);
588 }
589 } catch (error) {
590 // Log
591 logger.error('%s Incoming message %j processing error %s on request content type %s', this._logPrefix(), message, error, this._requests[messageId]);
592 // Send error
593 await this.sendError(messageId, error, commandName);
594 }
595 }
596
597 async sendHeartbeat() {
598 try {
599 const payload = {
600 currentTime: new Date().toISOString(),
601 };
602 await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'Heartbeat');
603 } catch (error) {
604 logger.error(this._logPrefix() + ' Send Heartbeat error: ' + error);
605 throw error;
606 }
607 }
608
609 async sendBootNotification() {
610 try {
611 await this.sendMessage(Utils.generateUUID(), this._bootNotificationMessage, Constants.OCPP_JSON_CALL_MESSAGE, 'BootNotification');
612 } catch (error) {
613 logger.error(this._logPrefix() + ' Send BootNotification error: ' + error);
614 throw error;
615 }
616 }
617
618 async sendStatusNotification(connectorId: number, status: string, errorCode = 'NoError') {
619 try {
620 const payload = {
621 connectorId,
622 errorCode,
623 status,
624 };
625 await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StatusNotification');
626 } catch (error) {
627 logger.error(this._logPrefix() + ' Send StatusNotification error: ' + error);
628 throw error;
629 }
630 }
631
632 async sendStartTransaction(connectorId: number, idTag?: string): Promise<unknown> {
633 try {
634 const payload = {
635 connectorId,
636 ...!Utils.isUndefined(idTag) ? { idTag } : { idTag: '' },
637 meterStart: 0,
638 timestamp: new Date().toISOString(),
639 };
640 return await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StartTransaction');
641 } catch (error) {
642 logger.error(this._logPrefix() + ' Send StartTransaction error: ' + error);
643 throw error;
644 }
645 }
646
647 async sendStopTransaction(transactionId: number, reason = ''): Promise<void> {
648 try {
649 const payload = {
650 transactionId,
651 meterStop: 0,
652 timestamp: new Date().toISOString(),
653 ...reason && { reason },
654 };
655 await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StopTransaction');
656 } catch (error) {
657 logger.error(this._logPrefix() + ' Send StopTransaction error: ' + error);
658 throw error;
659 }
660 }
661
662 // eslint-disable-next-line consistent-this
663 async sendMeterValues(connectorId: number, interval: number, self: ChargingStation, debug = false): Promise<void> {
664 try {
665 const sampledValues = {
666 timestamp: new Date().toISOString(),
667 sampledValue: [],
668 };
669 const meterValuesTemplate = self.getConnector(connectorId).MeterValues;
670 for (let index = 0; index < meterValuesTemplate.length; index++) {
671 const connector = self.getConnector(connectorId);
672 // SoC measurand
673 if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === 'SoC' && self._getConfigurationKey('MeterValuesSampledData').value.includes('SoC')) {
674 sampledValues.sampledValue.push({
675 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'Percent' },
676 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
677 measurand: meterValuesTemplate[index].measurand,
678 ...!Utils.isUndefined(meterValuesTemplate[index].location) ? { location: meterValuesTemplate[index].location } : { location: 'EV' },
679 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: Utils.getRandomInt(100) },
680 });
681 const sampledValuesIndex = sampledValues.sampledValue.length - 1;
682 if (sampledValues.sampledValue[sampledValuesIndex].value > 100 || debug) {
683 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`);
684 }
685 // Voltage measurand
686 } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === 'Voltage' && self._getConfigurationKey('MeterValuesSampledData').value.includes('Voltage')) {
687 const voltageMeasurandValue = Utils.getRandomFloatRounded(self._getVoltageOut() + self._getVoltageOut() * 0.1, self._getVoltageOut() - self._getVoltageOut() * 0.1);
688 sampledValues.sampledValue.push({
689 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'V' },
690 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
691 measurand: meterValuesTemplate[index].measurand,
692 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
693 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: voltageMeasurandValue },
694 });
695 for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) {
696 const voltageValue = sampledValues.sampledValue[sampledValues.sampledValue.length - 1].value;
697 let phaseValue;
698 if (voltageValue >= 0 && voltageValue <= 250) {
699 phaseValue = `L${phase}-N`;
700 } else if (voltageValue > 250) {
701 phaseValue = `L${phase}-L${(phase + 1) % self._getNumberOfPhases() !== 0 ? (phase + 1) % self._getNumberOfPhases() : self._getNumberOfPhases()}`;
702 }
703 sampledValues.sampledValue.push({
704 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'V' },
705 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
706 measurand: meterValuesTemplate[index].measurand,
707 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
708 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: voltageMeasurandValue },
709 phase: phaseValue,
710 });
711 }
712 // Power.Active.Import measurand
713 } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === 'Power.Active.Import' && self._getConfigurationKey('MeterValuesSampledData').value.includes('Power.Active.Import')) {
714 // FIXME: factor out powerDivider checks
715 if (Utils.isUndefined(self._stationInfo.powerDivider)) {
716 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
717 logger.error(errMsg);
718 throw Error(errMsg);
719 } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) {
720 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}`;
721 logger.error(errMsg);
722 throw Error(errMsg);
723 }
724 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`;
725 const powerMeasurandValues = {} as MeasurandValues ;
726 const maxPower = Math.round(self._stationInfo.maxPower / self._stationInfo.powerDivider);
727 const maxPowerPerPhase = Math.round((self._stationInfo.maxPower / self._stationInfo.powerDivider) / self._getNumberOfPhases());
728 switch (self._getPowerOutType()) {
729 case 'AC':
730 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
731 powerMeasurandValues.L1 = Utils.getRandomFloatRounded(maxPowerPerPhase);
732 powerMeasurandValues.L2 = 0;
733 powerMeasurandValues.L3 = 0;
734 if (self._getNumberOfPhases() === 3) {
735 powerMeasurandValues.L2 = Utils.getRandomFloatRounded(maxPowerPerPhase);
736 powerMeasurandValues.L3 = Utils.getRandomFloatRounded(maxPowerPerPhase);
737 }
738 powerMeasurandValues.all = Utils.roundTo(powerMeasurandValues.L1 + powerMeasurandValues.L2 + powerMeasurandValues.L3, 2);
739 }
740 break;
741 case 'DC':
742 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
743 powerMeasurandValues.all = Utils.getRandomFloatRounded(maxPower);
744 }
745 break;
746 default:
747 logger.error(errMsg);
748 throw Error(errMsg);
749 }
750 sampledValues.sampledValue.push({
751 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'W' },
752 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
753 measurand: meterValuesTemplate[index].measurand,
754 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
755 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: powerMeasurandValues.all },
756 });
757 const sampledValuesIndex = sampledValues.sampledValue.length - 1;
758 if (sampledValues.sampledValue[sampledValuesIndex].value > maxPower || debug) {
759 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}`);
760 }
761 for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) {
762 const phaseValue = `L${phase}-N`;
763 sampledValues.sampledValue.push({
764 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'W' },
765 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
766 ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand },
767 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
768 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: powerMeasurandValues[`L${phase}`] },
769 phase: phaseValue,
770 });
771 }
772 // Current.Import measurand
773 } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === 'Current.Import' && self._getConfigurationKey('MeterValuesSampledData').value.includes('Current.Import')) {
774 // FIXME: factor out powerDivider checks
775 if (Utils.isUndefined(self._stationInfo.powerDivider)) {
776 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
777 logger.error(errMsg);
778 throw Error(errMsg);
779 } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) {
780 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}`;
781 logger.error(errMsg);
782 throw Error(errMsg);
783 }
784 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`;
785 const currentMeasurandValues = {} as MeasurandValues;
786 let maxAmperage;
787 switch (self._getPowerOutType()) {
788 case 'AC':
789 maxAmperage = ElectricUtils.ampPerPhaseFromPower(self._getNumberOfPhases(), self._stationInfo.maxPower / self._stationInfo.powerDivider, self._getVoltageOut());
790 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
791 currentMeasurandValues.L1 = Utils.getRandomFloatRounded(maxAmperage);
792 currentMeasurandValues.L2 = 0;
793 currentMeasurandValues.L3 = 0;
794 if (self._getNumberOfPhases() === 3) {
795 currentMeasurandValues.L2 = Utils.getRandomFloatRounded(maxAmperage);
796 currentMeasurandValues.L3 = Utils.getRandomFloatRounded(maxAmperage);
797 }
798 currentMeasurandValues.all = Utils.roundTo((currentMeasurandValues.L1 + currentMeasurandValues.L2 + currentMeasurandValues.L3) / self._getNumberOfPhases(), 2);
799 }
800 break;
801 case 'DC':
802 maxAmperage = ElectricUtils.ampTotalFromPower(self._stationInfo.maxPower / self._stationInfo.powerDivider, self._getVoltageOut());
803 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
804 currentMeasurandValues.all = Utils.getRandomFloatRounded(maxAmperage);
805 }
806 break;
807 default:
808 logger.error(errMsg);
809 throw Error(errMsg);
810 }
811 sampledValues.sampledValue.push({
812 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'A' },
813 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
814 measurand: meterValuesTemplate[index].measurand,
815 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
816 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: currentMeasurandValues.all },
817 });
818 const sampledValuesIndex = sampledValues.sampledValue.length - 1;
819 if (sampledValues.sampledValue[sampledValuesIndex].value > maxAmperage || debug) {
820 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}`);
821 }
822 for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) {
823 const phaseValue = `L${phase}`;
824 sampledValues.sampledValue.push({
825 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'A' },
826 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
827 ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand },
828 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
829 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: currentMeasurandValues[phaseValue] },
830 phase: phaseValue,
831 });
832 }
833 // Energy.Active.Import.Register measurand (default)
834 } else if (!meterValuesTemplate[index].measurand || meterValuesTemplate[index].measurand === 'Energy.Active.Import.Register') {
835 // FIXME: factor out powerDivider checks
836 if (Utils.isUndefined(self._stationInfo.powerDivider)) {
837 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
838 logger.error(errMsg);
839 throw Error(errMsg);
840 } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) {
841 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}`;
842 logger.error(errMsg);
843 throw Error(errMsg);
844 }
845 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
846 const measurandValue = Utils.getRandomInt(self._stationInfo.maxPower / (self._stationInfo.powerDivider * 3600000) * interval);
847 // Persist previous value in connector
848 if (connector && !Utils.isNullOrUndefined(connector.lastEnergyActiveImportRegisterValue) && connector.lastEnergyActiveImportRegisterValue >= 0) {
849 connector.lastEnergyActiveImportRegisterValue += measurandValue;
850 } else {
851 connector.lastEnergyActiveImportRegisterValue = 0;
852 }
853 }
854 sampledValues.sampledValue.push({
855 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'Wh' },
856 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
857 ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand },
858 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
859 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: connector.lastEnergyActiveImportRegisterValue },
860 });
861 const sampledValuesIndex = sampledValues.sampledValue.length - 1;
862 const maxConsumption = Math.round(self._stationInfo.maxPower * 3600 / (self._stationInfo.powerDivider * interval));
863 if (sampledValues.sampledValue[sampledValuesIndex].value > maxConsumption || debug) {
864 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}`);
865 }
866 // Unsupported measurand
867 } else {
868 logger.info(`${self._logPrefix()} Unsupported MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'} on connectorId ${connectorId}`);
869 }
870 }
871
872 const payload = {
873 connectorId,
874 transactionId: self.getConnector(connectorId).transactionId,
875 meterValue: sampledValues,
876 };
877 await self.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'MeterValues');
878 } catch (error) {
879 logger.error(self._logPrefix() + ' Send MeterValues error: ' + error);
880 throw error;
881 }
882 }
883
884 async sendError(messageId, err: Error|OCPPError, commandName) {
885 // Check exception type: only OCPP error are accepted
886 const error = err instanceof OCPPError ? err : new OCPPError(Constants.OCPP_ERROR_INTERNAL_ERROR, err.message, err.stack && err.stack);
887 // Send error
888 return this.sendMessage(messageId, error, Constants.OCPP_JSON_CALL_ERROR_MESSAGE, commandName);
889 }
890
891 async sendMessage(messageId, commandParams, messageType = Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName: string) {
892 // eslint-disable-next-line @typescript-eslint/no-this-alias
893 const self = this;
894 // Send a message through wsConnection
895 return new Promise((resolve, reject) => {
896 let messageToSend;
897 // Type of message
898 switch (messageType) {
899 // Request
900 case Constants.OCPP_JSON_CALL_MESSAGE:
901 // Build request
902 this._requests[messageId] = [responseCallback, rejectCallback, commandParams];
903 messageToSend = JSON.stringify([messageType, messageId, commandName, commandParams]);
904 break;
905 // Response
906 case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
907 // Build response
908 messageToSend = JSON.stringify([messageType, messageId, commandParams]);
909 break;
910 // Error Message
911 case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
912 // Build Error Message
913 messageToSend = JSON.stringify([messageType, messageId, commandParams.code ? commandParams.code : Constants.OCPP_ERROR_GENERIC_ERROR, commandParams.message ? commandParams.message : '', commandParams.details ? commandParams.details : {}]);
914 break;
915 }
916 // Check if wsConnection is ready
917 if (this._wsConnection && this._wsConnection.readyState === WebSocket.OPEN) {
918 if (this.getEnableStatistics()) {
919 this._statistics.addMessage(commandName, messageType);
920 }
921 // Yes: Send Message
922 this._wsConnection.send(messageToSend);
923 } else {
924 let dups = false;
925 // Handle dups in buffer
926 for (const message of this._messageQueue) {
927 // Same message
928 if (JSON.stringify(messageToSend) === JSON.stringify(message)) {
929 dups = true;
930 break;
931 }
932 }
933 if (!dups) {
934 // Buffer message
935 this._messageQueue.push(messageToSend);
936 }
937 // Reject it
938 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 : {}));
939 }
940 // Response?
941 if (messageType === Constants.OCPP_JSON_CALL_RESULT_MESSAGE) {
942 // Yes: send Ok
943 resolve();
944 } else if (messageType === Constants.OCPP_JSON_CALL_ERROR_MESSAGE) {
945 // Send timeout
946 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);
947 }
948
949 // Function that will receive the request's response
950 function responseCallback(payload, requestPayload): void {
951 if (self.getEnableStatistics()) {
952 self._statistics.addMessage(commandName, messageType);
953 }
954 // Send the response
955 self.handleResponse(commandName, payload, requestPayload);
956 resolve(payload);
957 }
958
959 // Function that will receive the request's rejection
960 function rejectCallback(error: OCPPError): void {
961 if (self.getEnableStatistics()) {
962 self._statistics.addMessage(commandName, messageType);
963 }
964 logger.debug(`${self._logPrefix()} Error %j occurred when calling command %s with parameters %j`, error, commandName, commandParams);
965 // Build Exception
966 // eslint-disable-next-line no-empty-function
967 self._requests[messageId] = [() => { }, () => { }, '']; // Properly format the request
968 // Send error
969 reject(error);
970 }
971 });
972 }
973
974 handleResponse(commandName: string, payload, requestPayload) {
975 const responseCallbackFn = 'handleResponse' + commandName;
976 if (typeof this[responseCallbackFn] === 'function') {
977 this[responseCallbackFn](payload, requestPayload);
978 } else {
979 logger.error(this._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn);
980 }
981 }
982
983 handleResponseBootNotification(payload, requestPayload) {
984 if (payload.status === 'Accepted') {
985 this._heartbeatInterval = payload.interval * 1000;
986 this._addConfigurationKey('HeartBeatInterval', Utils.convertToInt(payload.interval));
987 this._addConfigurationKey('HeartbeatInterval', Utils.convertToInt(payload.interval), false, false);
988 this._startMessageSequence();
989 } else if (payload.status === 'Pending') {
990 logger.info(this._logPrefix() + ' Charging station in pending state on the central server');
991 } else {
992 logger.info(this._logPrefix() + ' Charging station rejected by the central server');
993 }
994 }
995
996 _initTransactionOnConnector(connectorId) {
997 this.getConnector(connectorId).transactionStarted = false;
998 this.getConnector(connectorId).transactionId = null;
999 this.getConnector(connectorId).idTag = null;
1000 this.getConnector(connectorId).lastEnergyActiveImportRegisterValue = -1;
1001 }
1002
1003 _resetTransactionOnConnector(connectorId) {
1004 this._initTransactionOnConnector(connectorId);
1005 if (this.getConnector(connectorId).transactionSetInterval) {
1006 clearInterval(this.getConnector(connectorId).transactionSetInterval);
1007 }
1008 }
1009
1010 handleResponseStartTransaction(payload, requestPayload) {
1011 if (this.getConnector(requestPayload.connectorId).transactionStarted) {
1012 logger.debug(this._logPrefix() + ' Try to start a transaction on an already used connector ' + requestPayload.connectorId + ': %s', this.getConnector(requestPayload.connectorId));
1013 return;
1014 }
1015
1016 let transactionConnectorId;
1017 for (const connector in this._connectors) {
1018 if (Utils.convertToInt(connector) === Utils.convertToInt(requestPayload.connectorId)) {
1019 transactionConnectorId = connector;
1020 break;
1021 }
1022 }
1023 if (!transactionConnectorId) {
1024 logger.error(this._logPrefix() + ' Try to start a transaction on a non existing connector Id ' + requestPayload.connectorId);
1025 return;
1026 }
1027 if (payload.idTagInfo && payload.idTagInfo.status === 'Accepted') {
1028 this.getConnector(requestPayload.connectorId).transactionStarted = true;
1029 this.getConnector(requestPayload.connectorId).transactionId = payload.transactionId;
1030 this.getConnector(requestPayload.connectorId).idTag = requestPayload.idTag;
1031 this.getConnector(requestPayload.connectorId).lastEnergyActiveImportRegisterValue = 0;
1032 this.sendStatusNotification(requestPayload.connectorId, 'Charging');
1033 logger.info(this._logPrefix() + ' Transaction ' + payload.transactionId + ' STARTED on ' + this._stationInfo.name + '#' + requestPayload.connectorId + ' for idTag ' + requestPayload.idTag);
1034 if (this._stationInfo.powerSharedByConnectors) {
1035 this._stationInfo.powerDivider++;
1036 }
1037 const configuredMeterValueSampleInterval = this._getConfigurationKey('MeterValueSampleInterval');
1038 this._startMeterValues(requestPayload.connectorId,
1039 configuredMeterValueSampleInterval ? configuredMeterValueSampleInterval.value * 1000 : 60000);
1040 } else {
1041 logger.error(this._logPrefix() + ' Starting transaction id ' + payload.transactionId + ' REJECTED with status ' + payload.idTagInfo.status + ', idTag ' + requestPayload.idTag);
1042 this._resetTransactionOnConnector(requestPayload.connectorId);
1043 this.sendStatusNotification(requestPayload.connectorId, 'Available');
1044 }
1045 }
1046
1047 handleResponseStopTransaction(payload, requestPayload) {
1048 let transactionConnectorId;
1049 for (const connector in this._connectors) {
1050 if (this.getConnector(Utils.convertToInt(connector)).transactionId === requestPayload.transactionId) {
1051 transactionConnectorId = connector;
1052 break;
1053 }
1054 }
1055 if (!transactionConnectorId) {
1056 logger.error(this._logPrefix() + ' Try to stop a non existing transaction ' + requestPayload.transactionId);
1057 return;
1058 }
1059 if (payload.idTagInfo && payload.idTagInfo.status === 'Accepted') {
1060 this.sendStatusNotification(transactionConnectorId, 'Available');
1061 if (this._stationInfo.powerSharedByConnectors) {
1062 this._stationInfo.powerDivider--;
1063 }
1064 logger.info(this._logPrefix() + ' Transaction ' + requestPayload.transactionId + ' STOPPED on ' + this._stationInfo.name + '#' + transactionConnectorId);
1065 this._resetTransactionOnConnector(transactionConnectorId);
1066 } else {
1067 logger.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload.transactionId + ' REJECTED with status ' + payload.idTagInfo.status);
1068 }
1069 }
1070
1071 handleResponseStatusNotification(payload, requestPayload) {
1072 logger.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload, requestPayload);
1073 }
1074
1075 handleResponseMeterValues(payload, requestPayload) {
1076 logger.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload, requestPayload);
1077 }
1078
1079 handleResponseHeartbeat(payload, requestPayload) {
1080 logger.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload, requestPayload);
1081 }
1082
1083 async handleRequest(messageId, commandName, commandPayload) {
1084 let response;
1085 // Call
1086 if (typeof this['handleRequest' + commandName] === 'function') {
1087 try {
1088 // Call the method to build the response
1089 response = await this['handleRequest' + commandName](commandPayload);
1090 } catch (error) {
1091 // Log
1092 logger.error(this._logPrefix() + ' Handle request error: ' + error);
1093 // Send back response to inform backend
1094 await this.sendError(messageId, error, commandName);
1095 throw error;
1096 }
1097 } else {
1098 // Throw exception
1099 await this.sendError(messageId, new OCPPError(Constants.OCPP_ERROR_NOT_IMPLEMENTED, `${commandName} is not implemented`, {}), commandName);
1100 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
1101 }
1102 // Send response
1103 await this.sendMessage(messageId, response, Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName);
1104 }
1105
1106 // Simulate charging station restart
1107 async handleRequestReset(commandPayload) {
1108 setImmediate(async () => {
1109 await this.stop(commandPayload.type + 'Reset');
1110 await Utils.sleep(this._stationInfo.resetTime);
1111 await this.start();
1112 });
1113 logger.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${this._stationInfo.resetTime}ms`);
1114 return Constants.OCPP_RESPONSE_ACCEPTED;
1115 }
1116
1117 _getConfigurationKey(key) {
1118 return this._configuration.configurationKey.find((configElement) => configElement.key === key);
1119 }
1120
1121 _addConfigurationKey(key, value, readonly = false, visible = true, reboot = false) {
1122 const keyFound = this._getConfigurationKey(key);
1123 if (!keyFound) {
1124 this._configuration.configurationKey.push({
1125 key,
1126 readonly,
1127 value,
1128 visible,
1129 reboot,
1130 });
1131 }
1132 }
1133
1134 _setConfigurationKeyValue(key, value) {
1135 const keyFound = this._getConfigurationKey(key);
1136 if (keyFound) {
1137 const keyIndex = this._configuration.configurationKey.indexOf(keyFound);
1138 this._configuration.configurationKey[keyIndex].value = value;
1139 }
1140 }
1141
1142 async handleRequestGetConfiguration(commandPayload) {
1143 const configurationKey = [];
1144 const unknownKey = [];
1145 if (Utils.isEmptyArray(commandPayload.key)) {
1146 for (const configuration of this._configuration.configurationKey) {
1147 if (Utils.isUndefined(configuration.visible)) {
1148 configuration.visible = true;
1149 } else {
1150 configuration.visible = Utils.convertToBoolean(configuration.visible);
1151 }
1152 if (!configuration.visible) {
1153 continue;
1154 }
1155 configurationKey.push({
1156 key: configuration.key,
1157 readonly: configuration.readonly,
1158 value: configuration.value,
1159 });
1160 }
1161 } else {
1162 for (const configurationKey of commandPayload.key) {
1163 const keyFound = this._getConfigurationKey(configurationKey);
1164 if (keyFound) {
1165 if (Utils.isUndefined(keyFound.visible)) {
1166 keyFound.visible = true;
1167 } else {
1168 keyFound.visible = Utils.convertToBoolean(configurationKey.visible);
1169 }
1170 if (!keyFound.visible) {
1171 continue;
1172 }
1173 configurationKey.push({
1174 key: keyFound.key,
1175 readonly: keyFound.readonly,
1176 value: keyFound.value,
1177 });
1178 } else {
1179 unknownKey.push(configurationKey);
1180 }
1181 }
1182 }
1183 return {
1184 configurationKey,
1185 unknownKey,
1186 };
1187 }
1188
1189 async handleRequestChangeConfiguration(commandPayload) {
1190 const keyToChange = this._getConfigurationKey(commandPayload.key);
1191 if (!keyToChange) {
1192 return { status: Constants.OCPP_ERROR_NOT_SUPPORTED };
1193 } else if (keyToChange && Utils.convertToBoolean(keyToChange.readonly)) {
1194 return Constants.OCPP_RESPONSE_REJECTED;
1195 } else if (keyToChange && !Utils.convertToBoolean(keyToChange.readonly)) {
1196 const keyIndex = this._configuration.configurationKey.indexOf(keyToChange);
1197 this._configuration.configurationKey[keyIndex].value = commandPayload.value;
1198 let triggerHeartbeatRestart = false;
1199 if (keyToChange.key === 'HeartBeatInterval') {
1200 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload.value);
1201 triggerHeartbeatRestart = true;
1202 }
1203 if (keyToChange.key === 'HeartbeatInterval') {
1204 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload.value);
1205 triggerHeartbeatRestart = true;
1206 }
1207 if (triggerHeartbeatRestart) {
1208 this._heartbeatInterval = Utils.convertToInt(commandPayload.value) * 1000;
1209 // Stop heartbeat
1210 this._stopHeartbeat();
1211 // Start heartbeat
1212 this._startHeartbeat();
1213 }
1214 if (Utils.convertToBoolean(keyToChange.reboot)) {
1215 return Constants.OCPP_RESPONSE_REBOOT_REQUIRED;
1216 }
1217 return Constants.OCPP_RESPONSE_ACCEPTED;
1218 }
1219 }
1220
1221 async handleRequestRemoteStartTransaction(commandPayload) {
1222 const transactionConnectorID = commandPayload.connectorId ? commandPayload.connectorId : '1';
1223 if (this._getAuthorizeRemoteTxRequests() && this._getLocalAuthListEnabled() && this.hasAuthorizedTags()) {
1224 // Check if authorized
1225 if (this._authorizedTags.find((value) => value === commandPayload.idTag)) {
1226 // Authorization successful start transaction
1227 await this.sendStartTransaction(transactionConnectorID, commandPayload.idTag);
1228 logger.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID + ' for idTag ' + commandPayload.idTag);
1229 return Constants.OCPP_RESPONSE_ACCEPTED;
1230 }
1231 logger.error(this._logPrefix() + ' Remote starting transaction REJECTED with status ' + commandPayload.idTagInfo.status + ', idTag ' + commandPayload.idTag);
1232 return Constants.OCPP_RESPONSE_REJECTED;
1233 }
1234 // No local authorization check required => start transaction
1235 await this.sendStartTransaction(transactionConnectorID, commandPayload.idTag);
1236 logger.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID + ' for idTag ' + commandPayload.idTag);
1237 return Constants.OCPP_RESPONSE_ACCEPTED;
1238 }
1239
1240 async handleRequestRemoteStopTransaction(commandPayload) {
1241 for (const connector in this._connectors) {
1242 if (this.getConnector(Utils.convertToInt(connector)).transactionId === commandPayload.transactionId) {
1243 await this.sendStopTransaction(commandPayload.transactionId);
1244 return Constants.OCPP_RESPONSE_ACCEPTED;
1245 }
1246 }
1247 logger.info(this._logPrefix() + ' Try to stop remotely a non existing transaction ' + commandPayload.transactionId);
1248 return Constants.OCPP_RESPONSE_REJECTED;
1249 }
1250}
1251