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