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