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