1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import { ACElectricUtils
, DCElectricUtils
} from
'../utils/ElectricUtils';
6 BootNotificationRequest
,
10 IncomingRequestCommand
,
13 StatusNotificationRequest
,
14 } from
'../types/ocpp/Requests';
16 BootNotificationResponse
,
22 StatusNotificationResponse
,
23 } from
'../types/ocpp/Responses';
27 ChargingSchedulePeriod
,
28 } from
'../types/ocpp/ChargingProfile';
29 import { ChargingProfileKindType
, RecurrencyKindType
} from
'../types/ocpp/1.6/ChargingProfile';
30 import ChargingStationConfiguration
, { Section
} from
'../types/ChargingStationConfiguration';
31 import ChargingStationOcppConfiguration
, {
33 } from
'../types/ChargingStationOcppConfiguration';
34 import ChargingStationTemplate
, {
40 } from
'../types/ChargingStationTemplate';
42 ConnectorPhaseRotation
,
43 StandardParametersKey
,
44 SupportedFeatureProfiles
,
45 VendorDefaultParametersKey
,
46 } from
'../types/ocpp/Configuration';
47 import { MeterValue
, MeterValueMeasurand
, MeterValuePhase
} from
'../types/ocpp/MeterValues';
49 StopTransactionReason
,
50 StopTransactionRequest
,
51 StopTransactionResponse
,
52 } from
'../types/ocpp/Transaction';
53 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
54 import WebSocket
, { Data
, OPEN
, RawData
} from
'ws';
56 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
57 import BaseError from
'../exception/BaseError';
58 import { ChargePointErrorCode
} from
'../types/ocpp/ChargePointErrorCode';
59 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
60 import ChargingStationInfo from
'../types/ChargingStationInfo';
61 import { ChargingStationWorkerMessageEvents
} from
'../types/ChargingStationWorker';
62 import Configuration from
'../utils/Configuration';
63 import { ConnectorStatus
} from
'../types/ConnectorStatus';
64 import Constants from
'../utils/Constants';
65 import { ErrorType
} from
'../types/ocpp/ErrorType';
66 import { FileType
} from
'../types/FileType';
67 import FileUtils from
'../utils/FileUtils';
68 import { JsonType
} from
'../types/JsonType';
69 import { MessageType
} from
'../types/ocpp/MessageType';
70 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
71 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
72 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
73 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
74 import OCPPError from
'../exception/OCPPError';
75 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
76 import OCPPRequestService from
'./ocpp/OCPPRequestService';
77 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
78 import PerformanceStatistics from
'../performance/PerformanceStatistics';
79 import { SampledValueTemplate
} from
'../types/MeasurandPerPhaseSampledValueTemplates';
80 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
81 import { URL
} from
'url';
82 import Utils from
'../utils/Utils';
83 import crypto from
'crypto';
85 import logger from
'../utils/Logger';
86 import moment from
'moment';
87 import { parentPort
} from
'worker_threads';
88 import path from
'path';
90 export 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
;
116 constructor(index
: number, templateFile
: string) {
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>();
126 this.authorizedTags
= this.getAuthorizedTags();
129 private get
wsConnectionUrl(): URL
{
130 return this.getSupervisionUrlOcppConfiguration()
132 this.getConfigurationKey(this.getSupervisionUrlOcppKey()).value
+
134 this.stationInfo
.chargingStationId
136 : this.wsConfiguredConnectionUrl
;
139 public logPrefix(): string {
140 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId} |`);
143 public getBootNotificationRequest(): BootNotificationRequest
{
144 return this.bootNotificationRequest
;
147 public getRandomIdTag(): string {
148 const index
= Math.floor(Utils
.secureRandom() * this.authorizedTags
.length
);
149 return this.authorizedTags
[index
];
152 public hasAuthorizedTags(): boolean {
153 return !Utils
.isEmptyArray(this.authorizedTags
);
156 public getEnableStatistics(): boolean | undefined {
157 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
158 ? this.stationInfo
.enableStatistics
162 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
163 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
166 public getNumberOfPhases(): number | undefined {
167 switch (this.getCurrentOutType()) {
169 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
)
170 ? this.stationInfo
.numberOfPhases
177 public isWebSocketConnectionOpened(): boolean {
178 return this?.wsConnection
?.readyState
=== OPEN
;
181 public getRegistrationStatus(): RegistrationStatus
{
182 return this?.bootNotificationResponse
?.status;
185 public isInUnknownState(): boolean {
186 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
189 public isInPendingState(): boolean {
190 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
193 public isInAcceptedState(): boolean {
194 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
197 public isInRejectedState(): boolean {
198 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
201 public isRegistered(): boolean {
202 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
205 public isChargingStationAvailable(): boolean {
206 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
209 public isConnectorAvailable(id
: number): boolean {
210 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
213 public getNumberOfConnectors(): number {
214 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
217 public getConnectorStatus(id
: number): ConnectorStatus
{
218 return this.connectors
.get(id
);
221 public getCurrentOutType(): CurrentType
| undefined {
222 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
225 public getOcppStrictCompliance(): boolean {
226 return this.stationInfo
.ocppStrictCompliance
?? false;
229 public getVoltageOut(): number | undefined {
230 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${
232 }, cannot define default voltage out`;
233 let defaultVoltageOut
: number;
234 switch (this.getCurrentOutType()) {
236 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
239 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
242 logger
.error(errMsg
);
243 throw new Error(errMsg
);
245 return !Utils
.isUndefined(this.stationInfo
.voltageOut
)
246 ? this.stationInfo
.voltageOut
250 public getConnectorMaximumAvailablePower(connectorId
: number): number {
251 let connectorAmperageLimitationPowerLimit
: number;
253 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
254 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
256 connectorAmperageLimitationPowerLimit
=
257 (this.getCurrentOutType() === CurrentType
.AC
258 ? ACElectricUtils
.powerTotal(
259 this.getNumberOfPhases(),
260 this.getVoltageOut(),
261 this.getAmperageLimitation() * this.getNumberOfConnectors()
263 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
264 this.stationInfo
.powerDivider
;
266 const connectorMaximumPower
= this.getMaximumPower() / this.stationInfo
.powerDivider
;
267 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
269 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
270 isNaN(connectorAmperageLimitationPowerLimit
)
272 : connectorAmperageLimitationPowerLimit
,
273 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
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
;
285 public getOutOfOrderEndMeterValues(): boolean {
286 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
289 public getBeginEndMeterValues(): boolean {
290 return this.stationInfo
.beginEndMeterValues
?? false;
293 public getMeteringPerTransaction(): boolean {
294 return this.stationInfo
.meteringPerTransaction
?? true;
297 public getTransactionDataMeterValues(): boolean {
298 return this.stationInfo
.transactionDataMeterValues
?? false;
301 public getMainVoltageMeterValues(): boolean {
302 return this.stationInfo
.mainVoltageMeterValues
?? true;
305 public getPhaseLineToLineVoltageMeterValues(): boolean {
306 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
309 public getCustomValueLimitationMeterValues(): boolean {
310 return this.stationInfo
.customValueLimitationMeterValues
?? true;
313 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
314 for (const connectorId
of this.connectors
.keys()) {
317 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
324 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
325 const transactionConnectorStatus
= this.getConnectorStatus(
326 this.getConnectorIdByTransactionId(transactionId
)
328 if (this.getMeteringPerTransaction()) {
329 return transactionConnectorStatus
?.transactionEnergyActiveImportRegisterValue
;
331 return transactionConnectorStatus
?.energyActiveImportRegisterValue
;
334 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
335 const connectorStatus
= this.getConnectorStatus(connectorId
);
336 if (this.getMeteringPerTransaction()) {
337 return connectorStatus
?.transactionEnergyActiveImportRegisterValue
;
339 return connectorStatus
?.energyActiveImportRegisterValue
;
342 public getAuthorizeRemoteTxRequests(): boolean {
343 const authorizeRemoteTxRequests
= this.getConfigurationKey(
344 StandardParametersKey
.AuthorizeRemoteTxRequests
346 return authorizeRemoteTxRequests
347 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
351 public getLocalAuthListEnabled(): boolean {
352 const localAuthListEnabled
= this.getConfigurationKey(
353 StandardParametersKey
.LocalAuthListEnabled
355 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
358 public restartWebSocketPing(): void {
359 // Stop WebSocket ping
360 this.stopWebSocketPing();
361 // Start WebSocket ping
362 this.startWebSocketPing();
365 public getSampledValueTemplate(
367 measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
368 phase
?: MeterValuePhase
369 ): SampledValueTemplate
| undefined {
370 const onPhaseStr
= phase
? `on phase ${phase} ` : '';
371 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
373 `${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
378 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
379 !this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)?.value
.includes(
384 `${this.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
385 StandardParametersKey.MeterValuesSampledData
390 const sampledValueTemplates
: SampledValueTemplate
[] =
391 this.getConnectorStatus(connectorId
).MeterValues
;
394 !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
;
398 !Constants
.SUPPORTED_MEASURANDS
.includes(
399 sampledValueTemplates
[index
]?.measurand
??
400 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
404 `${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
408 sampledValueTemplates
[index
]?.phase
=== phase
&&
409 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
410 this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)?.value
.includes(
414 return sampledValueTemplates
[index
];
417 !sampledValueTemplates
[index
].phase
&&
418 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
419 this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)?.value
.includes(
423 return sampledValueTemplates
[index
];
425 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
426 (!sampledValueTemplates
[index
].measurand
||
427 sampledValueTemplates
[index
].measurand
=== measurand
)
429 return sampledValueTemplates
[index
];
432 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
433 const errorMsg
= `${this.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
434 logger
.error(errorMsg
);
435 throw new Error(errorMsg
);
438 `${this.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
442 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
443 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
446 public startHeartbeat(): void {
448 this.getHeartbeatInterval() &&
449 this.getHeartbeatInterval() > 0 &&
450 !this.heartbeatSetInterval
452 // eslint-disable-next-line @typescript-eslint/no-misused-promises
453 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
454 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
456 RequestCommand
.HEARTBEAT
458 }, this.getHeartbeatInterval());
461 ' Heartbeat started every ' +
462 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
464 } else if (this.heartbeatSetInterval
) {
467 ' Heartbeat already started every ' +
468 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
472 `${this.logPrefix()} Heartbeat interval set to ${
473 this.getHeartbeatInterval()
474 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
475 : this.getHeartbeatInterval()
476 }, not starting the heartbeat`
481 public restartHeartbeat(): void {
483 this.stopHeartbeat();
485 this.startHeartbeat();
488 public startMeterValues(connectorId
: number, interval
: number): void {
489 if (connectorId
=== 0) {
491 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
495 if (!this.getConnectorStatus(connectorId
)) {
497 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
501 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
503 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
507 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
508 !this.getConnectorStatus(connectorId
)?.transactionId
511 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
516 // eslint-disable-next-line @typescript-eslint/no-misused-promises
517 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
518 // eslint-disable-next-line @typescript-eslint/no-misused-promises
519 async (): Promise
<void> => {
520 // FIXME: Implement OCPP version agnostic helpers
521 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
524 this.getConnectorStatus(connectorId
).transactionId
,
527 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
529 RequestCommand
.METER_VALUES
,
532 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
533 meterValue
: [meterValue
],
541 `${this.logPrefix()} Charging station ${
542 StandardParametersKey.MeterValueSampleInterval
543 } configuration set to ${
544 interval ? Utils.formatDurationMilliSeconds(interval) : interval
545 }, not sending MeterValues`
550 public start(): void {
551 if (this.getEnableStatistics()) {
552 this.performanceStatistics
.start();
554 this.openWSConnection();
555 // Handle WebSocket message
556 this.wsConnection
.on(
558 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
560 // Handle WebSocket error
561 this.wsConnection
.on(
563 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
565 // Handle WebSocket close
566 this.wsConnection
.on(
568 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
570 // Handle WebSocket open
571 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
572 // Handle WebSocket ping
573 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
574 // Handle WebSocket pong
575 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
576 // Monitor authorization file
577 FileUtils
.watchJsonFile
<string[]>(
579 FileType
.Authorization
,
580 this.getAuthorizationFile(),
583 // Monitor charging station template file
584 FileUtils
.watchJsonFile(
586 FileType
.ChargingStationTemplate
,
589 (event
, filename
): void => {
590 if (filename
&& event
=== 'change') {
593 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
595 } file have changed, reload`
601 !this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
602 this.automaticTransactionGenerator
604 this.automaticTransactionGenerator
.stop();
606 this.startAutomaticTransactionGenerator();
607 if (this.getEnableStatistics()) {
608 this.performanceStatistics
.restart();
610 this.performanceStatistics
.stop();
612 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
615 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
622 parentPort
.postMessage({
623 id
: ChargingStationWorkerMessageEvents
.STARTED
,
624 data
: { id
: this.stationInfo
.chargingStationId
},
628 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
629 // Stop message sequence
630 await this.stopMessageSequence(reason
);
631 for (const connectorId
of this.connectors
.keys()) {
632 if (connectorId
> 0) {
633 await this.ocppRequestService
.requestHandler
<
634 StatusNotificationRequest
,
635 StatusNotificationResponse
636 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
638 status: ChargePointStatus
.UNAVAILABLE
,
639 errorCode
: ChargePointErrorCode
.NO_ERROR
,
641 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
644 if (this.isWebSocketConnectionOpened()) {
645 this.wsConnection
.close();
647 if (this.getEnableStatistics()) {
648 this.performanceStatistics
.stop();
650 this.bootNotificationResponse
= null;
651 parentPort
.postMessage({
652 id
: ChargingStationWorkerMessageEvents
.STOPPED
,
653 data
: { id
: this.stationInfo
.chargingStationId
},
658 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
659 await this.stop(reason
);
660 await Utils
.sleep(this.stationInfo
.resetTime
);
661 this.stationInfo
= this.getStationInfo();
662 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
666 public getConfigurationKey(
667 key
: string | StandardParametersKey
,
668 caseInsensitive
= false
669 ): ConfigurationKey
| undefined {
670 return this.ocppConfiguration
.configurationKey
.find((configElement
) => {
671 if (caseInsensitive
) {
672 return configElement
.key
.toLowerCase() === key
.toLowerCase();
674 return configElement
.key
=== key
;
678 public addConfigurationKey(
679 key
: string | StandardParametersKey
,
681 options
: { readonly?: boolean; visible
?: boolean; reboot
?: boolean } = {
686 params
: { overwrite
?: boolean; save
?: boolean } = { overwrite
: false, save
: false }
688 options
= options
?? ({} as { readonly?: boolean; visible
?: boolean; reboot
?: boolean });
689 options
.readonly = options
?.readonly ?? false;
690 options
.visible
= options
?.visible
?? true;
691 options
.reboot
= options
?.reboot
?? false;
692 let keyFound
= this.getConfigurationKey(key
);
693 if (keyFound
&& params
?.overwrite
) {
694 this.deleteConfigurationKey(keyFound
.key
, { save
: false });
695 keyFound
= undefined;
698 this.ocppConfiguration
.configurationKey
.push({
700 readonly: options
.readonly,
702 visible
: options
.visible
,
703 reboot
: options
.reboot
,
705 params
?.save
&& this.saveOcppConfiguration();
708 `${this.logPrefix()} Trying to add an already existing configuration key: %j`,
714 public setConfigurationKeyValue(
715 key
: string | StandardParametersKey
,
717 caseInsensitive
= false
719 const keyFound
= this.getConfigurationKey(key
, caseInsensitive
);
721 this.ocppConfiguration
.configurationKey
[
722 this.ocppConfiguration
.configurationKey
.indexOf(keyFound
)
724 this.saveOcppConfiguration();
727 `${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`,
733 public deleteConfigurationKey(
734 key
: string | StandardParametersKey
,
735 params
: { save
?: boolean; caseInsensitive
?: boolean } = { save
: true, caseInsensitive
: false }
736 ): ConfigurationKey
[] {
737 const keyFound
= this.getConfigurationKey(key
, params
?.caseInsensitive
);
739 const deletedConfigurationKey
= this.ocppConfiguration
.configurationKey
.splice(
740 this.ocppConfiguration
.configurationKey
.indexOf(keyFound
),
743 params
?.save
&& this.saveOcppConfiguration();
744 return deletedConfigurationKey
;
748 public getChargingProfilePowerLimit(connectorId
: number): number | undefined {
749 let limit
: number, matchingChargingProfile
: ChargingProfile
;
750 let chargingProfiles
: ChargingProfile
[] = [];
751 // Get charging profiles for connector and sort by stack level
752 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
753 (a
, b
) => b
.stackLevel
- a
.stackLevel
755 // Get profiles on connector 0
756 if (this.getConnectorStatus(0).chargingProfiles
) {
757 chargingProfiles
.push(
758 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
761 if (!Utils
.isEmptyArray(chargingProfiles
)) {
762 const result
= this.getLimitFromChargingProfiles(chargingProfiles
);
763 if (!Utils
.isNullOrUndefined(result
)) {
764 limit
= result
.limit
;
765 matchingChargingProfile
= result
.matchingChargingProfile
;
766 switch (this.getCurrentOutType()) {
769 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
770 ChargingRateUnitType
.WATT
772 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
776 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
777 ChargingRateUnitType
.WATT
779 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
782 const connectorMaximumPower
= this.getMaximumPower() / this.stationInfo
.powerDivider
;
783 if (limit
> connectorMaximumPower
) {
785 `${this.logPrefix()} Charging profile id ${
786 matchingChargingProfile.chargingProfileId
787 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
788 this.getConnectorStatus(connectorId
).chargingProfiles
790 limit
= connectorMaximumPower
;
797 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
798 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
800 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
802 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
804 if (!Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
806 `${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`
808 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
810 let cpReplaced
= false;
811 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
812 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
813 (chargingProfile
: ChargingProfile
, index
: number) => {
815 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
816 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
817 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
819 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
825 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
828 public resetConnectorStatus(connectorId
: number): void {
829 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
830 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
831 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
832 this.getConnectorStatus(connectorId
).transactionStarted
= false;
833 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
834 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
835 delete this.getConnectorStatus(connectorId
).transactionId
;
836 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
837 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
838 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
839 this.stopMeterValues(connectorId
);
842 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
843 return this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)?.value
.includes(
848 public bufferMessage(message
: string): void {
849 this.messageBuffer
.add(message
);
852 private flushMessageBuffer() {
853 if (this.messageBuffer
.size
> 0) {
854 this.messageBuffer
.forEach((message
) => {
855 // TODO: evaluate the need to track performance
856 this.wsConnection
.send(message
);
857 this.messageBuffer
.delete(message
);
862 private getSupervisionUrlOcppConfiguration(): boolean {
863 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
866 private getSupervisionUrlOcppKey(): string {
867 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
870 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
871 // In case of multiple instances: add instance index to charging station id
872 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
873 const idSuffix
= stationTemplate
.nameSuffix
?? '';
874 const idStr
= '000000000' + this.index
.toString();
875 return stationTemplate
.fixedName
876 ? stationTemplate
.baseName
877 : stationTemplate
.baseName
+
879 instanceIndex
.toString() +
880 idStr
.substring(idStr
.length
- 4) +
884 private getRandomSerialNumberSuffix(params
?: {
885 randomBytesLength
?: number;
888 const randomSerialNumberSuffix
= crypto
889 .randomBytes(params
?.randomBytesLength
?? 16)
891 if (params
?.upperCase
) {
892 return randomSerialNumberSuffix
.toUpperCase();
894 return randomSerialNumberSuffix
;
897 private getTemplateFromFile(): ChargingStationTemplate
| null {
898 let template
: ChargingStationTemplate
= null;
900 const measureId
= `${FileType.ChargingStationTemplate} read`;
901 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
903 (JSON
.parse(fs
.readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
) ??
904 ({} as ChargingStationTemplate
);
905 PerformanceStatistics
.endMeasure(measureId
, beginId
);
906 template
.templateHash
= crypto
907 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
908 .update(JSON
.stringify(template
))
911 FileUtils
.handleFileException(
913 FileType
.ChargingStationTemplate
,
915 error
as NodeJS
.ErrnoException
921 private createSerialNumber(
922 stationInfo
: ChargingStationInfo
,
923 existingStationInfo
?: ChargingStationInfo
,
924 params
: { randomSerialNumberUpperCase
?: boolean; randomSerialNumber
?: boolean } = {
925 randomSerialNumberUpperCase
: true,
926 randomSerialNumber
: true,
929 params
= params
?? {};
930 params
.randomSerialNumberUpperCase
= params
?.randomSerialNumberUpperCase
?? true;
931 params
.randomSerialNumber
= params
?.randomSerialNumber
?? true;
932 if (!Utils
.isEmptyObject(existingStationInfo
)) {
933 existingStationInfo
?.chargePointSerialNumber
&&
934 (stationInfo
.chargePointSerialNumber
= existingStationInfo
.chargePointSerialNumber
);
935 existingStationInfo
?.chargeBoxSerialNumber
&&
936 (stationInfo
.chargeBoxSerialNumber
= existingStationInfo
.chargeBoxSerialNumber
);
937 existingStationInfo
?.meterSerialNumber
&&
938 (stationInfo
.meterSerialNumber
= existingStationInfo
.meterSerialNumber
);
940 const serialNumberSuffix
= params
?.randomSerialNumber
941 ? this.getRandomSerialNumberSuffix({ upperCase
: params
.randomSerialNumberUpperCase
})
943 stationInfo
.chargePointSerialNumber
=
944 stationInfo
?.chargePointSerialNumberPrefix
&&
945 stationInfo
.chargePointSerialNumberPrefix
+ serialNumberSuffix
;
946 stationInfo
.chargeBoxSerialNumber
=
947 stationInfo
?.chargeBoxSerialNumberPrefix
&&
948 stationInfo
.chargeBoxSerialNumberPrefix
+ serialNumberSuffix
;
949 stationInfo
.meterSerialNumber
=
950 stationInfo
?.meterSerialNumberPrefix
&&
951 stationInfo
.meterSerialNumberPrefix
+ serialNumberSuffix
;
955 private getStationInfoFromTemplate(): ChargingStationInfo
{
956 const stationInfo
: ChargingStationInfo
= this.getTemplateFromFile();
957 if (Utils
.isNullOrUndefined(stationInfo
)) {
958 const logMsg
= 'Failed to read charging station template file';
959 logger
.error(`${this.logPrefix()} ${logMsg}`);
960 throw new BaseError(logMsg
);
962 if (Utils
.isEmptyObject(stationInfo
)) {
964 `${this.logPrefix()} Empty charging station information from template file ${
969 const chargingStationId
= this.getChargingStationId(stationInfo
);
970 // Deprecation template keys section
971 this.warnDeprecatedTemplateKey(
975 "Use 'supervisionUrls' instead"
977 this.convertDeprecatedTemplateKey(stationInfo
, 'supervisionUrl', 'supervisionUrls');
978 stationInfo
.wsOptions
= stationInfo
?.wsOptions
?? {};
979 if (!Utils
.isEmptyArray(stationInfo
.power
)) {
980 stationInfo
.power
= stationInfo
.power
as number[];
981 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationInfo
.power
.length
);
982 stationInfo
.maximumPower
=
983 stationInfo
.powerUnit
=== PowerUnits
.KILO_WATT
984 ? stationInfo
.power
[powerArrayRandomIndex
] * 1000
985 : stationInfo
.power
[powerArrayRandomIndex
];
987 stationInfo
.power
= stationInfo
.power
as number;
988 stationInfo
.maximumPower
=
989 stationInfo
.powerUnit
=== PowerUnits
.KILO_WATT
990 ? stationInfo
.power
* 1000
993 delete stationInfo
.power
;
994 delete stationInfo
.powerUnit
;
995 stationInfo
.chargingStationId
= chargingStationId
;
996 stationInfo
.resetTime
= stationInfo
.resetTime
997 ? stationInfo
.resetTime
* 1000
998 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
1002 private createStationInfoHash(stationInfo
: ChargingStationInfo
): ChargingStationInfo
{
1003 if (!Utils
.isEmptyObject(stationInfo
)) {
1004 const previousInfoHash
= stationInfo
?.infoHash
?? '';
1005 delete stationInfo
.infoHash
;
1006 const currentInfoHash
= crypto
1007 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1008 .update(JSON
.stringify(stationInfo
))
1011 Utils
.isEmptyString(previousInfoHash
) ||
1012 (!Utils
.isEmptyString(previousInfoHash
) && currentInfoHash
!== previousInfoHash
)
1014 stationInfo
.infoHash
= currentInfoHash
;
1016 stationInfo
.infoHash
= previousInfoHash
;
1022 private getStationInfoFromFile(): ChargingStationInfo
{
1023 let stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? ({} as ChargingStationInfo
);
1024 stationInfo
= this.createStationInfoHash(stationInfo
);
1028 private getStationInfo(): ChargingStationInfo
{
1029 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
1030 this.hashId
= this.getHashId(stationInfoFromTemplate
);
1031 this.configurationFile
= path
.join(
1032 path
.resolve(__dirname
, '../'),
1035 this.hashId
+ '.json'
1037 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
1038 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
1039 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
1040 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
1041 return this.stationInfo
;
1043 return stationInfoFromFile
;
1045 this.createSerialNumber(stationInfoFromTemplate
, stationInfoFromFile
);
1046 return stationInfoFromTemplate
;
1049 private saveStationInfo(): void {
1050 this.saveConfiguration(Section
.stationInfo
);
1053 private getOcppVersion(): OCPPVersion
{
1054 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
1057 private getOcppPersistentConfiguration(): boolean {
1058 return this.stationInfo
.ocppPersistentConfiguration
?? true;
1061 private handleUnsupportedVersion(version
: OCPPVersion
) {
1062 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
1065 logger
.error(errMsg
);
1066 throw new Error(errMsg
);
1069 private createBootNotificationRequest(stationInfo
: ChargingStationInfo
): BootNotificationRequest
{
1071 chargePointModel
: stationInfo
.chargePointModel
,
1072 chargePointVendor
: stationInfo
.chargePointVendor
,
1073 ...(!Utils
.isUndefined(stationInfo
.chargeBoxSerialNumber
) && {
1074 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumber
,
1076 ...(!Utils
.isUndefined(stationInfo
.chargePointSerialNumber
) && {
1077 chargePointSerialNumber
: stationInfo
.chargePointSerialNumber
,
1079 ...(!Utils
.isUndefined(stationInfo
.firmwareVersion
) && {
1080 firmwareVersion
: stationInfo
.firmwareVersion
,
1082 ...(!Utils
.isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
1083 ...(!Utils
.isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
1084 ...(!Utils
.isUndefined(stationInfo
.meterSerialNumber
) && {
1085 meterSerialNumber
: stationInfo
.meterSerialNumber
,
1087 ...(!Utils
.isUndefined(stationInfo
.meterType
) && {
1088 meterType
: stationInfo
.meterType
,
1093 private getHashId(stationInfo
: ChargingStationInfo
): string {
1094 const hashBootNotificationRequest
= {
1095 chargePointModel
: stationInfo
.chargePointModel
,
1096 chargePointVendor
: stationInfo
.chargePointVendor
,
1097 ...(!Utils
.isUndefined(stationInfo
.chargeBoxSerialNumberPrefix
) && {
1098 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumberPrefix
,
1100 ...(!Utils
.isUndefined(stationInfo
.chargePointSerialNumberPrefix
) && {
1101 chargePointSerialNumber
: stationInfo
.chargePointSerialNumberPrefix
,
1103 ...(!Utils
.isUndefined(stationInfo
.firmwareVersion
) && {
1104 firmwareVersion
: stationInfo
.firmwareVersion
,
1106 ...(!Utils
.isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
1107 ...(!Utils
.isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
1108 ...(!Utils
.isUndefined(stationInfo
.meterSerialNumberPrefix
) && {
1109 meterSerialNumber
: stationInfo
.meterSerialNumberPrefix
,
1111 ...(!Utils
.isUndefined(stationInfo
.meterType
) && {
1112 meterType
: stationInfo
.meterType
,
1116 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1117 .update(JSON
.stringify(hashBootNotificationRequest
) + stationInfo
.chargingStationId
)
1121 private initialize(): void {
1122 this.stationInfo
= this.getStationInfo();
1123 logger
.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
1124 this.bootNotificationRequest
= this.createBootNotificationRequest(this.stationInfo
);
1125 this.ocppConfiguration
= this.getOcppConfiguration();
1126 this.stationInfo
?.Configuration
&& delete this.stationInfo
.Configuration
;
1127 this.wsConfiguredConnectionUrl
= new URL(
1128 this.getConfiguredSupervisionUrl().href
+ '/' + this.stationInfo
.chargingStationId
1130 // Build connectors if needed
1131 const maxConnectors
= this.getMaxNumberOfConnectors();
1132 this.checkMaxConnectors(maxConnectors
);
1133 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
1134 this.checkTemplateMaxConnectors(templateMaxConnectors
);
1137 (this.stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
1138 !this.stationInfo
.randomConnectors
1141 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
1143 }, forcing random connector configurations affectation`
1145 this.stationInfo
.randomConnectors
= true;
1147 this.initializeConnectors(this.stationInfo
, maxConnectors
, templateMaxConnectors
);
1148 this.stationInfo
.maximumAmperage
= this.getMaximumAmperage();
1149 this.stationInfo
= this.createStationInfoHash(this.stationInfo
);
1150 this.saveStationInfo();
1151 // Avoid duplication of connectors related information in RAM
1152 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
1153 // OCPP configuration
1154 this.initializeOcppConfiguration();
1155 if (this.getEnableStatistics()) {
1156 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1158 this.stationInfo
.chargingStationId
,
1159 this.wsConnectionUrl
1162 switch (this.getOcppVersion()) {
1163 case OCPPVersion
.VERSION_16
:
1164 this.ocppIncomingRequestService
=
1165 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1166 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1167 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1171 this.handleUnsupportedVersion(this.getOcppVersion());
1174 if (this.stationInfo
.autoRegister
) {
1175 this.bootNotificationResponse
= {
1176 currentTime
: new Date().toISOString(),
1177 interval
: this.getHeartbeatInterval() / 1000,
1178 status: RegistrationStatus
.ACCEPTED
,
1181 this.stationInfo
.powerDivider
= this.getPowerDivider();
1184 private initializeOcppConfiguration(): void {
1185 if (!this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
)) {
1186 this.addConfigurationKey(StandardParametersKey
.HeartbeatInterval
, '0');
1188 if (!this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
)) {
1189 this.addConfigurationKey(StandardParametersKey
.HeartBeatInterval
, '0', { visible
: false });
1192 this.getSupervisionUrlOcppConfiguration() &&
1193 !this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1195 this.addConfigurationKey(
1196 this.getSupervisionUrlOcppKey(),
1197 this.getConfiguredSupervisionUrl().href
,
1201 !this.getSupervisionUrlOcppConfiguration() &&
1202 this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1204 this.deleteConfigurationKey(this.getSupervisionUrlOcppKey(), { save
: false });
1207 this.stationInfo
.amperageLimitationOcppKey
&&
1208 !this.getConfigurationKey(this.stationInfo
.amperageLimitationOcppKey
)
1210 this.addConfigurationKey(
1211 this.stationInfo
.amperageLimitationOcppKey
,
1212 (this.stationInfo
.maximumAmperage
* this.getAmperageLimitationUnitDivider()).toString()
1215 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
1216 this.addConfigurationKey(
1217 StandardParametersKey
.SupportedFeatureProfiles
,
1218 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1221 this.addConfigurationKey(
1222 StandardParametersKey
.NumberOfConnectors
,
1223 this.getNumberOfConnectors().toString(),
1227 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
1228 this.addConfigurationKey(
1229 StandardParametersKey
.MeterValuesSampledData
,
1230 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1233 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
1234 const connectorPhaseRotation
= [];
1235 for (const connectorId
of this.connectors
.keys()) {
1237 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1238 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1239 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1240 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1242 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1243 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1244 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1245 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1248 this.addConfigurationKey(
1249 StandardParametersKey
.ConnectorPhaseRotation
,
1250 connectorPhaseRotation
.toString()
1253 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
1254 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
1257 !this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
) &&
1258 this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)?.value
.includes(
1259 SupportedFeatureProfiles
.LocalAuthListManagement
1262 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
1264 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
1265 this.addConfigurationKey(
1266 StandardParametersKey
.ConnectionTimeOut
,
1267 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1270 this.saveOcppConfiguration();
1273 private initializeConnectors(
1274 stationInfo
: ChargingStationInfo
,
1275 maxConnectors
: number,
1276 templateMaxConnectors
: number
1278 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1279 const logMsg
= `${this.logPrefix()} No already defined connectors and charging station information from template ${
1281 } with no connectors configuration defined`;
1282 logger
.error(logMsg
);
1283 throw new BaseError(logMsg
);
1285 if (!stationInfo
?.Connectors
[0]) {
1287 `${this.logPrefix()} Charging station information from template ${
1289 } with no connector Id 0 configuration`
1292 if (stationInfo
?.Connectors
) {
1293 const connectorsConfigHash
= crypto
1294 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1295 .update(JSON
.stringify(stationInfo
?.Connectors
) + maxConnectors
.toString())
1297 const connectorsConfigChanged
=
1298 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1299 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1300 connectorsConfigChanged
&& this.connectors
.clear();
1301 this.connectorsConfigurationHash
= connectorsConfigHash
;
1302 // Add connector Id 0
1303 let lastConnector
= '0';
1304 for (lastConnector
in stationInfo
?.Connectors
) {
1305 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1307 lastConnectorId
=== 0 &&
1308 this.getUseConnectorId0() &&
1309 stationInfo
?.Connectors
[lastConnector
]
1311 this.connectors
.set(
1313 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1315 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1316 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1317 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1321 // Generate all connectors
1322 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1323 for (let index
= 1; index
<= maxConnectors
; index
++) {
1324 const randConnectorId
= stationInfo
.randomConnectors
1325 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1327 this.connectors
.set(
1329 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1331 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1332 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1333 this.getConnectorStatus(index
).chargingProfiles
= [];
1340 `${this.logPrefix()} Charging station information from template ${
1342 } with no connectors configuration defined, using already defined connectors`
1345 // Initialize transaction attributes on connectors
1346 for (const connectorId
of this.connectors
.keys()) {
1347 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1348 this.initializeConnectorStatus(connectorId
);
1353 private checkMaxConnectors(maxConnectors
: number): void {
1354 if (maxConnectors
<= 0) {
1356 `${this.logPrefix()} Charging station information from template ${
1358 } with ${maxConnectors} connectors`
1363 private checkTemplateMaxConnectors(templateMaxConnectors
: number): void {
1364 if (templateMaxConnectors
=== 0) {
1366 `${this.logPrefix()} Charging station information from template ${
1368 } with empty connectors configuration`
1370 } else if (templateMaxConnectors
< 0) {
1372 `${this.logPrefix()} Charging station information from template ${
1374 } with no connectors configuration defined`
1379 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1380 let configuration
: ChargingStationConfiguration
= null;
1381 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1383 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1384 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1385 configuration
= JSON
.parse(
1386 fs
.readFileSync(this.configurationFile
, 'utf8')
1387 ) as ChargingStationConfiguration
;
1388 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1390 FileUtils
.handleFileException(
1392 FileType
.ChargingStationConfiguration
,
1393 this.configurationFile
,
1394 error
as NodeJS
.ErrnoException
1398 return configuration
;
1401 private saveConfiguration(section
?: Section
): void {
1402 if (this.configurationFile
) {
1404 const configurationData
: ChargingStationConfiguration
=
1405 this.getConfigurationFromFile() ?? {};
1406 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1407 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1410 case Section
.ocppConfiguration
:
1411 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1413 case Section
.stationInfo
:
1414 if (configurationData
?.stationInfo
?.infoHash
=== this.stationInfo
?.infoHash
) {
1416 `${this.logPrefix()} Not saving unchanged charging station information to configuration file ${
1417 this.configurationFile
1422 configurationData
.stationInfo
= this.stationInfo
;
1425 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1426 if (configurationData
?.stationInfo
?.infoHash
!== this.stationInfo
?.infoHash
) {
1427 configurationData
.stationInfo
= this.stationInfo
;
1431 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1432 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1433 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1434 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1435 fs
.closeSync(fileDescriptor
);
1436 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1438 FileUtils
.handleFileException(
1440 FileType
.ChargingStationConfiguration
,
1441 this.configurationFile
,
1442 error
as NodeJS
.ErrnoException
1447 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1452 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
{
1453 return this.getTemplateFromFile().Configuration
?? ({} as ChargingStationOcppConfiguration
);
1456 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1457 let configuration
: ChargingStationConfiguration
= null;
1458 if (this.getOcppPersistentConfiguration()) {
1459 const configurationFromFile
= this.getConfigurationFromFile();
1460 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1462 configuration
&& delete configuration
.stationInfo
;
1463 return configuration
;
1466 private getOcppConfiguration(): ChargingStationOcppConfiguration
{
1467 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1468 if (!ocppConfiguration
) {
1469 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1471 return ocppConfiguration
;
1474 private saveOcppConfiguration(): void {
1475 if (this.getOcppPersistentConfiguration()) {
1476 this.saveConfiguration(Section
.ocppConfiguration
);
1480 private async onOpen(): Promise
<void> {
1481 if (this.isWebSocketConnectionOpened()) {
1483 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1485 if (!this.isRegistered()) {
1486 // Send BootNotification
1487 let registrationRetryCount
= 0;
1489 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1490 BootNotificationRequest
,
1491 BootNotificationResponse
1494 RequestCommand
.BOOT_NOTIFICATION
,
1496 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1497 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1498 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1499 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1500 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1501 iccid
: this.bootNotificationRequest
.iccid
,
1502 imsi
: this.bootNotificationRequest
.imsi
,
1503 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1504 meterType
: this.bootNotificationRequest
.meterType
,
1506 { skipBufferingOnError
: true }
1508 if (!this.isRegistered()) {
1509 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1511 this.bootNotificationResponse
?.interval
1512 ? this.bootNotificationResponse
.interval
* 1000
1513 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1517 !this.isRegistered() &&
1518 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1519 this.getRegistrationMaxRetries() === -1)
1522 if (this.isRegistered()) {
1523 if (this.isInAcceptedState()) {
1524 await this.startMessageSequence();
1525 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1529 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1532 this.stopped
&& (this.stopped
= false);
1533 this.autoReconnectRetryCount
= 0;
1534 this.wsConnectionRestarted
= false;
1537 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1542 private async onClose(code
: number, reason
: string): Promise
<void> {
1545 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1546 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1548 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1550 )}' and reason '${reason}'`
1552 this.autoReconnectRetryCount
= 0;
1557 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1559 )}' and reason '${reason}'`
1561 await this.reconnect(code
);
1566 private async onMessage(data
: Data
): Promise
<void> {
1567 let messageType
: number;
1568 let messageId
: string;
1569 let commandName
: IncomingRequestCommand
;
1570 let commandPayload
: JsonType
;
1571 let errorType
: ErrorType
;
1572 let errorMessage
: string;
1573 let errorDetails
: JsonType
;
1574 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1575 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1576 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1577 let requestPayload
: JsonType
;
1578 let cachedRequest
: CachedRequest
;
1581 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1582 if (Utils
.isIterable(request
)) {
1583 [messageType
, messageId
] = request
;
1584 // Check the type of message
1585 switch (messageType
) {
1587 case MessageType
.CALL_MESSAGE
:
1588 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1589 if (this.getEnableStatistics()) {
1590 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1593 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1597 // Process the message
1598 await this.ocppIncomingRequestService
.incomingRequestHandler(
1606 case MessageType
.CALL_RESULT_MESSAGE
:
1607 [, , commandPayload
] = request
as Response
;
1608 if (!this.requests
.has(messageId
)) {
1610 throw new OCPPError(
1611 ErrorType
.INTERNAL_ERROR
,
1612 `Response for unknown message id ${messageId}`,
1618 cachedRequest
= this.requests
.get(messageId
);
1619 if (Utils
.isIterable(cachedRequest
)) {
1620 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1622 throw new OCPPError(
1623 ErrorType
.PROTOCOL_ERROR
,
1624 `Cached request for message id ${messageId} response is not iterable`,
1626 cachedRequest
as unknown
as JsonType
1630 `${this.logPrefix()} << Command '${
1631 requestCommandName ?? ''
1632 }' received response payload: ${JSON.stringify(request)}`
1634 responseCallback(commandPayload
, requestPayload
);
1637 case MessageType
.CALL_ERROR_MESSAGE
:
1638 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1639 if (!this.requests
.has(messageId
)) {
1641 throw new OCPPError(
1642 ErrorType
.INTERNAL_ERROR
,
1643 `Error response for unknown message id ${messageId}`,
1645 { errorType
, errorMessage
, errorDetails
}
1648 cachedRequest
= this.requests
.get(messageId
);
1649 if (Utils
.isIterable(cachedRequest
)) {
1650 [, errorCallback
, requestCommandName
] = cachedRequest
;
1652 throw new OCPPError(
1653 ErrorType
.PROTOCOL_ERROR
,
1654 `Cached request for message id ${messageId} error response is not iterable`,
1656 cachedRequest
as unknown
as JsonType
1660 `${this.logPrefix()} << Command '${
1661 requestCommandName ?? ''
1662 }' received error payload: ${JSON.stringify(request)}`
1664 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1668 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1669 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
1670 logger
.error(errMsg
);
1671 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1674 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not iterable', null, {
1681 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1684 this.requests
.get(messageId
),
1688 messageType
=== MessageType
.CALL_MESSAGE
&&
1689 (await this.ocppRequestService
.sendError(
1693 commandName
?? requestCommandName
?? null
1698 private onPing(): void {
1699 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1702 private onPong(): void {
1703 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1706 private onError(error
: WSError
): void {
1707 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
1710 private getAuthorizationFile(): string | undefined {
1712 this.stationInfo
.authorizationFile
&&
1714 path
.resolve(__dirname
, '../'),
1716 path
.basename(this.stationInfo
.authorizationFile
)
1721 private getAuthorizedTags(): string[] {
1722 let authorizedTags
: string[] = [];
1723 const authorizationFile
= this.getAuthorizationFile();
1724 if (authorizationFile
) {
1726 // Load authorization file
1727 authorizedTags
= JSON
.parse(fs
.readFileSync(authorizationFile
, 'utf8')) as string[];
1729 FileUtils
.handleFileException(
1731 FileType
.Authorization
,
1733 error
as NodeJS
.ErrnoException
1738 this.logPrefix() + ' No authorization file given in template file ' + this.templateFile
1741 return authorizedTags
;
1744 private getUseConnectorId0(): boolean | undefined {
1745 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
)
1746 ? this.stationInfo
.useConnectorId0
1750 private getNumberOfRunningTransactions(): number {
1752 for (const connectorId
of this.connectors
.keys()) {
1753 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1761 private getConnectionTimeout(): number | undefined {
1762 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
1764 parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ??
1765 Constants
.DEFAULT_CONNECTION_TIMEOUT
1768 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1771 // -1 for unlimited, 0 for disabling
1772 private getAutoReconnectMaxRetries(): number | undefined {
1773 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1774 return this.stationInfo
.autoReconnectMaxRetries
;
1776 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1777 return Configuration
.getAutoReconnectMaxRetries();
1783 private getRegistrationMaxRetries(): number | undefined {
1784 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1785 return this.stationInfo
.registrationMaxRetries
;
1790 private getPowerDivider(): number {
1791 let powerDivider
= this.getNumberOfConnectors();
1792 if (this.stationInfo
.powerSharedByConnectors
) {
1793 powerDivider
= this.getNumberOfRunningTransactions();
1795 return powerDivider
;
1798 private getTemplateMaxNumberOfConnectors(): number {
1799 if (!this.stationInfo
?.Connectors
) {
1802 return Object.keys(this.stationInfo
?.Connectors
).length
;
1805 private getMaxNumberOfConnectors(): number {
1806 let maxConnectors
: number;
1807 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
1808 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
1809 // Distribute evenly the number of connectors
1810 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
1811 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
1812 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
1814 maxConnectors
= this.stationInfo
?.Connectors
[0]
1815 ? this.getTemplateMaxNumberOfConnectors() - 1
1816 : this.getTemplateMaxNumberOfConnectors();
1818 return maxConnectors
;
1821 private getMaximumPower(): number {
1822 return (this.stationInfo
['maxPower'] as number) ?? this.stationInfo
.maximumPower
;
1825 private getMaximumAmperage(): number | undefined {
1826 const maximumPower
= this.getMaximumPower();
1827 switch (this.getCurrentOutType()) {
1828 case CurrentType
.AC
:
1829 return ACElectricUtils
.amperagePerPhaseFromPower(
1830 this.getNumberOfPhases(),
1831 maximumPower
/ this.getNumberOfConnectors(),
1832 this.getVoltageOut()
1834 case CurrentType
.DC
:
1835 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut());
1839 private getAmperageLimitationUnitDivider(): number {
1840 let unitDivider
= 1;
1841 switch (this.stationInfo
.amperageLimitationUnit
) {
1842 case AmpereUnits
.DECI_AMPERE
:
1845 case AmpereUnits
.CENTI_AMPERE
:
1848 case AmpereUnits
.MILLI_AMPERE
:
1855 private getAmperageLimitation(): number | undefined {
1857 this.stationInfo
.amperageLimitationOcppKey
&&
1858 this.getConfigurationKey(this.stationInfo
.amperageLimitationOcppKey
)
1862 this.getConfigurationKey(this.stationInfo
.amperageLimitationOcppKey
).value
1863 ) / this.getAmperageLimitationUnitDivider()
1868 private async startMessageSequence(): Promise
<void> {
1869 if (this.stationInfo
.autoRegister
) {
1870 await this.ocppRequestService
.requestHandler
<
1871 BootNotificationRequest
,
1872 BootNotificationResponse
1875 RequestCommand
.BOOT_NOTIFICATION
,
1877 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1878 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1879 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1880 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1881 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1882 iccid
: this.bootNotificationRequest
.iccid
,
1883 imsi
: this.bootNotificationRequest
.imsi
,
1884 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1885 meterType
: this.bootNotificationRequest
.meterType
,
1887 { skipBufferingOnError
: true }
1890 // Start WebSocket ping
1891 this.startWebSocketPing();
1893 this.startHeartbeat();
1894 // Initialize connectors status
1895 for (const connectorId
of this.connectors
.keys()) {
1896 if (connectorId
=== 0) {
1900 !this.getConnectorStatus(connectorId
)?.status &&
1901 this.getConnectorStatus(connectorId
)?.bootStatus
1903 // Send status in template at startup
1904 await this.ocppRequestService
.requestHandler
<
1905 StatusNotificationRequest
,
1906 StatusNotificationResponse
1907 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1909 status: this.getConnectorStatus(connectorId
).bootStatus
,
1910 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1912 this.getConnectorStatus(connectorId
).status =
1913 this.getConnectorStatus(connectorId
).bootStatus
;
1916 this.getConnectorStatus(connectorId
)?.status &&
1917 this.getConnectorStatus(connectorId
)?.bootStatus
1919 // Send status in template after reset
1920 await this.ocppRequestService
.requestHandler
<
1921 StatusNotificationRequest
,
1922 StatusNotificationResponse
1923 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1925 status: this.getConnectorStatus(connectorId
).bootStatus
,
1926 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1928 this.getConnectorStatus(connectorId
).status =
1929 this.getConnectorStatus(connectorId
).bootStatus
;
1930 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1931 // Send previous status at template reload
1932 await this.ocppRequestService
.requestHandler
<
1933 StatusNotificationRequest
,
1934 StatusNotificationResponse
1935 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1937 status: this.getConnectorStatus(connectorId
).status,
1938 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1941 // Send default status
1942 await this.ocppRequestService
.requestHandler
<
1943 StatusNotificationRequest
,
1944 StatusNotificationResponse
1945 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1947 status: ChargePointStatus
.AVAILABLE
,
1948 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1950 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1954 this.startAutomaticTransactionGenerator();
1957 private startAutomaticTransactionGenerator() {
1958 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
1959 if (!this.automaticTransactionGenerator
) {
1960 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
1962 if (!this.automaticTransactionGenerator
.started
) {
1963 this.automaticTransactionGenerator
.start();
1968 private async stopMessageSequence(
1969 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1971 // Stop WebSocket ping
1972 this.stopWebSocketPing();
1974 this.stopHeartbeat();
1977 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1978 this.automaticTransactionGenerator
?.started
1980 this.automaticTransactionGenerator
.stop();
1982 for (const connectorId
of this.connectors
.keys()) {
1983 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1984 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1986 this.getBeginEndMeterValues() &&
1987 this.getOcppStrictCompliance() &&
1988 !this.getOutOfOrderEndMeterValues()
1990 // FIXME: Implement OCPP version agnostic helpers
1991 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1994 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1996 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
1998 RequestCommand
.METER_VALUES
,
2002 meterValue
: transactionEndMeterValue
,
2006 await this.ocppRequestService
.requestHandler
<
2007 StopTransactionRequest
,
2008 StopTransactionResponse
2009 >(this, RequestCommand
.STOP_TRANSACTION
, {
2011 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
2012 idTag
: this.getTransactionIdTag(transactionId
),
2020 private startWebSocketPing(): void {
2021 const webSocketPingInterval
: number = this.getConfigurationKey(
2022 StandardParametersKey
.WebSocketPingInterval
2024 ? Utils
.convertToInt(
2025 this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
2028 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
2029 this.webSocketPingSetInterval
= setInterval(() => {
2030 if (this.isWebSocketConnectionOpened()) {
2031 this.wsConnection
.ping((): void => {
2032 /* This is intentional */
2035 }, webSocketPingInterval
* 1000);
2038 ' WebSocket ping started every ' +
2039 Utils
.formatDurationSeconds(webSocketPingInterval
)
2041 } else if (this.webSocketPingSetInterval
) {
2044 ' WebSocket ping every ' +
2045 Utils
.formatDurationSeconds(webSocketPingInterval
) +
2050 `${this.logPrefix()} WebSocket ping interval set to ${
2051 webSocketPingInterval
2052 ? Utils.formatDurationSeconds(webSocketPingInterval)
2053 : webSocketPingInterval
2054 }, not starting the WebSocket ping`
2059 private stopWebSocketPing(): void {
2060 if (this.webSocketPingSetInterval
) {
2061 clearInterval(this.webSocketPingSetInterval
);
2065 private warnDeprecatedTemplateKey(
2066 template
: ChargingStationTemplate
,
2068 chargingStationId
: string,
2071 if (!Utils
.isUndefined(template
[key
])) {
2072 const logPrefixStr
= ` ${chargingStationId} |`;
2074 `${Utils.logPrefix(logPrefixStr)} Deprecated template key '${key}' usage in file '${
2076 }'${logMsgToAppend && '. ' + logMsgToAppend}`
2081 private convertDeprecatedTemplateKey(
2082 template
: ChargingStationTemplate
,
2083 deprecatedKey
: string,
2086 if (!Utils
.isUndefined(template
[deprecatedKey
])) {
2087 template
[key
] = template
[deprecatedKey
] as unknown
;
2088 delete template
[deprecatedKey
];
2092 private getConfiguredSupervisionUrl(): URL
{
2093 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
2094 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
2096 if (!Utils
.isEmptyArray(supervisionUrls
)) {
2098 switch (Configuration
.getSupervisionUrlDistribution()) {
2099 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2100 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
2102 case SupervisionUrlDistribution
.RANDOM
:
2104 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
2106 case SupervisionUrlDistribution
.SEQUENTIAL
:
2107 if (this.index
<= supervisionUrls
.length
) {
2108 urlIndex
= this.index
- 1;
2111 `${this.logPrefix()} No more configured supervision urls available, using the first one`
2117 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2118 SupervisionUrlDistribution.ROUND_ROBIN
2121 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
2124 return new URL(supervisionUrls
[urlIndex
]);
2126 return new URL(supervisionUrls
as string);
2129 private getHeartbeatInterval(): number | undefined {
2130 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
2131 if (HeartbeatInterval
) {
2132 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
2134 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
2135 if (HeartBeatInterval
) {
2136 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
2138 !this.stationInfo
.autoRegister
&&
2140 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
2141 Constants.DEFAULT_HEARTBEAT_INTERVAL
2144 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
2147 private stopHeartbeat(): void {
2148 if (this.heartbeatSetInterval
) {
2149 clearInterval(this.heartbeatSetInterval
);
2153 private openWSConnection(
2154 options
: WsOptions
= this.stationInfo
.wsOptions
,
2155 forceCloseOpened
= false
2157 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
2159 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
2160 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
2162 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
2164 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
2165 this.wsConnection
.close();
2167 let protocol
: string;
2168 switch (this.getOcppVersion()) {
2169 case OCPPVersion
.VERSION_16
:
2170 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
2173 this.handleUnsupportedVersion(this.getOcppVersion());
2176 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
2178 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString()
2182 private stopMeterValues(connectorId
: number) {
2183 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
2184 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
2188 private getReconnectExponentialDelay(): boolean | undefined {
2189 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
2190 ? this.stationInfo
.reconnectExponentialDelay
2194 private async reconnect(code
: number): Promise
<void> {
2195 // Stop WebSocket ping
2196 this.stopWebSocketPing();
2198 this.stopHeartbeat();
2199 // Stop the ATG if needed
2201 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
2202 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
2203 this.automaticTransactionGenerator
?.started
2205 this.automaticTransactionGenerator
.stop();
2208 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2209 this.getAutoReconnectMaxRetries() === -1
2211 this.autoReconnectRetryCount
++;
2212 const reconnectDelay
= this.getReconnectExponentialDelay()
2213 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2214 : this.getConnectionTimeout() * 1000;
2215 const reconnectTimeout
= reconnectDelay
- 100 > 0 && reconnectDelay
;
2217 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
2220 )}ms, timeout ${reconnectTimeout}ms`
2222 await Utils
.sleep(reconnectDelay
);
2225 ' WebSocket: reconnecting try #' +
2226 this.autoReconnectRetryCount
.toString()
2228 this.openWSConnection(
2229 { ...this.stationInfo
.wsOptions
, handshakeTimeout
: reconnectTimeout
},
2232 this.wsConnectionRestarted
= true;
2233 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2235 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2236 this.autoReconnectRetryCount
2237 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2242 private initializeConnectorStatus(connectorId
: number): void {
2243 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2244 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2245 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2246 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2247 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2248 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
2252 * Charging profiles should already be sorted by connectorId and stack level (highest stack level has priority)
2254 * @param {ChargingProfile[]} chargingProfiles
2255 * @returns {{ limit, matchingChargingProfile }}
2257 private getLimitFromChargingProfiles(chargingProfiles
: ChargingProfile
[]): {
2259 matchingChargingProfile
: ChargingProfile
;
2261 for (const chargingProfile
of chargingProfiles
) {
2263 const currentMoment
= moment();
2264 const chargingSchedule
= chargingProfile
.chargingSchedule
;
2265 // Check type (recurring) and if it is already active
2266 // Adjust the daily recurring schedule to today
2268 chargingProfile
.chargingProfileKind
=== ChargingProfileKindType
.RECURRING
&&
2269 chargingProfile
.recurrencyKind
=== RecurrencyKindType
.DAILY
&&
2270 currentMoment
.isAfter(chargingSchedule
.startSchedule
)
2272 const currentDate
= new Date();
2273 chargingSchedule
.startSchedule
= new Date(chargingSchedule
.startSchedule
);
2274 chargingSchedule
.startSchedule
.setFullYear(
2275 currentDate
.getFullYear(),
2276 currentDate
.getMonth(),
2277 currentDate
.getDate()
2279 // Check if the start of the schedule is yesterday
2280 if (moment(chargingSchedule
.startSchedule
).isAfter(currentMoment
)) {
2281 chargingSchedule
.startSchedule
.setDate(currentDate
.getDate() - 1);
2283 } else if (moment(chargingSchedule
.startSchedule
).isAfter(currentMoment
)) {
2286 // Check if the charging profile is active
2288 moment(chargingSchedule
.startSchedule
)
2289 .add(chargingSchedule
.duration
, 's')
2290 .isAfter(currentMoment
)
2292 let lastButOneSchedule
: ChargingSchedulePeriod
;
2293 // Search the right schedule period
2294 for (const schedulePeriod
of chargingSchedule
.chargingSchedulePeriod
) {
2295 // Handling of only one period
2297 chargingSchedule
.chargingSchedulePeriod
.length
=== 1 &&
2298 schedulePeriod
.startPeriod
=== 0
2301 limit
: schedulePeriod
.limit
,
2302 matchingChargingProfile
: chargingProfile
,
2305 `${this.logPrefix()} Matching charging profile found for power limitation: %j`,
2310 // Find the right schedule period
2312 moment(chargingSchedule
.startSchedule
)
2313 .add(schedulePeriod
.startPeriod
, 's')
2314 .isAfter(currentMoment
)
2316 // Found the schedule: last but one is the correct one
2318 limit
: lastButOneSchedule
.limit
,
2319 matchingChargingProfile
: chargingProfile
,
2322 `${this.logPrefix()} Matching charging profile found for power limitation: %j`,
2328 lastButOneSchedule
= schedulePeriod
;
2329 // Handle the last schedule period
2331 schedulePeriod
.startPeriod
===
2332 chargingSchedule
.chargingSchedulePeriod
[
2333 chargingSchedule
.chargingSchedulePeriod
.length
- 1
2337 limit
: lastButOneSchedule
.limit
,
2338 matchingChargingProfile
: chargingProfile
,
2341 `${this.logPrefix()} Matching charging profile found for power limitation: %j`,