d1745f75529cf8868d7d7f62fcb46851162849ba
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
1 import { BootNotificationResponse, RegistrationStatus } from '../types/ocpp/Responses';
2 import ChargingStationConfiguration, { ConfigurationKey } from '../types/ChargingStationConfiguration';
3 import ChargingStationTemplate, { CurrentOutType, VoltageOut } from '../types/ChargingStationTemplate';
4 import Connectors, { Connector } from '../types/Connectors';
5 import { PerformanceObserver, performance } from 'perf_hooks';
6 import Requests, { AvailabilityType, BootNotificationRequest, IncomingRequest, IncomingRequestCommand } from '../types/ocpp/Requests';
7 import WebSocket, { MessageEvent } from 'ws';
8
9 import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
10 import { ChargePointStatus } from '../types/ocpp/ChargePointStatus';
11 import { ChargingProfile } from '../types/ocpp/ChargingProfile';
12 import ChargingStationInfo from '../types/ChargingStationInfo';
13 import Configuration from '../utils/Configuration';
14 import Constants from '../utils/Constants';
15 import { MessageType } from '../types/ocpp/MessageType';
16 import { MeterValueMeasurand } from '../types/ocpp/MeterValues';
17 import OCPP16IncomingRequestService from './ocpp/1.6/OCCP16IncomingRequestService';
18 import OCPP16RequestService from './ocpp/1.6/OCPP16RequestService';
19 import OCPP16ResponseService from './ocpp/1.6/OCPP16ResponseService';
20 import OCPPError from './OcppError';
21 import OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService';
22 import OCPPRequestService from './ocpp/OCPPRequestService';
23 import { OCPPVersion } from '../types/ocpp/OCPPVersion';
24 import PerformanceStatistics from '../utils/PerformanceStatistics';
25 import { StandardParametersKey } from '../types/ocpp/Configuration';
26 import { StopTransactionReason } from '../types/ocpp/Transaction';
27 import Utils from '../utils/Utils';
28 import { WebSocketCloseEventStatusCode } from '../types/WebSocket';
29 import crypto from 'crypto';
30 import fs from 'fs';
31 import logger from '../utils/Logger';
32 import path from 'path';
33
34 export default class ChargingStation {
35 public stationTemplateFile: string;
36 public authorizedTags: string[];
37 public stationInfo: ChargingStationInfo;
38 public connectors: Connectors;
39 public configuration: ChargingStationConfiguration;
40 public hasStopped: boolean;
41 public wsConnection: WebSocket;
42 public requests: Requests;
43 public messageQueue: string[];
44 public performanceStatistics: PerformanceStatistics;
45 public heartbeatSetInterval: NodeJS.Timeout;
46 public ocppIncomingRequestService: OCPPIncomingRequestService;
47 public ocppRequestService: OCPPRequestService;
48 private index: number;
49 private bootNotificationRequest: BootNotificationRequest;
50 private bootNotificationResponse: BootNotificationResponse;
51 private connectorsConfigurationHash: string;
52 private supervisionUrl: string;
53 private wsConnectionUrl: string;
54 private hasSocketRestarted: boolean;
55 private autoReconnectRetryCount: number;
56 private automaticTransactionGeneration: AutomaticTransactionGenerator;
57 private performanceObserver: PerformanceObserver;
58 private webSocketPingSetInterval: NodeJS.Timeout;
59
60 constructor(index: number, stationTemplateFile: string) {
61 this.index = index;
62 this.stationTemplateFile = stationTemplateFile;
63 this.connectors = {} as Connectors;
64 this.initialize();
65
66 this.hasStopped = false;
67 this.hasSocketRestarted = false;
68 this.autoReconnectRetryCount = 0;
69
70 this.requests = {} as Requests;
71 this.messageQueue = [] as string[];
72
73 this.authorizedTags = this.getAuthorizedTags();
74 }
75
76 public logPrefix(): string {
77 return Utils.logPrefix(` ${this.stationInfo.chargingStationId} |`);
78 }
79
80 public getRandomTagId(): string {
81 const index = Math.floor(Math.random() * this.authorizedTags.length);
82 return this.authorizedTags[index];
83 }
84
85 public hasAuthorizedTags(): boolean {
86 return !Utils.isEmptyArray(this.authorizedTags);
87 }
88
89 public getEnableStatistics(): boolean {
90 return !Utils.isUndefined(this.stationInfo.enableStatistics) ? this.stationInfo.enableStatistics : true;
91 }
92
93 public getNumberOfPhases(): number {
94 switch (this.getCurrentOutType()) {
95 case CurrentOutType.AC:
96 return !Utils.isUndefined(this.stationInfo.numberOfPhases) ? this.stationInfo.numberOfPhases : 3;
97 case CurrentOutType.DC:
98 return 0;
99 }
100 }
101
102 public isWebSocketOpen(): boolean {
103 return this.wsConnection?.readyState === WebSocket.OPEN;
104 }
105
106 public isRegistered(): boolean {
107 return this.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED;
108 }
109
110 public isChargingStationAvailable(): boolean {
111 return this.getConnector(0).availability === AvailabilityType.OPERATIVE;
112 }
113
114 public isConnectorAvailable(id: number): boolean {
115 return this.getConnector(id).availability === AvailabilityType.OPERATIVE;
116 }
117
118 public getConnector(id: number): Connector {
119 return this.connectors[id];
120 }
121
122 public getCurrentOutType(): CurrentOutType {
123 return !Utils.isUndefined(this.stationInfo.currentOutType) ? this.stationInfo.currentOutType : CurrentOutType.AC;
124 }
125
126 public getVoltageOut(): number {
127 const errMsg = `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
128 let defaultVoltageOut: number;
129 switch (this.getCurrentOutType()) {
130 case CurrentOutType.AC:
131 defaultVoltageOut = VoltageOut.VOLTAGE_230;
132 break;
133 case CurrentOutType.DC:
134 defaultVoltageOut = VoltageOut.VOLTAGE_400;
135 break;
136 default:
137 logger.error(errMsg);
138 throw Error(errMsg);
139 }
140 return !Utils.isUndefined(this.stationInfo.voltageOut) ? this.stationInfo.voltageOut : defaultVoltageOut;
141 }
142
143 public getTransactionIdTag(transactionId: number): string {
144 for (const connector in this.connectors) {
145 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) {
146 return this.getConnector(Utils.convertToInt(connector)).idTag;
147 }
148 }
149 }
150
151 public getTransactionMeterStop(transactionId: number): number {
152 for (const connector in this.connectors) {
153 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) {
154 return this.getConnector(Utils.convertToInt(connector)).lastEnergyActiveImportRegisterValue;
155 }
156 }
157 }
158
159 public getAuthorizeRemoteTxRequests(): boolean {
160 const authorizeRemoteTxRequests = this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests);
161 return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false;
162 }
163
164 public getLocalAuthListEnabled(): boolean {
165 const localAuthListEnabled = this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled);
166 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
167 }
168
169 public restartWebSocketPing(): void {
170 // Stop WebSocket ping
171 this.stopWebSocketPing();
172 // Start WebSocket ping
173 this.startWebSocketPing();
174 }
175
176 public startHeartbeat(): void {
177 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval) {
178 // eslint-disable-next-line @typescript-eslint/no-misused-promises
179 this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
180 await this.ocppRequestService.sendHeartbeat();
181 }, this.getHeartbeatInterval());
182 logger.info(this.logPrefix() + ' Heartbeat started every ' + Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
183 } else if (this.heartbeatSetInterval) {
184 logger.info(this.logPrefix() + ' Heartbeat already started every ' + Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
185 } else {
186 logger.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
187 }
188 }
189
190 public restartHeartbeat(): void {
191 // Stop heartbeat
192 this.stopHeartbeat();
193 // Start heartbeat
194 this.startHeartbeat();
195 }
196
197 public startMeterValues(connectorId: number, interval: number): void {
198 if (connectorId === 0) {
199 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
200 return;
201 }
202 if (!this.getConnector(connectorId)) {
203 logger.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
204 return;
205 }
206 if (!this.getConnector(connectorId)?.transactionStarted) {
207 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
208 return;
209 } else if (this.getConnector(connectorId)?.transactionStarted && !this.getConnector(connectorId)?.transactionId) {
210 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
211 return;
212 }
213 if (interval > 0) {
214 // eslint-disable-next-line @typescript-eslint/no-misused-promises
215 this.getConnector(connectorId).transactionSetInterval = setInterval(async (): Promise<void> => {
216 if (this.getEnableStatistics()) {
217 const sendMeterValues = performance.timerify(this.ocppRequestService.sendMeterValues);
218 this.performanceObserver.observe({
219 entryTypes: ['function'],
220 });
221 await sendMeterValues(connectorId, this.getConnector(connectorId).transactionId, interval, this.ocppRequestService);
222 } else {
223 await this.ocppRequestService.sendMeterValues(connectorId, this.getConnector(connectorId).transactionId, interval, this.ocppRequestService);
224 }
225 }, interval);
226 } else {
227 logger.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.milliSecondsToHHMMSS(interval) : interval}, not sending MeterValues`);
228 }
229 }
230
231 public start(): void {
232 this.openWSConnection();
233 // Monitor authorization file
234 this.startAuthorizationFileMonitoring();
235 // Monitor station template file
236 this.startStationTemplateFileMonitoring();
237 // Handle Socket incoming messages
238 this.wsConnection.on('message', this.onMessage.bind(this));
239 // Handle Socket error
240 this.wsConnection.on('error', this.onError.bind(this));
241 // Handle Socket close
242 this.wsConnection.on('close', this.onClose.bind(this));
243 // Handle Socket opening connection
244 this.wsConnection.on('open', this.onOpen.bind(this));
245 // Handle Socket ping
246 this.wsConnection.on('ping', this.onPing.bind(this));
247 // Handle Socket pong
248 this.wsConnection.on('pong', this.onPong.bind(this));
249 }
250
251 public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
252 // Stop message sequence
253 await this.stopMessageSequence(reason);
254 for (const connector in this.connectors) {
255 if (Utils.convertToInt(connector) > 0) {
256 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.UNAVAILABLE);
257 this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.UNAVAILABLE;
258 }
259 }
260 if (this.isWebSocketOpen()) {
261 this.wsConnection.close();
262 }
263 this.bootNotificationResponse = null;
264 this.hasStopped = true;
265 }
266
267 public getConfigurationKey(key: string | StandardParametersKey, caseInsensitive = false): ConfigurationKey {
268 const configurationKey: ConfigurationKey = this.configuration.configurationKey.find((configElement) => {
269 if (caseInsensitive) {
270 return configElement.key.toLowerCase() === key.toLowerCase();
271 }
272 return configElement.key === key;
273 });
274 return configurationKey;
275 }
276
277 public addConfigurationKey(key: string | StandardParametersKey, value: string, readonly = false, visible = true, reboot = false): void {
278 const keyFound = this.getConfigurationKey(key);
279 if (!keyFound) {
280 this.configuration.configurationKey.push({
281 key,
282 readonly,
283 value,
284 visible,
285 reboot,
286 });
287 } else {
288 logger.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound);
289 }
290 }
291
292 public setConfigurationKeyValue(key: string | StandardParametersKey, value: string): void {
293 const keyFound = this.getConfigurationKey(key);
294 if (keyFound) {
295 const keyIndex = this.configuration.configurationKey.indexOf(keyFound);
296 this.configuration.configurationKey[keyIndex].value = value;
297 } else {
298 logger.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key, value });
299 }
300 }
301
302 public setChargingProfile(connectorId: number, cp: ChargingProfile): boolean {
303 if (!Utils.isEmptyArray(this.getConnector(connectorId).chargingProfiles)) {
304 this.getConnector(connectorId).chargingProfiles.forEach((chargingProfile: ChargingProfile, index: number) => {
305 if (chargingProfile.chargingProfileId === cp.chargingProfileId
306 || (chargingProfile.stackLevel === cp.stackLevel && chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)) {
307 this.getConnector(connectorId).chargingProfiles[index] = cp;
308 return true;
309 }
310 });
311 }
312 this.getConnector(connectorId).chargingProfiles.push(cp);
313 return true;
314 }
315
316 public resetTransactionOnConnector(connectorId: number): void {
317 this.initTransactionOnConnector(connectorId);
318 if (this.getConnector(connectorId)?.transactionSetInterval) {
319 clearInterval(this.getConnector(connectorId).transactionSetInterval);
320 }
321 }
322
323 public addToMessageQueue(message: string): void {
324 let dups = false;
325 // Handle dups in message queue
326 for (const bufferedMessage of this.messageQueue) {
327 // Message already in the queue
328 if (message === bufferedMessage) {
329 dups = true;
330 break;
331 }
332 }
333 if (!dups) {
334 // Queue message
335 this.messageQueue.push(message);
336 }
337 }
338
339 private flushMessageQueue() {
340 if (!Utils.isEmptyArray(this.messageQueue)) {
341 this.messageQueue.forEach((message, index) => {
342 this.messageQueue.splice(index, 1);
343 this.wsConnection.send(message);
344 });
345 }
346 }
347
348 private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
349 // In case of multiple instances: add instance index to charging station id
350 let instanceIndex = process.env.CF_INSTANCE_INDEX ? process.env.CF_INSTANCE_INDEX : 0;
351 instanceIndex = instanceIndex > 0 ? instanceIndex : '';
352 const idSuffix = stationTemplate.nameSuffix ? stationTemplate.nameSuffix : '';
353 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex.toString() + ('000000000' + this.index.toString()).substr(('000000000' + this.index.toString()).length - 4) + idSuffix;
354 }
355
356 private buildStationInfo(): ChargingStationInfo {
357 let stationTemplateFromFile: ChargingStationTemplate;
358 try {
359 // Load template file
360 const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r');
361 stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate;
362 fs.closeSync(fileDescriptor);
363 } catch (error) {
364 logger.error('Template file ' + this.stationTemplateFile + ' loading error: %j', error);
365 throw error;
366 }
367 const stationInfo: ChargingStationInfo = stationTemplateFromFile || {} as ChargingStationInfo;
368 if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
369 stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
370 stationInfo.maxPower = stationTemplateFromFile.power[Math.floor(Math.random() * stationTemplateFromFile.power.length)];
371 } else {
372 stationInfo.maxPower = stationTemplateFromFile.power as number;
373 }
374 stationInfo.chargingStationId = this.getChargingStationId(stationTemplateFromFile);
375 stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
376 return stationInfo;
377 }
378
379 private getOCPPVersion(): OCPPVersion {
380 return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
381 }
382
383 private handleUnsupportedVersion(version: OCPPVersion) {
384 const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
385 logger.error(errMsg);
386 throw new Error(errMsg);
387 }
388
389 private initialize(): void {
390 this.stationInfo = this.buildStationInfo();
391 this.bootNotificationRequest = {
392 chargePointModel: this.stationInfo.chargePointModel,
393 chargePointVendor: this.stationInfo.chargePointVendor,
394 ...!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix },
395 ...!Utils.isUndefined(this.stationInfo.firmwareVersion) && { firmwareVersion: this.stationInfo.firmwareVersion },
396 };
397 this.configuration = this.getTemplateChargingStationConfiguration();
398 this.supervisionUrl = this.getSupervisionURL();
399 this.wsConnectionUrl = this.supervisionUrl + '/' + this.stationInfo.chargingStationId;
400 // Build connectors if needed
401 const maxConnectors = this.getMaxNumberOfConnectors();
402 if (maxConnectors <= 0) {
403 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
404 }
405 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
406 if (templateMaxConnectors <= 0) {
407 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
408 }
409 if (!this.stationInfo.Connectors[0]) {
410 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
411 }
412 // Sanity check
413 if (maxConnectors > (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this.stationInfo.randomConnectors) {
414 logger.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
415 this.stationInfo.randomConnectors = true;
416 }
417 const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()).digest('hex');
418 // FIXME: Handle shrinking the number of connectors
419 if (!this.connectors || (this.connectors && this.connectorsConfigurationHash !== connectorsConfigHash)) {
420 this.connectorsConfigurationHash = connectorsConfigHash;
421 // Add connector Id 0
422 let lastConnector = '0';
423 for (lastConnector in this.stationInfo.Connectors) {
424 if (Utils.convertToInt(lastConnector) === 0 && this.getUseConnectorId0() && this.stationInfo.Connectors[lastConnector]) {
425 this.connectors[lastConnector] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[lastConnector]);
426 this.connectors[lastConnector].availability = AvailabilityType.OPERATIVE;
427 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
428 this.connectors[lastConnector].chargingProfiles = [];
429 }
430 }
431 }
432 // Generate all connectors
433 if ((this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
434 for (let index = 1; index <= maxConnectors; index++) {
435 const randConnectorID = this.stationInfo.randomConnectors ? Utils.getRandomInt(Utils.convertToInt(lastConnector), 1) : index;
436 this.connectors[index] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[randConnectorID]);
437 this.connectors[index].availability = AvailabilityType.OPERATIVE;
438 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
439 this.connectors[index].chargingProfiles = [];
440 }
441 }
442 }
443 }
444 // Avoid duplication of connectors related information
445 delete this.stationInfo.Connectors;
446 // Initialize transaction attributes on connectors
447 for (const connector in this.connectors) {
448 if (Utils.convertToInt(connector) > 0 && !this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
449 this.initTransactionOnConnector(Utils.convertToInt(connector));
450 }
451 }
452 switch (this.getOCPPVersion()) {
453 case OCPPVersion.VERSION_16:
454 this.ocppIncomingRequestService = new OCPP16IncomingRequestService(this);
455 this.ocppRequestService = new OCPP16RequestService(this, new OCPP16ResponseService(this));
456 break;
457 default:
458 this.handleUnsupportedVersion(this.getOCPPVersion());
459 break;
460 }
461 // OCPP parameters
462 this.addConfigurationKey(StandardParametersKey.NumberOfConnectors, this.getNumberOfConnectors().toString(), true);
463 if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) {
464 this.addConfigurationKey(StandardParametersKey.MeterValuesSampledData, MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER);
465 }
466 this.stationInfo.powerDivider = this.getPowerDivider();
467 if (this.getEnableStatistics()) {
468 this.performanceStatistics = new PerformanceStatistics(this.stationInfo.chargingStationId);
469 this.performanceObserver = new PerformanceObserver((list) => {
470 const entry = list.getEntries()[0];
471 this.performanceStatistics.logPerformance(entry, Constants.ENTITY_CHARGING_STATION);
472 this.performanceObserver.disconnect();
473 });
474 }
475 }
476
477 private async onOpen(): Promise<void> {
478 logger.info(`${this.logPrefix()} Is connected to server through ${this.wsConnectionUrl}`);
479 if (!this.isRegistered()) {
480 // Send BootNotification
481 let registrationRetryCount = 0;
482 do {
483 this.bootNotificationResponse = await this.ocppRequestService.sendBootNotification(this.bootNotificationRequest.chargePointModel,
484 this.bootNotificationRequest.chargePointVendor, this.bootNotificationRequest.chargeBoxSerialNumber, this.bootNotificationRequest.firmwareVersion);
485 if (!this.isRegistered()) {
486 registrationRetryCount++;
487 await Utils.sleep(this.bootNotificationResponse?.interval ? this.bootNotificationResponse.interval * 1000 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL);
488 }
489 } while (!this.isRegistered() && (registrationRetryCount <= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
490 }
491 if (this.isRegistered()) {
492 await this.startMessageSequence();
493 this.hasStopped && (this.hasStopped = false);
494 if (this.hasSocketRestarted && this.isWebSocketOpen()) {
495 this.flushMessageQueue();
496 }
497 } else {
498 logger.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
499 }
500 this.autoReconnectRetryCount = 0;
501 this.hasSocketRestarted = false;
502 }
503
504 private async onClose(closeEvent): Promise<void> {
505 switch (closeEvent) {
506 case WebSocketCloseEventStatusCode.CLOSE_NORMAL: // Normal close
507 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
508 logger.info(`${this.logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
509 this.autoReconnectRetryCount = 0;
510 break;
511 default: // Abnormal close
512 logger.error(`${this.logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
513 await this.reconnect(closeEvent);
514 break;
515 }
516 }
517
518 private async onMessage(messageEvent: MessageEvent): Promise<void> {
519 let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [0, '', '' as IncomingRequestCommand, {}, {}];
520 let responseCallback: (payload: Record<string, unknown> | string, requestPayload: Record<string, unknown>) => void;
521 let rejectCallback: (error: OCPPError) => void;
522 let requestPayload: Record<string, unknown>;
523 let errMsg: string;
524 try {
525 // Parse the message
526 [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(messageEvent.toString()) as IncomingRequest;
527
528 // Check the Type of message
529 switch (messageType) {
530 // Incoming Message
531 case MessageType.CALL_MESSAGE:
532 if (this.getEnableStatistics()) {
533 this.performanceStatistics.addMessage(commandName, messageType);
534 }
535 // Process the call
536 await this.ocppIncomingRequestService.handleRequest(messageId, commandName, commandPayload);
537 break;
538 // Outcome Message
539 case MessageType.CALL_RESULT_MESSAGE:
540 // Respond
541 if (Utils.isIterable(this.requests[messageId])) {
542 [responseCallback, , requestPayload] = this.requests[messageId];
543 } else {
544 throw new Error(`Response request for message id ${messageId} is not iterable`);
545 }
546 if (!responseCallback) {
547 // Error
548 throw new Error(`Response request for unknown message id ${messageId}`);
549 }
550 delete this.requests[messageId];
551 responseCallback(commandName, requestPayload);
552 break;
553 // Error Message
554 case MessageType.CALL_ERROR_MESSAGE:
555 if (!this.requests[messageId]) {
556 // Error
557 throw new Error(`Error request for unknown message id ${messageId}`);
558 }
559 if (Utils.isIterable(this.requests[messageId])) {
560 [, rejectCallback] = this.requests[messageId];
561 } else {
562 throw new Error(`Error request for message id ${messageId} is not iterable`);
563 }
564 delete this.requests[messageId];
565 rejectCallback(new OCPPError(commandName, commandPayload.toString(), errorDetails));
566 break;
567 // Error
568 default:
569 errMsg = `${this.logPrefix()} Wrong message type ${messageType}`;
570 logger.error(errMsg);
571 throw new Error(errMsg);
572 }
573 } catch (error) {
574 // Log
575 logger.error('%s Incoming message %j processing error %j on request content type %j', this.logPrefix(), messageEvent, error, this.requests[messageId]);
576 // Send error
577 messageType !== MessageType.CALL_ERROR_MESSAGE && await this.ocppRequestService.sendError(messageId, error, commandName);
578 }
579 }
580
581 private onPing(): void {
582 logger.debug(this.logPrefix() + ' Has received a WS ping (rfc6455) from the server');
583 }
584
585 private onPong(): void {
586 logger.debug(this.logPrefix() + ' Has received a WS pong (rfc6455) from the server');
587 }
588
589 private async onError(errorEvent): Promise<void> {
590 logger.error(this.logPrefix() + ' Socket error: %j', errorEvent);
591 // pragma switch (errorEvent.code) {
592 // case 'ECONNREFUSED':
593 // await this._reconnect(errorEvent);
594 // break;
595 // }
596 }
597
598 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration {
599 return this.stationInfo.Configuration ? this.stationInfo.Configuration : {} as ChargingStationConfiguration;
600 }
601
602 private getAuthorizationFile(): string {
603 return this.stationInfo.authorizationFile && path.join(path.resolve(__dirname, '../'), 'assets', path.basename(this.stationInfo.authorizationFile));
604 }
605
606 private getAuthorizedTags(): string[] {
607 let authorizedTags: string[] = [];
608 const authorizationFile = this.getAuthorizationFile();
609 if (authorizationFile) {
610 try {
611 // Load authorization file
612 const fileDescriptor = fs.openSync(authorizationFile, 'r');
613 authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[];
614 fs.closeSync(fileDescriptor);
615 } catch (error) {
616 logger.error(this.logPrefix() + ' Authorization file ' + authorizationFile + ' loading error: %j', error);
617 throw error;
618 }
619 } else {
620 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile);
621 }
622 return authorizedTags;
623 }
624
625 private getUseConnectorId0(): boolean {
626 return !Utils.isUndefined(this.stationInfo.useConnectorId0) ? this.stationInfo.useConnectorId0 : true;
627 }
628
629 private getNumberOfRunningTransactions(): number {
630 let trxCount = 0;
631 for (const connector in this.connectors) {
632 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
633 trxCount++;
634 }
635 }
636 return trxCount;
637 }
638
639 // 0 for disabling
640 private getConnectionTimeout(): number {
641 if (!Utils.isUndefined(this.stationInfo.connectionTimeout)) {
642 return this.stationInfo.connectionTimeout;
643 }
644 if (!Utils.isUndefined(Configuration.getConnectionTimeout())) {
645 return Configuration.getConnectionTimeout();
646 }
647 return 30;
648 }
649
650 // -1 for unlimited, 0 for disabling
651 private getAutoReconnectMaxRetries(): number {
652 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
653 return this.stationInfo.autoReconnectMaxRetries;
654 }
655 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
656 return Configuration.getAutoReconnectMaxRetries();
657 }
658 return -1;
659 }
660
661 // 0 for disabling
662 private getRegistrationMaxRetries(): number {
663 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
664 return this.stationInfo.registrationMaxRetries;
665 }
666 return -1;
667 }
668
669 private getPowerDivider(): number {
670 let powerDivider = this.getNumberOfConnectors();
671 if (this.stationInfo.powerSharedByConnectors) {
672 powerDivider = this.getNumberOfRunningTransactions();
673 }
674 return powerDivider;
675 }
676
677 private getTemplateMaxNumberOfConnectors(): number {
678 return Object.keys(this.stationInfo.Connectors).length;
679 }
680
681 private getMaxNumberOfConnectors(): number {
682 let maxConnectors = 0;
683 if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) {
684 const numberOfConnectors = this.stationInfo.numberOfConnectors as number[];
685 // Distribute evenly the number of connectors
686 maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length];
687 } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) {
688 maxConnectors = this.stationInfo.numberOfConnectors as number;
689 } else {
690 maxConnectors = this.stationInfo.Connectors[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
691 }
692 return maxConnectors;
693 }
694
695 private getNumberOfConnectors(): number {
696 return this.connectors[0] ? Object.keys(this.connectors).length - 1 : Object.keys(this.connectors).length;
697 }
698
699 private async startMessageSequence(): Promise<void> {
700 // Start WebSocket ping
701 this.startWebSocketPing();
702 // Start heartbeat
703 this.startHeartbeat();
704 // Initialize connectors status
705 for (const connector in this.connectors) {
706 if (Utils.convertToInt(connector) === 0) {
707 continue;
708 } else if (!this.hasStopped && !this.getConnector(Utils.convertToInt(connector))?.status && this.getConnector(Utils.convertToInt(connector))?.bootStatus) {
709 // Send status in template at startup
710 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
711 this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus;
712 } else if (this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.bootStatus) {
713 // Send status in template after reset
714 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
715 this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus;
716 } else if (!this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.status) {
717 // Send previous status at template reload
718 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).status);
719 } else {
720 // Send default status
721 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.AVAILABLE);
722 this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.AVAILABLE;
723 }
724 }
725 // Start the ATG
726 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
727 if (!this.automaticTransactionGeneration) {
728 this.automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
729 }
730 if (this.automaticTransactionGeneration.timeToStop) {
731 // The ATG might sleep
732 void this.automaticTransactionGeneration.start();
733 }
734 }
735 if (this.getEnableStatistics()) {
736 this.performanceStatistics.start();
737 }
738 }
739
740 private async stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
741 // Stop WebSocket ping
742 this.stopWebSocketPing();
743 // Stop heartbeat
744 this.stopHeartbeat();
745 // Stop the ATG
746 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
747 this.automaticTransactionGeneration &&
748 !this.automaticTransactionGeneration.timeToStop) {
749 await this.automaticTransactionGeneration.stop(reason);
750 } else {
751 for (const connector in this.connectors) {
752 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
753 const transactionId = this.getConnector(Utils.convertToInt(connector)).transactionId;
754 await this.ocppRequestService.sendStopTransaction(transactionId, this.getTransactionMeterStop(transactionId), this.getTransactionIdTag(transactionId), reason);
755 }
756 }
757 }
758 }
759
760 private startWebSocketPing(): void {
761 const webSocketPingInterval: number = this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval) ? Utils.convertToInt(this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value) : 0;
762 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
763 this.webSocketPingSetInterval = setInterval(() => {
764 if (this.isWebSocketOpen()) {
765 this.wsConnection.ping((): void => { });
766 }
767 }, webSocketPingInterval * 1000);
768 logger.info(this.logPrefix() + ' WebSocket ping started every ' + Utils.secondsToHHMMSS(webSocketPingInterval));
769 } else if (this.webSocketPingSetInterval) {
770 logger.info(this.logPrefix() + ' WebSocket ping every ' + Utils.secondsToHHMMSS(webSocketPingInterval) + ' already started');
771 } else {
772 logger.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
773 }
774 }
775
776 private stopWebSocketPing(): void {
777 if (this.webSocketPingSetInterval) {
778 clearInterval(this.webSocketPingSetInterval);
779 this.webSocketPingSetInterval = null;
780 }
781 }
782
783 private getSupervisionURL(): string {
784 const supervisionUrls = Utils.cloneObject<string | string[]>(this.stationInfo.supervisionURL ? this.stationInfo.supervisionURL : Configuration.getSupervisionURLs());
785 let indexUrl = 0;
786 if (!Utils.isEmptyArray(supervisionUrls)) {
787 if (Configuration.getDistributeStationsToTenantsEqually()) {
788 indexUrl = this.index % supervisionUrls.length;
789 } else {
790 // Get a random url
791 indexUrl = Math.floor(Math.random() * supervisionUrls.length);
792 }
793 return supervisionUrls[indexUrl];
794 }
795 return supervisionUrls as string;
796 }
797
798 private getHeartbeatInterval(): number {
799 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
800 if (HeartbeatInterval) {
801 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
802 }
803 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
804 if (HeartBeatInterval) {
805 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
806 }
807 }
808
809 private stopHeartbeat(): void {
810 if (this.heartbeatSetInterval) {
811 clearInterval(this.heartbeatSetInterval);
812 this.heartbeatSetInterval = null;
813 }
814 }
815
816 private openWSConnection(options?: WebSocket.ClientOptions, forceCloseOpened = false): void {
817 if (Utils.isUndefined(options)) {
818 options = {} as WebSocket.ClientOptions;
819 }
820 if (Utils.isUndefined(options.handshakeTimeout)) {
821 options.handshakeTimeout = this.getConnectionTimeout() * 1000;
822 }
823 if (this.isWebSocketOpen() && forceCloseOpened) {
824 this.wsConnection.close();
825 }
826 let protocol;
827 switch (this.getOCPPVersion()) {
828 case OCPPVersion.VERSION_16:
829 protocol = 'ocpp' + OCPPVersion.VERSION_16;
830 break;
831 default:
832 this.handleUnsupportedVersion(this.getOCPPVersion());
833 break;
834 }
835 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
836 logger.info(this.logPrefix() + ' Will communicate through URL ' + this.supervisionUrl);
837 }
838
839 private startAuthorizationFileMonitoring(): void {
840 fs.watch(this.getAuthorizationFile()).on('change', (e) => {
841 try {
842 logger.debug(this.logPrefix() + ' Authorization file ' + this.getAuthorizationFile() + ' have changed, reload');
843 // Initialize authorizedTags
844 this.authorizedTags = this.getAuthorizedTags();
845 } catch (error) {
846 logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error);
847 }
848 });
849 }
850
851 private startStationTemplateFileMonitoring(): void {
852 // eslint-disable-next-line @typescript-eslint/no-misused-promises
853 fs.watch(this.stationTemplateFile).on('change', async (e): Promise<void> => {
854 try {
855 logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload');
856 // Initialize
857 this.initialize();
858 // Stop the ATG
859 if (!this.stationInfo.AutomaticTransactionGenerator.enable &&
860 this.automaticTransactionGeneration) {
861 await this.automaticTransactionGeneration.stop();
862 }
863 // Start the ATG
864 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
865 if (!this.automaticTransactionGeneration) {
866 this.automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
867 }
868 if (this.automaticTransactionGeneration.timeToStop) {
869 // The ATG might sleep
870 void this.automaticTransactionGeneration.start();
871 }
872 }
873 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
874 } catch (error) {
875 logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error);
876 }
877 });
878 }
879
880 private getReconnectExponentialDelay(): boolean {
881 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false;
882 }
883
884 private async reconnect(error): Promise<void> {
885 // Stop heartbeat
886 this.stopHeartbeat();
887 // Stop the ATG if needed
888 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
889 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
890 this.automaticTransactionGeneration &&
891 !this.automaticTransactionGeneration.timeToStop) {
892 this.automaticTransactionGeneration.stop().catch(() => { });
893 }
894 if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
895 this.autoReconnectRetryCount++;
896 const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000);
897 logger.error(`${this.logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
898 await Utils.sleep(reconnectDelay);
899 logger.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount.toString());
900 this.openWSConnection({ handshakeTimeout: reconnectDelay - 100 });
901 this.hasSocketRestarted = true;
902 } else if (this.getAutoReconnectMaxRetries() !== -1) {
903 logger.error(`${this.logPrefix()} Socket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
904 }
905 }
906
907 private initTransactionOnConnector(connectorId: number): void {
908 this.getConnector(connectorId).transactionStarted = false;
909 this.getConnector(connectorId).transactionId = null;
910 this.getConnector(connectorId).idTag = null;
911 this.getConnector(connectorId).lastEnergyActiveImportRegisterValue = -1;
912 }
913 }
914