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