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