1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import PerformanceStatistics from
'../performance/PerformanceStatistics';
5 AutomaticTransactionGeneratorConfiguration
,
7 } from
'../types/AutomaticTransactionGenerator';
8 import { MeterValuesRequest
, RequestCommand
} from
'../types/ocpp/Requests';
9 import type { MeterValuesResponse
} from
'../types/ocpp/Responses';
14 StartTransactionRequest
,
15 StartTransactionResponse
,
16 StopTransactionReason
,
17 StopTransactionRequest
,
18 StopTransactionResponse
,
19 } from
'../types/ocpp/Transaction';
20 import Constants from
'../utils/Constants';
21 import logger from
'../utils/Logger';
22 import Utils from
'../utils/Utils';
23 import type ChargingStation from
'./ChargingStation';
24 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
26 export default class AutomaticTransactionGenerator
{
27 private static readonly instances
: Map
<string, AutomaticTransactionGenerator
> = new Map
<
29 AutomaticTransactionGenerator
32 public readonly configuration
: AutomaticTransactionGeneratorConfiguration
;
33 public started
: boolean;
34 private readonly chargingStation
: ChargingStation
;
35 private readonly connectorsStatus
: Map
<number, Status
>;
38 automaticTransactionGeneratorConfiguration
: AutomaticTransactionGeneratorConfiguration
,
39 chargingStation
: ChargingStation
41 this.configuration
= automaticTransactionGeneratorConfiguration
;
42 this.chargingStation
= chargingStation
;
43 this.connectorsStatus
= new Map
<number, Status
>();
44 this.stopConnectors();
48 public static getInstance(
49 automaticTransactionGeneratorConfiguration
: AutomaticTransactionGeneratorConfiguration
,
50 chargingStation
: ChargingStation
51 ): AutomaticTransactionGenerator
{
52 if (!AutomaticTransactionGenerator
.instances
.has(chargingStation
.stationInfo
.hashId
)) {
53 AutomaticTransactionGenerator
.instances
.set(
54 chargingStation
.stationInfo
.hashId
,
55 new AutomaticTransactionGenerator(
56 automaticTransactionGeneratorConfiguration
,
61 return AutomaticTransactionGenerator
.instances
.get(chargingStation
.stationInfo
.hashId
);
64 public start(): void {
66 logger
.error(`${this.logPrefix()} trying to start while already started`);
69 this.startConnectors();
75 logger
.error(`${this.logPrefix()} trying to stop while not started`);
78 this.stopConnectors();
82 private startConnectors(): void {
84 this.connectorsStatus
?.size
> 0 &&
85 this.connectorsStatus
.size
!== this.chargingStation
.getNumberOfConnectors()
87 this.connectorsStatus
.clear();
89 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
90 if (connectorId
> 0) {
91 this.startConnector(connectorId
);
96 private stopConnectors(): void {
97 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
98 if (connectorId
> 0) {
99 this.stopConnector(connectorId
);
104 private async internalStartConnector(connectorId
: number): Promise
<void> {
105 this.initializeConnectorStatus(connectorId
);
107 this.logPrefix(connectorId
) +
108 ' started on connector and will run for ' +
109 Utils
.formatDurationMilliSeconds(
110 this.connectorsStatus
.get(connectorId
).stopDate
.getTime() -
111 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
114 while (this.connectorsStatus
.get(connectorId
).start
) {
115 if (new Date() > this.connectorsStatus
.get(connectorId
).stopDate
) {
116 this.stopConnector(connectorId
);
119 if (!this.chargingStation
.isInAcceptedState()) {
121 this.logPrefix(connectorId
) +
122 ' entered in transaction loop while the charging station is not in accepted state'
124 this.stopConnector(connectorId
);
127 if (!this.chargingStation
.isChargingStationAvailable()) {
129 this.logPrefix(connectorId
) +
130 ' entered in transaction loop while the charging station is unavailable'
132 this.stopConnector(connectorId
);
135 if (!this.chargingStation
.isConnectorAvailable(connectorId
)) {
139 )} entered in transaction loop while the connector ${connectorId} is unavailable`
141 this.stopConnector(connectorId
);
144 if (!this.chargingStation
?.ocppRequestService
) {
148 )} transaction loop waiting for charging station service to be initialized`
151 await Utils
.sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
152 } while (!this.chargingStation
?.ocppRequestService
);
155 Utils
.getRandomInteger(
156 this.configuration
.maxDelayBetweenTwoTransactions
,
157 this.configuration
.minDelayBetweenTwoTransactions
160 this.logPrefix(connectorId
) + ' waiting for ' + Utils
.formatDurationMilliSeconds(wait
)
162 await Utils
.sleep(wait
);
163 const start
= Utils
.secureRandom();
164 if (start
< this.configuration
.probabilityOfStart
) {
165 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
167 const startResponse
= await this.startTransaction(connectorId
);
168 this.connectorsStatus
.get(connectorId
).startTransactionRequests
++;
169 if (startResponse
?.idTagInfo
?.status !== AuthorizationStatus
.ACCEPTED
) {
170 logger
.warn(this.logPrefix(connectorId
) + ' start transaction rejected');
171 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
++;
173 // Wait until end of transaction
175 Utils
.getRandomInteger(this.configuration
.maxDuration
, this.configuration
.minDuration
) *
178 this.logPrefix(connectorId
) +
180 this.chargingStation
.getConnectorStatus(connectorId
).transactionId
.toString() +
181 ' started and will stop in ' +
182 Utils
.formatDurationMilliSeconds(waitTrxEnd
)
184 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
++;
185 await Utils
.sleep(waitTrxEnd
);
188 this.logPrefix(connectorId
) +
189 ' stop transaction ' +
190 this.chargingStation
.getConnectorStatus(connectorId
).transactionId
.toString()
192 await this.stopTransaction(connectorId
);
195 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
++;
196 this.connectorsStatus
.get(connectorId
).skippedTransactions
++;
198 this.logPrefix(connectorId
) +
199 ' skipped consecutively ' +
200 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
.toString() +
202 this.connectorsStatus
.get(connectorId
).skippedTransactions
.toString() +
206 this.connectorsStatus
.get(connectorId
).lastRunDate
= new Date();
208 await this.stopTransaction(connectorId
);
209 this.connectorsStatus
.get(connectorId
).stoppedDate
= new Date();
211 this.logPrefix(connectorId
) +
212 ' stopped on connector and lasted for ' +
213 Utils
.formatDurationMilliSeconds(
214 this.connectorsStatus
.get(connectorId
).stoppedDate
.getTime() -
215 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
219 `${this.logPrefix(connectorId)} connector status: %j`,
220 this.connectorsStatus
.get(connectorId
)
224 private startConnector(connectorId
: number): void {
225 // Avoid hogging the event loop with a busy loop
227 this.internalStartConnector(connectorId
).catch(() => {
228 /* This is intentional */
233 private stopConnector(connectorId
: number): void {
234 this.connectorsStatus
.set(connectorId
, {
235 ...this.connectorsStatus
.get(connectorId
),
240 private initializeConnectorStatus(connectorId
: number): void {
241 this.connectorsStatus
.get(connectorId
).authorizeRequests
=
242 this?.connectorsStatus
.get(connectorId
)?.authorizeRequests
?? 0;
243 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
=
244 this?.connectorsStatus
.get(connectorId
)?.acceptedAuthorizeRequests
?? 0;
245 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
=
246 this?.connectorsStatus
.get(connectorId
)?.rejectedAuthorizeRequests
?? 0;
247 this.connectorsStatus
.get(connectorId
).startTransactionRequests
=
248 this?.connectorsStatus
.get(connectorId
)?.startTransactionRequests
?? 0;
249 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
=
250 this?.connectorsStatus
.get(connectorId
)?.acceptedStartTransactionRequests
?? 0;
251 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
=
252 this?.connectorsStatus
.get(connectorId
)?.rejectedStartTransactionRequests
?? 0;
253 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
=
254 this?.connectorsStatus
.get(connectorId
)?.stopTransactionRequests
?? 0;
255 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
256 this.connectorsStatus
.get(connectorId
).skippedTransactions
=
257 this?.connectorsStatus
.get(connectorId
)?.skippedTransactions
?? 0;
258 const previousRunDuration
=
259 this?.connectorsStatus
.get(connectorId
)?.startDate
&&
260 this?.connectorsStatus
.get(connectorId
)?.lastRunDate
261 ? this.connectorsStatus
.get(connectorId
).lastRunDate
.getTime() -
262 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
264 this.connectorsStatus
.get(connectorId
).startDate
= new Date();
265 this.connectorsStatus
.get(connectorId
).stopDate
= new Date(
266 this.connectorsStatus
.get(connectorId
).startDate
.getTime() +
267 (this.configuration
.stopAfterHours
??
268 Constants
.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS
) *
273 this.connectorsStatus
.get(connectorId
).start
= true;
276 private async startTransaction(
278 ): Promise
<StartTransactionResponse
| AuthorizeResponse
> {
279 const measureId
= 'StartTransaction with ATG';
280 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
281 let startResponse
: StartTransactionResponse
;
282 if (this.chargingStation
.hasAuthorizedTags()) {
283 const idTag
= this.chargingStation
.getRandomIdTag();
284 const startTransactionLogMsg
= `${this.logPrefix(
286 )} start transaction for idTag '${idTag}'`;
287 if (this.getRequireAuthorize()) {
288 this.chargingStation
.getConnectorStatus(connectorId
).authorizeIdTag
= idTag
;
290 const authorizeResponse
: AuthorizeResponse
=
291 await this.chargingStation
.ocppRequestService
.requestHandler
<
294 >(this.chargingStation
, RequestCommand
.AUTHORIZE
, {
297 this.connectorsStatus
.get(connectorId
).authorizeRequests
++;
298 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
299 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
++;
300 logger
.info(startTransactionLogMsg
);
302 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
303 StartTransactionRequest
,
304 StartTransactionResponse
305 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
309 PerformanceStatistics
.endMeasure(measureId
, beginId
);
310 return startResponse
;
312 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
++;
313 PerformanceStatistics
.endMeasure(measureId
, beginId
);
314 return authorizeResponse
;
316 logger
.info(startTransactionLogMsg
);
318 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
319 StartTransactionRequest
,
320 StartTransactionResponse
321 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
325 PerformanceStatistics
.endMeasure(measureId
, beginId
);
326 return startResponse
;
328 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
329 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
330 StartTransactionRequest
,
331 StartTransactionResponse
332 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
333 PerformanceStatistics
.endMeasure(measureId
, beginId
);
334 return startResponse
;
337 private async stopTransaction(
339 reason
: StopTransactionReason
= StopTransactionReason
.NONE
340 ): Promise
<StopTransactionResponse
> {
341 const measureId
= 'StopTransaction with ATG';
342 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
343 let transactionId
= 0;
344 let stopResponse
: StopTransactionResponse
;
345 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
) {
346 transactionId
= this.chargingStation
.getConnectorStatus(connectorId
).transactionId
;
348 this.chargingStation
.getBeginEndMeterValues() &&
349 this.chargingStation
.getOcppStrictCompliance() &&
350 !this.chargingStation
.getOutOfOrderEndMeterValues()
352 // FIXME: Implement OCPP version agnostic helpers
353 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
354 this.chargingStation
,
356 this.chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
)
358 await this.chargingStation
.ocppRequestService
.requestHandler
<
361 >(this.chargingStation
, RequestCommand
.METER_VALUES
, {
364 meterValue
: [transactionEndMeterValue
],
367 stopResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
368 StopTransactionRequest
,
369 StopTransactionResponse
370 >(this.chargingStation
, RequestCommand
.STOP_TRANSACTION
, {
372 meterStop
: this.chargingStation
.getEnergyActiveImportRegisterByTransactionId(
376 idTag
: this.chargingStation
.getTransactionIdTag(transactionId
),
379 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
++;
382 `${this.logPrefix(connectorId)} trying to stop a not started transaction${
383 transactionId ? ' ' + transactionId.toString() : ''
387 PerformanceStatistics
.endMeasure(measureId
, beginId
);
391 private getRequireAuthorize(): boolean {
392 return this.configuration
?.requireAuthorize
?? true;
395 private logPrefix(connectorId
?: number): string {
396 return Utils
.logPrefix(
397 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
398 connectorId && ` on connector #${connectorId.toString()}
`