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 {
220 this.isInUnknownState() === false &&
221 (this.isInAcceptedState() === true || this.isInPendingState() === true)
225 public isChargingStationAvailable(): boolean {
226 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
229 public isConnectorAvailable(id
: number): boolean {
230 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
233 public getNumberOfConnectors(): number {
234 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
237 public getConnectorStatus(id
: number): ConnectorStatus
| undefined {
238 return this.connectors
.get(id
);
241 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
242 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
;
245 public getOcppStrictCompliance(): boolean {
246 return this.stationInfo
?.ocppStrictCompliance
?? false;
249 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
250 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
251 this.getCurrentOutType(stationInfo
),
255 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
256 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
257 ? localStationInfo
.voltageOut
261 public getConnectorMaximumAvailablePower(connectorId
: number): number {
262 let connectorAmperageLimitationPowerLimit
: number;
264 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
265 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
267 connectorAmperageLimitationPowerLimit
=
268 (this.getCurrentOutType() === CurrentType
.AC
269 ? ACElectricUtils
.powerTotal(
270 this.getNumberOfPhases(),
271 this.getVoltageOut(),
272 this.getAmperageLimitation() * this.getNumberOfConnectors()
274 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
277 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
278 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
280 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
281 isNaN(connectorAmperageLimitationPowerLimit
)
283 : connectorAmperageLimitationPowerLimit
,
284 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
288 public getTransactionIdTag(transactionId
: number): string | undefined {
289 for (const connectorId
of this.connectors
.keys()) {
290 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
291 return this.getConnectorStatus(connectorId
).transactionIdTag
;
296 public getOutOfOrderEndMeterValues(): boolean {
297 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
300 public getBeginEndMeterValues(): boolean {
301 return this.stationInfo
?.beginEndMeterValues
?? false;
304 public getMeteringPerTransaction(): boolean {
305 return this.stationInfo
?.meteringPerTransaction
?? true;
308 public getTransactionDataMeterValues(): boolean {
309 return this.stationInfo
?.transactionDataMeterValues
?? false;
312 public getMainVoltageMeterValues(): boolean {
313 return this.stationInfo
?.mainVoltageMeterValues
?? true;
316 public getPhaseLineToLineVoltageMeterValues(): boolean {
317 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
320 public getCustomValueLimitationMeterValues(): boolean {
321 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
324 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
325 for (const connectorId
of this.connectors
.keys()) {
328 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
335 public getEnergyActiveImportRegisterByTransactionId(
336 transactionId
: number,
339 return this.getEnergyActiveImportRegister(
340 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
345 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number {
346 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
));
349 public getAuthorizeRemoteTxRequests(): boolean {
350 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
352 StandardParametersKey
.AuthorizeRemoteTxRequests
354 return authorizeRemoteTxRequests
355 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
359 public getLocalAuthListEnabled(): boolean {
360 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
362 StandardParametersKey
.LocalAuthListEnabled
364 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
367 public startHeartbeat(): void {
369 this.getHeartbeatInterval() &&
370 this.getHeartbeatInterval() > 0 &&
371 !this.heartbeatSetInterval
373 // eslint-disable-next-line @typescript-eslint/no-misused-promises
374 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
375 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
377 RequestCommand
.HEARTBEAT
379 }, this.getHeartbeatInterval());
382 ' Heartbeat started every ' +
383 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
385 } else if (this.heartbeatSetInterval
) {
388 ' Heartbeat already started every ' +
389 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
393 `${this.logPrefix()} Heartbeat interval set to ${
394 this.getHeartbeatInterval()
395 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
396 : this.getHeartbeatInterval()
397 }, not starting the heartbeat`
402 public restartHeartbeat(): void {
404 this.stopHeartbeat();
406 this.startHeartbeat();
409 public restartWebSocketPing(): void {
410 // Stop WebSocket ping
411 this.stopWebSocketPing();
412 // Start WebSocket ping
413 this.startWebSocketPing();
416 public startMeterValues(connectorId
: number, interval
: number): void {
417 if (connectorId
=== 0) {
419 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
423 if (!this.getConnectorStatus(connectorId
)) {
425 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
429 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
431 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
435 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
436 !this.getConnectorStatus(connectorId
)?.transactionId
439 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
444 // eslint-disable-next-line @typescript-eslint/no-misused-promises
445 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
446 // eslint-disable-next-line @typescript-eslint/no-misused-promises
447 async (): Promise
<void> => {
448 // FIXME: Implement OCPP version agnostic helpers
449 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
452 this.getConnectorStatus(connectorId
).transactionId
,
455 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
457 RequestCommand
.METER_VALUES
,
460 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
461 meterValue
: [meterValue
],
469 `${this.logPrefix()} Charging station ${
470 StandardParametersKey.MeterValueSampleInterval
471 } configuration set to ${
472 interval ? Utils.formatDurationMilliSeconds(interval) : interval
473 }, not sending MeterValues`
478 public start(): void {
479 if (this.started
=== false) {
480 if (this.starting
=== false) {
481 this.starting
= true;
482 if (this.getEnableStatistics()) {
483 this.performanceStatistics
.start();
485 this.openWSConnection();
486 // Monitor charging station template file
487 this.templateFileWatcher
= FileUtils
.watchJsonFile(
489 FileType
.ChargingStationTemplate
,
492 (event
, filename
): void => {
493 if (filename
&& event
=== 'change') {
496 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
498 } file have changed, reload`
500 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
504 this.stopAutomaticTransactionGenerator();
506 this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true
508 this.startAutomaticTransactionGenerator();
510 if (this.getEnableStatistics()) {
511 this.performanceStatistics
.restart();
513 this.performanceStatistics
.stop();
515 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
518 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
526 parentPort
.postMessage(MessageChannelUtils
.buildStartedMessage(this));
527 this.starting
= false;
529 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
532 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
536 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
537 if (this.started
=== true) {
538 if (this.stopping
=== false) {
539 this.stopping
= true;
540 await this.stopMessageSequence(reason
);
541 this.closeWSConnection();
542 if (this.getEnableStatistics()) {
543 this.performanceStatistics
.stop();
545 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
546 this.templateFileWatcher
.close();
547 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
548 this.bootNotificationResponse
= null;
549 this.started
= false;
550 parentPort
.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
551 this.stopping
= false;
553 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
556 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
560 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
561 await this.stop(reason
);
562 await Utils
.sleep(this.stationInfo
.resetTime
);
567 public saveOcppConfiguration(): void {
568 if (this.getOcppPersistentConfiguration()) {
569 this.saveConfiguration();
573 public resetConnectorStatus(connectorId
: number): void {
574 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
575 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
576 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
577 this.getConnectorStatus(connectorId
).transactionStarted
= false;
578 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
579 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
580 delete this.getConnectorStatus(connectorId
).transactionId
;
581 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
582 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
583 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
584 this.stopMeterValues(connectorId
);
585 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
588 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean {
589 return ChargingStationConfigurationUtils
.getConfigurationKey(
591 StandardParametersKey
.SupportedFeatureProfiles
592 )?.value
.includes(featureProfile
);
595 public bufferMessage(message
: string): void {
596 this.messageBuffer
.add(message
);
599 public openWSConnection(
600 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
601 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
603 terminateOpened
: false,
606 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
607 params
.closeOpened
= params
?.closeOpened
?? false;
608 params
.terminateOpened
= params
?.terminateOpened
?? false;
610 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
611 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
613 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
615 if (params
?.closeOpened
) {
616 this.closeWSConnection();
618 if (params
?.terminateOpened
) {
619 this.terminateWSConnection();
621 let protocol
: string;
622 switch (this.getOcppVersion()) {
623 case OCPPVersion
.VERSION_16
:
624 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
627 this.handleUnsupportedVersion(this.getOcppVersion());
631 if (this.isWebSocketConnectionOpened() === true) {
633 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
639 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
642 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
644 // Handle WebSocket message
645 this.wsConnection
.on(
647 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
649 // Handle WebSocket error
650 this.wsConnection
.on(
652 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
654 // Handle WebSocket close
655 this.wsConnection
.on(
657 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
659 // Handle WebSocket open
660 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
661 // Handle WebSocket ping
662 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
663 // Handle WebSocket pong
664 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
667 public closeWSConnection(): void {
668 if (this.isWebSocketConnectionOpened() === true) {
669 this.wsConnection
.close();
670 this.wsConnection
= null;
674 public startAutomaticTransactionGenerator(
675 connectorIds
?: number[],
676 automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
678 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
679 automaticTransactionGeneratorConfiguration
??
680 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
683 if (!Utils
.isEmptyArray(connectorIds
)) {
684 for (const connectorId
of connectorIds
) {
685 this.automaticTransactionGenerator
.startConnector(connectorId
);
688 this.automaticTransactionGenerator
.start();
690 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
693 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
694 if (!Utils
.isEmptyArray(connectorIds
)) {
695 for (const connectorId
of connectorIds
) {
696 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
699 this.automaticTransactionGenerator
?.stop();
701 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
704 public async stopTransactionOnConnector(
706 reason
= StopTransactionReason
.NONE
707 ): Promise
<StopTransactionResponse
> {
708 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
710 this.getBeginEndMeterValues() === true &&
711 this.getOcppStrictCompliance() === true &&
712 this.getOutOfOrderEndMeterValues() === false
714 // FIXME: Implement OCPP version agnostic helpers
715 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
718 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
720 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
722 RequestCommand
.METER_VALUES
,
726 meterValue
: [transactionEndMeterValue
],
730 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
732 RequestCommand
.STOP_TRANSACTION
,
735 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
741 private flushMessageBuffer(): void {
742 if (this.messageBuffer
.size
> 0) {
743 this.messageBuffer
.forEach((message
) => {
744 // TODO: evaluate the need to track performance
745 this.wsConnection
.send(message
);
746 this.messageBuffer
.delete(message
);
751 private getSupervisionUrlOcppConfiguration(): boolean {
752 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
755 private getSupervisionUrlOcppKey(): string {
756 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
759 private getTemplateFromFile(): ChargingStationTemplate
| null {
760 let template
: ChargingStationTemplate
= null;
762 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
763 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
765 const measureId
= `${FileType.ChargingStationTemplate} read`;
766 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
767 template
= JSON
.parse(
768 fs
.readFileSync(this.templateFile
, 'utf8')
769 ) as ChargingStationTemplate
;
770 PerformanceStatistics
.endMeasure(measureId
, beginId
);
771 template
.templateHash
= crypto
772 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
773 .update(JSON
.stringify(template
))
775 this.sharedLRUCache
.setChargingStationTemplate(template
);
778 FileUtils
.handleFileException(
780 FileType
.ChargingStationTemplate
,
782 error
as NodeJS
.ErrnoException
788 private getStationInfoFromTemplate(): ChargingStationInfo
{
789 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
790 if (Utils
.isNullOrUndefined(stationTemplate
)) {
791 const errorMsg
= 'Failed to read charging station template file';
792 logger
.error(`${this.logPrefix()} ${errorMsg}`);
793 throw new BaseError(errorMsg
);
795 if (Utils
.isEmptyObject(stationTemplate
)) {
796 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
797 logger
.error(`${this.logPrefix()} ${errorMsg}`);
798 throw new BaseError(errorMsg
);
800 // Deprecation template keys section
801 ChargingStationUtils
.warnDeprecatedTemplateKey(
806 "Use 'supervisionUrls' instead"
808 ChargingStationUtils
.convertDeprecatedTemplateKey(
813 const stationInfo
: ChargingStationInfo
=
814 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
815 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
816 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
820 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
821 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
822 stationTemplate
.power
= stationTemplate
.power
as number[];
823 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
824 stationInfo
.maximumPower
=
825 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
826 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
827 : stationTemplate
.power
[powerArrayRandomIndex
];
829 stationTemplate
.power
= stationTemplate
.power
as number;
830 stationInfo
.maximumPower
=
831 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
832 ? stationTemplate
.power
* 1000
833 : stationTemplate
.power
;
835 stationInfo
.resetTime
= stationTemplate
.resetTime
836 ? stationTemplate
.resetTime
* 1000
837 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
838 const configuredMaxConnectors
=
839 ChargingStationUtils
.getConfiguredNumberOfConnectors(stationTemplate
);
840 ChargingStationUtils
.checkConfiguredMaxConnectors(
841 configuredMaxConnectors
,
845 const templateMaxConnectors
=
846 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
847 ChargingStationUtils
.checkTemplateMaxConnectors(
848 templateMaxConnectors
,
853 configuredMaxConnectors
>
854 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
855 !stationTemplate
?.randomConnectors
858 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
860 }, forcing random connector configurations affectation`
862 stationInfo
.randomConnectors
= true;
864 // Build connectors if needed (FIXME: should be factored out)
865 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
866 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
867 ChargingStationUtils
.createStationInfoHash(stationInfo
);
871 private getStationInfoFromFile(): ChargingStationInfo
| null {
872 let stationInfo
: ChargingStationInfo
= null;
873 this.getStationInfoPersistentConfiguration() &&
874 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
875 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
879 private getStationInfo(): ChargingStationInfo
{
880 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
881 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
882 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
883 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
884 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
885 return this.stationInfo
;
887 return stationInfoFromFile
;
889 stationInfoFromFile
&&
890 ChargingStationUtils
.propagateSerialNumber(
891 this.getTemplateFromFile(),
893 stationInfoFromTemplate
895 return stationInfoFromTemplate
;
898 private saveStationInfo(): void {
899 if (this.getStationInfoPersistentConfiguration()) {
900 this.saveConfiguration();
904 private getOcppVersion(): OCPPVersion
{
905 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
908 private getOcppPersistentConfiguration(): boolean {
909 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
912 private getStationInfoPersistentConfiguration(): boolean {
913 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
916 private handleUnsupportedVersion(version
: OCPPVersion
) {
917 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
918 logger
.error(`${this.logPrefix()} ${errMsg}`);
919 throw new BaseError(errMsg
);
922 private initialize(): void {
923 this.configurationFile
= path
.join(
924 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
925 ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile()) + '.json'
927 this.stationInfo
= this.getStationInfo();
928 this.saveStationInfo();
929 // Avoid duplication of connectors related information in RAM
930 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
931 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
932 if (this.getEnableStatistics()) {
933 this.performanceStatistics
= PerformanceStatistics
.getInstance(
934 this.stationInfo
.hashId
,
935 this.stationInfo
.chargingStationId
,
936 this.configuredSupervisionUrl
939 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
942 this.powerDivider
= this.getPowerDivider();
943 // OCPP configuration
944 this.ocppConfiguration
= this.getOcppConfiguration();
945 this.initializeOcppConfiguration();
946 switch (this.getOcppVersion()) {
947 case OCPPVersion
.VERSION_16
:
948 this.ocppIncomingRequestService
=
949 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
950 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
951 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
955 this.handleUnsupportedVersion(this.getOcppVersion());
958 if (this.stationInfo
?.autoRegister
=== true) {
959 this.bootNotificationResponse
= {
960 currentTime
: new Date().toISOString(),
961 interval
: this.getHeartbeatInterval() / 1000,
962 status: RegistrationStatus
.ACCEPTED
,
967 private initializeOcppConfiguration(): void {
969 !ChargingStationConfigurationUtils
.getConfigurationKey(
971 StandardParametersKey
.HeartbeatInterval
974 ChargingStationConfigurationUtils
.addConfigurationKey(
976 StandardParametersKey
.HeartbeatInterval
,
981 !ChargingStationConfigurationUtils
.getConfigurationKey(
983 StandardParametersKey
.HeartBeatInterval
986 ChargingStationConfigurationUtils
.addConfigurationKey(
988 StandardParametersKey
.HeartBeatInterval
,
994 this.getSupervisionUrlOcppConfiguration() &&
995 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
997 ChargingStationConfigurationUtils
.addConfigurationKey(
999 this.getSupervisionUrlOcppKey(),
1000 this.configuredSupervisionUrl
.href
,
1004 !this.getSupervisionUrlOcppConfiguration() &&
1005 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1007 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1009 this.getSupervisionUrlOcppKey(),
1014 this.stationInfo
.amperageLimitationOcppKey
&&
1015 !ChargingStationConfigurationUtils
.getConfigurationKey(
1017 this.stationInfo
.amperageLimitationOcppKey
1020 ChargingStationConfigurationUtils
.addConfigurationKey(
1022 this.stationInfo
.amperageLimitationOcppKey
,
1024 this.stationInfo
.maximumAmperage
*
1025 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1030 !ChargingStationConfigurationUtils
.getConfigurationKey(
1032 StandardParametersKey
.SupportedFeatureProfiles
1035 ChargingStationConfigurationUtils
.addConfigurationKey(
1037 StandardParametersKey
.SupportedFeatureProfiles
,
1038 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1041 ChargingStationConfigurationUtils
.addConfigurationKey(
1043 StandardParametersKey
.NumberOfConnectors
,
1044 this.getNumberOfConnectors().toString(),
1049 !ChargingStationConfigurationUtils
.getConfigurationKey(
1051 StandardParametersKey
.MeterValuesSampledData
1054 ChargingStationConfigurationUtils
.addConfigurationKey(
1056 StandardParametersKey
.MeterValuesSampledData
,
1057 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1061 !ChargingStationConfigurationUtils
.getConfigurationKey(
1063 StandardParametersKey
.ConnectorPhaseRotation
1066 const connectorPhaseRotation
= [];
1067 for (const connectorId
of this.connectors
.keys()) {
1069 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1070 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1071 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1072 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1074 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1075 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1076 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1077 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1080 ChargingStationConfigurationUtils
.addConfigurationKey(
1082 StandardParametersKey
.ConnectorPhaseRotation
,
1083 connectorPhaseRotation
.toString()
1087 !ChargingStationConfigurationUtils
.getConfigurationKey(
1089 StandardParametersKey
.AuthorizeRemoteTxRequests
1092 ChargingStationConfigurationUtils
.addConfigurationKey(
1094 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1099 !ChargingStationConfigurationUtils
.getConfigurationKey(
1101 StandardParametersKey
.LocalAuthListEnabled
1103 ChargingStationConfigurationUtils
.getConfigurationKey(
1105 StandardParametersKey
.SupportedFeatureProfiles
1106 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1108 ChargingStationConfigurationUtils
.addConfigurationKey(
1110 StandardParametersKey
.LocalAuthListEnabled
,
1115 !ChargingStationConfigurationUtils
.getConfigurationKey(
1117 StandardParametersKey
.ConnectionTimeOut
1120 ChargingStationConfigurationUtils
.addConfigurationKey(
1122 StandardParametersKey
.ConnectionTimeOut
,
1123 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1126 this.saveOcppConfiguration();
1129 private initializeConnectors(
1130 stationInfo
: ChargingStationInfo
,
1131 configuredMaxConnectors
: number,
1132 templateMaxConnectors
: number
1134 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1135 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1136 logger
.error(`${this.logPrefix()} ${logMsg}`);
1137 throw new BaseError(logMsg
);
1139 if (!stationInfo
?.Connectors
[0]) {
1141 `${this.logPrefix()} Charging station information from template ${
1143 } with no connector Id 0 configuration`
1146 if (stationInfo
?.Connectors
) {
1147 const connectorsConfigHash
= crypto
1148 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1149 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1151 const connectorsConfigChanged
=
1152 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1153 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1154 connectorsConfigChanged
&& this.connectors
.clear();
1155 this.connectorsConfigurationHash
= connectorsConfigHash
;
1156 // Add connector Id 0
1157 let lastConnector
= '0';
1158 for (lastConnector
in stationInfo
?.Connectors
) {
1159 const connectorStatus
= stationInfo
?.Connectors
[lastConnector
];
1160 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1162 lastConnectorId
=== 0 &&
1163 this.getUseConnectorId0(stationInfo
) === true &&
1166 this.checkStationInfoConnectorStatus(lastConnectorId
, connectorStatus
);
1167 this.connectors
.set(
1169 Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
)
1171 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1172 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1173 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1177 // Generate all connectors
1178 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1179 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1180 const randConnectorId
= stationInfo
?.randomConnectors
1181 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1183 const connectorStatus
= stationInfo
?.Connectors
[randConnectorId
.toString()];
1184 this.checkStationInfoConnectorStatus(randConnectorId
, connectorStatus
);
1185 this.connectors
.set(index
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
1186 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1187 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1188 this.getConnectorStatus(index
).chargingProfiles
= [];
1195 `${this.logPrefix()} Charging station information from template ${
1197 } with no connectors configuration defined, using already defined connectors`
1200 // Initialize transaction attributes on connectors
1201 for (const connectorId
of this.connectors
.keys()) {
1204 (this.getConnectorStatus(connectorId
).transactionStarted
=== undefined ||
1205 this.getConnectorStatus(connectorId
).transactionStarted
=== false)
1207 this.initializeConnectorStatus(connectorId
);
1212 private checkStationInfoConnectorStatus(
1213 connectorId
: number,
1214 connectorStatus
: ConnectorStatus
1216 if (!Utils
.isNullOrUndefined(connectorStatus
?.status)) {
1218 `${this.logPrefix()} Charging station information from template ${
1220 } with connector ${connectorId} status configuration defined, undefine it`
1222 connectorStatus
.status = undefined;
1226 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1227 let configuration
: ChargingStationConfiguration
= null;
1228 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1230 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1231 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1232 this.configurationFileHash
1235 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1236 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1237 configuration
= JSON
.parse(
1238 fs
.readFileSync(this.configurationFile
, 'utf8')
1239 ) as ChargingStationConfiguration
;
1240 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1241 this.configurationFileHash
= configuration
.configurationHash
;
1242 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1245 FileUtils
.handleFileException(
1247 FileType
.ChargingStationConfiguration
,
1248 this.configurationFile
,
1249 error
as NodeJS
.ErrnoException
1253 return configuration
;
1256 private saveConfiguration(): void {
1257 if (this.configurationFile
) {
1259 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1260 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1262 const configurationData
: ChargingStationConfiguration
=
1263 this.getConfigurationFromFile() ?? {};
1264 this.ocppConfiguration
?.configurationKey
&&
1265 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1266 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1267 delete configurationData
.configurationHash
;
1268 const configurationHash
= crypto
1269 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1270 .update(JSON
.stringify(configurationData
))
1272 if (this.configurationFileHash
!== configurationHash
) {
1273 configurationData
.configurationHash
= configurationHash
;
1274 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1275 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1276 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1277 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1278 fs
.closeSync(fileDescriptor
);
1279 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1280 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1281 this.configurationFileHash
= configurationHash
;
1282 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1285 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1286 this.configurationFile
1291 FileUtils
.handleFileException(
1293 FileType
.ChargingStationConfiguration
,
1294 this.configurationFile
,
1295 error
as NodeJS
.ErrnoException
1300 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1305 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1306 return this.getTemplateFromFile()?.Configuration
?? null;
1309 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1310 let configuration
: ChargingStationConfiguration
= null;
1311 if (this.getOcppPersistentConfiguration()) {
1312 const configurationFromFile
= this.getConfigurationFromFile();
1313 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1315 configuration
&& delete configuration
.stationInfo
;
1316 return configuration
;
1319 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1320 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1321 if (!ocppConfiguration
) {
1322 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1324 return ocppConfiguration
;
1327 private async onOpen(): Promise
<void> {
1328 if (this.isWebSocketConnectionOpened() === true) {
1330 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1332 if (this.isRegistered() === false) {
1333 // Send BootNotification
1334 let registrationRetryCount
= 0;
1336 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1337 BootNotificationRequest
,
1338 BootNotificationResponse
1339 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1340 skipBufferingOnError
: true,
1342 if (this.isRegistered() === false) {
1343 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1345 this.bootNotificationResponse
?.interval
1346 ? this.bootNotificationResponse
.interval
* 1000
1347 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1351 this.isRegistered() === false &&
1352 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1353 this.getRegistrationMaxRetries() === -1)
1356 if (this.isRegistered() === true) {
1357 if (this.isInAcceptedState()) {
1358 await this.startMessageSequence();
1362 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1365 this.wsConnectionRestarted
= false;
1366 this.autoReconnectRetryCount
= 0;
1367 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1370 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1375 private async onClose(code
: number, reason
: string): Promise
<void> {
1378 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1379 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1381 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1383 )}' and reason '${reason}'`
1385 this.autoReconnectRetryCount
= 0;
1390 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1392 )}' and reason '${reason}'`
1394 this.started
=== true && (await this.reconnect());
1397 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1400 private async onMessage(data
: Data
): Promise
<void> {
1401 let messageType
: number;
1402 let messageId
: string;
1403 let commandName
: IncomingRequestCommand
;
1404 let commandPayload
: JsonType
;
1405 let errorType
: ErrorType
;
1406 let errorMessage
: string;
1407 let errorDetails
: JsonType
;
1408 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1409 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1410 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1411 let requestPayload
: JsonType
;
1412 let cachedRequest
: CachedRequest
;
1415 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1416 if (Array.isArray(request
) === true) {
1417 [messageType
, messageId
] = request
;
1418 // Check the type of message
1419 switch (messageType
) {
1421 case MessageType
.CALL_MESSAGE
:
1422 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1423 if (this.getEnableStatistics() === true) {
1424 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1427 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1431 // Process the message
1432 await this.ocppIncomingRequestService
.incomingRequestHandler(
1440 case MessageType
.CALL_RESULT_MESSAGE
:
1441 [, , commandPayload
] = request
as Response
;
1442 if (this.requests
.has(messageId
) === false) {
1444 throw new OCPPError(
1445 ErrorType
.INTERNAL_ERROR
,
1446 `Response for unknown message id ${messageId}`,
1452 cachedRequest
= this.requests
.get(messageId
);
1453 if (Array.isArray(cachedRequest
) === true) {
1454 [responseCallback
, errorCallback
, requestCommandName
, requestPayload
] = cachedRequest
;
1456 throw new OCPPError(
1457 ErrorType
.PROTOCOL_ERROR
,
1458 `Cached request for message id ${messageId} response is not an array`,
1460 cachedRequest
as unknown
as JsonType
1464 `${this.logPrefix()} << Command '${
1465 requestCommandName ?? Constants.UNKNOWN_COMMAND
1466 }' received response payload: ${JSON.stringify(request)}`
1468 responseCallback(commandPayload
, requestPayload
);
1471 case MessageType
.CALL_ERROR_MESSAGE
:
1472 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1473 if (this.requests
.has(messageId
) === false) {
1475 throw new OCPPError(
1476 ErrorType
.INTERNAL_ERROR
,
1477 `Error response for unknown message id ${messageId}`,
1479 { errorType
, errorMessage
, errorDetails
}
1482 cachedRequest
= this.requests
.get(messageId
);
1483 if (Array.isArray(cachedRequest
) === true) {
1484 [, errorCallback
, requestCommandName
] = cachedRequest
;
1486 throw new OCPPError(
1487 ErrorType
.PROTOCOL_ERROR
,
1488 `Cached request for message id ${messageId} error response is not an array`,
1490 cachedRequest
as unknown
as JsonType
1494 `${this.logPrefix()} << Command '${
1495 requestCommandName ?? Constants.UNKNOWN_COMMAND
1496 }' received error payload: ${JSON.stringify(request)}`
1498 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1502 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1503 errMsg
= `Wrong message type ${messageType}`;
1504 logger
.error(`${this.logPrefix()} ${errMsg}`);
1505 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1507 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1509 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1516 `${this.logPrefix()} Incoming OCPP command '${
1517 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1518 }' message '${data.toString()}'${
1519 messageType !== MessageType.CALL_MESSAGE
1520 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1522 } processing error:`,
1525 if (error
instanceof OCPPError
=== false) {
1527 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1528 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1529 }' message '${data.toString()}' handling is not an OCPPError:`,
1533 switch (messageType
) {
1534 case MessageType
.CALL_MESSAGE
:
1536 await this.ocppRequestService
.sendError(
1540 commandName
?? requestCommandName
?? null
1543 case MessageType
.CALL_RESULT_MESSAGE
:
1544 case MessageType
.CALL_ERROR_MESSAGE
:
1545 if (errorCallback
) {
1546 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1547 errorCallback(error
as OCPPError
, false);
1549 // Remove the request from the cache in case of error at response handling
1550 this.requests
.delete(messageId
);
1557 private onPing(): void {
1558 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1561 private onPong(): void {
1562 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1565 private onError(error
: WSError
): void {
1566 this.closeWSConnection();
1567 logger
.error(this.logPrefix() + ' WebSocket error:', error
);
1570 private getEnergyActiveImportRegister(
1571 connectorStatus
: ConnectorStatus
,
1574 if (this.getMeteringPerTransaction() === true) {
1577 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1578 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1583 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1584 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1588 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean {
1589 const localStationInfo
= stationInfo
?? this.stationInfo
;
1590 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1591 ? localStationInfo
.useConnectorId0
1595 private getNumberOfRunningTransactions(): number {
1597 for (const connectorId
of this.connectors
.keys()) {
1598 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1605 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1606 for (const connectorId
of this.connectors
.keys()) {
1607 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1608 await this.stopTransactionOnConnector(connectorId
, reason
);
1614 private getConnectionTimeout(): number {
1616 ChargingStationConfigurationUtils
.getConfigurationKey(
1618 StandardParametersKey
.ConnectionTimeOut
1623 ChargingStationConfigurationUtils
.getConfigurationKey(
1625 StandardParametersKey
.ConnectionTimeOut
1627 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1630 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1633 // -1 for unlimited, 0 for disabling
1634 private getAutoReconnectMaxRetries(): number {
1635 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1636 return this.stationInfo
.autoReconnectMaxRetries
;
1638 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1639 return Configuration
.getAutoReconnectMaxRetries();
1645 private getRegistrationMaxRetries(): number {
1646 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1647 return this.stationInfo
.registrationMaxRetries
;
1652 private getPowerDivider(): number {
1653 let powerDivider
= this.getNumberOfConnectors();
1654 if (this.stationInfo
?.powerSharedByConnectors
) {
1655 powerDivider
= this.getNumberOfRunningTransactions();
1657 return powerDivider
;
1660 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1661 const localStationInfo
= stationInfo
?? this.stationInfo
;
1662 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1665 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1666 const maximumPower
= this.getMaximumPower(stationInfo
);
1667 switch (this.getCurrentOutType(stationInfo
)) {
1668 case CurrentType
.AC
:
1669 return ACElectricUtils
.amperagePerPhaseFromPower(
1670 this.getNumberOfPhases(stationInfo
),
1671 maximumPower
/ this.getNumberOfConnectors(),
1672 this.getVoltageOut(stationInfo
)
1674 case CurrentType
.DC
:
1675 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1679 private getAmperageLimitation(): number | undefined {
1681 this.stationInfo
.amperageLimitationOcppKey
&&
1682 ChargingStationConfigurationUtils
.getConfigurationKey(
1684 this.stationInfo
.amperageLimitationOcppKey
1689 ChargingStationConfigurationUtils
.getConfigurationKey(
1691 this.stationInfo
.amperageLimitationOcppKey
1693 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1698 private getChargingProfilePowerLimit(connectorId
: number): number | undefined {
1699 let limit
: number, matchingChargingProfile
: ChargingProfile
;
1700 let chargingProfiles
: ChargingProfile
[] = [];
1701 // Get charging profiles for connector and sort by stack level
1702 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
1703 (a
, b
) => b
.stackLevel
- a
.stackLevel
1705 // Get profiles on connector 0
1706 if (this.getConnectorStatus(0).chargingProfiles
) {
1707 chargingProfiles
.push(
1708 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
1711 if (!Utils
.isEmptyArray(chargingProfiles
)) {
1712 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
1716 if (!Utils
.isNullOrUndefined(result
)) {
1717 limit
= result
.limit
;
1718 matchingChargingProfile
= result
.matchingChargingProfile
;
1719 switch (this.getCurrentOutType()) {
1720 case CurrentType
.AC
:
1722 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
1723 ChargingRateUnitType
.WATT
1725 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
1727 case CurrentType
.DC
:
1729 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
1730 ChargingRateUnitType
.WATT
1732 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
1734 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
1735 if (limit
> connectorMaximumPower
) {
1737 `${this.logPrefix()} Charging profile id ${
1738 matchingChargingProfile.chargingProfileId
1739 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
1740 this.getConnectorStatus(connectorId
).chargingProfiles
1742 limit
= connectorMaximumPower
;
1749 private async startMessageSequence(): Promise
<void> {
1750 if (this.stationInfo
?.autoRegister
=== true) {
1751 await this.ocppRequestService
.requestHandler
<
1752 BootNotificationRequest
,
1753 BootNotificationResponse
1754 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1755 skipBufferingOnError
: true,
1758 // Start WebSocket ping
1759 this.startWebSocketPing();
1761 this.startHeartbeat();
1762 // Initialize connectors status
1763 for (const connectorId
of this.connectors
.keys()) {
1764 let chargePointStatus
: ChargePointStatus
;
1765 if (connectorId
=== 0) {
1768 !this.getConnectorStatus(connectorId
)?.status &&
1769 (this.isChargingStationAvailable() === false ||
1770 this.isConnectorAvailable(connectorId
) === false)
1772 chargePointStatus
= ChargePointStatus
.UNAVAILABLE
;
1774 !this.getConnectorStatus(connectorId
)?.status &&
1775 this.getConnectorStatus(connectorId
)?.bootStatus
1777 // Set boot status in template at startup
1778 chargePointStatus
= this.getConnectorStatus(connectorId
).bootStatus
;
1779 } else if (this.getConnectorStatus(connectorId
)?.status) {
1780 // Set previous status at startup
1781 chargePointStatus
= this.getConnectorStatus(connectorId
).status;
1783 // Set default status
1784 chargePointStatus
= ChargePointStatus
.AVAILABLE
;
1786 await this.ocppRequestService
.requestHandler
<
1787 StatusNotificationRequest
,
1788 StatusNotificationResponse
1789 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1791 status: chargePointStatus
,
1792 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1794 this.getConnectorStatus(connectorId
).status = chargePointStatus
;
1797 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true) {
1798 this.startAutomaticTransactionGenerator();
1800 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
1803 private async stopMessageSequence(
1804 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1806 // Stop WebSocket ping
1807 this.stopWebSocketPing();
1809 this.stopHeartbeat();
1810 // Stop ongoing transactions
1811 if (this.automaticTransactionGenerator
?.started
=== true) {
1812 this.stopAutomaticTransactionGenerator();
1814 await this.stopRunningTransactions(reason
);
1816 for (const connectorId
of this.connectors
.keys()) {
1817 if (connectorId
> 0) {
1818 await this.ocppRequestService
.requestHandler
<
1819 StatusNotificationRequest
,
1820 StatusNotificationResponse
1821 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1823 status: ChargePointStatus
.UNAVAILABLE
,
1824 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1826 this.getConnectorStatus(connectorId
).status = null;
1831 private startWebSocketPing(): void {
1832 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1834 StandardParametersKey
.WebSocketPingInterval
1836 ? Utils
.convertToInt(
1837 ChargingStationConfigurationUtils
.getConfigurationKey(
1839 StandardParametersKey
.WebSocketPingInterval
1843 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1844 this.webSocketPingSetInterval
= setInterval(() => {
1845 if (this.isWebSocketConnectionOpened() === true) {
1846 this.wsConnection
.ping((): void => {
1847 /* This is intentional */
1850 }, webSocketPingInterval
* 1000);
1853 ' WebSocket ping started every ' +
1854 Utils
.formatDurationSeconds(webSocketPingInterval
)
1856 } else if (this.webSocketPingSetInterval
) {
1859 ' WebSocket ping already started every ' +
1860 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
=== false &&
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
);
1990 this.logPrefix() + ' WebSocket connection retry #' + this.autoReconnectRetryCount
.toString()
1992 this.openWSConnection(
1993 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
1994 { closeOpened
: true }
1996 this.wsConnectionRestarted
= true;
1997 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1999 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2000 this.autoReconnectRetryCount
2001 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`
2006 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
2007 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2010 private initializeConnectorStatus(connectorId
: number): void {
2011 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2012 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2013 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2014 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2015 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2016 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;