iso15118 0.5.0

ISO 15118 vehicle-to-grid (V2G) communication — EXI codec, message sets, session engines and Plug & Charge signatures; sans-I/O and no_std-capable, for both EVCC and SECC
Documentation
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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
//! A whole ISO 15118-2 session, EVCC to SECC, with no sockets and no clock.
//!
//! This is the point of the sans-I/O design: a charging session — protocol
//! handshake, session setup, service discovery, authorization, DC cable check,
//! pre-charge, the charge loop, welding detection and shutdown — runs as a
//! plain unit test in microseconds, with time as a variable the test increments.
//!
//! The two sides talk to each other through byte vectors, so everything the
//! wire would carry is exercised: V2GTP framing, EXI, the document event codes,
//! session-id checking and the ordering rules.

#![cfg(all(feature = "iso2", feature = "evcc", feature = "secc"))]

use iso15118::evcc::{Evcc, EvccConfig};
use iso15118::iso2::{
    Body, BodyChoice, ChargeProgress, DCEVSEStatus, DCEVSEStatusCode, EnergyTransferMode,
    IsolationLevel, MessageHeader, PaymentOption, ResponseCode, V2GMessage,
};
use iso15118::message::Message;
use iso15118::secc::{self, Secc, SeccConfig};
use iso15118::session::{Instant, Millis, SessionId, Timer};
use iso15118::{Protocol, Protocols};
use iso15118::{evcc, iso2};

const SESSION_ID: SessionId = SessionId::new([0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]);

/// The two sides, wired to each other by byte vectors and a shared clock.
struct Link {
    evcc: Evcc,
    secc: Secc,
    now: Instant,
}

impl Link {
    fn new() -> Self {
        let evcc = Evcc::new(EvccConfig {
            protocols: Protocols::only(Protocol::Iso2),
            ..Default::default()
        });
        let mut secc = Secc::new(SeccConfig {
            protocols: Protocols::only(Protocol::Iso2),
            session_id: SESSION_ID,
            ..Default::default()
        });
        let now = Instant::ZERO;
        secc.opened(now);
        Self { evcc, secc, now }
    }

    fn advance(&mut self, by: Millis) {
        self.now = self.now + by;
        self.evcc.handle_timeout(self.now);
        self.secc.handle_timeout(self.now);
    }

    /// Moves whatever the EVCC has queued to the SECC, and back.
    fn pump(&mut self) {
        let up = self.evcc.take_transmit();
        if !up.is_empty() {
            self.secc.handle_input(self.now, &up).expect("SECC input");
        }
        let down = self.secc.take_transmit();
        if !down.is_empty() {
            self.evcc.handle_input(self.now, &down).expect("EVCC input");
        }
    }

    /// Drains the SECC's events, answering each request with `answer`.
    fn serve(&mut self, answer: impl Fn(&Message) -> Message) {
        while let Some(event) = self.secc.poll_event() {
            match event {
                secc::Event::Request(req) => {
                    let res = answer(&req);
                    self.secc.respond(self.now, res).expect("respond");
                }
                secc::Event::Refused { message, reason, .. } => {
                    panic!("SECC refused {}: {reason}", message.name())
                }
                _ => {}
            }
        }
    }

    /// Sends `request`, lets the SECC answer it, and returns the answer.
    fn exchange(&mut self, request: BodyChoice) -> BodyChoice {
        self.evcc.request(self.now, wrap(request)).expect("request");
        self.pump();
        self.serve(|req| wrap(reply_to(req)));
        self.pump();
        let mut answer = None;
        while let Some(event) = self.evcc.poll_event() {
            if let evcc::Event::Response(res) = event {
                answer = unwrap(&res);
            }
        }
        answer.expect("a response")
    }
}

fn header() -> MessageHeader {
    MessageHeader {
        session_id: SESSION_ID.as_bytes().to_vec(),
        notification: None,
        signature: None,
    }
}

fn wrap(choice: BodyChoice) -> Message {
    Message::Iso2(Box::new(iso2::Document::V2GMessage(V2GMessage {
        header: header(),
        body: Body { choice: Some(choice) },
    })))
}

fn unwrap(message: &Message) -> Option<BodyChoice> {
    match message {
        Message::Iso2(doc) => match &**doc {
            iso2::Document::V2GMessage(m) => m.body.choice.clone(),
            _ => None,
        },
        _ => None,
    }
}

/// A charging station that says yes to everything, which is all this test needs
/// it to do: the point here is the sequencing, not the policy.
#[allow(
    clippy::too_many_lines,
    clippy::match_same_arms,
    reason = "one arm per message reads as the table it is"
)]
fn reply_to(request: &Message) -> BodyChoice {
    use BodyChoice as B;
    let status = DCEVSEStatus {
        notification_max_delay: 0,
        evse_notification: iso2::EVSENotification::None,
        evse_isolation_status: Some(IsolationLevel::Valid),
        evse_status_code: DCEVSEStatusCode::EVSEReady,
    };
    match unwrap(request).expect("a body") {
        B::SessionSetupReq(_) => B::SessionSetupRes(iso2::SessionSetupRes {
            response_code: ResponseCode::OKNewSessionEstablished,
            evse_id: "DE*ABC*E123*45".into(),
            evse_time_stamp: Some(1_725_456_343),
        }),
        B::ServiceDiscoveryReq(_) => B::ServiceDiscoveryRes(iso2::ServiceDiscoveryRes {
            response_code: ResponseCode::OK,
            payment_option_list: iso2::PaymentOptionList {
                payment_option: alloc_vec(PaymentOption::ExternalPayment),
            },
            charge_service: iso2::ChargeService {
                service_id: 1,
                service_name: None,
                service_category: iso2::ServiceCategory::EVCharging,
                service_scope: None,
                free_service: false,
                supported_energy_transfer_mode: iso2::SupportedEnergyTransferMode {
                    energy_transfer_mode: alloc_vec(EnergyTransferMode::DCExtended),
                },
            },
            service_list: None,
        }),
        B::PaymentServiceSelectionReq(_) => {
            B::PaymentServiceSelectionRes(iso2::PaymentServiceSelectionRes {
                response_code: ResponseCode::OK,
            })
        }
        B::AuthorizationReq(_) => B::AuthorizationRes(iso2::AuthorizationRes {
            response_code: ResponseCode::OK,
            evse_processing: iso2::EVSEProcessing::Finished,
        }),
        B::ChargeParameterDiscoveryReq(_) => {
            B::ChargeParameterDiscoveryRes(iso2::ChargeParameterDiscoveryRes {
                response_code: ResponseCode::OK,
                evse_processing: iso2::EVSEProcessing::Finished,
                choice_2: None,
                choice_3: iso2::ChargeParameterDiscoveryResChoice3::DCEVSEChargeParameter(
                    iso2::DCEVSEChargeParameter {
                        dc_evse_status: status.clone(),
                        evse_maximum_current_limit: physical(200),
                        evse_maximum_power_limit: kilo(150),
                        evse_maximum_voltage_limit: physical(900),
                        evse_minimum_current_limit: physical(0),
                        evse_minimum_voltage_limit: physical(150),
                        evse_current_regulation_tolerance: None,
                        evse_peak_current_ripple: physical(1),
                        evse_energy_to_be_delivered: None,
                    },
                ),
            })
        }
        B::CableCheckReq(_) => B::CableCheckRes(iso2::CableCheckRes {
            response_code: ResponseCode::OK,
            dc_evse_status: status.clone(),
            evse_processing: iso2::EVSEProcessing::Finished,
        }),
        B::PreChargeReq(_) => B::PreChargeRes(iso2::PreChargeRes {
            response_code: ResponseCode::OK,
            dc_evse_status: status.clone(),
            evse_present_voltage: physical(400),
        }),
        B::PowerDeliveryReq(_) => B::PowerDeliveryRes(iso2::PowerDeliveryRes {
            response_code: ResponseCode::OK,
            choice: iso2::PowerDeliveryResChoice::DCEVSEStatus(status.clone()),
        }),
        B::CurrentDemandReq(_) => B::CurrentDemandRes(iso2::CurrentDemandRes {
            response_code: ResponseCode::OK,
            dc_evse_status: status,
            evse_present_voltage: physical(400),
            evse_present_current: physical(100),
            evse_current_limit_achieved: false,
            evse_voltage_limit_achieved: false,
            evse_power_limit_achieved: false,
            evse_maximum_voltage_limit: None,
            evse_maximum_current_limit: None,
            evse_maximum_power_limit: None,
            evse_id: "DE*ABC*E123*45".into(),
            sa_schedule_tuple_id: 1,
            meter_info: None,
            receipt_required: None,
        }),
        B::WeldingDetectionReq(_) => B::WeldingDetectionRes(iso2::WeldingDetectionRes {
            response_code: ResponseCode::OK,
            dc_evse_status: DCEVSEStatus {
                notification_max_delay: 0,
                evse_notification: iso2::EVSENotification::None,
                evse_isolation_status: Some(IsolationLevel::Valid),
                evse_status_code: DCEVSEStatusCode::EVSEShutdown,
            },
            evse_present_voltage: physical(0),
        }),
        B::SessionStopReq(_) => {
            B::SessionStopRes(iso2::SessionStopRes { response_code: ResponseCode::OK })
        }
        other => panic!("the charger has no answer for {other:?}"),
    }
}

