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 getConnectorIdByTransactionId(transactionId
: number): number | undefined {
310 for (const connectorId
of this.connectors
.keys()) {
313 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
320 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
321 const transactionConnectorStatus
= this.getConnectorStatus(
322 this.getConnectorIdByTransactionId(transactionId
)
324 if (this.getMeteringPerTransaction()) {
325 return transactionConnectorStatus
?.transactionEnergyActiveImportRegisterValue
;
327 return transactionConnectorStatus
?.energyActiveImportRegisterValue
;
330 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
331 const connectorStatus
= this.getConnectorStatus(connectorId
);
332 if (this.getMeteringPerTransaction()) {
333 return connectorStatus
?.transactionEnergyActiveImportRegisterValue
;
335 return connectorStatus
?.energyActiveImportRegisterValue
;
338 public getAuthorizeRemoteTxRequests(): boolean {
339 const authorizeRemoteTxRequests
= this.getConfigurationKey(
340 StandardParametersKey
.AuthorizeRemoteTxRequests
342 return authorizeRemoteTxRequests
343 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
347 public getLocalAuthListEnabled(): boolean {
348 const localAuthListEnabled
= this.getConfigurationKey(
349 StandardParametersKey
.LocalAuthListEnabled
351 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
354 public restartWebSocketPing(): void {
355 // Stop WebSocket ping
356 this.stopWebSocketPing();
357 // Start WebSocket ping
358 this.startWebSocketPing();
361 public getSampledValueTemplate(
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
)) {
369 `${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
374 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
375 !this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)?.value
.includes(
380 `${this.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
381 StandardParametersKey.MeterValuesSampledData
386 const sampledValueTemplates
: SampledValueTemplate
[] =
387 this.getConnectorStatus(connectorId
).MeterValues
;
390 !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
;
394 !Constants
.SUPPORTED_MEASURANDS
.includes(
395 sampledValueTemplates
[index
]?.measurand
??
396 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
400 `${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
404 sampledValueTemplates
[index
]?.phase
=== phase
&&
405 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
406 this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)?.value
.includes(
410 return sampledValueTemplates
[index
];
413 !sampledValueTemplates
[index
].phase
&&
414 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
415 this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)?.value
.includes(
419 return sampledValueTemplates
[index
];
421 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
422 (!sampledValueTemplates
[index
].measurand
||
423 sampledValueTemplates
[index
].measurand
=== measurand
)
425 return sampledValueTemplates
[index
];
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
);
434 `${this.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
438 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
439 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
442 public startHeartbeat(): void {
444 this.getHeartbeatInterval() &&
445 this.getHeartbeatInterval() > 0 &&
446 !this.heartbeatSetInterval
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
453 }, this.getHeartbeatInterval());
456 ' Heartbeat started every ' +
457 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
459 } else if (this.heartbeatSetInterval
) {
462 ' Heartbeat already started every ' +
463 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
467 `${this.logPrefix()} Heartbeat interval set to ${
468 this.getHeartbeatInterval()
469 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
470 : this.getHeartbeatInterval()
471 }, not starting the heartbeat`
476 public restartHeartbeat(): void {
478 this.stopHeartbeat();
480 this.startHeartbeat();
483 public startMeterValues(connectorId
: number, interval
: number): void {
484 if (connectorId
=== 0) {
486 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
490 if (!this.getConnectorStatus(connectorId
)) {
492 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
496 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
498 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
502 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
503 !this.getConnectorStatus(connectorId
)?.transactionId
506 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
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(
519 this.getConnectorStatus(connectorId
).transactionId
,
522 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
523 RequestCommand
.METER_VALUES
,
526 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
527 meterValue
: [meterValue
],
535 `${this.logPrefix()} Charging station ${
536 StandardParametersKey.MeterValueSampleInterval
537 } configuration set to ${
538 interval ? Utils.formatDurationMilliSeconds(interval) : interval
539 }, not sending MeterValues`
544 public start(): void {
545 if (this.getEnableStatistics()) {
546 this.performanceStatistics
.start();
548 this.openWSConnection();
549 // Handle WebSocket message
550 this.wsConnection
.on(
552 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
554 // Handle WebSocket error
555 this.wsConnection
.on(
557 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
559 // Handle WebSocket close
560 this.wsConnection
.on(
562 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
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[]>(
573 FileType
.Authorization
,
574 this.getAuthorizationFile(),
577 // Monitor charging station template file
578 FileUtils
.watchJsonFile(
580 FileType
.ChargingStationTemplate
,
583 (event
, filename
): void => {
584 if (filename
&& event
=== 'change') {
587 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
589 } file have changed, reload`
595 !this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
596 this.automaticTransactionGenerator
598 this.automaticTransactionGenerator
.stop();
600 this.startAutomaticTransactionGenerator();
601 if (this.getEnableStatistics()) {
602 this.performanceStatistics
.restart();
604 this.performanceStatistics
.stop();
606 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
609 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
616 parentPort
.postMessage({
617 id
: ChargingStationWorkerMessageEvents
.STARTED
,
618 data
: { id
: this.stationInfo
.chargingStationId
},
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
, {
632 status: ChargePointStatus
.UNAVAILABLE
,
633 errorCode
: ChargePointErrorCode
.NO_ERROR
,
635 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
638 if (this.isWebSocketConnectionOpened()) {
639 this.wsConnection
.close();
641 if (this.getEnableStatistics()) {
642 this.performanceStatistics
.stop();
644 this.bootNotificationResponse
= null;
645 parentPort
.postMessage({
646 id
: ChargingStationWorkerMessageEvents
.STOPPED
,
647 data
: { id
: this.stationInfo
.chargingStationId
},
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
;
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();
668 return configElement
.key
=== key
;
672 public addConfigurationKey(
673 key
: string | StandardParametersKey
,
675 options
: { readonly?: boolean; visible
?: boolean; reboot
?: boolean } = {
680 params
: { overwrite
?: boolean; save
?: boolean } = { overwrite
: false, save
: false }
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;
692 this.ocppConfiguration
.configurationKey
.push({
694 readonly: options
.readonly,
696 visible
: options
.visible
,
697 reboot
: options
.reboot
,
699 params
?.save
&& this.saveOcppConfiguration();
702 `${this.logPrefix()} Trying to add an already existing configuration key: %j`,
708 public setConfigurationKeyValue(
709 key
: string | StandardParametersKey
,
711 caseInsensitive
= false
713 const keyFound
= this.getConfigurationKey(key
, caseInsensitive
);
715 this.ocppConfiguration
.configurationKey
[
716 this.ocppConfiguration
.configurationKey
.indexOf(keyFound
)
718 this.saveOcppConfiguration();
721 `${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`,
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
);
733 const deletedConfigurationKey
= this.ocppConfiguration
.configurationKey
.splice(
734 this.ocppConfiguration
.configurationKey
.indexOf(keyFound
),
737 params
?.save
&& this.saveOcppConfiguration();
738 return deletedConfigurationKey
;
742 public getChargingProfilePowerLimit(connectorId
: number): number | undefined {
744 let matchingChargingProfile
: ChargingProfile
;
745 let chargingProfiles
: ChargingProfile
[] = [];
746 // Get profiles for connector and sort by stack level
747 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
748 (a
, b
) => b
.stackLevel
- a
.stackLevel
750 // Get profiles on connector 0
751 if (this.getConnectorStatus(0).chargingProfiles
) {
752 chargingProfiles
.push(
753 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
756 if (!Utils
.isEmptyArray(chargingProfiles
)) {
757 const result
= this.getCurrentLimitFromOCPPProfiles(chargingProfiles
);
758 if (!Utils
.isNullOrUndefined(result
)) {
759 limit
= result
.limit
;
760 matchingChargingProfile
= result
.matchingChargingProfile
;
761 switch (this.getCurrentOutType()) {
764 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
765 ChargingRateUnitType
.WATT
767 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
771 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
772 ChargingRateUnitType
.WATT
774 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
777 const connectorMaximumPower
= this.getMaximumPower() / this.stationInfo
.powerDivider
;
778 if (limit
> connectorMaximumPower
) {
780 `${this.logPrefix()} Charging profile id ${
781 matchingChargingProfile.chargingProfileId
782 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
783 this.getConnectorStatus(connectorId
).chargingProfiles
785 limit
= connectorMaximumPower
;
792 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
793 // Add support for connectorID 0
794 if (!Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
795 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
797 let cpReplaced
= false;
798 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
799 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
800 (chargingProfile
: ChargingProfile
, index
: number) => {
802 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
803 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
804 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
806 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
812 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
815 public resetConnectorStatus(connectorId
: number): void {
816 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
817 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
818 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
819 this.getConnectorStatus(connectorId
).transactionStarted
= false;
820 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
821 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
822 delete this.getConnectorStatus(connectorId
).transactionId
;
823 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
824 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
825 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
826 this.stopMeterValues(connectorId
);
829 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
830 return this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)?.value
.includes(
835 public bufferMessage(message
: string): void {
836 this.messageBuffer
.add(message
);
839 private flushMessageBuffer() {
840 if (this.messageBuffer
.size
> 0) {
841 this.messageBuffer
.forEach((message
) => {
842 // TODO: evaluate the need to track performance
843 this.wsConnection
.send(message
);
844 this.messageBuffer
.delete(message
);
849 private getSupervisionUrlOcppConfiguration(): boolean {
850 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
853 private getSupervisionUrlOcppKey(): string {
854 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
857 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
858 // In case of multiple instances: add instance index to charging station id
859 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
860 const idSuffix
= stationTemplate
.nameSuffix
?? '';
861 const idStr
= '000000000' + this.index
.toString();
862 return stationTemplate
.fixedName
863 ? stationTemplate
.baseName
864 : stationTemplate
.baseName
+
866 instanceIndex
.toString() +
867 idStr
.substring(idStr
.length
- 4) +
871 private getRandomSerialNumberSuffix(params
?: {
872 randomBytesLength
?: number;
875 const randomSerialNumberSuffix
= crypto
876 .randomBytes(params
?.randomBytesLength
?? 16)
878 if (params
?.upperCase
) {
879 return randomSerialNumberSuffix
.toUpperCase();
881 return randomSerialNumberSuffix
;
884 private getTemplateFromFile(): ChargingStationTemplate
| null {
885 let template
: ChargingStationTemplate
= null;
887 const measureId
= `${FileType.ChargingStationTemplate} read`;
888 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
890 (JSON
.parse(fs
.readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
) ??
891 ({} as ChargingStationTemplate
);
892 PerformanceStatistics
.endMeasure(measureId
, beginId
);
893 template
.templateHash
= crypto
894 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
895 .update(JSON
.stringify(template
))
898 FileUtils
.handleFileException(
900 FileType
.ChargingStationTemplate
,
902 error
as NodeJS
.ErrnoException
908 private createSerialNumber(
909 stationInfo
: ChargingStationInfo
,
910 existingStationInfo
?: ChargingStationInfo
,
911 params
: { randomSerialNumberUpperCase
?: boolean; randomSerialNumber
?: boolean } = {
912 randomSerialNumberUpperCase
: true,
913 randomSerialNumber
: true,
916 params
= params
?? {};
917 params
.randomSerialNumberUpperCase
= params
?.randomSerialNumberUpperCase
?? true;
918 params
.randomSerialNumber
= params
?.randomSerialNumber
?? true;
919 if (!Utils
.isEmptyObject(existingStationInfo
)) {
920 existingStationInfo
?.chargePointSerialNumber
&&
921 (stationInfo
.chargePointSerialNumber
= existingStationInfo
.chargePointSerialNumber
);
922 existingStationInfo
?.chargeBoxSerialNumber
&&
923 (stationInfo
.chargeBoxSerialNumber
= existingStationInfo
.chargeBoxSerialNumber
);
924 existingStationInfo
?.meterSerialNumber
&&
925 (stationInfo
.meterSerialNumber
= existingStationInfo
.meterSerialNumber
);
927 const serialNumberSuffix
= params
?.randomSerialNumber
928 ? this.getRandomSerialNumberSuffix({ upperCase
: params
.randomSerialNumberUpperCase
})
930 stationInfo
.chargePointSerialNumber
=
931 stationInfo
?.chargePointSerialNumberPrefix
&&
932 stationInfo
.chargePointSerialNumberPrefix
+ serialNumberSuffix
;
933 stationInfo
.chargeBoxSerialNumber
=
934 stationInfo
?.chargeBoxSerialNumberPrefix
&&
935 stationInfo
.chargeBoxSerialNumberPrefix
+ serialNumberSuffix
;
936 stationInfo
.meterSerialNumber
=
937 stationInfo
?.meterSerialNumberPrefix
&&
938 stationInfo
.meterSerialNumberPrefix
+ serialNumberSuffix
;
942 private getStationInfoFromTemplate(): ChargingStationInfo
{
943 const stationInfo
: ChargingStationInfo
= this.getTemplateFromFile();
944 if (Utils
.isNullOrUndefined(stationInfo
)) {
945 const logMsg
= 'Failed to read charging station template file';
946 logger
.error(`${this.logPrefix()} ${logMsg}`);
947 throw new BaseError(logMsg
);
949 if (Utils
.isEmptyObject(stationInfo
)) {
951 `${this.logPrefix()} Empty charging station information from template file ${
956 const chargingStationId
= this.getChargingStationId(stationInfo
);
957 // Deprecation template keys section
958 this.warnDeprecatedTemplateKey(
962 "Use 'supervisionUrls' instead"
964 this.convertDeprecatedTemplateKey(stationInfo
, 'supervisionUrl', 'supervisionUrls');
965 stationInfo
.wsOptions
= stationInfo
?.wsOptions
?? {};
966 if (!Utils
.isEmptyArray(stationInfo
.power
)) {
967 stationInfo
.power
= stationInfo
.power
as number[];
968 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationInfo
.power
.length
);
969 stationInfo
.maximumPower
=
970 stationInfo
.powerUnit
=== PowerUnits
.KILO_WATT
971 ? stationInfo
.power
[powerArrayRandomIndex
] * 1000
972 : stationInfo
.power
[powerArrayRandomIndex
];
974 stationInfo
.power
= stationInfo
.power
as number;
975 stationInfo
.maximumPower
=
976 stationInfo
.powerUnit
=== PowerUnits
.KILO_WATT
977 ? stationInfo
.power
* 1000
980 delete stationInfo
.power
;
981 delete stationInfo
.powerUnit
;
982 stationInfo
.chargingStationId
= chargingStationId
;
983 stationInfo
.resetTime
= stationInfo
.resetTime
984 ? stationInfo
.resetTime
* 1000
985 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
989 private createStationInfoHash(stationInfo
: ChargingStationInfo
): ChargingStationInfo
{
990 if (!Utils
.isEmptyObject(stationInfo
)) {
991 const previousInfoHash
= stationInfo
?.infoHash
?? '';
992 delete stationInfo
.infoHash
;
993 const currentInfoHash
= crypto
994 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
995 .update(JSON
.stringify(stationInfo
))
998 Utils
.isEmptyString(previousInfoHash
) ||
999 (!Utils
.isEmptyString(previousInfoHash
) && currentInfoHash
!== previousInfoHash
)
1001 stationInfo
.infoHash
= currentInfoHash
;
1003 stationInfo
.infoHash
= previousInfoHash
;
1009 private getStationInfoFromFile(): ChargingStationInfo
{
1010 let stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? ({} as ChargingStationInfo
);
1011 stationInfo
= this.createStationInfoHash(stationInfo
);
1015 private getStationInfo(): ChargingStationInfo
{
1016 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
1017 this.hashId
= this.getHashId(stationInfoFromTemplate
);
1018 this.configurationFile
= path
.join(
1019 path
.resolve(__dirname
, '../'),
1022 this.hashId
+ '.json'
1024 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
1025 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
1026 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
1027 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
1028 return this.stationInfo
;
1030 return stationInfoFromFile
;
1032 this.createSerialNumber(stationInfoFromTemplate
, stationInfoFromFile
);
1033 return stationInfoFromTemplate
;
1036 private saveStationInfo(): void {
1037 this.saveConfiguration(Section
.stationInfo
);
1040 private getOcppVersion(): OCPPVersion
{
1041 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
1044 private getOcppPersistentConfiguration(): boolean {
1045 return this.stationInfo
.ocppPersistentConfiguration
?? true;
1048 private handleUnsupportedVersion(version
: OCPPVersion
) {
1049 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
1052 logger
.error(errMsg
);
1053 throw new Error(errMsg
);
1056 private createBootNotificationRequest(stationInfo
: ChargingStationInfo
): BootNotificationRequest
{
1058 chargePointModel
: stationInfo
.chargePointModel
,
1059 chargePointVendor
: stationInfo
.chargePointVendor
,
1060 ...(!Utils
.isUndefined(stationInfo
.chargeBoxSerialNumber
) && {
1061 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumber
,
1063 ...(!Utils
.isUndefined(stationInfo
.chargePointSerialNumber
) && {
1064 chargePointSerialNumber
: stationInfo
.chargePointSerialNumber
,
1066 ...(!Utils
.isUndefined(stationInfo
.firmwareVersion
) && {
1067 firmwareVersion
: stationInfo
.firmwareVersion
,
1069 ...(!Utils
.isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
1070 ...(!Utils
.isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
1071 ...(!Utils
.isUndefined(stationInfo
.meterSerialNumber
) && {
1072 meterSerialNumber
: stationInfo
.meterSerialNumber
,
1074 ...(!Utils
.isUndefined(stationInfo
.meterType
) && {
1075 meterType
: stationInfo
.meterType
,
1080 private getHashId(stationInfo
: ChargingStationInfo
): string {
1081 const hashBootNotificationRequest
= {
1082 chargePointModel
: stationInfo
.chargePointModel
,
1083 chargePointVendor
: stationInfo
.chargePointVendor
,
1084 ...(!Utils
.isUndefined(stationInfo
.chargeBoxSerialNumberPrefix
) && {
1085 chargeBoxSerialNumber
: stationInfo
.chargeBoxSerialNumberPrefix
,
1087 ...(!Utils
.isUndefined(stationInfo
.chargePointSerialNumberPrefix
) && {
1088 chargePointSerialNumber
: stationInfo
.chargePointSerialNumberPrefix
,
1090 ...(!Utils
.isUndefined(stationInfo
.firmwareVersion
) && {
1091 firmwareVersion
: stationInfo
.firmwareVersion
,
1093 ...(!Utils
.isUndefined(stationInfo
.iccid
) && { iccid
: stationInfo
.iccid
}),
1094 ...(!Utils
.isUndefined(stationInfo
.imsi
) && { imsi
: stationInfo
.imsi
}),
1095 ...(!Utils
.isUndefined(stationInfo
.meterSerialNumberPrefix
) && {
1096 meterSerialNumber
: stationInfo
.meterSerialNumberPrefix
,
1098 ...(!Utils
.isUndefined(stationInfo
.meterType
) && {
1099 meterType
: stationInfo
.meterType
,
1103 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1104 .update(JSON
.stringify(hashBootNotificationRequest
) + stationInfo
.chargingStationId
)
1108 private initialize(): void {
1109 this.stationInfo
= this.getStationInfo();
1110 logger
.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
1111 this.bootNotificationRequest
= this.createBootNotificationRequest(this.stationInfo
);
1112 this.ocppConfiguration
= this.getOcppConfiguration();
1113 this.stationInfo
?.Configuration
&& delete this.stationInfo
.Configuration
;
1114 this.wsConfiguredConnectionUrl
= new URL(
1115 this.getConfiguredSupervisionUrl().href
+ '/' + this.stationInfo
.chargingStationId
1117 // Build connectors if needed
1118 const maxConnectors
= this.getMaxNumberOfConnectors();
1119 this.checkMaxConnectors(maxConnectors
);
1120 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
1121 this.checkTemplateMaxConnectors(templateMaxConnectors
);
1124 (this.stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
1125 !this.stationInfo
.randomConnectors
1128 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
1130 }, forcing random connector configurations affectation`
1132 this.stationInfo
.randomConnectors
= true;
1134 this.initializeConnectors(this.stationInfo
, maxConnectors
, templateMaxConnectors
);
1135 this.stationInfo
.maximumAmperage
= this.getMaximumAmperage();
1136 this.stationInfo
= this.createStationInfoHash(this.stationInfo
);
1137 this.saveStationInfo();
1138 // Avoid duplication of connectors related information in RAM
1139 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
1140 // OCPP configuration
1141 this.initializeOcppConfiguration();
1142 if (this.getEnableStatistics()) {
1143 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1145 this.stationInfo
.chargingStationId
,
1146 this.wsConnectionUrl
1149 switch (this.getOcppVersion()) {
1150 case OCPPVersion
.VERSION_16
:
1151 this.ocppIncomingRequestService
=
1152 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>(this);
1153 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1155 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>(this)
1159 this.handleUnsupportedVersion(this.getOcppVersion());
1162 if (this.stationInfo
.autoRegister
) {
1163 this.bootNotificationResponse
= {
1164 currentTime
: new Date().toISOString(),
1165 interval
: this.getHeartbeatInterval() / 1000,
1166 status: RegistrationStatus
.ACCEPTED
,
1169 this.stationInfo
.powerDivider
= this.getPowerDivider();
1172 private initializeOcppConfiguration(): void {
1173 if (!this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
)) {
1174 this.addConfigurationKey(StandardParametersKey
.HeartbeatInterval
, '0');
1176 if (!this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
)) {
1177 this.addConfigurationKey(StandardParametersKey
.HeartBeatInterval
, '0', { visible
: false });
1180 this.getSupervisionUrlOcppConfiguration() &&
1181 !this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1183 this.addConfigurationKey(
1184 this.getSupervisionUrlOcppKey(),
1185 this.getConfiguredSupervisionUrl().href
,
1189 !this.getSupervisionUrlOcppConfiguration() &&
1190 this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1192 this.deleteConfigurationKey(this.getSupervisionUrlOcppKey(), { save
: false });
1195 this.stationInfo
.amperageLimitationOcppKey
&&
1196 !this.getConfigurationKey(this.stationInfo
.amperageLimitationOcppKey
)
1198 this.addConfigurationKey(
1199 this.stationInfo
.amperageLimitationOcppKey
,
1200 (this.stationInfo
.maximumAmperage
* this.getAmperageLimitationUnitDivider()).toString()
1203 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
1204 this.addConfigurationKey(
1205 StandardParametersKey
.SupportedFeatureProfiles
,
1206 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1209 this.addConfigurationKey(
1210 StandardParametersKey
.NumberOfConnectors
,
1211 this.getNumberOfConnectors().toString(),
1215 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
1216 this.addConfigurationKey(
1217 StandardParametersKey
.MeterValuesSampledData
,
1218 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1221 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
1222 const connectorPhaseRotation
= [];
1223 for (const connectorId
of this.connectors
.keys()) {
1225 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1226 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1227 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1228 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1230 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1231 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1232 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1233 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1236 this.addConfigurationKey(
1237 StandardParametersKey
.ConnectorPhaseRotation
,
1238 connectorPhaseRotation
.toString()
1241 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
1242 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
1245 !this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
) &&
1246 this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)?.value
.includes(
1247 SupportedFeatureProfiles
.LocalAuthListManagement
1250 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
1252 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
1253 this.addConfigurationKey(
1254 StandardParametersKey
.ConnectionTimeOut
,
1255 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1258 this.saveOcppConfiguration();
1261 private initializeConnectors(
1262 stationInfo
: ChargingStationInfo
,
1263 maxConnectors
: number,
1264 templateMaxConnectors
: number
1266 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1267 const logMsg
= `${this.logPrefix()} No already defined connectors and charging station information from template ${
1269 } with no connectors configuration defined`;
1270 logger
.error(logMsg
);
1271 throw new BaseError(logMsg
);
1273 if (!stationInfo
?.Connectors
[0]) {
1275 `${this.logPrefix()} Charging station information from template ${
1277 } with no connector Id 0 configuration`
1280 if (stationInfo
?.Connectors
) {
1281 const connectorsConfigHash
= crypto
1282 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1283 .update(JSON
.stringify(stationInfo
?.Connectors
) + maxConnectors
.toString())
1285 const connectorsConfigChanged
=
1286 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1287 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1288 connectorsConfigChanged
&& this.connectors
.clear();
1289 this.connectorsConfigurationHash
= connectorsConfigHash
;
1290 // Add connector Id 0
1291 let lastConnector
= '0';
1292 for (lastConnector
in stationInfo
?.Connectors
) {
1293 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1295 lastConnectorId
=== 0 &&
1296 this.getUseConnectorId0() &&
1297 stationInfo
?.Connectors
[lastConnector
]
1299 this.connectors
.set(
1301 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1303 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1304 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1305 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1309 // Generate all connectors
1310 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1311 for (let index
= 1; index
<= maxConnectors
; index
++) {
1312 const randConnectorId
= stationInfo
.randomConnectors
1313 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1315 this.connectors
.set(
1317 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1319 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1320 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1321 this.getConnectorStatus(index
).chargingProfiles
= [];
1328 `${this.logPrefix()} Charging station information from template ${
1330 } with no connectors configuration defined, using already defined connectors`
1333 // Initialize transaction attributes on connectors
1334 for (const connectorId
of this.connectors
.keys()) {
1335 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1336 this.initializeConnectorStatus(connectorId
);
1341 private checkMaxConnectors(maxConnectors
: number): void {
1342 if (maxConnectors
<= 0) {
1344 `${this.logPrefix()} Charging station information from template ${
1346 } with ${maxConnectors} connectors`
1351 private checkTemplateMaxConnectors(templateMaxConnectors
: number): void {
1352 if (templateMaxConnectors
=== 0) {
1354 `${this.logPrefix()} Charging station information from template ${
1356 } with empty connectors configuration`
1358 } else if (templateMaxConnectors
< 0) {
1360 `${this.logPrefix()} Charging station information from template ${
1362 } with no connectors configuration defined`
1367 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1368 let configuration
: ChargingStationConfiguration
= null;
1369 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1371 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1372 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1373 configuration
= JSON
.parse(
1374 fs
.readFileSync(this.configurationFile
, 'utf8')
1375 ) as ChargingStationConfiguration
;
1376 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1378 FileUtils
.handleFileException(
1380 FileType
.ChargingStationConfiguration
,
1381 this.configurationFile
,
1382 error
as NodeJS
.ErrnoException
1386 return configuration
;
1389 private saveConfiguration(section
?: Section
): void {
1390 if (this.configurationFile
) {
1392 const configurationData
: ChargingStationConfiguration
=
1393 this.getConfigurationFromFile() ?? {};
1394 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1395 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1398 case Section
.ocppConfiguration
:
1399 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1401 case Section
.stationInfo
:
1402 if (configurationData
?.stationInfo
?.infoHash
=== this.stationInfo
?.infoHash
) {
1404 `${this.logPrefix()} Not saving unchanged charging station information to configuration file ${
1405 this.configurationFile
1410 configurationData
.stationInfo
= this.stationInfo
;
1413 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1414 if (configurationData
?.stationInfo
?.infoHash
!== this.stationInfo
?.infoHash
) {
1415 configurationData
.stationInfo
= this.stationInfo
;
1419 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1420 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1421 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1422 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1423 fs
.closeSync(fileDescriptor
);
1424 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1426 FileUtils
.handleFileException(
1428 FileType
.ChargingStationConfiguration
,
1429 this.configurationFile
,
1430 error
as NodeJS
.ErrnoException
1435 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1440 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
{
1441 return this.getTemplateFromFile().Configuration
?? ({} as ChargingStationOcppConfiguration
);
1444 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1445 let configuration
: ChargingStationConfiguration
= null;
1446 if (this.getOcppPersistentConfiguration()) {
1447 const configurationFromFile
= this.getConfigurationFromFile();
1448 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1450 configuration
&& delete configuration
.stationInfo
;
1451 return configuration
;
1454 private getOcppConfiguration(): ChargingStationOcppConfiguration
{
1455 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1456 if (!ocppConfiguration
) {
1457 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1459 return ocppConfiguration
;
1462 private saveOcppConfiguration(): void {
1463 if (this.getOcppPersistentConfiguration()) {
1464 this.saveConfiguration(Section
.ocppConfiguration
);
1468 private async onOpen(): Promise
<void> {
1469 if (this.isWebSocketConnectionOpened()) {
1471 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1473 if (!this.isRegistered()) {
1474 // Send BootNotification
1475 let registrationRetryCount
= 0;
1477 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1478 BootNotificationRequest
,
1479 BootNotificationResponse
1481 RequestCommand
.BOOT_NOTIFICATION
,
1483 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1484 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1485 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1486 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1487 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1488 iccid
: this.bootNotificationRequest
.iccid
,
1489 imsi
: this.bootNotificationRequest
.imsi
,
1490 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1491 meterType
: this.bootNotificationRequest
.meterType
,
1493 { skipBufferingOnError
: true }
1495 if (!this.isRegistered()) {
1496 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1498 this.bootNotificationResponse
?.interval
1499 ? this.bootNotificationResponse
.interval
* 1000
1500 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1504 !this.isRegistered() &&
1505 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1506 this.getRegistrationMaxRetries() === -1)
1509 if (this.isRegistered()) {
1510 if (this.isInAcceptedState()) {
1511 await this.startMessageSequence();
1512 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1516 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1519 this.stopped
&& (this.stopped
= false);
1520 this.autoReconnectRetryCount
= 0;
1521 this.wsConnectionRestarted
= false;
1524 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1529 private async onClose(code
: number, reason
: string): Promise
<void> {
1532 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1533 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1535 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1537 )}' and reason '${reason}'`
1539 this.autoReconnectRetryCount
= 0;
1544 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1546 )}' and reason '${reason}'`
1548 await this.reconnect(code
);
1553 private async onMessage(data
: Data
): Promise
<void> {
1554 let messageType
: number;
1555 let messageId
: string;
1556 let commandName
: IncomingRequestCommand
;
1557 let commandPayload
: JsonType
;
1558 let errorType
: ErrorType
;
1559 let errorMessage
: string;
1560 let errorDetails
: JsonType
;
1561 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1562 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1563 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1564 let requestPayload
: JsonType
;
1565 let cachedRequest
: CachedRequest
;
1568 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1569 if (Utils
.isIterable(request
)) {
1570 [messageType
, messageId
] = request
;
1571 // Check the type of message
1572 switch (messageType
) {
1574 case MessageType
.CALL_MESSAGE
:
1575 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1576 if (this.getEnableStatistics()) {
1577 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1580 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1584 // Process the message
1585 await this.ocppIncomingRequestService
.incomingRequestHandler(
1592 case MessageType
.CALL_RESULT_MESSAGE
:
1593 [, , commandPayload
] = request
as Response
;
1594 if (!this.requests
.has(messageId
)) {
1596 throw new OCPPError(
1597 ErrorType
.INTERNAL_ERROR
,
1598 `Response for unknown message id ${messageId}`,
1604 cachedRequest
= this.requests
.get(messageId
);
1605 if (Utils
.isIterable(cachedRequest
)) {
1606 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1608 throw new OCPPError(
1609 ErrorType
.PROTOCOL_ERROR
,
1610 `Cached request for message id ${messageId} response is not iterable`,
1612 cachedRequest
as unknown
as JsonType
1616 `${this.logPrefix()} << Command '${
1617 requestCommandName ?? ''
1618 }' received response payload: ${JSON.stringify(request)}`
1620 responseCallback(commandPayload
, requestPayload
);
1623 case MessageType
.CALL_ERROR_MESSAGE
:
1624 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1625 if (!this.requests
.has(messageId
)) {
1627 throw new OCPPError(
1628 ErrorType
.INTERNAL_ERROR
,
1629 `Error response for unknown message id ${messageId}`,
1631 { errorType
, errorMessage
, errorDetails
}
1634 cachedRequest
= this.requests
.get(messageId
);
1635 if (Utils
.isIterable(cachedRequest
)) {
1636 [, errorCallback
, requestCommandName
] = cachedRequest
;
1638 throw new OCPPError(
1639 ErrorType
.PROTOCOL_ERROR
,
1640 `Cached request for message id ${messageId} error response is not iterable`,
1642 cachedRequest
as unknown
as JsonType
1646 `${this.logPrefix()} << Command '${
1647 requestCommandName ?? ''
1648 }' received error payload: ${JSON.stringify(request)}`
1650 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1654 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1655 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
1656 logger
.error(errMsg
);
1657 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1660 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not iterable', null, {
1667 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1670 this.requests
.get(messageId
),
1674 messageType
=== MessageType
.CALL_MESSAGE
&&
1675 (await this.ocppRequestService
.sendError(
1678 commandName
?? requestCommandName
?? null
1683 private onPing(): void {
1684 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1687 private onPong(): void {
1688 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1691 private onError(error
: WSError
): void {
1692 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
1695 private getAuthorizationFile(): string | undefined {
1697 this.stationInfo
.authorizationFile
&&
1699 path
.resolve(__dirname
, '../'),
1701 path
.basename(this.stationInfo
.authorizationFile
)
1706 private getAuthorizedTags(): string[] {
1707 let authorizedTags
: string[] = [];
1708 const authorizationFile
= this.getAuthorizationFile();
1709 if (authorizationFile
) {
1711 // Load authorization file
1712 authorizedTags
= JSON
.parse(fs
.readFileSync(authorizationFile
, 'utf8')) as string[];
1714 FileUtils
.handleFileException(
1716 FileType
.Authorization
,
1718 error
as NodeJS
.ErrnoException
1723 this.logPrefix() + ' No authorization file given in template file ' + this.templateFile
1726 return authorizedTags
;
1729 private getUseConnectorId0(): boolean | undefined {
1730 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
)
1731 ? this.stationInfo
.useConnectorId0
1735 private getNumberOfRunningTransactions(): number {
1737 for (const connectorId
of this.connectors
.keys()) {
1738 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1746 private getConnectionTimeout(): number | undefined {
1747 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
1749 parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ??
1750 Constants
.DEFAULT_CONNECTION_TIMEOUT
1753 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1756 // -1 for unlimited, 0 for disabling
1757 private getAutoReconnectMaxRetries(): number | undefined {
1758 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1759 return this.stationInfo
.autoReconnectMaxRetries
;
1761 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1762 return Configuration
.getAutoReconnectMaxRetries();
1768 private getRegistrationMaxRetries(): number | undefined {
1769 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1770 return this.stationInfo
.registrationMaxRetries
;
1775 private getPowerDivider(): number {
1776 let powerDivider
= this.getNumberOfConnectors();
1777 if (this.stationInfo
.powerSharedByConnectors
) {
1778 powerDivider
= this.getNumberOfRunningTransactions();
1780 return powerDivider
;
1783 private getTemplateMaxNumberOfConnectors(): number {
1784 if (!this.stationInfo
?.Connectors
) {
1787 return Object.keys(this.stationInfo
?.Connectors
).length
;
1790 private getMaxNumberOfConnectors(): number {
1791 let maxConnectors
: number;
1792 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
1793 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
1794 // Distribute evenly the number of connectors
1795 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
1796 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
1797 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
1799 maxConnectors
= this.stationInfo
?.Connectors
[0]
1800 ? this.getTemplateMaxNumberOfConnectors() - 1
1801 : this.getTemplateMaxNumberOfConnectors();
1803 return maxConnectors
;
1806 private getMaximumPower(): number {
1807 return (this.stationInfo
['maxPower'] as number) ?? this.stationInfo
.maximumPower
;
1810 private getMaximumAmperage(): number | undefined {
1811 const maximumPower
= this.getMaximumPower();
1812 switch (this.getCurrentOutType()) {
1813 case CurrentType
.AC
:
1814 return ACElectricUtils
.amperagePerPhaseFromPower(
1815 this.getNumberOfPhases(),
1816 maximumPower
/ this.getNumberOfConnectors(),
1817 this.getVoltageOut()
1819 case CurrentType
.DC
:
1820 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut());
1824 private getAmperageLimitationUnitDivider(): number {
1825 let unitDivider
= 1;
1826 switch (this.stationInfo
.amperageLimitationUnit
) {
1827 case AmpereUnits
.DECI_AMPERE
:
1830 case AmpereUnits
.CENTI_AMPERE
:
1833 case AmpereUnits
.MILLI_AMPERE
:
1840 private getAmperageLimitation(): number | undefined {
1842 this.stationInfo
.amperageLimitationOcppKey
&&
1843 this.getConfigurationKey(this.stationInfo
.amperageLimitationOcppKey
)
1847 this.getConfigurationKey(this.stationInfo
.amperageLimitationOcppKey
).value
1848 ) / this.getAmperageLimitationUnitDivider()
1853 private async startMessageSequence(): Promise
<void> {
1854 if (this.stationInfo
.autoRegister
) {
1855 await this.ocppRequestService
.requestHandler
<
1856 BootNotificationRequest
,
1857 BootNotificationResponse
1859 RequestCommand
.BOOT_NOTIFICATION
,
1861 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1862 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1863 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1864 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1865 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1866 iccid
: this.bootNotificationRequest
.iccid
,
1867 imsi
: this.bootNotificationRequest
.imsi
,
1868 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1869 meterType
: this.bootNotificationRequest
.meterType
,
1871 { skipBufferingOnError
: true }
1874 // Start WebSocket ping
1875 this.startWebSocketPing();
1877 this.startHeartbeat();
1878 // Initialize connectors status
1879 for (const connectorId
of this.connectors
.keys()) {
1880 if (connectorId
=== 0) {
1884 !this.getConnectorStatus(connectorId
)?.status &&
1885 this.getConnectorStatus(connectorId
)?.bootStatus
1887 // Send status in template at startup
1888 await this.ocppRequestService
.requestHandler
<
1889 StatusNotificationRequest
,
1890 StatusNotificationResponse
1891 >(RequestCommand
.STATUS_NOTIFICATION
, {
1893 status: this.getConnectorStatus(connectorId
).bootStatus
,
1894 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1896 this.getConnectorStatus(connectorId
).status =
1897 this.getConnectorStatus(connectorId
).bootStatus
;
1900 this.getConnectorStatus(connectorId
)?.status &&
1901 this.getConnectorStatus(connectorId
)?.bootStatus
1903 // Send status in template after reset
1904 await this.ocppRequestService
.requestHandler
<
1905 StatusNotificationRequest
,
1906 StatusNotificationResponse
1907 >(RequestCommand
.STATUS_NOTIFICATION
, {
1909 status: this.getConnectorStatus(connectorId
).bootStatus
,
1910 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1912 this.getConnectorStatus(connectorId
).status =
1913 this.getConnectorStatus(connectorId
).bootStatus
;
1914 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1915 // Send previous status at template reload
1916 await this.ocppRequestService
.requestHandler
<
1917 StatusNotificationRequest
,
1918 StatusNotificationResponse
1919 >(RequestCommand
.STATUS_NOTIFICATION
, {
1921 status: this.getConnectorStatus(connectorId
).status,
1922 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1925 // Send default status
1926 await this.ocppRequestService
.requestHandler
<
1927 StatusNotificationRequest
,
1928 StatusNotificationResponse
1929 >(RequestCommand
.STATUS_NOTIFICATION
, {
1931 status: ChargePointStatus
.AVAILABLE
,
1932 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1934 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1938 this.startAutomaticTransactionGenerator();
1941 private startAutomaticTransactionGenerator() {
1942 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
1943 if (!this.automaticTransactionGenerator
) {
1944 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
1946 if (!this.automaticTransactionGenerator
.started
) {
1947 this.automaticTransactionGenerator
.start();
1952 private async stopMessageSequence(
1953 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1955 // Stop WebSocket ping
1956 this.stopWebSocketPing();
1958 this.stopHeartbeat();
1961 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1962 this.automaticTransactionGenerator
?.started
1964 this.automaticTransactionGenerator
.stop();
1966 for (const connectorId
of this.connectors
.keys()) {
1967 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1968 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1970 this.getBeginEndMeterValues() &&
1971 this.getOcppStrictCompliance() &&
1972 !this.getOutOfOrderEndMeterValues()
1974 // FIXME: Implement OCPP version agnostic helpers
1975 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1978 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1980 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
1981 RequestCommand
.METER_VALUES
,
1985 meterValue
: transactionEndMeterValue
,
1989 await this.ocppRequestService
.requestHandler
<
1990 StopTransactionRequest
,
1991 StopTransactionResponse
1992 >(RequestCommand
.STOP_TRANSACTION
, {
1994 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1995 idTag
: this.getTransactionIdTag(transactionId
),
2003 private startWebSocketPing(): void {
2004 const webSocketPingInterval
: number = this.getConfigurationKey(
2005 StandardParametersKey
.WebSocketPingInterval
2007 ? Utils
.convertToInt(
2008 this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
2011 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
2012 this.webSocketPingSetInterval
= setInterval(() => {
2013 if (this.isWebSocketConnectionOpened()) {
2014 this.wsConnection
.ping((): void => {
2015 /* This is intentional */
2018 }, webSocketPingInterval
* 1000);
2021 ' WebSocket ping started every ' +
2022 Utils
.formatDurationSeconds(webSocketPingInterval
)
2024 } else if (this.webSocketPingSetInterval
) {
2027 ' WebSocket ping every ' +
2028 Utils
.formatDurationSeconds(webSocketPingInterval
) +
2033 `${this.logPrefix()} WebSocket ping interval set to ${
2034 webSocketPingInterval
2035 ? Utils.formatDurationSeconds(webSocketPingInterval)
2036 : webSocketPingInterval
2037 }, not starting the WebSocket ping`
2042 private stopWebSocketPing(): void {
2043 if (this.webSocketPingSetInterval
) {
2044 clearInterval(this.webSocketPingSetInterval
);
2048 private warnDeprecatedTemplateKey(
2049 template
: ChargingStationTemplate
,
2051 chargingStationId
: string,
2054 if (!Utils
.isUndefined(template
[key
])) {
2055 const logPrefixStr
= ` ${chargingStationId} |`;
2057 `${Utils.logPrefix(logPrefixStr)} Deprecated template key '${key}' usage in file '${
2059 }'${logMsgToAppend && '. ' + logMsgToAppend}`
2064 private convertDeprecatedTemplateKey(
2065 template
: ChargingStationTemplate
,
2066 deprecatedKey
: string,
2069 if (!Utils
.isUndefined(template
[deprecatedKey
])) {
2070 template
[key
] = template
[deprecatedKey
] as unknown
;
2071 delete template
[deprecatedKey
];
2075 private getConfiguredSupervisionUrl(): URL
{
2076 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
2077 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
2079 if (!Utils
.isEmptyArray(supervisionUrls
)) {
2081 switch (Configuration
.getSupervisionUrlDistribution()) {
2082 case SupervisionUrlDistribution
.ROUND_ROBIN
:
2083 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
2085 case SupervisionUrlDistribution
.RANDOM
:
2087 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
2089 case SupervisionUrlDistribution
.SEQUENTIAL
:
2090 if (this.index
<= supervisionUrls
.length
) {
2091 urlIndex
= this.index
- 1;
2094 `${this.logPrefix()} No more configured supervision urls available, using the first one`
2100 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2101 SupervisionUrlDistribution.ROUND_ROBIN
2104 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
2107 return new URL(supervisionUrls
[urlIndex
]);
2109 return new URL(supervisionUrls
as string);
2112 private getHeartbeatInterval(): number | undefined {
2113 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
2114 if (HeartbeatInterval
) {
2115 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
2117 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
2118 if (HeartBeatInterval
) {
2119 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
2121 !this.stationInfo
.autoRegister
&&
2123 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
2124 Constants.DEFAULT_HEARTBEAT_INTERVAL
2127 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
2130 private stopHeartbeat(): void {
2131 if (this.heartbeatSetInterval
) {
2132 clearInterval(this.heartbeatSetInterval
);
2136 private openWSConnection(
2137 options
: WsOptions
= this.stationInfo
.wsOptions
,
2138 forceCloseOpened
= false
2140 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
2142 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
2143 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
2145 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
2147 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
2148 this.wsConnection
.close();
2150 let protocol
: string;
2151 switch (this.getOcppVersion()) {
2152 case OCPPVersion
.VERSION_16
:
2153 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
2156 this.handleUnsupportedVersion(this.getOcppVersion());
2159 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
2161 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString()
2165 private stopMeterValues(connectorId
: number) {
2166 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
2167 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
2171 private getReconnectExponentialDelay(): boolean | undefined {
2172 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
2173 ? this.stationInfo
.reconnectExponentialDelay
2177 private async reconnect(code
: number): Promise
<void> {
2178 // Stop WebSocket ping
2179 this.stopWebSocketPing();
2181 this.stopHeartbeat();
2182 // Stop the ATG if needed
2184 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
2185 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
2186 this.automaticTransactionGenerator
?.started
2188 this.automaticTransactionGenerator
.stop();
2191 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2192 this.getAutoReconnectMaxRetries() === -1
2194 this.autoReconnectRetryCount
++;
2195 const reconnectDelay
= this.getReconnectExponentialDelay()
2196 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2197 : this.getConnectionTimeout() * 1000;
2198 const reconnectTimeout
= reconnectDelay
- 100 > 0 && reconnectDelay
;
2200 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
2203 )}ms, timeout ${reconnectTimeout}ms`
2205 await Utils
.sleep(reconnectDelay
);
2208 ' WebSocket: reconnecting try #' +
2209 this.autoReconnectRetryCount
.toString()
2211 this.openWSConnection(
2212 { ...this.stationInfo
.wsOptions
, handshakeTimeout
: reconnectTimeout
},
2215 this.wsConnectionRestarted
= true;
2216 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2218 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2219 this.autoReconnectRetryCount
2220 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2225 private initializeConnectorStatus(connectorId
: number): void {
2226 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2227 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2228 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2229 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2230 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2231 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
2234 private getCurrentLimitFromOCPPProfiles(chargingProfiles
: ChargingProfile
[]): {
2236 matchingChargingProfile
: ChargingProfile
;
2238 for (const chargingProfile
of chargingProfiles
) {
2239 // Profiles should already be sorted by connectorID and Stack Level (highest stack level has prio)
2241 const now
= moment();
2242 const chargingSchedule
= chargingProfile
.chargingSchedule
;
2243 // Check type (Recurring) and if it is already active
2244 // Adjust the Daily Recurring Schedule to today
2246 chargingProfile
.chargingProfileKind
=== ChargingProfileKindType
.RECURRING
&&
2247 chargingProfile
.recurrencyKind
=== RecurrencyKindType
.DAILY
&&
2248 now
.isAfter(chargingSchedule
.startSchedule
)
2250 const currentDate
= new Date();
2251 chargingSchedule
.startSchedule
= new Date(chargingSchedule
.startSchedule
);
2252 chargingSchedule
.startSchedule
.setFullYear(
2253 currentDate
.getFullYear(),
2254 currentDate
.getMonth(),
2255 currentDate
.getDate()
2257 // Check if the start of the schedule is yesterday
2258 if (moment(chargingSchedule
.startSchedule
).isAfter(now
)) {
2259 chargingSchedule
.startSchedule
.setDate(currentDate
.getDate() - 1);
2261 } else if (moment(chargingSchedule
.startSchedule
).isAfter(now
)) {
2264 // Check if the Charging Profile is active
2265 if (moment(chargingSchedule
.startSchedule
).add(chargingSchedule
.duration
, 's').isAfter(now
)) {
2266 let lastButOneSchedule
: ChargingSchedulePeriod
;
2267 // Search the right Schedule Period
2268 for (const schedulePeriod
of chargingSchedule
.chargingSchedulePeriod
) {
2269 // Handling of only one period
2271 chargingSchedule
.chargingSchedulePeriod
.length
=== 1 &&
2272 schedulePeriod
.startPeriod
=== 0
2274 return { limit
: schedulePeriod
.limit
, matchingChargingProfile
: chargingProfile
};
2276 // Find the right Schedule Periods
2278 moment(chargingSchedule
.startSchedule
).add(schedulePeriod
.startPeriod
, 's').isAfter(now
)
2280 // Found the schedule: Last but one is the correct one
2281 return { limit
: lastButOneSchedule
.limit
, matchingChargingProfile
: chargingProfile
};
2284 lastButOneSchedule
= schedulePeriod
;
2285 // Handle the last schedule period
2287 schedulePeriod
.startPeriod
===
2288 chargingSchedule
.chargingSchedulePeriod
[
2289 chargingSchedule
.chargingSchedulePeriod
.length
- 1
2292 return { limit
: lastButOneSchedule
.limit
, matchingChargingProfile
: chargingProfile
};