Fix ATG run duration computation
[e-mobility-charging-stations-simulator.git] / src / charging-station / AutomaticTransactionGenerator.ts
CommitLineData
c8eeb62b
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
c0560973 3import { AuthorizationStatus, AuthorizeResponse, StartTransactionResponse, StopTransactionReason, StopTransactionResponse } from '../types/ocpp/Transaction';
6af9012e
JB
4
5import ChargingStation from './ChargingStation';
6import Constants from '../utils/Constants';
a6b3c6c3 7import PerformanceStatistics from '../performance/PerformanceStatistics';
6af9012e
JB
8import Utils from '../utils/Utils';
9import logger from '../utils/Logger';
10
11export default class AutomaticTransactionGenerator {
265e4266 12 public started: boolean;
7d75bee1 13 private startDate!: Date;
265e4266 14 private lastRunDate!: Date;
7d75bee1 15 private stopDate!: Date;
ad2f27c3 16 private chargingStation: ChargingStation;
6af9012e
JB
17
18 constructor(chargingStation: ChargingStation) {
ad2f27c3 19 this.chargingStation = chargingStation;
265e4266 20 this.started = false;
6af9012e
JB
21 }
22
7d75bee1 23 public start(): void {
0045cef5 24 const previousRunDuration = (this?.startDate && this?.lastRunDate) ? (this.lastRunDate.getTime() - this.startDate.getTime()) : 0;
7d75bee1 25 this.startDate = new Date();
0045cef5 26 this.lastRunDate = this.startDate;
58fad749
JB
27 this.stopDate = new Date(this.startDate.getTime()
28 + (this.chargingStation.stationInfo?.AutomaticTransactionGenerator?.stopAfterHours ?? Constants.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS) * 3600 * 1000
0045cef5 29 - previousRunDuration);
265e4266 30 this.started = true;
ad2f27c3 31 for (const connector in this.chargingStation.connectors) {
6af9012e 32 if (Utils.convertToInt(connector) > 0) {
7d75bee1
JB
33 // Avoid hogging the event loop with a busy loop
34 setImmediate(() => {
35 this.startOnConnector(Utils.convertToInt(connector)).catch(() => { /* This is intentional */ });
36 });
6af9012e
JB
37 }
38 }
d7d1db72 39 logger.info(this.logPrefix() + ' started and will run for ' + Utils.formatDurationMilliSeconds(this.stopDate.getTime() - this.startDate.getTime()));
6af9012e
JB
40 }
41
0045cef5 42 public stop(): void {
265e4266
JB
43 if (!this.started) {
44 logger.error(`${this.logPrefix()} trying to stop while not started`);
45 return;
46 }
265e4266 47 this.started = false;
0045cef5 48 logger.info(`${this.logPrefix()} over and lasted for ${Utils.formatDurationMilliSeconds(this.lastRunDate.getTime() - this.startDate.getTime())}. Stopping all transactions`);
6af9012e
JB
49 }
50
7d75bee1
JB
51 private async startOnConnector(connectorId: number): Promise<void> {
52 logger.info(this.logPrefix(connectorId) + ' started on connector');
b322b8b4
JB
53 let skippedTransactions = 0;
54 let skippedTransactionsTotal = 0;
265e4266 55 while (this.started) {
7d75bee1 56 if ((new Date()) > this.stopDate) {
0045cef5 57 this.stop();
17991e8c
JB
58 break;
59 }
c0560973
JB
60 if (!this.chargingStation.isRegistered()) {
61 logger.error(this.logPrefix(connectorId) + ' Entered in transaction loop while the charging station is not registered');
17991e8c
JB
62 break;
63 }
c0560973
JB
64 if (!this.chargingStation.isChargingStationAvailable()) {
65 logger.info(this.logPrefix(connectorId) + ' Entered in transaction loop while the charging station is unavailable');
0045cef5 66 this.stop();
ab5f4b03
JB
67 break;
68 }
c0560973
JB
69 if (!this.chargingStation.isConnectorAvailable(connectorId)) {
70 logger.info(`${this.logPrefix(connectorId)} Entered in transaction loop while the connector ${connectorId} is unavailable, stop it`);
17991e8c
JB
71 break;
72 }
c0560973
JB
73 if (!this.chargingStation?.ocppRequestService) {
74 logger.info(`${this.logPrefix(connectorId)} Transaction loop waiting for charging station service to be initialized`);
75 do {
a4cc42ea 76 await Utils.sleep(Constants.CHARGING_STATION_ATG_INITIALIZATION_TIME);
c0560973
JB
77 } while (!this.chargingStation?.ocppRequestService);
78 }
ad2f27c3
JB
79 const wait = Utils.getRandomInt(this.chargingStation.stationInfo.AutomaticTransactionGenerator.maxDelayBetweenTwoTransactions,
80 this.chargingStation.stationInfo.AutomaticTransactionGenerator.minDelayBetweenTwoTransactions) * 1000;
d7d1db72 81 logger.info(this.logPrefix(connectorId) + ' waiting for ' + Utils.formatDurationMilliSeconds(wait));
6af9012e 82 await Utils.sleep(wait);
c37528f1 83 const start = Utils.secureRandom();
ad2f27c3 84 if (start < this.chargingStation.stationInfo.AutomaticTransactionGenerator.probabilityOfStart) {
b322b8b4 85 skippedTransactions = 0;
6af9012e 86 // Start transaction
aef1b33a 87 const startResponse = await this.startTransaction(connectorId);
ef6076c1 88 if (startResponse?.idTagInfo?.status !== AuthorizationStatus.ACCEPTED) {
54b1efe0 89 logger.warn(this.logPrefix(connectorId) + ' transaction rejected');
6af9012e
JB
90 await Utils.sleep(Constants.CHARGING_STATION_ATG_WAIT_TIME);
91 } else {
92 // Wait until end of transaction
ad2f27c3
JB
93 const waitTrxEnd = Utils.getRandomInt(this.chargingStation.stationInfo.AutomaticTransactionGenerator.maxDuration,
94 this.chargingStation.stationInfo.AutomaticTransactionGenerator.minDuration) * 1000;
d7d1db72 95 logger.info(this.logPrefix(connectorId) + ' transaction ' + this.chargingStation.getConnector(connectorId).transactionId.toString() + ' will stop in ' + Utils.formatDurationMilliSeconds(waitTrxEnd));
6af9012e
JB
96 await Utils.sleep(waitTrxEnd);
97 // Stop transaction
ad2f27c3 98 if (this.chargingStation.getConnector(connectorId)?.transactionStarted) {
c0560973 99 logger.info(this.logPrefix(connectorId) + ' stop transaction ' + this.chargingStation.getConnector(connectorId).transactionId.toString());
aef1b33a 100 await this.stopTransaction(connectorId);
6af9012e
JB
101 }
102 }
103 } else {
b322b8b4
JB
104 skippedTransactions++;
105 skippedTransactionsTotal++;
106 logger.info(this.logPrefix(connectorId) + ' skipped transaction ' + skippedTransactions.toString() + '/' + skippedTransactionsTotal.toString());
6af9012e 107 }
265e4266 108 this.lastRunDate = new Date();
7d75bee1 109 }
0045cef5 110 await this.stopTransaction(connectorId);
7d75bee1 111 logger.info(this.logPrefix(connectorId) + ' stopped on connector');
6af9012e
JB
112 }
113
aef1b33a
JB
114 private async startTransaction(connectorId: number): Promise<StartTransactionResponse | AuthorizeResponse> {
115 const measureId = 'StartTransaction with ATG';
116 const beginId = PerformanceStatistics.beginMeasure(measureId);
117 let startResponse: StartTransactionResponse;
118 if (this.chargingStation.hasAuthorizedTags()) {
119 const tagId = this.chargingStation.getRandomTagId();
120 if (this.chargingStation.getAutomaticTransactionGeneratorRequireAuthorize()) {
5fdab605 121 // Authorize tagId
aef1b33a 122 const authorizeResponse = await this.chargingStation.ocppRequestService.sendAuthorize(connectorId, tagId);
5fdab605 123 if (authorizeResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
aef1b33a 124 logger.info(this.logPrefix(connectorId) + ' start transaction for tagID ' + tagId);
5fdab605 125 // Start transaction
aef1b33a
JB
126 startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId, tagId);
127 PerformanceStatistics.endMeasure(measureId, beginId);
128 return startResponse;
5fdab605 129 }
aef1b33a 130 PerformanceStatistics.endMeasure(measureId, beginId);
4faad557 131 return authorizeResponse;
ef6076c1 132 }
aef1b33a 133 logger.info(this.logPrefix(connectorId) + ' start transaction for tagID ' + tagId);
5fdab605 134 // Start transaction
aef1b33a
JB
135 startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId, tagId);
136 PerformanceStatistics.endMeasure(measureId, beginId);
137 return startResponse;
6af9012e 138 }
aef1b33a
JB
139 logger.info(this.logPrefix(connectorId) + ' start transaction without a tagID');
140 startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId);
141 PerformanceStatistics.endMeasure(measureId, beginId);
142 return startResponse;
6af9012e
JB
143 }
144
0045cef5 145 private async stopTransaction(connectorId: number, reason: StopTransactionReason = StopTransactionReason.NONE): Promise<StopTransactionResponse> {
aef1b33a
JB
146 const measureId = 'StopTransaction with ATG';
147 const beginId = PerformanceStatistics.beginMeasure(measureId);
148 const transactionId = this.chargingStation.getConnector(connectorId).transactionId;
0045cef5
JB
149 let stopResponse: StopTransactionResponse;
150 if (this.chargingStation.getConnector(connectorId)?.transactionStarted) {
151 stopResponse = await this.chargingStation.ocppRequestService.sendStopTransaction(transactionId,
152 this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId),
153 this.chargingStation.getTransactionIdTag(transactionId),
154 reason);
155 } else {
156 logger.warn(`${this.logPrefix(connectorId)} trying to stop a not started transaction ${transactionId}`);
157 }
aef1b33a
JB
158 PerformanceStatistics.endMeasure(measureId, beginId);
159 return stopResponse;
c0560973
JB
160 }
161
6e0964c8 162 private logPrefix(connectorId?: number): string {
c0560973 163 if (connectorId) {
54b1efe0 164 return Utils.logPrefix(' ' + this.chargingStation.stationInfo.chargingStationId + ' | ATG on connector #' + connectorId.toString() + ':');
c0560973 165 }
54b1efe0 166 return Utils.logPrefix(' ' + this.chargingStation.stationInfo.chargingStationId + ' | ATG:');
6af9012e
JB
167 }
168}