1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import crypto from
'crypto';
5 import path from
'path';
6 import { URL
} from
'url';
7 import { parentPort
} from
'worker_threads';
9 import WebSocket
, { Data
, RawData
} from
'ws';
11 import BaseError from
'../exception/BaseError';
12 import OCPPError from
'../exception/OCPPError';
13 import PerformanceStatistics from
'../performance/PerformanceStatistics';
14 import { AutomaticTransactionGeneratorConfiguration
} from
'../types/AutomaticTransactionGenerator';
15 import ChargingStationConfiguration from
'../types/ChargingStationConfiguration';
16 import ChargingStationInfo from
'../types/ChargingStationInfo';
17 import ChargingStationOcppConfiguration from
'../types/ChargingStationOcppConfiguration';
18 import ChargingStationTemplate
, {
22 } from
'../types/ChargingStationTemplate';
23 import { ChargingStationWorkerMessageEvents
} from
'../types/ChargingStationWorker';
24 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
25 import { ConnectorStatus
} from
'../types/ConnectorStatus';
26 import { FileType
} from
'../types/FileType';
27 import { JsonType
} from
'../types/JsonType';
28 import { ChargePointErrorCode
} from
'../types/ocpp/ChargePointErrorCode';
29 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
30 import { ChargingProfile
, ChargingRateUnitType
} from
'../types/ocpp/ChargingProfile';
32 ConnectorPhaseRotation
,
33 StandardParametersKey
,
34 SupportedFeatureProfiles
,
35 VendorDefaultParametersKey
,
36 } from
'../types/ocpp/Configuration';
37 import { ErrorType
} from
'../types/ocpp/ErrorType';
38 import { MessageType
} from
'../types/ocpp/MessageType';
39 import { MeterValue
, MeterValueMeasurand
} from
'../types/ocpp/MeterValues';
40 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
43 BootNotificationRequest
,
47 IncomingRequestCommand
,
50 StatusNotificationRequest
,
51 } from
'../types/ocpp/Requests';
53 BootNotificationResponse
,
59 StatusNotificationResponse
,
60 } from
'../types/ocpp/Responses';
62 StopTransactionReason
,
63 StopTransactionRequest
,
64 StopTransactionResponse
,
65 } from
'../types/ocpp/Transaction';
66 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
67 import Configuration from
'../utils/Configuration';
68 import Constants from
'../utils/Constants';
69 import { ACElectricUtils
, DCElectricUtils
} from
'../utils/ElectricUtils';
70 import FileUtils from
'../utils/FileUtils';
71 import logger from
'../utils/Logger';
72 import Utils from
'../utils/Utils';
73 import AuthorizedTagsCache from
'./AuthorizedTagsCache';
74 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
75 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
76 import { ChargingStationUtils
} from
'./ChargingStationUtils';
77 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
78 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
79 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
80 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
81 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
82 import OCPPRequestService from
'./ocpp/OCPPRequestService';
83 import SharedLRUCache from
'./SharedLRUCache';
85 export default class ChargingStation
{
86 public hashId
!: string;
87 public readonly templateFile
: string;
88 public authorizedTagsCache
: AuthorizedTagsCache
;
89 public stationInfo
!: ChargingStationInfo
;
90 public readonly connectors
: Map
<number, ConnectorStatus
>;
91 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
92 public wsConnection
!: WebSocket
;
93 public readonly requests
: Map
<string, CachedRequest
>;
94 public performanceStatistics
!: PerformanceStatistics
;
95 public heartbeatSetInterval
!: NodeJS
.Timeout
;
96 public ocppRequestService
!: OCPPRequestService
;
97 public bootNotificationResponse
!: BootNotificationResponse
| null;
98 public powerDivider
!: number;
99 private readonly index
: number;
100 private configurationFile
!: string;
101 private configurationFileHash
!: string;
102 private bootNotificationRequest
!: BootNotificationRequest
;
103 private connectorsConfigurationHash
!: string;
104 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
105 private readonly messageBuffer
: Set
<string>;
106 private configuredSupervisionUrl
!: URL
;
107 private wsConnectionRestarted
: boolean;
108 private autoReconnectRetryCount
: number;
109 private stopped
: boolean;
110 private templateFileWatcher
!: fs
.FSWatcher
;
111 private readonly sharedLRUCache
: SharedLRUCache
;
112 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
113 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
115 constructor(index
: number, templateFile
: string) {
117 this.templateFile
= templateFile
;
118 this.stopped
= false;
119 this.wsConnectionRestarted
= false;
120 this.autoReconnectRetryCount
= 0;
121 this.sharedLRUCache
= SharedLRUCache
.getInstance();
122 this.authorizedTagsCache
= AuthorizedTagsCache
.getInstance();
123 this.connectors
= new Map
<number, ConnectorStatus
>();
124 this.requests
= new Map
<string, CachedRequest
>();
125 this.messageBuffer
= new Set
<string>();
129 private get
wsConnectionUrl(): URL
{
131 (this.getSupervisionUrlOcppConfiguration()
132 ? ChargingStationConfigurationUtils
.getConfigurationKey(
134 this.getSupervisionUrlOcppKey()
136 : this.configuredSupervisionUrl
.href
) +
138 this.stationInfo
.chargingStationId
142 public logPrefix(): string {
143 return Utils
.logPrefix(
145 this?.stationInfo?.chargingStationId ??
146 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
151 public getBootNotificationRequest(): BootNotificationRequest
{
152 return this.bootNotificationRequest
;
155 public getRandomIdTag(): string {
156 const authorizationFile
= ChargingStationUtils
.getAuthorizationFile(this.stationInfo
);
157 const index
= Math.floor(
158 Utils
.secureRandom() * this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
).length
160 return this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
)[index
];
163 public hasAuthorizedTags(): boolean {
164 return !Utils
.isEmptyArray(
165 this.authorizedTagsCache
.getAuthorizedTags(
166 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
)
171 public getEnableStatistics(): boolean | undefined {
172 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
173 ? this.stationInfo
.enableStatistics
177 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
178 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
181 public getPayloadSchemaValidation(): boolean | undefined {
182 return this.stationInfo
.payloadSchemaValidation
?? true;
185 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
186 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
187 switch (this.getCurrentOutType(stationInfo
)) {
189 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
190 ? localStationInfo
.numberOfPhases
197 public isWebSocketConnectionOpened(): boolean {
198 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
201 public getRegistrationStatus(): RegistrationStatus
{
202 return this?.bootNotificationResponse
?.status;
205 public isInUnknownState(): boolean {
206 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
209 public isInPendingState(): boolean {
210 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
213 public isInAcceptedState(): boolean {
214 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
217 public isInRejectedState(): boolean {
218 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
221 public isRegistered(): boolean {
222 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
225 public isChargingStationAvailable(): boolean {
226 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
229 public isConnectorAvailable(id
: number): boolean {
230 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
233 public getNumberOfConnectors(): number {
234 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
237 public getConnectorStatus(id
: number): ConnectorStatus
{
238 return this.connectors
.get(id
);
241 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
242 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
;
245 public getOcppStrictCompliance(): boolean {
246 return this.stationInfo
?.ocppStrictCompliance
?? false;
249 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
250 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
251 this.getCurrentOutType(stationInfo
),
255 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
256 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
257 ? localStationInfo
.voltageOut
261 public getConnectorMaximumAvailablePower(connectorId
: number): number {
262 let connectorAmperageLimitationPowerLimit
: number;
264 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
265 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
267 connectorAmperageLimitationPowerLimit
=
268 (this.getCurrentOutType() === CurrentType
.AC
269 ? ACElectricUtils
.powerTotal(
270 this.getNumberOfPhases(),
271 this.getVoltageOut(),
272 this.getAmperageLimitation() * this.getNumberOfConnectors()
274 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
277 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
278 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
280 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
281 isNaN(connectorAmperageLimitationPowerLimit
)
283 : connectorAmperageLimitationPowerLimit
,
284 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
288 public getTransactionIdTag(transactionId
: number): string | undefined {
289 for (const connectorId
of this.connectors
.keys()) {
290 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
291 return this.getConnectorStatus(connectorId
).transactionIdTag
;
296 public getOutOfOrderEndMeterValues(): boolean {
297 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
300 public getBeginEndMeterValues(): boolean {
301 return this.stationInfo
?.beginEndMeterValues
?? false;
304 public getMeteringPerTransaction(): boolean {
305 return this.stationInfo
?.meteringPerTransaction
?? true;
308 public getTransactionDataMeterValues(): boolean {
309 return this.stationInfo
?.transactionDataMeterValues
?? false;
312 public getMainVoltageMeterValues(): boolean {
313 return this.stationInfo
?.mainVoltageMeterValues
?? true;
316 public getPhaseLineToLineVoltageMeterValues(): boolean {
317 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
320 public getCustomValueLimitationMeterValues(): boolean {
321 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
324 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
325 for (const connectorId
of this.connectors
.keys()) {
328 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
335 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
336 const transactionConnectorStatus
= this.getConnectorStatus(
337 this.getConnectorIdByTransactionId(transactionId
)
339 if (this.getMeteringPerTransaction()) {
340 return transactionConnectorStatus
?.transactionEnergyActiveImportRegisterValue
;
342 return transactionConnectorStatus
?.energyActiveImportRegisterValue
;
345 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
346 const connectorStatus
= this.getConnectorStatus(connectorId
);
347 if (this.getMeteringPerTransaction()) {
348 return connectorStatus
?.transactionEnergyActiveImportRegisterValue
;
350 return connectorStatus
?.energyActiveImportRegisterValue
;
353 public getAuthorizeRemoteTxRequests(): boolean {
354 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
356 StandardParametersKey
.AuthorizeRemoteTxRequests
358 return authorizeRemoteTxRequests
359 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
363 public getLocalAuthListEnabled(): boolean {
364 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
366 StandardParametersKey
.LocalAuthListEnabled
368 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
371 public startHeartbeat(): void {
373 this.getHeartbeatInterval() &&
374 this.getHeartbeatInterval() > 0 &&
375 !this.heartbeatSetInterval
377 // eslint-disable-next-line @typescript-eslint/no-misused-promises
378 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
379 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
381 RequestCommand
.HEARTBEAT
383 }, this.getHeartbeatInterval());
386 ' Heartbeat started every ' +
387 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
389 } else if (this.heartbeatSetInterval
) {
392 ' Heartbeat already started every ' +
393 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
397 `${this.logPrefix()} Heartbeat interval set to ${
398 this.getHeartbeatInterval()
399 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
400 : this.getHeartbeatInterval()
401 }, not starting the heartbeat`
406 public restartHeartbeat(): void {
408 this.stopHeartbeat();
410 this.startHeartbeat();
413 public restartWebSocketPing(): void {
414 // Stop WebSocket ping
415 this.stopWebSocketPing();
416 // Start WebSocket ping
417 this.startWebSocketPing();
420 public startMeterValues(connectorId
: number, interval
: number): void {
421 if (connectorId
=== 0) {
423 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
427 if (!this.getConnectorStatus(connectorId
)) {
429 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
433 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
435 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
439 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
440 !this.getConnectorStatus(connectorId
)?.transactionId
443 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
448 // eslint-disable-next-line @typescript-eslint/no-misused-promises
449 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
450 // eslint-disable-next-line @typescript-eslint/no-misused-promises
451 async (): Promise
<void> => {
452 // FIXME: Implement OCPP version agnostic helpers
453 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
456 this.getConnectorStatus(connectorId
).transactionId
,
459 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
461 RequestCommand
.METER_VALUES
,
464 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
465 meterValue
: [meterValue
],
473 `${this.logPrefix()} Charging station ${
474 StandardParametersKey.MeterValueSampleInterval
475 } configuration set to ${
476 interval ? Utils.formatDurationMilliSeconds(interval) : interval
477 }, not sending MeterValues`
482 public start(): void {
483 if (this.getEnableStatistics()) {
484 this.performanceStatistics
.start();
486 this.openWSConnection();
487 // Monitor charging station template file
488 this.templateFileWatcher
= FileUtils
.watchJsonFile(
490 FileType
.ChargingStationTemplate
,
493 (event
, filename
): void => {
494 if (filename
&& event
=== 'change') {
497 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
499 } file have changed, reload`
501 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
505 this.stopAutomaticTransactionGenerator();
506 this.startAutomaticTransactionGenerator();
507 if (this.getEnableStatistics()) {
508 this.performanceStatistics
.restart();
510 this.performanceStatistics
.stop();
512 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
515 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
522 parentPort
.postMessage({
523 id
: ChargingStationWorkerMessageEvents
.STARTED
,
524 data
: { id
: this.stationInfo
.chargingStationId
},
528 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
529 // Stop message sequence
530 await this.stopMessageSequence(reason
);
531 for (const connectorId
of this.connectors
.keys()) {
532 if (connectorId
> 0) {
533 await this.ocppRequestService
.requestHandler
<
534 StatusNotificationRequest
,
535 StatusNotificationResponse
536 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
538 status: ChargePointStatus
.UNAVAILABLE
,
539 errorCode
: ChargePointErrorCode
.NO_ERROR
,
541 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
544 this.closeWSConnection();
545 if (this.getEnableStatistics()) {
546 this.performanceStatistics
.stop();
548 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
549 this.templateFileWatcher
.close();
550 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
551 this.bootNotificationResponse
= null;
552 parentPort
.postMessage({
553 id
: ChargingStationWorkerMessageEvents
.STOPPED
,
554 data
: { id
: this.stationInfo
.chargingStationId
},
559 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
560 await this.stop(reason
);
561 await Utils
.sleep(this.stationInfo
.resetTime
);
566 public saveOcppConfiguration(): void {
567 if (this.getOcppPersistentConfiguration()) {
568 this.saveConfiguration();
572 public getChargingProfilePowerLimit(connectorId
: number): number | undefined {
573 let limit
: number, matchingChargingProfile
: ChargingProfile
;
574 let chargingProfiles
: ChargingProfile
[] = [];
575 // Get charging profiles for connector and sort by stack level
576 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
577 (a
, b
) => b
.stackLevel
- a
.stackLevel
579 // Get profiles on connector 0
580 if (this.getConnectorStatus(0).chargingProfiles
) {
581 chargingProfiles
.push(
582 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
585 if (!Utils
.isEmptyArray(chargingProfiles
)) {
586 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
590 if (!Utils
.isNullOrUndefined(result
)) {
591 limit
= result
.limit
;
592 matchingChargingProfile
= result
.matchingChargingProfile
;
593 switch (this.getCurrentOutType()) {
596 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
597 ChargingRateUnitType
.WATT
599 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
603 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
604 ChargingRateUnitType
.WATT
606 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
609 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
610 if (limit
> connectorMaximumPower
) {
612 `${this.logPrefix()} Charging profile id ${
613 matchingChargingProfile.chargingProfileId
614 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
615 this.getConnectorStatus(connectorId
).chargingProfiles
617 limit
= connectorMaximumPower
;
624 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
625 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
627 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
629 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
631 if (!Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
633 `${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`
635 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
637 let cpReplaced
= false;
638 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
639 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
640 (chargingProfile
: ChargingProfile
, index
: number) => {
642 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
643 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
644 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
646 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
652 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
655 public resetConnectorStatus(connectorId
: number): void {
656 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
657 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
658 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
659 this.getConnectorStatus(connectorId
).transactionStarted
= false;
660 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
661 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
662 delete this.getConnectorStatus(connectorId
).transactionId
;
663 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
664 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
665 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
666 this.stopMeterValues(connectorId
);
669 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
670 return ChargingStationConfigurationUtils
.getConfigurationKey(
672 StandardParametersKey
.SupportedFeatureProfiles
673 )?.value
.includes(featureProfile
);
676 public bufferMessage(message
: string): void {
677 this.messageBuffer
.add(message
);
680 private flushMessageBuffer() {
681 if (this.messageBuffer
.size
> 0) {
682 this.messageBuffer
.forEach((message
) => {
683 // TODO: evaluate the need to track performance
684 this.wsConnection
.send(message
);
685 this.messageBuffer
.delete(message
);
690 private getSupervisionUrlOcppConfiguration(): boolean {
691 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
694 private getSupervisionUrlOcppKey(): string {
695 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
698 private getTemplateFromFile(): ChargingStationTemplate
| null {
699 let template
: ChargingStationTemplate
= null;
701 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
702 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
704 const measureId
= `${FileType.ChargingStationTemplate} read`;
705 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
706 template
= JSON
.parse(
707 fs
.readFileSync(this.templateFile
, 'utf8')
708 ) as ChargingStationTemplate
;
709 PerformanceStatistics
.endMeasure(measureId
, beginId
);
710 template
.templateHash
= crypto
711 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
712 .update(JSON
.stringify(template
))
714 this.sharedLRUCache
.setChargingStationTemplate(template
);
717 FileUtils
.handleFileException(
719 FileType
.ChargingStationTemplate
,
721 error
as NodeJS
.ErrnoException
727 private getStationInfoFromTemplate(): ChargingStationInfo
{
728 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
729 if (Utils
.isNullOrUndefined(stationTemplate
)) {
730 const errorMsg
= 'Failed to read charging station template file';
731 logger
.error(`${this.logPrefix()} ${errorMsg}`);
732 throw new BaseError(errorMsg
);
734 if (Utils
.isEmptyObject(stationTemplate
)) {
735 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
736 logger
.error(`${this.logPrefix()} ${errorMsg}`);
737 throw new BaseError(errorMsg
);
739 // Deprecation template keys section
740 ChargingStationUtils
.warnDeprecatedTemplateKey(
745 "Use 'supervisionUrls' instead"
747 ChargingStationUtils
.convertDeprecatedTemplateKey(
752 const stationInfo
: ChargingStationInfo
=
753 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
754 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
758 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
759 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
760 stationTemplate
.power
= stationTemplate
.power
as number[];
761 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
762 stationInfo
.maximumPower
=
763 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
764 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
765 : stationTemplate
.power
[powerArrayRandomIndex
];
767 stationTemplate
.power
= stationTemplate
.power
as number;
768 stationInfo
.maximumPower
=
769 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
770 ? stationTemplate
.power
* 1000
771 : stationTemplate
.power
;
773 stationInfo
.resetTime
= stationTemplate
.resetTime
774 ? stationTemplate
.resetTime
* 1000
775 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
776 const configuredMaxConnectors
= ChargingStationUtils
.getConfiguredNumberOfConnectors(
780 ChargingStationUtils
.checkConfiguredMaxConnectors(
781 configuredMaxConnectors
,
785 const templateMaxConnectors
=
786 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
787 ChargingStationUtils
.checkTemplateMaxConnectors(
788 templateMaxConnectors
,
793 configuredMaxConnectors
>
794 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
795 !stationTemplate
?.randomConnectors
798 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
800 }, forcing random connector configurations affectation`
802 stationInfo
.randomConnectors
= true;
804 // Build connectors if needed (FIXME: should be factored out)
805 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
806 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
807 ChargingStationUtils
.createStationInfoHash(stationInfo
);
811 private getStationInfoFromFile(): ChargingStationInfo
| null {
812 let stationInfo
: ChargingStationInfo
= null;
813 this.getStationInfoPersistentConfiguration() &&
814 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
815 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
819 private getStationInfo(): ChargingStationInfo
{
820 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
821 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
822 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
823 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
824 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
825 return this.stationInfo
;
827 return stationInfoFromFile
;
829 stationInfoFromFile
&&
830 ChargingStationUtils
.propagateSerialNumber(
831 this.getTemplateFromFile(),
833 stationInfoFromTemplate
835 return stationInfoFromTemplate
;
838 private saveStationInfo(): void {
839 if (this.getStationInfoPersistentConfiguration()) {
840 this.saveConfiguration();
844 private getOcppVersion(): OCPPVersion
{
845 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
848 private getOcppPersistentConfiguration(): boolean {
849 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
852 private getStationInfoPersistentConfiguration(): boolean {
853 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
856 private handleUnsupportedVersion(version
: OCPPVersion
) {
857 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
860 logger
.error(errMsg
);
861 throw new Error(errMsg
);
864 private initialize(): void {
865 this.hashId
= ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile());
866 logger
.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
867 this.configurationFile
= path
.join(
868 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
869 this.hashId
+ '.json'
871 this.stationInfo
= this.getStationInfo();
872 this.saveStationInfo();
873 // Avoid duplication of connectors related information in RAM
874 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
875 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
876 if (this.getEnableStatistics()) {
877 this.performanceStatistics
= PerformanceStatistics
.getInstance(
879 this.stationInfo
.chargingStationId
,
880 this.configuredSupervisionUrl
883 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
886 this.powerDivider
= this.getPowerDivider();
887 // OCPP configuration
888 this.ocppConfiguration
= this.getOcppConfiguration();
889 this.initializeOcppConfiguration();
890 switch (this.getOcppVersion()) {
891 case OCPPVersion
.VERSION_16
:
892 this.ocppIncomingRequestService
=
893 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
894 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
895 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
899 this.handleUnsupportedVersion(this.getOcppVersion());
902 if (this.stationInfo
?.autoRegister
) {
903 this.bootNotificationResponse
= {
904 currentTime
: new Date().toISOString(),
905 interval
: this.getHeartbeatInterval() / 1000,
906 status: RegistrationStatus
.ACCEPTED
,
911 private initializeOcppConfiguration(): void {
913 !ChargingStationConfigurationUtils
.getConfigurationKey(
915 StandardParametersKey
.HeartbeatInterval
918 ChargingStationConfigurationUtils
.addConfigurationKey(
920 StandardParametersKey
.HeartbeatInterval
,
925 !ChargingStationConfigurationUtils
.getConfigurationKey(
927 StandardParametersKey
.HeartBeatInterval
930 ChargingStationConfigurationUtils
.addConfigurationKey(
932 StandardParametersKey
.HeartBeatInterval
,
938 this.getSupervisionUrlOcppConfiguration() &&
939 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
941 ChargingStationConfigurationUtils
.addConfigurationKey(
943 this.getSupervisionUrlOcppKey(),
944 this.configuredSupervisionUrl
.href
,
948 !this.getSupervisionUrlOcppConfiguration() &&
949 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
951 ChargingStationConfigurationUtils
.deleteConfigurationKey(
953 this.getSupervisionUrlOcppKey(),
958 this.stationInfo
.amperageLimitationOcppKey
&&
959 !ChargingStationConfigurationUtils
.getConfigurationKey(
961 this.stationInfo
.amperageLimitationOcppKey
964 ChargingStationConfigurationUtils
.addConfigurationKey(
966 this.stationInfo
.amperageLimitationOcppKey
,
968 this.stationInfo
.maximumAmperage
*
969 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
974 !ChargingStationConfigurationUtils
.getConfigurationKey(
976 StandardParametersKey
.SupportedFeatureProfiles
979 ChargingStationConfigurationUtils
.addConfigurationKey(
981 StandardParametersKey
.SupportedFeatureProfiles
,
982 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
985 ChargingStationConfigurationUtils
.addConfigurationKey(
987 StandardParametersKey
.NumberOfConnectors
,
988 this.getNumberOfConnectors().toString(),
993 !ChargingStationConfigurationUtils
.getConfigurationKey(
995 StandardParametersKey
.MeterValuesSampledData
998 ChargingStationConfigurationUtils
.addConfigurationKey(
1000 StandardParametersKey
.MeterValuesSampledData
,
1001 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1005 !ChargingStationConfigurationUtils
.getConfigurationKey(
1007 StandardParametersKey
.ConnectorPhaseRotation
1010 const connectorPhaseRotation
= [];
1011 for (const connectorId
of this.connectors
.keys()) {
1013 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1014 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1015 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1016 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1018 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1019 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1020 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1021 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1024 ChargingStationConfigurationUtils
.addConfigurationKey(
1026 StandardParametersKey
.ConnectorPhaseRotation
,
1027 connectorPhaseRotation
.toString()
1031 !ChargingStationConfigurationUtils
.getConfigurationKey(
1033 StandardParametersKey
.AuthorizeRemoteTxRequests
1036 ChargingStationConfigurationUtils
.addConfigurationKey(
1038 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1043 !ChargingStationConfigurationUtils
.getConfigurationKey(
1045 StandardParametersKey
.LocalAuthListEnabled
1047 ChargingStationConfigurationUtils
.getConfigurationKey(
1049 StandardParametersKey
.SupportedFeatureProfiles
1050 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1052 ChargingStationConfigurationUtils
.addConfigurationKey(
1054 StandardParametersKey
.LocalAuthListEnabled
,
1059 !ChargingStationConfigurationUtils
.getConfigurationKey(
1061 StandardParametersKey
.ConnectionTimeOut
1064 ChargingStationConfigurationUtils
.addConfigurationKey(
1066 StandardParametersKey
.ConnectionTimeOut
,
1067 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1070 this.saveOcppConfiguration();
1073 private initializeConnectors(
1074 stationInfo
: ChargingStationInfo
,
1075 configuredMaxConnectors
: number,
1076 templateMaxConnectors
: number
1078 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1079 const logMsg
= `${this.logPrefix()} No already defined connectors and charging station information from template ${
1081 } with no connectors configuration defined`;
1082 logger
.error(logMsg
);
1083 throw new BaseError(logMsg
);
1085 if (!stationInfo
?.Connectors
[0]) {
1087 `${this.logPrefix()} Charging station information from template ${
1089 } with no connector Id 0 configuration`
1092 if (stationInfo
?.Connectors
) {
1093 const connectorsConfigHash
= crypto
1094 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1095 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1097 const connectorsConfigChanged
=
1098 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1099 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1100 connectorsConfigChanged
&& this.connectors
.clear();
1101 this.connectorsConfigurationHash
= connectorsConfigHash
;
1102 // Add connector Id 0
1103 let lastConnector
= '0';
1104 for (lastConnector
in stationInfo
?.Connectors
) {
1105 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1107 lastConnectorId
=== 0 &&
1108 this.getUseConnectorId0(stationInfo
) &&
1109 stationInfo
?.Connectors
[lastConnector
]
1111 this.connectors
.set(
1113 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1115 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1116 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1117 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1121 // Generate all connectors
1122 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1123 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1124 const randConnectorId
= stationInfo
?.randomConnectors
1125 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1127 this.connectors
.set(
1129 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1131 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1132 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1133 this.getConnectorStatus(index
).chargingProfiles
= [];
1140 `${this.logPrefix()} Charging station information from template ${
1142 } with no connectors configuration defined, using already defined connectors`
1145 // Initialize transaction attributes on connectors
1146 for (const connectorId
of this.connectors
.keys()) {
1147 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1148 this.initializeConnectorStatus(connectorId
);
1153 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1154 let configuration
: ChargingStationConfiguration
= null;
1155 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1157 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1158 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1159 this.configurationFileHash
1162 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1163 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1164 configuration
= JSON
.parse(
1165 fs
.readFileSync(this.configurationFile
, 'utf8')
1166 ) as ChargingStationConfiguration
;
1167 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1168 this.configurationFileHash
= configuration
.configurationHash
;
1169 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1172 FileUtils
.handleFileException(
1174 FileType
.ChargingStationConfiguration
,
1175 this.configurationFile
,
1176 error
as NodeJS
.ErrnoException
1180 return configuration
;
1183 private saveConfiguration(): void {
1184 if (this.configurationFile
) {
1186 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1187 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1189 const configurationData
: ChargingStationConfiguration
=
1190 this.getConfigurationFromFile() ?? {};
1191 this.ocppConfiguration
?.configurationKey
&&
1192 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1193 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1194 delete configurationData
.configurationHash
;
1195 const configurationHash
= crypto
1196 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1197 .update(JSON
.stringify(configurationData
))
1199 if (this.configurationFileHash
!== configurationHash
) {
1200 configurationData
.configurationHash
= configurationHash
;
1201 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1202 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1203 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1204 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1205 fs
.closeSync(fileDescriptor
);
1206 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1207 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1208 this.configurationFileHash
= configurationHash
;
1209 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1212 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1213 this.configurationFile
1218 FileUtils
.handleFileException(
1220 FileType
.ChargingStationConfiguration
,
1221 this.configurationFile
,
1222 error
as NodeJS
.ErrnoException
1227 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1232 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1233 return this.getTemplateFromFile()?.Configuration
?? null;
1236 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1237 let configuration
: ChargingStationConfiguration
= null;
1238 if (this.getOcppPersistentConfiguration()) {
1239 const configurationFromFile
= this.getConfigurationFromFile();
1240 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1242 configuration
&& delete configuration
.stationInfo
;
1243 return configuration
;
1246 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1247 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1248 if (!ocppConfiguration
) {
1249 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1251 return ocppConfiguration
;
1254 private async onOpen(): Promise
<void> {
1255 if (this.isWebSocketConnectionOpened()) {
1257 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1259 if (!this.isRegistered()) {
1260 // Send BootNotification
1261 let registrationRetryCount
= 0;
1263 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1264 BootNotificationRequest
,
1265 BootNotificationResponse
1268 RequestCommand
.BOOT_NOTIFICATION
,
1270 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1271 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1272 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1273 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1274 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1275 iccid
: this.bootNotificationRequest
.iccid
,
1276 imsi
: this.bootNotificationRequest
.imsi
,
1277 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1278 meterType
: this.bootNotificationRequest
.meterType
,
1280 { skipBufferingOnError
: true }
1282 if (!this.isRegistered()) {
1283 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1285 this.bootNotificationResponse
?.interval
1286 ? this.bootNotificationResponse
.interval
* 1000
1287 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1291 !this.isRegistered() &&
1292 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1293 this.getRegistrationMaxRetries() === -1)
1296 if (this.isRegistered()) {
1297 if (this.isInAcceptedState()) {
1298 await this.startMessageSequence();
1299 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1303 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1306 this.stopped
&& (this.stopped
= false);
1307 this.autoReconnectRetryCount
= 0;
1308 this.wsConnectionRestarted
= false;
1311 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1316 private async onClose(code
: number, reason
: string): Promise
<void> {
1319 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1320 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1322 `${this.logPrefix()} WebSocket normally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1324 )}' and reason '${reason}'`
1326 this.autoReconnectRetryCount
= 0;
1331 `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1333 )}' and reason '${reason}'`
1335 await this.reconnect(code
);
1340 private async onMessage(data
: Data
): Promise
<void> {
1341 let messageType
: number;
1342 let messageId
: string;
1343 let commandName
: IncomingRequestCommand
;
1344 let commandPayload
: JsonType
;
1345 let errorType
: ErrorType
;
1346 let errorMessage
: string;
1347 let errorDetails
: JsonType
;
1348 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1349 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1350 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1351 let requestPayload
: JsonType
;
1352 let cachedRequest
: CachedRequest
;
1355 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1356 if (Utils
.isIterable(request
)) {
1357 [messageType
, messageId
] = request
;
1358 // Check the type of message
1359 switch (messageType
) {
1361 case MessageType
.CALL_MESSAGE
:
1362 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1363 if (this.getEnableStatistics()) {
1364 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1367 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1371 // Process the message
1372 await this.ocppIncomingRequestService
.incomingRequestHandler(
1380 case MessageType
.CALL_RESULT_MESSAGE
:
1381 [, , commandPayload
] = request
as Response
;
1382 if (!this.requests
.has(messageId
)) {
1384 throw new OCPPError(
1385 ErrorType
.INTERNAL_ERROR
,
1386 `Response for unknown message id ${messageId}`,
1392 cachedRequest
= this.requests
.get(messageId
);
1393 if (Utils
.isIterable(cachedRequest
)) {
1394 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1396 throw new OCPPError(
1397 ErrorType
.PROTOCOL_ERROR
,
1398 `Cached request for message id ${messageId} response is not iterable`,
1400 cachedRequest
as unknown
as JsonType
1404 `${this.logPrefix()} << Command '${
1405 requestCommandName ?? 'unknown'
1406 }' received response payload: ${JSON.stringify(request)}`
1408 responseCallback(commandPayload
, requestPayload
);
1411 case MessageType
.CALL_ERROR_MESSAGE
:
1412 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1413 if (!this.requests
.has(messageId
)) {
1415 throw new OCPPError(
1416 ErrorType
.INTERNAL_ERROR
,
1417 `Error response for unknown message id ${messageId}`,
1419 { errorType
, errorMessage
, errorDetails
}
1422 cachedRequest
= this.requests
.get(messageId
);
1423 if (Utils
.isIterable(cachedRequest
)) {
1424 [, errorCallback
, requestCommandName
] = cachedRequest
;
1426 throw new OCPPError(
1427 ErrorType
.PROTOCOL_ERROR
,
1428 `Cached request for message id ${messageId} error response is not iterable`,
1430 cachedRequest
as unknown
as JsonType
1434 `${this.logPrefix()} << Command '${
1435 requestCommandName ?? 'unknown'
1436 }' received error payload: ${JSON.stringify(request)}`
1438 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1442 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1443 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
1444 logger
.error(errMsg
);
1445 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1448 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not iterable', null, {
1455 "%s Incoming OCPP '%s' message '%j' matching cached request '%j' processing error: %j",
1457 commandName
?? requestCommandName
?? null,
1459 this.requests
.get(messageId
),
1462 if (!(error
instanceof OCPPError
)) {
1464 "%s Error thrown at incoming OCPP '%s' message '%j' handling is not an OCPPError: %j",
1466 commandName
?? requestCommandName
?? null,
1472 messageType
=== MessageType
.CALL_MESSAGE
&&
1473 (await this.ocppRequestService
.sendError(
1477 commandName
?? requestCommandName
?? null
1482 private onPing(): void {
1483 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1486 private onPong(): void {
1487 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1490 private onError(error
: WSError
): void {
1491 this.closeWSConnection();
1492 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
1495 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean | undefined {
1496 const localStationInfo
= stationInfo
?? this.stationInfo
;
1497 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1498 ? localStationInfo
.useConnectorId0
1502 private getNumberOfRunningTransactions(): number {
1504 for (const connectorId
of this.connectors
.keys()) {
1505 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1513 private getConnectionTimeout(): number | undefined {
1515 ChargingStationConfigurationUtils
.getConfigurationKey(
1517 StandardParametersKey
.ConnectionTimeOut
1522 ChargingStationConfigurationUtils
.getConfigurationKey(
1524 StandardParametersKey
.ConnectionTimeOut
1526 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1529 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1532 // -1 for unlimited, 0 for disabling
1533 private getAutoReconnectMaxRetries(): number | undefined {
1534 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1535 return this.stationInfo
.autoReconnectMaxRetries
;
1537 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1538 return Configuration
.getAutoReconnectMaxRetries();
1544 private getRegistrationMaxRetries(): number | undefined {
1545 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1546 return this.stationInfo
.registrationMaxRetries
;
1551 private getPowerDivider(): number {
1552 let powerDivider
= this.getNumberOfConnectors();
1553 if (this.stationInfo
?.powerSharedByConnectors
) {
1554 powerDivider
= this.getNumberOfRunningTransactions();
1556 return powerDivider
;
1559 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1560 const localStationInfo
= stationInfo
?? this.stationInfo
;
1561 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1564 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1565 const maximumPower
= this.getMaximumPower(stationInfo
);
1566 switch (this.getCurrentOutType(stationInfo
)) {
1567 case CurrentType
.AC
:
1568 return ACElectricUtils
.amperagePerPhaseFromPower(
1569 this.getNumberOfPhases(stationInfo
),
1570 maximumPower
/ this.getNumberOfConnectors(),
1571 this.getVoltageOut(stationInfo
)
1573 case CurrentType
.DC
:
1574 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1578 private getAmperageLimitation(): number | undefined {
1580 this.stationInfo
.amperageLimitationOcppKey
&&
1581 ChargingStationConfigurationUtils
.getConfigurationKey(
1583 this.stationInfo
.amperageLimitationOcppKey
1588 ChargingStationConfigurationUtils
.getConfigurationKey(
1590 this.stationInfo
.amperageLimitationOcppKey
1592 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1597 private async startMessageSequence(): Promise
<void> {
1598 if (this.stationInfo
?.autoRegister
) {
1599 await this.ocppRequestService
.requestHandler
<
1600 BootNotificationRequest
,
1601 BootNotificationResponse
1604 RequestCommand
.BOOT_NOTIFICATION
,
1606 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1607 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1608 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1609 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1610 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1611 iccid
: this.bootNotificationRequest
.iccid
,
1612 imsi
: this.bootNotificationRequest
.imsi
,
1613 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1614 meterType
: this.bootNotificationRequest
.meterType
,
1616 { skipBufferingOnError
: true }
1619 // Start WebSocket ping
1620 this.startWebSocketPing();
1622 this.startHeartbeat();
1623 // Initialize connectors status
1624 for (const connectorId
of this.connectors
.keys()) {
1625 if (connectorId
=== 0) {
1629 !this.getConnectorStatus(connectorId
)?.status &&
1630 this.getConnectorStatus(connectorId
)?.bootStatus
1632 // Send status in template at startup
1633 await this.ocppRequestService
.requestHandler
<
1634 StatusNotificationRequest
,
1635 StatusNotificationResponse
1636 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1638 status: this.getConnectorStatus(connectorId
).bootStatus
,
1639 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1641 this.getConnectorStatus(connectorId
).status =
1642 this.getConnectorStatus(connectorId
).bootStatus
;
1645 this.getConnectorStatus(connectorId
)?.status &&
1646 this.getConnectorStatus(connectorId
)?.bootStatus
1648 // Send status in template after reset
1649 await this.ocppRequestService
.requestHandler
<
1650 StatusNotificationRequest
,
1651 StatusNotificationResponse
1652 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1654 status: this.getConnectorStatus(connectorId
).bootStatus
,
1655 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1657 this.getConnectorStatus(connectorId
).status =
1658 this.getConnectorStatus(connectorId
).bootStatus
;
1659 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1660 // Send previous status at template reload
1661 await this.ocppRequestService
.requestHandler
<
1662 StatusNotificationRequest
,
1663 StatusNotificationResponse
1664 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1666 status: this.getConnectorStatus(connectorId
).status,
1667 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1670 // Send default status
1671 await this.ocppRequestService
.requestHandler
<
1672 StatusNotificationRequest
,
1673 StatusNotificationResponse
1674 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1676 status: ChargePointStatus
.AVAILABLE
,
1677 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1679 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1683 this.startAutomaticTransactionGenerator();
1686 private startAutomaticTransactionGenerator() {
1687 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
) {
1688 if (!this.automaticTransactionGenerator
) {
1689 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
1690 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
1694 if (!this.automaticTransactionGenerator
.started
) {
1695 this.automaticTransactionGenerator
.start();
1700 private stopAutomaticTransactionGenerator(): void {
1701 if (this.automaticTransactionGenerator
?.started
) {
1702 this.automaticTransactionGenerator
.stop();
1703 this.automaticTransactionGenerator
= null;
1707 private async stopMessageSequence(
1708 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1710 // Stop WebSocket ping
1711 this.stopWebSocketPing();
1713 this.stopHeartbeat();
1714 // Stop ongoing transactions
1715 if (this.automaticTransactionGenerator
?.configuration
?.enable
) {
1716 this.stopAutomaticTransactionGenerator();
1718 for (const connectorId
of this.connectors
.keys()) {
1719 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1720 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1722 this.getBeginEndMeterValues() &&
1723 this.getOcppStrictCompliance() &&
1724 !this.getOutOfOrderEndMeterValues()
1726 // FIXME: Implement OCPP version agnostic helpers
1727 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1730 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1732 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
1734 RequestCommand
.METER_VALUES
,
1738 meterValue
: [transactionEndMeterValue
],
1742 await this.ocppRequestService
.requestHandler
<
1743 StopTransactionRequest
,
1744 StopTransactionResponse
1745 >(this, RequestCommand
.STOP_TRANSACTION
, {
1747 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1748 idTag
: this.getTransactionIdTag(transactionId
),
1756 private startWebSocketPing(): void {
1757 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1759 StandardParametersKey
.WebSocketPingInterval
1761 ? Utils
.convertToInt(
1762 ChargingStationConfigurationUtils
.getConfigurationKey(
1764 StandardParametersKey
.WebSocketPingInterval
1768 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1769 this.webSocketPingSetInterval
= setInterval(() => {
1770 if (this.isWebSocketConnectionOpened()) {
1771 this.wsConnection
.ping((): void => {
1772 /* This is intentional */
1775 }, webSocketPingInterval
* 1000);
1778 ' WebSocket ping started every ' +
1779 Utils
.formatDurationSeconds(webSocketPingInterval
)
1781 } else if (this.webSocketPingSetInterval
) {
1784 ' WebSocket ping every ' +
1785 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1790 `${this.logPrefix()} WebSocket ping interval set to ${
1791 webSocketPingInterval
1792 ? Utils.formatDurationSeconds(webSocketPingInterval)
1793 : webSocketPingInterval
1794 }, not starting the WebSocket ping`
1799 private stopWebSocketPing(): void {
1800 if (this.webSocketPingSetInterval
) {
1801 clearInterval(this.webSocketPingSetInterval
);
1805 private getConfiguredSupervisionUrl(): URL
{
1806 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1807 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1809 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1811 switch (Configuration
.getSupervisionUrlDistribution()) {
1812 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1813 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1815 case SupervisionUrlDistribution
.RANDOM
:
1817 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1819 case SupervisionUrlDistribution
.SEQUENTIAL
:
1820 if (this.index
<= supervisionUrls
.length
) {
1821 urlIndex
= this.index
- 1;
1824 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1830 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1831 SupervisionUrlDistribution.ROUND_ROBIN
1834 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1837 return new URL(supervisionUrls
[urlIndex
]);
1839 return new URL(supervisionUrls
as string);
1842 private getHeartbeatInterval(): number | undefined {
1843 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1845 StandardParametersKey
.HeartbeatInterval
1847 if (HeartbeatInterval
) {
1848 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1850 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1852 StandardParametersKey
.HeartBeatInterval
1854 if (HeartBeatInterval
) {
1855 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1857 !this.stationInfo
?.autoRegister
&&
1859 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1860 Constants.DEFAULT_HEARTBEAT_INTERVAL
1863 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1866 private stopHeartbeat(): void {
1867 if (this.heartbeatSetInterval
) {
1868 clearInterval(this.heartbeatSetInterval
);
1872 private openWSConnection(
1873 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
1874 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
1876 terminateOpened
: false,
1879 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
1880 params
.closeOpened
= params
?.closeOpened
?? false;
1881 params
.terminateOpened
= params
?.terminateOpened
?? false;
1883 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
1884 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
1886 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
1888 if (params
?.closeOpened
) {
1889 this.closeWSConnection();
1891 if (params
?.terminateOpened
) {
1892 this.terminateWSConnection();
1894 let protocol
: string;
1895 switch (this.getOcppVersion()) {
1896 case OCPPVersion
.VERSION_16
:
1897 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
1900 this.handleUnsupportedVersion(this.getOcppVersion());
1905 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString()
1908 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
1910 // Handle WebSocket message
1911 this.wsConnection
.on(
1913 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
1915 // Handle WebSocket error
1916 this.wsConnection
.on(
1918 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
1920 // Handle WebSocket close
1921 this.wsConnection
.on(
1923 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
1925 // Handle WebSocket open
1926 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
1927 // Handle WebSocket ping
1928 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
1929 // Handle WebSocket pong
1930 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
1933 private closeWSConnection(): void {
1934 if (this.isWebSocketConnectionOpened()) {
1935 this.wsConnection
.close();
1936 this.wsConnection
= null;
1940 private terminateWSConnection(): void {
1941 if (this.isWebSocketConnectionOpened()) {
1942 this.wsConnection
.terminate();
1943 this.wsConnection
= null;
1947 private stopMeterValues(connectorId
: number) {
1948 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1949 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1953 private getReconnectExponentialDelay(): boolean | undefined {
1954 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1955 ? this.stationInfo
.reconnectExponentialDelay
1959 private async reconnect(code
: number): Promise
<void> {
1960 // Stop WebSocket ping
1961 this.stopWebSocketPing();
1963 this.stopHeartbeat();
1964 // Stop the ATG if needed
1965 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
) {
1966 this.stopAutomaticTransactionGenerator();
1969 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1970 this.getAutoReconnectMaxRetries() === -1
1972 this.autoReconnectRetryCount
++;
1973 const reconnectDelay
= this.getReconnectExponentialDelay()
1974 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1975 : this.getConnectionTimeout() * 1000;
1976 const reconnectDelayWithdraw
= 1000;
1977 const reconnectTimeout
=
1978 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
1979 ? reconnectDelay
- reconnectDelayWithdraw
1982 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1985 )}ms, timeout ${reconnectTimeout}ms`
1987 await Utils
.sleep(reconnectDelay
);
1990 ' WebSocket: reconnecting try #' +
1991 this.autoReconnectRetryCount
.toString()
1993 this.openWSConnection(
1994 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
1995 { closeOpened
: true }
1997 this.wsConnectionRestarted
= true;
1998 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2000 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2001 this.autoReconnectRetryCount
2002 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2007 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
2008 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2011 private initializeConnectorStatus(connectorId
: number): void {
2012 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2013 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2014 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2015 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2016 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2017 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;