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 this.connectorsStatus
.get(connectorId
).stoppedDate
= new Date();
231 this.logPrefix(connectorId
) +
232 ' stopped on connector and lasted for ' +
233 Utils
.formatDurationMilliSeconds(
234 this.connectorsStatus
.get(connectorId
).stoppedDate
.getTime() -
235 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
239 `${this.logPrefix(connectorId)} connector status: %j`,
240 this.connectorsStatus
.get(connectorId
)
244 private initializeConnectorStatus(connectorId
: number): void {
245 this.connectorsStatus
.get(connectorId
).authorizeRequests
=
246 this?.connectorsStatus
.get(connectorId
)?.authorizeRequests
?? 0;
247 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
=
248 this?.connectorsStatus
.get(connectorId
)?.acceptedAuthorizeRequests
?? 0;
249 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
=
250 this?.connectorsStatus
.get(connectorId
)?.rejectedAuthorizeRequests
?? 0;
251 this.connectorsStatus
.get(connectorId
).startTransactionRequests
=
252 this?.connectorsStatus
.get(connectorId
)?.startTransactionRequests
?? 0;
253 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
=
254 this?.connectorsStatus
.get(connectorId
)?.acceptedStartTransactionRequests
?? 0;
255 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
=
256 this?.connectorsStatus
.get(connectorId
)?.rejectedStartTransactionRequests
?? 0;
257 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
=
258 this?.connectorsStatus
.get(connectorId
)?.stopTransactionRequests
?? 0;
259 this.connectorsStatus
.get(connectorId
).acceptedStopTransactionRequests
=
260 this?.connectorsStatus
.get(connectorId
)?.acceptedStopTransactionRequests
?? 0;
261 this.connectorsStatus
.get(connectorId
).rejectedStopTransactionRequests
=
262 this?.connectorsStatus
.get(connectorId
)?.rejectedStopTransactionRequests
?? 0;
263 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
264 this.connectorsStatus
.get(connectorId
).skippedTransactions
=
265 this?.connectorsStatus
.get(connectorId
)?.skippedTransactions
?? 0;
266 const previousRunDuration
=
267 this?.connectorsStatus
.get(connectorId
)?.startDate
&&
268 this?.connectorsStatus
.get(connectorId
)?.lastRunDate
269 ? this.connectorsStatus
.get(connectorId
).lastRunDate
.getTime() -
270 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
272 this.connectorsStatus
.get(connectorId
).startDate
= new Date();
273 this.connectorsStatus
.get(connectorId
).stopDate
= new Date(
274 this.connectorsStatus
.get(connectorId
).startDate
.getTime() +
275 (this.configuration
.stopAfterHours
??
276 Constants
.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS
) *
281 this.connectorsStatus
.get(connectorId
).start
= true;
284 private async startTransaction(
286 ): Promise
<StartTransactionResponse
| AuthorizeResponse
> {
287 const measureId
= 'StartTransaction with ATG';
288 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
289 let startResponse
: StartTransactionResponse
;
290 if (this.chargingStation
.hasAuthorizedTags()) {
291 const idTag
= this.chargingStation
.getRandomIdTag();
292 const startTransactionLogMsg
= `${this.logPrefix(
294 )} start transaction for idTag '${idTag}'`;
295 if (this.getRequireAuthorize()) {
296 this.chargingStation
.getConnectorStatus(connectorId
).authorizeIdTag
= idTag
;
298 const authorizeResponse
: AuthorizeResponse
=
299 await this.chargingStation
.ocppRequestService
.requestHandler
<
302 >(this.chargingStation
, RequestCommand
.AUTHORIZE
, {
305 this.connectorsStatus
.get(connectorId
).authorizeRequests
++;
306 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
307 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
++;
308 logger
.info(startTransactionLogMsg
);
310 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
311 StartTransactionRequest
,
312 StartTransactionResponse
313 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
317 PerformanceStatistics
.endMeasure(measureId
, beginId
);
318 return startResponse
;
320 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
++;
321 PerformanceStatistics
.endMeasure(measureId
, beginId
);
322 return authorizeResponse
;
324 logger
.info(startTransactionLogMsg
);
326 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
327 StartTransactionRequest
,
328 StartTransactionResponse
329 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
333 PerformanceStatistics
.endMeasure(measureId
, beginId
);
334 return startResponse
;
336 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
337 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
338 StartTransactionRequest
,
339 StartTransactionResponse
340 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
341 PerformanceStatistics
.endMeasure(measureId
, beginId
);
342 return startResponse
;
345 private async stopTransaction(
347 reason
: StopTransactionReason
= StopTransactionReason
.LOCAL
348 ): Promise
<StopTransactionResponse
> {
349 const measureId
= 'StopTransaction with ATG';
350 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
351 let stopResponse
: StopTransactionResponse
;
352 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
353 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
354 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
++;
355 if (stopResponse
.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
356 this.connectorsStatus
.get(connectorId
).acceptedStopTransactionRequests
++;
358 this.connectorsStatus
.get(connectorId
).rejectedStopTransactionRequests
++;
361 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
).transactionId
;
363 `${this.logPrefix(connectorId)} trying to stop a not started transaction${
364 transactionId ? ' ' + transactionId.toString() : ''
368 PerformanceStatistics
.endMeasure(measureId
, beginId
);
372 private getRequireAuthorize(): boolean {
373 return this.configuration
?.requireAuthorize
?? true;
376 private logPrefix(connectorId
?: number): string {
377 return Utils
.logPrefix(
378 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
379 connectorId !== undefined ? ` on connector #${connectorId.toString()}
` : ''