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
, MessageEvent
, RawData
} from
'ws';
11 import BaseError from
'../exception/BaseError';
12 import OCPPError from
'../exception/OCPPError';
13 import PerformanceStatistics from
'../performance/PerformanceStatistics';
14 import { AutomaticTransactionGeneratorConfiguration
} from
'../types/AutomaticTransactionGenerator';
15 import ChargingStationConfiguration from
'../types/ChargingStationConfiguration';
16 import ChargingStationInfo from
'../types/ChargingStationInfo';
17 import ChargingStationOcppConfiguration from
'../types/ChargingStationOcppConfiguration';
18 import ChargingStationTemplate
, {
22 } from
'../types/ChargingStationTemplate';
23 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
24 import { ConnectorStatus
} from
'../types/ConnectorStatus';
25 import { FileType
} from
'../types/FileType';
26 import { 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 StartTransactionRequest
,
62 StartTransactionResponse
,
63 StopTransactionReason
,
64 StopTransactionRequest
,
65 StopTransactionResponse
,
66 } from
'../types/ocpp/Transaction';
67 import { ProcedureName
} from
'../types/UIProtocol';
68 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
69 import { WorkerBroadcastChannelData
} from
'../types/WorkerBroadcastChannel';
70 import Configuration from
'../utils/Configuration';
71 import Constants from
'../utils/Constants';
72 import { ACElectricUtils
, DCElectricUtils
} from
'../utils/ElectricUtils';
73 import FileUtils from
'../utils/FileUtils';
74 import logger from
'../utils/Logger';
75 import Utils from
'../utils/Utils';
76 import AuthorizedTagsCache from
'./AuthorizedTagsCache';
77 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
78 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
79 import { ChargingStationUtils
} from
'./ChargingStationUtils';
80 import { MessageChannelUtils
} from
'./MessageChannelUtils';
81 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
82 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
83 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
84 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
85 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
86 import OCPPRequestService from
'./ocpp/OCPPRequestService';
87 import SharedLRUCache from
'./SharedLRUCache';
88 import WorkerBroadcastChannel from
'./WorkerBroadcastChannel';
90 export default class ChargingStation
{
91 public hashId
!: string;
92 public readonly templateFile
: string;
93 public authorizedTagsCache
: AuthorizedTagsCache
;
94 public stationInfo
!: ChargingStationInfo
;
95 public readonly connectors
: Map
<number, ConnectorStatus
>;
96 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
97 public wsConnection
!: WebSocket
;
98 public readonly requests
: Map
<string, CachedRequest
>;
99 public performanceStatistics
!: PerformanceStatistics
;
100 public heartbeatSetInterval
!: NodeJS
.Timeout
;
101 public ocppRequestService
!: OCPPRequestService
;
102 public bootNotificationResponse
!: BootNotificationResponse
| null;
103 public powerDivider
!: number;
104 private readonly index
: number;
105 private configurationFile
!: string;
106 private configurationFileHash
!: string;
107 private bootNotificationRequest
!: BootNotificationRequest
;
108 private connectorsConfigurationHash
!: string;
109 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
110 private readonly messageBuffer
: Set
<string>;
111 private configuredSupervisionUrl
!: URL
;
112 private wsConnectionRestarted
: boolean;
113 private autoReconnectRetryCount
: number;
114 private stopped
: boolean;
115 private templateFileWatcher
!: fs
.FSWatcher
;
116 private readonly sharedLRUCache
: SharedLRUCache
;
117 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
118 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
119 private workerBroadcastChannel
: WorkerBroadcastChannel
;
121 constructor(index
: number, templateFile
: string) {
123 this.templateFile
= templateFile
;
124 this.stopped
= false;
125 this.wsConnectionRestarted
= false;
126 this.autoReconnectRetryCount
= 0;
127 this.sharedLRUCache
= SharedLRUCache
.getInstance();
128 this.authorizedTagsCache
= AuthorizedTagsCache
.getInstance();
129 this.connectors
= new Map
<number, ConnectorStatus
>();
130 this.requests
= new Map
<string, CachedRequest
>();
131 this.messageBuffer
= new Set
<string>();
132 this.workerBroadcastChannel
= new WorkerBroadcastChannel();
134 this.workerBroadcastChannel
.onmessage
= this.handleWorkerBroadcastChannelMessage
.bind(this) as (
135 message
: MessageEvent
141 private get
wsConnectionUrl(): URL
{
143 (this.getSupervisionUrlOcppConfiguration()
144 ? ChargingStationConfigurationUtils
.getConfigurationKey(
146 this.getSupervisionUrlOcppKey()
148 : this.configuredSupervisionUrl
.href
) +
150 this.stationInfo
.chargingStationId
154 public logPrefix(): string {
155 return Utils
.logPrefix(
157 this?.stationInfo?.chargingStationId ??
158 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
163 public getBootNotificationRequest(): BootNotificationRequest
{
164 return this.bootNotificationRequest
;
167 public getRandomIdTag(): string {
168 const authorizationFile
= ChargingStationUtils
.getAuthorizationFile(this.stationInfo
);
169 const index
= Math.floor(
170 Utils
.secureRandom() * this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
).length
172 return this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
)[index
];
175 public hasAuthorizedTags(): boolean {
176 return !Utils
.isEmptyArray(
177 this.authorizedTagsCache
.getAuthorizedTags(
178 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
)
183 public getEnableStatistics(): boolean | undefined {
184 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
185 ? this.stationInfo
.enableStatistics
189 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
190 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
193 public getPayloadSchemaValidation(): boolean | undefined {
194 return this.stationInfo
.payloadSchemaValidation
?? true;
197 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
198 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
199 switch (this.getCurrentOutType(stationInfo
)) {
201 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
202 ? localStationInfo
.numberOfPhases
209 public isWebSocketConnectionOpened(): boolean {
210 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
213 public getRegistrationStatus(): RegistrationStatus
{
214 return this?.bootNotificationResponse
?.status;
217 public isInUnknownState(): boolean {
218 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
221 public isInPendingState(): boolean {
222 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
225 public isInAcceptedState(): boolean {
226 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
229 public isInRejectedState(): boolean {
230 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
233 public isRegistered(): boolean {
234 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
237 public isChargingStationAvailable(): boolean {
238 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
241 public isConnectorAvailable(id
: number): boolean {
242 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
245 public getNumberOfConnectors(): number {
246 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
249 public getConnectorStatus(id
: number): ConnectorStatus
{
250 return this.connectors
.get(id
);
253 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
254 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
;
257 public getOcppStrictCompliance(): boolean {
258 return this.stationInfo
?.ocppStrictCompliance
?? false;
261 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
262 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
263 this.getCurrentOutType(stationInfo
),
267 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
268 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
269 ? localStationInfo
.voltageOut
273 public getConnectorMaximumAvailablePower(connectorId
: number): number {
274 let connectorAmperageLimitationPowerLimit
: number;
276 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
277 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
279 connectorAmperageLimitationPowerLimit
=
280 (this.getCurrentOutType() === CurrentType
.AC
281 ? ACElectricUtils
.powerTotal(
282 this.getNumberOfPhases(),
283 this.getVoltageOut(),
284 this.getAmperageLimitation() * this.getNumberOfConnectors()
286 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
289 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
290 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
292 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
293 isNaN(connectorAmperageLimitationPowerLimit
)
295 : connectorAmperageLimitationPowerLimit
,
296 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
300 public getTransactionIdTag(transactionId
: number): string | undefined {
301 for (const connectorId
of this.connectors
.keys()) {
302 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
303 return this.getConnectorStatus(connectorId
).transactionIdTag
;
308 public getOutOfOrderEndMeterValues(): boolean {
309 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
312 public getBeginEndMeterValues(): boolean {
313 return this.stationInfo
?.beginEndMeterValues
?? false;
316 public getMeteringPerTransaction(): boolean {
317 return this.stationInfo
?.meteringPerTransaction
?? true;
320 public getTransactionDataMeterValues(): boolean {
321 return this.stationInfo
?.transactionDataMeterValues
?? false;
324 public getMainVoltageMeterValues(): boolean {
325 return this.stationInfo
?.mainVoltageMeterValues
?? true;
328 public getPhaseLineToLineVoltageMeterValues(): boolean {
329 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
332 public getCustomValueLimitationMeterValues(): boolean {
333 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
336 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
337 for (const connectorId
of this.connectors
.keys()) {
340 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
347 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
348 const transactionConnectorStatus
= this.getConnectorStatus(
349 this.getConnectorIdByTransactionId(transactionId
)
351 if (this.getMeteringPerTransaction()) {
352 return transactionConnectorStatus
?.transactionEnergyActiveImportRegisterValue
;
354 return transactionConnectorStatus
?.energyActiveImportRegisterValue
;
357 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
358 const connectorStatus
= this.getConnectorStatus(connectorId
);
359 if (this.getMeteringPerTransaction()) {
360 return connectorStatus
?.transactionEnergyActiveImportRegisterValue
;
362 return connectorStatus
?.energyActiveImportRegisterValue
;
365 public getAuthorizeRemoteTxRequests(): boolean {
366 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
368 StandardParametersKey
.AuthorizeRemoteTxRequests
370 return authorizeRemoteTxRequests
371 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
375 public getLocalAuthListEnabled(): boolean {
376 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
378 StandardParametersKey
.LocalAuthListEnabled
380 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
383 public startHeartbeat(): void {
385 this.getHeartbeatInterval() &&
386 this.getHeartbeatInterval() > 0 &&
387 !this.heartbeatSetInterval
389 // eslint-disable-next-line @typescript-eslint/no-misused-promises
390 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
391 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
393 RequestCommand
.HEARTBEAT
395 }, this.getHeartbeatInterval());
398 ' Heartbeat started every ' +
399 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
401 } else if (this.heartbeatSetInterval
) {
404 ' Heartbeat already started every ' +
405 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
409 `${this.logPrefix()} Heartbeat interval set to ${
410 this.getHeartbeatInterval()
411 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
412 : this.getHeartbeatInterval()
413 }, not starting the heartbeat`
418 public restartHeartbeat(): void {
420 this.stopHeartbeat();
422 this.startHeartbeat();
425 public restartWebSocketPing(): void {
426 // Stop WebSocket ping
427 this.stopWebSocketPing();
428 // Start WebSocket ping
429 this.startWebSocketPing();
432 public startMeterValues(connectorId
: number, interval
: number): void {
433 if (connectorId
=== 0) {
435 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
439 if (!this.getConnectorStatus(connectorId
)) {
441 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
445 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
447 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
451 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
452 !this.getConnectorStatus(connectorId
)?.transactionId
455 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
460 // eslint-disable-next-line @typescript-eslint/no-misused-promises
461 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
462 // eslint-disable-next-line @typescript-eslint/no-misused-promises
463 async (): Promise
<void> => {
464 // FIXME: Implement OCPP version agnostic helpers
465 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
468 this.getConnectorStatus(connectorId
).transactionId
,
471 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
473 RequestCommand
.METER_VALUES
,
476 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
477 meterValue
: [meterValue
],
485 `${this.logPrefix()} Charging station ${
486 StandardParametersKey.MeterValueSampleInterval
487 } configuration set to ${
488 interval ? Utils.formatDurationMilliSeconds(interval) : interval
489 }, not sending MeterValues`
494 public start(): void {
495 if (this.getEnableStatistics()) {
496 this.performanceStatistics
.start();
498 this.openWSConnection();
499 // Monitor charging station template file
500 this.templateFileWatcher
= FileUtils
.watchJsonFile(
502 FileType
.ChargingStationTemplate
,
505 (event
, filename
): void => {
506 if (filename
&& event
=== 'change') {
509 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
511 } file have changed, reload`
513 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
517 this.stopAutomaticTransactionGenerator();
518 this.startAutomaticTransactionGenerator();
519 if (this.getEnableStatistics()) {
520 this.performanceStatistics
.restart();
522 this.performanceStatistics
.stop();
524 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
527 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
534 parentPort
.postMessage(MessageChannelUtils
.buildStartedMessage(this));
537 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
538 // Stop message sequence
539 await this.stopMessageSequence(reason
);
540 for (const connectorId
of this.connectors
.keys()) {
541 if (connectorId
> 0) {
542 await this.ocppRequestService
.requestHandler
<
543 StatusNotificationRequest
,
544 StatusNotificationResponse
545 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
547 status: ChargePointStatus
.UNAVAILABLE
,
548 errorCode
: ChargePointErrorCode
.NO_ERROR
,
550 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
553 this.closeWSConnection();
554 if (this.getEnableStatistics()) {
555 this.performanceStatistics
.stop();
557 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
558 this.templateFileWatcher
.close();
559 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
560 this.bootNotificationResponse
= null;
561 parentPort
.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
565 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
566 await this.stop(reason
);
567 await Utils
.sleep(this.stationInfo
.resetTime
);
572 public saveOcppConfiguration(): void {
573 if (this.getOcppPersistentConfiguration()) {
574 this.saveConfiguration();
578 public getChargingProfilePowerLimit(connectorId
: number): number | undefined {
579 let limit
: number, matchingChargingProfile
: ChargingProfile
;
580 let chargingProfiles
: ChargingProfile
[] = [];
581 // Get charging profiles for connector and sort by stack level
582 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
583 (a
, b
) => b
.stackLevel
- a
.stackLevel
585 // Get profiles on connector 0
586 if (this.getConnectorStatus(0).chargingProfiles
) {
587 chargingProfiles
.push(
588 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
591 if (!Utils
.isEmptyArray(chargingProfiles
)) {
592 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
596 if (!Utils
.isNullOrUndefined(result
)) {
597 limit
= result
.limit
;
598 matchingChargingProfile
= result
.matchingChargingProfile
;
599 switch (this.getCurrentOutType()) {
602 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
603 ChargingRateUnitType
.WATT
605 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
609 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
610 ChargingRateUnitType
.WATT
612 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
615 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
616 if (limit
> connectorMaximumPower
) {
618 `${this.logPrefix()} Charging profile id ${
619 matchingChargingProfile.chargingProfileId
620 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
621 this.getConnectorStatus(connectorId
).chargingProfiles
623 limit
= connectorMaximumPower
;
630 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
631 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
633 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
635 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
637 if (!Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
639 `${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`
641 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
643 let cpReplaced
= false;
644 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
645 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
646 (chargingProfile
: ChargingProfile
, index
: number) => {
648 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
649 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
650 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
652 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
658 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
661 public resetConnectorStatus(connectorId
: number): void {
662 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
663 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
664 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
665 this.getConnectorStatus(connectorId
).transactionStarted
= false;
666 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
667 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
668 delete this.getConnectorStatus(connectorId
).transactionId
;
669 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
670 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
671 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
672 this.stopMeterValues(connectorId
);
675 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
676 return ChargingStationConfigurationUtils
.getConfigurationKey(
678 StandardParametersKey
.SupportedFeatureProfiles
679 )?.value
.includes(featureProfile
);
682 public bufferMessage(message
: string): void {
683 this.messageBuffer
.add(message
);
686 private flushMessageBuffer() {
687 if (this.messageBuffer
.size
> 0) {
688 this.messageBuffer
.forEach((message
) => {
689 // TODO: evaluate the need to track performance
690 this.wsConnection
.send(message
);
691 this.messageBuffer
.delete(message
);
696 private getSupervisionUrlOcppConfiguration(): boolean {
697 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
700 private getSupervisionUrlOcppKey(): string {
701 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
704 private getTemplateFromFile(): ChargingStationTemplate
| null {
705 let template
: ChargingStationTemplate
= null;
707 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
708 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
710 const measureId
= `${FileType.ChargingStationTemplate} read`;
711 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
712 template
= JSON
.parse(
713 fs
.readFileSync(this.templateFile
, 'utf8')
714 ) as ChargingStationTemplate
;
715 PerformanceStatistics
.endMeasure(measureId
, beginId
);
716 template
.templateHash
= crypto
717 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
718 .update(JSON
.stringify(template
))
720 this.sharedLRUCache
.setChargingStationTemplate(template
);
723 FileUtils
.handleFileException(
725 FileType
.ChargingStationTemplate
,
727 error
as NodeJS
.ErrnoException
733 private getStationInfoFromTemplate(): ChargingStationInfo
{
734 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
735 if (Utils
.isNullOrUndefined(stationTemplate
)) {
736 const errorMsg
= 'Failed to read charging station template file';
737 logger
.error(`${this.logPrefix()} ${errorMsg}`);
738 throw new BaseError(errorMsg
);
740 if (Utils
.isEmptyObject(stationTemplate
)) {
741 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
742 logger
.error(`${this.logPrefix()} ${errorMsg}`);
743 throw new BaseError(errorMsg
);
745 // Deprecation template keys section
746 ChargingStationUtils
.warnDeprecatedTemplateKey(
751 "Use 'supervisionUrls' instead"
753 ChargingStationUtils
.convertDeprecatedTemplateKey(
758 const stationInfo
: ChargingStationInfo
=
759 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
760 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
764 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
765 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
766 stationTemplate
.power
= stationTemplate
.power
as number[];
767 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
768 stationInfo
.maximumPower
=
769 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
770 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
771 : stationTemplate
.power
[powerArrayRandomIndex
];
773 stationTemplate
.power
= stationTemplate
.power
as number;
774 stationInfo
.maximumPower
=
775 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
776 ? stationTemplate
.power
* 1000
777 : stationTemplate
.power
;
779 stationInfo
.resetTime
= stationTemplate
.resetTime
780 ? stationTemplate
.resetTime
* 1000
781 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
782 const configuredMaxConnectors
= ChargingStationUtils
.getConfiguredNumberOfConnectors(
786 ChargingStationUtils
.checkConfiguredMaxConnectors(
787 configuredMaxConnectors
,
791 const templateMaxConnectors
=
792 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
793 ChargingStationUtils
.checkTemplateMaxConnectors(
794 templateMaxConnectors
,
799 configuredMaxConnectors
>
800 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
801 !stationTemplate
?.randomConnectors
804 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
806 }, forcing random connector configurations affectation`
808 stationInfo
.randomConnectors
= true;
810 // Build connectors if needed (FIXME: should be factored out)
811 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
812 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
813 ChargingStationUtils
.createStationInfoHash(stationInfo
);
817 private getStationInfoFromFile(): ChargingStationInfo
| null {
818 let stationInfo
: ChargingStationInfo
= null;
819 this.getStationInfoPersistentConfiguration() &&
820 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
821 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
825 private getStationInfo(): ChargingStationInfo
{
826 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
827 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
828 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
829 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
830 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
831 return this.stationInfo
;
833 return stationInfoFromFile
;
835 stationInfoFromFile
&&
836 ChargingStationUtils
.propagateSerialNumber(
837 this.getTemplateFromFile(),
839 stationInfoFromTemplate
841 return stationInfoFromTemplate
;
844 private saveStationInfo(): void {
845 if (this.getStationInfoPersistentConfiguration()) {
846 this.saveConfiguration();
850 private getOcppVersion(): OCPPVersion
{
851 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
854 private getOcppPersistentConfiguration(): boolean {
855 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
858 private getStationInfoPersistentConfiguration(): boolean {
859 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
862 private handleUnsupportedVersion(version
: OCPPVersion
) {
863 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
866 logger
.error(errMsg
);
867 throw new Error(errMsg
);
870 private initialize(): void {
871 this.hashId
= ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile());
872 logger
.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
873 this.configurationFile
= path
.join(
874 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
875 this.hashId
+ '.json'
877 this.stationInfo
= this.getStationInfo();
878 this.saveStationInfo();
879 // Avoid duplication of connectors related information in RAM
880 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
881 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
882 if (this.getEnableStatistics()) {
883 this.performanceStatistics
= PerformanceStatistics
.getInstance(
885 this.stationInfo
.chargingStationId
,
886 this.configuredSupervisionUrl
889 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
892 this.powerDivider
= this.getPowerDivider();
893 // OCPP configuration
894 this.ocppConfiguration
= this.getOcppConfiguration();
895 this.initializeOcppConfiguration();
896 switch (this.getOcppVersion()) {
897 case OCPPVersion
.VERSION_16
:
898 this.ocppIncomingRequestService
=
899 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
900 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
901 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
905 this.handleUnsupportedVersion(this.getOcppVersion());
908 if (this.stationInfo
?.autoRegister
) {
909 this.bootNotificationResponse
= {
910 currentTime
: new Date().toISOString(),
911 interval
: this.getHeartbeatInterval() / 1000,
912 status: RegistrationStatus
.ACCEPTED
,
917 private initializeOcppConfiguration(): void {
919 !ChargingStationConfigurationUtils
.getConfigurationKey(
921 StandardParametersKey
.HeartbeatInterval
924 ChargingStationConfigurationUtils
.addConfigurationKey(
926 StandardParametersKey
.HeartbeatInterval
,
931 !ChargingStationConfigurationUtils
.getConfigurationKey(
933 StandardParametersKey
.HeartBeatInterval
936 ChargingStationConfigurationUtils
.addConfigurationKey(
938 StandardParametersKey
.HeartBeatInterval
,
944 this.getSupervisionUrlOcppConfiguration() &&
945 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
947 ChargingStationConfigurationUtils
.addConfigurationKey(
949 this.getSupervisionUrlOcppKey(),
950 this.configuredSupervisionUrl
.href
,
954 !this.getSupervisionUrlOcppConfiguration() &&
955 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
957 ChargingStationConfigurationUtils
.deleteConfigurationKey(
959 this.getSupervisionUrlOcppKey(),
964 this.stationInfo
.amperageLimitationOcppKey
&&
965 !ChargingStationConfigurationUtils
.getConfigurationKey(
967 this.stationInfo
.amperageLimitationOcppKey
970 ChargingStationConfigurationUtils
.addConfigurationKey(
972 this.stationInfo
.amperageLimitationOcppKey
,
974 this.stationInfo
.maximumAmperage
*
975 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
980 !ChargingStationConfigurationUtils
.getConfigurationKey(
982 StandardParametersKey
.SupportedFeatureProfiles
985 ChargingStationConfigurationUtils
.addConfigurationKey(
987 StandardParametersKey
.SupportedFeatureProfiles
,
988 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
991 ChargingStationConfigurationUtils
.addConfigurationKey(
993 StandardParametersKey
.NumberOfConnectors
,
994 this.getNumberOfConnectors().toString(),
999 !ChargingStationConfigurationUtils
.getConfigurationKey(
1001 StandardParametersKey
.MeterValuesSampledData
1004 ChargingStationConfigurationUtils
.addConfigurationKey(
1006 StandardParametersKey
.MeterValuesSampledData
,
1007 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1011 !ChargingStationConfigurationUtils
.getConfigurationKey(
1013 StandardParametersKey
.ConnectorPhaseRotation
1016 const connectorPhaseRotation
= [];
1017 for (const connectorId
of this.connectors
.keys()) {
1019 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1020 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1021 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1022 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1024 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1025 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1026 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1027 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1030 ChargingStationConfigurationUtils
.addConfigurationKey(
1032 StandardParametersKey
.ConnectorPhaseRotation
,
1033 connectorPhaseRotation
.toString()
1037 !ChargingStationConfigurationUtils
.getConfigurationKey(
1039 StandardParametersKey
.AuthorizeRemoteTxRequests
1042 ChargingStationConfigurationUtils
.addConfigurationKey(
1044 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1049 !ChargingStationConfigurationUtils
.getConfigurationKey(
1051 StandardParametersKey
.LocalAuthListEnabled
1053 ChargingStationConfigurationUtils
.getConfigurationKey(
1055 StandardParametersKey
.SupportedFeatureProfiles
1056 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1058 ChargingStationConfigurationUtils
.addConfigurationKey(
1060 StandardParametersKey
.LocalAuthListEnabled
,
1065 !ChargingStationConfigurationUtils
.getConfigurationKey(
1067 StandardParametersKey
.ConnectionTimeOut
1070 ChargingStationConfigurationUtils
.addConfigurationKey(
1072 StandardParametersKey
.ConnectionTimeOut
,
1073 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1076 this.saveOcppConfiguration();
1079 private initializeConnectors(
1080 stationInfo
: ChargingStationInfo
,
1081 configuredMaxConnectors
: number,
1082 templateMaxConnectors
: number
1084 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1085 const logMsg
= `${this.logPrefix()} No already defined connectors and charging station information from template ${
1087 } with no connectors configuration defined`;
1088 logger
.error(logMsg
);
1089 throw new BaseError(logMsg
);
1091 if (!stationInfo
?.Connectors
[0]) {
1093 `${this.logPrefix()} Charging station information from template ${
1095 } with no connector Id 0 configuration`
1098 if (stationInfo
?.Connectors
) {
1099 const connectorsConfigHash
= crypto
1100 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1101 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1103 const connectorsConfigChanged
=
1104 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1105 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1106 connectorsConfigChanged
&& this.connectors
.clear();
1107 this.connectorsConfigurationHash
= connectorsConfigHash
;
1108 // Add connector Id 0
1109 let lastConnector
= '0';
1110 for (lastConnector
in stationInfo
?.Connectors
) {
1111 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1113 lastConnectorId
=== 0 &&
1114 this.getUseConnectorId0(stationInfo
) &&
1115 stationInfo
?.Connectors
[lastConnector
]
1117 this.connectors
.set(
1119 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1121 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1122 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1123 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1127 // Generate all connectors
1128 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1129 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1130 const randConnectorId
= stationInfo
?.randomConnectors
1131 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1133 this.connectors
.set(
1135 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1137 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1138 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1139 this.getConnectorStatus(index
).chargingProfiles
= [];
1146 `${this.logPrefix()} Charging station information from template ${
1148 } with no connectors configuration defined, using already defined connectors`
1151 // Initialize transaction attributes on connectors
1152 for (const connectorId
of this.connectors
.keys()) {
1153 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1154 this.initializeConnectorStatus(connectorId
);
1159 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1160 let configuration
: ChargingStationConfiguration
= null;
1161 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1163 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1164 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1165 this.configurationFileHash
1168 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1169 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1170 configuration
= JSON
.parse(
1171 fs
.readFileSync(this.configurationFile
, 'utf8')
1172 ) as ChargingStationConfiguration
;
1173 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1174 this.configurationFileHash
= configuration
.configurationHash
;
1175 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1178 FileUtils
.handleFileException(
1180 FileType
.ChargingStationConfiguration
,
1181 this.configurationFile
,
1182 error
as NodeJS
.ErrnoException
1186 return configuration
;
1189 private saveConfiguration(): void {
1190 if (this.configurationFile
) {
1192 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1193 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1195 const configurationData
: ChargingStationConfiguration
=
1196 this.getConfigurationFromFile() ?? {};
1197 this.ocppConfiguration
?.configurationKey
&&
1198 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1199 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1200 delete configurationData
.configurationHash
;
1201 const configurationHash
= crypto
1202 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1203 .update(JSON
.stringify(configurationData
))
1205 if (this.configurationFileHash
!== configurationHash
) {
1206 configurationData
.configurationHash
= configurationHash
;
1207 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1208 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1209 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1210 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1211 fs
.closeSync(fileDescriptor
);
1212 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1213 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1214 this.configurationFileHash
= configurationHash
;
1215 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1218 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1219 this.configurationFile
1224 FileUtils
.handleFileException(
1226 FileType
.ChargingStationConfiguration
,
1227 this.configurationFile
,
1228 error
as NodeJS
.ErrnoException
1233 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1238 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1239 return this.getTemplateFromFile()?.Configuration
?? null;
1242 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1243 let configuration
: ChargingStationConfiguration
= null;
1244 if (this.getOcppPersistentConfiguration()) {
1245 const configurationFromFile
= this.getConfigurationFromFile();
1246 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1248 configuration
&& delete configuration
.stationInfo
;
1249 return configuration
;
1252 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1253 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1254 if (!ocppConfiguration
) {
1255 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1257 return ocppConfiguration
;
1260 private async onOpen(): Promise
<void> {
1261 if (this.isWebSocketConnectionOpened()) {
1263 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1265 if (!this.isRegistered()) {
1266 // Send BootNotification
1267 let registrationRetryCount
= 0;
1269 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1270 BootNotificationRequest
,
1271 BootNotificationResponse
1274 RequestCommand
.BOOT_NOTIFICATION
,
1276 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1277 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1278 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1279 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1280 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1281 iccid
: this.bootNotificationRequest
.iccid
,
1282 imsi
: this.bootNotificationRequest
.imsi
,
1283 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1284 meterType
: this.bootNotificationRequest
.meterType
,
1286 { skipBufferingOnError
: true }
1288 if (!this.isRegistered()) {
1289 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1291 this.bootNotificationResponse
?.interval
1292 ? this.bootNotificationResponse
.interval
* 1000
1293 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1297 !this.isRegistered() &&
1298 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1299 this.getRegistrationMaxRetries() === -1)
1302 if (this.isRegistered()) {
1303 if (this.isInAcceptedState()) {
1304 await this.startMessageSequence();
1305 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1309 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1312 this.stopped
&& (this.stopped
= false);
1313 this.autoReconnectRetryCount
= 0;
1314 this.wsConnectionRestarted
= false;
1317 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1322 private async onClose(code
: number, reason
: string): Promise
<void> {
1325 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1326 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1328 `${this.logPrefix()} WebSocket normally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1330 )}' and reason '${reason}'`
1332 this.autoReconnectRetryCount
= 0;
1337 `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1339 )}' and reason '${reason}'`
1341 await this.reconnect(code
);
1346 private async onMessage(data
: Data
): Promise
<void> {
1347 let messageType
: number;
1348 let messageId
: string;
1349 let commandName
: IncomingRequestCommand
;
1350 let commandPayload
: JsonType
;
1351 let errorType
: ErrorType
;
1352 let errorMessage
: string;
1353 let errorDetails
: JsonType
;
1354 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1355 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1356 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1357 let requestPayload
: JsonType
;
1358 let cachedRequest
: CachedRequest
;
1361 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1362 if (Utils
.isIterable(request
)) {
1363 [messageType
, messageId
] = request
;
1364 // Check the type of message
1365 switch (messageType
) {
1367 case MessageType
.CALL_MESSAGE
:
1368 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1369 if (this.getEnableStatistics()) {
1370 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1373 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1377 // Process the message
1378 await this.ocppIncomingRequestService
.incomingRequestHandler(
1386 case MessageType
.CALL_RESULT_MESSAGE
:
1387 [, , commandPayload
] = request
as Response
;
1388 if (!this.requests
.has(messageId
)) {
1390 throw new OCPPError(
1391 ErrorType
.INTERNAL_ERROR
,
1392 `Response for unknown message id ${messageId}`,
1398 cachedRequest
= this.requests
.get(messageId
);
1399 if (Utils
.isIterable(cachedRequest
)) {
1400 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1402 throw new OCPPError(
1403 ErrorType
.PROTOCOL_ERROR
,
1404 `Cached request for message id ${messageId} response is not iterable`,
1406 cachedRequest
as unknown
as JsonType
1410 `${this.logPrefix()} << Command '${
1411 requestCommandName ?? 'unknown'
1412 }' received response payload: ${JSON.stringify(request)}`
1414 responseCallback(commandPayload
, requestPayload
);
1417 case MessageType
.CALL_ERROR_MESSAGE
:
1418 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1419 if (!this.requests
.has(messageId
)) {
1421 throw new OCPPError(
1422 ErrorType
.INTERNAL_ERROR
,
1423 `Error response for unknown message id ${messageId}`,
1425 { errorType
, errorMessage
, errorDetails
}
1428 cachedRequest
= this.requests
.get(messageId
);
1429 if (Utils
.isIterable(cachedRequest
)) {
1430 [, errorCallback
, requestCommandName
] = cachedRequest
;
1432 throw new OCPPError(
1433 ErrorType
.PROTOCOL_ERROR
,
1434 `Cached request for message id ${messageId} error response is not iterable`,
1436 cachedRequest
as unknown
as JsonType
1440 `${this.logPrefix()} << Command '${
1441 requestCommandName ?? 'unknown'
1442 }' received error payload: ${JSON.stringify(request)}`
1444 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1448 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1449 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
1450 logger
.error(errMsg
);
1451 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1453 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1455 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not iterable', null, {
1462 "%s Incoming OCPP '%s' message '%j' matching cached request '%j' processing error:",
1464 commandName
?? requestCommandName
?? null,
1466 this.requests
.get(messageId
),
1469 if (!(error
instanceof OCPPError
)) {
1471 "%s Error thrown at incoming OCPP '%s' message '%j' handling is not an OCPPError:",
1473 commandName
?? requestCommandName
?? null,
1479 messageType
=== MessageType
.CALL_MESSAGE
&&
1480 (await this.ocppRequestService
.sendError(
1484 commandName
?? requestCommandName
?? null
1489 private onPing(): void {
1490 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1493 private onPong(): void {
1494 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1497 private onError(error
: WSError
): void {
1498 this.closeWSConnection();
1499 logger
.error(this.logPrefix() + ' WebSocket error:', error
);
1502 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean | undefined {
1503 const localStationInfo
= stationInfo
?? this.stationInfo
;
1504 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1505 ? localStationInfo
.useConnectorId0
1509 private getNumberOfRunningTransactions(): number {
1511 for (const connectorId
of this.connectors
.keys()) {
1512 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1520 private getConnectionTimeout(): number | undefined {
1522 ChargingStationConfigurationUtils
.getConfigurationKey(
1524 StandardParametersKey
.ConnectionTimeOut
1529 ChargingStationConfigurationUtils
.getConfigurationKey(
1531 StandardParametersKey
.ConnectionTimeOut
1533 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1536 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1539 // -1 for unlimited, 0 for disabling
1540 private getAutoReconnectMaxRetries(): number | undefined {
1541 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1542 return this.stationInfo
.autoReconnectMaxRetries
;
1544 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1545 return Configuration
.getAutoReconnectMaxRetries();
1551 private getRegistrationMaxRetries(): number | undefined {
1552 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1553 return this.stationInfo
.registrationMaxRetries
;
1558 private getPowerDivider(): number {
1559 let powerDivider
= this.getNumberOfConnectors();
1560 if (this.stationInfo
?.powerSharedByConnectors
) {
1561 powerDivider
= this.getNumberOfRunningTransactions();
1563 return powerDivider
;
1566 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1567 const localStationInfo
= stationInfo
?? this.stationInfo
;
1568 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1571 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1572 const maximumPower
= this.getMaximumPower(stationInfo
);
1573 switch (this.getCurrentOutType(stationInfo
)) {
1574 case CurrentType
.AC
:
1575 return ACElectricUtils
.amperagePerPhaseFromPower(
1576 this.getNumberOfPhases(stationInfo
),
1577 maximumPower
/ this.getNumberOfConnectors(),
1578 this.getVoltageOut(stationInfo
)
1580 case CurrentType
.DC
:
1581 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1585 private getAmperageLimitation(): number | undefined {
1587 this.stationInfo
.amperageLimitationOcppKey
&&
1588 ChargingStationConfigurationUtils
.getConfigurationKey(
1590 this.stationInfo
.amperageLimitationOcppKey
1595 ChargingStationConfigurationUtils
.getConfigurationKey(
1597 this.stationInfo
.amperageLimitationOcppKey
1599 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1604 private async startMessageSequence(): Promise
<void> {
1605 if (this.stationInfo
?.autoRegister
) {
1606 await this.ocppRequestService
.requestHandler
<
1607 BootNotificationRequest
,
1608 BootNotificationResponse
1611 RequestCommand
.BOOT_NOTIFICATION
,
1613 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1614 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1615 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1616 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1617 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1618 iccid
: this.bootNotificationRequest
.iccid
,
1619 imsi
: this.bootNotificationRequest
.imsi
,
1620 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1621 meterType
: this.bootNotificationRequest
.meterType
,
1623 { skipBufferingOnError
: true }
1626 // Start WebSocket ping
1627 this.startWebSocketPing();
1629 this.startHeartbeat();
1630 // Initialize connectors status
1631 for (const connectorId
of this.connectors
.keys()) {
1632 if (connectorId
=== 0) {
1636 !this.getConnectorStatus(connectorId
)?.status &&
1637 this.getConnectorStatus(connectorId
)?.bootStatus
1639 // Send status in template at startup
1640 await this.ocppRequestService
.requestHandler
<
1641 StatusNotificationRequest
,
1642 StatusNotificationResponse
1643 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1645 status: this.getConnectorStatus(connectorId
).bootStatus
,
1646 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1648 this.getConnectorStatus(connectorId
).status =
1649 this.getConnectorStatus(connectorId
).bootStatus
;
1652 this.getConnectorStatus(connectorId
)?.status &&
1653 this.getConnectorStatus(connectorId
)?.bootStatus
1655 // Send status in template after reset
1656 await this.ocppRequestService
.requestHandler
<
1657 StatusNotificationRequest
,
1658 StatusNotificationResponse
1659 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1661 status: this.getConnectorStatus(connectorId
).bootStatus
,
1662 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1664 this.getConnectorStatus(connectorId
).status =
1665 this.getConnectorStatus(connectorId
).bootStatus
;
1666 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1667 // Send previous status at template reload
1668 await this.ocppRequestService
.requestHandler
<
1669 StatusNotificationRequest
,
1670 StatusNotificationResponse
1671 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1673 status: this.getConnectorStatus(connectorId
).status,
1674 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1677 // Send default status
1678 await this.ocppRequestService
.requestHandler
<
1679 StatusNotificationRequest
,
1680 StatusNotificationResponse
1681 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1683 status: ChargePointStatus
.AVAILABLE
,
1684 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1686 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1690 this.startAutomaticTransactionGenerator();
1693 private startAutomaticTransactionGenerator() {
1694 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
) {
1695 if (!this.automaticTransactionGenerator
) {
1696 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
1697 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
1701 if (!this.automaticTransactionGenerator
.started
) {
1702 this.automaticTransactionGenerator
.start();
1707 private stopAutomaticTransactionGenerator(): void {
1708 if (this.automaticTransactionGenerator
?.started
) {
1709 this.automaticTransactionGenerator
.stop();
1710 this.automaticTransactionGenerator
= null;
1714 private async stopMessageSequence(
1715 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1717 // Stop WebSocket ping
1718 this.stopWebSocketPing();
1720 this.stopHeartbeat();
1721 // Stop ongoing transactions
1722 if (this.automaticTransactionGenerator
?.configuration
?.enable
) {
1723 this.stopAutomaticTransactionGenerator();
1725 for (const connectorId
of this.connectors
.keys()) {
1726 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1727 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1729 this.getBeginEndMeterValues() &&
1730 this.getOcppStrictCompliance() &&
1731 !this.getOutOfOrderEndMeterValues()
1733 // FIXME: Implement OCPP version agnostic helpers
1734 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1737 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1739 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
1741 RequestCommand
.METER_VALUES
,
1745 meterValue
: [transactionEndMeterValue
],
1749 await this.ocppRequestService
.requestHandler
<
1750 StopTransactionRequest
,
1751 StopTransactionResponse
1752 >(this, RequestCommand
.STOP_TRANSACTION
, {
1754 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1755 idTag
: this.getTransactionIdTag(transactionId
),
1763 private startWebSocketPing(): void {
1764 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1766 StandardParametersKey
.WebSocketPingInterval
1768 ? Utils
.convertToInt(
1769 ChargingStationConfigurationUtils
.getConfigurationKey(
1771 StandardParametersKey
.WebSocketPingInterval
1775 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1776 this.webSocketPingSetInterval
= setInterval(() => {
1777 if (this.isWebSocketConnectionOpened()) {
1778 this.wsConnection
.ping((): void => {
1779 /* This is intentional */
1782 }, webSocketPingInterval
* 1000);
1785 ' WebSocket ping started every ' +
1786 Utils
.formatDurationSeconds(webSocketPingInterval
)
1788 } else if (this.webSocketPingSetInterval
) {
1791 ' WebSocket ping every ' +
1792 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1797 `${this.logPrefix()} WebSocket ping interval set to ${
1798 webSocketPingInterval
1799 ? Utils.formatDurationSeconds(webSocketPingInterval)
1800 : webSocketPingInterval
1801 }, not starting the WebSocket ping`
1806 private stopWebSocketPing(): void {
1807 if (this.webSocketPingSetInterval
) {
1808 clearInterval(this.webSocketPingSetInterval
);
1812 private getConfiguredSupervisionUrl(): URL
{
1813 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1814 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1816 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1818 switch (Configuration
.getSupervisionUrlDistribution()) {
1819 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1820 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1822 case SupervisionUrlDistribution
.RANDOM
:
1824 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1826 case SupervisionUrlDistribution
.SEQUENTIAL
:
1827 if (this.index
<= supervisionUrls
.length
) {
1828 urlIndex
= this.index
- 1;
1831 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1837 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1838 SupervisionUrlDistribution.ROUND_ROBIN
1841 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1844 return new URL(supervisionUrls
[urlIndex
]);
1846 return new URL(supervisionUrls
as string);
1849 private getHeartbeatInterval(): number | undefined {
1850 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1852 StandardParametersKey
.HeartbeatInterval
1854 if (HeartbeatInterval
) {
1855 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1857 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1859 StandardParametersKey
.HeartBeatInterval
1861 if (HeartBeatInterval
) {
1862 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1864 !this.stationInfo
?.autoRegister
&&
1866 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1867 Constants.DEFAULT_HEARTBEAT_INTERVAL
1870 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1873 private stopHeartbeat(): void {
1874 if (this.heartbeatSetInterval
) {
1875 clearInterval(this.heartbeatSetInterval
);
1879 private openWSConnection(
1880 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
1881 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
1883 terminateOpened
: false,
1886 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
1887 params
.closeOpened
= params
?.closeOpened
?? false;
1888 params
.terminateOpened
= params
?.terminateOpened
?? false;
1890 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
1891 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
1893 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
1895 if (params
?.closeOpened
) {
1896 this.closeWSConnection();
1898 if (params
?.terminateOpened
) {
1899 this.terminateWSConnection();
1901 let protocol
: string;
1902 switch (this.getOcppVersion()) {
1903 case OCPPVersion
.VERSION_16
:
1904 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
1907 this.handleUnsupportedVersion(this.getOcppVersion());
1912 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString()
1915 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
1917 // Handle WebSocket message
1918 this.wsConnection
.on(
1920 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
1922 // Handle WebSocket error
1923 this.wsConnection
.on(
1925 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
1927 // Handle WebSocket close
1928 this.wsConnection
.on(
1930 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
1932 // Handle WebSocket open
1933 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
1934 // Handle WebSocket ping
1935 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
1936 // Handle WebSocket pong
1937 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
1940 private closeWSConnection(): void {
1941 if (this.isWebSocketConnectionOpened()) {
1942 this.wsConnection
.close();
1943 this.wsConnection
= null;
1947 private terminateWSConnection(): void {
1948 if (this.isWebSocketConnectionOpened()) {
1949 this.wsConnection
.terminate();
1950 this.wsConnection
= null;
1954 private stopMeterValues(connectorId
: number) {
1955 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1956 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1960 private getReconnectExponentialDelay(): boolean | undefined {
1961 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1962 ? this.stationInfo
.reconnectExponentialDelay
1966 private async reconnect(code
: number): Promise
<void> {
1967 // Stop WebSocket ping
1968 this.stopWebSocketPing();
1970 this.stopHeartbeat();
1971 // Stop the ATG if needed
1972 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
) {
1973 this.stopAutomaticTransactionGenerator();
1976 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1977 this.getAutoReconnectMaxRetries() === -1
1979 this.autoReconnectRetryCount
++;
1980 const reconnectDelay
= this.getReconnectExponentialDelay()
1981 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1982 : this.getConnectionTimeout() * 1000;
1983 const reconnectDelayWithdraw
= 1000;
1984 const reconnectTimeout
=
1985 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
1986 ? reconnectDelay
- reconnectDelayWithdraw
1989 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1992 )}ms, timeout ${reconnectTimeout}ms`
1994 await Utils
.sleep(reconnectDelay
);
1997 ' WebSocket: reconnecting try #' +
1998 this.autoReconnectRetryCount
.toString()
2000 this.openWSConnection(
2001 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
2002 { closeOpened
: true }
2004 this.wsConnectionRestarted
= true;
2005 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2007 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2008 this.autoReconnectRetryCount
2009 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2014 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
2015 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2018 private initializeConnectorStatus(connectorId
: number): void {
2019 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2020 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2021 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2022 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2023 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2024 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
2027 private async handleWorkerBroadcastChannelMessage(message
: MessageEvent
): Promise
<void> {
2028 const [command
, payload
] = message
.data
as unknown
as [
2030 WorkerBroadcastChannelData
2033 if (payload
.hashId
!== this.hashId
) {
2038 case ProcedureName
.START_TRANSACTION
:
2039 await this.ocppRequestService
.requestHandler
<
2040 StartTransactionRequest
,
2041 StartTransactionResponse
2042 >(this, RequestCommand
.START_TRANSACTION
, {
2043 connectorId
: payload
.connectorId
,
2044 idTag
: payload
.idTag
,
2047 case ProcedureName
.STOP_TRANSACTION
:
2048 await this.ocppRequestService
.requestHandler
<
2049 StopTransactionRequest
,
2050 StopTransactionResponse
2051 >(this, RequestCommand
.STOP_TRANSACTION
, {
2052 transactionId
: payload
.transactionId
,
2053 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(payload
.transactionId
),
2054 idTag
: this.getTransactionIdTag(payload
.transactionId
),
2055 reason
: StopTransactionReason
.NONE
,