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