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