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