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 { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
43 import WebSocket
, { Data
, OPEN
, RawData
} from
'ws';
45 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
46 import { AutomaticTransactionGeneratorConfiguration
} from
'../types/AutomaticTransactionGenerator';
47 import BaseError from
'../exception/BaseError';
48 import { ChargePointErrorCode
} from
'../types/ocpp/ChargePointErrorCode';
49 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
50 import { ChargingStationCache
} from
'./ChargingStationCache';
51 import ChargingStationConfiguration from
'../types/ChargingStationConfiguration';
52 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
53 import ChargingStationInfo from
'../types/ChargingStationInfo';
54 import ChargingStationOcppConfiguration from
'../types/ChargingStationOcppConfiguration';
55 import { ChargingStationUtils
} from
'./ChargingStationUtils';
56 import { ChargingStationWorkerMessageEvents
} from
'../types/ChargingStationWorker';
57 import Configuration from
'../utils/Configuration';
58 import { ConnectorStatus
} from
'../types/ConnectorStatus';
59 import Constants from
'../utils/Constants';
60 import { ErrorType
} from
'../types/ocpp/ErrorType';
61 import { FileType
} from
'../types/FileType';
62 import FileUtils from
'../utils/FileUtils';
63 import { JsonType
} from
'../types/JsonType';
64 import { MessageType
} from
'../types/ocpp/MessageType';
65 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
66 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
67 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
68 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
69 import OCPPError from
'../exception/OCPPError';
70 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
71 import OCPPRequestService from
'./ocpp/OCPPRequestService';
72 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
73 import PerformanceStatistics from
'../performance/PerformanceStatistics';
74 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
75 import { URL
} from
'url';
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
=== 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 if (this.isWebSocketConnectionOpened()) {
558 this.wsConnection
.close();
560 if (this.getEnableStatistics()) {
561 this.performanceStatistics
.stop();
563 this.cache
.deleteChargingStationConfiguration(this.configurationFileHash
);
564 this.cache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
565 this.bootNotificationResponse
= null;
566 parentPort
.postMessage({
567 id
: ChargingStationWorkerMessageEvents
.STOPPED
,
568 data
: { id
: this.stationInfo
.chargingStationId
},
573 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
574 await this.stop(reason
);
575 await Utils
.sleep(this.stationInfo
.resetTime
);
580 public saveOcppConfiguration(): void {
581 if (this.getOcppPersistentConfiguration()) {
582 this.saveConfiguration();
586 public getChargingProfilePowerLimit(connectorId
: number): number | undefined {
587 let limit
: number, matchingChargingProfile
: ChargingProfile
;
588 let chargingProfiles
: ChargingProfile
[] = [];
589 // Get charging profiles for connector and sort by stack level
590 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
591 (a
, b
) => b
.stackLevel
- a
.stackLevel
593 // Get profiles on connector 0
594 if (this.getConnectorStatus(0).chargingProfiles
) {
595 chargingProfiles
.push(
596 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
599 if (!Utils
.isEmptyArray(chargingProfiles
)) {
600 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
604 if (!Utils
.isNullOrUndefined(result
)) {
605 limit
= result
.limit
;
606 matchingChargingProfile
= result
.matchingChargingProfile
;
607 switch (this.getCurrentOutType()) {
610 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
611 ChargingRateUnitType
.WATT
613 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
617 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
618 ChargingRateUnitType
.WATT
620 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
623 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
624 if (limit
> connectorMaximumPower
) {
626 `${this.logPrefix()} Charging profile id ${
627 matchingChargingProfile.chargingProfileId
628 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
629 this.getConnectorStatus(connectorId
).chargingProfiles
631 limit
= connectorMaximumPower
;
638 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
639 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
641 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
643 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
645 if (!Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
647 `${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`
649 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
651 let cpReplaced
= false;
652 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
653 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
654 (chargingProfile
: ChargingProfile
, index
: number) => {
656 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
657 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
658 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
660 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
666 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
669 public resetConnectorStatus(connectorId
: number): void {
670 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
671 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
672 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
673 this.getConnectorStatus(connectorId
).transactionStarted
= false;
674 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
675 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
676 delete this.getConnectorStatus(connectorId
).transactionId
;
677 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
678 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
679 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
680 this.stopMeterValues(connectorId
);
683 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
684 return ChargingStationConfigurationUtils
.getConfigurationKey(
686 StandardParametersKey
.SupportedFeatureProfiles
687 )?.value
.includes(featureProfile
);
690 public bufferMessage(message
: string): void {
691 this.messageBuffer
.add(message
);
694 private flushMessageBuffer() {
695 if (this.messageBuffer
.size
> 0) {
696 this.messageBuffer
.forEach((message
) => {
697 // TODO: evaluate the need to track performance
698 this.wsConnection
.send(message
);
699 this.messageBuffer
.delete(message
);
704 private getSupervisionUrlOcppConfiguration(): boolean {
705 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
708 private getSupervisionUrlOcppKey(): string {
709 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
712 private getTemplateFromFile(): ChargingStationTemplate
| null {
713 let template
: ChargingStationTemplate
= null;
715 if (this.cache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
716 template
= this.cache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
718 const measureId
= `${FileType.ChargingStationTemplate} read`;
719 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
720 template
= JSON
.parse(
721 fs
.readFileSync(this.templateFile
, 'utf8')
722 ) as ChargingStationTemplate
;
723 PerformanceStatistics
.endMeasure(measureId
, beginId
);
724 template
.templateHash
= crypto
725 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
726 .update(JSON
.stringify(template
))
728 this.cache
.setChargingStationTemplate(template
);
731 FileUtils
.handleFileException(
733 FileType
.ChargingStationTemplate
,
735 error
as NodeJS
.ErrnoException
741 private getStationInfoFromTemplate(): ChargingStationInfo
{
742 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
743 if (Utils
.isNullOrUndefined(stationTemplate
)) {
744 const errorMsg
= 'Failed to read charging station template file';
745 logger
.error(`${this.logPrefix()} ${errorMsg}`);
746 throw new BaseError(errorMsg
);
748 if (Utils
.isEmptyObject(stationTemplate
)) {
749 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
750 logger
.error(`${this.logPrefix()} ${errorMsg}`);
751 throw new BaseError(errorMsg
);
753 // Deprecation template keys section
754 ChargingStationUtils
.warnDeprecatedTemplateKey(
759 "Use 'supervisionUrls' instead"
761 ChargingStationUtils
.convertDeprecatedTemplateKey(
766 const stationInfo
: ChargingStationInfo
=
767 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
768 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
772 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
773 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
774 stationTemplate
.power
= stationTemplate
.power
as number[];
775 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
776 stationInfo
.maximumPower
=
777 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
778 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
779 : stationTemplate
.power
[powerArrayRandomIndex
];
781 stationTemplate
.power
= stationTemplate
.power
as number;
782 stationInfo
.maximumPower
=
783 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
784 ? stationTemplate
.power
* 1000
785 : stationTemplate
.power
;
787 stationInfo
.resetTime
= stationTemplate
.resetTime
788 ? stationTemplate
.resetTime
* 1000
789 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
790 const configuredMaxConnectors
= ChargingStationUtils
.getConfiguredNumberOfConnectors(
794 ChargingStationUtils
.checkConfiguredMaxConnectors(
795 configuredMaxConnectors
,
799 const templateMaxConnectors
=
800 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
801 ChargingStationUtils
.checkTemplateMaxConnectors(
802 templateMaxConnectors
,
807 configuredMaxConnectors
>
808 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
809 !stationTemplate
?.randomConnectors
812 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
814 }, forcing random connector configurations affectation`
816 stationInfo
.randomConnectors
= true;
818 // Build connectors if needed (FIXME: should be factored out)
819 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
820 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
821 ChargingStationUtils
.createStationInfoHash(stationInfo
);
825 private getStationInfoFromFile(): ChargingStationInfo
| null {
826 let stationInfo
: ChargingStationInfo
= null;
827 this.getStationInfoPersistentConfiguration() &&
828 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
829 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
833 private getStationInfo(): ChargingStationInfo
{
834 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
835 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
836 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
837 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
838 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
839 return this.stationInfo
;
841 return stationInfoFromFile
;
843 stationInfoFromFile
&&
844 ChargingStationUtils
.propagateSerialNumber(
845 this.getTemplateFromFile(),
847 stationInfoFromTemplate
849 return stationInfoFromTemplate
;
852 private saveStationInfo(): void {
853 if (this.getStationInfoPersistentConfiguration()) {
854 this.saveConfiguration();
858 private getOcppVersion(): OCPPVersion
{
859 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
862 private getOcppPersistentConfiguration(): boolean {
863 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
866 private getStationInfoPersistentConfiguration(): boolean {
867 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
870 private handleUnsupportedVersion(version
: OCPPVersion
) {
871 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
874 logger
.error(errMsg
);
875 throw new Error(errMsg
);
878 private initialize(): void {
879 this.hashId
= ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile());
880 logger
.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
881 this.configurationFile
= path
.join(
882 path
.resolve(__dirname
, '../'),
885 this.hashId
+ '.json'
887 this.stationInfo
= this.getStationInfo();
888 this.saveStationInfo();
889 // Avoid duplication of connectors related information in RAM
890 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
891 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
892 if (this.getEnableStatistics()) {
893 this.performanceStatistics
= PerformanceStatistics
.getInstance(
895 this.stationInfo
.chargingStationId
,
896 this.configuredSupervisionUrl
899 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
902 this.authorizedTags
= ChargingStationUtils
.getAuthorizedTags(
907 this.powerDivider
= this.getPowerDivider();
908 // OCPP configuration
909 this.ocppConfiguration
= this.getOcppConfiguration();
910 this.initializeOcppConfiguration();
911 switch (this.getOcppVersion()) {
912 case OCPPVersion
.VERSION_16
:
913 this.ocppIncomingRequestService
=
914 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
915 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
916 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
920 this.handleUnsupportedVersion(this.getOcppVersion());
923 if (this.stationInfo
?.autoRegister
) {
924 this.bootNotificationResponse
= {
925 currentTime
: new Date().toISOString(),
926 interval
: this.getHeartbeatInterval() / 1000,
927 status: RegistrationStatus
.ACCEPTED
,
932 private initializeOcppConfiguration(): void {
934 !ChargingStationConfigurationUtils
.getConfigurationKey(
936 StandardParametersKey
.HeartbeatInterval
939 ChargingStationConfigurationUtils
.addConfigurationKey(
941 StandardParametersKey
.HeartbeatInterval
,
946 !ChargingStationConfigurationUtils
.getConfigurationKey(
948 StandardParametersKey
.HeartBeatInterval
951 ChargingStationConfigurationUtils
.addConfigurationKey(
953 StandardParametersKey
.HeartBeatInterval
,
959 this.getSupervisionUrlOcppConfiguration() &&
960 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
962 ChargingStationConfigurationUtils
.addConfigurationKey(
964 this.getSupervisionUrlOcppKey(),
965 this.configuredSupervisionUrl
.href
,
969 !this.getSupervisionUrlOcppConfiguration() &&
970 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
972 ChargingStationConfigurationUtils
.deleteConfigurationKey(
974 this.getSupervisionUrlOcppKey(),
979 this.stationInfo
.amperageLimitationOcppKey
&&
980 !ChargingStationConfigurationUtils
.getConfigurationKey(
982 this.stationInfo
.amperageLimitationOcppKey
985 ChargingStationConfigurationUtils
.addConfigurationKey(
987 this.stationInfo
.amperageLimitationOcppKey
,
989 this.stationInfo
.maximumAmperage
*
990 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
995 !ChargingStationConfigurationUtils
.getConfigurationKey(
997 StandardParametersKey
.SupportedFeatureProfiles
1000 ChargingStationConfigurationUtils
.addConfigurationKey(
1002 StandardParametersKey
.SupportedFeatureProfiles
,
1003 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1006 ChargingStationConfigurationUtils
.addConfigurationKey(
1008 StandardParametersKey
.NumberOfConnectors
,
1009 this.getNumberOfConnectors().toString(),
1014 !ChargingStationConfigurationUtils
.getConfigurationKey(
1016 StandardParametersKey
.MeterValuesSampledData
1019 ChargingStationConfigurationUtils
.addConfigurationKey(
1021 StandardParametersKey
.MeterValuesSampledData
,
1022 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1026 !ChargingStationConfigurationUtils
.getConfigurationKey(
1028 StandardParametersKey
.ConnectorPhaseRotation
1031 const connectorPhaseRotation
= [];
1032 for (const connectorId
of this.connectors
.keys()) {
1034 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1035 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1036 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1037 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1039 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1040 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1041 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1042 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1045 ChargingStationConfigurationUtils
.addConfigurationKey(
1047 StandardParametersKey
.ConnectorPhaseRotation
,
1048 connectorPhaseRotation
.toString()
1052 !ChargingStationConfigurationUtils
.getConfigurationKey(
1054 StandardParametersKey
.AuthorizeRemoteTxRequests
1057 ChargingStationConfigurationUtils
.addConfigurationKey(
1059 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1064 !ChargingStationConfigurationUtils
.getConfigurationKey(
1066 StandardParametersKey
.LocalAuthListEnabled
1068 ChargingStationConfigurationUtils
.getConfigurationKey(
1070 StandardParametersKey
.SupportedFeatureProfiles
1071 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1073 ChargingStationConfigurationUtils
.addConfigurationKey(
1075 StandardParametersKey
.LocalAuthListEnabled
,
1080 !ChargingStationConfigurationUtils
.getConfigurationKey(
1082 StandardParametersKey
.ConnectionTimeOut
1085 ChargingStationConfigurationUtils
.addConfigurationKey(
1087 StandardParametersKey
.ConnectionTimeOut
,
1088 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1091 this.saveOcppConfiguration();
1094 private initializeConnectors(
1095 stationInfo
: ChargingStationInfo
,
1096 configuredMaxConnectors
: number,
1097 templateMaxConnectors
: number
1099 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1100 const logMsg
= `${this.logPrefix()} No already defined connectors and charging station information from template ${
1102 } with no connectors configuration defined`;
1103 logger
.error(logMsg
);
1104 throw new BaseError(logMsg
);
1106 if (!stationInfo
?.Connectors
[0]) {
1108 `${this.logPrefix()} Charging station information from template ${
1110 } with no connector Id 0 configuration`
1113 if (stationInfo
?.Connectors
) {
1114 const connectorsConfigHash
= crypto
1115 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1116 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1118 const connectorsConfigChanged
=
1119 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1120 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1121 connectorsConfigChanged
&& this.connectors
.clear();
1122 this.connectorsConfigurationHash
= connectorsConfigHash
;
1123 // Add connector Id 0
1124 let lastConnector
= '0';
1125 for (lastConnector
in stationInfo
?.Connectors
) {
1126 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1128 lastConnectorId
=== 0 &&
1129 this.getUseConnectorId0(stationInfo
) &&
1130 stationInfo
?.Connectors
[lastConnector
]
1132 this.connectors
.set(
1134 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1136 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1137 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1138 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1142 // Generate all connectors
1143 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1144 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1145 const randConnectorId
= stationInfo
?.randomConnectors
1146 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1148 this.connectors
.set(
1150 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1152 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1153 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1154 this.getConnectorStatus(index
).chargingProfiles
= [];
1161 `${this.logPrefix()} Charging station information from template ${
1163 } with no connectors configuration defined, using already defined connectors`
1166 // Initialize transaction attributes on connectors
1167 for (const connectorId
of this.connectors
.keys()) {
1168 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1169 this.initializeConnectorStatus(connectorId
);
1174 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1175 let configuration
: ChargingStationConfiguration
= null;
1176 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1178 if (this.cache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1179 configuration
= this.cache
.getChargingStationConfiguration(this.configurationFileHash
);
1181 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1182 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1183 configuration
= JSON
.parse(
1184 fs
.readFileSync(this.configurationFile
, 'utf8')
1185 ) as ChargingStationConfiguration
;
1186 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1187 this.configurationFileHash
= configuration
.configurationHash
;
1188 this.cache
.setChargingStationConfiguration(configuration
);
1191 FileUtils
.handleFileException(
1193 FileType
.ChargingStationConfiguration
,
1194 this.configurationFile
,
1195 error
as NodeJS
.ErrnoException
1199 return configuration
;
1202 private saveConfiguration(): void {
1203 if (this.configurationFile
) {
1205 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1206 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1208 const configurationData
: ChargingStationConfiguration
=
1209 this.getConfigurationFromFile() ?? {};
1210 this.ocppConfiguration
?.configurationKey
&&
1211 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1212 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1213 delete configurationData
.configurationHash
;
1214 const configurationHash
= crypto
1215 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1216 .update(JSON
.stringify(configurationData
))
1218 if (this.configurationFileHash
!== configurationHash
) {
1219 configurationData
.configurationHash
= configurationHash
;
1220 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1221 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1222 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1223 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1224 fs
.closeSync(fileDescriptor
);
1225 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1226 this.cache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1227 this.configurationFileHash
= configurationHash
;
1228 this.cache
.setChargingStationConfiguration(configurationData
);
1231 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1232 this.configurationFile
1237 FileUtils
.handleFileException(
1239 FileType
.ChargingStationConfiguration
,
1240 this.configurationFile
,
1241 error
as NodeJS
.ErrnoException
1246 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1251 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1252 return this.getTemplateFromFile()?.Configuration
?? null;
1255 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1256 let configuration
: ChargingStationConfiguration
= null;
1257 if (this.getOcppPersistentConfiguration()) {
1258 const configurationFromFile
= this.getConfigurationFromFile();
1259 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1261 configuration
&& delete configuration
.stationInfo
;
1262 return configuration
;
1265 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1266 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1267 if (!ocppConfiguration
) {
1268 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1270 return ocppConfiguration
;
1273 private async onOpen(): Promise
<void> {
1274 if (this.isWebSocketConnectionOpened()) {
1276 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1278 if (!this.isRegistered()) {
1279 // Send BootNotification
1280 let registrationRetryCount
= 0;
1282 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1283 BootNotificationRequest
,
1284 BootNotificationResponse
1287 RequestCommand
.BOOT_NOTIFICATION
,
1289 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1290 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1291 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1292 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1293 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1294 iccid
: this.bootNotificationRequest
.iccid
,
1295 imsi
: this.bootNotificationRequest
.imsi
,
1296 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1297 meterType
: this.bootNotificationRequest
.meterType
,
1299 { skipBufferingOnError
: true }
1301 if (!this.isRegistered()) {
1302 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1304 this.bootNotificationResponse
?.interval
1305 ? this.bootNotificationResponse
.interval
* 1000
1306 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1310 !this.isRegistered() &&
1311 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1312 this.getRegistrationMaxRetries() === -1)
1315 if (this.isRegistered()) {
1316 if (this.isInAcceptedState()) {
1317 await this.startMessageSequence();
1318 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1322 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1325 this.stopped
&& (this.stopped
= false);
1326 this.autoReconnectRetryCount
= 0;
1327 this.wsConnectionRestarted
= false;
1330 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1335 private async onClose(code
: number, reason
: string): Promise
<void> {
1338 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1339 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1341 `${this.logPrefix()} WebSocket normally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1343 )}' and reason '${reason}'`
1345 this.autoReconnectRetryCount
= 0;
1350 `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1352 )}' and reason '${reason}'`
1354 await this.reconnect(code
);
1359 private async onMessage(data
: Data
): Promise
<void> {
1360 let messageType
: number;
1361 let messageId
: string;
1362 let commandName
: IncomingRequestCommand
;
1363 let commandPayload
: JsonType
;
1364 let errorType
: ErrorType
;
1365 let errorMessage
: string;
1366 let errorDetails
: JsonType
;
1367 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1368 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1369 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1370 let requestPayload
: JsonType
;
1371 let cachedRequest
: CachedRequest
;
1374 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1375 if (Utils
.isIterable(request
)) {
1376 [messageType
, messageId
] = request
;
1377 // Check the type of message
1378 switch (messageType
) {
1380 case MessageType
.CALL_MESSAGE
:
1381 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1382 if (this.getEnableStatistics()) {
1383 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1386 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1390 // Process the message
1391 await this.ocppIncomingRequestService
.incomingRequestHandler(
1399 case MessageType
.CALL_RESULT_MESSAGE
:
1400 [, , commandPayload
] = request
as Response
;
1401 if (!this.requests
.has(messageId
)) {
1403 throw new OCPPError(
1404 ErrorType
.INTERNAL_ERROR
,
1405 `Response for unknown message id ${messageId}`,
1411 cachedRequest
= this.requests
.get(messageId
);
1412 if (Utils
.isIterable(cachedRequest
)) {
1413 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1415 throw new OCPPError(
1416 ErrorType
.PROTOCOL_ERROR
,
1417 `Cached request for message id ${messageId} response is not iterable`,
1419 cachedRequest
as unknown
as JsonType
1423 `${this.logPrefix()} << Command '${
1424 requestCommandName ?? ''
1425 }' received response payload: ${JSON.stringify(request)}`
1427 responseCallback(commandPayload
, requestPayload
);
1430 case MessageType
.CALL_ERROR_MESSAGE
:
1431 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1432 if (!this.requests
.has(messageId
)) {
1434 throw new OCPPError(
1435 ErrorType
.INTERNAL_ERROR
,
1436 `Error response for unknown message id ${messageId}`,
1438 { errorType
, errorMessage
, errorDetails
}
1441 cachedRequest
= this.requests
.get(messageId
);
1442 if (Utils
.isIterable(cachedRequest
)) {
1443 [, errorCallback
, requestCommandName
] = cachedRequest
;
1445 throw new OCPPError(
1446 ErrorType
.PROTOCOL_ERROR
,
1447 `Cached request for message id ${messageId} error response is not iterable`,
1449 cachedRequest
as unknown
as JsonType
1453 `${this.logPrefix()} << Command '${
1454 requestCommandName ?? ''
1455 }' received error payload: ${JSON.stringify(request)}`
1457 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1461 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1462 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
1463 logger
.error(errMsg
);
1464 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1467 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not iterable', null, {
1474 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1477 this.requests
.get(messageId
),
1481 messageType
=== MessageType
.CALL_MESSAGE
&&
1482 (await this.ocppRequestService
.sendError(
1486 commandName
?? requestCommandName
?? null
1491 private onPing(): void {
1492 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1495 private onPong(): void {
1496 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1499 private onError(error
: WSError
): void {
1500 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
1503 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean | undefined {
1504 const localStationInfo
= stationInfo
?? this.stationInfo
;
1505 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1506 ? localStationInfo
.useConnectorId0
1510 private getNumberOfRunningTransactions(): number {
1512 for (const connectorId
of this.connectors
.keys()) {
1513 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1521 private getConnectionTimeout(): number | undefined {
1523 ChargingStationConfigurationUtils
.getConfigurationKey(
1525 StandardParametersKey
.ConnectionTimeOut
1530 ChargingStationConfigurationUtils
.getConfigurationKey(
1532 StandardParametersKey
.ConnectionTimeOut
1534 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1537 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1540 // -1 for unlimited, 0 for disabling
1541 private getAutoReconnectMaxRetries(): number | undefined {
1542 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1543 return this.stationInfo
.autoReconnectMaxRetries
;
1545 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1546 return Configuration
.getAutoReconnectMaxRetries();
1552 private getRegistrationMaxRetries(): number | undefined {
1553 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1554 return this.stationInfo
.registrationMaxRetries
;
1559 private getPowerDivider(): number {
1560 let powerDivider
= this.getNumberOfConnectors();
1561 if (this.stationInfo
?.powerSharedByConnectors
) {
1562 powerDivider
= this.getNumberOfRunningTransactions();
1564 return powerDivider
;
1567 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1568 const localStationInfo
= stationInfo
?? this.stationInfo
;
1569 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1572 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1573 const maximumPower
= this.getMaximumPower(stationInfo
);
1574 switch (this.getCurrentOutType(stationInfo
)) {
1575 case CurrentType
.AC
:
1576 return ACElectricUtils
.amperagePerPhaseFromPower(
1577 this.getNumberOfPhases(stationInfo
),
1578 maximumPower
/ this.getNumberOfConnectors(),
1579 this.getVoltageOut(stationInfo
)
1581 case CurrentType
.DC
:
1582 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1586 private getAmperageLimitation(): number | undefined {
1588 this.stationInfo
.amperageLimitationOcppKey
&&
1589 ChargingStationConfigurationUtils
.getConfigurationKey(
1591 this.stationInfo
.amperageLimitationOcppKey
1596 ChargingStationConfigurationUtils
.getConfigurationKey(
1598 this.stationInfo
.amperageLimitationOcppKey
1600 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1605 private async startMessageSequence(): Promise
<void> {
1606 if (this.stationInfo
?.autoRegister
) {
1607 await this.ocppRequestService
.requestHandler
<
1608 BootNotificationRequest
,
1609 BootNotificationResponse
1612 RequestCommand
.BOOT_NOTIFICATION
,
1614 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1615 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1616 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1617 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1618 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1619 iccid
: this.bootNotificationRequest
.iccid
,
1620 imsi
: this.bootNotificationRequest
.imsi
,
1621 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1622 meterType
: this.bootNotificationRequest
.meterType
,
1624 { skipBufferingOnError
: true }
1627 // Start WebSocket ping
1628 this.startWebSocketPing();
1630 this.startHeartbeat();
1631 // Initialize connectors status
1632 for (const connectorId
of this.connectors
.keys()) {
1633 if (connectorId
=== 0) {
1637 !this.getConnectorStatus(connectorId
)?.status &&
1638 this.getConnectorStatus(connectorId
)?.bootStatus
1640 // Send status in template at startup
1641 await this.ocppRequestService
.requestHandler
<
1642 StatusNotificationRequest
,
1643 StatusNotificationResponse
1644 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1646 status: this.getConnectorStatus(connectorId
).bootStatus
,
1647 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1649 this.getConnectorStatus(connectorId
).status =
1650 this.getConnectorStatus(connectorId
).bootStatus
;
1653 this.getConnectorStatus(connectorId
)?.status &&
1654 this.getConnectorStatus(connectorId
)?.bootStatus
1656 // Send status in template after reset
1657 await this.ocppRequestService
.requestHandler
<
1658 StatusNotificationRequest
,
1659 StatusNotificationResponse
1660 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1662 status: this.getConnectorStatus(connectorId
).bootStatus
,
1663 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1665 this.getConnectorStatus(connectorId
).status =
1666 this.getConnectorStatus(connectorId
).bootStatus
;
1667 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1668 // Send previous status at template reload
1669 await this.ocppRequestService
.requestHandler
<
1670 StatusNotificationRequest
,
1671 StatusNotificationResponse
1672 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1674 status: this.getConnectorStatus(connectorId
).status,
1675 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1678 // Send default status
1679 await this.ocppRequestService
.requestHandler
<
1680 StatusNotificationRequest
,
1681 StatusNotificationResponse
1682 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1684 status: ChargePointStatus
.AVAILABLE
,
1685 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1687 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1691 this.startAutomaticTransactionGenerator();
1694 private startAutomaticTransactionGenerator() {
1695 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
) {
1696 if (!this.automaticTransactionGenerator
) {
1697 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
1698 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
1702 if (!this.automaticTransactionGenerator
.started
) {
1703 this.automaticTransactionGenerator
.start();
1708 private stopAutomaticTransactionGenerator(): void {
1709 if (this.automaticTransactionGenerator
?.started
) {
1710 this.automaticTransactionGenerator
.stop();
1711 this.automaticTransactionGenerator
= null;
1715 private async stopMessageSequence(
1716 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1718 // Stop WebSocket ping
1719 this.stopWebSocketPing();
1721 this.stopHeartbeat();
1722 // Stop ongoing transactions
1723 if (this.automaticTransactionGenerator
?.configuration
?.enable
) {
1724 this.stopAutomaticTransactionGenerator();
1726 for (const connectorId
of this.connectors
.keys()) {
1727 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1728 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1730 this.getBeginEndMeterValues() &&
1731 this.getOcppStrictCompliance() &&
1732 !this.getOutOfOrderEndMeterValues()
1734 // FIXME: Implement OCPP version agnostic helpers
1735 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1738 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1740 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
1742 RequestCommand
.METER_VALUES
,
1746 meterValue
: transactionEndMeterValue
,
1750 await this.ocppRequestService
.requestHandler
<
1751 StopTransactionRequest
,
1752 StopTransactionResponse
1753 >(this, RequestCommand
.STOP_TRANSACTION
, {
1755 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1756 idTag
: this.getTransactionIdTag(transactionId
),
1764 private startWebSocketPing(): void {
1765 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1767 StandardParametersKey
.WebSocketPingInterval
1769 ? Utils
.convertToInt(
1770 ChargingStationConfigurationUtils
.getConfigurationKey(
1772 StandardParametersKey
.WebSocketPingInterval
1776 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1777 this.webSocketPingSetInterval
= setInterval(() => {
1778 if (this.isWebSocketConnectionOpened()) {
1779 this.wsConnection
.ping((): void => {
1780 /* This is intentional */
1783 }, webSocketPingInterval
* 1000);
1786 ' WebSocket ping started every ' +
1787 Utils
.formatDurationSeconds(webSocketPingInterval
)
1789 } else if (this.webSocketPingSetInterval
) {
1792 ' WebSocket ping every ' +
1793 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1798 `${this.logPrefix()} WebSocket ping interval set to ${
1799 webSocketPingInterval
1800 ? Utils.formatDurationSeconds(webSocketPingInterval)
1801 : webSocketPingInterval
1802 }, not starting the WebSocket ping`
1807 private stopWebSocketPing(): void {
1808 if (this.webSocketPingSetInterval
) {
1809 clearInterval(this.webSocketPingSetInterval
);
1813 private getConfiguredSupervisionUrl(): URL
{
1814 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1815 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1817 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1819 switch (Configuration
.getSupervisionUrlDistribution()) {
1820 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1821 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1823 case SupervisionUrlDistribution
.RANDOM
:
1825 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1827 case SupervisionUrlDistribution
.SEQUENTIAL
:
1828 if (this.index
<= supervisionUrls
.length
) {
1829 urlIndex
= this.index
- 1;
1832 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1838 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1839 SupervisionUrlDistribution.ROUND_ROBIN
1842 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1845 return new URL(supervisionUrls
[urlIndex
]);
1847 return new URL(supervisionUrls
as string);
1850 private getHeartbeatInterval(): number | undefined {
1851 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1853 StandardParametersKey
.HeartbeatInterval
1855 if (HeartbeatInterval
) {
1856 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1858 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1860 StandardParametersKey
.HeartBeatInterval
1862 if (HeartBeatInterval
) {
1863 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1865 !this.stationInfo
?.autoRegister
&&
1867 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1868 Constants.DEFAULT_HEARTBEAT_INTERVAL
1871 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1874 private stopHeartbeat(): void {
1875 if (this.heartbeatSetInterval
) {
1876 clearInterval(this.heartbeatSetInterval
);
1880 private openWSConnection(
1881 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
1882 forceCloseOpened
= false
1884 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
1886 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
1887 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
1889 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
1891 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
1892 this.wsConnection
.close();
1894 let protocol
: string;
1895 switch (this.getOcppVersion()) {
1896 case OCPPVersion
.VERSION_16
:
1897 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
1900 this.handleUnsupportedVersion(this.getOcppVersion());
1903 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
1905 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString()
1909 private stopMeterValues(connectorId
: number) {
1910 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1911 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1915 private getReconnectExponentialDelay(): boolean | undefined {
1916 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1917 ? this.stationInfo
.reconnectExponentialDelay
1921 private async reconnect(code
: number): Promise
<void> {
1922 // Stop WebSocket ping
1923 this.stopWebSocketPing();
1925 this.stopHeartbeat();
1926 // Stop the ATG if needed
1927 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
) {
1928 this.stopAutomaticTransactionGenerator();
1931 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1932 this.getAutoReconnectMaxRetries() === -1
1934 this.autoReconnectRetryCount
++;
1935 const reconnectDelay
= this.getReconnectExponentialDelay()
1936 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1937 : this.getConnectionTimeout() * 1000;
1938 const reconnectTimeout
= reconnectDelay
- 100 > 0 && reconnectDelay
;
1940 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1943 )}ms, timeout ${reconnectTimeout}ms`
1945 await Utils
.sleep(reconnectDelay
);
1948 ' WebSocket: reconnecting try #' +
1949 this.autoReconnectRetryCount
.toString()
1951 this.openWSConnection(
1952 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
1955 this.wsConnectionRestarted
= true;
1956 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1958 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
1959 this.autoReconnectRetryCount
1960 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
1965 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
1966 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
1969 private initializeConnectorStatus(connectorId
: number): void {
1970 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
1971 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
1972 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
1973 this.getConnectorStatus(connectorId
).transactionStarted
= false;
1974 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
1975 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;