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