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