d76ff970a2445fdb0c0039e35175459e5f4641b5
[e-mobility-charging-stations-simulator.git] / src / charging-station / AutomaticTransactionGenerator.ts
1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import {
4 AuthorizationStatus,
5 AuthorizeResponse,
6 StartTransactionResponse,
7 StopTransactionReason,
8 StopTransactionResponse,
9 } from '../types/ocpp/Transaction';
10
11 import type ChargingStation from './ChargingStation';
12 import Constants from '../utils/Constants';
13 import PerformanceStatistics from '../performance/PerformanceStatistics';
14 import { RequestCommand } from '../types/ocpp/Requests';
15 import { Status } from '../types/AutomaticTransactionGenerator';
16 import Utils from '../utils/Utils';
17 import logger from '../utils/Logger';
18
19 export default class AutomaticTransactionGenerator {
20 private static readonly instances: Map<string, AutomaticTransactionGenerator> = new Map<
21 string,
22 AutomaticTransactionGenerator
23 >();
24
25 public started: boolean;
26 private readonly chargingStation: ChargingStation;
27 private readonly connectorsStatus: Map<number, Status>;
28
29 private constructor(chargingStation: ChargingStation) {
30 this.chargingStation = chargingStation;
31 this.connectorsStatus = new Map<number, Status>();
32 this.stopConnectors();
33 this.started = false;
34 }
35
36 public static getInstance(chargingStation: ChargingStation): AutomaticTransactionGenerator {
37 if (!AutomaticTransactionGenerator.instances.has(chargingStation.id)) {
38 AutomaticTransactionGenerator.instances.set(
39 chargingStation.id,
40 new AutomaticTransactionGenerator(chargingStation)
41 );
42 }
43 return AutomaticTransactionGenerator.instances.get(chargingStation.id);
44 }
45
46 public start(): void {
47 if (this.started) {
48 logger.error(`${this.logPrefix()} trying to start while already started`);
49 return;
50 }
51 this.startConnectors();
52 this.started = true;
53 }
54
55 public stop(): void {
56 if (!this.started) {
57 logger.error(`${this.logPrefix()} trying to stop while not started`);
58 return;
59 }
60 this.stopConnectors();
61 this.started = false;
62 }
63
64 private startConnectors(): void {
65 if (
66 this.connectorsStatus?.size > 0 &&
67 this.connectorsStatus.size !== this.chargingStation.getNumberOfConnectors()
68 ) {
69 this.connectorsStatus.clear();
70 }
71 for (const connectorId of this.chargingStation.connectors.keys()) {
72 if (connectorId > 0) {
73 this.startConnector(connectorId);
74 }
75 }
76 }
77
78 private stopConnectors(): void {
79 for (const connectorId of this.chargingStation.connectors.keys()) {
80 if (connectorId > 0) {
81 this.stopConnector(connectorId);
82 }
83 }
84 }
85
86 private async internalStartConnector(connectorId: number): Promise<void> {
87 this.initStartConnectorStatus(connectorId);
88 logger.info(
89 this.logPrefix(connectorId) +
90 ' started on connector and will run for ' +
91 Utils.formatDurationMilliSeconds(
92 this.connectorsStatus.get(connectorId).stopDate.getTime() -
93 this.connectorsStatus.get(connectorId).startDate.getTime()
94 )
95 );
96 while (this.connectorsStatus.get(connectorId).start) {
97 if (new Date() > this.connectorsStatus.get(connectorId).stopDate) {
98 this.stopConnector(connectorId);
99 break;
100 }
101 if (!this.chargingStation.isInAcceptedState()) {
102 logger.error(
103 this.logPrefix(connectorId) +
104 ' entered in transaction loop while the charging station is not in accepted state'
105 );
106 this.stopConnector(connectorId);
107 break;
108 }
109 if (!this.chargingStation.isChargingStationAvailable()) {
110 logger.info(
111 this.logPrefix(connectorId) +
112 ' entered in transaction loop while the charging station is unavailable'
113 );
114 this.stopConnector(connectorId);
115 break;
116 }
117 if (!this.chargingStation.isConnectorAvailable(connectorId)) {
118 logger.info(
119 `${this.logPrefix(
120 connectorId
121 )} entered in transaction loop while the connector ${connectorId} is unavailable`
122 );
123 this.stopConnector(connectorId);
124 break;
125 }
126 if (!this.chargingStation?.ocppRequestService) {
127 logger.info(
128 `${this.logPrefix(
129 connectorId
130 )} transaction loop waiting for charging station service to be initialized`
131 );
132 do {
133 await Utils.sleep(Constants.CHARGING_STATION_ATG_INITIALIZATION_TIME);
134 } while (!this.chargingStation?.ocppRequestService);
135 }
136 const wait =
137 Utils.getRandomInteger(
138 this.chargingStation.stationInfo.AutomaticTransactionGenerator
139 .maxDelayBetweenTwoTransactions,
140 this.chargingStation.stationInfo.AutomaticTransactionGenerator
141 .minDelayBetweenTwoTransactions
142 ) * 1000;
143 logger.info(
144 this.logPrefix(connectorId) + ' waiting for ' + Utils.formatDurationMilliSeconds(wait)
145 );
146 await Utils.sleep(wait);
147 const start = Utils.secureRandom();
148 if (
149 start < this.chargingStation.stationInfo.AutomaticTransactionGenerator.probabilityOfStart
150 ) {
151 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0;
152 // Start transaction
153 const startResponse = await this.startTransaction(connectorId);
154 this.connectorsStatus.get(connectorId).startTransactionRequests++;
155 if (startResponse?.idTagInfo?.status !== AuthorizationStatus.ACCEPTED) {
156 logger.warn(this.logPrefix(connectorId) + ' start transaction rejected');
157 this.connectorsStatus.get(connectorId).rejectedStartTransactionRequests++;
158 } else {
159 // Wait until end of transaction
160 const waitTrxEnd =
161 Utils.getRandomInteger(
162 this.chargingStation.stationInfo.AutomaticTransactionGenerator.maxDuration,
163 this.chargingStation.stationInfo.AutomaticTransactionGenerator.minDuration
164 ) * 1000;
165 logger.info(
166 this.logPrefix(connectorId) +
167 ' transaction ' +
168 this.chargingStation.getConnectorStatus(connectorId).transactionId.toString() +
169 ' started and will stop in ' +
170 Utils.formatDurationMilliSeconds(waitTrxEnd)
171 );
172 this.connectorsStatus.get(connectorId).acceptedStartTransactionRequests++;
173 await Utils.sleep(waitTrxEnd);
174 // Stop transaction
175 logger.info(
176 this.logPrefix(connectorId) +
177 ' stop transaction ' +
178 this.chargingStation.getConnectorStatus(connectorId).transactionId.toString()
179 );
180 await this.stopTransaction(connectorId);
181 }
182 } else {
183 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions++;
184 this.connectorsStatus.get(connectorId).skippedTransactions++;
185 logger.info(
186 this.logPrefix(connectorId) +
187 ' skipped consecutively ' +
188 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions.toString() +
189 '/' +
190 this.connectorsStatus.get(connectorId).skippedTransactions.toString() +
191 ' transaction(s)'
192 );
193 }
194 this.connectorsStatus.get(connectorId).lastRunDate = new Date();
195 }
196 await this.stopTransaction(connectorId);
197 this.connectorsStatus.get(connectorId).stoppedDate = new Date();
198 logger.info(
199 this.logPrefix(connectorId) +
200 ' stopped on connector and lasted for ' +
201 Utils.formatDurationMilliSeconds(
202 this.connectorsStatus.get(connectorId).stoppedDate.getTime() -
203 this.connectorsStatus.get(connectorId).startDate.getTime()
204 )
205 );
206 logger.debug(
207 `${this.logPrefix(connectorId)} connector status %j`,
208 this.connectorsStatus.get(connectorId)
209 );
210 }
211
212 private startConnector(connectorId: number): void {
213 // Avoid hogging the event loop with a busy loop
214 setImmediate(() => {
215 this.internalStartConnector(connectorId).catch(() => {
216 /* This is intentional */
217 });
218 });
219 }
220
221 private stopConnector(connectorId: number): void {
222 this.connectorsStatus.set(connectorId, {
223 ...this.connectorsStatus.get(connectorId),
224 start: false,
225 });
226 }
227
228 private initStartConnectorStatus(connectorId: number): void {
229 this.connectorsStatus.get(connectorId).authorizeRequests =
230 this?.connectorsStatus.get(connectorId)?.authorizeRequests ?? 0;
231 this.connectorsStatus.get(connectorId).acceptedAuthorizeRequests =
232 this?.connectorsStatus.get(connectorId)?.acceptedAuthorizeRequests ?? 0;
233 this.connectorsStatus.get(connectorId).rejectedAuthorizeRequests =
234 this?.connectorsStatus.get(connectorId)?.rejectedAuthorizeRequests ?? 0;
235 this.connectorsStatus.get(connectorId).startTransactionRequests =
236 this?.connectorsStatus.get(connectorId)?.startTransactionRequests ?? 0;
237 this.connectorsStatus.get(connectorId).acceptedStartTransactionRequests =
238 this?.connectorsStatus.get(connectorId)?.acceptedStartTransactionRequests ?? 0;
239 this.connectorsStatus.get(connectorId).rejectedStartTransactionRequests =
240 this?.connectorsStatus.get(connectorId)?.rejectedStartTransactionRequests ?? 0;
241 this.connectorsStatus.get(connectorId).stopTransactionRequests =
242 this?.connectorsStatus.get(connectorId)?.stopTransactionRequests ?? 0;
243 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0;
244 this.connectorsStatus.get(connectorId).skippedTransactions =
245 this?.connectorsStatus.get(connectorId)?.skippedTransactions ?? 0;
246 const previousRunDuration =
247 this?.connectorsStatus.get(connectorId)?.startDate &&
248 this?.connectorsStatus.get(connectorId)?.lastRunDate
249 ? this.connectorsStatus.get(connectorId).lastRunDate.getTime() -
250 this.connectorsStatus.get(connectorId).startDate.getTime()
251 : 0;
252 this.connectorsStatus.get(connectorId).startDate = new Date();
253 this.connectorsStatus.get(connectorId).stopDate = new Date(
254 this.connectorsStatus.get(connectorId).startDate.getTime() +
255 (this.chargingStation.stationInfo?.AutomaticTransactionGenerator?.stopAfterHours ??
256 Constants.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS) *
257 3600 *
258 1000 -
259 previousRunDuration
260 );
261 this.connectorsStatus.get(connectorId).start = true;
262 }
263
264 private async startTransaction(
265 connectorId: number
266 ): Promise<StartTransactionResponse | AuthorizeResponse> {
267 const measureId = 'StartTransaction with ATG';
268 const beginId = PerformanceStatistics.beginMeasure(measureId);
269 let startResponse: StartTransactionResponse;
270 if (this.chargingStation.hasAuthorizedTags()) {
271 const idTag = this.chargingStation.getRandomIdTag();
272 if (this.chargingStation.getAutomaticTransactionGeneratorRequireAuthorize()) {
273 this.chargingStation.getConnectorStatus(connectorId).authorizeIdTag = idTag;
274 // Authorize idTag
275 const authorizeResponse: AuthorizeResponse =
276 (await this.chargingStation.ocppRequestService.sendMessageHandler(
277 RequestCommand.AUTHORIZE,
278 {
279 idTag,
280 }
281 )) as AuthorizeResponse;
282 this.connectorsStatus.get(connectorId).authorizeRequests++;
283 if (authorizeResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
284 this.connectorsStatus.get(connectorId).acceptedAuthorizeRequests++;
285 logger.info(this.logPrefix(connectorId) + ' start transaction for idTag ' + idTag);
286 // Start transaction
287 startResponse = (await this.chargingStation.ocppRequestService.sendMessageHandler(
288 RequestCommand.START_TRANSACTION,
289 {
290 connectorId,
291 idTag,
292 }
293 )) as StartTransactionResponse;
294 PerformanceStatistics.endMeasure(measureId, beginId);
295 return startResponse;
296 }
297 this.connectorsStatus.get(connectorId).rejectedAuthorizeRequests++;
298 PerformanceStatistics.endMeasure(measureId, beginId);
299 return authorizeResponse;
300 }
301 logger.info(this.logPrefix(connectorId) + ' start transaction for idTag ' + idTag);
302 // Start transaction
303 startResponse = (await this.chargingStation.ocppRequestService.sendMessageHandler(
304 RequestCommand.START_TRANSACTION,
305 {
306 connectorId,
307 idTag,
308 }
309 )) as StartTransactionResponse;
310 PerformanceStatistics.endMeasure(measureId, beginId);
311 return startResponse;
312 }
313 logger.info(this.logPrefix(connectorId) + ' start transaction without an idTag');
314 startResponse = (await this.chargingStation.ocppRequestService.sendMessageHandler(
315 RequestCommand.START_TRANSACTION,
316 { connectorId }
317 )) as StartTransactionResponse;
318 PerformanceStatistics.endMeasure(measureId, beginId);
319 return startResponse;
320 }
321
322 private async stopTransaction(
323 connectorId: number,
324 reason: StopTransactionReason = StopTransactionReason.NONE
325 ): Promise<StopTransactionResponse> {
326 const measureId = 'StopTransaction with ATG';
327 const beginId = PerformanceStatistics.beginMeasure(measureId);
328 let transactionId = 0;
329 let stopResponse: StopTransactionResponse;
330 if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted) {
331 transactionId = this.chargingStation.getConnectorStatus(connectorId).transactionId;
332 stopResponse = await this.chargingStation.ocppRequestService.sendStopTransaction(
333 transactionId,
334 this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId),
335 this.chargingStation.getTransactionIdTag(transactionId),
336 reason
337 );
338 this.connectorsStatus.get(connectorId).stopTransactionRequests++;
339 } else {
340 logger.warn(
341 `${this.logPrefix(connectorId)} trying to stop a not started transaction${
342 transactionId ? ' ' + transactionId.toString() : ''
343 }`
344 );
345 }
346 PerformanceStatistics.endMeasure(measureId, beginId);
347 return stopResponse;
348 }
349
350 private logPrefix(connectorId?: number): string {
351 if (connectorId) {
352 return Utils.logPrefix(
353 ' ' +
354 this.chargingStation.stationInfo.chargingStationId +
355 ' | ATG on connector #' +
356 connectorId.toString() +
357 ':'
358 );
359 }
360 return Utils.logPrefix(' ' + this.chargingStation.stationInfo.chargingStationId + ' | ATG:');
361 }
362 }