1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import { ACElectricUtils
, DCElectricUtils
} from
'../utils/ElectricUtils';
6 BootNotificationRequest
,
10 IncomingRequestCommand
,
13 StatusNotificationRequest
,
14 } from
'../types/ocpp/Requests';
16 BootNotificationResponse
,
22 StatusNotificationResponse
,
23 } from
'../types/ocpp/Responses';
24 import { ChargingProfile
, ChargingRateUnitType
} from
'../types/ocpp/ChargingProfile';
25 import ChargingStationConfiguration
, { Section
} from
'../types/ChargingStationConfiguration';
26 import ChargingStationTemplate
, {
30 } from
'../types/ChargingStationTemplate';
32 ConnectorPhaseRotation
,
33 StandardParametersKey
,
34 SupportedFeatureProfiles
,
35 VendorDefaultParametersKey
,
36 } from
'../types/ocpp/Configuration';
37 import { MeterValue
, MeterValueMeasurand
} from
'../types/ocpp/MeterValues';
39 StopTransactionReason
,
40 StopTransactionRequest
,
41 StopTransactionResponse
,
42 } from
'../types/ocpp/Transaction';
43 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
44 import WebSocket
, { Data
, OPEN
, RawData
} from
'ws';
46 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
47 import BaseError from
'../exception/BaseError';
48 import { ChargePointErrorCode
} from
'../types/ocpp/ChargePointErrorCode';
49 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
50 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
51 import ChargingStationInfo from
'../types/ChargingStationInfo';
52 import ChargingStationOcppConfiguration from
'../types/ChargingStationOcppConfiguration';
53 import { ChargingStationUtils
} from
'./ChargingStationUtils';
54 import { ChargingStationWorkerMessageEvents
} from
'../types/ChargingStationWorker';
55 import Configuration from
'../utils/Configuration';
56 import { ConnectorStatus
} from
'../types/ConnectorStatus';
57 import Constants from
'../utils/Constants';
58 import { ErrorType
} from
'../types/ocpp/ErrorType';
59 import { FileType
} from
'../types/FileType';
60 import FileUtils from
'../utils/FileUtils';
61 import { JsonType
} from
'../types/JsonType';
62 import { MessageType
} from
'../types/ocpp/MessageType';
63 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
64 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
65 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
66 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
67 import OCPPError from
'../exception/OCPPError';
68 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
69 import OCPPRequestService from
'./ocpp/OCPPRequestService';
70 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
71 import PerformanceStatistics from
'../performance/PerformanceStatistics';
72 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
73 import { URL
} from
'url';
74 import Utils from
'../utils/Utils';
75 import crypto from
'crypto';
77 import logger from
'../utils/Logger';
78 import { parentPort
} from
'worker_threads';
79 import path from
'path';
81 export default class ChargingStation
{
82 public hashId
!: string;
83 public readonly templateFile
: string;
84 public authorizedTags
: string[];
85 public stationInfo
!: ChargingStationInfo
;
86 public readonly connectors
: Map
<number, ConnectorStatus
>;
87 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
88 public wsConnection
!: WebSocket
;
89 public readonly requests
: Map
<string, CachedRequest
>;
90 public performanceStatistics
!: PerformanceStatistics
;
91 public heartbeatSetInterval
!: NodeJS
.Timeout
;
92 public ocppRequestService
!: OCPPRequestService
;
93 public bootNotificationResponse
!: BootNotificationResponse
| null;
94 private readonly index
: number;
95 private configurationFile
!: string;
96 private bootNotificationRequest
!: BootNotificationRequest
;
97 private connectorsConfigurationHash
!: string;
98 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
99 private readonly messageBuffer
: Set
<string>;
100 private wsConfiguredConnectionUrl
!: URL
;
101 private wsConnectionRestarted
: boolean;
102 private stopped
: boolean;
103 private autoReconnectRetryCount
: number;
104 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
105 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
107 constructor(index
: number, templateFile
: string) {
109 this.templateFile
= templateFile
;
110 this.stopped
= false;
111 this.wsConnectionRestarted
= false;
112 this.autoReconnectRetryCount
= 0;
113 this.connectors
= new Map
<number, ConnectorStatus
>();
114 this.requests
= new Map
<string, CachedRequest
>();
115 this.messageBuffer
= new Set
<string>();
117 this.authorizedTags
= this.getAuthorizedTags();
120 private get
wsConnectionUrl(): URL
{
121 return this.getSupervisionUrlOcppConfiguration()
123 ChargingStationConfigurationUtils
.getConfigurationKey(
125 this.getSupervisionUrlOcppKey()
128 this.stationInfo
.chargingStationId
130 : this.wsConfiguredConnectionUrl
;
133 public logPrefix(): string {
134 return Utils
.logPrefix(
136 this?.stationInfo?.chargingStationId ??
137 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
142 public getBootNotificationRequest(): BootNotificationRequest
{
143 return this.bootNotificationRequest
;
146 public getRandomIdTag(): string {
147 const index
= Math.floor(Utils
.secureRandom() * this.authorizedTags
.length
);
148 return this.authorizedTags
[index
];
151 public hasAuthorizedTags(): boolean {
152 return !Utils
.isEmptyArray(this.authorizedTags
);
155 public getEnableStatistics(): boolean | undefined {
156 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
157 ? this.stationInfo
.enableStatistics
161 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
162 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
165 public getNumberOfPhases(): number | undefined {
166 switch (this.getCurrentOutType()) {
168 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
)
169 ? this.stationInfo
.numberOfPhases
176 public isWebSocketConnectionOpened(): boolean {
177 return this?.wsConnection
?.readyState
=== OPEN
;
180 public getRegistrationStatus(): RegistrationStatus
{
181 return this?.bootNotificationResponse
?.status;
184 public isInUnknownState(): boolean {
185 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
188 public isInPendingState(): boolean {
189 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
192 public isInAcceptedState(): boolean {
193 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
196 public isInRejectedState(): boolean {
197 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
200 public isRegistered(): boolean {
201 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
204 public isChargingStationAvailable(): boolean {
205 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
208 public isConnectorAvailable(id
: number): boolean {
209 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
212 public getNumberOfConnectors(): number {
213 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
216 public getConnectorStatus(id
: number): ConnectorStatus
{
217 return this.connectors
.get(id
);
220 public getCurrentOutType(): CurrentType
| undefined {
221 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
224 public getOcppStrictCompliance(): boolean {
225 return this.stationInfo
?.ocppStrictCompliance
?? false;
228 public getVoltageOut(): number | undefined {
229 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
230 this.getCurrentOutType(),
234 return !Utils
.isUndefined(this.stationInfo
.voltageOut
)
235 ? this.stationInfo
.voltageOut
239 public getConnectorMaximumAvailablePower(connectorId
: number): number {
240 let connectorAmperageLimitationPowerLimit
: number;
242 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
243 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
245 connectorAmperageLimitationPowerLimit
=
246 (this.getCurrentOutType() === CurrentType
.AC
247 ? ACElectricUtils
.powerTotal(
248 this.getNumberOfPhases(),
249 this.getVoltageOut(),
250 this.getAmperageLimitation() * this.getNumberOfConnectors()
252 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
253 this.stationInfo
.powerDivider
;
255 const connectorMaximumPower
= this.getMaximumPower() / this.stationInfo
.powerDivider
;
256 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
258 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
259 isNaN(connectorAmperageLimitationPowerLimit
)
261 : connectorAmperageLimitationPowerLimit
,
262 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
266 public getTransactionIdTag(transactionId
: number): string | undefined {
267 for (const connectorId
of this.connectors
.keys()) {
268 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
269 return this.getConnectorStatus(connectorId
).transactionIdTag
;
274 public getOutOfOrderEndMeterValues(): boolean {
275 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
278 public getBeginEndMeterValues(): boolean {
279 return this.stationInfo
?.beginEndMeterValues
?? false;
282 public getMeteringPerTransaction(): boolean {
283 return this.stationInfo
?.meteringPerTransaction
?? true;
286 public getTransactionDataMeterValues(): boolean {
287 return this.stationInfo
?.transactionDataMeterValues
?? false;
290 public getMainVoltageMeterValues(): boolean {
291 return this.stationInfo
?.mainVoltageMeterValues
?? true;
294 public getPhaseLineToLineVoltageMeterValues(): boolean {
295 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
298 public getCustomValueLimitationMeterValues(): boolean {
299 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
302 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
303 for (const connectorId
of this.connectors
.keys()) {
306 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
313 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
314 const transactionConnectorStatus
= this.getConnectorStatus(
315 this.getConnectorIdByTransactionId(transactionId
)
317 if (this.getMeteringPerTransaction()) {
318 return transactionConnectorStatus
?.transactionEnergyActiveImportRegisterValue
;
320 return transactionConnectorStatus
?.energyActiveImportRegisterValue
;
323 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
324 const connectorStatus
= this.getConnectorStatus(connectorId
);
325 if (this.getMeteringPerTransaction()) {
326 return connectorStatus
?.transactionEnergyActiveImportRegisterValue
;
328 return connectorStatus
?.energyActiveImportRegisterValue
;
331 public getAuthorizeRemoteTxRequests(): boolean {
332 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
334 StandardParametersKey
.AuthorizeRemoteTxRequests
336 return authorizeRemoteTxRequests
337 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
341 public getLocalAuthListEnabled(): boolean {
342 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
344 StandardParametersKey
.LocalAuthListEnabled
346 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
349 public startHeartbeat(): void {
351 this.getHeartbeatInterval() &&
352 this.getHeartbeatInterval() > 0 &&
353 !this.heartbeatSetInterval
355 // eslint-disable-next-line @typescript-eslint/no-misused-promises
356 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
357 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
359 RequestCommand
.HEARTBEAT
361 }, this.getHeartbeatInterval());
364 ' Heartbeat started every ' +
365 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
367 } else if (this.heartbeatSetInterval
) {
370 ' Heartbeat already started every ' +
371 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
375 `${this.logPrefix()} Heartbeat interval set to ${
376 this.getHeartbeatInterval()
377 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
378 : this.getHeartbeatInterval()
379 }, not starting the heartbeat`
384 public restartHeartbeat(): void {
386 this.stopHeartbeat();
388 this.startHeartbeat();
391 public restartWebSocketPing(): void {
392 // Stop WebSocket ping
393 this.stopWebSocketPing();
394 // Start WebSocket ping
395 this.startWebSocketPing();
398 public startMeterValues(connectorId
: number, interval
: number): void {
399 if (connectorId
=== 0) {
401 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
405 if (!this.getConnectorStatus(connectorId
)) {
407 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
411 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
413 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
417 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
418 !this.getConnectorStatus(connectorId
)?.transactionId
421 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
426 // eslint-disable-next-line @typescript-eslint/no-misused-promises
427 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
428 // eslint-disable-next-line @typescript-eslint/no-misused-promises
429 async (): Promise
<void> => {
430 // FIXME: Implement OCPP version agnostic helpers
431 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
434 this.getConnectorStatus(connectorId
).transactionId
,
437 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
439 RequestCommand
.METER_VALUES
,
442 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
443 meterValue
: [meterValue
],
451 `${this.logPrefix()} Charging station ${
452 StandardParametersKey.MeterValueSampleInterval
453 } configuration set to ${
454 interval ? Utils.formatDurationMilliSeconds(interval) : interval
455 }, not sending MeterValues`
460 public start(): void {
461 if (this.getEnableStatistics()) {
462 this.performanceStatistics
.start();
464 this.openWSConnection();
465 // Handle WebSocket message
466 this.wsConnection
.on(
468 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
470 // Handle WebSocket error
471 this.wsConnection
.on(
473 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
475 // Handle WebSocket close
476 this.wsConnection
.on(
478 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
480 // Handle WebSocket open
481 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
482 // Handle WebSocket ping
483 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
484 // Handle WebSocket pong
485 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
486 // Monitor authorization file
487 FileUtils
.watchJsonFile
<string[]>(
489 FileType
.Authorization
,
490 this.getAuthorizationFile(),
493 // Monitor charging station template file
494 FileUtils
.watchJsonFile(
496 FileType
.ChargingStationTemplate
,
499 (event
, filename
): void => {
500 if (filename
&& event
=== 'change') {
503 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
505 } file have changed, reload`
511 !this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
512 this.automaticTransactionGenerator
514 this.automaticTransactionGenerator
.stop();
516 this.startAutomaticTransactionGenerator();
517 if (this.getEnableStatistics()) {
518 this.performanceStatistics
.restart();
520 this.performanceStatistics
.stop();
522 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
525 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
532 parentPort
.postMessage({
533 id
: ChargingStationWorkerMessageEvents
.STARTED
,
534 data
: { id
: this.stationInfo
.chargingStationId
},
538 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
539 // Stop message sequence
540 await this.stopMessageSequence(reason
);
541 for (const connectorId
of this.connectors
.keys()) {
542 if (connectorId
> 0) {
543 await this.ocppRequestService
.requestHandler
<
544 StatusNotificationRequest
,
545 StatusNotificationResponse
546 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
548 status: ChargePointStatus
.UNAVAILABLE
,
549 errorCode
: ChargePointErrorCode
.NO_ERROR
,
551 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
554 if (this.isWebSocketConnectionOpened()) {
555 this.wsConnection
.close();
557 if (this.getEnableStatistics()) {
558 this.performanceStatistics
.stop();
560 this.bootNotificationResponse
= null;
561 parentPort
.postMessage({
562 id
: ChargingStationWorkerMessageEvents
.STOPPED
,
563 data
: { id
: this.stationInfo
.chargingStationId
},
568 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
569 await this.stop(reason
);
570 await Utils
.sleep(this.stationInfo
.resetTime
);
571 this.stationInfo
= this.getStationInfo();
572 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
576 public saveOcppConfiguration(): void {
577 if (this.getOcppPersistentConfiguration()) {
578 this.saveConfiguration(Section
.ocppConfiguration
);
582 public getChargingProfilePowerLimit(connectorId
: number): number | undefined {
583 let limit
: number, matchingChargingProfile
: ChargingProfile
;
584 let chargingProfiles
: ChargingProfile
[] = [];
585 // Get charging profiles for connector and sort by stack level
586 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
587 (a
, b
) => b
.stackLevel
- a
.stackLevel
589 // Get profiles on connector 0
590 if (this.getConnectorStatus(0).chargingProfiles
) {
591 chargingProfiles
.push(
592 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
595 if (!Utils
.isEmptyArray(chargingProfiles
)) {
596 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
600 if (!Utils
.isNullOrUndefined(result
)) {
601 limit
= result
.limit
;
602 matchingChargingProfile
= result
.matchingChargingProfile
;
603 switch (this.getCurrentOutType()) {
606 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
607 ChargingRateUnitType
.WATT
609 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
613 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
614 ChargingRateUnitType
.WATT
616 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
619 const connectorMaximumPower
= this.getMaximumPower() / this.stationInfo
.powerDivider
;
620 if (limit
> connectorMaximumPower
) {
622 `${this.logPrefix()} Charging profile id ${
623 matchingChargingProfile.chargingProfileId
624 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
625 this.getConnectorStatus(connectorId
).chargingProfiles
627 limit
= connectorMaximumPower
;
634 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
635 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
637 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
639 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
641 if (!Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
643 `${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`
645 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
647 let cpReplaced
= false;
648 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
649 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
650 (chargingProfile
: ChargingProfile
, index
: number) => {
652 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
653 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
654 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
656 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
662 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
665 public resetConnectorStatus(connectorId
: number): void {
666 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
667 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
668 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
669 this.getConnectorStatus(connectorId
).transactionStarted
= false;
670 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
671 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
672 delete this.getConnectorStatus(connectorId
).transactionId
;
673 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
674 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
675 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
676 this.stopMeterValues(connectorId
);
679 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
680 return ChargingStationConfigurationUtils
.getConfigurationKey(
682 StandardParametersKey
.SupportedFeatureProfiles
683 )?.value
.includes(featureProfile
);
686 public bufferMessage(message
: string): void {
687 this.messageBuffer
.add(message
);
690 private flushMessageBuffer() {
691 if (this.messageBuffer
.size
> 0) {
692 this.messageBuffer
.forEach((message
) => {
693 // TODO: evaluate the need to track performance
694 this.wsConnection
.send(message
);
695 this.messageBuffer
.delete(message
);
700 private getSupervisionUrlOcppConfiguration(): boolean {
701 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
704 private getSupervisionUrlOcppKey(): string {
705 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
708 private getTemplateFromFile(): ChargingStationTemplate
| null {
709 let template
: ChargingStationTemplate
= null;
711 const measureId
= `${FileType.ChargingStationTemplate} read`;
712 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
713 template
= JSON
.parse(fs
.readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
;
714 PerformanceStatistics
.endMeasure(measureId
, beginId
);
715 template
.templateHash
= crypto
716 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
717 .update(JSON
.stringify(template
))
720 FileUtils
.handleFileException(
722 FileType
.ChargingStationTemplate
,
724 error
as NodeJS
.ErrnoException
730 private getStationInfoFromTemplate(): ChargingStationInfo
{
731 const stationInfo
: ChargingStationInfo
= this.getTemplateFromFile();
732 if (Utils
.isNullOrUndefined(stationInfo
)) {
733 const errorMsg
= 'Failed to read charging station template file';
734 logger
.error(`${this.logPrefix()} ${errorMsg}`);
735 throw new BaseError(errorMsg
);
737 if (Utils
.isEmptyObject(stationInfo
)) {
738 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
739 logger
.error(`${this.logPrefix()} ${errorMsg}`);
740 throw new BaseError(errorMsg
);
742 const chargingStationId
= ChargingStationUtils
.getChargingStationId(this.index
, stationInfo
);
743 // Deprecation template keys section
744 ChargingStationUtils
.warnDeprecatedTemplateKey(
749 "Use 'supervisionUrls' instead"
751 ChargingStationUtils
.convertDeprecatedTemplateKey(
756 if (!Utils
.isEmptyArray(stationInfo
.power
)) {
757 stationInfo
.power
= stationInfo
.power
as number[];
758 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationInfo
.power
.length
);
759 stationInfo
.maximumPower
=
760 stationInfo
.powerUnit
=== PowerUnits
.KILO_WATT
761 ? stationInfo
.power
[powerArrayRandomIndex
] * 1000
762 : stationInfo
.power
[powerArrayRandomIndex
];
764 stationInfo
.power
= stationInfo
.power
as number;
765 stationInfo
.maximumPower
=
766 stationInfo
.powerUnit
=== PowerUnits
.KILO_WATT
767 ? stationInfo
.power
* 1000
770 delete stationInfo
.power
;
771 delete stationInfo
.powerUnit
;
772 stationInfo
.chargingStationId
= chargingStationId
;
773 stationInfo
.resetTime
= stationInfo
.resetTime
774 ? stationInfo
.resetTime
* 1000
775 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
779 private getStationInfoFromFile(): ChargingStationInfo
| null {
780 let stationInfo
: ChargingStationInfo
= null;
781 if (this.getStationInfoPersistentConfiguration()) {
782 stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null;
785 stationInfo
= ChargingStationUtils
.createStationInfoHash(stationInfo
);
790 private getStationInfo(): ChargingStationInfo
{
791 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
792 this.hashId
= ChargingStationUtils
.getHashId(stationInfoFromTemplate
);
793 this.configurationFile
= path
.join(
794 path
.resolve(__dirname
, '../'),
797 this.hashId
+ '.json'
799 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
800 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
801 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
802 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
803 return this.stationInfo
;
805 return stationInfoFromFile
;
807 ChargingStationUtils
.createSerialNumber(stationInfoFromTemplate
, stationInfoFromFile
);
808 return stationInfoFromTemplate
;
811 private saveStationInfo(): void {
812 if (this.getStationInfoPersistentConfiguration()) {
813 this.saveConfiguration(Section
.stationInfo
);
817 private getOcppVersion(): OCPPVersion
{
818 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
821 private getOcppPersistentConfiguration(): boolean {
822 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
825 private getStationInfoPersistentConfiguration(): boolean {
826 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
829 private handleUnsupportedVersion(version
: OCPPVersion
) {
830 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
833 logger
.error(errMsg
);
834 throw new Error(errMsg
);
837 private initialize(): void {
838 this.stationInfo
= this.getStationInfo();
839 logger
.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
840 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
843 this.ocppConfiguration
= this.getOcppConfiguration();
844 this.stationInfo
?.Configuration
&& delete this.stationInfo
.Configuration
;
845 this.wsConfiguredConnectionUrl
= new URL(
846 this.getConfiguredSupervisionUrl().href
+ '/' + this.stationInfo
.chargingStationId
848 // Build connectors if needed
849 const maxConnectors
= this.getMaxNumberOfConnectors();
850 this.checkMaxConnectors(maxConnectors
);
851 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
852 this.checkTemplateMaxConnectors(templateMaxConnectors
);
855 (this.stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
856 !this.stationInfo
?.randomConnectors
859 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
861 }, forcing random connector configurations affectation`
863 this.stationInfo
.randomConnectors
= true;
865 this.initializeConnectors(this.stationInfo
, maxConnectors
, templateMaxConnectors
);
866 this.stationInfo
.maximumAmperage
= this.getMaximumAmperage();
867 if (this.stationInfo
) {
868 this.stationInfo
= ChargingStationUtils
.createStationInfoHash(this.stationInfo
);
870 this.saveStationInfo();
871 // Avoid duplication of connectors related information in RAM
872 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
873 // OCPP configuration
874 this.initializeOcppConfiguration();
875 if (this.getEnableStatistics()) {
876 this.performanceStatistics
= PerformanceStatistics
.getInstance(
878 this.stationInfo
.chargingStationId
,
882 switch (this.getOcppVersion()) {
883 case OCPPVersion
.VERSION_16
:
884 this.ocppIncomingRequestService
=
885 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
886 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
887 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
891 this.handleUnsupportedVersion(this.getOcppVersion());
894 if (this.stationInfo
.autoRegister
) {
895 this.bootNotificationResponse
= {
896 currentTime
: new Date().toISOString(),
897 interval
: this.getHeartbeatInterval() / 1000,
898 status: RegistrationStatus
.ACCEPTED
,
901 this.stationInfo
.powerDivider
= this.getPowerDivider();
904 private initializeOcppConfiguration(): void {
906 !ChargingStationConfigurationUtils
.getConfigurationKey(
908 StandardParametersKey
.HeartbeatInterval
911 ChargingStationConfigurationUtils
.addConfigurationKey(
913 StandardParametersKey
.HeartbeatInterval
,
918 !ChargingStationConfigurationUtils
.getConfigurationKey(
920 StandardParametersKey
.HeartBeatInterval
923 ChargingStationConfigurationUtils
.addConfigurationKey(
925 StandardParametersKey
.HeartBeatInterval
,
931 this.getSupervisionUrlOcppConfiguration() &&
932 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
934 ChargingStationConfigurationUtils
.addConfigurationKey(
936 this.getSupervisionUrlOcppKey(),
937 this.getConfiguredSupervisionUrl().href
,
941 !this.getSupervisionUrlOcppConfiguration() &&
942 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
944 ChargingStationConfigurationUtils
.deleteConfigurationKey(
946 this.getSupervisionUrlOcppKey(),
951 this.stationInfo
.amperageLimitationOcppKey
&&
952 !ChargingStationConfigurationUtils
.getConfigurationKey(
954 this.stationInfo
.amperageLimitationOcppKey
957 ChargingStationConfigurationUtils
.addConfigurationKey(
959 this.stationInfo
.amperageLimitationOcppKey
,
961 this.stationInfo
.maximumAmperage
*
962 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
967 !ChargingStationConfigurationUtils
.getConfigurationKey(
969 StandardParametersKey
.SupportedFeatureProfiles
972 ChargingStationConfigurationUtils
.addConfigurationKey(
974 StandardParametersKey
.SupportedFeatureProfiles
,
975 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
978 ChargingStationConfigurationUtils
.addConfigurationKey(
980 StandardParametersKey
.NumberOfConnectors
,
981 this.getNumberOfConnectors().toString(),
986 !ChargingStationConfigurationUtils
.getConfigurationKey(
988 StandardParametersKey
.MeterValuesSampledData
991 ChargingStationConfigurationUtils
.addConfigurationKey(
993 StandardParametersKey
.MeterValuesSampledData
,
994 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
998 !ChargingStationConfigurationUtils
.getConfigurationKey(
1000 StandardParametersKey
.ConnectorPhaseRotation
1003 const connectorPhaseRotation
= [];
1004 for (const connectorId
of this.connectors
.keys()) {
1006 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1007 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1008 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1009 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1011 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1012 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1013 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1014 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1017 ChargingStationConfigurationUtils
.addConfigurationKey(
1019 StandardParametersKey
.ConnectorPhaseRotation
,
1020 connectorPhaseRotation
.toString()
1024 !ChargingStationConfigurationUtils
.getConfigurationKey(
1026 StandardParametersKey
.AuthorizeRemoteTxRequests
1029 ChargingStationConfigurationUtils
.addConfigurationKey(
1031 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1036 !ChargingStationConfigurationUtils
.getConfigurationKey(
1038 StandardParametersKey
.LocalAuthListEnabled
1040 ChargingStationConfigurationUtils
.getConfigurationKey(
1042 StandardParametersKey
.SupportedFeatureProfiles
1043 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1045 ChargingStationConfigurationUtils
.addConfigurationKey(
1047 StandardParametersKey
.LocalAuthListEnabled
,
1052 !ChargingStationConfigurationUtils
.getConfigurationKey(
1054 StandardParametersKey
.ConnectionTimeOut
1057 ChargingStationConfigurationUtils
.addConfigurationKey(
1059 StandardParametersKey
.ConnectionTimeOut
,
1060 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1063 this.saveOcppConfiguration();
1066 private initializeConnectors(
1067 stationInfo
: ChargingStationInfo
,
1068 maxConnectors
: number,
1069 templateMaxConnectors
: number
1071 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1072 const logMsg
= `${this.logPrefix()} No already defined connectors and charging station information from template ${
1074 } with no connectors configuration defined`;
1075 logger
.error(logMsg
);
1076 throw new BaseError(logMsg
);
1078 if (!stationInfo
?.Connectors
[0]) {
1080 `${this.logPrefix()} Charging station information from template ${
1082 } with no connector Id 0 configuration`
1085 if (stationInfo
?.Connectors
) {
1086 const connectorsConfigHash
= crypto
1087 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1088 .update(JSON
.stringify(stationInfo
?.Connectors
) + maxConnectors
.toString())
1090 const connectorsConfigChanged
=
1091 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1092 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1093 connectorsConfigChanged
&& this.connectors
.clear();
1094 this.connectorsConfigurationHash
= connectorsConfigHash
;
1095 // Add connector Id 0
1096 let lastConnector
= '0';
1097 for (lastConnector
in stationInfo
?.Connectors
) {
1098 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1100 lastConnectorId
=== 0 &&
1101 this.getUseConnectorId0() &&
1102 stationInfo
?.Connectors
[lastConnector
]
1104 this.connectors
.set(
1106 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1108 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1109 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1110 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1114 // Generate all connectors
1115 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1116 for (let index
= 1; index
<= maxConnectors
; index
++) {
1117 const randConnectorId
= stationInfo
?.randomConnectors
1118 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1120 this.connectors
.set(
1122 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1124 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1125 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1126 this.getConnectorStatus(index
).chargingProfiles
= [];
1133 `${this.logPrefix()} Charging station information from template ${
1135 } with no connectors configuration defined, using already defined connectors`
1138 // Initialize transaction attributes on connectors
1139 for (const connectorId
of this.connectors
.keys()) {
1140 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1141 this.initializeConnectorStatus(connectorId
);
1146 private checkMaxConnectors(maxConnectors
: number): void {
1147 if (maxConnectors
<= 0) {
1149 `${this.logPrefix()} Charging station information from template ${
1151 } with ${maxConnectors} connectors`
1156 private checkTemplateMaxConnectors(templateMaxConnectors
: number): void {
1157 if (templateMaxConnectors
=== 0) {
1159 `${this.logPrefix()} Charging station information from template ${
1161 } with empty connectors configuration`
1163 } else if (templateMaxConnectors
< 0) {
1165 `${this.logPrefix()} Charging station information from template ${
1167 } with no connectors configuration defined`
1172 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1173 let configuration
: ChargingStationConfiguration
= null;
1174 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1176 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1177 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1178 configuration
= JSON
.parse(
1179 fs
.readFileSync(this.configurationFile
, 'utf8')
1180 ) as ChargingStationConfiguration
;
1181 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1183 FileUtils
.handleFileException(
1185 FileType
.ChargingStationConfiguration
,
1186 this.configurationFile
,
1187 error
as NodeJS
.ErrnoException
1191 return configuration
;
1194 private saveConfiguration(section
?: Section
): void {
1195 if (this.configurationFile
) {
1197 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1198 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1200 const configurationData
: ChargingStationConfiguration
=
1201 this.getConfigurationFromFile() ?? {};
1203 case Section
.ocppConfiguration
:
1204 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1206 case Section
.stationInfo
:
1207 if (configurationData
?.stationInfo
?.infoHash
=== this.stationInfo
?.infoHash
) {
1209 `${this.logPrefix()} Not saving unchanged charging station information to configuration file ${
1210 this.configurationFile
1215 configurationData
.stationInfo
= this.stationInfo
;
1218 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1219 if (configurationData
?.stationInfo
?.infoHash
!== this.stationInfo
?.infoHash
) {
1220 configurationData
.stationInfo
= this.stationInfo
;
1224 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1225 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1226 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1227 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1228 fs
.closeSync(fileDescriptor
);
1229 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1231 FileUtils
.handleFileException(
1233 FileType
.ChargingStationConfiguration
,
1234 this.configurationFile
,
1235 error
as NodeJS
.ErrnoException
1240 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1245 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1246 return this.getTemplateFromFile()?.Configuration
?? null;
1249 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1250 let configuration
: ChargingStationConfiguration
= null;
1251 if (this.getOcppPersistentConfiguration()) {
1252 const configurationFromFile
= this.getConfigurationFromFile();
1253 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1255 configuration
&& delete configuration
.stationInfo
;
1256 return configuration
;
1259 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1260 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1261 if (!ocppConfiguration
) {
1262 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1264 return ocppConfiguration
;
1267 private async onOpen(): Promise
<void> {
1268 if (this.isWebSocketConnectionOpened()) {
1270 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1272 if (!this.isRegistered()) {
1273 // Send BootNotification
1274 let registrationRetryCount
= 0;
1276 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1277 BootNotificationRequest
,
1278 BootNotificationResponse
1281 RequestCommand
.BOOT_NOTIFICATION
,
1283 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1284 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1285 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1286 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1287 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1288 iccid
: this.bootNotificationRequest
.iccid
,
1289 imsi
: this.bootNotificationRequest
.imsi
,
1290 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1291 meterType
: this.bootNotificationRequest
.meterType
,
1293 { skipBufferingOnError
: true }
1295 if (!this.isRegistered()) {
1296 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1298 this.bootNotificationResponse
?.interval
1299 ? this.bootNotificationResponse
.interval
* 1000
1300 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1304 !this.isRegistered() &&
1305 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1306 this.getRegistrationMaxRetries() === -1)
1309 if (this.isRegistered()) {
1310 if (this.isInAcceptedState()) {
1311 await this.startMessageSequence();
1312 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1316 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1319 this.stopped
&& (this.stopped
= false);
1320 this.autoReconnectRetryCount
= 0;
1321 this.wsConnectionRestarted
= false;
1324 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1329 private async onClose(code
: number, reason
: string): Promise
<void> {
1332 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1333 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1335 `${this.logPrefix()} WebSocket normally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1337 )}' and reason '${reason}'`
1339 this.autoReconnectRetryCount
= 0;
1344 `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1346 )}' and reason '${reason}'`
1348 await this.reconnect(code
);
1353 private async onMessage(data
: Data
): Promise
<void> {
1354 let messageType
: number;
1355 let messageId
: string;
1356 let commandName
: IncomingRequestCommand
;
1357 let commandPayload
: JsonType
;
1358 let errorType
: ErrorType
;
1359 let errorMessage
: string;
1360 let errorDetails
: JsonType
;
1361 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1362 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1363 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1364 let requestPayload
: JsonType
;
1365 let cachedRequest
: CachedRequest
;
1368 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1369 if (Utils
.isIterable(request
)) {
1370 [messageType
, messageId
] = request
;
1371 // Check the type of message
1372 switch (messageType
) {
1374 case MessageType
.CALL_MESSAGE
:
1375 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1376 if (this.getEnableStatistics()) {
1377 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1380 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1384 // Process the message
1385 await this.ocppIncomingRequestService
.incomingRequestHandler(
1393 case MessageType
.CALL_RESULT_MESSAGE
:
1394 [, , commandPayload
] = request
as Response
;
1395 if (!this.requests
.has(messageId
)) {
1397 throw new OCPPError(
1398 ErrorType
.INTERNAL_ERROR
,
1399 `Response for unknown message id ${messageId}`,
1405 cachedRequest
= this.requests
.get(messageId
);
1406 if (Utils
.isIterable(cachedRequest
)) {
1407 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1409 throw new OCPPError(
1410 ErrorType
.PROTOCOL_ERROR
,
1411 `Cached request for message id ${messageId} response is not iterable`,
1413 cachedRequest
as unknown
as JsonType
1417 `${this.logPrefix()} << Command '${
1418 requestCommandName ?? ''
1419 }' received response payload: ${JSON.stringify(request)}`
1421 responseCallback(commandPayload
, requestPayload
);
1424 case MessageType
.CALL_ERROR_MESSAGE
:
1425 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1426 if (!this.requests
.has(messageId
)) {
1428 throw new OCPPError(
1429 ErrorType
.INTERNAL_ERROR
,
1430 `Error response for unknown message id ${messageId}`,
1432 { errorType
, errorMessage
, errorDetails
}
1435 cachedRequest
= this.requests
.get(messageId
);
1436 if (Utils
.isIterable(cachedRequest
)) {
1437 [, errorCallback
, requestCommandName
] = cachedRequest
;
1439 throw new OCPPError(
1440 ErrorType
.PROTOCOL_ERROR
,
1441 `Cached request for message id ${messageId} error response is not iterable`,
1443 cachedRequest
as unknown
as JsonType
1447 `${this.logPrefix()} << Command '${
1448 requestCommandName ?? ''
1449 }' received error payload: ${JSON.stringify(request)}`
1451 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1455 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1456 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
1457 logger
.error(errMsg
);
1458 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1461 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not iterable', null, {
1468 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1471 this.requests
.get(messageId
),
1475 messageType
=== MessageType
.CALL_MESSAGE
&&
1476 (await this.ocppRequestService
.sendError(
1480 commandName
?? requestCommandName
?? null
1485 private onPing(): void {
1486 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1489 private onPong(): void {
1490 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1493 private onError(error
: WSError
): void {
1494 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
1497 private getAuthorizationFile(): string | undefined {
1499 this.stationInfo
.authorizationFile
&&
1501 path
.resolve(__dirname
, '../'),
1503 path
.basename(this.stationInfo
.authorizationFile
)
1508 private getAuthorizedTags(): string[] {
1509 let authorizedTags
: string[] = [];
1510 const authorizationFile
= this.getAuthorizationFile();
1511 if (authorizationFile
) {
1513 // Load authorization file
1514 authorizedTags
= JSON
.parse(fs
.readFileSync(authorizationFile
, 'utf8')) as string[];
1516 FileUtils
.handleFileException(
1518 FileType
.Authorization
,
1520 error
as NodeJS
.ErrnoException
1525 this.logPrefix() + ' No authorization file given in template file ' + this.templateFile
1528 return authorizedTags
;
1531 private getUseConnectorId0(): boolean | undefined {
1532 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
)
1533 ? this.stationInfo
.useConnectorId0
1537 private getNumberOfRunningTransactions(): number {
1539 for (const connectorId
of this.connectors
.keys()) {
1540 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1548 private getConnectionTimeout(): number | undefined {
1550 ChargingStationConfigurationUtils
.getConfigurationKey(
1552 StandardParametersKey
.ConnectionTimeOut
1557 ChargingStationConfigurationUtils
.getConfigurationKey(
1559 StandardParametersKey
.ConnectionTimeOut
1561 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1564 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1567 // -1 for unlimited, 0 for disabling
1568 private getAutoReconnectMaxRetries(): number | undefined {
1569 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1570 return this.stationInfo
.autoReconnectMaxRetries
;
1572 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1573 return Configuration
.getAutoReconnectMaxRetries();
1579 private getRegistrationMaxRetries(): number | undefined {
1580 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1581 return this.stationInfo
.registrationMaxRetries
;
1586 private getPowerDivider(): number {
1587 let powerDivider
= this.getNumberOfConnectors();
1588 if (this.stationInfo
.powerSharedByConnectors
) {
1589 powerDivider
= this.getNumberOfRunningTransactions();
1591 return powerDivider
;
1594 private getTemplateMaxNumberOfConnectors(): number {
1595 if (!this.stationInfo
?.Connectors
) {
1598 return Object.keys(this.stationInfo
?.Connectors
).length
;
1601 private getMaxNumberOfConnectors(): number {
1602 let maxConnectors
: number;
1603 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
1604 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
1605 // Distribute evenly the number of connectors
1606 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
1607 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
1608 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
1610 maxConnectors
= this.stationInfo
?.Connectors
[0]
1611 ? this.getTemplateMaxNumberOfConnectors() - 1
1612 : this.getTemplateMaxNumberOfConnectors();
1614 return maxConnectors
;
1617 private getMaximumPower(): number {
1618 return (this.stationInfo
['maxPower'] as number) ?? this.stationInfo
.maximumPower
;
1621 private getMaximumAmperage(): number | undefined {
1622 const maximumPower
= this.getMaximumPower();
1623 switch (this.getCurrentOutType()) {
1624 case CurrentType
.AC
:
1625 return ACElectricUtils
.amperagePerPhaseFromPower(
1626 this.getNumberOfPhases(),
1627 maximumPower
/ this.getNumberOfConnectors(),
1628 this.getVoltageOut()
1630 case CurrentType
.DC
:
1631 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut());
1635 private getAmperageLimitation(): number | undefined {
1637 this.stationInfo
.amperageLimitationOcppKey
&&
1638 ChargingStationConfigurationUtils
.getConfigurationKey(
1640 this.stationInfo
.amperageLimitationOcppKey
1645 ChargingStationConfigurationUtils
.getConfigurationKey(
1647 this.stationInfo
.amperageLimitationOcppKey
1649 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1654 private async startMessageSequence(): Promise
<void> {
1655 if (this.stationInfo
.autoRegister
) {
1656 await this.ocppRequestService
.requestHandler
<
1657 BootNotificationRequest
,
1658 BootNotificationResponse
1661 RequestCommand
.BOOT_NOTIFICATION
,
1663 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1664 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1665 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1666 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1667 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1668 iccid
: this.bootNotificationRequest
.iccid
,
1669 imsi
: this.bootNotificationRequest
.imsi
,
1670 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1671 meterType
: this.bootNotificationRequest
.meterType
,
1673 { skipBufferingOnError
: true }
1676 // Start WebSocket ping
1677 this.startWebSocketPing();
1679 this.startHeartbeat();
1680 // Initialize connectors status
1681 for (const connectorId
of this.connectors
.keys()) {
1682 if (connectorId
=== 0) {
1686 !this.getConnectorStatus(connectorId
)?.status &&
1687 this.getConnectorStatus(connectorId
)?.bootStatus
1689 // Send status in template at startup
1690 await this.ocppRequestService
.requestHandler
<
1691 StatusNotificationRequest
,
1692 StatusNotificationResponse
1693 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1695 status: this.getConnectorStatus(connectorId
).bootStatus
,
1696 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1698 this.getConnectorStatus(connectorId
).status =
1699 this.getConnectorStatus(connectorId
).bootStatus
;
1702 this.getConnectorStatus(connectorId
)?.status &&
1703 this.getConnectorStatus(connectorId
)?.bootStatus
1705 // Send status in template after reset
1706 await this.ocppRequestService
.requestHandler
<
1707 StatusNotificationRequest
,
1708 StatusNotificationResponse
1709 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1711 status: this.getConnectorStatus(connectorId
).bootStatus
,
1712 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1714 this.getConnectorStatus(connectorId
).status =
1715 this.getConnectorStatus(connectorId
).bootStatus
;
1716 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1717 // Send previous status at template reload
1718 await this.ocppRequestService
.requestHandler
<
1719 StatusNotificationRequest
,
1720 StatusNotificationResponse
1721 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1723 status: this.getConnectorStatus(connectorId
).status,
1724 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1727 // Send default status
1728 await this.ocppRequestService
.requestHandler
<
1729 StatusNotificationRequest
,
1730 StatusNotificationResponse
1731 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1733 status: ChargePointStatus
.AVAILABLE
,
1734 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1736 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1740 this.startAutomaticTransactionGenerator();
1743 private startAutomaticTransactionGenerator() {
1744 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
1745 if (!this.automaticTransactionGenerator
) {
1746 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
1748 if (!this.automaticTransactionGenerator
.started
) {
1749 this.automaticTransactionGenerator
.start();
1754 private async stopMessageSequence(
1755 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1757 // Stop WebSocket ping
1758 this.stopWebSocketPing();
1760 this.stopHeartbeat();
1763 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1764 this.automaticTransactionGenerator
?.started
1766 this.automaticTransactionGenerator
.stop();
1768 for (const connectorId
of this.connectors
.keys()) {
1769 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1770 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1772 this.getBeginEndMeterValues() &&
1773 this.getOcppStrictCompliance() &&
1774 !this.getOutOfOrderEndMeterValues()
1776 // FIXME: Implement OCPP version agnostic helpers
1777 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1780 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1782 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
1784 RequestCommand
.METER_VALUES
,
1788 meterValue
: transactionEndMeterValue
,
1792 await this.ocppRequestService
.requestHandler
<
1793 StopTransactionRequest
,
1794 StopTransactionResponse
1795 >(this, RequestCommand
.STOP_TRANSACTION
, {
1797 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1798 idTag
: this.getTransactionIdTag(transactionId
),
1806 private startWebSocketPing(): void {
1807 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1809 StandardParametersKey
.WebSocketPingInterval
1811 ? Utils
.convertToInt(
1812 ChargingStationConfigurationUtils
.getConfigurationKey(
1814 StandardParametersKey
.WebSocketPingInterval
1818 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1819 this.webSocketPingSetInterval
= setInterval(() => {
1820 if (this.isWebSocketConnectionOpened()) {
1821 this.wsConnection
.ping((): void => {
1822 /* This is intentional */
1825 }, webSocketPingInterval
* 1000);
1828 ' WebSocket ping started every ' +
1829 Utils
.formatDurationSeconds(webSocketPingInterval
)
1831 } else if (this.webSocketPingSetInterval
) {
1834 ' WebSocket ping every ' +
1835 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1840 `${this.logPrefix()} WebSocket ping interval set to ${
1841 webSocketPingInterval
1842 ? Utils.formatDurationSeconds(webSocketPingInterval)
1843 : webSocketPingInterval
1844 }, not starting the WebSocket ping`
1849 private stopWebSocketPing(): void {
1850 if (this.webSocketPingSetInterval
) {
1851 clearInterval(this.webSocketPingSetInterval
);
1855 private getConfiguredSupervisionUrl(): URL
{
1856 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1857 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1859 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1861 switch (Configuration
.getSupervisionUrlDistribution()) {
1862 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1863 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1865 case SupervisionUrlDistribution
.RANDOM
:
1867 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1869 case SupervisionUrlDistribution
.SEQUENTIAL
:
1870 if (this.index
<= supervisionUrls
.length
) {
1871 urlIndex
= this.index
- 1;
1874 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1880 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1881 SupervisionUrlDistribution.ROUND_ROBIN
1884 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1887 return new URL(supervisionUrls
[urlIndex
]);
1889 return new URL(supervisionUrls
as string);
1892 private getHeartbeatInterval(): number | undefined {
1893 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1895 StandardParametersKey
.HeartbeatInterval
1897 if (HeartbeatInterval
) {
1898 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1900 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1902 StandardParametersKey
.HeartBeatInterval
1904 if (HeartBeatInterval
) {
1905 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1907 !this.stationInfo
.autoRegister
&&
1909 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1910 Constants.DEFAULT_HEARTBEAT_INTERVAL
1913 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1916 private stopHeartbeat(): void {
1917 if (this.heartbeatSetInterval
) {
1918 clearInterval(this.heartbeatSetInterval
);
1922 private openWSConnection(
1923 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
1924 forceCloseOpened
= false
1926 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
1928 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
1929 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
1931 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
1933 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
1934 this.wsConnection
.close();
1936 let protocol
: string;
1937 switch (this.getOcppVersion()) {
1938 case OCPPVersion
.VERSION_16
:
1939 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
1942 this.handleUnsupportedVersion(this.getOcppVersion());
1945 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
1947 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString()
1951 private stopMeterValues(connectorId
: number) {
1952 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1953 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1957 private getReconnectExponentialDelay(): boolean | undefined {
1958 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1959 ? this.stationInfo
.reconnectExponentialDelay
1963 private async reconnect(code
: number): Promise
<void> {
1964 // Stop WebSocket ping
1965 this.stopWebSocketPing();
1967 this.stopHeartbeat();
1968 // Stop the ATG if needed
1970 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1971 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
1972 this.automaticTransactionGenerator
?.started
1974 this.automaticTransactionGenerator
.stop();
1977 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1978 this.getAutoReconnectMaxRetries() === -1
1980 this.autoReconnectRetryCount
++;
1981 const reconnectDelay
= this.getReconnectExponentialDelay()
1982 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1983 : this.getConnectionTimeout() * 1000;
1984 const reconnectTimeout
= reconnectDelay
- 100 > 0 && reconnectDelay
;
1986 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1989 )}ms, timeout ${reconnectTimeout}ms`
1991 await Utils
.sleep(reconnectDelay
);
1994 ' WebSocket: reconnecting try #' +
1995 this.autoReconnectRetryCount
.toString()
1997 this.openWSConnection(
1998 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
2001 this.wsConnectionRestarted
= true;
2002 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2004 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2005 this.autoReconnectRetryCount
2006 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2011 private initializeConnectorStatus(connectorId
: number): void {
2012 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2013 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2014 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2015 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2016 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2017 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;