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