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 JB |
521 | ); |
522 | parentPort.postMessage(MessageChannelUtils.buildStartedMessage(this)); | |
523 | this.starting = false; | |
524 | } else { | |
525 | logger.warn(`${this.logPrefix()} Charging station is already starting...`); | |
526 | } | |
950b1349 | 527 | } else { |
0d8852a5 | 528 | logger.warn(`${this.logPrefix()} Charging station is already started...`); |
950b1349 | 529 | } |
c0560973 JB |
530 | } |
531 | ||
60ddad53 | 532 | public async stop(reason?: StopTransactionReason): Promise<void> { |
0d8852a5 JB |
533 | if (this.started === true) { |
534 | if (this.stopping === false) { | |
535 | this.stopping = true; | |
536 | await this.stopMessageSequence(reason); | |
537 | for (const connectorId of this.connectors.keys()) { | |
538 | if (connectorId > 0) { | |
539 | await this.ocppRequestService.requestHandler< | |
540 | StatusNotificationRequest, | |
541 | StatusNotificationResponse | |
542 | >(this, RequestCommand.STATUS_NOTIFICATION, { | |
543 | connectorId, | |
544 | status: ChargePointStatus.UNAVAILABLE, | |
545 | errorCode: ChargePointErrorCode.NO_ERROR, | |
546 | }); | |
547 | this.getConnectorStatus(connectorId).status = ChargePointStatus.UNAVAILABLE; | |
548 | } | |
950b1349 | 549 | } |
0d8852a5 JB |
550 | this.closeWSConnection(); |
551 | if (this.getEnableStatistics()) { | |
552 | this.performanceStatistics.stop(); | |
553 | } | |
554 | this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash); | |
555 | this.templateFileWatcher.close(); | |
556 | this.sharedLRUCache.deleteChargingStationTemplate(this.stationInfo?.templateHash); | |
557 | this.bootNotificationResponse = null; | |
558 | this.started = false; | |
559 | parentPort.postMessage(MessageChannelUtils.buildStoppedMessage(this)); | |
560 | this.stopping = false; | |
561 | } else { | |
562 | logger.warn(`${this.logPrefix()} Charging station is already stopping...`); | |
c0560973 | 563 | } |
950b1349 | 564 | } else { |
0d8852a5 | 565 | logger.warn(`${this.logPrefix()} Charging station is already stopped...`); |
c0560973 | 566 | } |
c0560973 JB |
567 | } |
568 | ||
60ddad53 JB |
569 | public async reset(reason?: StopTransactionReason): Promise<void> { |
570 | await this.stop(reason); | |
94ec7e96 | 571 | await Utils.sleep(this.stationInfo.resetTime); |
fa7bccf4 | 572 | this.initialize(); |
94ec7e96 JB |
573 | this.start(); |
574 | } | |
575 | ||
17ac262c JB |
576 | public saveOcppConfiguration(): void { |
577 | if (this.getOcppPersistentConfiguration()) { | |
7c72977b | 578 | this.saveConfiguration(); |
e6895390 JB |
579 | } |
580 | } | |
581 | ||
a7fc8211 | 582 | public setChargingProfile(connectorId: number, cp: ChargingProfile): void { |
0bb3ee61 JB |
583 | if (Utils.isNullOrUndefined(this.getConnectorStatus(connectorId).chargingProfiles)) { |
584 | logger.error( | |
585 | `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization` | |
586 | ); | |
587 | this.getConnectorStatus(connectorId).chargingProfiles = []; | |
588 | } | |
53e5fd67 | 589 | if (Array.isArray(this.getConnectorStatus(connectorId).chargingProfiles) === false) { |
0bb3ee61 JB |
590 | logger.error( |
591 | `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an improper attribute type for the charging profiles array, applying proper type initialization` | |
592 | ); | |
1e5bbb96 O |
593 | this.getConnectorStatus(connectorId).chargingProfiles = []; |
594 | } | |
a7fc8211 | 595 | let cpReplaced = false; |
734d790d | 596 | if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId).chargingProfiles)) { |
e7aeea18 JB |
597 | this.getConnectorStatus(connectorId).chargingProfiles?.forEach( |
598 | (chargingProfile: ChargingProfile, index: number) => { | |
599 | if ( | |
600 | chargingProfile.chargingProfileId === cp.chargingProfileId || | |
601 | (chargingProfile.stackLevel === cp.stackLevel && | |
602 | chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose) | |
603 | ) { | |
604 | this.getConnectorStatus(connectorId).chargingProfiles[index] = cp; | |
605 | cpReplaced = true; | |
606 | } | |
c0560973 | 607 | } |
e7aeea18 | 608 | ); |
c0560973 | 609 | } |
734d790d | 610 | !cpReplaced && this.getConnectorStatus(connectorId).chargingProfiles?.push(cp); |
c0560973 JB |
611 | } |
612 | ||
a2653482 JB |
613 | public resetConnectorStatus(connectorId: number): void { |
614 | this.getConnectorStatus(connectorId).idTagLocalAuthorized = false; | |
615 | this.getConnectorStatus(connectorId).idTagAuthorized = false; | |
616 | this.getConnectorStatus(connectorId).transactionRemoteStarted = false; | |
734d790d | 617 | this.getConnectorStatus(connectorId).transactionStarted = false; |
a2653482 | 618 | delete this.getConnectorStatus(connectorId).localAuthorizeIdTag; |
734d790d JB |
619 | delete this.getConnectorStatus(connectorId).authorizeIdTag; |
620 | delete this.getConnectorStatus(connectorId).transactionId; | |
621 | delete this.getConnectorStatus(connectorId).transactionIdTag; | |
622 | this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0; | |
623 | delete this.getConnectorStatus(connectorId).transactionBeginMeterValue; | |
dd119a6b | 624 | this.stopMeterValues(connectorId); |
4f317101 | 625 | parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); |
2e6f5966 JB |
626 | } |
627 | ||
9383b2b1 | 628 | public hasFeatureProfile(featureProfile: SupportedFeatureProfiles): boolean { |
17ac262c JB |
629 | return ChargingStationConfigurationUtils.getConfigurationKey( |
630 | this, | |
631 | StandardParametersKey.SupportedFeatureProfiles | |
632 | )?.value.includes(featureProfile); | |
68cb8b91 JB |
633 | } |
634 | ||
8e242273 JB |
635 | public bufferMessage(message: string): void { |
636 | this.messageBuffer.add(message); | |
3ba2381e JB |
637 | } |
638 | ||
db2336d9 JB |
639 | public openWSConnection( |
640 | options: WsOptions = this.stationInfo?.wsOptions ?? {}, | |
641 | params: { closeOpened?: boolean; terminateOpened?: boolean } = { | |
642 | closeOpened: false, | |
643 | terminateOpened: false, | |
644 | } | |
645 | ): void { | |
646 | options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000; | |
647 | params.closeOpened = params?.closeOpened ?? false; | |
648 | params.terminateOpened = params?.terminateOpened ?? false; | |
649 | if ( | |
650 | !Utils.isNullOrUndefined(this.stationInfo.supervisionUser) && | |
651 | !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword) | |
652 | ) { | |
653 | options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`; | |
654 | } | |
655 | if (params?.closeOpened) { | |
656 | this.closeWSConnection(); | |
657 | } | |
658 | if (params?.terminateOpened) { | |
659 | this.terminateWSConnection(); | |
660 | } | |
661 | let protocol: string; | |
662 | switch (this.getOcppVersion()) { | |
663 | case OCPPVersion.VERSION_16: | |
664 | protocol = 'ocpp' + OCPPVersion.VERSION_16; | |
665 | break; | |
666 | default: | |
667 | this.handleUnsupportedVersion(this.getOcppVersion()); | |
668 | break; | |
669 | } | |
670 | ||
0a03f36c JB |
671 | if (this.isWebSocketConnectionOpened()) { |
672 | logger.warn( | |
673 | `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened` | |
674 | ); | |
675 | return; | |
676 | } | |
677 | ||
db2336d9 | 678 | logger.info( |
0a03f36c | 679 | `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}` |
db2336d9 JB |
680 | ); |
681 | ||
682 | this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options); | |
683 | ||
684 | // Handle WebSocket message | |
685 | this.wsConnection.on( | |
686 | 'message', | |
687 | this.onMessage.bind(this) as (this: WebSocket, data: RawData, isBinary: boolean) => void | |
688 | ); | |
689 | // Handle WebSocket error | |
690 | this.wsConnection.on( | |
691 | 'error', | |
692 | this.onError.bind(this) as (this: WebSocket, error: Error) => void | |
693 | ); | |
694 | // Handle WebSocket close | |
695 | this.wsConnection.on( | |
696 | 'close', | |
697 | this.onClose.bind(this) as (this: WebSocket, code: number, reason: Buffer) => void | |
698 | ); | |
699 | // Handle WebSocket open | |
700 | this.wsConnection.on('open', this.onOpen.bind(this) as (this: WebSocket) => void); | |
701 | // Handle WebSocket ping | |
702 | this.wsConnection.on('ping', this.onPing.bind(this) as (this: WebSocket, data: Buffer) => void); | |
703 | // Handle WebSocket pong | |
704 | this.wsConnection.on('pong', this.onPong.bind(this) as (this: WebSocket, data: Buffer) => void); | |
705 | } | |
706 | ||
707 | public closeWSConnection(): void { | |
708 | if (this.isWebSocketConnectionOpened()) { | |
709 | this.wsConnection.close(); | |
710 | this.wsConnection = null; | |
711 | } | |
712 | } | |
713 | ||
a5e9befc | 714 | public startAutomaticTransactionGenerator(connectorIds?: number[]): void { |
4f69be04 JB |
715 | if (!this.automaticTransactionGenerator) { |
716 | this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance( | |
717 | this.getAutomaticTransactionGeneratorConfigurationFromTemplate(), | |
718 | this | |
719 | ); | |
720 | } | |
a5e9befc JB |
721 | if (!Utils.isEmptyArray(connectorIds)) { |
722 | for (const connectorId of connectorIds) { | |
723 | this.automaticTransactionGenerator.startConnector(connectorId); | |
724 | } | |
725 | } else { | |
4f69be04 JB |
726 | this.automaticTransactionGenerator.start(); |
727 | } | |
23253faf | 728 | parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); |
4f69be04 JB |
729 | } |
730 | ||
a5e9befc JB |
731 | public stopAutomaticTransactionGenerator(connectorIds?: number[]): void { |
732 | if (!Utils.isEmptyArray(connectorIds)) { | |
733 | for (const connectorId of connectorIds) { | |
734 | this.automaticTransactionGenerator?.stopConnector(connectorId); | |
735 | } | |
736 | } else { | |
737 | this.automaticTransactionGenerator?.stop(); | |
4f69be04 | 738 | } |
23253faf | 739 | parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); |
4f69be04 JB |
740 | } |
741 | ||
5e3cb728 JB |
742 | public async stopTransactionOnConnector( |
743 | connectorId: number, | |
744 | reason = StopTransactionReason.NONE | |
745 | ): Promise<StopTransactionResponse> { | |
746 | const transactionId = this.getConnectorStatus(connectorId).transactionId; | |
747 | if ( | |
748 | this.getBeginEndMeterValues() && | |
749 | this.getOcppStrictCompliance() && | |
750 | !this.getOutOfOrderEndMeterValues() | |
751 | ) { | |
752 | // FIXME: Implement OCPP version agnostic helpers | |
753 | const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue( | |
754 | this, | |
755 | connectorId, | |
756 | this.getEnergyActiveImportRegisterByTransactionId(transactionId) | |
757 | ); | |
758 | await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>( | |
759 | this, | |
760 | RequestCommand.METER_VALUES, | |
761 | { | |
762 | connectorId, | |
763 | transactionId, | |
764 | meterValue: [transactionEndMeterValue], | |
765 | } | |
766 | ); | |
767 | } | |
768 | return this.ocppRequestService.requestHandler<StopTransactionRequest, StopTransactionResponse>( | |
769 | this, | |
770 | RequestCommand.STOP_TRANSACTION, | |
771 | { | |
772 | transactionId, | |
773 | meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId, true), | |
5e3cb728 JB |
774 | reason, |
775 | } | |
776 | ); | |
777 | } | |
778 | ||
f90c1757 | 779 | private flushMessageBuffer(): void { |
8e242273 JB |
780 | if (this.messageBuffer.size > 0) { |
781 | this.messageBuffer.forEach((message) => { | |
aef1b33a | 782 | // TODO: evaluate the need to track performance |
77f00f84 | 783 | this.wsConnection.send(message); |
8e242273 | 784 | this.messageBuffer.delete(message); |
77f00f84 JB |
785 | }); |
786 | } | |
787 | } | |
788 | ||
1f5df42a JB |
789 | private getSupervisionUrlOcppConfiguration(): boolean { |
790 | return this.stationInfo.supervisionUrlOcppConfiguration ?? false; | |
12fc74d6 JB |
791 | } |
792 | ||
e8e865ea JB |
793 | private getSupervisionUrlOcppKey(): string { |
794 | return this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl; | |
795 | } | |
796 | ||
9214b603 | 797 | private getTemplateFromFile(): ChargingStationTemplate | null { |
2484ac1e | 798 | let template: ChargingStationTemplate = null; |
5ad8570f | 799 | try { |
57adbebc JB |
800 | if (this.sharedLRUCache.hasChargingStationTemplate(this.stationInfo?.templateHash)) { |
801 | template = this.sharedLRUCache.getChargingStationTemplate(this.stationInfo.templateHash); | |
7c72977b JB |
802 | } else { |
803 | const measureId = `${FileType.ChargingStationTemplate} read`; | |
804 | const beginId = PerformanceStatistics.beginMeasure(measureId); | |
805 | template = JSON.parse( | |
806 | fs.readFileSync(this.templateFile, 'utf8') | |
807 | ) as ChargingStationTemplate; | |
808 | PerformanceStatistics.endMeasure(measureId, beginId); | |
809 | template.templateHash = crypto | |
810 | .createHash(Constants.DEFAULT_HASH_ALGORITHM) | |
811 | .update(JSON.stringify(template)) | |
812 | .digest('hex'); | |
57adbebc | 813 | this.sharedLRUCache.setChargingStationTemplate(template); |
7c72977b | 814 | } |
5ad8570f | 815 | } catch (error) { |
e7aeea18 JB |
816 | FileUtils.handleFileException( |
817 | this.logPrefix(), | |
a95873d8 | 818 | FileType.ChargingStationTemplate, |
2484ac1e | 819 | this.templateFile, |
e7aeea18 JB |
820 | error as NodeJS.ErrnoException |
821 | ); | |
5ad8570f | 822 | } |
2484ac1e JB |
823 | return template; |
824 | } | |
825 | ||
7a3a2ebb | 826 | private getStationInfoFromTemplate(): ChargingStationInfo { |
fa7bccf4 JB |
827 | const stationTemplate: ChargingStationTemplate = this.getTemplateFromFile(); |
828 | if (Utils.isNullOrUndefined(stationTemplate)) { | |
ccb1d6e9 JB |
829 | const errorMsg = 'Failed to read charging station template file'; |
830 | logger.error(`${this.logPrefix()} ${errorMsg}`); | |
831 | throw new BaseError(errorMsg); | |
94ec7e96 | 832 | } |
fa7bccf4 | 833 | if (Utils.isEmptyObject(stationTemplate)) { |
ccb1d6e9 JB |
834 | const errorMsg = `Empty charging station information from template file ${this.templateFile}`; |
835 | logger.error(`${this.logPrefix()} ${errorMsg}`); | |
836 | throw new BaseError(errorMsg); | |
94ec7e96 | 837 | } |
2dcfe98e | 838 | // Deprecation template keys section |
17ac262c | 839 | ChargingStationUtils.warnDeprecatedTemplateKey( |
fa7bccf4 | 840 | stationTemplate, |
e7aeea18 | 841 | 'supervisionUrl', |
17ac262c | 842 | this.templateFile, |
ccb1d6e9 | 843 | this.logPrefix(), |
e7aeea18 JB |
844 | "Use 'supervisionUrls' instead" |
845 | ); | |
17ac262c | 846 | ChargingStationUtils.convertDeprecatedTemplateKey( |
fa7bccf4 | 847 | stationTemplate, |
17ac262c JB |
848 | 'supervisionUrl', |
849 | 'supervisionUrls' | |
850 | ); | |
fa7bccf4 JB |
851 | const stationInfo: ChargingStationInfo = |
852 | ChargingStationUtils.stationTemplateToStationInfo(stationTemplate); | |
51c83d6f | 853 | stationInfo.hashId = ChargingStationUtils.getHashId(this.index, stationTemplate); |
fa7bccf4 JB |
854 | stationInfo.chargingStationId = ChargingStationUtils.getChargingStationId( |
855 | this.index, | |
856 | stationTemplate | |
857 | ); | |
858 | ChargingStationUtils.createSerialNumber(stationTemplate, stationInfo); | |
859 | if (!Utils.isEmptyArray(stationTemplate.power)) { | |
860 | stationTemplate.power = stationTemplate.power as number[]; | |
861 | const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationTemplate.power.length); | |
cc6e8ab5 | 862 | stationInfo.maximumPower = |
fa7bccf4 JB |
863 | stationTemplate.powerUnit === PowerUnits.KILO_WATT |
864 | ? stationTemplate.power[powerArrayRandomIndex] * 1000 | |
865 | : stationTemplate.power[powerArrayRandomIndex]; | |
5ad8570f | 866 | } else { |
fa7bccf4 | 867 | stationTemplate.power = stationTemplate.power as number; |
cc6e8ab5 | 868 | stationInfo.maximumPower = |
fa7bccf4 JB |
869 | stationTemplate.powerUnit === PowerUnits.KILO_WATT |
870 | ? stationTemplate.power * 1000 | |
871 | : stationTemplate.power; | |
872 | } | |
873 | stationInfo.resetTime = stationTemplate.resetTime | |
874 | ? stationTemplate.resetTime * 1000 | |
e7aeea18 | 875 | : Constants.CHARGING_STATION_DEFAULT_RESET_TIME; |
c72f6634 JB |
876 | const configuredMaxConnectors = |
877 | ChargingStationUtils.getConfiguredNumberOfConnectors(stationTemplate); | |
fa7bccf4 JB |
878 | ChargingStationUtils.checkConfiguredMaxConnectors( |
879 | configuredMaxConnectors, | |
880 | this.templateFile, | |
fc040c43 | 881 | this.logPrefix() |
fa7bccf4 JB |
882 | ); |
883 | const templateMaxConnectors = | |
884 | ChargingStationUtils.getTemplateMaxNumberOfConnectors(stationTemplate); | |
885 | ChargingStationUtils.checkTemplateMaxConnectors( | |
886 | templateMaxConnectors, | |
887 | this.templateFile, | |
fc040c43 | 888 | this.logPrefix() |
fa7bccf4 JB |
889 | ); |
890 | if ( | |
891 | configuredMaxConnectors > | |
892 | (stationTemplate?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && | |
893 | !stationTemplate?.randomConnectors | |
894 | ) { | |
895 | logger.warn( | |
896 | `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${ | |
897 | this.templateFile | |
898 | }, forcing random connector configurations affectation` | |
899 | ); | |
900 | stationInfo.randomConnectors = true; | |
901 | } | |
902 | // Build connectors if needed (FIXME: should be factored out) | |
903 | this.initializeConnectors(stationInfo, configuredMaxConnectors, templateMaxConnectors); | |
904 | stationInfo.maximumAmperage = this.getMaximumAmperage(stationInfo); | |
905 | ChargingStationUtils.createStationInfoHash(stationInfo); | |
9ac86a7e | 906 | return stationInfo; |
5ad8570f JB |
907 | } |
908 | ||
ccb1d6e9 JB |
909 | private getStationInfoFromFile(): ChargingStationInfo | null { |
910 | let stationInfo: ChargingStationInfo = null; | |
fa7bccf4 JB |
911 | this.getStationInfoPersistentConfiguration() && |
912 | (stationInfo = this.getConfigurationFromFile()?.stationInfo ?? null); | |
913 | stationInfo && ChargingStationUtils.createStationInfoHash(stationInfo); | |
f765beaa | 914 | return stationInfo; |
2484ac1e JB |
915 | } |
916 | ||
917 | private getStationInfo(): ChargingStationInfo { | |
918 | const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate(); | |
2484ac1e | 919 | const stationInfoFromFile: ChargingStationInfo = this.getStationInfoFromFile(); |
aca53a1a | 920 | // Priority: charging station info from template > charging station info from configuration file > charging station info attribute |
f765beaa | 921 | if (stationInfoFromFile?.templateHash === stationInfoFromTemplate.templateHash) { |
01efc60a JB |
922 | if (this.stationInfo?.infoHash === stationInfoFromFile?.infoHash) { |
923 | return this.stationInfo; | |
924 | } | |
2484ac1e | 925 | return stationInfoFromFile; |
f765beaa | 926 | } |
fec4d204 JB |
927 | stationInfoFromFile && |
928 | ChargingStationUtils.propagateSerialNumber( | |
929 | this.getTemplateFromFile(), | |
930 | stationInfoFromFile, | |
931 | stationInfoFromTemplate | |
932 | ); | |
01efc60a | 933 | return stationInfoFromTemplate; |
2484ac1e JB |
934 | } |
935 | ||
936 | private saveStationInfo(): void { | |
ccb1d6e9 | 937 | if (this.getStationInfoPersistentConfiguration()) { |
7c72977b | 938 | this.saveConfiguration(); |
ccb1d6e9 | 939 | } |
2484ac1e JB |
940 | } |
941 | ||
1f5df42a | 942 | private getOcppVersion(): OCPPVersion { |
aba95196 | 943 | return this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16; |
c0560973 JB |
944 | } |
945 | ||
e8e865ea | 946 | private getOcppPersistentConfiguration(): boolean { |
ccb1d6e9 JB |
947 | return this.stationInfo?.ocppPersistentConfiguration ?? true; |
948 | } | |
949 | ||
950 | private getStationInfoPersistentConfiguration(): boolean { | |
951 | return this.stationInfo?.stationInfoPersistentConfiguration ?? true; | |
e8e865ea JB |
952 | } |
953 | ||
c0560973 | 954 | private handleUnsupportedVersion(version: OCPPVersion) { |
fc040c43 JB |
955 | const errMsg = `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`; |
956 | logger.error(`${this.logPrefix()} ${errMsg}`); | |
6c8f5d90 | 957 | throw new BaseError(errMsg); |
c0560973 JB |
958 | } |
959 | ||
2484ac1e | 960 | private initialize(): void { |
fa7bccf4 | 961 | this.configurationFile = path.join( |
ee5f26a2 | 962 | path.dirname(this.templateFile.replace('station-templates', 'configurations')), |
b44b779a | 963 | ChargingStationUtils.getHashId(this.index, this.getTemplateFromFile()) + '.json' |
0642c3d2 | 964 | ); |
b44b779a JB |
965 | this.stationInfo = this.getStationInfo(); |
966 | this.saveStationInfo(); | |
967 | logger.info(`${this.logPrefix()} Charging station hashId '${this.stationInfo.hashId}'`); | |
7a3a2ebb | 968 | // Avoid duplication of connectors related information in RAM |
94ec7e96 | 969 | this.stationInfo?.Connectors && delete this.stationInfo.Connectors; |
fa7bccf4 | 970 | this.configuredSupervisionUrl = this.getConfiguredSupervisionUrl(); |
0642c3d2 JB |
971 | if (this.getEnableStatistics()) { |
972 | this.performanceStatistics = PerformanceStatistics.getInstance( | |
51c83d6f | 973 | this.stationInfo.hashId, |
0642c3d2 | 974 | this.stationInfo.chargingStationId, |
fa7bccf4 | 975 | this.configuredSupervisionUrl |
0642c3d2 JB |
976 | ); |
977 | } | |
fa7bccf4 JB |
978 | this.bootNotificationRequest = ChargingStationUtils.createBootNotificationRequest( |
979 | this.stationInfo | |
980 | ); | |
fa7bccf4 JB |
981 | this.powerDivider = this.getPowerDivider(); |
982 | // OCPP configuration | |
983 | this.ocppConfiguration = this.getOcppConfiguration(); | |
984 | this.initializeOcppConfiguration(); | |
1f5df42a | 985 | switch (this.getOcppVersion()) { |
c0560973 | 986 | case OCPPVersion.VERSION_16: |
e7aeea18 | 987 | this.ocppIncomingRequestService = |
08f130a0 | 988 | OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>(); |
e7aeea18 | 989 | this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>( |
08f130a0 | 990 | OCPP16ResponseService.getInstance<OCPP16ResponseService>() |
e7aeea18 | 991 | ); |
c0560973 JB |
992 | break; |
993 | default: | |
1f5df42a | 994 | this.handleUnsupportedVersion(this.getOcppVersion()); |
c0560973 JB |
995 | break; |
996 | } | |
7c72977b | 997 | if (this.stationInfo?.autoRegister) { |
47e22477 JB |
998 | this.bootNotificationResponse = { |
999 | currentTime: new Date().toISOString(), | |
1000 | interval: this.getHeartbeatInterval() / 1000, | |
e7aeea18 | 1001 | status: RegistrationStatus.ACCEPTED, |
47e22477 JB |
1002 | }; |
1003 | } | |
147d0e0f JB |
1004 | } |
1005 | ||
2484ac1e | 1006 | private initializeOcppConfiguration(): void { |
17ac262c JB |
1007 | if ( |
1008 | !ChargingStationConfigurationUtils.getConfigurationKey( | |
1009 | this, | |
1010 | StandardParametersKey.HeartbeatInterval | |
1011 | ) | |
1012 | ) { | |
1013 | ChargingStationConfigurationUtils.addConfigurationKey( | |
1014 | this, | |
1015 | StandardParametersKey.HeartbeatInterval, | |
1016 | '0' | |
1017 | ); | |
f0f65a62 | 1018 | } |
17ac262c JB |
1019 | if ( |
1020 | !ChargingStationConfigurationUtils.getConfigurationKey( | |
1021 | this, | |
1022 | StandardParametersKey.HeartBeatInterval | |
1023 | ) | |
1024 | ) { | |
1025 | ChargingStationConfigurationUtils.addConfigurationKey( | |
1026 | this, | |
1027 | StandardParametersKey.HeartBeatInterval, | |
1028 | '0', | |
1029 | { visible: false } | |
1030 | ); | |
f0f65a62 | 1031 | } |
e7aeea18 JB |
1032 | if ( |
1033 | this.getSupervisionUrlOcppConfiguration() && | |
17ac262c | 1034 | !ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey()) |
e7aeea18 | 1035 | ) { |
17ac262c JB |
1036 | ChargingStationConfigurationUtils.addConfigurationKey( |
1037 | this, | |
a59737e3 | 1038 | this.getSupervisionUrlOcppKey(), |
fa7bccf4 | 1039 | this.configuredSupervisionUrl.href, |
e7aeea18 JB |
1040 | { reboot: true } |
1041 | ); | |
e6895390 JB |
1042 | } else if ( |
1043 | !this.getSupervisionUrlOcppConfiguration() && | |
17ac262c | 1044 | ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey()) |
e6895390 | 1045 | ) { |
17ac262c JB |
1046 | ChargingStationConfigurationUtils.deleteConfigurationKey( |
1047 | this, | |
1048 | this.getSupervisionUrlOcppKey(), | |
1049 | { save: false } | |
1050 | ); | |
12fc74d6 | 1051 | } |
cc6e8ab5 JB |
1052 | if ( |
1053 | this.stationInfo.amperageLimitationOcppKey && | |
17ac262c JB |
1054 | !ChargingStationConfigurationUtils.getConfigurationKey( |
1055 | this, | |
1056 | this.stationInfo.amperageLimitationOcppKey | |
1057 | ) | |
cc6e8ab5 | 1058 | ) { |
17ac262c JB |
1059 | ChargingStationConfigurationUtils.addConfigurationKey( |
1060 | this, | |
cc6e8ab5 | 1061 | this.stationInfo.amperageLimitationOcppKey, |
17ac262c JB |
1062 | ( |
1063 | this.stationInfo.maximumAmperage * | |
1064 | ChargingStationUtils.getAmperageLimitationUnitDivider(this.stationInfo) | |
1065 | ).toString() | |
cc6e8ab5 JB |
1066 | ); |
1067 | } | |
17ac262c JB |
1068 | if ( |
1069 | !ChargingStationConfigurationUtils.getConfigurationKey( | |
1070 | this, | |
1071 | StandardParametersKey.SupportedFeatureProfiles | |
1072 | ) | |
1073 | ) { | |
1074 | ChargingStationConfigurationUtils.addConfigurationKey( | |
1075 | this, | |
e7aeea18 | 1076 | StandardParametersKey.SupportedFeatureProfiles, |
b22787b4 | 1077 | `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}` |
e7aeea18 JB |
1078 | ); |
1079 | } | |
17ac262c JB |
1080 | ChargingStationConfigurationUtils.addConfigurationKey( |
1081 | this, | |
e7aeea18 JB |
1082 | StandardParametersKey.NumberOfConnectors, |
1083 | this.getNumberOfConnectors().toString(), | |
a95873d8 JB |
1084 | { readonly: true }, |
1085 | { overwrite: true } | |
e7aeea18 | 1086 | ); |
17ac262c JB |
1087 | if ( |
1088 | !ChargingStationConfigurationUtils.getConfigurationKey( | |
1089 | this, | |
1090 | StandardParametersKey.MeterValuesSampledData | |
1091 | ) | |
1092 | ) { | |
1093 | ChargingStationConfigurationUtils.addConfigurationKey( | |
1094 | this, | |
e7aeea18 JB |
1095 | StandardParametersKey.MeterValuesSampledData, |
1096 | MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER | |
1097 | ); | |
7abfea5f | 1098 | } |
17ac262c JB |
1099 | if ( |
1100 | !ChargingStationConfigurationUtils.getConfigurationKey( | |
1101 | this, | |
1102 | StandardParametersKey.ConnectorPhaseRotation | |
1103 | ) | |
1104 | ) { | |
7e1dc878 | 1105 | const connectorPhaseRotation = []; |
734d790d | 1106 | for (const connectorId of this.connectors.keys()) { |
7e1dc878 | 1107 | // AC/DC |
734d790d JB |
1108 | if (connectorId === 0 && this.getNumberOfPhases() === 0) { |
1109 | connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`); | |
1110 | } else if (connectorId > 0 && this.getNumberOfPhases() === 0) { | |
1111 | connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`); | |
e7aeea18 | 1112 | // AC |
734d790d JB |
1113 | } else if (connectorId > 0 && this.getNumberOfPhases() === 1) { |
1114 | connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`); | |
1115 | } else if (connectorId > 0 && this.getNumberOfPhases() === 3) { | |
1116 | connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`); | |
7e1dc878 JB |
1117 | } |
1118 | } | |
17ac262c JB |
1119 | ChargingStationConfigurationUtils.addConfigurationKey( |
1120 | this, | |
e7aeea18 JB |
1121 | StandardParametersKey.ConnectorPhaseRotation, |
1122 | connectorPhaseRotation.toString() | |
1123 | ); | |
7e1dc878 | 1124 | } |
e7aeea18 | 1125 | if ( |
17ac262c JB |
1126 | !ChargingStationConfigurationUtils.getConfigurationKey( |
1127 | this, | |
1128 | StandardParametersKey.AuthorizeRemoteTxRequests | |
e7aeea18 JB |
1129 | ) |
1130 | ) { | |
17ac262c JB |
1131 | ChargingStationConfigurationUtils.addConfigurationKey( |
1132 | this, | |
1133 | StandardParametersKey.AuthorizeRemoteTxRequests, | |
1134 | 'true' | |
1135 | ); | |
36f6a92e | 1136 | } |
17ac262c JB |
1137 | if ( |
1138 | !ChargingStationConfigurationUtils.getConfigurationKey( | |
1139 | this, | |
1140 | StandardParametersKey.LocalAuthListEnabled | |
1141 | ) && | |
1142 | ChargingStationConfigurationUtils.getConfigurationKey( | |
1143 | this, | |
1144 | StandardParametersKey.SupportedFeatureProfiles | |
1145 | )?.value.includes(SupportedFeatureProfiles.LocalAuthListManagement) | |
1146 | ) { | |
1147 | ChargingStationConfigurationUtils.addConfigurationKey( | |
1148 | this, | |
1149 | StandardParametersKey.LocalAuthListEnabled, | |
1150 | 'false' | |
1151 | ); | |
1152 | } | |
1153 | if ( | |
1154 | !ChargingStationConfigurationUtils.getConfigurationKey( | |
1155 | this, | |
1156 | StandardParametersKey.ConnectionTimeOut | |
1157 | ) | |
1158 | ) { | |
1159 | ChargingStationConfigurationUtils.addConfigurationKey( | |
1160 | this, | |
e7aeea18 JB |
1161 | StandardParametersKey.ConnectionTimeOut, |
1162 | Constants.DEFAULT_CONNECTION_TIMEOUT.toString() | |
1163 | ); | |
8bce55bf | 1164 | } |
2484ac1e | 1165 | this.saveOcppConfiguration(); |
073bd098 JB |
1166 | } |
1167 | ||
3d25cc86 JB |
1168 | private initializeConnectors( |
1169 | stationInfo: ChargingStationInfo, | |
fa7bccf4 | 1170 | configuredMaxConnectors: number, |
3d25cc86 JB |
1171 | templateMaxConnectors: number |
1172 | ): void { | |
1173 | if (!stationInfo?.Connectors && this.connectors.size === 0) { | |
fc040c43 JB |
1174 | const logMsg = `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`; |
1175 | logger.error(`${this.logPrefix()} ${logMsg}`); | |
3d25cc86 JB |
1176 | throw new BaseError(logMsg); |
1177 | } | |
1178 | if (!stationInfo?.Connectors[0]) { | |
1179 | logger.warn( | |
1180 | `${this.logPrefix()} Charging station information from template ${ | |
1181 | this.templateFile | |
1182 | } with no connector Id 0 configuration` | |
1183 | ); | |
1184 | } | |
1185 | if (stationInfo?.Connectors) { | |
1186 | const connectorsConfigHash = crypto | |
1187 | .createHash(Constants.DEFAULT_HASH_ALGORITHM) | |
fa7bccf4 | 1188 | .update(JSON.stringify(stationInfo?.Connectors) + configuredMaxConnectors.toString()) |
3d25cc86 JB |
1189 | .digest('hex'); |
1190 | const connectorsConfigChanged = | |
1191 | this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash; | |
1192 | if (this.connectors?.size === 0 || connectorsConfigChanged) { | |
1193 | connectorsConfigChanged && this.connectors.clear(); | |
1194 | this.connectorsConfigurationHash = connectorsConfigHash; | |
1195 | // Add connector Id 0 | |
1196 | let lastConnector = '0'; | |
1197 | for (lastConnector in stationInfo?.Connectors) { | |
1198 | const lastConnectorId = Utils.convertToInt(lastConnector); | |
1199 | if ( | |
1200 | lastConnectorId === 0 && | |
bb83b5ed | 1201 | this.getUseConnectorId0(stationInfo) === true && |
3d25cc86 JB |
1202 | stationInfo?.Connectors[lastConnector] |
1203 | ) { | |
1204 | this.connectors.set( | |
1205 | lastConnectorId, | |
1206 | Utils.cloneObject<ConnectorStatus>(stationInfo?.Connectors[lastConnector]) | |
1207 | ); | |
1208 | this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE; | |
1209 | if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) { | |
1210 | this.getConnectorStatus(lastConnectorId).chargingProfiles = []; | |
1211 | } | |
1212 | } | |
1213 | } | |
1214 | // Generate all connectors | |
1215 | if ((stationInfo?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) { | |
fa7bccf4 | 1216 | for (let index = 1; index <= configuredMaxConnectors; index++) { |
ccb1d6e9 | 1217 | const randConnectorId = stationInfo?.randomConnectors |
3d25cc86 JB |
1218 | ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1) |
1219 | : index; | |
1220 | this.connectors.set( | |
1221 | index, | |
1222 | Utils.cloneObject<ConnectorStatus>(stationInfo?.Connectors[randConnectorId]) | |
1223 | ); | |
1224 | this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE; | |
1225 | if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) { | |
1226 | this.getConnectorStatus(index).chargingProfiles = []; | |
1227 | } | |
1228 | } | |
1229 | } | |
1230 | } | |
1231 | } else { | |
1232 | logger.warn( | |
1233 | `${this.logPrefix()} Charging station information from template ${ | |
1234 | this.templateFile | |
1235 | } with no connectors configuration defined, using already defined connectors` | |
1236 | ); | |
1237 | } | |
1238 | // Initialize transaction attributes on connectors | |
1239 | for (const connectorId of this.connectors.keys()) { | |
1984f194 JB |
1240 | if ( |
1241 | connectorId > 0 && | |
1242 | (this.getConnectorStatus(connectorId).transactionStarted === undefined || | |
1243 | this.getConnectorStatus(connectorId).transactionStarted === false) | |
1244 | ) { | |
3d25cc86 JB |
1245 | this.initializeConnectorStatus(connectorId); |
1246 | } | |
1247 | } | |
1248 | } | |
1249 | ||
7f7b65ca | 1250 | private getConfigurationFromFile(): ChargingStationConfiguration | null { |
073bd098 | 1251 | let configuration: ChargingStationConfiguration = null; |
2484ac1e | 1252 | if (this.configurationFile && fs.existsSync(this.configurationFile)) { |
073bd098 | 1253 | try { |
57adbebc JB |
1254 | if (this.sharedLRUCache.hasChargingStationConfiguration(this.configurationFileHash)) { |
1255 | configuration = this.sharedLRUCache.getChargingStationConfiguration( | |
1256 | this.configurationFileHash | |
1257 | ); | |
7c72977b JB |
1258 | } else { |
1259 | const measureId = `${FileType.ChargingStationConfiguration} read`; | |
1260 | const beginId = PerformanceStatistics.beginMeasure(measureId); | |
1261 | configuration = JSON.parse( | |
1262 | fs.readFileSync(this.configurationFile, 'utf8') | |
1263 | ) as ChargingStationConfiguration; | |
1264 | PerformanceStatistics.endMeasure(measureId, beginId); | |
1265 | this.configurationFileHash = configuration.configurationHash; | |
57adbebc | 1266 | this.sharedLRUCache.setChargingStationConfiguration(configuration); |
7c72977b | 1267 | } |
073bd098 JB |
1268 | } catch (error) { |
1269 | FileUtils.handleFileException( | |
1270 | this.logPrefix(), | |
a95873d8 | 1271 | FileType.ChargingStationConfiguration, |
073bd098 JB |
1272 | this.configurationFile, |
1273 | error as NodeJS.ErrnoException | |
1274 | ); | |
1275 | } | |
1276 | } | |
1277 | return configuration; | |
1278 | } | |
1279 | ||
7c72977b | 1280 | private saveConfiguration(): void { |
2484ac1e JB |
1281 | if (this.configurationFile) { |
1282 | try { | |
2484ac1e JB |
1283 | if (!fs.existsSync(path.dirname(this.configurationFile))) { |
1284 | fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true }); | |
073bd098 | 1285 | } |
ccb1d6e9 JB |
1286 | const configurationData: ChargingStationConfiguration = |
1287 | this.getConfigurationFromFile() ?? {}; | |
7c72977b JB |
1288 | this.ocppConfiguration?.configurationKey && |
1289 | (configurationData.configurationKey = this.ocppConfiguration.configurationKey); | |
1290 | this.stationInfo && (configurationData.stationInfo = this.stationInfo); | |
1291 | delete configurationData.configurationHash; | |
1292 | const configurationHash = crypto | |
1293 | .createHash(Constants.DEFAULT_HASH_ALGORITHM) | |
1294 | .update(JSON.stringify(configurationData)) | |
1295 | .digest('hex'); | |
1296 | if (this.configurationFileHash !== configurationHash) { | |
1297 | configurationData.configurationHash = configurationHash; | |
1298 | const measureId = `${FileType.ChargingStationConfiguration} write`; | |
1299 | const beginId = PerformanceStatistics.beginMeasure(measureId); | |
1300 | const fileDescriptor = fs.openSync(this.configurationFile, 'w'); | |
1301 | fs.writeFileSync(fileDescriptor, JSON.stringify(configurationData, null, 2), 'utf8'); | |
1302 | fs.closeSync(fileDescriptor); | |
1303 | PerformanceStatistics.endMeasure(measureId, beginId); | |
57adbebc | 1304 | this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash); |
7c72977b | 1305 | this.configurationFileHash = configurationHash; |
57adbebc | 1306 | this.sharedLRUCache.setChargingStationConfiguration(configurationData); |
7c72977b JB |
1307 | } else { |
1308 | logger.debug( | |
1309 | `${this.logPrefix()} Not saving unchanged charging station configuration file ${ | |
1310 | this.configurationFile | |
1311 | }` | |
1312 | ); | |
2484ac1e | 1313 | } |
2484ac1e JB |
1314 | } catch (error) { |
1315 | FileUtils.handleFileException( | |
1316 | this.logPrefix(), | |
1317 | FileType.ChargingStationConfiguration, | |
1318 | this.configurationFile, | |
1319 | error as NodeJS.ErrnoException | |
073bd098 JB |
1320 | ); |
1321 | } | |
2484ac1e JB |
1322 | } else { |
1323 | logger.error( | |
01efc60a | 1324 | `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file` |
2484ac1e | 1325 | ); |
073bd098 JB |
1326 | } |
1327 | } | |
1328 | ||
ccb1d6e9 JB |
1329 | private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration | null { |
1330 | return this.getTemplateFromFile()?.Configuration ?? null; | |
2484ac1e JB |
1331 | } |
1332 | ||
1333 | private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | null { | |
1334 | let configuration: ChargingStationConfiguration = null; | |
1335 | if (this.getOcppPersistentConfiguration()) { | |
7a3a2ebb JB |
1336 | const configurationFromFile = this.getConfigurationFromFile(); |
1337 | configuration = configurationFromFile?.configurationKey && configurationFromFile; | |
073bd098 | 1338 | } |
2484ac1e | 1339 | configuration && delete configuration.stationInfo; |
073bd098 | 1340 | return configuration; |
7dde0b73 JB |
1341 | } |
1342 | ||
ccb1d6e9 | 1343 | private getOcppConfiguration(): ChargingStationOcppConfiguration | null { |
2484ac1e JB |
1344 | let ocppConfiguration: ChargingStationOcppConfiguration = this.getOcppConfigurationFromFile(); |
1345 | if (!ocppConfiguration) { | |
1346 | ocppConfiguration = this.getOcppConfigurationFromTemplate(); | |
1347 | } | |
1348 | return ocppConfiguration; | |
1349 | } | |
1350 | ||
c0560973 | 1351 | private async onOpen(): Promise<void> { |
5144f4d1 JB |
1352 | if (this.isWebSocketConnectionOpened()) { |
1353 | logger.info( | |
1354 | `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded` | |
1355 | ); | |
94bb24d5 | 1356 | if (!this.isRegistered()) { |
5144f4d1 JB |
1357 | // Send BootNotification |
1358 | let registrationRetryCount = 0; | |
1359 | do { | |
f7f98c68 | 1360 | this.bootNotificationResponse = await this.ocppRequestService.requestHandler< |
5144f4d1 JB |
1361 | BootNotificationRequest, |
1362 | BootNotificationResponse | |
8bfbc743 JB |
1363 | >(this, RequestCommand.BOOT_NOTIFICATION, this.bootNotificationRequest, { |
1364 | skipBufferingOnError: true, | |
1365 | }); | |
94bb24d5 | 1366 | if (!this.isRegistered()) { |
5144f4d1 JB |
1367 | this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++; |
1368 | await Utils.sleep( | |
1369 | this.bootNotificationResponse?.interval | |
1370 | ? this.bootNotificationResponse.interval * 1000 | |
1371 | : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL | |
1372 | ); | |
1373 | } | |
1374 | } while ( | |
94bb24d5 | 1375 | !this.isRegistered() && |
5144f4d1 JB |
1376 | (registrationRetryCount <= this.getRegistrationMaxRetries() || |
1377 | this.getRegistrationMaxRetries() === -1) | |
1378 | ); | |
1379 | } | |
94bb24d5 JB |
1380 | if (this.isRegistered()) { |
1381 | if (this.isInAcceptedState()) { | |
1382 | await this.startMessageSequence(); | |
c0560973 | 1383 | } |
5144f4d1 JB |
1384 | } else { |
1385 | logger.error( | |
1386 | `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})` | |
1387 | ); | |
caad9d6b | 1388 | } |
5144f4d1 | 1389 | this.wsConnectionRestarted = false; |
aa428a31 JB |
1390 | this.autoReconnectRetryCount = 0; |
1391 | this.started = true; | |
5e3cb728 | 1392 | parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); |
2e6f5966 | 1393 | } else { |
5144f4d1 JB |
1394 | logger.warn( |
1395 | `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed` | |
e7aeea18 | 1396 | ); |
2e6f5966 | 1397 | } |
2e6f5966 JB |
1398 | } |
1399 | ||
6c65a295 | 1400 | private async onClose(code: number, reason: string): Promise<void> { |
d09085e9 | 1401 | switch (code) { |
6c65a295 JB |
1402 | // Normal close |
1403 | case WebSocketCloseEventStatusCode.CLOSE_NORMAL: | |
c0560973 | 1404 | case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS: |
e7aeea18 | 1405 | logger.info( |
5e3cb728 | 1406 | `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString( |
e7aeea18 JB |
1407 | code |
1408 | )}' and reason '${reason}'` | |
1409 | ); | |
c0560973 JB |
1410 | this.autoReconnectRetryCount = 0; |
1411 | break; | |
6c65a295 JB |
1412 | // Abnormal close |
1413 | default: | |
e7aeea18 | 1414 | logger.error( |
5e3cb728 | 1415 | `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString( |
e7aeea18 JB |
1416 | code |
1417 | )}' and reason '${reason}'` | |
1418 | ); | |
aa428a31 | 1419 | await this.reconnect(); |
c0560973 JB |
1420 | break; |
1421 | } | |
5e3cb728 | 1422 | parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); |
2e6f5966 JB |
1423 | } |
1424 | ||
16b0d4e7 | 1425 | private async onMessage(data: Data): Promise<void> { |
b3ec7bc1 JB |
1426 | let messageType: number; |
1427 | let messageId: string; | |
1428 | let commandName: IncomingRequestCommand; | |
1429 | let commandPayload: JsonType; | |
1430 | let errorType: ErrorType; | |
1431 | let errorMessage: string; | |
1432 | let errorDetails: JsonType; | |
1433 | let responseCallback: (payload: JsonType, requestPayload: JsonType) => void; | |
a2d1c0f1 | 1434 | let errorCallback: (error: OCPPError, requestStatistic?: boolean) => void; |
32b02249 | 1435 | let requestCommandName: RequestCommand | IncomingRequestCommand; |
b3ec7bc1 | 1436 | let requestPayload: JsonType; |
32b02249 | 1437 | let cachedRequest: CachedRequest; |
c0560973 JB |
1438 | let errMsg: string; |
1439 | try { | |
b3ec7bc1 | 1440 | const request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse; |
53e5fd67 | 1441 | if (Array.isArray(request) === true) { |
9934652c | 1442 | [messageType, messageId] = request; |
b3ec7bc1 JB |
1443 | // Check the type of message |
1444 | switch (messageType) { | |
1445 | // Incoming Message | |
1446 | case MessageType.CALL_MESSAGE: | |
9934652c | 1447 | [, , commandName, commandPayload] = request as IncomingRequest; |
0638ddd2 | 1448 | if (this.getEnableStatistics() === true) { |
b3ec7bc1 JB |
1449 | this.performanceStatistics.addRequestStatistic(commandName, messageType); |
1450 | } | |
1451 | logger.debug( | |
1452 | `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify( | |
1453 | request | |
1454 | )}` | |
1455 | ); | |
1456 | // Process the message | |
1457 | await this.ocppIncomingRequestService.incomingRequestHandler( | |
08f130a0 | 1458 | this, |
b3ec7bc1 JB |
1459 | messageId, |
1460 | commandName, | |
1461 | commandPayload | |
1462 | ); | |
1463 | break; | |
1464 | // Outcome Message | |
1465 | case MessageType.CALL_RESULT_MESSAGE: | |
9934652c | 1466 | [, , commandPayload] = request as Response; |
ba7965c4 | 1467 | if (this.requests.has(messageId) === false) { |
a2d1c0f1 JB |
1468 | // Error |
1469 | throw new OCPPError( | |
1470 | ErrorType.INTERNAL_ERROR, | |
1471 | `Response for unknown message id ${messageId}`, | |
1472 | null, | |
1473 | commandPayload | |
1474 | ); | |
1475 | } | |
b3ec7bc1 JB |
1476 | // Respond |
1477 | cachedRequest = this.requests.get(messageId); | |
53e5fd67 | 1478 | if (Array.isArray(cachedRequest) === true) { |
53e07f94 | 1479 | [responseCallback, errorCallback, requestCommandName, requestPayload] = cachedRequest; |
b3ec7bc1 JB |
1480 | } else { |
1481 | throw new OCPPError( | |
1482 | ErrorType.PROTOCOL_ERROR, | |
53e5fd67 | 1483 | `Cached request for message id ${messageId} response is not an array`, |
c2bc716f JB |
1484 | null, |
1485 | cachedRequest as unknown as JsonType | |
b3ec7bc1 JB |
1486 | ); |
1487 | } | |
1488 | logger.debug( | |
7ec6c5c9 | 1489 | `${this.logPrefix()} << Command '${ |
7369e417 | 1490 | requestCommandName ?? 'unknown' |
7ec6c5c9 | 1491 | }' received response payload: ${JSON.stringify(request)}` |
b3ec7bc1 | 1492 | ); |
a2d1c0f1 JB |
1493 | responseCallback(commandPayload, requestPayload); |
1494 | break; | |
1495 | // Error Message | |
1496 | case MessageType.CALL_ERROR_MESSAGE: | |
1497 | [, , errorType, errorMessage, errorDetails] = request as ErrorResponse; | |
ba7965c4 | 1498 | if (this.requests.has(messageId) === false) { |
b3ec7bc1 JB |
1499 | // Error |
1500 | throw new OCPPError( | |
1501 | ErrorType.INTERNAL_ERROR, | |
a2d1c0f1 | 1502 | `Error response for unknown message id ${messageId}`, |
c2bc716f | 1503 | null, |
a2d1c0f1 | 1504 | { errorType, errorMessage, errorDetails } |
b3ec7bc1 JB |
1505 | ); |
1506 | } | |
b3ec7bc1 | 1507 | cachedRequest = this.requests.get(messageId); |
53e5fd67 | 1508 | if (Array.isArray(cachedRequest) === true) { |
a2d1c0f1 | 1509 | [, errorCallback, requestCommandName] = cachedRequest; |
b3ec7bc1 JB |
1510 | } else { |
1511 | throw new OCPPError( | |
1512 | ErrorType.PROTOCOL_ERROR, | |
53e5fd67 | 1513 | `Cached request for message id ${messageId} error response is not an array`, |
c2bc716f JB |
1514 | null, |
1515 | cachedRequest as unknown as JsonType | |
b3ec7bc1 JB |
1516 | ); |
1517 | } | |
1518 | logger.debug( | |
7ec6c5c9 | 1519 | `${this.logPrefix()} << Command '${ |
7369e417 | 1520 | requestCommandName ?? 'unknown' |
7ec6c5c9 | 1521 | }' received error payload: ${JSON.stringify(request)}` |
b3ec7bc1 | 1522 | ); |
a2d1c0f1 | 1523 | errorCallback(new OCPPError(errorType, errorMessage, requestCommandName, errorDetails)); |
b3ec7bc1 JB |
1524 | break; |
1525 | // Error | |
1526 | default: | |
1527 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions | |
fc040c43 JB |
1528 | errMsg = `Wrong message type ${messageType}`; |
1529 | logger.error(`${this.logPrefix()} ${errMsg}`); | |
b3ec7bc1 JB |
1530 | throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg); |
1531 | } | |
32de5a57 | 1532 | parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); |
47e22477 | 1533 | } else { |
53e5fd67 | 1534 | throw new OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming message is not an array', null, { |
ba7965c4 | 1535 | request, |
ac54a9bb | 1536 | }); |
47e22477 | 1537 | } |
c0560973 JB |
1538 | } catch (error) { |
1539 | // Log | |
e7aeea18 | 1540 | logger.error( |
91a4f151 | 1541 | `${this.logPrefix()} Incoming OCPP command '${ |
fc040c43 | 1542 | commandName ?? requestCommandName ?? null |
9c5d9fa4 JB |
1543 | }' message '${data.toString()}'${ |
1544 | messageType !== MessageType.CALL_MESSAGE | |
1545 | ? ` matching cached request '${JSON.stringify(this.requests.get(messageId))}'` | |
1546 | : '' | |
1547 | } processing error:`, | |
e7aeea18 JB |
1548 | error |
1549 | ); | |
ba7965c4 | 1550 | if (error instanceof OCPPError === false) { |
247659af | 1551 | logger.warn( |
91a4f151 | 1552 | `${this.logPrefix()} Error thrown at incoming OCPP command '${ |
fc040c43 JB |
1553 | commandName ?? requestCommandName ?? null |
1554 | }' message '${data.toString()}' handling is not an OCPPError:`, | |
247659af JB |
1555 | error |
1556 | ); | |
1557 | } | |
13701f69 JB |
1558 | switch (messageType) { |
1559 | case MessageType.CALL_MESSAGE: | |
1560 | // Send error | |
1561 | await this.ocppRequestService.sendError( | |
1562 | this, | |
1563 | messageId, | |
1564 | error as OCPPError, | |
1565 | commandName ?? requestCommandName ?? null | |
1566 | ); | |
1567 | break; | |
1568 | case MessageType.CALL_RESULT_MESSAGE: | |
1569 | case MessageType.CALL_ERROR_MESSAGE: | |
1570 | if (errorCallback) { | |
1571 | // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op) | |
1572 | errorCallback(error as OCPPError, false); | |
1573 | } else { | |
1574 | // Remove the request from the cache in case of error at response handling | |
1575 | this.requests.delete(messageId); | |
1576 | } | |
de4cb8b6 | 1577 | break; |
ba7965c4 | 1578 | } |
c0560973 | 1579 | } |
2328be1e JB |
1580 | } |
1581 | ||
c0560973 | 1582 | private onPing(): void { |
9f2e3130 | 1583 | logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server'); |
c0560973 JB |
1584 | } |
1585 | ||
1586 | private onPong(): void { | |
9f2e3130 | 1587 | logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server'); |
c0560973 JB |
1588 | } |
1589 | ||
9534e74e | 1590 | private onError(error: WSError): void { |
bcc9c3c0 | 1591 | this.closeWSConnection(); |
32de5a57 | 1592 | logger.error(this.logPrefix() + ' WebSocket error:', error); |
c0560973 JB |
1593 | } |
1594 | ||
07989fad JB |
1595 | private getEnergyActiveImportRegister( |
1596 | connectorStatus: ConnectorStatus, | |
1597 | meterStop = false | |
1598 | ): number { | |
95bdbf12 | 1599 | if (this.getMeteringPerTransaction() === true) { |
07989fad JB |
1600 | return ( |
1601 | (meterStop === true | |
1602 | ? Math.round(connectorStatus?.transactionEnergyActiveImportRegisterValue) | |
1603 | : connectorStatus?.transactionEnergyActiveImportRegisterValue) ?? 0 | |
1604 | ); | |
1605 | } | |
1606 | return ( | |
1607 | (meterStop === true | |
1608 | ? Math.round(connectorStatus?.energyActiveImportRegisterValue) | |
1609 | : connectorStatus?.energyActiveImportRegisterValue) ?? 0 | |
1610 | ); | |
1611 | } | |
1612 | ||
bb83b5ed | 1613 | private getUseConnectorId0(stationInfo?: ChargingStationInfo): boolean { |
fa7bccf4 JB |
1614 | const localStationInfo = stationInfo ?? this.stationInfo; |
1615 | return !Utils.isUndefined(localStationInfo.useConnectorId0) | |
1616 | ? localStationInfo.useConnectorId0 | |
e7aeea18 | 1617 | : true; |
8bce55bf JB |
1618 | } |
1619 | ||
60ddad53 JB |
1620 | private getNumberOfRunningTransactions(): number { |
1621 | let trxCount = 0; | |
1622 | for (const connectorId of this.connectors.keys()) { | |
1623 | if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted === true) { | |
1624 | trxCount++; | |
1625 | } | |
1626 | } | |
1627 | return trxCount; | |
1628 | } | |
1629 | ||
1630 | private async stopRunningTransactions(reason = StopTransactionReason.NONE): Promise<void> { | |
1631 | for (const connectorId of this.connectors.keys()) { | |
1632 | if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted === true) { | |
1633 | await this.stopTransactionOnConnector(connectorId, reason); | |
1634 | } | |
1635 | } | |
1636 | } | |
1637 | ||
1f761b9a | 1638 | // 0 for disabling |
c72f6634 | 1639 | private getConnectionTimeout(): number { |
17ac262c JB |
1640 | if ( |
1641 | ChargingStationConfigurationUtils.getConfigurationKey( | |
1642 | this, | |
1643 | StandardParametersKey.ConnectionTimeOut | |
1644 | ) | |
1645 | ) { | |
e7aeea18 | 1646 | return ( |
17ac262c JB |
1647 | parseInt( |
1648 | ChargingStationConfigurationUtils.getConfigurationKey( | |
1649 | this, | |
1650 | StandardParametersKey.ConnectionTimeOut | |
1651 | ).value | |
1652 | ) ?? Constants.DEFAULT_CONNECTION_TIMEOUT | |
e7aeea18 | 1653 | ); |
291cb255 | 1654 | } |
291cb255 | 1655 | return Constants.DEFAULT_CONNECTION_TIMEOUT; |
3574dfd3 JB |
1656 | } |
1657 | ||
1f761b9a | 1658 | // -1 for unlimited, 0 for disabling |
c72f6634 | 1659 | private getAutoReconnectMaxRetries(): number { |
ad2f27c3 JB |
1660 | if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) { |
1661 | return this.stationInfo.autoReconnectMaxRetries; | |
3574dfd3 JB |
1662 | } |
1663 | if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) { | |
1664 | return Configuration.getAutoReconnectMaxRetries(); | |
1665 | } | |
1666 | return -1; | |
1667 | } | |
1668 | ||
ec977daf | 1669 | // 0 for disabling |
c72f6634 | 1670 | private getRegistrationMaxRetries(): number { |
ad2f27c3 JB |
1671 | if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) { |
1672 | return this.stationInfo.registrationMaxRetries; | |
32a1eb7a JB |
1673 | } |
1674 | return -1; | |
1675 | } | |
1676 | ||
c0560973 JB |
1677 | private getPowerDivider(): number { |
1678 | let powerDivider = this.getNumberOfConnectors(); | |
fa7bccf4 | 1679 | if (this.stationInfo?.powerSharedByConnectors) { |
c0560973 | 1680 | powerDivider = this.getNumberOfRunningTransactions(); |
6ecb15e4 JB |
1681 | } |
1682 | return powerDivider; | |
1683 | } | |
1684 | ||
fa7bccf4 JB |
1685 | private getMaximumPower(stationInfo?: ChargingStationInfo): number { |
1686 | const localStationInfo = stationInfo ?? this.stationInfo; | |
1687 | return (localStationInfo['maxPower'] as number) ?? localStationInfo.maximumPower; | |
0642c3d2 JB |
1688 | } |
1689 | ||
fa7bccf4 JB |
1690 | private getMaximumAmperage(stationInfo: ChargingStationInfo): number | undefined { |
1691 | const maximumPower = this.getMaximumPower(stationInfo); | |
1692 | switch (this.getCurrentOutType(stationInfo)) { | |
cc6e8ab5 JB |
1693 | case CurrentType.AC: |
1694 | return ACElectricUtils.amperagePerPhaseFromPower( | |
fa7bccf4 | 1695 | this.getNumberOfPhases(stationInfo), |
ad8537a7 | 1696 | maximumPower / this.getNumberOfConnectors(), |
fa7bccf4 | 1697 | this.getVoltageOut(stationInfo) |
cc6e8ab5 JB |
1698 | ); |
1699 | case CurrentType.DC: | |
fa7bccf4 | 1700 | return DCElectricUtils.amperage(maximumPower, this.getVoltageOut(stationInfo)); |
cc6e8ab5 JB |
1701 | } |
1702 | } | |
1703 | ||
cc6e8ab5 JB |
1704 | private getAmperageLimitation(): number | undefined { |
1705 | if ( | |
1706 | this.stationInfo.amperageLimitationOcppKey && | |
17ac262c JB |
1707 | ChargingStationConfigurationUtils.getConfigurationKey( |
1708 | this, | |
1709 | this.stationInfo.amperageLimitationOcppKey | |
1710 | ) | |
cc6e8ab5 JB |
1711 | ) { |
1712 | return ( | |
1713 | Utils.convertToInt( | |
17ac262c JB |
1714 | ChargingStationConfigurationUtils.getConfigurationKey( |
1715 | this, | |
1716 | this.stationInfo.amperageLimitationOcppKey | |
1717 | ).value | |
1718 | ) / ChargingStationUtils.getAmperageLimitationUnitDivider(this.stationInfo) | |
cc6e8ab5 JB |
1719 | ); |
1720 | } | |
1721 | } | |
1722 | ||
60ddad53 JB |
1723 | private getChargingProfilePowerLimit(connectorId: number): number | undefined { |
1724 | let limit: number, matchingChargingProfile: ChargingProfile; | |
1725 | let chargingProfiles: ChargingProfile[] = []; | |
1726 | // Get charging profiles for connector and sort by stack level | |
1727 | chargingProfiles = this.getConnectorStatus(connectorId).chargingProfiles.sort( | |
1728 | (a, b) => b.stackLevel - a.stackLevel | |
1729 | ); | |
1730 | // Get profiles on connector 0 | |
1731 | if (this.getConnectorStatus(0).chargingProfiles) { | |
1732 | chargingProfiles.push( | |
1733 | ...this.getConnectorStatus(0).chargingProfiles.sort((a, b) => b.stackLevel - a.stackLevel) | |
1734 | ); | |
1735 | } | |
1736 | if (!Utils.isEmptyArray(chargingProfiles)) { | |
1737 | const result = ChargingStationUtils.getLimitFromChargingProfiles( | |
1738 | chargingProfiles, | |
1739 | this.logPrefix() | |
1740 | ); | |
1741 | if (!Utils.isNullOrUndefined(result)) { | |
1742 | limit = result.limit; | |
1743 | matchingChargingProfile = result.matchingChargingProfile; | |
1744 | switch (this.getCurrentOutType()) { | |
1745 | case CurrentType.AC: | |
1746 | limit = | |
1747 | matchingChargingProfile.chargingSchedule.chargingRateUnit === | |
1748 | ChargingRateUnitType.WATT | |
1749 | ? limit | |
1750 | : ACElectricUtils.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit); | |
1751 | break; | |
1752 | case CurrentType.DC: | |
1753 | limit = | |
1754 | matchingChargingProfile.chargingSchedule.chargingRateUnit === | |
1755 | ChargingRateUnitType.WATT | |
1756 | ? limit | |
1757 | : DCElectricUtils.power(this.getVoltageOut(), limit); | |
1758 | } | |
1759 | const connectorMaximumPower = this.getMaximumPower() / this.powerDivider; | |
1760 | if (limit > connectorMaximumPower) { | |
1761 | logger.error( | |
1762 | `${this.logPrefix()} Charging profile id ${ | |
1763 | matchingChargingProfile.chargingProfileId | |
1764 | } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`, | |
1765 | this.getConnectorStatus(connectorId).chargingProfiles | |
1766 | ); | |
1767 | limit = connectorMaximumPower; | |
1768 | } | |
1769 | } | |
1770 | } | |
1771 | return limit; | |
1772 | } | |
1773 | ||
c0560973 | 1774 | private async startMessageSequence(): Promise<void> { |
7c72977b | 1775 | if (this.stationInfo?.autoRegister) { |
f7f98c68 | 1776 | await this.ocppRequestService.requestHandler< |
ef6fa3fb JB |
1777 | BootNotificationRequest, |
1778 | BootNotificationResponse | |
8bfbc743 JB |
1779 | >(this, RequestCommand.BOOT_NOTIFICATION, this.bootNotificationRequest, { |
1780 | skipBufferingOnError: true, | |
1781 | }); | |
6114e6f1 | 1782 | } |
136c90ba | 1783 | // Start WebSocket ping |
c0560973 | 1784 | this.startWebSocketPing(); |
5ad8570f | 1785 | // Start heartbeat |
c0560973 | 1786 | this.startHeartbeat(); |
0a60c33c | 1787 | // Initialize connectors status |
734d790d JB |
1788 | for (const connectorId of this.connectors.keys()) { |
1789 | if (connectorId === 0) { | |
593cf3f9 | 1790 | continue; |
e7aeea18 | 1791 | } else if ( |
452a82ca | 1792 | this.started === true && |
e7aeea18 JB |
1793 | !this.getConnectorStatus(connectorId)?.status && |
1794 | this.getConnectorStatus(connectorId)?.bootStatus | |
1795 | ) { | |
136c90ba | 1796 | // Send status in template at startup |
f7f98c68 | 1797 | await this.ocppRequestService.requestHandler< |
ef6fa3fb JB |
1798 | StatusNotificationRequest, |
1799 | StatusNotificationResponse | |
08f130a0 | 1800 | >(this, RequestCommand.STATUS_NOTIFICATION, { |
ef6fa3fb JB |
1801 | connectorId, |
1802 | status: this.getConnectorStatus(connectorId).bootStatus, | |
1803 | errorCode: ChargePointErrorCode.NO_ERROR, | |
1804 | }); | |
e7aeea18 JB |
1805 | this.getConnectorStatus(connectorId).status = |
1806 | this.getConnectorStatus(connectorId).bootStatus; | |
1807 | } else if ( | |
452a82ca | 1808 | this.started === false && |
e7aeea18 JB |
1809 | this.getConnectorStatus(connectorId)?.status && |
1810 | this.getConnectorStatus(connectorId)?.bootStatus | |
1811 | ) { | |
136c90ba | 1812 | // Send status in template after reset |
f7f98c68 | 1813 | await this.ocppRequestService.requestHandler< |
ef6fa3fb JB |
1814 | StatusNotificationRequest, |
1815 | StatusNotificationResponse | |
08f130a0 | 1816 | >(this, RequestCommand.STATUS_NOTIFICATION, { |
ef6fa3fb JB |
1817 | connectorId, |
1818 | status: this.getConnectorStatus(connectorId).bootStatus, | |
1819 | errorCode: ChargePointErrorCode.NO_ERROR, | |
1820 | }); | |
e7aeea18 JB |
1821 | this.getConnectorStatus(connectorId).status = |
1822 | this.getConnectorStatus(connectorId).bootStatus; | |
452a82ca | 1823 | } else if (this.started === true && this.getConnectorStatus(connectorId)?.status) { |
136c90ba | 1824 | // Send previous status at template reload |
f7f98c68 | 1825 | await this.ocppRequestService.requestHandler< |
ef6fa3fb JB |
1826 | StatusNotificationRequest, |
1827 | StatusNotificationResponse | |
08f130a0 | 1828 | >(this, RequestCommand.STATUS_NOTIFICATION, { |
ef6fa3fb JB |
1829 | connectorId, |
1830 | status: this.getConnectorStatus(connectorId).status, | |
1831 | errorCode: ChargePointErrorCode.NO_ERROR, | |
1832 | }); | |
5ad8570f | 1833 | } else { |
136c90ba | 1834 | // Send default status |
f7f98c68 | 1835 | await this.ocppRequestService.requestHandler< |
ef6fa3fb JB |
1836 | StatusNotificationRequest, |
1837 | StatusNotificationResponse | |
08f130a0 | 1838 | >(this, RequestCommand.STATUS_NOTIFICATION, { |
ef6fa3fb JB |
1839 | connectorId, |
1840 | status: ChargePointStatus.AVAILABLE, | |
1841 | errorCode: ChargePointErrorCode.NO_ERROR, | |
1842 | }); | |
734d790d | 1843 | this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE; |
5ad8570f JB |
1844 | } |
1845 | } | |
0a60c33c | 1846 | // Start the ATG |
60ddad53 | 1847 | if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable === true) { |
4f69be04 | 1848 | this.startAutomaticTransactionGenerator(); |
fa7bccf4 | 1849 | } |
aa428a31 | 1850 | this.wsConnectionRestarted === true && this.flushMessageBuffer(); |
fa7bccf4 JB |
1851 | } |
1852 | ||
e7aeea18 JB |
1853 | private async stopMessageSequence( |
1854 | reason: StopTransactionReason = StopTransactionReason.NONE | |
1855 | ): Promise<void> { | |
136c90ba | 1856 | // Stop WebSocket ping |
c0560973 | 1857 | this.stopWebSocketPing(); |
79411696 | 1858 | // Stop heartbeat |
c0560973 | 1859 | this.stopHeartbeat(); |
fa7bccf4 | 1860 | // Stop ongoing transactions |
b20eb107 | 1861 | if (this.automaticTransactionGenerator?.started === true) { |
60ddad53 JB |
1862 | this.stopAutomaticTransactionGenerator(); |
1863 | } else { | |
1864 | await this.stopRunningTransactions(reason); | |
79411696 JB |
1865 | } |
1866 | } | |
1867 | ||
c0560973 | 1868 | private startWebSocketPing(): void { |
17ac262c JB |
1869 | const webSocketPingInterval: number = ChargingStationConfigurationUtils.getConfigurationKey( |
1870 | this, | |
e7aeea18 JB |
1871 | StandardParametersKey.WebSocketPingInterval |
1872 | ) | |
1873 | ? Utils.convertToInt( | |
17ac262c JB |
1874 | ChargingStationConfigurationUtils.getConfigurationKey( |
1875 | this, | |
1876 | StandardParametersKey.WebSocketPingInterval | |
1877 | ).value | |
e7aeea18 | 1878 | ) |
9cd3dfb0 | 1879 | : 0; |
ad2f27c3 JB |
1880 | if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) { |
1881 | this.webSocketPingSetInterval = setInterval(() => { | |
d5bff457 | 1882 | if (this.isWebSocketConnectionOpened()) { |
e7aeea18 JB |
1883 | this.wsConnection.ping((): void => { |
1884 | /* This is intentional */ | |
1885 | }); | |
136c90ba JB |
1886 | } |
1887 | }, webSocketPingInterval * 1000); | |
e7aeea18 JB |
1888 | logger.info( |
1889 | this.logPrefix() + | |
1890 | ' WebSocket ping started every ' + | |
1891 | Utils.formatDurationSeconds(webSocketPingInterval) | |
1892 | ); | |
ad2f27c3 | 1893 | } else if (this.webSocketPingSetInterval) { |
e7aeea18 JB |
1894 | logger.info( |
1895 | this.logPrefix() + | |
1896 | ' WebSocket ping every ' + | |
1897 | Utils.formatDurationSeconds(webSocketPingInterval) + | |
1898 | ' already started' | |
1899 | ); | |
136c90ba | 1900 | } else { |
e7aeea18 JB |
1901 | logger.error( |
1902 | `${this.logPrefix()} WebSocket ping interval set to ${ | |
1903 | webSocketPingInterval | |
1904 | ? Utils.formatDurationSeconds(webSocketPingInterval) | |
1905 | : webSocketPingInterval | |
1906 | }, not starting the WebSocket ping` | |
1907 | ); | |
136c90ba JB |
1908 | } |
1909 | } | |
1910 | ||
c0560973 | 1911 | private stopWebSocketPing(): void { |
ad2f27c3 JB |
1912 | if (this.webSocketPingSetInterval) { |
1913 | clearInterval(this.webSocketPingSetInterval); | |
136c90ba JB |
1914 | } |
1915 | } | |
1916 | ||
1f5df42a | 1917 | private getConfiguredSupervisionUrl(): URL { |
e7aeea18 JB |
1918 | const supervisionUrls = Utils.cloneObject<string | string[]>( |
1919 | this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls() | |
1920 | ); | |
c0560973 | 1921 | if (!Utils.isEmptyArray(supervisionUrls)) { |
2dcfe98e JB |
1922 | switch (Configuration.getSupervisionUrlDistribution()) { |
1923 | case SupervisionUrlDistribution.ROUND_ROBIN: | |
c72f6634 JB |
1924 | // FIXME |
1925 | this.configuredSupervisionUrlIndex = (this.index - 1) % supervisionUrls.length; | |
2dcfe98e JB |
1926 | break; |
1927 | case SupervisionUrlDistribution.RANDOM: | |
c72f6634 JB |
1928 | this.configuredSupervisionUrlIndex = Math.floor( |
1929 | Utils.secureRandom() * supervisionUrls.length | |
1930 | ); | |
2dcfe98e | 1931 | break; |
c72f6634 JB |
1932 | case SupervisionUrlDistribution.CHARGING_STATION_AFFINITY: |
1933 | this.configuredSupervisionUrlIndex = (this.index - 1) % supervisionUrls.length; | |
2dcfe98e JB |
1934 | break; |
1935 | default: | |
e7aeea18 JB |
1936 | logger.error( |
1937 | `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${ | |
c72f6634 | 1938 | SupervisionUrlDistribution.CHARGING_STATION_AFFINITY |
e7aeea18 JB |
1939 | }` |
1940 | ); | |
c72f6634 | 1941 | this.configuredSupervisionUrlIndex = (this.index - 1) % supervisionUrls.length; |
2dcfe98e | 1942 | break; |
c0560973 | 1943 | } |
c72f6634 | 1944 | return new URL(supervisionUrls[this.configuredSupervisionUrlIndex]); |
c0560973 | 1945 | } |
57939a9d | 1946 | return new URL(supervisionUrls as string); |
136c90ba JB |
1947 | } |
1948 | ||
c72f6634 | 1949 | private getHeartbeatInterval(): number { |
17ac262c JB |
1950 | const HeartbeatInterval = ChargingStationConfigurationUtils.getConfigurationKey( |
1951 | this, | |
1952 | StandardParametersKey.HeartbeatInterval | |
1953 | ); | |
c0560973 JB |
1954 | if (HeartbeatInterval) { |
1955 | return Utils.convertToInt(HeartbeatInterval.value) * 1000; | |
1956 | } | |
17ac262c JB |
1957 | const HeartBeatInterval = ChargingStationConfigurationUtils.getConfigurationKey( |
1958 | this, | |
1959 | StandardParametersKey.HeartBeatInterval | |
1960 | ); | |
c0560973 JB |
1961 | if (HeartBeatInterval) { |
1962 | return Utils.convertToInt(HeartBeatInterval.value) * 1000; | |
0a60c33c | 1963 | } |
7c72977b | 1964 | !this.stationInfo?.autoRegister && |
e7aeea18 JB |
1965 | logger.warn( |
1966 | `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${ | |
1967 | Constants.DEFAULT_HEARTBEAT_INTERVAL | |
1968 | }` | |
1969 | ); | |
47e22477 | 1970 | return Constants.DEFAULT_HEARTBEAT_INTERVAL; |
0a60c33c JB |
1971 | } |
1972 | ||
c0560973 | 1973 | private stopHeartbeat(): void { |
ad2f27c3 JB |
1974 | if (this.heartbeatSetInterval) { |
1975 | clearInterval(this.heartbeatSetInterval); | |
7dde0b73 | 1976 | } |
5ad8570f JB |
1977 | } |
1978 | ||
55516218 JB |
1979 | private terminateWSConnection(): void { |
1980 | if (this.isWebSocketConnectionOpened()) { | |
1981 | this.wsConnection.terminate(); | |
1982 | this.wsConnection = null; | |
1983 | } | |
1984 | } | |
1985 | ||
dd119a6b | 1986 | private stopMeterValues(connectorId: number) { |
734d790d JB |
1987 | if (this.getConnectorStatus(connectorId)?.transactionSetInterval) { |
1988 | clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval); | |
dd119a6b JB |
1989 | } |
1990 | } | |
1991 | ||
c72f6634 | 1992 | private getReconnectExponentialDelay(): boolean { |
e7aeea18 JB |
1993 | return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) |
1994 | ? this.stationInfo.reconnectExponentialDelay | |
1995 | : false; | |
5ad8570f JB |
1996 | } |
1997 | ||
aa428a31 | 1998 | private async reconnect(): Promise<void> { |
7874b0b1 JB |
1999 | // Stop WebSocket ping |
2000 | this.stopWebSocketPing(); | |
136c90ba | 2001 | // Stop heartbeat |
c0560973 | 2002 | this.stopHeartbeat(); |
5ad8570f | 2003 | // Stop the ATG if needed |
6d9876e7 | 2004 | if (this.automaticTransactionGenerator?.configuration?.stopOnConnectionFailure === true) { |
fa7bccf4 | 2005 | this.stopAutomaticTransactionGenerator(); |
ad2f27c3 | 2006 | } |
e7aeea18 JB |
2007 | if ( |
2008 | this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || | |
2009 | this.getAutoReconnectMaxRetries() === -1 | |
2010 | ) { | |
ad2f27c3 | 2011 | this.autoReconnectRetryCount++; |
e7aeea18 JB |
2012 | const reconnectDelay = this.getReconnectExponentialDelay() |
2013 | ? Utils.exponentialDelay(this.autoReconnectRetryCount) | |
2014 | : this.getConnectionTimeout() * 1000; | |
1e080116 JB |
2015 | const reconnectDelayWithdraw = 1000; |
2016 | const reconnectTimeout = | |
2017 | reconnectDelay && reconnectDelay - reconnectDelayWithdraw > 0 | |
2018 | ? reconnectDelay - reconnectDelayWithdraw | |
2019 | : 0; | |
e7aeea18 JB |
2020 | logger.error( |
2021 | `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo( | |
2022 | reconnectDelay, | |
2023 | 2 | |
2024 | )}ms, timeout ${reconnectTimeout}ms` | |
2025 | ); | |
032d6efc | 2026 | await Utils.sleep(reconnectDelay); |
e7aeea18 JB |
2027 | logger.error( |
2028 | this.logPrefix() + | |
2029 | ' WebSocket: reconnecting try #' + | |
2030 | this.autoReconnectRetryCount.toString() | |
2031 | ); | |
2032 | this.openWSConnection( | |
ccb1d6e9 | 2033 | { ...(this.stationInfo?.wsOptions ?? {}), handshakeTimeout: reconnectTimeout }, |
1e080116 | 2034 | { closeOpened: true } |
e7aeea18 | 2035 | ); |
265e4266 | 2036 | this.wsConnectionRestarted = true; |
c0560973 | 2037 | } else if (this.getAutoReconnectMaxRetries() !== -1) { |
e7aeea18 | 2038 | logger.error( |
71a77ac2 | 2039 | `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${ |
e7aeea18 JB |
2040 | this.autoReconnectRetryCount |
2041 | }) or retry disabled (${this.getAutoReconnectMaxRetries()})` | |
2042 | ); | |
5ad8570f JB |
2043 | } |
2044 | } | |
2045 | ||
fa7bccf4 JB |
2046 | private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration | null { |
2047 | return this.getTemplateFromFile()?.AutomaticTransactionGenerator ?? null; | |
2048 | } | |
2049 | ||
a2653482 JB |
2050 | private initializeConnectorStatus(connectorId: number): void { |
2051 | this.getConnectorStatus(connectorId).idTagLocalAuthorized = false; | |
2052 | this.getConnectorStatus(connectorId).idTagAuthorized = false; | |
2053 | this.getConnectorStatus(connectorId).transactionRemoteStarted = false; | |
734d790d JB |
2054 | this.getConnectorStatus(connectorId).transactionStarted = false; |
2055 | this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0; | |
2056 | this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0; | |
0a60c33c | 2057 | } |
7dde0b73 | 2058 | } |