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