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