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