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