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 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
190 // Wait until end of transaction
192 Utils
.getRandomInteger(this.configuration
.maxDuration
, this.configuration
.minDuration
) *
195 this.logPrefix(connectorId
) +
197 this.chargingStation
.getConnectorStatus(connectorId
).transactionId
.toString() +
198 ' started and will stop in ' +
199 Utils
.formatDurationMilliSeconds(waitTrxEnd
)
201 await Utils
.sleep(waitTrxEnd
);
204 this.logPrefix(connectorId
) +
205 ' stop transaction ' +
206 this.chargingStation
.getConnectorStatus(connectorId
).transactionId
.toString()
208 await this.stopTransaction(connectorId
);
211 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
++;
212 this.connectorsStatus
.get(connectorId
).skippedTransactions
++;
214 this.logPrefix(connectorId
) +
215 ' skipped consecutively ' +
216 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
.toString() +
218 this.connectorsStatus
.get(connectorId
).skippedTransactions
.toString() +
222 this.connectorsStatus
.get(connectorId
).lastRunDate
= new Date();
224 this.connectorsStatus
.get(connectorId
).stoppedDate
= new Date();
226 this.logPrefix(connectorId
) +
227 ' stopped on connector and lasted for ' +
228 Utils
.formatDurationMilliSeconds(
229 this.connectorsStatus
.get(connectorId
).stoppedDate
.getTime() -
230 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
234 `${this.logPrefix(connectorId)} connector status: %j`,
235 this.connectorsStatus
.get(connectorId
)
239 private initializeConnectorStatus(connectorId
: number): void {
240 this.connectorsStatus
.get(connectorId
).authorizeRequests
=
241 this?.connectorsStatus
.get(connectorId
)?.authorizeRequests
?? 0;
242 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
=
243 this?.connectorsStatus
.get(connectorId
)?.acceptedAuthorizeRequests
?? 0;
244 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
=
245 this?.connectorsStatus
.get(connectorId
)?.rejectedAuthorizeRequests
?? 0;
246 this.connectorsStatus
.get(connectorId
).startTransactionRequests
=
247 this?.connectorsStatus
.get(connectorId
)?.startTransactionRequests
?? 0;
248 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
=
249 this?.connectorsStatus
.get(connectorId
)?.acceptedStartTransactionRequests
?? 0;
250 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
=
251 this?.connectorsStatus
.get(connectorId
)?.rejectedStartTransactionRequests
?? 0;
252 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
=
253 this?.connectorsStatus
.get(connectorId
)?.stopTransactionRequests
?? 0;
254 this.connectorsStatus
.get(connectorId
).acceptedStopTransactionRequests
=
255 this?.connectorsStatus
.get(connectorId
)?.acceptedStopTransactionRequests
?? 0;
256 this.connectorsStatus
.get(connectorId
).rejectedStopTransactionRequests
=
257 this?.connectorsStatus
.get(connectorId
)?.rejectedStopTransactionRequests
?? 0;
258 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
259 this.connectorsStatus
.get(connectorId
).skippedTransactions
=
260 this?.connectorsStatus
.get(connectorId
)?.skippedTransactions
?? 0;
261 const previousRunDuration
=
262 this?.connectorsStatus
.get(connectorId
)?.startDate
&&
263 this?.connectorsStatus
.get(connectorId
)?.lastRunDate
264 ? this.connectorsStatus
.get(connectorId
).lastRunDate
.getTime() -
265 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
267 this.connectorsStatus
.get(connectorId
).startDate
= new Date();
268 this.connectorsStatus
.get(connectorId
).stopDate
= new Date(
269 this.connectorsStatus
.get(connectorId
).startDate
.getTime() +
270 (this.configuration
.stopAfterHours
??
271 Constants
.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS
) *
276 this.connectorsStatus
.get(connectorId
).start
= true;
279 private async startTransaction(
281 ): Promise
<StartTransactionResponse
| undefined> {
282 const measureId
= 'StartTransaction with ATG';
283 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
284 let startResponse
: StartTransactionResponse
;
285 if (this.chargingStation
.hasAuthorizedTags()) {
286 const idTag
= this.chargingStation
.getRandomIdTag();
287 const startTransactionLogMsg
= `${this.logPrefix(
289 )} start transaction for idTag '${idTag}'`;
290 if (this.getRequireAuthorize()) {
291 this.chargingStation
.getConnectorStatus(connectorId
).authorizeIdTag
= idTag
;
293 const authorizeResponse
: AuthorizeResponse
=
294 await this.chargingStation
.ocppRequestService
.requestHandler
<
297 >(this.chargingStation
, RequestCommand
.AUTHORIZE
, {
300 this.connectorsStatus
.get(connectorId
).authorizeRequests
++;
301 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
302 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
++;
303 logger
.info(startTransactionLogMsg
);
305 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
306 StartTransactionRequest
,
307 StartTransactionResponse
308 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
312 this.connectorsStatus
.get(connectorId
).startTransactionRequests
++;
313 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
314 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
++;
316 logger
.warn(this.logPrefix(connectorId
) + ' start transaction rejected');
317 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
++;
319 PerformanceStatistics
.endMeasure(measureId
, beginId
);
320 return startResponse
;
322 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
++;
323 PerformanceStatistics
.endMeasure(measureId
, beginId
);
324 return startResponse
;
326 logger
.info(startTransactionLogMsg
);
328 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
329 StartTransactionRequest
,
330 StartTransactionResponse
331 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
335 PerformanceStatistics
.endMeasure(measureId
, beginId
);
336 return startResponse
;
338 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
339 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
340 StartTransactionRequest
,
341 StartTransactionResponse
342 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
343 PerformanceStatistics
.endMeasure(measureId
, beginId
);
344 return startResponse
;
347 private async stopTransaction(
349 reason
: StopTransactionReason
= StopTransactionReason
.LOCAL
350 ): Promise
<StopTransactionResponse
> {
351 const measureId
= 'StopTransaction with ATG';
352 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
353 let stopResponse
: StopTransactionResponse
;
354 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
355 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
356 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
++;
357 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
358 this.connectorsStatus
.get(connectorId
).acceptedStopTransactionRequests
++;
360 this.connectorsStatus
.get(connectorId
).rejectedStopTransactionRequests
++;
363 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
).transactionId
;
365 `${this.logPrefix(connectorId)} trying to stop a not started transaction${
366 transactionId ? ' ' + transactionId.toString() : ''
370 PerformanceStatistics
.endMeasure(measureId
, beginId
);
374 private getRequireAuthorize(): boolean {
375 return this.configuration
?.requireAuthorize
?? true;
378 private logPrefix(connectorId
?: number): string {
379 return Utils
.logPrefix(
380 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
381 connectorId !== undefined ? ` on connector #${connectorId.toString()}
` : ''