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