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