Improve charging profiles power limitation debugging
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
... / ...
CommitLineData
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3import { ACElectricUtils, DCElectricUtils } from '../utils/ElectricUtils';
4import {
5 AvailabilityType,
6 BootNotificationRequest,
7 CachedRequest,
8 HeartbeatRequest,
9 IncomingRequest,
10 IncomingRequestCommand,
11 MeterValuesRequest,
12 RequestCommand,
13 StatusNotificationRequest,
14} from '../types/ocpp/Requests';
15import {
16 BootNotificationResponse,
17 ErrorResponse,
18 HeartbeatResponse,
19 MeterValuesResponse,
20 RegistrationStatus,
21 Response,
22 StatusNotificationResponse,
23} from '../types/ocpp/Responses';
24import {
25 ChargingProfile,
26 ChargingRateUnitType,
27 ChargingSchedulePeriod,
28} from '../types/ocpp/ChargingProfile';
29import { ChargingProfileKindType, RecurrencyKindType } from '../types/ocpp/1.6/ChargingProfile';
30import ChargingStationConfiguration, { Section } from '../types/ChargingStationConfiguration';
31import ChargingStationOcppConfiguration, {
32 ConfigurationKey,
33} from '../types/ChargingStationOcppConfiguration';
34import ChargingStationTemplate, {
35 AmpereUnits,
36 CurrentType,
37 PowerUnits,
38 Voltage,
39 WsOptions,
40} from '../types/ChargingStationTemplate';
41import {
42 ConnectorPhaseRotation,
43 StandardParametersKey,
44 SupportedFeatureProfiles,
45 VendorDefaultParametersKey,
46} from '../types/ocpp/Configuration';
47import { MeterValue, MeterValueMeasurand, MeterValuePhase } from '../types/ocpp/MeterValues';
48import {
49 StopTransactionReason,
50 StopTransactionRequest,
51 StopTransactionResponse,
52} from '../types/ocpp/Transaction';
53import { WSError, WebSocketCloseEventStatusCode } from '../types/WebSocket';
54import WebSocket, { Data, OPEN, RawData } from 'ws';
55
56import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
57import BaseError from '../exception/BaseError';
58import { ChargePointErrorCode } from '../types/ocpp/ChargePointErrorCode';
59import { ChargePointStatus } from '../types/ocpp/ChargePointStatus';
60import ChargingStationInfo from '../types/ChargingStationInfo';
61import { ChargingStationWorkerMessageEvents } from '../types/ChargingStationWorker';
62import Configuration from '../utils/Configuration';
63import { ConnectorStatus } from '../types/ConnectorStatus';
64import Constants from '../utils/Constants';
65import { ErrorType } from '../types/ocpp/ErrorType';
66import { FileType } from '../types/FileType';
67import FileUtils from '../utils/FileUtils';
68import { JsonType } from '../types/JsonType';
69import { MessageType } from '../types/ocpp/MessageType';
70import OCPP16IncomingRequestService from './ocpp/1.6/OCPP16IncomingRequestService';
71import OCPP16RequestService from './ocpp/1.6/OCPP16RequestService';
72import OCPP16ResponseService from './ocpp/1.6/OCPP16ResponseService';
73import { OCPP16ServiceUtils } from './ocpp/1.6/OCPP16ServiceUtils';
74import OCPPError from '../exception/OCPPError';
75import OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService';
76import OCPPRequestService from './ocpp/OCPPRequestService';
77import { OCPPVersion } from '../types/ocpp/OCPPVersion';
78import PerformanceStatistics from '../performance/PerformanceStatistics';
79import { SampledValueTemplate } from '../types/MeasurandPerPhaseSampledValueTemplates';
80import { SupervisionUrlDistribution } from '../types/ConfigurationData';
81import { URL } from 'url';
82import Utils from '../utils/Utils';
83import crypto from 'crypto';
84import fs from 'fs';
85import logger from '../utils/Logger';
86import moment from 'moment';
87import { parentPort } from 'worker_threads';
88import path from 'path';
89
90export default class ChargingStation {
91 public hashId!: string;
92 public readonly templateFile: string;
93 public authorizedTags: string[];
94 public stationInfo!: ChargingStationInfo;
95 public readonly connectors: Map<number, ConnectorStatus>;
96 public ocppConfiguration!: ChargingStationOcppConfiguration;
97 public wsConnection!: WebSocket;
98 public readonly requests: Map<string, CachedRequest>;
99 public performanceStatistics!: PerformanceStatistics;
100 public heartbeatSetInterval!: NodeJS.Timeout;
101 public ocppRequestService!: OCPPRequestService;
102 public bootNotificationResponse!: BootNotificationResponse | null;
103 private readonly index: number;
104 private configurationFile!: string;
105 private bootNotificationRequest!: BootNotificationRequest;
106 private connectorsConfigurationHash!: string;
107 private ocppIncomingRequestService!: OCPPIncomingRequestService;
108 private readonly messageBuffer: Set<string>;
109 private wsConfiguredConnectionUrl!: URL;
110 private wsConnectionRestarted: boolean;
111 private stopped: boolean;
112 private autoReconnectRetryCount: number;
113 private automaticTransactionGenerator!: AutomaticTransactionGenerator;
114 private webSocketPingSetInterval!: NodeJS.Timeout;
115
116 constructor(index: number, templateFile: string) {
117 this.index = index;
118 this.templateFile = templateFile;
119 this.stopped = false;
120 this.wsConnectionRestarted = false;
121 this.autoReconnectRetryCount = 0;
122 this.connectors = new Map<number, ConnectorStatus>();
123 this.requests = new Map<string, CachedRequest>();
124 this.messageBuffer = new Set<string>();
125 this.initialize();
126 this.authorizedTags = this.getAuthorizedTags();
127 }
128
129 private get wsConnectionUrl(): URL {
130 return this.getSupervisionUrlOcppConfiguration()
131 ? new URL(
132 this.getConfigurationKey(this.getSupervisionUrlOcppKey()).value +
133 '/' +
134 this.stationInfo.chargingStationId
135 )
136 : this.wsConfiguredConnectionUrl;
137 }
138
139 public logPrefix(): string {
140 return Utils.logPrefix(` ${this.stationInfo.chargingStationId} |`);
141 }
142
143 public getBootNotificationRequest(): BootNotificationRequest {
144 return this.bootNotificationRequest;
145 }
146
147 public getRandomIdTag(): string {
148 const index = Math.floor(Utils.secureRandom() * this.authorizedTags.length);
149 return this.authorizedTags[index];
150 }
151
152 public hasAuthorizedTags(): boolean {
153 return !Utils.isEmptyArray(this.authorizedTags);
154 }
155
156 public getEnableStatistics(): boolean | undefined {
157 return !Utils.isUndefined(this.stationInfo.enableStatistics)
158 ? this.stationInfo.enableStatistics
159 : true;
160 }
161
162 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
163 return this.stationInfo.mayAuthorizeAtRemoteStart ?? true;
164 }
165
166 public getNumberOfPhases(): number | undefined {
167 switch (this.getCurrentOutType()) {
168 case CurrentType.AC:
169 return !Utils.isUndefined(this.stationInfo.numberOfPhases)
170 ? this.stationInfo.numberOfPhases
171 : 3;
172 case CurrentType.DC:
173 return 0;
174 }
175 }
176
177 public isWebSocketConnectionOpened(): boolean {
178 return this?.wsConnection?.readyState === OPEN;
179 }
180
181 public getRegistrationStatus(): RegistrationStatus {
182 return this?.bootNotificationResponse?.status;
183 }
184
185 public isInUnknownState(): boolean {
186 return Utils.isNullOrUndefined(this?.bootNotificationResponse?.status);
187 }
188
189 public isInPendingState(): boolean {
190 return this?.bootNotificationResponse?.status === RegistrationStatus.PENDING;
191 }
192
193 public isInAcceptedState(): boolean {
194 return this?.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED;
195 }
196
197 public isInRejectedState(): boolean {
198 return this?.bootNotificationResponse?.status === RegistrationStatus.REJECTED;
199 }
200
201 public isRegistered(): boolean {
202 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
203 }
204
205 public isChargingStationAvailable(): boolean {
206 return this.getConnectorStatus(0).availability === AvailabilityType.OPERATIVE;
207 }
208
209 public isConnectorAvailable(id: number): boolean {
210 return id > 0 && this.getConnectorStatus(id).availability === AvailabilityType.OPERATIVE;
211 }
212
213 public getNumberOfConnectors(): number {
214 return this.connectors.get(0) ? this.connectors.size - 1 : this.connectors.size;
215 }
216
217 public getConnectorStatus(id: number): ConnectorStatus {
218 return this.connectors.get(id);
219 }
220
221 public getCurrentOutType(): CurrentType | undefined {
222 return this.stationInfo.currentOutType ?? CurrentType.AC;
223 }
224
225 public getOcppStrictCompliance(): boolean {
226 return this.stationInfo.ocppStrictCompliance ?? false;
227 }
228
229 public getVoltageOut(): number | undefined {
230 const errMsg = `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${
231 this.templateFile
232 }, cannot define default voltage out`;
233 let defaultVoltageOut: number;
234 switch (this.getCurrentOutType()) {
235 case CurrentType.AC:
236 defaultVoltageOut = Voltage.VOLTAGE_230;
237 break;
238 case CurrentType.DC:
239 defaultVoltageOut = Voltage.VOLTAGE_400;
240 break;
241 default:
242 logger.error(errMsg);
243 throw new Error(errMsg);
244 }
245 return !Utils.isUndefined(this.stationInfo.voltageOut)
246 ? this.stationInfo.voltageOut
247 : defaultVoltageOut;
248 }
249
250 public getConnectorMaximumAvailablePower(connectorId: number): number {
251 let connectorAmperageLimitationPowerLimit: number;
252 if (
253 !Utils.isNullOrUndefined(this.getAmperageLimitation()) &&
254 this.getAmperageLimitation() < this.stationInfo.maximumAmperage
255 ) {
256 connectorAmperageLimitationPowerLimit =
257 (this.getCurrentOutType() === CurrentType.AC
258 ? ACElectricUtils.powerTotal(
259 this.getNumberOfPhases(),
260 this.getVoltageOut(),
261 this.getAmperageLimitation() * this.getNumberOfConnectors()
262 )
263 : DCElectricUtils.power(this.getVoltageOut(), this.getAmperageLimitation())) /
264 this.stationInfo.powerDivider;
265 }
266 const connectorMaximumPower = this.getMaximumPower() / this.stationInfo.powerDivider;
267 const connectorChargingProfilePowerLimit = this.getChargingProfilePowerLimit(connectorId);
268 return Math.min(
269 isNaN(connectorMaximumPower) ? Infinity : connectorMaximumPower,
270 isNaN(connectorAmperageLimitationPowerLimit)
271 ? Infinity
272 : connectorAmperageLimitationPowerLimit,
273 isNaN(connectorChargingProfilePowerLimit) ? Infinity : connectorChargingProfilePowerLimit
274 );
275 }
276
277 public getTransactionIdTag(transactionId: number): string | undefined {
278 for (const connectorId of this.connectors.keys()) {
279 if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
280 return this.getConnectorStatus(connectorId).transactionIdTag;
281 }
282 }
283 }
284
285 public getOutOfOrderEndMeterValues(): boolean {
286 return this.stationInfo.outOfOrderEndMeterValues ?? false;
287 }
288
289 public getBeginEndMeterValues(): boolean {
290 return this.stationInfo.beginEndMeterValues ?? false;
291 }
292
293 public getMeteringPerTransaction(): boolean {
294 return this.stationInfo.meteringPerTransaction ?? true;
295 }
296
297 public getTransactionDataMeterValues(): boolean {
298 return this.stationInfo.transactionDataMeterValues ?? false;
299 }
300
301 public getMainVoltageMeterValues(): boolean {
302 return this.stationInfo.mainVoltageMeterValues ?? true;
303 }
304
305 public getPhaseLineToLineVoltageMeterValues(): boolean {
306 return this.stationInfo.phaseLineToLineVoltageMeterValues ?? false;
307 }
308
309 public getConnectorIdByTransactionId(transactionId: number): number | undefined {
310 for (const connectorId of this.connectors.keys()) {
311 if (
312 connectorId > 0 &&
313 this.getConnectorStatus(connectorId)?.transactionId === transactionId
314 ) {
315 return connectorId;
316 }
317 }
318 }
319
320 public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined {
321 const transactionConnectorStatus = this.getConnectorStatus(
322 this.getConnectorIdByTransactionId(transactionId)
323 );
324 if (this.getMeteringPerTransaction()) {
325 return transactionConnectorStatus?.transactionEnergyActiveImportRegisterValue;
326 }
327 return transactionConnectorStatus?.energyActiveImportRegisterValue;
328 }
329
330 public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined {
331 const connectorStatus = this.getConnectorStatus(connectorId);
332 if (this.getMeteringPerTransaction()) {
333 return connectorStatus?.transactionEnergyActiveImportRegisterValue;
334 }
335 return connectorStatus?.energyActiveImportRegisterValue;
336 }
337
338 public getAuthorizeRemoteTxRequests(): boolean {
339 const authorizeRemoteTxRequests = this.getConfigurationKey(
340 StandardParametersKey.AuthorizeRemoteTxRequests
341 );
342 return authorizeRemoteTxRequests
343 ? Utils.convertToBoolean(authorizeRemoteTxRequests.value)
344 : false;
345 }
346
347 public getLocalAuthListEnabled(): boolean {
348 const localAuthListEnabled = this.getConfigurationKey(
349 StandardParametersKey.LocalAuthListEnabled
350 );
351 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
352 }
353
354 public restartWebSocketPing(): void {
355 // Stop WebSocket ping
356 this.stopWebSocketPing();
357 // Start WebSocket ping
358 this.startWebSocketPing();
359 }
360
361 public getSampledValueTemplate(
362 connectorId: number,
363 measurand: MeterValueMeasurand = MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER,
364 phase?: MeterValuePhase
365 ): SampledValueTemplate | undefined {
366 const onPhaseStr = phase ? `on phase ${phase} ` : '';
367 if (!Constants.SUPPORTED_MEASURANDS.includes(measurand)) {
368 logger.warn(
369 `${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
370 );
371 return;
372 }
373 if (
374 measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER &&
375 !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)?.value.includes(
376 measurand
377 )
378 ) {
379 logger.debug(
380 `${this.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
381 StandardParametersKey.MeterValuesSampledData
382 }' OCPP parameter`
383 );
384 return;
385 }
386 const sampledValueTemplates: SampledValueTemplate[] =
387 this.getConnectorStatus(connectorId).MeterValues;
388 for (
389 let index = 0;
390 !Utils.isEmptyArray(sampledValueTemplates) && index < sampledValueTemplates.length;
391 index++
392 ) {
393 if (
394 !Constants.SUPPORTED_MEASURANDS.includes(
395 sampledValueTemplates[index]?.measurand ??
396 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
397 )
398 ) {
399 logger.warn(
400 `${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
401 );
402 } else if (
403 phase &&
404 sampledValueTemplates[index]?.phase === phase &&
405 sampledValueTemplates[index]?.measurand === measurand &&
406 this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)?.value.includes(
407 measurand
408 )
409 ) {
410 return sampledValueTemplates[index];
411 } else if (
412 !phase &&
413 !sampledValueTemplates[index].phase &&
414 sampledValueTemplates[index]?.measurand === measurand &&
415 this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)?.value.includes(
416 measurand
417 )
418 ) {
419 return sampledValueTemplates[index];
420 } else if (
421 measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER &&
422 (!sampledValueTemplates[index].measurand ||
423 sampledValueTemplates[index].measurand === measurand)
424 ) {
425 return sampledValueTemplates[index];
426 }
427 }
428 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
429 const errorMsg = `${this.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
430 logger.error(errorMsg);
431 throw new Error(errorMsg);
432 }
433 logger.debug(
434 `${this.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
435 );
436 }
437
438 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
439 return this.stationInfo.AutomaticTransactionGenerator.requireAuthorize ?? true;
440 }
441
442 public startHeartbeat(): void {
443 if (
444 this.getHeartbeatInterval() &&
445 this.getHeartbeatInterval() > 0 &&
446 !this.heartbeatSetInterval
447 ) {
448 // eslint-disable-next-line @typescript-eslint/no-misused-promises
449 this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
450 await this.ocppRequestService.requestHandler<HeartbeatRequest, HeartbeatResponse>(
451 RequestCommand.HEARTBEAT
452 );
453 }, this.getHeartbeatInterval());
454 logger.info(
455 this.logPrefix() +
456 ' Heartbeat started every ' +
457 Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
458 );
459 } else if (this.heartbeatSetInterval) {
460 logger.info(
461 this.logPrefix() +
462 ' Heartbeat already started every ' +
463 Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
464 );
465 } else {
466 logger.error(
467 `${this.logPrefix()} Heartbeat interval set to ${
468 this.getHeartbeatInterval()
469 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
470 : this.getHeartbeatInterval()
471 }, not starting the heartbeat`
472 );
473 }
474 }
475
476 public restartHeartbeat(): void {
477 // Stop heartbeat
478 this.stopHeartbeat();
479 // Start heartbeat
480 this.startHeartbeat();
481 }
482
483 public startMeterValues(connectorId: number, interval: number): void {
484 if (connectorId === 0) {
485 logger.error(
486 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
487 );
488 return;
489 }
490 if (!this.getConnectorStatus(connectorId)) {
491 logger.error(
492 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
493 );
494 return;
495 }
496 if (!this.getConnectorStatus(connectorId)?.transactionStarted) {
497 logger.error(
498 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
499 );
500 return;
501 } else if (
502 this.getConnectorStatus(connectorId)?.transactionStarted &&
503 !this.getConnectorStatus(connectorId)?.transactionId
504 ) {
505 logger.error(
506 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
507 );
508 return;
509 }
510 if (interval > 0) {
511 // eslint-disable-next-line @typescript-eslint/no-misused-promises
512 this.getConnectorStatus(connectorId).transactionSetInterval = setInterval(
513 // eslint-disable-next-line @typescript-eslint/no-misused-promises
514 async (): Promise<void> => {
515 // FIXME: Implement OCPP version agnostic helpers
516 const meterValue: MeterValue = OCPP16ServiceUtils.buildMeterValue(
517 this,
518 connectorId,
519 this.getConnectorStatus(connectorId).transactionId,
520 interval
521 );
522 await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>(
523 RequestCommand.METER_VALUES,
524 {
525 connectorId,
526 transactionId: this.getConnectorStatus(connectorId).transactionId,
527 meterValue: [meterValue],
528 }
529 );
530 },
531 interval
532 );
533 } else {
534 logger.error(
535 `${this.logPrefix()} Charging station ${
536 StandardParametersKey.MeterValueSampleInterval
537 } configuration set to ${
538 interval ? Utils.formatDurationMilliSeconds(interval) : interval
539 }, not sending MeterValues`
540 );
541 }
542 }
543
544 public start(): void {
545 if (this.getEnableStatistics()) {
546 this.performanceStatistics.start();
547 }
548 this.openWSConnection();
549 // Handle WebSocket message
550 this.wsConnection.on(
551 'message',
552 this.onMessage.bind(this) as (this: WebSocket, data: RawData, isBinary: boolean) => void
553 );
554 // Handle WebSocket error
555 this.wsConnection.on(
556 'error',
557 this.onError.bind(this) as (this: WebSocket, error: Error) => void
558 );
559 // Handle WebSocket close
560 this.wsConnection.on(
561 'close',
562 this.onClose.bind(this) as (this: WebSocket, code: number, reason: Buffer) => void
563 );
564 // Handle WebSocket open
565 this.wsConnection.on('open', this.onOpen.bind(this) as (this: WebSocket) => void);
566 // Handle WebSocket ping
567 this.wsConnection.on('ping', this.onPing.bind(this) as (this: WebSocket, data: Buffer) => void);
568 // Handle WebSocket pong
569 this.wsConnection.on('pong', this.onPong.bind(this) as (this: WebSocket, data: Buffer) => void);
570 // Monitor authorization file
571 FileUtils.watchJsonFile<string[]>(
572 this.logPrefix(),
573 FileType.Authorization,
574 this.getAuthorizationFile(),
575 this.authorizedTags
576 );
577 // Monitor charging station template file
578 FileUtils.watchJsonFile(
579 this.logPrefix(),
580 FileType.ChargingStationTemplate,
581 this.templateFile,
582 null,
583 (event, filename): void => {
584 if (filename && event === 'change') {
585 try {
586 logger.debug(
587 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
588 this.templateFile
589 } file have changed, reload`
590 );
591 // Initialize
592 this.initialize();
593 // Restart the ATG
594 if (
595 !this.stationInfo.AutomaticTransactionGenerator.enable &&
596 this.automaticTransactionGenerator
597 ) {
598 this.automaticTransactionGenerator.stop();
599 }
600 this.startAutomaticTransactionGenerator();
601 if (this.getEnableStatistics()) {
602 this.performanceStatistics.restart();
603 } else {
604 this.performanceStatistics.stop();
605 }
606 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
607 } catch (error) {
608 logger.error(
609 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
610 error
611 );
612 }
613 }
614 }
615 );
616 parentPort.postMessage({
617 id: ChargingStationWorkerMessageEvents.STARTED,
618 data: { id: this.stationInfo.chargingStationId },
619 });
620 }
621
622 public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
623 // Stop message sequence
624 await this.stopMessageSequence(reason);
625 for (const connectorId of this.connectors.keys()) {
626 if (connectorId > 0) {
627 await this.ocppRequestService.requestHandler<
628 StatusNotificationRequest,
629 StatusNotificationResponse
630 >(RequestCommand.STATUS_NOTIFICATION, {
631 connectorId,
632 status: ChargePointStatus.UNAVAILABLE,
633 errorCode: ChargePointErrorCode.NO_ERROR,
634 });
635 this.getConnectorStatus(connectorId).status = ChargePointStatus.UNAVAILABLE;
636 }
637 }
638 if (this.isWebSocketConnectionOpened()) {
639 this.wsConnection.close();
640 }
641 if (this.getEnableStatistics()) {
642 this.performanceStatistics.stop();
643 }
644 this.bootNotificationResponse = null;
645 parentPort.postMessage({
646 id: ChargingStationWorkerMessageEvents.STOPPED,
647 data: { id: this.stationInfo.chargingStationId },
648 });
649 this.stopped = true;
650 }
651
652 public async reset(reason?: StopTransactionReason): Promise<void> {
653 await this.stop(reason);
654 await Utils.sleep(this.stationInfo.resetTime);
655 this.stationInfo = this.getStationInfo();
656 this.stationInfo?.Connectors && delete this.stationInfo.Connectors;
657 this.start();
658 }
659
660 public getConfigurationKey(
661 key: string | StandardParametersKey,
662 caseInsensitive = false
663 ): ConfigurationKey | undefined {
664 return this.ocppConfiguration.configurationKey.find((configElement) => {
665 if (caseInsensitive) {
666 return configElement.key.toLowerCase() === key.toLowerCase();
667 }
668 return configElement.key === key;
669 });
670 }
671
672 public addConfigurationKey(
673 key: string | StandardParametersKey,
674 value: string,
675 options: { readonly?: boolean; visible?: boolean; reboot?: boolean } = {
676 readonly: false,
677 visible: true,
678 reboot: false,
679 },
680 params: { overwrite?: boolean; save?: boolean } = { overwrite: false, save: false }
681 ): void {
682 options = options ?? ({} as { readonly?: boolean; visible?: boolean; reboot?: boolean });
683 options.readonly = options?.readonly ?? false;
684 options.visible = options?.visible ?? true;
685 options.reboot = options?.reboot ?? false;
686 let keyFound = this.getConfigurationKey(key);
687 if (keyFound && params?.overwrite) {
688 this.deleteConfigurationKey(keyFound.key, { save: false });
689 keyFound = undefined;
690 }
691 if (!keyFound) {
692 this.ocppConfiguration.configurationKey.push({
693 key,
694 readonly: options.readonly,
695 value,
696 visible: options.visible,
697 reboot: options.reboot,
698 });
699 params?.save && this.saveOcppConfiguration();
700 } else {
701 logger.error(
702 `${this.logPrefix()} Trying to add an already existing configuration key: %j`,
703 keyFound
704 );
705 }
706 }
707
708 public setConfigurationKeyValue(
709 key: string | StandardParametersKey,
710 value: string,
711 caseInsensitive = false
712 ): void {
713 const keyFound = this.getConfigurationKey(key, caseInsensitive);
714 if (keyFound) {
715 this.ocppConfiguration.configurationKey[
716 this.ocppConfiguration.configurationKey.indexOf(keyFound)
717 ].value = value;
718 this.saveOcppConfiguration();
719 } else {
720 logger.error(
721 `${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`,
722 { key, value }
723 );
724 }
725 }
726
727 public deleteConfigurationKey(
728 key: string | StandardParametersKey,
729 params: { save?: boolean; caseInsensitive?: boolean } = { save: true, caseInsensitive: false }
730 ): ConfigurationKey[] {
731 const keyFound = this.getConfigurationKey(key, params?.caseInsensitive);
732 if (keyFound) {
733 const deletedConfigurationKey = this.ocppConfiguration.configurationKey.splice(
734 this.ocppConfiguration.configurationKey.indexOf(keyFound),
735 1
736 );
737 params?.save && this.saveOcppConfiguration();
738 return deletedConfigurationKey;
739 }
740 }
741
742 public getChargingProfilePowerLimit(connectorId: number): number | undefined {
743 let limit: number, matchingChargingProfile: ChargingProfile;
744 let chargingProfiles: ChargingProfile[] = [];
745 // Get charging profiles for connector and sort by stack level
746 chargingProfiles = this.getConnectorStatus(connectorId).chargingProfiles.sort(
747 (a, b) => b.stackLevel - a.stackLevel
748 );
749 // Get profiles on connector 0
750 if (this.getConnectorStatus(0).chargingProfiles) {
751 chargingProfiles.push(
752 ...this.getConnectorStatus(0).chargingProfiles.sort((a, b) => b.stackLevel - a.stackLevel)
753 );
754 }
755 if (!Utils.isEmptyArray(chargingProfiles)) {
756 const result = this.getCurrentLimitFromChargingProfiles(chargingProfiles);
757 if (!Utils.isNullOrUndefined(result)) {
758 limit = result.limit;
759 matchingChargingProfile = result.matchingChargingProfile;
760 switch (this.getCurrentOutType()) {
761 case CurrentType.AC:
762 limit =
763 matchingChargingProfile.chargingSchedule.chargingRateUnit ===
764 ChargingRateUnitType.WATT
765 ? limit
766 : ACElectricUtils.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit);
767 break;
768 case CurrentType.DC:
769 limit =
770 matchingChargingProfile.chargingSchedule.chargingRateUnit ===
771 ChargingRateUnitType.WATT
772 ? limit
773 : DCElectricUtils.power(this.getVoltageOut(), limit);
774 }
775
776 const connectorMaximumPower = this.getMaximumPower() / this.stationInfo.powerDivider;
777 if (limit > connectorMaximumPower) {
778 logger.error(
779 `${this.logPrefix()} Charging profile id ${
780 matchingChargingProfile.chargingProfileId
781 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
782 this.getConnectorStatus(connectorId).chargingProfiles
783 );
784 limit = connectorMaximumPower;
785 }
786 }
787 }
788 return limit;
789 }
790
791 public setChargingProfile(connectorId: number, cp: ChargingProfile): void {
792 if (Utils.isNullOrUndefined(this.getConnectorStatus(connectorId).chargingProfiles)) {
793 logger.error(
794 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
795 );
796 this.getConnectorStatus(connectorId).chargingProfiles = [];
797 }
798 if (!Array.isArray(this.getConnectorStatus(connectorId).chargingProfiles)) {
799 logger.error(
800 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an improper attribute type for the charging profiles array, applying proper type initialization`
801 );
802 this.getConnectorStatus(connectorId).chargingProfiles = [];
803 }
804 let cpReplaced = false;
805 if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId).chargingProfiles)) {
806 this.getConnectorStatus(connectorId).chargingProfiles?.forEach(
807 (chargingProfile: ChargingProfile, index: number) => {
808 if (
809 chargingProfile.chargingProfileId === cp.chargingProfileId ||
810 (chargingProfile.stackLevel === cp.stackLevel &&
811 chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)
812 ) {
813 this.getConnectorStatus(connectorId).chargingProfiles[index] = cp;
814 cpReplaced = true;
815 }
816 }
817 );
818 }
819 !cpReplaced && this.getConnectorStatus(connectorId).chargingProfiles?.push(cp);
820 }
821
822 public resetConnectorStatus(connectorId: number): void {
823 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
824 this.getConnectorStatus(connectorId).idTagAuthorized = false;
825 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
826 this.getConnectorStatus(connectorId).transactionStarted = false;
827 delete this.getConnectorStatus(connectorId).localAuthorizeIdTag;
828 delete this.getConnectorStatus(connectorId).authorizeIdTag;
829 delete this.getConnectorStatus(connectorId).transactionId;
830 delete this.getConnectorStatus(connectorId).transactionIdTag;
831 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
832 delete this.getConnectorStatus(connectorId).transactionBeginMeterValue;
833 this.stopMeterValues(connectorId);
834 }
835
836 public hasFeatureProfile(featureProfile: SupportedFeatureProfiles) {
837 return this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)?.value.includes(
838 featureProfile
839 );
840 }
841
842 public bufferMessage(message: string): void {
843 this.messageBuffer.add(message);
844 }
845
846 private flushMessageBuffer() {
847 if (this.messageBuffer.size > 0) {
848 this.messageBuffer.forEach((message) => {
849 // TODO: evaluate the need to track performance
850 this.wsConnection.send(message);
851 this.messageBuffer.delete(message);
852 });
853 }
854 }
855
856 private getSupervisionUrlOcppConfiguration(): boolean {
857 return this.stationInfo.supervisionUrlOcppConfiguration ?? false;
858 }
859
860 private getSupervisionUrlOcppKey(): string {
861 return this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl;
862 }
863
864 private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
865 // In case of multiple instances: add instance index to charging station id
866 const instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0;
867 const idSuffix = stationTemplate.nameSuffix ?? '';
868 const idStr = '000000000' + this.index.toString();
869 return stationTemplate.fixedName
870 ? stationTemplate.baseName
871 : stationTemplate.baseName +
872 '-' +
873 instanceIndex.toString() +
874 idStr.substring(idStr.length - 4) +
875 idSuffix;
876 }
877
878 private getRandomSerialNumberSuffix(params?: {
879 randomBytesLength?: number;
880 upperCase?: boolean;
881 }): string {
882 const randomSerialNumberSuffix = crypto
883 .randomBytes(params?.randomBytesLength ?? 16)
884 .toString('hex');
885 if (params?.upperCase) {
886 return randomSerialNumberSuffix.toUpperCase();
887 }
888 return randomSerialNumberSuffix;
889 }
890
891 private getTemplateFromFile(): ChargingStationTemplate | null {
892 let template: ChargingStationTemplate = null;
893 try {
894 const measureId = `${FileType.ChargingStationTemplate} read`;
895 const beginId = PerformanceStatistics.beginMeasure(measureId);
896 template =
897 (JSON.parse(fs.readFileSync(this.templateFile, 'utf8')) as ChargingStationTemplate) ??
898 ({} as ChargingStationTemplate);
899 PerformanceStatistics.endMeasure(measureId, beginId);
900 template.templateHash = crypto
901 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
902 .update(JSON.stringify(template))
903 .digest('hex');
904 } catch (error) {
905 FileUtils.handleFileException(
906 this.logPrefix(),
907 FileType.ChargingStationTemplate,
908 this.templateFile,
909 error as NodeJS.ErrnoException
910 );
911 }
912 return template;
913 }
914
915 private createSerialNumber(
916 stationInfo: ChargingStationInfo,
917 existingStationInfo?: ChargingStationInfo,
918 params: { randomSerialNumberUpperCase?: boolean; randomSerialNumber?: boolean } = {
919 randomSerialNumberUpperCase: true,
920 randomSerialNumber: true,
921 }
922 ): void {
923 params = params ?? {};
924 params.randomSerialNumberUpperCase = params?.randomSerialNumberUpperCase ?? true;
925 params.randomSerialNumber = params?.randomSerialNumber ?? true;
926 if (!Utils.isEmptyObject(existingStationInfo)) {
927 existingStationInfo?.chargePointSerialNumber &&
928 (stationInfo.chargePointSerialNumber = existingStationInfo.chargePointSerialNumber);
929 existingStationInfo?.chargeBoxSerialNumber &&
930 (stationInfo.chargeBoxSerialNumber = existingStationInfo.chargeBoxSerialNumber);
931 existingStationInfo?.meterSerialNumber &&
932 (stationInfo.meterSerialNumber = existingStationInfo.meterSerialNumber);
933 } else {
934 const serialNumberSuffix = params?.randomSerialNumber
935 ? this.getRandomSerialNumberSuffix({ upperCase: params.randomSerialNumberUpperCase })
936 : '';
937 stationInfo.chargePointSerialNumber =
938 stationInfo?.chargePointSerialNumberPrefix &&
939 stationInfo.chargePointSerialNumberPrefix + serialNumberSuffix;
940 stationInfo.chargeBoxSerialNumber =
941 stationInfo?.chargeBoxSerialNumberPrefix &&
942 stationInfo.chargeBoxSerialNumberPrefix + serialNumberSuffix;
943 stationInfo.meterSerialNumber =
944 stationInfo?.meterSerialNumberPrefix &&
945 stationInfo.meterSerialNumberPrefix + serialNumberSuffix;
946 }
947 }
948
949 private getStationInfoFromTemplate(): ChargingStationInfo {
950 const stationInfo: ChargingStationInfo = this.getTemplateFromFile();
951 if (Utils.isNullOrUndefined(stationInfo)) {
952 const logMsg = 'Failed to read charging station template file';
953 logger.error(`${this.logPrefix()} ${logMsg}`);
954 throw new BaseError(logMsg);
955 }
956 if (Utils.isEmptyObject(stationInfo)) {
957 logger.warn(
958 `${this.logPrefix()} Empty charging station information from template file ${
959 this.templateFile
960 }`
961 );
962 }
963 const chargingStationId = this.getChargingStationId(stationInfo);
964 // Deprecation template keys section
965 this.warnDeprecatedTemplateKey(
966 stationInfo,
967 'supervisionUrl',
968 chargingStationId,
969 "Use 'supervisionUrls' instead"
970 );
971 this.convertDeprecatedTemplateKey(stationInfo, 'supervisionUrl', 'supervisionUrls');
972 stationInfo.wsOptions = stationInfo?.wsOptions ?? {};
973 if (!Utils.isEmptyArray(stationInfo.power)) {
974 stationInfo.power = stationInfo.power as number[];
975 const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationInfo.power.length);
976 stationInfo.maximumPower =
977 stationInfo.powerUnit === PowerUnits.KILO_WATT
978 ? stationInfo.power[powerArrayRandomIndex] * 1000
979 : stationInfo.power[powerArrayRandomIndex];
980 } else {
981 stationInfo.power = stationInfo.power as number;
982 stationInfo.maximumPower =
983 stationInfo.powerUnit === PowerUnits.KILO_WATT
984 ? stationInfo.power * 1000
985 : stationInfo.power;
986 }
987 delete stationInfo.power;
988 delete stationInfo.powerUnit;
989 stationInfo.chargingStationId = chargingStationId;
990 stationInfo.resetTime = stationInfo.resetTime
991 ? stationInfo.resetTime * 1000
992 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
993 return stationInfo;
994 }
995
996 private createStationInfoHash(stationInfo: ChargingStationInfo): ChargingStationInfo {
997 if (!Utils.isEmptyObject(stationInfo)) {
998 const previousInfoHash = stationInfo?.infoHash ?? '';
999 delete stationInfo.infoHash;
1000 const currentInfoHash = crypto
1001 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
1002 .update(JSON.stringify(stationInfo))
1003 .digest('hex');
1004 if (
1005 Utils.isEmptyString(previousInfoHash) ||
1006 (!Utils.isEmptyString(previousInfoHash) && currentInfoHash !== previousInfoHash)
1007 ) {
1008 stationInfo.infoHash = currentInfoHash;
1009 } else {
1010 stationInfo.infoHash = previousInfoHash;
1011 }
1012 }
1013 return stationInfo;
1014 }
1015
1016 private getStationInfoFromFile(): ChargingStationInfo {
1017 let stationInfo = this.getConfigurationFromFile()?.stationInfo ?? ({} as ChargingStationInfo);
1018 stationInfo = this.createStationInfoHash(stationInfo);
1019 return stationInfo;
1020 }
1021
1022 private getStationInfo(): ChargingStationInfo {
1023 const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate();
1024 this.hashId = this.getHashId(stationInfoFromTemplate);
1025 this.configurationFile = path.join(
1026 path.resolve(__dirname, '../'),
1027 'assets',
1028 'configurations',
1029 this.hashId + '.json'
1030 );
1031 const stationInfoFromFile: ChargingStationInfo = this.getStationInfoFromFile();
1032 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
1033 if (stationInfoFromFile?.templateHash === stationInfoFromTemplate.templateHash) {
1034 if (this.stationInfo?.infoHash === stationInfoFromFile?.infoHash) {
1035 return this.stationInfo;
1036 }
1037 return stationInfoFromFile;
1038 }
1039 this.createSerialNumber(stationInfoFromTemplate, stationInfoFromFile);
1040 return stationInfoFromTemplate;
1041 }
1042
1043 private saveStationInfo(): void {
1044 this.saveConfiguration(Section.stationInfo);
1045 }
1046
1047 private getOcppVersion(): OCPPVersion {
1048 return this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16;
1049 }
1050
1051 private getOcppPersistentConfiguration(): boolean {
1052 return this.stationInfo.ocppPersistentConfiguration ?? true;
1053 }
1054
1055 private handleUnsupportedVersion(version: OCPPVersion) {
1056 const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
1057 this.templateFile
1058 }`;
1059 logger.error(errMsg);
1060 throw new Error(errMsg);
1061 }
1062
1063 private createBootNotificationRequest(stationInfo: ChargingStationInfo): BootNotificationRequest {
1064 return {
1065 chargePointModel: stationInfo.chargePointModel,
1066 chargePointVendor: stationInfo.chargePointVendor,
1067 ...(!Utils.isUndefined(stationInfo.chargeBoxSerialNumber) && {
1068 chargeBoxSerialNumber: stationInfo.chargeBoxSerialNumber,
1069 }),
1070 ...(!Utils.isUndefined(stationInfo.chargePointSerialNumber) && {
1071 chargePointSerialNumber: stationInfo.chargePointSerialNumber,
1072 }),
1073 ...(!Utils.isUndefined(stationInfo.firmwareVersion) && {
1074 firmwareVersion: stationInfo.firmwareVersion,
1075 }),
1076 ...(!Utils.isUndefined(stationInfo.iccid) && { iccid: stationInfo.iccid }),
1077 ...(!Utils.isUndefined(stationInfo.imsi) && { imsi: stationInfo.imsi }),
1078 ...(!Utils.isUndefined(stationInfo.meterSerialNumber) && {
1079 meterSerialNumber: stationInfo.meterSerialNumber,
1080 }),
1081 ...(!Utils.isUndefined(stationInfo.meterType) && {
1082 meterType: stationInfo.meterType,
1083 }),
1084 };
1085 }
1086
1087 private getHashId(stationInfo: ChargingStationInfo): string {
1088 const hashBootNotificationRequest = {
1089 chargePointModel: stationInfo.chargePointModel,
1090 chargePointVendor: stationInfo.chargePointVendor,
1091 ...(!Utils.isUndefined(stationInfo.chargeBoxSerialNumberPrefix) && {
1092 chargeBoxSerialNumber: stationInfo.chargeBoxSerialNumberPrefix,
1093 }),
1094 ...(!Utils.isUndefined(stationInfo.chargePointSerialNumberPrefix) && {
1095 chargePointSerialNumber: stationInfo.chargePointSerialNumberPrefix,
1096 }),
1097 ...(!Utils.isUndefined(stationInfo.firmwareVersion) && {
1098 firmwareVersion: stationInfo.firmwareVersion,
1099 }),
1100 ...(!Utils.isUndefined(stationInfo.iccid) && { iccid: stationInfo.iccid }),
1101 ...(!Utils.isUndefined(stationInfo.imsi) && { imsi: stationInfo.imsi }),
1102 ...(!Utils.isUndefined(stationInfo.meterSerialNumberPrefix) && {
1103 meterSerialNumber: stationInfo.meterSerialNumberPrefix,
1104 }),
1105 ...(!Utils.isUndefined(stationInfo.meterType) && {
1106 meterType: stationInfo.meterType,
1107 }),
1108 };
1109 return crypto
1110 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
1111 .update(JSON.stringify(hashBootNotificationRequest) + stationInfo.chargingStationId)
1112 .digest('hex');
1113 }
1114
1115 private initialize(): void {
1116 this.stationInfo = this.getStationInfo();
1117 logger.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
1118 this.bootNotificationRequest = this.createBootNotificationRequest(this.stationInfo);
1119 this.ocppConfiguration = this.getOcppConfiguration();
1120 this.stationInfo?.Configuration && delete this.stationInfo.Configuration;
1121 this.wsConfiguredConnectionUrl = new URL(
1122 this.getConfiguredSupervisionUrl().href + '/' + this.stationInfo.chargingStationId
1123 );
1124 // Build connectors if needed
1125 const maxConnectors = this.getMaxNumberOfConnectors();
1126 this.checkMaxConnectors(maxConnectors);
1127 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
1128 this.checkTemplateMaxConnectors(templateMaxConnectors);
1129 if (
1130 maxConnectors >
1131 (this.stationInfo?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) &&
1132 !this.stationInfo.randomConnectors
1133 ) {
1134 logger.warn(
1135 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
1136 this.templateFile
1137 }, forcing random connector configurations affectation`
1138 );
1139 this.stationInfo.randomConnectors = true;
1140 }
1141 this.initializeConnectors(this.stationInfo, maxConnectors, templateMaxConnectors);
1142 this.stationInfo.maximumAmperage = this.getMaximumAmperage();
1143 this.stationInfo = this.createStationInfoHash(this.stationInfo);
1144 this.saveStationInfo();
1145 // Avoid duplication of connectors related information in RAM
1146 this.stationInfo?.Connectors && delete this.stationInfo.Connectors;
1147 // OCPP configuration
1148 this.initializeOcppConfiguration();
1149 if (this.getEnableStatistics()) {
1150 this.performanceStatistics = PerformanceStatistics.getInstance(
1151 this.hashId,
1152 this.stationInfo.chargingStationId,
1153 this.wsConnectionUrl
1154 );
1155 }
1156 switch (this.getOcppVersion()) {
1157 case OCPPVersion.VERSION_16:
1158 this.ocppIncomingRequestService =
1159 OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>(this);
1160 this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>(
1161 this,
1162 OCPP16ResponseService.getInstance<OCPP16ResponseService>(this)
1163 );
1164 break;
1165 default:
1166 this.handleUnsupportedVersion(this.getOcppVersion());
1167 break;
1168 }
1169 if (this.stationInfo.autoRegister) {
1170 this.bootNotificationResponse = {
1171 currentTime: new Date().toISOString(),
1172 interval: this.getHeartbeatInterval() / 1000,
1173 status: RegistrationStatus.ACCEPTED,
1174 };
1175 }
1176 this.stationInfo.powerDivider = this.getPowerDivider();
1177 }
1178
1179 private initializeOcppConfiguration(): void {
1180 if (!this.getConfigurationKey(StandardParametersKey.HeartbeatInterval)) {
1181 this.addConfigurationKey(StandardParametersKey.HeartbeatInterval, '0');
1182 }
1183 if (!this.getConfigurationKey(StandardParametersKey.HeartBeatInterval)) {
1184 this.addConfigurationKey(StandardParametersKey.HeartBeatInterval, '0', { visible: false });
1185 }
1186 if (
1187 this.getSupervisionUrlOcppConfiguration() &&
1188 !this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1189 ) {
1190 this.addConfigurationKey(
1191 this.getSupervisionUrlOcppKey(),
1192 this.getConfiguredSupervisionUrl().href,
1193 { reboot: true }
1194 );
1195 } else if (
1196 !this.getSupervisionUrlOcppConfiguration() &&
1197 this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1198 ) {
1199 this.deleteConfigurationKey(this.getSupervisionUrlOcppKey(), { save: false });
1200 }
1201 if (
1202 this.stationInfo.amperageLimitationOcppKey &&
1203 !this.getConfigurationKey(this.stationInfo.amperageLimitationOcppKey)
1204 ) {
1205 this.addConfigurationKey(
1206 this.stationInfo.amperageLimitationOcppKey,
1207 (this.stationInfo.maximumAmperage * this.getAmperageLimitationUnitDivider()).toString()
1208 );
1209 }
1210 if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) {
1211 this.addConfigurationKey(
1212 StandardParametersKey.SupportedFeatureProfiles,
1213 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1214 );
1215 }
1216 this.addConfigurationKey(
1217 StandardParametersKey.NumberOfConnectors,
1218 this.getNumberOfConnectors().toString(),
1219 { readonly: true },
1220 { overwrite: true }
1221 );
1222 if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) {
1223 this.addConfigurationKey(
1224 StandardParametersKey.MeterValuesSampledData,
1225 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
1226 );
1227 }
1228 if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) {
1229 const connectorPhaseRotation = [];
1230 for (const connectorId of this.connectors.keys()) {
1231 // AC/DC
1232 if (connectorId === 0 && this.getNumberOfPhases() === 0) {
1233 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1234 } else if (connectorId > 0 && this.getNumberOfPhases() === 0) {
1235 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1236 // AC
1237 } else if (connectorId > 0 && this.getNumberOfPhases() === 1) {
1238 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1239 } else if (connectorId > 0 && this.getNumberOfPhases() === 3) {
1240 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1241 }
1242 }
1243 this.addConfigurationKey(
1244 StandardParametersKey.ConnectorPhaseRotation,
1245 connectorPhaseRotation.toString()
1246 );
1247 }
1248 if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) {
1249 this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true');
1250 }
1251 if (
1252 !this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled) &&
1253 this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)?.value.includes(
1254 SupportedFeatureProfiles.LocalAuthListManagement
1255 )
1256 ) {
1257 this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false');
1258 }
1259 if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
1260 this.addConfigurationKey(
1261 StandardParametersKey.ConnectionTimeOut,
1262 Constants.DEFAULT_CONNECTION_TIMEOUT.toString()
1263 );
1264 }
1265 this.saveOcppConfiguration();
1266 }
1267
1268 private initializeConnectors(
1269 stationInfo: ChargingStationInfo,
1270 maxConnectors: number,
1271 templateMaxConnectors: number
1272 ): void {
1273 if (!stationInfo?.Connectors && this.connectors.size === 0) {
1274 const logMsg = `${this.logPrefix()} No already defined connectors and charging station information from template ${
1275 this.templateFile
1276 } with no connectors configuration defined`;
1277 logger.error(logMsg);
1278 throw new BaseError(logMsg);
1279 }
1280 if (!stationInfo?.Connectors[0]) {
1281 logger.warn(
1282 `${this.logPrefix()} Charging station information from template ${
1283 this.templateFile
1284 } with no connector Id 0 configuration`
1285 );
1286 }
1287 if (stationInfo?.Connectors) {
1288 const connectorsConfigHash = crypto
1289 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
1290 .update(JSON.stringify(stationInfo?.Connectors) + maxConnectors.toString())
1291 .digest('hex');
1292 const connectorsConfigChanged =
1293 this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash;
1294 if (this.connectors?.size === 0 || connectorsConfigChanged) {
1295 connectorsConfigChanged && this.connectors.clear();
1296 this.connectorsConfigurationHash = connectorsConfigHash;
1297 // Add connector Id 0
1298 let lastConnector = '0';
1299 for (lastConnector in stationInfo?.Connectors) {
1300 const lastConnectorId = Utils.convertToInt(lastConnector);
1301 if (
1302 lastConnectorId === 0 &&
1303 this.getUseConnectorId0() &&
1304 stationInfo?.Connectors[lastConnector]
1305 ) {
1306 this.connectors.set(
1307 lastConnectorId,
1308 Utils.cloneObject<ConnectorStatus>(stationInfo?.Connectors[lastConnector])
1309 );
1310 this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE;
1311 if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) {
1312 this.getConnectorStatus(lastConnectorId).chargingProfiles = [];
1313 }
1314 }
1315 }
1316 // Generate all connectors
1317 if ((stationInfo?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
1318 for (let index = 1; index <= maxConnectors; index++) {
1319 const randConnectorId = stationInfo.randomConnectors
1320 ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1)
1321 : index;
1322 this.connectors.set(
1323 index,
1324 Utils.cloneObject<ConnectorStatus>(stationInfo?.Connectors[randConnectorId])
1325 );
1326 this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE;
1327 if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) {
1328 this.getConnectorStatus(index).chargingProfiles = [];
1329 }
1330 }
1331 }
1332 }
1333 } else {
1334 logger.warn(
1335 `${this.logPrefix()} Charging station information from template ${
1336 this.templateFile
1337 } with no connectors configuration defined, using already defined connectors`
1338 );
1339 }
1340 // Initialize transaction attributes on connectors
1341 for (const connectorId of this.connectors.keys()) {
1342 if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) {
1343 this.initializeConnectorStatus(connectorId);
1344 }
1345 }
1346 }
1347
1348 private checkMaxConnectors(maxConnectors: number): void {
1349 if (maxConnectors <= 0) {
1350 logger.warn(
1351 `${this.logPrefix()} Charging station information from template ${
1352 this.templateFile
1353 } with ${maxConnectors} connectors`
1354 );
1355 }
1356 }
1357
1358 private checkTemplateMaxConnectors(templateMaxConnectors: number): void {
1359 if (templateMaxConnectors === 0) {
1360 logger.warn(
1361 `${this.logPrefix()} Charging station information from template ${
1362 this.templateFile
1363 } with empty connectors configuration`
1364 );
1365 } else if (templateMaxConnectors < 0) {
1366 logger.error(
1367 `${this.logPrefix()} Charging station information from template ${
1368 this.templateFile
1369 } with no connectors configuration defined`
1370 );
1371 }
1372 }
1373
1374 private getConfigurationFromFile(): ChargingStationConfiguration | null {
1375 let configuration: ChargingStationConfiguration = null;
1376 if (this.configurationFile && fs.existsSync(this.configurationFile)) {
1377 try {
1378 const measureId = `${FileType.ChargingStationConfiguration} read`;
1379 const beginId = PerformanceStatistics.beginMeasure(measureId);
1380 configuration = JSON.parse(
1381 fs.readFileSync(this.configurationFile, 'utf8')
1382 ) as ChargingStationConfiguration;
1383 PerformanceStatistics.endMeasure(measureId, beginId);
1384 } catch (error) {
1385 FileUtils.handleFileException(
1386 this.logPrefix(),
1387 FileType.ChargingStationConfiguration,
1388 this.configurationFile,
1389 error as NodeJS.ErrnoException
1390 );
1391 }
1392 }
1393 return configuration;
1394 }
1395
1396 private saveConfiguration(section?: Section): void {
1397 if (this.configurationFile) {
1398 try {
1399 const configurationData: ChargingStationConfiguration =
1400 this.getConfigurationFromFile() ?? {};
1401 if (!fs.existsSync(path.dirname(this.configurationFile))) {
1402 fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true });
1403 }
1404 switch (section) {
1405 case Section.ocppConfiguration:
1406 configurationData.configurationKey = this.ocppConfiguration.configurationKey;
1407 break;
1408 case Section.stationInfo:
1409 if (configurationData?.stationInfo?.infoHash === this.stationInfo?.infoHash) {
1410 logger.debug(
1411 `${this.logPrefix()} Not saving unchanged charging station information to configuration file ${
1412 this.configurationFile
1413 }`
1414 );
1415 return;
1416 }
1417 configurationData.stationInfo = this.stationInfo;
1418 break;
1419 default:
1420 configurationData.configurationKey = this.ocppConfiguration.configurationKey;
1421 if (configurationData?.stationInfo?.infoHash !== this.stationInfo?.infoHash) {
1422 configurationData.stationInfo = this.stationInfo;
1423 }
1424 break;
1425 }
1426 const measureId = `${FileType.ChargingStationConfiguration} write`;
1427 const beginId = PerformanceStatistics.beginMeasure(measureId);
1428 const fileDescriptor = fs.openSync(this.configurationFile, 'w');
1429 fs.writeFileSync(fileDescriptor, JSON.stringify(configurationData, null, 2), 'utf8');
1430 fs.closeSync(fileDescriptor);
1431 PerformanceStatistics.endMeasure(measureId, beginId);
1432 } catch (error) {
1433 FileUtils.handleFileException(
1434 this.logPrefix(),
1435 FileType.ChargingStationConfiguration,
1436 this.configurationFile,
1437 error as NodeJS.ErrnoException
1438 );
1439 }
1440 } else {
1441 logger.error(
1442 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1443 );
1444 }
1445 }
1446
1447 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration {
1448 return this.getTemplateFromFile().Configuration ?? ({} as ChargingStationOcppConfiguration);
1449 }
1450
1451 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | null {
1452 let configuration: ChargingStationConfiguration = null;
1453 if (this.getOcppPersistentConfiguration()) {
1454 const configurationFromFile = this.getConfigurationFromFile();
1455 configuration = configurationFromFile?.configurationKey && configurationFromFile;
1456 }
1457 configuration && delete configuration.stationInfo;
1458 return configuration;
1459 }
1460
1461 private getOcppConfiguration(): ChargingStationOcppConfiguration {
1462 let ocppConfiguration: ChargingStationOcppConfiguration = this.getOcppConfigurationFromFile();
1463 if (!ocppConfiguration) {
1464 ocppConfiguration = this.getOcppConfigurationFromTemplate();
1465 }
1466 return ocppConfiguration;
1467 }
1468
1469 private saveOcppConfiguration(): void {
1470 if (this.getOcppPersistentConfiguration()) {
1471 this.saveConfiguration(Section.ocppConfiguration);
1472 }
1473 }
1474
1475 private async onOpen(): Promise<void> {
1476 if (this.isWebSocketConnectionOpened()) {
1477 logger.info(
1478 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1479 );
1480 if (!this.isRegistered()) {
1481 // Send BootNotification
1482 let registrationRetryCount = 0;
1483 do {
1484 this.bootNotificationResponse = await this.ocppRequestService.requestHandler<
1485 BootNotificationRequest,
1486 BootNotificationResponse
1487 >(
1488 RequestCommand.BOOT_NOTIFICATION,
1489 {
1490 chargePointModel: this.bootNotificationRequest.chargePointModel,
1491 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1492 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1493 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
1494 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1495 iccid: this.bootNotificationRequest.iccid,
1496 imsi: this.bootNotificationRequest.imsi,
1497 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1498 meterType: this.bootNotificationRequest.meterType,
1499 },
1500 { skipBufferingOnError: true }
1501 );
1502 if (!this.isRegistered()) {
1503 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++;
1504 await Utils.sleep(
1505 this.bootNotificationResponse?.interval
1506 ? this.bootNotificationResponse.interval * 1000
1507 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1508 );
1509 }
1510 } while (
1511 !this.isRegistered() &&
1512 (registrationRetryCount <= this.getRegistrationMaxRetries() ||
1513 this.getRegistrationMaxRetries() === -1)
1514 );
1515 }
1516 if (this.isRegistered()) {
1517 if (this.isInAcceptedState()) {
1518 await this.startMessageSequence();
1519 this.wsConnectionRestarted && this.flushMessageBuffer();
1520 }
1521 } else {
1522 logger.error(
1523 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1524 );
1525 }
1526 this.stopped && (this.stopped = false);
1527 this.autoReconnectRetryCount = 0;
1528 this.wsConnectionRestarted = false;
1529 } else {
1530 logger.warn(
1531 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1532 );
1533 }
1534 }
1535
1536 private async onClose(code: number, reason: string): Promise<void> {
1537 switch (code) {
1538 // Normal close
1539 case WebSocketCloseEventStatusCode.CLOSE_NORMAL:
1540 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
1541 logger.info(
1542 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1543 code
1544 )}' and reason '${reason}'`
1545 );
1546 this.autoReconnectRetryCount = 0;
1547 break;
1548 // Abnormal close
1549 default:
1550 logger.error(
1551 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1552 code
1553 )}' and reason '${reason}'`
1554 );
1555 await this.reconnect(code);
1556 break;
1557 }
1558 }
1559
1560 private async onMessage(data: Data): Promise<void> {
1561 let messageType: number;
1562 let messageId: string;
1563 let commandName: IncomingRequestCommand;
1564 let commandPayload: JsonType;
1565 let errorType: ErrorType;
1566 let errorMessage: string;
1567 let errorDetails: JsonType;
1568 let responseCallback: (payload: JsonType, requestPayload: JsonType) => void;
1569 let errorCallback: (error: OCPPError, requestStatistic?: boolean) => void;
1570 let requestCommandName: RequestCommand | IncomingRequestCommand;
1571 let requestPayload: JsonType;
1572 let cachedRequest: CachedRequest;
1573 let errMsg: string;
1574 try {
1575 const request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse;
1576 if (Utils.isIterable(request)) {
1577 [messageType, messageId] = request;
1578 // Check the type of message
1579 switch (messageType) {
1580 // Incoming Message
1581 case MessageType.CALL_MESSAGE:
1582 [, , commandName, commandPayload] = request as IncomingRequest;
1583 if (this.getEnableStatistics()) {
1584 this.performanceStatistics.addRequestStatistic(commandName, messageType);
1585 }
1586 logger.debug(
1587 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1588 request
1589 )}`
1590 );
1591 // Process the message
1592 await this.ocppIncomingRequestService.incomingRequestHandler(
1593 messageId,
1594 commandName,
1595 commandPayload
1596 );
1597 break;
1598 // Outcome Message
1599 case MessageType.CALL_RESULT_MESSAGE:
1600 [, , commandPayload] = request as Response;
1601 if (!this.requests.has(messageId)) {
1602 // Error
1603 throw new OCPPError(
1604 ErrorType.INTERNAL_ERROR,
1605 `Response for unknown message id ${messageId}`,
1606 null,
1607 commandPayload
1608 );
1609 }
1610 // Respond
1611 cachedRequest = this.requests.get(messageId);
1612 if (Utils.isIterable(cachedRequest)) {
1613 [responseCallback, , requestCommandName, requestPayload] = cachedRequest;
1614 } else {
1615 throw new OCPPError(
1616 ErrorType.PROTOCOL_ERROR,
1617 `Cached request for message id ${messageId} response is not iterable`,
1618 null,
1619 cachedRequest as unknown as JsonType
1620 );
1621 }
1622 logger.debug(
1623 `${this.logPrefix()} << Command '${
1624 requestCommandName ?? ''
1625 }' received response payload: ${JSON.stringify(request)}`
1626 );
1627 responseCallback(commandPayload, requestPayload);
1628 break;
1629 // Error Message
1630 case MessageType.CALL_ERROR_MESSAGE:
1631 [, , errorType, errorMessage, errorDetails] = request as ErrorResponse;
1632 if (!this.requests.has(messageId)) {
1633 // Error
1634 throw new OCPPError(
1635 ErrorType.INTERNAL_ERROR,
1636 `Error response for unknown message id ${messageId}`,
1637 null,
1638 { errorType, errorMessage, errorDetails }
1639 );
1640 }
1641 cachedRequest = this.requests.get(messageId);
1642 if (Utils.isIterable(cachedRequest)) {
1643 [, errorCallback, requestCommandName] = cachedRequest;
1644 } else {
1645 throw new OCPPError(
1646 ErrorType.PROTOCOL_ERROR,
1647 `Cached request for message id ${messageId} error response is not iterable`,
1648 null,
1649 cachedRequest as unknown as JsonType
1650 );
1651 }
1652 logger.debug(
1653 `${this.logPrefix()} << Command '${
1654 requestCommandName ?? ''
1655 }' received error payload: ${JSON.stringify(request)}`
1656 );
1657 errorCallback(new OCPPError(errorType, errorMessage, requestCommandName, errorDetails));
1658 break;
1659 // Error
1660 default:
1661 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1662 errMsg = `${this.logPrefix()} Wrong message type ${messageType}`;
1663 logger.error(errMsg);
1664 throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg);
1665 }
1666 } else {
1667 throw new OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming message is not iterable', null, {
1668 payload: request,
1669 });
1670 }
1671 } catch (error) {
1672 // Log
1673 logger.error(
1674 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1675 this.logPrefix(),
1676 data.toString(),
1677 this.requests.get(messageId),
1678 error
1679 );
1680 // Send error
1681 messageType === MessageType.CALL_MESSAGE &&
1682 (await this.ocppRequestService.sendError(
1683 messageId,
1684 error as OCPPError,
1685 commandName ?? requestCommandName ?? null
1686 ));
1687 }
1688 }
1689
1690 private onPing(): void {
1691 logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1692 }
1693
1694 private onPong(): void {
1695 logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1696 }
1697
1698 private onError(error: WSError): void {
1699 logger.error(this.logPrefix() + ' WebSocket error: %j', error);
1700 }
1701
1702 private getAuthorizationFile(): string | undefined {
1703 return (
1704 this.stationInfo.authorizationFile &&
1705 path.join(
1706 path.resolve(__dirname, '../'),
1707 'assets',
1708 path.basename(this.stationInfo.authorizationFile)
1709 )
1710 );
1711 }
1712
1713 private getAuthorizedTags(): string[] {
1714 let authorizedTags: string[] = [];
1715 const authorizationFile = this.getAuthorizationFile();
1716 if (authorizationFile) {
1717 try {
1718 // Load authorization file
1719 authorizedTags = JSON.parse(fs.readFileSync(authorizationFile, 'utf8')) as string[];
1720 } catch (error) {
1721 FileUtils.handleFileException(
1722 this.logPrefix(),
1723 FileType.Authorization,
1724 authorizationFile,
1725 error as NodeJS.ErrnoException
1726 );
1727 }
1728 } else {
1729 logger.info(
1730 this.logPrefix() + ' No authorization file given in template file ' + this.templateFile
1731 );
1732 }
1733 return authorizedTags;
1734 }
1735
1736 private getUseConnectorId0(): boolean | undefined {
1737 return !Utils.isUndefined(this.stationInfo.useConnectorId0)
1738 ? this.stationInfo.useConnectorId0
1739 : true;
1740 }
1741
1742 private getNumberOfRunningTransactions(): number {
1743 let trxCount = 0;
1744 for (const connectorId of this.connectors.keys()) {
1745 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
1746 trxCount++;
1747 }
1748 }
1749 return trxCount;
1750 }
1751
1752 // 0 for disabling
1753 private getConnectionTimeout(): number | undefined {
1754 if (this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
1755 return (
1756 parseInt(this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut).value) ??
1757 Constants.DEFAULT_CONNECTION_TIMEOUT
1758 );
1759 }
1760 return Constants.DEFAULT_CONNECTION_TIMEOUT;
1761 }
1762
1763 // -1 for unlimited, 0 for disabling
1764 private getAutoReconnectMaxRetries(): number | undefined {
1765 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
1766 return this.stationInfo.autoReconnectMaxRetries;
1767 }
1768 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
1769 return Configuration.getAutoReconnectMaxRetries();
1770 }
1771 return -1;
1772 }
1773
1774 // 0 for disabling
1775 private getRegistrationMaxRetries(): number | undefined {
1776 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
1777 return this.stationInfo.registrationMaxRetries;
1778 }
1779 return -1;
1780 }
1781
1782 private getPowerDivider(): number {
1783 let powerDivider = this.getNumberOfConnectors();
1784 if (this.stationInfo.powerSharedByConnectors) {
1785 powerDivider = this.getNumberOfRunningTransactions();
1786 }
1787 return powerDivider;
1788 }
1789
1790 private getTemplateMaxNumberOfConnectors(): number {
1791 if (!this.stationInfo?.Connectors) {
1792 return -1;
1793 }
1794 return Object.keys(this.stationInfo?.Connectors).length;
1795 }
1796
1797 private getMaxNumberOfConnectors(): number {
1798 let maxConnectors: number;
1799 if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) {
1800 const numberOfConnectors = this.stationInfo.numberOfConnectors as number[];
1801 // Distribute evenly the number of connectors
1802 maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length];
1803 } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) {
1804 maxConnectors = this.stationInfo.numberOfConnectors as number;
1805 } else {
1806 maxConnectors = this.stationInfo?.Connectors[0]
1807 ? this.getTemplateMaxNumberOfConnectors() - 1
1808 : this.getTemplateMaxNumberOfConnectors();
1809 }
1810 return maxConnectors;
1811 }
1812
1813 private getMaximumPower(): number {
1814 return (this.stationInfo['maxPower'] as number) ?? this.stationInfo.maximumPower;
1815 }
1816
1817 private getMaximumAmperage(): number | undefined {
1818 const maximumPower = this.getMaximumPower();
1819 switch (this.getCurrentOutType()) {
1820 case CurrentType.AC:
1821 return ACElectricUtils.amperagePerPhaseFromPower(
1822 this.getNumberOfPhases(),
1823 maximumPower / this.getNumberOfConnectors(),
1824 this.getVoltageOut()
1825 );
1826 case CurrentType.DC:
1827 return DCElectricUtils.amperage(maximumPower, this.getVoltageOut());
1828 }
1829 }
1830
1831 private getAmperageLimitationUnitDivider(): number {
1832 let unitDivider = 1;
1833 switch (this.stationInfo.amperageLimitationUnit) {
1834 case AmpereUnits.DECI_AMPERE:
1835 unitDivider = 10;
1836 break;
1837 case AmpereUnits.CENTI_AMPERE:
1838 unitDivider = 100;
1839 break;
1840 case AmpereUnits.MILLI_AMPERE:
1841 unitDivider = 1000;
1842 break;
1843 }
1844 return unitDivider;
1845 }
1846
1847 private getAmperageLimitation(): number | undefined {
1848 if (
1849 this.stationInfo.amperageLimitationOcppKey &&
1850 this.getConfigurationKey(this.stationInfo.amperageLimitationOcppKey)
1851 ) {
1852 return (
1853 Utils.convertToInt(
1854 this.getConfigurationKey(this.stationInfo.amperageLimitationOcppKey).value
1855 ) / this.getAmperageLimitationUnitDivider()
1856 );
1857 }
1858 }
1859
1860 private async startMessageSequence(): Promise<void> {
1861 if (this.stationInfo.autoRegister) {
1862 await this.ocppRequestService.requestHandler<
1863 BootNotificationRequest,
1864 BootNotificationResponse
1865 >(
1866 RequestCommand.BOOT_NOTIFICATION,
1867 {
1868 chargePointModel: this.bootNotificationRequest.chargePointModel,
1869 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1870 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1871 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
1872 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1873 iccid: this.bootNotificationRequest.iccid,
1874 imsi: this.bootNotificationRequest.imsi,
1875 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1876 meterType: this.bootNotificationRequest.meterType,
1877 },
1878 { skipBufferingOnError: true }
1879 );
1880 }
1881 // Start WebSocket ping
1882 this.startWebSocketPing();
1883 // Start heartbeat
1884 this.startHeartbeat();
1885 // Initialize connectors status
1886 for (const connectorId of this.connectors.keys()) {
1887 if (connectorId === 0) {
1888 continue;
1889 } else if (
1890 !this.stopped &&
1891 !this.getConnectorStatus(connectorId)?.status &&
1892 this.getConnectorStatus(connectorId)?.bootStatus
1893 ) {
1894 // Send status in template at startup
1895 await this.ocppRequestService.requestHandler<
1896 StatusNotificationRequest,
1897 StatusNotificationResponse
1898 >(RequestCommand.STATUS_NOTIFICATION, {
1899 connectorId,
1900 status: this.getConnectorStatus(connectorId).bootStatus,
1901 errorCode: ChargePointErrorCode.NO_ERROR,
1902 });
1903 this.getConnectorStatus(connectorId).status =
1904 this.getConnectorStatus(connectorId).bootStatus;
1905 } else if (
1906 this.stopped &&
1907 this.getConnectorStatus(connectorId)?.status &&
1908 this.getConnectorStatus(connectorId)?.bootStatus
1909 ) {
1910 // Send status in template after reset
1911 await this.ocppRequestService.requestHandler<
1912 StatusNotificationRequest,
1913 StatusNotificationResponse
1914 >(RequestCommand.STATUS_NOTIFICATION, {
1915 connectorId,
1916 status: this.getConnectorStatus(connectorId).bootStatus,
1917 errorCode: ChargePointErrorCode.NO_ERROR,
1918 });
1919 this.getConnectorStatus(connectorId).status =
1920 this.getConnectorStatus(connectorId).bootStatus;
1921 } else if (!this.stopped && this.getConnectorStatus(connectorId)?.status) {
1922 // Send previous status at template reload
1923 await this.ocppRequestService.requestHandler<
1924 StatusNotificationRequest,
1925 StatusNotificationResponse
1926 >(RequestCommand.STATUS_NOTIFICATION, {
1927 connectorId,
1928 status: this.getConnectorStatus(connectorId).status,
1929 errorCode: ChargePointErrorCode.NO_ERROR,
1930 });
1931 } else {
1932 // Send default status
1933 await this.ocppRequestService.requestHandler<
1934 StatusNotificationRequest,
1935 StatusNotificationResponse
1936 >(RequestCommand.STATUS_NOTIFICATION, {
1937 connectorId,
1938 status: ChargePointStatus.AVAILABLE,
1939 errorCode: ChargePointErrorCode.NO_ERROR,
1940 });
1941 this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE;
1942 }
1943 }
1944 // Start the ATG
1945 this.startAutomaticTransactionGenerator();
1946 }
1947
1948 private startAutomaticTransactionGenerator() {
1949 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
1950 if (!this.automaticTransactionGenerator) {
1951 this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance(this);
1952 }
1953 if (!this.automaticTransactionGenerator.started) {
1954 this.automaticTransactionGenerator.start();
1955 }
1956 }
1957 }
1958
1959 private async stopMessageSequence(
1960 reason: StopTransactionReason = StopTransactionReason.NONE
1961 ): Promise<void> {
1962 // Stop WebSocket ping
1963 this.stopWebSocketPing();
1964 // Stop heartbeat
1965 this.stopHeartbeat();
1966 // Stop the ATG
1967 if (
1968 this.stationInfo.AutomaticTransactionGenerator.enable &&
1969 this.automaticTransactionGenerator?.started
1970 ) {
1971 this.automaticTransactionGenerator.stop();
1972 } else {
1973 for (const connectorId of this.connectors.keys()) {
1974 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
1975 const transactionId = this.getConnectorStatus(connectorId).transactionId;
1976 if (
1977 this.getBeginEndMeterValues() &&
1978 this.getOcppStrictCompliance() &&
1979 !this.getOutOfOrderEndMeterValues()
1980 ) {
1981 // FIXME: Implement OCPP version agnostic helpers
1982 const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue(
1983 this,
1984 connectorId,
1985 this.getEnergyActiveImportRegisterByTransactionId(transactionId)
1986 );
1987 await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>(
1988 RequestCommand.METER_VALUES,
1989 {
1990 connectorId,
1991 transactionId,
1992 meterValue: transactionEndMeterValue,
1993 }
1994 );
1995 }
1996 await this.ocppRequestService.requestHandler<
1997 StopTransactionRequest,
1998 StopTransactionResponse
1999 >(RequestCommand.STOP_TRANSACTION, {
2000 transactionId,
2001 meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId),
2002 idTag: this.getTransactionIdTag(transactionId),
2003 reason,
2004 });
2005 }
2006 }
2007 }
2008 }
2009
2010 private startWebSocketPing(): void {
2011 const webSocketPingInterval: number = this.getConfigurationKey(
2012 StandardParametersKey.WebSocketPingInterval
2013 )
2014 ? Utils.convertToInt(
2015 this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value
2016 )
2017 : 0;
2018 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
2019 this.webSocketPingSetInterval = setInterval(() => {
2020 if (this.isWebSocketConnectionOpened()) {
2021 this.wsConnection.ping((): void => {
2022 /* This is intentional */
2023 });
2024 }
2025 }, webSocketPingInterval * 1000);
2026 logger.info(
2027 this.logPrefix() +
2028 ' WebSocket ping started every ' +
2029 Utils.formatDurationSeconds(webSocketPingInterval)
2030 );
2031 } else if (this.webSocketPingSetInterval) {
2032 logger.info(
2033 this.logPrefix() +
2034 ' WebSocket ping every ' +
2035 Utils.formatDurationSeconds(webSocketPingInterval) +
2036 ' already started'
2037 );
2038 } else {
2039 logger.error(
2040 `${this.logPrefix()} WebSocket ping interval set to ${
2041 webSocketPingInterval
2042 ? Utils.formatDurationSeconds(webSocketPingInterval)
2043 : webSocketPingInterval
2044 }, not starting the WebSocket ping`
2045 );
2046 }
2047 }
2048
2049 private stopWebSocketPing(): void {
2050 if (this.webSocketPingSetInterval) {
2051 clearInterval(this.webSocketPingSetInterval);
2052 }
2053 }
2054
2055 private warnDeprecatedTemplateKey(
2056 template: ChargingStationTemplate,
2057 key: string,
2058 chargingStationId: string,
2059 logMsgToAppend = ''
2060 ): void {
2061 if (!Utils.isUndefined(template[key])) {
2062 const logPrefixStr = ` ${chargingStationId} |`;
2063 logger.warn(
2064 `${Utils.logPrefix(logPrefixStr)} Deprecated template key '${key}' usage in file '${
2065 this.templateFile
2066 }'${logMsgToAppend && '. ' + logMsgToAppend}`
2067 );
2068 }
2069 }
2070
2071 private convertDeprecatedTemplateKey(
2072 template: ChargingStationTemplate,
2073 deprecatedKey: string,
2074 key: string
2075 ): void {
2076 if (!Utils.isUndefined(template[deprecatedKey])) {
2077 template[key] = template[deprecatedKey] as unknown;
2078 delete template[deprecatedKey];
2079 }
2080 }
2081
2082 private getConfiguredSupervisionUrl(): URL {
2083 const supervisionUrls = Utils.cloneObject<string | string[]>(
2084 this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls()
2085 );
2086 if (!Utils.isEmptyArray(supervisionUrls)) {
2087 let urlIndex = 0;
2088 switch (Configuration.getSupervisionUrlDistribution()) {
2089 case SupervisionUrlDistribution.ROUND_ROBIN:
2090 urlIndex = (this.index - 1) % supervisionUrls.length;
2091 break;
2092 case SupervisionUrlDistribution.RANDOM:
2093 // Get a random url
2094 urlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length);
2095 break;
2096 case SupervisionUrlDistribution.SEQUENTIAL:
2097 if (this.index <= supervisionUrls.length) {
2098 urlIndex = this.index - 1;
2099 } else {
2100 logger.warn(
2101 `${this.logPrefix()} No more configured supervision urls available, using the first one`
2102 );
2103 }
2104 break;
2105 default:
2106 logger.error(
2107 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2108 SupervisionUrlDistribution.ROUND_ROBIN
2109 }`
2110 );
2111 urlIndex = (this.index - 1) % supervisionUrls.length;
2112 break;
2113 }
2114 return new URL(supervisionUrls[urlIndex]);
2115 }
2116 return new URL(supervisionUrls as string);
2117 }
2118
2119 private getHeartbeatInterval(): number | undefined {
2120 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
2121 if (HeartbeatInterval) {
2122 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
2123 }
2124 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
2125 if (HeartBeatInterval) {
2126 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
2127 }
2128 !this.stationInfo.autoRegister &&
2129 logger.warn(
2130 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
2131 Constants.DEFAULT_HEARTBEAT_INTERVAL
2132 }`
2133 );
2134 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
2135 }
2136
2137 private stopHeartbeat(): void {
2138 if (this.heartbeatSetInterval) {
2139 clearInterval(this.heartbeatSetInterval);
2140 }
2141 }
2142
2143 private openWSConnection(
2144 options: WsOptions = this.stationInfo.wsOptions,
2145 forceCloseOpened = false
2146 ): void {
2147 options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
2148 if (
2149 !Utils.isNullOrUndefined(this.stationInfo.supervisionUser) &&
2150 !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)
2151 ) {
2152 options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
2153 }
2154 if (this.isWebSocketConnectionOpened() && forceCloseOpened) {
2155 this.wsConnection.close();
2156 }
2157 let protocol: string;
2158 switch (this.getOcppVersion()) {
2159 case OCPPVersion.VERSION_16:
2160 protocol = 'ocpp' + OCPPVersion.VERSION_16;
2161 break;
2162 default:
2163 this.handleUnsupportedVersion(this.getOcppVersion());
2164 break;
2165 }
2166 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
2167 logger.info(
2168 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString()
2169 );
2170 }
2171
2172 private stopMeterValues(connectorId: number) {
2173 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
2174 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
2175 }
2176 }
2177
2178 private getReconnectExponentialDelay(): boolean | undefined {
2179 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay)
2180 ? this.stationInfo.reconnectExponentialDelay
2181 : false;
2182 }
2183
2184 private async reconnect(code: number): Promise<void> {
2185 // Stop WebSocket ping
2186 this.stopWebSocketPing();
2187 // Stop heartbeat
2188 this.stopHeartbeat();
2189 // Stop the ATG if needed
2190 if (
2191 this.stationInfo.AutomaticTransactionGenerator.enable &&
2192 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
2193 this.automaticTransactionGenerator?.started
2194 ) {
2195 this.automaticTransactionGenerator.stop();
2196 }
2197 if (
2198 this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() ||
2199 this.getAutoReconnectMaxRetries() === -1
2200 ) {
2201 this.autoReconnectRetryCount++;
2202 const reconnectDelay = this.getReconnectExponentialDelay()
2203 ? Utils.exponentialDelay(this.autoReconnectRetryCount)
2204 : this.getConnectionTimeout() * 1000;
2205 const reconnectTimeout = reconnectDelay - 100 > 0 && reconnectDelay;
2206 logger.error(
2207 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
2208 reconnectDelay,
2209 2
2210 )}ms, timeout ${reconnectTimeout}ms`
2211 );
2212 await Utils.sleep(reconnectDelay);
2213 logger.error(
2214 this.logPrefix() +
2215 ' WebSocket: reconnecting try #' +
2216 this.autoReconnectRetryCount.toString()
2217 );
2218 this.openWSConnection(
2219 { ...this.stationInfo.wsOptions, handshakeTimeout: reconnectTimeout },
2220 true
2221 );
2222 this.wsConnectionRestarted = true;
2223 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2224 logger.error(
2225 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2226 this.autoReconnectRetryCount
2227 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2228 );
2229 }
2230 }
2231
2232 private initializeConnectorStatus(connectorId: number): void {
2233 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
2234 this.getConnectorStatus(connectorId).idTagAuthorized = false;
2235 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
2236 this.getConnectorStatus(connectorId).transactionStarted = false;
2237 this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
2238 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
2239 }
2240
2241 /*
2242 * Charging profiles should already be sorted by connectorId and stack level (highest stack level has priority)
2243 */
2244 private getCurrentLimitFromChargingProfiles(chargingProfiles: ChargingProfile[]): {
2245 limit: number;
2246 matchingChargingProfile: ChargingProfile;
2247 } | null {
2248 for (const chargingProfile of chargingProfiles) {
2249 // Set helpers
2250 const currentMoment = moment();
2251 const chargingSchedule = chargingProfile.chargingSchedule;
2252 // Check type (recurring) and if it is already active
2253 // Adjust the daily recurring schedule to today
2254 if (
2255 chargingProfile.chargingProfileKind === ChargingProfileKindType.RECURRING &&
2256 chargingProfile.recurrencyKind === RecurrencyKindType.DAILY &&
2257 currentMoment.isAfter(chargingSchedule.startSchedule)
2258 ) {
2259 const currentDate = new Date();
2260 chargingSchedule.startSchedule = new Date(chargingSchedule.startSchedule);
2261 chargingSchedule.startSchedule.setFullYear(
2262 currentDate.getFullYear(),
2263 currentDate.getMonth(),
2264 currentDate.getDate()
2265 );
2266 // Check if the start of the schedule is yesterday
2267 if (moment(chargingSchedule.startSchedule).isAfter(currentMoment)) {
2268 chargingSchedule.startSchedule.setDate(currentDate.getDate() - 1);
2269 }
2270 } else if (moment(chargingSchedule.startSchedule).isAfter(currentMoment)) {
2271 return null;
2272 }
2273 // Check if the charging profile is active
2274 if (
2275 moment(chargingSchedule.startSchedule)
2276 .add(chargingSchedule.duration, 's')
2277 .isAfter(currentMoment)
2278 ) {
2279 let lastButOneSchedule: ChargingSchedulePeriod;
2280 // Search the right schedule period
2281 for (const schedulePeriod of chargingSchedule.chargingSchedulePeriod) {
2282 // Handling of only one period
2283 if (
2284 chargingSchedule.chargingSchedulePeriod.length === 1 &&
2285 schedulePeriod.startPeriod === 0
2286 ) {
2287 const result = {
2288 limit: schedulePeriod.limit,
2289 matchingChargingProfile: chargingProfile,
2290 };
2291 logger.debug(
2292 `${this.logPrefix()} Matching charging profile found for power limitation: %j`,
2293 result
2294 );
2295 return result;
2296 }
2297 // Find the right schedule period
2298 if (
2299 moment(chargingSchedule.startSchedule)
2300 .add(schedulePeriod.startPeriod, 's')
2301 .isAfter(currentMoment)
2302 ) {
2303 // Found the schedule: last but one is the correct one
2304 const result = {
2305 limit: lastButOneSchedule.limit,
2306 matchingChargingProfile: chargingProfile,
2307 };
2308 logger.debug(
2309 `${this.logPrefix()} Matching charging profile found for power limitation: %j`,
2310 result
2311 );
2312 return result;
2313 }
2314 // Keep it
2315 lastButOneSchedule = schedulePeriod;
2316 // Handle the last schedule period
2317 if (
2318 schedulePeriod.startPeriod ===
2319 chargingSchedule.chargingSchedulePeriod[
2320 chargingSchedule.chargingSchedulePeriod.length - 1
2321 ].startPeriod
2322 ) {
2323 const result = {
2324 limit: lastButOneSchedule.limit,
2325 matchingChargingProfile: chargingProfile,
2326 };
2327 logger.debug(
2328 `${this.logPrefix()} Matching charging profile found for power limitation: %j`,
2329 result
2330 );
2331 return result;
2332 }
2333 }
2334 }
2335 }
2336 return null;
2337 }
2338}