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