1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import crypto from
'crypto';
5 import path from
'path';
6 import { URL
} from
'url';
7 import { parentPort
} from
'worker_threads';
9 import WebSocket
, { Data
, RawData
} from
'ws';
11 import BaseError from
'../exception/BaseError';
12 import OCPPError from
'../exception/OCPPError';
13 import PerformanceStatistics from
'../performance/PerformanceStatistics';
14 import type { AutomaticTransactionGeneratorConfiguration
} from
'../types/AutomaticTransactionGenerator';
15 import type ChargingStationConfiguration from
'../types/ChargingStationConfiguration';
16 import type ChargingStationInfo from
'../types/ChargingStationInfo';
17 import type ChargingStationOcppConfiguration from
'../types/ChargingStationOcppConfiguration';
18 import ChargingStationTemplate
, {
22 } from
'../types/ChargingStationTemplate';
23 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
24 import type { ConnectorStatus
} from
'../types/ConnectorStatus';
25 import { FileType
} from
'../types/FileType';
26 import type { JsonType
} from
'../types/JsonType';
27 import { ChargePointErrorCode
} from
'../types/ocpp/ChargePointErrorCode';
28 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
29 import { ChargingProfile
, ChargingRateUnitType
} from
'../types/ocpp/ChargingProfile';
31 ConnectorPhaseRotation
,
32 StandardParametersKey
,
33 SupportedFeatureProfiles
,
34 VendorDefaultParametersKey
,
35 } from
'../types/ocpp/Configuration';
36 import { ErrorType
} from
'../types/ocpp/ErrorType';
37 import { MessageType
} from
'../types/ocpp/MessageType';
38 import { MeterValue
, MeterValueMeasurand
} from
'../types/ocpp/MeterValues';
39 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
42 BootNotificationRequest
,
46 IncomingRequestCommand
,
49 StatusNotificationRequest
,
50 } from
'../types/ocpp/Requests';
52 BootNotificationResponse
,
58 StatusNotificationResponse
,
59 } from
'../types/ocpp/Responses';
61 StopTransactionReason
,
62 StopTransactionRequest
,
63 StopTransactionResponse
,
64 } from
'../types/ocpp/Transaction';
65 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
66 import Configuration from
'../utils/Configuration';
67 import Constants from
'../utils/Constants';
68 import { ACElectricUtils
, DCElectricUtils
} from
'../utils/ElectricUtils';
69 import FileUtils from
'../utils/FileUtils';
70 import logger from
'../utils/Logger';
71 import Utils from
'../utils/Utils';
72 import AuthorizedTagsCache from
'./AuthorizedTagsCache';
73 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
74 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
75 import { ChargingStationUtils
} from
'./ChargingStationUtils';
76 import ChargingStationWorkerBroadcastChannel from
'./ChargingStationWorkerBroadcastChannel';
77 import { MessageChannelUtils
} from
'./MessageChannelUtils';
78 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
79 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
80 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
81 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
82 import type OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
83 import type OCPPRequestService from
'./ocpp/OCPPRequestService';
84 import SharedLRUCache from
'./SharedLRUCache';
86 export default class ChargingStation
{
87 public hashId
!: string;
88 public readonly templateFile
: string;
89 public authorizedTagsCache
: AuthorizedTagsCache
;
90 public stationInfo
!: ChargingStationInfo
;
91 public stopped
: boolean;
92 public readonly connectors
: Map
<number, ConnectorStatus
>;
93 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
94 public wsConnection
!: WebSocket
;
95 public readonly requests
: Map
<string, CachedRequest
>;
96 public performanceStatistics
!: PerformanceStatistics
;
97 public heartbeatSetInterval
!: NodeJS
.Timeout
;
98 public ocppRequestService
!: OCPPRequestService
;
99 public bootNotificationRequest
!: BootNotificationRequest
;
100 public bootNotificationResponse
!: BootNotificationResponse
| null;
101 public powerDivider
!: number;
102 private readonly index
: number;
103 private configurationFile
!: string;
104 private configurationFileHash
!: string;
105 private connectorsConfigurationHash
!: string;
106 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
107 private readonly messageBuffer
: Set
<string>;
108 private configuredSupervisionUrl
!: URL
;
109 private wsConnectionRestarted
: boolean;
110 private autoReconnectRetryCount
: number;
111 private templateFileWatcher
!: fs
.FSWatcher
;
112 private readonly sharedLRUCache
: SharedLRUCache
;
113 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
114 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
115 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
117 constructor(index
: number, templateFile
: string) {
119 this.templateFile
= templateFile
;
120 this.stopped
= false;
121 this.wsConnectionRestarted
= false;
122 this.autoReconnectRetryCount
= 0;
123 this.sharedLRUCache
= SharedLRUCache
.getInstance();
124 this.authorizedTagsCache
= AuthorizedTagsCache
.getInstance();
125 this.connectors
= new Map
<number, ConnectorStatus
>();
126 this.requests
= new Map
<string, CachedRequest
>();
127 this.messageBuffer
= new Set
<string>();
128 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
133 private get
wsConnectionUrl(): URL
{
135 (this.getSupervisionUrlOcppConfiguration()
136 ? ChargingStationConfigurationUtils
.getConfigurationKey(
138 this.getSupervisionUrlOcppKey()
140 : this.configuredSupervisionUrl
.href
) +
142 this.stationInfo
.chargingStationId
146 public logPrefix(): string {
147 return Utils
.logPrefix(
149 this?.stationInfo?.chargingStationId ??
150 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
155 public getRandomIdTag(): string {
156 const authorizationFile
= ChargingStationUtils
.getAuthorizationFile(this.stationInfo
);
157 const index
= Math.floor(
158 Utils
.secureRandom() * this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
).length
160 return this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
)[index
];
163 public hasAuthorizedTags(): boolean {
164 return !Utils
.isEmptyArray(
165 this.authorizedTagsCache
.getAuthorizedTags(
166 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
)
171 public getEnableStatistics(): boolean | undefined {
172 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
173 ? this.stationInfo
.enableStatistics
177 public getMustAuthorizeAtRemoteStart(): boolean | undefined {
178 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
181 public getPayloadSchemaValidation(): boolean | undefined {
182 return this.stationInfo
.payloadSchemaValidation
?? true;
185 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
186 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
187 switch (this.getCurrentOutType(stationInfo
)) {
189 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
190 ? localStationInfo
.numberOfPhases
197 public isWebSocketConnectionOpened(): boolean {
198 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
201 public getRegistrationStatus(): RegistrationStatus
{
202 return this?.bootNotificationResponse
?.status;
205 public isInUnknownState(): boolean {
206 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
209 public isInPendingState(): boolean {
210 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
213 public isInAcceptedState(): boolean {
214 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
217 public isInRejectedState(): boolean {
218 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
221 public isRegistered(): boolean {
222 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
225 public isChargingStationAvailable(): boolean {
226 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
229 public isConnectorAvailable(id
: number): boolean {
230 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
233 public getNumberOfConnectors(): number {
234 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
237 public getConnectorStatus(id
: number): ConnectorStatus
{
238 return this.connectors
.get(id
);
241 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
242 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
;
245 public getOcppStrictCompliance(): boolean {
246 return this.stationInfo
?.ocppStrictCompliance
?? false;
249 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
250 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
251 this.getCurrentOutType(stationInfo
),
255 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
256 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
257 ? localStationInfo
.voltageOut
261 public getConnectorMaximumAvailablePower(connectorId
: number): number {
262 let connectorAmperageLimitationPowerLimit
: number;
264 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
265 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
267 connectorAmperageLimitationPowerLimit
=
268 (this.getCurrentOutType() === CurrentType
.AC
269 ? ACElectricUtils
.powerTotal(
270 this.getNumberOfPhases(),
271 this.getVoltageOut(),
272 this.getAmperageLimitation() * this.getNumberOfConnectors()
274 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
277 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
278 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
280 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
281 isNaN(connectorAmperageLimitationPowerLimit
)
283 : connectorAmperageLimitationPowerLimit
,
284 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
288 public getTransactionIdTag(transactionId
: number): string | undefined {
289 for (const connectorId
of this.connectors
.keys()) {
290 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
291 return this.getConnectorStatus(connectorId
).transactionIdTag
;
296 public getOutOfOrderEndMeterValues(): boolean {
297 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
300 public getBeginEndMeterValues(): boolean {
301 return this.stationInfo
?.beginEndMeterValues
?? false;
304 public getMeteringPerTransaction(): boolean {
305 return this.stationInfo
?.meteringPerTransaction
?? true;
308 public getTransactionDataMeterValues(): boolean {
309 return this.stationInfo
?.transactionDataMeterValues
?? false;
312 public getMainVoltageMeterValues(): boolean {
313 return this.stationInfo
?.mainVoltageMeterValues
?? true;
316 public getPhaseLineToLineVoltageMeterValues(): boolean {
317 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
320 public getCustomValueLimitationMeterValues(): boolean {
321 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
324 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
325 for (const connectorId
of this.connectors
.keys()) {
328 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
335 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number {
336 const transactionConnectorStatus
= this.getConnectorStatus(
337 this.getConnectorIdByTransactionId(transactionId
)
339 if (this.getMeteringPerTransaction()) {
340 return transactionConnectorStatus
?.transactionEnergyActiveImportRegisterValue
?? 0;
342 return transactionConnectorStatus
?.energyActiveImportRegisterValue
?? 0;
345 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number {
346 const connectorStatus
= this.getConnectorStatus(connectorId
);
347 if (this.getMeteringPerTransaction()) {
348 return connectorStatus
?.transactionEnergyActiveImportRegisterValue
?? 0;
350 return connectorStatus
?.energyActiveImportRegisterValue
?? 0;
353 public getAuthorizeRemoteTxRequests(): boolean {
354 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
356 StandardParametersKey
.AuthorizeRemoteTxRequests
358 return authorizeRemoteTxRequests
359 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
363 public getLocalAuthListEnabled(): boolean {
364 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
366 StandardParametersKey
.LocalAuthListEnabled
368 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
371 public startHeartbeat(): void {
373 this.getHeartbeatInterval() &&
374 this.getHeartbeatInterval() > 0 &&
375 !this.heartbeatSetInterval
377 // eslint-disable-next-line @typescript-eslint/no-misused-promises
378 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
379 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
381 RequestCommand
.HEARTBEAT
383 }, this.getHeartbeatInterval());
386 ' Heartbeat started every ' +
387 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
389 } else if (this.heartbeatSetInterval
) {
392 ' Heartbeat already started every ' +
393 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
397 `${this.logPrefix()} Heartbeat interval set to ${
398 this.getHeartbeatInterval()
399 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
400 : this.getHeartbeatInterval()
401 }, not starting the heartbeat`
406 public restartHeartbeat(): void {
408 this.stopHeartbeat();
410 this.startHeartbeat();
413 public restartWebSocketPing(): void {
414 // Stop WebSocket ping
415 this.stopWebSocketPing();
416 // Start WebSocket ping
417 this.startWebSocketPing();
420 public startMeterValues(connectorId
: number, interval
: number): void {
421 if (connectorId
=== 0) {
423 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
427 if (!this.getConnectorStatus(connectorId
)) {
429 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
433 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
435 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
439 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
440 !this.getConnectorStatus(connectorId
)?.transactionId
443 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
448 // eslint-disable-next-line @typescript-eslint/no-misused-promises
449 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
450 // eslint-disable-next-line @typescript-eslint/no-misused-promises
451 async (): Promise
<void> => {
452 // FIXME: Implement OCPP version agnostic helpers
453 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
456 this.getConnectorStatus(connectorId
).transactionId
,
459 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
461 RequestCommand
.METER_VALUES
,
464 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
465 meterValue
: [meterValue
],
473 `${this.logPrefix()} Charging station ${
474 StandardParametersKey.MeterValueSampleInterval
475 } configuration set to ${
476 interval ? Utils.formatDurationMilliSeconds(interval) : interval
477 }, not sending MeterValues`
482 public start(): void {
483 if (this.getEnableStatistics()) {
484 this.performanceStatistics
.start();
486 this.openWSConnection();
487 // Monitor charging station template file
488 this.templateFileWatcher
= FileUtils
.watchJsonFile(
490 FileType
.ChargingStationTemplate
,
493 (event
, filename
): void => {
494 if (filename
&& event
=== 'change') {
497 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
499 } file have changed, reload`
501 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
505 this.stopAutomaticTransactionGenerator();
506 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
) {
507 this.startAutomaticTransactionGenerator();
509 if (this.getEnableStatistics()) {
510 this.performanceStatistics
.restart();
512 this.performanceStatistics
.stop();
514 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
517 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
524 parentPort
.postMessage(MessageChannelUtils
.buildStartedMessage(this));
527 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
528 // Stop message sequence
529 await this.stopMessageSequence(reason
);
530 for (const connectorId
of this.connectors
.keys()) {
531 if (connectorId
> 0) {
532 await this.ocppRequestService
.requestHandler
<
533 StatusNotificationRequest
,
534 StatusNotificationResponse
535 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
537 status: ChargePointStatus
.UNAVAILABLE
,
538 errorCode
: ChargePointErrorCode
.NO_ERROR
,
540 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
543 this.closeWSConnection();
544 if (this.getEnableStatistics()) {
545 this.performanceStatistics
.stop();
547 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
548 this.templateFileWatcher
.close();
549 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
550 this.bootNotificationResponse
= null;
552 parentPort
.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
555 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
556 await this.stop(reason
);
557 await Utils
.sleep(this.stationInfo
.resetTime
);
562 public saveOcppConfiguration(): void {
563 if (this.getOcppPersistentConfiguration()) {
564 this.saveConfiguration();
568 public getChargingProfilePowerLimit(connectorId
: number): number | undefined {
569 let limit
: number, matchingChargingProfile
: ChargingProfile
;
570 let chargingProfiles
: ChargingProfile
[] = [];
571 // Get charging profiles for connector and sort by stack level
572 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
573 (a
, b
) => b
.stackLevel
- a
.stackLevel
575 // Get profiles on connector 0
576 if (this.getConnectorStatus(0).chargingProfiles
) {
577 chargingProfiles
.push(
578 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
581 if (!Utils
.isEmptyArray(chargingProfiles
)) {
582 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
586 if (!Utils
.isNullOrUndefined(result
)) {
587 limit
= result
.limit
;
588 matchingChargingProfile
= result
.matchingChargingProfile
;
589 switch (this.getCurrentOutType()) {
592 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
593 ChargingRateUnitType
.WATT
595 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
599 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
600 ChargingRateUnitType
.WATT
602 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
605 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
606 if (limit
> connectorMaximumPower
) {
608 `${this.logPrefix()} Charging profile id ${
609 matchingChargingProfile.chargingProfileId
610 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
611 this.getConnectorStatus(connectorId
).chargingProfiles
613 limit
= connectorMaximumPower
;
620 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
621 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
623 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
625 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
627 if (Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
) === false) {
629 `${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`
631 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
633 let cpReplaced
= false;
634 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
635 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
636 (chargingProfile
: ChargingProfile
, index
: number) => {
638 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
639 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
640 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
642 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
648 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
651 public resetConnectorStatus(connectorId
: number): void {
652 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
653 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
654 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
655 this.getConnectorStatus(connectorId
).transactionStarted
= false;
656 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
657 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
658 delete this.getConnectorStatus(connectorId
).transactionId
;
659 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
660 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
661 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
662 this.stopMeterValues(connectorId
);
665 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
666 return ChargingStationConfigurationUtils
.getConfigurationKey(
668 StandardParametersKey
.SupportedFeatureProfiles
669 )?.value
.includes(featureProfile
);
672 public bufferMessage(message
: string): void {
673 this.messageBuffer
.add(message
);
676 public openWSConnection(
677 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
678 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
680 terminateOpened
: false,
683 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
684 params
.closeOpened
= params
?.closeOpened
?? false;
685 params
.terminateOpened
= params
?.terminateOpened
?? false;
687 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
688 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
690 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
692 if (params
?.closeOpened
) {
693 this.closeWSConnection();
695 if (params
?.terminateOpened
) {
696 this.terminateWSConnection();
698 let protocol
: string;
699 switch (this.getOcppVersion()) {
700 case OCPPVersion
.VERSION_16
:
701 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
704 this.handleUnsupportedVersion(this.getOcppVersion());
708 if (this.isWebSocketConnectionOpened()) {
710 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
716 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
719 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
721 // Handle WebSocket message
722 this.wsConnection
.on(
724 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
726 // Handle WebSocket error
727 this.wsConnection
.on(
729 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
731 // Handle WebSocket close
732 this.wsConnection
.on(
734 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
736 // Handle WebSocket open
737 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
738 // Handle WebSocket ping
739 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
740 // Handle WebSocket pong
741 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
744 public closeWSConnection(): void {
745 if (this.isWebSocketConnectionOpened()) {
746 this.wsConnection
.close();
747 this.wsConnection
= null;
751 public startAutomaticTransactionGenerator(): void {
752 if (!this.automaticTransactionGenerator
) {
753 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
754 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
758 if (!this.automaticTransactionGenerator
.started
) {
759 this.automaticTransactionGenerator
.start();
763 public stopAutomaticTransactionGenerator(): void {
764 if (this.automaticTransactionGenerator
?.started
) {
765 this.automaticTransactionGenerator
.stop();
766 this.automaticTransactionGenerator
= null;
770 private flushMessageBuffer(): void {
771 if (this.messageBuffer
.size
> 0) {
772 this.messageBuffer
.forEach((message
) => {
773 // TODO: evaluate the need to track performance
774 this.wsConnection
.send(message
);
775 this.messageBuffer
.delete(message
);
780 private getSupervisionUrlOcppConfiguration(): boolean {
781 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
784 private getSupervisionUrlOcppKey(): string {
785 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
788 private getTemplateFromFile(): ChargingStationTemplate
| null {
789 let template
: ChargingStationTemplate
= null;
791 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
792 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
794 const measureId
= `${FileType.ChargingStationTemplate} read`;
795 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
796 template
= JSON
.parse(
797 fs
.readFileSync(this.templateFile
, 'utf8')
798 ) as ChargingStationTemplate
;
799 PerformanceStatistics
.endMeasure(measureId
, beginId
);
800 template
.templateHash
= crypto
801 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
802 .update(JSON
.stringify(template
))
804 this.sharedLRUCache
.setChargingStationTemplate(template
);
807 FileUtils
.handleFileException(
809 FileType
.ChargingStationTemplate
,
811 error
as NodeJS
.ErrnoException
817 private getStationInfoFromTemplate(): ChargingStationInfo
{
818 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
819 if (Utils
.isNullOrUndefined(stationTemplate
)) {
820 const errorMsg
= 'Failed to read charging station template file';
821 logger
.error(`${this.logPrefix()} ${errorMsg}`);
822 throw new BaseError(errorMsg
);
824 if (Utils
.isEmptyObject(stationTemplate
)) {
825 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
826 logger
.error(`${this.logPrefix()} ${errorMsg}`);
827 throw new BaseError(errorMsg
);
829 // Deprecation template keys section
830 ChargingStationUtils
.warnDeprecatedTemplateKey(
835 "Use 'supervisionUrls' instead"
837 ChargingStationUtils
.convertDeprecatedTemplateKey(
842 const stationInfo
: ChargingStationInfo
=
843 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
844 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
848 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
849 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
850 stationTemplate
.power
= stationTemplate
.power
as number[];
851 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
852 stationInfo
.maximumPower
=
853 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
854 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
855 : stationTemplate
.power
[powerArrayRandomIndex
];
857 stationTemplate
.power
= stationTemplate
.power
as number;
858 stationInfo
.maximumPower
=
859 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
860 ? stationTemplate
.power
* 1000
861 : stationTemplate
.power
;
863 stationInfo
.resetTime
= stationTemplate
.resetTime
864 ? stationTemplate
.resetTime
* 1000
865 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
866 const configuredMaxConnectors
= ChargingStationUtils
.getConfiguredNumberOfConnectors(
870 ChargingStationUtils
.checkConfiguredMaxConnectors(
871 configuredMaxConnectors
,
875 const templateMaxConnectors
=
876 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
877 ChargingStationUtils
.checkTemplateMaxConnectors(
878 templateMaxConnectors
,
883 configuredMaxConnectors
>
884 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
885 !stationTemplate
?.randomConnectors
888 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
890 }, forcing random connector configurations affectation`
892 stationInfo
.randomConnectors
= true;
894 // Build connectors if needed (FIXME: should be factored out)
895 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
896 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
897 ChargingStationUtils
.createStationInfoHash(stationInfo
);
901 private getStationInfoFromFile(): ChargingStationInfo
| null {
902 let stationInfo
: ChargingStationInfo
= null;
903 this.getStationInfoPersistentConfiguration() &&
904 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
905 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
909 private getStationInfo(): ChargingStationInfo
{
910 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
911 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
912 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
913 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
914 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
915 return this.stationInfo
;
917 return stationInfoFromFile
;
919 stationInfoFromFile
&&
920 ChargingStationUtils
.propagateSerialNumber(
921 this.getTemplateFromFile(),
923 stationInfoFromTemplate
925 return stationInfoFromTemplate
;
928 private saveStationInfo(): void {
929 if (this.getStationInfoPersistentConfiguration()) {
930 this.saveConfiguration();
934 private getOcppVersion(): OCPPVersion
{
935 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
938 private getOcppPersistentConfiguration(): boolean {
939 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
942 private getStationInfoPersistentConfiguration(): boolean {
943 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
946 private handleUnsupportedVersion(version
: OCPPVersion
) {
947 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
948 logger
.error(`${this.logPrefix()} ${errMsg}`);
949 throw new BaseError(errMsg
);
952 private initialize(): void {
953 this.hashId
= ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile());
954 logger
.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
955 this.configurationFile
= path
.join(
956 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
957 this.hashId
+ '.json'
959 this.stationInfo
= this.getStationInfo();
960 this.saveStationInfo();
961 // Avoid duplication of connectors related information in RAM
962 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
963 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
964 if (this.getEnableStatistics()) {
965 this.performanceStatistics
= PerformanceStatistics
.getInstance(
967 this.stationInfo
.chargingStationId
,
968 this.configuredSupervisionUrl
971 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
974 this.powerDivider
= this.getPowerDivider();
975 // OCPP configuration
976 this.ocppConfiguration
= this.getOcppConfiguration();
977 this.initializeOcppConfiguration();
978 switch (this.getOcppVersion()) {
979 case OCPPVersion
.VERSION_16
:
980 this.ocppIncomingRequestService
=
981 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
982 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
983 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
987 this.handleUnsupportedVersion(this.getOcppVersion());
990 if (this.stationInfo
?.autoRegister
) {
991 this.bootNotificationResponse
= {
992 currentTime
: new Date().toISOString(),
993 interval
: this.getHeartbeatInterval() / 1000,
994 status: RegistrationStatus
.ACCEPTED
,
999 private initializeOcppConfiguration(): void {
1001 !ChargingStationConfigurationUtils
.getConfigurationKey(
1003 StandardParametersKey
.HeartbeatInterval
1006 ChargingStationConfigurationUtils
.addConfigurationKey(
1008 StandardParametersKey
.HeartbeatInterval
,
1013 !ChargingStationConfigurationUtils
.getConfigurationKey(
1015 StandardParametersKey
.HeartBeatInterval
1018 ChargingStationConfigurationUtils
.addConfigurationKey(
1020 StandardParametersKey
.HeartBeatInterval
,
1026 this.getSupervisionUrlOcppConfiguration() &&
1027 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1029 ChargingStationConfigurationUtils
.addConfigurationKey(
1031 this.getSupervisionUrlOcppKey(),
1032 this.configuredSupervisionUrl
.href
,
1036 !this.getSupervisionUrlOcppConfiguration() &&
1037 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1039 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1041 this.getSupervisionUrlOcppKey(),
1046 this.stationInfo
.amperageLimitationOcppKey
&&
1047 !ChargingStationConfigurationUtils
.getConfigurationKey(
1049 this.stationInfo
.amperageLimitationOcppKey
1052 ChargingStationConfigurationUtils
.addConfigurationKey(
1054 this.stationInfo
.amperageLimitationOcppKey
,
1056 this.stationInfo
.maximumAmperage
*
1057 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1062 !ChargingStationConfigurationUtils
.getConfigurationKey(
1064 StandardParametersKey
.SupportedFeatureProfiles
1067 ChargingStationConfigurationUtils
.addConfigurationKey(
1069 StandardParametersKey
.SupportedFeatureProfiles
,
1070 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1073 ChargingStationConfigurationUtils
.addConfigurationKey(
1075 StandardParametersKey
.NumberOfConnectors
,
1076 this.getNumberOfConnectors().toString(),
1081 !ChargingStationConfigurationUtils
.getConfigurationKey(
1083 StandardParametersKey
.MeterValuesSampledData
1086 ChargingStationConfigurationUtils
.addConfigurationKey(
1088 StandardParametersKey
.MeterValuesSampledData
,
1089 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1093 !ChargingStationConfigurationUtils
.getConfigurationKey(
1095 StandardParametersKey
.ConnectorPhaseRotation
1098 const connectorPhaseRotation
= [];
1099 for (const connectorId
of this.connectors
.keys()) {
1101 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1102 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1103 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1104 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1106 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1107 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1108 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1109 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1112 ChargingStationConfigurationUtils
.addConfigurationKey(
1114 StandardParametersKey
.ConnectorPhaseRotation
,
1115 connectorPhaseRotation
.toString()
1119 !ChargingStationConfigurationUtils
.getConfigurationKey(
1121 StandardParametersKey
.AuthorizeRemoteTxRequests
1124 ChargingStationConfigurationUtils
.addConfigurationKey(
1126 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1131 !ChargingStationConfigurationUtils
.getConfigurationKey(
1133 StandardParametersKey
.LocalAuthListEnabled
1135 ChargingStationConfigurationUtils
.getConfigurationKey(
1137 StandardParametersKey
.SupportedFeatureProfiles
1138 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1140 ChargingStationConfigurationUtils
.addConfigurationKey(
1142 StandardParametersKey
.LocalAuthListEnabled
,
1147 !ChargingStationConfigurationUtils
.getConfigurationKey(
1149 StandardParametersKey
.ConnectionTimeOut
1152 ChargingStationConfigurationUtils
.addConfigurationKey(
1154 StandardParametersKey
.ConnectionTimeOut
,
1155 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1158 this.saveOcppConfiguration();
1161 private initializeConnectors(
1162 stationInfo
: ChargingStationInfo
,
1163 configuredMaxConnectors
: number,
1164 templateMaxConnectors
: number
1166 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1167 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1168 logger
.error(`${this.logPrefix()} ${logMsg}`);
1169 throw new BaseError(logMsg
);
1171 if (!stationInfo
?.Connectors
[0]) {
1173 `${this.logPrefix()} Charging station information from template ${
1175 } with no connector Id 0 configuration`
1178 if (stationInfo
?.Connectors
) {
1179 const connectorsConfigHash
= crypto
1180 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1181 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1183 const connectorsConfigChanged
=
1184 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1185 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1186 connectorsConfigChanged
&& this.connectors
.clear();
1187 this.connectorsConfigurationHash
= connectorsConfigHash
;
1188 // Add connector Id 0
1189 let lastConnector
= '0';
1190 for (lastConnector
in stationInfo
?.Connectors
) {
1191 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1193 lastConnectorId
=== 0 &&
1194 this.getUseConnectorId0(stationInfo
) &&
1195 stationInfo
?.Connectors
[lastConnector
]
1197 this.connectors
.set(
1199 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1201 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1202 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1203 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1207 // Generate all connectors
1208 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1209 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1210 const randConnectorId
= stationInfo
?.randomConnectors
1211 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1213 this.connectors
.set(
1215 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1217 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1218 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1219 this.getConnectorStatus(index
).chargingProfiles
= [];
1226 `${this.logPrefix()} Charging station information from template ${
1228 } with no connectors configuration defined, using already defined connectors`
1231 // Initialize transaction attributes on connectors
1232 for (const connectorId
of this.connectors
.keys()) {
1233 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1234 this.initializeConnectorStatus(connectorId
);
1239 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1240 let configuration
: ChargingStationConfiguration
= null;
1241 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1243 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1244 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1245 this.configurationFileHash
1248 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1249 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1250 configuration
= JSON
.parse(
1251 fs
.readFileSync(this.configurationFile
, 'utf8')
1252 ) as ChargingStationConfiguration
;
1253 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1254 this.configurationFileHash
= configuration
.configurationHash
;
1255 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1258 FileUtils
.handleFileException(
1260 FileType
.ChargingStationConfiguration
,
1261 this.configurationFile
,
1262 error
as NodeJS
.ErrnoException
1266 return configuration
;
1269 private saveConfiguration(): void {
1270 if (this.configurationFile
) {
1272 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1273 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1275 const configurationData
: ChargingStationConfiguration
=
1276 this.getConfigurationFromFile() ?? {};
1277 this.ocppConfiguration
?.configurationKey
&&
1278 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1279 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1280 delete configurationData
.configurationHash
;
1281 const configurationHash
= crypto
1282 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1283 .update(JSON
.stringify(configurationData
))
1285 if (this.configurationFileHash
!== configurationHash
) {
1286 configurationData
.configurationHash
= configurationHash
;
1287 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1288 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1289 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1290 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1291 fs
.closeSync(fileDescriptor
);
1292 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1293 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1294 this.configurationFileHash
= configurationHash
;
1295 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1298 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1299 this.configurationFile
1304 FileUtils
.handleFileException(
1306 FileType
.ChargingStationConfiguration
,
1307 this.configurationFile
,
1308 error
as NodeJS
.ErrnoException
1313 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1318 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1319 return this.getTemplateFromFile()?.Configuration
?? null;
1322 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1323 let configuration
: ChargingStationConfiguration
= null;
1324 if (this.getOcppPersistentConfiguration()) {
1325 const configurationFromFile
= this.getConfigurationFromFile();
1326 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1328 configuration
&& delete configuration
.stationInfo
;
1329 return configuration
;
1332 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1333 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1334 if (!ocppConfiguration
) {
1335 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1337 return ocppConfiguration
;
1340 private async onOpen(): Promise
<void> {
1341 if (this.isWebSocketConnectionOpened()) {
1343 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1345 if (!this.isRegistered()) {
1346 // Send BootNotification
1347 let registrationRetryCount
= 0;
1349 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1350 BootNotificationRequest
,
1351 BootNotificationResponse
1354 RequestCommand
.BOOT_NOTIFICATION
,
1356 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1357 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1358 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1359 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1360 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1361 iccid
: this.bootNotificationRequest
.iccid
,
1362 imsi
: this.bootNotificationRequest
.imsi
,
1363 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1364 meterType
: this.bootNotificationRequest
.meterType
,
1366 { skipBufferingOnError
: true }
1368 if (!this.isRegistered()) {
1369 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1371 this.bootNotificationResponse
?.interval
1372 ? this.bootNotificationResponse
.interval
* 1000
1373 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1377 !this.isRegistered() &&
1378 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1379 this.getRegistrationMaxRetries() === -1)
1382 if (this.isRegistered()) {
1383 if (this.isInAcceptedState()) {
1384 await this.startMessageSequence();
1385 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1389 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1392 this.stopped
&& (this.stopped
= false);
1393 this.autoReconnectRetryCount
= 0;
1394 this.wsConnectionRestarted
= false;
1397 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1402 private async onClose(code
: number, reason
: string): Promise
<void> {
1405 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1406 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1408 `${this.logPrefix()} WebSocket normally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1410 )}' and reason '${reason}'`
1412 this.autoReconnectRetryCount
= 0;
1417 `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1419 )}' and reason '${reason}'`
1421 await this.reconnect(code
);
1426 private async onMessage(data
: Data
): Promise
<void> {
1427 let messageType
: number;
1428 let messageId
: string;
1429 let commandName
: IncomingRequestCommand
;
1430 let commandPayload
: JsonType
;
1431 let errorType
: ErrorType
;
1432 let errorMessage
: string;
1433 let errorDetails
: JsonType
;
1434 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1435 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1436 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1437 let requestPayload
: JsonType
;
1438 let cachedRequest
: CachedRequest
;
1441 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1442 if (Array.isArray(request
) === true) {
1443 [messageType
, messageId
] = request
;
1444 // Check the type of message
1445 switch (messageType
) {
1447 case MessageType
.CALL_MESSAGE
:
1448 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1449 if (this.getEnableStatistics()) {
1450 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1453 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1457 // Process the message
1458 await this.ocppIncomingRequestService
.incomingRequestHandler(
1466 case MessageType
.CALL_RESULT_MESSAGE
:
1467 [, , commandPayload
] = request
as Response
;
1468 if (!this.requests
.has(messageId
)) {
1470 throw new OCPPError(
1471 ErrorType
.INTERNAL_ERROR
,
1472 `Response for unknown message id ${messageId}`,
1478 cachedRequest
= this.requests
.get(messageId
);
1479 if (Array.isArray(cachedRequest
) === true) {
1480 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1482 throw new OCPPError(
1483 ErrorType
.PROTOCOL_ERROR
,
1484 `Cached request for message id ${messageId} response is not an array`,
1486 cachedRequest
as unknown
as JsonType
1490 `${this.logPrefix()} << Command '${
1491 requestCommandName ?? 'unknown'
1492 }' received response payload: ${JSON.stringify(request)}`
1494 responseCallback(commandPayload
, requestPayload
);
1497 case MessageType
.CALL_ERROR_MESSAGE
:
1498 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1499 if (!this.requests
.has(messageId
)) {
1501 throw new OCPPError(
1502 ErrorType
.INTERNAL_ERROR
,
1503 `Error response for unknown message id ${messageId}`,
1505 { errorType
, errorMessage
, errorDetails
}
1508 cachedRequest
= this.requests
.get(messageId
);
1509 if (Array.isArray(cachedRequest
) === true) {
1510 [, errorCallback
, requestCommandName
] = cachedRequest
;
1512 throw new OCPPError(
1513 ErrorType
.PROTOCOL_ERROR
,
1514 `Cached request for message id ${messageId} error response is not an array`,
1516 cachedRequest
as unknown
as JsonType
1520 `${this.logPrefix()} << Command '${
1521 requestCommandName ?? 'unknown'
1522 }' received error payload: ${JSON.stringify(request)}`
1524 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1528 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1529 errMsg
= `Wrong message type ${messageType}`;
1530 logger
.error(`${this.logPrefix()} ${errMsg}`);
1531 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1533 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1535 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1542 `${this.logPrefix()} Incoming OCPP command '${
1543 commandName ?? requestCommandName ?? null
1544 }' message '${data.toString()}' matching cached request '${JSON.stringify(
1545 this.requests.get(messageId)
1546 )}' processing error:`,
1549 if (!(error
instanceof OCPPError
)) {
1551 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1552 commandName ?? requestCommandName ?? null
1553 }' message '${data.toString()}' handling is not an OCPPError:`,
1558 messageType
=== MessageType
.CALL_MESSAGE
&&
1559 (await this.ocppRequestService
.sendError(
1563 commandName
?? requestCommandName
?? null
1568 private onPing(): void {
1569 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1572 private onPong(): void {
1573 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1576 private onError(error
: WSError
): void {
1577 this.closeWSConnection();
1578 logger
.error(this.logPrefix() + ' WebSocket error:', error
);
1581 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean | undefined {
1582 const localStationInfo
= stationInfo
?? this.stationInfo
;
1583 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1584 ? localStationInfo
.useConnectorId0
1588 private getNumberOfRunningTransactions(): number {
1590 for (const connectorId
of this.connectors
.keys()) {
1591 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1599 private getConnectionTimeout(): number | undefined {
1601 ChargingStationConfigurationUtils
.getConfigurationKey(
1603 StandardParametersKey
.ConnectionTimeOut
1608 ChargingStationConfigurationUtils
.getConfigurationKey(
1610 StandardParametersKey
.ConnectionTimeOut
1612 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1615 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1618 // -1 for unlimited, 0 for disabling
1619 private getAutoReconnectMaxRetries(): number | undefined {
1620 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1621 return this.stationInfo
.autoReconnectMaxRetries
;
1623 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1624 return Configuration
.getAutoReconnectMaxRetries();
1630 private getRegistrationMaxRetries(): number | undefined {
1631 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1632 return this.stationInfo
.registrationMaxRetries
;
1637 private getPowerDivider(): number {
1638 let powerDivider
= this.getNumberOfConnectors();
1639 if (this.stationInfo
?.powerSharedByConnectors
) {
1640 powerDivider
= this.getNumberOfRunningTransactions();
1642 return powerDivider
;
1645 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1646 const localStationInfo
= stationInfo
?? this.stationInfo
;
1647 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1650 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1651 const maximumPower
= this.getMaximumPower(stationInfo
);
1652 switch (this.getCurrentOutType(stationInfo
)) {
1653 case CurrentType
.AC
:
1654 return ACElectricUtils
.amperagePerPhaseFromPower(
1655 this.getNumberOfPhases(stationInfo
),
1656 maximumPower
/ this.getNumberOfConnectors(),
1657 this.getVoltageOut(stationInfo
)
1659 case CurrentType
.DC
:
1660 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1664 private getAmperageLimitation(): number | undefined {
1666 this.stationInfo
.amperageLimitationOcppKey
&&
1667 ChargingStationConfigurationUtils
.getConfigurationKey(
1669 this.stationInfo
.amperageLimitationOcppKey
1674 ChargingStationConfigurationUtils
.getConfigurationKey(
1676 this.stationInfo
.amperageLimitationOcppKey
1678 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1683 private async startMessageSequence(): Promise
<void> {
1684 if (this.stationInfo
?.autoRegister
) {
1685 await this.ocppRequestService
.requestHandler
<
1686 BootNotificationRequest
,
1687 BootNotificationResponse
1690 RequestCommand
.BOOT_NOTIFICATION
,
1692 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1693 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1694 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1695 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1696 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1697 iccid
: this.bootNotificationRequest
.iccid
,
1698 imsi
: this.bootNotificationRequest
.imsi
,
1699 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1700 meterType
: this.bootNotificationRequest
.meterType
,
1702 { skipBufferingOnError
: true }
1705 // Start WebSocket ping
1706 this.startWebSocketPing();
1708 this.startHeartbeat();
1709 // Initialize connectors status
1710 for (const connectorId
of this.connectors
.keys()) {
1711 if (connectorId
=== 0) {
1715 !this.getConnectorStatus(connectorId
)?.status &&
1716 this.getConnectorStatus(connectorId
)?.bootStatus
1718 // Send status in template at startup
1719 await this.ocppRequestService
.requestHandler
<
1720 StatusNotificationRequest
,
1721 StatusNotificationResponse
1722 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1724 status: this.getConnectorStatus(connectorId
).bootStatus
,
1725 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1727 this.getConnectorStatus(connectorId
).status =
1728 this.getConnectorStatus(connectorId
).bootStatus
;
1731 this.getConnectorStatus(connectorId
)?.status &&
1732 this.getConnectorStatus(connectorId
)?.bootStatus
1734 // Send status in template after reset
1735 await this.ocppRequestService
.requestHandler
<
1736 StatusNotificationRequest
,
1737 StatusNotificationResponse
1738 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1740 status: this.getConnectorStatus(connectorId
).bootStatus
,
1741 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1743 this.getConnectorStatus(connectorId
).status =
1744 this.getConnectorStatus(connectorId
).bootStatus
;
1745 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1746 // Send previous status at template reload
1747 await this.ocppRequestService
.requestHandler
<
1748 StatusNotificationRequest
,
1749 StatusNotificationResponse
1750 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1752 status: this.getConnectorStatus(connectorId
).status,
1753 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1756 // Send default status
1757 await this.ocppRequestService
.requestHandler
<
1758 StatusNotificationRequest
,
1759 StatusNotificationResponse
1760 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1762 status: ChargePointStatus
.AVAILABLE
,
1763 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1765 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1769 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
) {
1770 this.startAutomaticTransactionGenerator();
1774 private async stopMessageSequence(
1775 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1777 // Stop WebSocket ping
1778 this.stopWebSocketPing();
1780 this.stopHeartbeat();
1781 // Stop ongoing transactions
1782 if (this.getNumberOfRunningTransactions() > 0) {
1783 if (this.automaticTransactionGenerator
?.started
) {
1784 this.stopAutomaticTransactionGenerator();
1786 for (const connectorId
of this.connectors
.keys()) {
1787 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1788 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1790 this.getBeginEndMeterValues() &&
1791 this.getOcppStrictCompliance() &&
1792 !this.getOutOfOrderEndMeterValues()
1794 // FIXME: Implement OCPP version agnostic helpers
1795 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1798 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1800 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
1802 RequestCommand
.METER_VALUES
,
1806 meterValue
: [transactionEndMeterValue
],
1810 await this.ocppRequestService
.requestHandler
<
1811 StopTransactionRequest
,
1812 StopTransactionResponse
1813 >(this, RequestCommand
.STOP_TRANSACTION
, {
1815 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1816 idTag
: this.getTransactionIdTag(transactionId
),
1825 private startWebSocketPing(): void {
1826 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1828 StandardParametersKey
.WebSocketPingInterval
1830 ? Utils
.convertToInt(
1831 ChargingStationConfigurationUtils
.getConfigurationKey(
1833 StandardParametersKey
.WebSocketPingInterval
1837 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1838 this.webSocketPingSetInterval
= setInterval(() => {
1839 if (this.isWebSocketConnectionOpened()) {
1840 this.wsConnection
.ping((): void => {
1841 /* This is intentional */
1844 }, webSocketPingInterval
* 1000);
1847 ' WebSocket ping started every ' +
1848 Utils
.formatDurationSeconds(webSocketPingInterval
)
1850 } else if (this.webSocketPingSetInterval
) {
1853 ' WebSocket ping every ' +
1854 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1859 `${this.logPrefix()} WebSocket ping interval set to ${
1860 webSocketPingInterval
1861 ? Utils.formatDurationSeconds(webSocketPingInterval)
1862 : webSocketPingInterval
1863 }, not starting the WebSocket ping`
1868 private stopWebSocketPing(): void {
1869 if (this.webSocketPingSetInterval
) {
1870 clearInterval(this.webSocketPingSetInterval
);
1874 private getConfiguredSupervisionUrl(): URL
{
1875 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1876 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1878 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1880 switch (Configuration
.getSupervisionUrlDistribution()) {
1881 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1882 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1884 case SupervisionUrlDistribution
.RANDOM
:
1886 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1888 case SupervisionUrlDistribution
.SEQUENTIAL
:
1889 if (this.index
<= supervisionUrls
.length
) {
1890 urlIndex
= this.index
- 1;
1893 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1899 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1900 SupervisionUrlDistribution.ROUND_ROBIN
1903 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1906 return new URL(supervisionUrls
[urlIndex
]);
1908 return new URL(supervisionUrls
as string);
1911 private getHeartbeatInterval(): number | undefined {
1912 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1914 StandardParametersKey
.HeartbeatInterval
1916 if (HeartbeatInterval
) {
1917 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1919 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1921 StandardParametersKey
.HeartBeatInterval
1923 if (HeartBeatInterval
) {
1924 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1926 !this.stationInfo
?.autoRegister
&&
1928 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1929 Constants.DEFAULT_HEARTBEAT_INTERVAL
1932 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1935 private stopHeartbeat(): void {
1936 if (this.heartbeatSetInterval
) {
1937 clearInterval(this.heartbeatSetInterval
);
1941 private terminateWSConnection(): void {
1942 if (this.isWebSocketConnectionOpened()) {
1943 this.wsConnection
.terminate();
1944 this.wsConnection
= null;
1948 private stopMeterValues(connectorId
: number) {
1949 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1950 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1954 private getReconnectExponentialDelay(): boolean | undefined {
1955 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1956 ? this.stationInfo
.reconnectExponentialDelay
1960 private async reconnect(code
: number): Promise
<void> {
1961 // Stop WebSocket ping
1962 this.stopWebSocketPing();
1964 this.stopHeartbeat();
1965 // Stop the ATG if needed
1966 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
) {
1967 this.stopAutomaticTransactionGenerator();
1970 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1971 this.getAutoReconnectMaxRetries() === -1
1973 this.autoReconnectRetryCount
++;
1974 const reconnectDelay
= this.getReconnectExponentialDelay()
1975 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1976 : this.getConnectionTimeout() * 1000;
1977 const reconnectDelayWithdraw
= 1000;
1978 const reconnectTimeout
=
1979 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
1980 ? reconnectDelay
- reconnectDelayWithdraw
1983 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1986 )}ms, timeout ${reconnectTimeout}ms`
1988 await Utils
.sleep(reconnectDelay
);
1991 ' WebSocket: reconnecting try #' +
1992 this.autoReconnectRetryCount
.toString()
1994 this.openWSConnection(
1995 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
1996 { closeOpened
: true }
1998 this.wsConnectionRestarted
= true;
1999 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2001 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2002 this.autoReconnectRetryCount
2003 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2008 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
2009 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2012 private initializeConnectorStatus(connectorId
: number): void {
2013 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2014 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2015 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2016 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2017 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2018 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;