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