Coding style cleanups
[e-mobility-charging-stations-simulator.git] / src / charging-station / AutomaticTransactionGenerator.ts
CommitLineData
c8eeb62b
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
8114d10e 3import PerformanceStatistics from '../performance/PerformanceStatistics';
6c1761d4 4import type {
8114d10e
JB
5 AutomaticTransactionGeneratorConfiguration,
6 Status,
7} from '../types/AutomaticTransactionGenerator';
5e3cb728 8import { RequestCommand } from '../types/ocpp/Requests';
e7aeea18
JB
9import {
10 AuthorizationStatus,
ef6fa3fb 11 AuthorizeRequest,
e7aeea18 12 AuthorizeResponse,
ef6fa3fb 13 StartTransactionRequest,
e7aeea18
JB
14 StartTransactionResponse,
15 StopTransactionReason,
16 StopTransactionResponse,
17} from '../types/ocpp/Transaction';
6af9012e 18import Constants from '../utils/Constants';
9f2e3130 19import logger from '../utils/Logger';
8114d10e
JB
20import Utils from '../utils/Utils';
21import type ChargingStation from './ChargingStation';
6af9012e
JB
22
23export default class AutomaticTransactionGenerator {
e7aeea18
JB
24 private static readonly instances: Map<string, AutomaticTransactionGenerator> = new Map<
25 string,
26 AutomaticTransactionGenerator
27 >();
10068088 28
5e3cb728 29 public readonly connectorsStatus: Map<number, Status>;
fa7bccf4 30 public readonly configuration: AutomaticTransactionGeneratorConfiguration;
265e4266 31 public started: boolean;
9e23580d 32 private readonly chargingStation: ChargingStation;
6af9012e 33
fa7bccf4
JB
34 private constructor(
35 automaticTransactionGeneratorConfiguration: AutomaticTransactionGeneratorConfiguration,
36 chargingStation: ChargingStation
37 ) {
38 this.configuration = automaticTransactionGeneratorConfiguration;
ad2f27c3 39 this.chargingStation = chargingStation;
9664ec50 40 this.connectorsStatus = new Map<number, Status>();
72740232 41 this.stopConnectors();
265e4266 42 this.started = false;
6af9012e
JB
43 }
44
fa7bccf4
JB
45 public static getInstance(
46 automaticTransactionGeneratorConfiguration: AutomaticTransactionGeneratorConfiguration,
47 chargingStation: ChargingStation
48 ): AutomaticTransactionGenerator {
51c83d6f 49 if (!AutomaticTransactionGenerator.instances.has(chargingStation.stationInfo.hashId)) {
e7aeea18 50 AutomaticTransactionGenerator.instances.set(
51c83d6f 51 chargingStation.stationInfo.hashId,
fa7bccf4
JB
52 new AutomaticTransactionGenerator(
53 automaticTransactionGeneratorConfiguration,
54 chargingStation
55 )
e7aeea18 56 );
73b9adec 57 }
51c83d6f 58 return AutomaticTransactionGenerator.instances.get(chargingStation.stationInfo.hashId);
73b9adec
JB
59 }
60
7d75bee1 61 public start(): void {
a5e9befc
JB
62 if (this.started === true) {
63 logger.warn(`${this.logPrefix()} trying to start while already started`);
b809adf1
JB
64 return;
65 }
72740232 66 this.startConnectors();
265e4266 67 this.started = true;
6af9012e
JB
68 }
69
0045cef5 70 public stop(): void {
a5e9befc
JB
71 if (this.started === false) {
72 logger.warn(`${this.logPrefix()} trying to stop while not started`);
265e4266
JB
73 return;
74 }
72740232 75 this.stopConnectors();
265e4266 76 this.started = false;
6af9012e
JB
77 }
78
a5e9befc 79 public startConnector(connectorId: number): void {
ecb3869d 80 if (this.chargingStation.connectors.has(connectorId) === false) {
a5e9befc
JB
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 });
ecb3869d 91 } else if (this.connectorsStatus.get(connectorId)?.start === true) {
a5e9befc
JB
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
72740232 103 private startConnectors(): void {
e7aeea18
JB
104 if (
105 this.connectorsStatus?.size > 0 &&
106 this.connectorsStatus.size !== this.chargingStation.getNumberOfConnectors()
107 ) {
54544ef1
JB
108 this.connectorsStatus.clear();
109 }
734d790d 110 for (const connectorId of this.chargingStation.connectors.keys()) {
72740232 111 if (connectorId > 0) {
83a3286a 112 this.startConnector(connectorId);
72740232
JB
113 }
114 }
115 }
116
117 private stopConnectors(): void {
734d790d 118 for (const connectorId of this.chargingStation.connectors.keys()) {
72740232
JB
119 if (connectorId > 0) {
120 this.stopConnector(connectorId);
121 }
122 }
123 }
124
83a3286a 125 private async internalStartConnector(connectorId: number): Promise<void> {
6cd85def 126 this.initializeConnectorStatus(connectorId);
e7aeea18
JB
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 );
a5e9befc 135 while (this.connectorsStatus.get(connectorId).start === true) {
e7aeea18 136 if (new Date() > this.connectorsStatus.get(connectorId).stopDate) {
9664ec50 137 this.stopConnector(connectorId);
17991e8c
JB
138 break;
139 }
16cd35ad 140 if (!this.chargingStation.isInAcceptedState()) {
e7aeea18
JB
141 logger.error(
142 this.logPrefix(connectorId) +
143 ' entered in transaction loop while the charging station is not in accepted state'
144 );
9664ec50 145 this.stopConnector(connectorId);
17991e8c
JB
146 break;
147 }
c0560973 148 if (!this.chargingStation.isChargingStationAvailable()) {
e7aeea18
JB
149 logger.info(
150 this.logPrefix(connectorId) +
151 ' entered in transaction loop while the charging station is unavailable'
152 );
9664ec50 153 this.stopConnector(connectorId);
ab5f4b03
JB
154 break;
155 }
c0560973 156 if (!this.chargingStation.isConnectorAvailable(connectorId)) {
e7aeea18
JB
157 logger.info(
158 `${this.logPrefix(
159 connectorId
160 )} entered in transaction loop while the connector ${connectorId} is unavailable`
161 );
9c7195b2 162 this.stopConnector(connectorId);
17991e8c
JB
163 break;
164 }
c0560973 165 if (!this.chargingStation?.ocppRequestService) {
e7aeea18
JB
166 logger.info(
167 `${this.logPrefix(
168 connectorId
169 )} transaction loop waiting for charging station service to be initialized`
170 );
c0560973 171 do {
a4cc42ea 172 await Utils.sleep(Constants.CHARGING_STATION_ATG_INITIALIZATION_TIME);
c0560973
JB
173 } while (!this.chargingStation?.ocppRequestService);
174 }
e7aeea18
JB
175 const wait =
176 Utils.getRandomInteger(
fa7bccf4
JB
177 this.configuration.maxDelayBetweenTwoTransactions,
178 this.configuration.minDelayBetweenTwoTransactions
e7aeea18
JB
179 ) * 1000;
180 logger.info(
181 this.logPrefix(connectorId) + ' waiting for ' + Utils.formatDurationMilliSeconds(wait)
182 );
6af9012e 183 await Utils.sleep(wait);
c37528f1 184 const start = Utils.secureRandom();
fa7bccf4 185 if (start < this.configuration.probabilityOfStart) {
9664ec50 186 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0;
6af9012e 187 // Start transaction
aef1b33a 188 const startResponse = await this.startTransaction(connectorId);
071a9315 189 this.connectorsStatus.get(connectorId).startTransactionRequests++;
ef6076c1 190 if (startResponse?.idTagInfo?.status !== AuthorizationStatus.ACCEPTED) {
9f2e3130 191 logger.warn(this.logPrefix(connectorId) + ' start transaction rejected');
071a9315 192 this.connectorsStatus.get(connectorId).rejectedStartTransactionRequests++;
6af9012e
JB
193 } else {
194 // Wait until end of transaction
e7aeea18 195 const waitTrxEnd =
fa7bccf4
JB
196 Utils.getRandomInteger(this.configuration.maxDuration, this.configuration.minDuration) *
197 1000;
e7aeea18
JB
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 );
071a9315 205 this.connectorsStatus.get(connectorId).acceptedStartTransactionRequests++;
6af9012e
JB
206 await Utils.sleep(waitTrxEnd);
207 // Stop transaction
e7aeea18
JB
208 logger.info(
209 this.logPrefix(connectorId) +
210 ' stop transaction ' +
211 this.chargingStation.getConnectorStatus(connectorId).transactionId.toString()
212 );
85d20667 213 await this.stopTransaction(connectorId);
6af9012e
JB
214 }
215 } else {
9664ec50
JB
216 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions++;
217 this.connectorsStatus.get(connectorId).skippedTransactions++;
e7aeea18
JB
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 );
6af9012e 226 }
9664ec50 227 this.connectorsStatus.get(connectorId).lastRunDate = new Date();
7d75bee1 228 }
9664ec50 229 this.connectorsStatus.get(connectorId).stoppedDate = new Date();
e7aeea18
JB
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(
be9ee554 239 `${this.logPrefix(connectorId)} connector status: %j`,
e7aeea18
JB
240 this.connectorsStatus.get(connectorId)
241 );
6af9012e
JB
242 }
243
6cd85def 244 private initializeConnectorStatus(connectorId: number): void {
e7aeea18
JB
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;
6d9876e7
JB
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;
9664ec50 263 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0;
e7aeea18
JB
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;
9664ec50 272 this.connectorsStatus.get(connectorId).startDate = new Date();
e7aeea18
JB
273 this.connectorsStatus.get(connectorId).stopDate = new Date(
274 this.connectorsStatus.get(connectorId).startDate.getTime() +
fa7bccf4 275 (this.configuration.stopAfterHours ??
e7aeea18
JB
276 Constants.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS) *
277 3600 *
278 1000 -
279 previousRunDuration
280 );
9664ec50 281 this.connectorsStatus.get(connectorId).start = true;
72740232
JB
282 }
283
e7aeea18
JB
284 private async startTransaction(
285 connectorId: number
286 ): Promise<StartTransactionResponse | AuthorizeResponse> {
aef1b33a
JB
287 const measureId = 'StartTransaction with ATG';
288 const beginId = PerformanceStatistics.beginMeasure(measureId);
289 let startResponse: StartTransactionResponse;
290 if (this.chargingStation.hasAuthorizedTags()) {
f4bf2abd 291 const idTag = this.chargingStation.getRandomIdTag();
5cf9050d
JB
292 const startTransactionLogMsg = `${this.logPrefix(
293 connectorId
294 )} start transaction for idTag '${idTag}'`;
ccb1d6e9 295 if (this.getRequireAuthorize()) {
2e3d65ae 296 this.chargingStation.getConnectorStatus(connectorId).authorizeIdTag = idTag;
f4bf2abd 297 // Authorize idTag
2e3d65ae 298 const authorizeResponse: AuthorizeResponse =
f7f98c68 299 await this.chargingStation.ocppRequestService.requestHandler<
ef6fa3fb
JB
300 AuthorizeRequest,
301 AuthorizeResponse
08f130a0 302 >(this.chargingStation, RequestCommand.AUTHORIZE, {
ef6fa3fb
JB
303 idTag,
304 });
071a9315 305 this.connectorsStatus.get(connectorId).authorizeRequests++;
5fdab605 306 if (authorizeResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
071a9315 307 this.connectorsStatus.get(connectorId).acceptedAuthorizeRequests++;
5cf9050d 308 logger.info(startTransactionLogMsg);
5fdab605 309 // Start transaction
f7f98c68 310 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
ef6fa3fb
JB
311 StartTransactionRequest,
312 StartTransactionResponse
08f130a0 313 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
ef6fa3fb
JB
314 connectorId,
315 idTag,
316 });
aef1b33a
JB
317 PerformanceStatistics.endMeasure(measureId, beginId);
318 return startResponse;
5fdab605 319 }
071a9315 320 this.connectorsStatus.get(connectorId).rejectedAuthorizeRequests++;
aef1b33a 321 PerformanceStatistics.endMeasure(measureId, beginId);
4faad557 322 return authorizeResponse;
ef6076c1 323 }
5cf9050d 324 logger.info(startTransactionLogMsg);
5fdab605 325 // Start transaction
f7f98c68 326 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
ef6fa3fb
JB
327 StartTransactionRequest,
328 StartTransactionResponse
08f130a0 329 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
ef6fa3fb
JB
330 connectorId,
331 idTag,
332 });
aef1b33a
JB
333 PerformanceStatistics.endMeasure(measureId, beginId);
334 return startResponse;
6af9012e 335 }
5cf9050d 336 logger.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
f7f98c68 337 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
ef6fa3fb
JB
338 StartTransactionRequest,
339 StartTransactionResponse
08f130a0 340 >(this.chargingStation, RequestCommand.START_TRANSACTION, { connectorId });
aef1b33a
JB
341 PerformanceStatistics.endMeasure(measureId, beginId);
342 return startResponse;
6af9012e
JB
343 }
344
e7aeea18
JB
345 private async stopTransaction(
346 connectorId: number,
5e3cb728 347 reason: StopTransactionReason = StopTransactionReason.LOCAL
e7aeea18 348 ): Promise<StopTransactionResponse> {
aef1b33a
JB
349 const measureId = 'StopTransaction with ATG';
350 const beginId = PerformanceStatistics.beginMeasure(measureId);
0045cef5 351 let stopResponse: StopTransactionResponse;
6d9876e7 352 if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted === true) {
5e3cb728 353 stopResponse = await this.chargingStation.stopTransactionOnConnector(connectorId, reason);
071a9315 354 this.connectorsStatus.get(connectorId).stopTransactionRequests++;
6d9876e7
JB
355 if (stopResponse.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
356 this.connectorsStatus.get(connectorId).acceptedStopTransactionRequests++;
357 } else {
358 this.connectorsStatus.get(connectorId).rejectedStopTransactionRequests++;
359 }
0045cef5 360 } else {
5e3cb728 361 const transactionId = this.chargingStation.getConnectorStatus(connectorId).transactionId;
e7aeea18
JB
362 logger.warn(
363 `${this.logPrefix(connectorId)} trying to stop a not started transaction${
364 transactionId ? ' ' + transactionId.toString() : ''
365 }`
366 );
0045cef5 367 }
aef1b33a
JB
368 PerformanceStatistics.endMeasure(measureId, beginId);
369 return stopResponse;
c0560973
JB
370 }
371
ccb1d6e9 372 private getRequireAuthorize(): boolean {
fa7bccf4 373 return this.configuration?.requireAuthorize ?? true;
ccb1d6e9
JB
374 }
375
6e0964c8 376 private logPrefix(connectorId?: number): string {
6cd85def
JB
377 return Utils.logPrefix(
378 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
a5e9befc 379 connectorId !== undefined ? ` on connector #${connectorId.toString()}` : ''
6cd85def
JB
380 }:`
381 );
6af9012e
JB
382 }
383}