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