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