1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import BaseError from
'../exception/BaseError';
4 import PerformanceStatistics from
'../performance/PerformanceStatistics';
6 AutomaticTransactionGeneratorConfiguration
,
8 } from
'../types/AutomaticTransactionGenerator';
9 import { RequestCommand
} from
'../types/ocpp/Requests';
12 type AuthorizeRequest
,
13 type AuthorizeResponse
,
14 type StartTransactionRequest
,
15 type StartTransactionResponse
,
16 StopTransactionReason
,
17 type StopTransactionResponse
,
18 } from
'../types/ocpp/Transaction';
19 import Constants from
'../utils/Constants';
20 import logger from
'../utils/Logger';
21 import Utils from
'../utils/Utils';
22 import type ChargingStation from
'./ChargingStation';
24 export default class AutomaticTransactionGenerator
{
25 private static readonly instances
: Map
<string, AutomaticTransactionGenerator
> = new Map
<
27 AutomaticTransactionGenerator
30 public readonly connectorsStatus
: Map
<number, Status
>;
31 public readonly configuration
: AutomaticTransactionGeneratorConfiguration
;
32 public started
: boolean;
33 private readonly chargingStation
: ChargingStation
;
36 automaticTransactionGeneratorConfiguration
: AutomaticTransactionGeneratorConfiguration
,
37 chargingStation
: ChargingStation
40 this.configuration
= automaticTransactionGeneratorConfiguration
;
41 this.chargingStation
= chargingStation
;
42 this.connectorsStatus
= new Map
<number, Status
>();
43 this.initializeConnectorsStatus();
46 public static getInstance(
47 automaticTransactionGeneratorConfiguration
: AutomaticTransactionGeneratorConfiguration
,
48 chargingStation
: ChargingStation
49 ): AutomaticTransactionGenerator
{
50 if (AutomaticTransactionGenerator
.instances
.has(chargingStation
.stationInfo
.hashId
) === false) {
51 AutomaticTransactionGenerator
.instances
.set(
52 chargingStation
.stationInfo
.hashId
,
53 new AutomaticTransactionGenerator(
54 automaticTransactionGeneratorConfiguration
,
59 return AutomaticTransactionGenerator
.instances
.get(chargingStation
.stationInfo
.hashId
);
62 public start(): void {
63 if (this.started
=== true) {
64 logger
.warn(`${this.logPrefix()} is already started`);
67 this.startConnectors();
72 if (this.started
=== false) {
73 logger
.warn(`${this.logPrefix()} is already stopped`);
76 this.stopConnectors();
80 public startConnector(connectorId
: number): void {
81 if (this.connectorsStatus
.has(connectorId
) === false) {
82 logger
.error(`${this.logPrefix(connectorId)} starting on non existing connector`);
83 throw new BaseError(`Connector ${connectorId} does not exist`);
85 if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
86 // Avoid hogging the event loop with a busy loop
88 this.internalStartConnector(connectorId
).catch(() => {
89 /* This is intentional */
92 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
93 logger
.warn(`${this.logPrefix(connectorId)} is already started on connector`);
97 public stopConnector(connectorId
: number): void {
98 if (this.connectorsStatus
.has(connectorId
) === false) {
99 logger
.error(`${this.logPrefix(connectorId)} stopping on non existing connector`);
100 throw new BaseError(`Connector ${connectorId} does not exist`);
102 if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
103 this.connectorsStatus
.get(connectorId
).start
= false;
104 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
105 logger
.warn(`${this.logPrefix(connectorId)} is already stopped on connector`);
109 private startConnectors(): void {
111 this.connectorsStatus
?.size
> 0 &&
112 this.connectorsStatus
.size
!== this.chargingStation
.getNumberOfConnectors()
114 this.connectorsStatus
.clear();
115 this.initializeConnectorsStatus();
117 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
118 if (connectorId
> 0) {
119 this.startConnector(connectorId
);
124 private stopConnectors(): void {
125 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
126 if (connectorId
> 0) {
127 this.stopConnector(connectorId
);
132 private async internalStartConnector(connectorId
: number): Promise
<void> {
133 this.initializeConnectorStatus(connectorId
);
134 this.connectorsStatus
.get(connectorId
).start
= true;
136 this.logPrefix(connectorId
) +
137 ' started on connector and will run for ' +
138 Utils
.formatDurationMilliSeconds(
139 this.connectorsStatus
.get(connectorId
).stopDate
.getTime() -
140 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
143 while (this.connectorsStatus
.get(connectorId
).start
=== true) {
144 if (new Date() > this.connectorsStatus
.get(connectorId
).stopDate
) {
145 this.stopConnector(connectorId
);
148 if (!this.chargingStation
.isInAcceptedState()) {
150 this.logPrefix(connectorId
) +
151 ' entered in transaction loop while the charging station is not in accepted state'
153 this.stopConnector(connectorId
);
156 if (!this.chargingStation
.isChargingStationAvailable()) {
158 this.logPrefix(connectorId
) +
159 ' entered in transaction loop while the charging station is unavailable'
161 this.stopConnector(connectorId
);
164 if (!this.chargingStation
.isConnectorAvailable(connectorId
)) {
168 )} entered in transaction loop while the connector ${connectorId} is unavailable`
170 this.stopConnector(connectorId
);
173 if (!this.chargingStation
?.ocppRequestService
) {
177 )} transaction loop waiting for charging station service to be initialized`
180 await Utils
.sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
181 } while (!this.chargingStation
?.ocppRequestService
);
184 Utils
.getRandomInteger(
185 this.configuration
.maxDelayBetweenTwoTransactions
,
186 this.configuration
.minDelayBetweenTwoTransactions
189 this.logPrefix(connectorId
) + ' waiting for ' + Utils
.formatDurationMilliSeconds(wait
)
191 await Utils
.sleep(wait
);
192 const start
= Utils
.secureRandom();
193 if (start
< this.configuration
.probabilityOfStart
) {
194 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
196 const startResponse
= await this.startTransaction(connectorId
);
197 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
198 // Wait until end of transaction
200 Utils
.getRandomInteger(this.configuration
.maxDuration
, this.configuration
.minDuration
) *
203 this.logPrefix(connectorId
) +
205 this.chargingStation
.getConnectorStatus(connectorId
).transactionId
.toString() +
206 ' started and will stop in ' +
207 Utils
.formatDurationMilliSeconds(waitTrxEnd
)
209 await Utils
.sleep(waitTrxEnd
);
212 this.logPrefix(connectorId
) +
213 ' stop transaction ' +
214 this.chargingStation
.getConnectorStatus(connectorId
).transactionId
.toString()
216 await this.stopTransaction(connectorId
);
219 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
++;
220 this.connectorsStatus
.get(connectorId
).skippedTransactions
++;
222 this.logPrefix(connectorId
) +
223 ' skipped consecutively ' +
224 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
.toString() +
226 this.connectorsStatus
.get(connectorId
).skippedTransactions
.toString() +
230 this.connectorsStatus
.get(connectorId
).lastRunDate
= new Date();
232 this.connectorsStatus
.get(connectorId
).stoppedDate
= new Date();
234 this.logPrefix(connectorId
) +
235 ' stopped on connector and lasted for ' +
236 Utils
.formatDurationMilliSeconds(
237 this.connectorsStatus
.get(connectorId
).stoppedDate
.getTime() -
238 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
242 `${this.logPrefix(connectorId)} connector status: %j`,
243 this.connectorsStatus
.get(connectorId
)
247 private initializeConnectorStatus(connectorId
: number): void {
248 this.connectorsStatus
.get(connectorId
).authorizeRequests
=
249 this?.connectorsStatus
.get(connectorId
)?.authorizeRequests
?? 0;
250 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
=
251 this?.connectorsStatus
.get(connectorId
)?.acceptedAuthorizeRequests
?? 0;
252 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
=
253 this?.connectorsStatus
.get(connectorId
)?.rejectedAuthorizeRequests
?? 0;
254 this.connectorsStatus
.get(connectorId
).startTransactionRequests
=
255 this?.connectorsStatus
.get(connectorId
)?.startTransactionRequests
?? 0;
256 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
=
257 this?.connectorsStatus
.get(connectorId
)?.acceptedStartTransactionRequests
?? 0;
258 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
=
259 this?.connectorsStatus
.get(connectorId
)?.rejectedStartTransactionRequests
?? 0;
260 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
=
261 this?.connectorsStatus
.get(connectorId
)?.stopTransactionRequests
?? 0;
262 this.connectorsStatus
.get(connectorId
).acceptedStopTransactionRequests
=
263 this?.connectorsStatus
.get(connectorId
)?.acceptedStopTransactionRequests
?? 0;
264 this.connectorsStatus
.get(connectorId
).rejectedStopTransactionRequests
=
265 this?.connectorsStatus
.get(connectorId
)?.rejectedStopTransactionRequests
?? 0;
266 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
267 this.connectorsStatus
.get(connectorId
).skippedTransactions
=
268 this?.connectorsStatus
.get(connectorId
)?.skippedTransactions
?? 0;
269 const previousRunDuration
=
270 this?.connectorsStatus
.get(connectorId
)?.startDate
&&
271 this?.connectorsStatus
.get(connectorId
)?.lastRunDate
272 ? this.connectorsStatus
.get(connectorId
).lastRunDate
.getTime() -
273 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
275 this.connectorsStatus
.get(connectorId
).startDate
= new Date();
276 this.connectorsStatus
.get(connectorId
).stopDate
= new Date(
277 this.connectorsStatus
.get(connectorId
).startDate
.getTime() +
278 (this.configuration
.stopAfterHours
??
279 Constants
.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS
) *
284 this.connectorsStatus
.get(connectorId
).start
=
285 this?.connectorsStatus
.get(connectorId
)?.start
?? false;
288 private initializeConnectorsStatus(): void {
289 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
290 if (connectorId
> 0) {
291 this.connectorsStatus
.set(connectorId
, {
293 authorizeRequests
: 0,
294 acceptedAuthorizeRequests
: 0,
295 rejectedAuthorizeRequests
: 0,
296 startTransactionRequests
: 0,
297 acceptedStartTransactionRequests
: 0,
298 rejectedStartTransactionRequests
: 0,
299 stopTransactionRequests
: 0,
300 acceptedStopTransactionRequests
: 0,
301 rejectedStopTransactionRequests
: 0,
302 skippedConsecutiveTransactions
: 0,
303 skippedTransactions
: 0,
309 private async startTransaction(
311 ): Promise
<StartTransactionResponse
| undefined> {
312 const measureId
= 'StartTransaction with ATG';
313 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
314 let startResponse
: StartTransactionResponse
;
315 if (this.chargingStation
.hasAuthorizedTags()) {
316 const idTag
= this.chargingStation
.getRandomIdTag();
317 const startTransactionLogMsg
= `${this.logPrefix(
319 )} start transaction with an idTag '${idTag}'`;
320 if (this.getRequireAuthorize()) {
321 this.chargingStation
.getConnectorStatus(connectorId
).authorizeIdTag
= idTag
;
323 const authorizeResponse
: AuthorizeResponse
=
324 await this.chargingStation
.ocppRequestService
.requestHandler
<
327 >(this.chargingStation
, RequestCommand
.AUTHORIZE
, {
330 this.connectorsStatus
.get(connectorId
).authorizeRequests
++;
331 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
332 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
++;
333 logger
.info(startTransactionLogMsg
);
335 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
336 StartTransactionRequest
,
337 StartTransactionResponse
338 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
342 this.handleStartTransactionResponse(connectorId
, startResponse
);
343 PerformanceStatistics
.endMeasure(measureId
, beginId
);
344 return startResponse
;
346 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
++;
347 PerformanceStatistics
.endMeasure(measureId
, beginId
);
348 return startResponse
;
350 logger
.info(startTransactionLogMsg
);
352 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
353 StartTransactionRequest
,
354 StartTransactionResponse
355 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
359 this.handleStartTransactionResponse(connectorId
, startResponse
);
360 PerformanceStatistics
.endMeasure(measureId
, beginId
);
361 return startResponse
;
363 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
364 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
365 StartTransactionRequest
,
366 StartTransactionResponse
367 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
368 this.handleStartTransactionResponse(connectorId
, startResponse
);
369 PerformanceStatistics
.endMeasure(measureId
, beginId
);
370 return startResponse
;
373 private async stopTransaction(
375 reason
: StopTransactionReason
= StopTransactionReason
.LOCAL
376 ): Promise
<StopTransactionResponse
> {
377 const measureId
= 'StopTransaction with ATG';
378 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
379 let stopResponse
: StopTransactionResponse
;
380 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
381 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
382 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
++;
383 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
384 this.connectorsStatus
.get(connectorId
).acceptedStopTransactionRequests
++;
386 this.connectorsStatus
.get(connectorId
).rejectedStopTransactionRequests
++;
389 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
).transactionId
;
391 `${this.logPrefix(connectorId)} stopping a not started transaction${
392 transactionId ? ' ' + transactionId.toString() : ''
396 PerformanceStatistics
.endMeasure(measureId
, beginId
);
400 private getRequireAuthorize(): boolean {
401 return this.configuration
?.requireAuthorize
?? true;
404 private logPrefix(connectorId
?: number): string {
405 return Utils
.logPrefix(
406 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
407 connectorId !== undefined ? ` on connector #${connectorId.toString()}
` : ''
412 private handleStartTransactionResponse(
414 startResponse
: StartTransactionResponse
416 this.connectorsStatus
.get(connectorId
).startTransactionRequests
++;
417 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
418 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
++;
420 logger
.warn(this.logPrefix(connectorId
) + ' start transaction rejected');
421 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
++;