Permit to run code in async scope in the OCPP stack
[e-mobility-charging-stations-simulator.git] / src / charging-station / AutomaticTransactionGenerator.ts
1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import { AsyncResource } from 'async_hooks';
4
5 import BaseError from '../exception/BaseError';
6 import PerformanceStatistics from '../performance/PerformanceStatistics';
7 import {
8 type AutomaticTransactionGeneratorConfiguration,
9 IdTagDistribution,
10 type Status,
11 } from '../types/AutomaticTransactionGenerator';
12 import { RequestCommand } from '../types/ocpp/Requests';
13 import {
14 AuthorizationStatus,
15 type AuthorizeRequest,
16 type AuthorizeResponse,
17 type StartTransactionRequest,
18 type StartTransactionResponse,
19 StopTransactionReason,
20 type StopTransactionResponse,
21 } from '../types/ocpp/Transaction';
22 import Constants from '../utils/Constants';
23 import logger from '../utils/Logger';
24 import Utils from '../utils/Utils';
25 import type ChargingStation from './ChargingStation';
26 import { ChargingStationUtils } from './ChargingStationUtils';
27
28 const moduleName = 'AutomaticTransactionGenerator';
29
30 export default class AutomaticTransactionGenerator extends AsyncResource {
31 private static readonly instances: Map<string, AutomaticTransactionGenerator> = new Map<
32 string,
33 AutomaticTransactionGenerator
34 >();
35
36 public readonly connectorsStatus: Map<number, Status>;
37 public readonly configuration: AutomaticTransactionGeneratorConfiguration;
38 public started: boolean;
39 private readonly chargingStation: ChargingStation;
40 private idTagIndex: number;
41
42 private constructor(
43 automaticTransactionGeneratorConfiguration: AutomaticTransactionGeneratorConfiguration,
44 chargingStation: ChargingStation
45 ) {
46 super(moduleName);
47 this.started = false;
48 this.configuration = automaticTransactionGeneratorConfiguration;
49 this.chargingStation = chargingStation;
50 this.idTagIndex = 0;
51 this.connectorsStatus = new Map<number, Status>();
52 this.initializeConnectorsStatus();
53 }
54
55 public static getInstance(
56 automaticTransactionGeneratorConfiguration: AutomaticTransactionGeneratorConfiguration,
57 chargingStation: ChargingStation
58 ): AutomaticTransactionGenerator {
59 if (AutomaticTransactionGenerator.instances.has(chargingStation.stationInfo.hashId) === false) {
60 AutomaticTransactionGenerator.instances.set(
61 chargingStation.stationInfo.hashId,
62 new AutomaticTransactionGenerator(
63 automaticTransactionGeneratorConfiguration,
64 chargingStation
65 )
66 );
67 }
68 return AutomaticTransactionGenerator.instances.get(chargingStation.stationInfo.hashId);
69 }
70
71 public start(): void {
72 if (this.started === true) {
73 logger.warn(`${this.logPrefix()} is already started`);
74 return;
75 }
76 this.startConnectors();
77 this.started = true;
78 }
79
80 public stop(): void {
81 if (this.started === false) {
82 logger.warn(`${this.logPrefix()} is already stopped`);
83 return;
84 }
85 this.stopConnectors();
86 this.started = false;
87 }
88
89 public startConnector(connectorId: number): void {
90 if (this.connectorsStatus.has(connectorId) === false) {
91 logger.error(`${this.logPrefix(connectorId)} starting on non existing connector`);
92 throw new BaseError(`Connector ${connectorId} does not exist`);
93 }
94 if (this.connectorsStatus.get(connectorId)?.start === false) {
95 this.runInAsyncScope(
96 this.internalStartConnector.bind(this) as (
97 this: AutomaticTransactionGenerator,
98 ...args: any[]
99 ) => void,
100 this,
101 connectorId
102 );
103 } else if (this.connectorsStatus.get(connectorId)?.start === true) {
104 logger.warn(`${this.logPrefix(connectorId)} is already started on connector`);
105 }
106 }
107
108 public stopConnector(connectorId: number): void {
109 if (this.connectorsStatus.has(connectorId) === false) {
110 logger.error(`${this.logPrefix(connectorId)} stopping on non existing connector`);
111 throw new BaseError(`Connector ${connectorId} does not exist`);
112 }
113 if (this.connectorsStatus.get(connectorId)?.start === true) {
114 this.connectorsStatus.get(connectorId).start = false;
115 } else if (this.connectorsStatus.get(connectorId)?.start === false) {
116 logger.warn(`${this.logPrefix(connectorId)} is already stopped on connector`);
117 }
118 }
119
120 private startConnectors(): void {
121 if (
122 this.connectorsStatus?.size > 0 &&
123 this.connectorsStatus.size !== this.chargingStation.getNumberOfConnectors()
124 ) {
125 this.connectorsStatus.clear();
126 this.initializeConnectorsStatus();
127 }
128 for (const connectorId of this.chargingStation.connectors.keys()) {
129 if (connectorId > 0) {
130 this.startConnector(connectorId);
131 }
132 }
133 }
134
135 private stopConnectors(): void {
136 for (const connectorId of this.chargingStation.connectors.keys()) {
137 if (connectorId > 0) {
138 this.stopConnector(connectorId);
139 }
140 }
141 }
142
143 private async internalStartConnector(connectorId: number): Promise<void> {
144 this.setStartConnectorStatus(connectorId);
145 logger.info(
146 this.logPrefix(connectorId) +
147 ' started on connector and will run for ' +
148 Utils.formatDurationMilliSeconds(
149 this.connectorsStatus.get(connectorId).stopDate.getTime() -
150 this.connectorsStatus.get(connectorId).startDate.getTime()
151 )
152 );
153 while (this.connectorsStatus.get(connectorId).start === true) {
154 if (new Date() > this.connectorsStatus.get(connectorId).stopDate) {
155 this.stopConnector(connectorId);
156 break;
157 }
158 if (this.chargingStation.isInAcceptedState() === false) {
159 logger.error(
160 this.logPrefix(connectorId) +
161 ' entered in transaction loop while the charging station is not in accepted state'
162 );
163 this.stopConnector(connectorId);
164 break;
165 }
166 if (this.chargingStation.isChargingStationAvailable() === false) {
167 logger.info(
168 this.logPrefix(connectorId) +
169 ' entered in transaction loop while the charging station is unavailable'
170 );
171 this.stopConnector(connectorId);
172 break;
173 }
174 if (this.chargingStation.isConnectorAvailable(connectorId) === false) {
175 logger.info(
176 `${this.logPrefix(
177 connectorId
178 )} entered in transaction loop while the connector ${connectorId} is unavailable`
179 );
180 this.stopConnector(connectorId);
181 break;
182 }
183 if (!this.chargingStation?.ocppRequestService) {
184 logger.info(
185 `${this.logPrefix(
186 connectorId
187 )} transaction loop waiting for charging station service to be initialized`
188 );
189 do {
190 await Utils.sleep(Constants.CHARGING_STATION_ATG_INITIALIZATION_TIME);
191 } while (!this.chargingStation?.ocppRequestService);
192 }
193 const wait =
194 Utils.getRandomInteger(
195 this.configuration.maxDelayBetweenTwoTransactions,
196 this.configuration.minDelayBetweenTwoTransactions
197 ) * 1000;
198 logger.info(
199 this.logPrefix(connectorId) + ' waiting for ' + Utils.formatDurationMilliSeconds(wait)
200 );
201 await Utils.sleep(wait);
202 const start = Utils.secureRandom();
203 if (start < this.configuration.probabilityOfStart) {
204 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0;
205 // Start transaction
206 const startResponse = await this.startTransaction(connectorId);
207 if (startResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
208 // Wait until end of transaction
209 const waitTrxEnd =
210 Utils.getRandomInteger(this.configuration.maxDuration, this.configuration.minDuration) *
211 1000;
212 logger.info(
213 this.logPrefix(connectorId) +
214 ' transaction ' +
215 this.chargingStation.getConnectorStatus(connectorId).transactionId.toString() +
216 ' started and will stop in ' +
217 Utils.formatDurationMilliSeconds(waitTrxEnd)
218 );
219 await Utils.sleep(waitTrxEnd);
220 // Stop transaction
221 logger.info(
222 this.logPrefix(connectorId) +
223 ' stop transaction ' +
224 this.chargingStation.getConnectorStatus(connectorId).transactionId.toString()
225 );
226 await this.stopTransaction(connectorId);
227 }
228 } else {
229 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions++;
230 this.connectorsStatus.get(connectorId).skippedTransactions++;
231 logger.info(
232 this.logPrefix(connectorId) +
233 ' skipped consecutively ' +
234 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions.toString() +
235 '/' +
236 this.connectorsStatus.get(connectorId).skippedTransactions.toString() +
237 ' transaction(s)'
238 );
239 }
240 this.connectorsStatus.get(connectorId).lastRunDate = new Date();
241 }
242 this.connectorsStatus.get(connectorId).stoppedDate = new Date();
243 logger.info(
244 this.logPrefix(connectorId) +
245 ' stopped on connector and lasted for ' +
246 Utils.formatDurationMilliSeconds(
247 this.connectorsStatus.get(connectorId).stoppedDate.getTime() -
248 this.connectorsStatus.get(connectorId).startDate.getTime()
249 )
250 );
251 logger.debug(
252 `${this.logPrefix(connectorId)} connector status: %j`,
253 this.connectorsStatus.get(connectorId)
254 );
255 }
256
257 private setStartConnectorStatus(connectorId: number): void {
258 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0;
259 const previousRunDuration =
260 this?.connectorsStatus.get(connectorId)?.startDate &&
261 this?.connectorsStatus.get(connectorId)?.lastRunDate
262 ? this.connectorsStatus.get(connectorId).lastRunDate.getTime() -
263 this.connectorsStatus.get(connectorId).startDate.getTime()
264 : 0;
265 this.connectorsStatus.get(connectorId).startDate = new Date();
266 this.connectorsStatus.get(connectorId).stopDate = new Date(
267 this.connectorsStatus.get(connectorId).startDate.getTime() +
268 (this.configuration.stopAfterHours ??
269 Constants.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS) *
270 3600 *
271 1000 -
272 previousRunDuration
273 );
274 this.connectorsStatus.get(connectorId).start = true;
275 }
276
277 private initializeConnectorsStatus(): void {
278 for (const connectorId of this.chargingStation.connectors.keys()) {
279 if (connectorId > 0) {
280 this.connectorsStatus.set(connectorId, {
281 start: false,
282 authorizeRequests: 0,
283 acceptedAuthorizeRequests: 0,
284 rejectedAuthorizeRequests: 0,
285 startTransactionRequests: 0,
286 acceptedStartTransactionRequests: 0,
287 rejectedStartTransactionRequests: 0,
288 stopTransactionRequests: 0,
289 acceptedStopTransactionRequests: 0,
290 rejectedStopTransactionRequests: 0,
291 skippedConsecutiveTransactions: 0,
292 skippedTransactions: 0,
293 });
294 }
295 }
296 }
297
298 private async startTransaction(
299 connectorId: number
300 ): Promise<StartTransactionResponse | undefined> {
301 const measureId = 'StartTransaction with ATG';
302 const beginId = PerformanceStatistics.beginMeasure(measureId);
303 let startResponse: StartTransactionResponse;
304 if (this.chargingStation.hasAuthorizedTags()) {
305 const idTag = this.getIdTag(connectorId);
306 const startTransactionLogMsg = `${this.logPrefix(
307 connectorId
308 )} start transaction with an idTag '${idTag}'`;
309 if (this.getRequireAuthorize()) {
310 this.chargingStation.getConnectorStatus(connectorId).authorizeIdTag = idTag;
311 // Authorize idTag
312 const authorizeResponse: AuthorizeResponse =
313 await this.chargingStation.ocppRequestService.requestHandler<
314 AuthorizeRequest,
315 AuthorizeResponse
316 >(this.chargingStation, RequestCommand.AUTHORIZE, {
317 idTag,
318 });
319 this.connectorsStatus.get(connectorId).authorizeRequests++;
320 if (authorizeResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
321 this.connectorsStatus.get(connectorId).acceptedAuthorizeRequests++;
322 logger.info(startTransactionLogMsg);
323 // Start transaction
324 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
325 StartTransactionRequest,
326 StartTransactionResponse
327 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
328 connectorId,
329 idTag,
330 });
331 this.handleStartTransactionResponse(connectorId, startResponse);
332 PerformanceStatistics.endMeasure(measureId, beginId);
333 return startResponse;
334 }
335 this.connectorsStatus.get(connectorId).rejectedAuthorizeRequests++;
336 PerformanceStatistics.endMeasure(measureId, beginId);
337 return startResponse;
338 }
339 logger.info(startTransactionLogMsg);
340 // Start transaction
341 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
342 StartTransactionRequest,
343 StartTransactionResponse
344 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
345 connectorId,
346 idTag,
347 });
348 this.handleStartTransactionResponse(connectorId, startResponse);
349 PerformanceStatistics.endMeasure(measureId, beginId);
350 return startResponse;
351 }
352 logger.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
353 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
354 StartTransactionRequest,
355 StartTransactionResponse
356 >(this.chargingStation, RequestCommand.START_TRANSACTION, { connectorId });
357 this.handleStartTransactionResponse(connectorId, startResponse);
358 PerformanceStatistics.endMeasure(measureId, beginId);
359 return startResponse;
360 }
361
362 private async stopTransaction(
363 connectorId: number,
364 reason: StopTransactionReason = StopTransactionReason.LOCAL
365 ): Promise<StopTransactionResponse> {
366 const measureId = 'StopTransaction with ATG';
367 const beginId = PerformanceStatistics.beginMeasure(measureId);
368 let stopResponse: StopTransactionResponse;
369 if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted === true) {
370 stopResponse = await this.chargingStation.stopTransactionOnConnector(connectorId, reason);
371 this.connectorsStatus.get(connectorId).stopTransactionRequests++;
372 if (stopResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
373 this.connectorsStatus.get(connectorId).acceptedStopTransactionRequests++;
374 } else {
375 this.connectorsStatus.get(connectorId).rejectedStopTransactionRequests++;
376 }
377 } else {
378 const transactionId = this.chargingStation.getConnectorStatus(connectorId).transactionId;
379 logger.warn(
380 `${this.logPrefix(connectorId)} stopping a not started transaction${
381 transactionId ? ' ' + transactionId.toString() : ''
382 }`
383 );
384 }
385 PerformanceStatistics.endMeasure(measureId, beginId);
386 return stopResponse;
387 }
388
389 private getRequireAuthorize(): boolean {
390 return this.configuration?.requireAuthorize ?? true;
391 }
392
393 private getRandomIdTag(authorizationFile: string): string {
394 const tags = this.chargingStation.authorizedTagsCache.getAuthorizedTags(authorizationFile);
395 this.idTagIndex = Math.floor(Utils.secureRandom() * tags.length);
396 return tags[this.idTagIndex];
397 }
398
399 private getRoundRobinIdTag(authorizationFile: string): string {
400 const tags = this.chargingStation.authorizedTagsCache.getAuthorizedTags(authorizationFile);
401 const idTag = tags[this.idTagIndex];
402 this.idTagIndex = this.idTagIndex === tags.length - 1 ? 0 : this.idTagIndex + 1;
403 return idTag;
404 }
405
406 private getConnectorAffinityIdTag(authorizationFile: string, connectorId: number): string {
407 const tags = this.chargingStation.authorizedTagsCache.getAuthorizedTags(authorizationFile);
408 this.idTagIndex = (this.chargingStation.index - 1 + (connectorId - 1)) % tags.length;
409 return tags[this.idTagIndex];
410 }
411
412 private getIdTag(connectorId: number): string {
413 const authorizationFile = ChargingStationUtils.getAuthorizationFile(
414 this.chargingStation.stationInfo
415 );
416 switch (this.configuration?.idTagDistribution) {
417 case IdTagDistribution.RANDOM:
418 return this.getRandomIdTag(authorizationFile);
419 case IdTagDistribution.ROUND_ROBIN:
420 return this.getRoundRobinIdTag(authorizationFile);
421 case IdTagDistribution.CONNECTOR_AFFINITY:
422 return this.getConnectorAffinityIdTag(authorizationFile, connectorId);
423 default:
424 return this.getRoundRobinIdTag(authorizationFile);
425 }
426 }
427
428 private logPrefix(connectorId?: number): string {
429 return Utils.logPrefix(
430 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
431 connectorId !== undefined ? ` on connector #${connectorId.toString()}` : ''
432 }:`
433 );
434 }
435
436 private handleStartTransactionResponse(
437 connectorId: number,
438 startResponse: StartTransactionResponse
439 ): void {
440 this.connectorsStatus.get(connectorId).startTransactionRequests++;
441 if (startResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
442 this.connectorsStatus.get(connectorId).acceptedStartTransactionRequests++;
443 } else {
444 logger.warn(this.logPrefix(connectorId) + ' start transaction rejected');
445 this.connectorsStatus.get(connectorId).rejectedStartTransactionRequests++;
446 }
447 }
448 }