Commit | Line | Data |
---|---|---|
edd13439 | 1 | // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved. |
b4d34251 | 2 | |
d972af76 JB |
3 | import { createHash } from 'node:crypto'; |
4 | import { | |
5 | type FSWatcher, | |
6 | closeSync, | |
7 | existsSync, | |
8 | mkdirSync, | |
9 | openSync, | |
10 | readFileSync, | |
11 | writeFileSync, | |
12 | } from 'node:fs'; | |
13 | import { dirname, join } from 'node:path'; | |
130783a7 | 14 | import { URL } from 'node:url'; |
01f4001e | 15 | import { parentPort } from 'node:worker_threads'; |
8114d10e | 16 | |
be4c6702 | 17 | import { millisecondsToSeconds, secondsToMilliseconds } from 'date-fns'; |
5d280aae | 18 | import merge from 'just-merge'; |
d972af76 | 19 | import { type RawData, WebSocket } from 'ws'; |
8114d10e | 20 | |
4c3c0d59 | 21 | import { AutomaticTransactionGenerator } from './AutomaticTransactionGenerator'; |
7671fa0b | 22 | import { ChargingStationWorkerBroadcastChannel } from './broadcast-channel/ChargingStationWorkerBroadcastChannel'; |
f2d5e3d9 JB |
23 | import { |
24 | addConfigurationKey, | |
25 | deleteConfigurationKey, | |
26 | getConfigurationKey, | |
27 | setConfigurationKeyValue, | |
357a5553 | 28 | } from './ConfigurationKeyUtils'; |
fba11dc6 JB |
29 | import { |
30 | buildConnectorsMap, | |
31 | checkConnectorsConfiguration, | |
32 | checkStationInfoConnectorStatus, | |
33 | checkTemplate, | |
34 | countReservableConnectors, | |
35 | createBootNotificationRequest, | |
36 | createSerialNumber, | |
37 | getAmperageLimitationUnitDivider, | |
38 | getBootConnectorStatus, | |
39 | getChargingStationConnectorChargingProfilesPowerLimit, | |
40 | getChargingStationId, | |
41 | getDefaultVoltageOut, | |
42 | getHashId, | |
43 | getIdTagsFile, | |
44 | getMaxNumberOfEvses, | |
45 | getPhaseRotationValue, | |
d8093be1 | 46 | hasFeatureProfile, |
fba11dc6 JB |
47 | initializeConnectorsMapStatus, |
48 | propagateSerialNumber, | |
49 | stationTemplateToStationInfo, | |
50 | warnTemplateKeysDeprecation, | |
08b58f00 JB |
51 | } from './Helpers'; |
52 | import { IdTagsCache } from './IdTagsCache'; | |
53 | import { | |
54 | OCPP16IncomingRequestService, | |
55 | OCPP16RequestService, | |
56 | OCPP16ResponseService, | |
57 | OCPP16ServiceUtils, | |
58 | OCPP20IncomingRequestService, | |
59 | OCPP20RequestService, | |
60 | OCPP20ResponseService, | |
61 | type OCPPIncomingRequestService, | |
62 | type OCPPRequestService, | |
63 | OCPPServiceUtils, | |
64 | } from './ocpp'; | |
65 | import { SharedLRUCache } from './SharedLRUCache'; | |
268a74bb | 66 | import { BaseError, OCPPError } from '../exception'; |
b84bca85 | 67 | import { PerformanceStatistics } from '../performance'; |
e7aeea18 | 68 | import { |
268a74bb | 69 | type AutomaticTransactionGeneratorConfiguration, |
e7aeea18 | 70 | AvailabilityType, |
e0b0ee21 | 71 | type BootNotificationRequest, |
268a74bb | 72 | type BootNotificationResponse, |
e0b0ee21 | 73 | type CachedRequest, |
268a74bb JB |
74 | type ChargingStationConfiguration, |
75 | type ChargingStationInfo, | |
76 | type ChargingStationOcppConfiguration, | |
77 | type ChargingStationTemplate, | |
c8aafe0d | 78 | type ConnectorStatus, |
268a74bb JB |
79 | ConnectorStatusEnum, |
80 | CurrentType, | |
e0b0ee21 | 81 | type ErrorCallback, |
268a74bb JB |
82 | type ErrorResponse, |
83 | ErrorType, | |
2585c6e9 | 84 | type EvseStatus, |
52952bf8 | 85 | type EvseStatusConfiguration, |
268a74bb | 86 | FileType, |
c9a4f9ea JB |
87 | FirmwareStatus, |
88 | type FirmwareStatusNotificationRequest, | |
268a74bb JB |
89 | type FirmwareStatusNotificationResponse, |
90 | type FirmwareUpgrade, | |
e0b0ee21 | 91 | type HeartbeatRequest, |
268a74bb | 92 | type HeartbeatResponse, |
e0b0ee21 | 93 | type IncomingRequest, |
268a74bb JB |
94 | type IncomingRequestCommand, |
95 | type JsonType, | |
96 | MessageType, | |
97 | type MeterValue, | |
98 | MeterValueMeasurand, | |
e0b0ee21 | 99 | type MeterValuesRequest, |
268a74bb JB |
100 | type MeterValuesResponse, |
101 | OCPPVersion, | |
8ca6874c | 102 | type OutgoingRequest, |
268a74bb JB |
103 | PowerUnits, |
104 | RegistrationStatusEnumType, | |
e7aeea18 | 105 | RequestCommand, |
66dd3447 | 106 | type Reservation, |
2ca0ea90 | 107 | type ReservationFilterKey, |
66dd3447 | 108 | ReservationTerminationReason, |
268a74bb | 109 | type Response, |
268a74bb | 110 | StandardParametersKey, |
5ced7e80 | 111 | type Status, |
e0b0ee21 | 112 | type StatusNotificationRequest, |
e0b0ee21 | 113 | type StatusNotificationResponse, |
ef6fa3fb | 114 | StopTransactionReason, |
e0b0ee21 JB |
115 | type StopTransactionRequest, |
116 | type StopTransactionResponse, | |
268a74bb JB |
117 | SupervisionUrlDistribution, |
118 | SupportedFeatureProfiles, | |
6dad8e21 | 119 | VendorParametersKey, |
268a74bb JB |
120 | type WSError, |
121 | WebSocketCloseEventStatusCode, | |
122 | type WsOptions, | |
123 | } from '../types'; | |
60a74391 JB |
124 | import { |
125 | ACElectricUtils, | |
1227a6f1 JB |
126 | AsyncLock, |
127 | AsyncLockType, | |
60a74391 JB |
128 | Configuration, |
129 | Constants, | |
130 | DCElectricUtils, | |
179ed367 JB |
131 | buildChargingStationAutomaticTransactionGeneratorConfiguration, |
132 | buildConnectorsStatus, | |
133 | buildEvsesStatus, | |
c8faabc8 JB |
134 | buildStartedMessage, |
135 | buildStoppedMessage, | |
136 | buildUpdatedMessage, | |
9bf0ef23 JB |
137 | cloneObject, |
138 | convertToBoolean, | |
139 | convertToInt, | |
140 | exponentialDelay, | |
141 | formatDurationMilliSeconds, | |
142 | formatDurationSeconds, | |
143 | getRandomInteger, | |
144 | getWebSocketCloseEventStatusString, | |
fa5995d6 | 145 | handleFileException, |
9bf0ef23 JB |
146 | isNotEmptyArray, |
147 | isNotEmptyString, | |
148 | isNullOrUndefined, | |
149 | isUndefined, | |
150 | logPrefix, | |
60a74391 | 151 | logger, |
9bf0ef23 JB |
152 | roundTo, |
153 | secureRandom, | |
154 | sleep, | |
fa5995d6 | 155 | watchJsonFile, |
60a74391 | 156 | } from '../utils'; |
3f40bc9c | 157 | |
268a74bb | 158 | export class ChargingStation { |
c72f6634 | 159 | public readonly index: number; |
2484ac1e | 160 | public readonly templateFile: string; |
6e0964c8 | 161 | public stationInfo!: ChargingStationInfo; |
452a82ca | 162 | public started: boolean; |
cbf9b878 | 163 | public starting: boolean; |
f911a4af | 164 | public idTagsCache: IdTagsCache; |
551e477c JB |
165 | public automaticTransactionGenerator!: AutomaticTransactionGenerator | undefined; |
166 | public ocppConfiguration!: ChargingStationOcppConfiguration | undefined; | |
72092cfc | 167 | public wsConnection!: WebSocket | null; |
8df5ae48 | 168 | public readonly connectors: Map<number, ConnectorStatus>; |
2585c6e9 | 169 | public readonly evses: Map<number, EvseStatus>; |
9e23580d | 170 | public readonly requests: Map<string, CachedRequest>; |
551e477c | 171 | public performanceStatistics!: PerformanceStatistics | undefined; |
e1d9a0f4 | 172 | public heartbeatSetInterval?: NodeJS.Timeout; |
6e0964c8 | 173 | public ocppRequestService!: OCPPRequestService; |
0a03f36c | 174 | public bootNotificationRequest!: BootNotificationRequest; |
1895299d | 175 | public bootNotificationResponse!: BootNotificationResponse | undefined; |
fa7bccf4 | 176 | public powerDivider!: number; |
950b1349 | 177 | private stopping: boolean; |
073bd098 | 178 | private configurationFile!: string; |
7c72977b | 179 | private configurationFileHash!: string; |
6e0964c8 | 180 | private connectorsConfigurationHash!: string; |
2585c6e9 | 181 | private evsesConfigurationHash!: string; |
c7db8ecb | 182 | private automaticTransactionGeneratorConfiguration?: AutomaticTransactionGeneratorConfiguration; |
a472cf2b | 183 | private ocppIncomingRequestService!: OCPPIncomingRequestService; |
8e242273 | 184 | private readonly messageBuffer: Set<string>; |
fa7bccf4 | 185 | private configuredSupervisionUrl!: URL; |
265e4266 | 186 | private wsConnectionRestarted: boolean; |
ad2f27c3 | 187 | private autoReconnectRetryCount: number; |
d972af76 | 188 | private templateFileWatcher!: FSWatcher | undefined; |
cda5d0fb | 189 | private templateFileHash!: string; |
57adbebc | 190 | private readonly sharedLRUCache: SharedLRUCache; |
e1d9a0f4 | 191 | private webSocketPingSetInterval?: NodeJS.Timeout; |
89b7a234 | 192 | private readonly chargingStationWorkerBroadcastChannel: ChargingStationWorkerBroadcastChannel; |
178956d8 | 193 | private reservationExpirationSetInterval?: NodeJS.Timeout; |
6af9012e | 194 | |
2484ac1e | 195 | constructor(index: number, templateFile: string) { |
aa428a31 | 196 | this.started = false; |
950b1349 JB |
197 | this.starting = false; |
198 | this.stopping = false; | |
aa428a31 JB |
199 | this.wsConnectionRestarted = false; |
200 | this.autoReconnectRetryCount = 0; | |
ad2f27c3 | 201 | this.index = index; |
2484ac1e | 202 | this.templateFile = templateFile; |
9f2e3130 | 203 | this.connectors = new Map<number, ConnectorStatus>(); |
2585c6e9 | 204 | this.evses = new Map<number, EvseStatus>(); |
32b02249 | 205 | this.requests = new Map<string, CachedRequest>(); |
8e242273 | 206 | this.messageBuffer = new Set<string>(); |
b44b779a | 207 | this.sharedLRUCache = SharedLRUCache.getInstance(); |
f911a4af | 208 | this.idTagsCache = IdTagsCache.getInstance(); |
89b7a234 | 209 | this.chargingStationWorkerBroadcastChannel = new ChargingStationWorkerBroadcastChannel(this); |
32de5a57 | 210 | |
9f2e3130 | 211 | this.initialize(); |
c0560973 JB |
212 | } |
213 | ||
a14022a2 JB |
214 | public get hasEvses(): boolean { |
215 | return this.connectors.size === 0 && this.evses.size > 0; | |
216 | } | |
217 | ||
25f5a959 | 218 | private get wsConnectionUrl(): URL { |
fa7bccf4 | 219 | return new URL( |
44eb6026 | 220 | `${ |
269de583 | 221 | this.getSupervisionUrlOcppConfiguration() && |
9bf0ef23 | 222 | isNotEmptyString(this.getSupervisionUrlOcppKey()) && |
f2d5e3d9 JB |
223 | isNotEmptyString(getConfigurationKey(this, this.getSupervisionUrlOcppKey())?.value) |
224 | ? getConfigurationKey(this, this.getSupervisionUrlOcppKey())!.value | |
44eb6026 | 225 | : this.configuredSupervisionUrl.href |
5edd8ba0 | 226 | }/${this.stationInfo.chargingStationId}`, |
fa7bccf4 | 227 | ); |
12fc74d6 JB |
228 | } |
229 | ||
8b7072dc | 230 | public logPrefix = (): string => { |
9bf0ef23 | 231 | return logPrefix( |
ccb1d6e9 | 232 | ` ${ |
9bf0ef23 | 233 | (isNotEmptyString(this?.stationInfo?.chargingStationId) |
e302df1d | 234 | ? this?.stationInfo?.chargingStationId |
e1d9a0f4 | 235 | : getChargingStationId(this.index, this.getTemplateFromFile()!)) ?? |
e302df1d | 236 | 'Error at building log prefix' |
5edd8ba0 | 237 | } |`, |
ccb1d6e9 | 238 | ); |
8b7072dc | 239 | }; |
c0560973 | 240 | |
f911a4af | 241 | public hasIdTags(): boolean { |
e1d9a0f4 | 242 | return isNotEmptyArray(this.idTagsCache.getIdTags(getIdTagsFile(this.stationInfo)!)); |
c0560973 JB |
243 | } |
244 | ||
ad774cec JB |
245 | public getEnableStatistics(): boolean { |
246 | return this.stationInfo.enableStatistics ?? false; | |
c0560973 JB |
247 | } |
248 | ||
ad774cec | 249 | public getMustAuthorizeAtRemoteStart(): boolean { |
03ebf4c1 | 250 | return this.stationInfo.mustAuthorizeAtRemoteStart ?? true; |
a7fc8211 JB |
251 | } |
252 | ||
e1d9a0f4 | 253 | public getNumberOfPhases(stationInfo?: ChargingStationInfo): number { |
fa7bccf4 JB |
254 | const localStationInfo: ChargingStationInfo = stationInfo ?? this.stationInfo; |
255 | switch (this.getCurrentOutType(stationInfo)) { | |
4c2b4904 | 256 | case CurrentType.AC: |
e1d9a0f4 | 257 | return !isUndefined(localStationInfo.numberOfPhases) ? localStationInfo.numberOfPhases! : 3; |
4c2b4904 | 258 | case CurrentType.DC: |
c0560973 JB |
259 | return 0; |
260 | } | |
261 | } | |
262 | ||
d5bff457 | 263 | public isWebSocketConnectionOpened(): boolean { |
0d8140bd | 264 | return this?.wsConnection?.readyState === WebSocket.OPEN; |
c0560973 JB |
265 | } |
266 | ||
1895299d | 267 | public getRegistrationStatus(): RegistrationStatusEnumType | undefined { |
672fed6e JB |
268 | return this?.bootNotificationResponse?.status; |
269 | } | |
270 | ||
f7c2994d | 271 | public inUnknownState(): boolean { |
9bf0ef23 | 272 | return isNullOrUndefined(this?.bootNotificationResponse?.status); |
73c4266d JB |
273 | } |
274 | ||
f7c2994d | 275 | public inPendingState(): boolean { |
d270cc87 | 276 | return this?.bootNotificationResponse?.status === RegistrationStatusEnumType.PENDING; |
16cd35ad JB |
277 | } |
278 | ||
f7c2994d | 279 | public inAcceptedState(): boolean { |
d270cc87 | 280 | return this?.bootNotificationResponse?.status === RegistrationStatusEnumType.ACCEPTED; |
c0560973 JB |
281 | } |
282 | ||
f7c2994d | 283 | public inRejectedState(): boolean { |
d270cc87 | 284 | return this?.bootNotificationResponse?.status === RegistrationStatusEnumType.REJECTED; |
16cd35ad JB |
285 | } |
286 | ||
287 | public isRegistered(): boolean { | |
ed6cfcff | 288 | return ( |
f7c2994d JB |
289 | this.inUnknownState() === false && |
290 | (this.inAcceptedState() === true || this.inPendingState() === true) | |
ed6cfcff | 291 | ); |
16cd35ad JB |
292 | } |
293 | ||
c0560973 | 294 | public isChargingStationAvailable(): boolean { |
0d6f335f | 295 | return this.getConnectorStatus(0)?.availability === AvailabilityType.Operative; |
c0560973 JB |
296 | } |
297 | ||
a14022a2 JB |
298 | public hasConnector(connectorId: number): boolean { |
299 | if (this.hasEvses) { | |
300 | for (const evseStatus of this.evses.values()) { | |
301 | if (evseStatus.connectors.has(connectorId)) { | |
302 | return true; | |
303 | } | |
304 | } | |
305 | return false; | |
306 | } | |
307 | return this.connectors.has(connectorId); | |
308 | } | |
309 | ||
28e78158 JB |
310 | public isConnectorAvailable(connectorId: number): boolean { |
311 | return ( | |
312 | connectorId > 0 && | |
313 | this.getConnectorStatus(connectorId)?.availability === AvailabilityType.Operative | |
314 | ); | |
c0560973 JB |
315 | } |
316 | ||
54544ef1 | 317 | public getNumberOfConnectors(): number { |
28e78158 JB |
318 | if (this.hasEvses) { |
319 | let numberOfConnectors = 0; | |
320 | for (const [evseId, evseStatus] of this.evses) { | |
4334db72 JB |
321 | if (evseId > 0) { |
322 | numberOfConnectors += evseStatus.connectors.size; | |
28e78158 | 323 | } |
28e78158 JB |
324 | } |
325 | return numberOfConnectors; | |
326 | } | |
007b5bde | 327 | return this.connectors.has(0) ? this.connectors.size - 1 : this.connectors.size; |
54544ef1 JB |
328 | } |
329 | ||
28e78158 | 330 | public getNumberOfEvses(): number { |
007b5bde | 331 | return this.evses.has(0) ? this.evses.size - 1 : this.evses.size; |
28e78158 JB |
332 | } |
333 | ||
334 | public getConnectorStatus(connectorId: number): ConnectorStatus | undefined { | |
335 | if (this.hasEvses) { | |
336 | for (const evseStatus of this.evses.values()) { | |
337 | if (evseStatus.connectors.has(connectorId)) { | |
338 | return evseStatus.connectors.get(connectorId); | |
339 | } | |
340 | } | |
5e128725 | 341 | return undefined; |
28e78158 JB |
342 | } |
343 | return this.connectors.get(connectorId); | |
c0560973 JB |
344 | } |
345 | ||
fa7bccf4 | 346 | public getCurrentOutType(stationInfo?: ChargingStationInfo): CurrentType { |
72092cfc | 347 | return (stationInfo ?? this.stationInfo)?.currentOutType ?? CurrentType.AC; |
c0560973 JB |
348 | } |
349 | ||
672fed6e | 350 | public getOcppStrictCompliance(): boolean { |
0282b7c0 | 351 | return this.stationInfo?.ocppStrictCompliance ?? true; |
672fed6e JB |
352 | } |
353 | ||
e1d9a0f4 | 354 | public getVoltageOut(stationInfo?: ChargingStationInfo): number { |
fba11dc6 | 355 | const defaultVoltageOut = getDefaultVoltageOut( |
fa7bccf4 | 356 | this.getCurrentOutType(stationInfo), |
8a133cc8 | 357 | this.logPrefix(), |
5edd8ba0 | 358 | this.templateFile, |
492cf6ab | 359 | ); |
ac7f79af | 360 | return (stationInfo ?? this.stationInfo).voltageOut ?? defaultVoltageOut; |
c0560973 JB |
361 | } |
362 | ||
15068be9 JB |
363 | public getMaximumPower(stationInfo?: ChargingStationInfo): number { |
364 | const localStationInfo = stationInfo ?? this.stationInfo; | |
e1d9a0f4 | 365 | // eslint-disable-next-line @typescript-eslint/dot-notation |
a37fc6dc JB |
366 | return ( |
367 | (localStationInfo['maxPower' as keyof ChargingStationInfo] as number) ?? | |
368 | localStationInfo.maximumPower | |
369 | ); | |
15068be9 JB |
370 | } |
371 | ||
ad8537a7 | 372 | public getConnectorMaximumAvailablePower(connectorId: number): number { |
e1d9a0f4 | 373 | let connectorAmperageLimitationPowerLimit: number | undefined; |
b47d68d7 | 374 | if ( |
9bf0ef23 | 375 | !isNullOrUndefined(this.getAmperageLimitation()) && |
e1d9a0f4 | 376 | this.getAmperageLimitation()! < this.stationInfo.maximumAmperage! |
b47d68d7 | 377 | ) { |
4160ae28 JB |
378 | connectorAmperageLimitationPowerLimit = |
379 | (this.getCurrentOutType() === CurrentType.AC | |
cc6e8ab5 JB |
380 | ? ACElectricUtils.powerTotal( |
381 | this.getNumberOfPhases(), | |
382 | this.getVoltageOut(), | |
e1d9a0f4 | 383 | this.getAmperageLimitation()! * |
5edd8ba0 | 384 | (this.hasEvses ? this.getNumberOfEvses() : this.getNumberOfConnectors()), |
cc6e8ab5 | 385 | ) |
e1d9a0f4 | 386 | : DCElectricUtils.power(this.getVoltageOut(), this.getAmperageLimitation()!)) / |
fa7bccf4 | 387 | this.powerDivider; |
cc6e8ab5 | 388 | } |
fa7bccf4 | 389 | const connectorMaximumPower = this.getMaximumPower() / this.powerDivider; |
15068be9 | 390 | const connectorChargingProfilesPowerLimit = |
fba11dc6 | 391 | getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId); |
ad8537a7 JB |
392 | return Math.min( |
393 | isNaN(connectorMaximumPower) ? Infinity : connectorMaximumPower, | |
e1d9a0f4 | 394 | isNaN(connectorAmperageLimitationPowerLimit!) |
ad8537a7 | 395 | ? Infinity |
e1d9a0f4 JB |
396 | : connectorAmperageLimitationPowerLimit!, |
397 | isNaN(connectorChargingProfilesPowerLimit!) ? Infinity : connectorChargingProfilesPowerLimit!, | |
ad8537a7 | 398 | ); |
cc6e8ab5 JB |
399 | } |
400 | ||
6e0964c8 | 401 | public getTransactionIdTag(transactionId: number): string | undefined { |
28e78158 JB |
402 | if (this.hasEvses) { |
403 | for (const evseStatus of this.evses.values()) { | |
404 | for (const connectorStatus of evseStatus.connectors.values()) { | |
405 | if (connectorStatus.transactionId === transactionId) { | |
406 | return connectorStatus.transactionIdTag; | |
407 | } | |
408 | } | |
409 | } | |
410 | } else { | |
411 | for (const connectorId of this.connectors.keys()) { | |
3fa7f799 | 412 | if (this.getConnectorStatus(connectorId)?.transactionId === transactionId) { |
28e78158 JB |
413 | return this.getConnectorStatus(connectorId)?.transactionIdTag; |
414 | } | |
c0560973 JB |
415 | } |
416 | } | |
417 | } | |
418 | ||
ded57f02 JB |
419 | public getNumberOfRunningTransactions(): number { |
420 | let trxCount = 0; | |
421 | if (this.hasEvses) { | |
3fa7f799 JB |
422 | for (const [evseId, evseStatus] of this.evses) { |
423 | if (evseId === 0) { | |
424 | continue; | |
425 | } | |
ded57f02 JB |
426 | for (const connectorStatus of evseStatus.connectors.values()) { |
427 | if (connectorStatus.transactionStarted === true) { | |
428 | ++trxCount; | |
429 | } | |
430 | } | |
431 | } | |
432 | } else { | |
433 | for (const connectorId of this.connectors.keys()) { | |
434 | if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted === true) { | |
435 | ++trxCount; | |
436 | } | |
437 | } | |
438 | } | |
439 | return trxCount; | |
440 | } | |
441 | ||
6ed92bc1 | 442 | public getOutOfOrderEndMeterValues(): boolean { |
ccb1d6e9 | 443 | return this.stationInfo?.outOfOrderEndMeterValues ?? false; |
6ed92bc1 JB |
444 | } |
445 | ||
446 | public getBeginEndMeterValues(): boolean { | |
ccb1d6e9 | 447 | return this.stationInfo?.beginEndMeterValues ?? false; |
6ed92bc1 JB |
448 | } |
449 | ||
450 | public getMeteringPerTransaction(): boolean { | |
ccb1d6e9 | 451 | return this.stationInfo?.meteringPerTransaction ?? true; |
6ed92bc1 JB |
452 | } |
453 | ||
fd0c36fa | 454 | public getTransactionDataMeterValues(): boolean { |
ccb1d6e9 | 455 | return this.stationInfo?.transactionDataMeterValues ?? false; |
fd0c36fa JB |
456 | } |
457 | ||
9ccca265 | 458 | public getMainVoltageMeterValues(): boolean { |
ccb1d6e9 | 459 | return this.stationInfo?.mainVoltageMeterValues ?? true; |
9ccca265 JB |
460 | } |
461 | ||
6b10669b | 462 | public getPhaseLineToLineVoltageMeterValues(): boolean { |
ccb1d6e9 | 463 | return this.stationInfo?.phaseLineToLineVoltageMeterValues ?? false; |
9bd87386 JB |
464 | } |
465 | ||
7bc31f9c | 466 | public getCustomValueLimitationMeterValues(): boolean { |
ccb1d6e9 | 467 | return this.stationInfo?.customValueLimitationMeterValues ?? true; |
7bc31f9c JB |
468 | } |
469 | ||
f479a792 | 470 | public getConnectorIdByTransactionId(transactionId: number): number | undefined { |
28e78158 JB |
471 | if (this.hasEvses) { |
472 | for (const evseStatus of this.evses.values()) { | |
473 | for (const [connectorId, connectorStatus] of evseStatus.connectors) { | |
474 | if (connectorStatus.transactionId === transactionId) { | |
475 | return connectorId; | |
476 | } | |
477 | } | |
478 | } | |
479 | } else { | |
480 | for (const connectorId of this.connectors.keys()) { | |
3fa7f799 | 481 | if (this.getConnectorStatus(connectorId)?.transactionId === transactionId) { |
28e78158 JB |
482 | return connectorId; |
483 | } | |
c0560973 JB |
484 | } |
485 | } | |
486 | } | |
487 | ||
07989fad JB |
488 | public getEnergyActiveImportRegisterByTransactionId( |
489 | transactionId: number, | |
5edd8ba0 | 490 | rounded = false, |
07989fad JB |
491 | ): number { |
492 | return this.getEnergyActiveImportRegister( | |
e1d9a0f4 | 493 | this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId)!)!, |
5edd8ba0 | 494 | rounded, |
cbad1217 | 495 | ); |
cbad1217 JB |
496 | } |
497 | ||
18bf8274 | 498 | public getEnergyActiveImportRegisterByConnectorId(connectorId: number, rounded = false): number { |
e1d9a0f4 | 499 | return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId)!, rounded); |
6ed92bc1 JB |
500 | } |
501 | ||
c0560973 | 502 | public getAuthorizeRemoteTxRequests(): boolean { |
f2d5e3d9 | 503 | const authorizeRemoteTxRequests = getConfigurationKey( |
17ac262c | 504 | this, |
5edd8ba0 | 505 | StandardParametersKey.AuthorizeRemoteTxRequests, |
e7aeea18 | 506 | ); |
9bf0ef23 | 507 | return authorizeRemoteTxRequests ? convertToBoolean(authorizeRemoteTxRequests.value) : false; |
c0560973 JB |
508 | } |
509 | ||
510 | public getLocalAuthListEnabled(): boolean { | |
f2d5e3d9 | 511 | const localAuthListEnabled = getConfigurationKey( |
17ac262c | 512 | this, |
5edd8ba0 | 513 | StandardParametersKey.LocalAuthListEnabled, |
e7aeea18 | 514 | ); |
9bf0ef23 | 515 | return localAuthListEnabled ? convertToBoolean(localAuthListEnabled.value) : false; |
c0560973 JB |
516 | } |
517 | ||
8f953431 | 518 | public getHeartbeatInterval(): number { |
f2d5e3d9 | 519 | const HeartbeatInterval = getConfigurationKey(this, StandardParametersKey.HeartbeatInterval); |
8f953431 | 520 | if (HeartbeatInterval) { |
be4c6702 | 521 | return secondsToMilliseconds(convertToInt(HeartbeatInterval.value)); |
8f953431 | 522 | } |
f2d5e3d9 | 523 | const HeartBeatInterval = getConfigurationKey(this, StandardParametersKey.HeartBeatInterval); |
8f953431 | 524 | if (HeartBeatInterval) { |
be4c6702 | 525 | return secondsToMilliseconds(convertToInt(HeartBeatInterval.value)); |
8f953431 JB |
526 | } |
527 | this.stationInfo?.autoRegister === false && | |
528 | logger.warn( | |
529 | `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${ | |
530 | Constants.DEFAULT_HEARTBEAT_INTERVAL | |
5edd8ba0 | 531 | }`, |
8f953431 JB |
532 | ); |
533 | return Constants.DEFAULT_HEARTBEAT_INTERVAL; | |
534 | } | |
535 | ||
269de583 JB |
536 | public setSupervisionUrl(url: string): void { |
537 | if ( | |
538 | this.getSupervisionUrlOcppConfiguration() && | |
9bf0ef23 | 539 | isNotEmptyString(this.getSupervisionUrlOcppKey()) |
269de583 | 540 | ) { |
f2d5e3d9 | 541 | setConfigurationKeyValue(this, this.getSupervisionUrlOcppKey(), url); |
269de583 JB |
542 | } else { |
543 | this.stationInfo.supervisionUrls = url; | |
544 | this.saveStationInfo(); | |
545 | this.configuredSupervisionUrl = this.getConfiguredSupervisionUrl(); | |
546 | } | |
547 | } | |
548 | ||
c0560973 | 549 | public startHeartbeat(): void { |
5b43123f | 550 | if (this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval) { |
6a8329b4 JB |
551 | this.heartbeatSetInterval = setInterval(() => { |
552 | this.ocppRequestService | |
553 | .requestHandler<HeartbeatRequest, HeartbeatResponse>(this, RequestCommand.HEARTBEAT) | |
72092cfc | 554 | .catch((error) => { |
6a8329b4 JB |
555 | logger.error( |
556 | `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`, | |
5edd8ba0 | 557 | error, |
6a8329b4 JB |
558 | ); |
559 | }); | |
c0560973 | 560 | }, this.getHeartbeatInterval()); |
e7aeea18 | 561 | logger.info( |
9bf0ef23 | 562 | `${this.logPrefix()} Heartbeat started every ${formatDurationMilliSeconds( |
5edd8ba0 JB |
563 | this.getHeartbeatInterval(), |
564 | )}`, | |
e7aeea18 | 565 | ); |
c0560973 | 566 | } else if (this.heartbeatSetInterval) { |
e7aeea18 | 567 | logger.info( |
9bf0ef23 | 568 | `${this.logPrefix()} Heartbeat already started every ${formatDurationMilliSeconds( |
5edd8ba0 JB |
569 | this.getHeartbeatInterval(), |
570 | )}`, | |
e7aeea18 | 571 | ); |
c0560973 | 572 | } else { |
e7aeea18 | 573 | logger.error( |
66dd3447 | 574 | `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()}, |
5edd8ba0 | 575 | not starting the heartbeat`, |
e7aeea18 | 576 | ); |
c0560973 JB |
577 | } |
578 | } | |
579 | ||
580 | public restartHeartbeat(): void { | |
581 | // Stop heartbeat | |
582 | this.stopHeartbeat(); | |
583 | // Start heartbeat | |
584 | this.startHeartbeat(); | |
585 | } | |
586 | ||
17ac262c JB |
587 | public restartWebSocketPing(): void { |
588 | // Stop WebSocket ping | |
589 | this.stopWebSocketPing(); | |
590 | // Start WebSocket ping | |
591 | this.startWebSocketPing(); | |
592 | } | |
593 | ||
c0560973 JB |
594 | public startMeterValues(connectorId: number, interval: number): void { |
595 | if (connectorId === 0) { | |
e7aeea18 | 596 | logger.error( |
04c32a95 | 597 | `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}`, |
e7aeea18 | 598 | ); |
c0560973 JB |
599 | return; |
600 | } | |
734d790d | 601 | if (!this.getConnectorStatus(connectorId)) { |
e7aeea18 | 602 | logger.error( |
66dd3447 | 603 | `${this.logPrefix()} Trying to start MeterValues on non existing connector id |
04c32a95 | 604 | ${connectorId}`, |
e7aeea18 | 605 | ); |
c0560973 JB |
606 | return; |
607 | } | |
5e3cb728 | 608 | if (this.getConnectorStatus(connectorId)?.transactionStarted === false) { |
e7aeea18 | 609 | logger.error( |
66dd3447 | 610 | `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} |
5edd8ba0 | 611 | with no transaction started`, |
e7aeea18 | 612 | ); |
c0560973 | 613 | return; |
e7aeea18 | 614 | } else if ( |
5e3cb728 | 615 | this.getConnectorStatus(connectorId)?.transactionStarted === true && |
9bf0ef23 | 616 | isNullOrUndefined(this.getConnectorStatus(connectorId)?.transactionId) |
e7aeea18 JB |
617 | ) { |
618 | logger.error( | |
66dd3447 | 619 | `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} |
5edd8ba0 | 620 | with no transaction id`, |
e7aeea18 | 621 | ); |
c0560973 JB |
622 | return; |
623 | } | |
624 | if (interval > 0) { | |
e1d9a0f4 | 625 | this.getConnectorStatus(connectorId)!.transactionSetInterval = setInterval(() => { |
6a8329b4 JB |
626 | // FIXME: Implement OCPP version agnostic helpers |
627 | const meterValue: MeterValue = OCPP16ServiceUtils.buildMeterValue( | |
628 | this, | |
629 | connectorId, | |
e1d9a0f4 | 630 | this.getConnectorStatus(connectorId)!.transactionId!, |
5edd8ba0 | 631 | interval, |
6a8329b4 JB |
632 | ); |
633 | this.ocppRequestService | |
634 | .requestHandler<MeterValuesRequest, MeterValuesResponse>( | |
08f130a0 | 635 | this, |
f22266fd JB |
636 | RequestCommand.METER_VALUES, |
637 | { | |
638 | connectorId, | |
72092cfc | 639 | transactionId: this.getConnectorStatus(connectorId)?.transactionId, |
f22266fd | 640 | meterValue: [meterValue], |
5edd8ba0 | 641 | }, |
6a8329b4 | 642 | ) |
72092cfc | 643 | .catch((error) => { |
6a8329b4 JB |
644 | logger.error( |
645 | `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`, | |
5edd8ba0 | 646 | error, |
6a8329b4 JB |
647 | ); |
648 | }); | |
649 | }, interval); | |
c0560973 | 650 | } else { |
e7aeea18 JB |
651 | logger.error( |
652 | `${this.logPrefix()} Charging station ${ | |
653 | StandardParametersKey.MeterValueSampleInterval | |
5edd8ba0 | 654 | } configuration set to ${interval}, not sending MeterValues`, |
e7aeea18 | 655 | ); |
c0560973 JB |
656 | } |
657 | } | |
658 | ||
04b1261c JB |
659 | public stopMeterValues(connectorId: number) { |
660 | if (this.getConnectorStatus(connectorId)?.transactionSetInterval) { | |
661 | clearInterval(this.getConnectorStatus(connectorId)?.transactionSetInterval); | |
662 | } | |
663 | } | |
664 | ||
c0560973 | 665 | public start(): void { |
0d8852a5 JB |
666 | if (this.started === false) { |
667 | if (this.starting === false) { | |
668 | this.starting = true; | |
ad774cec | 669 | if (this.getEnableStatistics() === true) { |
551e477c | 670 | this.performanceStatistics?.start(); |
0d8852a5 | 671 | } |
d8093be1 | 672 | if (hasFeatureProfile(this, SupportedFeatureProfiles.Reservation)) { |
178956d8 | 673 | this.startReservationExpirationSetInterval(); |
d193a949 | 674 | } |
0d8852a5 JB |
675 | this.openWSConnection(); |
676 | // Monitor charging station template file | |
fa5995d6 | 677 | this.templateFileWatcher = watchJsonFile( |
0d8852a5 | 678 | this.templateFile, |
7164966d JB |
679 | FileType.ChargingStationTemplate, |
680 | this.logPrefix(), | |
681 | undefined, | |
0d8852a5 | 682 | (event, filename): void => { |
9bf0ef23 | 683 | if (isNotEmptyString(filename) && event === 'change') { |
0d8852a5 JB |
684 | try { |
685 | logger.debug( | |
686 | `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${ | |
687 | this.templateFile | |
5edd8ba0 | 688 | } file have changed, reload`, |
0d8852a5 | 689 | ); |
cda5d0fb | 690 | this.sharedLRUCache.deleteChargingStationTemplate(this.templateFileHash); |
0d8852a5 JB |
691 | // Initialize |
692 | this.initialize(); | |
e1d9a0f4 | 693 | this.idTagsCache.deleteIdTags(getIdTagsFile(this.stationInfo)!); |
0d8852a5 JB |
694 | // Restart the ATG |
695 | this.stopAutomaticTransactionGenerator(); | |
e3d35515 | 696 | delete this.automaticTransactionGeneratorConfiguration; |
ac7f79af | 697 | if (this.getAutomaticTransactionGeneratorConfiguration()?.enable === true) { |
0d8852a5 JB |
698 | this.startAutomaticTransactionGenerator(); |
699 | } | |
ad774cec | 700 | if (this.getEnableStatistics() === true) { |
551e477c | 701 | this.performanceStatistics?.restart(); |
0d8852a5 | 702 | } else { |
551e477c | 703 | this.performanceStatistics?.stop(); |
0d8852a5 JB |
704 | } |
705 | // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed | |
706 | } catch (error) { | |
707 | logger.error( | |
708 | `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`, | |
5edd8ba0 | 709 | error, |
0d8852a5 | 710 | ); |
950b1349 | 711 | } |
a95873d8 | 712 | } |
5edd8ba0 | 713 | }, |
0d8852a5 | 714 | ); |
56eb297e | 715 | this.started = true; |
c8faabc8 | 716 | parentPort?.postMessage(buildStartedMessage(this)); |
0d8852a5 JB |
717 | this.starting = false; |
718 | } else { | |
719 | logger.warn(`${this.logPrefix()} Charging station is already starting...`); | |
720 | } | |
950b1349 | 721 | } else { |
0d8852a5 | 722 | logger.warn(`${this.logPrefix()} Charging station is already started...`); |
950b1349 | 723 | } |
c0560973 JB |
724 | } |
725 | ||
60ddad53 | 726 | public async stop(reason?: StopTransactionReason): Promise<void> { |
0d8852a5 JB |
727 | if (this.started === true) { |
728 | if (this.stopping === false) { | |
729 | this.stopping = true; | |
730 | await this.stopMessageSequence(reason); | |
0d8852a5 | 731 | this.closeWSConnection(); |
ad774cec | 732 | if (this.getEnableStatistics() === true) { |
551e477c | 733 | this.performanceStatistics?.stop(); |
0d8852a5 | 734 | } |
d8093be1 | 735 | if (hasFeatureProfile(this, SupportedFeatureProfiles.Reservation)) { |
5543b88d JB |
736 | this.stopReservationExpirationSetInterval(); |
737 | } | |
0d8852a5 | 738 | this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash); |
72092cfc | 739 | this.templateFileWatcher?.close(); |
cda5d0fb | 740 | this.sharedLRUCache.deleteChargingStationTemplate(this.templateFileHash); |
cdde2cfe | 741 | delete this.bootNotificationResponse; |
0d8852a5 | 742 | this.started = false; |
ac7f79af | 743 | this.saveConfiguration(); |
c8faabc8 | 744 | parentPort?.postMessage(buildStoppedMessage(this)); |
0d8852a5 JB |
745 | this.stopping = false; |
746 | } else { | |
747 | logger.warn(`${this.logPrefix()} Charging station is already stopping...`); | |
c0560973 | 748 | } |
950b1349 | 749 | } else { |
0d8852a5 | 750 | logger.warn(`${this.logPrefix()} Charging station is already stopped...`); |
c0560973 | 751 | } |
c0560973 JB |
752 | } |
753 | ||
60ddad53 JB |
754 | public async reset(reason?: StopTransactionReason): Promise<void> { |
755 | await this.stop(reason); | |
e1d9a0f4 | 756 | await sleep(this.stationInfo.resetTime!); |
fa7bccf4 | 757 | this.initialize(); |
94ec7e96 JB |
758 | this.start(); |
759 | } | |
760 | ||
17ac262c JB |
761 | public saveOcppConfiguration(): void { |
762 | if (this.getOcppPersistentConfiguration()) { | |
b1bbdae5 | 763 | this.saveConfiguration(); |
e6895390 JB |
764 | } |
765 | } | |
766 | ||
8e242273 JB |
767 | public bufferMessage(message: string): void { |
768 | this.messageBuffer.add(message); | |
3ba2381e JB |
769 | } |
770 | ||
db2336d9 | 771 | public openWSConnection( |
abe9e9dd | 772 | options: WsOptions = this.stationInfo?.wsOptions ?? {}, |
db2336d9 JB |
773 | params: { closeOpened?: boolean; terminateOpened?: boolean } = { |
774 | closeOpened: false, | |
775 | terminateOpened: false, | |
5edd8ba0 | 776 | }, |
db2336d9 | 777 | ): void { |
be4c6702 | 778 | options = { handshakeTimeout: secondsToMilliseconds(this.getConnectionTimeout()), ...options }; |
b1bbdae5 | 779 | params = { ...{ closeOpened: false, terminateOpened: false }, ...params }; |
cbf9b878 | 780 | if (this.started === false && this.starting === false) { |
d1c6c833 | 781 | logger.warn( |
66dd3447 | 782 | `${this.logPrefix()} Cannot open OCPP connection to URL ${this.wsConnectionUrl.toString()} |
5edd8ba0 | 783 | on stopped charging station`, |
d1c6c833 JB |
784 | ); |
785 | return; | |
786 | } | |
db2336d9 | 787 | if ( |
9bf0ef23 JB |
788 | !isNullOrUndefined(this.stationInfo.supervisionUser) && |
789 | !isNullOrUndefined(this.stationInfo.supervisionPassword) | |
db2336d9 JB |
790 | ) { |
791 | options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`; | |
792 | } | |
793 | if (params?.closeOpened) { | |
794 | this.closeWSConnection(); | |
795 | } | |
796 | if (params?.terminateOpened) { | |
797 | this.terminateWSConnection(); | |
798 | } | |
db2336d9 | 799 | |
56eb297e | 800 | if (this.isWebSocketConnectionOpened() === true) { |
0a03f36c | 801 | logger.warn( |
66dd3447 | 802 | `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} |
5edd8ba0 | 803 | is already opened`, |
0a03f36c JB |
804 | ); |
805 | return; | |
806 | } | |
807 | ||
db2336d9 | 808 | logger.info( |
5edd8ba0 | 809 | `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`, |
db2336d9 JB |
810 | ); |
811 | ||
feff11ec JB |
812 | this.wsConnection = new WebSocket( |
813 | this.wsConnectionUrl, | |
814 | `ocpp${this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16}`, | |
5edd8ba0 | 815 | options, |
feff11ec | 816 | ); |
db2336d9 JB |
817 | |
818 | // Handle WebSocket message | |
819 | this.wsConnection.on( | |
820 | 'message', | |
5edd8ba0 | 821 | this.onMessage.bind(this) as (this: WebSocket, data: RawData, isBinary: boolean) => void, |
db2336d9 JB |
822 | ); |
823 | // Handle WebSocket error | |
824 | this.wsConnection.on( | |
825 | 'error', | |
5edd8ba0 | 826 | this.onError.bind(this) as (this: WebSocket, error: Error) => void, |
db2336d9 JB |
827 | ); |
828 | // Handle WebSocket close | |
829 | this.wsConnection.on( | |
830 | 'close', | |
5edd8ba0 | 831 | this.onClose.bind(this) as (this: WebSocket, code: number, reason: Buffer) => void, |
db2336d9 JB |
832 | ); |
833 | // Handle WebSocket open | |
834 | this.wsConnection.on('open', this.onOpen.bind(this) as (this: WebSocket) => void); | |
835 | // Handle WebSocket ping | |
836 | this.wsConnection.on('ping', this.onPing.bind(this) as (this: WebSocket, data: Buffer) => void); | |
837 | // Handle WebSocket pong | |
838 | this.wsConnection.on('pong', this.onPong.bind(this) as (this: WebSocket, data: Buffer) => void); | |
839 | } | |
840 | ||
841 | public closeWSConnection(): void { | |
56eb297e | 842 | if (this.isWebSocketConnectionOpened() === true) { |
72092cfc | 843 | this.wsConnection?.close(); |
db2336d9 JB |
844 | this.wsConnection = null; |
845 | } | |
846 | } | |
847 | ||
e1d9a0f4 | 848 | public getAutomaticTransactionGeneratorConfiguration(): AutomaticTransactionGeneratorConfiguration { |
c7db8ecb JB |
849 | if (isNullOrUndefined(this.automaticTransactionGeneratorConfiguration)) { |
850 | let automaticTransactionGeneratorConfiguration: | |
851 | | AutomaticTransactionGeneratorConfiguration | |
852 | | undefined; | |
853 | const automaticTransactionGeneratorConfigurationFromFile = | |
854 | this.getConfigurationFromFile()?.automaticTransactionGenerator; | |
855 | if ( | |
856 | this.getAutomaticTransactionGeneratorPersistentConfiguration() && | |
857 | automaticTransactionGeneratorConfigurationFromFile | |
858 | ) { | |
859 | automaticTransactionGeneratorConfiguration = | |
860 | automaticTransactionGeneratorConfigurationFromFile; | |
861 | } else { | |
862 | automaticTransactionGeneratorConfiguration = | |
863 | this.getTemplateFromFile()?.AutomaticTransactionGenerator; | |
864 | } | |
865 | this.automaticTransactionGeneratorConfiguration = { | |
866 | ...Constants.DEFAULT_ATG_CONFIGURATION, | |
867 | ...automaticTransactionGeneratorConfiguration, | |
868 | }; | |
ac7f79af | 869 | } |
c7db8ecb | 870 | return this.automaticTransactionGeneratorConfiguration!; |
ac7f79af JB |
871 | } |
872 | ||
5ced7e80 JB |
873 | public getAutomaticTransactionGeneratorStatuses(): Status[] | undefined { |
874 | return this.getConfigurationFromFile()?.automaticTransactionGeneratorStatuses; | |
875 | } | |
876 | ||
ac7f79af JB |
877 | public startAutomaticTransactionGenerator(connectorIds?: number[]): void { |
878 | this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance(this); | |
9bf0ef23 | 879 | if (isNotEmptyArray(connectorIds)) { |
e1d9a0f4 | 880 | for (const connectorId of connectorIds!) { |
551e477c | 881 | this.automaticTransactionGenerator?.startConnector(connectorId); |
a5e9befc JB |
882 | } |
883 | } else { | |
551e477c | 884 | this.automaticTransactionGenerator?.start(); |
4f69be04 | 885 | } |
cb60061f | 886 | this.saveAutomaticTransactionGeneratorConfiguration(); |
c8faabc8 | 887 | parentPort?.postMessage(buildUpdatedMessage(this)); |
4f69be04 JB |
888 | } |
889 | ||
a5e9befc | 890 | public stopAutomaticTransactionGenerator(connectorIds?: number[]): void { |
9bf0ef23 | 891 | if (isNotEmptyArray(connectorIds)) { |
e1d9a0f4 | 892 | for (const connectorId of connectorIds!) { |
a5e9befc JB |
893 | this.automaticTransactionGenerator?.stopConnector(connectorId); |
894 | } | |
895 | } else { | |
896 | this.automaticTransactionGenerator?.stop(); | |
4f69be04 | 897 | } |
cb60061f | 898 | this.saveAutomaticTransactionGeneratorConfiguration(); |
c8faabc8 | 899 | parentPort?.postMessage(buildUpdatedMessage(this)); |
4f69be04 JB |
900 | } |
901 | ||
5e3cb728 JB |
902 | public async stopTransactionOnConnector( |
903 | connectorId: number, | |
5edd8ba0 | 904 | reason = StopTransactionReason.NONE, |
5e3cb728 | 905 | ): Promise<StopTransactionResponse> { |
72092cfc | 906 | const transactionId = this.getConnectorStatus(connectorId)?.transactionId; |
5e3cb728 | 907 | if ( |
c7e8e0a2 JB |
908 | this.getBeginEndMeterValues() === true && |
909 | this.getOcppStrictCompliance() === true && | |
910 | this.getOutOfOrderEndMeterValues() === false | |
5e3cb728 JB |
911 | ) { |
912 | // FIXME: Implement OCPP version agnostic helpers | |
913 | const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue( | |
914 | this, | |
915 | connectorId, | |
e1d9a0f4 | 916 | this.getEnergyActiveImportRegisterByTransactionId(transactionId!), |
5e3cb728 JB |
917 | ); |
918 | await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>( | |
919 | this, | |
920 | RequestCommand.METER_VALUES, | |
921 | { | |
922 | connectorId, | |
923 | transactionId, | |
924 | meterValue: [transactionEndMeterValue], | |
5edd8ba0 | 925 | }, |
5e3cb728 JB |
926 | ); |
927 | } | |
928 | return this.ocppRequestService.requestHandler<StopTransactionRequest, StopTransactionResponse>( | |
929 | this, | |
930 | RequestCommand.STOP_TRANSACTION, | |
931 | { | |
932 | transactionId, | |
e1d9a0f4 | 933 | meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId!, true), |
5e3cb728 | 934 | reason, |
5edd8ba0 | 935 | }, |
5e3cb728 JB |
936 | ); |
937 | } | |
938 | ||
10e8c3e1 | 939 | public getReserveConnectorZeroSupported(): boolean { |
9bf0ef23 | 940 | return convertToBoolean( |
f2d5e3d9 | 941 | getConfigurationKey(this, StandardParametersKey.ReserveConnectorZeroSupported)!.value, |
24578c31 JB |
942 | ); |
943 | } | |
944 | ||
d193a949 | 945 | public async addReservation(reservation: Reservation): Promise<void> { |
2ca0ea90 | 946 | const reservationFound = this.getReservationBy('reservationId', reservation.reservationId); |
530e5fbb JB |
947 | if (!isUndefined(reservationFound)) { |
948 | await this.removeReservation( | |
949 | reservationFound!, | |
950 | ReservationTerminationReason.REPLACE_EXISTING, | |
951 | ); | |
d193a949 | 952 | } |
e1d9a0f4 | 953 | this.getConnectorStatus(reservation.connectorId)!.reservation = reservation; |
ec94a3cf | 954 | await OCPPServiceUtils.sendAndSetConnectorStatus( |
d193a949 | 955 | this, |
ec94a3cf JB |
956 | reservation.connectorId, |
957 | ConnectorStatusEnum.Reserved, | |
e1d9a0f4 | 958 | undefined, |
5edd8ba0 | 959 | { send: reservation.connectorId !== 0 }, |
d193a949 | 960 | ); |
24578c31 JB |
961 | } |
962 | ||
d193a949 JB |
963 | public async removeReservation( |
964 | reservation: Reservation, | |
5edd8ba0 | 965 | reason?: ReservationTerminationReason, |
d193a949 | 966 | ): Promise<void> { |
e1d9a0f4 | 967 | const connector = this.getConnectorStatus(reservation.connectorId)!; |
d193a949 | 968 | switch (reason) { |
96d96b12 | 969 | case ReservationTerminationReason.CONNECTOR_STATE_CHANGED: |
ec94a3cf | 970 | case ReservationTerminationReason.TRANSACTION_STARTED: |
ec9f36cc JB |
971 | delete connector.reservation; |
972 | break; | |
e74bc549 JB |
973 | case ReservationTerminationReason.RESERVATION_CANCELED: |
974 | case ReservationTerminationReason.REPLACE_EXISTING: | |
975 | case ReservationTerminationReason.EXPIRED: | |
ec94a3cf | 976 | await OCPPServiceUtils.sendAndSetConnectorStatus( |
d193a949 | 977 | this, |
ec94a3cf JB |
978 | reservation.connectorId, |
979 | ConnectorStatusEnum.Available, | |
e1d9a0f4 | 980 | undefined, |
5edd8ba0 | 981 | { send: reservation.connectorId !== 0 }, |
d193a949 | 982 | ); |
ec94a3cf | 983 | delete connector.reservation; |
d193a949 | 984 | break; |
b029e74e JB |
985 | default: |
986 | break; | |
d193a949 | 987 | } |
24578c31 JB |
988 | } |
989 | ||
3fa7f799 JB |
990 | public getReservationBy( |
991 | filterKey: ReservationFilterKey, | |
5edd8ba0 | 992 | value: number | string, |
3fa7f799 | 993 | ): Reservation | undefined { |
66dd3447 | 994 | if (this.hasEvses) { |
3fa7f799 JB |
995 | for (const evseStatus of this.evses.values()) { |
996 | for (const connectorStatus of evseStatus.connectors.values()) { | |
2ca0ea90 | 997 | if (connectorStatus?.reservation?.[filterKey] === value) { |
3fa7f799 | 998 | return connectorStatus.reservation; |
66dd3447 JB |
999 | } |
1000 | } | |
1001 | } | |
1002 | } else { | |
3fa7f799 | 1003 | for (const connectorStatus of this.connectors.values()) { |
2ca0ea90 | 1004 | if (connectorStatus?.reservation?.[filterKey] === value) { |
3fa7f799 | 1005 | return connectorStatus.reservation; |
66dd3447 JB |
1006 | } |
1007 | } | |
1008 | } | |
d193a949 JB |
1009 | } |
1010 | ||
e6948a57 JB |
1011 | public isConnectorReservable( |
1012 | reservationId: number, | |
1013 | idTag?: string, | |
1014 | connectorId?: number, | |
1015 | ): boolean { | |
1016 | const reservationExists = !isUndefined(this.getReservationBy('reservationId', reservationId)); | |
1017 | if (arguments.length === 1) { | |
1018 | return !reservationExists; | |
1019 | } else if (arguments.length > 1) { | |
1020 | const userReservationExists = | |
1021 | !isUndefined(idTag) && isUndefined(this.getReservationBy('idTag', idTag!)) ? false : true; | |
1022 | const notConnectorZero = isUndefined(connectorId) ? true : connectorId! > 0; | |
1023 | const freeConnectorsAvailable = this.getNumberOfReservableConnectors() > 0; | |
1024 | return ( | |
1025 | !reservationExists && !userReservationExists && notConnectorZero && freeConnectorsAvailable | |
1026 | ); | |
1027 | } | |
1028 | return false; | |
1029 | } | |
1030 | ||
1031 | private startReservationExpirationSetInterval(customInterval?: number): void { | |
d193a949 JB |
1032 | const interval = |
1033 | customInterval ?? Constants.DEFAULT_RESERVATION_EXPIRATION_OBSERVATION_INTERVAL; | |
42371a2e | 1034 | if (interval > 0) { |
04c32a95 JB |
1035 | logger.info( |
1036 | `${this.logPrefix()} Reservation expiration date checks started every ${formatDurationMilliSeconds( | |
1037 | interval, | |
1038 | )}`, | |
1039 | ); | |
37aa4e56 | 1040 | this.reservationExpirationSetInterval = setInterval((): void => { |
354c3fbe | 1041 | const currentDate = new Date(); |
42371a2e JB |
1042 | if (this.hasEvses) { |
1043 | for (const evseStatus of this.evses.values()) { | |
1044 | for (const connectorStatus of evseStatus.connectors.values()) { | |
354c3fbe JB |
1045 | if ( |
1046 | connectorStatus.reservation && | |
1047 | connectorStatus.reservation.expiryDate < currentDate | |
1048 | ) { | |
37aa4e56 | 1049 | this.removeReservation( |
8cc482a9 | 1050 | connectorStatus.reservation, |
42371a2e | 1051 | ReservationTerminationReason.EXPIRED, |
37aa4e56 | 1052 | ).catch(Constants.EMPTY_FUNCTION); |
42371a2e JB |
1053 | } |
1054 | } | |
1055 | } | |
1056 | } else { | |
1057 | for (const connectorStatus of this.connectors.values()) { | |
354c3fbe JB |
1058 | if ( |
1059 | connectorStatus.reservation && | |
1060 | connectorStatus.reservation.expiryDate < currentDate | |
1061 | ) { | |
37aa4e56 | 1062 | this.removeReservation( |
8cc482a9 | 1063 | connectorStatus.reservation, |
5edd8ba0 | 1064 | ReservationTerminationReason.EXPIRED, |
37aa4e56 | 1065 | ).catch(Constants.EMPTY_FUNCTION); |
66dd3447 JB |
1066 | } |
1067 | } | |
1068 | } | |
42371a2e JB |
1069 | }, interval); |
1070 | } | |
d193a949 JB |
1071 | } |
1072 | ||
e6948a57 JB |
1073 | private stopReservationExpirationSetInterval(): void { |
1074 | if (this.reservationExpirationSetInterval) { | |
1075 | clearInterval(this.reservationExpirationSetInterval); | |
1076 | } | |
d193a949 JB |
1077 | } |
1078 | ||
e6948a57 JB |
1079 | private restartReservationExpiryDateSetInterval(): void { |
1080 | this.stopReservationExpirationSetInterval(); | |
1081 | this.startReservationExpirationSetInterval(); | |
d193a949 JB |
1082 | } |
1083 | ||
1084 | private getNumberOfReservableConnectors(): number { | |
1085 | let reservableConnectors = 0; | |
66dd3447 | 1086 | if (this.hasEvses) { |
3fa7f799 | 1087 | for (const evseStatus of this.evses.values()) { |
fba11dc6 | 1088 | reservableConnectors += countReservableConnectors(evseStatus.connectors); |
66dd3447 JB |
1089 | } |
1090 | } else { | |
fba11dc6 | 1091 | reservableConnectors = countReservableConnectors(this.connectors); |
66dd3447 JB |
1092 | } |
1093 | return reservableConnectors - this.getNumberOfReservationsOnConnectorZero(); | |
1094 | } | |
1095 | ||
d193a949 | 1096 | private getNumberOfReservationsOnConnectorZero(): number { |
66dd3447 | 1097 | let numberOfReservations = 0; |
6913d568 JB |
1098 | if ( |
1099 | // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing | |
1100 | (this.hasEvses && this.evses.get(0)?.connectors.get(0)?.reservation) || | |
1101 | (!this.hasEvses && this.connectors.get(0)?.reservation) | |
1102 | ) { | |
66dd3447 JB |
1103 | ++numberOfReservations; |
1104 | } | |
1105 | return numberOfReservations; | |
24578c31 JB |
1106 | } |
1107 | ||
f90c1757 | 1108 | private flushMessageBuffer(): void { |
8e242273 | 1109 | if (this.messageBuffer.size > 0) { |
7d3b0f64 | 1110 | for (const message of this.messageBuffer.values()) { |
e1d9a0f4 JB |
1111 | let beginId: string | undefined; |
1112 | let commandName: RequestCommand | undefined; | |
8ca6874c | 1113 | const [messageType] = JSON.parse(message) as OutgoingRequest | Response | ErrorResponse; |
1431af78 JB |
1114 | const isRequest = messageType === MessageType.CALL_MESSAGE; |
1115 | if (isRequest) { | |
1116 | [, , commandName] = JSON.parse(message) as OutgoingRequest; | |
1117 | beginId = PerformanceStatistics.beginMeasure(commandName); | |
1118 | } | |
72092cfc | 1119 | this.wsConnection?.send(message); |
e1d9a0f4 | 1120 | isRequest && PerformanceStatistics.endMeasure(commandName!, beginId!); |
8ca6874c JB |
1121 | logger.debug( |
1122 | `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString( | |
5edd8ba0 JB |
1123 | messageType, |
1124 | )} payload sent: ${message}`, | |
8ca6874c | 1125 | ); |
8e242273 | 1126 | this.messageBuffer.delete(message); |
7d3b0f64 | 1127 | } |
77f00f84 JB |
1128 | } |
1129 | } | |
1130 | ||
1f5df42a JB |
1131 | private getSupervisionUrlOcppConfiguration(): boolean { |
1132 | return this.stationInfo.supervisionUrlOcppConfiguration ?? false; | |
12fc74d6 JB |
1133 | } |
1134 | ||
e8e865ea | 1135 | private getSupervisionUrlOcppKey(): string { |
6dad8e21 | 1136 | return this.stationInfo.supervisionUrlOcppKey ?? VendorParametersKey.ConnectionUrl; |
e8e865ea JB |
1137 | } |
1138 | ||
72092cfc | 1139 | private getTemplateFromFile(): ChargingStationTemplate | undefined { |
e1d9a0f4 | 1140 | let template: ChargingStationTemplate | undefined; |
5ad8570f | 1141 | try { |
cda5d0fb JB |
1142 | if (this.sharedLRUCache.hasChargingStationTemplate(this.templateFileHash)) { |
1143 | template = this.sharedLRUCache.getChargingStationTemplate(this.templateFileHash); | |
7c72977b JB |
1144 | } else { |
1145 | const measureId = `${FileType.ChargingStationTemplate} read`; | |
1146 | const beginId = PerformanceStatistics.beginMeasure(measureId); | |
d972af76 | 1147 | template = JSON.parse(readFileSync(this.templateFile, 'utf8')) as ChargingStationTemplate; |
7c72977b | 1148 | PerformanceStatistics.endMeasure(measureId, beginId); |
d972af76 | 1149 | template.templateHash = createHash(Constants.DEFAULT_HASH_ALGORITHM) |
7c72977b JB |
1150 | .update(JSON.stringify(template)) |
1151 | .digest('hex'); | |
57adbebc | 1152 | this.sharedLRUCache.setChargingStationTemplate(template); |
cda5d0fb | 1153 | this.templateFileHash = template.templateHash; |
7c72977b | 1154 | } |
5ad8570f | 1155 | } catch (error) { |
fa5995d6 | 1156 | handleFileException( |
2484ac1e | 1157 | this.templateFile, |
7164966d JB |
1158 | FileType.ChargingStationTemplate, |
1159 | error as NodeJS.ErrnoException, | |
5edd8ba0 | 1160 | this.logPrefix(), |
e7aeea18 | 1161 | ); |
5ad8570f | 1162 | } |
2484ac1e JB |
1163 | return template; |
1164 | } | |
1165 | ||
7a3a2ebb | 1166 | private getStationInfoFromTemplate(): ChargingStationInfo { |
e1d9a0f4 | 1167 | const stationTemplate: ChargingStationTemplate = this.getTemplateFromFile()!; |
fba11dc6 JB |
1168 | checkTemplate(stationTemplate, this.logPrefix(), this.templateFile); |
1169 | warnTemplateKeysDeprecation(stationTemplate, this.logPrefix(), this.templateFile); | |
8a133cc8 | 1170 | if (stationTemplate?.Connectors) { |
fba11dc6 | 1171 | checkConnectorsConfiguration(stationTemplate, this.logPrefix(), this.templateFile); |
8a133cc8 | 1172 | } |
fba11dc6 JB |
1173 | const stationInfo: ChargingStationInfo = stationTemplateToStationInfo(stationTemplate); |
1174 | stationInfo.hashId = getHashId(this.index, stationTemplate); | |
1175 | stationInfo.chargingStationId = getChargingStationId(this.index, stationTemplate); | |
72092cfc | 1176 | stationInfo.ocppVersion = stationTemplate?.ocppVersion ?? OCPPVersion.VERSION_16; |
fba11dc6 | 1177 | createSerialNumber(stationTemplate, stationInfo); |
9bf0ef23 | 1178 | if (isNotEmptyArray(stationTemplate?.power)) { |
551e477c | 1179 | stationTemplate.power = stationTemplate.power as number[]; |
9bf0ef23 | 1180 | const powerArrayRandomIndex = Math.floor(secureRandom() * stationTemplate.power.length); |
cc6e8ab5 | 1181 | stationInfo.maximumPower = |
72092cfc | 1182 | stationTemplate?.powerUnit === PowerUnits.KILO_WATT |
fa7bccf4 JB |
1183 | ? stationTemplate.power[powerArrayRandomIndex] * 1000 |
1184 | : stationTemplate.power[powerArrayRandomIndex]; | |
5ad8570f | 1185 | } else { |
551e477c | 1186 | stationTemplate.power = stationTemplate?.power as number; |
cc6e8ab5 | 1187 | stationInfo.maximumPower = |
72092cfc | 1188 | stationTemplate?.powerUnit === PowerUnits.KILO_WATT |
fa7bccf4 JB |
1189 | ? stationTemplate.power * 1000 |
1190 | : stationTemplate.power; | |
1191 | } | |
3637ca2c | 1192 | stationInfo.firmwareVersionPattern = |
72092cfc | 1193 | stationTemplate?.firmwareVersionPattern ?? Constants.SEMVER_PATTERN; |
3637ca2c | 1194 | if ( |
9bf0ef23 | 1195 | isNotEmptyString(stationInfo.firmwareVersion) && |
e1d9a0f4 | 1196 | new RegExp(stationInfo.firmwareVersionPattern).test(stationInfo.firmwareVersion!) === false |
3637ca2c JB |
1197 | ) { |
1198 | logger.warn( | |
1199 | `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${ | |
1200 | this.templateFile | |
5edd8ba0 | 1201 | } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`, |
3637ca2c JB |
1202 | ); |
1203 | } | |
598c886d | 1204 | stationInfo.firmwareUpgrade = merge<FirmwareUpgrade>( |
15748260 | 1205 | { |
598c886d JB |
1206 | versionUpgrade: { |
1207 | step: 1, | |
1208 | }, | |
15748260 JB |
1209 | reset: true, |
1210 | }, | |
5edd8ba0 | 1211 | stationTemplate?.firmwareUpgrade ?? {}, |
15748260 | 1212 | ); |
9bf0ef23 | 1213 | stationInfo.resetTime = !isNullOrUndefined(stationTemplate?.resetTime) |
be4c6702 | 1214 | ? secondsToMilliseconds(stationTemplate.resetTime!) |
e7aeea18 | 1215 | : Constants.CHARGING_STATION_DEFAULT_RESET_TIME; |
fa7bccf4 | 1216 | stationInfo.maximumAmperage = this.getMaximumAmperage(stationInfo); |
9ac86a7e | 1217 | return stationInfo; |
5ad8570f JB |
1218 | } |
1219 | ||
551e477c JB |
1220 | private getStationInfoFromFile(): ChargingStationInfo | undefined { |
1221 | let stationInfo: ChargingStationInfo | undefined; | |
f832e5df JB |
1222 | if (this.getStationInfoPersistentConfiguration()) { |
1223 | stationInfo = this.getConfigurationFromFile()?.stationInfo; | |
1224 | if (stationInfo) { | |
1225 | delete stationInfo?.infoHash; | |
1226 | } | |
1227 | } | |
f765beaa | 1228 | return stationInfo; |
2484ac1e JB |
1229 | } |
1230 | ||
1231 | private getStationInfo(): ChargingStationInfo { | |
1232 | const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate(); | |
551e477c | 1233 | const stationInfoFromFile: ChargingStationInfo | undefined = this.getStationInfoFromFile(); |
6b90dcca JB |
1234 | // Priority: |
1235 | // 1. charging station info from template | |
1236 | // 2. charging station info from configuration file | |
f765beaa | 1237 | if (stationInfoFromFile?.templateHash === stationInfoFromTemplate.templateHash) { |
e1d9a0f4 | 1238 | return stationInfoFromFile!; |
f765beaa | 1239 | } |
fec4d204 | 1240 | stationInfoFromFile && |
fba11dc6 | 1241 | propagateSerialNumber( |
e1d9a0f4 | 1242 | this.getTemplateFromFile()!, |
fec4d204 | 1243 | stationInfoFromFile, |
5edd8ba0 | 1244 | stationInfoFromTemplate, |
fec4d204 | 1245 | ); |
01efc60a | 1246 | return stationInfoFromTemplate; |
2484ac1e JB |
1247 | } |
1248 | ||
1249 | private saveStationInfo(): void { | |
ccb1d6e9 | 1250 | if (this.getStationInfoPersistentConfiguration()) { |
b1bbdae5 | 1251 | this.saveConfiguration(); |
ccb1d6e9 | 1252 | } |
2484ac1e JB |
1253 | } |
1254 | ||
e8e865ea | 1255 | private getOcppPersistentConfiguration(): boolean { |
ccb1d6e9 JB |
1256 | return this.stationInfo?.ocppPersistentConfiguration ?? true; |
1257 | } | |
1258 | ||
1259 | private getStationInfoPersistentConfiguration(): boolean { | |
1260 | return this.stationInfo?.stationInfoPersistentConfiguration ?? true; | |
e8e865ea JB |
1261 | } |
1262 | ||
5ced7e80 JB |
1263 | private getAutomaticTransactionGeneratorPersistentConfiguration(): boolean { |
1264 | return this.stationInfo?.automaticTransactionGeneratorPersistentConfiguration ?? true; | |
1265 | } | |
1266 | ||
c0560973 | 1267 | private handleUnsupportedVersion(version: OCPPVersion) { |
66dd3447 JB |
1268 | const errorMsg = `Unsupported protocol version '${version}' configured |
1269 | in template file ${this.templateFile}`; | |
ded57f02 JB |
1270 | logger.error(`${this.logPrefix()} ${errorMsg}`); |
1271 | throw new BaseError(errorMsg); | |
c0560973 JB |
1272 | } |
1273 | ||
2484ac1e | 1274 | private initialize(): void { |
e1d9a0f4 | 1275 | const stationTemplate = this.getTemplateFromFile()!; |
fba11dc6 | 1276 | checkTemplate(stationTemplate, this.logPrefix(), this.templateFile); |
d972af76 JB |
1277 | this.configurationFile = join( |
1278 | dirname(this.templateFile.replace('station-templates', 'configurations')), | |
5edd8ba0 | 1279 | `${getHashId(this.index, stationTemplate)}.json`, |
0642c3d2 | 1280 | ); |
a4f7c75f | 1281 | const chargingStationConfiguration = this.getConfigurationFromFile(); |
a4f7c75f | 1282 | if ( |
ba01a213 | 1283 | chargingStationConfiguration?.stationInfo?.templateHash === stationTemplate?.templateHash && |
e1d9a0f4 | 1284 | // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing |
a4f7c75f JB |
1285 | (chargingStationConfiguration?.connectorsStatus || chargingStationConfiguration?.evsesStatus) |
1286 | ) { | |
1287 | this.initializeConnectorsOrEvsesFromFile(chargingStationConfiguration); | |
1288 | } else { | |
1289 | this.initializeConnectorsOrEvsesFromTemplate(stationTemplate); | |
1290 | } | |
b44b779a | 1291 | this.stationInfo = this.getStationInfo(); |
3637ca2c JB |
1292 | if ( |
1293 | this.stationInfo.firmwareStatus === FirmwareStatus.Installing && | |
9bf0ef23 JB |
1294 | isNotEmptyString(this.stationInfo.firmwareVersion) && |
1295 | isNotEmptyString(this.stationInfo.firmwareVersionPattern) | |
3637ca2c | 1296 | ) { |
d812bdcb | 1297 | const patternGroup: number | undefined = |
15748260 | 1298 | this.stationInfo.firmwareUpgrade?.versionUpgrade?.patternGroup ?? |
d812bdcb | 1299 | this.stationInfo.firmwareVersion?.split('.').length; |
e1d9a0f4 JB |
1300 | const match = this.stationInfo |
1301 | .firmwareVersion!.match(new RegExp(this.stationInfo.firmwareVersionPattern!))! | |
1302 | .slice(1, patternGroup! + 1); | |
3637ca2c | 1303 | const patchLevelIndex = match.length - 1; |
5d280aae | 1304 | match[patchLevelIndex] = ( |
9bf0ef23 | 1305 | convertToInt(match[patchLevelIndex]) + |
e1d9a0f4 | 1306 | this.stationInfo.firmwareUpgrade!.versionUpgrade!.step! |
5d280aae | 1307 | ).toString(); |
72092cfc | 1308 | this.stationInfo.firmwareVersion = match?.join('.'); |
3637ca2c | 1309 | } |
6bccfcbc | 1310 | this.saveStationInfo(); |
6bccfcbc JB |
1311 | this.configuredSupervisionUrl = this.getConfiguredSupervisionUrl(); |
1312 | if (this.getEnableStatistics() === true) { | |
1313 | this.performanceStatistics = PerformanceStatistics.getInstance( | |
1314 | this.stationInfo.hashId, | |
e1d9a0f4 | 1315 | this.stationInfo.chargingStationId!, |
5edd8ba0 | 1316 | this.configuredSupervisionUrl, |
6bccfcbc JB |
1317 | ); |
1318 | } | |
fba11dc6 | 1319 | this.bootNotificationRequest = createBootNotificationRequest(this.stationInfo); |
692f2f64 JB |
1320 | this.powerDivider = this.getPowerDivider(); |
1321 | // OCPP configuration | |
1322 | this.ocppConfiguration = this.getOcppConfiguration(); | |
1323 | this.initializeOcppConfiguration(); | |
1324 | this.initializeOcppServices(); | |
1325 | if (this.stationInfo?.autoRegister === true) { | |
1326 | this.bootNotificationResponse = { | |
1327 | currentTime: new Date(), | |
be4c6702 | 1328 | interval: millisecondsToSeconds(this.getHeartbeatInterval()), |
692f2f64 JB |
1329 | status: RegistrationStatusEnumType.ACCEPTED, |
1330 | }; | |
1331 | } | |
147d0e0f JB |
1332 | } |
1333 | ||
feff11ec JB |
1334 | private initializeOcppServices(): void { |
1335 | const ocppVersion = this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16; | |
1336 | switch (ocppVersion) { | |
1337 | case OCPPVersion.VERSION_16: | |
1338 | this.ocppIncomingRequestService = | |
1339 | OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>(); | |
1340 | this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>( | |
5edd8ba0 | 1341 | OCPP16ResponseService.getInstance<OCPP16ResponseService>(), |
feff11ec JB |
1342 | ); |
1343 | break; | |
1344 | case OCPPVersion.VERSION_20: | |
1345 | case OCPPVersion.VERSION_201: | |
1346 | this.ocppIncomingRequestService = | |
1347 | OCPP20IncomingRequestService.getInstance<OCPP20IncomingRequestService>(); | |
1348 | this.ocppRequestService = OCPP20RequestService.getInstance<OCPP20RequestService>( | |
5edd8ba0 | 1349 | OCPP20ResponseService.getInstance<OCPP20ResponseService>(), |
feff11ec JB |
1350 | ); |
1351 | break; | |
1352 | default: | |
1353 | this.handleUnsupportedVersion(ocppVersion); | |
1354 | break; | |
1355 | } | |
1356 | } | |
1357 | ||
2484ac1e | 1358 | private initializeOcppConfiguration(): void { |
f2d5e3d9 JB |
1359 | if (!getConfigurationKey(this, StandardParametersKey.HeartbeatInterval)) { |
1360 | addConfigurationKey(this, StandardParametersKey.HeartbeatInterval, '0'); | |
f0f65a62 | 1361 | } |
f2d5e3d9 JB |
1362 | if (!getConfigurationKey(this, StandardParametersKey.HeartBeatInterval)) { |
1363 | addConfigurationKey(this, StandardParametersKey.HeartBeatInterval, '0', { visible: false }); | |
f0f65a62 | 1364 | } |
e7aeea18 JB |
1365 | if ( |
1366 | this.getSupervisionUrlOcppConfiguration() && | |
9bf0ef23 | 1367 | isNotEmptyString(this.getSupervisionUrlOcppKey()) && |
f2d5e3d9 | 1368 | !getConfigurationKey(this, this.getSupervisionUrlOcppKey()) |
e7aeea18 | 1369 | ) { |
f2d5e3d9 | 1370 | addConfigurationKey( |
17ac262c | 1371 | this, |
a59737e3 | 1372 | this.getSupervisionUrlOcppKey(), |
fa7bccf4 | 1373 | this.configuredSupervisionUrl.href, |
5edd8ba0 | 1374 | { reboot: true }, |
e7aeea18 | 1375 | ); |
e6895390 JB |
1376 | } else if ( |
1377 | !this.getSupervisionUrlOcppConfiguration() && | |
9bf0ef23 | 1378 | isNotEmptyString(this.getSupervisionUrlOcppKey()) && |
f2d5e3d9 | 1379 | getConfigurationKey(this, this.getSupervisionUrlOcppKey()) |
e6895390 | 1380 | ) { |
f2d5e3d9 | 1381 | deleteConfigurationKey(this, this.getSupervisionUrlOcppKey(), { save: false }); |
12fc74d6 | 1382 | } |
cc6e8ab5 | 1383 | if ( |
9bf0ef23 | 1384 | isNotEmptyString(this.stationInfo?.amperageLimitationOcppKey) && |
f2d5e3d9 | 1385 | !getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey!) |
cc6e8ab5 | 1386 | ) { |
f2d5e3d9 | 1387 | addConfigurationKey( |
17ac262c | 1388 | this, |
e1d9a0f4 | 1389 | this.stationInfo.amperageLimitationOcppKey!, |
17ac262c | 1390 | ( |
e1d9a0f4 | 1391 | this.stationInfo.maximumAmperage! * getAmperageLimitationUnitDivider(this.stationInfo) |
5edd8ba0 | 1392 | ).toString(), |
cc6e8ab5 JB |
1393 | ); |
1394 | } | |
f2d5e3d9 JB |
1395 | if (!getConfigurationKey(this, StandardParametersKey.SupportedFeatureProfiles)) { |
1396 | addConfigurationKey( | |
17ac262c | 1397 | this, |
e7aeea18 | 1398 | StandardParametersKey.SupportedFeatureProfiles, |
5edd8ba0 | 1399 | `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`, |
e7aeea18 JB |
1400 | ); |
1401 | } | |
f2d5e3d9 | 1402 | addConfigurationKey( |
17ac262c | 1403 | this, |
e7aeea18 JB |
1404 | StandardParametersKey.NumberOfConnectors, |
1405 | this.getNumberOfConnectors().toString(), | |
a95873d8 | 1406 | { readonly: true }, |
5edd8ba0 | 1407 | { overwrite: true }, |
e7aeea18 | 1408 | ); |
f2d5e3d9 JB |
1409 | if (!getConfigurationKey(this, StandardParametersKey.MeterValuesSampledData)) { |
1410 | addConfigurationKey( | |
17ac262c | 1411 | this, |
e7aeea18 | 1412 | StandardParametersKey.MeterValuesSampledData, |
5edd8ba0 | 1413 | MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER, |
e7aeea18 | 1414 | ); |
7abfea5f | 1415 | } |
f2d5e3d9 | 1416 | if (!getConfigurationKey(this, StandardParametersKey.ConnectorPhaseRotation)) { |
dd08d43d | 1417 | const connectorsPhaseRotation: string[] = []; |
28e78158 JB |
1418 | if (this.hasEvses) { |
1419 | for (const evseStatus of this.evses.values()) { | |
1420 | for (const connectorId of evseStatus.connectors.keys()) { | |
dd08d43d | 1421 | connectorsPhaseRotation.push( |
e1d9a0f4 | 1422 | getPhaseRotationValue(connectorId, this.getNumberOfPhases())!, |
dd08d43d | 1423 | ); |
28e78158 JB |
1424 | } |
1425 | } | |
1426 | } else { | |
1427 | for (const connectorId of this.connectors.keys()) { | |
dd08d43d | 1428 | connectorsPhaseRotation.push( |
e1d9a0f4 | 1429 | getPhaseRotationValue(connectorId, this.getNumberOfPhases())!, |
dd08d43d | 1430 | ); |
7e1dc878 JB |
1431 | } |
1432 | } | |
f2d5e3d9 | 1433 | addConfigurationKey( |
17ac262c | 1434 | this, |
e7aeea18 | 1435 | StandardParametersKey.ConnectorPhaseRotation, |
5edd8ba0 | 1436 | connectorsPhaseRotation.toString(), |
e7aeea18 | 1437 | ); |
7e1dc878 | 1438 | } |
f2d5e3d9 JB |
1439 | if (!getConfigurationKey(this, StandardParametersKey.AuthorizeRemoteTxRequests)) { |
1440 | addConfigurationKey(this, StandardParametersKey.AuthorizeRemoteTxRequests, 'true'); | |
36f6a92e | 1441 | } |
17ac262c | 1442 | if ( |
f2d5e3d9 JB |
1443 | !getConfigurationKey(this, StandardParametersKey.LocalAuthListEnabled) && |
1444 | getConfigurationKey(this, StandardParametersKey.SupportedFeatureProfiles)?.value?.includes( | |
1445 | SupportedFeatureProfiles.LocalAuthListManagement, | |
17ac262c JB |
1446 | ) |
1447 | ) { | |
f2d5e3d9 JB |
1448 | addConfigurationKey(this, StandardParametersKey.LocalAuthListEnabled, 'false'); |
1449 | } | |
1450 | if (!getConfigurationKey(this, StandardParametersKey.ConnectionTimeOut)) { | |
1451 | addConfigurationKey( | |
17ac262c | 1452 | this, |
e7aeea18 | 1453 | StandardParametersKey.ConnectionTimeOut, |
5edd8ba0 | 1454 | Constants.DEFAULT_CONNECTION_TIMEOUT.toString(), |
e7aeea18 | 1455 | ); |
8bce55bf | 1456 | } |
2484ac1e | 1457 | this.saveOcppConfiguration(); |
073bd098 JB |
1458 | } |
1459 | ||
a4f7c75f JB |
1460 | private initializeConnectorsOrEvsesFromFile(configuration: ChargingStationConfiguration): void { |
1461 | if (configuration?.connectorsStatus && !configuration?.evsesStatus) { | |
8df5ae48 | 1462 | for (const [connectorId, connectorStatus] of configuration.connectorsStatus.entries()) { |
9bf0ef23 | 1463 | this.connectors.set(connectorId, cloneObject<ConnectorStatus>(connectorStatus)); |
8df5ae48 | 1464 | } |
a4f7c75f JB |
1465 | } else if (configuration?.evsesStatus && !configuration?.connectorsStatus) { |
1466 | for (const [evseId, evseStatusConfiguration] of configuration.evsesStatus.entries()) { | |
9bf0ef23 | 1467 | const evseStatus = cloneObject<EvseStatusConfiguration>(evseStatusConfiguration); |
a4f7c75f JB |
1468 | delete evseStatus.connectorsStatus; |
1469 | this.evses.set(evseId, { | |
8df5ae48 | 1470 | ...(evseStatus as EvseStatus), |
a4f7c75f | 1471 | connectors: new Map<number, ConnectorStatus>( |
e1d9a0f4 | 1472 | evseStatusConfiguration.connectorsStatus!.map((connectorStatus, connectorId) => [ |
a4f7c75f JB |
1473 | connectorId, |
1474 | connectorStatus, | |
5edd8ba0 | 1475 | ]), |
a4f7c75f JB |
1476 | ), |
1477 | }); | |
1478 | } | |
1479 | } else if (configuration?.evsesStatus && configuration?.connectorsStatus) { | |
1480 | const errorMsg = `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`; | |
1481 | logger.error(`${this.logPrefix()} ${errorMsg}`); | |
1482 | throw new BaseError(errorMsg); | |
1483 | } else { | |
1484 | const errorMsg = `No connectors or evses defined in configuration file ${this.configurationFile}`; | |
1485 | logger.error(`${this.logPrefix()} ${errorMsg}`); | |
1486 | throw new BaseError(errorMsg); | |
1487 | } | |
1488 | } | |
1489 | ||
34eeb1fb | 1490 | private initializeConnectorsOrEvsesFromTemplate(stationTemplate: ChargingStationTemplate) { |
cda5d0fb | 1491 | if (stationTemplate?.Connectors && !stationTemplate?.Evses) { |
34eeb1fb | 1492 | this.initializeConnectorsFromTemplate(stationTemplate); |
cda5d0fb | 1493 | } else if (stationTemplate?.Evses && !stationTemplate?.Connectors) { |
34eeb1fb | 1494 | this.initializeEvsesFromTemplate(stationTemplate); |
cda5d0fb | 1495 | } else if (stationTemplate?.Evses && stationTemplate?.Connectors) { |
ae25f265 JB |
1496 | const errorMsg = `Connectors and evses defined at the same time in template file ${this.templateFile}`; |
1497 | logger.error(`${this.logPrefix()} ${errorMsg}`); | |
1498 | throw new BaseError(errorMsg); | |
1499 | } else { | |
1500 | const errorMsg = `No connectors or evses defined in template file ${this.templateFile}`; | |
1501 | logger.error(`${this.logPrefix()} ${errorMsg}`); | |
1502 | throw new BaseError(errorMsg); | |
1503 | } | |
1504 | } | |
1505 | ||
34eeb1fb | 1506 | private initializeConnectorsFromTemplate(stationTemplate: ChargingStationTemplate): void { |
cda5d0fb | 1507 | if (!stationTemplate?.Connectors && this.connectors.size === 0) { |
ded57f02 JB |
1508 | const errorMsg = `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`; |
1509 | logger.error(`${this.logPrefix()} ${errorMsg}`); | |
1510 | throw new BaseError(errorMsg); | |
3d25cc86 | 1511 | } |
e1d9a0f4 | 1512 | if (!stationTemplate?.Connectors?.[0]) { |
3d25cc86 JB |
1513 | logger.warn( |
1514 | `${this.logPrefix()} Charging station information from template ${ | |
1515 | this.templateFile | |
5edd8ba0 | 1516 | } with no connector id 0 configuration`, |
3d25cc86 JB |
1517 | ); |
1518 | } | |
cda5d0fb JB |
1519 | if (stationTemplate?.Connectors) { |
1520 | const { configuredMaxConnectors, templateMaxConnectors, templateMaxAvailableConnectors } = | |
fba11dc6 | 1521 | checkConnectorsConfiguration(stationTemplate, this.logPrefix(), this.templateFile); |
d972af76 | 1522 | const connectorsConfigHash = createHash(Constants.DEFAULT_HASH_ALGORITHM) |
cda5d0fb | 1523 | .update( |
5edd8ba0 | 1524 | `${JSON.stringify(stationTemplate?.Connectors)}${configuredMaxConnectors.toString()}`, |
cda5d0fb | 1525 | ) |
3d25cc86 JB |
1526 | .digest('hex'); |
1527 | const connectorsConfigChanged = | |
1528 | this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash; | |
1529 | if (this.connectors?.size === 0 || connectorsConfigChanged) { | |
1530 | connectorsConfigChanged && this.connectors.clear(); | |
1531 | this.connectorsConfigurationHash = connectorsConfigHash; | |
269196a8 JB |
1532 | if (templateMaxConnectors > 0) { |
1533 | for (let connectorId = 0; connectorId <= configuredMaxConnectors; connectorId++) { | |
1534 | if ( | |
1535 | connectorId === 0 && | |
cda5d0fb JB |
1536 | (!stationTemplate?.Connectors[connectorId] || |
1537 | this.getUseConnectorId0(stationTemplate) === false) | |
269196a8 JB |
1538 | ) { |
1539 | continue; | |
1540 | } | |
1541 | const templateConnectorId = | |
cda5d0fb | 1542 | connectorId > 0 && stationTemplate?.randomConnectors |
9bf0ef23 | 1543 | ? getRandomInteger(templateMaxAvailableConnectors, 1) |
269196a8 | 1544 | : connectorId; |
cda5d0fb | 1545 | const connectorStatus = stationTemplate?.Connectors[templateConnectorId]; |
fba11dc6 | 1546 | checkStationInfoConnectorStatus( |
ae25f265 | 1547 | templateConnectorId, |
04b1261c JB |
1548 | connectorStatus, |
1549 | this.logPrefix(), | |
5edd8ba0 | 1550 | this.templateFile, |
04b1261c | 1551 | ); |
9bf0ef23 | 1552 | this.connectors.set(connectorId, cloneObject<ConnectorStatus>(connectorStatus)); |
3d25cc86 | 1553 | } |
fba11dc6 | 1554 | initializeConnectorsMapStatus(this.connectors, this.logPrefix()); |
52952bf8 | 1555 | this.saveConnectorsStatus(); |
ae25f265 JB |
1556 | } else { |
1557 | logger.warn( | |
1558 | `${this.logPrefix()} Charging station information from template ${ | |
1559 | this.templateFile | |
5edd8ba0 | 1560 | } with no connectors configuration defined, cannot create connectors`, |
ae25f265 | 1561 | ); |
3d25cc86 JB |
1562 | } |
1563 | } | |
1564 | } else { | |
1565 | logger.warn( | |
1566 | `${this.logPrefix()} Charging station information from template ${ | |
1567 | this.templateFile | |
5edd8ba0 | 1568 | } with no connectors configuration defined, using already defined connectors`, |
3d25cc86 JB |
1569 | ); |
1570 | } | |
3d25cc86 JB |
1571 | } |
1572 | ||
34eeb1fb | 1573 | private initializeEvsesFromTemplate(stationTemplate: ChargingStationTemplate): void { |
cda5d0fb | 1574 | if (!stationTemplate?.Evses && this.evses.size === 0) { |
ded57f02 JB |
1575 | const errorMsg = `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`; |
1576 | logger.error(`${this.logPrefix()} ${errorMsg}`); | |
1577 | throw new BaseError(errorMsg); | |
2585c6e9 | 1578 | } |
e1d9a0f4 | 1579 | if (!stationTemplate?.Evses?.[0]) { |
2585c6e9 JB |
1580 | logger.warn( |
1581 | `${this.logPrefix()} Charging station information from template ${ | |
1582 | this.templateFile | |
5edd8ba0 | 1583 | } with no evse id 0 configuration`, |
2585c6e9 JB |
1584 | ); |
1585 | } | |
e1d9a0f4 | 1586 | if (!stationTemplate?.Evses?.[0]?.Connectors?.[0]) { |
59a0f26d JB |
1587 | logger.warn( |
1588 | `${this.logPrefix()} Charging station information from template ${ | |
1589 | this.templateFile | |
5edd8ba0 | 1590 | } with evse id 0 with no connector id 0 configuration`, |
59a0f26d JB |
1591 | ); |
1592 | } | |
cda5d0fb | 1593 | if (stationTemplate?.Evses) { |
d972af76 | 1594 | const evsesConfigHash = createHash(Constants.DEFAULT_HASH_ALGORITHM) |
ba01a213 | 1595 | .update(JSON.stringify(stationTemplate?.Evses)) |
2585c6e9 JB |
1596 | .digest('hex'); |
1597 | const evsesConfigChanged = | |
1598 | this.evses?.size !== 0 && this.evsesConfigurationHash !== evsesConfigHash; | |
1599 | if (this.evses?.size === 0 || evsesConfigChanged) { | |
1600 | evsesConfigChanged && this.evses.clear(); | |
1601 | this.evsesConfigurationHash = evsesConfigHash; | |
fba11dc6 | 1602 | const templateMaxEvses = getMaxNumberOfEvses(stationTemplate?.Evses); |
ae25f265 | 1603 | if (templateMaxEvses > 0) { |
cda5d0fb | 1604 | for (const evse in stationTemplate.Evses) { |
9bf0ef23 | 1605 | const evseId = convertToInt(evse); |
52952bf8 | 1606 | this.evses.set(evseId, { |
fba11dc6 | 1607 | connectors: buildConnectorsMap( |
cda5d0fb | 1608 | stationTemplate?.Evses[evse]?.Connectors, |
ae25f265 | 1609 | this.logPrefix(), |
5edd8ba0 | 1610 | this.templateFile, |
ae25f265 JB |
1611 | ), |
1612 | availability: AvailabilityType.Operative, | |
1613 | }); | |
e1d9a0f4 | 1614 | initializeConnectorsMapStatus(this.evses.get(evseId)!.connectors, this.logPrefix()); |
ae25f265 | 1615 | } |
52952bf8 | 1616 | this.saveEvsesStatus(); |
ae25f265 JB |
1617 | } else { |
1618 | logger.warn( | |
1619 | `${this.logPrefix()} Charging station information from template ${ | |
04b1261c | 1620 | this.templateFile |
5edd8ba0 | 1621 | } with no evses configuration defined, cannot create evses`, |
04b1261c | 1622 | ); |
2585c6e9 JB |
1623 | } |
1624 | } | |
513db108 JB |
1625 | } else { |
1626 | logger.warn( | |
1627 | `${this.logPrefix()} Charging station information from template ${ | |
1628 | this.templateFile | |
5edd8ba0 | 1629 | } with no evses configuration defined, using already defined evses`, |
513db108 | 1630 | ); |
2585c6e9 JB |
1631 | } |
1632 | } | |
1633 | ||
551e477c JB |
1634 | private getConfigurationFromFile(): ChargingStationConfiguration | undefined { |
1635 | let configuration: ChargingStationConfiguration | undefined; | |
9bf0ef23 | 1636 | if (isNotEmptyString(this.configurationFile) && existsSync(this.configurationFile)) { |
073bd098 | 1637 | try { |
57adbebc JB |
1638 | if (this.sharedLRUCache.hasChargingStationConfiguration(this.configurationFileHash)) { |
1639 | configuration = this.sharedLRUCache.getChargingStationConfiguration( | |
5edd8ba0 | 1640 | this.configurationFileHash, |
57adbebc | 1641 | ); |
7c72977b JB |
1642 | } else { |
1643 | const measureId = `${FileType.ChargingStationConfiguration} read`; | |
1644 | const beginId = PerformanceStatistics.beginMeasure(measureId); | |
1645 | configuration = JSON.parse( | |
5edd8ba0 | 1646 | readFileSync(this.configurationFile, 'utf8'), |
7c72977b JB |
1647 | ) as ChargingStationConfiguration; |
1648 | PerformanceStatistics.endMeasure(measureId, beginId); | |
57adbebc | 1649 | this.sharedLRUCache.setChargingStationConfiguration(configuration); |
e1d9a0f4 | 1650 | this.configurationFileHash = configuration.configurationHash!; |
7c72977b | 1651 | } |
073bd098 | 1652 | } catch (error) { |
fa5995d6 | 1653 | handleFileException( |
073bd098 | 1654 | this.configurationFile, |
7164966d JB |
1655 | FileType.ChargingStationConfiguration, |
1656 | error as NodeJS.ErrnoException, | |
5edd8ba0 | 1657 | this.logPrefix(), |
073bd098 JB |
1658 | ); |
1659 | } | |
1660 | } | |
1661 | return configuration; | |
1662 | } | |
1663 | ||
cb60061f | 1664 | private saveAutomaticTransactionGeneratorConfiguration(): void { |
5ced7e80 JB |
1665 | if (this.getAutomaticTransactionGeneratorPersistentConfiguration()) { |
1666 | this.saveConfiguration(); | |
1667 | } | |
ac7f79af JB |
1668 | } |
1669 | ||
52952bf8 | 1670 | private saveConnectorsStatus() { |
7446de3b | 1671 | this.saveConfiguration(); |
52952bf8 JB |
1672 | } |
1673 | ||
1674 | private saveEvsesStatus() { | |
7446de3b | 1675 | this.saveConfiguration(); |
52952bf8 JB |
1676 | } |
1677 | ||
179ed367 | 1678 | private saveConfiguration(): void { |
9bf0ef23 | 1679 | if (isNotEmptyString(this.configurationFile)) { |
2484ac1e | 1680 | try { |
d972af76 JB |
1681 | if (!existsSync(dirname(this.configurationFile))) { |
1682 | mkdirSync(dirname(this.configurationFile), { recursive: true }); | |
073bd098 | 1683 | } |
ae8ceef3 JB |
1684 | let configurationData: ChargingStationConfiguration = this.getConfigurationFromFile() |
1685 | ? cloneObject<ChargingStationConfiguration>(this.getConfigurationFromFile()!) | |
1686 | : {}; | |
34eeb1fb | 1687 | if (this.getStationInfoPersistentConfiguration() && this.stationInfo) { |
52952bf8 | 1688 | configurationData.stationInfo = this.stationInfo; |
5ced7e80 JB |
1689 | } else { |
1690 | delete configurationData.stationInfo; | |
52952bf8 | 1691 | } |
34eeb1fb | 1692 | if (this.getOcppPersistentConfiguration() && this.ocppConfiguration?.configurationKey) { |
52952bf8 | 1693 | configurationData.configurationKey = this.ocppConfiguration.configurationKey; |
5ced7e80 JB |
1694 | } else { |
1695 | delete configurationData.configurationKey; | |
52952bf8 | 1696 | } |
179ed367 JB |
1697 | configurationData = merge<ChargingStationConfiguration>( |
1698 | configurationData, | |
5edd8ba0 | 1699 | buildChargingStationAutomaticTransactionGeneratorConfiguration(this), |
179ed367 | 1700 | ); |
5ced7e80 JB |
1701 | if ( |
1702 | !this.getAutomaticTransactionGeneratorPersistentConfiguration() || | |
1703 | !this.getAutomaticTransactionGeneratorConfiguration() | |
1704 | ) { | |
1705 | delete configurationData.automaticTransactionGenerator; | |
1706 | } | |
b1bbdae5 | 1707 | if (this.connectors.size > 0) { |
179ed367 | 1708 | configurationData.connectorsStatus = buildConnectorsStatus(this); |
5ced7e80 JB |
1709 | } else { |
1710 | delete configurationData.connectorsStatus; | |
52952bf8 | 1711 | } |
b1bbdae5 | 1712 | if (this.evses.size > 0) { |
179ed367 | 1713 | configurationData.evsesStatus = buildEvsesStatus(this); |
5ced7e80 JB |
1714 | } else { |
1715 | delete configurationData.evsesStatus; | |
52952bf8 | 1716 | } |
7c72977b | 1717 | delete configurationData.configurationHash; |
d972af76 | 1718 | const configurationHash = createHash(Constants.DEFAULT_HASH_ALGORITHM) |
5ced7e80 JB |
1719 | .update( |
1720 | JSON.stringify({ | |
1721 | stationInfo: configurationData.stationInfo, | |
1722 | configurationKey: configurationData.configurationKey, | |
1723 | automaticTransactionGenerator: configurationData.automaticTransactionGenerator, | |
5edd8ba0 | 1724 | } as ChargingStationConfiguration), |
5ced7e80 | 1725 | ) |
7c72977b JB |
1726 | .digest('hex'); |
1727 | if (this.configurationFileHash !== configurationHash) { | |
dd485b56 | 1728 | AsyncLock.acquire(AsyncLockType.configuration) |
1227a6f1 JB |
1729 | .then(() => { |
1730 | configurationData.configurationHash = configurationHash; | |
1731 | const measureId = `${FileType.ChargingStationConfiguration} write`; | |
1732 | const beginId = PerformanceStatistics.beginMeasure(measureId); | |
d972af76 JB |
1733 | const fileDescriptor = openSync(this.configurationFile, 'w'); |
1734 | writeFileSync(fileDescriptor, JSON.stringify(configurationData, null, 2), 'utf8'); | |
1735 | closeSync(fileDescriptor); | |
1227a6f1 JB |
1736 | PerformanceStatistics.endMeasure(measureId, beginId); |
1737 | this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash); | |
1738 | this.sharedLRUCache.setChargingStationConfiguration(configurationData); | |
1739 | this.configurationFileHash = configurationHash; | |
1740 | }) | |
1741 | .catch((error) => { | |
fa5995d6 | 1742 | handleFileException( |
1227a6f1 JB |
1743 | this.configurationFile, |
1744 | FileType.ChargingStationConfiguration, | |
1745 | error as NodeJS.ErrnoException, | |
5edd8ba0 | 1746 | this.logPrefix(), |
1227a6f1 JB |
1747 | ); |
1748 | }) | |
1749 | .finally(() => { | |
dd485b56 | 1750 | AsyncLock.release(AsyncLockType.configuration).catch(Constants.EMPTY_FUNCTION); |
1227a6f1 | 1751 | }); |
7c72977b JB |
1752 | } else { |
1753 | logger.debug( | |
1754 | `${this.logPrefix()} Not saving unchanged charging station configuration file ${ | |
1755 | this.configurationFile | |
5edd8ba0 | 1756 | }`, |
7c72977b | 1757 | ); |
2484ac1e | 1758 | } |
2484ac1e | 1759 | } catch (error) { |
fa5995d6 | 1760 | handleFileException( |
2484ac1e | 1761 | this.configurationFile, |
7164966d JB |
1762 | FileType.ChargingStationConfiguration, |
1763 | error as NodeJS.ErrnoException, | |
5edd8ba0 | 1764 | this.logPrefix(), |
073bd098 JB |
1765 | ); |
1766 | } | |
2484ac1e JB |
1767 | } else { |
1768 | logger.error( | |
5edd8ba0 | 1769 | `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`, |
2484ac1e | 1770 | ); |
073bd098 JB |
1771 | } |
1772 | } | |
1773 | ||
551e477c JB |
1774 | private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration | undefined { |
1775 | return this.getTemplateFromFile()?.Configuration; | |
2484ac1e JB |
1776 | } |
1777 | ||
551e477c | 1778 | private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | undefined { |
60655b26 JB |
1779 | const configurationKey = this.getConfigurationFromFile()?.configurationKey; |
1780 | if (this.getOcppPersistentConfiguration() === true && configurationKey) { | |
1781 | return { configurationKey }; | |
648512ce | 1782 | } |
60655b26 | 1783 | return undefined; |
7dde0b73 JB |
1784 | } |
1785 | ||
551e477c JB |
1786 | private getOcppConfiguration(): ChargingStationOcppConfiguration | undefined { |
1787 | let ocppConfiguration: ChargingStationOcppConfiguration | undefined = | |
72092cfc | 1788 | this.getOcppConfigurationFromFile(); |
2484ac1e JB |
1789 | if (!ocppConfiguration) { |
1790 | ocppConfiguration = this.getOcppConfigurationFromTemplate(); | |
1791 | } | |
1792 | return ocppConfiguration; | |
1793 | } | |
1794 | ||
c0560973 | 1795 | private async onOpen(): Promise<void> { |
56eb297e | 1796 | if (this.isWebSocketConnectionOpened() === true) { |
5144f4d1 | 1797 | logger.info( |
5edd8ba0 | 1798 | `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`, |
5144f4d1 | 1799 | ); |
ed6cfcff | 1800 | if (this.isRegistered() === false) { |
5144f4d1 JB |
1801 | // Send BootNotification |
1802 | let registrationRetryCount = 0; | |
1803 | do { | |
f7f98c68 | 1804 | this.bootNotificationResponse = await this.ocppRequestService.requestHandler< |
5144f4d1 JB |
1805 | BootNotificationRequest, |
1806 | BootNotificationResponse | |
8bfbc743 JB |
1807 | >(this, RequestCommand.BOOT_NOTIFICATION, this.bootNotificationRequest, { |
1808 | skipBufferingOnError: true, | |
1809 | }); | |
ed6cfcff | 1810 | if (this.isRegistered() === false) { |
1fe0632a | 1811 | this.getRegistrationMaxRetries() !== -1 && ++registrationRetryCount; |
9bf0ef23 | 1812 | await sleep( |
1895299d | 1813 | this?.bootNotificationResponse?.interval |
be4c6702 | 1814 | ? secondsToMilliseconds(this.bootNotificationResponse.interval) |
5edd8ba0 | 1815 | : Constants.DEFAULT_BOOT_NOTIFICATION_INTERVAL, |
5144f4d1 JB |
1816 | ); |
1817 | } | |
1818 | } while ( | |
ed6cfcff | 1819 | this.isRegistered() === false && |
e1d9a0f4 | 1820 | (registrationRetryCount <= this.getRegistrationMaxRetries()! || |
5144f4d1 JB |
1821 | this.getRegistrationMaxRetries() === -1) |
1822 | ); | |
1823 | } | |
ed6cfcff | 1824 | if (this.isRegistered() === true) { |
f7c2994d | 1825 | if (this.inAcceptedState() === true) { |
94bb24d5 | 1826 | await this.startMessageSequence(); |
c0560973 | 1827 | } |
5144f4d1 JB |
1828 | } else { |
1829 | logger.error( | |
5edd8ba0 | 1830 | `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`, |
5144f4d1 | 1831 | ); |
caad9d6b | 1832 | } |
5144f4d1 | 1833 | this.wsConnectionRestarted = false; |
aa428a31 | 1834 | this.autoReconnectRetryCount = 0; |
c8faabc8 | 1835 | parentPort?.postMessage(buildUpdatedMessage(this)); |
2e6f5966 | 1836 | } else { |
5144f4d1 | 1837 | logger.warn( |
5edd8ba0 | 1838 | `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`, |
e7aeea18 | 1839 | ); |
2e6f5966 | 1840 | } |
2e6f5966 JB |
1841 | } |
1842 | ||
ef7d8c21 | 1843 | private async onClose(code: number, reason: Buffer): Promise<void> { |
d09085e9 | 1844 | switch (code) { |
6c65a295 JB |
1845 | // Normal close |
1846 | case WebSocketCloseEventStatusCode.CLOSE_NORMAL: | |
c0560973 | 1847 | case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS: |
e7aeea18 | 1848 | logger.info( |
9bf0ef23 | 1849 | `${this.logPrefix()} WebSocket normally closed with status '${getWebSocketCloseEventStatusString( |
5edd8ba0 JB |
1850 | code, |
1851 | )}' and reason '${reason.toString()}'`, | |
e7aeea18 | 1852 | ); |
c0560973 JB |
1853 | this.autoReconnectRetryCount = 0; |
1854 | break; | |
6c65a295 JB |
1855 | // Abnormal close |
1856 | default: | |
e7aeea18 | 1857 | logger.error( |
9bf0ef23 | 1858 | `${this.logPrefix()} WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString( |
5edd8ba0 JB |
1859 | code, |
1860 | )}' and reason '${reason.toString()}'`, | |
e7aeea18 | 1861 | ); |
56eb297e | 1862 | this.started === true && (await this.reconnect()); |
c0560973 JB |
1863 | break; |
1864 | } | |
c8faabc8 | 1865 | parentPort?.postMessage(buildUpdatedMessage(this)); |
2e6f5966 JB |
1866 | } |
1867 | ||
56d09fd7 JB |
1868 | private getCachedRequest(messageType: MessageType, messageId: string): CachedRequest | undefined { |
1869 | const cachedRequest = this.requests.get(messageId); | |
1870 | if (Array.isArray(cachedRequest) === true) { | |
1871 | return cachedRequest; | |
1872 | } | |
1873 | throw new OCPPError( | |
1874 | ErrorType.PROTOCOL_ERROR, | |
1875 | `Cached request for message id ${messageId} ${OCPPServiceUtils.getMessageTypeString( | |
5edd8ba0 | 1876 | messageType, |
56d09fd7 JB |
1877 | )} is not an array`, |
1878 | undefined, | |
5edd8ba0 | 1879 | cachedRequest as JsonType, |
56d09fd7 JB |
1880 | ); |
1881 | } | |
1882 | ||
1883 | private async handleIncomingMessage(request: IncomingRequest): Promise<void> { | |
1884 | const [messageType, messageId, commandName, commandPayload] = request; | |
1885 | if (this.getEnableStatistics() === true) { | |
1886 | this.performanceStatistics?.addRequestStatistic(commandName, messageType); | |
1887 | } | |
1888 | logger.debug( | |
1889 | `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify( | |
5edd8ba0 JB |
1890 | request, |
1891 | )}`, | |
56d09fd7 JB |
1892 | ); |
1893 | // Process the message | |
1894 | await this.ocppIncomingRequestService.incomingRequestHandler( | |
1895 | this, | |
1896 | messageId, | |
1897 | commandName, | |
5edd8ba0 | 1898 | commandPayload, |
56d09fd7 JB |
1899 | ); |
1900 | } | |
1901 | ||
1902 | private handleResponseMessage(response: Response): void { | |
1903 | const [messageType, messageId, commandPayload] = response; | |
1904 | if (this.requests.has(messageId) === false) { | |
1905 | // Error | |
1906 | throw new OCPPError( | |
1907 | ErrorType.INTERNAL_ERROR, | |
1908 | `Response for unknown message id ${messageId}`, | |
1909 | undefined, | |
5edd8ba0 | 1910 | commandPayload, |
56d09fd7 JB |
1911 | ); |
1912 | } | |
1913 | // Respond | |
1914 | const [responseCallback, , requestCommandName, requestPayload] = this.getCachedRequest( | |
1915 | messageType, | |
5edd8ba0 | 1916 | messageId, |
e1d9a0f4 | 1917 | )!; |
56d09fd7 JB |
1918 | logger.debug( |
1919 | `${this.logPrefix()} << Command '${ | |
1920 | requestCommandName ?? Constants.UNKNOWN_COMMAND | |
5edd8ba0 | 1921 | }' received response payload: ${JSON.stringify(response)}`, |
56d09fd7 JB |
1922 | ); |
1923 | responseCallback(commandPayload, requestPayload); | |
1924 | } | |
1925 | ||
1926 | private handleErrorMessage(errorResponse: ErrorResponse): void { | |
1927 | const [messageType, messageId, errorType, errorMessage, errorDetails] = errorResponse; | |
1928 | if (this.requests.has(messageId) === false) { | |
1929 | // Error | |
1930 | throw new OCPPError( | |
1931 | ErrorType.INTERNAL_ERROR, | |
1932 | `Error response for unknown message id ${messageId}`, | |
1933 | undefined, | |
5edd8ba0 | 1934 | { errorType, errorMessage, errorDetails }, |
56d09fd7 JB |
1935 | ); |
1936 | } | |
e1d9a0f4 | 1937 | const [, errorCallback, requestCommandName] = this.getCachedRequest(messageType, messageId)!; |
56d09fd7 JB |
1938 | logger.debug( |
1939 | `${this.logPrefix()} << Command '${ | |
1940 | requestCommandName ?? Constants.UNKNOWN_COMMAND | |
5edd8ba0 | 1941 | }' received error response payload: ${JSON.stringify(errorResponse)}`, |
56d09fd7 JB |
1942 | ); |
1943 | errorCallback(new OCPPError(errorType, errorMessage, requestCommandName, errorDetails)); | |
1944 | } | |
1945 | ||
ef7d8c21 | 1946 | private async onMessage(data: RawData): Promise<void> { |
e1d9a0f4 JB |
1947 | let request: IncomingRequest | Response | ErrorResponse | undefined; |
1948 | let messageType: number | undefined; | |
ded57f02 | 1949 | let errorMsg: string; |
c0560973 | 1950 | try { |
e1d9a0f4 | 1951 | // eslint-disable-next-line @typescript-eslint/no-base-to-string |
56d09fd7 | 1952 | request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse; |
53e5fd67 | 1953 | if (Array.isArray(request) === true) { |
56d09fd7 | 1954 | [messageType] = request; |
b3ec7bc1 JB |
1955 | // Check the type of message |
1956 | switch (messageType) { | |
1957 | // Incoming Message | |
1958 | case MessageType.CALL_MESSAGE: | |
56d09fd7 | 1959 | await this.handleIncomingMessage(request as IncomingRequest); |
b3ec7bc1 | 1960 | break; |
56d09fd7 | 1961 | // Response Message |
b3ec7bc1 | 1962 | case MessageType.CALL_RESULT_MESSAGE: |
56d09fd7 | 1963 | this.handleResponseMessage(request as Response); |
a2d1c0f1 JB |
1964 | break; |
1965 | // Error Message | |
1966 | case MessageType.CALL_ERROR_MESSAGE: | |
56d09fd7 | 1967 | this.handleErrorMessage(request as ErrorResponse); |
b3ec7bc1 | 1968 | break; |
56d09fd7 | 1969 | // Unknown Message |
b3ec7bc1 JB |
1970 | default: |
1971 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions | |
ded57f02 JB |
1972 | errorMsg = `Wrong message type ${messageType}`; |
1973 | logger.error(`${this.logPrefix()} ${errorMsg}`); | |
1974 | throw new OCPPError(ErrorType.PROTOCOL_ERROR, errorMsg); | |
b3ec7bc1 | 1975 | } |
c8faabc8 | 1976 | parentPort?.postMessage(buildUpdatedMessage(this)); |
47e22477 | 1977 | } else { |
e1d9a0f4 JB |
1978 | throw new OCPPError( |
1979 | ErrorType.PROTOCOL_ERROR, | |
1980 | 'Incoming message is not an array', | |
1981 | undefined, | |
1982 | { | |
1983 | request, | |
1984 | }, | |
1985 | ); | |
47e22477 | 1986 | } |
c0560973 | 1987 | } catch (error) { |
e1d9a0f4 JB |
1988 | let commandName: IncomingRequestCommand | undefined; |
1989 | let requestCommandName: RequestCommand | IncomingRequestCommand | undefined; | |
56d09fd7 | 1990 | let errorCallback: ErrorCallback; |
e1d9a0f4 | 1991 | const [, messageId] = request!; |
13701f69 JB |
1992 | switch (messageType) { |
1993 | case MessageType.CALL_MESSAGE: | |
56d09fd7 | 1994 | [, , commandName] = request as IncomingRequest; |
13701f69 | 1995 | // Send error |
56d09fd7 | 1996 | await this.ocppRequestService.sendError(this, messageId, error as OCPPError, commandName); |
13701f69 JB |
1997 | break; |
1998 | case MessageType.CALL_RESULT_MESSAGE: | |
1999 | case MessageType.CALL_ERROR_MESSAGE: | |
56d09fd7 | 2000 | if (this.requests.has(messageId) === true) { |
e1d9a0f4 | 2001 | [, errorCallback, requestCommandName] = this.getCachedRequest(messageType, messageId)!; |
13701f69 JB |
2002 | // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op) |
2003 | errorCallback(error as OCPPError, false); | |
2004 | } else { | |
2005 | // Remove the request from the cache in case of error at response handling | |
2006 | this.requests.delete(messageId); | |
2007 | } | |
de4cb8b6 | 2008 | break; |
ba7965c4 | 2009 | } |
56d09fd7 JB |
2010 | if (error instanceof OCPPError === false) { |
2011 | logger.warn( | |
2012 | `${this.logPrefix()} Error thrown at incoming OCPP command '${ | |
2013 | commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND | |
e1d9a0f4 | 2014 | // eslint-disable-next-line @typescript-eslint/no-base-to-string |
56d09fd7 | 2015 | }' message '${data.toString()}' handling is not an OCPPError:`, |
5edd8ba0 | 2016 | error, |
56d09fd7 JB |
2017 | ); |
2018 | } | |
2019 | logger.error( | |
2020 | `${this.logPrefix()} Incoming OCPP command '${ | |
2021 | commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND | |
e1d9a0f4 | 2022 | // eslint-disable-next-line @typescript-eslint/no-base-to-string |
56d09fd7 JB |
2023 | }' message '${data.toString()}'${ |
2024 | messageType !== MessageType.CALL_MESSAGE | |
2025 | ? ` matching cached request '${JSON.stringify(this.requests.get(messageId))}'` | |
2026 | : '' | |
2027 | } processing error:`, | |
5edd8ba0 | 2028 | error, |
56d09fd7 | 2029 | ); |
c0560973 | 2030 | } |
2328be1e JB |
2031 | } |
2032 | ||
c0560973 | 2033 | private onPing(): void { |
44eb6026 | 2034 | logger.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`); |
c0560973 JB |
2035 | } |
2036 | ||
2037 | private onPong(): void { | |
44eb6026 | 2038 | logger.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`); |
c0560973 JB |
2039 | } |
2040 | ||
9534e74e | 2041 | private onError(error: WSError): void { |
bcc9c3c0 | 2042 | this.closeWSConnection(); |
44eb6026 | 2043 | logger.error(`${this.logPrefix()} WebSocket error:`, error); |
c0560973 JB |
2044 | } |
2045 | ||
18bf8274 | 2046 | private getEnergyActiveImportRegister(connectorStatus: ConnectorStatus, rounded = false): number { |
95bdbf12 | 2047 | if (this.getMeteringPerTransaction() === true) { |
07989fad | 2048 | return ( |
18bf8274 | 2049 | (rounded === true |
e1d9a0f4 | 2050 | ? Math.round(connectorStatus.transactionEnergyActiveImportRegisterValue!) |
07989fad JB |
2051 | : connectorStatus?.transactionEnergyActiveImportRegisterValue) ?? 0 |
2052 | ); | |
2053 | } | |
2054 | return ( | |
18bf8274 | 2055 | (rounded === true |
e1d9a0f4 | 2056 | ? Math.round(connectorStatus.energyActiveImportRegisterValue!) |
07989fad JB |
2057 | : connectorStatus?.energyActiveImportRegisterValue) ?? 0 |
2058 | ); | |
2059 | } | |
2060 | ||
cda5d0fb JB |
2061 | private getUseConnectorId0(stationTemplate?: ChargingStationTemplate): boolean { |
2062 | return stationTemplate?.useConnectorId0 ?? true; | |
8bce55bf JB |
2063 | } |
2064 | ||
60ddad53 | 2065 | private async stopRunningTransactions(reason = StopTransactionReason.NONE): Promise<void> { |
28e78158 | 2066 | if (this.hasEvses) { |
3fa7f799 JB |
2067 | for (const [evseId, evseStatus] of this.evses) { |
2068 | if (evseId === 0) { | |
2069 | continue; | |
2070 | } | |
28e78158 JB |
2071 | for (const [connectorId, connectorStatus] of evseStatus.connectors) { |
2072 | if (connectorStatus.transactionStarted === true) { | |
2073 | await this.stopTransactionOnConnector(connectorId, reason); | |
2074 | } | |
2075 | } | |
2076 | } | |
2077 | } else { | |
2078 | for (const connectorId of this.connectors.keys()) { | |
2079 | if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted === true) { | |
2080 | await this.stopTransactionOnConnector(connectorId, reason); | |
2081 | } | |
60ddad53 JB |
2082 | } |
2083 | } | |
2084 | } | |
2085 | ||
1f761b9a | 2086 | // 0 for disabling |
c72f6634 | 2087 | private getConnectionTimeout(): number { |
f2d5e3d9 | 2088 | if (getConfigurationKey(this, StandardParametersKey.ConnectionTimeOut)) { |
e7aeea18 | 2089 | return ( |
f2d5e3d9 JB |
2090 | parseInt(getConfigurationKey(this, StandardParametersKey.ConnectionTimeOut)!.value!) ?? |
2091 | Constants.DEFAULT_CONNECTION_TIMEOUT | |
e7aeea18 | 2092 | ); |
291cb255 | 2093 | } |
291cb255 | 2094 | return Constants.DEFAULT_CONNECTION_TIMEOUT; |
3574dfd3 JB |
2095 | } |
2096 | ||
1f761b9a | 2097 | // -1 for unlimited, 0 for disabling |
72092cfc | 2098 | private getAutoReconnectMaxRetries(): number | undefined { |
b1bbdae5 JB |
2099 | return ( |
2100 | this.stationInfo.autoReconnectMaxRetries ?? Configuration.getAutoReconnectMaxRetries() ?? -1 | |
2101 | ); | |
3574dfd3 JB |
2102 | } |
2103 | ||
ec977daf | 2104 | // 0 for disabling |
72092cfc | 2105 | private getRegistrationMaxRetries(): number | undefined { |
b1bbdae5 | 2106 | return this.stationInfo.registrationMaxRetries ?? -1; |
32a1eb7a JB |
2107 | } |
2108 | ||
c0560973 | 2109 | private getPowerDivider(): number { |
b1bbdae5 | 2110 | let powerDivider = this.hasEvses ? this.getNumberOfEvses() : this.getNumberOfConnectors(); |
fa7bccf4 | 2111 | if (this.stationInfo?.powerSharedByConnectors) { |
c0560973 | 2112 | powerDivider = this.getNumberOfRunningTransactions(); |
6ecb15e4 JB |
2113 | } |
2114 | return powerDivider; | |
2115 | } | |
2116 | ||
fa7bccf4 JB |
2117 | private getMaximumAmperage(stationInfo: ChargingStationInfo): number | undefined { |
2118 | const maximumPower = this.getMaximumPower(stationInfo); | |
2119 | switch (this.getCurrentOutType(stationInfo)) { | |
cc6e8ab5 JB |
2120 | case CurrentType.AC: |
2121 | return ACElectricUtils.amperagePerPhaseFromPower( | |
fa7bccf4 | 2122 | this.getNumberOfPhases(stationInfo), |
b1bbdae5 | 2123 | maximumPower / (this.hasEvses ? this.getNumberOfEvses() : this.getNumberOfConnectors()), |
5edd8ba0 | 2124 | this.getVoltageOut(stationInfo), |
cc6e8ab5 JB |
2125 | ); |
2126 | case CurrentType.DC: | |
fa7bccf4 | 2127 | return DCElectricUtils.amperage(maximumPower, this.getVoltageOut(stationInfo)); |
cc6e8ab5 JB |
2128 | } |
2129 | } | |
2130 | ||
cc6e8ab5 JB |
2131 | private getAmperageLimitation(): number | undefined { |
2132 | if ( | |
9bf0ef23 | 2133 | isNotEmptyString(this.stationInfo?.amperageLimitationOcppKey) && |
f2d5e3d9 | 2134 | getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey!) |
cc6e8ab5 JB |
2135 | ) { |
2136 | return ( | |
9bf0ef23 | 2137 | convertToInt( |
f2d5e3d9 | 2138 | getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey!)?.value, |
fba11dc6 | 2139 | ) / getAmperageLimitationUnitDivider(this.stationInfo) |
cc6e8ab5 JB |
2140 | ); |
2141 | } | |
2142 | } | |
2143 | ||
c0560973 | 2144 | private async startMessageSequence(): Promise<void> { |
b7f9e41d | 2145 | if (this.stationInfo?.autoRegister === true) { |
f7f98c68 | 2146 | await this.ocppRequestService.requestHandler< |
ef6fa3fb JB |
2147 | BootNotificationRequest, |
2148 | BootNotificationResponse | |
8bfbc743 JB |
2149 | >(this, RequestCommand.BOOT_NOTIFICATION, this.bootNotificationRequest, { |
2150 | skipBufferingOnError: true, | |
2151 | }); | |
6114e6f1 | 2152 | } |
136c90ba | 2153 | // Start WebSocket ping |
c0560973 | 2154 | this.startWebSocketPing(); |
5ad8570f | 2155 | // Start heartbeat |
c0560973 | 2156 | this.startHeartbeat(); |
0a60c33c | 2157 | // Initialize connectors status |
c3b83130 JB |
2158 | if (this.hasEvses) { |
2159 | for (const [evseId, evseStatus] of this.evses) { | |
4334db72 JB |
2160 | if (evseId > 0) { |
2161 | for (const [connectorId, connectorStatus] of evseStatus.connectors) { | |
fba11dc6 | 2162 | const connectorBootStatus = getBootConnectorStatus(this, connectorId, connectorStatus); |
4334db72 JB |
2163 | await OCPPServiceUtils.sendAndSetConnectorStatus( |
2164 | this, | |
2165 | connectorId, | |
12f26d4a | 2166 | connectorBootStatus, |
5edd8ba0 | 2167 | evseId, |
4334db72 JB |
2168 | ); |
2169 | } | |
c3b83130 | 2170 | } |
4334db72 JB |
2171 | } |
2172 | } else { | |
2173 | for (const connectorId of this.connectors.keys()) { | |
2174 | if (connectorId > 0) { | |
fba11dc6 | 2175 | const connectorBootStatus = getBootConnectorStatus( |
c3b83130 JB |
2176 | this, |
2177 | connectorId, | |
e1d9a0f4 | 2178 | this.getConnectorStatus(connectorId)!, |
c3b83130 JB |
2179 | ); |
2180 | await OCPPServiceUtils.sendAndSetConnectorStatus(this, connectorId, connectorBootStatus); | |
2181 | } | |
2182 | } | |
5ad8570f | 2183 | } |
c9a4f9ea JB |
2184 | if (this.stationInfo?.firmwareStatus === FirmwareStatus.Installing) { |
2185 | await this.ocppRequestService.requestHandler< | |
2186 | FirmwareStatusNotificationRequest, | |
2187 | FirmwareStatusNotificationResponse | |
2188 | >(this, RequestCommand.FIRMWARE_STATUS_NOTIFICATION, { | |
2189 | status: FirmwareStatus.Installed, | |
2190 | }); | |
2191 | this.stationInfo.firmwareStatus = FirmwareStatus.Installed; | |
c9a4f9ea | 2192 | } |
3637ca2c | 2193 | |
0a60c33c | 2194 | // Start the ATG |
ac7f79af | 2195 | if (this.getAutomaticTransactionGeneratorConfiguration()?.enable === true) { |
4f69be04 | 2196 | this.startAutomaticTransactionGenerator(); |
fa7bccf4 | 2197 | } |
aa428a31 | 2198 | this.wsConnectionRestarted === true && this.flushMessageBuffer(); |
fa7bccf4 JB |
2199 | } |
2200 | ||
e7aeea18 | 2201 | private async stopMessageSequence( |
5edd8ba0 | 2202 | reason: StopTransactionReason = StopTransactionReason.NONE, |
e7aeea18 | 2203 | ): Promise<void> { |
136c90ba | 2204 | // Stop WebSocket ping |
c0560973 | 2205 | this.stopWebSocketPing(); |
79411696 | 2206 | // Stop heartbeat |
c0560973 | 2207 | this.stopHeartbeat(); |
fa7bccf4 | 2208 | // Stop ongoing transactions |
b20eb107 | 2209 | if (this.automaticTransactionGenerator?.started === true) { |
60ddad53 JB |
2210 | this.stopAutomaticTransactionGenerator(); |
2211 | } else { | |
2212 | await this.stopRunningTransactions(reason); | |
79411696 | 2213 | } |
039211f9 JB |
2214 | if (this.hasEvses) { |
2215 | for (const [evseId, evseStatus] of this.evses) { | |
2216 | if (evseId > 0) { | |
2217 | for (const [connectorId, connectorStatus] of evseStatus.connectors) { | |
2218 | await this.ocppRequestService.requestHandler< | |
2219 | StatusNotificationRequest, | |
2220 | StatusNotificationResponse | |
2221 | >( | |
2222 | this, | |
2223 | RequestCommand.STATUS_NOTIFICATION, | |
2224 | OCPPServiceUtils.buildStatusNotificationRequest( | |
2225 | this, | |
2226 | connectorId, | |
12f26d4a | 2227 | ConnectorStatusEnum.Unavailable, |
5edd8ba0 JB |
2228 | evseId, |
2229 | ), | |
039211f9 JB |
2230 | ); |
2231 | delete connectorStatus?.status; | |
2232 | } | |
2233 | } | |
2234 | } | |
2235 | } else { | |
2236 | for (const connectorId of this.connectors.keys()) { | |
2237 | if (connectorId > 0) { | |
2238 | await this.ocppRequestService.requestHandler< | |
2239 | StatusNotificationRequest, | |
2240 | StatusNotificationResponse | |
2241 | >( | |
6e939d9e | 2242 | this, |
039211f9 JB |
2243 | RequestCommand.STATUS_NOTIFICATION, |
2244 | OCPPServiceUtils.buildStatusNotificationRequest( | |
2245 | this, | |
2246 | connectorId, | |
5edd8ba0 JB |
2247 | ConnectorStatusEnum.Unavailable, |
2248 | ), | |
039211f9 JB |
2249 | ); |
2250 | delete this.getConnectorStatus(connectorId)?.status; | |
2251 | } | |
45c0ae82 JB |
2252 | } |
2253 | } | |
79411696 JB |
2254 | } |
2255 | ||
c0560973 | 2256 | private startWebSocketPing(): void { |
f2d5e3d9 | 2257 | const webSocketPingInterval: number = getConfigurationKey( |
17ac262c | 2258 | this, |
5edd8ba0 | 2259 | StandardParametersKey.WebSocketPingInterval, |
e7aeea18 | 2260 | ) |
f2d5e3d9 | 2261 | ? convertToInt(getConfigurationKey(this, StandardParametersKey.WebSocketPingInterval)?.value) |
9cd3dfb0 | 2262 | : 0; |
ad2f27c3 JB |
2263 | if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) { |
2264 | this.webSocketPingSetInterval = setInterval(() => { | |
56eb297e | 2265 | if (this.isWebSocketConnectionOpened() === true) { |
72092cfc | 2266 | this.wsConnection?.ping(); |
136c90ba | 2267 | } |
be4c6702 | 2268 | }, secondsToMilliseconds(webSocketPingInterval)); |
e7aeea18 | 2269 | logger.info( |
9bf0ef23 | 2270 | `${this.logPrefix()} WebSocket ping started every ${formatDurationSeconds( |
5edd8ba0 JB |
2271 | webSocketPingInterval, |
2272 | )}`, | |
e7aeea18 | 2273 | ); |
ad2f27c3 | 2274 | } else if (this.webSocketPingSetInterval) { |
e7aeea18 | 2275 | logger.info( |
9bf0ef23 | 2276 | `${this.logPrefix()} WebSocket ping already started every ${formatDurationSeconds( |
5edd8ba0 JB |
2277 | webSocketPingInterval, |
2278 | )}`, | |
e7aeea18 | 2279 | ); |
136c90ba | 2280 | } else { |
e7aeea18 | 2281 | logger.error( |
5edd8ba0 | 2282 | `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`, |
e7aeea18 | 2283 | ); |
136c90ba JB |
2284 | } |
2285 | } | |
2286 | ||
c0560973 | 2287 | private stopWebSocketPing(): void { |
ad2f27c3 JB |
2288 | if (this.webSocketPingSetInterval) { |
2289 | clearInterval(this.webSocketPingSetInterval); | |
dfe81c8f | 2290 | delete this.webSocketPingSetInterval; |
136c90ba JB |
2291 | } |
2292 | } | |
2293 | ||
1f5df42a | 2294 | private getConfiguredSupervisionUrl(): URL { |
d5c3df49 | 2295 | let configuredSupervisionUrl: string; |
72092cfc | 2296 | const supervisionUrls = this.stationInfo?.supervisionUrls ?? Configuration.getSupervisionUrls(); |
9bf0ef23 | 2297 | if (isNotEmptyArray(supervisionUrls)) { |
269de583 | 2298 | let configuredSupervisionUrlIndex: number; |
2dcfe98e | 2299 | switch (Configuration.getSupervisionUrlDistribution()) { |
2dcfe98e | 2300 | case SupervisionUrlDistribution.RANDOM: |
e1d9a0f4 JB |
2301 | configuredSupervisionUrlIndex = Math.floor( |
2302 | secureRandom() * (supervisionUrls as string[]).length, | |
2303 | ); | |
2dcfe98e | 2304 | break; |
a52a6446 | 2305 | case SupervisionUrlDistribution.ROUND_ROBIN: |
c72f6634 | 2306 | case SupervisionUrlDistribution.CHARGING_STATION_AFFINITY: |
2dcfe98e | 2307 | default: |
a52a6446 | 2308 | Object.values(SupervisionUrlDistribution).includes( |
e1d9a0f4 | 2309 | Configuration.getSupervisionUrlDistribution()!, |
a52a6446 JB |
2310 | ) === false && |
2311 | logger.error( | |
e1d9a0f4 | 2312 | // eslint-disable-next-line @typescript-eslint/no-base-to-string |
a52a6446 JB |
2313 | `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${ |
2314 | SupervisionUrlDistribution.CHARGING_STATION_AFFINITY | |
5edd8ba0 | 2315 | }`, |
a52a6446 | 2316 | ); |
e1d9a0f4 | 2317 | configuredSupervisionUrlIndex = (this.index - 1) % (supervisionUrls as string[]).length; |
2dcfe98e | 2318 | break; |
c0560973 | 2319 | } |
e1d9a0f4 | 2320 | configuredSupervisionUrl = (supervisionUrls as string[])[configuredSupervisionUrlIndex]; |
d5c3df49 JB |
2321 | } else { |
2322 | configuredSupervisionUrl = supervisionUrls as string; | |
2323 | } | |
9bf0ef23 | 2324 | if (isNotEmptyString(configuredSupervisionUrl)) { |
d5c3df49 | 2325 | return new URL(configuredSupervisionUrl); |
c0560973 | 2326 | } |
49c508b0 | 2327 | const errorMsg = 'No supervision url(s) configured'; |
7f77d16f JB |
2328 | logger.error(`${this.logPrefix()} ${errorMsg}`); |
2329 | throw new BaseError(`${errorMsg}`); | |
136c90ba JB |
2330 | } |
2331 | ||
c0560973 | 2332 | private stopHeartbeat(): void { |
ad2f27c3 JB |
2333 | if (this.heartbeatSetInterval) { |
2334 | clearInterval(this.heartbeatSetInterval); | |
dfe81c8f | 2335 | delete this.heartbeatSetInterval; |
7dde0b73 | 2336 | } |
5ad8570f JB |
2337 | } |
2338 | ||
55516218 | 2339 | private terminateWSConnection(): void { |
56eb297e | 2340 | if (this.isWebSocketConnectionOpened() === true) { |
72092cfc | 2341 | this.wsConnection?.terminate(); |
55516218 JB |
2342 | this.wsConnection = null; |
2343 | } | |
2344 | } | |
2345 | ||
c72f6634 | 2346 | private getReconnectExponentialDelay(): boolean { |
a14885a3 | 2347 | return this.stationInfo?.reconnectExponentialDelay ?? false; |
5ad8570f JB |
2348 | } |
2349 | ||
aa428a31 | 2350 | private async reconnect(): Promise<void> { |
7874b0b1 JB |
2351 | // Stop WebSocket ping |
2352 | this.stopWebSocketPing(); | |
136c90ba | 2353 | // Stop heartbeat |
c0560973 | 2354 | this.stopHeartbeat(); |
5ad8570f | 2355 | // Stop the ATG if needed |
ac7f79af | 2356 | if (this.getAutomaticTransactionGeneratorConfiguration().stopOnConnectionFailure === true) { |
fa7bccf4 | 2357 | this.stopAutomaticTransactionGenerator(); |
ad2f27c3 | 2358 | } |
e7aeea18 | 2359 | if ( |
e1d9a0f4 | 2360 | this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries()! || |
e7aeea18 JB |
2361 | this.getAutoReconnectMaxRetries() === -1 |
2362 | ) { | |
1fe0632a | 2363 | ++this.autoReconnectRetryCount; |
e7aeea18 | 2364 | const reconnectDelay = this.getReconnectExponentialDelay() |
9bf0ef23 | 2365 | ? exponentialDelay(this.autoReconnectRetryCount) |
be4c6702 | 2366 | : secondsToMilliseconds(this.getConnectionTimeout()); |
1e080116 JB |
2367 | const reconnectDelayWithdraw = 1000; |
2368 | const reconnectTimeout = | |
2369 | reconnectDelay && reconnectDelay - reconnectDelayWithdraw > 0 | |
2370 | ? reconnectDelay - reconnectDelayWithdraw | |
2371 | : 0; | |
e7aeea18 | 2372 | logger.error( |
9bf0ef23 | 2373 | `${this.logPrefix()} WebSocket connection retry in ${roundTo( |
e7aeea18 | 2374 | reconnectDelay, |
5edd8ba0 JB |
2375 | 2, |
2376 | )}ms, timeout ${reconnectTimeout}ms`, | |
e7aeea18 | 2377 | ); |
9bf0ef23 | 2378 | await sleep(reconnectDelay); |
e7aeea18 | 2379 | logger.error( |
5edd8ba0 | 2380 | `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`, |
e7aeea18 JB |
2381 | ); |
2382 | this.openWSConnection( | |
59b6ed8d | 2383 | { |
abe9e9dd | 2384 | ...(this.stationInfo?.wsOptions ?? {}), |
59b6ed8d JB |
2385 | handshakeTimeout: reconnectTimeout, |
2386 | }, | |
5edd8ba0 | 2387 | { closeOpened: true }, |
e7aeea18 | 2388 | ); |
265e4266 | 2389 | this.wsConnectionRestarted = true; |
c0560973 | 2390 | } else if (this.getAutoReconnectMaxRetries() !== -1) { |
e7aeea18 | 2391 | logger.error( |
d56ea27c | 2392 | `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${ |
e7aeea18 | 2393 | this.autoReconnectRetryCount |
5edd8ba0 | 2394 | }) or retries disabled (${this.getAutoReconnectMaxRetries()})`, |
e7aeea18 | 2395 | ); |
5ad8570f JB |
2396 | } |
2397 | } | |
7dde0b73 | 2398 | } |