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 this.startAutomaticTransactionGenerator();
507 if (this.getEnableStatistics()) {
508 this.performanceStatistics
.restart();
510 this.performanceStatistics
.stop();
512 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
515 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
522 parentPort
.postMessage(MessageChannelUtils
.buildStartedMessage(this));
525 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
526 // Stop message sequence
527 await this.stopMessageSequence(reason
);
528 for (const connectorId
of this.connectors
.keys()) {
529 if (connectorId
> 0) {
530 await this.ocppRequestService
.requestHandler
<
531 StatusNotificationRequest
,
532 StatusNotificationResponse
533 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
535 status: ChargePointStatus
.UNAVAILABLE
,
536 errorCode
: ChargePointErrorCode
.NO_ERROR
,
538 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
541 this.closeWSConnection();
542 if (this.getEnableStatistics()) {
543 this.performanceStatistics
.stop();
545 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
546 this.templateFileWatcher
.close();
547 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
548 this.bootNotificationResponse
= null;
550 parentPort
.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
553 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
554 await this.stop(reason
);
555 await Utils
.sleep(this.stationInfo
.resetTime
);
560 public saveOcppConfiguration(): void {
561 if (this.getOcppPersistentConfiguration()) {
562 this.saveConfiguration();
566 public getChargingProfilePowerLimit(connectorId
: number): number | undefined {
567 let limit
: number, matchingChargingProfile
: ChargingProfile
;
568 let chargingProfiles
: ChargingProfile
[] = [];
569 // Get charging profiles for connector and sort by stack level
570 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
571 (a
, b
) => b
.stackLevel
- a
.stackLevel
573 // Get profiles on connector 0
574 if (this.getConnectorStatus(0).chargingProfiles
) {
575 chargingProfiles
.push(
576 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
579 if (!Utils
.isEmptyArray(chargingProfiles
)) {
580 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
584 if (!Utils
.isNullOrUndefined(result
)) {
585 limit
= result
.limit
;
586 matchingChargingProfile
= result
.matchingChargingProfile
;
587 switch (this.getCurrentOutType()) {
590 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
591 ChargingRateUnitType
.WATT
593 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
597 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
598 ChargingRateUnitType
.WATT
600 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
603 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
604 if (limit
> connectorMaximumPower
) {
606 `${this.logPrefix()} Charging profile id ${
607 matchingChargingProfile.chargingProfileId
608 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
609 this.getConnectorStatus(connectorId
).chargingProfiles
611 limit
= connectorMaximumPower
;
618 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
619 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
621 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
623 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
625 if (Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
) === false) {
627 `${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`
629 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
631 let cpReplaced
= false;
632 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
633 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
634 (chargingProfile
: ChargingProfile
, index
: number) => {
636 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
637 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
638 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
640 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
646 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
649 public resetConnectorStatus(connectorId
: number): void {
650 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
651 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
652 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
653 this.getConnectorStatus(connectorId
).transactionStarted
= false;
654 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
655 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
656 delete this.getConnectorStatus(connectorId
).transactionId
;
657 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
658 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
659 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
660 this.stopMeterValues(connectorId
);
663 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
664 return ChargingStationConfigurationUtils
.getConfigurationKey(
666 StandardParametersKey
.SupportedFeatureProfiles
667 )?.value
.includes(featureProfile
);
670 public bufferMessage(message
: string): void {
671 this.messageBuffer
.add(message
);
674 public openWSConnection(
675 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
676 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
678 terminateOpened
: false,
681 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
682 params
.closeOpened
= params
?.closeOpened
?? false;
683 params
.terminateOpened
= params
?.terminateOpened
?? false;
685 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
686 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
688 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
690 if (params
?.closeOpened
) {
691 this.closeWSConnection();
693 if (params
?.terminateOpened
) {
694 this.terminateWSConnection();
696 let protocol
: string;
697 switch (this.getOcppVersion()) {
698 case OCPPVersion
.VERSION_16
:
699 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
702 this.handleUnsupportedVersion(this.getOcppVersion());
706 if (this.isWebSocketConnectionOpened()) {
708 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
714 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
717 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
719 // Handle WebSocket message
720 this.wsConnection
.on(
722 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
724 // Handle WebSocket error
725 this.wsConnection
.on(
727 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
729 // Handle WebSocket close
730 this.wsConnection
.on(
732 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
734 // Handle WebSocket open
735 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
736 // Handle WebSocket ping
737 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
738 // Handle WebSocket pong
739 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
742 public closeWSConnection(): void {
743 if (this.isWebSocketConnectionOpened()) {
744 this.wsConnection
.close();
745 this.wsConnection
= null;
749 private flushMessageBuffer() {
750 if (this.messageBuffer
.size
> 0) {
751 this.messageBuffer
.forEach((message
) => {
752 // TODO: evaluate the need to track performance
753 this.wsConnection
.send(message
);
754 this.messageBuffer
.delete(message
);
759 private getSupervisionUrlOcppConfiguration(): boolean {
760 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
763 private getSupervisionUrlOcppKey(): string {
764 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
767 private getTemplateFromFile(): ChargingStationTemplate
| null {
768 let template
: ChargingStationTemplate
= null;
770 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
771 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
773 const measureId
= `${FileType.ChargingStationTemplate} read`;
774 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
775 template
= JSON
.parse(
776 fs
.readFileSync(this.templateFile
, 'utf8')
777 ) as ChargingStationTemplate
;
778 PerformanceStatistics
.endMeasure(measureId
, beginId
);
779 template
.templateHash
= crypto
780 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
781 .update(JSON
.stringify(template
))
783 this.sharedLRUCache
.setChargingStationTemplate(template
);
786 FileUtils
.handleFileException(
788 FileType
.ChargingStationTemplate
,
790 error
as NodeJS
.ErrnoException
796 private getStationInfoFromTemplate(): ChargingStationInfo
{
797 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
798 if (Utils
.isNullOrUndefined(stationTemplate
)) {
799 const errorMsg
= 'Failed to read charging station template file';
800 logger
.error(`${this.logPrefix()} ${errorMsg}`);
801 throw new BaseError(errorMsg
);
803 if (Utils
.isEmptyObject(stationTemplate
)) {
804 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
805 logger
.error(`${this.logPrefix()} ${errorMsg}`);
806 throw new BaseError(errorMsg
);
808 // Deprecation template keys section
809 ChargingStationUtils
.warnDeprecatedTemplateKey(
814 "Use 'supervisionUrls' instead"
816 ChargingStationUtils
.convertDeprecatedTemplateKey(
821 const stationInfo
: ChargingStationInfo
=
822 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
823 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
827 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
828 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
829 stationTemplate
.power
= stationTemplate
.power
as number[];
830 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
831 stationInfo
.maximumPower
=
832 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
833 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
834 : stationTemplate
.power
[powerArrayRandomIndex
];
836 stationTemplate
.power
= stationTemplate
.power
as number;
837 stationInfo
.maximumPower
=
838 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
839 ? stationTemplate
.power
* 1000
840 : stationTemplate
.power
;
842 stationInfo
.resetTime
= stationTemplate
.resetTime
843 ? stationTemplate
.resetTime
* 1000
844 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
845 const configuredMaxConnectors
= ChargingStationUtils
.getConfiguredNumberOfConnectors(
849 ChargingStationUtils
.checkConfiguredMaxConnectors(
850 configuredMaxConnectors
,
854 const templateMaxConnectors
=
855 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
856 ChargingStationUtils
.checkTemplateMaxConnectors(
857 templateMaxConnectors
,
862 configuredMaxConnectors
>
863 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
864 !stationTemplate
?.randomConnectors
867 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
869 }, forcing random connector configurations affectation`
871 stationInfo
.randomConnectors
= true;
873 // Build connectors if needed (FIXME: should be factored out)
874 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
875 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
876 ChargingStationUtils
.createStationInfoHash(stationInfo
);
880 private getStationInfoFromFile(): ChargingStationInfo
| null {
881 let stationInfo
: ChargingStationInfo
= null;
882 this.getStationInfoPersistentConfiguration() &&
883 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
884 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
888 private getStationInfo(): ChargingStationInfo
{
889 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
890 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
891 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
892 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
893 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
894 return this.stationInfo
;
896 return stationInfoFromFile
;
898 stationInfoFromFile
&&
899 ChargingStationUtils
.propagateSerialNumber(
900 this.getTemplateFromFile(),
902 stationInfoFromTemplate
904 return stationInfoFromTemplate
;
907 private saveStationInfo(): void {
908 if (this.getStationInfoPersistentConfiguration()) {
909 this.saveConfiguration();
913 private getOcppVersion(): OCPPVersion
{
914 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
917 private getOcppPersistentConfiguration(): boolean {
918 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
921 private getStationInfoPersistentConfiguration(): boolean {
922 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
925 private handleUnsupportedVersion(version
: OCPPVersion
) {
926 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
927 logger
.error(`${this.logPrefix()} ${errMsg}`);
928 throw new BaseError(errMsg
);
931 private initialize(): void {
932 this.hashId
= ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile());
933 logger
.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
934 this.configurationFile
= path
.join(
935 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
936 this.hashId
+ '.json'
938 this.stationInfo
= this.getStationInfo();
939 this.saveStationInfo();
940 // Avoid duplication of connectors related information in RAM
941 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
942 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
943 if (this.getEnableStatistics()) {
944 this.performanceStatistics
= PerformanceStatistics
.getInstance(
946 this.stationInfo
.chargingStationId
,
947 this.configuredSupervisionUrl
950 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
953 this.powerDivider
= this.getPowerDivider();
954 // OCPP configuration
955 this.ocppConfiguration
= this.getOcppConfiguration();
956 this.initializeOcppConfiguration();
957 switch (this.getOcppVersion()) {
958 case OCPPVersion
.VERSION_16
:
959 this.ocppIncomingRequestService
=
960 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
961 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
962 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
966 this.handleUnsupportedVersion(this.getOcppVersion());
969 if (this.stationInfo
?.autoRegister
) {
970 this.bootNotificationResponse
= {
971 currentTime
: new Date().toISOString(),
972 interval
: this.getHeartbeatInterval() / 1000,
973 status: RegistrationStatus
.ACCEPTED
,
978 private initializeOcppConfiguration(): void {
980 !ChargingStationConfigurationUtils
.getConfigurationKey(
982 StandardParametersKey
.HeartbeatInterval
985 ChargingStationConfigurationUtils
.addConfigurationKey(
987 StandardParametersKey
.HeartbeatInterval
,
992 !ChargingStationConfigurationUtils
.getConfigurationKey(
994 StandardParametersKey
.HeartBeatInterval
997 ChargingStationConfigurationUtils
.addConfigurationKey(
999 StandardParametersKey
.HeartBeatInterval
,
1005 this.getSupervisionUrlOcppConfiguration() &&
1006 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1008 ChargingStationConfigurationUtils
.addConfigurationKey(
1010 this.getSupervisionUrlOcppKey(),
1011 this.configuredSupervisionUrl
.href
,
1015 !this.getSupervisionUrlOcppConfiguration() &&
1016 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1018 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1020 this.getSupervisionUrlOcppKey(),
1025 this.stationInfo
.amperageLimitationOcppKey
&&
1026 !ChargingStationConfigurationUtils
.getConfigurationKey(
1028 this.stationInfo
.amperageLimitationOcppKey
1031 ChargingStationConfigurationUtils
.addConfigurationKey(
1033 this.stationInfo
.amperageLimitationOcppKey
,
1035 this.stationInfo
.maximumAmperage
*
1036 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1041 !ChargingStationConfigurationUtils
.getConfigurationKey(
1043 StandardParametersKey
.SupportedFeatureProfiles
1046 ChargingStationConfigurationUtils
.addConfigurationKey(
1048 StandardParametersKey
.SupportedFeatureProfiles
,
1049 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1052 ChargingStationConfigurationUtils
.addConfigurationKey(
1054 StandardParametersKey
.NumberOfConnectors
,
1055 this.getNumberOfConnectors().toString(),
1060 !ChargingStationConfigurationUtils
.getConfigurationKey(
1062 StandardParametersKey
.MeterValuesSampledData
1065 ChargingStationConfigurationUtils
.addConfigurationKey(
1067 StandardParametersKey
.MeterValuesSampledData
,
1068 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1072 !ChargingStationConfigurationUtils
.getConfigurationKey(
1074 StandardParametersKey
.ConnectorPhaseRotation
1077 const connectorPhaseRotation
= [];
1078 for (const connectorId
of this.connectors
.keys()) {
1080 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1081 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1082 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1083 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1085 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1086 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1087 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1088 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1091 ChargingStationConfigurationUtils
.addConfigurationKey(
1093 StandardParametersKey
.ConnectorPhaseRotation
,
1094 connectorPhaseRotation
.toString()
1098 !ChargingStationConfigurationUtils
.getConfigurationKey(
1100 StandardParametersKey
.AuthorizeRemoteTxRequests
1103 ChargingStationConfigurationUtils
.addConfigurationKey(
1105 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1110 !ChargingStationConfigurationUtils
.getConfigurationKey(
1112 StandardParametersKey
.LocalAuthListEnabled
1114 ChargingStationConfigurationUtils
.getConfigurationKey(
1116 StandardParametersKey
.SupportedFeatureProfiles
1117 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1119 ChargingStationConfigurationUtils
.addConfigurationKey(
1121 StandardParametersKey
.LocalAuthListEnabled
,
1126 !ChargingStationConfigurationUtils
.getConfigurationKey(
1128 StandardParametersKey
.ConnectionTimeOut
1131 ChargingStationConfigurationUtils
.addConfigurationKey(
1133 StandardParametersKey
.ConnectionTimeOut
,
1134 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1137 this.saveOcppConfiguration();
1140 private initializeConnectors(
1141 stationInfo
: ChargingStationInfo
,
1142 configuredMaxConnectors
: number,
1143 templateMaxConnectors
: number
1145 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1146 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1147 logger
.error(`${this.logPrefix()} ${logMsg}`);
1148 throw new BaseError(logMsg
);
1150 if (!stationInfo
?.Connectors
[0]) {
1152 `${this.logPrefix()} Charging station information from template ${
1154 } with no connector Id 0 configuration`
1157 if (stationInfo
?.Connectors
) {
1158 const connectorsConfigHash
= crypto
1159 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1160 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1162 const connectorsConfigChanged
=
1163 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1164 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1165 connectorsConfigChanged
&& this.connectors
.clear();
1166 this.connectorsConfigurationHash
= connectorsConfigHash
;
1167 // Add connector Id 0
1168 let lastConnector
= '0';
1169 for (lastConnector
in stationInfo
?.Connectors
) {
1170 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1172 lastConnectorId
=== 0 &&
1173 this.getUseConnectorId0(stationInfo
) &&
1174 stationInfo
?.Connectors
[lastConnector
]
1176 this.connectors
.set(
1178 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1180 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1181 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1182 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1186 // Generate all connectors
1187 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1188 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1189 const randConnectorId
= stationInfo
?.randomConnectors
1190 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1192 this.connectors
.set(
1194 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1196 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1197 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1198 this.getConnectorStatus(index
).chargingProfiles
= [];
1205 `${this.logPrefix()} Charging station information from template ${
1207 } with no connectors configuration defined, using already defined connectors`
1210 // Initialize transaction attributes on connectors
1211 for (const connectorId
of this.connectors
.keys()) {
1212 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1213 this.initializeConnectorStatus(connectorId
);
1218 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1219 let configuration
: ChargingStationConfiguration
= null;
1220 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1222 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1223 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1224 this.configurationFileHash
1227 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1228 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1229 configuration
= JSON
.parse(
1230 fs
.readFileSync(this.configurationFile
, 'utf8')
1231 ) as ChargingStationConfiguration
;
1232 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1233 this.configurationFileHash
= configuration
.configurationHash
;
1234 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1237 FileUtils
.handleFileException(
1239 FileType
.ChargingStationConfiguration
,
1240 this.configurationFile
,
1241 error
as NodeJS
.ErrnoException
1245 return configuration
;
1248 private saveConfiguration(): void {
1249 if (this.configurationFile
) {
1251 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1252 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1254 const configurationData
: ChargingStationConfiguration
=
1255 this.getConfigurationFromFile() ?? {};
1256 this.ocppConfiguration
?.configurationKey
&&
1257 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1258 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1259 delete configurationData
.configurationHash
;
1260 const configurationHash
= crypto
1261 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1262 .update(JSON
.stringify(configurationData
))
1264 if (this.configurationFileHash
!== configurationHash
) {
1265 configurationData
.configurationHash
= configurationHash
;
1266 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1267 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1268 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1269 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1270 fs
.closeSync(fileDescriptor
);
1271 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1272 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1273 this.configurationFileHash
= configurationHash
;
1274 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1277 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1278 this.configurationFile
1283 FileUtils
.handleFileException(
1285 FileType
.ChargingStationConfiguration
,
1286 this.configurationFile
,
1287 error
as NodeJS
.ErrnoException
1292 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1297 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1298 return this.getTemplateFromFile()?.Configuration
?? null;
1301 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1302 let configuration
: ChargingStationConfiguration
= null;
1303 if (this.getOcppPersistentConfiguration()) {
1304 const configurationFromFile
= this.getConfigurationFromFile();
1305 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1307 configuration
&& delete configuration
.stationInfo
;
1308 return configuration
;
1311 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1312 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1313 if (!ocppConfiguration
) {
1314 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1316 return ocppConfiguration
;
1319 private async onOpen(): Promise
<void> {
1320 if (this.isWebSocketConnectionOpened()) {
1322 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1324 if (!this.isRegistered()) {
1325 // Send BootNotification
1326 let registrationRetryCount
= 0;
1328 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1329 BootNotificationRequest
,
1330 BootNotificationResponse
1333 RequestCommand
.BOOT_NOTIFICATION
,
1335 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1336 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1337 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1338 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1339 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1340 iccid
: this.bootNotificationRequest
.iccid
,
1341 imsi
: this.bootNotificationRequest
.imsi
,
1342 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1343 meterType
: this.bootNotificationRequest
.meterType
,
1345 { skipBufferingOnError
: true }
1347 if (!this.isRegistered()) {
1348 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1350 this.bootNotificationResponse
?.interval
1351 ? this.bootNotificationResponse
.interval
* 1000
1352 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1356 !this.isRegistered() &&
1357 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1358 this.getRegistrationMaxRetries() === -1)
1361 if (this.isRegistered()) {
1362 if (this.isInAcceptedState()) {
1363 await this.startMessageSequence();
1364 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1368 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1371 this.stopped
&& (this.stopped
= false);
1372 this.autoReconnectRetryCount
= 0;
1373 this.wsConnectionRestarted
= false;
1376 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1381 private async onClose(code
: number, reason
: string): Promise
<void> {
1384 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1385 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1387 `${this.logPrefix()} WebSocket normally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1389 )}' and reason '${reason}'`
1391 this.autoReconnectRetryCount
= 0;
1396 `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1398 )}' and reason '${reason}'`
1400 await this.reconnect(code
);
1405 private async onMessage(data
: Data
): Promise
<void> {
1406 let messageType
: number;
1407 let messageId
: string;
1408 let commandName
: IncomingRequestCommand
;
1409 let commandPayload
: JsonType
;
1410 let errorType
: ErrorType
;
1411 let errorMessage
: string;
1412 let errorDetails
: JsonType
;
1413 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1414 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1415 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1416 let requestPayload
: JsonType
;
1417 let cachedRequest
: CachedRequest
;
1420 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1421 if (Array.isArray(request
) === true) {
1422 [messageType
, messageId
] = request
;
1423 // Check the type of message
1424 switch (messageType
) {
1426 case MessageType
.CALL_MESSAGE
:
1427 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1428 if (this.getEnableStatistics()) {
1429 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1432 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1436 // Process the message
1437 await this.ocppIncomingRequestService
.incomingRequestHandler(
1445 case MessageType
.CALL_RESULT_MESSAGE
:
1446 [, , commandPayload
] = request
as Response
;
1447 if (!this.requests
.has(messageId
)) {
1449 throw new OCPPError(
1450 ErrorType
.INTERNAL_ERROR
,
1451 `Response for unknown message id ${messageId}`,
1457 cachedRequest
= this.requests
.get(messageId
);
1458 if (Array.isArray(cachedRequest
) === true) {
1459 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1461 throw new OCPPError(
1462 ErrorType
.PROTOCOL_ERROR
,
1463 `Cached request for message id ${messageId} response is not an array`,
1465 cachedRequest
as unknown
as JsonType
1469 `${this.logPrefix()} << Command '${
1470 requestCommandName ?? 'unknown'
1471 }' received response payload: ${JSON.stringify(request)}`
1473 responseCallback(commandPayload
, requestPayload
);
1476 case MessageType
.CALL_ERROR_MESSAGE
:
1477 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1478 if (!this.requests
.has(messageId
)) {
1480 throw new OCPPError(
1481 ErrorType
.INTERNAL_ERROR
,
1482 `Error response for unknown message id ${messageId}`,
1484 { errorType
, errorMessage
, errorDetails
}
1487 cachedRequest
= this.requests
.get(messageId
);
1488 if (Array.isArray(cachedRequest
) === true) {
1489 [, errorCallback
, requestCommandName
] = cachedRequest
;
1491 throw new OCPPError(
1492 ErrorType
.PROTOCOL_ERROR
,
1493 `Cached request for message id ${messageId} error response is not an array`,
1495 cachedRequest
as unknown
as JsonType
1499 `${this.logPrefix()} << Command '${
1500 requestCommandName ?? 'unknown'
1501 }' received error payload: ${JSON.stringify(request)}`
1503 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1507 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1508 errMsg
= `Wrong message type ${messageType}`;
1509 logger
.error(`${this.logPrefix()} ${errMsg}`);
1510 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1512 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1514 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1521 `${this.logPrefix()} Incoming OCPP command '${
1522 commandName ?? requestCommandName ?? null
1523 }' message '${data.toString()}' matching cached request '${JSON.stringify(
1524 this.requests.get(messageId)
1525 )}' processing error:`,
1528 if (!(error
instanceof OCPPError
)) {
1530 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1531 commandName ?? requestCommandName ?? null
1532 }' message '${data.toString()}' handling is not an OCPPError:`,
1537 messageType
=== MessageType
.CALL_MESSAGE
&&
1538 (await this.ocppRequestService
.sendError(
1542 commandName
?? requestCommandName
?? null
1547 private onPing(): void {
1548 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1551 private onPong(): void {
1552 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1555 private onError(error
: WSError
): void {
1556 this.closeWSConnection();
1557 logger
.error(this.logPrefix() + ' WebSocket error:', error
);
1560 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean | undefined {
1561 const localStationInfo
= stationInfo
?? this.stationInfo
;
1562 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1563 ? localStationInfo
.useConnectorId0
1567 private getNumberOfRunningTransactions(): number {
1569 for (const connectorId
of this.connectors
.keys()) {
1570 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1578 private getConnectionTimeout(): number | undefined {
1580 ChargingStationConfigurationUtils
.getConfigurationKey(
1582 StandardParametersKey
.ConnectionTimeOut
1587 ChargingStationConfigurationUtils
.getConfigurationKey(
1589 StandardParametersKey
.ConnectionTimeOut
1591 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1594 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1597 // -1 for unlimited, 0 for disabling
1598 private getAutoReconnectMaxRetries(): number | undefined {
1599 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1600 return this.stationInfo
.autoReconnectMaxRetries
;
1602 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1603 return Configuration
.getAutoReconnectMaxRetries();
1609 private getRegistrationMaxRetries(): number | undefined {
1610 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1611 return this.stationInfo
.registrationMaxRetries
;
1616 private getPowerDivider(): number {
1617 let powerDivider
= this.getNumberOfConnectors();
1618 if (this.stationInfo
?.powerSharedByConnectors
) {
1619 powerDivider
= this.getNumberOfRunningTransactions();
1621 return powerDivider
;
1624 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1625 const localStationInfo
= stationInfo
?? this.stationInfo
;
1626 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1629 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1630 const maximumPower
= this.getMaximumPower(stationInfo
);
1631 switch (this.getCurrentOutType(stationInfo
)) {
1632 case CurrentType
.AC
:
1633 return ACElectricUtils
.amperagePerPhaseFromPower(
1634 this.getNumberOfPhases(stationInfo
),
1635 maximumPower
/ this.getNumberOfConnectors(),
1636 this.getVoltageOut(stationInfo
)
1638 case CurrentType
.DC
:
1639 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1643 private getAmperageLimitation(): number | undefined {
1645 this.stationInfo
.amperageLimitationOcppKey
&&
1646 ChargingStationConfigurationUtils
.getConfigurationKey(
1648 this.stationInfo
.amperageLimitationOcppKey
1653 ChargingStationConfigurationUtils
.getConfigurationKey(
1655 this.stationInfo
.amperageLimitationOcppKey
1657 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1662 private async startMessageSequence(): Promise
<void> {
1663 if (this.stationInfo
?.autoRegister
) {
1664 await this.ocppRequestService
.requestHandler
<
1665 BootNotificationRequest
,
1666 BootNotificationResponse
1669 RequestCommand
.BOOT_NOTIFICATION
,
1671 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1672 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1673 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1674 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1675 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1676 iccid
: this.bootNotificationRequest
.iccid
,
1677 imsi
: this.bootNotificationRequest
.imsi
,
1678 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1679 meterType
: this.bootNotificationRequest
.meterType
,
1681 { skipBufferingOnError
: true }
1684 // Start WebSocket ping
1685 this.startWebSocketPing();
1687 this.startHeartbeat();
1688 // Initialize connectors status
1689 for (const connectorId
of this.connectors
.keys()) {
1690 if (connectorId
=== 0) {
1694 !this.getConnectorStatus(connectorId
)?.status &&
1695 this.getConnectorStatus(connectorId
)?.bootStatus
1697 // Send status in template at startup
1698 await this.ocppRequestService
.requestHandler
<
1699 StatusNotificationRequest
,
1700 StatusNotificationResponse
1701 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1703 status: this.getConnectorStatus(connectorId
).bootStatus
,
1704 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1706 this.getConnectorStatus(connectorId
).status =
1707 this.getConnectorStatus(connectorId
).bootStatus
;
1710 this.getConnectorStatus(connectorId
)?.status &&
1711 this.getConnectorStatus(connectorId
)?.bootStatus
1713 // Send status in template after reset
1714 await this.ocppRequestService
.requestHandler
<
1715 StatusNotificationRequest
,
1716 StatusNotificationResponse
1717 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1719 status: this.getConnectorStatus(connectorId
).bootStatus
,
1720 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1722 this.getConnectorStatus(connectorId
).status =
1723 this.getConnectorStatus(connectorId
).bootStatus
;
1724 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1725 // Send previous status at template reload
1726 await this.ocppRequestService
.requestHandler
<
1727 StatusNotificationRequest
,
1728 StatusNotificationResponse
1729 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1731 status: this.getConnectorStatus(connectorId
).status,
1732 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1735 // Send default status
1736 await this.ocppRequestService
.requestHandler
<
1737 StatusNotificationRequest
,
1738 StatusNotificationResponse
1739 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1741 status: ChargePointStatus
.AVAILABLE
,
1742 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1744 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1748 this.startAutomaticTransactionGenerator();
1751 private startAutomaticTransactionGenerator() {
1752 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
) {
1753 if (!this.automaticTransactionGenerator
) {
1754 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
1755 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
1759 if (!this.automaticTransactionGenerator
.started
) {
1760 this.automaticTransactionGenerator
.start();
1765 private stopAutomaticTransactionGenerator(): void {
1766 if (this.automaticTransactionGenerator
?.started
) {
1767 this.automaticTransactionGenerator
.stop();
1768 this.automaticTransactionGenerator
= null;
1772 private async stopMessageSequence(
1773 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1775 // Stop WebSocket ping
1776 this.stopWebSocketPing();
1778 this.stopHeartbeat();
1779 // Stop ongoing transactions
1780 if (this.automaticTransactionGenerator
?.configuration
?.enable
) {
1781 this.stopAutomaticTransactionGenerator();
1783 for (const connectorId
of this.connectors
.keys()) {
1784 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1785 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1787 this.getBeginEndMeterValues() &&
1788 this.getOcppStrictCompliance() &&
1789 !this.getOutOfOrderEndMeterValues()
1791 // FIXME: Implement OCPP version agnostic helpers
1792 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1795 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1797 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
1799 RequestCommand
.METER_VALUES
,
1803 meterValue
: [transactionEndMeterValue
],
1807 await this.ocppRequestService
.requestHandler
<
1808 StopTransactionRequest
,
1809 StopTransactionResponse
1810 >(this, RequestCommand
.STOP_TRANSACTION
, {
1812 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1813 idTag
: this.getTransactionIdTag(transactionId
),
1821 private startWebSocketPing(): void {
1822 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1824 StandardParametersKey
.WebSocketPingInterval
1826 ? Utils
.convertToInt(
1827 ChargingStationConfigurationUtils
.getConfigurationKey(
1829 StandardParametersKey
.WebSocketPingInterval
1833 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1834 this.webSocketPingSetInterval
= setInterval(() => {
1835 if (this.isWebSocketConnectionOpened()) {
1836 this.wsConnection
.ping((): void => {
1837 /* This is intentional */
1840 }, webSocketPingInterval
* 1000);
1843 ' WebSocket ping started every ' +
1844 Utils
.formatDurationSeconds(webSocketPingInterval
)
1846 } else if (this.webSocketPingSetInterval
) {
1849 ' WebSocket ping every ' +
1850 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1855 `${this.logPrefix()} WebSocket ping interval set to ${
1856 webSocketPingInterval
1857 ? Utils.formatDurationSeconds(webSocketPingInterval)
1858 : webSocketPingInterval
1859 }, not starting the WebSocket ping`
1864 private stopWebSocketPing(): void {
1865 if (this.webSocketPingSetInterval
) {
1866 clearInterval(this.webSocketPingSetInterval
);
1870 private getConfiguredSupervisionUrl(): URL
{
1871 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1872 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1874 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1876 switch (Configuration
.getSupervisionUrlDistribution()) {
1877 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1878 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1880 case SupervisionUrlDistribution
.RANDOM
:
1882 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1884 case SupervisionUrlDistribution
.SEQUENTIAL
:
1885 if (this.index
<= supervisionUrls
.length
) {
1886 urlIndex
= this.index
- 1;
1889 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1895 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1896 SupervisionUrlDistribution.ROUND_ROBIN
1899 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1902 return new URL(supervisionUrls
[urlIndex
]);
1904 return new URL(supervisionUrls
as string);
1907 private getHeartbeatInterval(): number | undefined {
1908 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1910 StandardParametersKey
.HeartbeatInterval
1912 if (HeartbeatInterval
) {
1913 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1915 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1917 StandardParametersKey
.HeartBeatInterval
1919 if (HeartBeatInterval
) {
1920 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1922 !this.stationInfo
?.autoRegister
&&
1924 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1925 Constants.DEFAULT_HEARTBEAT_INTERVAL
1928 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1931 private stopHeartbeat(): void {
1932 if (this.heartbeatSetInterval
) {
1933 clearInterval(this.heartbeatSetInterval
);
1937 private terminateWSConnection(): void {
1938 if (this.isWebSocketConnectionOpened()) {
1939 this.wsConnection
.terminate();
1940 this.wsConnection
= null;
1944 private stopMeterValues(connectorId
: number) {
1945 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1946 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1950 private getReconnectExponentialDelay(): boolean | undefined {
1951 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1952 ? this.stationInfo
.reconnectExponentialDelay
1956 private async reconnect(code
: number): Promise
<void> {
1957 // Stop WebSocket ping
1958 this.stopWebSocketPing();
1960 this.stopHeartbeat();
1961 // Stop the ATG if needed
1962 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
) {
1963 this.stopAutomaticTransactionGenerator();
1966 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1967 this.getAutoReconnectMaxRetries() === -1
1969 this.autoReconnectRetryCount
++;
1970 const reconnectDelay
= this.getReconnectExponentialDelay()
1971 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1972 : this.getConnectionTimeout() * 1000;
1973 const reconnectDelayWithdraw
= 1000;
1974 const reconnectTimeout
=
1975 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
1976 ? reconnectDelay
- reconnectDelayWithdraw
1979 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1982 )}ms, timeout ${reconnectTimeout}ms`
1984 await Utils
.sleep(reconnectDelay
);
1987 ' WebSocket: reconnecting try #' +
1988 this.autoReconnectRetryCount
.toString()
1990 this.openWSConnection(
1991 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
1992 { closeOpened
: true }
1994 this.wsConnectionRestarted
= true;
1995 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1997 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
1998 this.autoReconnectRetryCount
1999 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2004 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
2005 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2008 private initializeConnectorStatus(connectorId
: number): void {
2009 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2010 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2011 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2012 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2013 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2014 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;