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