1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import PerformanceStatistics from
'../performance/PerformanceStatistics';
5 AutomaticTransactionGeneratorConfiguration
,
7 } from
'../types/AutomaticTransactionGenerator';
8 import { RequestCommand
} from
'../types/ocpp/Requests';
13 StartTransactionRequest
,
14 StartTransactionResponse
,
15 StopTransactionReason
,
16 StopTransactionResponse
,
17 } from
'../types/ocpp/Transaction';
18 import Constants from
'../utils/Constants';
19 import logger from
'../utils/Logger';
20 import Utils from
'../utils/Utils';
21 import type ChargingStation from
'./ChargingStation';
23 export default class AutomaticTransactionGenerator
{
24 private static readonly instances
: Map
<string, AutomaticTransactionGenerator
> = new Map
<
26 AutomaticTransactionGenerator
29 public readonly connectorsStatus
: Map
<number, Status
>;
30 public readonly configuration
: AutomaticTransactionGeneratorConfiguration
;
31 public started
: boolean;
32 private readonly chargingStation
: ChargingStation
;
35 automaticTransactionGeneratorConfiguration
: AutomaticTransactionGeneratorConfiguration
,
36 chargingStation
: ChargingStation
38 this.configuration
= automaticTransactionGeneratorConfiguration
;
39 this.chargingStation
= chargingStation
;
40 this.connectorsStatus
= new Map
<number, Status
>();
41 this.stopConnectors();
45 public static getInstance(
46 automaticTransactionGeneratorConfiguration
: AutomaticTransactionGeneratorConfiguration
,
47 chargingStation
: ChargingStation
48 ): AutomaticTransactionGenerator
{
49 if (!AutomaticTransactionGenerator
.instances
.has(chargingStation
.stationInfo
.hashId
)) {
50 AutomaticTransactionGenerator
.instances
.set(
51 chargingStation
.stationInfo
.hashId
,
52 new AutomaticTransactionGenerator(
53 automaticTransactionGeneratorConfiguration
,
58 return AutomaticTransactionGenerator
.instances
.get(chargingStation
.stationInfo
.hashId
);
61 public start(): void {
62 if (this.started
=== true) {
63 logger
.warn(`${this.logPrefix()} trying to start while already started`);
66 this.startConnectors();
71 if (this.started
=== false) {
72 logger
.warn(`${this.logPrefix()} trying to stop while not started`);
75 this.stopConnectors();
79 public startConnector(connectorId
: number): void {
80 if (this.chargingStation
.connectors
.has(connectorId
) === false) {
81 logger
.warn(`${this.logPrefix(connectorId)} trying to start on non existing connector`);
84 if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
85 // Avoid hogging the event loop with a busy loop
87 this.internalStartConnector(connectorId
).catch(() => {
88 /* This is intentional */
91 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
92 logger
.warn(`${this.logPrefix(connectorId)} already started on connector`);
96 public stopConnector(connectorId
: number): void {
97 this.connectorsStatus
.set(connectorId
, {
98 ...this.connectorsStatus
.get(connectorId
),
103 private startConnectors(): void {
105 this.connectorsStatus
?.size
> 0 &&
106 this.connectorsStatus
.size
!== this.chargingStation
.getNumberOfConnectors()
108 this.connectorsStatus
.clear();
110 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
111 if (connectorId
> 0) {
112 this.startConnector(connectorId
);
117 private stopConnectors(): void {
118 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
119 if (connectorId
> 0) {
120 this.stopConnector(connectorId
);
125 private async internalStartConnector(connectorId
: number): Promise
<void> {
126 this.initializeConnectorStatus(connectorId
);
128 this.logPrefix(connectorId
) +
129 ' started on connector and will run for ' +
130 Utils
.formatDurationMilliSeconds(
131 this.connectorsStatus
.get(connectorId
).stopDate
.getTime() -
132 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
135 while (this.connectorsStatus
.get(connectorId
).start
=== true) {
136 if (new Date() > this.connectorsStatus
.get(connectorId
).stopDate
) {
137 this.stopConnector(connectorId
);
140 if (!this.chargingStation
.isInAcceptedState()) {
142 this.logPrefix(connectorId
) +
143 ' entered in transaction loop while the charging station is not in accepted state'
145 this.stopConnector(connectorId
);
148 if (!this.chargingStation
.isChargingStationAvailable()) {
150 this.logPrefix(connectorId
) +
151 ' entered in transaction loop while the charging station is unavailable'
153 this.stopConnector(connectorId
);
156 if (!this.chargingStation
.isConnectorAvailable(connectorId
)) {
160 )} entered in transaction loop while the connector ${connectorId} is unavailable`
162 this.stopConnector(connectorId
);
165 if (!this.chargingStation
?.ocppRequestService
) {
169 )} transaction loop waiting for charging station service to be initialized`
172 await Utils
.sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
173 } while (!this.chargingStation
?.ocppRequestService
);
176 Utils
.getRandomInteger(
177 this.configuration
.maxDelayBetweenTwoTransactions
,
178 this.configuration
.minDelayBetweenTwoTransactions
181 this.logPrefix(connectorId
) + ' waiting for ' + Utils
.formatDurationMilliSeconds(wait
)
183 await Utils
.sleep(wait
);
184 const start
= Utils
.secureRandom();
185 if (start
< this.configuration
.probabilityOfStart
) {
186 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
188 const startResponse
= await this.startTransaction(connectorId
);
189 this.connectorsStatus
.get(connectorId
).startTransactionRequests
++;
190 if (startResponse
?.idTagInfo
?.status !== AuthorizationStatus
.ACCEPTED
) {
191 logger
.warn(this.logPrefix(connectorId
) + ' start transaction rejected');
192 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
++;
194 // Wait until end of transaction
196 Utils
.getRandomInteger(this.configuration
.maxDuration
, this.configuration
.minDuration
) *
199 this.logPrefix(connectorId
) +
201 this.chargingStation
.getConnectorStatus(connectorId
).transactionId
.toString() +
202 ' started and will stop in ' +
203 Utils
.formatDurationMilliSeconds(waitTrxEnd
)
205 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
++;
206 await Utils
.sleep(waitTrxEnd
);
209 this.logPrefix(connectorId
) +
210 ' stop transaction ' +
211 this.chargingStation
.getConnectorStatus(connectorId
).transactionId
.toString()
213 await this.stopTransaction(connectorId
);
216 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
++;
217 this.connectorsStatus
.get(connectorId
).skippedTransactions
++;
219 this.logPrefix(connectorId
) +
220 ' skipped consecutively ' +
221 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
.toString() +
223 this.connectorsStatus
.get(connectorId
).skippedTransactions
.toString() +
227 this.connectorsStatus
.get(connectorId
).lastRunDate
= new Date();
229 // await this.stopTransaction(connectorId);
230 this.connectorsStatus
.get(connectorId
).stoppedDate
= new Date();
232 this.logPrefix(connectorId
) +
233 ' stopped on connector and lasted for ' +
234 Utils
.formatDurationMilliSeconds(
235 this.connectorsStatus
.get(connectorId
).stoppedDate
.getTime() -
236 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
240 `${this.logPrefix(connectorId)} connector status: %j`,
241 this.connectorsStatus
.get(connectorId
)
245 private initializeConnectorStatus(connectorId
: number): void {
246 this.connectorsStatus
.get(connectorId
).authorizeRequests
=
247 this?.connectorsStatus
.get(connectorId
)?.authorizeRequests
?? 0;
248 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
=
249 this?.connectorsStatus
.get(connectorId
)?.acceptedAuthorizeRequests
?? 0;
250 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
=
251 this?.connectorsStatus
.get(connectorId
)?.rejectedAuthorizeRequests
?? 0;
252 this.connectorsStatus
.get(connectorId
).startTransactionRequests
=
253 this?.connectorsStatus
.get(connectorId
)?.startTransactionRequests
?? 0;
254 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
=
255 this?.connectorsStatus
.get(connectorId
)?.acceptedStartTransactionRequests
?? 0;
256 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
=
257 this?.connectorsStatus
.get(connectorId
)?.rejectedStartTransactionRequests
?? 0;
258 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
=
259 this?.connectorsStatus
.get(connectorId
)?.stopTransactionRequests
?? 0;
260 this.connectorsStatus
.get(connectorId
).acceptedStopTransactionRequests
=
261 this?.connectorsStatus
.get(connectorId
)?.acceptedStopTransactionRequests
?? 0;
262 this.connectorsStatus
.get(connectorId
).rejectedStopTransactionRequests
=
263 this?.connectorsStatus
.get(connectorId
)?.rejectedStopTransactionRequests
?? 0;
264 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
265 this.connectorsStatus
.get(connectorId
).skippedTransactions
=
266 this?.connectorsStatus
.get(connectorId
)?.skippedTransactions
?? 0;
267 const previousRunDuration
=
268 this?.connectorsStatus
.get(connectorId
)?.startDate
&&
269 this?.connectorsStatus
.get(connectorId
)?.lastRunDate
270 ? this.connectorsStatus
.get(connectorId
).lastRunDate
.getTime() -
271 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
273 this.connectorsStatus
.get(connectorId
).startDate
= new Date();
274 this.connectorsStatus
.get(connectorId
).stopDate
= new Date(
275 this.connectorsStatus
.get(connectorId
).startDate
.getTime() +
276 (this.configuration
.stopAfterHours
??
277 Constants
.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS
) *
282 this.connectorsStatus
.get(connectorId
).start
= true;
285 private async startTransaction(
287 ): Promise
<StartTransactionResponse
| AuthorizeResponse
> {
288 const measureId
= 'StartTransaction with ATG';
289 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
290 let startResponse
: StartTransactionResponse
;
291 if (this.chargingStation
.hasAuthorizedTags()) {
292 const idTag
= this.chargingStation
.getRandomIdTag();
293 const startTransactionLogMsg
= `${this.logPrefix(
295 )} start transaction for idTag '${idTag}'`;
296 if (this.getRequireAuthorize()) {
297 this.chargingStation
.getConnectorStatus(connectorId
).authorizeIdTag
= idTag
;
299 const authorizeResponse
: AuthorizeResponse
=
300 await this.chargingStation
.ocppRequestService
.requestHandler
<
303 >(this.chargingStation
, RequestCommand
.AUTHORIZE
, {
306 this.connectorsStatus
.get(connectorId
).authorizeRequests
++;
307 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
308 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
++;
309 logger
.info(startTransactionLogMsg
);
311 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
312 StartTransactionRequest
,
313 StartTransactionResponse
314 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
318 PerformanceStatistics
.endMeasure(measureId
, beginId
);
319 return startResponse
;
321 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
++;
322 PerformanceStatistics
.endMeasure(measureId
, beginId
);
323 return authorizeResponse
;
325 logger
.info(startTransactionLogMsg
);
327 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
328 StartTransactionRequest
,
329 StartTransactionResponse
330 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
334 PerformanceStatistics
.endMeasure(measureId
, beginId
);
335 return startResponse
;
337 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
338 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
339 StartTransactionRequest
,
340 StartTransactionResponse
341 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
342 PerformanceStatistics
.endMeasure(measureId
, beginId
);
343 return startResponse
;
346 private async stopTransaction(
348 reason
: StopTransactionReason
= StopTransactionReason
.LOCAL
349 ): Promise
<StopTransactionResponse
> {
350 const measureId
= 'StopTransaction with ATG';
351 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
352 let stopResponse
: StopTransactionResponse
;
353 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
354 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
355 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
++;
356 if (stopResponse
.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
357 this.connectorsStatus
.get(connectorId
).acceptedStopTransactionRequests
++;
359 this.connectorsStatus
.get(connectorId
).rejectedStopTransactionRequests
++;
362 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
).transactionId
;
364 `${this.logPrefix(connectorId)} trying to stop a not started transaction${
365 transactionId ? ' ' + transactionId.toString() : ''
369 PerformanceStatistics
.endMeasure(measureId
, beginId
);
373 private getRequireAuthorize(): boolean {
374 return this.configuration
?.requireAuthorize
?? true;
377 private logPrefix(connectorId
?: number): string {
378 return Utils
.logPrefix(
379 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
380 connectorId !== undefined ? ` on connector #${connectorId.toString()}
` : ''