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 this.wsConnectionRestarted
= false;
540 if (this.getEnableStatistics()) {
541 this.performanceStatistics
.stop();
543 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
544 this.templateFileWatcher
.close();
545 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
546 this.bootNotificationResponse
= null;
547 this.started
= false;
548 parentPort
.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
549 this.stopping
= false;
551 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
554 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
558 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
559 await this.stop(reason
);
560 await Utils
.sleep(this.stationInfo
.resetTime
);
565 public saveOcppConfiguration(): void {
566 if (this.getOcppPersistentConfiguration()) {
567 this.saveConfiguration();
571 public resetConnectorStatus(connectorId
: number): void {
572 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
573 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
574 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
575 this.getConnectorStatus(connectorId
).transactionStarted
= false;
576 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
577 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
578 delete this.getConnectorStatus(connectorId
).transactionId
;
579 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
580 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
581 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
582 this.stopMeterValues(connectorId
);
583 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
586 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean {
587 return ChargingStationConfigurationUtils
.getConfigurationKey(
589 StandardParametersKey
.SupportedFeatureProfiles
590 )?.value
.includes(featureProfile
);
593 public bufferMessage(message
: string): void {
594 this.messageBuffer
.add(message
);
597 public openWSConnection(
598 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
599 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
601 terminateOpened
: false,
604 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
605 params
.closeOpened
= params
?.closeOpened
?? false;
606 params
.terminateOpened
= params
?.terminateOpened
?? false;
608 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
609 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
611 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
613 if (params
?.closeOpened
) {
614 this.closeWSConnection();
616 if (params
?.terminateOpened
) {
617 this.terminateWSConnection();
619 let protocol
: string;
620 switch (this.getOcppVersion()) {
621 case OCPPVersion
.VERSION_16
:
622 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
625 this.handleUnsupportedVersion(this.getOcppVersion());
629 if (this.isWebSocketConnectionOpened() === true) {
631 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
637 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
640 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
642 // Handle WebSocket message
643 this.wsConnection
.on(
645 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
647 // Handle WebSocket error
648 this.wsConnection
.on(
650 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
652 // Handle WebSocket close
653 this.wsConnection
.on(
655 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
657 // Handle WebSocket open
658 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
659 // Handle WebSocket ping
660 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
661 // Handle WebSocket pong
662 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
665 public closeWSConnection(): void {
666 if (this.isWebSocketConnectionOpened() === true) {
667 this.wsConnection
.close();
668 this.wsConnection
= null;
672 public startAutomaticTransactionGenerator(
673 connectorIds
?: number[],
674 automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
676 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
677 automaticTransactionGeneratorConfiguration
??
678 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
681 if (!Utils
.isEmptyArray(connectorIds
)) {
682 for (const connectorId
of connectorIds
) {
683 this.automaticTransactionGenerator
.startConnector(connectorId
);
686 this.automaticTransactionGenerator
.start();
688 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
691 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
692 if (!Utils
.isEmptyArray(connectorIds
)) {
693 for (const connectorId
of connectorIds
) {
694 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
697 this.automaticTransactionGenerator
?.stop();
699 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
702 public async stopTransactionOnConnector(
704 reason
= StopTransactionReason
.NONE
705 ): Promise
<StopTransactionResponse
> {
706 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
708 this.getBeginEndMeterValues() &&
709 this.getOcppStrictCompliance() &&
710 !this.getOutOfOrderEndMeterValues()
712 // FIXME: Implement OCPP version agnostic helpers
713 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
716 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
718 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
720 RequestCommand
.METER_VALUES
,
724 meterValue
: [transactionEndMeterValue
],
728 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
730 RequestCommand
.STOP_TRANSACTION
,
733 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
739 private flushMessageBuffer(): void {
740 if (this.messageBuffer
.size
> 0) {
741 this.messageBuffer
.forEach((message
) => {
742 // TODO: evaluate the need to track performance
743 this.wsConnection
.send(message
);
744 this.messageBuffer
.delete(message
);
749 private getSupervisionUrlOcppConfiguration(): boolean {
750 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
753 private getSupervisionUrlOcppKey(): string {
754 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
757 private getTemplateFromFile(): ChargingStationTemplate
| null {
758 let template
: ChargingStationTemplate
= null;
760 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
761 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
763 const measureId
= `${FileType.ChargingStationTemplate} read`;
764 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
765 template
= JSON
.parse(
766 fs
.readFileSync(this.templateFile
, 'utf8')
767 ) as ChargingStationTemplate
;
768 PerformanceStatistics
.endMeasure(measureId
, beginId
);
769 template
.templateHash
= crypto
770 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
771 .update(JSON
.stringify(template
))
773 this.sharedLRUCache
.setChargingStationTemplate(template
);
776 FileUtils
.handleFileException(
778 FileType
.ChargingStationTemplate
,
780 error
as NodeJS
.ErrnoException
786 private getStationInfoFromTemplate(): ChargingStationInfo
{
787 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
788 if (Utils
.isNullOrUndefined(stationTemplate
)) {
789 const errorMsg
= 'Failed to read charging station template file';
790 logger
.error(`${this.logPrefix()} ${errorMsg}`);
791 throw new BaseError(errorMsg
);
793 if (Utils
.isEmptyObject(stationTemplate
)) {
794 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
795 logger
.error(`${this.logPrefix()} ${errorMsg}`);
796 throw new BaseError(errorMsg
);
798 // Deprecation template keys section
799 ChargingStationUtils
.warnDeprecatedTemplateKey(
804 "Use 'supervisionUrls' instead"
806 ChargingStationUtils
.convertDeprecatedTemplateKey(
811 const stationInfo
: ChargingStationInfo
=
812 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
813 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
814 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
818 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
819 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
820 stationTemplate
.power
= stationTemplate
.power
as number[];
821 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
822 stationInfo
.maximumPower
=
823 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
824 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
825 : stationTemplate
.power
[powerArrayRandomIndex
];
827 stationTemplate
.power
= stationTemplate
.power
as number;
828 stationInfo
.maximumPower
=
829 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
830 ? stationTemplate
.power
* 1000
831 : stationTemplate
.power
;
833 stationInfo
.resetTime
= stationTemplate
.resetTime
834 ? stationTemplate
.resetTime
* 1000
835 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
836 const configuredMaxConnectors
=
837 ChargingStationUtils
.getConfiguredNumberOfConnectors(stationTemplate
);
838 ChargingStationUtils
.checkConfiguredMaxConnectors(
839 configuredMaxConnectors
,
843 const templateMaxConnectors
=
844 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
845 ChargingStationUtils
.checkTemplateMaxConnectors(
846 templateMaxConnectors
,
851 configuredMaxConnectors
>
852 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
853 !stationTemplate
?.randomConnectors
856 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
858 }, forcing random connector configurations affectation`
860 stationInfo
.randomConnectors
= true;
862 // Build connectors if needed (FIXME: should be factored out)
863 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
864 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
865 ChargingStationUtils
.createStationInfoHash(stationInfo
);
869 private getStationInfoFromFile(): ChargingStationInfo
| null {
870 let stationInfo
: ChargingStationInfo
= null;
871 this.getStationInfoPersistentConfiguration() &&
872 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
873 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
877 private getStationInfo(): ChargingStationInfo
{
878 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
879 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
880 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
881 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
882 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
883 return this.stationInfo
;
885 return stationInfoFromFile
;
887 stationInfoFromFile
&&
888 ChargingStationUtils
.propagateSerialNumber(
889 this.getTemplateFromFile(),
891 stationInfoFromTemplate
893 return stationInfoFromTemplate
;
896 private saveStationInfo(): void {
897 if (this.getStationInfoPersistentConfiguration()) {
898 this.saveConfiguration();
902 private getOcppVersion(): OCPPVersion
{
903 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
906 private getOcppPersistentConfiguration(): boolean {
907 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
910 private getStationInfoPersistentConfiguration(): boolean {
911 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
914 private handleUnsupportedVersion(version
: OCPPVersion
) {
915 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
916 logger
.error(`${this.logPrefix()} ${errMsg}`);
917 throw new BaseError(errMsg
);
920 private initialize(): void {
921 this.configurationFile
= path
.join(
922 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
923 ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile()) + '.json'
925 this.stationInfo
= this.getStationInfo();
926 this.saveStationInfo();
927 // Avoid duplication of connectors related information in RAM
928 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
929 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
930 if (this.getEnableStatistics()) {
931 this.performanceStatistics
= PerformanceStatistics
.getInstance(
932 this.stationInfo
.hashId
,
933 this.stationInfo
.chargingStationId
,
934 this.configuredSupervisionUrl
937 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
940 this.powerDivider
= this.getPowerDivider();
941 // OCPP configuration
942 this.ocppConfiguration
= this.getOcppConfiguration();
943 this.initializeOcppConfiguration();
944 switch (this.getOcppVersion()) {
945 case OCPPVersion
.VERSION_16
:
946 this.ocppIncomingRequestService
=
947 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
948 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
949 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
953 this.handleUnsupportedVersion(this.getOcppVersion());
956 if (this.stationInfo
?.autoRegister
) {
957 this.bootNotificationResponse
= {
958 currentTime
: new Date().toISOString(),
959 interval
: this.getHeartbeatInterval() / 1000,
960 status: RegistrationStatus
.ACCEPTED
,
965 private initializeOcppConfiguration(): void {
967 !ChargingStationConfigurationUtils
.getConfigurationKey(
969 StandardParametersKey
.HeartbeatInterval
972 ChargingStationConfigurationUtils
.addConfigurationKey(
974 StandardParametersKey
.HeartbeatInterval
,
979 !ChargingStationConfigurationUtils
.getConfigurationKey(
981 StandardParametersKey
.HeartBeatInterval
984 ChargingStationConfigurationUtils
.addConfigurationKey(
986 StandardParametersKey
.HeartBeatInterval
,
992 this.getSupervisionUrlOcppConfiguration() &&
993 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
995 ChargingStationConfigurationUtils
.addConfigurationKey(
997 this.getSupervisionUrlOcppKey(),
998 this.configuredSupervisionUrl
.href
,
1002 !this.getSupervisionUrlOcppConfiguration() &&
1003 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1005 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1007 this.getSupervisionUrlOcppKey(),
1012 this.stationInfo
.amperageLimitationOcppKey
&&
1013 !ChargingStationConfigurationUtils
.getConfigurationKey(
1015 this.stationInfo
.amperageLimitationOcppKey
1018 ChargingStationConfigurationUtils
.addConfigurationKey(
1020 this.stationInfo
.amperageLimitationOcppKey
,
1022 this.stationInfo
.maximumAmperage
*
1023 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1028 !ChargingStationConfigurationUtils
.getConfigurationKey(
1030 StandardParametersKey
.SupportedFeatureProfiles
1033 ChargingStationConfigurationUtils
.addConfigurationKey(
1035 StandardParametersKey
.SupportedFeatureProfiles
,
1036 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1039 ChargingStationConfigurationUtils
.addConfigurationKey(
1041 StandardParametersKey
.NumberOfConnectors
,
1042 this.getNumberOfConnectors().toString(),
1047 !ChargingStationConfigurationUtils
.getConfigurationKey(
1049 StandardParametersKey
.MeterValuesSampledData
1052 ChargingStationConfigurationUtils
.addConfigurationKey(
1054 StandardParametersKey
.MeterValuesSampledData
,
1055 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1059 !ChargingStationConfigurationUtils
.getConfigurationKey(
1061 StandardParametersKey
.ConnectorPhaseRotation
1064 const connectorPhaseRotation
= [];
1065 for (const connectorId
of this.connectors
.keys()) {
1067 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1068 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1069 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1070 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1072 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1073 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1074 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1075 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1078 ChargingStationConfigurationUtils
.addConfigurationKey(
1080 StandardParametersKey
.ConnectorPhaseRotation
,
1081 connectorPhaseRotation
.toString()
1085 !ChargingStationConfigurationUtils
.getConfigurationKey(
1087 StandardParametersKey
.AuthorizeRemoteTxRequests
1090 ChargingStationConfigurationUtils
.addConfigurationKey(
1092 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1097 !ChargingStationConfigurationUtils
.getConfigurationKey(
1099 StandardParametersKey
.LocalAuthListEnabled
1101 ChargingStationConfigurationUtils
.getConfigurationKey(
1103 StandardParametersKey
.SupportedFeatureProfiles
1104 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1106 ChargingStationConfigurationUtils
.addConfigurationKey(
1108 StandardParametersKey
.LocalAuthListEnabled
,
1113 !ChargingStationConfigurationUtils
.getConfigurationKey(
1115 StandardParametersKey
.ConnectionTimeOut
1118 ChargingStationConfigurationUtils
.addConfigurationKey(
1120 StandardParametersKey
.ConnectionTimeOut
,
1121 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1124 this.saveOcppConfiguration();
1127 private initializeConnectors(
1128 stationInfo
: ChargingStationInfo
,
1129 configuredMaxConnectors
: number,
1130 templateMaxConnectors
: number
1132 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1133 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1134 logger
.error(`${this.logPrefix()} ${logMsg}`);
1135 throw new BaseError(logMsg
);
1137 if (!stationInfo
?.Connectors
[0]) {
1139 `${this.logPrefix()} Charging station information from template ${
1141 } with no connector Id 0 configuration`
1144 if (stationInfo
?.Connectors
) {
1145 const connectorsConfigHash
= crypto
1146 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1147 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1149 const connectorsConfigChanged
=
1150 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1151 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1152 connectorsConfigChanged
&& this.connectors
.clear();
1153 this.connectorsConfigurationHash
= connectorsConfigHash
;
1154 // Add connector Id 0
1155 let lastConnector
= '0';
1156 for (lastConnector
in stationInfo
?.Connectors
) {
1157 const connectorStatus
= stationInfo
?.Connectors
[lastConnector
];
1158 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1160 lastConnectorId
=== 0 &&
1161 this.getUseConnectorId0(stationInfo
) === true &&
1164 this.checkStationInfoConnectorStatus(lastConnectorId
, connectorStatus
);
1165 this.connectors
.set(
1167 Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
)
1169 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1170 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1171 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1175 // Generate all connectors
1176 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1177 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1178 const randConnectorId
= stationInfo
?.randomConnectors
1179 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1181 const connectorStatus
= stationInfo
?.Connectors
[randConnectorId
.toString()];
1182 this.checkStationInfoConnectorStatus(randConnectorId
, connectorStatus
);
1183 this.connectors
.set(index
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
1184 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1185 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1186 this.getConnectorStatus(index
).chargingProfiles
= [];
1193 `${this.logPrefix()} Charging station information from template ${
1195 } with no connectors configuration defined, using already defined connectors`
1198 // Initialize transaction attributes on connectors
1199 for (const connectorId
of this.connectors
.keys()) {
1202 (this.getConnectorStatus(connectorId
).transactionStarted
=== undefined ||
1203 this.getConnectorStatus(connectorId
).transactionStarted
=== false)
1205 this.initializeConnectorStatus(connectorId
);
1210 private checkStationInfoConnectorStatus(
1211 connectorId
: number,
1212 connectorStatus
: ConnectorStatus
1214 if (!Utils
.isNullOrUndefined(connectorStatus
?.status)) {
1216 `${this.logPrefix()} Charging station information from template ${
1218 } with connector ${connectorId} status configuration defined, undefine it`
1220 connectorStatus
.status = undefined;
1224 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1225 let configuration
: ChargingStationConfiguration
= null;
1226 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1228 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1229 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1230 this.configurationFileHash
1233 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1234 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1235 configuration
= JSON
.parse(
1236 fs
.readFileSync(this.configurationFile
, 'utf8')
1237 ) as ChargingStationConfiguration
;
1238 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1239 this.configurationFileHash
= configuration
.configurationHash
;
1240 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1243 FileUtils
.handleFileException(
1245 FileType
.ChargingStationConfiguration
,
1246 this.configurationFile
,
1247 error
as NodeJS
.ErrnoException
1251 return configuration
;
1254 private saveConfiguration(): void {
1255 if (this.configurationFile
) {
1257 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1258 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1260 const configurationData
: ChargingStationConfiguration
=
1261 this.getConfigurationFromFile() ?? {};
1262 this.ocppConfiguration
?.configurationKey
&&
1263 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1264 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1265 delete configurationData
.configurationHash
;
1266 const configurationHash
= crypto
1267 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1268 .update(JSON
.stringify(configurationData
))
1270 if (this.configurationFileHash
!== configurationHash
) {
1271 configurationData
.configurationHash
= configurationHash
;
1272 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1273 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1274 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1275 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1276 fs
.closeSync(fileDescriptor
);
1277 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1278 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1279 this.configurationFileHash
= configurationHash
;
1280 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1283 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1284 this.configurationFile
1289 FileUtils
.handleFileException(
1291 FileType
.ChargingStationConfiguration
,
1292 this.configurationFile
,
1293 error
as NodeJS
.ErrnoException
1298 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1303 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1304 return this.getTemplateFromFile()?.Configuration
?? null;
1307 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1308 let configuration
: ChargingStationConfiguration
= null;
1309 if (this.getOcppPersistentConfiguration()) {
1310 const configurationFromFile
= this.getConfigurationFromFile();
1311 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1313 configuration
&& delete configuration
.stationInfo
;
1314 return configuration
;
1317 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1318 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1319 if (!ocppConfiguration
) {
1320 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1322 return ocppConfiguration
;
1325 private async onOpen(): Promise
<void> {
1326 if (this.isWebSocketConnectionOpened() === true) {
1328 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1330 if (!this.isRegistered()) {
1331 // Send BootNotification
1332 let registrationRetryCount
= 0;
1334 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1335 BootNotificationRequest
,
1336 BootNotificationResponse
1337 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1338 skipBufferingOnError
: true,
1340 if (!this.isRegistered()) {
1341 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1343 this.bootNotificationResponse
?.interval
1344 ? this.bootNotificationResponse
.interval
* 1000
1345 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1349 !this.isRegistered() &&
1350 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1351 this.getRegistrationMaxRetries() === -1)
1354 if (this.isRegistered()) {
1355 if (this.isInAcceptedState()) {
1356 await this.startMessageSequence();
1360 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1363 this.wsConnectionRestarted
= false;
1364 this.autoReconnectRetryCount
= 0;
1365 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1368 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1373 private async onClose(code
: number, reason
: string): Promise
<void> {
1376 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1377 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1379 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1381 )}' and reason '${reason}'`
1383 this.autoReconnectRetryCount
= 0;
1388 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1390 )}' and reason '${reason}'`
1392 this.started
=== true && (await this.reconnect());
1395 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1398 private async onMessage(data
: Data
): Promise
<void> {
1399 let messageType
: number;
1400 let messageId
: string;
1401 let commandName
: IncomingRequestCommand
;
1402 let commandPayload
: JsonType
;
1403 let errorType
: ErrorType
;
1404 let errorMessage
: string;
1405 let errorDetails
: JsonType
;
1406 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1407 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1408 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1409 let requestPayload
: JsonType
;
1410 let cachedRequest
: CachedRequest
;
1413 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1414 if (Array.isArray(request
) === true) {
1415 [messageType
, messageId
] = request
;
1416 // Check the type of message
1417 switch (messageType
) {
1419 case MessageType
.CALL_MESSAGE
:
1420 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1421 if (this.getEnableStatistics() === true) {
1422 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1425 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1429 // Process the message
1430 await this.ocppIncomingRequestService
.incomingRequestHandler(
1438 case MessageType
.CALL_RESULT_MESSAGE
:
1439 [, , commandPayload
] = request
as Response
;
1440 if (this.requests
.has(messageId
) === false) {
1442 throw new OCPPError(
1443 ErrorType
.INTERNAL_ERROR
,
1444 `Response for unknown message id ${messageId}`,
1450 cachedRequest
= this.requests
.get(messageId
);
1451 if (Array.isArray(cachedRequest
) === true) {
1452 [responseCallback
, errorCallback
, requestCommandName
, requestPayload
] = cachedRequest
;
1454 throw new OCPPError(
1455 ErrorType
.PROTOCOL_ERROR
,
1456 `Cached request for message id ${messageId} response is not an array`,
1458 cachedRequest
as unknown
as JsonType
1462 `${this.logPrefix()} << Command '${
1463 requestCommandName ?? Constants.UNKNOWN_COMMAND
1464 }' received response payload: ${JSON.stringify(request)}`
1466 responseCallback(commandPayload
, requestPayload
);
1469 case MessageType
.CALL_ERROR_MESSAGE
:
1470 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1471 if (this.requests
.has(messageId
) === false) {
1473 throw new OCPPError(
1474 ErrorType
.INTERNAL_ERROR
,
1475 `Error response for unknown message id ${messageId}`,
1477 { errorType
, errorMessage
, errorDetails
}
1480 cachedRequest
= this.requests
.get(messageId
);
1481 if (Array.isArray(cachedRequest
) === true) {
1482 [, errorCallback
, requestCommandName
] = cachedRequest
;
1484 throw new OCPPError(
1485 ErrorType
.PROTOCOL_ERROR
,
1486 `Cached request for message id ${messageId} error response is not an array`,
1488 cachedRequest
as unknown
as JsonType
1492 `${this.logPrefix()} << Command '${
1493 requestCommandName ?? Constants.UNKNOWN_COMMAND
1494 }' received error payload: ${JSON.stringify(request)}`
1496 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1500 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1501 errMsg
= `Wrong message type ${messageType}`;
1502 logger
.error(`${this.logPrefix()} ${errMsg}`);
1503 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1505 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1507 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1514 `${this.logPrefix()} Incoming OCPP command '${
1515 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1516 }' message '${data.toString()}'${
1517 messageType !== MessageType.CALL_MESSAGE
1518 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1520 } processing error:`,
1523 if (error
instanceof OCPPError
=== false) {
1525 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1526 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1527 }' message '${data.toString()}' handling is not an OCPPError:`,
1531 switch (messageType
) {
1532 case MessageType
.CALL_MESSAGE
:
1534 await this.ocppRequestService
.sendError(
1538 commandName
?? requestCommandName
?? null
1541 case MessageType
.CALL_RESULT_MESSAGE
:
1542 case MessageType
.CALL_ERROR_MESSAGE
:
1543 if (errorCallback
) {
1544 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1545 errorCallback(error
as OCPPError
, false);
1547 // Remove the request from the cache in case of error at response handling
1548 this.requests
.delete(messageId
);
1555 private onPing(): void {
1556 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1559 private onPong(): void {
1560 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1563 private onError(error
: WSError
): void {
1564 this.closeWSConnection();
1565 logger
.error(this.logPrefix() + ' WebSocket error:', error
);
1568 private getEnergyActiveImportRegister(
1569 connectorStatus
: ConnectorStatus
,
1572 if (this.getMeteringPerTransaction() === true) {
1575 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1576 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1581 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1582 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1586 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean {
1587 const localStationInfo
= stationInfo
?? this.stationInfo
;
1588 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1589 ? localStationInfo
.useConnectorId0
1593 private getNumberOfRunningTransactions(): number {
1595 for (const connectorId
of this.connectors
.keys()) {
1596 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1603 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1604 for (const connectorId
of this.connectors
.keys()) {
1605 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1606 await this.stopTransactionOnConnector(connectorId
, reason
);
1612 private getConnectionTimeout(): number {
1614 ChargingStationConfigurationUtils
.getConfigurationKey(
1616 StandardParametersKey
.ConnectionTimeOut
1621 ChargingStationConfigurationUtils
.getConfigurationKey(
1623 StandardParametersKey
.ConnectionTimeOut
1625 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1628 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1631 // -1 for unlimited, 0 for disabling
1632 private getAutoReconnectMaxRetries(): number {
1633 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1634 return this.stationInfo
.autoReconnectMaxRetries
;
1636 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1637 return Configuration
.getAutoReconnectMaxRetries();
1643 private getRegistrationMaxRetries(): number {
1644 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1645 return this.stationInfo
.registrationMaxRetries
;
1650 private getPowerDivider(): number {
1651 let powerDivider
= this.getNumberOfConnectors();
1652 if (this.stationInfo
?.powerSharedByConnectors
) {
1653 powerDivider
= this.getNumberOfRunningTransactions();
1655 return powerDivider
;
1658 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1659 const localStationInfo
= stationInfo
?? this.stationInfo
;
1660 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1663 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1664 const maximumPower
= this.getMaximumPower(stationInfo
);
1665 switch (this.getCurrentOutType(stationInfo
)) {
1666 case CurrentType
.AC
:
1667 return ACElectricUtils
.amperagePerPhaseFromPower(
1668 this.getNumberOfPhases(stationInfo
),
1669 maximumPower
/ this.getNumberOfConnectors(),
1670 this.getVoltageOut(stationInfo
)
1672 case CurrentType
.DC
:
1673 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1677 private getAmperageLimitation(): number | undefined {
1679 this.stationInfo
.amperageLimitationOcppKey
&&
1680 ChargingStationConfigurationUtils
.getConfigurationKey(
1682 this.stationInfo
.amperageLimitationOcppKey
1687 ChargingStationConfigurationUtils
.getConfigurationKey(
1689 this.stationInfo
.amperageLimitationOcppKey
1691 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1696 private getChargingProfilePowerLimit(connectorId
: number): number | undefined {
1697 let limit
: number, matchingChargingProfile
: ChargingProfile
;
1698 let chargingProfiles
: ChargingProfile
[] = [];
1699 // Get charging profiles for connector and sort by stack level
1700 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
1701 (a
, b
) => b
.stackLevel
- a
.stackLevel
1703 // Get profiles on connector 0
1704 if (this.getConnectorStatus(0).chargingProfiles
) {
1705 chargingProfiles
.push(
1706 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
1709 if (!Utils
.isEmptyArray(chargingProfiles
)) {
1710 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
1714 if (!Utils
.isNullOrUndefined(result
)) {
1715 limit
= result
.limit
;
1716 matchingChargingProfile
= result
.matchingChargingProfile
;
1717 switch (this.getCurrentOutType()) {
1718 case CurrentType
.AC
:
1720 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
1721 ChargingRateUnitType
.WATT
1723 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
1725 case CurrentType
.DC
:
1727 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
1728 ChargingRateUnitType
.WATT
1730 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
1732 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
1733 if (limit
> connectorMaximumPower
) {
1735 `${this.logPrefix()} Charging profile id ${
1736 matchingChargingProfile.chargingProfileId
1737 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
1738 this.getConnectorStatus(connectorId
).chargingProfiles
1740 limit
= connectorMaximumPower
;
1747 private async startMessageSequence(): Promise
<void> {
1748 if (this.stationInfo
?.autoRegister
) {
1749 await this.ocppRequestService
.requestHandler
<
1750 BootNotificationRequest
,
1751 BootNotificationResponse
1752 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1753 skipBufferingOnError
: true,
1756 // Start WebSocket ping
1757 this.startWebSocketPing();
1759 this.startHeartbeat();
1760 // Initialize connectors status
1761 for (const connectorId
of this.connectors
.keys()) {
1762 let chargePointStatus
: ChargePointStatus
;
1763 if (connectorId
=== 0) {
1766 !this.getConnectorStatus(connectorId
)?.status &&
1767 (this.isChargingStationAvailable() === false ||
1768 (this.isChargingStationAvailable() === true &&
1769 this.isConnectorAvailable(connectorId
) === false))
1771 chargePointStatus
= ChargePointStatus
.UNAVAILABLE
;
1773 !this.getConnectorStatus(connectorId
)?.status &&
1774 this.getConnectorStatus(connectorId
)?.bootStatus
1776 // Set boot status in template at startup
1777 chargePointStatus
= this.getConnectorStatus(connectorId
).bootStatus
;
1778 } else if (this.getConnectorStatus(connectorId
)?.status) {
1779 // Set previous status at startup
1780 chargePointStatus
= this.getConnectorStatus(connectorId
).status;
1782 // Set default status
1783 chargePointStatus
= ChargePointStatus
.AVAILABLE
;
1785 await this.ocppRequestService
.requestHandler
<
1786 StatusNotificationRequest
,
1787 StatusNotificationResponse
1788 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1790 status: chargePointStatus
,
1791 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1793 this.getConnectorStatus(connectorId
).status = chargePointStatus
;
1796 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true) {
1797 this.startAutomaticTransactionGenerator();
1799 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
1802 private async stopMessageSequence(
1803 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1805 // Stop WebSocket ping
1806 this.stopWebSocketPing();
1808 this.stopHeartbeat();
1809 // Stop ongoing transactions
1810 if (this.automaticTransactionGenerator
?.started
=== true) {
1811 this.stopAutomaticTransactionGenerator();
1813 await this.stopRunningTransactions(reason
);
1815 for (const connectorId
of this.connectors
.keys()) {
1816 if (connectorId
> 0) {
1817 await this.ocppRequestService
.requestHandler
<
1818 StatusNotificationRequest
,
1819 StatusNotificationResponse
1820 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1822 status: ChargePointStatus
.UNAVAILABLE
,
1823 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1825 this.getConnectorStatus(connectorId
).status = null;
1830 private startWebSocketPing(): void {
1831 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1833 StandardParametersKey
.WebSocketPingInterval
1835 ? Utils
.convertToInt(
1836 ChargingStationConfigurationUtils
.getConfigurationKey(
1838 StandardParametersKey
.WebSocketPingInterval
1842 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1843 this.webSocketPingSetInterval
= setInterval(() => {
1844 if (this.isWebSocketConnectionOpened() === true) {
1845 this.wsConnection
.ping((): void => {
1846 /* This is intentional */
1849 }, webSocketPingInterval
* 1000);
1852 ' WebSocket ping started every ' +
1853 Utils
.formatDurationSeconds(webSocketPingInterval
)
1855 } else if (this.webSocketPingSetInterval
) {
1858 ' WebSocket ping every ' +
1859 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1864 `${this.logPrefix()} WebSocket ping interval set to ${
1865 webSocketPingInterval
1866 ? Utils.formatDurationSeconds(webSocketPingInterval)
1867 : webSocketPingInterval
1868 }, not starting the WebSocket ping`
1873 private stopWebSocketPing(): void {
1874 if (this.webSocketPingSetInterval
) {
1875 clearInterval(this.webSocketPingSetInterval
);
1879 private getConfiguredSupervisionUrl(): URL
{
1880 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1881 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1883 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1884 switch (Configuration
.getSupervisionUrlDistribution()) {
1885 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1887 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1889 case SupervisionUrlDistribution
.RANDOM
:
1890 this.configuredSupervisionUrlIndex
= Math.floor(
1891 Utils
.secureRandom() * supervisionUrls
.length
1894 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
1895 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1899 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1900 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
1903 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1906 return new URL(supervisionUrls
[this.configuredSupervisionUrlIndex
]);
1908 return new URL(supervisionUrls
as string);
1911 private getHeartbeatInterval(): number {
1912 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1914 StandardParametersKey
.HeartbeatInterval
1916 if (HeartbeatInterval
) {
1917 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1919 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1921 StandardParametersKey
.HeartBeatInterval
1923 if (HeartBeatInterval
) {
1924 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1926 !this.stationInfo
?.autoRegister
&&
1928 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1929 Constants.DEFAULT_HEARTBEAT_INTERVAL
1932 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1935 private stopHeartbeat(): void {
1936 if (this.heartbeatSetInterval
) {
1937 clearInterval(this.heartbeatSetInterval
);
1941 private terminateWSConnection(): void {
1942 if (this.isWebSocketConnectionOpened() === true) {
1943 this.wsConnection
.terminate();
1944 this.wsConnection
= null;
1948 private stopMeterValues(connectorId
: number) {
1949 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1950 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1954 private getReconnectExponentialDelay(): boolean {
1955 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1956 ? this.stationInfo
.reconnectExponentialDelay
1960 private async reconnect(): Promise
<void> {
1961 // Stop WebSocket ping
1962 this.stopWebSocketPing();
1964 this.stopHeartbeat();
1965 // Stop the ATG if needed
1966 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
=== true) {
1967 this.stopAutomaticTransactionGenerator();
1970 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1971 this.getAutoReconnectMaxRetries() === -1
1973 this.autoReconnectRetryCount
++;
1974 const reconnectDelay
= this.getReconnectExponentialDelay()
1975 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1976 : this.getConnectionTimeout() * 1000;
1977 const reconnectDelayWithdraw
= 1000;
1978 const reconnectTimeout
=
1979 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
1980 ? reconnectDelay
- reconnectDelayWithdraw
1983 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1986 )}ms, timeout ${reconnectTimeout}ms`
1988 await Utils
.sleep(reconnectDelay
);
1991 ' WebSocket: reconnecting try #' +
1992 this.autoReconnectRetryCount
.toString()
1994 this.openWSConnection(
1995 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
1996 { closeOpened
: true }
1998 this.wsConnectionRestarted
= true;
1999 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2001 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2002 this.autoReconnectRetryCount
2003 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2008 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
2009 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2012 private initializeConnectorStatus(connectorId
: number): void {
2013 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2014 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2015 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2016 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2017 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2018 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;