fn physical(value: i16) -> iso2::PhysicalValue {
    iso2::PhysicalValue { multiplier: 0, unit: iso2::UnitSymbol::V, value }
}

/// `PhysicalValueType` is a 16-bit value with a decimal exponent, which is how
/// 150 kW fits in a field that stops at 32767.
fn kilo(value: i16) -> iso2::PhysicalValue {
    iso2::PhysicalValue { multiplier: 3, unit: iso2::UnitSymbol::W, value }
}

fn alloc_vec<T>(item: T) -> Vec<T> {
    vec![item]
}

/// Runs the handshake and returns once both sides agree on ISO 15118-2.
fn negotiated() -> Link {
    let mut link = Link::new();
    link.evcc.start(link.now).expect("start");
    link.pump();
    link.serve(|_| unreachable!("the handshake needs no application decision"));
    link.pump();

    let agreed = core::iter::from_fn(|| link.evcc.poll_event())
        .find_map(|e| match e {
            evcc::Event::ProtocolAgreed(p) => Some(p),
            _ => None,
        })
        .expect("a protocol");
    assert_eq!(agreed, Protocol::Iso2);
    assert_eq!(link.secc.protocol(), Some(Protocol::Iso2));
    link
}

#[test]
fn a_whole_dc_charging_session_runs_without_a_socket() {
    let mut link = negotiated();

    let res = link.exchange(BodyChoice::SessionSetupReq(iso2::SessionSetupReq {
        evcc_id: vec![0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF],
    }));
    let BodyChoice::SessionSetupRes(setup) = res else { panic!("wrong response") };
    assert_eq!(setup.response_code, ResponseCode::OKNewSessionEstablished);
    assert_eq!(link.evcc.session_id(), SESSION_ID, "the charger assigned the id");

    link.exchange(BodyChoice::ServiceDiscoveryReq(iso2::ServiceDiscoveryReq {
        service_scope: None,
        service_category: None,
    }));
    link.exchange(BodyChoice::PaymentServiceSelectionReq(iso2::PaymentServiceSelectionReq {
        selected_payment_option: PaymentOption::ExternalPayment,
        selected_service_list: iso2::SelectedServiceList {
            selected_service: vec![iso2::SelectedService { service_id: 1, parameter_set_id: None }],
        },
    }));
    link.exchange(BodyChoice::AuthorizationReq(iso2::AuthorizationReq {
        id: None,
        gen_challenge: None,
    }));
    link.exchange(BodyChoice::ChargeParameterDiscoveryReq(iso2::ChargeParameterDiscoveryReq {
        max_entries_sa_schedule_tuple: None,
        requested_energy_transfer_mode: EnergyTransferMode::DCExtended,
        choice: iso2::ChargeParameterDiscoveryReqChoice::DCEVChargeParameter(
            dc_ev_charge_parameter(),
        ),
    }));

    // DC: isolation, then voltage matching, before a contactor closes.
    link.exchange(BodyChoice::CableCheckReq(iso2::CableCheckReq { dc_ev_status: ev_status() }));
    link.exchange(BodyChoice::PreChargeReq(iso2::PreChargeReq {
        dc_ev_status: ev_status(),
        ev_target_voltage: physical(400),
        ev_target_current: physical(2),
    }));
    link.exchange(BodyChoice::PowerDeliveryReq(power_delivery(ChargeProgress::Start)));

    for _ in 0..3 {
        link.exchange(BodyChoice::CurrentDemandReq(current_demand()));
        link.advance(Millis::from_millis(60));
    }

    link.exchange(BodyChoice::PowerDeliveryReq(power_delivery(ChargeProgress::Stop)));
    link.exchange(BodyChoice::WeldingDetectionReq(iso2::WeldingDetectionReq {
        dc_ev_status: ev_status(),
    }));
    link.exchange(BodyChoice::SessionStopReq(iso2::SessionStopReq {
        charging_session: iso2::ChargingSession::Terminate,
    }));

    assert!(link.secc.is_closed(), "the charger ends the session after SessionStopRes");
    assert!(link.evcc.is_closed(), "and so does the vehicle");
}

