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