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 readonly templateFile
: string;
88 public authorizedTagsCache
: AuthorizedTagsCache
;
89 public stationInfo
!: ChargingStationInfo
;
90 public stopped
: boolean;
91 public readonly connectors
: Map
<number, ConnectorStatus
>;
92 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
93 public wsConnection
!: WebSocket
;
94 public readonly requests
: Map
<string, CachedRequest
>;
95 public performanceStatistics
!: PerformanceStatistics
;
96 public heartbeatSetInterval
!: NodeJS
.Timeout
;
97 public ocppRequestService
!: OCPPRequestService
;
98 public bootNotificationRequest
!: BootNotificationRequest
;
99 public bootNotificationResponse
!: BootNotificationResponse
| null;
100 public powerDivider
!: number;
101 private readonly index
: number;
102 private configurationFile
!: string;
103 private configurationFileHash
!: string;
104 private connectorsConfigurationHash
!: string;
105 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
106 private readonly messageBuffer
: Set
<string>;
107 private configuredSupervisionUrl
!: URL
;
108 private wsConnectionRestarted
: boolean;
109 private autoReconnectRetryCount
: number;
110 private templateFileWatcher
!: fs
.FSWatcher
;
111 private readonly sharedLRUCache
: SharedLRUCache
;
112 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
113 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
114 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
116 constructor(index
: number, templateFile
: string) {
118 this.templateFile
= templateFile
;
119 this.stopped
= false;
120 this.wsConnectionRestarted
= false;
121 this.autoReconnectRetryCount
= 0;
122 this.sharedLRUCache
= SharedLRUCache
.getInstance();
123 this.authorizedTagsCache
= AuthorizedTagsCache
.getInstance();
124 this.connectors
= new Map
<number, ConnectorStatus
>();
125 this.requests
= new Map
<string, CachedRequest
>();
126 this.messageBuffer
= new Set
<string>();
127 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
132 private get
wsConnectionUrl(): URL
{
134 (this.getSupervisionUrlOcppConfiguration()
135 ? ChargingStationConfigurationUtils
.getConfigurationKey(
137 this.getSupervisionUrlOcppKey()
139 : this.configuredSupervisionUrl
.href
) +
141 this.stationInfo
.chargingStationId
145 public logPrefix(): string {
146 return Utils
.logPrefix(
148 this?.stationInfo?.chargingStationId ??
149 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
154 public getRandomIdTag(): string {
155 const authorizationFile
= ChargingStationUtils
.getAuthorizationFile(this.stationInfo
);
156 const index
= Math.floor(
157 Utils
.secureRandom() * this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
).length
159 return this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
)[index
];
162 public hasAuthorizedTags(): boolean {
163 return !Utils
.isEmptyArray(
164 this.authorizedTagsCache
.getAuthorizedTags(
165 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
)
170 public getEnableStatistics(): boolean | undefined {
171 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
172 ? this.stationInfo
.enableStatistics
176 public getMustAuthorizeAtRemoteStart(): boolean | undefined {
177 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
180 public getPayloadSchemaValidation(): boolean | undefined {
181 return this.stationInfo
.payloadSchemaValidation
?? true;
184 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
185 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
186 switch (this.getCurrentOutType(stationInfo
)) {
188 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
189 ? localStationInfo
.numberOfPhases
196 public isWebSocketConnectionOpened(): boolean {
197 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
200 public getRegistrationStatus(): RegistrationStatus
{
201 return this?.bootNotificationResponse
?.status;
204 public isInUnknownState(): boolean {
205 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
208 public isInPendingState(): boolean {
209 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
212 public isInAcceptedState(): boolean {
213 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
216 public isInRejectedState(): boolean {
217 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
220 public isRegistered(): boolean {
221 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
224 public isChargingStationAvailable(): boolean {
225 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
228 public isConnectorAvailable(id
: number): boolean {
229 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
232 public getNumberOfConnectors(): number {
233 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
236 public getConnectorStatus(id
: number): ConnectorStatus
{
237 return this.connectors
.get(id
);
240 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
241 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
;
244 public getOcppStrictCompliance(): boolean {
245 return this.stationInfo
?.ocppStrictCompliance
?? false;
248 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
249 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
250 this.getCurrentOutType(stationInfo
),
254 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
255 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
256 ? localStationInfo
.voltageOut
260 public getConnectorMaximumAvailablePower(connectorId
: number): number {
261 let connectorAmperageLimitationPowerLimit
: number;
263 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
264 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
266 connectorAmperageLimitationPowerLimit
=
267 (this.getCurrentOutType() === CurrentType
.AC
268 ? ACElectricUtils
.powerTotal(
269 this.getNumberOfPhases(),
270 this.getVoltageOut(),
271 this.getAmperageLimitation() * this.getNumberOfConnectors()
273 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
276 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
277 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
279 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
280 isNaN(connectorAmperageLimitationPowerLimit
)
282 : connectorAmperageLimitationPowerLimit
,
283 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
287 public getTransactionIdTag(transactionId
: number): string | undefined {
288 for (const connectorId
of this.connectors
.keys()) {
289 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
290 return this.getConnectorStatus(connectorId
).transactionIdTag
;
295 public getOutOfOrderEndMeterValues(): boolean {
296 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
299 public getBeginEndMeterValues(): boolean {
300 return this.stationInfo
?.beginEndMeterValues
?? false;
303 public getMeteringPerTransaction(): boolean {
304 return this.stationInfo
?.meteringPerTransaction
?? true;
307 public getTransactionDataMeterValues(): boolean {
308 return this.stationInfo
?.transactionDataMeterValues
?? false;
311 public getMainVoltageMeterValues(): boolean {
312 return this.stationInfo
?.mainVoltageMeterValues
?? true;
315 public getPhaseLineToLineVoltageMeterValues(): boolean {
316 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
319 public getCustomValueLimitationMeterValues(): boolean {
320 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
323 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
324 for (const connectorId
of this.connectors
.keys()) {
327 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
334 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number {
335 const transactionConnectorStatus
= this.getConnectorStatus(
336 this.getConnectorIdByTransactionId(transactionId
)
338 if (this.getMeteringPerTransaction()) {
339 return transactionConnectorStatus
?.transactionEnergyActiveImportRegisterValue
?? 0;
341 return transactionConnectorStatus
?.energyActiveImportRegisterValue
?? 0;
344 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number {
345 const connectorStatus
= this.getConnectorStatus(connectorId
);
346 if (this.getMeteringPerTransaction()) {
347 return connectorStatus
?.transactionEnergyActiveImportRegisterValue
?? 0;
349 return connectorStatus
?.energyActiveImportRegisterValue
?? 0;
352 public getAuthorizeRemoteTxRequests(): boolean {
353 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
355 StandardParametersKey
.AuthorizeRemoteTxRequests
357 return authorizeRemoteTxRequests
358 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
362 public getLocalAuthListEnabled(): boolean {
363 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
365 StandardParametersKey
.LocalAuthListEnabled
367 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
370 public startHeartbeat(): void {
372 this.getHeartbeatInterval() &&
373 this.getHeartbeatInterval() > 0 &&
374 !this.heartbeatSetInterval
376 // eslint-disable-next-line @typescript-eslint/no-misused-promises
377 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
378 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
380 RequestCommand
.HEARTBEAT
382 }, this.getHeartbeatInterval());
385 ' Heartbeat started every ' +
386 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
388 } else if (this.heartbeatSetInterval
) {
391 ' Heartbeat already started every ' +
392 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
396 `${this.logPrefix()} Heartbeat interval set to ${
397 this.getHeartbeatInterval()
398 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
399 : this.getHeartbeatInterval()
400 }, not starting the heartbeat`
405 public restartHeartbeat(): void {
407 this.stopHeartbeat();
409 this.startHeartbeat();
412 public restartWebSocketPing(): void {
413 // Stop WebSocket ping
414 this.stopWebSocketPing();
415 // Start WebSocket ping
416 this.startWebSocketPing();
419 public startMeterValues(connectorId
: number, interval
: number): void {
420 if (connectorId
=== 0) {
422 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
426 if (!this.getConnectorStatus(connectorId
)) {
428 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
432 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
434 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
438 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
439 !this.getConnectorStatus(connectorId
)?.transactionId
442 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
447 // eslint-disable-next-line @typescript-eslint/no-misused-promises
448 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
449 // eslint-disable-next-line @typescript-eslint/no-misused-promises
450 async (): Promise
<void> => {
451 // FIXME: Implement OCPP version agnostic helpers
452 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
455 this.getConnectorStatus(connectorId
).transactionId
,
458 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
460 RequestCommand
.METER_VALUES
,
463 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
464 meterValue
: [meterValue
],
472 `${this.logPrefix()} Charging station ${
473 StandardParametersKey.MeterValueSampleInterval
474 } configuration set to ${
475 interval ? Utils.formatDurationMilliSeconds(interval) : interval
476 }, not sending MeterValues`
481 public start(): void {
482 if (this.getEnableStatistics()) {
483 this.performanceStatistics
.start();
485 this.openWSConnection();
486 // Monitor charging station template file
487 this.templateFileWatcher
= FileUtils
.watchJsonFile(
489 FileType
.ChargingStationTemplate
,
492 (event
, filename
): void => {
493 if (filename
&& event
=== 'change') {
496 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
498 } file have changed, reload`
500 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
504 this.stopAutomaticTransactionGenerator();
505 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
) {
506 this.startAutomaticTransactionGenerator();
508 if (this.getEnableStatistics()) {
509 this.performanceStatistics
.restart();
511 this.performanceStatistics
.stop();
513 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
516 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
523 parentPort
.postMessage(MessageChannelUtils
.buildStartedMessage(this));
526 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
527 // Stop message sequence
528 await this.stopMessageSequence(reason
);
529 for (const connectorId
of this.connectors
.keys()) {
530 if (connectorId
> 0) {
531 await this.ocppRequestService
.requestHandler
<
532 StatusNotificationRequest
,
533 StatusNotificationResponse
534 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
536 status: ChargePointStatus
.UNAVAILABLE
,
537 errorCode
: ChargePointErrorCode
.NO_ERROR
,
539 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
542 this.closeWSConnection();
543 if (this.getEnableStatistics()) {
544 this.performanceStatistics
.stop();
546 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
547 this.templateFileWatcher
.close();
548 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
549 this.bootNotificationResponse
= null;
551 parentPort
.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
554 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
555 await this.stop(reason
);
556 await Utils
.sleep(this.stationInfo
.resetTime
);
561 public saveOcppConfiguration(): void {
562 if (this.getOcppPersistentConfiguration()) {
563 this.saveConfiguration();
567 public getChargingProfilePowerLimit(connectorId
: number): number | undefined {
568 let limit
: number, matchingChargingProfile
: ChargingProfile
;
569 let chargingProfiles
: ChargingProfile
[] = [];
570 // Get charging profiles for connector and sort by stack level
571 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
572 (a
, b
) => b
.stackLevel
- a
.stackLevel
574 // Get profiles on connector 0
575 if (this.getConnectorStatus(0).chargingProfiles
) {
576 chargingProfiles
.push(
577 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
580 if (!Utils
.isEmptyArray(chargingProfiles
)) {
581 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
585 if (!Utils
.isNullOrUndefined(result
)) {
586 limit
= result
.limit
;
587 matchingChargingProfile
= result
.matchingChargingProfile
;
588 switch (this.getCurrentOutType()) {
591 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
592 ChargingRateUnitType
.WATT
594 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
598 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
599 ChargingRateUnitType
.WATT
601 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
604 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
605 if (limit
> connectorMaximumPower
) {
607 `${this.logPrefix()} Charging profile id ${
608 matchingChargingProfile.chargingProfileId
609 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
610 this.getConnectorStatus(connectorId
).chargingProfiles
612 limit
= connectorMaximumPower
;
619 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
620 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
622 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
624 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
626 if (Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
) === false) {
628 `${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`
630 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
632 let cpReplaced
= false;
633 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
634 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
635 (chargingProfile
: ChargingProfile
, index
: number) => {
637 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
638 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
639 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
641 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
647 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
650 public resetConnectorStatus(connectorId
: number): void {
651 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
652 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
653 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
654 this.getConnectorStatus(connectorId
).transactionStarted
= false;
655 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
656 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
657 delete this.getConnectorStatus(connectorId
).transactionId
;
658 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
659 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
660 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
661 this.stopMeterValues(connectorId
);
664 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
665 return ChargingStationConfigurationUtils
.getConfigurationKey(
667 StandardParametersKey
.SupportedFeatureProfiles
668 )?.value
.includes(featureProfile
);
671 public bufferMessage(message
: string): void {
672 this.messageBuffer
.add(message
);
675 public openWSConnection(
676 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
677 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
679 terminateOpened
: false,
682 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
683 params
.closeOpened
= params
?.closeOpened
?? false;
684 params
.terminateOpened
= params
?.terminateOpened
?? false;
686 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
687 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
689 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
691 if (params
?.closeOpened
) {
692 this.closeWSConnection();
694 if (params
?.terminateOpened
) {
695 this.terminateWSConnection();
697 let protocol
: string;
698 switch (this.getOcppVersion()) {
699 case OCPPVersion
.VERSION_16
:
700 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
703 this.handleUnsupportedVersion(this.getOcppVersion());
707 if (this.isWebSocketConnectionOpened()) {
709 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
715 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
718 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
720 // Handle WebSocket message
721 this.wsConnection
.on(
723 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
725 // Handle WebSocket error
726 this.wsConnection
.on(
728 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
730 // Handle WebSocket close
731 this.wsConnection
.on(
733 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
735 // Handle WebSocket open
736 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
737 // Handle WebSocket ping
738 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
739 // Handle WebSocket pong
740 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
743 public closeWSConnection(): void {
744 if (this.isWebSocketConnectionOpened()) {
745 this.wsConnection
.close();
746 this.wsConnection
= null;
750 public startAutomaticTransactionGenerator(): void {
751 if (!this.automaticTransactionGenerator
) {
752 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
753 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
757 if (!this.automaticTransactionGenerator
.started
) {
758 this.automaticTransactionGenerator
.start();
762 public stopAutomaticTransactionGenerator(): void {
763 if (this.automaticTransactionGenerator
?.started
) {
764 this.automaticTransactionGenerator
.stop();
765 this.automaticTransactionGenerator
= null;
769 private flushMessageBuffer(): void {
770 if (this.messageBuffer
.size
> 0) {
771 this.messageBuffer
.forEach((message
) => {
772 // TODO: evaluate the need to track performance
773 this.wsConnection
.send(message
);
774 this.messageBuffer
.delete(message
);
779 private getSupervisionUrlOcppConfiguration(): boolean {
780 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
783 private getSupervisionUrlOcppKey(): string {
784 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
787 private getTemplateFromFile(): ChargingStationTemplate
| null {
788 let template
: ChargingStationTemplate
= null;
790 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
791 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
793 const measureId
= `${FileType.ChargingStationTemplate} read`;
794 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
795 template
= JSON
.parse(
796 fs
.readFileSync(this.templateFile
, 'utf8')
797 ) as ChargingStationTemplate
;
798 PerformanceStatistics
.endMeasure(measureId
, beginId
);
799 template
.templateHash
= crypto
800 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
801 .update(JSON
.stringify(template
))
803 this.sharedLRUCache
.setChargingStationTemplate(template
);
806 FileUtils
.handleFileException(
808 FileType
.ChargingStationTemplate
,
810 error
as NodeJS
.ErrnoException
816 private getStationInfoFromTemplate(): ChargingStationInfo
{
817 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
818 if (Utils
.isNullOrUndefined(stationTemplate
)) {
819 const errorMsg
= 'Failed to read charging station template file';
820 logger
.error(`${this.logPrefix()} ${errorMsg}`);
821 throw new BaseError(errorMsg
);
823 if (Utils
.isEmptyObject(stationTemplate
)) {
824 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
825 logger
.error(`${this.logPrefix()} ${errorMsg}`);
826 throw new BaseError(errorMsg
);
828 // Deprecation template keys section
829 ChargingStationUtils
.warnDeprecatedTemplateKey(
834 "Use 'supervisionUrls' instead"
836 ChargingStationUtils
.convertDeprecatedTemplateKey(
841 const stationInfo
: ChargingStationInfo
=
842 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
843 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, 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.stationInfo
= this.getStationInfo();
954 this.saveStationInfo();
955 logger
.info(`${this.logPrefix()} Charging station hashId '${this.stationInfo.hashId}'`);
956 this.configurationFile
= path
.join(
957 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
958 this.stationInfo
.hashId
+ '.json'
960 // Avoid duplication of connectors related information in RAM
961 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
962 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
963 if (this.getEnableStatistics()) {
964 this.performanceStatistics
= PerformanceStatistics
.getInstance(
965 this.stationInfo
.hashId
,
966 this.stationInfo
.chargingStationId
,
967 this.configuredSupervisionUrl
970 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
973 this.powerDivider
= this.getPowerDivider();
974 // OCPP configuration
975 this.ocppConfiguration
= this.getOcppConfiguration();
976 this.initializeOcppConfiguration();
977 switch (this.getOcppVersion()) {
978 case OCPPVersion
.VERSION_16
:
979 this.ocppIncomingRequestService
=
980 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
981 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
982 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
986 this.handleUnsupportedVersion(this.getOcppVersion());
989 if (this.stationInfo
?.autoRegister
) {
990 this.bootNotificationResponse
= {
991 currentTime
: new Date().toISOString(),
992 interval
: this.getHeartbeatInterval() / 1000,
993 status: RegistrationStatus
.ACCEPTED
,
998 private initializeOcppConfiguration(): void {
1000 !ChargingStationConfigurationUtils
.getConfigurationKey(
1002 StandardParametersKey
.HeartbeatInterval
1005 ChargingStationConfigurationUtils
.addConfigurationKey(
1007 StandardParametersKey
.HeartbeatInterval
,
1012 !ChargingStationConfigurationUtils
.getConfigurationKey(
1014 StandardParametersKey
.HeartBeatInterval
1017 ChargingStationConfigurationUtils
.addConfigurationKey(
1019 StandardParametersKey
.HeartBeatInterval
,
1025 this.getSupervisionUrlOcppConfiguration() &&
1026 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1028 ChargingStationConfigurationUtils
.addConfigurationKey(
1030 this.getSupervisionUrlOcppKey(),
1031 this.configuredSupervisionUrl
.href
,
1035 !this.getSupervisionUrlOcppConfiguration() &&
1036 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1038 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1040 this.getSupervisionUrlOcppKey(),
1045 this.stationInfo
.amperageLimitationOcppKey
&&
1046 !ChargingStationConfigurationUtils
.getConfigurationKey(
1048 this.stationInfo
.amperageLimitationOcppKey
1051 ChargingStationConfigurationUtils
.addConfigurationKey(
1053 this.stationInfo
.amperageLimitationOcppKey
,
1055 this.stationInfo
.maximumAmperage
*
1056 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1061 !ChargingStationConfigurationUtils
.getConfigurationKey(
1063 StandardParametersKey
.SupportedFeatureProfiles
1066 ChargingStationConfigurationUtils
.addConfigurationKey(
1068 StandardParametersKey
.SupportedFeatureProfiles
,
1069 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1072 ChargingStationConfigurationUtils
.addConfigurationKey(
1074 StandardParametersKey
.NumberOfConnectors
,
1075 this.getNumberOfConnectors().toString(),
1080 !ChargingStationConfigurationUtils
.getConfigurationKey(
1082 StandardParametersKey
.MeterValuesSampledData
1085 ChargingStationConfigurationUtils
.addConfigurationKey(
1087 StandardParametersKey
.MeterValuesSampledData
,
1088 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1092 !ChargingStationConfigurationUtils
.getConfigurationKey(
1094 StandardParametersKey
.ConnectorPhaseRotation
1097 const connectorPhaseRotation
= [];
1098 for (const connectorId
of this.connectors
.keys()) {
1100 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1101 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1102 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1103 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1105 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1106 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1107 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1108 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1111 ChargingStationConfigurationUtils
.addConfigurationKey(
1113 StandardParametersKey
.ConnectorPhaseRotation
,
1114 connectorPhaseRotation
.toString()
1118 !ChargingStationConfigurationUtils
.getConfigurationKey(
1120 StandardParametersKey
.AuthorizeRemoteTxRequests
1123 ChargingStationConfigurationUtils
.addConfigurationKey(
1125 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1130 !ChargingStationConfigurationUtils
.getConfigurationKey(
1132 StandardParametersKey
.LocalAuthListEnabled
1134 ChargingStationConfigurationUtils
.getConfigurationKey(
1136 StandardParametersKey
.SupportedFeatureProfiles
1137 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1139 ChargingStationConfigurationUtils
.addConfigurationKey(
1141 StandardParametersKey
.LocalAuthListEnabled
,
1146 !ChargingStationConfigurationUtils
.getConfigurationKey(
1148 StandardParametersKey
.ConnectionTimeOut
1151 ChargingStationConfigurationUtils
.addConfigurationKey(
1153 StandardParametersKey
.ConnectionTimeOut
,
1154 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1157 this.saveOcppConfiguration();
1160 private initializeConnectors(
1161 stationInfo
: ChargingStationInfo
,
1162 configuredMaxConnectors
: number,
1163 templateMaxConnectors
: number
1165 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1166 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1167 logger
.error(`${this.logPrefix()} ${logMsg}`);
1168 throw new BaseError(logMsg
);
1170 if (!stationInfo
?.Connectors
[0]) {
1172 `${this.logPrefix()} Charging station information from template ${
1174 } with no connector Id 0 configuration`
1177 if (stationInfo
?.Connectors
) {
1178 const connectorsConfigHash
= crypto
1179 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1180 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1182 const connectorsConfigChanged
=
1183 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1184 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1185 connectorsConfigChanged
&& this.connectors
.clear();
1186 this.connectorsConfigurationHash
= connectorsConfigHash
;
1187 // Add connector Id 0
1188 let lastConnector
= '0';
1189 for (lastConnector
in stationInfo
?.Connectors
) {
1190 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1192 lastConnectorId
=== 0 &&
1193 this.getUseConnectorId0(stationInfo
) &&
1194 stationInfo
?.Connectors
[lastConnector
]
1196 this.connectors
.set(
1198 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1200 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1201 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1202 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1206 // Generate all connectors
1207 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1208 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1209 const randConnectorId
= stationInfo
?.randomConnectors
1210 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1212 this.connectors
.set(
1214 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1216 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1217 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1218 this.getConnectorStatus(index
).chargingProfiles
= [];
1225 `${this.logPrefix()} Charging station information from template ${
1227 } with no connectors configuration defined, using already defined connectors`
1230 // Initialize transaction attributes on connectors
1231 for (const connectorId
of this.connectors
.keys()) {
1232 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1233 this.initializeConnectorStatus(connectorId
);
1238 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1239 let configuration
: ChargingStationConfiguration
= null;
1240 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1242 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1243 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1244 this.configurationFileHash
1247 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1248 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1249 configuration
= JSON
.parse(
1250 fs
.readFileSync(this.configurationFile
, 'utf8')
1251 ) as ChargingStationConfiguration
;
1252 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1253 this.configurationFileHash
= configuration
.configurationHash
;
1254 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1257 FileUtils
.handleFileException(
1259 FileType
.ChargingStationConfiguration
,
1260 this.configurationFile
,
1261 error
as NodeJS
.ErrnoException
1265 return configuration
;
1268 private saveConfiguration(): void {
1269 if (this.configurationFile
) {
1271 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1272 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1274 const configurationData
: ChargingStationConfiguration
=
1275 this.getConfigurationFromFile() ?? {};
1276 this.ocppConfiguration
?.configurationKey
&&
1277 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1278 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1279 delete configurationData
.configurationHash
;
1280 const configurationHash
= crypto
1281 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1282 .update(JSON
.stringify(configurationData
))
1284 if (this.configurationFileHash
!== configurationHash
) {
1285 configurationData
.configurationHash
= configurationHash
;
1286 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1287 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1288 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1289 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1290 fs
.closeSync(fileDescriptor
);
1291 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1292 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1293 this.configurationFileHash
= configurationHash
;
1294 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1297 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1298 this.configurationFile
1303 FileUtils
.handleFileException(
1305 FileType
.ChargingStationConfiguration
,
1306 this.configurationFile
,
1307 error
as NodeJS
.ErrnoException
1312 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1317 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1318 return this.getTemplateFromFile()?.Configuration
?? null;
1321 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1322 let configuration
: ChargingStationConfiguration
= null;
1323 if (this.getOcppPersistentConfiguration()) {
1324 const configurationFromFile
= this.getConfigurationFromFile();
1325 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1327 configuration
&& delete configuration
.stationInfo
;
1328 return configuration
;
1331 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1332 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1333 if (!ocppConfiguration
) {
1334 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1336 return ocppConfiguration
;
1339 private async onOpen(): Promise
<void> {
1340 if (this.isWebSocketConnectionOpened()) {
1342 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1344 if (!this.isRegistered()) {
1345 // Send BootNotification
1346 let registrationRetryCount
= 0;
1348 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1349 BootNotificationRequest
,
1350 BootNotificationResponse
1353 RequestCommand
.BOOT_NOTIFICATION
,
1355 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1356 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1357 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1358 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1359 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1360 iccid
: this.bootNotificationRequest
.iccid
,
1361 imsi
: this.bootNotificationRequest
.imsi
,
1362 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1363 meterType
: this.bootNotificationRequest
.meterType
,
1365 { skipBufferingOnError
: true }
1367 if (!this.isRegistered()) {
1368 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1370 this.bootNotificationResponse
?.interval
1371 ? this.bootNotificationResponse
.interval
* 1000
1372 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1376 !this.isRegistered() &&
1377 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1378 this.getRegistrationMaxRetries() === -1)
1381 if (this.isRegistered()) {
1382 if (this.isInAcceptedState()) {
1383 await this.startMessageSequence();
1384 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1388 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1391 this.stopped
&& (this.stopped
= false);
1392 this.autoReconnectRetryCount
= 0;
1393 this.wsConnectionRestarted
= false;
1396 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1401 private async onClose(code
: number, reason
: string): Promise
<void> {
1404 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1405 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1407 `${this.logPrefix()} WebSocket normally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1409 )}' and reason '${reason}'`
1411 this.autoReconnectRetryCount
= 0;
1416 `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1418 )}' and reason '${reason}'`
1420 await this.reconnect(code
);
1425 private async onMessage(data
: Data
): Promise
<void> {
1426 let messageType
: number;
1427 let messageId
: string;
1428 let commandName
: IncomingRequestCommand
;
1429 let commandPayload
: JsonType
;
1430 let errorType
: ErrorType
;
1431 let errorMessage
: string;
1432 let errorDetails
: JsonType
;
1433 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1434 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1435 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1436 let requestPayload
: JsonType
;
1437 let cachedRequest
: CachedRequest
;
1440 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1441 if (Array.isArray(request
) === true) {
1442 [messageType
, messageId
] = request
;
1443 // Check the type of message
1444 switch (messageType
) {
1446 case MessageType
.CALL_MESSAGE
:
1447 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1448 if (this.getEnableStatistics()) {
1449 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1452 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1456 // Process the message
1457 await this.ocppIncomingRequestService
.incomingRequestHandler(
1465 case MessageType
.CALL_RESULT_MESSAGE
:
1466 [, , commandPayload
] = request
as Response
;
1467 if (!this.requests
.has(messageId
)) {
1469 throw new OCPPError(
1470 ErrorType
.INTERNAL_ERROR
,
1471 `Response for unknown message id ${messageId}`,
1477 cachedRequest
= this.requests
.get(messageId
);
1478 if (Array.isArray(cachedRequest
) === true) {
1479 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1481 throw new OCPPError(
1482 ErrorType
.PROTOCOL_ERROR
,
1483 `Cached request for message id ${messageId} response is not an array`,
1485 cachedRequest
as unknown
as JsonType
1489 `${this.logPrefix()} << Command '${
1490 requestCommandName ?? 'unknown'
1491 }' received response payload: ${JSON.stringify(request)}`
1493 responseCallback(commandPayload
, requestPayload
);
1496 case MessageType
.CALL_ERROR_MESSAGE
:
1497 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1498 if (!this.requests
.has(messageId
)) {
1500 throw new OCPPError(
1501 ErrorType
.INTERNAL_ERROR
,
1502 `Error response for unknown message id ${messageId}`,
1504 { errorType
, errorMessage
, errorDetails
}
1507 cachedRequest
= this.requests
.get(messageId
);
1508 if (Array.isArray(cachedRequest
) === true) {
1509 [, errorCallback
, requestCommandName
] = cachedRequest
;
1511 throw new OCPPError(
1512 ErrorType
.PROTOCOL_ERROR
,
1513 `Cached request for message id ${messageId} error response is not an array`,
1515 cachedRequest
as unknown
as JsonType
1519 `${this.logPrefix()} << Command '${
1520 requestCommandName ?? 'unknown'
1521 }' received error payload: ${JSON.stringify(request)}`
1523 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1527 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1528 errMsg
= `Wrong message type ${messageType}`;
1529 logger
.error(`${this.logPrefix()} ${errMsg}`);
1530 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1532 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1534 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1541 `${this.logPrefix()} Incoming OCPP command '${
1542 commandName ?? requestCommandName ?? null
1543 }' message '${data.toString()}' matching cached request '${JSON.stringify(
1544 this.requests.get(messageId)
1545 )}' processing error:`,
1548 if (!(error
instanceof OCPPError
)) {
1550 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1551 commandName ?? requestCommandName ?? null
1552 }' message '${data.toString()}' handling is not an OCPPError:`,
1557 messageType
=== MessageType
.CALL_MESSAGE
&&
1558 (await this.ocppRequestService
.sendError(
1562 commandName
?? requestCommandName
?? null
1567 private onPing(): void {
1568 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1571 private onPong(): void {
1572 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1575 private onError(error
: WSError
): void {
1576 this.closeWSConnection();
1577 logger
.error(this.logPrefix() + ' WebSocket error:', error
);
1580 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean | undefined {
1581 const localStationInfo
= stationInfo
?? this.stationInfo
;
1582 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1583 ? localStationInfo
.useConnectorId0
1587 private getNumberOfRunningTransactions(): number {
1589 for (const connectorId
of this.connectors
.keys()) {
1590 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1598 private getConnectionTimeout(): number | undefined {
1600 ChargingStationConfigurationUtils
.getConfigurationKey(
1602 StandardParametersKey
.ConnectionTimeOut
1607 ChargingStationConfigurationUtils
.getConfigurationKey(
1609 StandardParametersKey
.ConnectionTimeOut
1611 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1614 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1617 // -1 for unlimited, 0 for disabling
1618 private getAutoReconnectMaxRetries(): number | undefined {
1619 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1620 return this.stationInfo
.autoReconnectMaxRetries
;
1622 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1623 return Configuration
.getAutoReconnectMaxRetries();
1629 private getRegistrationMaxRetries(): number | undefined {
1630 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1631 return this.stationInfo
.registrationMaxRetries
;
1636 private getPowerDivider(): number {
1637 let powerDivider
= this.getNumberOfConnectors();
1638 if (this.stationInfo
?.powerSharedByConnectors
) {
1639 powerDivider
= this.getNumberOfRunningTransactions();
1641 return powerDivider
;
1644 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1645 const localStationInfo
= stationInfo
?? this.stationInfo
;
1646 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1649 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1650 const maximumPower
= this.getMaximumPower(stationInfo
);
1651 switch (this.getCurrentOutType(stationInfo
)) {
1652 case CurrentType
.AC
:
1653 return ACElectricUtils
.amperagePerPhaseFromPower(
1654 this.getNumberOfPhases(stationInfo
),
1655 maximumPower
/ this.getNumberOfConnectors(),
1656 this.getVoltageOut(stationInfo
)
1658 case CurrentType
.DC
:
1659 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1663 private getAmperageLimitation(): number | undefined {
1665 this.stationInfo
.amperageLimitationOcppKey
&&
1666 ChargingStationConfigurationUtils
.getConfigurationKey(
1668 this.stationInfo
.amperageLimitationOcppKey
1673 ChargingStationConfigurationUtils
.getConfigurationKey(
1675 this.stationInfo
.amperageLimitationOcppKey
1677 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1682 private async startMessageSequence(): Promise
<void> {
1683 if (this.stationInfo
?.autoRegister
) {
1684 await this.ocppRequestService
.requestHandler
<
1685 BootNotificationRequest
,
1686 BootNotificationResponse
1689 RequestCommand
.BOOT_NOTIFICATION
,
1691 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1692 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1693 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1694 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1695 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1696 iccid
: this.bootNotificationRequest
.iccid
,
1697 imsi
: this.bootNotificationRequest
.imsi
,
1698 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1699 meterType
: this.bootNotificationRequest
.meterType
,
1701 { skipBufferingOnError
: true }
1704 // Start WebSocket ping
1705 this.startWebSocketPing();
1707 this.startHeartbeat();
1708 // Initialize connectors status
1709 for (const connectorId
of this.connectors
.keys()) {
1710 if (connectorId
=== 0) {
1714 !this.getConnectorStatus(connectorId
)?.status &&
1715 this.getConnectorStatus(connectorId
)?.bootStatus
1717 // Send status in template at startup
1718 await this.ocppRequestService
.requestHandler
<
1719 StatusNotificationRequest
,
1720 StatusNotificationResponse
1721 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1723 status: this.getConnectorStatus(connectorId
).bootStatus
,
1724 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1726 this.getConnectorStatus(connectorId
).status =
1727 this.getConnectorStatus(connectorId
).bootStatus
;
1730 this.getConnectorStatus(connectorId
)?.status &&
1731 this.getConnectorStatus(connectorId
)?.bootStatus
1733 // Send status in template after reset
1734 await this.ocppRequestService
.requestHandler
<
1735 StatusNotificationRequest
,
1736 StatusNotificationResponse
1737 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1739 status: this.getConnectorStatus(connectorId
).bootStatus
,
1740 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1742 this.getConnectorStatus(connectorId
).status =
1743 this.getConnectorStatus(connectorId
).bootStatus
;
1744 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1745 // Send previous status at template reload
1746 await this.ocppRequestService
.requestHandler
<
1747 StatusNotificationRequest
,
1748 StatusNotificationResponse
1749 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1751 status: this.getConnectorStatus(connectorId
).status,
1752 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1755 // Send default status
1756 await this.ocppRequestService
.requestHandler
<
1757 StatusNotificationRequest
,
1758 StatusNotificationResponse
1759 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1761 status: ChargePointStatus
.AVAILABLE
,
1762 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1764 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1768 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
) {
1769 this.startAutomaticTransactionGenerator();
1773 private async stopMessageSequence(
1774 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1776 // Stop WebSocket ping
1777 this.stopWebSocketPing();
1779 this.stopHeartbeat();
1780 // Stop ongoing transactions
1781 if (this.getNumberOfRunningTransactions() > 0) {
1782 if (this.automaticTransactionGenerator
?.started
) {
1783 this.stopAutomaticTransactionGenerator();
1785 for (const connectorId
of this.connectors
.keys()) {
1786 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1787 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1789 this.getBeginEndMeterValues() &&
1790 this.getOcppStrictCompliance() &&
1791 !this.getOutOfOrderEndMeterValues()
1793 // FIXME: Implement OCPP version agnostic helpers
1794 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1797 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1799 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
1801 RequestCommand
.METER_VALUES
,
1805 meterValue
: [transactionEndMeterValue
],
1809 await this.ocppRequestService
.requestHandler
<
1810 StopTransactionRequest
,
1811 StopTransactionResponse
1812 >(this, RequestCommand
.STOP_TRANSACTION
, {
1814 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1815 idTag
: this.getTransactionIdTag(transactionId
),
1824 private startWebSocketPing(): void {
1825 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1827 StandardParametersKey
.WebSocketPingInterval
1829 ? Utils
.convertToInt(
1830 ChargingStationConfigurationUtils
.getConfigurationKey(
1832 StandardParametersKey
.WebSocketPingInterval
1836 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1837 this.webSocketPingSetInterval
= setInterval(() => {
1838 if (this.isWebSocketConnectionOpened()) {
1839 this.wsConnection
.ping((): void => {
1840 /* This is intentional */
1843 }, webSocketPingInterval
* 1000);
1846 ' WebSocket ping started every ' +
1847 Utils
.formatDurationSeconds(webSocketPingInterval
)
1849 } else if (this.webSocketPingSetInterval
) {
1852 ' WebSocket ping every ' +
1853 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1858 `${this.logPrefix()} WebSocket ping interval set to ${
1859 webSocketPingInterval
1860 ? Utils.formatDurationSeconds(webSocketPingInterval)
1861 : webSocketPingInterval
1862 }, not starting the WebSocket ping`
1867 private stopWebSocketPing(): void {
1868 if (this.webSocketPingSetInterval
) {
1869 clearInterval(this.webSocketPingSetInterval
);
1873 private getConfiguredSupervisionUrl(): URL
{
1874 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1875 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1877 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1879 switch (Configuration
.getSupervisionUrlDistribution()) {
1880 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1881 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1883 case SupervisionUrlDistribution
.RANDOM
:
1885 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1887 case SupervisionUrlDistribution
.SEQUENTIAL
:
1888 if (this.index
<= supervisionUrls
.length
) {
1889 urlIndex
= this.index
- 1;
1892 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1898 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1899 SupervisionUrlDistribution.ROUND_ROBIN
1902 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1905 return new URL(supervisionUrls
[urlIndex
]);
1907 return new URL(supervisionUrls
as string);
1910 private getHeartbeatInterval(): number | undefined {
1911 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1913 StandardParametersKey
.HeartbeatInterval
1915 if (HeartbeatInterval
) {
1916 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1918 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1920 StandardParametersKey
.HeartBeatInterval
1922 if (HeartBeatInterval
) {
1923 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1925 !this.stationInfo
?.autoRegister
&&
1927 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1928 Constants.DEFAULT_HEARTBEAT_INTERVAL
1931 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1934 private stopHeartbeat(): void {
1935 if (this.heartbeatSetInterval
) {
1936 clearInterval(this.heartbeatSetInterval
);
1940 private terminateWSConnection(): void {
1941 if (this.isWebSocketConnectionOpened()) {
1942 this.wsConnection
.terminate();
1943 this.wsConnection
= null;
1947 private stopMeterValues(connectorId
: number) {
1948 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1949 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1953 private getReconnectExponentialDelay(): boolean | undefined {
1954 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1955 ? this.stationInfo
.reconnectExponentialDelay
1959 private async reconnect(code
: number): Promise
<void> {
1960 // Stop WebSocket ping
1961 this.stopWebSocketPing();
1963 this.stopHeartbeat();
1964 // Stop the ATG if needed
1965 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
) {
1966 this.stopAutomaticTransactionGenerator();
1969 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1970 this.getAutoReconnectMaxRetries() === -1
1972 this.autoReconnectRetryCount
++;
1973 const reconnectDelay
= this.getReconnectExponentialDelay()
1974 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1975 : this.getConnectionTimeout() * 1000;
1976 const reconnectDelayWithdraw
= 1000;
1977 const reconnectTimeout
=
1978 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
1979 ? reconnectDelay
- reconnectDelayWithdraw
1982 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1985 )}ms, timeout ${reconnectTimeout}ms`
1987 await Utils
.sleep(reconnectDelay
);
1990 ' WebSocket: reconnecting try #' +
1991 this.autoReconnectRetryCount
.toString()
1993 this.openWSConnection(
1994 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
1995 { closeOpened
: true }
1997 this.wsConnectionRestarted
= true;
1998 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2000 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2001 this.autoReconnectRetryCount
2002 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2007 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
2008 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2011 private initializeConnectorStatus(connectorId
: number): void {
2012 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2013 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2014 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2015 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2016 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2017 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;