#[test]
fn the_charger_refuses_a_request_that_is_out_of_sequence() {
    let mut link = negotiated();
    // Skipping straight to authorization: no session, no services, no payment.
    let _ = link.evcc.take_transmit();
    let bad = wrap(BodyChoice::AuthorizationReq(iso2::AuthorizationReq {
        id: None,
        gen_challenge: None,
    }));
    // Bypass the EVCC's own check — a conforming vehicle would not send this,
    // and the charger must not depend on that.
    let mut raw = iso15118::session::Connection::new();
    raw.set_protocol(Protocol::Iso2);
    raw.send(&bad).unwrap();
    let wire = raw.take_transmit();
    link.secc.handle_input(link.now, &wire).unwrap();

    let mut refused = None;
    let mut closed = None;
    while let Some(event) = link.secc.poll_event() {
        match event {
            secc::Event::Refused { response_code, reason, .. } => {
                refused = Some((response_code, reason));
            }
            secc::Event::Closed(why) => closed = Some(why),
            _ => {}
        }
    }
    let (code, reason) = refused.expect("a refusal");
    assert_eq!(code, ResponseCode::FAILEDSequenceError as u8);
    assert!(matches!(reason, secc::Refusal::Sequence(_)));
    assert_eq!(closed, Some(secc::Close::Refused));
}

#[test]
fn the_vehicle_refuses_to_send_a_request_that_is_out_of_sequence() {
    let mut link = negotiated();
    let e = link
        .evcc
        .request(link.now, wrap(BodyChoice::CurrentDemandReq(current_demand())))
        .unwrap_err();
    assert!(matches!(e, evcc::EvccError::Flow(_)), "caught locally, not on the wire: {e}");
    assert!(link.evcc.transmit_is_empty(), "nothing must have reached the wire");
}

#[test]
fn a_silent_vehicle_expires_the_sequence_timer() {
    let mut link = negotiated();
    link.exchange(BodyChoice::SessionSetupReq(iso2::SessionSetupReq {
        evcc_id: vec![0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF],
    }));
    while link.secc.poll_event().is_some() {}

    let deadline = link.secc.poll_timeout().expect("a deadline");
    assert_eq!(deadline - link.now, Millis::from_secs(60), "V2G_SECC_Sequence_Timeout");

    link.advance(Millis::from_secs(61));
    let closed = core::iter::from_fn(|| link.secc.poll_event()).find_map(|e| match e {
        secc::Event::Closed(why) => Some(why),
        _ => None,
    });
    assert_eq!(closed, Some(secc::Close::Timeout(Timer::Sequence)));
}

#[test]
fn a_silent_charger_expires_the_vehicles_message_timer() {
    let mut link = negotiated();
    link.evcc
        .request(
            link.now,
            wrap(BodyChoice::SessionSetupReq(iso2::SessionSetupReq { evcc_id: vec![0; 6] })),
        )
        .unwrap();
    assert_eq!(link.evcc.outstanding(), Some("SessionSetupReq"));

    // `SessionSetupRes` gets the default 2 s budget.
    let deadline = link.evcc.poll_timeout().expect("a deadline");
    assert_eq!(deadline - link.now, Millis::from_secs(2));

    link.advance(Millis::from_secs(3));
    let closed = core::iter::from_fn(|| link.evcc.poll_event()).find_map(|e| match e {
        evcc::Event::Closed(why) => Some(why),
        _ => None,
    });
    assert_eq!(closed, Some(evcc::Close::Timeout(Timer::Message)));
}

#[test]
fn a_charger_with_nothing_in_common_says_so_and_stops() {
    let mut evcc =
        Evcc::new(EvccConfig { protocols: Protocols::only(Protocol::Iso20), ..Default::default() });
    let mut secc = Secc::new(SeccConfig {
        protocols: Protocols::only(Protocol::Din70121),
        session_id: SESSION_ID,
        ..Default::default()
    });
    let now = Instant::ZERO;
    evcc.start(now).unwrap();
    secc.handle_input(now, &evcc.take_transmit()).unwrap();
    evcc.handle_input(now, &secc.take_transmit()).unwrap();

    assert!(secc.is_closed());
    let closed = core::iter::from_fn(|| evcc.poll_event()).find_map(|e| match e {
        evcc::Event::Closed(why) => Some(why),
        _ => None,
    });
    assert_eq!(closed, Some(evcc::Close::NoCommonProtocol));
}

fn ev_status() -> iso2::DCEVStatus {
    iso2::DCEVStatus {
        ev_ready: true,
        ev_error_code: iso2::DCEVErrorCode::NOERROR,
        ev_ress_soc: 42,
    }
}

fn dc_ev_charge_parameter() -> iso2::DCEVChargeParameter {
    iso2::DCEVChargeParameter {
        departure_time: None,
        dc_ev_status: ev_status(),
        ev_maximum_current_limit: physical(200),
        ev_maximum_power_limit: None,
        ev_maximum_voltage_limit: physical(900),
        ev_energy_capacity: None,
        ev_energy_request: None,
        full_soc: None,
        bulk_soc: None,
    }
}

fn power_delivery(progress: ChargeProgress) -> iso2::PowerDeliveryReq {
    iso2::PowerDeliveryReq {
        charge_progress: progress,
        sa_schedule_tuple_id: 1,
        charging_profile: None,
        choice: Some(iso2::PowerDeliveryReqChoice::DCEVPowerDeliveryParameter(
            iso2::DCEVPowerDeliveryParameter {
                dc_ev_status: ev_status(),
                bulk_charging_complete: None,
                charging_complete: false,
            },
        )),
    }
}

fn current_demand() -> iso2::CurrentDemandReq {
    iso2::CurrentDemandReq {
        dc_ev_status: ev_status(),
        ev_target_current: physical(100),
        ev_maximum_voltage_limit: None,
        ev_maximum_current_limit: None,
        ev_maximum_power_limit: None,
        bulk_charging_complete: None,
        charging_complete: false,
        remaining_time_to_full_soc: None,
        remaining_time_to_bulk_soc: None,
        ev_target_voltage: physical(400),
    }
}

