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:`,
522 parentPort
.postMessage(MessageChannelUtils
.buildStartedMessage(this));
523 this.starting
= false;
525 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
528 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
532 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
533 if (this.started
=== true) {
534 if (this.stopping
=== false) {
535 this.stopping
= true;
536 await this.stopMessageSequence(reason
);
537 for (const connectorId
of this.connectors
.keys()) {
538 if (connectorId
> 0) {
539 await this.ocppRequestService
.requestHandler
<
540 StatusNotificationRequest
,
541 StatusNotificationResponse
542 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
544 status: ChargePointStatus
.UNAVAILABLE
,
545 errorCode
: ChargePointErrorCode
.NO_ERROR
,
547 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
550 this.closeWSConnection();
551 if (this.getEnableStatistics()) {
552 this.performanceStatistics
.stop();
554 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
555 this.templateFileWatcher
.close();
556 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
557 this.bootNotificationResponse
= null;
558 this.started
= false;
559 parentPort
.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
560 this.stopping
= false;
562 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
565 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
569 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
570 await this.stop(reason
);
571 await Utils
.sleep(this.stationInfo
.resetTime
);
576 public saveOcppConfiguration(): void {
577 if (this.getOcppPersistentConfiguration()) {
578 this.saveConfiguration();
582 public resetConnectorStatus(connectorId
: number): void {
583 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
584 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
585 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
586 this.getConnectorStatus(connectorId
).transactionStarted
= false;
587 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
588 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
589 delete this.getConnectorStatus(connectorId
).transactionId
;
590 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
591 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
592 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
593 this.stopMeterValues(connectorId
);
594 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
597 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean {
598 return ChargingStationConfigurationUtils
.getConfigurationKey(
600 StandardParametersKey
.SupportedFeatureProfiles
601 )?.value
.includes(featureProfile
);
604 public bufferMessage(message
: string): void {
605 this.messageBuffer
.add(message
);
608 public openWSConnection(
609 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
610 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
612 terminateOpened
: false,
615 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
616 params
.closeOpened
= params
?.closeOpened
?? false;
617 params
.terminateOpened
= params
?.terminateOpened
?? false;
619 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
620 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
622 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
624 if (params
?.closeOpened
) {
625 this.closeWSConnection();
627 if (params
?.terminateOpened
) {
628 this.terminateWSConnection();
630 let protocol
: string;
631 switch (this.getOcppVersion()) {
632 case OCPPVersion
.VERSION_16
:
633 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
636 this.handleUnsupportedVersion(this.getOcppVersion());
640 if (this.isWebSocketConnectionOpened()) {
642 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
648 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
651 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
653 // Handle WebSocket message
654 this.wsConnection
.on(
656 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
658 // Handle WebSocket error
659 this.wsConnection
.on(
661 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
663 // Handle WebSocket close
664 this.wsConnection
.on(
666 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
668 // Handle WebSocket open
669 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
670 // Handle WebSocket ping
671 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
672 // Handle WebSocket pong
673 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
676 public closeWSConnection(): void {
677 if (this.isWebSocketConnectionOpened()) {
678 this.wsConnection
.close();
679 this.wsConnection
= null;
683 public startAutomaticTransactionGenerator(
684 connectorIds
?: number[],
685 automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
687 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
688 automaticTransactionGeneratorConfiguration
??
689 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
692 if (!Utils
.isEmptyArray(connectorIds
)) {
693 for (const connectorId
of connectorIds
) {
694 this.automaticTransactionGenerator
.startConnector(connectorId
);
697 this.automaticTransactionGenerator
.start();
699 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
702 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
703 if (!Utils
.isEmptyArray(connectorIds
)) {
704 for (const connectorId
of connectorIds
) {
705 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
708 this.automaticTransactionGenerator
?.stop();
710 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
713 public async stopTransactionOnConnector(
715 reason
= StopTransactionReason
.NONE
716 ): Promise
<StopTransactionResponse
> {
717 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
719 this.getBeginEndMeterValues() &&
720 this.getOcppStrictCompliance() &&
721 !this.getOutOfOrderEndMeterValues()
723 // FIXME: Implement OCPP version agnostic helpers
724 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
727 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
729 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
731 RequestCommand
.METER_VALUES
,
735 meterValue
: [transactionEndMeterValue
],
739 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
741 RequestCommand
.STOP_TRANSACTION
,
744 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
750 private flushMessageBuffer(): void {
751 if (this.messageBuffer
.size
> 0) {
752 this.messageBuffer
.forEach((message
) => {
753 // TODO: evaluate the need to track performance
754 this.wsConnection
.send(message
);
755 this.messageBuffer
.delete(message
);
760 private getSupervisionUrlOcppConfiguration(): boolean {
761 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
764 private getSupervisionUrlOcppKey(): string {
765 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
768 private getTemplateFromFile(): ChargingStationTemplate
| null {
769 let template
: ChargingStationTemplate
= null;
771 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
772 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
774 const measureId
= `${FileType.ChargingStationTemplate} read`;
775 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
776 template
= JSON
.parse(
777 fs
.readFileSync(this.templateFile
, 'utf8')
778 ) as ChargingStationTemplate
;
779 PerformanceStatistics
.endMeasure(measureId
, beginId
);
780 template
.templateHash
= crypto
781 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
782 .update(JSON
.stringify(template
))
784 this.sharedLRUCache
.setChargingStationTemplate(template
);
787 FileUtils
.handleFileException(
789 FileType
.ChargingStationTemplate
,
791 error
as NodeJS
.ErrnoException
797 private getStationInfoFromTemplate(): ChargingStationInfo
{
798 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
799 if (Utils
.isNullOrUndefined(stationTemplate
)) {
800 const errorMsg
= 'Failed to read charging station template file';
801 logger
.error(`${this.logPrefix()} ${errorMsg}`);
802 throw new BaseError(errorMsg
);
804 if (Utils
.isEmptyObject(stationTemplate
)) {
805 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
806 logger
.error(`${this.logPrefix()} ${errorMsg}`);
807 throw new BaseError(errorMsg
);
809 // Deprecation template keys section
810 ChargingStationUtils
.warnDeprecatedTemplateKey(
815 "Use 'supervisionUrls' instead"
817 ChargingStationUtils
.convertDeprecatedTemplateKey(
822 const stationInfo
: ChargingStationInfo
=
823 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
824 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
825 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
829 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
830 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
831 stationTemplate
.power
= stationTemplate
.power
as number[];
832 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
833 stationInfo
.maximumPower
=
834 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
835 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
836 : stationTemplate
.power
[powerArrayRandomIndex
];
838 stationTemplate
.power
= stationTemplate
.power
as number;
839 stationInfo
.maximumPower
=
840 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
841 ? stationTemplate
.power
* 1000
842 : stationTemplate
.power
;
844 stationInfo
.resetTime
= stationTemplate
.resetTime
845 ? stationTemplate
.resetTime
* 1000
846 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
847 const configuredMaxConnectors
=
848 ChargingStationUtils
.getConfiguredNumberOfConnectors(stationTemplate
);
849 ChargingStationUtils
.checkConfiguredMaxConnectors(
850 configuredMaxConnectors
,
854 const templateMaxConnectors
=
855 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
856 ChargingStationUtils
.checkTemplateMaxConnectors(
857 templateMaxConnectors
,
862 configuredMaxConnectors
>
863 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
864 !stationTemplate
?.randomConnectors
867 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
869 }, forcing random connector configurations affectation`
871 stationInfo
.randomConnectors
= true;
873 // Build connectors if needed (FIXME: should be factored out)
874 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
875 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
876 ChargingStationUtils
.createStationInfoHash(stationInfo
);
880 private getStationInfoFromFile(): ChargingStationInfo
| null {
881 let stationInfo
: ChargingStationInfo
= null;
882 this.getStationInfoPersistentConfiguration() &&
883 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
884 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
888 private getStationInfo(): ChargingStationInfo
{
889 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
890 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
891 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
892 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
893 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
894 return this.stationInfo
;
896 return stationInfoFromFile
;
898 stationInfoFromFile
&&
899 ChargingStationUtils
.propagateSerialNumber(
900 this.getTemplateFromFile(),
902 stationInfoFromTemplate
904 return stationInfoFromTemplate
;
907 private saveStationInfo(): void {
908 if (this.getStationInfoPersistentConfiguration()) {
909 this.saveConfiguration();
913 private getOcppVersion(): OCPPVersion
{
914 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
917 private getOcppPersistentConfiguration(): boolean {
918 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
921 private getStationInfoPersistentConfiguration(): boolean {
922 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
925 private handleUnsupportedVersion(version
: OCPPVersion
) {
926 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
927 logger
.error(`${this.logPrefix()} ${errMsg}`);
928 throw new BaseError(errMsg
);
931 private initialize(): void {
932 this.configurationFile
= path
.join(
933 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
934 ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile()) + '.json'
936 this.stationInfo
= this.getStationInfo();
937 this.saveStationInfo();
938 logger
.info(`${this.logPrefix()} Charging station hashId '${this.stationInfo.hashId}'`);
939 // Avoid duplication of connectors related information in RAM
940 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
941 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
942 if (this.getEnableStatistics()) {
943 this.performanceStatistics
= PerformanceStatistics
.getInstance(
944 this.stationInfo
.hashId
,
945 this.stationInfo
.chargingStationId
,
946 this.configuredSupervisionUrl
949 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
952 this.powerDivider
= this.getPowerDivider();
953 // OCPP configuration
954 this.ocppConfiguration
= this.getOcppConfiguration();
955 this.initializeOcppConfiguration();
956 switch (this.getOcppVersion()) {
957 case OCPPVersion
.VERSION_16
:
958 this.ocppIncomingRequestService
=
959 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
960 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
961 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
965 this.handleUnsupportedVersion(this.getOcppVersion());
968 if (this.stationInfo
?.autoRegister
) {
969 this.bootNotificationResponse
= {
970 currentTime
: new Date().toISOString(),
971 interval
: this.getHeartbeatInterval() / 1000,
972 status: RegistrationStatus
.ACCEPTED
,
977 private initializeOcppConfiguration(): void {
979 !ChargingStationConfigurationUtils
.getConfigurationKey(
981 StandardParametersKey
.HeartbeatInterval
984 ChargingStationConfigurationUtils
.addConfigurationKey(
986 StandardParametersKey
.HeartbeatInterval
,
991 !ChargingStationConfigurationUtils
.getConfigurationKey(
993 StandardParametersKey
.HeartBeatInterval
996 ChargingStationConfigurationUtils
.addConfigurationKey(
998 StandardParametersKey
.HeartBeatInterval
,
1004 this.getSupervisionUrlOcppConfiguration() &&
1005 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1007 ChargingStationConfigurationUtils
.addConfigurationKey(
1009 this.getSupervisionUrlOcppKey(),
1010 this.configuredSupervisionUrl
.href
,
1014 !this.getSupervisionUrlOcppConfiguration() &&
1015 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1017 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1019 this.getSupervisionUrlOcppKey(),
1024 this.stationInfo
.amperageLimitationOcppKey
&&
1025 !ChargingStationConfigurationUtils
.getConfigurationKey(
1027 this.stationInfo
.amperageLimitationOcppKey
1030 ChargingStationConfigurationUtils
.addConfigurationKey(
1032 this.stationInfo
.amperageLimitationOcppKey
,
1034 this.stationInfo
.maximumAmperage
*
1035 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1040 !ChargingStationConfigurationUtils
.getConfigurationKey(
1042 StandardParametersKey
.SupportedFeatureProfiles
1045 ChargingStationConfigurationUtils
.addConfigurationKey(
1047 StandardParametersKey
.SupportedFeatureProfiles
,
1048 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1051 ChargingStationConfigurationUtils
.addConfigurationKey(
1053 StandardParametersKey
.NumberOfConnectors
,
1054 this.getNumberOfConnectors().toString(),
1059 !ChargingStationConfigurationUtils
.getConfigurationKey(
1061 StandardParametersKey
.MeterValuesSampledData
1064 ChargingStationConfigurationUtils
.addConfigurationKey(
1066 StandardParametersKey
.MeterValuesSampledData
,
1067 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1071 !ChargingStationConfigurationUtils
.getConfigurationKey(
1073 StandardParametersKey
.ConnectorPhaseRotation
1076 const connectorPhaseRotation
= [];
1077 for (const connectorId
of this.connectors
.keys()) {
1079 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1080 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1081 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1082 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1084 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1085 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1086 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1087 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1090 ChargingStationConfigurationUtils
.addConfigurationKey(
1092 StandardParametersKey
.ConnectorPhaseRotation
,
1093 connectorPhaseRotation
.toString()
1097 !ChargingStationConfigurationUtils
.getConfigurationKey(
1099 StandardParametersKey
.AuthorizeRemoteTxRequests
1102 ChargingStationConfigurationUtils
.addConfigurationKey(
1104 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1109 !ChargingStationConfigurationUtils
.getConfigurationKey(
1111 StandardParametersKey
.LocalAuthListEnabled
1113 ChargingStationConfigurationUtils
.getConfigurationKey(
1115 StandardParametersKey
.SupportedFeatureProfiles
1116 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1118 ChargingStationConfigurationUtils
.addConfigurationKey(
1120 StandardParametersKey
.LocalAuthListEnabled
,
1125 !ChargingStationConfigurationUtils
.getConfigurationKey(
1127 StandardParametersKey
.ConnectionTimeOut
1130 ChargingStationConfigurationUtils
.addConfigurationKey(
1132 StandardParametersKey
.ConnectionTimeOut
,
1133 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1136 this.saveOcppConfiguration();
1139 private initializeConnectors(
1140 stationInfo
: ChargingStationInfo
,
1141 configuredMaxConnectors
: number,
1142 templateMaxConnectors
: number
1144 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1145 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1146 logger
.error(`${this.logPrefix()} ${logMsg}`);
1147 throw new BaseError(logMsg
);
1149 if (!stationInfo
?.Connectors
[0]) {
1151 `${this.logPrefix()} Charging station information from template ${
1153 } with no connector Id 0 configuration`
1156 if (stationInfo
?.Connectors
) {
1157 const connectorsConfigHash
= crypto
1158 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1159 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1161 const connectorsConfigChanged
=
1162 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1163 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1164 connectorsConfigChanged
&& this.connectors
.clear();
1165 this.connectorsConfigurationHash
= connectorsConfigHash
;
1166 // Add connector Id 0
1167 let lastConnector
= '0';
1168 for (lastConnector
in stationInfo
?.Connectors
) {
1169 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1171 lastConnectorId
=== 0 &&
1172 this.getUseConnectorId0(stationInfo
) === true &&
1173 stationInfo
?.Connectors
[lastConnector
]
1175 this.connectors
.set(
1177 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1179 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1180 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1181 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1185 // Generate all connectors
1186 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1187 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1188 const randConnectorId
= stationInfo
?.randomConnectors
1189 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1191 this.connectors
.set(
1193 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1195 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1196 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1197 this.getConnectorStatus(index
).chargingProfiles
= [];
1204 `${this.logPrefix()} Charging station information from template ${
1206 } with no connectors configuration defined, using already defined connectors`
1209 // Initialize transaction attributes on connectors
1210 for (const connectorId
of this.connectors
.keys()) {
1213 (this.getConnectorStatus(connectorId
).transactionStarted
=== undefined ||
1214 this.getConnectorStatus(connectorId
).transactionStarted
=== false)
1216 this.initializeConnectorStatus(connectorId
);
1221 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1222 let configuration
: ChargingStationConfiguration
= null;
1223 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1225 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1226 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1227 this.configurationFileHash
1230 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1231 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1232 configuration
= JSON
.parse(
1233 fs
.readFileSync(this.configurationFile
, 'utf8')
1234 ) as ChargingStationConfiguration
;
1235 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1236 this.configurationFileHash
= configuration
.configurationHash
;
1237 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1240 FileUtils
.handleFileException(
1242 FileType
.ChargingStationConfiguration
,
1243 this.configurationFile
,
1244 error
as NodeJS
.ErrnoException
1248 return configuration
;
1251 private saveConfiguration(): void {
1252 if (this.configurationFile
) {
1254 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1255 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1257 const configurationData
: ChargingStationConfiguration
=
1258 this.getConfigurationFromFile() ?? {};
1259 this.ocppConfiguration
?.configurationKey
&&
1260 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1261 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1262 delete configurationData
.configurationHash
;
1263 const configurationHash
= crypto
1264 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1265 .update(JSON
.stringify(configurationData
))
1267 if (this.configurationFileHash
!== configurationHash
) {
1268 configurationData
.configurationHash
= configurationHash
;
1269 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1270 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1271 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1272 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1273 fs
.closeSync(fileDescriptor
);
1274 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1275 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1276 this.configurationFileHash
= configurationHash
;
1277 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1280 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1281 this.configurationFile
1286 FileUtils
.handleFileException(
1288 FileType
.ChargingStationConfiguration
,
1289 this.configurationFile
,
1290 error
as NodeJS
.ErrnoException
1295 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1300 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1301 return this.getTemplateFromFile()?.Configuration
?? null;
1304 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1305 let configuration
: ChargingStationConfiguration
= null;
1306 if (this.getOcppPersistentConfiguration()) {
1307 const configurationFromFile
= this.getConfigurationFromFile();
1308 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1310 configuration
&& delete configuration
.stationInfo
;
1311 return configuration
;
1314 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1315 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1316 if (!ocppConfiguration
) {
1317 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1319 return ocppConfiguration
;
1322 private async onOpen(): Promise
<void> {
1323 if (this.isWebSocketConnectionOpened()) {
1325 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1327 if (!this.isRegistered()) {
1328 // Send BootNotification
1329 let registrationRetryCount
= 0;
1331 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1332 BootNotificationRequest
,
1333 BootNotificationResponse
1334 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1335 skipBufferingOnError
: true,
1337 if (!this.isRegistered()) {
1338 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1340 this.bootNotificationResponse
?.interval
1341 ? this.bootNotificationResponse
.interval
* 1000
1342 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1346 !this.isRegistered() &&
1347 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1348 this.getRegistrationMaxRetries() === -1)
1351 if (this.isRegistered()) {
1352 if (this.isInAcceptedState()) {
1353 await this.startMessageSequence();
1357 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1360 this.wsConnectionRestarted
= false;
1361 this.autoReconnectRetryCount
= 0;
1362 this.started
= true;
1363 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1366 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1371 private async onClose(code
: number, reason
: string): Promise
<void> {
1374 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1375 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1377 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1379 )}' and reason '${reason}'`
1381 this.autoReconnectRetryCount
= 0;
1386 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1388 )}' and reason '${reason}'`
1390 await this.reconnect();
1393 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1396 private async onMessage(data
: Data
): Promise
<void> {
1397 let messageType
: number;
1398 let messageId
: string;
1399 let commandName
: IncomingRequestCommand
;
1400 let commandPayload
: JsonType
;
1401 let errorType
: ErrorType
;
1402 let errorMessage
: string;
1403 let errorDetails
: JsonType
;
1404 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1405 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1406 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1407 let requestPayload
: JsonType
;
1408 let cachedRequest
: CachedRequest
;
1411 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1412 if (Array.isArray(request
) === true) {
1413 [messageType
, messageId
] = request
;
1414 // Check the type of message
1415 switch (messageType
) {
1417 case MessageType
.CALL_MESSAGE
:
1418 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1419 if (this.getEnableStatistics() === true) {
1420 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1423 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1427 // Process the message
1428 await this.ocppIncomingRequestService
.incomingRequestHandler(
1436 case MessageType
.CALL_RESULT_MESSAGE
:
1437 [, , commandPayload
] = request
as Response
;
1438 if (this.requests
.has(messageId
) === false) {
1440 throw new OCPPError(
1441 ErrorType
.INTERNAL_ERROR
,
1442 `Response for unknown message id ${messageId}`,
1448 cachedRequest
= this.requests
.get(messageId
);
1449 if (Array.isArray(cachedRequest
) === true) {
1450 [responseCallback
, errorCallback
, requestCommandName
, requestPayload
] = cachedRequest
;
1452 throw new OCPPError(
1453 ErrorType
.PROTOCOL_ERROR
,
1454 `Cached request for message id ${messageId} response is not an array`,
1456 cachedRequest
as unknown
as JsonType
1460 `${this.logPrefix()} << Command '${
1461 requestCommandName ?? Constants.UNKNOWN_COMMAND
1462 }' received response payload: ${JSON.stringify(request)}`
1464 responseCallback(commandPayload
, requestPayload
);
1467 case MessageType
.CALL_ERROR_MESSAGE
:
1468 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1469 if (this.requests
.has(messageId
) === false) {
1471 throw new OCPPError(
1472 ErrorType
.INTERNAL_ERROR
,
1473 `Error response for unknown message id ${messageId}`,
1475 { errorType
, errorMessage
, errorDetails
}
1478 cachedRequest
= this.requests
.get(messageId
);
1479 if (Array.isArray(cachedRequest
) === true) {
1480 [, errorCallback
, requestCommandName
] = cachedRequest
;
1482 throw new OCPPError(
1483 ErrorType
.PROTOCOL_ERROR
,
1484 `Cached request for message id ${messageId} error response is not an array`,
1486 cachedRequest
as unknown
as JsonType
1490 `${this.logPrefix()} << Command '${
1491 requestCommandName ?? Constants.UNKNOWN_COMMAND
1492 }' received error payload: ${JSON.stringify(request)}`
1494 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1498 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1499 errMsg
= `Wrong message type ${messageType}`;
1500 logger
.error(`${this.logPrefix()} ${errMsg}`);
1501 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1503 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1505 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1512 `${this.logPrefix()} Incoming OCPP command '${
1513 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1514 }' message '${data.toString()}'${
1515 messageType !== MessageType.CALL_MESSAGE
1516 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1518 } processing error:`,
1521 if (error
instanceof OCPPError
=== false) {
1523 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1524 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1525 }' message '${data.toString()}' handling is not an OCPPError:`,
1529 switch (messageType
) {
1530 case MessageType
.CALL_MESSAGE
:
1532 await this.ocppRequestService
.sendError(
1536 commandName
?? requestCommandName
?? null
1539 case MessageType
.CALL_RESULT_MESSAGE
:
1540 case MessageType
.CALL_ERROR_MESSAGE
:
1541 if (errorCallback
) {
1542 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1543 errorCallback(error
as OCPPError
, false);
1545 // Remove the request from the cache in case of error at response handling
1546 this.requests
.delete(messageId
);
1553 private onPing(): void {
1554 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1557 private onPong(): void {
1558 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1561 private onError(error
: WSError
): void {
1562 this.closeWSConnection();
1563 logger
.error(this.logPrefix() + ' WebSocket error:', error
);
1566 private getEnergyActiveImportRegister(
1567 connectorStatus
: ConnectorStatus
,
1570 if (this.getMeteringPerTransaction() === true) {
1573 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1574 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1579 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1580 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1584 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean {
1585 const localStationInfo
= stationInfo
?? this.stationInfo
;
1586 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1587 ? localStationInfo
.useConnectorId0
1591 private getNumberOfRunningTransactions(): number {
1593 for (const connectorId
of this.connectors
.keys()) {
1594 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1601 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1602 for (const connectorId
of this.connectors
.keys()) {
1603 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1604 await this.stopTransactionOnConnector(connectorId
, reason
);
1610 private getConnectionTimeout(): number {
1612 ChargingStationConfigurationUtils
.getConfigurationKey(
1614 StandardParametersKey
.ConnectionTimeOut
1619 ChargingStationConfigurationUtils
.getConfigurationKey(
1621 StandardParametersKey
.ConnectionTimeOut
1623 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1626 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1629 // -1 for unlimited, 0 for disabling
1630 private getAutoReconnectMaxRetries(): number {
1631 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1632 return this.stationInfo
.autoReconnectMaxRetries
;
1634 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1635 return Configuration
.getAutoReconnectMaxRetries();
1641 private getRegistrationMaxRetries(): number {
1642 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1643 return this.stationInfo
.registrationMaxRetries
;
1648 private getPowerDivider(): number {
1649 let powerDivider
= this.getNumberOfConnectors();
1650 if (this.stationInfo
?.powerSharedByConnectors
) {
1651 powerDivider
= this.getNumberOfRunningTransactions();
1653 return powerDivider
;
1656 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1657 const localStationInfo
= stationInfo
?? this.stationInfo
;
1658 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1661 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1662 const maximumPower
= this.getMaximumPower(stationInfo
);
1663 switch (this.getCurrentOutType(stationInfo
)) {
1664 case CurrentType
.AC
:
1665 return ACElectricUtils
.amperagePerPhaseFromPower(
1666 this.getNumberOfPhases(stationInfo
),
1667 maximumPower
/ this.getNumberOfConnectors(),
1668 this.getVoltageOut(stationInfo
)
1670 case CurrentType
.DC
:
1671 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1675 private getAmperageLimitation(): number | undefined {
1677 this.stationInfo
.amperageLimitationOcppKey
&&
1678 ChargingStationConfigurationUtils
.getConfigurationKey(
1680 this.stationInfo
.amperageLimitationOcppKey
1685 ChargingStationConfigurationUtils
.getConfigurationKey(
1687 this.stationInfo
.amperageLimitationOcppKey
1689 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1694 private getChargingProfilePowerLimit(connectorId
: number): number | undefined {
1695 let limit
: number, matchingChargingProfile
: ChargingProfile
;
1696 let chargingProfiles
: ChargingProfile
[] = [];
1697 // Get charging profiles for connector and sort by stack level
1698 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
1699 (a
, b
) => b
.stackLevel
- a
.stackLevel
1701 // Get profiles on connector 0
1702 if (this.getConnectorStatus(0).chargingProfiles
) {
1703 chargingProfiles
.push(
1704 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
1707 if (!Utils
.isEmptyArray(chargingProfiles
)) {
1708 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
1712 if (!Utils
.isNullOrUndefined(result
)) {
1713 limit
= result
.limit
;
1714 matchingChargingProfile
= result
.matchingChargingProfile
;
1715 switch (this.getCurrentOutType()) {
1716 case CurrentType
.AC
:
1718 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
1719 ChargingRateUnitType
.WATT
1721 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
1723 case CurrentType
.DC
:
1725 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
1726 ChargingRateUnitType
.WATT
1728 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
1730 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
1731 if (limit
> connectorMaximumPower
) {
1733 `${this.logPrefix()} Charging profile id ${
1734 matchingChargingProfile.chargingProfileId
1735 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
1736 this.getConnectorStatus(connectorId
).chargingProfiles
1738 limit
= connectorMaximumPower
;
1745 private async startMessageSequence(): Promise
<void> {
1746 if (this.stationInfo
?.autoRegister
) {
1747 await this.ocppRequestService
.requestHandler
<
1748 BootNotificationRequest
,
1749 BootNotificationResponse
1750 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1751 skipBufferingOnError
: true,
1754 // Start WebSocket ping
1755 this.startWebSocketPing();
1757 this.startHeartbeat();
1758 // Initialize connectors status
1759 for (const connectorId
of this.connectors
.keys()) {
1760 if (connectorId
=== 0) {
1763 this.started
=== true &&
1764 !this.getConnectorStatus(connectorId
)?.status &&
1765 this.getConnectorStatus(connectorId
)?.bootStatus
1767 // Send status in template at startup
1768 await this.ocppRequestService
.requestHandler
<
1769 StatusNotificationRequest
,
1770 StatusNotificationResponse
1771 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1773 status: this.getConnectorStatus(connectorId
).bootStatus
,
1774 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1776 this.getConnectorStatus(connectorId
).status =
1777 this.getConnectorStatus(connectorId
).bootStatus
;
1779 this.started
=== false &&
1780 this.getConnectorStatus(connectorId
)?.status &&
1781 this.getConnectorStatus(connectorId
)?.bootStatus
1783 // Send status in template after reset
1784 await this.ocppRequestService
.requestHandler
<
1785 StatusNotificationRequest
,
1786 StatusNotificationResponse
1787 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1789 status: this.getConnectorStatus(connectorId
).bootStatus
,
1790 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1792 this.getConnectorStatus(connectorId
).status =
1793 this.getConnectorStatus(connectorId
).bootStatus
;
1794 } else if (this.started
=== true && this.getConnectorStatus(connectorId
)?.status) {
1795 // Send previous status at template reload
1796 await this.ocppRequestService
.requestHandler
<
1797 StatusNotificationRequest
,
1798 StatusNotificationResponse
1799 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1801 status: this.getConnectorStatus(connectorId
).status,
1802 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1805 // Send default status
1806 await this.ocppRequestService
.requestHandler
<
1807 StatusNotificationRequest
,
1808 StatusNotificationResponse
1809 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1811 status: ChargePointStatus
.AVAILABLE
,
1812 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1814 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1818 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true) {
1819 this.startAutomaticTransactionGenerator();
1821 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
1824 private async stopMessageSequence(
1825 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1827 // Stop WebSocket ping
1828 this.stopWebSocketPing();
1830 this.stopHeartbeat();
1831 // Stop ongoing transactions
1832 if (this.automaticTransactionGenerator
?.started
=== true) {
1833 this.stopAutomaticTransactionGenerator();
1835 await this.stopRunningTransactions(reason
);
1839 private startWebSocketPing(): void {
1840 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1842 StandardParametersKey
.WebSocketPingInterval
1844 ? Utils
.convertToInt(
1845 ChargingStationConfigurationUtils
.getConfigurationKey(
1847 StandardParametersKey
.WebSocketPingInterval
1851 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1852 this.webSocketPingSetInterval
= setInterval(() => {
1853 if (this.isWebSocketConnectionOpened()) {
1854 this.wsConnection
.ping((): void => {
1855 /* This is intentional */
1858 }, webSocketPingInterval
* 1000);
1861 ' WebSocket ping started every ' +
1862 Utils
.formatDurationSeconds(webSocketPingInterval
)
1864 } else if (this.webSocketPingSetInterval
) {
1867 ' WebSocket ping every ' +
1868 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1873 `${this.logPrefix()} WebSocket ping interval set to ${
1874 webSocketPingInterval
1875 ? Utils.formatDurationSeconds(webSocketPingInterval)
1876 : webSocketPingInterval
1877 }, not starting the WebSocket ping`
1882 private stopWebSocketPing(): void {
1883 if (this.webSocketPingSetInterval
) {
1884 clearInterval(this.webSocketPingSetInterval
);
1888 private getConfiguredSupervisionUrl(): URL
{
1889 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1890 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1892 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1893 switch (Configuration
.getSupervisionUrlDistribution()) {
1894 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1896 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1898 case SupervisionUrlDistribution
.RANDOM
:
1899 this.configuredSupervisionUrlIndex
= Math.floor(
1900 Utils
.secureRandom() * supervisionUrls
.length
1903 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
1904 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1908 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1909 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
1912 this.configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1915 return new URL(supervisionUrls
[this.configuredSupervisionUrlIndex
]);
1917 return new URL(supervisionUrls
as string);
1920 private getHeartbeatInterval(): number {
1921 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1923 StandardParametersKey
.HeartbeatInterval
1925 if (HeartbeatInterval
) {
1926 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1928 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1930 StandardParametersKey
.HeartBeatInterval
1932 if (HeartBeatInterval
) {
1933 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1935 !this.stationInfo
?.autoRegister
&&
1937 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1938 Constants.DEFAULT_HEARTBEAT_INTERVAL
1941 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1944 private stopHeartbeat(): void {
1945 if (this.heartbeatSetInterval
) {
1946 clearInterval(this.heartbeatSetInterval
);
1950 private terminateWSConnection(): void {
1951 if (this.isWebSocketConnectionOpened()) {
1952 this.wsConnection
.terminate();
1953 this.wsConnection
= null;
1957 private stopMeterValues(connectorId
: number) {
1958 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1959 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1963 private getReconnectExponentialDelay(): boolean {
1964 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1965 ? this.stationInfo
.reconnectExponentialDelay
1969 private async reconnect(): Promise
<void> {
1970 // Stop WebSocket ping
1971 this.stopWebSocketPing();
1973 this.stopHeartbeat();
1974 // Stop the ATG if needed
1975 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
=== true) {
1976 this.stopAutomaticTransactionGenerator();
1979 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1980 this.getAutoReconnectMaxRetries() === -1
1982 this.autoReconnectRetryCount
++;
1983 const reconnectDelay
= this.getReconnectExponentialDelay()
1984 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1985 : this.getConnectionTimeout() * 1000;
1986 const reconnectDelayWithdraw
= 1000;
1987 const reconnectTimeout
=
1988 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
1989 ? reconnectDelay
- reconnectDelayWithdraw
1992 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1995 )}ms, timeout ${reconnectTimeout}ms`
1997 await Utils
.sleep(reconnectDelay
);
2000 ' WebSocket: reconnecting try #' +
2001 this.autoReconnectRetryCount
.toString()
2003 this.openWSConnection(
2004 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
2005 { closeOpened
: true }
2007 this.wsConnectionRestarted
= true;
2008 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2010 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2011 this.autoReconnectRetryCount
2012 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2017 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
2018 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2021 private initializeConnectorStatus(connectorId
: number): void {
2022 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2023 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2024 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2025 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2026 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2027 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;