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