/// ISO 15118 leaves no discretion after a `FAILED_*` response: the session is
/// over, and the only request the vehicle may still send is `SessionStopReq`.
/// A core that lets the flow carry on is the bug `EVerest`'s
/// `GHSA-9vv5-67cv-9crq` describes.
#[test]
fn a_failure_response_leaves_only_session_stop() {
    let mut link = negotiated();
    link.exchange(BodyChoice::SessionSetupReq(iso2::SessionSetupReq {
        evcc_id: vec![0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF],
    }));

    // The charger declines service discovery.
    link.evcc
        .request(
            link.now,
            wrap(BodyChoice::ServiceDiscoveryReq(iso2::ServiceDiscoveryReq {
                service_scope: None,
                service_category: None,
            })),
        )
        .unwrap();
    link.pump();
    link.serve(|_| {
        wrap(BodyChoice::ServiceDiscoveryRes(iso2::ServiceDiscoveryRes {
            response_code: ResponseCode::FAILEDServiceIDInvalid,
            payment_option_list: iso2::PaymentOptionList {
                payment_option: alloc_vec(PaymentOption::ExternalPayment),
            },
            charge_service: iso2::ChargeService {
                service_id: 1,
                service_name: None,
                service_category: iso2::ServiceCategory::EVCharging,
                service_scope: None,
                free_service: false,
                supported_energy_transfer_mode: iso2::SupportedEnergyTransferMode {
                    energy_transfer_mode: alloc_vec(EnergyTransferMode::DCExtended),
                },
            },
            service_list: None,
        }))
    });
    link.pump();

    let failed =
        core::iter::from_fn(|| link.evcc.poll_event()).any(|e| matches!(e, evcc::Event::Failed));
    assert!(failed, "the vehicle is told the response was a failure");

    // Both sides now refuse to go on with anything but the stop.
    let next = wrap(BodyChoice::PaymentServiceSelectionReq(iso2::PaymentServiceSelectionReq {
        selected_payment_option: PaymentOption::ExternalPayment,
        selected_service_list: iso2::SelectedServiceList {
            selected_service: vec![iso2::SelectedService { service_id: 1, parameter_set_id: None }],
        },
    }));
    assert!(link.evcc.request(link.now, next).is_err(), "the vehicle refuses to carry on");
    assert!(!link.secc.is_closed(), "the charger still waits for SessionStopReq");

    link.exchange(BodyChoice::SessionStopReq(iso2::SessionStopReq {
        charging_session: iso2::ChargingSession::Terminate,
    }));
    assert!(link.secc.is_closed());
    assert!(link.evcc.is_closed());
}

/// A paused session is finished but not terminated: both sides keep the id, so
/// the next session under it is a resume rather than a new one.
#[test]
fn a_paused_session_is_reported_as_paused() {
    let mut link = negotiated();
    link.exchange(BodyChoice::SessionSetupReq(iso2::SessionSetupReq {
        evcc_id: vec![0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF],
    }));
    link.exchange(BodyChoice::SessionStopReq(iso2::SessionStopReq {
        charging_session: iso2::ChargingSession::Pause,
    }));

    assert_eq!(link.evcc.session_id(), SESSION_ID, "the id survives, to resume under");
    assert!(link.secc.is_closed());
    assert!(link.evcc.is_closed());
}

/// The other half of a pause: the vehicle comes back with the id it was given,
/// and the station adopts it rather than assigning a new one.
///
/// Whether an id names a resumable session is stored state the core does not
/// hold — a schedule, an energy reading — so the decision is the application's
/// and `join_session` is how it says so.
#[test]
fn a_station_can_join_the_session_a_vehicle_asks_to_resume() {
    const PAUSED: SessionId = SessionId::new([0xDE, 0xAD, 0xBE, 0xEF, 0, 0, 0, 1]);

    // The vehicle says once, in configuration, which session it is rejoining —
    // rather than hand-placing an id in the one message out of thirty whose
    // session id is its own to choose.
    let mut link = Link::new();
    link.evcc = Evcc::new(EvccConfig {
        protocols: Protocols::only(Protocol::Iso2),
        rejoin: Some(PAUSED),
        ..Default::default()
    });
    link.evcc.start(link.now).unwrap();
    link.pump();
    link.serve(|_| unreachable!("the handshake needs no application decision"));
    link.pump();
    while link.evcc.poll_event().is_some() {}

    let setup = wrap(BodyChoice::SessionSetupReq(iso2::SessionSetupReq {
        evcc_id: vec![0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF],
    }));
    link.evcc.request(link.now, setup).unwrap();
    link.pump();

    while let Some(event) = link.secc.poll_event() {
        if let secc::Event::Request(req) = event {
            assert_eq!(req.session_id(), Some(PAUSED));
            link.secc.join_session(PAUSED);
            let res = wrap_with(
                PAUSED,
                BodyChoice::SessionSetupRes(iso2::SessionSetupRes {
                    response_code: ResponseCode::OKOldSessionJoined,
                    evse_id: "DE*ABC*E123*45".into(),
                    evse_time_stamp: Some(1_725_456_343),
                }),
            );
            link.secc.respond(link.now, res).unwrap();
        }
    }
    assert_eq!(link.secc.session_id(), PAUSED, "the station adopted the vehicle's id");
    link.pump();
    while link.evcc.poll_event().is_some() {}

    // The rest of the session runs under the resumed id, and the station's
    // check accepts it.
    let next = wrap_with(
        PAUSED,
        BodyChoice::ServiceDiscoveryReq(iso2::ServiceDiscoveryReq {
            service_scope: None,
            service_category: None,
        }),
    );
    link.evcc.request(link.now, next).unwrap();
    link.pump();
    link.serve(|req| wrap_with(PAUSED, reply_to(req)));
    assert!(!link.secc.is_closed(), "a resumed session is not a rejected one");
}

fn wrap_with(session_id: SessionId, choice: BodyChoice) -> Message {
    Message::Iso2(Box::new(iso2::Document::V2GMessage(V2GMessage {
        header: MessageHeader {
            session_id: session_id.as_bytes().to_vec(),
            notification: None,
            signature: None,
        },
        body: Body { choice: Some(choice) },
    })))
}

/// A `supportedAppProtocolReq` on the wire, offering exactly `protocols` in
/// exactly that priority order.
///
/// Built by hand rather than by an [`Evcc`], because an `Evcc` deliberately
/// will not offer a generation it has no message set for — and these tests are
/// about the charger meeting a vehicle that does.
fn offering(protocols: &[Protocol]) -> Vec<u8> {
    let mut conn = iso15118::session::Connection::new();
    let req = iso15118::app_protocol::SupportedAppProtocolReq::advertising(protocols);
    conn.send(&Message::AppProtocolReq(Box::new(req))).expect("encode the handshake");
    conn.take_transmit()
}

/// `Protocol::Din70121` exists so a charger can decline it by name, but this
/// crate has no DIN message set — its schemas are not freely available. A
/// charger configured for it must decline rather than agree to something it
/// cannot then speak.
#[test]
fn a_protocol_with_no_message_set_is_not_a_protocol_in_common() {
    let mut secc = Secc::new(SeccConfig {
        protocols: Protocols::only(Protocol::Din70121),
        session_id: SESSION_ID,
        ..Default::default()
    });
    let now = Instant::ZERO;
    secc.handle_input(now, &offering(&[Protocol::Din70121])).unwrap();

    assert!(secc.is_closed(), "the charger must decline what it cannot speak");
    assert_eq!(secc.protocol(), None);
}

