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(` ${this.stationInfo.chargingStationId} |`);
137 public getBootNotificationRequest(): BootNotificationRequest
{
138 return this.bootNotificationRequest
;
141 public getRandomIdTag(): string {
142 const index
= Math.floor(Utils
.secureRandom() * this.authorizedTags
.length
);
143 return this.authorizedTags
[index
];
146 public hasAuthorizedTags(): boolean {
147 return !Utils
.isEmptyArray(this.authorizedTags
);
150 public getEnableStatistics(): boolean | undefined {
151 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
152 ? this.stationInfo
.enableStatistics
156 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
157 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
160 public getNumberOfPhases(): number | undefined {
161 switch (this.getCurrentOutType()) {
163 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
)
164 ? this.stationInfo
.numberOfPhases
171 public isWebSocketConnectionOpened(): boolean {
172 return this?.wsConnection
?.readyState
=== OPEN
;
175 public getRegistrationStatus(): RegistrationStatus
{
176 return this?.bootNotificationResponse
?.status;
179 public isInUnknownState(): boolean {
180 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
183 public isInPendingState(): boolean {
184 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
187 public isInAcceptedState(): boolean {
188 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
191 public isInRejectedState(): boolean {
192 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
195 public isRegistered(): boolean {
196 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
199 public isChargingStationAvailable(): boolean {
200 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
203 public isConnectorAvailable(id
: number): boolean {
204 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
207 public getNumberOfConnectors(): number {
208 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
211 public getConnectorStatus(id
: number): ConnectorStatus
{
212 return this.connectors
.get(id
);
215 public getCurrentOutType(): CurrentType
| undefined {
216 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
219 public getOcppStrictCompliance(): boolean {
220 return this.stationInfo
.ocppStrictCompliance
?? false;
223 public getVoltageOut(): number | undefined {
224 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
225 this.getCurrentOutType(),
229 return !Utils
.isUndefined(this.stationInfo
.voltageOut
)
230 ? this.stationInfo
.voltageOut
234 public getConnectorMaximumAvailablePower(connectorId
: number): number {
235 let connectorAmperageLimitationPowerLimit
: number;
237 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
238 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
240 connectorAmperageLimitationPowerLimit
=
241 (this.getCurrentOutType() === CurrentType
.AC
242 ? ACElectricUtils
.powerTotal(
243 this.getNumberOfPhases(),
244 this.getVoltageOut(),
245 this.getAmperageLimitation() * this.getNumberOfConnectors()
247 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
248 this.stationInfo
.powerDivider
;
250 const connectorMaximumPower
= this.getMaximumPower() / this.stationInfo
.powerDivider
;
251 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
253 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
254 isNaN(connectorAmperageLimitationPowerLimit
)
256 : connectorAmperageLimitationPowerLimit
,
257 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
261 public getTransactionIdTag(transactionId
: number): string | undefined {
262 for (const connectorId
of this.connectors
.keys()) {
263 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
264 return this.getConnectorStatus(connectorId
).transactionIdTag
;
269 public getOutOfOrderEndMeterValues(): boolean {
270 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
273 public getBeginEndMeterValues(): boolean {
274 return this.stationInfo
.beginEndMeterValues
?? false;
277 public getMeteringPerTransaction(): boolean {
278 return this.stationInfo
.meteringPerTransaction
?? true;
281 public getTransactionDataMeterValues(): boolean {
282 return this.stationInfo
.transactionDataMeterValues
?? false;
285 public getMainVoltageMeterValues(): boolean {
286 return this.stationInfo
.mainVoltageMeterValues
?? true;
289 public getPhaseLineToLineVoltageMeterValues(): boolean {
290 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
293 public getCustomValueLimitationMeterValues(): boolean {
294 return this.stationInfo
.customValueLimitationMeterValues
?? true;
297 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
298 for (const connectorId
of this.connectors
.keys()) {
301 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
308 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
309 const transactionConnectorStatus
= this.getConnectorStatus(
310 this.getConnectorIdByTransactionId(transactionId
)
312 if (this.getMeteringPerTransaction()) {
313 return transactionConnectorStatus
?.transactionEnergyActiveImportRegisterValue
;
315 return transactionConnectorStatus
?.energyActiveImportRegisterValue
;
318 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
319 const connectorStatus
= this.getConnectorStatus(connectorId
);
320 if (this.getMeteringPerTransaction()) {
321 return connectorStatus
?.transactionEnergyActiveImportRegisterValue
;
323 return connectorStatus
?.energyActiveImportRegisterValue
;
326 public getAuthorizeRemoteTxRequests(): boolean {
327 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
329 StandardParametersKey
.AuthorizeRemoteTxRequests
331 return authorizeRemoteTxRequests
332 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
336 public getLocalAuthListEnabled(): boolean {
337 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
339 StandardParametersKey
.LocalAuthListEnabled
341 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
344 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
345 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
348 public startHeartbeat(): void {
350 this.getHeartbeatInterval() &&
351 this.getHeartbeatInterval() > 0 &&
352 !this.heartbeatSetInterval
354 // eslint-disable-next-line @typescript-eslint/no-misused-promises
355 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
356 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
358 RequestCommand
.HEARTBEAT
360 }, this.getHeartbeatInterval());
363 ' Heartbeat started every ' +
364 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
366 } else if (this.heartbeatSetInterval
) {
369 ' Heartbeat already started every ' +
370 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
374 `${this.logPrefix()} Heartbeat interval set to ${
375 this.getHeartbeatInterval()
376 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
377 : this.getHeartbeatInterval()
378 }, not starting the heartbeat`
383 public restartHeartbeat(): void {
385 this.stopHeartbeat();
387 this.startHeartbeat();
390 public restartWebSocketPing(): void {
391 // Stop WebSocket ping
392 this.stopWebSocketPing();
393 // Start WebSocket ping
394 this.startWebSocketPing();
397 public startMeterValues(connectorId
: number, interval
: number): void {
398 if (connectorId
=== 0) {
400 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
404 if (!this.getConnectorStatus(connectorId
)) {
406 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
410 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
412 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
416 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
417 !this.getConnectorStatus(connectorId
)?.transactionId
420 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
425 // eslint-disable-next-line @typescript-eslint/no-misused-promises
426 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
427 // eslint-disable-next-line @typescript-eslint/no-misused-promises
428 async (): Promise
<void> => {
429 // FIXME: Implement OCPP version agnostic helpers
430 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
433 this.getConnectorStatus(connectorId
).transactionId
,
436 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
438 RequestCommand
.METER_VALUES
,
441 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
442 meterValue
: [meterValue
],
450 `${this.logPrefix()} Charging station ${
451 StandardParametersKey.MeterValueSampleInterval
452 } configuration set to ${
453 interval ? Utils.formatDurationMilliSeconds(interval) : interval
454 }, not sending MeterValues`
459 public start(): void {
460 if (this.getEnableStatistics()) {
461 this.performanceStatistics
.start();
463 this.openWSConnection();
464 // Handle WebSocket message
465 this.wsConnection
.on(
467 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
469 // Handle WebSocket error
470 this.wsConnection
.on(
472 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
474 // Handle WebSocket close
475 this.wsConnection
.on(
477 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
479 // Handle WebSocket open
480 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
481 // Handle WebSocket ping
482 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
483 // Handle WebSocket pong
484 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
485 // Monitor authorization file
486 FileUtils
.watchJsonFile
<string[]>(
488 FileType
.Authorization
,
489 this.getAuthorizationFile(),
492 // Monitor charging station template file
493 FileUtils
.watchJsonFile(
495 FileType
.ChargingStationTemplate
,
498 (event
, filename
): void => {
499 if (filename
&& event
=== 'change') {
502 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
504 } file have changed, reload`
510 !this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
511 this.automaticTransactionGenerator
513 this.automaticTransactionGenerator
.stop();
515 this.startAutomaticTransactionGenerator();
516 if (this.getEnableStatistics()) {
517 this.performanceStatistics
.restart();
519 this.performanceStatistics
.stop();
521 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
524 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
531 parentPort
.postMessage({
532 id
: ChargingStationWorkerMessageEvents
.STARTED
,
533 data
: { id
: this.stationInfo
.chargingStationId
},
537 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
538 // Stop message sequence
539 await this.stopMessageSequence(reason
);
540 for (const connectorId
of this.connectors
.keys()) {
541 if (connectorId
> 0) {
542 await this.ocppRequestService
.requestHandler
<
543 StatusNotificationRequest
,
544 StatusNotificationResponse
545 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
547 status: ChargePointStatus
.UNAVAILABLE
,
548 errorCode
: ChargePointErrorCode
.NO_ERROR
,
550 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
553 if (this.isWebSocketConnectionOpened()) {
554 this.wsConnection
.close();
556 if (this.getEnableStatistics()) {
557 this.performanceStatistics
.stop();
559 this.bootNotificationResponse
= null;
560 parentPort
.postMessage({
561 id
: ChargingStationWorkerMessageEvents
.STOPPED
,
562 data
: { id
: this.stationInfo
.chargingStationId
},
567 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
568 await this.stop(reason
);
569 await Utils
.sleep(this.stationInfo
.resetTime
);
570 this.stationInfo
= this.getStationInfo();
571 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
575 public saveOcppConfiguration(): void {
576 if (this.getOcppPersistentConfiguration()) {
577 this.saveConfiguration(Section
.ocppConfiguration
);
581 public getChargingProfilePowerLimit(connectorId
: number): number | undefined {
582 let limit
: number, matchingChargingProfile
: ChargingProfile
;
583 let chargingProfiles
: ChargingProfile
[] = [];
584 // Get charging profiles for connector and sort by stack level
585 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
586 (a
, b
) => b
.stackLevel
- a
.stackLevel
588 // Get profiles on connector 0
589 if (this.getConnectorStatus(0).chargingProfiles
) {
590 chargingProfiles
.push(
591 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
594 if (!Utils
.isEmptyArray(chargingProfiles
)) {
595 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
599 if (!Utils
.isNullOrUndefined(result
)) {
600 limit
= result
.limit
;
601 matchingChargingProfile
= result
.matchingChargingProfile
;
602 switch (this.getCurrentOutType()) {
605 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
606 ChargingRateUnitType
.WATT
608 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
612 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
613 ChargingRateUnitType
.WATT
615 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
618 const connectorMaximumPower
= this.getMaximumPower() / this.stationInfo
.powerDivider
;
619 if (limit
> connectorMaximumPower
) {
621 `${this.logPrefix()} Charging profile id ${
622 matchingChargingProfile.chargingProfileId
623 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
624 this.getConnectorStatus(connectorId
).chargingProfiles
626 limit
= connectorMaximumPower
;
633 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
634 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
636 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
638 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
640 if (!Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
642 `${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`
644 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
646 let cpReplaced
= false;
647 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
648 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
649 (chargingProfile
: ChargingProfile
, index
: number) => {
651 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
652 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
653 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
655 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
661 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
664 public resetConnectorStatus(connectorId
: number): void {
665 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
666 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
667 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
668 this.getConnectorStatus(connectorId
).transactionStarted
= false;
669 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
670 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
671 delete this.getConnectorStatus(connectorId
).transactionId
;
672 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
673 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
674 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
675 this.stopMeterValues(connectorId
);
678 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
679 return ChargingStationConfigurationUtils
.getConfigurationKey(
681 StandardParametersKey
.SupportedFeatureProfiles
682 )?.value
.includes(featureProfile
);
685 public bufferMessage(message
: string): void {
686 this.messageBuffer
.add(message
);
689 private flushMessageBuffer() {
690 if (this.messageBuffer
.size
> 0) {
691 this.messageBuffer
.forEach((message
) => {
692 // TODO: evaluate the need to track performance
693 this.wsConnection
.send(message
);
694 this.messageBuffer
.delete(message
);
699 private getSupervisionUrlOcppConfiguration(): boolean {
700 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
703 private getSupervisionUrlOcppKey(): string {
704 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
707 private getTemplateFromFile(): ChargingStationTemplate
| null {
708 let template
: ChargingStationTemplate
= null;
710 const measureId
= `${FileType.ChargingStationTemplate} read`;
711 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
713 (JSON
.parse(fs
.readFileSync(this.templateFile
, 'utf8')) as ChargingStationTemplate
) ??
714 ({} as ChargingStationTemplate
);
715 PerformanceStatistics
.endMeasure(measureId
, beginId
);
716 template
.templateHash
= crypto
717 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
718 .update(JSON
.stringify(template
))
721 FileUtils
.handleFileException(
723 FileType
.ChargingStationTemplate
,
725 error
as NodeJS
.ErrnoException
731 private getStationInfoFromTemplate(): ChargingStationInfo
{
732 const stationInfo
: ChargingStationInfo
= this.getTemplateFromFile();
733 if (Utils
.isNullOrUndefined(stationInfo
)) {
734 const logMsg
= 'Failed to read charging station template file';
735 logger
.error(`${this.logPrefix()} ${logMsg}`);
736 throw new BaseError(logMsg
);
738 if (Utils
.isEmptyObject(stationInfo
)) {
740 `${this.logPrefix()} Empty charging station information from template file ${
745 const chargingStationId
= ChargingStationUtils
.getChargingStationId(this.index
, stationInfo
);
746 // Deprecation template keys section
747 ChargingStationUtils
.warnDeprecatedTemplateKey(
751 Utils
.logPrefix(` ${chargingStationId} |`),
752 "Use 'supervisionUrls' instead"
754 ChargingStationUtils
.convertDeprecatedTemplateKey(
759 stationInfo
.wsOptions
= stationInfo
?.wsOptions
?? {};
760 if (!Utils
.isEmptyArray(stationInfo
.power
)) {
761 stationInfo
.power
= stationInfo
.power
as number[];
762 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationInfo
.power
.length
);
763 stationInfo
.maximumPower
=
764 stationInfo
.powerUnit
=== PowerUnits
.KILO_WATT
765 ? stationInfo
.power
[powerArrayRandomIndex
] * 1000
766 : stationInfo
.power
[powerArrayRandomIndex
];
768 stationInfo
.power
= stationInfo
.power
as number;
769 stationInfo
.maximumPower
=
770 stationInfo
.powerUnit
=== PowerUnits
.KILO_WATT
771 ? stationInfo
.power
* 1000
774 delete stationInfo
.power
;
775 delete stationInfo
.powerUnit
;
776 stationInfo
.chargingStationId
= chargingStationId
;
777 stationInfo
.resetTime
= stationInfo
.resetTime
778 ? stationInfo
.resetTime
* 1000
779 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
783 private getStationInfoFromFile(): ChargingStationInfo
{
784 let stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? ({} as ChargingStationInfo
);
785 stationInfo
= ChargingStationUtils
.createStationInfoHash(stationInfo
);
789 private getStationInfo(): ChargingStationInfo
{
790 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
791 this.hashId
= ChargingStationUtils
.getHashId(stationInfoFromTemplate
);
792 this.configurationFile
= path
.join(
793 path
.resolve(__dirname
, '../'),
796 this.hashId
+ '.json'
798 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
799 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
800 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
801 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
802 return this.stationInfo
;
804 return stationInfoFromFile
;
806 ChargingStationUtils
.createSerialNumber(stationInfoFromTemplate
, stationInfoFromFile
);
807 return stationInfoFromTemplate
;
810 private saveStationInfo(): void {
811 this.saveConfiguration(Section
.stationInfo
);
814 private getOcppVersion(): OCPPVersion
{
815 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
818 private getOcppPersistentConfiguration(): boolean {
819 return this.stationInfo
.ocppPersistentConfiguration
?? true;
822 private handleUnsupportedVersion(version
: OCPPVersion
) {
823 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
826 logger
.error(errMsg
);
827 throw new Error(errMsg
);
830 private initialize(): void {
831 this.stationInfo
= this.getStationInfo();
832 logger
.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
833 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
836 this.ocppConfiguration
= this.getOcppConfiguration();
837 this.stationInfo
?.Configuration
&& delete this.stationInfo
.Configuration
;
838 this.wsConfiguredConnectionUrl
= new URL(
839 this.getConfiguredSupervisionUrl().href
+ '/' + this.stationInfo
.chargingStationId
841 // Build connectors if needed
842 const maxConnectors
= this.getMaxNumberOfConnectors();
843 this.checkMaxConnectors(maxConnectors
);
844 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
845 this.checkTemplateMaxConnectors(templateMaxConnectors
);
848 (this.stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
849 !this.stationInfo
.randomConnectors
852 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
854 }, forcing random connector configurations affectation`
856 this.stationInfo
.randomConnectors
= true;
858 this.initializeConnectors(this.stationInfo
, maxConnectors
, templateMaxConnectors
);
859 this.stationInfo
.maximumAmperage
= this.getMaximumAmperage();
860 this.stationInfo
= ChargingStationUtils
.createStationInfoHash(this.stationInfo
);
861 this.saveStationInfo();
862 // Avoid duplication of connectors related information in RAM
863 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
864 // OCPP configuration
865 this.initializeOcppConfiguration();
866 if (this.getEnableStatistics()) {
867 this.performanceStatistics
= PerformanceStatistics
.getInstance(
869 this.stationInfo
.chargingStationId
,
873 switch (this.getOcppVersion()) {
874 case OCPPVersion
.VERSION_16
:
875 this.ocppIncomingRequestService
=
876 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
877 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
878 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
882 this.handleUnsupportedVersion(this.getOcppVersion());
885 if (this.stationInfo
.autoRegister
) {
886 this.bootNotificationResponse
= {
887 currentTime
: new Date().toISOString(),
888 interval
: this.getHeartbeatInterval() / 1000,
889 status: RegistrationStatus
.ACCEPTED
,
892 this.stationInfo
.powerDivider
= this.getPowerDivider();
895 private initializeOcppConfiguration(): void {
897 !ChargingStationConfigurationUtils
.getConfigurationKey(
899 StandardParametersKey
.HeartbeatInterval
902 ChargingStationConfigurationUtils
.addConfigurationKey(
904 StandardParametersKey
.HeartbeatInterval
,
909 !ChargingStationConfigurationUtils
.getConfigurationKey(
911 StandardParametersKey
.HeartBeatInterval
914 ChargingStationConfigurationUtils
.addConfigurationKey(
916 StandardParametersKey
.HeartBeatInterval
,
922 this.getSupervisionUrlOcppConfiguration() &&
923 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
925 ChargingStationConfigurationUtils
.addConfigurationKey(
927 this.getSupervisionUrlOcppKey(),
928 this.getConfiguredSupervisionUrl().href
,
932 !this.getSupervisionUrlOcppConfiguration() &&
933 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
935 ChargingStationConfigurationUtils
.deleteConfigurationKey(
937 this.getSupervisionUrlOcppKey(),
942 this.stationInfo
.amperageLimitationOcppKey
&&
943 !ChargingStationConfigurationUtils
.getConfigurationKey(
945 this.stationInfo
.amperageLimitationOcppKey
948 ChargingStationConfigurationUtils
.addConfigurationKey(
950 this.stationInfo
.amperageLimitationOcppKey
,
952 this.stationInfo
.maximumAmperage
*
953 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
958 !ChargingStationConfigurationUtils
.getConfigurationKey(
960 StandardParametersKey
.SupportedFeatureProfiles
963 ChargingStationConfigurationUtils
.addConfigurationKey(
965 StandardParametersKey
.SupportedFeatureProfiles
,
966 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
969 ChargingStationConfigurationUtils
.addConfigurationKey(
971 StandardParametersKey
.NumberOfConnectors
,
972 this.getNumberOfConnectors().toString(),
977 !ChargingStationConfigurationUtils
.getConfigurationKey(
979 StandardParametersKey
.MeterValuesSampledData
982 ChargingStationConfigurationUtils
.addConfigurationKey(
984 StandardParametersKey
.MeterValuesSampledData
,
985 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
989 !ChargingStationConfigurationUtils
.getConfigurationKey(
991 StandardParametersKey
.ConnectorPhaseRotation
994 const connectorPhaseRotation
= [];
995 for (const connectorId
of this.connectors
.keys()) {
997 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
998 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
999 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1000 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1002 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1003 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1004 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1005 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1008 ChargingStationConfigurationUtils
.addConfigurationKey(
1010 StandardParametersKey
.ConnectorPhaseRotation
,
1011 connectorPhaseRotation
.toString()
1015 !ChargingStationConfigurationUtils
.getConfigurationKey(
1017 StandardParametersKey
.AuthorizeRemoteTxRequests
1020 ChargingStationConfigurationUtils
.addConfigurationKey(
1022 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1027 !ChargingStationConfigurationUtils
.getConfigurationKey(
1029 StandardParametersKey
.LocalAuthListEnabled
1031 ChargingStationConfigurationUtils
.getConfigurationKey(
1033 StandardParametersKey
.SupportedFeatureProfiles
1034 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1036 ChargingStationConfigurationUtils
.addConfigurationKey(
1038 StandardParametersKey
.LocalAuthListEnabled
,
1043 !ChargingStationConfigurationUtils
.getConfigurationKey(
1045 StandardParametersKey
.ConnectionTimeOut
1048 ChargingStationConfigurationUtils
.addConfigurationKey(
1050 StandardParametersKey
.ConnectionTimeOut
,
1051 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1054 this.saveOcppConfiguration();
1057 private initializeConnectors(
1058 stationInfo
: ChargingStationInfo
,
1059 maxConnectors
: number,
1060 templateMaxConnectors
: number
1062 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1063 const logMsg
= `${this.logPrefix()} No already defined connectors and charging station information from template ${
1065 } with no connectors configuration defined`;
1066 logger
.error(logMsg
);
1067 throw new BaseError(logMsg
);
1069 if (!stationInfo
?.Connectors
[0]) {
1071 `${this.logPrefix()} Charging station information from template ${
1073 } with no connector Id 0 configuration`
1076 if (stationInfo
?.Connectors
) {
1077 const connectorsConfigHash
= crypto
1078 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1079 .update(JSON
.stringify(stationInfo
?.Connectors
) + maxConnectors
.toString())
1081 const connectorsConfigChanged
=
1082 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1083 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1084 connectorsConfigChanged
&& this.connectors
.clear();
1085 this.connectorsConfigurationHash
= connectorsConfigHash
;
1086 // Add connector Id 0
1087 let lastConnector
= '0';
1088 for (lastConnector
in stationInfo
?.Connectors
) {
1089 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1091 lastConnectorId
=== 0 &&
1092 this.getUseConnectorId0() &&
1093 stationInfo
?.Connectors
[lastConnector
]
1095 this.connectors
.set(
1097 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1099 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1100 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1101 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1105 // Generate all connectors
1106 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1107 for (let index
= 1; index
<= maxConnectors
; index
++) {
1108 const randConnectorId
= stationInfo
.randomConnectors
1109 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1111 this.connectors
.set(
1113 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1115 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1116 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1117 this.getConnectorStatus(index
).chargingProfiles
= [];
1124 `${this.logPrefix()} Charging station information from template ${
1126 } with no connectors configuration defined, using already defined connectors`
1129 // Initialize transaction attributes on connectors
1130 for (const connectorId
of this.connectors
.keys()) {
1131 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1132 this.initializeConnectorStatus(connectorId
);
1137 private checkMaxConnectors(maxConnectors
: number): void {
1138 if (maxConnectors
<= 0) {
1140 `${this.logPrefix()} Charging station information from template ${
1142 } with ${maxConnectors} connectors`
1147 private checkTemplateMaxConnectors(templateMaxConnectors
: number): void {
1148 if (templateMaxConnectors
=== 0) {
1150 `${this.logPrefix()} Charging station information from template ${
1152 } with empty connectors configuration`
1154 } else if (templateMaxConnectors
< 0) {
1156 `${this.logPrefix()} Charging station information from template ${
1158 } with no connectors configuration defined`
1163 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1164 let configuration
: ChargingStationConfiguration
= null;
1165 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1167 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1168 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1169 configuration
= JSON
.parse(
1170 fs
.readFileSync(this.configurationFile
, 'utf8')
1171 ) as ChargingStationConfiguration
;
1172 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1174 FileUtils
.handleFileException(
1176 FileType
.ChargingStationConfiguration
,
1177 this.configurationFile
,
1178 error
as NodeJS
.ErrnoException
1182 return configuration
;
1185 private saveConfiguration(section
?: Section
): void {
1186 if (this.configurationFile
) {
1188 const configurationData
: ChargingStationConfiguration
=
1189 this.getConfigurationFromFile() ?? {};
1190 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1191 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1194 case Section
.ocppConfiguration
:
1195 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1197 case Section
.stationInfo
:
1198 if (configurationData
?.stationInfo
?.infoHash
=== this.stationInfo
?.infoHash
) {
1200 `${this.logPrefix()} Not saving unchanged charging station information to configuration file ${
1201 this.configurationFile
1206 configurationData
.stationInfo
= this.stationInfo
;
1209 configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
;
1210 if (configurationData
?.stationInfo
?.infoHash
!== this.stationInfo
?.infoHash
) {
1211 configurationData
.stationInfo
= this.stationInfo
;
1215 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1216 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1217 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1218 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1219 fs
.closeSync(fileDescriptor
);
1220 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1222 FileUtils
.handleFileException(
1224 FileType
.ChargingStationConfiguration
,
1225 this.configurationFile
,
1226 error
as NodeJS
.ErrnoException
1231 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1236 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
{
1237 return this.getTemplateFromFile().Configuration
?? ({} as ChargingStationOcppConfiguration
);
1240 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1241 let configuration
: ChargingStationConfiguration
= null;
1242 if (this.getOcppPersistentConfiguration()) {
1243 const configurationFromFile
= this.getConfigurationFromFile();
1244 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1246 configuration
&& delete configuration
.stationInfo
;
1247 return configuration
;
1250 private getOcppConfiguration(): ChargingStationOcppConfiguration
{
1251 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1252 if (!ocppConfiguration
) {
1253 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1255 return ocppConfiguration
;
1258 private async onOpen(): Promise
<void> {
1259 if (this.isWebSocketConnectionOpened()) {
1261 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1263 if (!this.isRegistered()) {
1264 // Send BootNotification
1265 let registrationRetryCount
= 0;
1267 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1268 BootNotificationRequest
,
1269 BootNotificationResponse
1272 RequestCommand
.BOOT_NOTIFICATION
,
1274 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1275 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1276 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1277 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1278 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1279 iccid
: this.bootNotificationRequest
.iccid
,
1280 imsi
: this.bootNotificationRequest
.imsi
,
1281 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1282 meterType
: this.bootNotificationRequest
.meterType
,
1284 { skipBufferingOnError
: true }
1286 if (!this.isRegistered()) {
1287 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1289 this.bootNotificationResponse
?.interval
1290 ? this.bootNotificationResponse
.interval
* 1000
1291 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1295 !this.isRegistered() &&
1296 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1297 this.getRegistrationMaxRetries() === -1)
1300 if (this.isRegistered()) {
1301 if (this.isInAcceptedState()) {
1302 await this.startMessageSequence();
1303 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1307 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1310 this.stopped
&& (this.stopped
= false);
1311 this.autoReconnectRetryCount
= 0;
1312 this.wsConnectionRestarted
= false;
1315 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1320 private async onClose(code
: number, reason
: string): Promise
<void> {
1323 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1324 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1326 `${this.logPrefix()} WebSocket normally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1328 )}' and reason '${reason}'`
1330 this.autoReconnectRetryCount
= 0;
1335 `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1337 )}' and reason '${reason}'`
1339 await this.reconnect(code
);
1344 private async onMessage(data
: Data
): Promise
<void> {
1345 let messageType
: number;
1346 let messageId
: string;
1347 let commandName
: IncomingRequestCommand
;
1348 let commandPayload
: JsonType
;
1349 let errorType
: ErrorType
;
1350 let errorMessage
: string;
1351 let errorDetails
: JsonType
;
1352 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1353 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1354 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1355 let requestPayload
: JsonType
;
1356 let cachedRequest
: CachedRequest
;
1359 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1360 if (Utils
.isIterable(request
)) {
1361 [messageType
, messageId
] = request
;
1362 // Check the type of message
1363 switch (messageType
) {
1365 case MessageType
.CALL_MESSAGE
:
1366 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1367 if (this.getEnableStatistics()) {
1368 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1371 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1375 // Process the message
1376 await this.ocppIncomingRequestService
.incomingRequestHandler(
1384 case MessageType
.CALL_RESULT_MESSAGE
:
1385 [, , commandPayload
] = request
as Response
;
1386 if (!this.requests
.has(messageId
)) {
1388 throw new OCPPError(
1389 ErrorType
.INTERNAL_ERROR
,
1390 `Response for unknown message id ${messageId}`,
1396 cachedRequest
= this.requests
.get(messageId
);
1397 if (Utils
.isIterable(cachedRequest
)) {
1398 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1400 throw new OCPPError(
1401 ErrorType
.PROTOCOL_ERROR
,
1402 `Cached request for message id ${messageId} response is not iterable`,
1404 cachedRequest
as unknown
as JsonType
1408 `${this.logPrefix()} << Command '${
1409 requestCommandName ?? ''
1410 }' received response payload: ${JSON.stringify(request)}`
1412 responseCallback(commandPayload
, requestPayload
);
1415 case MessageType
.CALL_ERROR_MESSAGE
:
1416 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1417 if (!this.requests
.has(messageId
)) {
1419 throw new OCPPError(
1420 ErrorType
.INTERNAL_ERROR
,
1421 `Error response for unknown message id ${messageId}`,
1423 { errorType
, errorMessage
, errorDetails
}
1426 cachedRequest
= this.requests
.get(messageId
);
1427 if (Utils
.isIterable(cachedRequest
)) {
1428 [, errorCallback
, requestCommandName
] = cachedRequest
;
1430 throw new OCPPError(
1431 ErrorType
.PROTOCOL_ERROR
,
1432 `Cached request for message id ${messageId} error response is not iterable`,
1434 cachedRequest
as unknown
as JsonType
1438 `${this.logPrefix()} << Command '${
1439 requestCommandName ?? ''
1440 }' received error payload: ${JSON.stringify(request)}`
1442 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1446 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1447 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
1448 logger
.error(errMsg
);
1449 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1452 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not iterable', null, {
1459 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1462 this.requests
.get(messageId
),
1466 messageType
=== MessageType
.CALL_MESSAGE
&&
1467 (await this.ocppRequestService
.sendError(
1471 commandName
?? requestCommandName
?? null
1476 private onPing(): void {
1477 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1480 private onPong(): void {
1481 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1484 private onError(error
: WSError
): void {
1485 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
1488 private getAuthorizationFile(): string | undefined {
1490 this.stationInfo
.authorizationFile
&&
1492 path
.resolve(__dirname
, '../'),
1494 path
.basename(this.stationInfo
.authorizationFile
)
1499 private getAuthorizedTags(): string[] {
1500 let authorizedTags
: string[] = [];
1501 const authorizationFile
= this.getAuthorizationFile();
1502 if (authorizationFile
) {
1504 // Load authorization file
1505 authorizedTags
= JSON
.parse(fs
.readFileSync(authorizationFile
, 'utf8')) as string[];
1507 FileUtils
.handleFileException(
1509 FileType
.Authorization
,
1511 error
as NodeJS
.ErrnoException
1516 this.logPrefix() + ' No authorization file given in template file ' + this.templateFile
1519 return authorizedTags
;
1522 private getUseConnectorId0(): boolean | undefined {
1523 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
)
1524 ? this.stationInfo
.useConnectorId0
1528 private getNumberOfRunningTransactions(): number {
1530 for (const connectorId
of this.connectors
.keys()) {
1531 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1539 private getConnectionTimeout(): number | undefined {
1541 ChargingStationConfigurationUtils
.getConfigurationKey(
1543 StandardParametersKey
.ConnectionTimeOut
1548 ChargingStationConfigurationUtils
.getConfigurationKey(
1550 StandardParametersKey
.ConnectionTimeOut
1552 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1555 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1558 // -1 for unlimited, 0 for disabling
1559 private getAutoReconnectMaxRetries(): number | undefined {
1560 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1561 return this.stationInfo
.autoReconnectMaxRetries
;
1563 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1564 return Configuration
.getAutoReconnectMaxRetries();
1570 private getRegistrationMaxRetries(): number | undefined {
1571 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1572 return this.stationInfo
.registrationMaxRetries
;
1577 private getPowerDivider(): number {
1578 let powerDivider
= this.getNumberOfConnectors();
1579 if (this.stationInfo
.powerSharedByConnectors
) {
1580 powerDivider
= this.getNumberOfRunningTransactions();
1582 return powerDivider
;
1585 private getTemplateMaxNumberOfConnectors(): number {
1586 if (!this.stationInfo
?.Connectors
) {
1589 return Object.keys(this.stationInfo
?.Connectors
).length
;
1592 private getMaxNumberOfConnectors(): number {
1593 let maxConnectors
: number;
1594 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
1595 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
1596 // Distribute evenly the number of connectors
1597 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
1598 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
1599 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
1601 maxConnectors
= this.stationInfo
?.Connectors
[0]
1602 ? this.getTemplateMaxNumberOfConnectors() - 1
1603 : this.getTemplateMaxNumberOfConnectors();
1605 return maxConnectors
;
1608 private getMaximumPower(): number {
1609 return (this.stationInfo
['maxPower'] as number) ?? this.stationInfo
.maximumPower
;
1612 private getMaximumAmperage(): number | undefined {
1613 const maximumPower
= this.getMaximumPower();
1614 switch (this.getCurrentOutType()) {
1615 case CurrentType
.AC
:
1616 return ACElectricUtils
.amperagePerPhaseFromPower(
1617 this.getNumberOfPhases(),
1618 maximumPower
/ this.getNumberOfConnectors(),
1619 this.getVoltageOut()
1621 case CurrentType
.DC
:
1622 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut());
1626 private getAmperageLimitation(): number | undefined {
1628 this.stationInfo
.amperageLimitationOcppKey
&&
1629 ChargingStationConfigurationUtils
.getConfigurationKey(
1631 this.stationInfo
.amperageLimitationOcppKey
1636 ChargingStationConfigurationUtils
.getConfigurationKey(
1638 this.stationInfo
.amperageLimitationOcppKey
1640 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1645 private async startMessageSequence(): Promise
<void> {
1646 if (this.stationInfo
.autoRegister
) {
1647 await this.ocppRequestService
.requestHandler
<
1648 BootNotificationRequest
,
1649 BootNotificationResponse
1652 RequestCommand
.BOOT_NOTIFICATION
,
1654 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1655 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1656 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1657 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1658 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1659 iccid
: this.bootNotificationRequest
.iccid
,
1660 imsi
: this.bootNotificationRequest
.imsi
,
1661 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1662 meterType
: this.bootNotificationRequest
.meterType
,
1664 { skipBufferingOnError
: true }
1667 // Start WebSocket ping
1668 this.startWebSocketPing();
1670 this.startHeartbeat();
1671 // Initialize connectors status
1672 for (const connectorId
of this.connectors
.keys()) {
1673 if (connectorId
=== 0) {
1677 !this.getConnectorStatus(connectorId
)?.status &&
1678 this.getConnectorStatus(connectorId
)?.bootStatus
1680 // Send status in template at startup
1681 await this.ocppRequestService
.requestHandler
<
1682 StatusNotificationRequest
,
1683 StatusNotificationResponse
1684 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1686 status: this.getConnectorStatus(connectorId
).bootStatus
,
1687 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1689 this.getConnectorStatus(connectorId
).status =
1690 this.getConnectorStatus(connectorId
).bootStatus
;
1693 this.getConnectorStatus(connectorId
)?.status &&
1694 this.getConnectorStatus(connectorId
)?.bootStatus
1696 // Send status in template after reset
1697 await this.ocppRequestService
.requestHandler
<
1698 StatusNotificationRequest
,
1699 StatusNotificationResponse
1700 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1702 status: this.getConnectorStatus(connectorId
).bootStatus
,
1703 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1705 this.getConnectorStatus(connectorId
).status =
1706 this.getConnectorStatus(connectorId
).bootStatus
;
1707 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1708 // Send previous status at template reload
1709 await this.ocppRequestService
.requestHandler
<
1710 StatusNotificationRequest
,
1711 StatusNotificationResponse
1712 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1714 status: this.getConnectorStatus(connectorId
).status,
1715 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1718 // Send default status
1719 await this.ocppRequestService
.requestHandler
<
1720 StatusNotificationRequest
,
1721 StatusNotificationResponse
1722 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1724 status: ChargePointStatus
.AVAILABLE
,
1725 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1727 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1731 this.startAutomaticTransactionGenerator();
1734 private startAutomaticTransactionGenerator() {
1735 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
1736 if (!this.automaticTransactionGenerator
) {
1737 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
1739 if (!this.automaticTransactionGenerator
.started
) {
1740 this.automaticTransactionGenerator
.start();
1745 private async stopMessageSequence(
1746 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1748 // Stop WebSocket ping
1749 this.stopWebSocketPing();
1751 this.stopHeartbeat();
1754 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1755 this.automaticTransactionGenerator
?.started
1757 this.automaticTransactionGenerator
.stop();
1759 for (const connectorId
of this.connectors
.keys()) {
1760 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1761 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1763 this.getBeginEndMeterValues() &&
1764 this.getOcppStrictCompliance() &&
1765 !this.getOutOfOrderEndMeterValues()
1767 // FIXME: Implement OCPP version agnostic helpers
1768 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1771 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1773 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
1775 RequestCommand
.METER_VALUES
,
1779 meterValue
: transactionEndMeterValue
,
1783 await this.ocppRequestService
.requestHandler
<
1784 StopTransactionRequest
,
1785 StopTransactionResponse
1786 >(this, RequestCommand
.STOP_TRANSACTION
, {
1788 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1789 idTag
: this.getTransactionIdTag(transactionId
),
1797 private startWebSocketPing(): void {
1798 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1800 StandardParametersKey
.WebSocketPingInterval
1802 ? Utils
.convertToInt(
1803 ChargingStationConfigurationUtils
.getConfigurationKey(
1805 StandardParametersKey
.WebSocketPingInterval
1809 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1810 this.webSocketPingSetInterval
= setInterval(() => {
1811 if (this.isWebSocketConnectionOpened()) {
1812 this.wsConnection
.ping((): void => {
1813 /* This is intentional */
1816 }, webSocketPingInterval
* 1000);
1819 ' WebSocket ping started every ' +
1820 Utils
.formatDurationSeconds(webSocketPingInterval
)
1822 } else if (this.webSocketPingSetInterval
) {
1825 ' WebSocket ping every ' +
1826 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1831 `${this.logPrefix()} WebSocket ping interval set to ${
1832 webSocketPingInterval
1833 ? Utils.formatDurationSeconds(webSocketPingInterval)
1834 : webSocketPingInterval
1835 }, not starting the WebSocket ping`
1840 private stopWebSocketPing(): void {
1841 if (this.webSocketPingSetInterval
) {
1842 clearInterval(this.webSocketPingSetInterval
);
1846 private getConfiguredSupervisionUrl(): URL
{
1847 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1848 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1850 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1852 switch (Configuration
.getSupervisionUrlDistribution()) {
1853 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1854 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1856 case SupervisionUrlDistribution
.RANDOM
:
1858 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1860 case SupervisionUrlDistribution
.SEQUENTIAL
:
1861 if (this.index
<= supervisionUrls
.length
) {
1862 urlIndex
= this.index
- 1;
1865 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1871 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1872 SupervisionUrlDistribution.ROUND_ROBIN
1875 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1878 return new URL(supervisionUrls
[urlIndex
]);
1880 return new URL(supervisionUrls
as string);
1883 private getHeartbeatInterval(): number | undefined {
1884 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1886 StandardParametersKey
.HeartbeatInterval
1888 if (HeartbeatInterval
) {
1889 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1891 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1893 StandardParametersKey
.HeartBeatInterval
1895 if (HeartBeatInterval
) {
1896 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1898 !this.stationInfo
.autoRegister
&&
1900 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1901 Constants.DEFAULT_HEARTBEAT_INTERVAL
1904 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1907 private stopHeartbeat(): void {
1908 if (this.heartbeatSetInterval
) {
1909 clearInterval(this.heartbeatSetInterval
);
1913 private openWSConnection(
1914 options
: WsOptions
= this.stationInfo
.wsOptions
,
1915 forceCloseOpened
= false
1917 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
1919 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
1920 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
1922 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
1924 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
1925 this.wsConnection
.close();
1927 let protocol
: string;
1928 switch (this.getOcppVersion()) {
1929 case OCPPVersion
.VERSION_16
:
1930 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
1933 this.handleUnsupportedVersion(this.getOcppVersion());
1936 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
1938 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString()
1942 private stopMeterValues(connectorId
: number) {
1943 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1944 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1948 private getReconnectExponentialDelay(): boolean | undefined {
1949 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1950 ? this.stationInfo
.reconnectExponentialDelay
1954 private async reconnect(code
: number): Promise
<void> {
1955 // Stop WebSocket ping
1956 this.stopWebSocketPing();
1958 this.stopHeartbeat();
1959 // Stop the ATG if needed
1961 this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1962 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
1963 this.automaticTransactionGenerator
?.started
1965 this.automaticTransactionGenerator
.stop();
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 reconnectTimeout
= reconnectDelay
- 100 > 0 && reconnectDelay
;
1977 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1980 )}ms, timeout ${reconnectTimeout}ms`
1982 await Utils
.sleep(reconnectDelay
);
1985 ' WebSocket: reconnecting try #' +
1986 this.autoReconnectRetryCount
.toString()
1988 this.openWSConnection(
1989 { ...this.stationInfo
.wsOptions
, handshakeTimeout
: reconnectTimeout
},
1992 this.wsConnectionRestarted
= true;
1993 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1995 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
1996 this.autoReconnectRetryCount
1997 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2002 private initializeConnectorStatus(connectorId
: number): void {
2003 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2004 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2005 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2006 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2007 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2008 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;