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