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