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