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 { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
24 import { ConnectorStatus
} from
'../types/ConnectorStatus';
25 import { FileType
} from
'../types/FileType';
26 import { JsonType
} from
'../types/JsonType';
27 import { ChargePointErrorCode
} from
'../types/ocpp/ChargePointErrorCode';
28 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
29 import { ChargingProfile
, ChargingRateUnitType
} from
'../types/ocpp/ChargingProfile';
31 ConnectorPhaseRotation
,
32 StandardParametersKey
,
33 SupportedFeatureProfiles
,
34 VendorDefaultParametersKey
,
35 } from
'../types/ocpp/Configuration';
36 import { ErrorType
} from
'../types/ocpp/ErrorType';
37 import { MessageType
} from
'../types/ocpp/MessageType';
38 import { MeterValue
, MeterValueMeasurand
} from
'../types/ocpp/MeterValues';
39 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
42 BootNotificationRequest
,
46 IncomingRequestCommand
,
49 StatusNotificationRequest
,
50 } from
'../types/ocpp/Requests';
52 BootNotificationResponse
,
58 StatusNotificationResponse
,
59 } from
'../types/ocpp/Responses';
61 StopTransactionReason
,
62 StopTransactionRequest
,
63 StopTransactionResponse
,
64 } from
'../types/ocpp/Transaction';
65 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
66 import Configuration from
'../utils/Configuration';
67 import Constants from
'../utils/Constants';
68 import { ACElectricUtils
, DCElectricUtils
} from
'../utils/ElectricUtils';
69 import FileUtils from
'../utils/FileUtils';
70 import logger from
'../utils/Logger';
71 import Utils from
'../utils/Utils';
72 import AuthorizedTagsCache from
'./AuthorizedTagsCache';
73 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
74 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
75 import { ChargingStationUtils
} from
'./ChargingStationUtils';
76 import ChargingStationWorkerBroadcastChannel from
'./ChargingStationWorkerBroadcastChannel';
77 import { MessageChannelUtils
} from
'./MessageChannelUtils';
78 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
79 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
80 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
81 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
82 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
83 import OCPPRequestService from
'./ocpp/OCPPRequestService';
84 import SharedLRUCache from
'./SharedLRUCache';
86 export default class ChargingStation
{
87 public hashId
!: string;
88 public readonly templateFile
: string;
89 public authorizedTagsCache
: AuthorizedTagsCache
;
90 public stationInfo
!: ChargingStationInfo
;
91 public stopped
: boolean;
92 public readonly connectors
: Map
<number, ConnectorStatus
>;
93 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
94 public wsConnection
!: WebSocket
;
95 public readonly requests
: Map
<string, CachedRequest
>;
96 public performanceStatistics
!: PerformanceStatistics
;
97 public heartbeatSetInterval
!: NodeJS
.Timeout
;
98 public ocppRequestService
!: OCPPRequestService
;
99 public bootNotificationResponse
!: BootNotificationResponse
| null;
100 public powerDivider
!: number;
101 private readonly index
: number;
102 private configurationFile
!: string;
103 private configurationFileHash
!: string;
104 private bootNotificationRequest
!: BootNotificationRequest
;
105 private connectorsConfigurationHash
!: string;
106 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
107 private readonly messageBuffer
: Set
<string>;
108 private configuredSupervisionUrl
!: URL
;
109 private wsConnectionRestarted
: boolean;
110 private autoReconnectRetryCount
: number;
111 private templateFileWatcher
!: fs
.FSWatcher
;
112 private readonly sharedLRUCache
: SharedLRUCache
;
113 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
114 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
115 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
117 constructor(index
: number, templateFile
: string) {
119 this.templateFile
= templateFile
;
120 this.stopped
= false;
121 this.wsConnectionRestarted
= false;
122 this.autoReconnectRetryCount
= 0;
123 this.sharedLRUCache
= SharedLRUCache
.getInstance();
124 this.authorizedTagsCache
= AuthorizedTagsCache
.getInstance();
125 this.connectors
= new Map
<number, ConnectorStatus
>();
126 this.requests
= new Map
<string, CachedRequest
>();
127 this.messageBuffer
= new Set
<string>();
128 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
133 private get
wsConnectionUrl(): URL
{
135 (this.getSupervisionUrlOcppConfiguration()
136 ? ChargingStationConfigurationUtils
.getConfigurationKey(
138 this.getSupervisionUrlOcppKey()
140 : this.configuredSupervisionUrl
.href
) +
142 this.stationInfo
.chargingStationId
146 public logPrefix(): string {
147 return Utils
.logPrefix(
149 this?.stationInfo?.chargingStationId ??
150 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
155 public getBootNotificationRequest(): BootNotificationRequest
{
156 return this.bootNotificationRequest
;
159 public getRandomIdTag(): string {
160 const authorizationFile
= ChargingStationUtils
.getAuthorizationFile(this.stationInfo
);
161 const index
= Math.floor(
162 Utils
.secureRandom() * this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
).length
164 return this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
)[index
];
167 public hasAuthorizedTags(): boolean {
168 return !Utils
.isEmptyArray(
169 this.authorizedTagsCache
.getAuthorizedTags(
170 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
)
175 public getEnableStatistics(): boolean | undefined {
176 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
177 ? this.stationInfo
.enableStatistics
181 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
182 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
185 public getPayloadSchemaValidation(): boolean | undefined {
186 return this.stationInfo
.payloadSchemaValidation
?? true;
189 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
190 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
191 switch (this.getCurrentOutType(stationInfo
)) {
193 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
194 ? localStationInfo
.numberOfPhases
201 public isWebSocketConnectionOpened(): boolean {
202 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
205 public getRegistrationStatus(): RegistrationStatus
{
206 return this?.bootNotificationResponse
?.status;
209 public isInUnknownState(): boolean {
210 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
213 public isInPendingState(): boolean {
214 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
217 public isInAcceptedState(): boolean {
218 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
221 public isInRejectedState(): boolean {
222 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
225 public isRegistered(): boolean {
226 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
229 public isChargingStationAvailable(): boolean {
230 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
233 public isConnectorAvailable(id
: number): boolean {
234 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
237 public getNumberOfConnectors(): number {
238 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
241 public getConnectorStatus(id
: number): ConnectorStatus
{
242 return this.connectors
.get(id
);
245 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
246 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
;
249 public getOcppStrictCompliance(): boolean {
250 return this.stationInfo
?.ocppStrictCompliance
?? false;
253 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
254 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
255 this.getCurrentOutType(stationInfo
),
259 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
260 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
261 ? localStationInfo
.voltageOut
265 public getConnectorMaximumAvailablePower(connectorId
: number): number {
266 let connectorAmperageLimitationPowerLimit
: number;
268 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
269 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
271 connectorAmperageLimitationPowerLimit
=
272 (this.getCurrentOutType() === CurrentType
.AC
273 ? ACElectricUtils
.powerTotal(
274 this.getNumberOfPhases(),
275 this.getVoltageOut(),
276 this.getAmperageLimitation() * this.getNumberOfConnectors()
278 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
281 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
282 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
284 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
285 isNaN(connectorAmperageLimitationPowerLimit
)
287 : connectorAmperageLimitationPowerLimit
,
288 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
292 public getTransactionIdTag(transactionId
: number): string | undefined {
293 for (const connectorId
of this.connectors
.keys()) {
294 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
295 return this.getConnectorStatus(connectorId
).transactionIdTag
;
300 public getOutOfOrderEndMeterValues(): boolean {
301 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
304 public getBeginEndMeterValues(): boolean {
305 return this.stationInfo
?.beginEndMeterValues
?? false;
308 public getMeteringPerTransaction(): boolean {
309 return this.stationInfo
?.meteringPerTransaction
?? true;
312 public getTransactionDataMeterValues(): boolean {
313 return this.stationInfo
?.transactionDataMeterValues
?? false;
316 public getMainVoltageMeterValues(): boolean {
317 return this.stationInfo
?.mainVoltageMeterValues
?? true;
320 public getPhaseLineToLineVoltageMeterValues(): boolean {
321 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
324 public getCustomValueLimitationMeterValues(): boolean {
325 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
328 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
329 for (const connectorId
of this.connectors
.keys()) {
332 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
339 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
340 const transactionConnectorStatus
= this.getConnectorStatus(
341 this.getConnectorIdByTransactionId(transactionId
)
343 if (this.getMeteringPerTransaction()) {
344 return transactionConnectorStatus
?.transactionEnergyActiveImportRegisterValue
;
346 return transactionConnectorStatus
?.energyActiveImportRegisterValue
;
349 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
350 const connectorStatus
= this.getConnectorStatus(connectorId
);
351 if (this.getMeteringPerTransaction()) {
352 return connectorStatus
?.transactionEnergyActiveImportRegisterValue
;
354 return connectorStatus
?.energyActiveImportRegisterValue
;
357 public getAuthorizeRemoteTxRequests(): boolean {
358 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
360 StandardParametersKey
.AuthorizeRemoteTxRequests
362 return authorizeRemoteTxRequests
363 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
367 public getLocalAuthListEnabled(): boolean {
368 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
370 StandardParametersKey
.LocalAuthListEnabled
372 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
375 public startHeartbeat(): void {
377 this.getHeartbeatInterval() &&
378 this.getHeartbeatInterval() > 0 &&
379 !this.heartbeatSetInterval
381 // eslint-disable-next-line @typescript-eslint/no-misused-promises
382 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
383 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
385 RequestCommand
.HEARTBEAT
387 }, this.getHeartbeatInterval());
390 ' Heartbeat started every ' +
391 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
393 } else if (this.heartbeatSetInterval
) {
396 ' Heartbeat already started every ' +
397 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
401 `${this.logPrefix()} Heartbeat interval set to ${
402 this.getHeartbeatInterval()
403 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
404 : this.getHeartbeatInterval()
405 }, not starting the heartbeat`
410 public restartHeartbeat(): void {
412 this.stopHeartbeat();
414 this.startHeartbeat();
417 public restartWebSocketPing(): void {
418 // Stop WebSocket ping
419 this.stopWebSocketPing();
420 // Start WebSocket ping
421 this.startWebSocketPing();
424 public startMeterValues(connectorId
: number, interval
: number): void {
425 if (connectorId
=== 0) {
427 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
431 if (!this.getConnectorStatus(connectorId
)) {
433 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
437 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
439 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
443 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
444 !this.getConnectorStatus(connectorId
)?.transactionId
447 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
452 // eslint-disable-next-line @typescript-eslint/no-misused-promises
453 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
454 // eslint-disable-next-line @typescript-eslint/no-misused-promises
455 async (): Promise
<void> => {
456 // FIXME: Implement OCPP version agnostic helpers
457 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
460 this.getConnectorStatus(connectorId
).transactionId
,
463 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
465 RequestCommand
.METER_VALUES
,
468 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
469 meterValue
: [meterValue
],
477 `${this.logPrefix()} Charging station ${
478 StandardParametersKey.MeterValueSampleInterval
479 } configuration set to ${
480 interval ? Utils.formatDurationMilliSeconds(interval) : interval
481 }, not sending MeterValues`
486 public start(): void {
487 if (this.getEnableStatistics()) {
488 this.performanceStatistics
.start();
490 this.openWSConnection();
491 // Monitor charging station template file
492 this.templateFileWatcher
= FileUtils
.watchJsonFile(
494 FileType
.ChargingStationTemplate
,
497 (event
, filename
): void => {
498 if (filename
&& event
=== 'change') {
501 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
503 } file have changed, reload`
505 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
509 this.stopAutomaticTransactionGenerator();
510 this.startAutomaticTransactionGenerator();
511 if (this.getEnableStatistics()) {
512 this.performanceStatistics
.restart();
514 this.performanceStatistics
.stop();
516 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
519 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
526 parentPort
.postMessage(MessageChannelUtils
.buildStartedMessage(this));
529 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
530 // Stop message sequence
531 await this.stopMessageSequence(reason
);
532 for (const connectorId
of this.connectors
.keys()) {
533 if (connectorId
> 0) {
534 await this.ocppRequestService
.requestHandler
<
535 StatusNotificationRequest
,
536 StatusNotificationResponse
537 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
539 status: ChargePointStatus
.UNAVAILABLE
,
540 errorCode
: ChargePointErrorCode
.NO_ERROR
,
542 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
545 this.closeWSConnection();
546 if (this.getEnableStatistics()) {
547 this.performanceStatistics
.stop();
549 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
550 this.templateFileWatcher
.close();
551 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
552 this.bootNotificationResponse
= null;
553 parentPort
.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
557 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
558 await this.stop(reason
);
559 await Utils
.sleep(this.stationInfo
.resetTime
);
564 public saveOcppConfiguration(): void {
565 if (this.getOcppPersistentConfiguration()) {
566 this.saveConfiguration();
570 public getChargingProfilePowerLimit(connectorId
: number): number | undefined {
571 let limit
: number, matchingChargingProfile
: ChargingProfile
;
572 let chargingProfiles
: ChargingProfile
[] = [];
573 // Get charging profiles for connector and sort by stack level
574 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
575 (a
, b
) => b
.stackLevel
- a
.stackLevel
577 // Get profiles on connector 0
578 if (this.getConnectorStatus(0).chargingProfiles
) {
579 chargingProfiles
.push(
580 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
583 if (!Utils
.isEmptyArray(chargingProfiles
)) {
584 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
588 if (!Utils
.isNullOrUndefined(result
)) {
589 limit
= result
.limit
;
590 matchingChargingProfile
= result
.matchingChargingProfile
;
591 switch (this.getCurrentOutType()) {
594 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
595 ChargingRateUnitType
.WATT
597 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
601 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
602 ChargingRateUnitType
.WATT
604 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
607 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
608 if (limit
> connectorMaximumPower
) {
610 `${this.logPrefix()} Charging profile id ${
611 matchingChargingProfile.chargingProfileId
612 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
613 this.getConnectorStatus(connectorId
).chargingProfiles
615 limit
= connectorMaximumPower
;
622 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
623 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
625 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
627 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
629 if (!Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
631 `${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`
633 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
635 let cpReplaced
= false;
636 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
637 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
638 (chargingProfile
: ChargingProfile
, index
: number) => {
640 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
641 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
642 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
644 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
650 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
653 public resetConnectorStatus(connectorId
: number): void {
654 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
655 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
656 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
657 this.getConnectorStatus(connectorId
).transactionStarted
= false;
658 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
659 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
660 delete this.getConnectorStatus(connectorId
).transactionId
;
661 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
662 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
663 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
664 this.stopMeterValues(connectorId
);
667 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
668 return ChargingStationConfigurationUtils
.getConfigurationKey(
670 StandardParametersKey
.SupportedFeatureProfiles
671 )?.value
.includes(featureProfile
);
674 public bufferMessage(message
: string): void {
675 this.messageBuffer
.add(message
);
678 private flushMessageBuffer() {
679 if (this.messageBuffer
.size
> 0) {
680 this.messageBuffer
.forEach((message
) => {
681 // TODO: evaluate the need to track performance
682 this.wsConnection
.send(message
);
683 this.messageBuffer
.delete(message
);
688 private getSupervisionUrlOcppConfiguration(): boolean {
689 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
692 private getSupervisionUrlOcppKey(): string {
693 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
696 private getTemplateFromFile(): ChargingStationTemplate
| null {
697 let template
: ChargingStationTemplate
= null;
699 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
700 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
702 const measureId
= `${FileType.ChargingStationTemplate} read`;
703 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
704 template
= JSON
.parse(
705 fs
.readFileSync(this.templateFile
, 'utf8')
706 ) as ChargingStationTemplate
;
707 PerformanceStatistics
.endMeasure(measureId
, beginId
);
708 template
.templateHash
= crypto
709 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
710 .update(JSON
.stringify(template
))
712 this.sharedLRUCache
.setChargingStationTemplate(template
);
715 FileUtils
.handleFileException(
717 FileType
.ChargingStationTemplate
,
719 error
as NodeJS
.ErrnoException
725 private getStationInfoFromTemplate(): ChargingStationInfo
{
726 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
727 if (Utils
.isNullOrUndefined(stationTemplate
)) {
728 const errorMsg
= 'Failed to read charging station template file';
729 logger
.error(`${this.logPrefix()} ${errorMsg}`);
730 throw new BaseError(errorMsg
);
732 if (Utils
.isEmptyObject(stationTemplate
)) {
733 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
734 logger
.error(`${this.logPrefix()} ${errorMsg}`);
735 throw new BaseError(errorMsg
);
737 // Deprecation template keys section
738 ChargingStationUtils
.warnDeprecatedTemplateKey(
743 "Use 'supervisionUrls' instead"
745 ChargingStationUtils
.convertDeprecatedTemplateKey(
750 const stationInfo
: ChargingStationInfo
=
751 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
752 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
756 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
757 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
758 stationTemplate
.power
= stationTemplate
.power
as number[];
759 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
760 stationInfo
.maximumPower
=
761 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
762 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
763 : stationTemplate
.power
[powerArrayRandomIndex
];
765 stationTemplate
.power
= stationTemplate
.power
as number;
766 stationInfo
.maximumPower
=
767 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
768 ? stationTemplate
.power
* 1000
769 : stationTemplate
.power
;
771 stationInfo
.resetTime
= stationTemplate
.resetTime
772 ? stationTemplate
.resetTime
* 1000
773 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
774 const configuredMaxConnectors
= ChargingStationUtils
.getConfiguredNumberOfConnectors(
778 ChargingStationUtils
.checkConfiguredMaxConnectors(
779 configuredMaxConnectors
,
783 const templateMaxConnectors
=
784 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
785 ChargingStationUtils
.checkTemplateMaxConnectors(
786 templateMaxConnectors
,
791 configuredMaxConnectors
>
792 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
793 !stationTemplate
?.randomConnectors
796 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
798 }, forcing random connector configurations affectation`
800 stationInfo
.randomConnectors
= true;
802 // Build connectors if needed (FIXME: should be factored out)
803 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
804 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
805 ChargingStationUtils
.createStationInfoHash(stationInfo
);
809 private getStationInfoFromFile(): ChargingStationInfo
| null {
810 let stationInfo
: ChargingStationInfo
= null;
811 this.getStationInfoPersistentConfiguration() &&
812 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
813 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
817 private getStationInfo(): ChargingStationInfo
{
818 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
819 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
820 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
821 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
822 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
823 return this.stationInfo
;
825 return stationInfoFromFile
;
827 stationInfoFromFile
&&
828 ChargingStationUtils
.propagateSerialNumber(
829 this.getTemplateFromFile(),
831 stationInfoFromTemplate
833 return stationInfoFromTemplate
;
836 private saveStationInfo(): void {
837 if (this.getStationInfoPersistentConfiguration()) {
838 this.saveConfiguration();
842 private getOcppVersion(): OCPPVersion
{
843 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
846 private getOcppPersistentConfiguration(): boolean {
847 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
850 private getStationInfoPersistentConfiguration(): boolean {
851 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
854 private handleUnsupportedVersion(version
: OCPPVersion
) {
855 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
858 logger
.error(errMsg
);
859 throw new Error(errMsg
);
862 private initialize(): void {
863 this.hashId
= ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile());
864 logger
.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
865 this.configurationFile
= path
.join(
866 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
867 this.hashId
+ '.json'
869 this.stationInfo
= this.getStationInfo();
870 this.saveStationInfo();
871 // Avoid duplication of connectors related information in RAM
872 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
873 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
874 if (this.getEnableStatistics()) {
875 this.performanceStatistics
= PerformanceStatistics
.getInstance(
877 this.stationInfo
.chargingStationId
,
878 this.configuredSupervisionUrl
881 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
884 this.powerDivider
= this.getPowerDivider();
885 // OCPP configuration
886 this.ocppConfiguration
= this.getOcppConfiguration();
887 this.initializeOcppConfiguration();
888 switch (this.getOcppVersion()) {
889 case OCPPVersion
.VERSION_16
:
890 this.ocppIncomingRequestService
=
891 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
892 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
893 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
897 this.handleUnsupportedVersion(this.getOcppVersion());
900 if (this.stationInfo
?.autoRegister
) {
901 this.bootNotificationResponse
= {
902 currentTime
: new Date().toISOString(),
903 interval
: this.getHeartbeatInterval() / 1000,
904 status: RegistrationStatus
.ACCEPTED
,
909 private initializeOcppConfiguration(): void {
911 !ChargingStationConfigurationUtils
.getConfigurationKey(
913 StandardParametersKey
.HeartbeatInterval
916 ChargingStationConfigurationUtils
.addConfigurationKey(
918 StandardParametersKey
.HeartbeatInterval
,
923 !ChargingStationConfigurationUtils
.getConfigurationKey(
925 StandardParametersKey
.HeartBeatInterval
928 ChargingStationConfigurationUtils
.addConfigurationKey(
930 StandardParametersKey
.HeartBeatInterval
,
936 this.getSupervisionUrlOcppConfiguration() &&
937 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
939 ChargingStationConfigurationUtils
.addConfigurationKey(
941 this.getSupervisionUrlOcppKey(),
942 this.configuredSupervisionUrl
.href
,
946 !this.getSupervisionUrlOcppConfiguration() &&
947 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
949 ChargingStationConfigurationUtils
.deleteConfigurationKey(
951 this.getSupervisionUrlOcppKey(),
956 this.stationInfo
.amperageLimitationOcppKey
&&
957 !ChargingStationConfigurationUtils
.getConfigurationKey(
959 this.stationInfo
.amperageLimitationOcppKey
962 ChargingStationConfigurationUtils
.addConfigurationKey(
964 this.stationInfo
.amperageLimitationOcppKey
,
966 this.stationInfo
.maximumAmperage
*
967 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
972 !ChargingStationConfigurationUtils
.getConfigurationKey(
974 StandardParametersKey
.SupportedFeatureProfiles
977 ChargingStationConfigurationUtils
.addConfigurationKey(
979 StandardParametersKey
.SupportedFeatureProfiles
,
980 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
983 ChargingStationConfigurationUtils
.addConfigurationKey(
985 StandardParametersKey
.NumberOfConnectors
,
986 this.getNumberOfConnectors().toString(),
991 !ChargingStationConfigurationUtils
.getConfigurationKey(
993 StandardParametersKey
.MeterValuesSampledData
996 ChargingStationConfigurationUtils
.addConfigurationKey(
998 StandardParametersKey
.MeterValuesSampledData
,
999 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1003 !ChargingStationConfigurationUtils
.getConfigurationKey(
1005 StandardParametersKey
.ConnectorPhaseRotation
1008 const connectorPhaseRotation
= [];
1009 for (const connectorId
of this.connectors
.keys()) {
1011 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1012 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1013 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1014 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1016 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1017 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1018 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1019 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1022 ChargingStationConfigurationUtils
.addConfigurationKey(
1024 StandardParametersKey
.ConnectorPhaseRotation
,
1025 connectorPhaseRotation
.toString()
1029 !ChargingStationConfigurationUtils
.getConfigurationKey(
1031 StandardParametersKey
.AuthorizeRemoteTxRequests
1034 ChargingStationConfigurationUtils
.addConfigurationKey(
1036 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1041 !ChargingStationConfigurationUtils
.getConfigurationKey(
1043 StandardParametersKey
.LocalAuthListEnabled
1045 ChargingStationConfigurationUtils
.getConfigurationKey(
1047 StandardParametersKey
.SupportedFeatureProfiles
1048 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1050 ChargingStationConfigurationUtils
.addConfigurationKey(
1052 StandardParametersKey
.LocalAuthListEnabled
,
1057 !ChargingStationConfigurationUtils
.getConfigurationKey(
1059 StandardParametersKey
.ConnectionTimeOut
1062 ChargingStationConfigurationUtils
.addConfigurationKey(
1064 StandardParametersKey
.ConnectionTimeOut
,
1065 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1068 this.saveOcppConfiguration();
1071 private initializeConnectors(
1072 stationInfo
: ChargingStationInfo
,
1073 configuredMaxConnectors
: number,
1074 templateMaxConnectors
: number
1076 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1077 const logMsg
= `${this.logPrefix()} No already defined connectors and charging station information from template ${
1079 } with no connectors configuration defined`;
1080 logger
.error(logMsg
);
1081 throw new BaseError(logMsg
);
1083 if (!stationInfo
?.Connectors
[0]) {
1085 `${this.logPrefix()} Charging station information from template ${
1087 } with no connector Id 0 configuration`
1090 if (stationInfo
?.Connectors
) {
1091 const connectorsConfigHash
= crypto
1092 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1093 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1095 const connectorsConfigChanged
=
1096 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1097 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1098 connectorsConfigChanged
&& this.connectors
.clear();
1099 this.connectorsConfigurationHash
= connectorsConfigHash
;
1100 // Add connector Id 0
1101 let lastConnector
= '0';
1102 for (lastConnector
in stationInfo
?.Connectors
) {
1103 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1105 lastConnectorId
=== 0 &&
1106 this.getUseConnectorId0(stationInfo
) &&
1107 stationInfo
?.Connectors
[lastConnector
]
1109 this.connectors
.set(
1111 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1113 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1114 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1115 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1119 // Generate all connectors
1120 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1121 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1122 const randConnectorId
= stationInfo
?.randomConnectors
1123 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1125 this.connectors
.set(
1127 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1129 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1130 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1131 this.getConnectorStatus(index
).chargingProfiles
= [];
1138 `${this.logPrefix()} Charging station information from template ${
1140 } with no connectors configuration defined, using already defined connectors`
1143 // Initialize transaction attributes on connectors
1144 for (const connectorId
of this.connectors
.keys()) {
1145 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1146 this.initializeConnectorStatus(connectorId
);
1151 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1152 let configuration
: ChargingStationConfiguration
= null;
1153 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1155 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1156 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1157 this.configurationFileHash
1160 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1161 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1162 configuration
= JSON
.parse(
1163 fs
.readFileSync(this.configurationFile
, 'utf8')
1164 ) as ChargingStationConfiguration
;
1165 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1166 this.configurationFileHash
= configuration
.configurationHash
;
1167 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1170 FileUtils
.handleFileException(
1172 FileType
.ChargingStationConfiguration
,
1173 this.configurationFile
,
1174 error
as NodeJS
.ErrnoException
1178 return configuration
;
1181 private saveConfiguration(): void {
1182 if (this.configurationFile
) {
1184 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1185 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1187 const configurationData
: ChargingStationConfiguration
=
1188 this.getConfigurationFromFile() ?? {};
1189 this.ocppConfiguration
?.configurationKey
&&
1190 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1191 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1192 delete configurationData
.configurationHash
;
1193 const configurationHash
= crypto
1194 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1195 .update(JSON
.stringify(configurationData
))
1197 if (this.configurationFileHash
!== configurationHash
) {
1198 configurationData
.configurationHash
= configurationHash
;
1199 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1200 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1201 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1202 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1203 fs
.closeSync(fileDescriptor
);
1204 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1205 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1206 this.configurationFileHash
= configurationHash
;
1207 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1210 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1211 this.configurationFile
1216 FileUtils
.handleFileException(
1218 FileType
.ChargingStationConfiguration
,
1219 this.configurationFile
,
1220 error
as NodeJS
.ErrnoException
1225 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1230 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1231 return this.getTemplateFromFile()?.Configuration
?? null;
1234 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1235 let configuration
: ChargingStationConfiguration
= null;
1236 if (this.getOcppPersistentConfiguration()) {
1237 const configurationFromFile
= this.getConfigurationFromFile();
1238 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1240 configuration
&& delete configuration
.stationInfo
;
1241 return configuration
;
1244 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1245 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1246 if (!ocppConfiguration
) {
1247 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1249 return ocppConfiguration
;
1252 private async onOpen(): Promise
<void> {
1253 if (this.isWebSocketConnectionOpened()) {
1255 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1257 if (!this.isRegistered()) {
1258 // Send BootNotification
1259 let registrationRetryCount
= 0;
1261 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1262 BootNotificationRequest
,
1263 BootNotificationResponse
1266 RequestCommand
.BOOT_NOTIFICATION
,
1268 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1269 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1270 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1271 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1272 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1273 iccid
: this.bootNotificationRequest
.iccid
,
1274 imsi
: this.bootNotificationRequest
.imsi
,
1275 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1276 meterType
: this.bootNotificationRequest
.meterType
,
1278 { skipBufferingOnError
: true }
1280 if (!this.isRegistered()) {
1281 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1283 this.bootNotificationResponse
?.interval
1284 ? this.bootNotificationResponse
.interval
* 1000
1285 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1289 !this.isRegistered() &&
1290 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1291 this.getRegistrationMaxRetries() === -1)
1294 if (this.isRegistered()) {
1295 if (this.isInAcceptedState()) {
1296 await this.startMessageSequence();
1297 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1301 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1304 this.stopped
&& (this.stopped
= false);
1305 this.autoReconnectRetryCount
= 0;
1306 this.wsConnectionRestarted
= false;
1309 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1314 private async onClose(code
: number, reason
: string): Promise
<void> {
1317 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1318 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1320 `${this.logPrefix()} WebSocket normally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1322 )}' and reason '${reason}'`
1324 this.autoReconnectRetryCount
= 0;
1329 `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1331 )}' and reason '${reason}'`
1333 await this.reconnect(code
);
1338 private async onMessage(data
: Data
): Promise
<void> {
1339 let messageType
: number;
1340 let messageId
: string;
1341 let commandName
: IncomingRequestCommand
;
1342 let commandPayload
: JsonType
;
1343 let errorType
: ErrorType
;
1344 let errorMessage
: string;
1345 let errorDetails
: JsonType
;
1346 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1347 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1348 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1349 let requestPayload
: JsonType
;
1350 let cachedRequest
: CachedRequest
;
1353 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1354 if (Utils
.isIterable(request
)) {
1355 [messageType
, messageId
] = request
;
1356 // Check the type of message
1357 switch (messageType
) {
1359 case MessageType
.CALL_MESSAGE
:
1360 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1361 if (this.getEnableStatistics()) {
1362 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1365 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1369 // Process the message
1370 await this.ocppIncomingRequestService
.incomingRequestHandler(
1378 case MessageType
.CALL_RESULT_MESSAGE
:
1379 [, , commandPayload
] = request
as Response
;
1380 if (!this.requests
.has(messageId
)) {
1382 throw new OCPPError(
1383 ErrorType
.INTERNAL_ERROR
,
1384 `Response for unknown message id ${messageId}`,
1390 cachedRequest
= this.requests
.get(messageId
);
1391 if (Utils
.isIterable(cachedRequest
)) {
1392 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1394 throw new OCPPError(
1395 ErrorType
.PROTOCOL_ERROR
,
1396 `Cached request for message id ${messageId} response is not iterable`,
1398 cachedRequest
as unknown
as JsonType
1402 `${this.logPrefix()} << Command '${
1403 requestCommandName ?? 'unknown'
1404 }' received response payload: ${JSON.stringify(request)}`
1406 responseCallback(commandPayload
, requestPayload
);
1409 case MessageType
.CALL_ERROR_MESSAGE
:
1410 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1411 if (!this.requests
.has(messageId
)) {
1413 throw new OCPPError(
1414 ErrorType
.INTERNAL_ERROR
,
1415 `Error response for unknown message id ${messageId}`,
1417 { errorType
, errorMessage
, errorDetails
}
1420 cachedRequest
= this.requests
.get(messageId
);
1421 if (Utils
.isIterable(cachedRequest
)) {
1422 [, errorCallback
, requestCommandName
] = cachedRequest
;
1424 throw new OCPPError(
1425 ErrorType
.PROTOCOL_ERROR
,
1426 `Cached request for message id ${messageId} error response is not iterable`,
1428 cachedRequest
as unknown
as JsonType
1432 `${this.logPrefix()} << Command '${
1433 requestCommandName ?? 'unknown'
1434 }' received error payload: ${JSON.stringify(request)}`
1436 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1440 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1441 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
1442 logger
.error(errMsg
);
1443 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1445 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1447 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not iterable', null, {
1454 "%s Incoming OCPP '%s' message '%j' matching cached request '%j' processing error:",
1456 commandName
?? requestCommandName
?? null,
1458 this.requests
.get(messageId
),
1461 if (!(error
instanceof OCPPError
)) {
1463 "%s Error thrown at incoming OCPP '%s' message '%j' handling is not an OCPPError:",
1465 commandName
?? requestCommandName
?? null,
1471 messageType
=== MessageType
.CALL_MESSAGE
&&
1472 (await this.ocppRequestService
.sendError(
1476 commandName
?? requestCommandName
?? null
1481 private onPing(): void {
1482 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1485 private onPong(): void {
1486 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1489 private onError(error
: WSError
): void {
1490 this.closeWSConnection();
1491 logger
.error(this.logPrefix() + ' WebSocket error:', error
);
1494 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean | undefined {
1495 const localStationInfo
= stationInfo
?? this.stationInfo
;
1496 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1497 ? localStationInfo
.useConnectorId0
1501 private getNumberOfRunningTransactions(): number {
1503 for (const connectorId
of this.connectors
.keys()) {
1504 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1512 private getConnectionTimeout(): number | undefined {
1514 ChargingStationConfigurationUtils
.getConfigurationKey(
1516 StandardParametersKey
.ConnectionTimeOut
1521 ChargingStationConfigurationUtils
.getConfigurationKey(
1523 StandardParametersKey
.ConnectionTimeOut
1525 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1528 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1531 // -1 for unlimited, 0 for disabling
1532 private getAutoReconnectMaxRetries(): number | undefined {
1533 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1534 return this.stationInfo
.autoReconnectMaxRetries
;
1536 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1537 return Configuration
.getAutoReconnectMaxRetries();
1543 private getRegistrationMaxRetries(): number | undefined {
1544 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1545 return this.stationInfo
.registrationMaxRetries
;
1550 private getPowerDivider(): number {
1551 let powerDivider
= this.getNumberOfConnectors();
1552 if (this.stationInfo
?.powerSharedByConnectors
) {
1553 powerDivider
= this.getNumberOfRunningTransactions();
1555 return powerDivider
;
1558 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1559 const localStationInfo
= stationInfo
?? this.stationInfo
;
1560 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1563 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1564 const maximumPower
= this.getMaximumPower(stationInfo
);
1565 switch (this.getCurrentOutType(stationInfo
)) {
1566 case CurrentType
.AC
:
1567 return ACElectricUtils
.amperagePerPhaseFromPower(
1568 this.getNumberOfPhases(stationInfo
),
1569 maximumPower
/ this.getNumberOfConnectors(),
1570 this.getVoltageOut(stationInfo
)
1572 case CurrentType
.DC
:
1573 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1577 private getAmperageLimitation(): number | undefined {
1579 this.stationInfo
.amperageLimitationOcppKey
&&
1580 ChargingStationConfigurationUtils
.getConfigurationKey(
1582 this.stationInfo
.amperageLimitationOcppKey
1587 ChargingStationConfigurationUtils
.getConfigurationKey(
1589 this.stationInfo
.amperageLimitationOcppKey
1591 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1596 private async startMessageSequence(): Promise
<void> {
1597 if (this.stationInfo
?.autoRegister
) {
1598 await this.ocppRequestService
.requestHandler
<
1599 BootNotificationRequest
,
1600 BootNotificationResponse
1603 RequestCommand
.BOOT_NOTIFICATION
,
1605 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1606 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1607 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1608 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1609 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1610 iccid
: this.bootNotificationRequest
.iccid
,
1611 imsi
: this.bootNotificationRequest
.imsi
,
1612 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1613 meterType
: this.bootNotificationRequest
.meterType
,
1615 { skipBufferingOnError
: true }
1618 // Start WebSocket ping
1619 this.startWebSocketPing();
1621 this.startHeartbeat();
1622 // Initialize connectors status
1623 for (const connectorId
of this.connectors
.keys()) {
1624 if (connectorId
=== 0) {
1628 !this.getConnectorStatus(connectorId
)?.status &&
1629 this.getConnectorStatus(connectorId
)?.bootStatus
1631 // Send status in template at startup
1632 await this.ocppRequestService
.requestHandler
<
1633 StatusNotificationRequest
,
1634 StatusNotificationResponse
1635 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1637 status: this.getConnectorStatus(connectorId
).bootStatus
,
1638 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1640 this.getConnectorStatus(connectorId
).status =
1641 this.getConnectorStatus(connectorId
).bootStatus
;
1644 this.getConnectorStatus(connectorId
)?.status &&
1645 this.getConnectorStatus(connectorId
)?.bootStatus
1647 // Send status in template after reset
1648 await this.ocppRequestService
.requestHandler
<
1649 StatusNotificationRequest
,
1650 StatusNotificationResponse
1651 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1653 status: this.getConnectorStatus(connectorId
).bootStatus
,
1654 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1656 this.getConnectorStatus(connectorId
).status =
1657 this.getConnectorStatus(connectorId
).bootStatus
;
1658 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1659 // Send previous status at template reload
1660 await this.ocppRequestService
.requestHandler
<
1661 StatusNotificationRequest
,
1662 StatusNotificationResponse
1663 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1665 status: this.getConnectorStatus(connectorId
).status,
1666 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1669 // Send default status
1670 await this.ocppRequestService
.requestHandler
<
1671 StatusNotificationRequest
,
1672 StatusNotificationResponse
1673 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1675 status: ChargePointStatus
.AVAILABLE
,
1676 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1678 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1682 this.startAutomaticTransactionGenerator();
1685 private startAutomaticTransactionGenerator() {
1686 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
) {
1687 if (!this.automaticTransactionGenerator
) {
1688 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
1689 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
1693 if (!this.automaticTransactionGenerator
.started
) {
1694 this.automaticTransactionGenerator
.start();
1699 private stopAutomaticTransactionGenerator(): void {
1700 if (this.automaticTransactionGenerator
?.started
) {
1701 this.automaticTransactionGenerator
.stop();
1702 this.automaticTransactionGenerator
= null;
1706 private async stopMessageSequence(
1707 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1709 // Stop WebSocket ping
1710 this.stopWebSocketPing();
1712 this.stopHeartbeat();
1713 // Stop ongoing transactions
1714 if (this.automaticTransactionGenerator
?.configuration
?.enable
) {
1715 this.stopAutomaticTransactionGenerator();
1717 for (const connectorId
of this.connectors
.keys()) {
1718 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1719 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1721 this.getBeginEndMeterValues() &&
1722 this.getOcppStrictCompliance() &&
1723 !this.getOutOfOrderEndMeterValues()
1725 // FIXME: Implement OCPP version agnostic helpers
1726 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1729 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1731 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
1733 RequestCommand
.METER_VALUES
,
1737 meterValue
: [transactionEndMeterValue
],
1741 await this.ocppRequestService
.requestHandler
<
1742 StopTransactionRequest
,
1743 StopTransactionResponse
1744 >(this, RequestCommand
.STOP_TRANSACTION
, {
1746 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1747 idTag
: this.getTransactionIdTag(transactionId
),
1755 private startWebSocketPing(): void {
1756 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1758 StandardParametersKey
.WebSocketPingInterval
1760 ? Utils
.convertToInt(
1761 ChargingStationConfigurationUtils
.getConfigurationKey(
1763 StandardParametersKey
.WebSocketPingInterval
1767 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1768 this.webSocketPingSetInterval
= setInterval(() => {
1769 if (this.isWebSocketConnectionOpened()) {
1770 this.wsConnection
.ping((): void => {
1771 /* This is intentional */
1774 }, webSocketPingInterval
* 1000);
1777 ' WebSocket ping started every ' +
1778 Utils
.formatDurationSeconds(webSocketPingInterval
)
1780 } else if (this.webSocketPingSetInterval
) {
1783 ' WebSocket ping every ' +
1784 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1789 `${this.logPrefix()} WebSocket ping interval set to ${
1790 webSocketPingInterval
1791 ? Utils.formatDurationSeconds(webSocketPingInterval)
1792 : webSocketPingInterval
1793 }, not starting the WebSocket ping`
1798 private stopWebSocketPing(): void {
1799 if (this.webSocketPingSetInterval
) {
1800 clearInterval(this.webSocketPingSetInterval
);
1804 private getConfiguredSupervisionUrl(): URL
{
1805 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1806 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1808 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1810 switch (Configuration
.getSupervisionUrlDistribution()) {
1811 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1812 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1814 case SupervisionUrlDistribution
.RANDOM
:
1816 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1818 case SupervisionUrlDistribution
.SEQUENTIAL
:
1819 if (this.index
<= supervisionUrls
.length
) {
1820 urlIndex
= this.index
- 1;
1823 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1829 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1830 SupervisionUrlDistribution.ROUND_ROBIN
1833 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1836 return new URL(supervisionUrls
[urlIndex
]);
1838 return new URL(supervisionUrls
as string);
1841 private getHeartbeatInterval(): number | undefined {
1842 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1844 StandardParametersKey
.HeartbeatInterval
1846 if (HeartbeatInterval
) {
1847 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1849 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1851 StandardParametersKey
.HeartBeatInterval
1853 if (HeartBeatInterval
) {
1854 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1856 !this.stationInfo
?.autoRegister
&&
1858 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1859 Constants.DEFAULT_HEARTBEAT_INTERVAL
1862 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1865 private stopHeartbeat(): void {
1866 if (this.heartbeatSetInterval
) {
1867 clearInterval(this.heartbeatSetInterval
);
1871 private openWSConnection(
1872 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
1873 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
1875 terminateOpened
: false,
1878 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
1879 params
.closeOpened
= params
?.closeOpened
?? false;
1880 params
.terminateOpened
= params
?.terminateOpened
?? false;
1882 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
1883 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
1885 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
1887 if (params
?.closeOpened
) {
1888 this.closeWSConnection();
1890 if (params
?.terminateOpened
) {
1891 this.terminateWSConnection();
1893 let protocol
: string;
1894 switch (this.getOcppVersion()) {
1895 case OCPPVersion
.VERSION_16
:
1896 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
1899 this.handleUnsupportedVersion(this.getOcppVersion());
1904 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString()
1907 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
1909 // Handle WebSocket message
1910 this.wsConnection
.on(
1912 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
1914 // Handle WebSocket error
1915 this.wsConnection
.on(
1917 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
1919 // Handle WebSocket close
1920 this.wsConnection
.on(
1922 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
1924 // Handle WebSocket open
1925 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
1926 // Handle WebSocket ping
1927 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
1928 // Handle WebSocket pong
1929 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
1932 private closeWSConnection(): void {
1933 if (this.isWebSocketConnectionOpened()) {
1934 this.wsConnection
.close();
1935 this.wsConnection
= null;
1939 private terminateWSConnection(): void {
1940 if (this.isWebSocketConnectionOpened()) {
1941 this.wsConnection
.terminate();
1942 this.wsConnection
= null;
1946 private stopMeterValues(connectorId
: number) {
1947 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1948 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1952 private getReconnectExponentialDelay(): boolean | undefined {
1953 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1954 ? this.stationInfo
.reconnectExponentialDelay
1958 private async reconnect(code
: number): Promise
<void> {
1959 // Stop WebSocket ping
1960 this.stopWebSocketPing();
1962 this.stopHeartbeat();
1963 // Stop the ATG if needed
1964 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
) {
1965 this.stopAutomaticTransactionGenerator();
1968 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1969 this.getAutoReconnectMaxRetries() === -1
1971 this.autoReconnectRetryCount
++;
1972 const reconnectDelay
= this.getReconnectExponentialDelay()
1973 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1974 : this.getConnectionTimeout() * 1000;
1975 const reconnectDelayWithdraw
= 1000;
1976 const reconnectTimeout
=
1977 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
1978 ? reconnectDelay
- reconnectDelayWithdraw
1981 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1984 )}ms, timeout ${reconnectTimeout}ms`
1986 await Utils
.sleep(reconnectDelay
);
1989 ' WebSocket: reconnecting try #' +
1990 this.autoReconnectRetryCount
.toString()
1992 this.openWSConnection(
1993 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
1994 { closeOpened
: true }
1996 this.wsConnectionRestarted
= true;
1997 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1999 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2000 this.autoReconnectRetryCount
2001 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2006 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
2007 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2010 private initializeConnectorStatus(connectorId
: number): void {
2011 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2012 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2013 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2014 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2015 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2016 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;