forked from matth-x/MicroOcpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnector.cpp
More file actions
834 lines (681 loc) · 31.5 KB
/
Copy pathConnector.cpp
File metadata and controls
834 lines (681 loc) · 31.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
// matth-x/ArduinoOcpp
// Copyright Matthias Akstaller 2019 - 2023
// MIT License
#include <ArduinoOcpp/Model/ChargeControl/Connector.h>
#include <ArduinoOcpp/Core/Context.h>
#include <ArduinoOcpp/Model/Model.h>
#include <ArduinoOcpp/Core/Request.h>
#include <ArduinoOcpp/Model/Transactions/TransactionStore.h>
#include <ArduinoOcpp/Core/Configuration.h>
#include <ArduinoOcpp/Operations/Authorize.h>
#include <ArduinoOcpp/Operations/StatusNotification.h>
#include <ArduinoOcpp/Operations/StartTransaction.h>
#include <ArduinoOcpp/Operations/StopTransaction.h>
#include <ArduinoOcpp/Operations/CiStrings.h>
#include <ArduinoOcpp/Debug.h>
#include <ArduinoOcpp/Model/Metering/MeteringService.h>
#include <ArduinoOcpp/Model/Reservation/ReservationService.h>
#include <ArduinoOcpp/Model/Authorization/AuthorizationService.h>
#include <ArduinoOcpp/Core/SimpleRequestFactory.h>
using namespace ArduinoOcpp;
using namespace ArduinoOcpp::Ocpp16;
Connector::Connector(Context& context, int connectorId)
: context(context), model(context.getModel()), connectorId{connectorId} {
char availabilityKey [CONF_KEYLEN_MAX + 1] = {'\0'};
snprintf(availabilityKey, CONF_KEYLEN_MAX + 1, "AO_AVAIL_CONN_%d", connectorId);
availability = declareConfiguration<bool>(availabilityKey, true, AO_KEYVALUE_FN, false, false, true, false);
connectionTimeOut = declareConfiguration<int>("ConnectionTimeOut", 30, CONFIGURATION_FN, true, true, true, false);
minimumStatusDuration = declareConfiguration<int>("MinimumStatusDuration", 0, CONFIGURATION_FN, true, true, true, false);
stopTransactionOnInvalidId = declareConfiguration<bool>("StopTransactionOnInvalidId", true, CONFIGURATION_FN, true, true, true, false);
stopTransactionOnEVSideDisconnect = declareConfiguration<bool>("StopTransactionOnEVSideDisconnect", true, CONFIGURATION_FN, true, true, true, false);
unlockConnectorOnEVSideDisconnect = declareConfiguration<bool>("UnlockConnectorOnEVSideDisconnect", true, CONFIGURATION_FN, true, true, true, false);
localPreAuthorize = declareConfiguration<bool>("LocalPreAuthorize", false, CONFIGURATION_FN, true, true, true, false);
allowOfflineTxForUnknownId = ArduinoOcpp::declareConfiguration<bool>("AllowOfflineTxForUnknownId", false, CONFIGURATION_FN);
//if the EVSE goes offline, can it continue to charge without sending StartTx / StopTx to the server when going online again?
silentOfflineTransactions = declareConfiguration<bool>("AO_SilentOfflineTransactions", false, CONFIGURATION_FN, true, true, true, false);
//how long the EVSE tries the Authorize request before it enters offline mode
authorizationTimeout = ArduinoOcpp::declareConfiguration<int>("AO_AuthorizationTimeout", 20, CONFIGURATION_FN);
//FreeVend mode
freeVendActive = declareConfiguration<bool>("AO_FreeVendActive", false, CONFIGURATION_FN, true, true, true, false);
freeVendIdTag = declareConfiguration<const char*>("AO_FreeVendIdTag", "", CONFIGURATION_FN, true, true, true, false);
if (!availability) {
AO_DBG_ERR("Cannot declare availability");
}
if (model.getTransactionStore()) {
transaction = model.getTransactionStore()->getLatestTransaction(connectorId);
} else {
AO_DBG_ERR("must initialize TxStore before Connector");
(void)0;
}
}
ChargePointStatus Connector::getStatus() {
/*
* Handle special case: This is the Connector for the whole CP (i.e. connectorId=0) --> only states Available, Unavailable, Faulted are possible
*/
if (connectorId == 0) {
if (isFaulted()) {
return ChargePointStatus::Faulted;
} else if (!isOperative()) {
return ChargePointStatus::Unavailable;
} else {
return ChargePointStatus::Available;
}
}
if (isFaulted()) {
return ChargePointStatus::Faulted;
} else if (!isOperative()) {
return ChargePointStatus::Unavailable;
} else if (transaction && transaction->isRunning()) {
//Transaction is currently running
if (connectorPluggedInput && !connectorPluggedInput()) { //special case when StopTransactionOnEVSideDisconnect is false
return ChargePointStatus::SuspendedEV;
}
if (!ocppPermitsCharge() ||
(evseReadyInput && !evseReadyInput())) {
return ChargePointStatus::SuspendedEVSE;
}
if (evReadyInput && !evReadyInput()) {
return ChargePointStatus::SuspendedEV;
}
return ChargePointStatus::Charging;
} else if (model.getReservationService() && model.getReservationService()->getReservation(connectorId)) {
return ChargePointStatus::Reserved;
} else if ((!transaction || !transaction->isActive()) && //no transaction preparation
(!connectorPluggedInput || !connectorPluggedInput()) && //no vehicle plugged
(!occupiedInput || !occupiedInput())) { //occupied override clear
return ChargePointStatus::Available;
} else {
/*
* Either in Preparing or Finishing state. Only way to know is from previous state
*/
const auto previous = currentStatus;
if (previous == ChargePointStatus::Finishing ||
previous == ChargePointStatus::Charging ||
previous == ChargePointStatus::SuspendedEV ||
previous == ChargePointStatus::SuspendedEVSE) {
return ChargePointStatus::Finishing;
} else {
return ChargePointStatus::Preparing;
}
}
AO_DBG_DEBUG("status undefined");
return ChargePointStatus::Faulted; //internal error
}
bool Connector::ocppPermitsCharge() {
if (connectorId == 0) {
AO_DBG_WARN("not supported for connectorId == 0");
return false;
}
bool suspendDeAuthorizedIdTag = transaction && transaction->isIdTagDeauthorized(); //if idTag status is "DeAuthorized" and if charging should stop
//check special case for DeAuthorized idTags: FreeVend mode
if (suspendDeAuthorizedIdTag && freeVendActive && *freeVendActive) {
suspendDeAuthorizedIdTag = false;
}
return transaction &&
transaction->isRunning() &&
transaction->isActive() &&
!isFaulted() &&
!suspendDeAuthorizedIdTag;
}
void Connector::loop() {
if (!trackLoopExecute) {
trackLoopExecute = true;
}
if (transaction && transaction->isAborted()) {
//If the transaction is aborted (invalidated before started), delete all artifacts from flash
//This is an optimization. The memory management will attempt to remove those files again later
bool removed = true;
if (auto mService = model.getMeteringService()) {
removed &= mService->removeTxMeterData(connectorId, transaction->getTxNr());
}
if (removed) {
removed &= model.getTransactionStore()->remove(connectorId, transaction->getTxNr());
}
if (removed) {
model.getTransactionStore()->setTxEnd(connectorId, transaction->getTxNr()); //roll back creation of last tx entry
}
AO_DBG_DEBUG("collect aborted transaction %u-%u %s", connectorId, transaction->getTxNr(), removed ? "" : "failure");
transaction = nullptr;
}
if (transaction && transaction->isCompleted()) {
AO_DBG_DEBUG("collect obsolete transaction %u-%u", connectorId, transaction->getTxNr());
transaction = nullptr;
}
if (transaction) { //begin exclusively transaction-related operations
if (connectorPluggedInput) {
if (transaction->isRunning() && transaction->isActive() && !connectorPluggedInput()) {
if (!stopTransactionOnEVSideDisconnect || *stopTransactionOnEVSideDisconnect) {
AO_DBG_DEBUG("Stop Tx due to EV disconnect");
transaction->setStopReason("EVDisconnected");
transaction->setInactive();
transaction->commit();
}
}
}
if (transaction->isActive() &&
!transaction->getStartSync().isRequested() &&
transaction->getBeginTimestamp() > MIN_TIME &&
connectionTimeOut && *connectionTimeOut > 0 &&
model.getClock().now() - transaction->getBeginTimestamp() >= *connectionTimeOut) {
AO_DBG_INFO("Session mngt: timeout");
transaction->setInactive();
transaction->commit();
updateTxNotification(TxNotification::ConnectionTimeout);
}
if (transaction->isActive() &&
transaction->isIdTagDeauthorized() && ( //transaction has been deAuthorized
!transaction->isRunning() || //if transaction hasn't started yet, always end
!stopTransactionOnInvalidId || *stopTransactionOnInvalidId)) { //if transaction is running, behavior depends on StopTransactionOnInvalidId
AO_DBG_DEBUG("DeAuthorize session");
transaction->setStopReason("DeAuthorized");
transaction->setInactive();
transaction->commit();
}
/*
* Check conditions for start or stop transaction
*/
if (!transaction->isRunning()) {
//start tx?
if (transaction->isActive() && transaction->isAuthorized() && //tx must be authorized
(!connectorPluggedInput || connectorPluggedInput()) && //if applicable, connector must be plugged
isOperative() && //only start tx if charger is free of error conditions
(!startTxReadyInput || startTxReadyInput())) { //if defined, user Input for allowing StartTx must be true
//start Transaction
AO_DBG_INFO("Session mngt: trigger StartTransaction");
auto meteringService = model.getMeteringService();
if (transaction->getMeterStart() < 0 && meteringService) {
auto meterStart = meteringService->readTxEnergyMeter(transaction->getConnectorId(), ReadingContext::TransactionBegin);
if (meterStart && *meterStart) {
transaction->setMeterStart(meterStart->toInteger());
} else {
AO_DBG_ERR("MeterStart undefined");
}
}
if (transaction->getStartTimestamp() <= MIN_TIME) {
transaction->setStartTimestamp(model.getClock().now());
transaction->setStartBootNr(model.getBootNr());
}
updateTxNotification(TxNotification::StartTx);
if (transaction->isSilent()) {
AO_DBG_INFO("silent Transaction: omit StartTx");
transaction->getStartSync().setRequested();
transaction->getStartSync().confirm();
transaction->commit();
return;
}
transaction->commit();
if (model.getMeteringService()) {
model.getMeteringService()->beginTxMeterData(transaction.get());
}
auto startTx = makeRequest(new StartTransaction(model, transaction));
startTx->setTimeout(0);
startTx->setOnReceiveConfListener([this] (JsonObject response) {
//fetch authorization status from StartTransaction.conf() for user notification
const char* idTagInfoStatus = response["idTagInfo"]["status"] | "_Undefined";
if (strcmp(idTagInfoStatus, "Accepted")) {
updateTxNotification(TxNotification::DeAuthorized);
}
});
context.initiateRequest(std::move(startTx));
return;
}
} else {
//stop tx?
if (!transaction->isActive() &&
(!stopTxReadyInput || stopTxReadyInput())) {
//stop transaction
AO_DBG_INFO("Session mngt: trigger StopTransaction");
if (transaction->isSilent()) {
AO_DBG_INFO("silent Transaction: omit StopTx");
updateTxNotification(TxNotification::StopTx);
transaction->getStopSync().setRequested();
transaction->getStopSync().confirm();
if (auto mService = model.getMeteringService()) {
mService->removeTxMeterData(connectorId, transaction->getTxNr());
}
model.getTransactionStore()->remove(connectorId, transaction->getTxNr());
model.getTransactionStore()->setTxEnd(connectorId, transaction->getTxNr());
transaction = nullptr;
return;
}
auto meteringService = model.getMeteringService();
if (transaction->getMeterStop() < 0 && meteringService) {
auto meterStop = meteringService->readTxEnergyMeter(transaction->getConnectorId(), ReadingContext::TransactionEnd);
if (meterStop && *meterStop) {
transaction->setMeterStop(meterStop->toInteger());
} else {
AO_DBG_ERR("MeterStop undefined");
}
}
if (transaction->getStopTimestamp() <= MIN_TIME) {
transaction->setStopTimestamp(model.getClock().now());
transaction->setStopBootNr(model.getBootNr());
}
transaction->commit();
updateTxNotification(TxNotification::StopTx);
std::shared_ptr<TransactionMeterData> stopTxData;
if (meteringService) {
stopTxData = meteringService->endTxMeterData(transaction.get());
}
std::unique_ptr<Request> stopTx;
if (stopTxData) {
stopTx = makeRequest(new StopTransaction(model, std::move(transaction), stopTxData->retrieveStopTxData()));
} else {
stopTx = makeRequest(new StopTransaction(model, std::move(transaction)));
}
stopTx->setTimeout(0);
context.initiateRequest(std::move(stopTx));
return;
}
}
} //end transaction-related operations
//handle FreeVend mode
if (freeVendActive && *freeVendActive && connectorPluggedInput) {
if (!freeVendTrackPlugged && connectorPluggedInput() && !transaction) {
const char *idTag = freeVendIdTag && *freeVendIdTag ? *freeVendIdTag : "";
if (!idTag || *idTag == '\0') {
idTag = "A0000000";
}
AO_DBG_INFO("begin FreeVend Tx using idTag %s", idTag);
beginTransaction_authorized(idTag);
if (!transaction) {
AO_DBG_ERR("could not begin FreeVend Tx");
(void)0;
}
}
freeVendTrackPlugged = connectorPluggedInput();
}
auto status = getStatus();
for (auto i = std::min(errorDataInputs.size(), trackErrorDataInputs.size()); i >= 1; i--) {
auto index = i - 1;
auto error = errorDataInputs[index].operator()();
if (error.isError && !trackErrorDataInputs[index]) {
//new error
auto statusNotification = makeRequest(
new StatusNotification(connectorId, status, model.getClock().now(), error));
statusNotification->setTimeout(0);
context.initiateRequest(std::move(statusNotification));
currentStatus = status;
reportedStatus = status;
trackErrorDataInputs[index] = true;
} else if (!error.isError && trackErrorDataInputs[index]) {
//reset error
trackErrorDataInputs[index] = false;
}
}
if (status != currentStatus) {
currentStatus = status;
t_statusTransition = ao_tick_ms();
AO_DBG_DEBUG("Status changed%s", *minimumStatusDuration ? ", will report delayed" : "");
}
if (reportedStatus != currentStatus &&
model.getClock().now() >= Timestamp(2010,0,0,0,0,0) &&
(*minimumStatusDuration <= 0 || //MinimumStatusDuration disabled
ao_tick_ms() - t_statusTransition >= ((unsigned long) *minimumStatusDuration) * 1000UL)) {
reportedStatus = currentStatus;
Timestamp reportedTimestamp = model.getClock().now();
reportedTimestamp -= (ao_tick_ms() - t_statusTransition) / 1000UL;
auto statusNotification = makeRequest(
new StatusNotification(connectorId, reportedStatus, reportedTimestamp, getErrorCode()));
statusNotification->setTimeout(0);
context.initiateRequest(std::move(statusNotification));
return;
}
return;
}
bool Connector::isFaulted() {
//for (auto i = errorDataInputs.begin(); i != errorDataInputs.end(); ++i) {
for (size_t i = 0; i < errorDataInputs.size(); i++) {
if (errorDataInputs[i].operator()().isFaulted) {
return true;
}
}
return false;
}
const char *Connector::getErrorCode() {
for (auto i = errorDataInputs.size(); i >= 1; i--) {
auto error = errorDataInputs[i-1].operator()();
if (error.isError && error.errorCode) {
return error.errorCode;
}
}
return nullptr;
}
std::shared_ptr<Transaction> Connector::allocateTransaction() {
decltype(allocateTransaction()) tx;
//clean possible aorted tx
auto txr = model.getTransactionStore()->getTxEnd(connectorId);
auto txsize = model.getTransactionStore()->size(connectorId);
for (decltype(txsize) i = 0; i < txsize; i++) {
txr = (txr + MAX_TX_CNT - 1) % MAX_TX_CNT; //decrement by 1
auto tx = model.getTransactionStore()->getTransaction(connectorId, txr);
//check if dangling silent tx, aborted tx, or corrupted entry (tx == null)
if (!tx || tx->isSilent() || tx->isAborted()) {
//yes, remove
bool removed = true;
if (auto mService = model.getMeteringService()) {
removed &= mService->removeTxMeterData(connectorId, txr);
}
if (removed) {
removed &= model.getTransactionStore()->remove(connectorId, txr);
}
if (removed) {
model.getTransactionStore()->setTxEnd(connectorId, txr);
AO_DBG_WARN("deleted dangling silent or aborted tx for new transaction");
} else {
AO_DBG_ERR("memory corruption");
break;
}
} else {
//no, tx record trimmed, end
break;
}
}
//try to create new transaction
tx = model.getTransactionStore()->createTransaction(connectorId);
if (!tx) {
//could not create transaction - now, try to replace tx history entry
auto txl = model.getTransactionStore()->getTxBegin(connectorId);
auto txsize = model.getTransactionStore()->size(connectorId);
for (decltype(txsize) i = 0; i < txsize; i++) {
if (tx) {
//success, finished here
break;
}
//no transaction allocated, delete history entry to make space
auto txhist = model.getTransactionStore()->getTransaction(connectorId, txl);
//oldest entry, now check if it's history and can be removed or corrupted entry
if (!txhist || txhist->isCompleted()) {
//yes, remove
bool removed = true;
if (auto mService = model.getMeteringService()) {
removed &= mService->removeTxMeterData(connectorId, txl);
}
if (removed) {
removed &= model.getTransactionStore()->remove(connectorId, txl);
}
if (removed) {
model.getTransactionStore()->setTxBegin(connectorId, (txl + 1) % MAX_TX_CNT);
AO_DBG_DEBUG("deleted tx history entry for new transaction");
tx = model.getTransactionStore()->createTransaction(connectorId);
} else {
AO_DBG_ERR("memory corruption");
break;
}
} else {
//no, end of history reached, don't delete further tx
AO_DBG_DEBUG("cannot delete more tx");
break;
}
txl++;
txl %= MAX_TX_CNT;
}
}
if (!tx) {
//couldn't create normal transaction -> check if to start charging without real transaction
if (silentOfflineTransactions && *silentOfflineTransactions) {
//try to handle charging session without sending StartTx or StopTx to the server
tx = model.getTransactionStore()->createTransaction(connectorId, true);
if (tx) {
AO_DBG_DEBUG("created silent transaction");
(void)0;
}
}
}
return tx;
}
std::shared_ptr<Transaction> Connector::beginTransaction(const char *idTag) {
if (transaction) {
AO_DBG_WARN("tx process still running. Please call endTransaction(...) before");
return nullptr;
}
auto rService = model.getReservationService();
AuthorizationData *localAuth = nullptr;
bool expiredLocalAuth = false;
//check local OCPP whitelist
if (auto authService = model.getAuthorizationService()) {
localAuth = authService->getLocalAuthorization(idTag);
//check if blocked by reservation
Reservation *reservation = nullptr;
if (localAuth && rService) {
reservation = rService->getReservation(
connectorId,
idTag,
localAuth->getParentIdTag() ? localAuth->getParentIdTag() : nullptr);
if (reservation && !reservation->matches(
idTag,
localAuth->getParentIdTag() ? localAuth->getParentIdTag() : nullptr)) {
//reservation found for connector but does not match idTag or parentIdTag
AO_DBG_DEBUG("reservation blocks local auth at connector %u", connectorId);
localAuth = nullptr;;
}
}
if (localAuth && localAuth->getAuthorizationStatus() != AuthorizationStatus::Accepted) {
AO_DBG_DEBUG("local auth denied (%s)", idTag);
localAuth = nullptr;
}
//check expiry
if (localAuth && localAuth->getExpiryDate()) {
auto& tnow = model.getClock().now();
if (tnow >= *localAuth->getExpiryDate()) {
AO_DBG_DEBUG("idTag %s local auth entry expired", idTag);
localAuth = nullptr;
expiredLocalAuth = true;
}
}
}
transaction = allocateTransaction();
if (!transaction) {
AO_DBG_ERR("could not allocate Tx");
return nullptr;
}
if (!idTag || *idTag == '\0') {
//input string is empty
transaction->setIdTag("");
} else {
transaction->setIdTag(idTag);
}
transaction->setBeginTimestamp(model.getClock().now());
AO_DBG_DEBUG("Begin transaction process (%s), prepare", idTag != nullptr ? idTag : "");
//check for local preauthorization
if (localPreAuthorize && *localPreAuthorize) {
if (localAuth && localAuth->getAuthorizationStatus() == AuthorizationStatus::Accepted) {
AO_DBG_DEBUG("Begin transaction process (%s), preauthorized locally", idTag != nullptr ? idTag : "");
transaction->setAuthorized();
updateTxNotification(TxNotification::Authorized);
}
}
transaction->commit();
auto authorize = makeRequest(new Authorize(context.getModel(), idTag));
authorize->setTimeout(authorizationTimeout && *authorizationTimeout > 0 ? *authorizationTimeout * 1000UL : 20UL * 1000UL);
auto tx = transaction;
authorize->setOnReceiveConfListener([this, tx] (JsonObject response) {
JsonObject idTagInfo = response["idTagInfo"];
if (strcmp("Accepted", idTagInfo["status"] | "UNDEFINED")) {
//Authorization rejected, abort transaction
AO_DBG_DEBUG("Authorize rejected (%s), abort tx process", tx->getIdTag());
tx->setIdTagDeauthorized();
tx->commit();
updateTxNotification(TxNotification::AuthorizationRejected);
return;
}
if (model.getReservationService()) {
auto reservation = model.getReservationService()->getReservation(
connectorId,
tx->getIdTag(),
idTagInfo["parentIdTag"] | (const char*) nullptr);
if (reservation && !reservation->matches(
tx->getIdTag(),
idTagInfo["parentIdTag"] | (const char*) nullptr)) {
//reservation found for connector but does not match idTag or parentIdTag
AO_DBG_INFO("connector %u reserved - abort transaction", connectorId);
tx->setInactive();
tx->commit();
updateTxNotification(TxNotification::ReservationConflict);
return;
}
}
AO_DBG_DEBUG("Authorized transaction process (%s)", tx->getIdTag());
tx->setAuthorized();
tx->commit();
updateTxNotification(TxNotification::Authorized);
});
authorize->setOnTimeoutListener([this, tx, localAuth, expiredLocalAuth] () {
if (expiredLocalAuth) {
//local auth entry exists, but is expired -> avoid offline tx
AO_DBG_DEBUG("Abort transaction process (%s), timeout, expired local auth", tx->getIdTag());
tx->setInactive();
tx->commit();
updateTxNotification(TxNotification::AuthorizationTimeout);
return;
}
if (localAuth) {
AO_DBG_DEBUG("Offline transaction process (%s), locally authorized", tx->getIdTag());
tx->setAuthorized();
tx->commit();
updateTxNotification(TxNotification::Authorized);
return;
}
if (model.getReservationService()) {
auto reservation = model.getReservationService()->getReservation(
connectorId,
tx->getIdTag());
if (reservation && !reservation->matches(
tx->getIdTag())) {
//reservation found for connector but does not match idTag or parentIdTag
AO_DBG_INFO("connector %u reserved (offline) - abort transaction", connectorId);
tx->setInactive();
tx->commit();
updateTxNotification(TxNotification::ReservationConflict);
return;
}
}
if (allowOfflineTxForUnknownId && (bool) *allowOfflineTxForUnknownId) {
AO_DBG_DEBUG("Offline transaction process (%s), allow unknown ID", tx->getIdTag());
tx->setAuthorized();
tx->commit();
updateTxNotification(TxNotification::Authorized);
return;
}
AO_DBG_DEBUG("Abort transaction process (%s): timeout", tx->getIdTag());
tx->setInactive();
tx->commit();
updateTxNotification(TxNotification::AuthorizationTimeout);
return; //offline tx disabled
});
context.initiateRequest(std::move(authorize));
return transaction;
}
std::shared_ptr<Transaction> Connector::beginTransaction_authorized(const char *idTag, const char *parentIdTag) {
if (transaction) {
AO_DBG_WARN("tx process still running. Please call endTransaction(...) before");
return nullptr;
}
transaction = allocateTransaction();
if (!transaction) {
AO_DBG_ERR("could not allocate Tx");
return nullptr;
}
if (!idTag || *idTag == '\0') {
//input string is empty
transaction->setIdTag("");
} else {
transaction->setIdTag(idTag);
}
transaction->setBeginTimestamp(model.getClock().now());
AO_DBG_DEBUG("Begin transaction process (%s), already authorized", idTag != nullptr ? idTag : "");
transaction->setAuthorized();
if (model.getReservationService()) {
if (auto reservation = model.getReservationService()->getReservation(connectorId, idTag, parentIdTag)) {
if (reservation->matches(idTag, parentIdTag)) {
transaction->setReservationId(reservation->getReservationId());
}
}
}
transaction->commit();
return transaction;
}
void Connector::endTransaction(const char *idTag, const char *reason) {
if (!transaction || !transaction->isActive()) {
//transaction already ended / not active anymore
return;
}
if (idTag && *idTag != '\0' && !strcmp(idTag, transaction->getIdTag())) {
//given stop idTag differs from start idTag. Make Authorization check first
AO_DBG_WARN("authorization status of stop idTag not checked automatically yet");
(void)0;
}
AO_DBG_DEBUG("End session started by idTag %s",
transaction->getIdTag());
if (idTag && *idTag != '\0') {
transaction->setStopIdTag(idTag);
}
if (reason) {
transaction->setStopReason(reason);
}
transaction->setInactive();
transaction->commit();
}
std::shared_ptr<Transaction>& Connector::getTransaction() {
return transaction;
}
bool Connector::isOperative() {
if (isFaulted()) {
return false;
}
if (!trackLoopExecute) {
return false;
}
if (transaction && transaction->isRunning()) {
return true;
}
return availabilityVolatile && *availability;
}
void Connector::setAvailability(bool available) {
*availability = available;
configuration_save();
}
void Connector::setAvailabilityVolatile(bool available) {
availabilityVolatile = available;
}
void Connector::setConnectorPluggedInput(std::function<bool()> connectorPlugged) {
this->connectorPluggedInput = connectorPlugged;
}
void Connector::setEvReadyInput(std::function<bool()> evRequestsEnergy) {
this->evReadyInput = evRequestsEnergy;
}
void Connector::setEvseReadyInput(std::function<bool()> connectorEnergized) {
this->evseReadyInput = connectorEnergized;
}
void Connector::addErrorCodeInput(std::function<const char*()> connectorErrorCode) {
addErrorDataInput([connectorErrorCode] () -> ErrorData {
return ErrorData(connectorErrorCode());
});
}
void Connector::addErrorDataInput(std::function<ErrorData ()> errorDataInput) {
this->errorDataInputs.push_back(errorDataInput);
this->trackErrorDataInputs.push_back(false);
}
void Connector::setOnUnlockConnector(std::function<PollResult<bool>()> unlockConnector) {
this->onUnlockConnector = unlockConnector;
}
std::function<PollResult<bool>()> Connector::getOnUnlockConnector() {
return this->onUnlockConnector;
}
void Connector::setStartTxReadyInput(std::function<bool()> startTxReady) {
this->startTxReadyInput = startTxReady;
}
void Connector::setStopTxReadyInput(std::function<bool()> stopTxReady) {
this->stopTxReadyInput = stopTxReady;
}
void Connector::setOccupiedInput(std::function<bool()> occupied) {
this->occupiedInput = occupied;
}
void Connector::setTxNotificationOutput(std::function<void(TxNotification, Transaction*)> txNotificationOutput) {
this->txNotificationOutput = txNotificationOutput;
}
void Connector::updateTxNotification(TxNotification event) {
if (txNotificationOutput) {
txNotificationOutput(event, transaction.get());
}
}