Fix build due to winston types definition
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
CommitLineData
b4d34251
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
32b02249 3import { AvailabilityType, BootNotificationRequest, CachedRequest, IncomingRequest, IncomingRequestCommand, RequestCommand } from '../types/ocpp/Requests';
efa43e52 4import { BootNotificationResponse, RegistrationStatus } from '../types/ocpp/Responses';
e118beaa 5import ChargingStationConfiguration, { ConfigurationKey } from '../types/ChargingStationConfiguration';
4c2b4904 6import ChargingStationTemplate, { CurrentType, PowerUnits, Voltage } from '../types/ChargingStationTemplate';
12fc74d6 7import { ConnectorPhaseRotation, StandardParametersKey, SupportedFeatureProfiles, VendorDefaultParametersKey } from '../types/ocpp/Configuration';
9ccca265 8import { MeterValueMeasurand, MeterValuePhase } from '../types/ocpp/MeterValues';
16b0d4e7 9import { WSError, WebSocketCloseEventStatusCode } from '../types/WebSocket';
58fad749 10import WebSocket, { ClientOptions, Data, OPEN } from 'ws';
3f40bc9c 11
6af9012e 12import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
c0560973
JB
13import { ChargePointStatus } from '../types/ocpp/ChargePointStatus';
14import { ChargingProfile } from '../types/ocpp/ChargingProfile';
9ac86a7e 15import ChargingStationInfo from '../types/ChargingStationInfo';
ee0f106b 16import { ChargingStationWorkerMessageEvents } from '../types/ChargingStationWorker';
15042c5f 17import { ClientRequestArgs } from 'http';
6af9012e 18import Configuration from '../utils/Configuration';
057e2042 19import { ConnectorStatus } from '../types/ConnectorStatus';
63b48f77 20import Constants from '../utils/Constants';
14763b46 21import { ErrorType } from '../types/ocpp/ErrorType';
23132a44 22import FileUtils from '../utils/FileUtils';
d2a64eb5 23import { MessageType } from '../types/ocpp/MessageType';
e7171280 24import OCPP16IncomingRequestService from './ocpp/1.6/OCPP16IncomingRequestService';
c0560973
JB
25import OCPP16RequestService from './ocpp/1.6/OCPP16RequestService';
26import OCPP16ResponseService from './ocpp/1.6/OCPP16ResponseService';
e58068fd 27import OCPPError from '../exception/OCPPError';
c0560973
JB
28import OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService';
29import OCPPRequestService from './ocpp/OCPPRequestService';
30import { OCPPVersion } from '../types/ocpp/OCPPVersion';
a6b3c6c3 31import PerformanceStatistics from '../performance/PerformanceStatistics';
057e2042 32import { SampledValueTemplate } from '../types/MeasurandPerPhaseSampledValueTemplates';
c0560973 33import { StopTransactionReason } from '../types/ocpp/Transaction';
57939a9d 34import { URL } from 'url';
6af9012e 35import Utils from '../utils/Utils';
3f40bc9c
JB
36import crypto from 'crypto';
37import fs from 'fs';
6af9012e 38import logger from '../utils/Logger';
ee0f106b 39import { parentPort } from 'worker_threads';
bf1866b2 40import path from 'path';
3f40bc9c
JB
41
42export default class ChargingStation {
9e23580d 43 public readonly stationTemplateFile: string;
c0560973 44 public authorizedTags: string[];
6e0964c8 45 public stationInfo!: ChargingStationInfo;
9e23580d 46 public readonly connectors: Map<number, ConnectorStatus>;
6e0964c8 47 public configuration!: ChargingStationConfiguration;
6e0964c8 48 public wsConnection!: WebSocket;
9e23580d 49 public readonly requests: Map<string, CachedRequest>;
6e0964c8
JB
50 public performanceStatistics!: PerformanceStatistics;
51 public heartbeatSetInterval!: NodeJS.Timeout;
6e0964c8 52 public ocppRequestService!: OCPPRequestService;
9e23580d 53 private readonly index: number;
6e0964c8
JB
54 private bootNotificationRequest!: BootNotificationRequest;
55 private bootNotificationResponse!: BootNotificationResponse | null;
56 private connectorsConfigurationHash!: string;
a472cf2b 57 private ocppIncomingRequestService!: OCPPIncomingRequestService;
8e242273 58 private readonly messageBuffer: Set<string>;
12fc74d6 59 private wsConfiguredConnectionUrl!: URL;
265e4266 60 private wsConnectionRestarted: boolean;
a472cf2b 61 private stopped: boolean;
ad2f27c3 62 private autoReconnectRetryCount: number;
265e4266 63 private automaticTransactionGenerator!: AutomaticTransactionGenerator;
6e0964c8 64 private webSocketPingSetInterval!: NodeJS.Timeout;
6af9012e
JB
65
66 constructor(index: number, stationTemplateFile: string) {
ad2f27c3
JB
67 this.index = index;
68 this.stationTemplateFile = stationTemplateFile;
734d790d 69 this.connectors = new Map<number, ConnectorStatus>();
c0560973 70 this.initialize();
2e6f5966 71
265e4266
JB
72 this.stopped = false;
73 this.wsConnectionRestarted = false;
ad2f27c3 74 this.autoReconnectRetryCount = 0;
2e6f5966 75
32b02249 76 this.requests = new Map<string, CachedRequest>();
8e242273 77 this.messageBuffer = new Set<string>();
2e6f5966 78
c0560973
JB
79 this.authorizedTags = this.getAuthorizedTags();
80 }
81
12fc74d6 82 get wsConnectionUrl(): URL {
1f5df42a 83 return this.getSupervisionUrlOcppConfiguration() ? new URL(this.getConfigurationKey(this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl).value + '/' + this.stationInfo.chargingStationId) : this.wsConfiguredConnectionUrl;
12fc74d6
JB
84 }
85
c0560973 86 public logPrefix(): string {
54b1efe0 87 return Utils.logPrefix(` ${this.stationInfo.chargingStationId} |`);
c0560973
JB
88 }
89
802cfa13
JB
90 public getBootNotificationRequest(): BootNotificationRequest {
91 return this.bootNotificationRequest;
92 }
93
f4bf2abd 94 public getRandomIdTag(): string {
c37528f1 95 const index = Math.floor(Utils.secureRandom() * this.authorizedTags.length);
c0560973
JB
96 return this.authorizedTags[index];
97 }
98
99 public hasAuthorizedTags(): boolean {
100 return !Utils.isEmptyArray(this.authorizedTags);
101 }
102
6e0964c8 103 public getEnableStatistics(): boolean | undefined {
c0560973
JB
104 return !Utils.isUndefined(this.stationInfo.enableStatistics) ? this.stationInfo.enableStatistics : true;
105 }
106
a7fc8211
JB
107 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
108 return this.stationInfo.mayAuthorizeAtRemoteStart ?? true;
109 }
110
6e0964c8 111 public getNumberOfPhases(): number | undefined {
7decf1b6 112 switch (this.getCurrentOutType()) {
4c2b4904 113 case CurrentType.AC:
c0560973 114 return !Utils.isUndefined(this.stationInfo.numberOfPhases) ? this.stationInfo.numberOfPhases : 3;
4c2b4904 115 case CurrentType.DC:
c0560973
JB
116 return 0;
117 }
118 }
119
d5bff457 120 public isWebSocketConnectionOpened(): boolean {
e58068fd 121 return this?.wsConnection?.readyState === OPEN;
c0560973
JB
122 }
123
124 public isRegistered(): boolean {
e58068fd 125 return this?.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED;
c0560973
JB
126 }
127
128 public isChargingStationAvailable(): boolean {
734d790d 129 return this.getConnectorStatus(0).availability === AvailabilityType.OPERATIVE;
c0560973
JB
130 }
131
132 public isConnectorAvailable(id: number): boolean {
734d790d 133 return this.getConnectorStatus(id).availability === AvailabilityType.OPERATIVE;
c0560973
JB
134 }
135
54544ef1
JB
136 public getNumberOfConnectors(): number {
137 return this.connectors.get(0) ? this.connectors.size - 1 : this.connectors.size;
138 }
139
734d790d
JB
140 public getConnectorStatus(id: number): ConnectorStatus {
141 return this.connectors.get(id);
c0560973
JB
142 }
143
4c2b4904
JB
144 public getCurrentOutType(): CurrentType | undefined {
145 return this.stationInfo.currentOutType ?? CurrentType.AC;
c0560973
JB
146 }
147
6e0964c8 148 public getVoltageOut(): number | undefined {
7decf1b6 149 const errMsg = `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
c0560973 150 let defaultVoltageOut: number;
7decf1b6 151 switch (this.getCurrentOutType()) {
4c2b4904
JB
152 case CurrentType.AC:
153 defaultVoltageOut = Voltage.VOLTAGE_230;
c0560973 154 break;
4c2b4904
JB
155 case CurrentType.DC:
156 defaultVoltageOut = Voltage.VOLTAGE_400;
c0560973
JB
157 break;
158 default:
159 logger.error(errMsg);
290d006c 160 throw new Error(errMsg);
c0560973
JB
161 }
162 return !Utils.isUndefined(this.stationInfo.voltageOut) ? this.stationInfo.voltageOut : defaultVoltageOut;
163 }
164
6e0964c8 165 public getTransactionIdTag(transactionId: number): string | undefined {
734d790d
JB
166 for (const connectorId of this.connectors.keys()) {
167 if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
168 return this.getConnectorStatus(connectorId).transactionIdTag;
c0560973
JB
169 }
170 }
171 }
172
6ed92bc1
JB
173 public getOutOfOrderEndMeterValues(): boolean {
174 return this.stationInfo.outOfOrderEndMeterValues ?? false;
175 }
176
177 public getBeginEndMeterValues(): boolean {
178 return this.stationInfo.beginEndMeterValues ?? false;
179 }
180
181 public getMeteringPerTransaction(): boolean {
182 return this.stationInfo.meteringPerTransaction ?? true;
183 }
184
fd0c36fa
JB
185 public getTransactionDataMeterValues(): boolean {
186 return this.stationInfo.transactionDataMeterValues ?? false;
187 }
188
9ccca265
JB
189 public getMainVoltageMeterValues(): boolean {
190 return this.stationInfo.mainVoltageMeterValues ?? true;
191 }
192
6b10669b
JB
193 public getPhaseLineToLineVoltageMeterValues(): boolean {
194 return this.stationInfo.phaseLineToLineVoltageMeterValues ?? false;
9bd87386
JB
195 }
196
6ed92bc1
JB
197 public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined {
198 if (this.getMeteringPerTransaction()) {
734d790d
JB
199 for (const connectorId of this.connectors.keys()) {
200 if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
201 return this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue;
6ed92bc1
JB
202 }
203 }
204 }
734d790d
JB
205 for (const connectorId of this.connectors.keys()) {
206 if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
207 return this.getConnectorStatus(connectorId).energyActiveImportRegisterValue;
c0560973
JB
208 }
209 }
210 }
211
6ed92bc1
JB
212 public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined {
213 if (this.getMeteringPerTransaction()) {
734d790d 214 return this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue;
6ed92bc1 215 }
734d790d 216 return this.getConnectorStatus(connectorId).energyActiveImportRegisterValue;
6ed92bc1
JB
217 }
218
c0560973
JB
219 public getAuthorizeRemoteTxRequests(): boolean {
220 const authorizeRemoteTxRequests = this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests);
221 return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false;
222 }
223
224 public getLocalAuthListEnabled(): boolean {
225 const localAuthListEnabled = this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled);
226 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
227 }
228
229 public restartWebSocketPing(): void {
230 // Stop WebSocket ping
231 this.stopWebSocketPing();
232 // Start WebSocket ping
233 this.startWebSocketPing();
234 }
235
9ccca265
JB
236 public getSampledValueTemplate(connectorId: number, measurand: MeterValueMeasurand = MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER,
237 phase?: MeterValuePhase): SampledValueTemplate | undefined {
238 if (!Constants.SUPPORTED_MEASURANDS.includes(measurand)) {
7d75bee1 239 logger.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}`);
9bd87386
JB
240 return;
241 }
242 if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
7d75bee1 243 logger.debug(`${this.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId} not found in '${StandardParametersKey.MeterValuesSampledData}' OCPP parameter`);
9ccca265
JB
244 return;
245 }
734d790d 246 const sampledValueTemplates: SampledValueTemplate[] = this.getConnectorStatus(connectorId).MeterValues;
9ccca265 247 for (let index = 0; !Utils.isEmptyArray(sampledValueTemplates) && index < sampledValueTemplates.length; index++) {
290d006c 248 if (!Constants.SUPPORTED_MEASURANDS.includes(sampledValueTemplates[index]?.measurand ?? MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER)) {
7d75bee1 249 logger.warn(`${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}`);
47e22477 250 } else if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand
32b02249 251 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
9ccca265
JB
252 return sampledValueTemplates[index];
253 } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand
32b02249 254 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
9ccca265
JB
255 return sampledValueTemplates[index];
256 } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
32b02249 257 && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) {
9ccca265
JB
258 return sampledValueTemplates[index];
259 }
260 }
9bd87386 261 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
7d75bee1 262 const errorMsg = `${this.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
de96acad
JB
263 logger.error(errorMsg);
264 throw new Error(errorMsg);
9ccca265 265 }
7d75bee1 266 logger.debug(`${this.logPrefix()} No MeterValues for measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}`);
9ccca265
JB
267 }
268
e644918b
JB
269 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
270 return this.stationInfo.AutomaticTransactionGenerator.requireAuthorize ?? true;
271 }
272
c0560973
JB
273 public startHeartbeat(): void {
274 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval) {
71623267
JB
275 // eslint-disable-next-line @typescript-eslint/no-misused-promises
276 this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
c0560973
JB
277 await this.ocppRequestService.sendHeartbeat();
278 }, this.getHeartbeatInterval());
d7d1db72 279 logger.info(this.logPrefix() + ' Heartbeat started every ' + Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()));
c0560973 280 } else if (this.heartbeatSetInterval) {
d7d1db72 281 logger.info(this.logPrefix() + ' Heartbeat already started every ' + Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()));
c0560973 282 } else {
d7d1db72 283 logger.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
c0560973
JB
284 }
285 }
286
287 public restartHeartbeat(): void {
288 // Stop heartbeat
289 this.stopHeartbeat();
290 // Start heartbeat
291 this.startHeartbeat();
292 }
293
294 public startMeterValues(connectorId: number, interval: number): void {
295 if (connectorId === 0) {
296 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
297 return;
298 }
734d790d 299 if (!this.getConnectorStatus(connectorId)) {
c0560973
JB
300 logger.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
301 return;
302 }
734d790d 303 if (!this.getConnectorStatus(connectorId)?.transactionStarted) {
c0560973
JB
304 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
305 return;
734d790d 306 } else if (this.getConnectorStatus(connectorId)?.transactionStarted && !this.getConnectorStatus(connectorId)?.transactionId) {
c0560973
JB
307 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
308 return;
309 }
310 if (interval > 0) {
71623267 311 // eslint-disable-next-line @typescript-eslint/no-misused-promises
734d790d
JB
312 this.getConnectorStatus(connectorId).transactionSetInterval = setInterval(async (): Promise<void> => {
313 await this.ocppRequestService.sendMeterValues(connectorId, this.getConnectorStatus(connectorId).transactionId, interval);
c0560973
JB
314 }, interval);
315 } else {
d7d1db72 316 logger.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.formatDurationMilliSeconds(interval) : interval}, not sending MeterValues`);
c0560973
JB
317 }
318 }
319
320 public start(): void {
7874b0b1
JB
321 if (this.getEnableStatistics()) {
322 this.performanceStatistics.start();
323 }
c0560973
JB
324 this.openWSConnection();
325 // Monitor authorization file
326 this.startAuthorizationFileMonitoring();
327 // Monitor station template file
328 this.startStationTemplateFileMonitoring();
8bf88613 329 // Handle WebSocket message
c0560973 330 this.wsConnection.on('message', this.onMessage.bind(this));
5dc8b1b5 331 // Handle WebSocket error
c0560973 332 this.wsConnection.on('error', this.onError.bind(this));
5dc8b1b5 333 // Handle WebSocket close
c0560973 334 this.wsConnection.on('close', this.onClose.bind(this));
8bf88613 335 // Handle WebSocket open
c0560973 336 this.wsConnection.on('open', this.onOpen.bind(this));
5dc8b1b5 337 // Handle WebSocket ping
c0560973 338 this.wsConnection.on('ping', this.onPing.bind(this));
5dc8b1b5 339 // Handle WebSocket pong
c0560973 340 this.wsConnection.on('pong', this.onPong.bind(this));
ee0f106b 341 parentPort.postMessage({ id: ChargingStationWorkerMessageEvents.STARTED, data: { id: this.stationInfo.chargingStationId } });
c0560973
JB
342 }
343
344 public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
345 // Stop message sequence
346 await this.stopMessageSequence(reason);
734d790d
JB
347 for (const connectorId of this.connectors.keys()) {
348 if (connectorId > 0) {
349 await this.ocppRequestService.sendStatusNotification(connectorId, ChargePointStatus.UNAVAILABLE);
350 this.getConnectorStatus(connectorId).status = ChargePointStatus.UNAVAILABLE;
c0560973
JB
351 }
352 }
d5bff457 353 if (this.isWebSocketConnectionOpened()) {
c0560973
JB
354 this.wsConnection.close();
355 }
7874b0b1
JB
356 if (this.getEnableStatistics()) {
357 this.performanceStatistics.stop();
358 }
c0560973 359 this.bootNotificationResponse = null;
ee0f106b 360 parentPort.postMessage({ id: ChargingStationWorkerMessageEvents.STOPPED, data: { id: this.stationInfo.chargingStationId } });
265e4266 361 this.stopped = true;
c0560973
JB
362 }
363
6e0964c8 364 public getConfigurationKey(key: string | StandardParametersKey, caseInsensitive = false): ConfigurationKey | undefined {
7874b0b1 365 return this.configuration.configurationKey.find((configElement) => {
c0560973
JB
366 if (caseInsensitive) {
367 return configElement.key.toLowerCase() === key.toLowerCase();
368 }
369 return configElement.key === key;
370 });
c0560973
JB
371 }
372
12fc74d6 373 public addConfigurationKey(key: string | StandardParametersKey, value: string, options: { readonly?: boolean, visible?: boolean, reboot?: boolean } = { readonly: false, visible: true, reboot: false }): void {
c0560973 374 const keyFound = this.getConfigurationKey(key);
12fc74d6
JB
375 const readonly = options.readonly;
376 const visible = options.visible;
377 const reboot = options.reboot;
c0560973
JB
378 if (!keyFound) {
379 this.configuration.configurationKey.push({
380 key,
381 readonly,
382 value,
383 visible,
384 reboot,
385 });
386 } else {
387 logger.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound);
388 }
389 }
390
391 public setConfigurationKeyValue(key: string | StandardParametersKey, value: string): void {
392 const keyFound = this.getConfigurationKey(key);
393 if (keyFound) {
394 const keyIndex = this.configuration.configurationKey.indexOf(keyFound);
395 this.configuration.configurationKey[keyIndex].value = value;
396 } else {
397 logger.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key, value });
398 }
399 }
400
a7fc8211
JB
401 public setChargingProfile(connectorId: number, cp: ChargingProfile): void {
402 let cpReplaced = false;
734d790d
JB
403 if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId).chargingProfiles)) {
404 this.getConnectorStatus(connectorId).chargingProfiles?.forEach((chargingProfile: ChargingProfile, index: number) => {
c0560973 405 if (chargingProfile.chargingProfileId === cp.chargingProfileId
32b02249 406 || (chargingProfile.stackLevel === cp.stackLevel && chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)) {
734d790d 407 this.getConnectorStatus(connectorId).chargingProfiles[index] = cp;
a7fc8211 408 cpReplaced = true;
c0560973
JB
409 }
410 });
411 }
734d790d 412 !cpReplaced && this.getConnectorStatus(connectorId).chargingProfiles?.push(cp);
c0560973
JB
413 }
414
a2653482
JB
415 public resetConnectorStatus(connectorId: number): void {
416 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
417 this.getConnectorStatus(connectorId).idTagAuthorized = false;
418 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
734d790d 419 this.getConnectorStatus(connectorId).transactionStarted = false;
a2653482 420 delete this.getConnectorStatus(connectorId).localAuthorizeIdTag;
734d790d
JB
421 delete this.getConnectorStatus(connectorId).authorizeIdTag;
422 delete this.getConnectorStatus(connectorId).transactionId;
423 delete this.getConnectorStatus(connectorId).transactionIdTag;
424 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
425 delete this.getConnectorStatus(connectorId).transactionBeginMeterValue;
dd119a6b 426 this.stopMeterValues(connectorId);
2e6f5966
JB
427 }
428
8e242273
JB
429 public bufferMessage(message: string): void {
430 this.messageBuffer.add(message);
3ba2381e
JB
431 }
432
8e242273
JB
433 private flushMessageBuffer() {
434 if (this.messageBuffer.size > 0) {
435 this.messageBuffer.forEach((message) => {
aef1b33a 436 // TODO: evaluate the need to track performance
77f00f84 437 this.wsConnection.send(message);
8e242273 438 this.messageBuffer.delete(message);
77f00f84
JB
439 });
440 }
441 }
442
1f5df42a
JB
443 private getSupervisionUrlOcppConfiguration(): boolean {
444 return this.stationInfo.supervisionUrlOcppConfiguration ?? false;
12fc74d6
JB
445 }
446
c0560973 447 private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
ef6076c1 448 // In case of multiple instances: add instance index to charging station id
203bc097 449 const instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0;
9ccca265 450 const idSuffix = stationTemplate.nameSuffix ?? '';
ad2f27c3 451 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex.toString() + ('000000000' + this.index.toString()).substr(('000000000' + this.index.toString()).length - 4) + idSuffix;
5ad8570f
JB
452 }
453
c0560973 454 private buildStationInfo(): ChargingStationInfo {
9ac86a7e 455 let stationTemplateFromFile: ChargingStationTemplate;
5ad8570f
JB
456 try {
457 // Load template file
ad2f27c3 458 const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r');
9ac86a7e 459 stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate;
5ad8570f
JB
460 fs.closeSync(fileDescriptor);
461 } catch (error) {
88184022 462 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error as NodeJS.ErrnoException);
5ad8570f 463 }
510f0fa5 464 const stationInfo: ChargingStationInfo = stationTemplateFromFile ?? {} as ChargingStationInfo;
cd8dd457 465 stationInfo.wsOptions = stationTemplateFromFile?.wsOptions ?? {};
0a60c33c 466 if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
9ac86a7e 467 stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
c37528f1 468 const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationTemplateFromFile.power.length);
510f0fa5
JB
469 stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
470 ? stationTemplateFromFile.power[powerArrayRandomIndex] * 1000
471 : stationTemplateFromFile.power[powerArrayRandomIndex];
5ad8570f 472 } else {
510f0fa5
JB
473 stationTemplateFromFile.power = stationTemplateFromFile.power as number;
474 stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
fd0c36fa 475 ? stationTemplateFromFile.power * 1000
510f0fa5 476 : stationTemplateFromFile.power;
5ad8570f 477 }
fd0c36fa
JB
478 delete stationInfo.power;
479 delete stationInfo.powerUnit;
c0560973 480 stationInfo.chargingStationId = this.getChargingStationId(stationTemplateFromFile);
9ac86a7e
JB
481 stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
482 return stationInfo;
5ad8570f
JB
483 }
484
1f5df42a 485 private getOcppVersion(): OCPPVersion {
c0560973
JB
486 return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
487 }
488
489 private handleUnsupportedVersion(version: OCPPVersion) {
490 const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
491 logger.error(errMsg);
492 throw new Error(errMsg);
493 }
494
495 private initialize(): void {
496 this.stationInfo = this.buildStationInfo();
37486900 497 this.configuration = this.getTemplateChargingStationConfiguration();
798010fa 498 delete this.stationInfo.Configuration;
ad2f27c3
JB
499 this.bootNotificationRequest = {
500 chargePointModel: this.stationInfo.chargePointModel,
501 chargePointVendor: this.stationInfo.chargePointVendor,
502 ...!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix },
503 ...!Utils.isUndefined(this.stationInfo.firmwareVersion) && { firmwareVersion: this.stationInfo.firmwareVersion },
2e6f5966 504 };
0a60c33c 505 // Build connectors if needed
c0560973 506 const maxConnectors = this.getMaxNumberOfConnectors();
6ecb15e4 507 if (maxConnectors <= 0) {
c0560973 508 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
7abfea5f 509 }
c0560973 510 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
7abfea5f 511 if (templateMaxConnectors <= 0) {
c0560973 512 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
593cf3f9 513 }
ad2f27c3 514 if (!this.stationInfo.Connectors[0]) {
c0560973 515 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
7abfea5f
JB
516 }
517 // Sanity check
ad2f27c3 518 if (maxConnectors > (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this.stationInfo.randomConnectors) {
c0560973 519 logger.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
ad2f27c3 520 this.stationInfo.randomConnectors = true;
6ecb15e4 521 }
ad2f27c3 522 const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()).digest('hex');
54544ef1
JB
523 const connectorsConfigChanged = this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash;
524 if (this.connectors?.size === 0 || connectorsConfigChanged) {
734d790d 525 connectorsConfigChanged && (this.connectors.clear());
ad2f27c3 526 this.connectorsConfigurationHash = connectorsConfigHash;
7abfea5f 527 // Add connector Id 0
6af9012e 528 let lastConnector = '0';
ad2f27c3 529 for (lastConnector in this.stationInfo.Connectors) {
734d790d
JB
530 const lastConnectorId = Utils.convertToInt(lastConnector);
531 if (lastConnectorId === 0 && this.getUseConnectorId0() && this.stationInfo.Connectors[lastConnector]) {
532 this.connectors.set(lastConnectorId, Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[lastConnector]));
533 this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE;
534 if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) {
535 this.getConnectorStatus(lastConnectorId).chargingProfiles = [];
418106c8 536 }
0a60c33c
JB
537 }
538 }
0a60c33c 539 // Generate all connectors
ad2f27c3 540 if ((this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
7abfea5f 541 for (let index = 1; index <= maxConnectors; index++) {
72740232 542 const randConnectorId = this.stationInfo.randomConnectors ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1) : index;
734d790d
JB
543 this.connectors.set(index, Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[randConnectorId]));
544 this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE;
545 if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) {
546 this.getConnectorStatus(index).chargingProfiles = [];
418106c8 547 }
7abfea5f 548 }
0a60c33c
JB
549 }
550 }
d4a73fb7 551 // Avoid duplication of connectors related information
ad2f27c3 552 delete this.stationInfo.Connectors;
0a60c33c 553 // Initialize transaction attributes on connectors
734d790d
JB
554 for (const connectorId of this.connectors.keys()) {
555 if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) {
a2653482 556 this.initializeConnectorStatus(connectorId);
0a60c33c
JB
557 }
558 }
1f5df42a
JB
559 this.wsConfiguredConnectionUrl = new URL(this.getConfiguredSupervisionUrl().href + '/' + this.stationInfo.chargingStationId);
560 switch (this.getOcppVersion()) {
c0560973
JB
561 case OCPPVersion.VERSION_16:
562 this.ocppIncomingRequestService = new OCPP16IncomingRequestService(this);
563 this.ocppRequestService = new OCPP16RequestService(this, new OCPP16ResponseService(this));
564 break;
565 default:
1f5df42a 566 this.handleUnsupportedVersion(this.getOcppVersion());
c0560973
JB
567 break;
568 }
7abfea5f 569 // OCPP parameters
1f5df42a 570 this.initOcppParameters();
47e22477
JB
571 if (this.stationInfo.autoRegister) {
572 this.bootNotificationResponse = {
573 currentTime: new Date().toISOString(),
574 interval: this.getHeartbeatInterval() / 1000,
575 status: RegistrationStatus.ACCEPTED
576 };
577 }
147d0e0f
JB
578 this.stationInfo.powerDivider = this.getPowerDivider();
579 if (this.getEnableStatistics()) {
2a370053 580 this.performanceStatistics = new PerformanceStatistics(this.stationInfo.chargingStationId, this.wsConnectionUrl);
147d0e0f
JB
581 }
582 }
583
1f5df42a
JB
584 private initOcppParameters(): void {
585 if (this.getSupervisionUrlOcppConfiguration() && !this.getConfigurationKey(this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl)) {
586 this.addConfigurationKey(VendorDefaultParametersKey.ConnectionUrl, this.getConfiguredSupervisionUrl().href, { reboot: true });
12fc74d6 587 }
36f6a92e
JB
588 if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) {
589 this.addConfigurationKey(StandardParametersKey.SupportedFeatureProfiles, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`);
590 }
12fc74d6 591 this.addConfigurationKey(StandardParametersKey.NumberOfConnectors, this.getNumberOfConnectors().toString(), { readonly: true });
c0560973
JB
592 if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) {
593 this.addConfigurationKey(StandardParametersKey.MeterValuesSampledData, MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER);
7abfea5f 594 }
7e1dc878
JB
595 if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) {
596 const connectorPhaseRotation = [];
734d790d 597 for (const connectorId of this.connectors.keys()) {
7e1dc878 598 // AC/DC
734d790d
JB
599 if (connectorId === 0 && this.getNumberOfPhases() === 0) {
600 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
601 } else if (connectorId > 0 && this.getNumberOfPhases() === 0) {
602 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
7e1dc878 603 // AC
734d790d
JB
604 } else if (connectorId > 0 && this.getNumberOfPhases() === 1) {
605 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
606 } else if (connectorId > 0 && this.getNumberOfPhases() === 3) {
607 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
7e1dc878
JB
608 }
609 }
610 this.addConfigurationKey(StandardParametersKey.ConnectorPhaseRotation, connectorPhaseRotation.toString());
611 }
36f6a92e
JB
612 if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) {
613 this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true');
614 }
615 if (!this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled)
32b02249 616 && this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles).value.includes(SupportedFeatureProfiles.Local_Auth_List_Management)) {
36f6a92e
JB
617 this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false');
618 }
147d0e0f
JB
619 if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
620 this.addConfigurationKey(StandardParametersKey.ConnectionTimeOut, Constants.DEFAULT_CONNECTION_TIMEOUT.toString());
8bce55bf 621 }
7dde0b73
JB
622 }
623
c0560973 624 private async onOpen(): Promise<void> {
e9017bfc 625 logger.info(`${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`);
c0560973
JB
626 if (!this.isRegistered()) {
627 // Send BootNotification
628 let registrationRetryCount = 0;
629 do {
43d673d9
JB
630 this.bootNotificationResponse = await this.ocppRequestService.sendBootNotification(this.bootNotificationRequest.chargePointModel,
631 this.bootNotificationRequest.chargePointVendor, this.bootNotificationRequest.chargeBoxSerialNumber, this.bootNotificationRequest.firmwareVersion);
c0560973
JB
632 if (!this.isRegistered()) {
633 registrationRetryCount++;
634 await Utils.sleep(this.bootNotificationResponse?.interval ? this.bootNotificationResponse.interval * 1000 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL);
635 }
636 } while (!this.isRegistered() && (registrationRetryCount <= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
c7db4718 637 }
e58068fd
JB
638 if (this.isRegistered() && this.stationInfo.autoRegister) {
639 await this.ocppRequestService.sendBootNotification(this.bootNotificationRequest.chargePointModel,
640 this.bootNotificationRequest.chargePointVendor, this.bootNotificationRequest.chargeBoxSerialNumber, this.bootNotificationRequest.firmwareVersion);
641 }
c7db4718 642 if (this.isRegistered()) {
c0560973 643 await this.startMessageSequence();
265e4266
JB
644 this.stopped && (this.stopped = false);
645 if (this.wsConnectionRestarted && this.isWebSocketConnectionOpened()) {
8e242273 646 this.flushMessageBuffer();
2e6f5966
JB
647 }
648 } else {
c0560973 649 logger.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
2e6f5966 650 }
c0560973 651 this.autoReconnectRetryCount = 0;
265e4266 652 this.wsConnectionRestarted = false;
2e6f5966
JB
653 }
654
6c65a295 655 private async onClose(code: number, reason: string): Promise<void> {
d09085e9 656 switch (code) {
6c65a295
JB
657 // Normal close
658 case WebSocketCloseEventStatusCode.CLOSE_NORMAL:
c0560973 659 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
5dc8b1b5 660 logger.info(`${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
c0560973
JB
661 this.autoReconnectRetryCount = 0;
662 break;
6c65a295
JB
663 // Abnormal close
664 default:
5dc8b1b5 665 logger.error(`${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
d09085e9 666 await this.reconnect(code);
c0560973
JB
667 break;
668 }
2e6f5966
JB
669 }
670
16b0d4e7 671 private async onMessage(data: Data): Promise<void> {
c0560973 672 let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [0, '', '' as IncomingRequestCommand, {}, {}];
193d2c0a 673 let responseCallback: (payload: Record<string, unknown> | string, requestPayload: Record<string, unknown>) => void;
9239b49a 674 let rejectCallback: (error: OCPPError, requestStatistic?: boolean) => void;
32b02249 675 let requestCommandName: RequestCommand | IncomingRequestCommand;
c0560973 676 let requestPayload: Record<string, unknown>;
32b02249 677 let cachedRequest: CachedRequest;
c0560973
JB
678 let errMsg: string;
679 try {
16b0d4e7 680 const request = JSON.parse(data.toString()) as IncomingRequest;
47e22477
JB
681 if (Utils.isIterable(request)) {
682 // Parse the message
683 [messageType, messageId, commandName, commandPayload, errorDetails] = request;
684 } else {
a6b3c6c3 685 throw new OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming request is not iterable', commandName);
47e22477 686 }
c0560973
JB
687 // Check the Type of message
688 switch (messageType) {
689 // Incoming Message
690 case MessageType.CALL_MESSAGE:
691 if (this.getEnableStatistics()) {
aef1b33a 692 this.performanceStatistics.addRequestStatistic(commandName, messageType);
c0560973
JB
693 }
694 // Process the call
695 await this.ocppIncomingRequestService.handleRequest(messageId, commandName, commandPayload);
696 break;
697 // Outcome Message
698 case MessageType.CALL_RESULT_MESSAGE:
699 // Respond
16b0d4e7
JB
700 cachedRequest = this.requests.get(messageId);
701 if (Utils.isIterable(cachedRequest)) {
32b02249 702 [responseCallback, , , requestPayload] = cachedRequest;
c0560973 703 } else {
a685c3af 704 throw new OCPPError(ErrorType.PROTOCOL_ERROR, `Cached request for message id ${messageId} response is not iterable`, commandName);
c0560973
JB
705 }
706 if (!responseCallback) {
707 // Error
a685c3af 708 throw new OCPPError(ErrorType.INTERNAL_ERROR, `Response for unknown message id ${messageId}`, commandName);
c0560973 709 }
c0560973
JB
710 responseCallback(commandName, requestPayload);
711 break;
712 // Error Message
713 case MessageType.CALL_ERROR_MESSAGE:
16b0d4e7 714 cachedRequest = this.requests.get(messageId);
16b0d4e7 715 if (Utils.isIterable(cachedRequest)) {
32b02249 716 [, rejectCallback, requestCommandName] = cachedRequest;
c0560973 717 } else {
a685c3af 718 throw new OCPPError(ErrorType.PROTOCOL_ERROR, `Cached request for message id ${messageId} error response is not iterable`);
c0560973 719 }
32b02249
JB
720 if (!rejectCallback) {
721 // Error
a685c3af 722 throw new OCPPError(ErrorType.INTERNAL_ERROR, `Error response for unknown message id ${messageId}`, requestCommandName);
32b02249
JB
723 }
724 rejectCallback(new OCPPError(commandName, commandPayload.toString(), requestCommandName, errorDetails));
c0560973
JB
725 break;
726 // Error
727 default:
728 errMsg = `${this.logPrefix()} Wrong message type ${messageType}`;
729 logger.error(errMsg);
14763b46 730 throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg);
c0560973
JB
731 }
732 } catch (error) {
733 // Log
6d9abcc2 734 logger.error('%s Incoming OCPP message %j matching cached request %j processing error %j', this.logPrefix(), data.toString(), this.requests.get(messageId), error);
c0560973 735 // Send error
88184022 736 messageType === MessageType.CALL_MESSAGE && await this.ocppRequestService.sendError(messageId, error as OCPPError, commandName);
c0560973 737 }
2328be1e
JB
738 }
739
c0560973 740 private onPing(): void {
57939a9d 741 logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
c0560973
JB
742 }
743
744 private onPong(): void {
57939a9d 745 logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
c0560973
JB
746 }
747
16b0d4e7 748 private async onError(error: WSError): Promise<void> {
5dc8b1b5 749 logger.error(this.logPrefix() + ' WebSocket error: %j', error);
16b0d4e7 750 // switch (error.code) {
c0560973 751 // case 'ECONNREFUSED':
16b0d4e7 752 // await this.reconnect(error);
c0560973
JB
753 // break;
754 // }
755 }
756
757 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration {
7874b0b1 758 return this.stationInfo.Configuration ?? {} as ChargingStationConfiguration;
c0560973
JB
759 }
760
6e0964c8 761 private getAuthorizationFile(): string | undefined {
bf1866b2 762 return this.stationInfo.authorizationFile && path.join(path.resolve(__dirname, '../'), 'assets', path.basename(this.stationInfo.authorizationFile));
c0560973
JB
763 }
764
765 private getAuthorizedTags(): string[] {
766 let authorizedTags: string[] = [];
767 const authorizationFile = this.getAuthorizationFile();
768 if (authorizationFile) {
769 try {
770 // Load authorization file
771 const fileDescriptor = fs.openSync(authorizationFile, 'r');
772 authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[];
773 fs.closeSync(fileDescriptor);
774 } catch (error) {
88184022 775 FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error as NodeJS.ErrnoException);
c0560973
JB
776 }
777 } else {
778 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile);
8c4da341 779 }
c0560973
JB
780 return authorizedTags;
781 }
782
6e0964c8 783 private getUseConnectorId0(): boolean | undefined {
c0560973 784 return !Utils.isUndefined(this.stationInfo.useConnectorId0) ? this.stationInfo.useConnectorId0 : true;
8bce55bf
JB
785 }
786
c0560973 787 private getNumberOfRunningTransactions(): number {
6ecb15e4 788 let trxCount = 0;
734d790d
JB
789 for (const connectorId of this.connectors.keys()) {
790 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
6ecb15e4
JB
791 trxCount++;
792 }
793 }
794 return trxCount;
795 }
796
1f761b9a 797 // 0 for disabling
6e0964c8 798 private getConnectionTimeout(): number | undefined {
291cb255
JB
799 if (this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
800 return parseInt(this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut).value) ?? Constants.DEFAULT_CONNECTION_TIMEOUT;
801 }
291cb255 802 return Constants.DEFAULT_CONNECTION_TIMEOUT;
3574dfd3
JB
803 }
804
1f761b9a 805 // -1 for unlimited, 0 for disabling
6e0964c8 806 private getAutoReconnectMaxRetries(): number | undefined {
ad2f27c3
JB
807 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
808 return this.stationInfo.autoReconnectMaxRetries;
3574dfd3
JB
809 }
810 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
811 return Configuration.getAutoReconnectMaxRetries();
812 }
813 return -1;
814 }
815
ec977daf 816 // 0 for disabling
6e0964c8 817 private getRegistrationMaxRetries(): number | undefined {
ad2f27c3
JB
818 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
819 return this.stationInfo.registrationMaxRetries;
32a1eb7a
JB
820 }
821 return -1;
822 }
823
c0560973
JB
824 private getPowerDivider(): number {
825 let powerDivider = this.getNumberOfConnectors();
ad2f27c3 826 if (this.stationInfo.powerSharedByConnectors) {
c0560973 827 powerDivider = this.getNumberOfRunningTransactions();
6ecb15e4
JB
828 }
829 return powerDivider;
830 }
831
c0560973 832 private getTemplateMaxNumberOfConnectors(): number {
ad2f27c3 833 return Object.keys(this.stationInfo.Connectors).length;
7abfea5f
JB
834 }
835
c0560973 836 private getMaxNumberOfConnectors(): number {
e58068fd 837 let maxConnectors: number;
ad2f27c3
JB
838 if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) {
839 const numberOfConnectors = this.stationInfo.numberOfConnectors as number[];
6ecb15e4 840 // Distribute evenly the number of connectors
ad2f27c3
JB
841 maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length];
842 } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) {
843 maxConnectors = this.stationInfo.numberOfConnectors as number;
488fd3a7 844 } else {
c0560973 845 maxConnectors = this.stationInfo.Connectors[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
5ad8570f
JB
846 }
847 return maxConnectors;
2e6f5966
JB
848 }
849
c0560973 850 private async startMessageSequence(): Promise<void> {
136c90ba 851 // Start WebSocket ping
c0560973 852 this.startWebSocketPing();
5ad8570f 853 // Start heartbeat
c0560973 854 this.startHeartbeat();
0a60c33c 855 // Initialize connectors status
734d790d
JB
856 for (const connectorId of this.connectors.keys()) {
857 if (connectorId === 0) {
593cf3f9 858 continue;
734d790d 859 } else if (!this.stopped && !this.getConnectorStatus(connectorId)?.status && this.getConnectorStatus(connectorId)?.bootStatus) {
136c90ba 860 // Send status in template at startup
734d790d
JB
861 await this.ocppRequestService.sendStatusNotification(connectorId, this.getConnectorStatus(connectorId).bootStatus);
862 this.getConnectorStatus(connectorId).status = this.getConnectorStatus(connectorId).bootStatus;
863 } else if (this.stopped && this.getConnectorStatus(connectorId)?.status && this.getConnectorStatus(connectorId)?.bootStatus) {
136c90ba 864 // Send status in template after reset
734d790d
JB
865 await this.ocppRequestService.sendStatusNotification(connectorId, this.getConnectorStatus(connectorId).bootStatus);
866 this.getConnectorStatus(connectorId).status = this.getConnectorStatus(connectorId).bootStatus;
867 } else if (!this.stopped && this.getConnectorStatus(connectorId)?.status) {
136c90ba 868 // Send previous status at template reload
734d790d 869 await this.ocppRequestService.sendStatusNotification(connectorId, this.getConnectorStatus(connectorId).status);
5ad8570f 870 } else {
136c90ba 871 // Send default status
734d790d
JB
872 await this.ocppRequestService.sendStatusNotification(connectorId, ChargePointStatus.AVAILABLE);
873 this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE;
5ad8570f
JB
874 }
875 }
0a60c33c 876 // Start the ATG
dd119a6b 877 this.startAutomaticTransactionGenerator();
dd119a6b
JB
878 }
879
880 private startAutomaticTransactionGenerator() {
ad2f27c3 881 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
265e4266
JB
882 if (!this.automaticTransactionGenerator) {
883 this.automaticTransactionGenerator = new AutomaticTransactionGenerator(this);
5ad8570f 884 }
265e4266
JB
885 if (!this.automaticTransactionGenerator.started) {
886 this.automaticTransactionGenerator.start();
5ad8570f
JB
887 }
888 }
5ad8570f
JB
889 }
890
c0560973 891 private async stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
136c90ba 892 // Stop WebSocket ping
c0560973 893 this.stopWebSocketPing();
79411696 894 // Stop heartbeat
c0560973 895 this.stopHeartbeat();
79411696 896 // Stop the ATG
ad2f27c3 897 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
265e4266
JB
898 this.automaticTransactionGenerator &&
899 this.automaticTransactionGenerator.started) {
0045cef5 900 this.automaticTransactionGenerator.stop();
79411696 901 } else {
734d790d
JB
902 for (const connectorId of this.connectors.keys()) {
903 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
904 const transactionId = this.getConnectorStatus(connectorId).transactionId;
6ed92bc1
JB
905 await this.ocppRequestService.sendStopTransaction(transactionId, this.getEnergyActiveImportRegisterByTransactionId(transactionId),
906 this.getTransactionIdTag(transactionId), reason);
79411696
JB
907 }
908 }
909 }
910 }
911
c0560973 912 private startWebSocketPing(): void {
9cd3dfb0
JB
913 const webSocketPingInterval: number = this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval)
914 ? Utils.convertToInt(this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value)
915 : 0;
ad2f27c3
JB
916 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
917 this.webSocketPingSetInterval = setInterval(() => {
d5bff457 918 if (this.isWebSocketConnectionOpened()) {
0dad4bda 919 this.wsConnection.ping((): void => { /* This is intentional */ });
136c90ba
JB
920 }
921 }, webSocketPingInterval * 1000);
d7d1db72 922 logger.info(this.logPrefix() + ' WebSocket ping started every ' + Utils.formatDurationSeconds(webSocketPingInterval));
ad2f27c3 923 } else if (this.webSocketPingSetInterval) {
d7d1db72 924 logger.info(this.logPrefix() + ' WebSocket ping every ' + Utils.formatDurationSeconds(webSocketPingInterval) + ' already started');
136c90ba 925 } else {
d7d1db72 926 logger.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.formatDurationSeconds(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
136c90ba
JB
927 }
928 }
929
c0560973 930 private stopWebSocketPing(): void {
ad2f27c3
JB
931 if (this.webSocketPingSetInterval) {
932 clearInterval(this.webSocketPingSetInterval);
136c90ba
JB
933 }
934 }
935
1f5df42a
JB
936 private getConfiguredSupervisionUrl(): URL {
937 const supervisionUrls = Utils.cloneObject<string | string[]>(this.stationInfo.supervisionUrl ?? Configuration.getSupervisionUrls());
c0560973
JB
938 let indexUrl = 0;
939 if (!Utils.isEmptyArray(supervisionUrls)) {
940 if (Configuration.getDistributeStationsToTenantsEqually()) {
941 indexUrl = this.index % supervisionUrls.length;
942 } else {
943 // Get a random url
c37528f1 944 indexUrl = Math.floor(Utils.secureRandom() * supervisionUrls.length);
c0560973 945 }
57939a9d 946 return new URL(supervisionUrls[indexUrl]);
c0560973 947 }
57939a9d 948 return new URL(supervisionUrls as string);
136c90ba
JB
949 }
950
6e0964c8 951 private getHeartbeatInterval(): number | undefined {
c0560973
JB
952 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
953 if (HeartbeatInterval) {
954 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
955 }
956 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
957 if (HeartBeatInterval) {
958 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
0a60c33c 959 }
47e22477
JB
960 !this.stationInfo.autoRegister && logger.warn(`${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${Constants.DEFAULT_HEARTBEAT_INTERVAL}`);
961 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
0a60c33c
JB
962 }
963
c0560973 964 private stopHeartbeat(): void {
ad2f27c3
JB
965 if (this.heartbeatSetInterval) {
966 clearInterval(this.heartbeatSetInterval);
7dde0b73 967 }
5ad8570f
JB
968 }
969
cd8dd457 970 private openWSConnection(options: ClientOptions & ClientRequestArgs = this.stationInfo.wsOptions, forceCloseOpened = false): void {
37486900 971 options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
15042c5f
JB
972 if (!Utils.isNullOrUndefined(this.stationInfo.supervisionUser) && !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)) {
973 options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
974 }
d5bff457 975 if (this.isWebSocketConnectionOpened() && forceCloseOpened) {
c0560973
JB
976 this.wsConnection.close();
977 }
88184022 978 let protocol: string;
1f5df42a 979 switch (this.getOcppVersion()) {
c0560973
JB
980 case OCPPVersion.VERSION_16:
981 protocol = 'ocpp' + OCPPVersion.VERSION_16;
982 break;
983 default:
1f5df42a 984 this.handleUnsupportedVersion(this.getOcppVersion());
c0560973
JB
985 break;
986 }
987 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
e9017bfc 988 logger.info(this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString());
136c90ba
JB
989 }
990
dd119a6b 991 private stopMeterValues(connectorId: number) {
734d790d
JB
992 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
993 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
dd119a6b
JB
994 }
995 }
996
c0560973 997 private startAuthorizationFileMonitoring(): void {
23132a44
JB
998 const authorizationFile = this.getAuthorizationFile();
999 if (authorizationFile) {
5ad8570f 1000 try {
3ec10737
JB
1001 fs.watch(authorizationFile, (event, filename) => {
1002 if (filename && event === 'change') {
1003 try {
1004 logger.debug(this.logPrefix() + ' Authorization file ' + authorizationFile + ' have changed, reload');
1005 // Initialize authorizedTags
1006 this.authorizedTags = this.getAuthorizedTags();
1007 } catch (error) {
1008 logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error);
1009 }
23132a44
JB
1010 }
1011 });
5ad8570f 1012 } catch (error) {
88184022 1013 FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error as NodeJS.ErrnoException);
5ad8570f 1014 }
23132a44
JB
1015 } else {
1016 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile + '. Not monitoring changes');
1017 }
5ad8570f
JB
1018 }
1019
c0560973 1020 private startStationTemplateFileMonitoring(): void {
23132a44 1021 try {
b809adf1 1022 fs.watch(this.stationTemplateFile, (event, filename): void => {
3ec10737
JB
1023 if (filename && event === 'change') {
1024 try {
1025 logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload');
1026 // Initialize
1027 this.initialize();
1028 // Restart the ATG
1029 if (!this.stationInfo.AutomaticTransactionGenerator.enable &&
32b02249 1030 this.automaticTransactionGenerator) {
0045cef5 1031 this.automaticTransactionGenerator.stop();
3ec10737
JB
1032 }
1033 this.startAutomaticTransactionGenerator();
1034 if (this.getEnableStatistics()) {
1035 this.performanceStatistics.restart();
1036 } else {
1037 this.performanceStatistics.stop();
1038 }
1039 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1040 } catch (error) {
1041 logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error);
087a502d 1042 }
79411696 1043 }
23132a44
JB
1044 });
1045 } catch (error) {
88184022 1046 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error as NodeJS.ErrnoException);
23132a44 1047 }
5ad8570f
JB
1048 }
1049
6e0964c8 1050 private getReconnectExponentialDelay(): boolean | undefined {
c0560973 1051 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false;
5ad8570f
JB
1052 }
1053
d09085e9 1054 private async reconnect(code: number): Promise<void> {
7874b0b1
JB
1055 // Stop WebSocket ping
1056 this.stopWebSocketPing();
136c90ba 1057 // Stop heartbeat
c0560973 1058 this.stopHeartbeat();
5ad8570f 1059 // Stop the ATG if needed
ad2f27c3
JB
1060 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
1061 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
265e4266
JB
1062 this.automaticTransactionGenerator &&
1063 this.automaticTransactionGenerator.started) {
0045cef5 1064 this.automaticTransactionGenerator.stop();
ad2f27c3 1065 }
c0560973 1066 if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
ad2f27c3 1067 this.autoReconnectRetryCount++;
c0560973 1068 const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000);
37486900 1069 const reconnectTimeout = (reconnectDelay - 100) > 0 && reconnectDelay;
5dc8b1b5 1070 logger.error(`${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectTimeout}ms`);
032d6efc 1071 await Utils.sleep(reconnectDelay);
5dc8b1b5 1072 logger.error(this.logPrefix() + ' WebSocket: reconnecting try #' + this.autoReconnectRetryCount.toString());
cd8dd457 1073 this.openWSConnection({ ...this.stationInfo.wsOptions, handshakeTimeout: reconnectTimeout }, true);
265e4266 1074 this.wsConnectionRestarted = true;
c0560973 1075 } else if (this.getAutoReconnectMaxRetries() !== -1) {
5dc8b1b5 1076 logger.error(`${this.logPrefix()} WebSocket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
5ad8570f
JB
1077 }
1078 }
1079
a2653482
JB
1080 private initializeConnectorStatus(connectorId: number): void {
1081 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
1082 this.getConnectorStatus(connectorId).idTagAuthorized = false;
1083 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
734d790d
JB
1084 this.getConnectorStatus(connectorId).transactionStarted = false;
1085 this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
1086 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
0a60c33c 1087 }
7dde0b73
JB
1088}
1089