/// The narrowing has to happen *before* the negotiation, not after it.
///
/// A vehicle that prefers DIN SPEC 70121 and offers ISO 15118-2 as its fallback
/// is the common case in the German DC fleet. Filtering the station's set after
/// picking a winner would let DIN win on priority and then be dropped, taking
/// the whole session with it — when the two sides had a generation in common
/// all along.
#[test]
fn a_charger_falls_back_to_the_generation_it_can_actually_speak() {
    let mut secc = Secc::new(SeccConfig {
        protocols: Protocols::from_slice(&[Protocol::Din70121, Protocol::Iso2]),
        session_id: SESSION_ID,
        ..Default::default()
    });
    let now = Instant::ZERO;
    // Priority 1 is DIN, priority 2 is ISO 15118-2.
    secc.handle_input(now, &offering(&[Protocol::Din70121, Protocol::Iso2])).unwrap();

    assert!(!secc.is_closed(), "ISO 15118-2 was on offer and the charger speaks it");
    assert_eq!(secc.protocol(), Some(Protocol::Iso2));
    assert_eq!(secc.poll_event(), Some(secc::Event::ProtocolAgreed(Protocol::Iso2)));
}

/// The vehicle's half of the same rule: what it cannot speak, it does not
/// offer.
///
/// Advertising a generation and then failing on the charger's acceptance of it
/// wastes the one exchange that exists to settle the question. And if the
/// filtering leaves nothing, that is a configuration mistake worth reporting
/// before any bytes exist rather than as a session that dies at the first
/// message.
#[test]
fn a_vehicle_does_not_offer_a_generation_it_has_no_message_set_for() {
    let mut evcc = Evcc::new(EvccConfig {
        protocols: Protocols::from_slice(&[Protocol::Din70121, Protocol::Iso2]),
        ..Default::default()
    });
    evcc.start(Instant::ZERO).unwrap();

    let req = match iso15118::message::Message::decode(
        None,
        iso15118::v2gtp::PayloadType::ExiEncodedV2gMessage,
        &evcc.take_transmit()[iso15118::v2gtp::HEADER_LEN..],
    )
    .unwrap()
    {
        iso15118::message::Message::AppProtocolReq(req) => req,
        other => panic!("expected the handshake, got {}", other.name()),
    };
    assert_eq!(
        req.app_protocols.iter().map(|e| e.protocol_namespace.as_str()).collect::<Vec<_>>(),
        [Protocol::Iso2.namespace()],
        "DIN was configured but has no message set, so it is never offered"
    );
    // ...and the schema id it did assign resolves back to what it meant.
    assert_eq!(req.protocol_for_schema_id(1), Some(Protocol::Iso2));

    let mut nothing = Evcc::new(EvccConfig {
        protocols: Protocols::only(Protocol::Din70121),
        ..Default::default()
    });
    assert!(matches!(nothing.start(Instant::ZERO), Err(evcc::EvccError::NothingToOffer { .. })));
}

/// The other half of half-duplex: the *vehicle* does not pipeline either.
///
/// The ordering graph cannot catch this on its own, because a charge loop's
/// `CurrentDemandReq` is legal over and over — what makes the second one wrong
/// is that the first has not been answered yet.
#[test]
fn the_vehicle_will_not_ask_a_second_question_before_the_first_is_answered() {
    let mut link = charging();
    link.evcc.request(link.now, wrap(BodyChoice::CurrentDemandReq(current_demand()))).unwrap();
    assert_eq!(link.evcc.outstanding(), Some("CurrentDemandReq"));

    let again = link.evcc.request(link.now, wrap(BodyChoice::CurrentDemandReq(current_demand())));
    assert!(matches!(
        again,
        Err(evcc::EvccError::AwaitingResponse {
            outstanding: "CurrentDemandReq",
            got: "CurrentDemandReq"
        })
    ));

    // ...and the refusal changed nothing: the first request is still the one
    // outstanding, and answering it still works.
    link.pump();
    link.serve(|req| wrap(reply_to(req)));
    link.pump();
    assert_eq!(link.evcc.outstanding(), None, "the one request was answered");
}

/// The session id is the station's to assign and neither side's to choose per
/// message, so the drivers stamp it rather than trusting the application to.
#[test]
fn the_session_id_is_stamped_in_rather_than_taken_from_the_message() {
    let mut link = negotiated();
    link.exchange(BodyChoice::SessionSetupReq(iso2::SessionSetupReq { evcc_id: vec![0; 6] }));
    assert_eq!(link.evcc.session_id(), SESSION_ID);

    // An application that builds a request with the wrong id — or with none —
    // still puts the right one on the wire.
    link.evcc
        .request(
            link.now,
            wrap_with(
                SessionId::new([0xDE, 0xAD, 0xBE, 0xEF, 0, 0, 0, 0]),
                BodyChoice::ServiceDiscoveryReq(iso2::ServiceDiscoveryReq {
                    service_scope: None,
                    service_category: None,
                }),
            ),
        )
        .unwrap();
    link.pump();

    let request = core::iter::from_fn(|| link.secc.poll_event())
        .find_map(|e| match e {
            secc::Event::Request(m) => Some(m),
            _ => None,
        })
        .expect("the station accepted it");
    assert_eq!(request.session_id(), Some(SESSION_ID), "the wrong id never reached the wire");
}

/// A station that answers the wrong question has a bug the vehicle would find;
/// finding it locally costs one string comparison.
#[test]
fn the_station_cannot_answer_one_request_with_another_s_response() {
    let mut link = negotiated();
    link.evcc
        .request(
            link.now,
            wrap(BodyChoice::SessionSetupReq(iso2::SessionSetupReq { evcc_id: vec![0; 6] })),
        )
        .unwrap();
    link.pump();
    let _ = core::iter::from_fn(|| link.secc.poll_event()).count();

    let wrong = wrap(BodyChoice::ServiceDiscoveryRes(iso2::ServiceDiscoveryRes {
        response_code: ResponseCode::OK,
        payment_option_list: iso2::PaymentOptionList {
            payment_option: alloc_vec(PaymentOption::ExternalPayment),
        },
        charge_service: iso2::ChargeService {
            service_id: 1,
            service_name: None,
            service_category: iso2::ServiceCategory::EVCharging,
            service_scope: None,
            free_service: false,
            supported_energy_transfer_mode: iso2::SupportedEnergyTransferMode {
                energy_transfer_mode: alloc_vec(EnergyTransferMode::DCExtended),
            },
        },
        service_list: None,
    }));
    assert!(matches!(
        link.secc.respond(link.now, wrong),
        Err(secc::SeccError::WrongResponse { expected: "SessionSetupReq", .. })
    ));

    // The right one still works: a refusal must not consume the obligation.
    let right = wrap(reply_to(&wrap(BodyChoice::SessionSetupReq(iso2::SessionSetupReq {
        evcc_id: vec![0; 6],
    }))));
    link.secc.respond(link.now, right).unwrap();
    assert!(!link.secc.awaiting_response());
}

/// ...and answering when nothing was asked is refused too, rather than being
/// framed and sent to a vehicle that is waiting for something else.
#[test]
fn the_station_cannot_answer_a_question_nobody_asked() {
    let mut link = negotiated();
    let stray =
        wrap(BodyChoice::SessionStopRes(iso2::SessionStopRes { response_code: ResponseCode::OK }));
    assert!(matches!(
        link.secc.respond(link.now, stray),
        Err(secc::SeccError::NothingToAnswer("SessionStopRes"))
    ));
    assert!(link.secc.transmit_is_empty(), "nothing was queued");
}

