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