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