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