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 getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
182 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
183 switch (this.getCurrentOutType(stationInfo
)) {
185 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
186 ? localStationInfo
.numberOfPhases
193 public isWebSocketConnectionOpened(): boolean {
194 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
197 public getRegistrationStatus(): RegistrationStatus
{
198 return this?.bootNotificationResponse
?.status;
201 public isInUnknownState(): boolean {
202 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
205 public isInPendingState(): boolean {
206 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
209 public isInAcceptedState(): boolean {
210 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
213 public isInRejectedState(): boolean {
214 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
217 public isRegistered(): boolean {
218 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
221 public isChargingStationAvailable(): boolean {
222 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
225 public isConnectorAvailable(id
: number): boolean {
226 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
229 public getNumberOfConnectors(): number {
230 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
233 public getConnectorStatus(id
: number): ConnectorStatus
{
234 return this.connectors
.get(id
);
237 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
238 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
;
241 public getOcppStrictCompliance(): boolean {
242 return this.stationInfo
?.ocppStrictCompliance
?? false;
245 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
246 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
247 this.getCurrentOutType(stationInfo
),
251 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
252 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
253 ? localStationInfo
.voltageOut
257 public getConnectorMaximumAvailablePower(connectorId
: number): number {
258 let connectorAmperageLimitationPowerLimit
: number;
260 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
261 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
263 connectorAmperageLimitationPowerLimit
=
264 (this.getCurrentOutType() === CurrentType
.AC
265 ? ACElectricUtils
.powerTotal(
266 this.getNumberOfPhases(),
267 this.getVoltageOut(),
268 this.getAmperageLimitation() * this.getNumberOfConnectors()
270 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
273 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
274 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
276 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
277 isNaN(connectorAmperageLimitationPowerLimit
)
279 : connectorAmperageLimitationPowerLimit
,
280 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
284 public getTransactionIdTag(transactionId
: number): string | undefined {
285 for (const connectorId
of this.connectors
.keys()) {
286 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
287 return this.getConnectorStatus(connectorId
).transactionIdTag
;
292 public getOutOfOrderEndMeterValues(): boolean {
293 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
296 public getBeginEndMeterValues(): boolean {
297 return this.stationInfo
?.beginEndMeterValues
?? false;
300 public getMeteringPerTransaction(): boolean {
301 return this.stationInfo
?.meteringPerTransaction
?? true;
304 public getTransactionDataMeterValues(): boolean {
305 return this.stationInfo
?.transactionDataMeterValues
?? false;
308 public getMainVoltageMeterValues(): boolean {
309 return this.stationInfo
?.mainVoltageMeterValues
?? true;
312 public getPhaseLineToLineVoltageMeterValues(): boolean {
313 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
316 public getCustomValueLimitationMeterValues(): boolean {
317 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
320 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
321 for (const connectorId
of this.connectors
.keys()) {
324 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
331 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
332 const transactionConnectorStatus
= this.getConnectorStatus(
333 this.getConnectorIdByTransactionId(transactionId
)
335 if (this.getMeteringPerTransaction()) {
336 return transactionConnectorStatus
?.transactionEnergyActiveImportRegisterValue
;
338 return transactionConnectorStatus
?.energyActiveImportRegisterValue
;
341 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
342 const connectorStatus
= this.getConnectorStatus(connectorId
);
343 if (this.getMeteringPerTransaction()) {
344 return connectorStatus
?.transactionEnergyActiveImportRegisterValue
;
346 return connectorStatus
?.energyActiveImportRegisterValue
;
349 public getAuthorizeRemoteTxRequests(): boolean {
350 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
352 StandardParametersKey
.AuthorizeRemoteTxRequests
354 return authorizeRemoteTxRequests
355 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
359 public getLocalAuthListEnabled(): boolean {
360 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
362 StandardParametersKey
.LocalAuthListEnabled
364 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
367 public startHeartbeat(): void {
369 this.getHeartbeatInterval() &&
370 this.getHeartbeatInterval() > 0 &&
371 !this.heartbeatSetInterval
373 // eslint-disable-next-line @typescript-eslint/no-misused-promises
374 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
375 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
377 RequestCommand
.HEARTBEAT
379 }, this.getHeartbeatInterval());
382 ' Heartbeat started every ' +
383 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
385 } else if (this.heartbeatSetInterval
) {
388 ' Heartbeat already started every ' +
389 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
393 `${this.logPrefix()} Heartbeat interval set to ${
394 this.getHeartbeatInterval()
395 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
396 : this.getHeartbeatInterval()
397 }, not starting the heartbeat`
402 public restartHeartbeat(): void {
404 this.stopHeartbeat();
406 this.startHeartbeat();
409 public restartWebSocketPing(): void {
410 // Stop WebSocket ping
411 this.stopWebSocketPing();
412 // Start WebSocket ping
413 this.startWebSocketPing();
416 public startMeterValues(connectorId
: number, interval
: number): void {
417 if (connectorId
=== 0) {
419 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
423 if (!this.getConnectorStatus(connectorId
)) {
425 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
429 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
431 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
435 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
436 !this.getConnectorStatus(connectorId
)?.transactionId
439 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
444 // eslint-disable-next-line @typescript-eslint/no-misused-promises
445 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
446 // eslint-disable-next-line @typescript-eslint/no-misused-promises
447 async (): Promise
<void> => {
448 // FIXME: Implement OCPP version agnostic helpers
449 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
452 this.getConnectorStatus(connectorId
).transactionId
,
455 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
457 RequestCommand
.METER_VALUES
,
460 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
461 meterValue
: [meterValue
],
469 `${this.logPrefix()} Charging station ${
470 StandardParametersKey.MeterValueSampleInterval
471 } configuration set to ${
472 interval ? Utils.formatDurationMilliSeconds(interval) : interval
473 }, not sending MeterValues`
478 public start(): void {
479 if (this.getEnableStatistics()) {
480 this.performanceStatistics
.start();
482 this.openWSConnection();
483 // Monitor charging station template file
484 this.templateFileWatcher
= FileUtils
.watchJsonFile(
486 FileType
.ChargingStationTemplate
,
489 (event
, filename
): void => {
490 if (filename
&& event
=== 'change') {
493 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
495 } file have changed, reload`
497 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
501 this.stopAutomaticTransactionGenerator();
502 this.startAutomaticTransactionGenerator();
503 if (this.getEnableStatistics()) {
504 this.performanceStatistics
.restart();
506 this.performanceStatistics
.stop();
508 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
511 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
518 parentPort
.postMessage({
519 id
: ChargingStationWorkerMessageEvents
.STARTED
,
520 data
: { id
: this.stationInfo
.chargingStationId
},
524 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
525 // Stop message sequence
526 await this.stopMessageSequence(reason
);
527 for (const connectorId
of this.connectors
.keys()) {
528 if (connectorId
> 0) {
529 await this.ocppRequestService
.requestHandler
<
530 StatusNotificationRequest
,
531 StatusNotificationResponse
532 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
534 status: ChargePointStatus
.UNAVAILABLE
,
535 errorCode
: ChargePointErrorCode
.NO_ERROR
,
537 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
540 this.closeWSConnection();
541 if (this.getEnableStatistics()) {
542 this.performanceStatistics
.stop();
544 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
545 this.templateFileWatcher
.close();
546 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
547 this.bootNotificationResponse
= null;
548 parentPort
.postMessage({
549 id
: ChargingStationWorkerMessageEvents
.STOPPED
,
550 data
: { id
: this.stationInfo
.chargingStationId
},
555 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
556 await this.stop(reason
);
557 await Utils
.sleep(this.stationInfo
.resetTime
);
562 public saveOcppConfiguration(): void {
563 if (this.getOcppPersistentConfiguration()) {
564 this.saveConfiguration();
568 public getChargingProfilePowerLimit(connectorId
: number): number | undefined {
569 let limit
: number, matchingChargingProfile
: ChargingProfile
;
570 let chargingProfiles
: ChargingProfile
[] = [];
571 // Get charging profiles for connector and sort by stack level
572 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
573 (a
, b
) => b
.stackLevel
- a
.stackLevel
575 // Get profiles on connector 0
576 if (this.getConnectorStatus(0).chargingProfiles
) {
577 chargingProfiles
.push(
578 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
581 if (!Utils
.isEmptyArray(chargingProfiles
)) {
582 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
586 if (!Utils
.isNullOrUndefined(result
)) {
587 limit
= result
.limit
;
588 matchingChargingProfile
= result
.matchingChargingProfile
;
589 switch (this.getCurrentOutType()) {
592 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
593 ChargingRateUnitType
.WATT
595 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
599 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
600 ChargingRateUnitType
.WATT
602 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
605 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
606 if (limit
> connectorMaximumPower
) {
608 `${this.logPrefix()} Charging profile id ${
609 matchingChargingProfile.chargingProfileId
610 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
611 this.getConnectorStatus(connectorId
).chargingProfiles
613 limit
= connectorMaximumPower
;
620 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
621 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
623 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
625 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
627 if (!Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
629 `${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`
631 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
633 let cpReplaced
= false;
634 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
635 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
636 (chargingProfile
: ChargingProfile
, index
: number) => {
638 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
639 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
640 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
642 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
648 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
651 public resetConnectorStatus(connectorId
: number): void {
652 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
653 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
654 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
655 this.getConnectorStatus(connectorId
).transactionStarted
= false;
656 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
657 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
658 delete this.getConnectorStatus(connectorId
).transactionId
;
659 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
660 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
661 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
662 this.stopMeterValues(connectorId
);
665 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
666 return ChargingStationConfigurationUtils
.getConfigurationKey(
668 StandardParametersKey
.SupportedFeatureProfiles
669 )?.value
.includes(featureProfile
);
672 public bufferMessage(message
: string): void {
673 this.messageBuffer
.add(message
);
676 private flushMessageBuffer() {
677 if (this.messageBuffer
.size
> 0) {
678 this.messageBuffer
.forEach((message
) => {
679 // TODO: evaluate the need to track performance
680 this.wsConnection
.send(message
);
681 this.messageBuffer
.delete(message
);
686 private getSupervisionUrlOcppConfiguration(): boolean {
687 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
690 private getSupervisionUrlOcppKey(): string {
691 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
694 private getTemplateFromFile(): ChargingStationTemplate
| null {
695 let template
: ChargingStationTemplate
= null;
697 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
698 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
700 const measureId
= `${FileType.ChargingStationTemplate} read`;
701 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
702 template
= JSON
.parse(
703 fs
.readFileSync(this.templateFile
, 'utf8')
704 ) as ChargingStationTemplate
;
705 PerformanceStatistics
.endMeasure(measureId
, beginId
);
706 template
.templateHash
= crypto
707 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
708 .update(JSON
.stringify(template
))
710 this.sharedLRUCache
.setChargingStationTemplate(template
);
713 FileUtils
.handleFileException(
715 FileType
.ChargingStationTemplate
,
717 error
as NodeJS
.ErrnoException
723 private getStationInfoFromTemplate(): ChargingStationInfo
{
724 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
725 if (Utils
.isNullOrUndefined(stationTemplate
)) {
726 const errorMsg
= 'Failed to read charging station template file';
727 logger
.error(`${this.logPrefix()} ${errorMsg}`);
728 throw new BaseError(errorMsg
);
730 if (Utils
.isEmptyObject(stationTemplate
)) {
731 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
732 logger
.error(`${this.logPrefix()} ${errorMsg}`);
733 throw new BaseError(errorMsg
);
735 // Deprecation template keys section
736 ChargingStationUtils
.warnDeprecatedTemplateKey(
741 "Use 'supervisionUrls' instead"
743 ChargingStationUtils
.convertDeprecatedTemplateKey(
748 const stationInfo
: ChargingStationInfo
=
749 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
750 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
754 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
755 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
756 stationTemplate
.power
= stationTemplate
.power
as number[];
757 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
758 stationInfo
.maximumPower
=
759 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
760 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
761 : stationTemplate
.power
[powerArrayRandomIndex
];
763 stationTemplate
.power
= stationTemplate
.power
as number;
764 stationInfo
.maximumPower
=
765 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
766 ? stationTemplate
.power
* 1000
767 : stationTemplate
.power
;
769 stationInfo
.resetTime
= stationTemplate
.resetTime
770 ? stationTemplate
.resetTime
* 1000
771 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
772 const configuredMaxConnectors
= ChargingStationUtils
.getConfiguredNumberOfConnectors(
776 ChargingStationUtils
.checkConfiguredMaxConnectors(
777 configuredMaxConnectors
,
781 const templateMaxConnectors
=
782 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
783 ChargingStationUtils
.checkTemplateMaxConnectors(
784 templateMaxConnectors
,
789 configuredMaxConnectors
>
790 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
791 !stationTemplate
?.randomConnectors
794 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
796 }, forcing random connector configurations affectation`
798 stationInfo
.randomConnectors
= true;
800 // Build connectors if needed (FIXME: should be factored out)
801 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
802 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
803 ChargingStationUtils
.createStationInfoHash(stationInfo
);
807 private getStationInfoFromFile(): ChargingStationInfo
| null {
808 let stationInfo
: ChargingStationInfo
= null;
809 this.getStationInfoPersistentConfiguration() &&
810 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
811 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
815 private getStationInfo(): ChargingStationInfo
{
816 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
817 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
818 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
819 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
820 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
821 return this.stationInfo
;
823 return stationInfoFromFile
;
825 stationInfoFromFile
&&
826 ChargingStationUtils
.propagateSerialNumber(
827 this.getTemplateFromFile(),
829 stationInfoFromTemplate
831 return stationInfoFromTemplate
;
834 private saveStationInfo(): void {
835 if (this.getStationInfoPersistentConfiguration()) {
836 this.saveConfiguration();
840 private getOcppVersion(): OCPPVersion
{
841 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
844 private getOcppPersistentConfiguration(): boolean {
845 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
848 private getStationInfoPersistentConfiguration(): boolean {
849 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
852 private handleUnsupportedVersion(version
: OCPPVersion
) {
853 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
856 logger
.error(errMsg
);
857 throw new Error(errMsg
);
860 private initialize(): void {
861 this.hashId
= ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile());
862 logger
.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
863 this.configurationFile
= path
.join(
864 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
865 this.hashId
+ '.json'
867 this.stationInfo
= this.getStationInfo();
868 this.saveStationInfo();
869 // Avoid duplication of connectors related information in RAM
870 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
871 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
872 if (this.getEnableStatistics()) {
873 this.performanceStatistics
= PerformanceStatistics
.getInstance(
875 this.stationInfo
.chargingStationId
,
876 this.configuredSupervisionUrl
879 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
882 this.powerDivider
= this.getPowerDivider();
883 // OCPP configuration
884 this.ocppConfiguration
= this.getOcppConfiguration();
885 this.initializeOcppConfiguration();
886 switch (this.getOcppVersion()) {
887 case OCPPVersion
.VERSION_16
:
888 this.ocppIncomingRequestService
=
889 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
890 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
891 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
895 this.handleUnsupportedVersion(this.getOcppVersion());
898 if (this.stationInfo
?.autoRegister
) {
899 this.bootNotificationResponse
= {
900 currentTime
: new Date().toISOString(),
901 interval
: this.getHeartbeatInterval() / 1000,
902 status: RegistrationStatus
.ACCEPTED
,
907 private initializeOcppConfiguration(): void {
909 !ChargingStationConfigurationUtils
.getConfigurationKey(
911 StandardParametersKey
.HeartbeatInterval
914 ChargingStationConfigurationUtils
.addConfigurationKey(
916 StandardParametersKey
.HeartbeatInterval
,
921 !ChargingStationConfigurationUtils
.getConfigurationKey(
923 StandardParametersKey
.HeartBeatInterval
926 ChargingStationConfigurationUtils
.addConfigurationKey(
928 StandardParametersKey
.HeartBeatInterval
,
934 this.getSupervisionUrlOcppConfiguration() &&
935 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
937 ChargingStationConfigurationUtils
.addConfigurationKey(
939 this.getSupervisionUrlOcppKey(),
940 this.configuredSupervisionUrl
.href
,
944 !this.getSupervisionUrlOcppConfiguration() &&
945 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
947 ChargingStationConfigurationUtils
.deleteConfigurationKey(
949 this.getSupervisionUrlOcppKey(),
954 this.stationInfo
.amperageLimitationOcppKey
&&
955 !ChargingStationConfigurationUtils
.getConfigurationKey(
957 this.stationInfo
.amperageLimitationOcppKey
960 ChargingStationConfigurationUtils
.addConfigurationKey(
962 this.stationInfo
.amperageLimitationOcppKey
,
964 this.stationInfo
.maximumAmperage
*
965 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
970 !ChargingStationConfigurationUtils
.getConfigurationKey(
972 StandardParametersKey
.SupportedFeatureProfiles
975 ChargingStationConfigurationUtils
.addConfigurationKey(
977 StandardParametersKey
.SupportedFeatureProfiles
,
978 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
981 ChargingStationConfigurationUtils
.addConfigurationKey(
983 StandardParametersKey
.NumberOfConnectors
,
984 this.getNumberOfConnectors().toString(),
989 !ChargingStationConfigurationUtils
.getConfigurationKey(
991 StandardParametersKey
.MeterValuesSampledData
994 ChargingStationConfigurationUtils
.addConfigurationKey(
996 StandardParametersKey
.MeterValuesSampledData
,
997 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1001 !ChargingStationConfigurationUtils
.getConfigurationKey(
1003 StandardParametersKey
.ConnectorPhaseRotation
1006 const connectorPhaseRotation
= [];
1007 for (const connectorId
of this.connectors
.keys()) {
1009 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1010 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1011 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1012 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1014 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1015 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1016 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1017 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1020 ChargingStationConfigurationUtils
.addConfigurationKey(
1022 StandardParametersKey
.ConnectorPhaseRotation
,
1023 connectorPhaseRotation
.toString()
1027 !ChargingStationConfigurationUtils
.getConfigurationKey(
1029 StandardParametersKey
.AuthorizeRemoteTxRequests
1032 ChargingStationConfigurationUtils
.addConfigurationKey(
1034 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1039 !ChargingStationConfigurationUtils
.getConfigurationKey(
1041 StandardParametersKey
.LocalAuthListEnabled
1043 ChargingStationConfigurationUtils
.getConfigurationKey(
1045 StandardParametersKey
.SupportedFeatureProfiles
1046 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1048 ChargingStationConfigurationUtils
.addConfigurationKey(
1050 StandardParametersKey
.LocalAuthListEnabled
,
1055 !ChargingStationConfigurationUtils
.getConfigurationKey(
1057 StandardParametersKey
.ConnectionTimeOut
1060 ChargingStationConfigurationUtils
.addConfigurationKey(
1062 StandardParametersKey
.ConnectionTimeOut
,
1063 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1066 this.saveOcppConfiguration();
1069 private initializeConnectors(
1070 stationInfo
: ChargingStationInfo
,
1071 configuredMaxConnectors
: number,
1072 templateMaxConnectors
: number
1074 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1075 const logMsg
= `${this.logPrefix()} No already defined connectors and charging station information from template ${
1077 } with no connectors configuration defined`;
1078 logger
.error(logMsg
);
1079 throw new BaseError(logMsg
);
1081 if (!stationInfo
?.Connectors
[0]) {
1083 `${this.logPrefix()} Charging station information from template ${
1085 } with no connector Id 0 configuration`
1088 if (stationInfo
?.Connectors
) {
1089 const connectorsConfigHash
= crypto
1090 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1091 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1093 const connectorsConfigChanged
=
1094 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1095 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1096 connectorsConfigChanged
&& this.connectors
.clear();
1097 this.connectorsConfigurationHash
= connectorsConfigHash
;
1098 // Add connector Id 0
1099 let lastConnector
= '0';
1100 for (lastConnector
in stationInfo
?.Connectors
) {
1101 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1103 lastConnectorId
=== 0 &&
1104 this.getUseConnectorId0(stationInfo
) &&
1105 stationInfo
?.Connectors
[lastConnector
]
1107 this.connectors
.set(
1109 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1111 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1112 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1113 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1117 // Generate all connectors
1118 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1119 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1120 const randConnectorId
= stationInfo
?.randomConnectors
1121 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1123 this.connectors
.set(
1125 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1127 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1128 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1129 this.getConnectorStatus(index
).chargingProfiles
= [];
1136 `${this.logPrefix()} Charging station information from template ${
1138 } with no connectors configuration defined, using already defined connectors`
1141 // Initialize transaction attributes on connectors
1142 for (const connectorId
of this.connectors
.keys()) {
1143 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1144 this.initializeConnectorStatus(connectorId
);
1149 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1150 let configuration
: ChargingStationConfiguration
= null;
1151 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1153 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1154 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1155 this.configurationFileHash
1158 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1159 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1160 configuration
= JSON
.parse(
1161 fs
.readFileSync(this.configurationFile
, 'utf8')
1162 ) as ChargingStationConfiguration
;
1163 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1164 this.configurationFileHash
= configuration
.configurationHash
;
1165 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1168 FileUtils
.handleFileException(
1170 FileType
.ChargingStationConfiguration
,
1171 this.configurationFile
,
1172 error
as NodeJS
.ErrnoException
1176 return configuration
;
1179 private saveConfiguration(): void {
1180 if (this.configurationFile
) {
1182 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1183 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1185 const configurationData
: ChargingStationConfiguration
=
1186 this.getConfigurationFromFile() ?? {};
1187 this.ocppConfiguration
?.configurationKey
&&
1188 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1189 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1190 delete configurationData
.configurationHash
;
1191 const configurationHash
= crypto
1192 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1193 .update(JSON
.stringify(configurationData
))
1195 if (this.configurationFileHash
!== configurationHash
) {
1196 configurationData
.configurationHash
= configurationHash
;
1197 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1198 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1199 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1200 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1201 fs
.closeSync(fileDescriptor
);
1202 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1203 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1204 this.configurationFileHash
= configurationHash
;
1205 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1208 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1209 this.configurationFile
1214 FileUtils
.handleFileException(
1216 FileType
.ChargingStationConfiguration
,
1217 this.configurationFile
,
1218 error
as NodeJS
.ErrnoException
1223 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1228 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1229 return this.getTemplateFromFile()?.Configuration
?? null;
1232 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1233 let configuration
: ChargingStationConfiguration
= null;
1234 if (this.getOcppPersistentConfiguration()) {
1235 const configurationFromFile
= this.getConfigurationFromFile();
1236 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1238 configuration
&& delete configuration
.stationInfo
;
1239 return configuration
;
1242 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1243 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1244 if (!ocppConfiguration
) {
1245 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1247 return ocppConfiguration
;
1250 private async onOpen(): Promise
<void> {
1251 if (this.isWebSocketConnectionOpened()) {
1253 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1255 if (!this.isRegistered()) {
1256 // Send BootNotification
1257 let registrationRetryCount
= 0;
1259 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1260 BootNotificationRequest
,
1261 BootNotificationResponse
1264 RequestCommand
.BOOT_NOTIFICATION
,
1266 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1267 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1268 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1269 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1270 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1271 iccid
: this.bootNotificationRequest
.iccid
,
1272 imsi
: this.bootNotificationRequest
.imsi
,
1273 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1274 meterType
: this.bootNotificationRequest
.meterType
,
1276 { skipBufferingOnError
: true }
1278 if (!this.isRegistered()) {
1279 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1281 this.bootNotificationResponse
?.interval
1282 ? this.bootNotificationResponse
.interval
* 1000
1283 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1287 !this.isRegistered() &&
1288 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1289 this.getRegistrationMaxRetries() === -1)
1292 if (this.isRegistered()) {
1293 if (this.isInAcceptedState()) {
1294 await this.startMessageSequence();
1295 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1299 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1302 this.stopped
&& (this.stopped
= false);
1303 this.autoReconnectRetryCount
= 0;
1304 this.wsConnectionRestarted
= false;
1307 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1312 private async onClose(code
: number, reason
: string): Promise
<void> {
1315 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1316 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1318 `${this.logPrefix()} WebSocket normally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1320 )}' and reason '${reason}'`
1322 this.autoReconnectRetryCount
= 0;
1327 `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1329 )}' and reason '${reason}'`
1331 await this.reconnect(code
);
1336 private async onMessage(data
: Data
): Promise
<void> {
1337 let messageType
: number;
1338 let messageId
: string;
1339 let commandName
: IncomingRequestCommand
;
1340 let commandPayload
: JsonType
;
1341 let errorType
: ErrorType
;
1342 let errorMessage
: string;
1343 let errorDetails
: JsonType
;
1344 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1345 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1346 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1347 let requestPayload
: JsonType
;
1348 let cachedRequest
: CachedRequest
;
1351 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1352 if (Utils
.isIterable(request
)) {
1353 [messageType
, messageId
] = request
;
1354 // Check the type of message
1355 switch (messageType
) {
1357 case MessageType
.CALL_MESSAGE
:
1358 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1359 if (this.getEnableStatistics()) {
1360 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1363 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1367 // Process the message
1368 await this.ocppIncomingRequestService
.incomingRequestHandler(
1376 case MessageType
.CALL_RESULT_MESSAGE
:
1377 [, , commandPayload
] = request
as Response
;
1378 if (!this.requests
.has(messageId
)) {
1380 throw new OCPPError(
1381 ErrorType
.INTERNAL_ERROR
,
1382 `Response for unknown message id ${messageId}`,
1388 cachedRequest
= this.requests
.get(messageId
);
1389 if (Utils
.isIterable(cachedRequest
)) {
1390 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1392 throw new OCPPError(
1393 ErrorType
.PROTOCOL_ERROR
,
1394 `Cached request for message id ${messageId} response is not iterable`,
1396 cachedRequest
as unknown
as JsonType
1400 `${this.logPrefix()} << Command '${
1401 requestCommandName ?? 'unknown'
1402 }' received response payload: ${JSON.stringify(request)}`
1404 responseCallback(commandPayload
, requestPayload
);
1407 case MessageType
.CALL_ERROR_MESSAGE
:
1408 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1409 if (!this.requests
.has(messageId
)) {
1411 throw new OCPPError(
1412 ErrorType
.INTERNAL_ERROR
,
1413 `Error response for unknown message id ${messageId}`,
1415 { errorType
, errorMessage
, errorDetails
}
1418 cachedRequest
= this.requests
.get(messageId
);
1419 if (Utils
.isIterable(cachedRequest
)) {
1420 [, errorCallback
, requestCommandName
] = cachedRequest
;
1422 throw new OCPPError(
1423 ErrorType
.PROTOCOL_ERROR
,
1424 `Cached request for message id ${messageId} error response is not iterable`,
1426 cachedRequest
as unknown
as JsonType
1430 `${this.logPrefix()} << Command '${
1431 requestCommandName ?? 'unknown'
1432 }' received error payload: ${JSON.stringify(request)}`
1434 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1438 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1439 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
1440 logger
.error(errMsg
);
1441 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1444 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not iterable', null, {
1451 "%s Incoming OCPP '%s' message '%j' matching cached request '%j' processing error: %j",
1453 commandName
?? requestCommandName
?? null,
1455 this.requests
.get(messageId
),
1458 if (!(error
instanceof OCPPError
)) {
1460 "%s Error thrown at incoming OCPP '%s' message '%j' handling is not an OCPPError: %j",
1462 commandName
?? requestCommandName
?? null,
1468 messageType
=== MessageType
.CALL_MESSAGE
&&
1469 (await this.ocppRequestService
.sendError(
1473 commandName
?? requestCommandName
?? null
1478 private onPing(): void {
1479 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1482 private onPong(): void {
1483 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1486 private onError(error
: WSError
): void {
1487 this.closeWSConnection();
1488 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
1491 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean | undefined {
1492 const localStationInfo
= stationInfo
?? this.stationInfo
;
1493 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1494 ? localStationInfo
.useConnectorId0
1498 private getNumberOfRunningTransactions(): number {
1500 for (const connectorId
of this.connectors
.keys()) {
1501 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1509 private getConnectionTimeout(): number | undefined {
1511 ChargingStationConfigurationUtils
.getConfigurationKey(
1513 StandardParametersKey
.ConnectionTimeOut
1518 ChargingStationConfigurationUtils
.getConfigurationKey(
1520 StandardParametersKey
.ConnectionTimeOut
1522 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1525 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1528 // -1 for unlimited, 0 for disabling
1529 private getAutoReconnectMaxRetries(): number | undefined {
1530 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1531 return this.stationInfo
.autoReconnectMaxRetries
;
1533 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1534 return Configuration
.getAutoReconnectMaxRetries();
1540 private getRegistrationMaxRetries(): number | undefined {
1541 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1542 return this.stationInfo
.registrationMaxRetries
;
1547 private getPowerDivider(): number {
1548 let powerDivider
= this.getNumberOfConnectors();
1549 if (this.stationInfo
?.powerSharedByConnectors
) {
1550 powerDivider
= this.getNumberOfRunningTransactions();
1552 return powerDivider
;
1555 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1556 const localStationInfo
= stationInfo
?? this.stationInfo
;
1557 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1560 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1561 const maximumPower
= this.getMaximumPower(stationInfo
);
1562 switch (this.getCurrentOutType(stationInfo
)) {
1563 case CurrentType
.AC
:
1564 return ACElectricUtils
.amperagePerPhaseFromPower(
1565 this.getNumberOfPhases(stationInfo
),
1566 maximumPower
/ this.getNumberOfConnectors(),
1567 this.getVoltageOut(stationInfo
)
1569 case CurrentType
.DC
:
1570 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1574 private getAmperageLimitation(): number | undefined {
1576 this.stationInfo
.amperageLimitationOcppKey
&&
1577 ChargingStationConfigurationUtils
.getConfigurationKey(
1579 this.stationInfo
.amperageLimitationOcppKey
1584 ChargingStationConfigurationUtils
.getConfigurationKey(
1586 this.stationInfo
.amperageLimitationOcppKey
1588 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1593 private async startMessageSequence(): Promise
<void> {
1594 if (this.stationInfo
?.autoRegister
) {
1595 await this.ocppRequestService
.requestHandler
<
1596 BootNotificationRequest
,
1597 BootNotificationResponse
1600 RequestCommand
.BOOT_NOTIFICATION
,
1602 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1603 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1604 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1605 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1606 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1607 iccid
: this.bootNotificationRequest
.iccid
,
1608 imsi
: this.bootNotificationRequest
.imsi
,
1609 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1610 meterType
: this.bootNotificationRequest
.meterType
,
1612 { skipBufferingOnError
: true }
1615 // Start WebSocket ping
1616 this.startWebSocketPing();
1618 this.startHeartbeat();
1619 // Initialize connectors status
1620 for (const connectorId
of this.connectors
.keys()) {
1621 if (connectorId
=== 0) {
1625 !this.getConnectorStatus(connectorId
)?.status &&
1626 this.getConnectorStatus(connectorId
)?.bootStatus
1628 // Send status in template at startup
1629 await this.ocppRequestService
.requestHandler
<
1630 StatusNotificationRequest
,
1631 StatusNotificationResponse
1632 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1634 status: this.getConnectorStatus(connectorId
).bootStatus
,
1635 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1637 this.getConnectorStatus(connectorId
).status =
1638 this.getConnectorStatus(connectorId
).bootStatus
;
1641 this.getConnectorStatus(connectorId
)?.status &&
1642 this.getConnectorStatus(connectorId
)?.bootStatus
1644 // Send status in template after reset
1645 await this.ocppRequestService
.requestHandler
<
1646 StatusNotificationRequest
,
1647 StatusNotificationResponse
1648 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1650 status: this.getConnectorStatus(connectorId
).bootStatus
,
1651 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1653 this.getConnectorStatus(connectorId
).status =
1654 this.getConnectorStatus(connectorId
).bootStatus
;
1655 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1656 // Send previous status at template reload
1657 await this.ocppRequestService
.requestHandler
<
1658 StatusNotificationRequest
,
1659 StatusNotificationResponse
1660 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1662 status: this.getConnectorStatus(connectorId
).status,
1663 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1666 // Send default status
1667 await this.ocppRequestService
.requestHandler
<
1668 StatusNotificationRequest
,
1669 StatusNotificationResponse
1670 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1672 status: ChargePointStatus
.AVAILABLE
,
1673 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1675 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1679 this.startAutomaticTransactionGenerator();
1682 private startAutomaticTransactionGenerator() {
1683 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
) {
1684 if (!this.automaticTransactionGenerator
) {
1685 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
1686 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
1690 if (!this.automaticTransactionGenerator
.started
) {
1691 this.automaticTransactionGenerator
.start();
1696 private stopAutomaticTransactionGenerator(): void {
1697 if (this.automaticTransactionGenerator
?.started
) {
1698 this.automaticTransactionGenerator
.stop();
1699 this.automaticTransactionGenerator
= null;
1703 private async stopMessageSequence(
1704 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1706 // Stop WebSocket ping
1707 this.stopWebSocketPing();
1709 this.stopHeartbeat();
1710 // Stop ongoing transactions
1711 if (this.automaticTransactionGenerator
?.configuration
?.enable
) {
1712 this.stopAutomaticTransactionGenerator();
1714 for (const connectorId
of this.connectors
.keys()) {
1715 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1716 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1718 this.getBeginEndMeterValues() &&
1719 this.getOcppStrictCompliance() &&
1720 !this.getOutOfOrderEndMeterValues()
1722 // FIXME: Implement OCPP version agnostic helpers
1723 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1726 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1728 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
1730 RequestCommand
.METER_VALUES
,
1734 meterValue
: [transactionEndMeterValue
],
1738 await this.ocppRequestService
.requestHandler
<
1739 StopTransactionRequest
,
1740 StopTransactionResponse
1741 >(this, RequestCommand
.STOP_TRANSACTION
, {
1743 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1744 idTag
: this.getTransactionIdTag(transactionId
),
1752 private startWebSocketPing(): void {
1753 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1755 StandardParametersKey
.WebSocketPingInterval
1757 ? Utils
.convertToInt(
1758 ChargingStationConfigurationUtils
.getConfigurationKey(
1760 StandardParametersKey
.WebSocketPingInterval
1764 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1765 this.webSocketPingSetInterval
= setInterval(() => {
1766 if (this.isWebSocketConnectionOpened()) {
1767 this.wsConnection
.ping((): void => {
1768 /* This is intentional */
1771 }, webSocketPingInterval
* 1000);
1774 ' WebSocket ping started every ' +
1775 Utils
.formatDurationSeconds(webSocketPingInterval
)
1777 } else if (this.webSocketPingSetInterval
) {
1780 ' WebSocket ping every ' +
1781 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1786 `${this.logPrefix()} WebSocket ping interval set to ${
1787 webSocketPingInterval
1788 ? Utils.formatDurationSeconds(webSocketPingInterval)
1789 : webSocketPingInterval
1790 }, not starting the WebSocket ping`
1795 private stopWebSocketPing(): void {
1796 if (this.webSocketPingSetInterval
) {
1797 clearInterval(this.webSocketPingSetInterval
);
1801 private getConfiguredSupervisionUrl(): URL
{
1802 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1803 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1805 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1807 switch (Configuration
.getSupervisionUrlDistribution()) {
1808 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1809 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1811 case SupervisionUrlDistribution
.RANDOM
:
1813 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1815 case SupervisionUrlDistribution
.SEQUENTIAL
:
1816 if (this.index
<= supervisionUrls
.length
) {
1817 urlIndex
= this.index
- 1;
1820 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1826 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1827 SupervisionUrlDistribution.ROUND_ROBIN
1830 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1833 return new URL(supervisionUrls
[urlIndex
]);
1835 return new URL(supervisionUrls
as string);
1838 private getHeartbeatInterval(): number | undefined {
1839 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1841 StandardParametersKey
.HeartbeatInterval
1843 if (HeartbeatInterval
) {
1844 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1846 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1848 StandardParametersKey
.HeartBeatInterval
1850 if (HeartBeatInterval
) {
1851 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1853 !this.stationInfo
?.autoRegister
&&
1855 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1856 Constants.DEFAULT_HEARTBEAT_INTERVAL
1859 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1862 private stopHeartbeat(): void {
1863 if (this.heartbeatSetInterval
) {
1864 clearInterval(this.heartbeatSetInterval
);
1868 private openWSConnection(
1869 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
1870 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
1872 terminateOpened
: false,
1875 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
1876 params
.closeOpened
= params
?.closeOpened
?? false;
1877 params
.terminateOpened
= params
?.terminateOpened
?? false;
1879 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
1880 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
1882 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
1884 if (params
?.closeOpened
) {
1885 this.closeWSConnection();
1887 if (params
?.terminateOpened
) {
1888 this.terminateWSConnection();
1890 let protocol
: string;
1891 switch (this.getOcppVersion()) {
1892 case OCPPVersion
.VERSION_16
:
1893 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
1896 this.handleUnsupportedVersion(this.getOcppVersion());
1901 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString()
1904 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
1906 // Handle WebSocket message
1907 this.wsConnection
.on(
1909 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
1911 // Handle WebSocket error
1912 this.wsConnection
.on(
1914 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
1916 // Handle WebSocket close
1917 this.wsConnection
.on(
1919 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
1921 // Handle WebSocket open
1922 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
1923 // Handle WebSocket ping
1924 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
1925 // Handle WebSocket pong
1926 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
1929 private closeWSConnection(): void {
1930 if (this.isWebSocketConnectionOpened()) {
1931 this.wsConnection
.close();
1932 this.wsConnection
= null;
1936 private terminateWSConnection(): void {
1937 if (this.isWebSocketConnectionOpened()) {
1938 this.wsConnection
.terminate();
1939 this.wsConnection
= null;
1943 private stopMeterValues(connectorId
: number) {
1944 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1945 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1949 private getReconnectExponentialDelay(): boolean | undefined {
1950 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1951 ? this.stationInfo
.reconnectExponentialDelay
1955 private async reconnect(code
: number): Promise
<void> {
1956 // Stop WebSocket ping
1957 this.stopWebSocketPing();
1959 this.stopHeartbeat();
1960 // Stop the ATG if needed
1961 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
) {
1962 this.stopAutomaticTransactionGenerator();
1965 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1966 this.getAutoReconnectMaxRetries() === -1
1968 this.autoReconnectRetryCount
++;
1969 const reconnectDelay
= this.getReconnectExponentialDelay()
1970 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1971 : this.getConnectionTimeout() * 1000;
1972 const reconnectDelayWithdraw
= 1000;
1973 const reconnectTimeout
=
1974 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
1975 ? reconnectDelay
- reconnectDelayWithdraw
1978 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1981 )}ms, timeout ${reconnectTimeout}ms`
1983 await Utils
.sleep(reconnectDelay
);
1986 ' WebSocket: reconnecting try #' +
1987 this.autoReconnectRetryCount
.toString()
1989 this.openWSConnection(
1990 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
1991 { closeOpened
: true }
1993 this.wsConnectionRestarted
= true;
1994 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1996 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
1997 this.autoReconnectRetryCount
1998 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2003 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
2004 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2007 private initializeConnectorStatus(connectorId
: number): void {
2008 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2009 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2010 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2011 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2012 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2013 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;