/// `n` back-to-back `CurrentDemandReq` frames on one wire, as a peer that does
/// not wait to be answered would send them.
///
/// Framed straight through a [`Connection`](iso15118::session::Connection)
/// rather than through [`Evcc`], because `Evcc` refuses to pipeline — that is
/// the other half of the same rule, and it has its own test. A hostile peer is
/// not running this crate.
fn pipelined(n: usize) -> Vec<u8> {
    let mut peer = iso15118::session::Connection::new();
    peer.set_protocol(Protocol::Iso2);
    for _ in 0..n {
        peer.send(&wrap(BodyChoice::CurrentDemandReq(current_demand()))).unwrap();
    }
    peer.take_transmit()
}

/// V2G is half-duplex: the vehicle may not send again before it is answered.
/// A peer that pipelines a burst of repeatable requests — a charge loop turns,
/// and `CurrentDemandReq` is legal over and over — would otherwise have every
/// one of them decoded and queued as an event before the station answered a
/// single one, which is an unbounded queue on an unauthenticated peer's say-so.
#[test]
fn the_charger_reads_one_request_at_a_time() {
    let mut link = charging();

    link.secc.handle_input(link.now, &pipelined(4)).expect("SECC input");
    assert!(link.secc.awaiting_response(), "one request is outstanding");
    let requests = core::iter::from_fn(|| link.secc.poll_event())
        .filter(|e| matches!(e, secc::Event::Request(_)))
        .count();
    assert_eq!(requests, 1, "the other three wait until this one is answered");
}

/// More than a handful of unanswered frames is not a peer that is merely early;
/// it is one that is not following the protocol, and the receiver stops rather
/// than buffering for it.
#[test]
fn a_flood_of_pipelined_frames_ends_the_stream() {
    let mut link = charging();

    let burst = pipelined(iso15118::session::MAX_PENDING_FRAMES + 1);
    assert!(link.secc.handle_input(link.now, &burst).is_err(), "the flood is refused");
}

/// A stream that stops being a V2G session ends the session, and it is not the
/// application's decision.
///
/// `handle_input` returning `Err` is the whole of what the caller sees, and a
/// caller that logs it and calls again is the ordinary shape of a server loop.
/// So the engine has to be shut before it returns: `EVerest`'s MEDIUM-14 is a
/// correctly-computed refusal an application was free to ignore, and a
/// correctly-reported framing fault an application is free to ignore is the
/// same bug wearing a different hat.
///
/// Four things are checked, because "it returned an error" is the one of them
/// that was already true: the session is closed, the closure is *reported* as
/// an event, later input is inert, and the frames the peer had already queued
/// behind the fault are gone rather than waiting to be parsed on the next call.
#[test]
fn a_stream_that_stops_being_a_session_closes_it() {
    let mut link = charging();

    // A frame this session's own grammar cannot decode, followed by a request
    // that would decode perfectly well.
    let mut peer = iso15118::session::Connection::new();
    peer.set_protocol(Protocol::Iso2);
    peer.send_frame(iso15118::v2gtp::PayloadType::ExiEncodedV2gMessage, &[0xFF; 8]).unwrap();
    let mut wire = peer.take_transmit();
    wire.extend_from_slice(&pipelined(1));

    let err = link.secc.handle_input(link.now, &wire);
    assert!(err.is_err(), "the frame does not decode");
    assert!(link.secc.is_closed(), "and the session is over, not merely complaining");

    let closed = core::iter::from_fn(|| link.secc.poll_event())
        .any(|e| matches!(e, secc::Event::Closed(secc::Close::Fatal)));
    assert!(closed, "the application is told, rather than having to infer it from the Err");

    assert_eq!(link.secc.poll_timeout(), None, "every timer is disarmed");
    assert!(!link.secc.awaiting_response(), "there is nothing left to answer");

    // The good frame behind the bad one is not resurrected by the next call:
    // the peer that produced the fault also chose where that frame started.
    link.secc.handle_input(link.now, &[]).expect("a closed session accepts input inertly");
    assert!(link.secc.poll_event().is_none());
}

/// The same rule on the vehicle's side. \[V2G2-482\] has the EVCC stop the
/// session on a response that answers nothing, and a rule the caller may skip
/// is not that rule.
#[test]
fn a_charger_that_answers_nothing_closes_the_vehicles_session() {
    let mut link = negotiated();
    let mut charger = iso15118::session::Connection::new();
    charger.set_protocol(Protocol::Iso2);
    charger
        .send(&wrap(reply_to(&wrap(BodyChoice::ServiceDiscoveryReq(iso2::ServiceDiscoveryReq {
            service_scope: None,
            service_category: None,
        })))))
        .unwrap();
    let wire = charger.take_transmit();

    assert!(link.evcc.handle_input(link.now, &wire).is_err());
    assert!(link.evcc.is_closed());
    assert!(
        core::iter::from_fn(|| link.evcc.poll_event())
            .any(|e| matches!(e, evcc::Event::Closed(evcc::Close::Fatal))),
    );
}

/// The `supportedAppProtocol` handshake happens once \[V2G2-536\],
/// \[V2G2-541\], and the reason to check it here rather than to reason about
/// it is what a second one would *do*: replace the ordering graph with a fresh
/// one at `Phase::Start`, discarding the payment option, the transfer mode and
/// the failure latch. A peer with nothing left but `SessionStopReq` would be
/// back at the top of the flow.
///
/// It is not reachable through `Connection` — once a generation has won,
/// payload type `0x8001` is read as that generation's message set (D12) — which
/// is exactly why the clause is here: that argument lives in another file.
#[test]
fn the_handshake_cannot_be_replayed_to_reset_the_flow() {
    let mut link = charging();
    assert!(matches!(link.secc.flow().map(iso15118::session::Flow::phase_name), Some("Charging")));

    // Framed as the handshake is framed, but arriving in a session that has
    // already negotiated one.
    let mut peer = iso15118::session::Connection::new();
    peer.send(&Message::AppProtocolReq(Box::new(
        iso15118::app_protocol::SupportedAppProtocolReq::advertising([Protocol::Iso2]),
    )))
    .unwrap();
    let wire = peer.take_transmit();

    assert!(link.secc.handle_input(link.now, &wire).is_err());
    assert!(link.secc.is_closed(), "the session ends rather than restarting");
}

