1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import crypto from
'crypto';
5 import path from
'path';
6 import { URL
} from
'url';
7 import { parentPort
} from
'worker_threads';
9 import WebSocket
, { Data
, RawData
} from
'ws';
11 import BaseError from
'../exception/BaseError';
12 import OCPPError from
'../exception/OCPPError';
13 import PerformanceStatistics from
'../performance/PerformanceStatistics';
14 import type { AutomaticTransactionGeneratorConfiguration
} from
'../types/AutomaticTransactionGenerator';
15 import type ChargingStationConfiguration from
'../types/ChargingStationConfiguration';
16 import type ChargingStationInfo from
'../types/ChargingStationInfo';
17 import type ChargingStationOcppConfiguration from
'../types/ChargingStationOcppConfiguration';
18 import ChargingStationTemplate
, {
22 } from
'../types/ChargingStationTemplate';
23 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
24 import type { ConnectorStatus
} from
'../types/ConnectorStatus';
25 import { FileType
} from
'../types/FileType';
26 import type { JsonType
} from
'../types/JsonType';
27 import { ChargePointErrorCode
} from
'../types/ocpp/ChargePointErrorCode';
28 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
29 import { ChargingProfile
, ChargingRateUnitType
} from
'../types/ocpp/ChargingProfile';
31 ConnectorPhaseRotation
,
32 StandardParametersKey
,
33 SupportedFeatureProfiles
,
34 VendorDefaultParametersKey
,
35 } from
'../types/ocpp/Configuration';
36 import { ErrorType
} from
'../types/ocpp/ErrorType';
37 import { MessageType
} from
'../types/ocpp/MessageType';
38 import { MeterValue
, MeterValueMeasurand
} from
'../types/ocpp/MeterValues';
39 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
42 BootNotificationRequest
,
46 IncomingRequestCommand
,
49 StatusNotificationRequest
,
50 } from
'../types/ocpp/Requests';
52 BootNotificationResponse
,
58 StatusNotificationResponse
,
59 } from
'../types/ocpp/Responses';
61 StopTransactionReason
,
62 StopTransactionRequest
,
63 StopTransactionResponse
,
64 } from
'../types/ocpp/Transaction';
65 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
66 import Configuration from
'../utils/Configuration';
67 import Constants from
'../utils/Constants';
68 import { ACElectricUtils
, DCElectricUtils
} from
'../utils/ElectricUtils';
69 import FileUtils from
'../utils/FileUtils';
70 import logger from
'../utils/Logger';
71 import Utils from
'../utils/Utils';
72 import AuthorizedTagsCache from
'./AuthorizedTagsCache';
73 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
74 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
75 import { ChargingStationUtils
} from
'./ChargingStationUtils';
76 import ChargingStationWorkerBroadcastChannel from
'./ChargingStationWorkerBroadcastChannel';
77 import { MessageChannelUtils
} from
'./MessageChannelUtils';
78 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
79 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
80 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
81 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
82 import type OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
83 import type OCPPRequestService from
'./ocpp/OCPPRequestService';
84 import SharedLRUCache from
'./SharedLRUCache';
86 export default class ChargingStation
{
87 public hashId
!: string;
88 public readonly templateFile
: string;
89 public authorizedTagsCache
: AuthorizedTagsCache
;
90 public stationInfo
!: ChargingStationInfo
;
91 public stopped
: boolean;
92 public readonly connectors
: Map
<number, ConnectorStatus
>;
93 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
94 public wsConnection
!: WebSocket
;
95 public readonly requests
: Map
<string, CachedRequest
>;
96 public performanceStatistics
!: PerformanceStatistics
;
97 public heartbeatSetInterval
!: NodeJS
.Timeout
;
98 public ocppRequestService
!: OCPPRequestService
;
99 public bootNotificationResponse
!: BootNotificationResponse
| null;
100 public powerDivider
!: number;
101 private readonly index
: number;
102 private configurationFile
!: string;
103 private configurationFileHash
!: string;
104 private bootNotificationRequest
!: BootNotificationRequest
;
105 private connectorsConfigurationHash
!: string;
106 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
107 private readonly messageBuffer
: Set
<string>;
108 private configuredSupervisionUrl
!: URL
;
109 private wsConnectionRestarted
: boolean;
110 private autoReconnectRetryCount
: number;
111 private templateFileWatcher
!: fs
.FSWatcher
;
112 private readonly sharedLRUCache
: SharedLRUCache
;
113 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
114 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
115 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
117 constructor(index
: number, templateFile
: string) {
119 this.templateFile
= templateFile
;
120 this.stopped
= false;
121 this.wsConnectionRestarted
= false;
122 this.autoReconnectRetryCount
= 0;
123 this.sharedLRUCache
= SharedLRUCache
.getInstance();
124 this.authorizedTagsCache
= AuthorizedTagsCache
.getInstance();
125 this.connectors
= new Map
<number, ConnectorStatus
>();
126 this.requests
= new Map
<string, CachedRequest
>();
127 this.messageBuffer
= new Set
<string>();
128 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
133 private get
wsConnectionUrl(): URL
{
135 (this.getSupervisionUrlOcppConfiguration()
136 ? ChargingStationConfigurationUtils
.getConfigurationKey(
138 this.getSupervisionUrlOcppKey()
140 : this.configuredSupervisionUrl
.href
) +
142 this.stationInfo
.chargingStationId
146 public logPrefix(): string {
147 return Utils
.logPrefix(
149 this?.stationInfo?.chargingStationId ??
150 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
155 public getBootNotificationRequest(): BootNotificationRequest
{
156 return this.bootNotificationRequest
;
159 public getRandomIdTag(): string {
160 const authorizationFile
= ChargingStationUtils
.getAuthorizationFile(this.stationInfo
);
161 const index
= Math.floor(
162 Utils
.secureRandom() * this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
).length
164 return this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
)[index
];
167 public hasAuthorizedTags(): boolean {
168 return !Utils
.isEmptyArray(
169 this.authorizedTagsCache
.getAuthorizedTags(
170 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
)
175 public getEnableStatistics(): boolean | undefined {
176 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
177 ? this.stationInfo
.enableStatistics
181 public getMustAuthorizeAtRemoteStart(): boolean | undefined {
182 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
185 public getPayloadSchemaValidation(): boolean | undefined {
186 return this.stationInfo
.payloadSchemaValidation
?? true;
189 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
190 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
191 switch (this.getCurrentOutType(stationInfo
)) {
193 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
194 ? localStationInfo
.numberOfPhases
201 public isWebSocketConnectionOpened(): boolean {
202 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
205 public getRegistrationStatus(): RegistrationStatus
{
206 return this?.bootNotificationResponse
?.status;
209 public isInUnknownState(): boolean {
210 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
213 public isInPendingState(): boolean {
214 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
217 public isInAcceptedState(): boolean {
218 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
221 public isInRejectedState(): boolean {
222 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
225 public isRegistered(): boolean {
226 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
229 public isChargingStationAvailable(): boolean {
230 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
233 public isConnectorAvailable(id
: number): boolean {
234 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
237 public getNumberOfConnectors(): number {
238 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
241 public getConnectorStatus(id
: number): ConnectorStatus
{
242 return this.connectors
.get(id
);
245 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
246 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
;
249 public getOcppStrictCompliance(): boolean {
250 return this.stationInfo
?.ocppStrictCompliance
?? false;
253 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
254 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
255 this.getCurrentOutType(stationInfo
),
259 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
260 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
261 ? localStationInfo
.voltageOut
265 public getConnectorMaximumAvailablePower(connectorId
: number): number {
266 let connectorAmperageLimitationPowerLimit
: number;
268 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
269 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
271 connectorAmperageLimitationPowerLimit
=
272 (this.getCurrentOutType() === CurrentType
.AC
273 ? ACElectricUtils
.powerTotal(
274 this.getNumberOfPhases(),
275 this.getVoltageOut(),
276 this.getAmperageLimitation() * this.getNumberOfConnectors()
278 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
281 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
282 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
284 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
285 isNaN(connectorAmperageLimitationPowerLimit
)
287 : connectorAmperageLimitationPowerLimit
,
288 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
292 public getTransactionIdTag(transactionId
: number): string | undefined {
293 for (const connectorId
of this.connectors
.keys()) {
294 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
295 return this.getConnectorStatus(connectorId
).transactionIdTag
;
300 public getOutOfOrderEndMeterValues(): boolean {
301 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
304 public getBeginEndMeterValues(): boolean {
305 return this.stationInfo
?.beginEndMeterValues
?? false;
308 public getMeteringPerTransaction(): boolean {
309 return this.stationInfo
?.meteringPerTransaction
?? true;
312 public getTransactionDataMeterValues(): boolean {
313 return this.stationInfo
?.transactionDataMeterValues
?? false;
316 public getMainVoltageMeterValues(): boolean {
317 return this.stationInfo
?.mainVoltageMeterValues
?? true;
320 public getPhaseLineToLineVoltageMeterValues(): boolean {
321 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
324 public getCustomValueLimitationMeterValues(): boolean {
325 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
328 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
329 for (const connectorId
of this.connectors
.keys()) {
332 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
339 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number {
340 const transactionConnectorStatus
= this.getConnectorStatus(
341 this.getConnectorIdByTransactionId(transactionId
)
343 if (this.getMeteringPerTransaction()) {
344 return transactionConnectorStatus
?.transactionEnergyActiveImportRegisterValue
?? 0;
346 return transactionConnectorStatus
?.energyActiveImportRegisterValue
?? 0;
349 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number {
350 const connectorStatus
= this.getConnectorStatus(connectorId
);
351 if (this.getMeteringPerTransaction()) {
352 return connectorStatus
?.transactionEnergyActiveImportRegisterValue
?? 0;
354 return connectorStatus
?.energyActiveImportRegisterValue
?? 0;
357 public getAuthorizeRemoteTxRequests(): boolean {
358 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
360 StandardParametersKey
.AuthorizeRemoteTxRequests
362 return authorizeRemoteTxRequests
363 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
367 public getLocalAuthListEnabled(): boolean {
368 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
370 StandardParametersKey
.LocalAuthListEnabled
372 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
375 public startHeartbeat(): void {
377 this.getHeartbeatInterval() &&
378 this.getHeartbeatInterval() > 0 &&
379 !this.heartbeatSetInterval
381 // eslint-disable-next-line @typescript-eslint/no-misused-promises
382 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
383 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
385 RequestCommand
.HEARTBEAT
387 }, this.getHeartbeatInterval());
390 ' Heartbeat started every ' +
391 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
393 } else if (this.heartbeatSetInterval
) {
396 ' Heartbeat already started every ' +
397 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
401 `${this.logPrefix()} Heartbeat interval set to ${
402 this.getHeartbeatInterval()
403 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
404 : this.getHeartbeatInterval()
405 }, not starting the heartbeat`
410 public restartHeartbeat(): void {
412 this.stopHeartbeat();
414 this.startHeartbeat();
417 public restartWebSocketPing(): void {
418 // Stop WebSocket ping
419 this.stopWebSocketPing();
420 // Start WebSocket ping
421 this.startWebSocketPing();
424 public startMeterValues(connectorId
: number, interval
: number): void {
425 if (connectorId
=== 0) {
427 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
431 if (!this.getConnectorStatus(connectorId
)) {
433 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
437 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
439 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
443 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
444 !this.getConnectorStatus(connectorId
)?.transactionId
447 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
452 // eslint-disable-next-line @typescript-eslint/no-misused-promises
453 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
454 // eslint-disable-next-line @typescript-eslint/no-misused-promises
455 async (): Promise
<void> => {
456 // FIXME: Implement OCPP version agnostic helpers
457 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
460 this.getConnectorStatus(connectorId
).transactionId
,
463 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
465 RequestCommand
.METER_VALUES
,
468 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
469 meterValue
: [meterValue
],
477 `${this.logPrefix()} Charging station ${
478 StandardParametersKey.MeterValueSampleInterval
479 } configuration set to ${
480 interval ? Utils.formatDurationMilliSeconds(interval) : interval
481 }, not sending MeterValues`
486 public start(): void {
487 if (this.getEnableStatistics()) {
488 this.performanceStatistics
.start();
490 this.openWSConnection();
491 // Monitor charging station template file
492 this.templateFileWatcher
= FileUtils
.watchJsonFile(
494 FileType
.ChargingStationTemplate
,
497 (event
, filename
): void => {
498 if (filename
&& event
=== 'change') {
501 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
503 } file have changed, reload`
505 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
509 this.stopAutomaticTransactionGenerator();
510 this.startAutomaticTransactionGenerator();
511 if (this.getEnableStatistics()) {
512 this.performanceStatistics
.restart();
514 this.performanceStatistics
.stop();
516 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
519 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
526 parentPort
.postMessage(MessageChannelUtils
.buildStartedMessage(this));
529 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
530 // Stop message sequence
531 await this.stopMessageSequence(reason
);
532 for (const connectorId
of this.connectors
.keys()) {
533 if (connectorId
> 0) {
534 await this.ocppRequestService
.requestHandler
<
535 StatusNotificationRequest
,
536 StatusNotificationResponse
537 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
539 status: ChargePointStatus
.UNAVAILABLE
,
540 errorCode
: ChargePointErrorCode
.NO_ERROR
,
542 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
545 this.closeWSConnection();
546 if (this.getEnableStatistics()) {
547 this.performanceStatistics
.stop();
549 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
550 this.templateFileWatcher
.close();
551 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
552 this.bootNotificationResponse
= null;
554 parentPort
.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
557 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
558 await this.stop(reason
);
559 await Utils
.sleep(this.stationInfo
.resetTime
);
564 public saveOcppConfiguration(): void {
565 if (this.getOcppPersistentConfiguration()) {
566 this.saveConfiguration();
570 public getChargingProfilePowerLimit(connectorId
: number): number | undefined {
571 let limit
: number, matchingChargingProfile
: ChargingProfile
;
572 let chargingProfiles
: ChargingProfile
[] = [];
573 // Get charging profiles for connector and sort by stack level
574 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
575 (a
, b
) => b
.stackLevel
- a
.stackLevel
577 // Get profiles on connector 0
578 if (this.getConnectorStatus(0).chargingProfiles
) {
579 chargingProfiles
.push(
580 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
583 if (!Utils
.isEmptyArray(chargingProfiles
)) {
584 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
588 if (!Utils
.isNullOrUndefined(result
)) {
589 limit
= result
.limit
;
590 matchingChargingProfile
= result
.matchingChargingProfile
;
591 switch (this.getCurrentOutType()) {
594 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
595 ChargingRateUnitType
.WATT
597 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
601 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
602 ChargingRateUnitType
.WATT
604 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
607 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
608 if (limit
> connectorMaximumPower
) {
610 `${this.logPrefix()} Charging profile id ${
611 matchingChargingProfile.chargingProfileId
612 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
613 this.getConnectorStatus(connectorId
).chargingProfiles
615 limit
= connectorMaximumPower
;
622 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
623 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
625 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
627 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
629 if (Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
) === false) {
631 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an improper attribute type for the charging profiles array, applying proper type initialization`
633 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
635 let cpReplaced
= false;
636 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
637 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
638 (chargingProfile
: ChargingProfile
, index
: number) => {
640 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
641 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
642 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
644 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
650 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
653 public resetConnectorStatus(connectorId
: number): void {
654 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
655 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
656 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
657 this.getConnectorStatus(connectorId
).transactionStarted
= false;
658 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
659 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
660 delete this.getConnectorStatus(connectorId
).transactionId
;
661 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
662 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
663 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
664 this.stopMeterValues(connectorId
);
667 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
668 return ChargingStationConfigurationUtils
.getConfigurationKey(
670 StandardParametersKey
.SupportedFeatureProfiles
671 )?.value
.includes(featureProfile
);
674 public bufferMessage(message
: string): void {
675 this.messageBuffer
.add(message
);
678 public openWSConnection(
679 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
680 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
682 terminateOpened
: false,
685 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
686 params
.closeOpened
= params
?.closeOpened
?? false;
687 params
.terminateOpened
= params
?.terminateOpened
?? false;
689 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
690 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
692 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
694 if (params
?.closeOpened
) {
695 this.closeWSConnection();
697 if (params
?.terminateOpened
) {
698 this.terminateWSConnection();
700 let protocol
: string;
701 switch (this.getOcppVersion()) {
702 case OCPPVersion
.VERSION_16
:
703 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
706 this.handleUnsupportedVersion(this.getOcppVersion());
711 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString()
714 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
716 // Handle WebSocket message
717 this.wsConnection
.on(
719 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
721 // Handle WebSocket error
722 this.wsConnection
.on(
724 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
726 // Handle WebSocket close
727 this.wsConnection
.on(
729 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
731 // Handle WebSocket open
732 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
733 // Handle WebSocket ping
734 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
735 // Handle WebSocket pong
736 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
739 public closeWSConnection(): void {
740 if (this.isWebSocketConnectionOpened()) {
741 this.wsConnection
.close();
742 this.wsConnection
= null;
746 private flushMessageBuffer() {
747 if (this.messageBuffer
.size
> 0) {
748 this.messageBuffer
.forEach((message
) => {
749 // TODO: evaluate the need to track performance
750 this.wsConnection
.send(message
);
751 this.messageBuffer
.delete(message
);
756 private getSupervisionUrlOcppConfiguration(): boolean {
757 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
760 private getSupervisionUrlOcppKey(): string {
761 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
764 private getTemplateFromFile(): ChargingStationTemplate
| null {
765 let template
: ChargingStationTemplate
= null;
767 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
768 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
770 const measureId
= `${FileType.ChargingStationTemplate} read`;
771 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
772 template
= JSON
.parse(
773 fs
.readFileSync(this.templateFile
, 'utf8')
774 ) as ChargingStationTemplate
;
775 PerformanceStatistics
.endMeasure(measureId
, beginId
);
776 template
.templateHash
= crypto
777 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
778 .update(JSON
.stringify(template
))
780 this.sharedLRUCache
.setChargingStationTemplate(template
);
783 FileUtils
.handleFileException(
785 FileType
.ChargingStationTemplate
,
787 error
as NodeJS
.ErrnoException
793 private getStationInfoFromTemplate(): ChargingStationInfo
{
794 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
795 if (Utils
.isNullOrUndefined(stationTemplate
)) {
796 const errorMsg
= 'Failed to read charging station template file';
797 logger
.error(`${this.logPrefix()} ${errorMsg}`);
798 throw new BaseError(errorMsg
);
800 if (Utils
.isEmptyObject(stationTemplate
)) {
801 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
802 logger
.error(`${this.logPrefix()} ${errorMsg}`);
803 throw new BaseError(errorMsg
);
805 // Deprecation template keys section
806 ChargingStationUtils
.warnDeprecatedTemplateKey(
811 "Use 'supervisionUrls' instead"
813 ChargingStationUtils
.convertDeprecatedTemplateKey(
818 const stationInfo
: ChargingStationInfo
=
819 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
820 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
824 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
825 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
826 stationTemplate
.power
= stationTemplate
.power
as number[];
827 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
828 stationInfo
.maximumPower
=
829 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
830 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
831 : stationTemplate
.power
[powerArrayRandomIndex
];
833 stationTemplate
.power
= stationTemplate
.power
as number;
834 stationInfo
.maximumPower
=
835 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
836 ? stationTemplate
.power
* 1000
837 : stationTemplate
.power
;
839 stationInfo
.resetTime
= stationTemplate
.resetTime
840 ? stationTemplate
.resetTime
* 1000
841 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
842 const configuredMaxConnectors
= ChargingStationUtils
.getConfiguredNumberOfConnectors(
846 ChargingStationUtils
.checkConfiguredMaxConnectors(
847 configuredMaxConnectors
,
851 const templateMaxConnectors
=
852 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
853 ChargingStationUtils
.checkTemplateMaxConnectors(
854 templateMaxConnectors
,
859 configuredMaxConnectors
>
860 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
861 !stationTemplate
?.randomConnectors
864 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
866 }, forcing random connector configurations affectation`
868 stationInfo
.randomConnectors
= true;
870 // Build connectors if needed (FIXME: should be factored out)
871 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
872 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
873 ChargingStationUtils
.createStationInfoHash(stationInfo
);
877 private getStationInfoFromFile(): ChargingStationInfo
| null {
878 let stationInfo
: ChargingStationInfo
= null;
879 this.getStationInfoPersistentConfiguration() &&
880 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
881 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
885 private getStationInfo(): ChargingStationInfo
{
886 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
887 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
888 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
889 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
890 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
891 return this.stationInfo
;
893 return stationInfoFromFile
;
895 stationInfoFromFile
&&
896 ChargingStationUtils
.propagateSerialNumber(
897 this.getTemplateFromFile(),
899 stationInfoFromTemplate
901 return stationInfoFromTemplate
;
904 private saveStationInfo(): void {
905 if (this.getStationInfoPersistentConfiguration()) {
906 this.saveConfiguration();
910 private getOcppVersion(): OCPPVersion
{
911 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
914 private getOcppPersistentConfiguration(): boolean {
915 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
918 private getStationInfoPersistentConfiguration(): boolean {
919 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
922 private handleUnsupportedVersion(version
: OCPPVersion
) {
923 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
924 logger
.error(`${this.logPrefix()} ${errMsg}`);
925 throw new BaseError(errMsg
);
928 private initialize(): void {
929 this.hashId
= ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile());
930 logger
.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
931 this.configurationFile
= path
.join(
932 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
933 this.hashId
+ '.json'
935 this.stationInfo
= this.getStationInfo();
936 this.saveStationInfo();
937 // Avoid duplication of connectors related information in RAM
938 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
939 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
940 if (this.getEnableStatistics()) {
941 this.performanceStatistics
= PerformanceStatistics
.getInstance(
943 this.stationInfo
.chargingStationId
,
944 this.configuredSupervisionUrl
947 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
950 this.powerDivider
= this.getPowerDivider();
951 // OCPP configuration
952 this.ocppConfiguration
= this.getOcppConfiguration();
953 this.initializeOcppConfiguration();
954 switch (this.getOcppVersion()) {
955 case OCPPVersion
.VERSION_16
:
956 this.ocppIncomingRequestService
=
957 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
958 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
959 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
963 this.handleUnsupportedVersion(this.getOcppVersion());
966 if (this.stationInfo
?.autoRegister
) {
967 this.bootNotificationResponse
= {
968 currentTime
: new Date().toISOString(),
969 interval
: this.getHeartbeatInterval() / 1000,
970 status: RegistrationStatus
.ACCEPTED
,
975 private initializeOcppConfiguration(): void {
977 !ChargingStationConfigurationUtils
.getConfigurationKey(
979 StandardParametersKey
.HeartbeatInterval
982 ChargingStationConfigurationUtils
.addConfigurationKey(
984 StandardParametersKey
.HeartbeatInterval
,
989 !ChargingStationConfigurationUtils
.getConfigurationKey(
991 StandardParametersKey
.HeartBeatInterval
994 ChargingStationConfigurationUtils
.addConfigurationKey(
996 StandardParametersKey
.HeartBeatInterval
,
1002 this.getSupervisionUrlOcppConfiguration() &&
1003 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1005 ChargingStationConfigurationUtils
.addConfigurationKey(
1007 this.getSupervisionUrlOcppKey(),
1008 this.configuredSupervisionUrl
.href
,
1012 !this.getSupervisionUrlOcppConfiguration() &&
1013 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1015 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1017 this.getSupervisionUrlOcppKey(),
1022 this.stationInfo
.amperageLimitationOcppKey
&&
1023 !ChargingStationConfigurationUtils
.getConfigurationKey(
1025 this.stationInfo
.amperageLimitationOcppKey
1028 ChargingStationConfigurationUtils
.addConfigurationKey(
1030 this.stationInfo
.amperageLimitationOcppKey
,
1032 this.stationInfo
.maximumAmperage
*
1033 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1038 !ChargingStationConfigurationUtils
.getConfigurationKey(
1040 StandardParametersKey
.SupportedFeatureProfiles
1043 ChargingStationConfigurationUtils
.addConfigurationKey(
1045 StandardParametersKey
.SupportedFeatureProfiles
,
1046 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1049 ChargingStationConfigurationUtils
.addConfigurationKey(
1051 StandardParametersKey
.NumberOfConnectors
,
1052 this.getNumberOfConnectors().toString(),
1057 !ChargingStationConfigurationUtils
.getConfigurationKey(
1059 StandardParametersKey
.MeterValuesSampledData
1062 ChargingStationConfigurationUtils
.addConfigurationKey(
1064 StandardParametersKey
.MeterValuesSampledData
,
1065 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1069 !ChargingStationConfigurationUtils
.getConfigurationKey(
1071 StandardParametersKey
.ConnectorPhaseRotation
1074 const connectorPhaseRotation
= [];
1075 for (const connectorId
of this.connectors
.keys()) {
1077 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1078 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1079 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1080 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1082 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1083 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1084 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1085 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1088 ChargingStationConfigurationUtils
.addConfigurationKey(
1090 StandardParametersKey
.ConnectorPhaseRotation
,
1091 connectorPhaseRotation
.toString()
1095 !ChargingStationConfigurationUtils
.getConfigurationKey(
1097 StandardParametersKey
.AuthorizeRemoteTxRequests
1100 ChargingStationConfigurationUtils
.addConfigurationKey(
1102 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1107 !ChargingStationConfigurationUtils
.getConfigurationKey(
1109 StandardParametersKey
.LocalAuthListEnabled
1111 ChargingStationConfigurationUtils
.getConfigurationKey(
1113 StandardParametersKey
.SupportedFeatureProfiles
1114 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1116 ChargingStationConfigurationUtils
.addConfigurationKey(
1118 StandardParametersKey
.LocalAuthListEnabled
,
1123 !ChargingStationConfigurationUtils
.getConfigurationKey(
1125 StandardParametersKey
.ConnectionTimeOut
1128 ChargingStationConfigurationUtils
.addConfigurationKey(
1130 StandardParametersKey
.ConnectionTimeOut
,
1131 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1134 this.saveOcppConfiguration();
1137 private initializeConnectors(
1138 stationInfo
: ChargingStationInfo
,
1139 configuredMaxConnectors
: number,
1140 templateMaxConnectors
: number
1142 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1143 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1144 logger
.error(`${this.logPrefix()} ${logMsg}`);
1145 throw new BaseError(logMsg
);
1147 if (!stationInfo
?.Connectors
[0]) {
1149 `${this.logPrefix()} Charging station information from template ${
1151 } with no connector Id 0 configuration`
1154 if (stationInfo
?.Connectors
) {
1155 const connectorsConfigHash
= crypto
1156 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1157 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1159 const connectorsConfigChanged
=
1160 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1161 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1162 connectorsConfigChanged
&& this.connectors
.clear();
1163 this.connectorsConfigurationHash
= connectorsConfigHash
;
1164 // Add connector Id 0
1165 let lastConnector
= '0';
1166 for (lastConnector
in stationInfo
?.Connectors
) {
1167 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1169 lastConnectorId
=== 0 &&
1170 this.getUseConnectorId0(stationInfo
) &&
1171 stationInfo
?.Connectors
[lastConnector
]
1173 this.connectors
.set(
1175 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1177 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1178 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1179 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1183 // Generate all connectors
1184 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1185 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1186 const randConnectorId
= stationInfo
?.randomConnectors
1187 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1189 this.connectors
.set(
1191 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1193 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1194 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1195 this.getConnectorStatus(index
).chargingProfiles
= [];
1202 `${this.logPrefix()} Charging station information from template ${
1204 } with no connectors configuration defined, using already defined connectors`
1207 // Initialize transaction attributes on connectors
1208 for (const connectorId
of this.connectors
.keys()) {
1209 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1210 this.initializeConnectorStatus(connectorId
);
1215 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1216 let configuration
: ChargingStationConfiguration
= null;
1217 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1219 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1220 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1221 this.configurationFileHash
1224 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1225 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1226 configuration
= JSON
.parse(
1227 fs
.readFileSync(this.configurationFile
, 'utf8')
1228 ) as ChargingStationConfiguration
;
1229 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1230 this.configurationFileHash
= configuration
.configurationHash
;
1231 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1234 FileUtils
.handleFileException(
1236 FileType
.ChargingStationConfiguration
,
1237 this.configurationFile
,
1238 error
as NodeJS
.ErrnoException
1242 return configuration
;
1245 private saveConfiguration(): void {
1246 if (this.configurationFile
) {
1248 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1249 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1251 const configurationData
: ChargingStationConfiguration
=
1252 this.getConfigurationFromFile() ?? {};
1253 this.ocppConfiguration
?.configurationKey
&&
1254 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1255 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1256 delete configurationData
.configurationHash
;
1257 const configurationHash
= crypto
1258 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1259 .update(JSON
.stringify(configurationData
))
1261 if (this.configurationFileHash
!== configurationHash
) {
1262 configurationData
.configurationHash
= configurationHash
;
1263 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1264 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1265 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1266 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1267 fs
.closeSync(fileDescriptor
);
1268 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1269 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1270 this.configurationFileHash
= configurationHash
;
1271 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1274 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1275 this.configurationFile
1280 FileUtils
.handleFileException(
1282 FileType
.ChargingStationConfiguration
,
1283 this.configurationFile
,
1284 error
as NodeJS
.ErrnoException
1289 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1294 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1295 return this.getTemplateFromFile()?.Configuration
?? null;
1298 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1299 let configuration
: ChargingStationConfiguration
= null;
1300 if (this.getOcppPersistentConfiguration()) {
1301 const configurationFromFile
= this.getConfigurationFromFile();
1302 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1304 configuration
&& delete configuration
.stationInfo
;
1305 return configuration
;
1308 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1309 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1310 if (!ocppConfiguration
) {
1311 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1313 return ocppConfiguration
;
1316 private async onOpen(): Promise
<void> {
1317 if (this.isWebSocketConnectionOpened()) {
1319 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1321 if (!this.isRegistered()) {
1322 // Send BootNotification
1323 let registrationRetryCount
= 0;
1325 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1326 BootNotificationRequest
,
1327 BootNotificationResponse
1330 RequestCommand
.BOOT_NOTIFICATION
,
1332 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1333 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1334 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1335 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1336 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1337 iccid
: this.bootNotificationRequest
.iccid
,
1338 imsi
: this.bootNotificationRequest
.imsi
,
1339 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1340 meterType
: this.bootNotificationRequest
.meterType
,
1342 { skipBufferingOnError
: true }
1344 if (!this.isRegistered()) {
1345 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1347 this.bootNotificationResponse
?.interval
1348 ? this.bootNotificationResponse
.interval
* 1000
1349 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1353 !this.isRegistered() &&
1354 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1355 this.getRegistrationMaxRetries() === -1)
1358 if (this.isRegistered()) {
1359 if (this.isInAcceptedState()) {
1360 await this.startMessageSequence();
1361 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1365 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1368 this.stopped
&& (this.stopped
= false);
1369 this.autoReconnectRetryCount
= 0;
1370 this.wsConnectionRestarted
= false;
1373 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1378 private async onClose(code
: number, reason
: string): Promise
<void> {
1381 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1382 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1384 `${this.logPrefix()} WebSocket normally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1386 )}' and reason '${reason}'`
1388 this.autoReconnectRetryCount
= 0;
1393 `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1395 )}' and reason '${reason}'`
1397 await this.reconnect(code
);
1402 private async onMessage(data
: Data
): Promise
<void> {
1403 let messageType
: number;
1404 let messageId
: string;
1405 let commandName
: IncomingRequestCommand
;
1406 let commandPayload
: JsonType
;
1407 let errorType
: ErrorType
;
1408 let errorMessage
: string;
1409 let errorDetails
: JsonType
;
1410 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1411 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1412 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1413 let requestPayload
: JsonType
;
1414 let cachedRequest
: CachedRequest
;
1417 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1418 if (Array.isArray(request
) === true) {
1419 [messageType
, messageId
] = request
;
1420 // Check the type of message
1421 switch (messageType
) {
1423 case MessageType
.CALL_MESSAGE
:
1424 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1425 if (this.getEnableStatistics()) {
1426 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1429 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1433 // Process the message
1434 await this.ocppIncomingRequestService
.incomingRequestHandler(
1442 case MessageType
.CALL_RESULT_MESSAGE
:
1443 [, , commandPayload
] = request
as Response
;
1444 if (!this.requests
.has(messageId
)) {
1446 throw new OCPPError(
1447 ErrorType
.INTERNAL_ERROR
,
1448 `Response for unknown message id ${messageId}`,
1454 cachedRequest
= this.requests
.get(messageId
);
1455 if (Array.isArray(cachedRequest
) === true) {
1456 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1458 throw new OCPPError(
1459 ErrorType
.PROTOCOL_ERROR
,
1460 `Cached request for message id ${messageId} response is not an array`,
1462 cachedRequest
as unknown
as JsonType
1466 `${this.logPrefix()} << Command '${
1467 requestCommandName ?? 'unknown'
1468 }' received response payload: ${JSON.stringify(request)}`
1470 responseCallback(commandPayload
, requestPayload
);
1473 case MessageType
.CALL_ERROR_MESSAGE
:
1474 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1475 if (!this.requests
.has(messageId
)) {
1477 throw new OCPPError(
1478 ErrorType
.INTERNAL_ERROR
,
1479 `Error response for unknown message id ${messageId}`,
1481 { errorType
, errorMessage
, errorDetails
}
1484 cachedRequest
= this.requests
.get(messageId
);
1485 if (Array.isArray(cachedRequest
) === true) {
1486 [, errorCallback
, requestCommandName
] = cachedRequest
;
1488 throw new OCPPError(
1489 ErrorType
.PROTOCOL_ERROR
,
1490 `Cached request for message id ${messageId} error response is not an array`,
1492 cachedRequest
as unknown
as JsonType
1496 `${this.logPrefix()} << Command '${
1497 requestCommandName ?? 'unknown'
1498 }' received error payload: ${JSON.stringify(request)}`
1500 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1504 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1505 errMsg
= `Wrong message type ${messageType}`;
1506 logger
.error(`${this.logPrefix()} ${errMsg}`);
1507 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1509 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1511 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1518 `${this.logPrefix()} Incoming OCPP command '${
1519 commandName ?? requestCommandName ?? null
1520 }' message '${data.toString()}' matching cached request '${JSON.stringify(
1521 this.requests.get(messageId)
1522 )}' processing error:`,
1525 if (!(error
instanceof OCPPError
)) {
1527 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1528 commandName ?? requestCommandName ?? null
1529 }' message '${data.toString()}' handling is not an OCPPError:`,
1534 messageType
=== MessageType
.CALL_MESSAGE
&&
1535 (await this.ocppRequestService
.sendError(
1539 commandName
?? requestCommandName
?? null
1544 private onPing(): void {
1545 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1548 private onPong(): void {
1549 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1552 private onError(error
: WSError
): void {
1553 this.closeWSConnection();
1554 logger
.error(this.logPrefix() + ' WebSocket error:', error
);
1557 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean | undefined {
1558 const localStationInfo
= stationInfo
?? this.stationInfo
;
1559 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1560 ? localStationInfo
.useConnectorId0
1564 private getNumberOfRunningTransactions(): number {
1566 for (const connectorId
of this.connectors
.keys()) {
1567 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1575 private getConnectionTimeout(): number | undefined {
1577 ChargingStationConfigurationUtils
.getConfigurationKey(
1579 StandardParametersKey
.ConnectionTimeOut
1584 ChargingStationConfigurationUtils
.getConfigurationKey(
1586 StandardParametersKey
.ConnectionTimeOut
1588 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1591 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1594 // -1 for unlimited, 0 for disabling
1595 private getAutoReconnectMaxRetries(): number | undefined {
1596 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1597 return this.stationInfo
.autoReconnectMaxRetries
;
1599 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1600 return Configuration
.getAutoReconnectMaxRetries();
1606 private getRegistrationMaxRetries(): number | undefined {
1607 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1608 return this.stationInfo
.registrationMaxRetries
;
1613 private getPowerDivider(): number {
1614 let powerDivider
= this.getNumberOfConnectors();
1615 if (this.stationInfo
?.powerSharedByConnectors
) {
1616 powerDivider
= this.getNumberOfRunningTransactions();
1618 return powerDivider
;
1621 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1622 const localStationInfo
= stationInfo
?? this.stationInfo
;
1623 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1626 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1627 const maximumPower
= this.getMaximumPower(stationInfo
);
1628 switch (this.getCurrentOutType(stationInfo
)) {
1629 case CurrentType
.AC
:
1630 return ACElectricUtils
.amperagePerPhaseFromPower(
1631 this.getNumberOfPhases(stationInfo
),
1632 maximumPower
/ this.getNumberOfConnectors(),
1633 this.getVoltageOut(stationInfo
)
1635 case CurrentType
.DC
:
1636 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1640 private getAmperageLimitation(): number | undefined {
1642 this.stationInfo
.amperageLimitationOcppKey
&&
1643 ChargingStationConfigurationUtils
.getConfigurationKey(
1645 this.stationInfo
.amperageLimitationOcppKey
1650 ChargingStationConfigurationUtils
.getConfigurationKey(
1652 this.stationInfo
.amperageLimitationOcppKey
1654 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1659 private async startMessageSequence(): Promise
<void> {
1660 if (this.stationInfo
?.autoRegister
) {
1661 await this.ocppRequestService
.requestHandler
<
1662 BootNotificationRequest
,
1663 BootNotificationResponse
1666 RequestCommand
.BOOT_NOTIFICATION
,
1668 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1669 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1670 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1671 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1672 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1673 iccid
: this.bootNotificationRequest
.iccid
,
1674 imsi
: this.bootNotificationRequest
.imsi
,
1675 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1676 meterType
: this.bootNotificationRequest
.meterType
,
1678 { skipBufferingOnError
: true }
1681 // Start WebSocket ping
1682 this.startWebSocketPing();
1684 this.startHeartbeat();
1685 // Initialize connectors status
1686 for (const connectorId
of this.connectors
.keys()) {
1687 if (connectorId
=== 0) {
1691 !this.getConnectorStatus(connectorId
)?.status &&
1692 this.getConnectorStatus(connectorId
)?.bootStatus
1694 // Send status in template at startup
1695 await this.ocppRequestService
.requestHandler
<
1696 StatusNotificationRequest
,
1697 StatusNotificationResponse
1698 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1700 status: this.getConnectorStatus(connectorId
).bootStatus
,
1701 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1703 this.getConnectorStatus(connectorId
).status =
1704 this.getConnectorStatus(connectorId
).bootStatus
;
1707 this.getConnectorStatus(connectorId
)?.status &&
1708 this.getConnectorStatus(connectorId
)?.bootStatus
1710 // Send status in template after reset
1711 await this.ocppRequestService
.requestHandler
<
1712 StatusNotificationRequest
,
1713 StatusNotificationResponse
1714 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1716 status: this.getConnectorStatus(connectorId
).bootStatus
,
1717 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1719 this.getConnectorStatus(connectorId
).status =
1720 this.getConnectorStatus(connectorId
).bootStatus
;
1721 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1722 // Send previous status at template reload
1723 await this.ocppRequestService
.requestHandler
<
1724 StatusNotificationRequest
,
1725 StatusNotificationResponse
1726 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1728 status: this.getConnectorStatus(connectorId
).status,
1729 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1732 // Send default status
1733 await this.ocppRequestService
.requestHandler
<
1734 StatusNotificationRequest
,
1735 StatusNotificationResponse
1736 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1738 status: ChargePointStatus
.AVAILABLE
,
1739 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1741 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1745 this.startAutomaticTransactionGenerator();
1748 private startAutomaticTransactionGenerator() {
1749 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
) {
1750 if (!this.automaticTransactionGenerator
) {
1751 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
1752 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
1756 if (!this.automaticTransactionGenerator
.started
) {
1757 this.automaticTransactionGenerator
.start();
1762 private stopAutomaticTransactionGenerator(): void {
1763 if (this.automaticTransactionGenerator
?.started
) {
1764 this.automaticTransactionGenerator
.stop();
1765 this.automaticTransactionGenerator
= null;
1769 private async stopMessageSequence(
1770 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1772 // Stop WebSocket ping
1773 this.stopWebSocketPing();
1775 this.stopHeartbeat();
1776 // Stop ongoing transactions
1777 if (this.automaticTransactionGenerator
?.configuration
?.enable
) {
1778 this.stopAutomaticTransactionGenerator();
1780 for (const connectorId
of this.connectors
.keys()) {
1781 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1782 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1784 this.getBeginEndMeterValues() &&
1785 this.getOcppStrictCompliance() &&
1786 !this.getOutOfOrderEndMeterValues()
1788 // FIXME: Implement OCPP version agnostic helpers
1789 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1792 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1794 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
1796 RequestCommand
.METER_VALUES
,
1800 meterValue
: [transactionEndMeterValue
],
1804 await this.ocppRequestService
.requestHandler
<
1805 StopTransactionRequest
,
1806 StopTransactionResponse
1807 >(this, RequestCommand
.STOP_TRANSACTION
, {
1809 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1810 idTag
: this.getTransactionIdTag(transactionId
),
1818 private startWebSocketPing(): void {
1819 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1821 StandardParametersKey
.WebSocketPingInterval
1823 ? Utils
.convertToInt(
1824 ChargingStationConfigurationUtils
.getConfigurationKey(
1826 StandardParametersKey
.WebSocketPingInterval
1830 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1831 this.webSocketPingSetInterval
= setInterval(() => {
1832 if (this.isWebSocketConnectionOpened()) {
1833 this.wsConnection
.ping((): void => {
1834 /* This is intentional */
1837 }, webSocketPingInterval
* 1000);
1840 ' WebSocket ping started every ' +
1841 Utils
.formatDurationSeconds(webSocketPingInterval
)
1843 } else if (this.webSocketPingSetInterval
) {
1846 ' WebSocket ping every ' +
1847 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1852 `${this.logPrefix()} WebSocket ping interval set to ${
1853 webSocketPingInterval
1854 ? Utils.formatDurationSeconds(webSocketPingInterval)
1855 : webSocketPingInterval
1856 }, not starting the WebSocket ping`
1861 private stopWebSocketPing(): void {
1862 if (this.webSocketPingSetInterval
) {
1863 clearInterval(this.webSocketPingSetInterval
);
1867 private getConfiguredSupervisionUrl(): URL
{
1868 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1869 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1871 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1873 switch (Configuration
.getSupervisionUrlDistribution()) {
1874 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1875 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1877 case SupervisionUrlDistribution
.RANDOM
:
1879 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1881 case SupervisionUrlDistribution
.SEQUENTIAL
:
1882 if (this.index
<= supervisionUrls
.length
) {
1883 urlIndex
= this.index
- 1;
1886 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1892 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1893 SupervisionUrlDistribution.ROUND_ROBIN
1896 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1899 return new URL(supervisionUrls
[urlIndex
]);
1901 return new URL(supervisionUrls
as string);
1904 private getHeartbeatInterval(): number | undefined {
1905 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1907 StandardParametersKey
.HeartbeatInterval
1909 if (HeartbeatInterval
) {
1910 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1912 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1914 StandardParametersKey
.HeartBeatInterval
1916 if (HeartBeatInterval
) {
1917 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1919 !this.stationInfo
?.autoRegister
&&
1921 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1922 Constants.DEFAULT_HEARTBEAT_INTERVAL
1925 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1928 private stopHeartbeat(): void {
1929 if (this.heartbeatSetInterval
) {
1930 clearInterval(this.heartbeatSetInterval
);
1934 private terminateWSConnection(): void {
1935 if (this.isWebSocketConnectionOpened()) {
1936 this.wsConnection
.terminate();
1937 this.wsConnection
= null;
1941 private stopMeterValues(connectorId
: number) {
1942 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1943 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1947 private getReconnectExponentialDelay(): boolean | undefined {
1948 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1949 ? this.stationInfo
.reconnectExponentialDelay
1953 private async reconnect(code
: number): Promise
<void> {
1954 // Stop WebSocket ping
1955 this.stopWebSocketPing();
1957 this.stopHeartbeat();
1958 // Stop the ATG if needed
1959 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
) {
1960 this.stopAutomaticTransactionGenerator();
1963 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1964 this.getAutoReconnectMaxRetries() === -1
1966 this.autoReconnectRetryCount
++;
1967 const reconnectDelay
= this.getReconnectExponentialDelay()
1968 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1969 : this.getConnectionTimeout() * 1000;
1970 const reconnectDelayWithdraw
= 1000;
1971 const reconnectTimeout
=
1972 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
1973 ? reconnectDelay
- reconnectDelayWithdraw
1976 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1979 )}ms, timeout ${reconnectTimeout}ms`
1981 await Utils
.sleep(reconnectDelay
);
1984 ' WebSocket: reconnecting try #' +
1985 this.autoReconnectRetryCount
.toString()
1987 this.openWSConnection(
1988 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
1989 { closeOpened
: true }
1991 this.wsConnectionRestarted
= true;
1992 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1994 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
1995 this.autoReconnectRetryCount
1996 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2001 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
2002 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2005 private initializeConnectorStatus(connectorId
: number): void {
2006 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2007 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2008 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2009 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2010 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2011 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;