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';
19 type ChargingStationTemplate
,
23 } from
'../types/ChargingStationTemplate';
24 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
25 import type { ConnectorStatus
} from
'../types/ConnectorStatus';
26 import { FileType
} from
'../types/FileType';
27 import type { JsonType
} from
'../types/JsonType';
28 import { ChargePointErrorCode
} from
'../types/ocpp/ChargePointErrorCode';
29 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
30 import { ChargingProfile
, ChargingRateUnitType
} from
'../types/ocpp/ChargingProfile';
32 ConnectorPhaseRotation
,
33 StandardParametersKey
,
34 SupportedFeatureProfiles
,
35 VendorDefaultParametersKey
,
36 } from
'../types/ocpp/Configuration';
37 import { ErrorType
} from
'../types/ocpp/ErrorType';
38 import { MessageType
} from
'../types/ocpp/MessageType';
39 import { MeterValue
, MeterValueMeasurand
} from
'../types/ocpp/MeterValues';
40 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
43 BootNotificationRequest
,
47 IncomingRequestCommand
,
50 StatusNotificationRequest
,
51 } from
'../types/ocpp/Requests';
53 BootNotificationResponse
,
59 StatusNotificationResponse
,
60 } from
'../types/ocpp/Responses';
62 StopTransactionReason
,
63 StopTransactionRequest
,
64 StopTransactionResponse
,
65 } from
'../types/ocpp/Transaction';
66 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
67 import Configuration from
'../utils/Configuration';
68 import Constants from
'../utils/Constants';
69 import { ACElectricUtils
, DCElectricUtils
} from
'../utils/ElectricUtils';
70 import FileUtils from
'../utils/FileUtils';
71 import logger from
'../utils/Logger';
72 import Utils from
'../utils/Utils';
73 import AuthorizedTagsCache from
'./AuthorizedTagsCache';
74 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
75 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
76 import { ChargingStationUtils
} from
'./ChargingStationUtils';
77 import ChargingStationWorkerBroadcastChannel from
'./ChargingStationWorkerBroadcastChannel';
78 import { MessageChannelUtils
} from
'./MessageChannelUtils';
79 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
80 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
81 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
82 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
83 import type OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
84 import type OCPPRequestService from
'./ocpp/OCPPRequestService';
85 import SharedLRUCache from
'./SharedLRUCache';
87 export default class ChargingStation
{
88 public readonly index
: number;
89 public readonly templateFile
: string;
90 public stationInfo
!: ChargingStationInfo
;
91 public started
: boolean;
92 public authorizedTagsCache
: AuthorizedTagsCache
;
93 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
94 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
95 public wsConnection
!: WebSocket
;
96 public readonly connectors
: Map
<number, ConnectorStatus
>;
97 public readonly requests
: Map
<string, CachedRequest
>;
98 public performanceStatistics
!: PerformanceStatistics
;
99 public heartbeatSetInterval
!: NodeJS
.Timeout
;
100 public ocppRequestService
!: OCPPRequestService
;
101 public bootNotificationRequest
!: BootNotificationRequest
;
102 public bootNotificationResponse
!: BootNotificationResponse
| null;
103 public powerDivider
!: number;
104 private starting
: boolean;
105 private stopping
: boolean;
106 private configurationFile
!: string;
107 private configurationFileHash
!: string;
108 private connectorsConfigurationHash
!: string;
109 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
110 private readonly messageBuffer
: Set
<string>;
111 private configuredSupervisionUrl
!: URL
;
112 private configuredSupervisionUrlIndex
!: number;
113 private wsConnectionRestarted
: boolean;
114 private autoReconnectRetryCount
: number;
115 private templateFileWatcher
!: fs
.FSWatcher
;
116 private readonly sharedLRUCache
: SharedLRUCache
;
117 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
118 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
120 constructor(index
: number, templateFile
: string) {
121 this.started
= false;
122 this.starting
= false;
123 this.stopping
= false;
124 this.wsConnectionRestarted
= false;
125 this.autoReconnectRetryCount
= 0;
127 this.templateFile
= templateFile
;
128 this.connectors
= new Map
<number, ConnectorStatus
>();
129 this.requests
= new Map
<string, CachedRequest
>();
130 this.messageBuffer
= new Set
<string>();
131 this.sharedLRUCache
= SharedLRUCache
.getInstance();
132 this.authorizedTagsCache
= AuthorizedTagsCache
.getInstance();
133 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
138 private get
wsConnectionUrl(): URL
{
140 (this.getSupervisionUrlOcppConfiguration()
141 ? ChargingStationConfigurationUtils
.getConfigurationKey(
143 this.getSupervisionUrlOcppKey()
145 : this.configuredSupervisionUrl
.href
) +
147 this.stationInfo
.chargingStationId
151 public logPrefix(): string {
152 return Utils
.logPrefix(
154 this?.stationInfo?.chargingStationId ??
155 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
160 public hasAuthorizedTags(): boolean {
161 return !Utils
.isEmptyArray(
162 this.authorizedTagsCache
.getAuthorizedTags(
163 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
)
168 public getEnableStatistics(): boolean | undefined {
169 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
170 ? this.stationInfo
.enableStatistics
174 public getMustAuthorizeAtRemoteStart(): boolean | undefined {
175 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
178 public getPayloadSchemaValidation(): boolean | undefined {
179 return this.stationInfo
.payloadSchemaValidation
?? true;
182 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
183 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
184 switch (this.getCurrentOutType(stationInfo
)) {
186 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
187 ? localStationInfo
.numberOfPhases
194 public isWebSocketConnectionOpened(): boolean {
195 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
198 public getRegistrationStatus(): RegistrationStatus
{
199 return this?.bootNotificationResponse
?.status;
202 public isInUnknownState(): boolean {
203 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
206 public isInPendingState(): boolean {
207 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
210 public isInAcceptedState(): boolean {
211 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
214 public isInRejectedState(): boolean {
215 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
218 public isRegistered(): boolean {
219 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
222 public isChargingStationAvailable(): boolean {
223 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
226 public isConnectorAvailable(id
: number): boolean {
227 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
230 public getNumberOfConnectors(): number {
231 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
234 public getConnectorStatus(id
: number): ConnectorStatus
| undefined {
235 return this.connectors
.get(id
);
238 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
239 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
;
242 public getOcppStrictCompliance(): boolean {
243 return this.stationInfo
?.ocppStrictCompliance
?? false;
246 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
247 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
248 this.getCurrentOutType(stationInfo
),
252 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
253 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
254 ? localStationInfo
.voltageOut
258 public getConnectorMaximumAvailablePower(connectorId
: number): number {
259 let connectorAmperageLimitationPowerLimit
: number;
261 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
262 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
264 connectorAmperageLimitationPowerLimit
=
265 (this.getCurrentOutType() === CurrentType
.AC
266 ? ACElectricUtils
.powerTotal(
267 this.getNumberOfPhases(),
268 this.getVoltageOut(),
269 this.getAmperageLimitation() * this.getNumberOfConnectors()
271 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
274 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
275 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
277 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
278 isNaN(connectorAmperageLimitationPowerLimit
)
280 : connectorAmperageLimitationPowerLimit
,
281 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
285 public getTransactionIdTag(transactionId
: number): string | undefined {
286 for (const connectorId
of this.connectors
.keys()) {
287 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
288 return this.getConnectorStatus(connectorId
).transactionIdTag
;
293 public getOutOfOrderEndMeterValues(): boolean {
294 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
297 public getBeginEndMeterValues(): boolean {
298 return this.stationInfo
?.beginEndMeterValues
?? false;
301 public getMeteringPerTransaction(): boolean {
302 return this.stationInfo
?.meteringPerTransaction
?? true;
305 public getTransactionDataMeterValues(): boolean {
306 return this.stationInfo
?.transactionDataMeterValues
?? false;
309 public getMainVoltageMeterValues(): boolean {
310 return this.stationInfo
?.mainVoltageMeterValues
?? true;
313 public getPhaseLineToLineVoltageMeterValues(): boolean {
314 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
317 public getCustomValueLimitationMeterValues(): boolean {
318 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
321 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
322 for (const connectorId
of this.connectors
.keys()) {
325 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
332 public getEnergyActiveImportRegisterByTransactionId(
333 transactionId
: number,
336 return this.getEnergyActiveImportRegister(
337 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
342 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number {
343 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
));
346 public getAuthorizeRemoteTxRequests(): boolean {
347 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
349 StandardParametersKey
.AuthorizeRemoteTxRequests
351 return authorizeRemoteTxRequests
352 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
356 public getLocalAuthListEnabled(): boolean {
357 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
359 StandardParametersKey
.LocalAuthListEnabled
361 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
364 public startHeartbeat(): void {
366 this.getHeartbeatInterval() &&
367 this.getHeartbeatInterval() > 0 &&
368 !this.heartbeatSetInterval
370 // eslint-disable-next-line @typescript-eslint/no-misused-promises
371 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
372 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
374 RequestCommand
.HEARTBEAT
376 }, this.getHeartbeatInterval());
379 ' Heartbeat started every ' +
380 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
382 } else if (this.heartbeatSetInterval
) {
385 ' Heartbeat already started every ' +
386 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
390 `${this.logPrefix()} Heartbeat interval set to ${
391 this.getHeartbeatInterval()
392 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
393 : this.getHeartbeatInterval()
394 }, not starting the heartbeat`
399 public restartHeartbeat(): void {
401 this.stopHeartbeat();
403 this.startHeartbeat();
406 public restartWebSocketPing(): void {
407 // Stop WebSocket ping
408 this.stopWebSocketPing();
409 // Start WebSocket ping
410 this.startWebSocketPing();
413 public startMeterValues(connectorId
: number, interval
: number): void {
414 if (connectorId
=== 0) {
416 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
420 if (!this.getConnectorStatus(connectorId
)) {
422 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
426 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
428 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
432 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
433 !this.getConnectorStatus(connectorId
)?.transactionId
436 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
441 // eslint-disable-next-line @typescript-eslint/no-misused-promises
442 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
443 // eslint-disable-next-line @typescript-eslint/no-misused-promises
444 async (): Promise
<void> => {
445 // FIXME: Implement OCPP version agnostic helpers
446 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
449 this.getConnectorStatus(connectorId
).transactionId
,
452 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
454 RequestCommand
.METER_VALUES
,
457 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
458 meterValue
: [meterValue
],
466 `${this.logPrefix()} Charging station ${
467 StandardParametersKey.MeterValueSampleInterval
468 } configuration set to ${
469 interval ? Utils.formatDurationMilliSeconds(interval) : interval
470 }, not sending MeterValues`
475 public start(): void {
476 if (this.started
=== false) {
477 if (this.starting
=== false) {
478 this.starting
= true;
479 if (this.getEnableStatistics()) {
480 this.performanceStatistics
.start();
482 this.openWSConnection();
483 // Monitor charging station template file
484 this.templateFileWatcher
= FileUtils
.watchJsonFile(
486 FileType
.ChargingStationTemplate
,
489 (event
, filename
): void => {
490 if (filename
&& event
=== 'change') {
493 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
495 } file have changed, reload`
497 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
501 this.stopAutomaticTransactionGenerator();
503 this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true
505 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:`,
523 parentPort
.postMessage(MessageChannelUtils
.buildStartedMessage(this));
524 this.starting
= false;
526 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
529 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
533 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
534 if (this.started
=== true) {
535 if (this.stopping
=== false) {
536 this.stopping
= true;
537 await this.stopMessageSequence(reason
);
538 this.closeWSConnection();
539 if (this.getEnableStatistics()) {
540 this.performanceStatistics
.stop();
542 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
543 this.templateFileWatcher
.close();
544 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
545 this.bootNotificationResponse
= null;
546 this.started
= false;
547 parentPort
.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
548 this.stopping
= false;
550 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
553 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
557 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
558 await this.stop(reason
);
559 await Utils
.sleep(this.stationInfo
.resetTime
);
564 public saveOcppConfiguration(): void {
565 if (this.getOcppPersistentConfiguration()) {
566 this.saveConfiguration();
570 public resetConnectorStatus(connectorId
: number): void {
571 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
572 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
573 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
574 this.getConnectorStatus(connectorId
).transactionStarted
= false;
575 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
576 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
577 delete this.getConnectorStatus(connectorId
).transactionId
;
578 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
579 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
580 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
581 this.stopMeterValues(connectorId
);
582 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
585 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean {
586 return ChargingStationConfigurationUtils
.getConfigurationKey(
588 StandardParametersKey
.SupportedFeatureProfiles
589 )?.value
.includes(featureProfile
);
592 public bufferMessage(message
: string): void {
593 this.messageBuffer
.add(message
);
596 public openWSConnection(
597 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
598 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
600 terminateOpened
: false,
603 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
604 params
.closeOpened
= params
?.closeOpened
?? false;
605 params
.terminateOpened
= params
?.terminateOpened
?? false;
607 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
608 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
610 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
612 if (params
?.closeOpened
) {
613 this.closeWSConnection();
615 if (params
?.terminateOpened
) {
616 this.terminateWSConnection();
618 let protocol
: string;
619 switch (this.getOcppVersion()) {
620 case OCPPVersion
.VERSION_16
:
621 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
624 this.handleUnsupportedVersion(this.getOcppVersion());
628 if (this.isWebSocketConnectionOpened() === true) {
630 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
636 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
639 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
641 // Handle WebSocket message
642 this.wsConnection
.on(
644 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
646 // Handle WebSocket error
647 this.wsConnection
.on(
649 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
651 // Handle WebSocket close
652 this.wsConnection
.on(
654 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
656 // Handle WebSocket open
657 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
658 // Handle WebSocket ping
659 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
660 // Handle WebSocket pong
661 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
664 public closeWSConnection(): void {
665 if (this.isWebSocketConnectionOpened() === true) {
666 this.wsConnection
.close();
667 this.wsConnection
= null;
671 public startAutomaticTransactionGenerator(
672 connectorIds
?: number[],
673 automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
675 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
676 automaticTransactionGeneratorConfiguration
??
677 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
680 if (!Utils
.isEmptyArray(connectorIds
)) {
681 for (const connectorId
of connectorIds
) {
682 this.automaticTransactionGenerator
.startConnector(connectorId
);
685 this.automaticTransactionGenerator
.start();
687 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
690 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
691 if (!Utils
.isEmptyArray(connectorIds
)) {
692 for (const connectorId
of connectorIds
) {
693 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
696 this.automaticTransactionGenerator
?.stop();
698 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
701 public async stopTransactionOnConnector(
703 reason
= StopTransactionReason
.NONE
704 ): Promise
<StopTransactionResponse
> {
705 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
707 this.getBeginEndMeterValues() &&
708 this.getOcppStrictCompliance() &&
709 !this.getOutOfOrderEndMeterValues()
711 // FIXME: Implement OCPP version agnostic helpers
712 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
715 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
717 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
719 RequestCommand
.METER_VALUES
,
723 meterValue
: [transactionEndMeterValue
],
727 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
729 RequestCommand
.STOP_TRANSACTION
,
732 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
738 private flushMessageBuffer(): void {
739 if (this.messageBuffer
.size
> 0) {
740 this.messageBuffer
.forEach((message
) => {
741 // TODO: evaluate the need to track performance
742 this.wsConnection
.send(message
);
743 this.messageBuffer
.delete(message
);
748 private getSupervisionUrlOcppConfiguration(): boolean {
749 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
752 private getSupervisionUrlOcppKey(): string {
753 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
756 private getTemplateFromFile(): ChargingStationTemplate
| null {
757 let template
: ChargingStationTemplate
= null;
759 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
760 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
762 const measureId
= `${FileType.ChargingStationTemplate} read`;
763 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
764 template
= JSON
.parse(
765 fs
.readFileSync(this.templateFile
, 'utf8')
766 ) as ChargingStationTemplate
;
767 PerformanceStatistics
.endMeasure(measureId
, beginId
);
768 template
.templateHash
= crypto
769 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
770 .update(JSON
.stringify(template
))
772 this.sharedLRUCache
.setChargingStationTemplate(template
);
775 FileUtils
.handleFileException(
777 FileType
.ChargingStationTemplate
,
779 error
as NodeJS
.ErrnoException
785 private getStationInfoFromTemplate(): ChargingStationInfo
{
786 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
787 if (Utils
.isNullOrUndefined(stationTemplate
)) {
788 const errorMsg
= 'Failed to read charging station template file';
789 logger
.error(`${this.logPrefix()} ${errorMsg}`);
790 throw new BaseError(errorMsg
);
792 if (Utils
.isEmptyObject(stationTemplate
)) {
793 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
794 logger
.error(`${this.logPrefix()} ${errorMsg}`);
795 throw new BaseError(errorMsg
);
797 // Deprecation template keys section
798 ChargingStationUtils
.warnDeprecatedTemplateKey(
803 "Use 'supervisionUrls' instead"
805 ChargingStationUtils
.convertDeprecatedTemplateKey(
810 const stationInfo
: ChargingStationInfo
=
811 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
812 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
813 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
817 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
818 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
819 stationTemplate
.power
= stationTemplate
.power
as number[];
820 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
821 stationInfo
.maximumPower
=
822 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
823 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
824 : stationTemplate
.power
[powerArrayRandomIndex
];
826 stationTemplate
.power
= stationTemplate
.power
as number;
827 stationInfo
.maximumPower
=
828 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
829 ? stationTemplate
.power
* 1000
830 : stationTemplate
.power
;
832 stationInfo
.resetTime
= stationTemplate
.resetTime
833 ? stationTemplate
.resetTime
* 1000
834 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
835 const configuredMaxConnectors
=
836 ChargingStationUtils
.getConfiguredNumberOfConnectors(stationTemplate
);
837 ChargingStationUtils
.checkConfiguredMaxConnectors(
838 configuredMaxConnectors
,
842 const templateMaxConnectors
=
843 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
844 ChargingStationUtils
.checkTemplateMaxConnectors(
845 templateMaxConnectors
,
850 configuredMaxConnectors
>
851 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
852 !stationTemplate
?.randomConnectors
855 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
857 }, forcing random connector configurations affectation`
859 stationInfo
.randomConnectors
= true;
861 // Build connectors if needed (FIXME: should be factored out)
862 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
863 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
864 ChargingStationUtils
.createStationInfoHash(stationInfo
);
868 private getStationInfoFromFile(): ChargingStationInfo
| null {
869 let stationInfo
: ChargingStationInfo
= null;
870 this.getStationInfoPersistentConfiguration() &&
871 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
872 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
876 private getStationInfo(): ChargingStationInfo
{
877 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
878 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
879 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
880 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
881 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
882 return this.stationInfo
;
884 return stationInfoFromFile
;
886 stationInfoFromFile
&&
887 ChargingStationUtils
.propagateSerialNumber(
888 this.getTemplateFromFile(),
890 stationInfoFromTemplate
892 return stationInfoFromTemplate
;
895 private saveStationInfo(): void {
896 if (this.getStationInfoPersistentConfiguration()) {
897 this.saveConfiguration();
901 private getOcppVersion(): OCPPVersion
{
902 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
905 private getOcppPersistentConfiguration(): boolean {
906 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
909 private getStationInfoPersistentConfiguration(): boolean {
910 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
913 private handleUnsupportedVersion(version
: OCPPVersion
) {
914 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
915 logger
.error(`${this.logPrefix()} ${errMsg}`);
916 throw new BaseError(errMsg
);
919 private initialize(): void {
920 this.configurationFile
= path
.join(
921 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
922 ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile()) + '.json'
924 this.stationInfo
= this.getStationInfo();
925 this.saveStationInfo();
926 // Avoid duplication of connectors related information in RAM
927 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
928 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
929 if (this.getEnableStatistics()) {
930 this.performanceStatistics
= PerformanceStatistics
.getInstance(
931 this.stationInfo
.hashId
,
932 this.stationInfo
.chargingStationId
,
933 this.configuredSupervisionUrl
936 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
939 this.powerDivider
= this.getPowerDivider();
940 // OCPP configuration
941 this.ocppConfiguration
= this.getOcppConfiguration();
942 this.initializeOcppConfiguration();
943 switch (this.getOcppVersion()) {
944 case OCPPVersion
.VERSION_16
:
945 this.ocppIncomingRequestService
=
946 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
947 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
948 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
952 this.handleUnsupportedVersion(this.getOcppVersion());
955 if (this.stationInfo
?.autoRegister
=== true) {
956 this.bootNotificationResponse
= {
957 currentTime
: new Date().toISOString(),
958 interval
: this.getHeartbeatInterval() / 1000,
959 status: RegistrationStatus
.ACCEPTED
,
964 private initializeOcppConfiguration(): void {
966 !ChargingStationConfigurationUtils
.getConfigurationKey(
968 StandardParametersKey
.HeartbeatInterval
971 ChargingStationConfigurationUtils
.addConfigurationKey(
973 StandardParametersKey
.HeartbeatInterval
,
978 !ChargingStationConfigurationUtils
.getConfigurationKey(
980 StandardParametersKey
.HeartBeatInterval
983 ChargingStationConfigurationUtils
.addConfigurationKey(
985 StandardParametersKey
.HeartBeatInterval
,
991 this.getSupervisionUrlOcppConfiguration() &&
992 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
994 ChargingStationConfigurationUtils
.addConfigurationKey(
996 this.getSupervisionUrlOcppKey(),
997 this.configuredSupervisionUrl
.href
,
1001 !this.getSupervisionUrlOcppConfiguration() &&
1002 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1004 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1006 this.getSupervisionUrlOcppKey(),
1011 this.stationInfo
.amperageLimitationOcppKey
&&
1012 !ChargingStationConfigurationUtils
.getConfigurationKey(
1014 this.stationInfo
.amperageLimitationOcppKey
1017 ChargingStationConfigurationUtils
.addConfigurationKey(
1019 this.stationInfo
.amperageLimitationOcppKey
,
1021 this.stationInfo
.maximumAmperage
*
1022 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1027 !ChargingStationConfigurationUtils
.getConfigurationKey(
1029 StandardParametersKey
.SupportedFeatureProfiles
1032 ChargingStationConfigurationUtils
.addConfigurationKey(
1034 StandardParametersKey
.SupportedFeatureProfiles
,
1035 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1038 ChargingStationConfigurationUtils
.addConfigurationKey(
1040 StandardParametersKey
.NumberOfConnectors
,
1041 this.getNumberOfConnectors().toString(),
1046 !ChargingStationConfigurationUtils
.getConfigurationKey(
1048 StandardParametersKey
.MeterValuesSampledData
1051 ChargingStationConfigurationUtils
.addConfigurationKey(
1053 StandardParametersKey
.MeterValuesSampledData
,
1054 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1058 !ChargingStationConfigurationUtils
.getConfigurationKey(
1060 StandardParametersKey
.ConnectorPhaseRotation
1063 const connectorPhaseRotation
= [];
1064 for (const connectorId
of this.connectors
.keys()) {
1066 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1067 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1068 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1069 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1071 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1072 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1073 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1074 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1077 ChargingStationConfigurationUtils
.addConfigurationKey(
1079 StandardParametersKey
.ConnectorPhaseRotation
,
1080 connectorPhaseRotation
.toString()
1084 !ChargingStationConfigurationUtils
.getConfigurationKey(
1086 StandardParametersKey
.AuthorizeRemoteTxRequests
1089 ChargingStationConfigurationUtils
.addConfigurationKey(
1091 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1096 !ChargingStationConfigurationUtils
.getConfigurationKey(
1098 StandardParametersKey
.LocalAuthListEnabled
1100 ChargingStationConfigurationUtils
.getConfigurationKey(
1102 StandardParametersKey
.SupportedFeatureProfiles
1103 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1105 ChargingStationConfigurationUtils
.addConfigurationKey(
1107 StandardParametersKey
.LocalAuthListEnabled
,
1112 !ChargingStationConfigurationUtils
.getConfigurationKey(
1114 StandardParametersKey
.ConnectionTimeOut
1117 ChargingStationConfigurationUtils
.addConfigurationKey(
1119 StandardParametersKey
.ConnectionTimeOut
,
1120 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1123 this.saveOcppConfiguration();
1126 private initializeConnectors(
1127 stationInfo
: ChargingStationInfo
,
1128 configuredMaxConnectors
: number,
1129 templateMaxConnectors
: number
1131 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1132 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1133 logger
.error(`${this.logPrefix()} ${logMsg}`);
1134 throw new BaseError(logMsg
);
1136 if (!stationInfo
?.Connectors
[0]) {
1138 `${this.logPrefix()} Charging station information from template ${
1140 } with no connector Id 0 configuration`
1143 if (stationInfo
?.Connectors
) {
1144 const connectorsConfigHash
= crypto
1145 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1146 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1148 const connectorsConfigChanged
=
1149 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1150 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1151 connectorsConfigChanged
&& this.connectors
.clear();
1152 this.connectorsConfigurationHash
= connectorsConfigHash
;
1153 // Add connector Id 0
1154 let lastConnector
= '0';
1155 for (lastConnector
in stationInfo
?.Connectors
) {
1156 const connectorStatus
= stationInfo
?.Connectors
[lastConnector
];
1157 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1159 lastConnectorId
=== 0 &&
1160 this.getUseConnectorId0(stationInfo
) === true &&
1163 this.checkStationInfoConnectorStatus(lastConnectorId
, connectorStatus
);
1164 this.connectors
.set(
1166 Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
)
1168 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1169 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1170 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1174 // Generate all connectors
1175 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1176 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1177 const randConnectorId
= stationInfo
?.randomConnectors
1178 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1180 const connectorStatus
= stationInfo
?.Connectors
[randConnectorId
.toString()];
1181 this.checkStationInfoConnectorStatus(randConnectorId
, connectorStatus
);
1182 this.connectors
.set(index
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
1183 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1184 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1185 this.getConnectorStatus(index
).chargingProfiles
= [];
1192 `${this.logPrefix()} Charging station information from template ${
1194 } with no connectors configuration defined, using already defined connectors`
1197 // Initialize transaction attributes on connectors
1198 for (const connectorId
of this.connectors
.keys()) {
1201 (this.getConnectorStatus(connectorId
).transactionStarted
=== undefined ||
1202 this.getConnectorStatus(connectorId
).transactionStarted
=== false)
1204 this.initializeConnectorStatus(connectorId
);
1209 private checkStationInfoConnectorStatus(
1210 connectorId
: number,
1211 connectorStatus
: ConnectorStatus
1213 if (!Utils
.isNullOrUndefined(connectorStatus
?.status)) {
1215 `${this.logPrefix()} Charging station information from template ${
1217 } with connector ${connectorId} status configuration defined, undefine it`
1219 connectorStatus
.status = undefined;
1223 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1224 let configuration
: ChargingStationConfiguration
= null;
1225 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1227 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1228 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1229 this.configurationFileHash
1232 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1233 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1234 configuration
= JSON
.parse(
1235 fs
.readFileSync(this.configurationFile
, 'utf8')
1236 ) as ChargingStationConfiguration
;
1237 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1238 this.configurationFileHash
= configuration
.configurationHash
;
1239 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1242 FileUtils
.handleFileException(
1244 FileType
.ChargingStationConfiguration
,
1245 this.configurationFile
,
1246 error
as NodeJS
.ErrnoException
1250 return configuration
;
1253 private saveConfiguration(): void {
1254 if (this.configurationFile
) {
1256 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1257 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1259 const configurationData
: ChargingStationConfiguration
=
1260 this.getConfigurationFromFile() ?? {};
1261 this.ocppConfiguration
?.configurationKey
&&
1262 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1263 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1264 delete configurationData
.configurationHash
;
1265 const configurationHash
= crypto
1266 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1267 .update(JSON
.stringify(configurationData
))
1269 if (this.configurationFileHash
!== configurationHash
) {
1270 configurationData
.configurationHash
= configurationHash
;
1271 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1272 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1273 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1274 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1275 fs
.closeSync(fileDescriptor
);
1276 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1277 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1278 this.configurationFileHash
= configurationHash
;
1279 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1282 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1283 this.configurationFile
1288 FileUtils
.handleFileException(
1290 FileType
.ChargingStationConfiguration
,
1291 this.configurationFile
,
1292 error
as NodeJS
.ErrnoException
1297 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1302 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1303 return this.getTemplateFromFile()?.Configuration
?? null;
1306 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1307 let configuration
: ChargingStationConfiguration
= null;
1308 if (this.getOcppPersistentConfiguration()) {
1309 const configurationFromFile
= this.getConfigurationFromFile();
1310 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1312 configuration
&& delete configuration
.stationInfo
;
1313 return configuration
;
1316 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1317 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1318 if (!ocppConfiguration
) {
1319 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1321 return ocppConfiguration
;
1324 private async onOpen(): Promise
<void> {
1325 if (this.isWebSocketConnectionOpened() === true) {
1327 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1329 if (!this.isRegistered()) {
1330 // Send BootNotification
1331 let registrationRetryCount
= 0;
1333 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1334 BootNotificationRequest
,
1335 BootNotificationResponse
1336 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1337 skipBufferingOnError
: true,
1339 if (!this.isRegistered()) {
1340 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1342 this.bootNotificationResponse
?.interval
1343 ? this.bootNotificationResponse
.interval
* 1000
1344 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1348 !this.isRegistered() &&
1349 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1350 this.getRegistrationMaxRetries() === -1)
1353 if (this.isRegistered()) {
1354 if (this.isInAcceptedState()) {
1355 await this.startMessageSequence();
1359 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1362 this.wsConnectionRestarted
= false;
1363 this.autoReconnectRetryCount
= 0;
1364 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1367 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1372 private async onClose(code
: number, reason
: string): Promise
<void> {
1375 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1376 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1378 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1380 )}' and reason '${reason}'`
1382 this.autoReconnectRetryCount
= 0;
1387 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1389 )}' and reason '${reason}'`
1391 this.started
=== true && (await this.reconnect());
1394 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1397 private async onMessage(data
: Data
): Promise
<void> {
1398 let messageType
: number;
1399 let messageId
: string;
1400 let commandName
: IncomingRequestCommand
;
1401 let commandPayload
: JsonType
;
1402 let errorType
: ErrorType
;
1403 let errorMessage
: string;
1404 let errorDetails
: JsonType
;
1405 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1406 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1407 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1408 let requestPayload
: JsonType
;
1409 let cachedRequest
: CachedRequest
;
1412 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1413 if (Array.isArray(request
) === true) {
1414 [messageType
, messageId
] = request
;
1415 // Check the type of message
1416 switch (messageType
) {
1418 case MessageType
.CALL_MESSAGE
:
1419 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1420 if (this.getEnableStatistics() === true) {
1421 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1424 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1428 // Process the message
1429 await this.ocppIncomingRequestService
.incomingRequestHandler(
1437 case MessageType
.CALL_RESULT_MESSAGE
:
1438 [, , commandPayload
] = request
as Response
;
1439 if (this.requests
.has(messageId
) === false) {
1441 throw new OCPPError(
1442 ErrorType
.INTERNAL_ERROR
,
1443 `Response for unknown message id ${messageId}`,
1449 cachedRequest
= this.requests
.get(messageId
);
1450 if (Array.isArray(cachedRequest
) === true) {
1451 [responseCallback
, errorCallback
, requestCommandName
, requestPayload
] = cachedRequest
;
1453 throw new OCPPError(
1454 ErrorType
.PROTOCOL_ERROR
,
1455 `Cached request for message id ${messageId} response is not an array`,
1457 cachedRequest
as unknown
as JsonType
1461 `${this.logPrefix()} << Command '${
1462 requestCommandName ?? Constants.UNKNOWN_COMMAND
1463 }' received response payload: ${JSON.stringify(request)}`
1465 responseCallback(commandPayload
, requestPayload
);
1468 case MessageType
.CALL_ERROR_MESSAGE
:
1469 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1470 if (this.requests
.has(messageId
) === false) {
1472 throw new OCPPError(
1473 ErrorType
.INTERNAL_ERROR
,
1474 `Error response for unknown message id ${messageId}`,
1476 { errorType
, errorMessage
, errorDetails
}
1479 cachedRequest
= this.requests
.get(messageId
);
1480 if (Array.isArray(cachedRequest
) === true) {
1481 [, errorCallback
, requestCommandName
] = cachedRequest
;
1483 throw new OCPPError(
1484 ErrorType
.PROTOCOL_ERROR
,
1485 `Cached request for message id ${messageId} error response is not an array`,
1487 cachedRequest
as unknown
as JsonType
1491 `${this.logPrefix()} << Command '${
1492 requestCommandName ?? Constants.UNKNOWN_COMMAND
1493 }' received error payload: ${JSON.stringify(request)}`
1495 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1499 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1500 errMsg
= `Wrong message type ${messageType}`;
1501 logger
.error(`${this.logPrefix()} ${errMsg}`);
1502 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1504 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1506 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1513 `${this.logPrefix()} Incoming OCPP command '${
1514 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1515 }' message '${data.toString()}'${
1516 messageType !== MessageType.CALL_MESSAGE
1517 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1519 } processing error:`,
1522 if (error
instanceof OCPPError
=== false) {
1524 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1525 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1526 }' message '${data.toString()}' handling is not an OCPPError:`,
1530 switch (messageType
) {
1531 case MessageType
.CALL_MESSAGE
:
1533 await this.ocppRequestService
.sendError(
1537 commandName
?? requestCommandName
?? null
1540 case MessageType
.CALL_RESULT_MESSAGE
:
1541 case MessageType
.CALL_ERROR_MESSAGE
:
1542 if (errorCallback
) {
1543 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1544 errorCallback(error
as OCPPError
, false);
1546 // Remove the request from the cache in case of error at response handling
1547 this.requests
.delete(messageId
);
1554 private onPing(): void {
1555 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1558 private onPong(): void {
1559 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1562 private onError(error
: WSError
): void {
1563 this.closeWSConnection();
1564 logger
.error(this.logPrefix() + ' WebSocket error:', error
);
1567 private getEnergyActiveImportRegister(
1568 connectorStatus
: ConnectorStatus
,
1571 if (this.getMeteringPerTransaction() === true) {
1574 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1575 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1580 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1581 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1585 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean {
1586 const localStationInfo
= stationInfo
?? this.stationInfo
;
1587 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1588 ? localStationInfo
.useConnectorId0
1592 private getNumberOfRunningTransactions(): number {
1594 for (const connectorId
of this.connectors
.keys()) {
1595 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1602 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1603 for (const connectorId
of this.connectors
.keys()) {
1604 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1605 await this.stopTransactionOnConnector(connectorId
, reason
);
1611 private getConnectionTimeout(): number {
1613 ChargingStationConfigurationUtils
.getConfigurationKey(
1615 StandardParametersKey
.ConnectionTimeOut
1620 ChargingStationConfigurationUtils
.getConfigurationKey(
1622 StandardParametersKey
.ConnectionTimeOut
1624 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1627 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1630 // -1 for unlimited, 0 for disabling
1631 private getAutoReconnectMaxRetries(): number {
1632 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1633 return this.stationInfo
.autoReconnectMaxRetries
;
1635 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1636 return Configuration
.getAutoReconnectMaxRetries();
1642 private getRegistrationMaxRetries(): number {
1643 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1644 return this.stationInfo
.registrationMaxRetries
;
1649 private getPowerDivider(): number {
1650 let powerDivider
= this.getNumberOfConnectors();
1651 if (this.stationInfo
?.powerSharedByConnectors
) {
1652 powerDivider
= this.getNumberOfRunningTransactions();
1654 return powerDivider
;
1657 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1658 const localStationInfo
= stationInfo
?? this.stationInfo
;
1659 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1662 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1663 const maximumPower
= this.getMaximumPower(stationInfo
);
1664 switch (this.getCurrentOutType(stationInfo
)) {
1665 case CurrentType
.AC
:
1666 return ACElectricUtils
.amperagePerPhaseFromPower(
1667 this.getNumberOfPhases(stationInfo
),
1668 maximumPower
/ this.getNumberOfConnectors(),
1669 this.getVoltageOut(stationInfo
)
1671 case CurrentType
.DC
:
1672 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1676 private getAmperageLimitation(): number | undefined {
1678 this.stationInfo
.amperageLimitationOcppKey
&&
1679 ChargingStationConfigurationUtils
.getConfigurationKey(
1681 this.stationInfo
.amperageLimitationOcppKey
1686 ChargingStationConfigurationUtils
.getConfigurationKey(
1688 this.stationInfo
.amperageLimitationOcppKey
1690 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1695 private getChargingProfilePowerLimit(connectorId
: number): number | undefined {
1696 let limit
: number, matchingChargingProfile
: ChargingProfile
;
1697 let chargingProfiles
: ChargingProfile
[] = [];
1698 // Get charging profiles for connector and sort by stack level
1699 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
1700 (a
, b
) => b
.stackLevel
- a
.stackLevel
1702 // Get profiles on connector 0
1703 if (this.getConnectorStatus(0).chargingProfiles
) {
1704 chargingProfiles
.push(
1705 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
1708 if (!Utils
.isEmptyArray(chargingProfiles
)) {
1709 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
1713 if (!Utils
.isNullOrUndefined(result
)) {
1714 limit
= result
.limit
;
1715 matchingChargingProfile
= result
.matchingChargingProfile
;
1716 switch (this.getCurrentOutType()) {
1717 case CurrentType
.AC
:
1719 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
1720 ChargingRateUnitType
.WATT
1722 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
1724 case CurrentType
.DC
:
1726 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
1727 ChargingRateUnitType
.WATT
1729 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
1731 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
1732 if (limit
> connectorMaximumPower
) {
1734 `${this.logPrefix()} Charging profile id ${
1735 matchingChargingProfile.chargingProfileId
1736 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
1737 this.getConnectorStatus(connectorId
).chargingProfiles
1739 limit
= connectorMaximumPower
;
1746 private async startMessageSequence(): Promise
<void> {
1747 if (this.stationInfo
?.autoRegister
=== true) {
1748 await this.ocppRequestService
.requestHandler
<
1749 BootNotificationRequest
,
1750 BootNotificationResponse
1751 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1752 skipBufferingOnError
: true,
1755 // Start WebSocket ping
1756 this.startWebSocketPing();
1758 this.startHeartbeat();
1759 // Initialize connectors status
1760 for (const connectorId
of this.connectors
.keys()) {
1761 let chargePointStatus
: ChargePointStatus
;
1762 if (connectorId
=== 0) {
1765 !this.getConnectorStatus(connectorId
)?.status &&
1766 (this.isChargingStationAvailable() === false ||
1767 this.isConnectorAvailable(connectorId
) === false)
1769 chargePointStatus
= ChargePointStatus
.UNAVAILABLE
;
1771 !this.getConnectorStatus(connectorId
)?.status &&
1772 this.getConnectorStatus(connectorId
)?.bootStatus
1774 // Set boot status in template at startup
1775 chargePointStatus
= this.getConnectorStatus(connectorId
).bootStatus
;
1776 } else if (this.getConnectorStatus(connectorId
)?.status) {
1777 // Set previous status at startup
1778 chargePointStatus
= this.getConnectorStatus(connectorId
).status;
1780 // Set default status
1781 chargePointStatus
= ChargePointStatus
.AVAILABLE
;
1783 await this.ocppRequestService
.requestHandler
<
1784 StatusNotificationRequest
,
1785 StatusNotificationResponse
1786 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1788 status: chargePointStatus
,
1789 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1791 this.getConnectorStatus(connectorId
).status = chargePointStatus
;
1794 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true) {
1795 this.startAutomaticTransactionGenerator();
1797 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
1800 private async stopMessageSequence(
1801 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1803 // Stop WebSocket ping
1804 this.stopWebSocketPing();
1806 this.stopHeartbeat();
1807 // Stop ongoing transactions
1808 if (this.automaticTransactionGenerator
?.started
=== true) {
1809 this.stopAutomaticTransactionGenerator();
1811 await this.stopRunningTransactions(reason
);
1813 for (const connectorId
of this.connectors
.keys()) {
1814 if (connectorId
> 0) {
1815 await this.ocppRequestService
.requestHandler
<
1816 StatusNotificationRequest
,
1817 StatusNotificationResponse
1818 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1820 status: ChargePointStatus
.UNAVAILABLE
,
1821 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1823 this.getConnectorStatus(connectorId
).status = null;
1828 private startWebSocketPing(): void {
1829 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1831 StandardParametersKey
.WebSocketPingInterval
1833 ? Utils
.convertToInt(
1834 ChargingStationConfigurationUtils
.getConfigurationKey(
1836 StandardParametersKey
.WebSocketPingInterval
1840 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1841 this.webSocketPingSetInterval
= setInterval(() => {
1842 if (this.isWebSocketConnectionOpened() === true) {
1843 this.wsConnection
.ping((): void => {
1844 /* This is intentional */
1847 }, webSocketPingInterval
* 1000);
1850 ' WebSocket ping started every ' +
1851 Utils
.formatDurationSeconds(webSocketPingInterval
)
1853 } else if (this.webSocketPingSetInterval
) {
1856 ' WebSocket ping already started every ' +
1857 Utils
.formatDurationSeconds(webSocketPingInterval
)
1861 `${this.logPrefix()} WebSocket ping interval set to ${
1862 webSocketPingInterval
1863 ? Utils.formatDurationSeconds(webSocketPingInterval)
1864 : webSocketPingInterval
1865 }, not starting the WebSocket ping`
1870 private stopWebSocketPing(): void {
1871 if (this.webSocketPingSetInterval
) {
1872 clearInterval(this.webSocketPingSetInterval
);
1876 private getConfiguredSupervisionUrl(): URL
{
1877 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1878 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1880 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1881 switch (Configuration
.getSupervisionUrlDistribution()) {
1882 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1884 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1886 case SupervisionUrlDistribution
.RANDOM
:
1887 this.configuredSupervisionUrlIndex
= Math.floor(
1888 Utils
.secureRandom() * supervisionUrls
.length
1891 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
1892 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1896 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1897 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
1900 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1903 return new URL(supervisionUrls
[this.configuredSupervisionUrlIndex
]);
1905 return new URL(supervisionUrls
as string);
1908 private getHeartbeatInterval(): number {
1909 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1911 StandardParametersKey
.HeartbeatInterval
1913 if (HeartbeatInterval
) {
1914 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1916 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1918 StandardParametersKey
.HeartBeatInterval
1920 if (HeartBeatInterval
) {
1921 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1923 this.stationInfo
?.autoRegister
=== false &&
1925 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1926 Constants.DEFAULT_HEARTBEAT_INTERVAL
1929 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1932 private stopHeartbeat(): void {
1933 if (this.heartbeatSetInterval
) {
1934 clearInterval(this.heartbeatSetInterval
);
1938 private terminateWSConnection(): void {
1939 if (this.isWebSocketConnectionOpened() === true) {
1940 this.wsConnection
.terminate();
1941 this.wsConnection
= null;
1945 private stopMeterValues(connectorId
: number) {
1946 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1947 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1951 private getReconnectExponentialDelay(): boolean {
1952 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1953 ? this.stationInfo
.reconnectExponentialDelay
1957 private async reconnect(): Promise
<void> {
1958 // Stop WebSocket ping
1959 this.stopWebSocketPing();
1961 this.stopHeartbeat();
1962 // Stop the ATG if needed
1963 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
=== true) {
1964 this.stopAutomaticTransactionGenerator();
1967 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1968 this.getAutoReconnectMaxRetries() === -1
1970 this.autoReconnectRetryCount
++;
1971 const reconnectDelay
= this.getReconnectExponentialDelay()
1972 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1973 : this.getConnectionTimeout() * 1000;
1974 const reconnectDelayWithdraw
= 1000;
1975 const reconnectTimeout
=
1976 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
1977 ? reconnectDelay
- reconnectDelayWithdraw
1980 `${this.logPrefix()} WebSocket connection retry in ${Utils.roundTo(
1983 )}ms, timeout ${reconnectTimeout}ms`
1985 await Utils
.sleep(reconnectDelay
);
1987 this.logPrefix() + ' WebSocket connection retry #' + this.autoReconnectRetryCount
.toString()
1989 this.openWSConnection(
1990 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
1991 { closeOpened
: true }
1993 this.wsConnectionRestarted
= true;
1994 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1996 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
1997 this.autoReconnectRetryCount
1998 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`
2003 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
2004 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2007 private initializeConnectorStatus(connectorId
: number): void {
2008 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2009 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2010 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2011 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2012 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2013 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;