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 { |
0bb3ee61 | 743 | let limit: number, matchingChargingProfile: ChargingProfile; |
1e5bbb96 | 744 | let chargingProfiles: ChargingProfile[] = []; |
0bb3ee61 | 745 | // Get charging profiles for connector and sort by stack level |
1e5bbb96 O |
746 | chargingProfiles = this.getConnectorStatus(connectorId).chargingProfiles.sort( |
747 | (a, b) => b.stackLevel - a.stackLevel | |
748 | ); | |
749 | // Get profiles on connector 0 | |
750 | if (this.getConnectorStatus(0).chargingProfiles) { | |
751 | chargingProfiles.push( | |
752 | ...this.getConnectorStatus(0).chargingProfiles.sort((a, b) => b.stackLevel - a.stackLevel) | |
cfa9539e | 753 | ); |
cfa9539e | 754 | } |
1e5bbb96 | 755 | if (!Utils.isEmptyArray(chargingProfiles)) { |
0bb3ee61 | 756 | const result = this.getCurrentLimitFromChargingProfiles(chargingProfiles); |
1e5bbb96 O |
757 | if (!Utils.isNullOrUndefined(result)) { |
758 | limit = result.limit; | |
759 | matchingChargingProfile = result.matchingChargingProfile; | |
760 | switch (this.getCurrentOutType()) { | |
761 | case CurrentType.AC: | |
762 | limit = | |
763 | matchingChargingProfile.chargingSchedule.chargingRateUnit === | |
764 | ChargingRateUnitType.WATT | |
765 | ? limit | |
766 | : ACElectricUtils.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit); | |
767 | break; | |
768 | case CurrentType.DC: | |
769 | limit = | |
770 | matchingChargingProfile.chargingSchedule.chargingRateUnit === | |
771 | ChargingRateUnitType.WATT | |
772 | ? limit | |
773 | : DCElectricUtils.power(this.getVoltageOut(), limit); | |
774 | } | |
775 | ||
776 | const connectorMaximumPower = this.getMaximumPower() / this.stationInfo.powerDivider; | |
777 | if (limit > connectorMaximumPower) { | |
778 | logger.error( | |
779 | `${this.logPrefix()} Charging profile id ${ | |
780 | matchingChargingProfile.chargingProfileId | |
781 | } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`, | |
782 | this.getConnectorStatus(connectorId).chargingProfiles | |
783 | ); | |
784 | limit = connectorMaximumPower; | |
785 | } | |
cfa9539e | 786 | } |
ad8537a7 | 787 | } |
ad8537a7 | 788 | return limit; |
cfa9539e JB |
789 | } |
790 | ||
a7fc8211 | 791 | public setChargingProfile(connectorId: number, cp: ChargingProfile): void { |
0bb3ee61 JB |
792 | if (Utils.isNullOrUndefined(this.getConnectorStatus(connectorId).chargingProfiles)) { |
793 | logger.error( | |
794 | `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization` | |
795 | ); | |
796 | this.getConnectorStatus(connectorId).chargingProfiles = []; | |
797 | } | |
1e5bbb96 | 798 | if (!Array.isArray(this.getConnectorStatus(connectorId).chargingProfiles)) { |
0bb3ee61 JB |
799 | logger.error( |
800 | `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an improper attribute type for the charging profiles array, applying proper type initialization` | |
801 | ); | |
1e5bbb96 O |
802 | this.getConnectorStatus(connectorId).chargingProfiles = []; |
803 | } | |
a7fc8211 | 804 | let cpReplaced = false; |
734d790d | 805 | if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId).chargingProfiles)) { |
e7aeea18 JB |
806 | this.getConnectorStatus(connectorId).chargingProfiles?.forEach( |
807 | (chargingProfile: ChargingProfile, index: number) => { | |
808 | if ( | |
809 | chargingProfile.chargingProfileId === cp.chargingProfileId || | |
810 | (chargingProfile.stackLevel === cp.stackLevel && | |
811 | chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose) | |
812 | ) { | |
813 | this.getConnectorStatus(connectorId).chargingProfiles[index] = cp; | |
814 | cpReplaced = true; | |
815 | } | |
c0560973 | 816 | } |
e7aeea18 | 817 | ); |
c0560973 | 818 | } |
734d790d | 819 | !cpReplaced && this.getConnectorStatus(connectorId).chargingProfiles?.push(cp); |
c0560973 JB |
820 | } |
821 | ||
a2653482 JB |
822 | public resetConnectorStatus(connectorId: number): void { |
823 | this.getConnectorStatus(connectorId).idTagLocalAuthorized = false; | |
824 | this.getConnectorStatus(connectorId).idTagAuthorized = false; | |
825 | this.getConnectorStatus(connectorId).transactionRemoteStarted = false; | |
734d790d | 826 | this.getConnectorStatus(connectorId).transactionStarted = false; |
a2653482 | 827 | delete this.getConnectorStatus(connectorId).localAuthorizeIdTag; |
734d790d JB |
828 | delete this.getConnectorStatus(connectorId).authorizeIdTag; |
829 | delete this.getConnectorStatus(connectorId).transactionId; | |
830 | delete this.getConnectorStatus(connectorId).transactionIdTag; | |
831 | this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0; | |
832 | delete this.getConnectorStatus(connectorId).transactionBeginMeterValue; | |
dd119a6b | 833 | this.stopMeterValues(connectorId); |
2e6f5966 JB |
834 | } |
835 | ||
68cb8b91 JB |
836 | public hasFeatureProfile(featureProfile: SupportedFeatureProfiles) { |
837 | return this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)?.value.includes( | |
838 | featureProfile | |
839 | ); | |
840 | } | |
841 | ||
8e242273 JB |
842 | public bufferMessage(message: string): void { |
843 | this.messageBuffer.add(message); | |
3ba2381e JB |
844 | } |
845 | ||
8e242273 JB |
846 | private flushMessageBuffer() { |
847 | if (this.messageBuffer.size > 0) { | |
848 | this.messageBuffer.forEach((message) => { | |
aef1b33a | 849 | // TODO: evaluate the need to track performance |
77f00f84 | 850 | this.wsConnection.send(message); |
8e242273 | 851 | this.messageBuffer.delete(message); |
77f00f84 JB |
852 | }); |
853 | } | |
854 | } | |
855 | ||
1f5df42a JB |
856 | private getSupervisionUrlOcppConfiguration(): boolean { |
857 | return this.stationInfo.supervisionUrlOcppConfiguration ?? false; | |
12fc74d6 JB |
858 | } |
859 | ||
e8e865ea JB |
860 | private getSupervisionUrlOcppKey(): string { |
861 | return this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl; | |
862 | } | |
863 | ||
c0560973 | 864 | private getChargingStationId(stationTemplate: ChargingStationTemplate): string { |
ef6076c1 | 865 | // In case of multiple instances: add instance index to charging station id |
203bc097 | 866 | const instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0; |
9ccca265 | 867 | const idSuffix = stationTemplate.nameSuffix ?? ''; |
de1ec47b | 868 | const idStr = '000000000' + this.index.toString(); |
e7aeea18 JB |
869 | return stationTemplate.fixedName |
870 | ? stationTemplate.baseName | |
871 | : stationTemplate.baseName + | |
872 | '-' + | |
873 | instanceIndex.toString() + | |
de1ec47b | 874 | idStr.substring(idStr.length - 4) + |
e7aeea18 | 875 | idSuffix; |
5ad8570f JB |
876 | } |
877 | ||
efb85e20 JB |
878 | private getRandomSerialNumberSuffix(params?: { |
879 | randomBytesLength?: number; | |
880 | upperCase?: boolean; | |
881 | }): string { | |
882 | const randomSerialNumberSuffix = crypto | |
883 | .randomBytes(params?.randomBytesLength ?? 16) | |
884 | .toString('hex'); | |
885 | if (params?.upperCase) { | |
886 | return randomSerialNumberSuffix.toUpperCase(); | |
887 | } | |
888 | return randomSerialNumberSuffix; | |
889 | } | |
890 | ||
9214b603 | 891 | private getTemplateFromFile(): ChargingStationTemplate | null { |
2484ac1e | 892 | let template: ChargingStationTemplate = null; |
5ad8570f | 893 | try { |
42a3eee7 JB |
894 | const measureId = `${FileType.ChargingStationTemplate} read`; |
895 | const beginId = PerformanceStatistics.beginMeasure(measureId); | |
f765beaa JB |
896 | template = |
897 | (JSON.parse(fs.readFileSync(this.templateFile, 'utf8')) as ChargingStationTemplate) ?? | |
898 | ({} as ChargingStationTemplate); | |
42a3eee7 | 899 | PerformanceStatistics.endMeasure(measureId, beginId); |
f765beaa JB |
900 | template.templateHash = crypto |
901 | .createHash(Constants.DEFAULT_HASH_ALGORITHM) | |
902 | .update(JSON.stringify(template)) | |
903 | .digest('hex'); | |
5ad8570f | 904 | } catch (error) { |
e7aeea18 JB |
905 | FileUtils.handleFileException( |
906 | this.logPrefix(), | |
a95873d8 | 907 | FileType.ChargingStationTemplate, |
2484ac1e | 908 | this.templateFile, |
e7aeea18 JB |
909 | error as NodeJS.ErrnoException |
910 | ); | |
5ad8570f | 911 | } |
2484ac1e JB |
912 | return template; |
913 | } | |
914 | ||
915 | private createSerialNumber( | |
916 | stationInfo: ChargingStationInfo, | |
7a3a2ebb JB |
917 | existingStationInfo?: ChargingStationInfo, |
918 | params: { randomSerialNumberUpperCase?: boolean; randomSerialNumber?: boolean } = { | |
919 | randomSerialNumberUpperCase: true, | |
920 | randomSerialNumber: true, | |
921 | } | |
2484ac1e | 922 | ): void { |
7a3a2ebb JB |
923 | params = params ?? {}; |
924 | params.randomSerialNumberUpperCase = params?.randomSerialNumberUpperCase ?? true; | |
925 | params.randomSerialNumber = params?.randomSerialNumber ?? true; | |
94ec7e96 | 926 | if (!Utils.isEmptyObject(existingStationInfo)) { |
7a3a2ebb JB |
927 | existingStationInfo?.chargePointSerialNumber && |
928 | (stationInfo.chargePointSerialNumber = existingStationInfo.chargePointSerialNumber); | |
929 | existingStationInfo?.chargeBoxSerialNumber && | |
930 | (stationInfo.chargeBoxSerialNumber = existingStationInfo.chargeBoxSerialNumber); | |
0b7c34ba JB |
931 | existingStationInfo?.meterSerialNumber && |
932 | (stationInfo.meterSerialNumber = existingStationInfo.meterSerialNumber); | |
7a3a2ebb JB |
933 | } else { |
934 | const serialNumberSuffix = params?.randomSerialNumber | |
935 | ? this.getRandomSerialNumberSuffix({ upperCase: params.randomSerialNumberUpperCase }) | |
936 | : ''; | |
937 | stationInfo.chargePointSerialNumber = | |
938 | stationInfo?.chargePointSerialNumberPrefix && | |
939 | stationInfo.chargePointSerialNumberPrefix + serialNumberSuffix; | |
940 | stationInfo.chargeBoxSerialNumber = | |
941 | stationInfo?.chargeBoxSerialNumberPrefix && | |
942 | stationInfo.chargeBoxSerialNumberPrefix + serialNumberSuffix; | |
0b7c34ba JB |
943 | stationInfo.meterSerialNumber = |
944 | stationInfo?.meterSerialNumberPrefix && | |
945 | stationInfo.meterSerialNumberPrefix + serialNumberSuffix; | |
7a3a2ebb JB |
946 | } |
947 | } | |
948 | ||
949 | private getStationInfoFromTemplate(): ChargingStationInfo { | |
f765beaa | 950 | const stationInfo: ChargingStationInfo = this.getTemplateFromFile(); |
94ec7e96 | 951 | if (Utils.isNullOrUndefined(stationInfo)) { |
3ead11ba | 952 | const logMsg = 'Failed to read charging station template file'; |
94ec7e96 JB |
953 | logger.error(`${this.logPrefix()} ${logMsg}`); |
954 | throw new BaseError(logMsg); | |
955 | } | |
956 | if (Utils.isEmptyObject(stationInfo)) { | |
3d25cc86 JB |
957 | logger.warn( |
958 | `${this.logPrefix()} Empty charging station information from template file ${ | |
959 | this.templateFile | |
960 | }` | |
961 | ); | |
94ec7e96 | 962 | } |
7a3a2ebb | 963 | const chargingStationId = this.getChargingStationId(stationInfo); |
2dcfe98e | 964 | // Deprecation template keys section |
e7aeea18 | 965 | this.warnDeprecatedTemplateKey( |
7a3a2ebb | 966 | stationInfo, |
e7aeea18 JB |
967 | 'supervisionUrl', |
968 | chargingStationId, | |
969 | "Use 'supervisionUrls' instead" | |
970 | ); | |
7a3a2ebb JB |
971 | this.convertDeprecatedTemplateKey(stationInfo, 'supervisionUrl', 'supervisionUrls'); |
972 | stationInfo.wsOptions = stationInfo?.wsOptions ?? {}; | |
973 | if (!Utils.isEmptyArray(stationInfo.power)) { | |
974 | stationInfo.power = stationInfo.power as number[]; | |
975 | const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationInfo.power.length); | |
cc6e8ab5 | 976 | stationInfo.maximumPower = |
7a3a2ebb JB |
977 | stationInfo.powerUnit === PowerUnits.KILO_WATT |
978 | ? stationInfo.power[powerArrayRandomIndex] * 1000 | |
979 | : stationInfo.power[powerArrayRandomIndex]; | |
5ad8570f | 980 | } else { |
7a3a2ebb | 981 | stationInfo.power = stationInfo.power as number; |
cc6e8ab5 | 982 | stationInfo.maximumPower = |
7a3a2ebb JB |
983 | stationInfo.powerUnit === PowerUnits.KILO_WATT |
984 | ? stationInfo.power * 1000 | |
985 | : stationInfo.power; | |
5ad8570f | 986 | } |
fd0c36fa JB |
987 | delete stationInfo.power; |
988 | delete stationInfo.powerUnit; | |
2dcfe98e | 989 | stationInfo.chargingStationId = chargingStationId; |
7a3a2ebb JB |
990 | stationInfo.resetTime = stationInfo.resetTime |
991 | ? stationInfo.resetTime * 1000 | |
e7aeea18 | 992 | : Constants.CHARGING_STATION_DEFAULT_RESET_TIME; |
9ac86a7e | 993 | return stationInfo; |
5ad8570f JB |
994 | } |
995 | ||
01efc60a | 996 | private createStationInfoHash(stationInfo: ChargingStationInfo): ChargingStationInfo { |
3ead11ba JB |
997 | if (!Utils.isEmptyObject(stationInfo)) { |
998 | const previousInfoHash = stationInfo?.infoHash ?? ''; | |
999 | delete stationInfo.infoHash; | |
1000 | const currentInfoHash = crypto | |
1001 | .createHash(Constants.DEFAULT_HASH_ALGORITHM) | |
1002 | .update(JSON.stringify(stationInfo)) | |
1003 | .digest('hex'); | |
1004 | if ( | |
1005 | Utils.isEmptyString(previousInfoHash) || | |
1006 | (!Utils.isEmptyString(previousInfoHash) && currentInfoHash !== previousInfoHash) | |
1007 | ) { | |
1008 | stationInfo.infoHash = currentInfoHash; | |
1009 | } else { | |
1010 | stationInfo.infoHash = previousInfoHash; | |
1011 | } | |
01efc60a JB |
1012 | } |
1013 | return stationInfo; | |
1014 | } | |
1015 | ||
1016 | private getStationInfoFromFile(): ChargingStationInfo { | |
1017 | let stationInfo = this.getConfigurationFromFile()?.stationInfo ?? ({} as ChargingStationInfo); | |
1018 | stationInfo = this.createStationInfoHash(stationInfo); | |
f765beaa | 1019 | return stationInfo; |
2484ac1e JB |
1020 | } |
1021 | ||
1022 | private getStationInfo(): ChargingStationInfo { | |
1023 | const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate(); | |
7a3a2ebb | 1024 | this.hashId = this.getHashId(stationInfoFromTemplate); |
2484ac1e JB |
1025 | this.configurationFile = path.join( |
1026 | path.resolve(__dirname, '../'), | |
1027 | 'assets', | |
1028 | 'configurations', | |
1029 | this.hashId + '.json' | |
1030 | ); | |
1031 | const stationInfoFromFile: ChargingStationInfo = this.getStationInfoFromFile(); | |
aca53a1a | 1032 | // Priority: charging station info from template > charging station info from configuration file > charging station info attribute |
f765beaa | 1033 | if (stationInfoFromFile?.templateHash === stationInfoFromTemplate.templateHash) { |
01efc60a JB |
1034 | if (this.stationInfo?.infoHash === stationInfoFromFile?.infoHash) { |
1035 | return this.stationInfo; | |
1036 | } | |
2484ac1e | 1037 | return stationInfoFromFile; |
f765beaa | 1038 | } |
01efc60a JB |
1039 | this.createSerialNumber(stationInfoFromTemplate, stationInfoFromFile); |
1040 | return stationInfoFromTemplate; | |
2484ac1e JB |
1041 | } |
1042 | ||
1043 | private saveStationInfo(): void { | |
1044 | this.saveConfiguration(Section.stationInfo); | |
1045 | } | |
1046 | ||
1f5df42a | 1047 | private getOcppVersion(): OCPPVersion { |
aba95196 | 1048 | return this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16; |
c0560973 JB |
1049 | } |
1050 | ||
e8e865ea JB |
1051 | private getOcppPersistentConfiguration(): boolean { |
1052 | return this.stationInfo.ocppPersistentConfiguration ?? true; | |
1053 | } | |
1054 | ||
c0560973 | 1055 | private handleUnsupportedVersion(version: OCPPVersion) { |
e7aeea18 | 1056 | const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${ |
2484ac1e | 1057 | this.templateFile |
e7aeea18 | 1058 | }`; |
9f2e3130 | 1059 | logger.error(errMsg); |
c0560973 JB |
1060 | throw new Error(errMsg); |
1061 | } | |
1062 | ||
2484ac1e JB |
1063 | private createBootNotificationRequest(stationInfo: ChargingStationInfo): BootNotificationRequest { |
1064 | return { | |
1065 | chargePointModel: stationInfo.chargePointModel, | |
1066 | chargePointVendor: stationInfo.chargePointVendor, | |
1067 | ...(!Utils.isUndefined(stationInfo.chargeBoxSerialNumber) && { | |
1068 | chargeBoxSerialNumber: stationInfo.chargeBoxSerialNumber, | |
e7aeea18 | 1069 | }), |
2484ac1e JB |
1070 | ...(!Utils.isUndefined(stationInfo.chargePointSerialNumber) && { |
1071 | chargePointSerialNumber: stationInfo.chargePointSerialNumber, | |
43bb4cd9 | 1072 | }), |
2484ac1e JB |
1073 | ...(!Utils.isUndefined(stationInfo.firmwareVersion) && { |
1074 | firmwareVersion: stationInfo.firmwareVersion, | |
e7aeea18 | 1075 | }), |
2484ac1e JB |
1076 | ...(!Utils.isUndefined(stationInfo.iccid) && { iccid: stationInfo.iccid }), |
1077 | ...(!Utils.isUndefined(stationInfo.imsi) && { imsi: stationInfo.imsi }), | |
1078 | ...(!Utils.isUndefined(stationInfo.meterSerialNumber) && { | |
1079 | meterSerialNumber: stationInfo.meterSerialNumber, | |
3f94cab5 | 1080 | }), |
2484ac1e JB |
1081 | ...(!Utils.isUndefined(stationInfo.meterType) && { |
1082 | meterType: stationInfo.meterType, | |
3f94cab5 | 1083 | }), |
2e6f5966 | 1084 | }; |
2484ac1e JB |
1085 | } |
1086 | ||
7a3a2ebb JB |
1087 | private getHashId(stationInfo: ChargingStationInfo): string { |
1088 | const hashBootNotificationRequest = { | |
1089 | chargePointModel: stationInfo.chargePointModel, | |
1090 | chargePointVendor: stationInfo.chargePointVendor, | |
1091 | ...(!Utils.isUndefined(stationInfo.chargeBoxSerialNumberPrefix) && { | |
1092 | chargeBoxSerialNumber: stationInfo.chargeBoxSerialNumberPrefix, | |
1093 | }), | |
1094 | ...(!Utils.isUndefined(stationInfo.chargePointSerialNumberPrefix) && { | |
1095 | chargePointSerialNumber: stationInfo.chargePointSerialNumberPrefix, | |
1096 | }), | |
1097 | ...(!Utils.isUndefined(stationInfo.firmwareVersion) && { | |
1098 | firmwareVersion: stationInfo.firmwareVersion, | |
1099 | }), | |
1100 | ...(!Utils.isUndefined(stationInfo.iccid) && { iccid: stationInfo.iccid }), | |
1101 | ...(!Utils.isUndefined(stationInfo.imsi) && { imsi: stationInfo.imsi }), | |
0b7c34ba JB |
1102 | ...(!Utils.isUndefined(stationInfo.meterSerialNumberPrefix) && { |
1103 | meterSerialNumber: stationInfo.meterSerialNumberPrefix, | |
7a3a2ebb JB |
1104 | }), |
1105 | ...(!Utils.isUndefined(stationInfo.meterType) && { | |
1106 | meterType: stationInfo.meterType, | |
1107 | }), | |
1108 | }; | |
2484ac1e | 1109 | return crypto |
3f94cab5 | 1110 | .createHash(Constants.DEFAULT_HASH_ALGORITHM) |
7a3a2ebb | 1111 | .update(JSON.stringify(hashBootNotificationRequest) + stationInfo.chargingStationId) |
3f94cab5 | 1112 | .digest('hex'); |
2484ac1e JB |
1113 | } |
1114 | ||
1115 | private initialize(): void { | |
1116 | this.stationInfo = this.getStationInfo(); | |
3f94cab5 | 1117 | logger.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`); |
2484ac1e JB |
1118 | this.bootNotificationRequest = this.createBootNotificationRequest(this.stationInfo); |
1119 | this.ocppConfiguration = this.getOcppConfiguration(); | |
01efc60a | 1120 | this.stationInfo?.Configuration && delete this.stationInfo.Configuration; |
0642c3d2 JB |
1121 | this.wsConfiguredConnectionUrl = new URL( |
1122 | this.getConfiguredSupervisionUrl().href + '/' + this.stationInfo.chargingStationId | |
1123 | ); | |
0a60c33c | 1124 | // Build connectors if needed |
c0560973 | 1125 | const maxConnectors = this.getMaxNumberOfConnectors(); |
3d25cc86 | 1126 | this.checkMaxConnectors(maxConnectors); |
c0560973 | 1127 | const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors(); |
3d25cc86 | 1128 | this.checkTemplateMaxConnectors(templateMaxConnectors); |
e7aeea18 JB |
1129 | if ( |
1130 | maxConnectors > | |
94ec7e96 | 1131 | (this.stationInfo?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && |
e7aeea18 JB |
1132 | !this.stationInfo.randomConnectors |
1133 | ) { | |
1134 | logger.warn( | |
1135 | `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${ | |
2484ac1e | 1136 | this.templateFile |
e7aeea18 JB |
1137 | }, forcing random connector configurations affectation` |
1138 | ); | |
ad2f27c3 | 1139 | this.stationInfo.randomConnectors = true; |
6ecb15e4 | 1140 | } |
3d25cc86 | 1141 | this.initializeConnectors(this.stationInfo, maxConnectors, templateMaxConnectors); |
cc6e8ab5 | 1142 | this.stationInfo.maximumAmperage = this.getMaximumAmperage(); |
01efc60a | 1143 | this.stationInfo = this.createStationInfoHash(this.stationInfo); |
cc6e8ab5 | 1144 | this.saveStationInfo(); |
7a3a2ebb | 1145 | // Avoid duplication of connectors related information in RAM |
94ec7e96 | 1146 | this.stationInfo?.Connectors && delete this.stationInfo.Connectors; |
2484ac1e JB |
1147 | // OCPP configuration |
1148 | this.initializeOcppConfiguration(); | |
0642c3d2 JB |
1149 | if (this.getEnableStatistics()) { |
1150 | this.performanceStatistics = PerformanceStatistics.getInstance( | |
1151 | this.hashId, | |
1152 | this.stationInfo.chargingStationId, | |
1153 | this.wsConnectionUrl | |
1154 | ); | |
1155 | } | |
1f5df42a | 1156 | switch (this.getOcppVersion()) { |
c0560973 | 1157 | case OCPPVersion.VERSION_16: |
e7aeea18 JB |
1158 | this.ocppIncomingRequestService = |
1159 | OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>(this); | |
1160 | this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>( | |
1161 | this, | |
1162 | OCPP16ResponseService.getInstance<OCPP16ResponseService>(this) | |
1163 | ); | |
c0560973 JB |
1164 | break; |
1165 | default: | |
1f5df42a | 1166 | this.handleUnsupportedVersion(this.getOcppVersion()); |
c0560973 JB |
1167 | break; |
1168 | } | |
47e22477 JB |
1169 | if (this.stationInfo.autoRegister) { |
1170 | this.bootNotificationResponse = { | |
1171 | currentTime: new Date().toISOString(), | |
1172 | interval: this.getHeartbeatInterval() / 1000, | |
e7aeea18 | 1173 | status: RegistrationStatus.ACCEPTED, |
47e22477 JB |
1174 | }; |
1175 | } | |
147d0e0f | 1176 | this.stationInfo.powerDivider = this.getPowerDivider(); |
147d0e0f JB |
1177 | } |
1178 | ||
2484ac1e | 1179 | private initializeOcppConfiguration(): void { |
f0f65a62 JB |
1180 | if (!this.getConfigurationKey(StandardParametersKey.HeartbeatInterval)) { |
1181 | this.addConfigurationKey(StandardParametersKey.HeartbeatInterval, '0'); | |
1182 | } | |
1183 | if (!this.getConfigurationKey(StandardParametersKey.HeartBeatInterval)) { | |
1184 | this.addConfigurationKey(StandardParametersKey.HeartBeatInterval, '0', { visible: false }); | |
1185 | } | |
e7aeea18 JB |
1186 | if ( |
1187 | this.getSupervisionUrlOcppConfiguration() && | |
a59737e3 | 1188 | !this.getConfigurationKey(this.getSupervisionUrlOcppKey()) |
e7aeea18 JB |
1189 | ) { |
1190 | this.addConfigurationKey( | |
a59737e3 | 1191 | this.getSupervisionUrlOcppKey(), |
e7aeea18 JB |
1192 | this.getConfiguredSupervisionUrl().href, |
1193 | { reboot: true } | |
1194 | ); | |
e6895390 JB |
1195 | } else if ( |
1196 | !this.getSupervisionUrlOcppConfiguration() && | |
1197 | this.getConfigurationKey(this.getSupervisionUrlOcppKey()) | |
1198 | ) { | |
1199 | this.deleteConfigurationKey(this.getSupervisionUrlOcppKey(), { save: false }); | |
12fc74d6 | 1200 | } |
cc6e8ab5 JB |
1201 | if ( |
1202 | this.stationInfo.amperageLimitationOcppKey && | |
1203 | !this.getConfigurationKey(this.stationInfo.amperageLimitationOcppKey) | |
1204 | ) { | |
1205 | this.addConfigurationKey( | |
1206 | this.stationInfo.amperageLimitationOcppKey, | |
1207 | (this.stationInfo.maximumAmperage * this.getAmperageLimitationUnitDivider()).toString() | |
1208 | ); | |
1209 | } | |
36f6a92e | 1210 | if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) { |
e7aeea18 JB |
1211 | this.addConfigurationKey( |
1212 | StandardParametersKey.SupportedFeatureProfiles, | |
b22787b4 | 1213 | `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}` |
e7aeea18 JB |
1214 | ); |
1215 | } | |
1216 | this.addConfigurationKey( | |
1217 | StandardParametersKey.NumberOfConnectors, | |
1218 | this.getNumberOfConnectors().toString(), | |
a95873d8 JB |
1219 | { readonly: true }, |
1220 | { overwrite: true } | |
e7aeea18 | 1221 | ); |
c0560973 | 1222 | if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) { |
e7aeea18 JB |
1223 | this.addConfigurationKey( |
1224 | StandardParametersKey.MeterValuesSampledData, | |
1225 | MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER | |
1226 | ); | |
7abfea5f | 1227 | } |
7e1dc878 JB |
1228 | if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) { |
1229 | const connectorPhaseRotation = []; | |
734d790d | 1230 | for (const connectorId of this.connectors.keys()) { |
7e1dc878 | 1231 | // AC/DC |
734d790d JB |
1232 | if (connectorId === 0 && this.getNumberOfPhases() === 0) { |
1233 | connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`); | |
1234 | } else if (connectorId > 0 && this.getNumberOfPhases() === 0) { | |
1235 | connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`); | |
e7aeea18 | 1236 | // AC |
734d790d JB |
1237 | } else if (connectorId > 0 && this.getNumberOfPhases() === 1) { |
1238 | connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`); | |
1239 | } else if (connectorId > 0 && this.getNumberOfPhases() === 3) { | |
1240 | connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`); | |
7e1dc878 JB |
1241 | } |
1242 | } | |
e7aeea18 JB |
1243 | this.addConfigurationKey( |
1244 | StandardParametersKey.ConnectorPhaseRotation, | |
1245 | connectorPhaseRotation.toString() | |
1246 | ); | |
7e1dc878 | 1247 | } |
36f6a92e JB |
1248 | if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) { |
1249 | this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true'); | |
1250 | } | |
e7aeea18 JB |
1251 | if ( |
1252 | !this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled) && | |
68cb8b91 | 1253 | this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)?.value.includes( |
b22787b4 | 1254 | SupportedFeatureProfiles.LocalAuthListManagement |
e7aeea18 JB |
1255 | ) |
1256 | ) { | |
36f6a92e JB |
1257 | this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false'); |
1258 | } | |
147d0e0f | 1259 | if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) { |
e7aeea18 JB |
1260 | this.addConfigurationKey( |
1261 | StandardParametersKey.ConnectionTimeOut, | |
1262 | Constants.DEFAULT_CONNECTION_TIMEOUT.toString() | |
1263 | ); | |
8bce55bf | 1264 | } |
2484ac1e | 1265 | this.saveOcppConfiguration(); |
073bd098 JB |
1266 | } |
1267 | ||
3d25cc86 JB |
1268 | private initializeConnectors( |
1269 | stationInfo: ChargingStationInfo, | |
1270 | maxConnectors: number, | |
1271 | templateMaxConnectors: number | |
1272 | ): void { | |
1273 | if (!stationInfo?.Connectors && this.connectors.size === 0) { | |
1274 | const logMsg = `${this.logPrefix()} No already defined connectors and charging station information from template ${ | |
1275 | this.templateFile | |
1276 | } with no connectors configuration defined`; | |
1277 | logger.error(logMsg); | |
1278 | throw new BaseError(logMsg); | |
1279 | } | |
1280 | if (!stationInfo?.Connectors[0]) { | |
1281 | logger.warn( | |
1282 | `${this.logPrefix()} Charging station information from template ${ | |
1283 | this.templateFile | |
1284 | } with no connector Id 0 configuration` | |
1285 | ); | |
1286 | } | |
1287 | if (stationInfo?.Connectors) { | |
1288 | const connectorsConfigHash = crypto | |
1289 | .createHash(Constants.DEFAULT_HASH_ALGORITHM) | |
1290 | .update(JSON.stringify(stationInfo?.Connectors) + maxConnectors.toString()) | |
1291 | .digest('hex'); | |
1292 | const connectorsConfigChanged = | |
1293 | this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash; | |
1294 | if (this.connectors?.size === 0 || connectorsConfigChanged) { | |
1295 | connectorsConfigChanged && this.connectors.clear(); | |
1296 | this.connectorsConfigurationHash = connectorsConfigHash; | |
1297 | // Add connector Id 0 | |
1298 | let lastConnector = '0'; | |
1299 | for (lastConnector in stationInfo?.Connectors) { | |
1300 | const lastConnectorId = Utils.convertToInt(lastConnector); | |
1301 | if ( | |
1302 | lastConnectorId === 0 && | |
1303 | this.getUseConnectorId0() && | |
1304 | stationInfo?.Connectors[lastConnector] | |
1305 | ) { | |
1306 | this.connectors.set( | |
1307 | lastConnectorId, | |
1308 | Utils.cloneObject<ConnectorStatus>(stationInfo?.Connectors[lastConnector]) | |
1309 | ); | |
1310 | this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE; | |
1311 | if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) { | |
1312 | this.getConnectorStatus(lastConnectorId).chargingProfiles = []; | |
1313 | } | |
1314 | } | |
1315 | } | |
1316 | // Generate all connectors | |
1317 | if ((stationInfo?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) { | |
1318 | for (let index = 1; index <= maxConnectors; index++) { | |
1319 | const randConnectorId = stationInfo.randomConnectors | |
1320 | ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1) | |
1321 | : index; | |
1322 | this.connectors.set( | |
1323 | index, | |
1324 | Utils.cloneObject<ConnectorStatus>(stationInfo?.Connectors[randConnectorId]) | |
1325 | ); | |
1326 | this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE; | |
1327 | if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) { | |
1328 | this.getConnectorStatus(index).chargingProfiles = []; | |
1329 | } | |
1330 | } | |
1331 | } | |
1332 | } | |
1333 | } else { | |
1334 | logger.warn( | |
1335 | `${this.logPrefix()} Charging station information from template ${ | |
1336 | this.templateFile | |
1337 | } with no connectors configuration defined, using already defined connectors` | |
1338 | ); | |
1339 | } | |
1340 | // Initialize transaction attributes on connectors | |
1341 | for (const connectorId of this.connectors.keys()) { | |
1342 | if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) { | |
1343 | this.initializeConnectorStatus(connectorId); | |
1344 | } | |
1345 | } | |
1346 | } | |
1347 | ||
1348 | private checkMaxConnectors(maxConnectors: number): void { | |
1349 | if (maxConnectors <= 0) { | |
1350 | logger.warn( | |
1351 | `${this.logPrefix()} Charging station information from template ${ | |
1352 | this.templateFile | |
1353 | } with ${maxConnectors} connectors` | |
1354 | ); | |
1355 | } | |
1356 | } | |
1357 | ||
1358 | private checkTemplateMaxConnectors(templateMaxConnectors: number): void { | |
1359 | if (templateMaxConnectors === 0) { | |
1360 | logger.warn( | |
1361 | `${this.logPrefix()} Charging station information from template ${ | |
1362 | this.templateFile | |
1363 | } with empty connectors configuration` | |
1364 | ); | |
1365 | } else if (templateMaxConnectors < 0) { | |
1366 | logger.error( | |
1367 | `${this.logPrefix()} Charging station information from template ${ | |
1368 | this.templateFile | |
1369 | } with no connectors configuration defined` | |
1370 | ); | |
1371 | } | |
1372 | } | |
1373 | ||
7f7b65ca | 1374 | private getConfigurationFromFile(): ChargingStationConfiguration | null { |
073bd098 | 1375 | let configuration: ChargingStationConfiguration = null; |
2484ac1e | 1376 | if (this.configurationFile && fs.existsSync(this.configurationFile)) { |
073bd098 | 1377 | try { |
42a3eee7 | 1378 | const measureId = `${FileType.ChargingStationConfiguration} read`; |
0642c3d2 | 1379 | const beginId = PerformanceStatistics.beginMeasure(measureId); |
073bd098 | 1380 | configuration = JSON.parse( |
a95873d8 | 1381 | fs.readFileSync(this.configurationFile, 'utf8') |
073bd098 | 1382 | ) as ChargingStationConfiguration; |
42a3eee7 | 1383 | PerformanceStatistics.endMeasure(measureId, beginId); |
073bd098 JB |
1384 | } catch (error) { |
1385 | FileUtils.handleFileException( | |
1386 | this.logPrefix(), | |
a95873d8 | 1387 | FileType.ChargingStationConfiguration, |
073bd098 JB |
1388 | this.configurationFile, |
1389 | error as NodeJS.ErrnoException | |
1390 | ); | |
1391 | } | |
1392 | } | |
1393 | return configuration; | |
1394 | } | |
1395 | ||
2484ac1e JB |
1396 | private saveConfiguration(section?: Section): void { |
1397 | if (this.configurationFile) { | |
1398 | try { | |
1399 | const configurationData: ChargingStationConfiguration = | |
1400 | this.getConfigurationFromFile() ?? {}; | |
1401 | if (!fs.existsSync(path.dirname(this.configurationFile))) { | |
1402 | fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true }); | |
073bd098 | 1403 | } |
2484ac1e JB |
1404 | switch (section) { |
1405 | case Section.ocppConfiguration: | |
1406 | configurationData.configurationKey = this.ocppConfiguration.configurationKey; | |
1407 | break; | |
1408 | case Section.stationInfo: | |
01efc60a JB |
1409 | if (configurationData?.stationInfo?.infoHash === this.stationInfo?.infoHash) { |
1410 | logger.debug( | |
3d25cc86 | 1411 | `${this.logPrefix()} Not saving unchanged charging station information to configuration file ${ |
01efc60a JB |
1412 | this.configurationFile |
1413 | }` | |
1414 | ); | |
1415 | return; | |
1416 | } | |
2484ac1e JB |
1417 | configurationData.stationInfo = this.stationInfo; |
1418 | break; | |
1419 | default: | |
1420 | configurationData.configurationKey = this.ocppConfiguration.configurationKey; | |
01efc60a JB |
1421 | if (configurationData?.stationInfo?.infoHash !== this.stationInfo?.infoHash) { |
1422 | configurationData.stationInfo = this.stationInfo; | |
1423 | } | |
2484ac1e JB |
1424 | break; |
1425 | } | |
42a3eee7 JB |
1426 | const measureId = `${FileType.ChargingStationConfiguration} write`; |
1427 | const beginId = PerformanceStatistics.beginMeasure(measureId); | |
2484ac1e JB |
1428 | const fileDescriptor = fs.openSync(this.configurationFile, 'w'); |
1429 | fs.writeFileSync(fileDescriptor, JSON.stringify(configurationData, null, 2), 'utf8'); | |
1430 | fs.closeSync(fileDescriptor); | |
42a3eee7 | 1431 | PerformanceStatistics.endMeasure(measureId, beginId); |
2484ac1e JB |
1432 | } catch (error) { |
1433 | FileUtils.handleFileException( | |
1434 | this.logPrefix(), | |
1435 | FileType.ChargingStationConfiguration, | |
1436 | this.configurationFile, | |
1437 | error as NodeJS.ErrnoException | |
073bd098 JB |
1438 | ); |
1439 | } | |
2484ac1e JB |
1440 | } else { |
1441 | logger.error( | |
01efc60a | 1442 | `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file` |
2484ac1e | 1443 | ); |
073bd098 JB |
1444 | } |
1445 | } | |
1446 | ||
2484ac1e JB |
1447 | private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration { |
1448 | return this.getTemplateFromFile().Configuration ?? ({} as ChargingStationOcppConfiguration); | |
1449 | } | |
1450 | ||
1451 | private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | null { | |
1452 | let configuration: ChargingStationConfiguration = null; | |
1453 | if (this.getOcppPersistentConfiguration()) { | |
7a3a2ebb JB |
1454 | const configurationFromFile = this.getConfigurationFromFile(); |
1455 | configuration = configurationFromFile?.configurationKey && configurationFromFile; | |
073bd098 | 1456 | } |
2484ac1e | 1457 | configuration && delete configuration.stationInfo; |
073bd098 | 1458 | return configuration; |
7dde0b73 JB |
1459 | } |
1460 | ||
2484ac1e JB |
1461 | private getOcppConfiguration(): ChargingStationOcppConfiguration { |
1462 | let ocppConfiguration: ChargingStationOcppConfiguration = this.getOcppConfigurationFromFile(); | |
1463 | if (!ocppConfiguration) { | |
1464 | ocppConfiguration = this.getOcppConfigurationFromTemplate(); | |
1465 | } | |
1466 | return ocppConfiguration; | |
1467 | } | |
1468 | ||
1469 | private saveOcppConfiguration(): void { | |
1470 | if (this.getOcppPersistentConfiguration()) { | |
1471 | this.saveConfiguration(Section.ocppConfiguration); | |
1472 | } | |
1473 | } | |
1474 | ||
c0560973 | 1475 | private async onOpen(): Promise<void> { |
5144f4d1 JB |
1476 | if (this.isWebSocketConnectionOpened()) { |
1477 | logger.info( | |
1478 | `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded` | |
1479 | ); | |
94bb24d5 | 1480 | if (!this.isRegistered()) { |
5144f4d1 JB |
1481 | // Send BootNotification |
1482 | let registrationRetryCount = 0; | |
1483 | do { | |
f7f98c68 | 1484 | this.bootNotificationResponse = await this.ocppRequestService.requestHandler< |
5144f4d1 JB |
1485 | BootNotificationRequest, |
1486 | BootNotificationResponse | |
1487 | >( | |
f22266fd JB |
1488 | RequestCommand.BOOT_NOTIFICATION, |
1489 | { | |
1490 | chargePointModel: this.bootNotificationRequest.chargePointModel, | |
1491 | chargePointVendor: this.bootNotificationRequest.chargePointVendor, | |
1492 | chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber, | |
1493 | firmwareVersion: this.bootNotificationRequest.firmwareVersion, | |
1494 | chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber, | |
1495 | iccid: this.bootNotificationRequest.iccid, | |
1496 | imsi: this.bootNotificationRequest.imsi, | |
1497 | meterSerialNumber: this.bootNotificationRequest.meterSerialNumber, | |
1498 | meterType: this.bootNotificationRequest.meterType, | |
1499 | }, | |
1500 | { skipBufferingOnError: true } | |
1501 | ); | |
94bb24d5 | 1502 | if (!this.isRegistered()) { |
5144f4d1 JB |
1503 | this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++; |
1504 | await Utils.sleep( | |
1505 | this.bootNotificationResponse?.interval | |
1506 | ? this.bootNotificationResponse.interval * 1000 | |
1507 | : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL | |
1508 | ); | |
1509 | } | |
1510 | } while ( | |
94bb24d5 | 1511 | !this.isRegistered() && |
5144f4d1 JB |
1512 | (registrationRetryCount <= this.getRegistrationMaxRetries() || |
1513 | this.getRegistrationMaxRetries() === -1) | |
1514 | ); | |
1515 | } | |
94bb24d5 JB |
1516 | if (this.isRegistered()) { |
1517 | if (this.isInAcceptedState()) { | |
1518 | await this.startMessageSequence(); | |
1519 | this.wsConnectionRestarted && this.flushMessageBuffer(); | |
c0560973 | 1520 | } |
5144f4d1 JB |
1521 | } else { |
1522 | logger.error( | |
1523 | `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})` | |
1524 | ); | |
caad9d6b | 1525 | } |
94bb24d5 | 1526 | this.stopped && (this.stopped = false); |
5144f4d1 JB |
1527 | this.autoReconnectRetryCount = 0; |
1528 | this.wsConnectionRestarted = false; | |
2e6f5966 | 1529 | } else { |
5144f4d1 JB |
1530 | logger.warn( |
1531 | `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed` | |
e7aeea18 | 1532 | ); |
2e6f5966 | 1533 | } |
2e6f5966 JB |
1534 | } |
1535 | ||
6c65a295 | 1536 | private async onClose(code: number, reason: string): Promise<void> { |
d09085e9 | 1537 | switch (code) { |
6c65a295 JB |
1538 | // Normal close |
1539 | case WebSocketCloseEventStatusCode.CLOSE_NORMAL: | |
c0560973 | 1540 | case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS: |
e7aeea18 JB |
1541 | logger.info( |
1542 | `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString( | |
1543 | code | |
1544 | )}' and reason '${reason}'` | |
1545 | ); | |
c0560973 JB |
1546 | this.autoReconnectRetryCount = 0; |
1547 | break; | |
6c65a295 JB |
1548 | // Abnormal close |
1549 | default: | |
e7aeea18 JB |
1550 | logger.error( |
1551 | `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString( | |
1552 | code | |
1553 | )}' and reason '${reason}'` | |
1554 | ); | |
d09085e9 | 1555 | await this.reconnect(code); |
c0560973 JB |
1556 | break; |
1557 | } | |
2e6f5966 JB |
1558 | } |
1559 | ||
16b0d4e7 | 1560 | private async onMessage(data: Data): Promise<void> { |
b3ec7bc1 JB |
1561 | let messageType: number; |
1562 | let messageId: string; | |
1563 | let commandName: IncomingRequestCommand; | |
1564 | let commandPayload: JsonType; | |
1565 | let errorType: ErrorType; | |
1566 | let errorMessage: string; | |
1567 | let errorDetails: JsonType; | |
1568 | let responseCallback: (payload: JsonType, requestPayload: JsonType) => void; | |
a2d1c0f1 | 1569 | let errorCallback: (error: OCPPError, requestStatistic?: boolean) => void; |
32b02249 | 1570 | let requestCommandName: RequestCommand | IncomingRequestCommand; |
b3ec7bc1 | 1571 | let requestPayload: JsonType; |
32b02249 | 1572 | let cachedRequest: CachedRequest; |
c0560973 JB |
1573 | let errMsg: string; |
1574 | try { | |
b3ec7bc1 | 1575 | const request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse; |
47e22477 | 1576 | if (Utils.isIterable(request)) { |
9934652c | 1577 | [messageType, messageId] = request; |
b3ec7bc1 JB |
1578 | // Check the type of message |
1579 | switch (messageType) { | |
1580 | // Incoming Message | |
1581 | case MessageType.CALL_MESSAGE: | |
9934652c | 1582 | [, , commandName, commandPayload] = request as IncomingRequest; |
b3ec7bc1 JB |
1583 | if (this.getEnableStatistics()) { |
1584 | this.performanceStatistics.addRequestStatistic(commandName, messageType); | |
1585 | } | |
1586 | logger.debug( | |
1587 | `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify( | |
1588 | request | |
1589 | )}` | |
1590 | ); | |
1591 | // Process the message | |
1592 | await this.ocppIncomingRequestService.incomingRequestHandler( | |
1593 | messageId, | |
1594 | commandName, | |
1595 | commandPayload | |
1596 | ); | |
1597 | break; | |
1598 | // Outcome Message | |
1599 | case MessageType.CALL_RESULT_MESSAGE: | |
9934652c | 1600 | [, , commandPayload] = request as Response; |
a2d1c0f1 JB |
1601 | if (!this.requests.has(messageId)) { |
1602 | // Error | |
1603 | throw new OCPPError( | |
1604 | ErrorType.INTERNAL_ERROR, | |
1605 | `Response for unknown message id ${messageId}`, | |
1606 | null, | |
1607 | commandPayload | |
1608 | ); | |
1609 | } | |
b3ec7bc1 JB |
1610 | // Respond |
1611 | cachedRequest = this.requests.get(messageId); | |
1612 | if (Utils.isIterable(cachedRequest)) { | |
1613 | [responseCallback, , requestCommandName, requestPayload] = cachedRequest; | |
1614 | } else { | |
1615 | throw new OCPPError( | |
1616 | ErrorType.PROTOCOL_ERROR, | |
c2bc716f JB |
1617 | `Cached request for message id ${messageId} response is not iterable`, |
1618 | null, | |
1619 | cachedRequest as unknown as JsonType | |
b3ec7bc1 JB |
1620 | ); |
1621 | } | |
1622 | logger.debug( | |
7ec6c5c9 JB |
1623 | `${this.logPrefix()} << Command '${ |
1624 | requestCommandName ?? '' | |
1625 | }' received response payload: ${JSON.stringify(request)}` | |
b3ec7bc1 | 1626 | ); |
a2d1c0f1 JB |
1627 | responseCallback(commandPayload, requestPayload); |
1628 | break; | |
1629 | // Error Message | |
1630 | case MessageType.CALL_ERROR_MESSAGE: | |
1631 | [, , errorType, errorMessage, errorDetails] = request as ErrorResponse; | |
1632 | if (!this.requests.has(messageId)) { | |
b3ec7bc1 JB |
1633 | // Error |
1634 | throw new OCPPError( | |
1635 | ErrorType.INTERNAL_ERROR, | |
a2d1c0f1 | 1636 | `Error response for unknown message id ${messageId}`, |
c2bc716f | 1637 | null, |
a2d1c0f1 | 1638 | { errorType, errorMessage, errorDetails } |
b3ec7bc1 JB |
1639 | ); |
1640 | } | |
b3ec7bc1 JB |
1641 | cachedRequest = this.requests.get(messageId); |
1642 | if (Utils.isIterable(cachedRequest)) { | |
a2d1c0f1 | 1643 | [, errorCallback, requestCommandName] = cachedRequest; |
b3ec7bc1 JB |
1644 | } else { |
1645 | throw new OCPPError( | |
1646 | ErrorType.PROTOCOL_ERROR, | |
c2bc716f JB |
1647 | `Cached request for message id ${messageId} error response is not iterable`, |
1648 | null, | |
1649 | cachedRequest as unknown as JsonType | |
b3ec7bc1 JB |
1650 | ); |
1651 | } | |
1652 | logger.debug( | |
7ec6c5c9 JB |
1653 | `${this.logPrefix()} << Command '${ |
1654 | requestCommandName ?? '' | |
1655 | }' received error payload: ${JSON.stringify(request)}` | |
b3ec7bc1 | 1656 | ); |
a2d1c0f1 | 1657 | errorCallback(new OCPPError(errorType, errorMessage, requestCommandName, errorDetails)); |
b3ec7bc1 JB |
1658 | break; |
1659 | // Error | |
1660 | default: | |
1661 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions | |
1662 | errMsg = `${this.logPrefix()} Wrong message type ${messageType}`; | |
1663 | logger.error(errMsg); | |
1664 | throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg); | |
1665 | } | |
47e22477 | 1666 | } else { |
ac54a9bb JB |
1667 | throw new OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming message is not iterable', null, { |
1668 | payload: request, | |
1669 | }); | |
47e22477 | 1670 | } |
c0560973 JB |
1671 | } catch (error) { |
1672 | // Log | |
e7aeea18 JB |
1673 | logger.error( |
1674 | '%s Incoming OCPP message %j matching cached request %j processing error %j', | |
1675 | this.logPrefix(), | |
1676 | data.toString(), | |
1677 | this.requests.get(messageId), | |
1678 | error | |
1679 | ); | |
c0560973 | 1680 | // Send error |
e7aeea18 | 1681 | messageType === MessageType.CALL_MESSAGE && |
b3ec7bc1 JB |
1682 | (await this.ocppRequestService.sendError( |
1683 | messageId, | |
1684 | error as OCPPError, | |
a2d1c0f1 | 1685 | commandName ?? requestCommandName ?? null |
b3ec7bc1 | 1686 | )); |
c0560973 | 1687 | } |
2328be1e JB |
1688 | } |
1689 | ||
c0560973 | 1690 | private onPing(): void { |
9f2e3130 | 1691 | logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server'); |
c0560973 JB |
1692 | } |
1693 | ||
1694 | private onPong(): void { | |
9f2e3130 | 1695 | logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server'); |
c0560973 JB |
1696 | } |
1697 | ||
9534e74e | 1698 | private onError(error: WSError): void { |
9f2e3130 | 1699 | logger.error(this.logPrefix() + ' WebSocket error: %j', error); |
c0560973 JB |
1700 | } |
1701 | ||
6e0964c8 | 1702 | private getAuthorizationFile(): string | undefined { |
e7aeea18 JB |
1703 | return ( |
1704 | this.stationInfo.authorizationFile && | |
1705 | path.join( | |
1706 | path.resolve(__dirname, '../'), | |
1707 | 'assets', | |
1708 | path.basename(this.stationInfo.authorizationFile) | |
1709 | ) | |
1710 | ); | |
c0560973 JB |
1711 | } |
1712 | ||
1713 | private getAuthorizedTags(): string[] { | |
1714 | let authorizedTags: string[] = []; | |
1715 | const authorizationFile = this.getAuthorizationFile(); | |
1716 | if (authorizationFile) { | |
1717 | try { | |
1718 | // Load authorization file | |
a95873d8 | 1719 | authorizedTags = JSON.parse(fs.readFileSync(authorizationFile, 'utf8')) as string[]; |
c0560973 | 1720 | } catch (error) { |
e7aeea18 JB |
1721 | FileUtils.handleFileException( |
1722 | this.logPrefix(), | |
a95873d8 | 1723 | FileType.Authorization, |
e7aeea18 JB |
1724 | authorizationFile, |
1725 | error as NodeJS.ErrnoException | |
1726 | ); | |
c0560973 JB |
1727 | } |
1728 | } else { | |
e7aeea18 | 1729 | logger.info( |
2484ac1e | 1730 | this.logPrefix() + ' No authorization file given in template file ' + this.templateFile |
e7aeea18 | 1731 | ); |
8c4da341 | 1732 | } |
c0560973 JB |
1733 | return authorizedTags; |
1734 | } | |
1735 | ||
6e0964c8 | 1736 | private getUseConnectorId0(): boolean | undefined { |
e7aeea18 JB |
1737 | return !Utils.isUndefined(this.stationInfo.useConnectorId0) |
1738 | ? this.stationInfo.useConnectorId0 | |
1739 | : true; | |
8bce55bf JB |
1740 | } |
1741 | ||
c0560973 | 1742 | private getNumberOfRunningTransactions(): number { |
6ecb15e4 | 1743 | let trxCount = 0; |
734d790d JB |
1744 | for (const connectorId of this.connectors.keys()) { |
1745 | if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) { | |
6ecb15e4 JB |
1746 | trxCount++; |
1747 | } | |
1748 | } | |
1749 | return trxCount; | |
1750 | } | |
1751 | ||
1f761b9a | 1752 | // 0 for disabling |
6e0964c8 | 1753 | private getConnectionTimeout(): number | undefined { |
291cb255 | 1754 | if (this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) { |
e7aeea18 JB |
1755 | return ( |
1756 | parseInt(this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut).value) ?? | |
1757 | Constants.DEFAULT_CONNECTION_TIMEOUT | |
1758 | ); | |
291cb255 | 1759 | } |
291cb255 | 1760 | return Constants.DEFAULT_CONNECTION_TIMEOUT; |
3574dfd3 JB |
1761 | } |
1762 | ||
1f761b9a | 1763 | // -1 for unlimited, 0 for disabling |
6e0964c8 | 1764 | private getAutoReconnectMaxRetries(): number | undefined { |
ad2f27c3 JB |
1765 | if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) { |
1766 | return this.stationInfo.autoReconnectMaxRetries; | |
3574dfd3 JB |
1767 | } |
1768 | if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) { | |
1769 | return Configuration.getAutoReconnectMaxRetries(); | |
1770 | } | |
1771 | return -1; | |
1772 | } | |
1773 | ||
ec977daf | 1774 | // 0 for disabling |
6e0964c8 | 1775 | private getRegistrationMaxRetries(): number | undefined { |
ad2f27c3 JB |
1776 | if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) { |
1777 | return this.stationInfo.registrationMaxRetries; | |
32a1eb7a JB |
1778 | } |
1779 | return -1; | |
1780 | } | |
1781 | ||
c0560973 JB |
1782 | private getPowerDivider(): number { |
1783 | let powerDivider = this.getNumberOfConnectors(); | |
ad2f27c3 | 1784 | if (this.stationInfo.powerSharedByConnectors) { |
c0560973 | 1785 | powerDivider = this.getNumberOfRunningTransactions(); |
6ecb15e4 JB |
1786 | } |
1787 | return powerDivider; | |
1788 | } | |
1789 | ||
c0560973 | 1790 | private getTemplateMaxNumberOfConnectors(): number { |
94ec7e96 JB |
1791 | if (!this.stationInfo?.Connectors) { |
1792 | return -1; | |
1793 | } | |
1794 | return Object.keys(this.stationInfo?.Connectors).length; | |
7abfea5f JB |
1795 | } |
1796 | ||
c0560973 | 1797 | private getMaxNumberOfConnectors(): number { |
e58068fd | 1798 | let maxConnectors: number; |
ad2f27c3 JB |
1799 | if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) { |
1800 | const numberOfConnectors = this.stationInfo.numberOfConnectors as number[]; | |
6ecb15e4 | 1801 | // Distribute evenly the number of connectors |
ad2f27c3 JB |
1802 | maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length]; |
1803 | } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) { | |
1804 | maxConnectors = this.stationInfo.numberOfConnectors as number; | |
488fd3a7 | 1805 | } else { |
94ec7e96 | 1806 | maxConnectors = this.stationInfo?.Connectors[0] |
e7aeea18 JB |
1807 | ? this.getTemplateMaxNumberOfConnectors() - 1 |
1808 | : this.getTemplateMaxNumberOfConnectors(); | |
5ad8570f JB |
1809 | } |
1810 | return maxConnectors; | |
2e6f5966 JB |
1811 | } |
1812 | ||
0642c3d2 JB |
1813 | private getMaximumPower(): number { |
1814 | return (this.stationInfo['maxPower'] as number) ?? this.stationInfo.maximumPower; | |
1815 | } | |
1816 | ||
cc6e8ab5 | 1817 | private getMaximumAmperage(): number | undefined { |
0642c3d2 | 1818 | const maximumPower = this.getMaximumPower(); |
cc6e8ab5 JB |
1819 | switch (this.getCurrentOutType()) { |
1820 | case CurrentType.AC: | |
1821 | return ACElectricUtils.amperagePerPhaseFromPower( | |
1822 | this.getNumberOfPhases(), | |
ad8537a7 | 1823 | maximumPower / this.getNumberOfConnectors(), |
cc6e8ab5 JB |
1824 | this.getVoltageOut() |
1825 | ); | |
1826 | case CurrentType.DC: | |
ad8537a7 | 1827 | return DCElectricUtils.amperage(maximumPower, this.getVoltageOut()); |
cc6e8ab5 JB |
1828 | } |
1829 | } | |
1830 | ||
1831 | private getAmperageLimitationUnitDivider(): number { | |
1832 | let unitDivider = 1; | |
1833 | switch (this.stationInfo.amperageLimitationUnit) { | |
1834 | case AmpereUnits.DECI_AMPERE: | |
1835 | unitDivider = 10; | |
1836 | break; | |
1837 | case AmpereUnits.CENTI_AMPERE: | |
1838 | unitDivider = 100; | |
1839 | break; | |
1840 | case AmpereUnits.MILLI_AMPERE: | |
1841 | unitDivider = 1000; | |
1842 | break; | |
1843 | } | |
1844 | return unitDivider; | |
1845 | } | |
1846 | ||
1847 | private getAmperageLimitation(): number | undefined { | |
1848 | if ( | |
1849 | this.stationInfo.amperageLimitationOcppKey && | |
1850 | this.getConfigurationKey(this.stationInfo.amperageLimitationOcppKey) | |
1851 | ) { | |
1852 | return ( | |
1853 | Utils.convertToInt( | |
1854 | this.getConfigurationKey(this.stationInfo.amperageLimitationOcppKey).value | |
1855 | ) / this.getAmperageLimitationUnitDivider() | |
1856 | ); | |
1857 | } | |
1858 | } | |
1859 | ||
c0560973 | 1860 | private async startMessageSequence(): Promise<void> { |
6114e6f1 | 1861 | if (this.stationInfo.autoRegister) { |
f7f98c68 | 1862 | await this.ocppRequestService.requestHandler< |
ef6fa3fb JB |
1863 | BootNotificationRequest, |
1864 | BootNotificationResponse | |
1865 | >( | |
6a8b180d JB |
1866 | RequestCommand.BOOT_NOTIFICATION, |
1867 | { | |
1868 | chargePointModel: this.bootNotificationRequest.chargePointModel, | |
1869 | chargePointVendor: this.bootNotificationRequest.chargePointVendor, | |
1870 | chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber, | |
1871 | firmwareVersion: this.bootNotificationRequest.firmwareVersion, | |
29d1e2e7 JB |
1872 | chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber, |
1873 | iccid: this.bootNotificationRequest.iccid, | |
1874 | imsi: this.bootNotificationRequest.imsi, | |
1875 | meterSerialNumber: this.bootNotificationRequest.meterSerialNumber, | |
1876 | meterType: this.bootNotificationRequest.meterType, | |
6a8b180d JB |
1877 | }, |
1878 | { skipBufferingOnError: true } | |
e7aeea18 | 1879 | ); |
6114e6f1 | 1880 | } |
136c90ba | 1881 | // Start WebSocket ping |
c0560973 | 1882 | this.startWebSocketPing(); |
5ad8570f | 1883 | // Start heartbeat |
c0560973 | 1884 | this.startHeartbeat(); |
0a60c33c | 1885 | // Initialize connectors status |
734d790d JB |
1886 | for (const connectorId of this.connectors.keys()) { |
1887 | if (connectorId === 0) { | |
593cf3f9 | 1888 | continue; |
e7aeea18 JB |
1889 | } else if ( |
1890 | !this.stopped && | |
1891 | !this.getConnectorStatus(connectorId)?.status && | |
1892 | this.getConnectorStatus(connectorId)?.bootStatus | |
1893 | ) { | |
136c90ba | 1894 | // Send status in template at startup |
f7f98c68 | 1895 | await this.ocppRequestService.requestHandler< |
ef6fa3fb JB |
1896 | StatusNotificationRequest, |
1897 | StatusNotificationResponse | |
1898 | >(RequestCommand.STATUS_NOTIFICATION, { | |
1899 | connectorId, | |
1900 | status: this.getConnectorStatus(connectorId).bootStatus, | |
1901 | errorCode: ChargePointErrorCode.NO_ERROR, | |
1902 | }); | |
e7aeea18 JB |
1903 | this.getConnectorStatus(connectorId).status = |
1904 | this.getConnectorStatus(connectorId).bootStatus; | |
1905 | } else if ( | |
1906 | this.stopped && | |
1907 | this.getConnectorStatus(connectorId)?.status && | |
1908 | this.getConnectorStatus(connectorId)?.bootStatus | |
1909 | ) { | |
136c90ba | 1910 | // Send status in template after reset |
f7f98c68 | 1911 | await this.ocppRequestService.requestHandler< |
ef6fa3fb JB |
1912 | StatusNotificationRequest, |
1913 | StatusNotificationResponse | |
1914 | >(RequestCommand.STATUS_NOTIFICATION, { | |
1915 | connectorId, | |
1916 | status: this.getConnectorStatus(connectorId).bootStatus, | |
1917 | errorCode: ChargePointErrorCode.NO_ERROR, | |
1918 | }); | |
e7aeea18 JB |
1919 | this.getConnectorStatus(connectorId).status = |
1920 | this.getConnectorStatus(connectorId).bootStatus; | |
734d790d | 1921 | } else if (!this.stopped && this.getConnectorStatus(connectorId)?.status) { |
136c90ba | 1922 | // Send previous status at template reload |
f7f98c68 | 1923 | await this.ocppRequestService.requestHandler< |
ef6fa3fb JB |
1924 | StatusNotificationRequest, |
1925 | StatusNotificationResponse | |
1926 | >(RequestCommand.STATUS_NOTIFICATION, { | |
1927 | connectorId, | |
1928 | status: this.getConnectorStatus(connectorId).status, | |
1929 | errorCode: ChargePointErrorCode.NO_ERROR, | |
1930 | }); | |
5ad8570f | 1931 | } else { |
136c90ba | 1932 | // Send default status |
f7f98c68 | 1933 | await this.ocppRequestService.requestHandler< |
ef6fa3fb JB |
1934 | StatusNotificationRequest, |
1935 | StatusNotificationResponse | |
1936 | >(RequestCommand.STATUS_NOTIFICATION, { | |
1937 | connectorId, | |
1938 | status: ChargePointStatus.AVAILABLE, | |
1939 | errorCode: ChargePointErrorCode.NO_ERROR, | |
1940 | }); | |
734d790d | 1941 | this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE; |
5ad8570f JB |
1942 | } |
1943 | } | |
0a60c33c | 1944 | // Start the ATG |
dd119a6b | 1945 | this.startAutomaticTransactionGenerator(); |
dd119a6b JB |
1946 | } |
1947 | ||
1948 | private startAutomaticTransactionGenerator() { | |
ad2f27c3 | 1949 | if (this.stationInfo.AutomaticTransactionGenerator.enable) { |
265e4266 | 1950 | if (!this.automaticTransactionGenerator) { |
73b9adec | 1951 | this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance(this); |
5ad8570f | 1952 | } |
265e4266 JB |
1953 | if (!this.automaticTransactionGenerator.started) { |
1954 | this.automaticTransactionGenerator.start(); | |
5ad8570f JB |
1955 | } |
1956 | } | |
5ad8570f JB |
1957 | } |
1958 | ||
e7aeea18 JB |
1959 | private async stopMessageSequence( |
1960 | reason: StopTransactionReason = StopTransactionReason.NONE | |
1961 | ): Promise<void> { | |
136c90ba | 1962 | // Stop WebSocket ping |
c0560973 | 1963 | this.stopWebSocketPing(); |
79411696 | 1964 | // Stop heartbeat |
c0560973 | 1965 | this.stopHeartbeat(); |
79411696 | 1966 | // Stop the ATG |
e7aeea18 JB |
1967 | if ( |
1968 | this.stationInfo.AutomaticTransactionGenerator.enable && | |
1969 | this.automaticTransactionGenerator?.started | |
1970 | ) { | |
0045cef5 | 1971 | this.automaticTransactionGenerator.stop(); |
79411696 | 1972 | } else { |
734d790d JB |
1973 | for (const connectorId of this.connectors.keys()) { |
1974 | if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) { | |
1975 | const transactionId = this.getConnectorStatus(connectorId).transactionId; | |
68c993d5 JB |
1976 | if ( |
1977 | this.getBeginEndMeterValues() && | |
1978 | this.getOcppStrictCompliance() && | |
1979 | !this.getOutOfOrderEndMeterValues() | |
1980 | ) { | |
1981 | // FIXME: Implement OCPP version agnostic helpers | |
1982 | const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue( | |
1983 | this, | |
1984 | connectorId, | |
1985 | this.getEnergyActiveImportRegisterByTransactionId(transactionId) | |
1986 | ); | |
f7f98c68 JB |
1987 | await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>( |
1988 | RequestCommand.METER_VALUES, | |
1989 | { | |
1990 | connectorId, | |
1991 | transactionId, | |
1992 | meterValue: transactionEndMeterValue, | |
1993 | } | |
1994 | ); | |
ef6fa3fb | 1995 | } |
f7f98c68 | 1996 | await this.ocppRequestService.requestHandler< |
ef6fa3fb JB |
1997 | StopTransactionRequest, |
1998 | StopTransactionResponse | |
1999 | >(RequestCommand.STOP_TRANSACTION, { | |
2000 | transactionId, | |
2001 | meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId), | |
2002 | idTag: this.getTransactionIdTag(transactionId), | |
2003 | reason, | |
2004 | }); | |
79411696 JB |
2005 | } |
2006 | } | |
2007 | } | |
2008 | } | |
2009 | ||
c0560973 | 2010 | private startWebSocketPing(): void { |
e7aeea18 JB |
2011 | const webSocketPingInterval: number = this.getConfigurationKey( |
2012 | StandardParametersKey.WebSocketPingInterval | |
2013 | ) | |
2014 | ? Utils.convertToInt( | |
2015 | this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value | |
2016 | ) | |
9cd3dfb0 | 2017 | : 0; |
ad2f27c3 JB |
2018 | if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) { |
2019 | this.webSocketPingSetInterval = setInterval(() => { | |
d5bff457 | 2020 | if (this.isWebSocketConnectionOpened()) { |
e7aeea18 JB |
2021 | this.wsConnection.ping((): void => { |
2022 | /* This is intentional */ | |
2023 | }); | |
136c90ba JB |
2024 | } |
2025 | }, webSocketPingInterval * 1000); | |
e7aeea18 JB |
2026 | logger.info( |
2027 | this.logPrefix() + | |
2028 | ' WebSocket ping started every ' + | |
2029 | Utils.formatDurationSeconds(webSocketPingInterval) | |
2030 | ); | |
ad2f27c3 | 2031 | } else if (this.webSocketPingSetInterval) { |
e7aeea18 JB |
2032 | logger.info( |
2033 | this.logPrefix() + | |
2034 | ' WebSocket ping every ' + | |
2035 | Utils.formatDurationSeconds(webSocketPingInterval) + | |
2036 | ' already started' | |
2037 | ); | |
136c90ba | 2038 | } else { |
e7aeea18 JB |
2039 | logger.error( |
2040 | `${this.logPrefix()} WebSocket ping interval set to ${ | |
2041 | webSocketPingInterval | |
2042 | ? Utils.formatDurationSeconds(webSocketPingInterval) | |
2043 | : webSocketPingInterval | |
2044 | }, not starting the WebSocket ping` | |
2045 | ); | |
136c90ba JB |
2046 | } |
2047 | } | |
2048 | ||
c0560973 | 2049 | private stopWebSocketPing(): void { |
ad2f27c3 JB |
2050 | if (this.webSocketPingSetInterval) { |
2051 | clearInterval(this.webSocketPingSetInterval); | |
136c90ba JB |
2052 | } |
2053 | } | |
2054 | ||
e7aeea18 JB |
2055 | private warnDeprecatedTemplateKey( |
2056 | template: ChargingStationTemplate, | |
2057 | key: string, | |
2058 | chargingStationId: string, | |
2059 | logMsgToAppend = '' | |
2060 | ): void { | |
2dcfe98e | 2061 | if (!Utils.isUndefined(template[key])) { |
e7aeea18 JB |
2062 | const logPrefixStr = ` ${chargingStationId} |`; |
2063 | logger.warn( | |
2064 | `${Utils.logPrefix(logPrefixStr)} Deprecated template key '${key}' usage in file '${ | |
2484ac1e | 2065 | this.templateFile |
e7aeea18 JB |
2066 | }'${logMsgToAppend && '. ' + logMsgToAppend}` |
2067 | ); | |
2dcfe98e JB |
2068 | } |
2069 | } | |
2070 | ||
e7aeea18 JB |
2071 | private convertDeprecatedTemplateKey( |
2072 | template: ChargingStationTemplate, | |
2073 | deprecatedKey: string, | |
2074 | key: string | |
2075 | ): void { | |
2dcfe98e | 2076 | if (!Utils.isUndefined(template[deprecatedKey])) { |
c0f4be74 | 2077 | template[key] = template[deprecatedKey] as unknown; |
2dcfe98e JB |
2078 | delete template[deprecatedKey]; |
2079 | } | |
2080 | } | |
2081 | ||
1f5df42a | 2082 | private getConfiguredSupervisionUrl(): URL { |
e7aeea18 JB |
2083 | const supervisionUrls = Utils.cloneObject<string | string[]>( |
2084 | this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls() | |
2085 | ); | |
c0560973 | 2086 | if (!Utils.isEmptyArray(supervisionUrls)) { |
2dcfe98e JB |
2087 | let urlIndex = 0; |
2088 | switch (Configuration.getSupervisionUrlDistribution()) { | |
2089 | case SupervisionUrlDistribution.ROUND_ROBIN: | |
2090 | urlIndex = (this.index - 1) % supervisionUrls.length; | |
2091 | break; | |
2092 | case SupervisionUrlDistribution.RANDOM: | |
2093 | // Get a random url | |
2094 | urlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length); | |
2095 | break; | |
2096 | case SupervisionUrlDistribution.SEQUENTIAL: | |
2097 | if (this.index <= supervisionUrls.length) { | |
2098 | urlIndex = this.index - 1; | |
2099 | } else { | |
e7aeea18 JB |
2100 | logger.warn( |
2101 | `${this.logPrefix()} No more configured supervision urls available, using the first one` | |
2102 | ); | |
2dcfe98e JB |
2103 | } |
2104 | break; | |
2105 | default: | |
e7aeea18 JB |
2106 | logger.error( |
2107 | `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${ | |
2108 | SupervisionUrlDistribution.ROUND_ROBIN | |
2109 | }` | |
2110 | ); | |
2dcfe98e JB |
2111 | urlIndex = (this.index - 1) % supervisionUrls.length; |
2112 | break; | |
c0560973 | 2113 | } |
2dcfe98e | 2114 | return new URL(supervisionUrls[urlIndex]); |
c0560973 | 2115 | } |
57939a9d | 2116 | return new URL(supervisionUrls as string); |
136c90ba JB |
2117 | } |
2118 | ||
6e0964c8 | 2119 | private getHeartbeatInterval(): number | undefined { |
c0560973 JB |
2120 | const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval); |
2121 | if (HeartbeatInterval) { | |
2122 | return Utils.convertToInt(HeartbeatInterval.value) * 1000; | |
2123 | } | |
2124 | const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval); | |
2125 | if (HeartBeatInterval) { | |
2126 | return Utils.convertToInt(HeartBeatInterval.value) * 1000; | |
0a60c33c | 2127 | } |
e7aeea18 JB |
2128 | !this.stationInfo.autoRegister && |
2129 | logger.warn( | |
2130 | `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${ | |
2131 | Constants.DEFAULT_HEARTBEAT_INTERVAL | |
2132 | }` | |
2133 | ); | |
47e22477 | 2134 | return Constants.DEFAULT_HEARTBEAT_INTERVAL; |
0a60c33c JB |
2135 | } |
2136 | ||
c0560973 | 2137 | private stopHeartbeat(): void { |
ad2f27c3 JB |
2138 | if (this.heartbeatSetInterval) { |
2139 | clearInterval(this.heartbeatSetInterval); | |
7dde0b73 | 2140 | } |
5ad8570f JB |
2141 | } |
2142 | ||
e7aeea18 | 2143 | private openWSConnection( |
2484ac1e | 2144 | options: WsOptions = this.stationInfo.wsOptions, |
e7aeea18 JB |
2145 | forceCloseOpened = false |
2146 | ): void { | |
37486900 | 2147 | options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000; |
e7aeea18 JB |
2148 | if ( |
2149 | !Utils.isNullOrUndefined(this.stationInfo.supervisionUser) && | |
2150 | !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword) | |
2151 | ) { | |
15042c5f JB |
2152 | options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`; |
2153 | } | |
d5bff457 | 2154 | if (this.isWebSocketConnectionOpened() && forceCloseOpened) { |
c0560973 JB |
2155 | this.wsConnection.close(); |
2156 | } | |
88184022 | 2157 | let protocol: string; |
1f5df42a | 2158 | switch (this.getOcppVersion()) { |
c0560973 JB |
2159 | case OCPPVersion.VERSION_16: |
2160 | protocol = 'ocpp' + OCPPVersion.VERSION_16; | |
2161 | break; | |
2162 | default: | |
1f5df42a | 2163 | this.handleUnsupportedVersion(this.getOcppVersion()); |
c0560973 JB |
2164 | break; |
2165 | } | |
2166 | this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options); | |
e7aeea18 JB |
2167 | logger.info( |
2168 | this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString() | |
2169 | ); | |
136c90ba JB |
2170 | } |
2171 | ||
dd119a6b | 2172 | private stopMeterValues(connectorId: number) { |
734d790d JB |
2173 | if (this.getConnectorStatus(connectorId)?.transactionSetInterval) { |
2174 | clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval); | |
dd119a6b JB |
2175 | } |
2176 | } | |
2177 | ||
6e0964c8 | 2178 | private getReconnectExponentialDelay(): boolean | undefined { |
e7aeea18 JB |
2179 | return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) |
2180 | ? this.stationInfo.reconnectExponentialDelay | |
2181 | : false; | |
5ad8570f JB |
2182 | } |
2183 | ||
d09085e9 | 2184 | private async reconnect(code: number): Promise<void> { |
7874b0b1 JB |
2185 | // Stop WebSocket ping |
2186 | this.stopWebSocketPing(); | |
136c90ba | 2187 | // Stop heartbeat |
c0560973 | 2188 | this.stopHeartbeat(); |
5ad8570f | 2189 | // Stop the ATG if needed |
e7aeea18 JB |
2190 | if ( |
2191 | this.stationInfo.AutomaticTransactionGenerator.enable && | |
ad2f27c3 | 2192 | this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure && |
e7aeea18 JB |
2193 | this.automaticTransactionGenerator?.started |
2194 | ) { | |
0045cef5 | 2195 | this.automaticTransactionGenerator.stop(); |
ad2f27c3 | 2196 | } |
e7aeea18 JB |
2197 | if ( |
2198 | this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || | |
2199 | this.getAutoReconnectMaxRetries() === -1 | |
2200 | ) { | |
ad2f27c3 | 2201 | this.autoReconnectRetryCount++; |
e7aeea18 JB |
2202 | const reconnectDelay = this.getReconnectExponentialDelay() |
2203 | ? Utils.exponentialDelay(this.autoReconnectRetryCount) | |
2204 | : this.getConnectionTimeout() * 1000; | |
2205 | const reconnectTimeout = reconnectDelay - 100 > 0 && reconnectDelay; | |
2206 | logger.error( | |
2207 | `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo( | |
2208 | reconnectDelay, | |
2209 | 2 | |
2210 | )}ms, timeout ${reconnectTimeout}ms` | |
2211 | ); | |
032d6efc | 2212 | await Utils.sleep(reconnectDelay); |
e7aeea18 JB |
2213 | logger.error( |
2214 | this.logPrefix() + | |
2215 | ' WebSocket: reconnecting try #' + | |
2216 | this.autoReconnectRetryCount.toString() | |
2217 | ); | |
2218 | this.openWSConnection( | |
2219 | { ...this.stationInfo.wsOptions, handshakeTimeout: reconnectTimeout }, | |
2220 | true | |
2221 | ); | |
265e4266 | 2222 | this.wsConnectionRestarted = true; |
c0560973 | 2223 | } else if (this.getAutoReconnectMaxRetries() !== -1) { |
e7aeea18 | 2224 | logger.error( |
71a77ac2 | 2225 | `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${ |
e7aeea18 JB |
2226 | this.autoReconnectRetryCount |
2227 | }) or retry disabled (${this.getAutoReconnectMaxRetries()})` | |
2228 | ); | |
5ad8570f JB |
2229 | } |
2230 | } | |
2231 | ||
a2653482 JB |
2232 | private initializeConnectorStatus(connectorId: number): void { |
2233 | this.getConnectorStatus(connectorId).idTagLocalAuthorized = false; | |
2234 | this.getConnectorStatus(connectorId).idTagAuthorized = false; | |
2235 | this.getConnectorStatus(connectorId).transactionRemoteStarted = false; | |
734d790d JB |
2236 | this.getConnectorStatus(connectorId).transactionStarted = false; |
2237 | this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0; | |
2238 | this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0; | |
0a60c33c | 2239 | } |
1e5bbb96 | 2240 | |
0bb3ee61 JB |
2241 | /* |
2242 | * Charging profiles should already be sorted by connectorId and stack level (highest stack level has priority) | |
2243 | */ | |
2244 | private getCurrentLimitFromChargingProfiles(chargingProfiles: ChargingProfile[]): { | |
1e5bbb96 O |
2245 | limit: number; |
2246 | matchingChargingProfile: ChargingProfile; | |
0bb3ee61 | 2247 | } | null { |
1e5bbb96 | 2248 | for (const chargingProfile of chargingProfiles) { |
1e5bbb96 | 2249 | // Set helpers |
0bb3ee61 | 2250 | const currentMoment = moment(); |
1e5bbb96 | 2251 | const chargingSchedule = chargingProfile.chargingSchedule; |
0bb3ee61 JB |
2252 | // Check type (recurring) and if it is already active |
2253 | // Adjust the daily recurring schedule to today | |
1e5bbb96 O |
2254 | if ( |
2255 | chargingProfile.chargingProfileKind === ChargingProfileKindType.RECURRING && | |
2256 | chargingProfile.recurrencyKind === RecurrencyKindType.DAILY && | |
0bb3ee61 | 2257 | currentMoment.isAfter(chargingSchedule.startSchedule) |
1e5bbb96 O |
2258 | ) { |
2259 | const currentDate = new Date(); | |
2260 | chargingSchedule.startSchedule = new Date(chargingSchedule.startSchedule); | |
2261 | chargingSchedule.startSchedule.setFullYear( | |
2262 | currentDate.getFullYear(), | |
2263 | currentDate.getMonth(), | |
2264 | currentDate.getDate() | |
2265 | ); | |
2266 | // Check if the start of the schedule is yesterday | |
0bb3ee61 | 2267 | if (moment(chargingSchedule.startSchedule).isAfter(currentMoment)) { |
1e5bbb96 O |
2268 | chargingSchedule.startSchedule.setDate(currentDate.getDate() - 1); |
2269 | } | |
0bb3ee61 | 2270 | } else if (moment(chargingSchedule.startSchedule).isAfter(currentMoment)) { |
1e5bbb96 O |
2271 | return null; |
2272 | } | |
0bb3ee61 JB |
2273 | // Check if the charging profile is active |
2274 | if ( | |
2275 | moment(chargingSchedule.startSchedule) | |
2276 | .add(chargingSchedule.duration, 's') | |
2277 | .isAfter(currentMoment) | |
2278 | ) { | |
1e5bbb96 | 2279 | let lastButOneSchedule: ChargingSchedulePeriod; |
0bb3ee61 | 2280 | // Search the right schedule period |
1e5bbb96 O |
2281 | for (const schedulePeriod of chargingSchedule.chargingSchedulePeriod) { |
2282 | // Handling of only one period | |
2283 | if ( | |
2284 | chargingSchedule.chargingSchedulePeriod.length === 1 && | |
2285 | schedulePeriod.startPeriod === 0 | |
2286 | ) { | |
0bb3ee61 JB |
2287 | const result = { |
2288 | limit: schedulePeriod.limit, | |
2289 | matchingChargingProfile: chargingProfile, | |
2290 | }; | |
2291 | logger.debug( | |
2292 | `${this.logPrefix()} Matching charging profile found for power limitation: %j`, | |
2293 | result | |
2294 | ); | |
2295 | return result; | |
1e5bbb96 | 2296 | } |
0bb3ee61 | 2297 | // Find the right schedule period |
1e5bbb96 | 2298 | if ( |
0bb3ee61 JB |
2299 | moment(chargingSchedule.startSchedule) |
2300 | .add(schedulePeriod.startPeriod, 's') | |
2301 | .isAfter(currentMoment) | |
1e5bbb96 | 2302 | ) { |
0bb3ee61 JB |
2303 | // Found the schedule: last but one is the correct one |
2304 | const result = { | |
2305 | limit: lastButOneSchedule.limit, | |
2306 | matchingChargingProfile: chargingProfile, | |
2307 | }; | |
2308 | logger.debug( | |
2309 | `${this.logPrefix()} Matching charging profile found for power limitation: %j`, | |
2310 | result | |
2311 | ); | |
2312 | return result; | |
1e5bbb96 O |
2313 | } |
2314 | // Keep it | |
2315 | lastButOneSchedule = schedulePeriod; | |
2316 | // Handle the last schedule period | |
2317 | if ( | |
2318 | schedulePeriod.startPeriod === | |
2319 | chargingSchedule.chargingSchedulePeriod[ | |
2320 | chargingSchedule.chargingSchedulePeriod.length - 1 | |
2321 | ].startPeriod | |
2322 | ) { | |
0bb3ee61 JB |
2323 | const result = { |
2324 | limit: lastButOneSchedule.limit, | |
2325 | matchingChargingProfile: chargingProfile, | |
2326 | }; | |
2327 | logger.debug( | |
2328 | `${this.logPrefix()} Matching charging profile found for power limitation: %j`, | |
2329 | result | |
2330 | ); | |
2331 | return result; | |
1e5bbb96 O |
2332 | } |
2333 | } | |
2334 | } | |
2335 | } | |
2336 | return null; | |
2337 | } | |
7dde0b73 | 2338 | } |