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 ChargingStationTemplate
, {
29 } from
'../types/ChargingStationTemplate';
31 ConnectorPhaseRotation
,
32 StandardParametersKey
,
33 SupportedFeatureProfiles
,
34 VendorDefaultParametersKey
,
35 } from
'../types/ocpp/Configuration';
36 import { MeterValue
, MeterValueMeasurand
} from
'../types/ocpp/MeterValues';
38 StopTransactionReason
,
39 StopTransactionRequest
,
40 StopTransactionResponse
,
41 } from
'../types/ocpp/Transaction';
42 import { URL
, fileURLToPath
} from
'url';
43 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
44 import WebSocket
, { Data
, RawData
} from
'ws';
46 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
47 import { AutomaticTransactionGeneratorConfiguration
} from
'../types/AutomaticTransactionGenerator';
48 import BaseError from
'../exception/BaseError';
49 import { ChargePointErrorCode
} from
'../types/ocpp/ChargePointErrorCode';
50 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
51 import { ChargingStationCache
} from
'./ChargingStationCache';
52 import ChargingStationConfiguration from
'../types/ChargingStationConfiguration';
53 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
54 import ChargingStationInfo from
'../types/ChargingStationInfo';
55 import ChargingStationOcppConfiguration from
'../types/ChargingStationOcppConfiguration';
56 import { ChargingStationUtils
} from
'./ChargingStationUtils';
57 import { ChargingStationWorkerMessageEvents
} from
'../types/ChargingStationWorker';
58 import Configuration from
'../utils/Configuration';
59 import { ConnectorStatus
} from
'../types/ConnectorStatus';
60 import Constants from
'../utils/Constants';
61 import { ErrorType
} from
'../types/ocpp/ErrorType';
62 import { FileType
} from
'../types/FileType';
63 import FileUtils from
'../utils/FileUtils';
64 import { JsonType
} from
'../types/JsonType';
65 import { MessageType
} from
'../types/ocpp/MessageType';
66 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
67 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
68 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
69 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
70 import OCPPError from
'../exception/OCPPError';
71 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
72 import OCPPRequestService from
'./ocpp/OCPPRequestService';
73 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
74 import PerformanceStatistics from
'../performance/PerformanceStatistics';
75 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
76 import Utils from
'../utils/Utils';
77 import crypto from
'crypto';
79 import logger from
'../utils/Logger';
80 import { parentPort
} from
'worker_threads';
81 import path from
'path';
83 export default class ChargingStation
{
84 public hashId
!: string;
85 public readonly templateFile
: string;
86 public authorizedTags
: string[];
87 public stationInfo
!: ChargingStationInfo
;
88 public readonly connectors
: Map
<number, ConnectorStatus
>;
89 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
90 public wsConnection
!: WebSocket
;
91 public readonly requests
: Map
<string, CachedRequest
>;
92 public performanceStatistics
!: PerformanceStatistics
;
93 public heartbeatSetInterval
!: NodeJS
.Timeout
;
94 public ocppRequestService
!: OCPPRequestService
;
95 public bootNotificationResponse
!: BootNotificationResponse
| null;
96 public powerDivider
!: number;
97 private readonly index
: number;
98 private configurationFile
!: string;
99 private configurationFileHash
!: string;
100 private bootNotificationRequest
!: BootNotificationRequest
;
101 private connectorsConfigurationHash
!: string;
102 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
103 private readonly messageBuffer
: Set
<string>;
104 private configuredSupervisionUrl
!: URL
;
105 private wsConnectionRestarted
: boolean;
106 private autoReconnectRetryCount
: number;
107 private stopped
: boolean;
108 private readonly cache
: ChargingStationCache
;
109 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
110 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
112 constructor(index
: number, templateFile
: string) {
114 this.templateFile
= templateFile
;
115 this.stopped
= false;
116 this.wsConnectionRestarted
= false;
117 this.autoReconnectRetryCount
= 0;
118 this.cache
= ChargingStationCache
.getInstance();
119 this.connectors
= new Map
<number, ConnectorStatus
>();
120 this.requests
= new Map
<string, CachedRequest
>();
121 this.messageBuffer
= new Set
<string>();
125 private get
wsConnectionUrl(): URL
{
127 (this.getSupervisionUrlOcppConfiguration()
128 ? ChargingStationConfigurationUtils
.getConfigurationKey(
130 this.getSupervisionUrlOcppKey()
132 : this.configuredSupervisionUrl
.href
) +
134 this.stationInfo
.chargingStationId
138 public logPrefix(): string {
139 return Utils
.logPrefix(
141 this?.stationInfo?.chargingStationId ??
142 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
147 public getBootNotificationRequest(): BootNotificationRequest
{
148 return this.bootNotificationRequest
;
151 public getRandomIdTag(): string {
152 const index
= Math.floor(Utils
.secureRandom() * this.authorizedTags
.length
);
153 return this.authorizedTags
[index
];
156 public hasAuthorizedTags(): boolean {
157 return !Utils
.isEmptyArray(this.authorizedTags
);
160 public getEnableStatistics(): boolean | undefined {
161 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
162 ? this.stationInfo
.enableStatistics
166 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
167 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
170 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
171 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
172 switch (this.getCurrentOutType(stationInfo
)) {
174 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
175 ? localStationInfo
.numberOfPhases
182 public isWebSocketConnectionOpened(): boolean {
183 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
186 public getRegistrationStatus(): RegistrationStatus
{
187 return this?.bootNotificationResponse
?.status;
190 public isInUnknownState(): boolean {
191 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
194 public isInPendingState(): boolean {
195 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
198 public isInAcceptedState(): boolean {
199 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
202 public isInRejectedState(): boolean {
203 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
206 public isRegistered(): boolean {
207 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
210 public isChargingStationAvailable(): boolean {
211 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
214 public isConnectorAvailable(id
: number): boolean {
215 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
218 public getNumberOfConnectors(): number {
219 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
222 public getConnectorStatus(id
: number): ConnectorStatus
{
223 return this.connectors
.get(id
);
226 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
227 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
;
230 public getOcppStrictCompliance(): boolean {
231 return this.stationInfo
?.ocppStrictCompliance
?? false;
234 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
235 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
236 this.getCurrentOutType(stationInfo
),
240 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
241 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
242 ? localStationInfo
.voltageOut
246 public getConnectorMaximumAvailablePower(connectorId
: number): number {
247 let connectorAmperageLimitationPowerLimit
: number;
249 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
250 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
252 connectorAmperageLimitationPowerLimit
=
253 (this.getCurrentOutType() === CurrentType
.AC
254 ? ACElectricUtils
.powerTotal(
255 this.getNumberOfPhases(),
256 this.getVoltageOut(),
257 this.getAmperageLimitation() * this.getNumberOfConnectors()
259 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
262 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
263 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
265 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
266 isNaN(connectorAmperageLimitationPowerLimit
)
268 : connectorAmperageLimitationPowerLimit
,
269 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
273 public getTransactionIdTag(transactionId
: number): string | undefined {
274 for (const connectorId
of this.connectors
.keys()) {
275 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
276 return this.getConnectorStatus(connectorId
).transactionIdTag
;
281 public getOutOfOrderEndMeterValues(): boolean {
282 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
285 public getBeginEndMeterValues(): boolean {
286 return this.stationInfo
?.beginEndMeterValues
?? false;
289 public getMeteringPerTransaction(): boolean {
290 return this.stationInfo
?.meteringPerTransaction
?? true;
293 public getTransactionDataMeterValues(): boolean {
294 return this.stationInfo
?.transactionDataMeterValues
?? false;
297 public getMainVoltageMeterValues(): boolean {
298 return this.stationInfo
?.mainVoltageMeterValues
?? true;
301 public getPhaseLineToLineVoltageMeterValues(): boolean {
302 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
305 public getCustomValueLimitationMeterValues(): boolean {
306 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
309 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
310 for (const connectorId
of this.connectors
.keys()) {
313 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
320 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
321 const transactionConnectorStatus
= this.getConnectorStatus(
322 this.getConnectorIdByTransactionId(transactionId
)
324 if (this.getMeteringPerTransaction()) {
325 return transactionConnectorStatus
?.transactionEnergyActiveImportRegisterValue
;
327 return transactionConnectorStatus
?.energyActiveImportRegisterValue
;
330 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
331 const connectorStatus
= this.getConnectorStatus(connectorId
);
332 if (this.getMeteringPerTransaction()) {
333 return connectorStatus
?.transactionEnergyActiveImportRegisterValue
;
335 return connectorStatus
?.energyActiveImportRegisterValue
;
338 public getAuthorizeRemoteTxRequests(): boolean {
339 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
341 StandardParametersKey
.AuthorizeRemoteTxRequests
343 return authorizeRemoteTxRequests
344 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
348 public getLocalAuthListEnabled(): boolean {
349 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
351 StandardParametersKey
.LocalAuthListEnabled
353 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
356 public startHeartbeat(): void {
358 this.getHeartbeatInterval() &&
359 this.getHeartbeatInterval() > 0 &&
360 !this.heartbeatSetInterval
362 // eslint-disable-next-line @typescript-eslint/no-misused-promises
363 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
364 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
366 RequestCommand
.HEARTBEAT
368 }, this.getHeartbeatInterval());
371 ' Heartbeat started every ' +
372 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
374 } else if (this.heartbeatSetInterval
) {
377 ' Heartbeat already started every ' +
378 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
382 `${this.logPrefix()} Heartbeat interval set to ${
383 this.getHeartbeatInterval()
384 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
385 : this.getHeartbeatInterval()
386 }, not starting the heartbeat`
391 public restartHeartbeat(): void {
393 this.stopHeartbeat();
395 this.startHeartbeat();
398 public restartWebSocketPing(): void {
399 // Stop WebSocket ping
400 this.stopWebSocketPing();
401 // Start WebSocket ping
402 this.startWebSocketPing();
405 public startMeterValues(connectorId
: number, interval
: number): void {
406 if (connectorId
=== 0) {
408 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
412 if (!this.getConnectorStatus(connectorId
)) {
414 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
418 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
420 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
424 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
425 !this.getConnectorStatus(connectorId
)?.transactionId
428 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
433 // eslint-disable-next-line @typescript-eslint/no-misused-promises
434 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
435 // eslint-disable-next-line @typescript-eslint/no-misused-promises
436 async (): Promise
<void> => {
437 // FIXME: Implement OCPP version agnostic helpers
438 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
441 this.getConnectorStatus(connectorId
).transactionId
,
444 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
446 RequestCommand
.METER_VALUES
,
449 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
450 meterValue
: [meterValue
],
458 `${this.logPrefix()} Charging station ${
459 StandardParametersKey.MeterValueSampleInterval
460 } configuration set to ${
461 interval ? Utils.formatDurationMilliSeconds(interval) : interval
462 }, not sending MeterValues`
467 public start(): void {
468 if (this.getEnableStatistics()) {
469 this.performanceStatistics
.start();
471 this.openWSConnection();
472 // Handle WebSocket message
473 this.wsConnection
.on(
475 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
477 // Handle WebSocket error
478 this.wsConnection
.on(
480 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
482 // Handle WebSocket close
483 this.wsConnection
.on(
485 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
487 // Handle WebSocket open
488 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
489 // Handle WebSocket ping
490 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
491 // Handle WebSocket pong
492 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
493 // Monitor authorization file
494 FileUtils
.watchJsonFile
<string[]>(
496 FileType
.Authorization
,
497 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
),
500 // Monitor charging station template file
501 FileUtils
.watchJsonFile(
503 FileType
.ChargingStationTemplate
,
506 (event
, filename
): void => {
507 if (filename
&& event
=== 'change') {
510 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
512 } file have changed, reload`
514 this.cache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
518 this.stopAutomaticTransactionGenerator();
519 this.startAutomaticTransactionGenerator();
520 if (this.getEnableStatistics()) {
521 this.performanceStatistics
.restart();
523 this.performanceStatistics
.stop();
525 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
528 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
535 parentPort
.postMessage({
536 id
: ChargingStationWorkerMessageEvents
.STARTED
,
537 data
: { id
: this.stationInfo
.chargingStationId
},
541 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
542 // Stop message sequence
543 await this.stopMessageSequence(reason
);
544 for (const connectorId
of this.connectors
.keys()) {
545 if (connectorId
> 0) {
546 await this.ocppRequestService
.requestHandler
<
547 StatusNotificationRequest
,
548 StatusNotificationResponse
549 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
551 status: ChargePointStatus
.UNAVAILABLE
,
552 errorCode
: ChargePointErrorCode
.NO_ERROR
,
554 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
557 this.closeWSConnection();
558 if (this.getEnableStatistics()) {
559 this.performanceStatistics
.stop();
561 this.cache
.deleteChargingStationConfiguration(this.configurationFileHash
);
562 this.cache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
563 this.bootNotificationResponse
= null;
564 parentPort
.postMessage({
565 id
: ChargingStationWorkerMessageEvents
.STOPPED
,
566 data
: { id
: this.stationInfo
.chargingStationId
},
571 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
572 await this.stop(reason
);
573 await Utils
.sleep(this.stationInfo
.resetTime
);
578 public saveOcppConfiguration(): void {
579 if (this.getOcppPersistentConfiguration()) {
580 this.saveConfiguration();
584 public getChargingProfilePowerLimit(connectorId
: number): number | undefined {
585 let limit
: number, matchingChargingProfile
: ChargingProfile
;
586 let chargingProfiles
: ChargingProfile
[] = [];
587 // Get charging profiles for connector and sort by stack level
588 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
589 (a
, b
) => b
.stackLevel
- a
.stackLevel
591 // Get profiles on connector 0
592 if (this.getConnectorStatus(0).chargingProfiles
) {
593 chargingProfiles
.push(
594 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
597 if (!Utils
.isEmptyArray(chargingProfiles
)) {
598 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
602 if (!Utils
.isNullOrUndefined(result
)) {
603 limit
= result
.limit
;
604 matchingChargingProfile
= result
.matchingChargingProfile
;
605 switch (this.getCurrentOutType()) {
608 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
609 ChargingRateUnitType
.WATT
611 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
615 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
616 ChargingRateUnitType
.WATT
618 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
621 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
622 if (limit
> connectorMaximumPower
) {
624 `${this.logPrefix()} Charging profile id ${
625 matchingChargingProfile.chargingProfileId
626 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
627 this.getConnectorStatus(connectorId
).chargingProfiles
629 limit
= connectorMaximumPower
;
636 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
637 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
639 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
641 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
643 if (!Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
645 `${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`
647 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
649 let cpReplaced
= false;
650 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
651 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
652 (chargingProfile
: ChargingProfile
, index
: number) => {
654 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
655 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
656 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
658 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
664 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
667 public resetConnectorStatus(connectorId
: number): void {
668 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
669 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
670 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
671 this.getConnectorStatus(connectorId
).transactionStarted
= false;
672 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
673 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
674 delete this.getConnectorStatus(connectorId
).transactionId
;
675 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
676 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
677 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
678 this.stopMeterValues(connectorId
);
681 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
682 return ChargingStationConfigurationUtils
.getConfigurationKey(
684 StandardParametersKey
.SupportedFeatureProfiles
685 )?.value
.includes(featureProfile
);
688 public bufferMessage(message
: string): void {
689 this.messageBuffer
.add(message
);
692 private flushMessageBuffer() {
693 if (this.messageBuffer
.size
> 0) {
694 this.messageBuffer
.forEach((message
) => {
695 // TODO: evaluate the need to track performance
696 this.wsConnection
.send(message
);
697 this.messageBuffer
.delete(message
);
702 private getSupervisionUrlOcppConfiguration(): boolean {
703 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
706 private getSupervisionUrlOcppKey(): string {
707 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
710 private getTemplateFromFile(): ChargingStationTemplate
| null {
711 let template
: ChargingStationTemplate
= null;
713 if (this.cache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
714 template
= this.cache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
716 const measureId
= `${FileType.ChargingStationTemplate} read`;
717 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
718 template
= JSON
.parse(
719 fs
.readFileSync(this.templateFile
, 'utf8')
720 ) as ChargingStationTemplate
;
721 PerformanceStatistics
.endMeasure(measureId
, beginId
);
722 template
.templateHash
= crypto
723 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
724 .update(JSON
.stringify(template
))
726 this.cache
.setChargingStationTemplate(template
);
729 FileUtils
.handleFileException(
731 FileType
.ChargingStationTemplate
,
733 error
as NodeJS
.ErrnoException
739 private getStationInfoFromTemplate(): ChargingStationInfo
{
740 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
741 if (Utils
.isNullOrUndefined(stationTemplate
)) {
742 const errorMsg
= 'Failed to read charging station template file';
743 logger
.error(`${this.logPrefix()} ${errorMsg}`);
744 throw new BaseError(errorMsg
);
746 if (Utils
.isEmptyObject(stationTemplate
)) {
747 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
748 logger
.error(`${this.logPrefix()} ${errorMsg}`);
749 throw new BaseError(errorMsg
);
751 // Deprecation template keys section
752 ChargingStationUtils
.warnDeprecatedTemplateKey(
757 "Use 'supervisionUrls' instead"
759 ChargingStationUtils
.convertDeprecatedTemplateKey(
764 const stationInfo
: ChargingStationInfo
=
765 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
766 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
770 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
771 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
772 stationTemplate
.power
= stationTemplate
.power
as number[];
773 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
774 stationInfo
.maximumPower
=
775 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
776 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
777 : stationTemplate
.power
[powerArrayRandomIndex
];
779 stationTemplate
.power
= stationTemplate
.power
as number;
780 stationInfo
.maximumPower
=
781 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
782 ? stationTemplate
.power
* 1000
783 : stationTemplate
.power
;
785 stationInfo
.resetTime
= stationTemplate
.resetTime
786 ? stationTemplate
.resetTime
* 1000
787 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
788 const configuredMaxConnectors
= ChargingStationUtils
.getConfiguredNumberOfConnectors(
792 ChargingStationUtils
.checkConfiguredMaxConnectors(
793 configuredMaxConnectors
,
797 const templateMaxConnectors
=
798 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
799 ChargingStationUtils
.checkTemplateMaxConnectors(
800 templateMaxConnectors
,
805 configuredMaxConnectors
>
806 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
807 !stationTemplate
?.randomConnectors
810 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
812 }, forcing random connector configurations affectation`
814 stationInfo
.randomConnectors
= true;
816 // Build connectors if needed (FIXME: should be factored out)
817 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
818 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
819 ChargingStationUtils
.createStationInfoHash(stationInfo
);
823 private getStationInfoFromFile(): ChargingStationInfo
| null {
824 let stationInfo
: ChargingStationInfo
= null;
825 this.getStationInfoPersistentConfiguration() &&
826 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
827 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
831 private getStationInfo(): ChargingStationInfo
{
832 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
833 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
834 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
835 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
836 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
837 return this.stationInfo
;
839 return stationInfoFromFile
;
841 stationInfoFromFile
&&
842 ChargingStationUtils
.propagateSerialNumber(
843 this.getTemplateFromFile(),
845 stationInfoFromTemplate
847 return stationInfoFromTemplate
;
850 private saveStationInfo(): void {
851 if (this.getStationInfoPersistentConfiguration()) {
852 this.saveConfiguration();
856 private getOcppVersion(): OCPPVersion
{
857 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
860 private getOcppPersistentConfiguration(): boolean {
861 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
864 private getStationInfoPersistentConfiguration(): boolean {
865 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
868 private handleUnsupportedVersion(version
: OCPPVersion
) {
869 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
872 logger
.error(errMsg
);
873 throw new Error(errMsg
);
876 private initialize(): void {
877 this.hashId
= ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile());
878 logger
.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
879 this.configurationFile
= path
.join(
880 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
883 this.hashId
+ '.json'
885 this.stationInfo
= this.getStationInfo();
886 this.saveStationInfo();
887 // Avoid duplication of connectors related information in RAM
888 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
889 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
890 if (this.getEnableStatistics()) {
891 this.performanceStatistics
= PerformanceStatistics
.getInstance(
893 this.stationInfo
.chargingStationId
,
894 this.configuredSupervisionUrl
897 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
900 this.authorizedTags
= ChargingStationUtils
.getAuthorizedTags(
905 this.powerDivider
= this.getPowerDivider();
906 // OCPP configuration
907 this.ocppConfiguration
= this.getOcppConfiguration();
908 this.initializeOcppConfiguration();
909 switch (this.getOcppVersion()) {
910 case OCPPVersion
.VERSION_16
:
911 this.ocppIncomingRequestService
=
912 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
913 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
914 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
918 this.handleUnsupportedVersion(this.getOcppVersion());
921 if (this.stationInfo
?.autoRegister
) {
922 this.bootNotificationResponse
= {
923 currentTime
: new Date().toISOString(),
924 interval
: this.getHeartbeatInterval() / 1000,
925 status: RegistrationStatus
.ACCEPTED
,
930 private initializeOcppConfiguration(): void {
932 !ChargingStationConfigurationUtils
.getConfigurationKey(
934 StandardParametersKey
.HeartbeatInterval
937 ChargingStationConfigurationUtils
.addConfigurationKey(
939 StandardParametersKey
.HeartbeatInterval
,
944 !ChargingStationConfigurationUtils
.getConfigurationKey(
946 StandardParametersKey
.HeartBeatInterval
949 ChargingStationConfigurationUtils
.addConfigurationKey(
951 StandardParametersKey
.HeartBeatInterval
,
957 this.getSupervisionUrlOcppConfiguration() &&
958 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
960 ChargingStationConfigurationUtils
.addConfigurationKey(
962 this.getSupervisionUrlOcppKey(),
963 this.configuredSupervisionUrl
.href
,
967 !this.getSupervisionUrlOcppConfiguration() &&
968 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
970 ChargingStationConfigurationUtils
.deleteConfigurationKey(
972 this.getSupervisionUrlOcppKey(),
977 this.stationInfo
.amperageLimitationOcppKey
&&
978 !ChargingStationConfigurationUtils
.getConfigurationKey(
980 this.stationInfo
.amperageLimitationOcppKey
983 ChargingStationConfigurationUtils
.addConfigurationKey(
985 this.stationInfo
.amperageLimitationOcppKey
,
987 this.stationInfo
.maximumAmperage
*
988 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
993 !ChargingStationConfigurationUtils
.getConfigurationKey(
995 StandardParametersKey
.SupportedFeatureProfiles
998 ChargingStationConfigurationUtils
.addConfigurationKey(
1000 StandardParametersKey
.SupportedFeatureProfiles
,
1001 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1004 ChargingStationConfigurationUtils
.addConfigurationKey(
1006 StandardParametersKey
.NumberOfConnectors
,
1007 this.getNumberOfConnectors().toString(),
1012 !ChargingStationConfigurationUtils
.getConfigurationKey(
1014 StandardParametersKey
.MeterValuesSampledData
1017 ChargingStationConfigurationUtils
.addConfigurationKey(
1019 StandardParametersKey
.MeterValuesSampledData
,
1020 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1024 !ChargingStationConfigurationUtils
.getConfigurationKey(
1026 StandardParametersKey
.ConnectorPhaseRotation
1029 const connectorPhaseRotation
= [];
1030 for (const connectorId
of this.connectors
.keys()) {
1032 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1033 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1034 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1035 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1037 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1038 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1039 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1040 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1043 ChargingStationConfigurationUtils
.addConfigurationKey(
1045 StandardParametersKey
.ConnectorPhaseRotation
,
1046 connectorPhaseRotation
.toString()
1050 !ChargingStationConfigurationUtils
.getConfigurationKey(
1052 StandardParametersKey
.AuthorizeRemoteTxRequests
1055 ChargingStationConfigurationUtils
.addConfigurationKey(
1057 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1062 !ChargingStationConfigurationUtils
.getConfigurationKey(
1064 StandardParametersKey
.LocalAuthListEnabled
1066 ChargingStationConfigurationUtils
.getConfigurationKey(
1068 StandardParametersKey
.SupportedFeatureProfiles
1069 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1071 ChargingStationConfigurationUtils
.addConfigurationKey(
1073 StandardParametersKey
.LocalAuthListEnabled
,
1078 !ChargingStationConfigurationUtils
.getConfigurationKey(
1080 StandardParametersKey
.ConnectionTimeOut
1083 ChargingStationConfigurationUtils
.addConfigurationKey(
1085 StandardParametersKey
.ConnectionTimeOut
,
1086 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1089 this.saveOcppConfiguration();
1092 private initializeConnectors(
1093 stationInfo
: ChargingStationInfo
,
1094 configuredMaxConnectors
: number,
1095 templateMaxConnectors
: number
1097 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1098 const logMsg
= `${this.logPrefix()} No already defined connectors and charging station information from template ${
1100 } with no connectors configuration defined`;
1101 logger
.error(logMsg
);
1102 throw new BaseError(logMsg
);
1104 if (!stationInfo
?.Connectors
[0]) {
1106 `${this.logPrefix()} Charging station information from template ${
1108 } with no connector Id 0 configuration`
1111 if (stationInfo
?.Connectors
) {
1112 const connectorsConfigHash
= crypto
1113 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1114 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1116 const connectorsConfigChanged
=
1117 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1118 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1119 connectorsConfigChanged
&& this.connectors
.clear();
1120 this.connectorsConfigurationHash
= connectorsConfigHash
;
1121 // Add connector Id 0
1122 let lastConnector
= '0';
1123 for (lastConnector
in stationInfo
?.Connectors
) {
1124 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1126 lastConnectorId
=== 0 &&
1127 this.getUseConnectorId0(stationInfo
) &&
1128 stationInfo
?.Connectors
[lastConnector
]
1130 this.connectors
.set(
1132 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1134 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1135 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1136 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1140 // Generate all connectors
1141 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1142 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1143 const randConnectorId
= stationInfo
?.randomConnectors
1144 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1146 this.connectors
.set(
1148 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1150 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1151 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1152 this.getConnectorStatus(index
).chargingProfiles
= [];
1159 `${this.logPrefix()} Charging station information from template ${
1161 } with no connectors configuration defined, using already defined connectors`
1164 // Initialize transaction attributes on connectors
1165 for (const connectorId
of this.connectors
.keys()) {
1166 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1167 this.initializeConnectorStatus(connectorId
);
1172 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1173 let configuration
: ChargingStationConfiguration
= null;
1174 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1176 if (this.cache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1177 configuration
= this.cache
.getChargingStationConfiguration(this.configurationFileHash
);
1179 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1180 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1181 configuration
= JSON
.parse(
1182 fs
.readFileSync(this.configurationFile
, 'utf8')
1183 ) as ChargingStationConfiguration
;
1184 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1185 this.configurationFileHash
= configuration
.configurationHash
;
1186 this.cache
.setChargingStationConfiguration(configuration
);
1189 FileUtils
.handleFileException(
1191 FileType
.ChargingStationConfiguration
,
1192 this.configurationFile
,
1193 error
as NodeJS
.ErrnoException
1197 return configuration
;
1200 private saveConfiguration(): void {
1201 if (this.configurationFile
) {
1203 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1204 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1206 const configurationData
: ChargingStationConfiguration
=
1207 this.getConfigurationFromFile() ?? {};
1208 this.ocppConfiguration
?.configurationKey
&&
1209 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1210 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1211 delete configurationData
.configurationHash
;
1212 const configurationHash
= crypto
1213 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1214 .update(JSON
.stringify(configurationData
))
1216 if (this.configurationFileHash
!== configurationHash
) {
1217 configurationData
.configurationHash
= configurationHash
;
1218 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1219 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1220 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1221 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1222 fs
.closeSync(fileDescriptor
);
1223 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1224 this.cache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1225 this.configurationFileHash
= configurationHash
;
1226 this.cache
.setChargingStationConfiguration(configurationData
);
1229 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1230 this.configurationFile
1235 FileUtils
.handleFileException(
1237 FileType
.ChargingStationConfiguration
,
1238 this.configurationFile
,
1239 error
as NodeJS
.ErrnoException
1244 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1249 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1250 return this.getTemplateFromFile()?.Configuration
?? null;
1253 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1254 let configuration
: ChargingStationConfiguration
= null;
1255 if (this.getOcppPersistentConfiguration()) {
1256 const configurationFromFile
= this.getConfigurationFromFile();
1257 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1259 configuration
&& delete configuration
.stationInfo
;
1260 return configuration
;
1263 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1264 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1265 if (!ocppConfiguration
) {
1266 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1268 return ocppConfiguration
;
1271 private async onOpen(): Promise
<void> {
1272 if (this.isWebSocketConnectionOpened()) {
1274 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1276 if (!this.isRegistered()) {
1277 // Send BootNotification
1278 let registrationRetryCount
= 0;
1280 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1281 BootNotificationRequest
,
1282 BootNotificationResponse
1285 RequestCommand
.BOOT_NOTIFICATION
,
1287 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1288 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1289 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1290 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1291 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1292 iccid
: this.bootNotificationRequest
.iccid
,
1293 imsi
: this.bootNotificationRequest
.imsi
,
1294 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1295 meterType
: this.bootNotificationRequest
.meterType
,
1297 { skipBufferingOnError
: true }
1299 if (!this.isRegistered()) {
1300 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1302 this.bootNotificationResponse
?.interval
1303 ? this.bootNotificationResponse
.interval
* 1000
1304 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1308 !this.isRegistered() &&
1309 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1310 this.getRegistrationMaxRetries() === -1)
1313 if (this.isRegistered()) {
1314 if (this.isInAcceptedState()) {
1315 await this.startMessageSequence();
1316 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1320 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1323 this.stopped
&& (this.stopped
= false);
1324 this.autoReconnectRetryCount
= 0;
1325 this.wsConnectionRestarted
= false;
1328 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1333 private async onClose(code
: number, reason
: string): Promise
<void> {
1336 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1337 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1339 `${this.logPrefix()} WebSocket normally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1341 )}' and reason '${reason}'`
1343 this.autoReconnectRetryCount
= 0;
1348 `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1350 )}' and reason '${reason}'`
1352 await this.reconnect(code
);
1357 private async onMessage(data
: Data
): Promise
<void> {
1358 let messageType
: number;
1359 let messageId
: string;
1360 let commandName
: IncomingRequestCommand
;
1361 let commandPayload
: JsonType
;
1362 let errorType
: ErrorType
;
1363 let errorMessage
: string;
1364 let errorDetails
: JsonType
;
1365 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1366 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1367 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1368 let requestPayload
: JsonType
;
1369 let cachedRequest
: CachedRequest
;
1372 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1373 if (Utils
.isIterable(request
)) {
1374 [messageType
, messageId
] = request
;
1375 // Check the type of message
1376 switch (messageType
) {
1378 case MessageType
.CALL_MESSAGE
:
1379 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1380 if (this.getEnableStatistics()) {
1381 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1384 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1388 // Process the message
1389 await this.ocppIncomingRequestService
.incomingRequestHandler(
1397 case MessageType
.CALL_RESULT_MESSAGE
:
1398 [, , commandPayload
] = request
as Response
;
1399 if (!this.requests
.has(messageId
)) {
1401 throw new OCPPError(
1402 ErrorType
.INTERNAL_ERROR
,
1403 `Response for unknown message id ${messageId}`,
1409 cachedRequest
= this.requests
.get(messageId
);
1410 if (Utils
.isIterable(cachedRequest
)) {
1411 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1413 throw new OCPPError(
1414 ErrorType
.PROTOCOL_ERROR
,
1415 `Cached request for message id ${messageId} response is not iterable`,
1417 cachedRequest
as unknown
as JsonType
1421 `${this.logPrefix()} << Command '${
1422 requestCommandName ?? ''
1423 }' received response payload: ${JSON.stringify(request)}`
1425 responseCallback(commandPayload
, requestPayload
);
1428 case MessageType
.CALL_ERROR_MESSAGE
:
1429 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1430 if (!this.requests
.has(messageId
)) {
1432 throw new OCPPError(
1433 ErrorType
.INTERNAL_ERROR
,
1434 `Error response for unknown message id ${messageId}`,
1436 { errorType
, errorMessage
, errorDetails
}
1439 cachedRequest
= this.requests
.get(messageId
);
1440 if (Utils
.isIterable(cachedRequest
)) {
1441 [, errorCallback
, requestCommandName
] = cachedRequest
;
1443 throw new OCPPError(
1444 ErrorType
.PROTOCOL_ERROR
,
1445 `Cached request for message id ${messageId} error response is not iterable`,
1447 cachedRequest
as unknown
as JsonType
1451 `${this.logPrefix()} << Command '${
1452 requestCommandName ?? ''
1453 }' received error payload: ${JSON.stringify(request)}`
1455 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1459 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1460 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
1461 logger
.error(errMsg
);
1462 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1465 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not iterable', null, {
1472 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1475 this.requests
.get(messageId
),
1479 messageType
=== MessageType
.CALL_MESSAGE
&&
1480 (await this.ocppRequestService
.sendError(
1484 commandName
?? requestCommandName
?? null
1489 private onPing(): void {
1490 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1493 private onPong(): void {
1494 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1497 private onError(error
: WSError
): void {
1498 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
1501 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean | undefined {
1502 const localStationInfo
= stationInfo
?? this.stationInfo
;
1503 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1504 ? localStationInfo
.useConnectorId0
1508 private getNumberOfRunningTransactions(): number {
1510 for (const connectorId
of this.connectors
.keys()) {
1511 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1519 private getConnectionTimeout(): number | undefined {
1521 ChargingStationConfigurationUtils
.getConfigurationKey(
1523 StandardParametersKey
.ConnectionTimeOut
1528 ChargingStationConfigurationUtils
.getConfigurationKey(
1530 StandardParametersKey
.ConnectionTimeOut
1532 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1535 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1538 // -1 for unlimited, 0 for disabling
1539 private getAutoReconnectMaxRetries(): number | undefined {
1540 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1541 return this.stationInfo
.autoReconnectMaxRetries
;
1543 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1544 return Configuration
.getAutoReconnectMaxRetries();
1550 private getRegistrationMaxRetries(): number | undefined {
1551 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1552 return this.stationInfo
.registrationMaxRetries
;
1557 private getPowerDivider(): number {
1558 let powerDivider
= this.getNumberOfConnectors();
1559 if (this.stationInfo
?.powerSharedByConnectors
) {
1560 powerDivider
= this.getNumberOfRunningTransactions();
1562 return powerDivider
;
1565 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1566 const localStationInfo
= stationInfo
?? this.stationInfo
;
1567 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1570 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1571 const maximumPower
= this.getMaximumPower(stationInfo
);
1572 switch (this.getCurrentOutType(stationInfo
)) {
1573 case CurrentType
.AC
:
1574 return ACElectricUtils
.amperagePerPhaseFromPower(
1575 this.getNumberOfPhases(stationInfo
),
1576 maximumPower
/ this.getNumberOfConnectors(),
1577 this.getVoltageOut(stationInfo
)
1579 case CurrentType
.DC
:
1580 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1584 private getAmperageLimitation(): number | undefined {
1586 this.stationInfo
.amperageLimitationOcppKey
&&
1587 ChargingStationConfigurationUtils
.getConfigurationKey(
1589 this.stationInfo
.amperageLimitationOcppKey
1594 ChargingStationConfigurationUtils
.getConfigurationKey(
1596 this.stationInfo
.amperageLimitationOcppKey
1598 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1603 private async startMessageSequence(): Promise
<void> {
1604 if (this.stationInfo
?.autoRegister
) {
1605 await this.ocppRequestService
.requestHandler
<
1606 BootNotificationRequest
,
1607 BootNotificationResponse
1610 RequestCommand
.BOOT_NOTIFICATION
,
1612 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1613 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1614 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1615 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1616 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1617 iccid
: this.bootNotificationRequest
.iccid
,
1618 imsi
: this.bootNotificationRequest
.imsi
,
1619 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1620 meterType
: this.bootNotificationRequest
.meterType
,
1622 { skipBufferingOnError
: true }
1625 // Start WebSocket ping
1626 this.startWebSocketPing();
1628 this.startHeartbeat();
1629 // Initialize connectors status
1630 for (const connectorId
of this.connectors
.keys()) {
1631 if (connectorId
=== 0) {
1635 !this.getConnectorStatus(connectorId
)?.status &&
1636 this.getConnectorStatus(connectorId
)?.bootStatus
1638 // Send status in template at startup
1639 await this.ocppRequestService
.requestHandler
<
1640 StatusNotificationRequest
,
1641 StatusNotificationResponse
1642 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1644 status: this.getConnectorStatus(connectorId
).bootStatus
,
1645 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1647 this.getConnectorStatus(connectorId
).status =
1648 this.getConnectorStatus(connectorId
).bootStatus
;
1651 this.getConnectorStatus(connectorId
)?.status &&
1652 this.getConnectorStatus(connectorId
)?.bootStatus
1654 // Send status in template after reset
1655 await this.ocppRequestService
.requestHandler
<
1656 StatusNotificationRequest
,
1657 StatusNotificationResponse
1658 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1660 status: this.getConnectorStatus(connectorId
).bootStatus
,
1661 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1663 this.getConnectorStatus(connectorId
).status =
1664 this.getConnectorStatus(connectorId
).bootStatus
;
1665 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1666 // Send previous status at template reload
1667 await this.ocppRequestService
.requestHandler
<
1668 StatusNotificationRequest
,
1669 StatusNotificationResponse
1670 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1672 status: this.getConnectorStatus(connectorId
).status,
1673 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1676 // Send default status
1677 await this.ocppRequestService
.requestHandler
<
1678 StatusNotificationRequest
,
1679 StatusNotificationResponse
1680 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1682 status: ChargePointStatus
.AVAILABLE
,
1683 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1685 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1689 this.startAutomaticTransactionGenerator();
1692 private startAutomaticTransactionGenerator() {
1693 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
) {
1694 if (!this.automaticTransactionGenerator
) {
1695 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
1696 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
1700 if (!this.automaticTransactionGenerator
.started
) {
1701 this.automaticTransactionGenerator
.start();
1706 private stopAutomaticTransactionGenerator(): void {
1707 if (this.automaticTransactionGenerator
?.started
) {
1708 this.automaticTransactionGenerator
.stop();
1709 this.automaticTransactionGenerator
= null;
1713 private async stopMessageSequence(
1714 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1716 // Stop WebSocket ping
1717 this.stopWebSocketPing();
1719 this.stopHeartbeat();
1720 // Stop ongoing transactions
1721 if (this.automaticTransactionGenerator
?.configuration
?.enable
) {
1722 this.stopAutomaticTransactionGenerator();
1724 for (const connectorId
of this.connectors
.keys()) {
1725 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1726 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1728 this.getBeginEndMeterValues() &&
1729 this.getOcppStrictCompliance() &&
1730 !this.getOutOfOrderEndMeterValues()
1732 // FIXME: Implement OCPP version agnostic helpers
1733 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1736 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1738 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
1740 RequestCommand
.METER_VALUES
,
1744 meterValue
: transactionEndMeterValue
,
1748 await this.ocppRequestService
.requestHandler
<
1749 StopTransactionRequest
,
1750 StopTransactionResponse
1751 >(this, RequestCommand
.STOP_TRANSACTION
, {
1753 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1754 idTag
: this.getTransactionIdTag(transactionId
),
1762 private startWebSocketPing(): void {
1763 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1765 StandardParametersKey
.WebSocketPingInterval
1767 ? Utils
.convertToInt(
1768 ChargingStationConfigurationUtils
.getConfigurationKey(
1770 StandardParametersKey
.WebSocketPingInterval
1774 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1775 this.webSocketPingSetInterval
= setInterval(() => {
1776 if (this.isWebSocketConnectionOpened()) {
1777 this.wsConnection
.ping((): void => {
1778 /* This is intentional */
1781 }, webSocketPingInterval
* 1000);
1784 ' WebSocket ping started every ' +
1785 Utils
.formatDurationSeconds(webSocketPingInterval
)
1787 } else if (this.webSocketPingSetInterval
) {
1790 ' WebSocket ping every ' +
1791 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1796 `${this.logPrefix()} WebSocket ping interval set to ${
1797 webSocketPingInterval
1798 ? Utils.formatDurationSeconds(webSocketPingInterval)
1799 : webSocketPingInterval
1800 }, not starting the WebSocket ping`
1805 private stopWebSocketPing(): void {
1806 if (this.webSocketPingSetInterval
) {
1807 clearInterval(this.webSocketPingSetInterval
);
1811 private getConfiguredSupervisionUrl(): URL
{
1812 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1813 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1815 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1817 switch (Configuration
.getSupervisionUrlDistribution()) {
1818 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1819 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1821 case SupervisionUrlDistribution
.RANDOM
:
1823 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1825 case SupervisionUrlDistribution
.SEQUENTIAL
:
1826 if (this.index
<= supervisionUrls
.length
) {
1827 urlIndex
= this.index
- 1;
1830 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1836 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1837 SupervisionUrlDistribution.ROUND_ROBIN
1840 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1843 return new URL(supervisionUrls
[urlIndex
]);
1845 return new URL(supervisionUrls
as string);
1848 private getHeartbeatInterval(): number | undefined {
1849 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1851 StandardParametersKey
.HeartbeatInterval
1853 if (HeartbeatInterval
) {
1854 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1856 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1858 StandardParametersKey
.HeartBeatInterval
1860 if (HeartBeatInterval
) {
1861 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1863 !this.stationInfo
?.autoRegister
&&
1865 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1866 Constants.DEFAULT_HEARTBEAT_INTERVAL
1869 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1872 private stopHeartbeat(): void {
1873 if (this.heartbeatSetInterval
) {
1874 clearInterval(this.heartbeatSetInterval
);
1878 private openWSConnection(
1879 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
1880 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
1882 terminateOpened
: false,
1885 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
1886 params
.closeOpened
= params
?.closeOpened
?? false;
1887 params
.terminateOpened
= params
?.terminateOpened
?? false;
1889 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
1890 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
1892 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
1894 if (params
?.closeOpened
) {
1895 this.closeWSConnection();
1897 if (params
?.terminateOpened
) {
1898 this.terminateWSConnection();
1900 let protocol
: string;
1901 switch (this.getOcppVersion()) {
1902 case OCPPVersion
.VERSION_16
:
1903 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
1906 this.handleUnsupportedVersion(this.getOcppVersion());
1909 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
1911 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString()
1915 private closeWSConnection(): void {
1916 if (this.isWebSocketConnectionOpened()) {
1917 this.wsConnection
.close();
1918 this.wsConnection
= null;
1922 private terminateWSConnection(): void {
1923 if (this.isWebSocketConnectionOpened()) {
1924 this.wsConnection
.terminate();
1925 this.wsConnection
= null;
1929 private stopMeterValues(connectorId
: number) {
1930 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1931 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1935 private getReconnectExponentialDelay(): boolean | undefined {
1936 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1937 ? this.stationInfo
.reconnectExponentialDelay
1941 private async reconnect(code
: number): Promise
<void> {
1942 // Stop WebSocket ping
1943 this.stopWebSocketPing();
1945 this.stopHeartbeat();
1946 // Stop the ATG if needed
1947 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
) {
1948 this.stopAutomaticTransactionGenerator();
1951 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1952 this.getAutoReconnectMaxRetries() === -1
1954 this.autoReconnectRetryCount
++;
1955 const reconnectDelay
= this.getReconnectExponentialDelay()
1956 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1957 : this.getConnectionTimeout() * 1000;
1958 const reconnectDelayWithdraw
= 1000;
1959 const reconnectTimeout
=
1960 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
1961 ? reconnectDelay
- reconnectDelayWithdraw
1964 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1967 )}ms, timeout ${reconnectTimeout}ms`
1969 await Utils
.sleep(reconnectDelay
);
1972 ' WebSocket: reconnecting try #' +
1973 this.autoReconnectRetryCount
.toString()
1975 this.openWSConnection(
1976 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
1977 { closeOpened
: true }
1979 this.wsConnectionRestarted
= true;
1980 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1982 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
1983 this.autoReconnectRetryCount
1984 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
1989 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
1990 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
1993 private initializeConnectorStatus(connectorId
: number): void {
1994 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
1995 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
1996 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
1997 this.getConnectorStatus(connectorId
).transactionStarted
= false;
1998 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
1999 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;