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