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