Fix request and response handling in all registration state
[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';
9664ec50 8import { Status } from '../types/AutomaticTransactionGenerator';
6af9012e
JB
9import Utils from '../utils/Utils';
10import logger from '../utils/Logger';
11
12export default class AutomaticTransactionGenerator {
265e4266 13 public started: boolean;
9e23580d
JB
14 private readonly chargingStation: ChargingStation;
15 private readonly connectorsStatus: Map<number, Status>;
6af9012e
JB
16
17 constructor(chargingStation: ChargingStation) {
ad2f27c3 18 this.chargingStation = chargingStation;
9664ec50 19 this.connectorsStatus = new Map<number, Status>();
72740232 20 this.stopConnectors();
265e4266 21 this.started = false;
6af9012e
JB
22 }
23
7d75bee1 24 public start(): void {
b809adf1
JB
25 if (this.started) {
26 logger.error(`${this.logPrefix()} trying to start while already started`);
27 return;
28 }
72740232 29 this.startConnectors();
265e4266 30 this.started = true;
6af9012e
JB
31 }
32
0045cef5 33 public stop(): void {
265e4266
JB
34 if (!this.started) {
35 logger.error(`${this.logPrefix()} trying to stop while not started`);
36 return;
37 }
72740232 38 this.stopConnectors();
265e4266 39 this.started = false;
6af9012e
JB
40 }
41
72740232 42 private startConnectors(): void {
8e242273 43 if (this.connectorsStatus?.size > 0 && this.connectorsStatus.size !== this.chargingStation.getNumberOfConnectors()) {
54544ef1
JB
44 this.connectorsStatus.clear();
45 }
734d790d 46 for (const connectorId of this.chargingStation.connectors.keys()) {
72740232 47 if (connectorId > 0) {
83a3286a 48 this.startConnector(connectorId);
72740232
JB
49 }
50 }
51 }
52
53 private stopConnectors(): void {
734d790d 54 for (const connectorId of this.chargingStation.connectors.keys()) {
72740232
JB
55 if (connectorId > 0) {
56 this.stopConnector(connectorId);
57 }
58 }
59 }
60
83a3286a 61 private async internalStartConnector(connectorId: number): Promise<void> {
9664ec50
JB
62 this.initStartConnectorStatus(connectorId);
63 logger.info(this.logPrefix(connectorId) + ' started on connector and will run for ' + Utils.formatDurationMilliSeconds(this.connectorsStatus.get(connectorId).stopDate.getTime() - this.connectorsStatus.get(connectorId).startDate.getTime()));
64 while (this.connectorsStatus.get(connectorId).start) {
65 if ((new Date()) > this.connectorsStatus.get(connectorId).stopDate) {
66 this.stopConnector(connectorId);
17991e8c
JB
67 break;
68 }
16cd35ad 69 if (!this.chargingStation.isInAcceptedState()) {
caad9d6b 70 logger.error(this.logPrefix(connectorId) + ' entered in transaction loop while the charging station is not in accepted state');
9664ec50 71 this.stopConnector(connectorId);
17991e8c
JB
72 break;
73 }
c0560973 74 if (!this.chargingStation.isChargingStationAvailable()) {
9664ec50
JB
75 logger.info(this.logPrefix(connectorId) + ' entered in transaction loop while the charging station is unavailable');
76 this.stopConnector(connectorId);
ab5f4b03
JB
77 break;
78 }
c0560973 79 if (!this.chargingStation.isConnectorAvailable(connectorId)) {
9664ec50 80 logger.info(`${this.logPrefix(connectorId)} entered in transaction loop while the connector ${connectorId} is unavailable`);
9c7195b2 81 this.stopConnector(connectorId);
17991e8c
JB
82 break;
83 }
c0560973 84 if (!this.chargingStation?.ocppRequestService) {
9664ec50 85 logger.info(`${this.logPrefix(connectorId)} transaction loop waiting for charging station service to be initialized`);
c0560973 86 do {
a4cc42ea 87 await Utils.sleep(Constants.CHARGING_STATION_ATG_INITIALIZATION_TIME);
c0560973
JB
88 } while (!this.chargingStation?.ocppRequestService);
89 }
72740232 90 const wait = Utils.getRandomInteger(this.chargingStation.stationInfo.AutomaticTransactionGenerator.maxDelayBetweenTwoTransactions,
ad2f27c3 91 this.chargingStation.stationInfo.AutomaticTransactionGenerator.minDelayBetweenTwoTransactions) * 1000;
d7d1db72 92 logger.info(this.logPrefix(connectorId) + ' waiting for ' + Utils.formatDurationMilliSeconds(wait));
6af9012e 93 await Utils.sleep(wait);
c37528f1 94 const start = Utils.secureRandom();
ad2f27c3 95 if (start < this.chargingStation.stationInfo.AutomaticTransactionGenerator.probabilityOfStart) {
9664ec50 96 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0;
6af9012e 97 // Start transaction
aef1b33a 98 const startResponse = await this.startTransaction(connectorId);
071a9315 99 this.connectorsStatus.get(connectorId).startTransactionRequests++;
ef6076c1 100 if (startResponse?.idTagInfo?.status !== AuthorizationStatus.ACCEPTED) {
9664ec50 101 logger.warn(this.logPrefix(connectorId) + ' start transaction rejected');
071a9315 102 this.connectorsStatus.get(connectorId).rejectedStartTransactionRequests++;
6af9012e
JB
103 } else {
104 // Wait until end of transaction
72740232 105 const waitTrxEnd = Utils.getRandomInteger(this.chargingStation.stationInfo.AutomaticTransactionGenerator.maxDuration,
ad2f27c3 106 this.chargingStation.stationInfo.AutomaticTransactionGenerator.minDuration) * 1000;
734d790d 107 logger.info(this.logPrefix(connectorId) + ' transaction ' + this.chargingStation.getConnectorStatus(connectorId).transactionId.toString() + ' started and will stop in ' + Utils.formatDurationMilliSeconds(waitTrxEnd));
071a9315 108 this.connectorsStatus.get(connectorId).acceptedStartTransactionRequests++;
6af9012e
JB
109 await Utils.sleep(waitTrxEnd);
110 // Stop transaction
734d790d 111 logger.info(this.logPrefix(connectorId) + ' stop transaction ' + this.chargingStation.getConnectorStatus(connectorId).transactionId.toString());
85d20667 112 await this.stopTransaction(connectorId);
6af9012e
JB
113 }
114 } else {
9664ec50
JB
115 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions++;
116 this.connectorsStatus.get(connectorId).skippedTransactions++;
117 logger.info(this.logPrefix(connectorId) + ' skipped consecutively ' + this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions.toString() + '/' + this.connectorsStatus.get(connectorId).skippedTransactions.toString() + ' transaction(s)');
6af9012e 118 }
9664ec50 119 this.connectorsStatus.get(connectorId).lastRunDate = new Date();
7d75bee1 120 }
0045cef5 121 await this.stopTransaction(connectorId);
9664ec50
JB
122 this.connectorsStatus.get(connectorId).stoppedDate = new Date();
123 logger.info(this.logPrefix(connectorId) + ' stopped on connector and lasted for ' + Utils.formatDurationMilliSeconds(this.connectorsStatus.get(connectorId).stoppedDate.getTime() - this.connectorsStatus.get(connectorId).startDate.getTime()));
124 logger.debug(`${this.logPrefix(connectorId)} connector status %j`, this.connectorsStatus.get(connectorId));
6af9012e
JB
125 }
126
83a3286a
JB
127 private startConnector(connectorId: number): void {
128 // Avoid hogging the event loop with a busy loop
129 setImmediate(() => {
130 this.internalStartConnector(connectorId).catch(() => { /* This is intentional */ });
131 });
132 }
133
72740232 134 private stopConnector(connectorId: number): void {
b2bece24 135 this.connectorsStatus.set(connectorId, { ...this.connectorsStatus.get(connectorId), start: false });
9664ec50
JB
136 }
137
138 private initStartConnectorStatus(connectorId: number): void {
071a9315
JB
139 this.connectorsStatus.get(connectorId).authorizeRequests = this?.connectorsStatus.get(connectorId)?.authorizeRequests ?? 0;
140 this.connectorsStatus.get(connectorId).acceptedAuthorizeRequests = this?.connectorsStatus.get(connectorId)?.acceptedAuthorizeRequests ?? 0;
141 this.connectorsStatus.get(connectorId).rejectedAuthorizeRequests = this?.connectorsStatus.get(connectorId)?.rejectedAuthorizeRequests ?? 0;
142 this.connectorsStatus.get(connectorId).startTransactionRequests = this?.connectorsStatus.get(connectorId)?.startTransactionRequests ?? 0;
143 this.connectorsStatus.get(connectorId).acceptedStartTransactionRequests = this?.connectorsStatus.get(connectorId)?.acceptedStartTransactionRequests ?? 0;
144 this.connectorsStatus.get(connectorId).rejectedStartTransactionRequests = this?.connectorsStatus.get(connectorId)?.rejectedStartTransactionRequests ?? 0;
145 this.connectorsStatus.get(connectorId).stopTransactionRequests = this?.connectorsStatus.get(connectorId)?.stopTransactionRequests ?? 0;
9664ec50 146 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0;
071a9315 147 this.connectorsStatus.get(connectorId).skippedTransactions = this?.connectorsStatus.get(connectorId)?.skippedTransactions ?? 0;
9664ec50
JB
148 const previousRunDuration = (this?.connectorsStatus.get(connectorId)?.startDate && this?.connectorsStatus.get(connectorId)?.lastRunDate)
149 ? (this.connectorsStatus.get(connectorId).lastRunDate.getTime() - this.connectorsStatus.get(connectorId).startDate.getTime())
150 : 0;
151 this.connectorsStatus.get(connectorId).startDate = new Date();
152 this.connectorsStatus.get(connectorId).stopDate = new Date(this.connectorsStatus.get(connectorId).startDate.getTime()
153 + (this.chargingStation.stationInfo?.AutomaticTransactionGenerator?.stopAfterHours ?? Constants.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS) * 3600 * 1000
154 - previousRunDuration);
155 this.connectorsStatus.get(connectorId).start = true;
72740232
JB
156 }
157
aef1b33a
JB
158 private async startTransaction(connectorId: number): Promise<StartTransactionResponse | AuthorizeResponse> {
159 const measureId = 'StartTransaction with ATG';
160 const beginId = PerformanceStatistics.beginMeasure(measureId);
161 let startResponse: StartTransactionResponse;
162 if (this.chargingStation.hasAuthorizedTags()) {
f4bf2abd 163 const idTag = this.chargingStation.getRandomIdTag();
aef1b33a 164 if (this.chargingStation.getAutomaticTransactionGeneratorRequireAuthorize()) {
f4bf2abd
JB
165 // Authorize idTag
166 const authorizeResponse = await this.chargingStation.ocppRequestService.sendAuthorize(connectorId, idTag);
071a9315 167 this.connectorsStatus.get(connectorId).authorizeRequests++;
5fdab605 168 if (authorizeResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
071a9315 169 this.connectorsStatus.get(connectorId).acceptedAuthorizeRequests++;
f4bf2abd 170 logger.info(this.logPrefix(connectorId) + ' start transaction for idTag ' + idTag);
5fdab605 171 // Start transaction
f4bf2abd 172 startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId, idTag);
aef1b33a
JB
173 PerformanceStatistics.endMeasure(measureId, beginId);
174 return startResponse;
5fdab605 175 }
071a9315 176 this.connectorsStatus.get(connectorId).rejectedAuthorizeRequests++;
aef1b33a 177 PerformanceStatistics.endMeasure(measureId, beginId);
4faad557 178 return authorizeResponse;
ef6076c1 179 }
f4bf2abd 180 logger.info(this.logPrefix(connectorId) + ' start transaction for idTag ' + idTag);
5fdab605 181 // Start transaction
f4bf2abd 182 startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId, idTag);
aef1b33a
JB
183 PerformanceStatistics.endMeasure(measureId, beginId);
184 return startResponse;
6af9012e 185 }
107efcc6 186 logger.info(this.logPrefix(connectorId) + ' start transaction without an idTag');
aef1b33a
JB
187 startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId);
188 PerformanceStatistics.endMeasure(measureId, beginId);
189 return startResponse;
6af9012e
JB
190 }
191
0045cef5 192 private async stopTransaction(connectorId: number, reason: StopTransactionReason = StopTransactionReason.NONE): Promise<StopTransactionResponse> {
aef1b33a
JB
193 const measureId = 'StopTransaction with ATG';
194 const beginId = PerformanceStatistics.beginMeasure(measureId);
8eb02b62 195 let transactionId = 0;
0045cef5 196 let stopResponse: StopTransactionResponse;
734d790d
JB
197 if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted) {
198 transactionId = this.chargingStation.getConnectorStatus(connectorId).transactionId;
0045cef5
JB
199 stopResponse = await this.chargingStation.ocppRequestService.sendStopTransaction(transactionId,
200 this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId),
201 this.chargingStation.getTransactionIdTag(transactionId),
202 reason);
071a9315 203 this.connectorsStatus.get(connectorId).stopTransactionRequests++;
0045cef5 204 } else {
8eb02b62 205 logger.warn(`${this.logPrefix(connectorId)} trying to stop a not started transaction${transactionId ? ' ' + transactionId.toString() : ''}`);
0045cef5 206 }
aef1b33a
JB
207 PerformanceStatistics.endMeasure(measureId, beginId);
208 return stopResponse;
c0560973
JB
209 }
210
6e0964c8 211 private logPrefix(connectorId?: number): string {
c0560973 212 if (connectorId) {
54b1efe0 213 return Utils.logPrefix(' ' + this.chargingStation.stationInfo.chargingStationId + ' | ATG on connector #' + connectorId.toString() + ':');
c0560973 214 }
54b1efe0 215 return Utils.logPrefix(' ' + this.chargingStation.stationInfo.chargingStationId + ' | ATG:');
6af9012e
JB
216 }
217}