Apply dependencies update
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
CommitLineData
b4d34251
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
cc6e8ab5 3import { ACElectricUtils, DCElectricUtils } from '../utils/ElectricUtils';
e7aeea18
JB
4import {
5 AvailabilityType,
6 BootNotificationRequest,
7 CachedRequest,
ef6fa3fb 8 HeartbeatRequest,
e7aeea18
JB
9 IncomingRequest,
10 IncomingRequestCommand,
ef6fa3fb 11 MeterValuesRequest,
e7aeea18 12 RequestCommand,
ef6fa3fb 13 StatusNotificationRequest,
e7aeea18 14} from '../types/ocpp/Requests';
f22266fd
JB
15import {
16 BootNotificationResponse,
b3ec7bc1 17 ErrorResponse,
f22266fd
JB
18 HeartbeatResponse,
19 MeterValuesResponse,
20 RegistrationStatus,
b3ec7bc1 21 Response,
f22266fd
JB
22 StatusNotificationResponse,
23} from '../types/ocpp/Responses';
17ac262c 24import { ChargingProfile, ChargingRateUnitType } from '../types/ocpp/ChargingProfile';
e7aeea18
JB
25import ChargingStationTemplate, {
26 CurrentType,
27 PowerUnits,
2484ac1e 28 WsOptions,
e7aeea18
JB
29} from '../types/ChargingStationTemplate';
30import {
31 ConnectorPhaseRotation,
32 StandardParametersKey,
33 SupportedFeatureProfiles,
34 VendorDefaultParametersKey,
35} from '../types/ocpp/Configuration';
492cf6ab 36import { MeterValue, MeterValueMeasurand } from '../types/ocpp/MeterValues';
ef6fa3fb
JB
37import {
38 StopTransactionReason,
39 StopTransactionRequest,
40 StopTransactionResponse,
41} from '../types/ocpp/Transaction';
0d8140bd 42import { URL, fileURLToPath } from 'url';
16b0d4e7 43import { WSError, WebSocketCloseEventStatusCode } from '../types/WebSocket';
0d8140bd 44import WebSocket, { Data, RawData } from 'ws';
3f40bc9c 45
9d7484a4 46import AuthorizedTagsCache from './AuthorizedTagsCache';
6af9012e 47import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
fa7bccf4 48import { AutomaticTransactionGeneratorConfiguration } from '../types/AutomaticTransactionGenerator';
94ec7e96 49import BaseError from '../exception/BaseError';
93b4a429 50import { ChargePointErrorCode } from '../types/ocpp/ChargePointErrorCode';
c0560973 51import { ChargePointStatus } from '../types/ocpp/ChargePointStatus';
7c72977b 52import ChargingStationConfiguration from '../types/ChargingStationConfiguration';
17ac262c 53import { ChargingStationConfigurationUtils } from './ChargingStationConfigurationUtils';
9ac86a7e 54import ChargingStationInfo from '../types/ChargingStationInfo';
17ac262c
JB
55import ChargingStationOcppConfiguration from '../types/ChargingStationOcppConfiguration';
56import { ChargingStationUtils } from './ChargingStationUtils';
ee0f106b 57import { ChargingStationWorkerMessageEvents } from '../types/ChargingStationWorker';
6af9012e 58import Configuration from '../utils/Configuration';
057e2042 59import { ConnectorStatus } from '../types/ConnectorStatus';
63b48f77 60import Constants from '../utils/Constants';
14763b46 61import { ErrorType } from '../types/ocpp/ErrorType';
a95873d8 62import { FileType } from '../types/FileType';
23132a44 63import FileUtils from '../utils/FileUtils';
d1888640 64import { JsonType } from '../types/JsonType';
d2a64eb5 65import { MessageType } from '../types/ocpp/MessageType';
e7171280 66import OCPP16IncomingRequestService from './ocpp/1.6/OCPP16IncomingRequestService';
c0560973
JB
67import OCPP16RequestService from './ocpp/1.6/OCPP16RequestService';
68import OCPP16ResponseService from './ocpp/1.6/OCPP16ResponseService';
68c993d5 69import { OCPP16ServiceUtils } from './ocpp/1.6/OCPP16ServiceUtils';
e58068fd 70import OCPPError from '../exception/OCPPError';
c0560973
JB
71import OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService';
72import OCPPRequestService from './ocpp/OCPPRequestService';
73import { OCPPVersion } from '../types/ocpp/OCPPVersion';
a6b3c6c3 74import PerformanceStatistics from '../performance/PerformanceStatistics';
57adbebc 75import SharedLRUCache from './SharedLRUCache';
2dcfe98e 76import { SupervisionUrlDistribution } from '../types/ConfigurationData';
6af9012e 77import Utils from '../utils/Utils';
3f40bc9c
JB
78import crypto from 'crypto';
79import fs from 'fs';
9f2e3130 80import logger from '../utils/Logger';
ee0f106b 81import { parentPort } from 'worker_threads';
bf1866b2 82import path from 'path';
3f40bc9c
JB
83
84export default class ChargingStation {
3f94cab5 85 public hashId!: string;
2484ac1e 86 public readonly templateFile: string;
9d7484a4 87 public authorizedTagsCache: AuthorizedTagsCache;
6e0964c8 88 public stationInfo!: ChargingStationInfo;
9e23580d 89 public readonly connectors: Map<number, ConnectorStatus>;
2484ac1e 90 public ocppConfiguration!: ChargingStationOcppConfiguration;
6e0964c8 91 public wsConnection!: WebSocket;
9e23580d 92 public readonly requests: Map<string, CachedRequest>;
6e0964c8
JB
93 public performanceStatistics!: PerformanceStatistics;
94 public heartbeatSetInterval!: NodeJS.Timeout;
6e0964c8 95 public ocppRequestService!: OCPPRequestService;
ae711c83 96 public bootNotificationResponse!: BootNotificationResponse | null;
fa7bccf4 97 public powerDivider!: number;
9e23580d 98 private readonly index: number;
073bd098 99 private configurationFile!: string;
7c72977b 100 private configurationFileHash!: string;
6e0964c8 101 private bootNotificationRequest!: BootNotificationRequest;
6e0964c8 102 private connectorsConfigurationHash!: string;
a472cf2b 103 private ocppIncomingRequestService!: OCPPIncomingRequestService;
8e242273 104 private readonly messageBuffer: Set<string>;
fa7bccf4 105 private configuredSupervisionUrl!: URL;
265e4266 106 private wsConnectionRestarted: boolean;
ad2f27c3 107 private autoReconnectRetryCount: number;
fa7bccf4 108 private stopped: boolean;
9d7484a4 109 private templateFileWatcher!: fs.FSWatcher;
57adbebc 110 private readonly sharedLRUCache: SharedLRUCache;
265e4266 111 private automaticTransactionGenerator!: AutomaticTransactionGenerator;
6e0964c8 112 private webSocketPingSetInterval!: NodeJS.Timeout;
6af9012e 113
2484ac1e 114 constructor(index: number, templateFile: string) {
ad2f27c3 115 this.index = index;
2484ac1e 116 this.templateFile = templateFile;
265e4266
JB
117 this.stopped = false;
118 this.wsConnectionRestarted = false;
ad2f27c3 119 this.autoReconnectRetryCount = 0;
57adbebc 120 this.sharedLRUCache = SharedLRUCache.getInstance();
9d7484a4 121 this.authorizedTagsCache = AuthorizedTagsCache.getInstance();
9f2e3130 122 this.connectors = new Map<number, ConnectorStatus>();
32b02249 123 this.requests = new Map<string, CachedRequest>();
8e242273 124 this.messageBuffer = new Set<string>();
9f2e3130 125 this.initialize();
c0560973
JB
126 }
127
25f5a959 128 private get wsConnectionUrl(): URL {
fa7bccf4
JB
129 return new URL(
130 (this.getSupervisionUrlOcppConfiguration()
131 ? ChargingStationConfigurationUtils.getConfigurationKey(
17ac262c
JB
132 this,
133 this.getSupervisionUrlOcppKey()
fa7bccf4
JB
134 ).value
135 : this.configuredSupervisionUrl.href) +
136 '/' +
137 this.stationInfo.chargingStationId
138 );
12fc74d6
JB
139 }
140
c0560973 141 public logPrefix(): string {
ccb1d6e9
JB
142 return Utils.logPrefix(
143 ` ${
144 this?.stationInfo?.chargingStationId ??
145 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
146 } |`
147 );
c0560973
JB
148 }
149
802cfa13
JB
150 public getBootNotificationRequest(): BootNotificationRequest {
151 return this.bootNotificationRequest;
152 }
153
f4bf2abd 154 public getRandomIdTag(): string {
9d7484a4
JB
155 const authorizationFile = ChargingStationUtils.getAuthorizationFile(this.stationInfo);
156 const index = Math.floor(
157 Utils.secureRandom() * this.authorizedTagsCache.getAuthorizedTags(authorizationFile).length
158 );
159 return this.authorizedTagsCache.getAuthorizedTags(authorizationFile)[index];
c0560973
JB
160 }
161
162 public hasAuthorizedTags(): boolean {
9d7484a4
JB
163 return !Utils.isEmptyArray(
164 this.authorizedTagsCache.getAuthorizedTags(
165 ChargingStationUtils.getAuthorizationFile(this.stationInfo)
166 )
167 );
c0560973
JB
168 }
169
6e0964c8 170 public getEnableStatistics(): boolean | undefined {
e7aeea18
JB
171 return !Utils.isUndefined(this.stationInfo.enableStatistics)
172 ? this.stationInfo.enableStatistics
173 : true;
c0560973
JB
174 }
175
a7fc8211
JB
176 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
177 return this.stationInfo.mayAuthorizeAtRemoteStart ?? true;
178 }
179
fa7bccf4
JB
180 public getNumberOfPhases(stationInfo?: ChargingStationInfo): number | undefined {
181 const localStationInfo: ChargingStationInfo = stationInfo ?? this.stationInfo;
182 switch (this.getCurrentOutType(stationInfo)) {
4c2b4904 183 case CurrentType.AC:
fa7bccf4
JB
184 return !Utils.isUndefined(localStationInfo.numberOfPhases)
185 ? localStationInfo.numberOfPhases
e7aeea18 186 : 3;
4c2b4904 187 case CurrentType.DC:
c0560973
JB
188 return 0;
189 }
190 }
191
d5bff457 192 public isWebSocketConnectionOpened(): boolean {
0d8140bd 193 return this?.wsConnection?.readyState === WebSocket.OPEN;
c0560973
JB
194 }
195
672fed6e
JB
196 public getRegistrationStatus(): RegistrationStatus {
197 return this?.bootNotificationResponse?.status;
198 }
199
73c4266d
JB
200 public isInUnknownState(): boolean {
201 return Utils.isNullOrUndefined(this?.bootNotificationResponse?.status);
202 }
203
16cd35ad
JB
204 public isInPendingState(): boolean {
205 return this?.bootNotificationResponse?.status === RegistrationStatus.PENDING;
206 }
207
208 public isInAcceptedState(): boolean {
e58068fd 209 return this?.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED;
c0560973
JB
210 }
211
16cd35ad
JB
212 public isInRejectedState(): boolean {
213 return this?.bootNotificationResponse?.status === RegistrationStatus.REJECTED;
214 }
215
216 public isRegistered(): boolean {
73c4266d 217 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
16cd35ad
JB
218 }
219
c0560973 220 public isChargingStationAvailable(): boolean {
734d790d 221 return this.getConnectorStatus(0).availability === AvailabilityType.OPERATIVE;
c0560973
JB
222 }
223
224 public isConnectorAvailable(id: number): boolean {
9f2e3130 225 return id > 0 && this.getConnectorStatus(id).availability === AvailabilityType.OPERATIVE;
c0560973
JB
226 }
227
54544ef1
JB
228 public getNumberOfConnectors(): number {
229 return this.connectors.get(0) ? this.connectors.size - 1 : this.connectors.size;
230 }
231
734d790d
JB
232 public getConnectorStatus(id: number): ConnectorStatus {
233 return this.connectors.get(id);
c0560973
JB
234 }
235
fa7bccf4
JB
236 public getCurrentOutType(stationInfo?: ChargingStationInfo): CurrentType {
237 return (stationInfo ?? this.stationInfo).currentOutType ?? CurrentType.AC;
c0560973
JB
238 }
239
672fed6e 240 public getOcppStrictCompliance(): boolean {
ccb1d6e9 241 return this.stationInfo?.ocppStrictCompliance ?? false;
672fed6e
JB
242 }
243
fa7bccf4 244 public getVoltageOut(stationInfo?: ChargingStationInfo): number | undefined {
492cf6ab 245 const defaultVoltageOut = ChargingStationUtils.getDefaultVoltageOut(
fa7bccf4 246 this.getCurrentOutType(stationInfo),
492cf6ab
JB
247 this.templateFile,
248 this.logPrefix()
249 );
fa7bccf4
JB
250 const localStationInfo: ChargingStationInfo = stationInfo ?? this.stationInfo;
251 return !Utils.isUndefined(localStationInfo.voltageOut)
252 ? localStationInfo.voltageOut
e7aeea18 253 : defaultVoltageOut;
c0560973
JB
254 }
255
ad8537a7 256 public getConnectorMaximumAvailablePower(connectorId: number): number {
d20f43b5 257 let connectorAmperageLimitationPowerLimit: number;
b47d68d7
JB
258 if (
259 !Utils.isNullOrUndefined(this.getAmperageLimitation()) &&
260 this.getAmperageLimitation() < this.stationInfo.maximumAmperage
261 ) {
4160ae28
JB
262 connectorAmperageLimitationPowerLimit =
263 (this.getCurrentOutType() === CurrentType.AC
cc6e8ab5
JB
264 ? ACElectricUtils.powerTotal(
265 this.getNumberOfPhases(),
266 this.getVoltageOut(),
da57964c 267 this.getAmperageLimitation() * this.getNumberOfConnectors()
cc6e8ab5 268 )
4160ae28 269 : DCElectricUtils.power(this.getVoltageOut(), this.getAmperageLimitation())) /
fa7bccf4 270 this.powerDivider;
cc6e8ab5 271 }
fa7bccf4 272 const connectorMaximumPower = this.getMaximumPower() / this.powerDivider;
7b872eaa 273 const connectorChargingProfilePowerLimit = this.getChargingProfilePowerLimit(connectorId);
ad8537a7
JB
274 return Math.min(
275 isNaN(connectorMaximumPower) ? Infinity : connectorMaximumPower,
276 isNaN(connectorAmperageLimitationPowerLimit)
277 ? Infinity
278 : connectorAmperageLimitationPowerLimit,
279 isNaN(connectorChargingProfilePowerLimit) ? Infinity : connectorChargingProfilePowerLimit
280 );
cc6e8ab5
JB
281 }
282
6e0964c8 283 public getTransactionIdTag(transactionId: number): string | undefined {
734d790d
JB
284 for (const connectorId of this.connectors.keys()) {
285 if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
286 return this.getConnectorStatus(connectorId).transactionIdTag;
c0560973
JB
287 }
288 }
289 }
290
6ed92bc1 291 public getOutOfOrderEndMeterValues(): boolean {
ccb1d6e9 292 return this.stationInfo?.outOfOrderEndMeterValues ?? false;
6ed92bc1
JB
293 }
294
295 public getBeginEndMeterValues(): boolean {
ccb1d6e9 296 return this.stationInfo?.beginEndMeterValues ?? false;
6ed92bc1
JB
297 }
298
299 public getMeteringPerTransaction(): boolean {
ccb1d6e9 300 return this.stationInfo?.meteringPerTransaction ?? true;
6ed92bc1
JB
301 }
302
fd0c36fa 303 public getTransactionDataMeterValues(): boolean {
ccb1d6e9 304 return this.stationInfo?.transactionDataMeterValues ?? false;
fd0c36fa
JB
305 }
306
9ccca265 307 public getMainVoltageMeterValues(): boolean {
ccb1d6e9 308 return this.stationInfo?.mainVoltageMeterValues ?? true;
9ccca265
JB
309 }
310
6b10669b 311 public getPhaseLineToLineVoltageMeterValues(): boolean {
ccb1d6e9 312 return this.stationInfo?.phaseLineToLineVoltageMeterValues ?? false;
9bd87386
JB
313 }
314
7bc31f9c 315 public getCustomValueLimitationMeterValues(): boolean {
ccb1d6e9 316 return this.stationInfo?.customValueLimitationMeterValues ?? true;
7bc31f9c
JB
317 }
318
f479a792 319 public getConnectorIdByTransactionId(transactionId: number): number | undefined {
734d790d 320 for (const connectorId of this.connectors.keys()) {
f479a792
JB
321 if (
322 connectorId > 0 &&
323 this.getConnectorStatus(connectorId)?.transactionId === transactionId
324 ) {
325 return connectorId;
c0560973
JB
326 }
327 }
328 }
329
cbad1217
JB
330 public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined {
331 const transactionConnectorStatus = this.getConnectorStatus(
332 this.getConnectorIdByTransactionId(transactionId)
333 );
334 if (this.getMeteringPerTransaction()) {
335 return transactionConnectorStatus?.transactionEnergyActiveImportRegisterValue;
336 }
337 return transactionConnectorStatus?.energyActiveImportRegisterValue;
338 }
339
6ed92bc1 340 public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined {
cbad1217 341 const connectorStatus = this.getConnectorStatus(connectorId);
6ed92bc1 342 if (this.getMeteringPerTransaction()) {
cbad1217 343 return connectorStatus?.transactionEnergyActiveImportRegisterValue;
6ed92bc1 344 }
cbad1217 345 return connectorStatus?.energyActiveImportRegisterValue;
6ed92bc1
JB
346 }
347
c0560973 348 public getAuthorizeRemoteTxRequests(): boolean {
17ac262c
JB
349 const authorizeRemoteTxRequests = ChargingStationConfigurationUtils.getConfigurationKey(
350 this,
e7aeea18
JB
351 StandardParametersKey.AuthorizeRemoteTxRequests
352 );
353 return authorizeRemoteTxRequests
354 ? Utils.convertToBoolean(authorizeRemoteTxRequests.value)
355 : false;
c0560973
JB
356 }
357
358 public getLocalAuthListEnabled(): boolean {
17ac262c
JB
359 const localAuthListEnabled = ChargingStationConfigurationUtils.getConfigurationKey(
360 this,
e7aeea18
JB
361 StandardParametersKey.LocalAuthListEnabled
362 );
c0560973
JB
363 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
364 }
365
c0560973 366 public startHeartbeat(): void {
e7aeea18
JB
367 if (
368 this.getHeartbeatInterval() &&
369 this.getHeartbeatInterval() > 0 &&
370 !this.heartbeatSetInterval
371 ) {
71623267
JB
372 // eslint-disable-next-line @typescript-eslint/no-misused-promises
373 this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
f7f98c68 374 await this.ocppRequestService.requestHandler<HeartbeatRequest, HeartbeatResponse>(
08f130a0 375 this,
f22266fd
JB
376 RequestCommand.HEARTBEAT
377 );
c0560973 378 }, this.getHeartbeatInterval());
e7aeea18
JB
379 logger.info(
380 this.logPrefix() +
381 ' Heartbeat started every ' +
382 Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
383 );
c0560973 384 } else if (this.heartbeatSetInterval) {
e7aeea18
JB
385 logger.info(
386 this.logPrefix() +
387 ' Heartbeat already started every ' +
388 Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
389 );
c0560973 390 } else {
e7aeea18
JB
391 logger.error(
392 `${this.logPrefix()} Heartbeat interval set to ${
393 this.getHeartbeatInterval()
394 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
395 : this.getHeartbeatInterval()
396 }, not starting the heartbeat`
397 );
c0560973
JB
398 }
399 }
400
401 public restartHeartbeat(): void {
402 // Stop heartbeat
403 this.stopHeartbeat();
404 // Start heartbeat
405 this.startHeartbeat();
406 }
407
17ac262c
JB
408 public restartWebSocketPing(): void {
409 // Stop WebSocket ping
410 this.stopWebSocketPing();
411 // Start WebSocket ping
412 this.startWebSocketPing();
413 }
414
c0560973
JB
415 public startMeterValues(connectorId: number, interval: number): void {
416 if (connectorId === 0) {
e7aeea18
JB
417 logger.error(
418 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
419 );
c0560973
JB
420 return;
421 }
734d790d 422 if (!this.getConnectorStatus(connectorId)) {
e7aeea18
JB
423 logger.error(
424 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
425 );
c0560973
JB
426 return;
427 }
734d790d 428 if (!this.getConnectorStatus(connectorId)?.transactionStarted) {
e7aeea18
JB
429 logger.error(
430 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
431 );
c0560973 432 return;
e7aeea18
JB
433 } else if (
434 this.getConnectorStatus(connectorId)?.transactionStarted &&
435 !this.getConnectorStatus(connectorId)?.transactionId
436 ) {
437 logger.error(
438 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
439 );
c0560973
JB
440 return;
441 }
442 if (interval > 0) {
71623267 443 // eslint-disable-next-line @typescript-eslint/no-misused-promises
e7aeea18 444 this.getConnectorStatus(connectorId).transactionSetInterval = setInterval(
9534e74e 445 // eslint-disable-next-line @typescript-eslint/no-misused-promises
e7aeea18 446 async (): Promise<void> => {
0f3d5941
JB
447 // FIXME: Implement OCPP version agnostic helpers
448 const meterValue: MeterValue = OCPP16ServiceUtils.buildMeterValue(
449 this,
e7aeea18
JB
450 connectorId,
451 this.getConnectorStatus(connectorId).transactionId,
452 interval
453 );
f7f98c68 454 await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>(
08f130a0 455 this,
f22266fd
JB
456 RequestCommand.METER_VALUES,
457 {
458 connectorId,
459 transactionId: this.getConnectorStatus(connectorId).transactionId,
460 meterValue: [meterValue],
461 }
462 );
e7aeea18
JB
463 },
464 interval
465 );
c0560973 466 } else {
e7aeea18
JB
467 logger.error(
468 `${this.logPrefix()} Charging station ${
469 StandardParametersKey.MeterValueSampleInterval
470 } configuration set to ${
471 interval ? Utils.formatDurationMilliSeconds(interval) : interval
472 }, not sending MeterValues`
473 );
c0560973
JB
474 }
475 }
476
477 public start(): void {
7874b0b1
JB
478 if (this.getEnableStatistics()) {
479 this.performanceStatistics.start();
480 }
c0560973 481 this.openWSConnection();
94bb24d5
JB
482 // Handle WebSocket message
483 this.wsConnection.on(
484 'message',
485 this.onMessage.bind(this) as (this: WebSocket, data: RawData, isBinary: boolean) => void
486 );
487 // Handle WebSocket error
488 this.wsConnection.on(
489 'error',
490 this.onError.bind(this) as (this: WebSocket, error: Error) => void
491 );
492 // Handle WebSocket close
493 this.wsConnection.on(
494 'close',
495 this.onClose.bind(this) as (this: WebSocket, code: number, reason: Buffer) => void
496 );
497 // Handle WebSocket open
498 this.wsConnection.on('open', this.onOpen.bind(this) as (this: WebSocket) => void);
499 // Handle WebSocket ping
500 this.wsConnection.on('ping', this.onPing.bind(this) as (this: WebSocket, data: Buffer) => void);
501 // Handle WebSocket pong
502 this.wsConnection.on('pong', this.onPong.bind(this) as (this: WebSocket, data: Buffer) => void);
a95873d8 503 // Monitor charging station template file
9d7484a4 504 this.templateFileWatcher = FileUtils.watchJsonFile(
a95873d8
JB
505 this.logPrefix(),
506 FileType.ChargingStationTemplate,
2484ac1e 507 this.templateFile,
a95873d8
JB
508 null,
509 (event, filename): void => {
510 if (filename && event === 'change') {
511 try {
512 logger.debug(
513 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
2484ac1e 514 this.templateFile
a95873d8
JB
515 } file have changed, reload`
516 );
57adbebc 517 this.sharedLRUCache.deleteChargingStationTemplate(this.stationInfo?.templateHash);
a95873d8
JB
518 // Initialize
519 this.initialize();
520 // Restart the ATG
fa7bccf4 521 this.stopAutomaticTransactionGenerator();
a95873d8
JB
522 this.startAutomaticTransactionGenerator();
523 if (this.getEnableStatistics()) {
524 this.performanceStatistics.restart();
525 } else {
526 this.performanceStatistics.stop();
527 }
528 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
529 } catch (error) {
530 logger.error(
531 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
532 error
533 );
534 }
535 }
536 }
537 );
e7aeea18
JB
538 parentPort.postMessage({
539 id: ChargingStationWorkerMessageEvents.STARTED,
540 data: { id: this.stationInfo.chargingStationId },
541 });
c0560973
JB
542 }
543
544 public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
545 // Stop message sequence
546 await this.stopMessageSequence(reason);
734d790d
JB
547 for (const connectorId of this.connectors.keys()) {
548 if (connectorId > 0) {
f7f98c68 549 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
550 StatusNotificationRequest,
551 StatusNotificationResponse
08f130a0 552 >(this, RequestCommand.STATUS_NOTIFICATION, {
ef6fa3fb
JB
553 connectorId,
554 status: ChargePointStatus.UNAVAILABLE,
555 errorCode: ChargePointErrorCode.NO_ERROR,
556 });
734d790d 557 this.getConnectorStatus(connectorId).status = ChargePointStatus.UNAVAILABLE;
c0560973
JB
558 }
559 }
55516218 560 this.closeWSConnection();
7874b0b1
JB
561 if (this.getEnableStatistics()) {
562 this.performanceStatistics.stop();
563 }
57adbebc 564 this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash);
9d7484a4 565 this.templateFileWatcher.close();
57adbebc 566 this.sharedLRUCache.deleteChargingStationTemplate(this.stationInfo?.templateHash);
c0560973 567 this.bootNotificationResponse = null;
e7aeea18
JB
568 parentPort.postMessage({
569 id: ChargingStationWorkerMessageEvents.STOPPED,
570 data: { id: this.stationInfo.chargingStationId },
571 });
265e4266 572 this.stopped = true;
c0560973
JB
573 }
574
94ec7e96
JB
575 public async reset(reason?: StopTransactionReason): Promise<void> {
576 await this.stop(reason);
577 await Utils.sleep(this.stationInfo.resetTime);
fa7bccf4 578 this.initialize();
94ec7e96
JB
579 this.start();
580 }
581
17ac262c
JB
582 public saveOcppConfiguration(): void {
583 if (this.getOcppPersistentConfiguration()) {
7c72977b 584 this.saveConfiguration();
e6895390
JB
585 }
586 }
587
ad8537a7 588 public getChargingProfilePowerLimit(connectorId: number): number | undefined {
0bb3ee61 589 let limit: number, matchingChargingProfile: ChargingProfile;
1e5bbb96 590 let chargingProfiles: ChargingProfile[] = [];
0bb3ee61 591 // Get charging profiles for connector and sort by stack level
1e5bbb96
O
592 chargingProfiles = this.getConnectorStatus(connectorId).chargingProfiles.sort(
593 (a, b) => b.stackLevel - a.stackLevel
594 );
595 // Get profiles on connector 0
596 if (this.getConnectorStatus(0).chargingProfiles) {
597 chargingProfiles.push(
598 ...this.getConnectorStatus(0).chargingProfiles.sort((a, b) => b.stackLevel - a.stackLevel)
cfa9539e 599 );
cfa9539e 600 }
1e5bbb96 601 if (!Utils.isEmptyArray(chargingProfiles)) {
17ac262c
JB
602 const result = ChargingStationUtils.getLimitFromChargingProfiles(
603 chargingProfiles,
604 Utils.logPrefix()
605 );
1e5bbb96
O
606 if (!Utils.isNullOrUndefined(result)) {
607 limit = result.limit;
608 matchingChargingProfile = result.matchingChargingProfile;
609 switch (this.getCurrentOutType()) {
610 case CurrentType.AC:
611 limit =
612 matchingChargingProfile.chargingSchedule.chargingRateUnit ===
613 ChargingRateUnitType.WATT
614 ? limit
615 : ACElectricUtils.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit);
616 break;
617 case CurrentType.DC:
618 limit =
619 matchingChargingProfile.chargingSchedule.chargingRateUnit ===
620 ChargingRateUnitType.WATT
621 ? limit
622 : DCElectricUtils.power(this.getVoltageOut(), limit);
623 }
624
fa7bccf4 625 const connectorMaximumPower = this.getMaximumPower() / this.powerDivider;
1e5bbb96
O
626 if (limit > connectorMaximumPower) {
627 logger.error(
628 `${this.logPrefix()} Charging profile id ${
629 matchingChargingProfile.chargingProfileId
630 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
631 this.getConnectorStatus(connectorId).chargingProfiles
632 );
633 limit = connectorMaximumPower;
634 }
cfa9539e 635 }
ad8537a7 636 }
ad8537a7 637 return limit;
cfa9539e
JB
638 }
639
a7fc8211 640 public setChargingProfile(connectorId: number, cp: ChargingProfile): void {
0bb3ee61
JB
641 if (Utils.isNullOrUndefined(this.getConnectorStatus(connectorId).chargingProfiles)) {
642 logger.error(
643 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
644 );
645 this.getConnectorStatus(connectorId).chargingProfiles = [];
646 }
1e5bbb96 647 if (!Array.isArray(this.getConnectorStatus(connectorId).chargingProfiles)) {
0bb3ee61
JB
648 logger.error(
649 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an improper attribute type for the charging profiles array, applying proper type initialization`
650 );
1e5bbb96
O
651 this.getConnectorStatus(connectorId).chargingProfiles = [];
652 }
a7fc8211 653 let cpReplaced = false;
734d790d 654 if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId).chargingProfiles)) {
e7aeea18
JB
655 this.getConnectorStatus(connectorId).chargingProfiles?.forEach(
656 (chargingProfile: ChargingProfile, index: number) => {
657 if (
658 chargingProfile.chargingProfileId === cp.chargingProfileId ||
659 (chargingProfile.stackLevel === cp.stackLevel &&
660 chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)
661 ) {
662 this.getConnectorStatus(connectorId).chargingProfiles[index] = cp;
663 cpReplaced = true;
664 }
c0560973 665 }
e7aeea18 666 );
c0560973 667 }
734d790d 668 !cpReplaced && this.getConnectorStatus(connectorId).chargingProfiles?.push(cp);
c0560973
JB
669 }
670
a2653482
JB
671 public resetConnectorStatus(connectorId: number): void {
672 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
673 this.getConnectorStatus(connectorId).idTagAuthorized = false;
674 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
734d790d 675 this.getConnectorStatus(connectorId).transactionStarted = false;
a2653482 676 delete this.getConnectorStatus(connectorId).localAuthorizeIdTag;
734d790d
JB
677 delete this.getConnectorStatus(connectorId).authorizeIdTag;
678 delete this.getConnectorStatus(connectorId).transactionId;
679 delete this.getConnectorStatus(connectorId).transactionIdTag;
680 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
681 delete this.getConnectorStatus(connectorId).transactionBeginMeterValue;
dd119a6b 682 this.stopMeterValues(connectorId);
2e6f5966
JB
683 }
684
68cb8b91 685 public hasFeatureProfile(featureProfile: SupportedFeatureProfiles) {
17ac262c
JB
686 return ChargingStationConfigurationUtils.getConfigurationKey(
687 this,
688 StandardParametersKey.SupportedFeatureProfiles
689 )?.value.includes(featureProfile);
68cb8b91
JB
690 }
691
8e242273
JB
692 public bufferMessage(message: string): void {
693 this.messageBuffer.add(message);
3ba2381e
JB
694 }
695
8e242273
JB
696 private flushMessageBuffer() {
697 if (this.messageBuffer.size > 0) {
698 this.messageBuffer.forEach((message) => {
aef1b33a 699 // TODO: evaluate the need to track performance
77f00f84 700 this.wsConnection.send(message);
8e242273 701 this.messageBuffer.delete(message);
77f00f84
JB
702 });
703 }
704 }
705
1f5df42a
JB
706 private getSupervisionUrlOcppConfiguration(): boolean {
707 return this.stationInfo.supervisionUrlOcppConfiguration ?? false;
12fc74d6
JB
708 }
709
e8e865ea
JB
710 private getSupervisionUrlOcppKey(): string {
711 return this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl;
712 }
713
9214b603 714 private getTemplateFromFile(): ChargingStationTemplate | null {
2484ac1e 715 let template: ChargingStationTemplate = null;
5ad8570f 716 try {
57adbebc
JB
717 if (this.sharedLRUCache.hasChargingStationTemplate(this.stationInfo?.templateHash)) {
718 template = this.sharedLRUCache.getChargingStationTemplate(this.stationInfo.templateHash);
7c72977b
JB
719 } else {
720 const measureId = `${FileType.ChargingStationTemplate} read`;
721 const beginId = PerformanceStatistics.beginMeasure(measureId);
722 template = JSON.parse(
723 fs.readFileSync(this.templateFile, 'utf8')
724 ) as ChargingStationTemplate;
725 PerformanceStatistics.endMeasure(measureId, beginId);
726 template.templateHash = crypto
727 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
728 .update(JSON.stringify(template))
729 .digest('hex');
57adbebc 730 this.sharedLRUCache.setChargingStationTemplate(template);
7c72977b 731 }
5ad8570f 732 } catch (error) {
e7aeea18
JB
733 FileUtils.handleFileException(
734 this.logPrefix(),
a95873d8 735 FileType.ChargingStationTemplate,
2484ac1e 736 this.templateFile,
e7aeea18
JB
737 error as NodeJS.ErrnoException
738 );
5ad8570f 739 }
2484ac1e
JB
740 return template;
741 }
742
7a3a2ebb 743 private getStationInfoFromTemplate(): ChargingStationInfo {
fa7bccf4
JB
744 const stationTemplate: ChargingStationTemplate = this.getTemplateFromFile();
745 if (Utils.isNullOrUndefined(stationTemplate)) {
ccb1d6e9
JB
746 const errorMsg = 'Failed to read charging station template file';
747 logger.error(`${this.logPrefix()} ${errorMsg}`);
748 throw new BaseError(errorMsg);
94ec7e96 749 }
fa7bccf4 750 if (Utils.isEmptyObject(stationTemplate)) {
ccb1d6e9
JB
751 const errorMsg = `Empty charging station information from template file ${this.templateFile}`;
752 logger.error(`${this.logPrefix()} ${errorMsg}`);
753 throw new BaseError(errorMsg);
94ec7e96 754 }
2dcfe98e 755 // Deprecation template keys section
17ac262c 756 ChargingStationUtils.warnDeprecatedTemplateKey(
fa7bccf4 757 stationTemplate,
e7aeea18 758 'supervisionUrl',
17ac262c 759 this.templateFile,
ccb1d6e9 760 this.logPrefix(),
e7aeea18
JB
761 "Use 'supervisionUrls' instead"
762 );
17ac262c 763 ChargingStationUtils.convertDeprecatedTemplateKey(
fa7bccf4 764 stationTemplate,
17ac262c
JB
765 'supervisionUrl',
766 'supervisionUrls'
767 );
fa7bccf4
JB
768 const stationInfo: ChargingStationInfo =
769 ChargingStationUtils.stationTemplateToStationInfo(stationTemplate);
770 stationInfo.chargingStationId = ChargingStationUtils.getChargingStationId(
771 this.index,
772 stationTemplate
773 );
774 ChargingStationUtils.createSerialNumber(stationTemplate, stationInfo);
775 if (!Utils.isEmptyArray(stationTemplate.power)) {
776 stationTemplate.power = stationTemplate.power as number[];
777 const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationTemplate.power.length);
cc6e8ab5 778 stationInfo.maximumPower =
fa7bccf4
JB
779 stationTemplate.powerUnit === PowerUnits.KILO_WATT
780 ? stationTemplate.power[powerArrayRandomIndex] * 1000
781 : stationTemplate.power[powerArrayRandomIndex];
5ad8570f 782 } else {
fa7bccf4 783 stationTemplate.power = stationTemplate.power as number;
cc6e8ab5 784 stationInfo.maximumPower =
fa7bccf4
JB
785 stationTemplate.powerUnit === PowerUnits.KILO_WATT
786 ? stationTemplate.power * 1000
787 : stationTemplate.power;
788 }
789 stationInfo.resetTime = stationTemplate.resetTime
790 ? stationTemplate.resetTime * 1000
e7aeea18 791 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
fa7bccf4
JB
792 const configuredMaxConnectors = ChargingStationUtils.getConfiguredNumberOfConnectors(
793 this.index,
794 stationTemplate
795 );
796 ChargingStationUtils.checkConfiguredMaxConnectors(
797 configuredMaxConnectors,
798 this.templateFile,
799 Utils.logPrefix()
800 );
801 const templateMaxConnectors =
802 ChargingStationUtils.getTemplateMaxNumberOfConnectors(stationTemplate);
803 ChargingStationUtils.checkTemplateMaxConnectors(
804 templateMaxConnectors,
805 this.templateFile,
806 Utils.logPrefix()
807 );
808 if (
809 configuredMaxConnectors >
810 (stationTemplate?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) &&
811 !stationTemplate?.randomConnectors
812 ) {
813 logger.warn(
814 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
815 this.templateFile
816 }, forcing random connector configurations affectation`
817 );
818 stationInfo.randomConnectors = true;
819 }
820 // Build connectors if needed (FIXME: should be factored out)
821 this.initializeConnectors(stationInfo, configuredMaxConnectors, templateMaxConnectors);
822 stationInfo.maximumAmperage = this.getMaximumAmperage(stationInfo);
823 ChargingStationUtils.createStationInfoHash(stationInfo);
9ac86a7e 824 return stationInfo;
5ad8570f
JB
825 }
826
ccb1d6e9
JB
827 private getStationInfoFromFile(): ChargingStationInfo | null {
828 let stationInfo: ChargingStationInfo = null;
fa7bccf4
JB
829 this.getStationInfoPersistentConfiguration() &&
830 (stationInfo = this.getConfigurationFromFile()?.stationInfo ?? null);
831 stationInfo && ChargingStationUtils.createStationInfoHash(stationInfo);
f765beaa 832 return stationInfo;
2484ac1e
JB
833 }
834
835 private getStationInfo(): ChargingStationInfo {
836 const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate();
2484ac1e 837 const stationInfoFromFile: ChargingStationInfo = this.getStationInfoFromFile();
aca53a1a 838 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
f765beaa 839 if (stationInfoFromFile?.templateHash === stationInfoFromTemplate.templateHash) {
01efc60a
JB
840 if (this.stationInfo?.infoHash === stationInfoFromFile?.infoHash) {
841 return this.stationInfo;
842 }
2484ac1e 843 return stationInfoFromFile;
f765beaa 844 }
fec4d204
JB
845 stationInfoFromFile &&
846 ChargingStationUtils.propagateSerialNumber(
847 this.getTemplateFromFile(),
848 stationInfoFromFile,
849 stationInfoFromTemplate
850 );
01efc60a 851 return stationInfoFromTemplate;
2484ac1e
JB
852 }
853
854 private saveStationInfo(): void {
ccb1d6e9 855 if (this.getStationInfoPersistentConfiguration()) {
7c72977b 856 this.saveConfiguration();
ccb1d6e9 857 }
2484ac1e
JB
858 }
859
1f5df42a 860 private getOcppVersion(): OCPPVersion {
aba95196 861 return this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16;
c0560973
JB
862 }
863
e8e865ea 864 private getOcppPersistentConfiguration(): boolean {
ccb1d6e9
JB
865 return this.stationInfo?.ocppPersistentConfiguration ?? true;
866 }
867
868 private getStationInfoPersistentConfiguration(): boolean {
869 return this.stationInfo?.stationInfoPersistentConfiguration ?? true;
e8e865ea
JB
870 }
871
c0560973 872 private handleUnsupportedVersion(version: OCPPVersion) {
e7aeea18 873 const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
2484ac1e 874 this.templateFile
e7aeea18 875 }`;
9f2e3130 876 logger.error(errMsg);
c0560973
JB
877 throw new Error(errMsg);
878 }
879
2484ac1e 880 private initialize(): void {
fa7bccf4 881 this.hashId = ChargingStationUtils.getHashId(this.index, this.getTemplateFromFile());
3f94cab5 882 logger.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
fa7bccf4 883 this.configurationFile = path.join(
0d8140bd 884 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
fa7bccf4
JB
885 'assets',
886 'configurations',
887 this.hashId + '.json'
0642c3d2 888 );
fa7bccf4 889 this.stationInfo = this.getStationInfo();
cc6e8ab5 890 this.saveStationInfo();
7a3a2ebb 891 // Avoid duplication of connectors related information in RAM
94ec7e96 892 this.stationInfo?.Connectors && delete this.stationInfo.Connectors;
fa7bccf4 893 this.configuredSupervisionUrl = this.getConfiguredSupervisionUrl();
0642c3d2
JB
894 if (this.getEnableStatistics()) {
895 this.performanceStatistics = PerformanceStatistics.getInstance(
896 this.hashId,
897 this.stationInfo.chargingStationId,
fa7bccf4 898 this.configuredSupervisionUrl
0642c3d2
JB
899 );
900 }
fa7bccf4
JB
901 this.bootNotificationRequest = ChargingStationUtils.createBootNotificationRequest(
902 this.stationInfo
903 );
fa7bccf4
JB
904 this.powerDivider = this.getPowerDivider();
905 // OCPP configuration
906 this.ocppConfiguration = this.getOcppConfiguration();
907 this.initializeOcppConfiguration();
1f5df42a 908 switch (this.getOcppVersion()) {
c0560973 909 case OCPPVersion.VERSION_16:
e7aeea18 910 this.ocppIncomingRequestService =
08f130a0 911 OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>();
e7aeea18 912 this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>(
08f130a0 913 OCPP16ResponseService.getInstance<OCPP16ResponseService>()
e7aeea18 914 );
c0560973
JB
915 break;
916 default:
1f5df42a 917 this.handleUnsupportedVersion(this.getOcppVersion());
c0560973
JB
918 break;
919 }
7c72977b 920 if (this.stationInfo?.autoRegister) {
47e22477
JB
921 this.bootNotificationResponse = {
922 currentTime: new Date().toISOString(),
923 interval: this.getHeartbeatInterval() / 1000,
e7aeea18 924 status: RegistrationStatus.ACCEPTED,
47e22477
JB
925 };
926 }
147d0e0f
JB
927 }
928
2484ac1e 929 private initializeOcppConfiguration(): void {
17ac262c
JB
930 if (
931 !ChargingStationConfigurationUtils.getConfigurationKey(
932 this,
933 StandardParametersKey.HeartbeatInterval
934 )
935 ) {
936 ChargingStationConfigurationUtils.addConfigurationKey(
937 this,
938 StandardParametersKey.HeartbeatInterval,
939 '0'
940 );
f0f65a62 941 }
17ac262c
JB
942 if (
943 !ChargingStationConfigurationUtils.getConfigurationKey(
944 this,
945 StandardParametersKey.HeartBeatInterval
946 )
947 ) {
948 ChargingStationConfigurationUtils.addConfigurationKey(
949 this,
950 StandardParametersKey.HeartBeatInterval,
951 '0',
952 { visible: false }
953 );
f0f65a62 954 }
e7aeea18
JB
955 if (
956 this.getSupervisionUrlOcppConfiguration() &&
17ac262c 957 !ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
e7aeea18 958 ) {
17ac262c
JB
959 ChargingStationConfigurationUtils.addConfigurationKey(
960 this,
a59737e3 961 this.getSupervisionUrlOcppKey(),
fa7bccf4 962 this.configuredSupervisionUrl.href,
e7aeea18
JB
963 { reboot: true }
964 );
e6895390
JB
965 } else if (
966 !this.getSupervisionUrlOcppConfiguration() &&
17ac262c 967 ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
e6895390 968 ) {
17ac262c
JB
969 ChargingStationConfigurationUtils.deleteConfigurationKey(
970 this,
971 this.getSupervisionUrlOcppKey(),
972 { save: false }
973 );
12fc74d6 974 }
cc6e8ab5
JB
975 if (
976 this.stationInfo.amperageLimitationOcppKey &&
17ac262c
JB
977 !ChargingStationConfigurationUtils.getConfigurationKey(
978 this,
979 this.stationInfo.amperageLimitationOcppKey
980 )
cc6e8ab5 981 ) {
17ac262c
JB
982 ChargingStationConfigurationUtils.addConfigurationKey(
983 this,
cc6e8ab5 984 this.stationInfo.amperageLimitationOcppKey,
17ac262c
JB
985 (
986 this.stationInfo.maximumAmperage *
987 ChargingStationUtils.getAmperageLimitationUnitDivider(this.stationInfo)
988 ).toString()
cc6e8ab5
JB
989 );
990 }
17ac262c
JB
991 if (
992 !ChargingStationConfigurationUtils.getConfigurationKey(
993 this,
994 StandardParametersKey.SupportedFeatureProfiles
995 )
996 ) {
997 ChargingStationConfigurationUtils.addConfigurationKey(
998 this,
e7aeea18 999 StandardParametersKey.SupportedFeatureProfiles,
b22787b4 1000 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
e7aeea18
JB
1001 );
1002 }
17ac262c
JB
1003 ChargingStationConfigurationUtils.addConfigurationKey(
1004 this,
e7aeea18
JB
1005 StandardParametersKey.NumberOfConnectors,
1006 this.getNumberOfConnectors().toString(),
a95873d8
JB
1007 { readonly: true },
1008 { overwrite: true }
e7aeea18 1009 );
17ac262c
JB
1010 if (
1011 !ChargingStationConfigurationUtils.getConfigurationKey(
1012 this,
1013 StandardParametersKey.MeterValuesSampledData
1014 )
1015 ) {
1016 ChargingStationConfigurationUtils.addConfigurationKey(
1017 this,
e7aeea18
JB
1018 StandardParametersKey.MeterValuesSampledData,
1019 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
1020 );
7abfea5f 1021 }
17ac262c
JB
1022 if (
1023 !ChargingStationConfigurationUtils.getConfigurationKey(
1024 this,
1025 StandardParametersKey.ConnectorPhaseRotation
1026 )
1027 ) {
7e1dc878 1028 const connectorPhaseRotation = [];
734d790d 1029 for (const connectorId of this.connectors.keys()) {
7e1dc878 1030 // AC/DC
734d790d
JB
1031 if (connectorId === 0 && this.getNumberOfPhases() === 0) {
1032 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1033 } else if (connectorId > 0 && this.getNumberOfPhases() === 0) {
1034 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
e7aeea18 1035 // AC
734d790d
JB
1036 } else if (connectorId > 0 && this.getNumberOfPhases() === 1) {
1037 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1038 } else if (connectorId > 0 && this.getNumberOfPhases() === 3) {
1039 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
7e1dc878
JB
1040 }
1041 }
17ac262c
JB
1042 ChargingStationConfigurationUtils.addConfigurationKey(
1043 this,
e7aeea18
JB
1044 StandardParametersKey.ConnectorPhaseRotation,
1045 connectorPhaseRotation.toString()
1046 );
7e1dc878 1047 }
e7aeea18 1048 if (
17ac262c
JB
1049 !ChargingStationConfigurationUtils.getConfigurationKey(
1050 this,
1051 StandardParametersKey.AuthorizeRemoteTxRequests
e7aeea18
JB
1052 )
1053 ) {
17ac262c
JB
1054 ChargingStationConfigurationUtils.addConfigurationKey(
1055 this,
1056 StandardParametersKey.AuthorizeRemoteTxRequests,
1057 'true'
1058 );
36f6a92e 1059 }
17ac262c
JB
1060 if (
1061 !ChargingStationConfigurationUtils.getConfigurationKey(
1062 this,
1063 StandardParametersKey.LocalAuthListEnabled
1064 ) &&
1065 ChargingStationConfigurationUtils.getConfigurationKey(
1066 this,
1067 StandardParametersKey.SupportedFeatureProfiles
1068 )?.value.includes(SupportedFeatureProfiles.LocalAuthListManagement)
1069 ) {
1070 ChargingStationConfigurationUtils.addConfigurationKey(
1071 this,
1072 StandardParametersKey.LocalAuthListEnabled,
1073 'false'
1074 );
1075 }
1076 if (
1077 !ChargingStationConfigurationUtils.getConfigurationKey(
1078 this,
1079 StandardParametersKey.ConnectionTimeOut
1080 )
1081 ) {
1082 ChargingStationConfigurationUtils.addConfigurationKey(
1083 this,
e7aeea18
JB
1084 StandardParametersKey.ConnectionTimeOut,
1085 Constants.DEFAULT_CONNECTION_TIMEOUT.toString()
1086 );
8bce55bf 1087 }
2484ac1e 1088 this.saveOcppConfiguration();
073bd098
JB
1089 }
1090
3d25cc86
JB
1091 private initializeConnectors(
1092 stationInfo: ChargingStationInfo,
fa7bccf4 1093 configuredMaxConnectors: number,
3d25cc86
JB
1094 templateMaxConnectors: number
1095 ): void {
1096 if (!stationInfo?.Connectors && this.connectors.size === 0) {
1097 const logMsg = `${this.logPrefix()} No already defined connectors and charging station information from template ${
1098 this.templateFile
1099 } with no connectors configuration defined`;
1100 logger.error(logMsg);
1101 throw new BaseError(logMsg);
1102 }
1103 if (!stationInfo?.Connectors[0]) {
1104 logger.warn(
1105 `${this.logPrefix()} Charging station information from template ${
1106 this.templateFile
1107 } with no connector Id 0 configuration`
1108 );
1109 }
1110 if (stationInfo?.Connectors) {
1111 const connectorsConfigHash = crypto
1112 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
fa7bccf4 1113 .update(JSON.stringify(stationInfo?.Connectors) + configuredMaxConnectors.toString())
3d25cc86
JB
1114 .digest('hex');
1115 const connectorsConfigChanged =
1116 this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash;
1117 if (this.connectors?.size === 0 || connectorsConfigChanged) {
1118 connectorsConfigChanged && this.connectors.clear();
1119 this.connectorsConfigurationHash = connectorsConfigHash;
1120 // Add connector Id 0
1121 let lastConnector = '0';
1122 for (lastConnector in stationInfo?.Connectors) {
1123 const lastConnectorId = Utils.convertToInt(lastConnector);
1124 if (
1125 lastConnectorId === 0 &&
fa7bccf4 1126 this.getUseConnectorId0(stationInfo) &&
3d25cc86
JB
1127 stationInfo?.Connectors[lastConnector]
1128 ) {
1129 this.connectors.set(
1130 lastConnectorId,
1131 Utils.cloneObject<ConnectorStatus>(stationInfo?.Connectors[lastConnector])
1132 );
1133 this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE;
1134 if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) {
1135 this.getConnectorStatus(lastConnectorId).chargingProfiles = [];
1136 }
1137 }
1138 }
1139 // Generate all connectors
1140 if ((stationInfo?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
fa7bccf4 1141 for (let index = 1; index <= configuredMaxConnectors; index++) {
ccb1d6e9 1142 const randConnectorId = stationInfo?.randomConnectors
3d25cc86
JB
1143 ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1)
1144 : index;
1145 this.connectors.set(
1146 index,
1147 Utils.cloneObject<ConnectorStatus>(stationInfo?.Connectors[randConnectorId])
1148 );
1149 this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE;
1150 if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) {
1151 this.getConnectorStatus(index).chargingProfiles = [];
1152 }
1153 }
1154 }
1155 }
1156 } else {
1157 logger.warn(
1158 `${this.logPrefix()} Charging station information from template ${
1159 this.templateFile
1160 } with no connectors configuration defined, using already defined connectors`
1161 );
1162 }
1163 // Initialize transaction attributes on connectors
1164 for (const connectorId of this.connectors.keys()) {
1165 if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) {
1166 this.initializeConnectorStatus(connectorId);
1167 }
1168 }
1169 }
1170
7f7b65ca 1171 private getConfigurationFromFile(): ChargingStationConfiguration | null {
073bd098 1172 let configuration: ChargingStationConfiguration = null;
2484ac1e 1173 if (this.configurationFile && fs.existsSync(this.configurationFile)) {
073bd098 1174 try {
57adbebc
JB
1175 if (this.sharedLRUCache.hasChargingStationConfiguration(this.configurationFileHash)) {
1176 configuration = this.sharedLRUCache.getChargingStationConfiguration(
1177 this.configurationFileHash
1178 );
7c72977b
JB
1179 } else {
1180 const measureId = `${FileType.ChargingStationConfiguration} read`;
1181 const beginId = PerformanceStatistics.beginMeasure(measureId);
1182 configuration = JSON.parse(
1183 fs.readFileSync(this.configurationFile, 'utf8')
1184 ) as ChargingStationConfiguration;
1185 PerformanceStatistics.endMeasure(measureId, beginId);
1186 this.configurationFileHash = configuration.configurationHash;
57adbebc 1187 this.sharedLRUCache.setChargingStationConfiguration(configuration);
7c72977b 1188 }
073bd098
JB
1189 } catch (error) {
1190 FileUtils.handleFileException(
1191 this.logPrefix(),
a95873d8 1192 FileType.ChargingStationConfiguration,
073bd098
JB
1193 this.configurationFile,
1194 error as NodeJS.ErrnoException
1195 );
1196 }
1197 }
1198 return configuration;
1199 }
1200
7c72977b 1201 private saveConfiguration(): void {
2484ac1e
JB
1202 if (this.configurationFile) {
1203 try {
2484ac1e
JB
1204 if (!fs.existsSync(path.dirname(this.configurationFile))) {
1205 fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true });
073bd098 1206 }
ccb1d6e9
JB
1207 const configurationData: ChargingStationConfiguration =
1208 this.getConfigurationFromFile() ?? {};
7c72977b
JB
1209 this.ocppConfiguration?.configurationKey &&
1210 (configurationData.configurationKey = this.ocppConfiguration.configurationKey);
1211 this.stationInfo && (configurationData.stationInfo = this.stationInfo);
1212 delete configurationData.configurationHash;
1213 const configurationHash = crypto
1214 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
1215 .update(JSON.stringify(configurationData))
1216 .digest('hex');
1217 if (this.configurationFileHash !== configurationHash) {
1218 configurationData.configurationHash = configurationHash;
1219 const measureId = `${FileType.ChargingStationConfiguration} write`;
1220 const beginId = PerformanceStatistics.beginMeasure(measureId);
1221 const fileDescriptor = fs.openSync(this.configurationFile, 'w');
1222 fs.writeFileSync(fileDescriptor, JSON.stringify(configurationData, null, 2), 'utf8');
1223 fs.closeSync(fileDescriptor);
1224 PerformanceStatistics.endMeasure(measureId, beginId);
57adbebc 1225 this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash);
7c72977b 1226 this.configurationFileHash = configurationHash;
57adbebc 1227 this.sharedLRUCache.setChargingStationConfiguration(configurationData);
7c72977b
JB
1228 } else {
1229 logger.debug(
1230 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1231 this.configurationFile
1232 }`
1233 );
2484ac1e 1234 }
2484ac1e
JB
1235 } catch (error) {
1236 FileUtils.handleFileException(
1237 this.logPrefix(),
1238 FileType.ChargingStationConfiguration,
1239 this.configurationFile,
1240 error as NodeJS.ErrnoException
073bd098
JB
1241 );
1242 }
2484ac1e
JB
1243 } else {
1244 logger.error(
01efc60a 1245 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
2484ac1e 1246 );
073bd098
JB
1247 }
1248 }
1249
ccb1d6e9
JB
1250 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration | null {
1251 return this.getTemplateFromFile()?.Configuration ?? null;
2484ac1e
JB
1252 }
1253
1254 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | null {
1255 let configuration: ChargingStationConfiguration = null;
1256 if (this.getOcppPersistentConfiguration()) {
7a3a2ebb
JB
1257 const configurationFromFile = this.getConfigurationFromFile();
1258 configuration = configurationFromFile?.configurationKey && configurationFromFile;
073bd098 1259 }
2484ac1e 1260 configuration && delete configuration.stationInfo;
073bd098 1261 return configuration;
7dde0b73
JB
1262 }
1263
ccb1d6e9 1264 private getOcppConfiguration(): ChargingStationOcppConfiguration | null {
2484ac1e
JB
1265 let ocppConfiguration: ChargingStationOcppConfiguration = this.getOcppConfigurationFromFile();
1266 if (!ocppConfiguration) {
1267 ocppConfiguration = this.getOcppConfigurationFromTemplate();
1268 }
1269 return ocppConfiguration;
1270 }
1271
c0560973 1272 private async onOpen(): Promise<void> {
5144f4d1
JB
1273 if (this.isWebSocketConnectionOpened()) {
1274 logger.info(
1275 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1276 );
94bb24d5 1277 if (!this.isRegistered()) {
5144f4d1
JB
1278 // Send BootNotification
1279 let registrationRetryCount = 0;
1280 do {
f7f98c68 1281 this.bootNotificationResponse = await this.ocppRequestService.requestHandler<
5144f4d1
JB
1282 BootNotificationRequest,
1283 BootNotificationResponse
1284 >(
08f130a0 1285 this,
f22266fd
JB
1286 RequestCommand.BOOT_NOTIFICATION,
1287 {
1288 chargePointModel: this.bootNotificationRequest.chargePointModel,
1289 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1290 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1291 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
1292 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1293 iccid: this.bootNotificationRequest.iccid,
1294 imsi: this.bootNotificationRequest.imsi,
1295 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1296 meterType: this.bootNotificationRequest.meterType,
1297 },
1298 { skipBufferingOnError: true }
1299 );
94bb24d5 1300 if (!this.isRegistered()) {
5144f4d1
JB
1301 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++;
1302 await Utils.sleep(
1303 this.bootNotificationResponse?.interval
1304 ? this.bootNotificationResponse.interval * 1000
1305 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1306 );
1307 }
1308 } while (
94bb24d5 1309 !this.isRegistered() &&
5144f4d1
JB
1310 (registrationRetryCount <= this.getRegistrationMaxRetries() ||
1311 this.getRegistrationMaxRetries() === -1)
1312 );
1313 }
94bb24d5
JB
1314 if (this.isRegistered()) {
1315 if (this.isInAcceptedState()) {
1316 await this.startMessageSequence();
1317 this.wsConnectionRestarted && this.flushMessageBuffer();
c0560973 1318 }
5144f4d1
JB
1319 } else {
1320 logger.error(
1321 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1322 );
caad9d6b 1323 }
94bb24d5 1324 this.stopped && (this.stopped = false);
5144f4d1
JB
1325 this.autoReconnectRetryCount = 0;
1326 this.wsConnectionRestarted = false;
2e6f5966 1327 } else {
5144f4d1
JB
1328 logger.warn(
1329 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
e7aeea18 1330 );
2e6f5966 1331 }
2e6f5966
JB
1332 }
1333
6c65a295 1334 private async onClose(code: number, reason: string): Promise<void> {
d09085e9 1335 switch (code) {
6c65a295
JB
1336 // Normal close
1337 case WebSocketCloseEventStatusCode.CLOSE_NORMAL:
c0560973 1338 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
e7aeea18 1339 logger.info(
17ac262c 1340 `${this.logPrefix()} WebSocket normally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
e7aeea18
JB
1341 code
1342 )}' and reason '${reason}'`
1343 );
c0560973
JB
1344 this.autoReconnectRetryCount = 0;
1345 break;
6c65a295
JB
1346 // Abnormal close
1347 default:
e7aeea18 1348 logger.error(
17ac262c 1349 `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
e7aeea18
JB
1350 code
1351 )}' and reason '${reason}'`
1352 );
d09085e9 1353 await this.reconnect(code);
c0560973
JB
1354 break;
1355 }
2e6f5966
JB
1356 }
1357
16b0d4e7 1358 private async onMessage(data: Data): Promise<void> {
b3ec7bc1
JB
1359 let messageType: number;
1360 let messageId: string;
1361 let commandName: IncomingRequestCommand;
1362 let commandPayload: JsonType;
1363 let errorType: ErrorType;
1364 let errorMessage: string;
1365 let errorDetails: JsonType;
1366 let responseCallback: (payload: JsonType, requestPayload: JsonType) => void;
a2d1c0f1 1367 let errorCallback: (error: OCPPError, requestStatistic?: boolean) => void;
32b02249 1368 let requestCommandName: RequestCommand | IncomingRequestCommand;
b3ec7bc1 1369 let requestPayload: JsonType;
32b02249 1370 let cachedRequest: CachedRequest;
c0560973
JB
1371 let errMsg: string;
1372 try {
b3ec7bc1 1373 const request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse;
47e22477 1374 if (Utils.isIterable(request)) {
9934652c 1375 [messageType, messageId] = request;
b3ec7bc1
JB
1376 // Check the type of message
1377 switch (messageType) {
1378 // Incoming Message
1379 case MessageType.CALL_MESSAGE:
9934652c 1380 [, , commandName, commandPayload] = request as IncomingRequest;
b3ec7bc1
JB
1381 if (this.getEnableStatistics()) {
1382 this.performanceStatistics.addRequestStatistic(commandName, messageType);
1383 }
1384 logger.debug(
1385 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1386 request
1387 )}`
1388 );
1389 // Process the message
1390 await this.ocppIncomingRequestService.incomingRequestHandler(
08f130a0 1391 this,
b3ec7bc1
JB
1392 messageId,
1393 commandName,
1394 commandPayload
1395 );
1396 break;
1397 // Outcome Message
1398 case MessageType.CALL_RESULT_MESSAGE:
9934652c 1399 [, , commandPayload] = request as Response;
a2d1c0f1
JB
1400 if (!this.requests.has(messageId)) {
1401 // Error
1402 throw new OCPPError(
1403 ErrorType.INTERNAL_ERROR,
1404 `Response for unknown message id ${messageId}`,
1405 null,
1406 commandPayload
1407 );
1408 }
b3ec7bc1
JB
1409 // Respond
1410 cachedRequest = this.requests.get(messageId);
1411 if (Utils.isIterable(cachedRequest)) {
1412 [responseCallback, , requestCommandName, requestPayload] = cachedRequest;
1413 } else {
1414 throw new OCPPError(
1415 ErrorType.PROTOCOL_ERROR,
c2bc716f
JB
1416 `Cached request for message id ${messageId} response is not iterable`,
1417 null,
1418 cachedRequest as unknown as JsonType
b3ec7bc1
JB
1419 );
1420 }
1421 logger.debug(
7ec6c5c9
JB
1422 `${this.logPrefix()} << Command '${
1423 requestCommandName ?? ''
1424 }' received response payload: ${JSON.stringify(request)}`
b3ec7bc1 1425 );
a2d1c0f1
JB
1426 responseCallback(commandPayload, requestPayload);
1427 break;
1428 // Error Message
1429 case MessageType.CALL_ERROR_MESSAGE:
1430 [, , errorType, errorMessage, errorDetails] = request as ErrorResponse;
1431 if (!this.requests.has(messageId)) {
b3ec7bc1
JB
1432 // Error
1433 throw new OCPPError(
1434 ErrorType.INTERNAL_ERROR,
a2d1c0f1 1435 `Error response for unknown message id ${messageId}`,
c2bc716f 1436 null,
a2d1c0f1 1437 { errorType, errorMessage, errorDetails }
b3ec7bc1
JB
1438 );
1439 }
b3ec7bc1
JB
1440 cachedRequest = this.requests.get(messageId);
1441 if (Utils.isIterable(cachedRequest)) {
a2d1c0f1 1442 [, errorCallback, requestCommandName] = cachedRequest;
b3ec7bc1
JB
1443 } else {
1444 throw new OCPPError(
1445 ErrorType.PROTOCOL_ERROR,
c2bc716f
JB
1446 `Cached request for message id ${messageId} error response is not iterable`,
1447 null,
1448 cachedRequest as unknown as JsonType
b3ec7bc1
JB
1449 );
1450 }
1451 logger.debug(
7ec6c5c9
JB
1452 `${this.logPrefix()} << Command '${
1453 requestCommandName ?? ''
1454 }' received error payload: ${JSON.stringify(request)}`
b3ec7bc1 1455 );
a2d1c0f1 1456 errorCallback(new OCPPError(errorType, errorMessage, requestCommandName, errorDetails));
b3ec7bc1
JB
1457 break;
1458 // Error
1459 default:
1460 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1461 errMsg = `${this.logPrefix()} Wrong message type ${messageType}`;
1462 logger.error(errMsg);
1463 throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg);
1464 }
47e22477 1465 } else {
ac54a9bb
JB
1466 throw new OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming message is not iterable', null, {
1467 payload: request,
1468 });
47e22477 1469 }
c0560973
JB
1470 } catch (error) {
1471 // Log
e7aeea18
JB
1472 logger.error(
1473 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1474 this.logPrefix(),
1475 data.toString(),
1476 this.requests.get(messageId),
1477 error
1478 );
c0560973 1479 // Send error
e7aeea18 1480 messageType === MessageType.CALL_MESSAGE &&
b3ec7bc1 1481 (await this.ocppRequestService.sendError(
08f130a0 1482 this,
b3ec7bc1
JB
1483 messageId,
1484 error as OCPPError,
a2d1c0f1 1485 commandName ?? requestCommandName ?? null
b3ec7bc1 1486 ));
c0560973 1487 }
2328be1e
JB
1488 }
1489
c0560973 1490 private onPing(): void {
9f2e3130 1491 logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
c0560973
JB
1492 }
1493
1494 private onPong(): void {
9f2e3130 1495 logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
c0560973
JB
1496 }
1497
9534e74e 1498 private onError(error: WSError): void {
9f2e3130 1499 logger.error(this.logPrefix() + ' WebSocket error: %j', error);
c0560973
JB
1500 }
1501
fa7bccf4
JB
1502 private getUseConnectorId0(stationInfo?: ChargingStationInfo): boolean | undefined {
1503 const localStationInfo = stationInfo ?? this.stationInfo;
1504 return !Utils.isUndefined(localStationInfo.useConnectorId0)
1505 ? localStationInfo.useConnectorId0
e7aeea18 1506 : true;
8bce55bf
JB
1507 }
1508
c0560973 1509 private getNumberOfRunningTransactions(): number {
6ecb15e4 1510 let trxCount = 0;
734d790d
JB
1511 for (const connectorId of this.connectors.keys()) {
1512 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
6ecb15e4
JB
1513 trxCount++;
1514 }
1515 }
1516 return trxCount;
1517 }
1518
1f761b9a 1519 // 0 for disabling
6e0964c8 1520 private getConnectionTimeout(): number | undefined {
17ac262c
JB
1521 if (
1522 ChargingStationConfigurationUtils.getConfigurationKey(
1523 this,
1524 StandardParametersKey.ConnectionTimeOut
1525 )
1526 ) {
e7aeea18 1527 return (
17ac262c
JB
1528 parseInt(
1529 ChargingStationConfigurationUtils.getConfigurationKey(
1530 this,
1531 StandardParametersKey.ConnectionTimeOut
1532 ).value
1533 ) ?? Constants.DEFAULT_CONNECTION_TIMEOUT
e7aeea18 1534 );
291cb255 1535 }
291cb255 1536 return Constants.DEFAULT_CONNECTION_TIMEOUT;
3574dfd3
JB
1537 }
1538
1f761b9a 1539 // -1 for unlimited, 0 for disabling
6e0964c8 1540 private getAutoReconnectMaxRetries(): number | undefined {
ad2f27c3
JB
1541 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
1542 return this.stationInfo.autoReconnectMaxRetries;
3574dfd3
JB
1543 }
1544 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
1545 return Configuration.getAutoReconnectMaxRetries();
1546 }
1547 return -1;
1548 }
1549
ec977daf 1550 // 0 for disabling
6e0964c8 1551 private getRegistrationMaxRetries(): number | undefined {
ad2f27c3
JB
1552 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
1553 return this.stationInfo.registrationMaxRetries;
32a1eb7a
JB
1554 }
1555 return -1;
1556 }
1557
c0560973
JB
1558 private getPowerDivider(): number {
1559 let powerDivider = this.getNumberOfConnectors();
fa7bccf4 1560 if (this.stationInfo?.powerSharedByConnectors) {
c0560973 1561 powerDivider = this.getNumberOfRunningTransactions();
6ecb15e4
JB
1562 }
1563 return powerDivider;
1564 }
1565
fa7bccf4
JB
1566 private getMaximumPower(stationInfo?: ChargingStationInfo): number {
1567 const localStationInfo = stationInfo ?? this.stationInfo;
1568 return (localStationInfo['maxPower'] as number) ?? localStationInfo.maximumPower;
0642c3d2
JB
1569 }
1570
fa7bccf4
JB
1571 private getMaximumAmperage(stationInfo: ChargingStationInfo): number | undefined {
1572 const maximumPower = this.getMaximumPower(stationInfo);
1573 switch (this.getCurrentOutType(stationInfo)) {
cc6e8ab5
JB
1574 case CurrentType.AC:
1575 return ACElectricUtils.amperagePerPhaseFromPower(
fa7bccf4 1576 this.getNumberOfPhases(stationInfo),
ad8537a7 1577 maximumPower / this.getNumberOfConnectors(),
fa7bccf4 1578 this.getVoltageOut(stationInfo)
cc6e8ab5
JB
1579 );
1580 case CurrentType.DC:
fa7bccf4 1581 return DCElectricUtils.amperage(maximumPower, this.getVoltageOut(stationInfo));
cc6e8ab5
JB
1582 }
1583 }
1584
cc6e8ab5
JB
1585 private getAmperageLimitation(): number | undefined {
1586 if (
1587 this.stationInfo.amperageLimitationOcppKey &&
17ac262c
JB
1588 ChargingStationConfigurationUtils.getConfigurationKey(
1589 this,
1590 this.stationInfo.amperageLimitationOcppKey
1591 )
cc6e8ab5
JB
1592 ) {
1593 return (
1594 Utils.convertToInt(
17ac262c
JB
1595 ChargingStationConfigurationUtils.getConfigurationKey(
1596 this,
1597 this.stationInfo.amperageLimitationOcppKey
1598 ).value
1599 ) / ChargingStationUtils.getAmperageLimitationUnitDivider(this.stationInfo)
cc6e8ab5
JB
1600 );
1601 }
1602 }
1603
c0560973 1604 private async startMessageSequence(): Promise<void> {
7c72977b 1605 if (this.stationInfo?.autoRegister) {
f7f98c68 1606 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1607 BootNotificationRequest,
1608 BootNotificationResponse
1609 >(
08f130a0 1610 this,
6a8b180d
JB
1611 RequestCommand.BOOT_NOTIFICATION,
1612 {
1613 chargePointModel: this.bootNotificationRequest.chargePointModel,
1614 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1615 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1616 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
29d1e2e7
JB
1617 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1618 iccid: this.bootNotificationRequest.iccid,
1619 imsi: this.bootNotificationRequest.imsi,
1620 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1621 meterType: this.bootNotificationRequest.meterType,
6a8b180d
JB
1622 },
1623 { skipBufferingOnError: true }
e7aeea18 1624 );
6114e6f1 1625 }
136c90ba 1626 // Start WebSocket ping
c0560973 1627 this.startWebSocketPing();
5ad8570f 1628 // Start heartbeat
c0560973 1629 this.startHeartbeat();
0a60c33c 1630 // Initialize connectors status
734d790d
JB
1631 for (const connectorId of this.connectors.keys()) {
1632 if (connectorId === 0) {
593cf3f9 1633 continue;
e7aeea18
JB
1634 } else if (
1635 !this.stopped &&
1636 !this.getConnectorStatus(connectorId)?.status &&
1637 this.getConnectorStatus(connectorId)?.bootStatus
1638 ) {
136c90ba 1639 // Send status in template at startup
f7f98c68 1640 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1641 StatusNotificationRequest,
1642 StatusNotificationResponse
08f130a0 1643 >(this, RequestCommand.STATUS_NOTIFICATION, {
ef6fa3fb
JB
1644 connectorId,
1645 status: this.getConnectorStatus(connectorId).bootStatus,
1646 errorCode: ChargePointErrorCode.NO_ERROR,
1647 });
e7aeea18
JB
1648 this.getConnectorStatus(connectorId).status =
1649 this.getConnectorStatus(connectorId).bootStatus;
1650 } else if (
1651 this.stopped &&
1652 this.getConnectorStatus(connectorId)?.status &&
1653 this.getConnectorStatus(connectorId)?.bootStatus
1654 ) {
136c90ba 1655 // Send status in template after reset
f7f98c68 1656 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1657 StatusNotificationRequest,
1658 StatusNotificationResponse
08f130a0 1659 >(this, RequestCommand.STATUS_NOTIFICATION, {
ef6fa3fb
JB
1660 connectorId,
1661 status: this.getConnectorStatus(connectorId).bootStatus,
1662 errorCode: ChargePointErrorCode.NO_ERROR,
1663 });
e7aeea18
JB
1664 this.getConnectorStatus(connectorId).status =
1665 this.getConnectorStatus(connectorId).bootStatus;
734d790d 1666 } else if (!this.stopped && this.getConnectorStatus(connectorId)?.status) {
136c90ba 1667 // Send previous status at template reload
f7f98c68 1668 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1669 StatusNotificationRequest,
1670 StatusNotificationResponse
08f130a0 1671 >(this, RequestCommand.STATUS_NOTIFICATION, {
ef6fa3fb
JB
1672 connectorId,
1673 status: this.getConnectorStatus(connectorId).status,
1674 errorCode: ChargePointErrorCode.NO_ERROR,
1675 });
5ad8570f 1676 } else {
136c90ba 1677 // Send default status
f7f98c68 1678 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1679 StatusNotificationRequest,
1680 StatusNotificationResponse
08f130a0 1681 >(this, RequestCommand.STATUS_NOTIFICATION, {
ef6fa3fb
JB
1682 connectorId,
1683 status: ChargePointStatus.AVAILABLE,
1684 errorCode: ChargePointErrorCode.NO_ERROR,
1685 });
734d790d 1686 this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE;
5ad8570f
JB
1687 }
1688 }
0a60c33c 1689 // Start the ATG
dd119a6b 1690 this.startAutomaticTransactionGenerator();
dd119a6b
JB
1691 }
1692
1693 private startAutomaticTransactionGenerator() {
fa7bccf4 1694 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable) {
265e4266 1695 if (!this.automaticTransactionGenerator) {
fa7bccf4
JB
1696 this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance(
1697 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
1698 this
1699 );
5ad8570f 1700 }
265e4266
JB
1701 if (!this.automaticTransactionGenerator.started) {
1702 this.automaticTransactionGenerator.start();
5ad8570f
JB
1703 }
1704 }
5ad8570f
JB
1705 }
1706
fa7bccf4
JB
1707 private stopAutomaticTransactionGenerator(): void {
1708 if (this.automaticTransactionGenerator?.started) {
1709 this.automaticTransactionGenerator.stop();
1710 this.automaticTransactionGenerator = null;
1711 }
1712 }
1713
e7aeea18
JB
1714 private async stopMessageSequence(
1715 reason: StopTransactionReason = StopTransactionReason.NONE
1716 ): Promise<void> {
136c90ba 1717 // Stop WebSocket ping
c0560973 1718 this.stopWebSocketPing();
79411696 1719 // Stop heartbeat
c0560973 1720 this.stopHeartbeat();
fa7bccf4
JB
1721 // Stop ongoing transactions
1722 if (this.automaticTransactionGenerator?.configuration?.enable) {
1723 this.stopAutomaticTransactionGenerator();
79411696 1724 } else {
734d790d
JB
1725 for (const connectorId of this.connectors.keys()) {
1726 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
1727 const transactionId = this.getConnectorStatus(connectorId).transactionId;
68c993d5
JB
1728 if (
1729 this.getBeginEndMeterValues() &&
1730 this.getOcppStrictCompliance() &&
1731 !this.getOutOfOrderEndMeterValues()
1732 ) {
1733 // FIXME: Implement OCPP version agnostic helpers
1734 const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue(
1735 this,
1736 connectorId,
1737 this.getEnergyActiveImportRegisterByTransactionId(transactionId)
1738 );
f7f98c68 1739 await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>(
08f130a0 1740 this,
f7f98c68
JB
1741 RequestCommand.METER_VALUES,
1742 {
1743 connectorId,
1744 transactionId,
1745 meterValue: transactionEndMeterValue,
1746 }
1747 );
ef6fa3fb 1748 }
f7f98c68 1749 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1750 StopTransactionRequest,
1751 StopTransactionResponse
08f130a0 1752 >(this, RequestCommand.STOP_TRANSACTION, {
ef6fa3fb
JB
1753 transactionId,
1754 meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId),
1755 idTag: this.getTransactionIdTag(transactionId),
1756 reason,
1757 });
79411696
JB
1758 }
1759 }
1760 }
1761 }
1762
c0560973 1763 private startWebSocketPing(): void {
17ac262c
JB
1764 const webSocketPingInterval: number = ChargingStationConfigurationUtils.getConfigurationKey(
1765 this,
e7aeea18
JB
1766 StandardParametersKey.WebSocketPingInterval
1767 )
1768 ? Utils.convertToInt(
17ac262c
JB
1769 ChargingStationConfigurationUtils.getConfigurationKey(
1770 this,
1771 StandardParametersKey.WebSocketPingInterval
1772 ).value
e7aeea18 1773 )
9cd3dfb0 1774 : 0;
ad2f27c3
JB
1775 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
1776 this.webSocketPingSetInterval = setInterval(() => {
d5bff457 1777 if (this.isWebSocketConnectionOpened()) {
e7aeea18
JB
1778 this.wsConnection.ping((): void => {
1779 /* This is intentional */
1780 });
136c90ba
JB
1781 }
1782 }, webSocketPingInterval * 1000);
e7aeea18
JB
1783 logger.info(
1784 this.logPrefix() +
1785 ' WebSocket ping started every ' +
1786 Utils.formatDurationSeconds(webSocketPingInterval)
1787 );
ad2f27c3 1788 } else if (this.webSocketPingSetInterval) {
e7aeea18
JB
1789 logger.info(
1790 this.logPrefix() +
1791 ' WebSocket ping every ' +
1792 Utils.formatDurationSeconds(webSocketPingInterval) +
1793 ' already started'
1794 );
136c90ba 1795 } else {
e7aeea18
JB
1796 logger.error(
1797 `${this.logPrefix()} WebSocket ping interval set to ${
1798 webSocketPingInterval
1799 ? Utils.formatDurationSeconds(webSocketPingInterval)
1800 : webSocketPingInterval
1801 }, not starting the WebSocket ping`
1802 );
136c90ba
JB
1803 }
1804 }
1805
c0560973 1806 private stopWebSocketPing(): void {
ad2f27c3
JB
1807 if (this.webSocketPingSetInterval) {
1808 clearInterval(this.webSocketPingSetInterval);
136c90ba
JB
1809 }
1810 }
1811
1f5df42a 1812 private getConfiguredSupervisionUrl(): URL {
e7aeea18
JB
1813 const supervisionUrls = Utils.cloneObject<string | string[]>(
1814 this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls()
1815 );
c0560973 1816 if (!Utils.isEmptyArray(supervisionUrls)) {
2dcfe98e
JB
1817 let urlIndex = 0;
1818 switch (Configuration.getSupervisionUrlDistribution()) {
1819 case SupervisionUrlDistribution.ROUND_ROBIN:
1820 urlIndex = (this.index - 1) % supervisionUrls.length;
1821 break;
1822 case SupervisionUrlDistribution.RANDOM:
1823 // Get a random url
1824 urlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length);
1825 break;
1826 case SupervisionUrlDistribution.SEQUENTIAL:
1827 if (this.index <= supervisionUrls.length) {
1828 urlIndex = this.index - 1;
1829 } else {
e7aeea18
JB
1830 logger.warn(
1831 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1832 );
2dcfe98e
JB
1833 }
1834 break;
1835 default:
e7aeea18
JB
1836 logger.error(
1837 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1838 SupervisionUrlDistribution.ROUND_ROBIN
1839 }`
1840 );
2dcfe98e
JB
1841 urlIndex = (this.index - 1) % supervisionUrls.length;
1842 break;
c0560973 1843 }
2dcfe98e 1844 return new URL(supervisionUrls[urlIndex]);
c0560973 1845 }
57939a9d 1846 return new URL(supervisionUrls as string);
136c90ba
JB
1847 }
1848
6e0964c8 1849 private getHeartbeatInterval(): number | undefined {
17ac262c
JB
1850 const HeartbeatInterval = ChargingStationConfigurationUtils.getConfigurationKey(
1851 this,
1852 StandardParametersKey.HeartbeatInterval
1853 );
c0560973
JB
1854 if (HeartbeatInterval) {
1855 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
1856 }
17ac262c
JB
1857 const HeartBeatInterval = ChargingStationConfigurationUtils.getConfigurationKey(
1858 this,
1859 StandardParametersKey.HeartBeatInterval
1860 );
c0560973
JB
1861 if (HeartBeatInterval) {
1862 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
0a60c33c 1863 }
7c72977b 1864 !this.stationInfo?.autoRegister &&
e7aeea18
JB
1865 logger.warn(
1866 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1867 Constants.DEFAULT_HEARTBEAT_INTERVAL
1868 }`
1869 );
47e22477 1870 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
0a60c33c
JB
1871 }
1872
c0560973 1873 private stopHeartbeat(): void {
ad2f27c3
JB
1874 if (this.heartbeatSetInterval) {
1875 clearInterval(this.heartbeatSetInterval);
7dde0b73 1876 }
5ad8570f
JB
1877 }
1878
e7aeea18 1879 private openWSConnection(
ccb1d6e9 1880 options: WsOptions = this.stationInfo?.wsOptions ?? {},
1e080116
JB
1881 params: { closeOpened?: boolean; terminateOpened?: boolean } = {
1882 closeOpened: false,
1883 terminateOpened: false,
1884 }
e7aeea18 1885 ): void {
37486900 1886 options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
1e080116 1887 params.closeOpened = params?.closeOpened ?? false;
d86d12d2 1888 params.terminateOpened = params?.terminateOpened ?? false;
e7aeea18
JB
1889 if (
1890 !Utils.isNullOrUndefined(this.stationInfo.supervisionUser) &&
1891 !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)
1892 ) {
15042c5f
JB
1893 options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
1894 }
55516218
JB
1895 if (params?.closeOpened) {
1896 this.closeWSConnection();
c0560973 1897 }
55516218
JB
1898 if (params?.terminateOpened) {
1899 this.terminateWSConnection();
1e080116 1900 }
88184022 1901 let protocol: string;
1f5df42a 1902 switch (this.getOcppVersion()) {
c0560973
JB
1903 case OCPPVersion.VERSION_16:
1904 protocol = 'ocpp' + OCPPVersion.VERSION_16;
1905 break;
1906 default:
1f5df42a 1907 this.handleUnsupportedVersion(this.getOcppVersion());
c0560973
JB
1908 break;
1909 }
1910 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
e7aeea18
JB
1911 logger.info(
1912 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString()
1913 );
136c90ba
JB
1914 }
1915
55516218
JB
1916 private closeWSConnection(): void {
1917 if (this.isWebSocketConnectionOpened()) {
1918 this.wsConnection.close();
1919 this.wsConnection = null;
1920 }
1921 }
1922
1923 private terminateWSConnection(): void {
1924 if (this.isWebSocketConnectionOpened()) {
1925 this.wsConnection.terminate();
1926 this.wsConnection = null;
1927 }
1928 }
1929
dd119a6b 1930 private stopMeterValues(connectorId: number) {
734d790d
JB
1931 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
1932 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
dd119a6b
JB
1933 }
1934 }
1935
6e0964c8 1936 private getReconnectExponentialDelay(): boolean | undefined {
e7aeea18
JB
1937 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay)
1938 ? this.stationInfo.reconnectExponentialDelay
1939 : false;
5ad8570f
JB
1940 }
1941
d09085e9 1942 private async reconnect(code: number): Promise<void> {
7874b0b1
JB
1943 // Stop WebSocket ping
1944 this.stopWebSocketPing();
136c90ba 1945 // Stop heartbeat
c0560973 1946 this.stopHeartbeat();
5ad8570f 1947 // Stop the ATG if needed
fa7bccf4
JB
1948 if (this.automaticTransactionGenerator?.configuration?.stopOnConnectionFailure) {
1949 this.stopAutomaticTransactionGenerator();
ad2f27c3 1950 }
e7aeea18
JB
1951 if (
1952 this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() ||
1953 this.getAutoReconnectMaxRetries() === -1
1954 ) {
ad2f27c3 1955 this.autoReconnectRetryCount++;
e7aeea18
JB
1956 const reconnectDelay = this.getReconnectExponentialDelay()
1957 ? Utils.exponentialDelay(this.autoReconnectRetryCount)
1958 : this.getConnectionTimeout() * 1000;
1e080116
JB
1959 const reconnectDelayWithdraw = 1000;
1960 const reconnectTimeout =
1961 reconnectDelay && reconnectDelay - reconnectDelayWithdraw > 0
1962 ? reconnectDelay - reconnectDelayWithdraw
1963 : 0;
e7aeea18
JB
1964 logger.error(
1965 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1966 reconnectDelay,
1967 2
1968 )}ms, timeout ${reconnectTimeout}ms`
1969 );
032d6efc 1970 await Utils.sleep(reconnectDelay);
e7aeea18
JB
1971 logger.error(
1972 this.logPrefix() +
1973 ' WebSocket: reconnecting try #' +
1974 this.autoReconnectRetryCount.toString()
1975 );
1976 this.openWSConnection(
ccb1d6e9 1977 { ...(this.stationInfo?.wsOptions ?? {}), handshakeTimeout: reconnectTimeout },
1e080116 1978 { closeOpened: true }
e7aeea18 1979 );
265e4266 1980 this.wsConnectionRestarted = true;
c0560973 1981 } else if (this.getAutoReconnectMaxRetries() !== -1) {
e7aeea18 1982 logger.error(
71a77ac2 1983 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
e7aeea18
JB
1984 this.autoReconnectRetryCount
1985 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
1986 );
5ad8570f
JB
1987 }
1988 }
1989
fa7bccf4
JB
1990 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration | null {
1991 return this.getTemplateFromFile()?.AutomaticTransactionGenerator ?? null;
1992 }
1993
a2653482
JB
1994 private initializeConnectorStatus(connectorId: number): void {
1995 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
1996 this.getConnectorStatus(connectorId).idTagAuthorized = false;
1997 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
734d790d
JB
1998 this.getConnectorStatus(connectorId).transactionStarted = false;
1999 this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
2000 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
0a60c33c 2001 }
7dde0b73 2002}