/// A ceiling the documentation tells a constrained target to lower has to be
/// reachable from the type that target configures.
#[test]
fn both_reassembly_ceilings_are_configurable_from_the_role_drivers() {
    let mut secc = Secc::new(SeccConfig {
        protocols: Protocols::only(Protocol::Iso2),
        session_id: SESSION_ID,
        max_pending_frames: 1,
        ..Default::default()
    });
    let now = Instant::ZERO;
    secc.opened(now);
    secc.handle_input(now, &offering(&[Protocol::Iso2])).unwrap();
    let _ = secc.take_transmit();

    // Two frames where one is allowed, and the handshake is already answered.
    let mut peer = iso15118::session::Connection::new();
    peer.set_protocol(Protocol::Iso2);
    for _ in 0..2 {
        peer.send(&wrap(BodyChoice::SessionSetupReq(iso2::SessionSetupReq {
            evcc_id: vec![0; 6],
        })))
        .unwrap();
    }
    assert!(matches!(
        secc.handle_input(now, &peer.take_transmit()),
        Err(secc::SeccError::Connection(iso15118::session::ConnectionError::TooManyFrames {
            limit: 1
        }))
    ));
}

/// Table 109 has two halves, and only one of them is a deadline. The station's
/// is a *performance* time — nothing enforces it, because missing it is not a
/// fault this side can observe — so what the engine owes the application is the
/// number, against the session clock.
#[test]
fn the_station_can_see_how_long_it_has_to_answer() {
    use iso15118::session::timers::iso2 as t;

    let mut link = charging();
    link.evcc.request(link.now, wrap(BodyChoice::CurrentDemandReq(current_demand()))).unwrap();
    link.pump();

    // 25 ms for a DC charge loop, against the vehicle's 250 ms timeout. That
    // ratio is the constraint on where the answer may come from.
    assert_eq!(link.secc.response_due(), Some(link.now + t::SECC_MSG_PERFORMANCE_CURRENT_DEMAND),);
    assert!(t::SECC_MSG_PERFORMANCE_CURRENT_DEMAND < t::MSG_TIMEOUT_CURRENT_DEMAND);

    link.serve(|req| wrap(reply_to(req)));
    assert_eq!(link.secc.response_due(), None, "nothing outstanding, nothing due");
}

/// The vehicle's half of the same pair, from the other side: \[V2G2-485\]
/// starts `V2G_EVCC_Sequence_Performance_Time` when the response lands, and the
/// station's `V2G_SECC_Sequence_Timeout` is twenty seconds behind it.
#[test]
fn the_vehicle_can_see_how_long_it_has_to_ask_again() {
    use iso15118::session::timers::iso2 as t;

    let mut link = charging();
    assert_eq!(link.evcc.next_request_due(), Some(link.now + t::EVCC_SEQUENCE_PERFORMANCE_TIME),);
    assert!(t::EVCC_SEQUENCE_PERFORMANCE_TIME < t::SECC_SEQUENCE_TIMEOUT);

    // While a question is outstanding the answer is bounded by the message
    // timer instead, which *is* enforced — so there is nothing to advise.
    link.evcc.request(link.now, wrap(BodyChoice::CurrentDemandReq(current_demand()))).unwrap();
    assert_eq!(link.evcc.next_request_due(), None);
}

/// The flow graph constrains requests, so nothing but this check stops a
/// charger from answering one request with another request's response — or
/// from volunteering responses to a vehicle that asked for nothing.
#[test]
fn the_vehicle_refuses_an_answer_to_a_question_it_did_not_ask() {
    let mut link = negotiated();
    link.evcc
        .request(
            link.now,
            wrap(BodyChoice::SessionSetupReq(iso2::SessionSetupReq { evcc_id: vec![0; 6] })),
        )
        .unwrap();
    let _ = link.evcc.take_transmit();

    // A well-formed, in-session `ServiceDiscoveryRes` — for a request that was
    // never sent.
    let mut charger = iso15118::session::Connection::new();
    charger.set_protocol(Protocol::Iso2);
    charger
        .send(&wrap(reply_to(&wrap(BodyChoice::ServiceDiscoveryReq(iso2::ServiceDiscoveryReq {
            service_scope: None,
            service_category: None,
        })))))
        .unwrap();
    let wire = charger.take_transmit();

    assert!(matches!(
        link.evcc.handle_input(link.now, &wire),
        Err(evcc::EvccError::UnexpectedResponse { expected: Some("SessionSetupReq"), .. })
    ));
}

/// A cable check is a *loop*: the station answers `Ongoing` and the vehicle
/// asks again. The per-message timeout says nothing about how long that may go
/// on, so without a budget of its own a vehicle waits forever for an isolation
/// test that will never finish \[V2G2-717\].
#[test]
fn the_cable_check_loop_has_a_budget_the_repeats_do_not_extend() {
    let mut link = negotiated();
    for req in setup_through_authorization() {
        link.exchange(req);
    }
    link.exchange(BodyChoice::ChargeParameterDiscoveryReq(charge_parameter_discovery()));

    let started = link.now;
    link.evcc.request(link.now, wrap(BodyChoice::CableCheckReq(cable_check()))).unwrap();
    assert_eq!(
        link.evcc.poll_timeout(),
        Some(started + Millis::from_secs(2)),
        "the per-message budget is the nearer deadline"
    );

    // The station keeps answering `Ongoing`, so the vehicle keeps asking.
    for _ in 0..8 {
        link.pump();
        link.serve(|req| wrap(reply_to(req)));
        link.pump();
        while link.evcc.poll_event().is_some() {}
        link.advance(Millis::from_secs(5));
        if link.evcc.is_closed() {
            break;
        }
        link.evcc.request(link.now, wrap(BodyChoice::CableCheckReq(cable_check()))).unwrap();
    }

    let closed = core::iter::from_fn(|| link.evcc.poll_event()).find_map(|e| match e {
        evcc::Event::Closed(why) => Some(why),
        _ => None,
    });
    assert_eq!(
        closed,
        Some(evcc::Close::Timeout(Timer::Ongoing)),
        "the loop budget runs from the first request, not from the last"
    );
    assert!(
        link.now - started >= Millis::from_secs(40),
        "V2G_EVCC_CableCheck_Timeout is 40 s, not 40 s per repeat"
    );
}

fn cable_check() -> iso2::CableCheckReq {
    iso2::CableCheckReq { dc_ev_status: ev_status() }
}

fn charge_parameter_discovery() -> iso2::ChargeParameterDiscoveryReq {
    iso2::ChargeParameterDiscoveryReq {
        max_entries_sa_schedule_tuple: None,
        requested_energy_transfer_mode: EnergyTransferMode::DCExtended,
        choice: iso2::ChargeParameterDiscoveryReqChoice::DCEVChargeParameter(
            dc_ev_charge_parameter(),
        ),
    }
}

