Push down at the connector level ATG states
[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 { Status } from '../types/AutomaticTransactionGenerator';
9 import Utils from '../utils/Utils';
10 import logger from '../utils/Logger';
11
12 export default class AutomaticTransactionGenerator {
13 public started: boolean;
14 private chargingStation: ChargingStation;
15 private connectorsStatus: Map<number, Status>;
16
17 constructor(chargingStation: ChargingStation) {
18 this.chargingStation = chargingStation;
19 this.connectorsStatus = new Map<number, Status>();
20 this.stopConnectors();
21 this.started = false;
22 }
23
24 public start(): void {
25 if (this.started) {
26 logger.error(`${this.logPrefix()} trying to start while already started`);
27 return;
28 }
29 this.startConnectors();
30 this.started = true;
31 }
32
33 public stop(): void {
34 if (!this.started) {
35 logger.error(`${this.logPrefix()} trying to stop while not started`);
36 return;
37 }
38 this.stopConnectors();
39 this.started = false;
40 }
41
42 private startConnectors(): void {
43 for (const connector in this.chargingStation.connectors) {
44 const connectorId = Utils.convertToInt(connector);
45 if (connectorId > 0) {
46 // Avoid hogging the event loop with a busy loop
47 setImmediate(() => {
48 this.startConnector(connectorId).catch(() => { /* This is intentional */ });
49 });
50 }
51 }
52 }
53
54 private stopConnectors(): void {
55 for (const connector in this.chargingStation.connectors) {
56 const connectorId = Utils.convertToInt(connector);
57 if (connectorId > 0) {
58 this.stopConnector(connectorId);
59 }
60 }
61 }
62
63 private async startConnector(connectorId: number): Promise<void> {
64 this.initStartConnectorStatus(connectorId);
65 logger.info(this.logPrefix(connectorId) + ' started on connector and will run for ' + Utils.formatDurationMilliSeconds(this.connectorsStatus.get(connectorId).stopDate.getTime() - this.connectorsStatus.get(connectorId).startDate.getTime()));
66 while (this.connectorsStatus.get(connectorId).start) {
67 if ((new Date()) > this.connectorsStatus.get(connectorId).stopDate) {
68 this.stopConnector(connectorId);
69 break;
70 }
71 if (!this.chargingStation.isRegistered()) {
72 logger.error(this.logPrefix(connectorId) + ' entered in transaction loop while the charging station is not registered');
73 this.stopConnector(connectorId);
74 break;
75 }
76 if (!this.chargingStation.isChargingStationAvailable()) {
77 logger.info(this.logPrefix(connectorId) + ' entered in transaction loop while the charging station is unavailable');
78 this.stopConnector(connectorId);
79 break;
80 }
81 if (!this.chargingStation.isConnectorAvailable(connectorId)) {
82 logger.info(`${this.logPrefix(connectorId)} entered in transaction loop while the connector ${connectorId} is unavailable`);
83 this.stopConnector(connectorId);
84 break;
85 }
86 if (!this.chargingStation?.ocppRequestService) {
87 logger.info(`${this.logPrefix(connectorId)} transaction loop waiting for charging station service to be initialized`);
88 do {
89 await Utils.sleep(Constants.CHARGING_STATION_ATG_INITIALIZATION_TIME);
90 } while (!this.chargingStation?.ocppRequestService);
91 }
92 const wait = Utils.getRandomInteger(this.chargingStation.stationInfo.AutomaticTransactionGenerator.maxDelayBetweenTwoTransactions,
93 this.chargingStation.stationInfo.AutomaticTransactionGenerator.minDelayBetweenTwoTransactions) * 1000;
94 logger.info(this.logPrefix(connectorId) + ' waiting for ' + Utils.formatDurationMilliSeconds(wait));
95 await Utils.sleep(wait);
96 const start = Utils.secureRandom();
97 if (start < this.chargingStation.stationInfo.AutomaticTransactionGenerator.probabilityOfStart) {
98 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0;
99 // Start transaction
100 const startResponse = await this.startTransaction(connectorId);
101 if (startResponse?.idTagInfo?.status !== AuthorizationStatus.ACCEPTED) {
102 logger.warn(this.logPrefix(connectorId) + ' start transaction rejected');
103 await Utils.sleep(Constants.CHARGING_STATION_ATG_WAIT_TIME);
104 } else {
105 // Wait until end of transaction
106 const waitTrxEnd = Utils.getRandomInteger(this.chargingStation.stationInfo.AutomaticTransactionGenerator.maxDuration,
107 this.chargingStation.stationInfo.AutomaticTransactionGenerator.minDuration) * 1000;
108 logger.info(this.logPrefix(connectorId) + ' transaction ' + this.chargingStation.getConnector(connectorId).transactionId.toString() + ' started and will stop in ' + Utils.formatDurationMilliSeconds(waitTrxEnd));
109 await Utils.sleep(waitTrxEnd);
110 // Stop transaction
111 logger.info(this.logPrefix(connectorId) + ' stop transaction ' + this.chargingStation.getConnector(connectorId).transactionId.toString());
112 await this.stopTransaction(connectorId);
113 }
114 } else {
115 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions++;
116 this.connectorsStatus.get(connectorId).skippedTransactions++;
117 logger.info(this.logPrefix(connectorId) + ' skipped consecutively ' + this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions.toString() + '/' + this.connectorsStatus.get(connectorId).skippedTransactions.toString() + ' transaction(s)');
118 }
119 this.connectorsStatus.get(connectorId).lastRunDate = new Date();
120 }
121 await this.stopTransaction(connectorId);
122 this.connectorsStatus.get(connectorId).stoppedDate = new Date();
123 logger.info(this.logPrefix(connectorId) + ' stopped on connector and lasted for ' + Utils.formatDurationMilliSeconds(this.connectorsStatus.get(connectorId).stoppedDate.getTime() - this.connectorsStatus.get(connectorId).startDate.getTime()));
124 logger.debug(`${this.logPrefix(connectorId)} connector status %j`, this.connectorsStatus.get(connectorId));
125 }
126
127 private stopConnector(connectorId: number): void {
128 this.connectorsStatus.set(connectorId, { start: false });
129 }
130
131 private initStartConnectorStatus(connectorId: number): void {
132 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0;
133 this.connectorsStatus.get(connectorId).skippedTransactions = 0;
134 const previousRunDuration = (this?.connectorsStatus.get(connectorId)?.startDate && this?.connectorsStatus.get(connectorId)?.lastRunDate)
135 ? (this.connectorsStatus.get(connectorId).lastRunDate.getTime() - this.connectorsStatus.get(connectorId).startDate.getTime())
136 : 0;
137 this.connectorsStatus.get(connectorId).startDate = new Date();
138 this.connectorsStatus.get(connectorId).stopDate = new Date(this.connectorsStatus.get(connectorId).startDate.getTime()
139 + (this.chargingStation.stationInfo?.AutomaticTransactionGenerator?.stopAfterHours ?? Constants.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS) * 3600 * 1000
140 - previousRunDuration);
141 this.connectorsStatus.get(connectorId).start = true;
142 }
143
144 private async startTransaction(connectorId: number): Promise<StartTransactionResponse | AuthorizeResponse> {
145 const measureId = 'StartTransaction with ATG';
146 const beginId = PerformanceStatistics.beginMeasure(measureId);
147 let startResponse: StartTransactionResponse;
148 if (this.chargingStation.hasAuthorizedTags()) {
149 const idTag = this.chargingStation.getRandomIdTag();
150 if (this.chargingStation.getAutomaticTransactionGeneratorRequireAuthorize()) {
151 // Authorize idTag
152 const authorizeResponse = await this.chargingStation.ocppRequestService.sendAuthorize(connectorId, idTag);
153 if (authorizeResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
154 logger.info(this.logPrefix(connectorId) + ' start transaction for idTag ' + idTag);
155 // Start transaction
156 startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId, idTag);
157 PerformanceStatistics.endMeasure(measureId, beginId);
158 return startResponse;
159 }
160 PerformanceStatistics.endMeasure(measureId, beginId);
161 return authorizeResponse;
162 }
163 logger.info(this.logPrefix(connectorId) + ' start transaction for idTag ' + idTag);
164 // Start transaction
165 startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId, idTag);
166 PerformanceStatistics.endMeasure(measureId, beginId);
167 return startResponse;
168 }
169 logger.info(this.logPrefix(connectorId) + ' start transaction without an idTag');
170 startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId);
171 PerformanceStatistics.endMeasure(measureId, beginId);
172 return startResponse;
173 }
174
175 private async stopTransaction(connectorId: number, reason: StopTransactionReason = StopTransactionReason.NONE): Promise<StopTransactionResponse> {
176 const measureId = 'StopTransaction with ATG';
177 const beginId = PerformanceStatistics.beginMeasure(measureId);
178 let transactionId = 0;
179 let stopResponse: StopTransactionResponse;
180 if (this.chargingStation.getConnector(connectorId)?.transactionStarted) {
181 transactionId = this.chargingStation.getConnector(connectorId).transactionId;
182 stopResponse = await this.chargingStation.ocppRequestService.sendStopTransaction(transactionId,
183 this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId),
184 this.chargingStation.getTransactionIdTag(transactionId),
185 reason);
186 } else {
187 logger.warn(`${this.logPrefix(connectorId)} trying to stop a not started transaction${transactionId ? ' ' + transactionId.toString() : ''}`);
188 }
189 PerformanceStatistics.endMeasure(measureId, beginId);
190 return stopResponse;
191 }
192
193 private logPrefix(connectorId?: number): string {
194 if (connectorId) {
195 return Utils.logPrefix(' ' + this.chargingStation.stationInfo.chargingStationId + ' | ATG on connector #' + connectorId.toString() + ':');
196 }
197 return Utils.logPrefix(' ' + this.chargingStation.stationInfo.chargingStationId + ' | ATG:');
198 }
199 }