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