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