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