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