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