Secure random integer generator inputs
[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 Utils from '../utils/Utils';
9 import logger from '../utils/Logger';
10
11 export default class AutomaticTransactionGenerator {
12 public timeToStop: boolean;
13 private startDate!: Date;
14 private stopDate!: Date;
15 private chargingStation: ChargingStation;
16
17 constructor(chargingStation: ChargingStation) {
18 this.chargingStation = chargingStation;
19 this.timeToStop = true;
20 }
21
22 public start(): void {
23 this.startDate = new Date();
24 this.stopDate = new Date(this.startDate.getTime() + (this.chargingStation.stationInfo?.AutomaticTransactionGenerator?.stopAfterHours ?? Constants.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS) * 3600 * 1000);
25 this.timeToStop = false;
26 for (const connector in this.chargingStation.connectors) {
27 if (Utils.convertToInt(connector) > 0) {
28 // Avoid hogging the event loop with a busy loop
29 setImmediate(() => {
30 this.startOnConnector(Utils.convertToInt(connector)).catch(() => { /* This is intentional */ });
31 });
32 }
33 }
34 logger.info(this.logPrefix() + ' started and will run for ' + Utils.milliSecondsToHHMMSS(this.stopDate.getTime() - this.startDate.getTime()));
35 }
36
37 public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
38 logger.info(this.logPrefix() + ' over. Stopping all transactions');
39 for (const connector in this.chargingStation.connectors) {
40 const transactionId = this.chargingStation.getConnector(Utils.convertToInt(connector)).transactionId;
41 if (this.chargingStation.getConnector(Utils.convertToInt(connector)).transactionStarted) {
42 logger.info(this.logPrefix(Utils.convertToInt(connector)) + ' over. Stop transaction ' + transactionId.toString());
43 await this.chargingStation.ocppRequestService.sendStopTransaction(transactionId, this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId),
44 this.chargingStation.getTransactionIdTag(transactionId), reason);
45 }
46 }
47 this.timeToStop = true;
48 }
49
50 private async startOnConnector(connectorId: number): Promise<void> {
51 logger.info(this.logPrefix(connectorId) + ' started on connector');
52 let transactionSkip = 0;
53 let totalTransactionSkip = 0;
54 while (!this.timeToStop) {
55 if ((new Date()) > this.stopDate) {
56 await this.stop();
57 break;
58 }
59 if (!this.chargingStation.isRegistered()) {
60 logger.error(this.logPrefix(connectorId) + ' Entered in transaction loop while the charging station is not registered');
61 break;
62 }
63 if (!this.chargingStation.isChargingStationAvailable()) {
64 logger.info(this.logPrefix(connectorId) + ' Entered in transaction loop while the charging station is unavailable');
65 await this.stop();
66 break;
67 }
68 if (!this.chargingStation.isConnectorAvailable(connectorId)) {
69 logger.info(`${this.logPrefix(connectorId)} Entered in transaction loop while the connector ${connectorId} is unavailable, stop it`);
70 break;
71 }
72 if (!this.chargingStation?.ocppRequestService) {
73 logger.info(`${this.logPrefix(connectorId)} Transaction loop waiting for charging station service to be initialized`);
74 do {
75 await Utils.sleep(Constants.CHARGING_STATION_ATG_INITIALIZATION_TIME);
76 } while (!this.chargingStation?.ocppRequestService);
77 }
78 const wait = Utils.getRandomInt(this.chargingStation.stationInfo.AutomaticTransactionGenerator.maxDelayBetweenTwoTransactions,
79 this.chargingStation.stationInfo.AutomaticTransactionGenerator.minDelayBetweenTwoTransactions) * 1000;
80 logger.info(this.logPrefix(connectorId) + ' waiting for ' + Utils.milliSecondsToHHMMSS(wait));
81 await Utils.sleep(wait);
82 const start = Utils.secureRandom();
83 if (start < this.chargingStation.stationInfo.AutomaticTransactionGenerator.probabilityOfStart) {
84 transactionSkip = 0;
85 // Start transaction
86 const startResponse = await this.startTransaction(connectorId);
87 if (startResponse?.idTagInfo?.status !== AuthorizationStatus.ACCEPTED) {
88 logger.warn(this.logPrefix(connectorId) + ' transaction rejected');
89 await Utils.sleep(Constants.CHARGING_STATION_ATG_WAIT_TIME);
90 } else {
91 // Wait until end of transaction
92 const waitTrxEnd = Utils.getRandomInt(this.chargingStation.stationInfo.AutomaticTransactionGenerator.maxDuration,
93 this.chargingStation.stationInfo.AutomaticTransactionGenerator.minDuration) * 1000;
94 logger.info(this.logPrefix(connectorId) + ' transaction ' + this.chargingStation.getConnector(connectorId).transactionId.toString() + ' will stop in ' + Utils.milliSecondsToHHMMSS(waitTrxEnd));
95 await Utils.sleep(waitTrxEnd);
96 // Stop transaction
97 if (this.chargingStation.getConnector(connectorId)?.transactionStarted) {
98 logger.info(this.logPrefix(connectorId) + ' stop transaction ' + this.chargingStation.getConnector(connectorId).transactionId.toString());
99 await this.stopTransaction(connectorId);
100 }
101 }
102 } else {
103 transactionSkip++;
104 totalTransactionSkip++;
105 logger.info(this.logPrefix(connectorId) + ' skipped transaction ' + transactionSkip.toString() + '/' + totalTransactionSkip.toString());
106 }
107 }
108 logger.info(this.logPrefix(connectorId) + ' stopped on connector');
109 }
110
111 private async startTransaction(connectorId: number): Promise<StartTransactionResponse | AuthorizeResponse> {
112 const measureId = 'StartTransaction with ATG';
113 const beginId = PerformanceStatistics.beginMeasure(measureId);
114 let startResponse: StartTransactionResponse;
115 if (this.chargingStation.hasAuthorizedTags()) {
116 const tagId = this.chargingStation.getRandomTagId();
117 if (this.chargingStation.getAutomaticTransactionGeneratorRequireAuthorize()) {
118 // Authorize tagId
119 const authorizeResponse = await this.chargingStation.ocppRequestService.sendAuthorize(connectorId, tagId);
120 if (authorizeResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
121 logger.info(this.logPrefix(connectorId) + ' start transaction for tagID ' + tagId);
122 // Start transaction
123 startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId, tagId);
124 PerformanceStatistics.endMeasure(measureId, beginId);
125 return startResponse;
126 }
127 PerformanceStatistics.endMeasure(measureId, beginId);
128 return authorizeResponse;
129 }
130 logger.info(this.logPrefix(connectorId) + ' start transaction for tagID ' + tagId);
131 // Start transaction
132 startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId, tagId);
133 PerformanceStatistics.endMeasure(measureId, beginId);
134 return startResponse;
135 }
136 logger.info(this.logPrefix(connectorId) + ' start transaction without a tagID');
137 startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId);
138 PerformanceStatistics.endMeasure(measureId, beginId);
139 return startResponse;
140 }
141
142 private async stopTransaction(connectorId: number): Promise<StopTransactionResponse> {
143 const measureId = 'StopTransaction with ATG';
144 const beginId = PerformanceStatistics.beginMeasure(measureId);
145 const transactionId = this.chargingStation.getConnector(connectorId).transactionId;
146 const stopResponse = this.chargingStation.ocppRequestService.sendStopTransaction(transactionId,
147 this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId), this.chargingStation.getTransactionIdTag(transactionId));
148 PerformanceStatistics.endMeasure(measureId, beginId);
149 return stopResponse;
150 }
151
152 private logPrefix(connectorId?: number): string {
153 if (connectorId) {
154 return Utils.logPrefix(' ' + this.chargingStation.stationInfo.chargingStationId + ' | ATG on connector #' + connectorId.toString() + ':');
155 }
156 return Utils.logPrefix(' ' + this.chargingStation.stationInfo.chargingStationId + ' | ATG:');
157 }
158 }