UI Server: Add support for starting the ATG on defined connectors
[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';
8import { MeterValuesRequest, RequestCommand } from '../types/ocpp/Requests';
6c1761d4 9import type { MeterValuesResponse } from '../types/ocpp/Responses';
e7aeea18
JB
10import {
11 AuthorizationStatus,
ef6fa3fb 12 AuthorizeRequest,
e7aeea18 13 AuthorizeResponse,
ef6fa3fb 14 StartTransactionRequest,
e7aeea18
JB
15 StartTransactionResponse,
16 StopTransactionReason,
ef6fa3fb 17 StopTransactionRequest,
e7aeea18
JB
18 StopTransactionResponse,
19} from '../types/ocpp/Transaction';
6af9012e 20import Constants from '../utils/Constants';
9f2e3130 21import logger from '../utils/Logger';
8114d10e
JB
22import Utils from '../utils/Utils';
23import type ChargingStation from './ChargingStation';
24import { OCPP16ServiceUtils } from './ocpp/1.6/OCPP16ServiceUtils';
6af9012e
JB
25
26export default class AutomaticTransactionGenerator {
e7aeea18
JB
27 private static readonly instances: Map<string, AutomaticTransactionGenerator> = new Map<
28 string,
29 AutomaticTransactionGenerator
30 >();
10068088 31
fa7bccf4 32 public readonly configuration: AutomaticTransactionGeneratorConfiguration;
265e4266 33 public started: boolean;
9e23580d
JB
34 private readonly chargingStation: ChargingStation;
35 private readonly connectorsStatus: Map<number, Status>;
6af9012e 36
fa7bccf4
JB
37 private constructor(
38 automaticTransactionGeneratorConfiguration: AutomaticTransactionGeneratorConfiguration,
39 chargingStation: ChargingStation
40 ) {
41 this.configuration = automaticTransactionGeneratorConfiguration;
ad2f27c3 42 this.chargingStation = chargingStation;
9664ec50 43 this.connectorsStatus = new Map<number, Status>();
72740232 44 this.stopConnectors();
265e4266 45 this.started = false;
6af9012e
JB
46 }
47
fa7bccf4
JB
48 public static getInstance(
49 automaticTransactionGeneratorConfiguration: AutomaticTransactionGeneratorConfiguration,
50 chargingStation: ChargingStation
51 ): AutomaticTransactionGenerator {
51c83d6f 52 if (!AutomaticTransactionGenerator.instances.has(chargingStation.stationInfo.hashId)) {
e7aeea18 53 AutomaticTransactionGenerator.instances.set(
51c83d6f 54 chargingStation.stationInfo.hashId,
fa7bccf4
JB
55 new AutomaticTransactionGenerator(
56 automaticTransactionGeneratorConfiguration,
57 chargingStation
58 )
e7aeea18 59 );
73b9adec 60 }
51c83d6f 61 return AutomaticTransactionGenerator.instances.get(chargingStation.stationInfo.hashId);
73b9adec
JB
62 }
63
7d75bee1 64 public start(): void {
a5e9befc
JB
65 if (this.started === true) {
66 logger.warn(`${this.logPrefix()} trying to start while already started`);
b809adf1
JB
67 return;
68 }
72740232 69 this.startConnectors();
265e4266 70 this.started = true;
6af9012e
JB
71 }
72
0045cef5 73 public stop(): void {
a5e9befc
JB
74 if (this.started === false) {
75 logger.warn(`${this.logPrefix()} trying to stop while not started`);
265e4266
JB
76 return;
77 }
72740232 78 this.stopConnectors();
265e4266 79 this.started = false;
6af9012e
JB
80 }
81
a5e9befc
JB
82 public startConnector(connectorId: number): void {
83 if (this.connectorsStatus.has(connectorId) === false) {
84 logger.warn(`${this.logPrefix(connectorId)} trying to start on non existing connector`);
85 return;
86 }
87 if (this.connectorsStatus.get(connectorId)?.start === false) {
88 // Avoid hogging the event loop with a busy loop
89 setImmediate(() => {
90 this.internalStartConnector(connectorId).catch(() => {
91 /* This is intentional */
92 });
93 });
94 } else {
95 logger.warn(`${this.logPrefix(connectorId)} already started on connector`);
96 }
97 }
98
99 public stopConnector(connectorId: number): void {
100 this.connectorsStatus.set(connectorId, {
101 ...this.connectorsStatus.get(connectorId),
102 start: false,
103 });
104 }
105
72740232 106 private startConnectors(): void {
e7aeea18
JB
107 if (
108 this.connectorsStatus?.size > 0 &&
109 this.connectorsStatus.size !== this.chargingStation.getNumberOfConnectors()
110 ) {
54544ef1
JB
111 this.connectorsStatus.clear();
112 }
734d790d 113 for (const connectorId of this.chargingStation.connectors.keys()) {
72740232 114 if (connectorId > 0) {
83a3286a 115 this.startConnector(connectorId);
72740232
JB
116 }
117 }
118 }
119
120 private stopConnectors(): void {
734d790d 121 for (const connectorId of this.chargingStation.connectors.keys()) {
72740232
JB
122 if (connectorId > 0) {
123 this.stopConnector(connectorId);
124 }
125 }
126 }
127
83a3286a 128 private async internalStartConnector(connectorId: number): Promise<void> {
6cd85def 129 this.initializeConnectorStatus(connectorId);
e7aeea18
JB
130 logger.info(
131 this.logPrefix(connectorId) +
132 ' started on connector and will run for ' +
133 Utils.formatDurationMilliSeconds(
134 this.connectorsStatus.get(connectorId).stopDate.getTime() -
135 this.connectorsStatus.get(connectorId).startDate.getTime()
136 )
137 );
a5e9befc 138 while (this.connectorsStatus.get(connectorId).start === true) {
e7aeea18 139 if (new Date() > this.connectorsStatus.get(connectorId).stopDate) {
9664ec50 140 this.stopConnector(connectorId);
17991e8c
JB
141 break;
142 }
16cd35ad 143 if (!this.chargingStation.isInAcceptedState()) {
e7aeea18
JB
144 logger.error(
145 this.logPrefix(connectorId) +
146 ' entered in transaction loop while the charging station is not in accepted state'
147 );
9664ec50 148 this.stopConnector(connectorId);
17991e8c
JB
149 break;
150 }
c0560973 151 if (!this.chargingStation.isChargingStationAvailable()) {
e7aeea18
JB
152 logger.info(
153 this.logPrefix(connectorId) +
154 ' entered in transaction loop while the charging station is unavailable'
155 );
9664ec50 156 this.stopConnector(connectorId);
ab5f4b03
JB
157 break;
158 }
c0560973 159 if (!this.chargingStation.isConnectorAvailable(connectorId)) {
e7aeea18
JB
160 logger.info(
161 `${this.logPrefix(
162 connectorId
163 )} entered in transaction loop while the connector ${connectorId} is unavailable`
164 );
9c7195b2 165 this.stopConnector(connectorId);
17991e8c
JB
166 break;
167 }
c0560973 168 if (!this.chargingStation?.ocppRequestService) {
e7aeea18
JB
169 logger.info(
170 `${this.logPrefix(
171 connectorId
172 )} transaction loop waiting for charging station service to be initialized`
173 );
c0560973 174 do {
a4cc42ea 175 await Utils.sleep(Constants.CHARGING_STATION_ATG_INITIALIZATION_TIME);
c0560973
JB
176 } while (!this.chargingStation?.ocppRequestService);
177 }
e7aeea18
JB
178 const wait =
179 Utils.getRandomInteger(
fa7bccf4
JB
180 this.configuration.maxDelayBetweenTwoTransactions,
181 this.configuration.minDelayBetweenTwoTransactions
e7aeea18
JB
182 ) * 1000;
183 logger.info(
184 this.logPrefix(connectorId) + ' waiting for ' + Utils.formatDurationMilliSeconds(wait)
185 );
6af9012e 186 await Utils.sleep(wait);
c37528f1 187 const start = Utils.secureRandom();
fa7bccf4 188 if (start < this.configuration.probabilityOfStart) {
9664ec50 189 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0;
6af9012e 190 // Start transaction
aef1b33a 191 const startResponse = await this.startTransaction(connectorId);
071a9315 192 this.connectorsStatus.get(connectorId).startTransactionRequests++;
ef6076c1 193 if (startResponse?.idTagInfo?.status !== AuthorizationStatus.ACCEPTED) {
9f2e3130 194 logger.warn(this.logPrefix(connectorId) + ' start transaction rejected');
071a9315 195 this.connectorsStatus.get(connectorId).rejectedStartTransactionRequests++;
6af9012e
JB
196 } else {
197 // Wait until end of transaction
e7aeea18 198 const waitTrxEnd =
fa7bccf4
JB
199 Utils.getRandomInteger(this.configuration.maxDuration, this.configuration.minDuration) *
200 1000;
e7aeea18
JB
201 logger.info(
202 this.logPrefix(connectorId) +
203 ' transaction ' +
204 this.chargingStation.getConnectorStatus(connectorId).transactionId.toString() +
205 ' started and will stop in ' +
206 Utils.formatDurationMilliSeconds(waitTrxEnd)
207 );
071a9315 208 this.connectorsStatus.get(connectorId).acceptedStartTransactionRequests++;
6af9012e
JB
209 await Utils.sleep(waitTrxEnd);
210 // Stop transaction
e7aeea18
JB
211 logger.info(
212 this.logPrefix(connectorId) +
213 ' stop transaction ' +
214 this.chargingStation.getConnectorStatus(connectorId).transactionId.toString()
215 );
85d20667 216 await this.stopTransaction(connectorId);
6af9012e
JB
217 }
218 } else {
9664ec50
JB
219 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions++;
220 this.connectorsStatus.get(connectorId).skippedTransactions++;
e7aeea18
JB
221 logger.info(
222 this.logPrefix(connectorId) +
223 ' skipped consecutively ' +
224 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions.toString() +
225 '/' +
226 this.connectorsStatus.get(connectorId).skippedTransactions.toString() +
227 ' transaction(s)'
228 );
6af9012e 229 }
9664ec50 230 this.connectorsStatus.get(connectorId).lastRunDate = new Date();
7d75bee1 231 }
0045cef5 232 await this.stopTransaction(connectorId);
9664ec50 233 this.connectorsStatus.get(connectorId).stoppedDate = new Date();
e7aeea18
JB
234 logger.info(
235 this.logPrefix(connectorId) +
236 ' stopped on connector and lasted for ' +
237 Utils.formatDurationMilliSeconds(
238 this.connectorsStatus.get(connectorId).stoppedDate.getTime() -
239 this.connectorsStatus.get(connectorId).startDate.getTime()
240 )
241 );
242 logger.debug(
be9ee554 243 `${this.logPrefix(connectorId)} connector status: %j`,
e7aeea18
JB
244 this.connectorsStatus.get(connectorId)
245 );
6af9012e
JB
246 }
247
6cd85def 248 private initializeConnectorStatus(connectorId: number): void {
e7aeea18
JB
249 this.connectorsStatus.get(connectorId).authorizeRequests =
250 this?.connectorsStatus.get(connectorId)?.authorizeRequests ?? 0;
251 this.connectorsStatus.get(connectorId).acceptedAuthorizeRequests =
252 this?.connectorsStatus.get(connectorId)?.acceptedAuthorizeRequests ?? 0;
253 this.connectorsStatus.get(connectorId).rejectedAuthorizeRequests =
254 this?.connectorsStatus.get(connectorId)?.rejectedAuthorizeRequests ?? 0;
255 this.connectorsStatus.get(connectorId).startTransactionRequests =
256 this?.connectorsStatus.get(connectorId)?.startTransactionRequests ?? 0;
257 this.connectorsStatus.get(connectorId).acceptedStartTransactionRequests =
258 this?.connectorsStatus.get(connectorId)?.acceptedStartTransactionRequests ?? 0;
259 this.connectorsStatus.get(connectorId).rejectedStartTransactionRequests =
260 this?.connectorsStatus.get(connectorId)?.rejectedStartTransactionRequests ?? 0;
261 this.connectorsStatus.get(connectorId).stopTransactionRequests =
262 this?.connectorsStatus.get(connectorId)?.stopTransactionRequests ?? 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,
347 reason: StopTransactionReason = StopTransactionReason.NONE
348 ): Promise<StopTransactionResponse> {
aef1b33a
JB
349 const measureId = 'StopTransaction with ATG';
350 const beginId = PerformanceStatistics.beginMeasure(measureId);
8eb02b62 351 let transactionId = 0;
0045cef5 352 let stopResponse: StopTransactionResponse;
734d790d
JB
353 if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted) {
354 transactionId = this.chargingStation.getConnectorStatus(connectorId).transactionId;
68c993d5
JB
355 if (
356 this.chargingStation.getBeginEndMeterValues() &&
357 this.chargingStation.getOcppStrictCompliance() &&
358 !this.chargingStation.getOutOfOrderEndMeterValues()
359 ) {
360 // FIXME: Implement OCPP version agnostic helpers
361 const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue(
362 this.chargingStation,
363 connectorId,
364 this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId)
365 );
f7f98c68 366 await this.chargingStation.ocppRequestService.requestHandler<
ef6fa3fb
JB
367 MeterValuesRequest,
368 MeterValuesResponse
08f130a0 369 >(this.chargingStation, RequestCommand.METER_VALUES, {
ef6fa3fb
JB
370 connectorId,
371 transactionId,
7369e417 372 meterValue: [transactionEndMeterValue],
ef6fa3fb 373 });
68c993d5 374 }
f7f98c68 375 stopResponse = await this.chargingStation.ocppRequestService.requestHandler<
ef6fa3fb
JB
376 StopTransactionRequest,
377 StopTransactionResponse
08f130a0 378 >(this.chargingStation, RequestCommand.STOP_TRANSACTION, {
ef6fa3fb 379 transactionId,
07989fad
JB
380 meterStop: this.chargingStation.getEnergyActiveImportRegisterByTransactionId(
381 transactionId,
382 true
383 ),
ef6fa3fb
JB
384 idTag: this.chargingStation.getTransactionIdTag(transactionId),
385 reason,
386 });
071a9315 387 this.connectorsStatus.get(connectorId).stopTransactionRequests++;
0045cef5 388 } else {
e7aeea18
JB
389 logger.warn(
390 `${this.logPrefix(connectorId)} trying to stop a not started transaction${
391 transactionId ? ' ' + transactionId.toString() : ''
392 }`
393 );
0045cef5 394 }
aef1b33a
JB
395 PerformanceStatistics.endMeasure(measureId, beginId);
396 return stopResponse;
c0560973
JB
397 }
398
ccb1d6e9 399 private getRequireAuthorize(): boolean {
fa7bccf4 400 return this.configuration?.requireAuthorize ?? true;
ccb1d6e9
JB
401 }
402
6e0964c8 403 private logPrefix(connectorId?: number): string {
6cd85def
JB
404 return Utils.logPrefix(
405 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
a5e9befc 406 connectorId !== undefined ? ` on connector #${connectorId.toString()}` : ''
6cd85def
JB
407 }:`
408 );
6af9012e
JB
409 }
410}