fn setup_through_authorization() -> Vec<BodyChoice> {
    vec![
        BodyChoice::SessionSetupReq(iso2::SessionSetupReq {
            evcc_id: vec![0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF],
        }),
        BodyChoice::ServiceDiscoveryReq(iso2::ServiceDiscoveryReq {
            service_scope: None,
            service_category: None,
        }),
        BodyChoice::PaymentServiceSelectionReq(iso2::PaymentServiceSelectionReq {
            selected_payment_option: PaymentOption::ExternalPayment,
            selected_service_list: iso2::SelectedServiceList {
                selected_service: alloc_vec(iso2::SelectedService {
                    service_id: 1,
                    parameter_set_id: None,
                }),
            },
        }),
        BodyChoice::AuthorizationReq(iso2::AuthorizationReq { id: None, gen_challenge: None }),
    ]
}

/// A session driven as far as the charge loop.
fn charging() -> Link {
    let mut link = negotiated();
    for req in setup_through_authorization() {
        link.exchange(req);
    }
    link.exchange(BodyChoice::ChargeParameterDiscoveryReq(charge_parameter_discovery()));
    link.exchange(BodyChoice::CableCheckReq(cable_check()));
    link.exchange(BodyChoice::PreChargeReq(iso2::PreChargeReq {
        dc_ev_status: ev_status(),
        ev_target_voltage: physical(400),
        ev_target_current: physical(2),
    }));
    link.exchange(BodyChoice::PowerDeliveryReq(power_delivery(ChargeProgress::Start)));
    link
}

/// \[V2G2-750\]: the station returns a session id *different from zero*.
///
/// [`SeccConfig::session_id`] has no usable default — the crate has no RNG, so
/// the bytes are the caller's — and the placeholder it starts at is the one
/// value the requirement forbids. Left unset it would go on the wire, the
/// vehicle would have nothing to check later messages against, and a
/// well-behaved one would end the session without ever saying why. So the
/// station refuses to answer instead, on the side that can still fix it.
#[test]
fn a_station_that_was_never_given_a_session_id_refuses_to_assign_one() {
    let mut link = Link::new();
    // Replace the station with one whose id was never configured, then run the
    // handshake so the flow exists.
    link.secc = Secc::new(SeccConfig {
        protocols: Protocols::only(Protocol::Iso2),
        // `session_id` left at the `SessionId::NONE` placeholder.
        ..Default::default()
    });
    link.secc.opened(link.now);
    link.evcc.start(link.now).expect("start");
    link.pump();
    link.serve(|_| unreachable!("the handshake needs no application decision"));
    link.pump();

    link.evcc
        .request(
            link.now,
            wrap(BodyChoice::SessionSetupReq(iso2::SessionSetupReq {
                evcc_id: vec![1, 2, 3, 4, 5, 6],
            })),
        )
        .expect("SessionSetupReq");
    link.pump();

    let Some(secc::Event::Request(req)) = link.secc.poll_event() else {
        panic!("expected a SessionSetupReq")
    };
    let res = wrap(reply_to(&req));
    assert_eq!(
        link.secc.respond(link.now, res),
        Err(secc::SeccError::NoSessionId),
        "a station with no id to assign must not answer SessionSetupReq"
    );
    assert!(link.secc.transmit_is_empty(), "nothing unusable reaches the wire");

    // ...and it stays answerable: adopting an id — which is also what rejoining
    // a session this station paused does — lets the same response go out.
    link.secc.join_session(SESSION_ID);
    link.secc.respond(link.now, wrap(reply_to(&req))).expect("respond once an id exists");
    assert!(!link.secc.transmit_is_empty());
}

/// \[V2G2-713\]: when the station's own loop budget runs out it *answers*
/// `FAILED` rather than going quiet.
///
/// The station's `V2G_SECC_CableCheck_Performance_Time` is 38 s and the
/// vehicle's `V2G_EVCC_CableCheck_Timeout` is 40 s (Table 111). The two-second
/// gap is not slack — it is the room the answer fits in. A station armed with
/// the vehicle's 40 s could only ever reach its deadline after the vehicle had
/// already abandoned the session, which is the same as not having one.
///
/// The answer rides on the vehicle's *next* request, because that is when there
/// is something to answer: a loop budget expires between exchanges, with the
/// station idle and nothing outstanding.
#[test]
fn a_station_out_of_time_says_so_instead_of_going_quiet() {
    let mut link = negotiated();
    for req in setup_through_authorization() {
        link.exchange(req);
    }
    link.exchange(BodyChoice::ChargeParameterDiscoveryReq(charge_parameter_discovery()));

    let started = link.now;
    let mut overdue = None;

    // The station keeps answering `Ongoing`; the vehicle keeps asking. Three
    // seconds a turn steps over the station's 38 s without reaching the
    // vehicle's 40 s, which is the whole point of the gap between them.
    for _ in 0..16 {
        link.evcc.request(link.now, wrap(BodyChoice::CableCheckReq(cable_check()))).unwrap();
        link.pump();

        while let Some(event) = link.secc.poll_event() {
            match event {
                secc::Event::Request(req) => {
                    link.secc.respond(link.now, wrap(reply_to(&req))).expect("respond");
                }
                secc::Event::Overdue { message, response_code, phase } => {
                    overdue = Some((link.now - started, message, response_code, phase));
                }
                _ => {}
            }
        }
        link.pump();
        while link.evcc.poll_event().is_some() {}
        if overdue.is_some() {
            break;
        }
        link.advance(Millis::from_secs(3));
        assert!(!link.evcc.is_closed(), "the vehicle must not give up first");
    }

    let (elapsed, message, response_code, phase) =
        overdue.expect("the station's budget must run out");
    assert_eq!(phase, "CableCheck");
    assert_eq!(message.name(), "CableCheckReq", "the request to answer comes with the event");
    assert_eq!(response_code, ResponseCode::FAILED as u8, "[V2G2-713] asks for plain FAILED");
    assert!(
        elapsed >= Millis::from_secs(38) && elapsed < Millis::from_secs(40),
        "the station gives up at 38 s, inside the vehicle's 40 s: {elapsed}"
    );

    // The station answers that request, with FAILED, and the answer goes out.
    let refusal = wrap(BodyChoice::CableCheckRes(iso2::CableCheckRes {
        response_code: ResponseCode::FAILED,
        dc_evse_status: DCEVSEStatus {
            notification_max_delay: 0,
            evse_notification: iso2::EVSENotification::None,
            evse_isolation_status: Some(IsolationLevel::Invalid),
            evse_status_code: DCEVSEStatusCode::EVSENotReady,
        },
        evse_processing: iso2::EVSEProcessing::Finished,
    }));
    link.secc.respond(link.now, refusal).expect("the FAILED answer goes out");
    link.pump();

    // ...and the vehicle hears it as a failure, with only a stop left to send.
    let events: Vec<_> = core::iter::from_fn(|| link.evcc.poll_event()).collect();
    assert!(events.iter().any(|e| matches!(e, evcc::Event::Failed)), "{events:?}");
    assert!(
        link.evcc.request(link.now, wrap(BodyChoice::CableCheckReq(cable_check()))).is_err(),
        "after a failure only SessionStopReq is left"
    );
}