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';
24 import { ChargingProfile
, ChargingRateUnitType
} from
'../types/ocpp/ChargingProfile';
25 import ChargingStationTemplate
, {
29 } from
'../types/ChargingStationTemplate';
31 ConnectorPhaseRotation
,
32 StandardParametersKey
,
33 SupportedFeatureProfiles
,
34 VendorDefaultParametersKey
,
35 } from
'../types/ocpp/Configuration';
36 import { MeterValue
, MeterValueMeasurand
} from
'../types/ocpp/MeterValues';
38 StopTransactionReason
,
39 StopTransactionRequest
,
40 StopTransactionResponse
,
41 } from
'../types/ocpp/Transaction';
42 import { URL
, fileURLToPath
} from
'url';
43 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
44 import WebSocket
, { Data
, RawData
} from
'ws';
46 import AuthorizedTagsCache from
'./AuthorizedTagsCache';
47 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
48 import { AutomaticTransactionGeneratorConfiguration
} from
'../types/AutomaticTransactionGenerator';
49 import BaseError from
'../exception/BaseError';
50 import { ChargePointErrorCode
} from
'../types/ocpp/ChargePointErrorCode';
51 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
52 import ChargingStationConfiguration from
'../types/ChargingStationConfiguration';
53 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
54 import ChargingStationInfo from
'../types/ChargingStationInfo';
55 import ChargingStationOcppConfiguration from
'../types/ChargingStationOcppConfiguration';
56 import { ChargingStationUtils
} from
'./ChargingStationUtils';
57 import { ChargingStationWorkerMessageEvents
} from
'../types/ChargingStationWorker';
58 import Configuration from
'../utils/Configuration';
59 import { ConnectorStatus
} from
'../types/ConnectorStatus';
60 import Constants from
'../utils/Constants';
61 import { ErrorType
} from
'../types/ocpp/ErrorType';
62 import { FileType
} from
'../types/FileType';
63 import FileUtils from
'../utils/FileUtils';
64 import { JsonType
} from
'../types/JsonType';
65 import { MessageType
} from
'../types/ocpp/MessageType';
66 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
67 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
68 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
69 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
70 import OCPPError from
'../exception/OCPPError';
71 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
72 import OCPPRequestService from
'./ocpp/OCPPRequestService';
73 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
74 import PerformanceStatistics from
'../performance/PerformanceStatistics';
75 import SharedLRUCache from
'./SharedLRUCache';
76 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
77 import Utils from
'../utils/Utils';
78 import crypto from
'crypto';
80 import logger from
'../utils/Logger';
81 import { parentPort
} from
'worker_threads';
82 import path from
'path';
84 export default class ChargingStation
{
85 public hashId
!: string;
86 public readonly templateFile
: string;
87 public authorizedTagsCache
: AuthorizedTagsCache
;
88 public stationInfo
!: ChargingStationInfo
;
89 public readonly connectors
: Map
<number, ConnectorStatus
>;
90 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
91 public wsConnection
!: WebSocket
;
92 public readonly requests
: Map
<string, CachedRequest
>;
93 public performanceStatistics
!: PerformanceStatistics
;
94 public heartbeatSetInterval
!: NodeJS
.Timeout
;
95 public ocppRequestService
!: OCPPRequestService
;
96 public bootNotificationResponse
!: BootNotificationResponse
| null;
97 public powerDivider
!: number;
98 private readonly index
: number;
99 private configurationFile
!: string;
100 private configurationFileHash
!: string;
101 private bootNotificationRequest
!: BootNotificationRequest
;
102 private connectorsConfigurationHash
!: string;
103 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
104 private readonly messageBuffer
: Set
<string>;
105 private configuredSupervisionUrl
!: URL
;
106 private wsConnectionRestarted
: boolean;
107 private autoReconnectRetryCount
: number;
108 private stopped
: boolean;
109 private templateFileWatcher
!: fs
.FSWatcher
;
110 private readonly sharedLRUCache
: SharedLRUCache
;
111 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
112 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
114 constructor(index
: number, templateFile
: string) {
116 this.templateFile
= templateFile
;
117 this.stopped
= false;
118 this.wsConnectionRestarted
= false;
119 this.autoReconnectRetryCount
= 0;
120 this.sharedLRUCache
= SharedLRUCache
.getInstance();
121 this.authorizedTagsCache
= AuthorizedTagsCache
.getInstance();
122 this.connectors
= new Map
<number, ConnectorStatus
>();
123 this.requests
= new Map
<string, CachedRequest
>();
124 this.messageBuffer
= new Set
<string>();
128 private get
wsConnectionUrl(): URL
{
130 (this.getSupervisionUrlOcppConfiguration()
131 ? ChargingStationConfigurationUtils
.getConfigurationKey(
133 this.getSupervisionUrlOcppKey()
135 : this.configuredSupervisionUrl
.href
) +
137 this.stationInfo
.chargingStationId
141 public logPrefix(): string {
142 return Utils
.logPrefix(
144 this?.stationInfo?.chargingStationId ??
145 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
150 public getBootNotificationRequest(): BootNotificationRequest
{
151 return this.bootNotificationRequest
;
154 public getRandomIdTag(): string {
155 const authorizationFile
= ChargingStationUtils
.getAuthorizationFile(this.stationInfo
);
156 const index
= Math.floor(
157 Utils
.secureRandom() * this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
).length
159 return this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
)[index
];
162 public hasAuthorizedTags(): boolean {
163 return !Utils
.isEmptyArray(
164 this.authorizedTagsCache
.getAuthorizedTags(
165 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
)
170 public getEnableStatistics(): boolean | undefined {
171 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
172 ? this.stationInfo
.enableStatistics
176 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
177 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
180 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
181 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
182 switch (this.getCurrentOutType(stationInfo
)) {
184 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
185 ? localStationInfo
.numberOfPhases
192 public isWebSocketConnectionOpened(): boolean {
193 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
196 public getRegistrationStatus(): RegistrationStatus
{
197 return this?.bootNotificationResponse
?.status;
200 public isInUnknownState(): boolean {
201 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
204 public isInPendingState(): boolean {
205 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
208 public isInAcceptedState(): boolean {
209 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
212 public isInRejectedState(): boolean {
213 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
216 public isRegistered(): boolean {
217 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
220 public isChargingStationAvailable(): boolean {
221 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
224 public isConnectorAvailable(id
: number): boolean {
225 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
228 public getNumberOfConnectors(): number {
229 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
232 public getConnectorStatus(id
: number): ConnectorStatus
{
233 return this.connectors
.get(id
);
236 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
237 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
;
240 public getOcppStrictCompliance(): boolean {
241 return this.stationInfo
?.ocppStrictCompliance
?? false;
244 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
245 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
246 this.getCurrentOutType(stationInfo
),
250 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
251 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
252 ? localStationInfo
.voltageOut
256 public getConnectorMaximumAvailablePower(connectorId
: number): number {
257 let connectorAmperageLimitationPowerLimit
: number;
259 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
260 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
262 connectorAmperageLimitationPowerLimit
=
263 (this.getCurrentOutType() === CurrentType
.AC
264 ? ACElectricUtils
.powerTotal(
265 this.getNumberOfPhases(),
266 this.getVoltageOut(),
267 this.getAmperageLimitation() * this.getNumberOfConnectors()
269 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
272 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
273 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
275 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
276 isNaN(connectorAmperageLimitationPowerLimit
)
278 : connectorAmperageLimitationPowerLimit
,
279 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
283 public getTransactionIdTag(transactionId
: number): string | undefined {
284 for (const connectorId
of this.connectors
.keys()) {
285 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
286 return this.getConnectorStatus(connectorId
).transactionIdTag
;
291 public getOutOfOrderEndMeterValues(): boolean {
292 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
295 public getBeginEndMeterValues(): boolean {
296 return this.stationInfo
?.beginEndMeterValues
?? false;
299 public getMeteringPerTransaction(): boolean {
300 return this.stationInfo
?.meteringPerTransaction
?? true;
303 public getTransactionDataMeterValues(): boolean {
304 return this.stationInfo
?.transactionDataMeterValues
?? false;
307 public getMainVoltageMeterValues(): boolean {
308 return this.stationInfo
?.mainVoltageMeterValues
?? true;
311 public getPhaseLineToLineVoltageMeterValues(): boolean {
312 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
315 public getCustomValueLimitationMeterValues(): boolean {
316 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
319 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
320 for (const connectorId
of this.connectors
.keys()) {
323 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
330 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
331 const transactionConnectorStatus
= this.getConnectorStatus(
332 this.getConnectorIdByTransactionId(transactionId
)
334 if (this.getMeteringPerTransaction()) {
335 return transactionConnectorStatus
?.transactionEnergyActiveImportRegisterValue
;
337 return transactionConnectorStatus
?.energyActiveImportRegisterValue
;
340 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
341 const connectorStatus
= this.getConnectorStatus(connectorId
);
342 if (this.getMeteringPerTransaction()) {
343 return connectorStatus
?.transactionEnergyActiveImportRegisterValue
;
345 return connectorStatus
?.energyActiveImportRegisterValue
;
348 public getAuthorizeRemoteTxRequests(): boolean {
349 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
351 StandardParametersKey
.AuthorizeRemoteTxRequests
353 return authorizeRemoteTxRequests
354 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
358 public getLocalAuthListEnabled(): boolean {
359 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
361 StandardParametersKey
.LocalAuthListEnabled
363 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
366 public startHeartbeat(): void {
368 this.getHeartbeatInterval() &&
369 this.getHeartbeatInterval() > 0 &&
370 !this.heartbeatSetInterval
372 // eslint-disable-next-line @typescript-eslint/no-misused-promises
373 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
374 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
376 RequestCommand
.HEARTBEAT
378 }, this.getHeartbeatInterval());
381 ' Heartbeat started every ' +
382 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
384 } else if (this.heartbeatSetInterval
) {
387 ' Heartbeat already started every ' +
388 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
392 `${this.logPrefix()} Heartbeat interval set to ${
393 this.getHeartbeatInterval()
394 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
395 : this.getHeartbeatInterval()
396 }, not starting the heartbeat`
401 public restartHeartbeat(): void {
403 this.stopHeartbeat();
405 this.startHeartbeat();
408 public restartWebSocketPing(): void {
409 // Stop WebSocket ping
410 this.stopWebSocketPing();
411 // Start WebSocket ping
412 this.startWebSocketPing();
415 public startMeterValues(connectorId
: number, interval
: number): void {
416 if (connectorId
=== 0) {
418 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
422 if (!this.getConnectorStatus(connectorId
)) {
424 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
428 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
430 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
434 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
435 !this.getConnectorStatus(connectorId
)?.transactionId
438 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
443 // eslint-disable-next-line @typescript-eslint/no-misused-promises
444 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
445 // eslint-disable-next-line @typescript-eslint/no-misused-promises
446 async (): Promise
<void> => {
447 // FIXME: Implement OCPP version agnostic helpers
448 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
451 this.getConnectorStatus(connectorId
).transactionId
,
454 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
456 RequestCommand
.METER_VALUES
,
459 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
460 meterValue
: [meterValue
],
468 `${this.logPrefix()} Charging station ${
469 StandardParametersKey.MeterValueSampleInterval
470 } configuration set to ${
471 interval ? Utils.formatDurationMilliSeconds(interval) : interval
472 }, not sending MeterValues`
477 public start(): void {
478 if (this.getEnableStatistics()) {
479 this.performanceStatistics
.start();
481 this.openWSConnection();
482 // Handle WebSocket message
483 this.wsConnection
.on(
485 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
487 // Handle WebSocket error
488 this.wsConnection
.on(
490 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
492 // Handle WebSocket close
493 this.wsConnection
.on(
495 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
497 // Handle WebSocket open
498 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
499 // Handle WebSocket ping
500 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
501 // Handle WebSocket pong
502 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
503 // Monitor charging station template file
504 this.templateFileWatcher
= FileUtils
.watchJsonFile(
506 FileType
.ChargingStationTemplate
,
509 (event
, filename
): void => {
510 if (filename
&& event
=== 'change') {
513 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
515 } file have changed, reload`
517 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
521 this.stopAutomaticTransactionGenerator();
522 this.startAutomaticTransactionGenerator();
523 if (this.getEnableStatistics()) {
524 this.performanceStatistics
.restart();
526 this.performanceStatistics
.stop();
528 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
531 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
538 parentPort
.postMessage({
539 id
: ChargingStationWorkerMessageEvents
.STARTED
,
540 data
: { id
: this.stationInfo
.chargingStationId
},
544 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
545 // Stop message sequence
546 await this.stopMessageSequence(reason
);
547 for (const connectorId
of this.connectors
.keys()) {
548 if (connectorId
> 0) {
549 await this.ocppRequestService
.requestHandler
<
550 StatusNotificationRequest
,
551 StatusNotificationResponse
552 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
554 status: ChargePointStatus
.UNAVAILABLE
,
555 errorCode
: ChargePointErrorCode
.NO_ERROR
,
557 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
560 this.closeWSConnection();
561 if (this.getEnableStatistics()) {
562 this.performanceStatistics
.stop();
564 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
565 this.templateFileWatcher
.close();
566 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
567 this.bootNotificationResponse
= null;
568 parentPort
.postMessage({
569 id
: ChargingStationWorkerMessageEvents
.STOPPED
,
570 data
: { id
: this.stationInfo
.chargingStationId
},
575 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
576 await this.stop(reason
);
577 await Utils
.sleep(this.stationInfo
.resetTime
);
582 public saveOcppConfiguration(): void {
583 if (this.getOcppPersistentConfiguration()) {
584 this.saveConfiguration();
588 public getChargingProfilePowerLimit(connectorId
: number): number | undefined {
589 let limit
: number, matchingChargingProfile
: ChargingProfile
;
590 let chargingProfiles
: ChargingProfile
[] = [];
591 // Get charging profiles for connector and sort by stack level
592 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
593 (a
, b
) => b
.stackLevel
- a
.stackLevel
595 // Get profiles on connector 0
596 if (this.getConnectorStatus(0).chargingProfiles
) {
597 chargingProfiles
.push(
598 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
601 if (!Utils
.isEmptyArray(chargingProfiles
)) {
602 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
606 if (!Utils
.isNullOrUndefined(result
)) {
607 limit
= result
.limit
;
608 matchingChargingProfile
= result
.matchingChargingProfile
;
609 switch (this.getCurrentOutType()) {
612 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
613 ChargingRateUnitType
.WATT
615 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
619 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
620 ChargingRateUnitType
.WATT
622 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
625 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
626 if (limit
> connectorMaximumPower
) {
628 `${this.logPrefix()} Charging profile id ${
629 matchingChargingProfile.chargingProfileId
630 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
631 this.getConnectorStatus(connectorId
).chargingProfiles
633 limit
= connectorMaximumPower
;
640 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
641 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
643 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
645 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
647 if (!Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
649 `${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`
651 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
653 let cpReplaced
= false;
654 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
655 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
656 (chargingProfile
: ChargingProfile
, index
: number) => {
658 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
659 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
660 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
662 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
668 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
671 public resetConnectorStatus(connectorId
: number): void {
672 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
673 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
674 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
675 this.getConnectorStatus(connectorId
).transactionStarted
= false;
676 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
677 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
678 delete this.getConnectorStatus(connectorId
).transactionId
;
679 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
680 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
681 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
682 this.stopMeterValues(connectorId
);
685 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
686 return ChargingStationConfigurationUtils
.getConfigurationKey(
688 StandardParametersKey
.SupportedFeatureProfiles
689 )?.value
.includes(featureProfile
);
692 public bufferMessage(message
: string): void {
693 this.messageBuffer
.add(message
);
696 private flushMessageBuffer() {
697 if (this.messageBuffer
.size
> 0) {
698 this.messageBuffer
.forEach((message
) => {
699 // TODO: evaluate the need to track performance
700 this.wsConnection
.send(message
);
701 this.messageBuffer
.delete(message
);
706 private getSupervisionUrlOcppConfiguration(): boolean {
707 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
710 private getSupervisionUrlOcppKey(): string {
711 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
714 private getTemplateFromFile(): ChargingStationTemplate
| null {
715 let template
: ChargingStationTemplate
= null;
717 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
718 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
720 const measureId
= `${FileType.ChargingStationTemplate} read`;
721 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
722 template
= JSON
.parse(
723 fs
.readFileSync(this.templateFile
, 'utf8')
724 ) as ChargingStationTemplate
;
725 PerformanceStatistics
.endMeasure(measureId
, beginId
);
726 template
.templateHash
= crypto
727 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
728 .update(JSON
.stringify(template
))
730 this.sharedLRUCache
.setChargingStationTemplate(template
);
733 FileUtils
.handleFileException(
735 FileType
.ChargingStationTemplate
,
737 error
as NodeJS
.ErrnoException
743 private getStationInfoFromTemplate(): ChargingStationInfo
{
744 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
745 if (Utils
.isNullOrUndefined(stationTemplate
)) {
746 const errorMsg
= 'Failed to read charging station template file';
747 logger
.error(`${this.logPrefix()} ${errorMsg}`);
748 throw new BaseError(errorMsg
);
750 if (Utils
.isEmptyObject(stationTemplate
)) {
751 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
752 logger
.error(`${this.logPrefix()} ${errorMsg}`);
753 throw new BaseError(errorMsg
);
755 // Deprecation template keys section
756 ChargingStationUtils
.warnDeprecatedTemplateKey(
761 "Use 'supervisionUrls' instead"
763 ChargingStationUtils
.convertDeprecatedTemplateKey(
768 const stationInfo
: ChargingStationInfo
=
769 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
770 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
774 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
775 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
776 stationTemplate
.power
= stationTemplate
.power
as number[];
777 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
778 stationInfo
.maximumPower
=
779 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
780 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
781 : stationTemplate
.power
[powerArrayRandomIndex
];
783 stationTemplate
.power
= stationTemplate
.power
as number;
784 stationInfo
.maximumPower
=
785 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
786 ? stationTemplate
.power
* 1000
787 : stationTemplate
.power
;
789 stationInfo
.resetTime
= stationTemplate
.resetTime
790 ? stationTemplate
.resetTime
* 1000
791 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
792 const configuredMaxConnectors
= ChargingStationUtils
.getConfiguredNumberOfConnectors(
796 ChargingStationUtils
.checkConfiguredMaxConnectors(
797 configuredMaxConnectors
,
801 const templateMaxConnectors
=
802 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
803 ChargingStationUtils
.checkTemplateMaxConnectors(
804 templateMaxConnectors
,
809 configuredMaxConnectors
>
810 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
811 !stationTemplate
?.randomConnectors
814 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
816 }, forcing random connector configurations affectation`
818 stationInfo
.randomConnectors
= true;
820 // Build connectors if needed (FIXME: should be factored out)
821 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
822 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
823 ChargingStationUtils
.createStationInfoHash(stationInfo
);
827 private getStationInfoFromFile(): ChargingStationInfo
| null {
828 let stationInfo
: ChargingStationInfo
= null;
829 this.getStationInfoPersistentConfiguration() &&
830 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
831 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
835 private getStationInfo(): ChargingStationInfo
{
836 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
837 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
838 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
839 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
840 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
841 return this.stationInfo
;
843 return stationInfoFromFile
;
845 stationInfoFromFile
&&
846 ChargingStationUtils
.propagateSerialNumber(
847 this.getTemplateFromFile(),
849 stationInfoFromTemplate
851 return stationInfoFromTemplate
;
854 private saveStationInfo(): void {
855 if (this.getStationInfoPersistentConfiguration()) {
856 this.saveConfiguration();
860 private getOcppVersion(): OCPPVersion
{
861 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
864 private getOcppPersistentConfiguration(): boolean {
865 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
868 private getStationInfoPersistentConfiguration(): boolean {
869 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
872 private handleUnsupportedVersion(version
: OCPPVersion
) {
873 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
876 logger
.error(errMsg
);
877 throw new Error(errMsg
);
880 private initialize(): void {
881 this.hashId
= ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile());
882 logger
.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
883 this.configurationFile
= path
.join(
884 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
887 this.hashId
+ '.json'
889 this.stationInfo
= this.getStationInfo();
890 this.saveStationInfo();
891 // Avoid duplication of connectors related information in RAM
892 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
893 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
894 if (this.getEnableStatistics()) {
895 this.performanceStatistics
= PerformanceStatistics
.getInstance(
897 this.stationInfo
.chargingStationId
,
898 this.configuredSupervisionUrl
901 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
904 this.powerDivider
= this.getPowerDivider();
905 // OCPP configuration
906 this.ocppConfiguration
= this.getOcppConfiguration();
907 this.initializeOcppConfiguration();
908 switch (this.getOcppVersion()) {
909 case OCPPVersion
.VERSION_16
:
910 this.ocppIncomingRequestService
=
911 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
912 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
913 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
917 this.handleUnsupportedVersion(this.getOcppVersion());
920 if (this.stationInfo
?.autoRegister
) {
921 this.bootNotificationResponse
= {
922 currentTime
: new Date().toISOString(),
923 interval
: this.getHeartbeatInterval() / 1000,
924 status: RegistrationStatus
.ACCEPTED
,
929 private initializeOcppConfiguration(): void {
931 !ChargingStationConfigurationUtils
.getConfigurationKey(
933 StandardParametersKey
.HeartbeatInterval
936 ChargingStationConfigurationUtils
.addConfigurationKey(
938 StandardParametersKey
.HeartbeatInterval
,
943 !ChargingStationConfigurationUtils
.getConfigurationKey(
945 StandardParametersKey
.HeartBeatInterval
948 ChargingStationConfigurationUtils
.addConfigurationKey(
950 StandardParametersKey
.HeartBeatInterval
,
956 this.getSupervisionUrlOcppConfiguration() &&
957 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
959 ChargingStationConfigurationUtils
.addConfigurationKey(
961 this.getSupervisionUrlOcppKey(),
962 this.configuredSupervisionUrl
.href
,
966 !this.getSupervisionUrlOcppConfiguration() &&
967 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
969 ChargingStationConfigurationUtils
.deleteConfigurationKey(
971 this.getSupervisionUrlOcppKey(),
976 this.stationInfo
.amperageLimitationOcppKey
&&
977 !ChargingStationConfigurationUtils
.getConfigurationKey(
979 this.stationInfo
.amperageLimitationOcppKey
982 ChargingStationConfigurationUtils
.addConfigurationKey(
984 this.stationInfo
.amperageLimitationOcppKey
,
986 this.stationInfo
.maximumAmperage
*
987 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
992 !ChargingStationConfigurationUtils
.getConfigurationKey(
994 StandardParametersKey
.SupportedFeatureProfiles
997 ChargingStationConfigurationUtils
.addConfigurationKey(
999 StandardParametersKey
.SupportedFeatureProfiles
,
1000 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1003 ChargingStationConfigurationUtils
.addConfigurationKey(
1005 StandardParametersKey
.NumberOfConnectors
,
1006 this.getNumberOfConnectors().toString(),
1011 !ChargingStationConfigurationUtils
.getConfigurationKey(
1013 StandardParametersKey
.MeterValuesSampledData
1016 ChargingStationConfigurationUtils
.addConfigurationKey(
1018 StandardParametersKey
.MeterValuesSampledData
,
1019 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1023 !ChargingStationConfigurationUtils
.getConfigurationKey(
1025 StandardParametersKey
.ConnectorPhaseRotation
1028 const connectorPhaseRotation
= [];
1029 for (const connectorId
of this.connectors
.keys()) {
1031 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1032 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1033 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1034 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1036 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1037 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1038 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1039 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1042 ChargingStationConfigurationUtils
.addConfigurationKey(
1044 StandardParametersKey
.ConnectorPhaseRotation
,
1045 connectorPhaseRotation
.toString()
1049 !ChargingStationConfigurationUtils
.getConfigurationKey(
1051 StandardParametersKey
.AuthorizeRemoteTxRequests
1054 ChargingStationConfigurationUtils
.addConfigurationKey(
1056 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1061 !ChargingStationConfigurationUtils
.getConfigurationKey(
1063 StandardParametersKey
.LocalAuthListEnabled
1065 ChargingStationConfigurationUtils
.getConfigurationKey(
1067 StandardParametersKey
.SupportedFeatureProfiles
1068 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1070 ChargingStationConfigurationUtils
.addConfigurationKey(
1072 StandardParametersKey
.LocalAuthListEnabled
,
1077 !ChargingStationConfigurationUtils
.getConfigurationKey(
1079 StandardParametersKey
.ConnectionTimeOut
1082 ChargingStationConfigurationUtils
.addConfigurationKey(
1084 StandardParametersKey
.ConnectionTimeOut
,
1085 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1088 this.saveOcppConfiguration();
1091 private initializeConnectors(
1092 stationInfo
: ChargingStationInfo
,
1093 configuredMaxConnectors
: number,
1094 templateMaxConnectors
: number
1096 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1097 const logMsg
= `${this.logPrefix()} No already defined connectors and charging station information from template ${
1099 } with no connectors configuration defined`;
1100 logger
.error(logMsg
);
1101 throw new BaseError(logMsg
);
1103 if (!stationInfo
?.Connectors
[0]) {
1105 `${this.logPrefix()} Charging station information from template ${
1107 } with no connector Id 0 configuration`
1110 if (stationInfo
?.Connectors
) {
1111 const connectorsConfigHash
= crypto
1112 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1113 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1115 const connectorsConfigChanged
=
1116 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1117 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1118 connectorsConfigChanged
&& this.connectors
.clear();
1119 this.connectorsConfigurationHash
= connectorsConfigHash
;
1120 // Add connector Id 0
1121 let lastConnector
= '0';
1122 for (lastConnector
in stationInfo
?.Connectors
) {
1123 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1125 lastConnectorId
=== 0 &&
1126 this.getUseConnectorId0(stationInfo
) &&
1127 stationInfo
?.Connectors
[lastConnector
]
1129 this.connectors
.set(
1131 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1133 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1134 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1135 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1139 // Generate all connectors
1140 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1141 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1142 const randConnectorId
= stationInfo
?.randomConnectors
1143 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1145 this.connectors
.set(
1147 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1149 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1150 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1151 this.getConnectorStatus(index
).chargingProfiles
= [];
1158 `${this.logPrefix()} Charging station information from template ${
1160 } with no connectors configuration defined, using already defined connectors`
1163 // Initialize transaction attributes on connectors
1164 for (const connectorId
of this.connectors
.keys()) {
1165 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1166 this.initializeConnectorStatus(connectorId
);
1171 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1172 let configuration
: ChargingStationConfiguration
= null;
1173 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1175 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1176 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1177 this.configurationFileHash
1180 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1181 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1182 configuration
= JSON
.parse(
1183 fs
.readFileSync(this.configurationFile
, 'utf8')
1184 ) as ChargingStationConfiguration
;
1185 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1186 this.configurationFileHash
= configuration
.configurationHash
;
1187 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1190 FileUtils
.handleFileException(
1192 FileType
.ChargingStationConfiguration
,
1193 this.configurationFile
,
1194 error
as NodeJS
.ErrnoException
1198 return configuration
;
1201 private saveConfiguration(): void {
1202 if (this.configurationFile
) {
1204 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1205 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1207 const configurationData
: ChargingStationConfiguration
=
1208 this.getConfigurationFromFile() ?? {};
1209 this.ocppConfiguration
?.configurationKey
&&
1210 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1211 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1212 delete configurationData
.configurationHash
;
1213 const configurationHash
= crypto
1214 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1215 .update(JSON
.stringify(configurationData
))
1217 if (this.configurationFileHash
!== configurationHash
) {
1218 configurationData
.configurationHash
= configurationHash
;
1219 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1220 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1221 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1222 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1223 fs
.closeSync(fileDescriptor
);
1224 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1225 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1226 this.configurationFileHash
= configurationHash
;
1227 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1230 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1231 this.configurationFile
1236 FileUtils
.handleFileException(
1238 FileType
.ChargingStationConfiguration
,
1239 this.configurationFile
,
1240 error
as NodeJS
.ErrnoException
1245 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1250 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1251 return this.getTemplateFromFile()?.Configuration
?? null;
1254 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1255 let configuration
: ChargingStationConfiguration
= null;
1256 if (this.getOcppPersistentConfiguration()) {
1257 const configurationFromFile
= this.getConfigurationFromFile();
1258 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1260 configuration
&& delete configuration
.stationInfo
;
1261 return configuration
;
1264 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1265 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1266 if (!ocppConfiguration
) {
1267 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1269 return ocppConfiguration
;
1272 private async onOpen(): Promise
<void> {
1273 if (this.isWebSocketConnectionOpened()) {
1275 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1277 if (!this.isRegistered()) {
1278 // Send BootNotification
1279 let registrationRetryCount
= 0;
1281 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1282 BootNotificationRequest
,
1283 BootNotificationResponse
1286 RequestCommand
.BOOT_NOTIFICATION
,
1288 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1289 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1290 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1291 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1292 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1293 iccid
: this.bootNotificationRequest
.iccid
,
1294 imsi
: this.bootNotificationRequest
.imsi
,
1295 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1296 meterType
: this.bootNotificationRequest
.meterType
,
1298 { skipBufferingOnError
: true }
1300 if (!this.isRegistered()) {
1301 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1303 this.bootNotificationResponse
?.interval
1304 ? this.bootNotificationResponse
.interval
* 1000
1305 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1309 !this.isRegistered() &&
1310 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1311 this.getRegistrationMaxRetries() === -1)
1314 if (this.isRegistered()) {
1315 if (this.isInAcceptedState()) {
1316 await this.startMessageSequence();
1317 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1321 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1324 this.stopped
&& (this.stopped
= false);
1325 this.autoReconnectRetryCount
= 0;
1326 this.wsConnectionRestarted
= false;
1329 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1334 private async onClose(code
: number, reason
: string): Promise
<void> {
1337 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1338 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1340 `${this.logPrefix()} WebSocket normally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1342 )}' and reason '${reason}'`
1344 this.autoReconnectRetryCount
= 0;
1349 `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1351 )}' and reason '${reason}'`
1353 await this.reconnect(code
);
1358 private async onMessage(data
: Data
): Promise
<void> {
1359 let messageType
: number;
1360 let messageId
: string;
1361 let commandName
: IncomingRequestCommand
;
1362 let commandPayload
: JsonType
;
1363 let errorType
: ErrorType
;
1364 let errorMessage
: string;
1365 let errorDetails
: JsonType
;
1366 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1367 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1368 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1369 let requestPayload
: JsonType
;
1370 let cachedRequest
: CachedRequest
;
1373 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1374 if (Utils
.isIterable(request
)) {
1375 [messageType
, messageId
] = request
;
1376 // Check the type of message
1377 switch (messageType
) {
1379 case MessageType
.CALL_MESSAGE
:
1380 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1381 if (this.getEnableStatistics()) {
1382 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1385 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1389 // Process the message
1390 await this.ocppIncomingRequestService
.incomingRequestHandler(
1398 case MessageType
.CALL_RESULT_MESSAGE
:
1399 [, , commandPayload
] = request
as Response
;
1400 if (!this.requests
.has(messageId
)) {
1402 throw new OCPPError(
1403 ErrorType
.INTERNAL_ERROR
,
1404 `Response for unknown message id ${messageId}`,
1410 cachedRequest
= this.requests
.get(messageId
);
1411 if (Utils
.isIterable(cachedRequest
)) {
1412 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1414 throw new OCPPError(
1415 ErrorType
.PROTOCOL_ERROR
,
1416 `Cached request for message id ${messageId} response is not iterable`,
1418 cachedRequest
as unknown
as JsonType
1422 `${this.logPrefix()} << Command '${
1423 requestCommandName ?? ''
1424 }' received response payload: ${JSON.stringify(request)}`
1426 responseCallback(commandPayload
, requestPayload
);
1429 case MessageType
.CALL_ERROR_MESSAGE
:
1430 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1431 if (!this.requests
.has(messageId
)) {
1433 throw new OCPPError(
1434 ErrorType
.INTERNAL_ERROR
,
1435 `Error response for unknown message id ${messageId}`,
1437 { errorType
, errorMessage
, errorDetails
}
1440 cachedRequest
= this.requests
.get(messageId
);
1441 if (Utils
.isIterable(cachedRequest
)) {
1442 [, errorCallback
, requestCommandName
] = cachedRequest
;
1444 throw new OCPPError(
1445 ErrorType
.PROTOCOL_ERROR
,
1446 `Cached request for message id ${messageId} error response is not iterable`,
1448 cachedRequest
as unknown
as JsonType
1452 `${this.logPrefix()} << Command '${
1453 requestCommandName ?? ''
1454 }' received error payload: ${JSON.stringify(request)}`
1456 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1460 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1461 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
1462 logger
.error(errMsg
);
1463 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1466 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not iterable', null, {
1473 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1476 this.requests
.get(messageId
),
1480 messageType
=== MessageType
.CALL_MESSAGE
&&
1481 (await this.ocppRequestService
.sendError(
1485 commandName
?? requestCommandName
?? null
1490 private onPing(): void {
1491 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1494 private onPong(): void {
1495 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1498 private onError(error
: WSError
): void {
1499 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
1502 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean | undefined {
1503 const localStationInfo
= stationInfo
?? this.stationInfo
;
1504 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1505 ? localStationInfo
.useConnectorId0
1509 private getNumberOfRunningTransactions(): number {
1511 for (const connectorId
of this.connectors
.keys()) {
1512 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1520 private getConnectionTimeout(): number | undefined {
1522 ChargingStationConfigurationUtils
.getConfigurationKey(
1524 StandardParametersKey
.ConnectionTimeOut
1529 ChargingStationConfigurationUtils
.getConfigurationKey(
1531 StandardParametersKey
.ConnectionTimeOut
1533 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1536 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1539 // -1 for unlimited, 0 for disabling
1540 private getAutoReconnectMaxRetries(): number | undefined {
1541 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1542 return this.stationInfo
.autoReconnectMaxRetries
;
1544 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1545 return Configuration
.getAutoReconnectMaxRetries();
1551 private getRegistrationMaxRetries(): number | undefined {
1552 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1553 return this.stationInfo
.registrationMaxRetries
;
1558 private getPowerDivider(): number {
1559 let powerDivider
= this.getNumberOfConnectors();
1560 if (this.stationInfo
?.powerSharedByConnectors
) {
1561 powerDivider
= this.getNumberOfRunningTransactions();
1563 return powerDivider
;
1566 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1567 const localStationInfo
= stationInfo
?? this.stationInfo
;
1568 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1571 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1572 const maximumPower
= this.getMaximumPower(stationInfo
);
1573 switch (this.getCurrentOutType(stationInfo
)) {
1574 case CurrentType
.AC
:
1575 return ACElectricUtils
.amperagePerPhaseFromPower(
1576 this.getNumberOfPhases(stationInfo
),
1577 maximumPower
/ this.getNumberOfConnectors(),
1578 this.getVoltageOut(stationInfo
)
1580 case CurrentType
.DC
:
1581 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1585 private getAmperageLimitation(): number | undefined {
1587 this.stationInfo
.amperageLimitationOcppKey
&&
1588 ChargingStationConfigurationUtils
.getConfigurationKey(
1590 this.stationInfo
.amperageLimitationOcppKey
1595 ChargingStationConfigurationUtils
.getConfigurationKey(
1597 this.stationInfo
.amperageLimitationOcppKey
1599 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1604 private async startMessageSequence(): Promise
<void> {
1605 if (this.stationInfo
?.autoRegister
) {
1606 await this.ocppRequestService
.requestHandler
<
1607 BootNotificationRequest
,
1608 BootNotificationResponse
1611 RequestCommand
.BOOT_NOTIFICATION
,
1613 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1614 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1615 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1616 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1617 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1618 iccid
: this.bootNotificationRequest
.iccid
,
1619 imsi
: this.bootNotificationRequest
.imsi
,
1620 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1621 meterType
: this.bootNotificationRequest
.meterType
,
1623 { skipBufferingOnError
: true }
1626 // Start WebSocket ping
1627 this.startWebSocketPing();
1629 this.startHeartbeat();
1630 // Initialize connectors status
1631 for (const connectorId
of this.connectors
.keys()) {
1632 if (connectorId
=== 0) {
1636 !this.getConnectorStatus(connectorId
)?.status &&
1637 this.getConnectorStatus(connectorId
)?.bootStatus
1639 // Send status in template at startup
1640 await this.ocppRequestService
.requestHandler
<
1641 StatusNotificationRequest
,
1642 StatusNotificationResponse
1643 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1645 status: this.getConnectorStatus(connectorId
).bootStatus
,
1646 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1648 this.getConnectorStatus(connectorId
).status =
1649 this.getConnectorStatus(connectorId
).bootStatus
;
1652 this.getConnectorStatus(connectorId
)?.status &&
1653 this.getConnectorStatus(connectorId
)?.bootStatus
1655 // Send status in template after reset
1656 await this.ocppRequestService
.requestHandler
<
1657 StatusNotificationRequest
,
1658 StatusNotificationResponse
1659 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1661 status: this.getConnectorStatus(connectorId
).bootStatus
,
1662 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1664 this.getConnectorStatus(connectorId
).status =
1665 this.getConnectorStatus(connectorId
).bootStatus
;
1666 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1667 // Send previous status at template reload
1668 await this.ocppRequestService
.requestHandler
<
1669 StatusNotificationRequest
,
1670 StatusNotificationResponse
1671 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1673 status: this.getConnectorStatus(connectorId
).status,
1674 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1677 // Send default status
1678 await this.ocppRequestService
.requestHandler
<
1679 StatusNotificationRequest
,
1680 StatusNotificationResponse
1681 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1683 status: ChargePointStatus
.AVAILABLE
,
1684 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1686 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1690 this.startAutomaticTransactionGenerator();
1693 private startAutomaticTransactionGenerator() {
1694 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
) {
1695 if (!this.automaticTransactionGenerator
) {
1696 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
1697 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
1701 if (!this.automaticTransactionGenerator
.started
) {
1702 this.automaticTransactionGenerator
.start();
1707 private stopAutomaticTransactionGenerator(): void {
1708 if (this.automaticTransactionGenerator
?.started
) {
1709 this.automaticTransactionGenerator
.stop();
1710 this.automaticTransactionGenerator
= null;
1714 private async stopMessageSequence(
1715 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1717 // Stop WebSocket ping
1718 this.stopWebSocketPing();
1720 this.stopHeartbeat();
1721 // Stop ongoing transactions
1722 if (this.automaticTransactionGenerator
?.configuration
?.enable
) {
1723 this.stopAutomaticTransactionGenerator();
1725 for (const connectorId
of this.connectors
.keys()) {
1726 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1727 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1729 this.getBeginEndMeterValues() &&
1730 this.getOcppStrictCompliance() &&
1731 !this.getOutOfOrderEndMeterValues()
1733 // FIXME: Implement OCPP version agnostic helpers
1734 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1737 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1739 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
1741 RequestCommand
.METER_VALUES
,
1745 meterValue
: transactionEndMeterValue
,
1749 await this.ocppRequestService
.requestHandler
<
1750 StopTransactionRequest
,
1751 StopTransactionResponse
1752 >(this, RequestCommand
.STOP_TRANSACTION
, {
1754 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1755 idTag
: this.getTransactionIdTag(transactionId
),
1763 private startWebSocketPing(): void {
1764 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1766 StandardParametersKey
.WebSocketPingInterval
1768 ? Utils
.convertToInt(
1769 ChargingStationConfigurationUtils
.getConfigurationKey(
1771 StandardParametersKey
.WebSocketPingInterval
1775 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1776 this.webSocketPingSetInterval
= setInterval(() => {
1777 if (this.isWebSocketConnectionOpened()) {
1778 this.wsConnection
.ping((): void => {
1779 /* This is intentional */
1782 }, webSocketPingInterval
* 1000);
1785 ' WebSocket ping started every ' +
1786 Utils
.formatDurationSeconds(webSocketPingInterval
)
1788 } else if (this.webSocketPingSetInterval
) {
1791 ' WebSocket ping every ' +
1792 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1797 `${this.logPrefix()} WebSocket ping interval set to ${
1798 webSocketPingInterval
1799 ? Utils.formatDurationSeconds(webSocketPingInterval)
1800 : webSocketPingInterval
1801 }, not starting the WebSocket ping`
1806 private stopWebSocketPing(): void {
1807 if (this.webSocketPingSetInterval
) {
1808 clearInterval(this.webSocketPingSetInterval
);
1812 private getConfiguredSupervisionUrl(): URL
{
1813 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1814 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1816 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1818 switch (Configuration
.getSupervisionUrlDistribution()) {
1819 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1820 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1822 case SupervisionUrlDistribution
.RANDOM
:
1824 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1826 case SupervisionUrlDistribution
.SEQUENTIAL
:
1827 if (this.index
<= supervisionUrls
.length
) {
1828 urlIndex
= this.index
- 1;
1831 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1837 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1838 SupervisionUrlDistribution.ROUND_ROBIN
1841 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1844 return new URL(supervisionUrls
[urlIndex
]);
1846 return new URL(supervisionUrls
as string);
1849 private getHeartbeatInterval(): number | undefined {
1850 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1852 StandardParametersKey
.HeartbeatInterval
1854 if (HeartbeatInterval
) {
1855 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1857 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1859 StandardParametersKey
.HeartBeatInterval
1861 if (HeartBeatInterval
) {
1862 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1864 !this.stationInfo
?.autoRegister
&&
1866 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1867 Constants.DEFAULT_HEARTBEAT_INTERVAL
1870 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1873 private stopHeartbeat(): void {
1874 if (this.heartbeatSetInterval
) {
1875 clearInterval(this.heartbeatSetInterval
);
1879 private openWSConnection(
1880 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
1881 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
1883 terminateOpened
: false,
1886 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
1887 params
.closeOpened
= params
?.closeOpened
?? false;
1888 params
.terminateOpened
= params
?.terminateOpened
?? false;
1890 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
1891 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
1893 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
1895 if (params
?.closeOpened
) {
1896 this.closeWSConnection();
1898 if (params
?.terminateOpened
) {
1899 this.terminateWSConnection();
1901 let protocol
: string;
1902 switch (this.getOcppVersion()) {
1903 case OCPPVersion
.VERSION_16
:
1904 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
1907 this.handleUnsupportedVersion(this.getOcppVersion());
1910 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
1912 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString()
1916 private closeWSConnection(): void {
1917 if (this.isWebSocketConnectionOpened()) {
1918 this.wsConnection
.close();
1919 this.wsConnection
= null;
1923 private terminateWSConnection(): void {
1924 if (this.isWebSocketConnectionOpened()) {
1925 this.wsConnection
.terminate();
1926 this.wsConnection
= null;
1930 private stopMeterValues(connectorId
: number) {
1931 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1932 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1936 private getReconnectExponentialDelay(): boolean | undefined {
1937 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1938 ? this.stationInfo
.reconnectExponentialDelay
1942 private async reconnect(code
: number): Promise
<void> {
1943 // Stop WebSocket ping
1944 this.stopWebSocketPing();
1946 this.stopHeartbeat();
1947 // Stop the ATG if needed
1948 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
) {
1949 this.stopAutomaticTransactionGenerator();
1952 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1953 this.getAutoReconnectMaxRetries() === -1
1955 this.autoReconnectRetryCount
++;
1956 const reconnectDelay
= this.getReconnectExponentialDelay()
1957 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1958 : this.getConnectionTimeout() * 1000;
1959 const reconnectDelayWithdraw
= 1000;
1960 const reconnectTimeout
=
1961 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
1962 ? reconnectDelay
- reconnectDelayWithdraw
1965 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1968 )}ms, timeout ${reconnectTimeout}ms`
1970 await Utils
.sleep(reconnectDelay
);
1973 ' WebSocket: reconnecting try #' +
1974 this.autoReconnectRetryCount
.toString()
1976 this.openWSConnection(
1977 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
1978 { closeOpened
: true }
1980 this.wsConnectionRestarted
= true;
1981 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1983 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
1984 this.autoReconnectRetryCount
1985 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
1990 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
1991 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
1994 private initializeConnectorStatus(connectorId
: number): void {
1995 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
1996 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
1997 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
1998 this.getConnectorStatus(connectorId
).transactionStarted
= false;
1999 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2000 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;