diff --git a/README.md b/README.md index f4ec9c9..74abede 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ rather than copying them. | `dbc/` | Wire formats of the shared nodes: `bench.dbc` (classic), `genset.dbc` (J1939), and `full.dbc`, both merged, the one file tools load; `lib/codec_/` and `full.dbc` are generated by `just dbc` | | `arxml/` | `can-full.arxml`, the can-full bench as an AUTOSAR R19-11 System Template; the DC-DC's AUTOSAR tables are generated from it (`just arxml`) | | `toolchain/` | The firmware build image | -| `testing/` | Host-side pytest suites and fixtures, run against any SocketCAN channel | +| `testing/` | Host-side pytest suites and fixtures, run against any SocketCAN channel; `suites/v2g` brings its own EVerest SIL (`just test-v2g`) | | `bench/` | A Renode bench for any set of nodes, and the agent image; each bench builds on it, and `just test-bench` runs a suite on it | | `tools/` | Host scripts: filling a node's A2L with one build's addresses (the build runs it), generating the DC-DC's AUTOSAR tables from `arxml/` (`just arxml`) | | `justfile` | Shared recipes: building nodes, `twister`, `test-bench`, and `hil` for a flashed board | diff --git a/justfile b/justfile index 1bda86d..5b89499 100644 --- a/justfile +++ b/justfile @@ -16,6 +16,12 @@ TOOLCHAIN := "zelos-examples-toolchain:" + ZEPHYR + "-" + `shasum -a 256 toolcha BOARD := "nucleo_h753zi" # The part on that board, for probe-rs. CHIP := "STM32H753ZITx" +# The V2G SIL image: EVerest pinned by digest, plus the suite's tools. Tagged by +# its Dockerfile, as TOOLCHAIN is. +V2G_SIL := "zelos-examples-v2g-sil:" + `shasum -a 256 testing/suites/v2g/Dockerfile | cut -c1-12` +# The SIL's container: the suite mounted, the capabilities its link needs, and +# IPv6, which V2G runs on. +V2G_RUN := "--cap-add NET_ADMIN --cap-add SYS_ADMIN --sysctl net.ipv6.conf.all.disable_ipv6=0 -v \"$PWD/testing/suites/v2g:/suite:ro\"" # The Docker volume holding the west workspace, or an absolute host path to # bind instead. Override to build two trees at once. WORKSPACE := env("ZELOS_WEST_VOLUME", "zxws") @@ -140,6 +146,29 @@ hil ELF CHANNEL +SUITES: # --durations: the slowest tests, timed, after the results. cd testing && uv run --frozen pytest "${suites[@]}" --channel {{ CHANNEL }} --a2l "${elf%.elf}.a2l" --durations=10 +# The SIL needs CAP_NET_ADMIN for the veth and CAP_SYS_ADMIN for the EV's +# network namespace. ARGS go to pytest, e.g. `-k din`. +# +# Run the V2G suite: EVerest's EVSE and EV charge over a veth pair, captured. +test-v2g *ARGS: _v2g_sil + docker run --rm {{ V2G_RUN }} {{ V2G_SIL }} /suite {{ ARGS }} + +# Record the V2G demo captures and their message sidecars again: ISO 15118-2, DIN 70121, ISO 15118-20. +v2g-record: _v2g_sil + #!/usr/bin/env bash + set -euo pipefail + out=$(mktemp -d) + trap 'rm -rf "$out"' EXIT + docker run --rm {{ V2G_RUN }} -v "$out:/out" --entrypoint bash {{ V2G_SIL }} -c \ + "python3 -m pytest -p no:cacheprovider -q /suite/test_session.py::test_session --record /out; \ + status=\$?; chown -R $(id -u):$(id -g) /out; exit \$status" + for p in iso2:iso2-dc din:din-dc iso20-dc iso20-dc-bpt iso20-ac iso20-ac-bpt; do + name=${p#*:} p=${p%:*} + cp "$out/test_session[$p]/$p.pcapng" "testing/suites/v2g/captures/$name.pcapng" + cp "$out/test_session[$p]/$p.messages.csv" "testing/suites/v2g/captures/$name.messages.csv" + done + ls -l testing/suites/v2g/captures/ + # Remove the cached Zephyr workspace. Frees about 2 GB. clean-workspace: docker volume rm {{ WORKSPACE }} @@ -161,6 +190,11 @@ _fresh ELFS +SOURCES: exit 1 fi +# Build the V2G SIL image. Cached by Docker after the first run. +_v2g_sil: + docker image inspect {{ V2G_SIL }} > /dev/null 2>&1 || \ + docker build -q -t {{ V2G_SIL }} testing/suites/v2g > /dev/null + # Build the firmware toolchain image. Cached by Docker after the first run. _toolchain: docker image inspect {{ TOOLCHAIN }} > /dev/null 2>&1 || \ diff --git a/testing/suites/v2g/Dockerfile b/testing/suites/v2g/Dockerfile new file mode 100644 index 0000000..f0edb6a --- /dev/null +++ b/testing/suites/v2g/Dockerfile @@ -0,0 +1,26 @@ +# The V2G SIL: EVerest's demo image, pinned, plus the broker, the capture +# tools and pytest. EVerest 2025.10.0 (everest-demo tag 2025.10.0-single-phase). +FROM ghcr.io/everest/everest-demo/manager@sha256:9165d0937323ae61ee2e496f68f3c4a465ed9099740e489df1f0161265492756 + +RUN apt-get update \ + && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ + mosquitto mosquitto-clients iproute2 tshark \ + && rm -rf /var/lib/apt/lists/* \ + && pip install --no-cache-dir --break-system-packages pytest==9.1.1 + +# EVerest's test PKI, where its modules look: Evse15118D20 and Josev's +# ISO 15118-20 states read the V2G certificates even without TLS. +RUN cd /ext/source/tests/ocpp_tests/test_sets/everest-aux && ./install_certs.sh /ext/dist + +# Josev's TLS 1.3 client presents a vehicle certificate, which that PKI lacks: +# one leaf, signed by its V2G root. +RUN cd /ext/dist/etc/everest/certs && mkdir client/vehicle && pw=$(cat client/v2g/V2G_ROOT_CA_PASSWORD.txt) \ + && openssl ecparam -genkey -name prime256v1 | openssl ec -aes-128-cbc -passout pass:$pw -out client/vehicle/VEHICLE_LEAF.key \ + && openssl req -new -key client/vehicle/VEHICLE_LEAF.key -passin pass:$pw -subj "/CN=SIL vehicle" -out /tmp/vehicle.csr \ + && printf 'basicConstraints=critical,CA:false\nkeyUsage=critical,digitalSignature\n' > /tmp/vehicle.ext \ + && openssl x509 -req -in /tmp/vehicle.csr -extfile /tmp/vehicle.ext -CA ca/v2g/V2G_ROOT_CA.pem -CAkey client/v2g/V2G_ROOT_CA.key \ + -passin pass:$pw -set_serial 1 -days 3650 -out client/vehicle/VEHICLE_CERT_CHAIN.pem \ + && echo $pw > client/vehicle/VEHICLE_LEAF_PASSWORD.txt && rm /tmp/vehicle.* + +WORKDIR /suite +ENTRYPOINT ["python3", "-m", "pytest", "-p", "no:cacheprovider"] diff --git a/testing/suites/v2g/README.md b/testing/suites/v2g/README.md new file mode 100644 index 0000000..1302f7d --- /dev/null +++ b/testing/suites/v2g/README.md @@ -0,0 +1,90 @@ +# V2G suite + +Charging sessions between an EVerest EVSE and an EVerest EV over a veth pair, +each captured on the link: DC over ISO 15118-2 and DIN 70121, DC and AC over +ISO 15118-20, each also bidirectional (BPT), and ISO 15118-2 and -20 DC over +TLS. Software in the loop: no modems, no CP line. + +```bash +just test-v2g # from the repository root; Linux Docker +just test-v2g -k din # pytest arguments pass through +just test-v2g -k iso20 # the ISO 15118-20 sessions +just test-v2g -k tls # the TLS sessions +just v2g-record # record captures/ again +``` + +## The SIL + +| Piece | What it is | +|---|---| +| Image | `everest-demo/manager` 2025.10.0-single-phase, pinned by digest (`Dockerfile`), plus Mosquitto, tshark and pytest, and EVerest's test PKI installed where its modules look | +| EVSE | `EvseV2G` on `v2g-evse`, no TLS but in the TLS sessions, with EVerest's simulated DC supply, isolation monitor and board (`everest.yaml`). ISO 15118-20: `Evse15118D20` (libiso15118, cbv2g codec) in its place, no TLS; AC with the simulated board alone (`everest-ac.yaml`) | +| EV | `PyEvJosev` (Josev, EXIficient codec) driven by `EvManager`, standalone in its own network namespace on `v2g-ev`. ISO 15118-20: it offers one energy service first, `DC`, `DC_BPT`, `AC` or `AC_BPT`, which the EVSE selects | +| SLAC | `SlacSimulator`, in process: no HomePlug frames on the link | +| Broker | Mosquitto on a Unix socket, reachable from both namespaces | +| Capture | dumpcap on `v2g-evse`: SDP, the V2G TCP connection, neighbour discovery | + +The container needs `CAP_NET_ADMIN` (the veth) and `CAP_SYS_ADMIN` (the EV's +namespace), which `just test-v2g` grants. + +## The checks + +Truth is the link. Each capture is walked at the V2GTP layer: SDP request and +response, the response's address and port the ones the EV connected to, then +each direction of the one TCP connection split into V2GTP frames with nothing +left over, requests and responses alternating. EXI is not decoded. Frames are +named by the EVSE's record of them (`v2g_messages`): `EvseV2G`'s matched on +bytes, `Evse15118D20`'s, a name alone, on direction and V2GTP payload type +(0x8002 common, 0x8003 AC, 0x8004 DC). + +| Test | EV does | Asserts | +|---|---|---| +| `test_session[iso2]`, `[din]` | charges 5 s, then stops | protocol selected; SessionSetup first, CableCheck, PreCharge, PowerDelivery, a CurrentDemand loop, PowerDelivery, WeldingDetection, SessionStop last; FIN, no RST | +| `test_session[iso20-dc]`, `[iso20-dc-bpt]` | the same over ISO 15118-20 | protocol selected; SessionSetup, AuthorizationSetup, Authorization, ServiceDiscovery first, DC_CableCheck, DC_PreCharge, PowerDelivery, a DC_ChargeLoop, PowerDelivery, DC_WeldingDetection, SessionStop last; FIN, no RST | +| `test_session[iso20-ac]`, `[iso20-ac-bpt]` | draws 16 A on three phases for 5 s, then stops | the same start, AC_ChargeParameterDiscovery, ScheduleExchange, PowerDelivery, an AC_ChargeLoop, PowerDelivery, SessionStop last; FIN, no RST | +| `test_session[iso2-tls]`, `[iso20-dc-tls]` | the `iso2` and `iso20-dc` sessions over TLS 1.2 and TLS 1.3 | the same, on what tshark decrypts with the EVSE's key log (`tls_key_logging`, `enable_tls_key_logging`); SDP asks for and offers TLS; FIN | +| `test_ev_unplug_mid_current_demand` | unplugs in CurrentDemand | ends in CurrentDemand: no PowerDelivery stop, no WeldingDetection, no SessionStop | +| `test_isolation_fault` | charges; the isolation monitor reads 10 kOhm | CableCheck, then no PreCharge and no CurrentDemand | +| `test_capture_fixture` | - | the committed captures pass the same link checks, and each sidecar row points at a V2GTP frame's start, in order and direction; needs only tshark | + +## Captures + +One full session each, from `test_session`, 13 to 21 KB: `iso2-dc`, `din-dc`, +`iso20-dc`, `iso20-dc-bpt`, `iso20-ac`, `iso20-ac-bpt` (`.pcapng`). Link-local +addresses from random MACs. The ISO 15118-20 sessions run in dynamic control +mode, in plain TCP. The TLS sessions have no committed capture. + +Each has a sidecar, `.messages.csv`: one row per V2GTP frame, `frame` +(the capture's frame number of the segment holding its first byte), +`direction` (`ev` or `evse`) and `message` (e.g. `CurrentDemandReq`, +`DC_ChargeLoopReq`), named from the EVSE's record matched to the wire. No EXI bytes: the record's +responses are not the wire's (below). `just v2g-record` writes both. + +## Known EVerest behaviour + +- EvseV2G 2025.10 records each response in its request's buffer: the request's + V2GTP header and length, the response's EXI cut or padded to it. Requests are + recorded exactly. The suite matches responses on their common prefix. +- Evse15118D20 2025.10 records a message's name alone, its own spelling + (`DcChargeLoopReq`); the sidecar has the schema's (`DC_ChargeLoopReq`). +- Evse15118D20 does not start without a V2G certificate, and Josev's + ISO 15118-20 AuthorizationSetup reads the V2G root, TLS or not. The image + ships empty certificate directories and EVerest's test PKI beside them, which + the `Dockerfile` installs with EVerest's own script. +- `config-sil-ac-d20.yaml` starts its session with `iso_start_v2g_session AC`, + which EvManager 2025.10 rejects (three arguments); `conftest.py` passes the + departure time and energy amount too. +- Josev's ISO 15118-20 EV reports a constant PresentSOC (10). +- With key logging on, EvseV2G and Evse15118D20 write each secret to + `tls_session_keys.log` and send the same line, one per datagram, to `ff02::1` + on the link, from the first free port from 49152 up to the EV's TCP port. +- Josev's TLS 1.3 client needs a vehicle certificate, which EVerest's test PKI + lacks; the `Dockerfile` signs one with the test V2G root. +- Over TLS Josev pays by contract where the EVSE offers it, and stays in + Authorization until the EVSE's timeout: nothing here authorizes a contract. + The TLS sessions turn the offer off (`payment_enable_contract`). +- At the end of a TLS session the EVSE sends close_notify and FIN, then + resets the connection on the EV's close_notify. +- Real SLAC (`EvseSlac`, `EvSlac`) over the veth does not match: without a + modem no `CM_SET_KEY.CNF` comes back, so `EvseSlac` stays in reset and + `EvSlac` fails. The HomePlug AV frames do cross the link. diff --git a/testing/suites/v2g/captures/din-dc.messages.csv b/testing/suites/v2g/captures/din-dc.messages.csv new file mode 100644 index 0000000..cd7ffda --- /dev/null +++ b/testing/suites/v2g/captures/din-dc.messages.csv @@ -0,0 +1,65 @@ +frame,direction,message +11,ev,SupportedAppProtocolReq +13,evse,SupportedAppProtocolRes +15,ev,SessionSetupReq +17,evse,SessionSetupRes +19,ev,ServiceDiscoveryReq +21,evse,ServiceDiscoveryRes +23,ev,ServicePaymentSelectionReq +25,evse,ServicePaymentSelectionRes +27,ev,ContractAuthenticationReq +30,evse,ContractAuthenticationRes +32,ev,ContractAuthenticationReq +34,evse,ContractAuthenticationRes +37,ev,ChargeParameterDiscoveryReq +39,evse,ChargeParameterDiscoveryRes +41,ev,CableCheckReq +43,evse,CableCheckRes +45,ev,CableCheckReq +47,evse,CableCheckRes +49,ev,CableCheckReq +51,evse,CableCheckRes +53,ev,CableCheckReq +55,evse,CableCheckRes +57,ev,CableCheckReq +59,evse,CableCheckRes +61,ev,CableCheckReq +63,evse,CableCheckRes +65,ev,CableCheckReq +67,evse,CableCheckRes +69,ev,PreChargeReq +71,evse,PreChargeRes +73,ev,PreChargeReq +75,evse,PreChargeRes +77,ev,PowerDeliveryReq +79,evse,PowerDeliveryRes +81,ev,CurrentDemandReq +83,evse,CurrentDemandRes +85,ev,CurrentDemandReq +87,evse,CurrentDemandRes +89,ev,CurrentDemandReq +91,evse,CurrentDemandRes +93,ev,CurrentDemandReq +95,evse,CurrentDemandRes +97,ev,CurrentDemandReq +99,evse,CurrentDemandRes +101,ev,CurrentDemandReq +103,evse,CurrentDemandRes +105,ev,CurrentDemandReq +107,evse,CurrentDemandRes +109,ev,CurrentDemandReq +111,evse,CurrentDemandRes +113,ev,CurrentDemandReq +115,evse,CurrentDemandRes +117,ev,PowerDeliveryReq +119,evse,PowerDeliveryRes +121,ev,WeldingDetectionReq +123,evse,WeldingDetectionRes +126,ev,WeldingDetectionReq +128,evse,WeldingDetectionRes +130,ev,WeldingDetectionReq +132,evse,WeldingDetectionRes +134,ev,WeldingDetectionReq +136,evse,WeldingDetectionRes +138,ev,SessionStopReq +140,evse,SessionStopRes diff --git a/testing/suites/v2g/captures/din-dc.pcapng b/testing/suites/v2g/captures/din-dc.pcapng new file mode 100644 index 0000000..eed47aa Binary files /dev/null and b/testing/suites/v2g/captures/din-dc.pcapng differ diff --git a/testing/suites/v2g/captures/iso2-dc.messages.csv b/testing/suites/v2g/captures/iso2-dc.messages.csv new file mode 100644 index 0000000..18e3a5f --- /dev/null +++ b/testing/suites/v2g/captures/iso2-dc.messages.csv @@ -0,0 +1,69 @@ +frame,direction,message +13,ev,SupportedAppProtocolReq +15,evse,SupportedAppProtocolRes +18,ev,SessionSetupReq +20,evse,SessionSetupRes +22,ev,ServiceDiscoveryReq +24,evse,ServiceDiscoveryRes +26,ev,PaymentServiceSelectionReq +28,evse,PaymentServiceSelectionRes +30,ev,AuthorizationReq +32,evse,AuthorizationRes +34,ev,AuthorizationReq +36,evse,AuthorizationRes +38,ev,ChargeParameterDiscoveryReq +40,evse,ChargeParameterDiscoveryRes +42,ev,CableCheckReq +44,evse,CableCheckRes +46,ev,CableCheckReq +48,evse,CableCheckRes +50,ev,CableCheckReq +52,evse,CableCheckRes +54,ev,CableCheckReq +56,evse,CableCheckRes +58,ev,CableCheckReq +60,evse,CableCheckRes +62,ev,CableCheckReq +64,evse,CableCheckRes +66,ev,CableCheckReq +68,evse,CableCheckRes +70,ev,CableCheckReq +72,evse,CableCheckRes +74,ev,CableCheckReq +76,evse,CableCheckRes +78,ev,PreChargeReq +80,evse,PreChargeRes +83,ev,PreChargeReq +85,evse,PreChargeRes +87,ev,PowerDeliveryReq +89,evse,PowerDeliveryRes +92,ev,CurrentDemandReq +94,evse,CurrentDemandRes +96,ev,CurrentDemandReq +98,evse,CurrentDemandRes +100,ev,CurrentDemandReq +102,evse,CurrentDemandRes +104,ev,CurrentDemandReq +106,evse,CurrentDemandRes +108,ev,CurrentDemandReq +110,evse,CurrentDemandRes +112,ev,CurrentDemandReq +114,evse,CurrentDemandRes +116,ev,CurrentDemandReq +118,evse,CurrentDemandRes +120,ev,CurrentDemandReq +122,evse,CurrentDemandRes +124,ev,CurrentDemandReq +126,evse,CurrentDemandRes +128,ev,PowerDeliveryReq +130,evse,PowerDeliveryRes +132,ev,WeldingDetectionReq +134,evse,WeldingDetectionRes +136,ev,WeldingDetectionReq +138,evse,WeldingDetectionRes +140,ev,WeldingDetectionReq +142,evse,WeldingDetectionRes +144,ev,WeldingDetectionReq +146,evse,WeldingDetectionRes +148,ev,SessionStopReq +150,evse,SessionStopRes diff --git a/testing/suites/v2g/captures/iso2-dc.pcapng b/testing/suites/v2g/captures/iso2-dc.pcapng new file mode 100644 index 0000000..d3c3c15 Binary files /dev/null and b/testing/suites/v2g/captures/iso2-dc.pcapng differ diff --git a/testing/suites/v2g/captures/iso20-ac-bpt.messages.csv b/testing/suites/v2g/captures/iso20-ac-bpt.messages.csv new file mode 100644 index 0000000..8b612b9 --- /dev/null +++ b/testing/suites/v2g/captures/iso20-ac-bpt.messages.csv @@ -0,0 +1,49 @@ +frame,direction,message +13,ev,SupportedAppProtocolReq +15,evse,SupportedAppProtocolRes +18,ev,SessionSetupReq +20,evse,SessionSetupRes +22,ev,AuthorizationSetupReq +24,evse,AuthorizationSetupRes +26,ev,AuthorizationReq +27,evse,AuthorizationRes +29,ev,ServiceDiscoveryReq +30,evse,ServiceDiscoveryRes +32,ev,ServiceDetailReq +33,evse,ServiceDetailRes +35,ev,ServiceDetailReq +36,evse,ServiceDetailRes +38,ev,ServiceDetailReq +39,evse,ServiceDetailRes +41,ev,ServiceDetailReq +42,evse,ServiceDetailRes +44,ev,ServiceSelectionReq +45,evse,ServiceSelectionRes +47,ev,AC_ChargeParameterDiscoveryReq +48,evse,AC_ChargeParameterDiscoveryRes +50,ev,ScheduleExchangeReq +51,evse,ScheduleExchangeRes +53,ev,PowerDeliveryReq +55,evse,PowerDeliveryRes +58,ev,PowerDeliveryReq +60,evse,PowerDeliveryRes +62,ev,AC_ChargeLoopReq +64,evse,AC_ChargeLoopRes +67,ev,AC_ChargeLoopReq +69,evse,AC_ChargeLoopRes +71,ev,AC_ChargeLoopReq +72,evse,AC_ChargeLoopRes +74,ev,AC_ChargeLoopReq +75,evse,AC_ChargeLoopRes +77,ev,AC_ChargeLoopReq +78,evse,AC_ChargeLoopRes +80,ev,AC_ChargeLoopReq +81,evse,AC_ChargeLoopRes +83,ev,AC_ChargeLoopReq +84,evse,AC_ChargeLoopRes +86,ev,AC_ChargeLoopReq +87,evse,AC_ChargeLoopRes +89,ev,PowerDeliveryReq +90,evse,PowerDeliveryRes +92,ev,SessionStopReq +93,evse,SessionStopRes diff --git a/testing/suites/v2g/captures/iso20-ac-bpt.pcapng b/testing/suites/v2g/captures/iso20-ac-bpt.pcapng new file mode 100644 index 0000000..fccd270 Binary files /dev/null and b/testing/suites/v2g/captures/iso20-ac-bpt.pcapng differ diff --git a/testing/suites/v2g/captures/iso20-ac.messages.csv b/testing/suites/v2g/captures/iso20-ac.messages.csv new file mode 100644 index 0000000..ecb21f7 --- /dev/null +++ b/testing/suites/v2g/captures/iso20-ac.messages.csv @@ -0,0 +1,47 @@ +frame,direction,message +12,ev,SupportedAppProtocolReq +14,evse,SupportedAppProtocolRes +16,ev,SessionSetupReq +18,evse,SessionSetupRes +20,ev,AuthorizationSetupReq +22,evse,AuthorizationSetupRes +24,ev,AuthorizationReq +25,evse,AuthorizationRes +27,ev,ServiceDiscoveryReq +28,evse,ServiceDiscoveryRes +30,ev,ServiceDetailReq +31,evse,ServiceDetailRes +33,ev,ServiceDetailReq +34,evse,ServiceDetailRes +36,ev,ServiceDetailReq +37,evse,ServiceDetailRes +39,ev,ServiceSelectionReq +40,evse,ServiceSelectionRes +42,ev,AC_ChargeParameterDiscoveryReq +43,evse,AC_ChargeParameterDiscoveryRes +45,ev,ScheduleExchangeReq +46,evse,ScheduleExchangeRes +48,ev,PowerDeliveryReq +50,evse,PowerDeliveryRes +52,ev,AC_ChargeLoopReq +54,evse,AC_ChargeLoopRes +58,ev,AC_ChargeLoopReq +60,evse,AC_ChargeLoopRes +62,ev,AC_ChargeLoopReq +64,evse,AC_ChargeLoopRes +66,ev,AC_ChargeLoopReq +67,evse,AC_ChargeLoopRes +69,ev,AC_ChargeLoopReq +70,evse,AC_ChargeLoopRes +72,ev,AC_ChargeLoopReq +73,evse,AC_ChargeLoopRes +75,ev,AC_ChargeLoopReq +76,evse,AC_ChargeLoopRes +78,ev,AC_ChargeLoopReq +79,evse,AC_ChargeLoopRes +81,ev,AC_ChargeLoopReq +82,evse,AC_ChargeLoopRes +84,ev,PowerDeliveryReq +85,evse,PowerDeliveryRes +87,ev,SessionStopReq +88,evse,SessionStopRes diff --git a/testing/suites/v2g/captures/iso20-ac.pcapng b/testing/suites/v2g/captures/iso20-ac.pcapng new file mode 100644 index 0000000..e1aa861 Binary files /dev/null and b/testing/suites/v2g/captures/iso20-ac.pcapng differ diff --git a/testing/suites/v2g/captures/iso20-dc-bpt.messages.csv b/testing/suites/v2g/captures/iso20-dc-bpt.messages.csv new file mode 100644 index 0000000..ab6ab93 --- /dev/null +++ b/testing/suites/v2g/captures/iso20-dc-bpt.messages.csv @@ -0,0 +1,77 @@ +frame,direction,message +10,ev,SupportedAppProtocolReq +12,evse,SupportedAppProtocolRes +15,ev,SessionSetupReq +17,evse,SessionSetupRes +19,ev,AuthorizationSetupReq +21,evse,AuthorizationSetupRes +23,ev,AuthorizationReq +24,evse,AuthorizationRes +26,ev,ServiceDiscoveryReq +27,evse,ServiceDiscoveryRes +29,ev,ServiceDetailReq +30,evse,ServiceDetailRes +32,ev,ServiceDetailReq +33,evse,ServiceDetailRes +35,ev,ServiceSelectionReq +36,evse,ServiceSelectionRes +38,ev,DC_ChargeParameterDiscoveryReq +39,evse,DC_ChargeParameterDiscoveryRes +41,ev,ScheduleExchangeReq +42,evse,ScheduleExchangeRes +44,ev,DC_CableCheckReq +45,evse,DC_CableCheckRes +47,ev,DC_CableCheckReq +48,evse,DC_CableCheckRes +50,ev,DC_CableCheckReq +51,evse,DC_CableCheckRes +54,ev,DC_CableCheckReq +55,evse,DC_CableCheckRes +57,ev,DC_CableCheckReq +58,evse,DC_CableCheckRes +60,ev,DC_CableCheckReq +61,evse,DC_CableCheckRes +63,ev,DC_CableCheckReq +64,evse,DC_CableCheckRes +66,ev,DC_CableCheckReq +67,evse,DC_CableCheckRes +70,ev,DC_CableCheckReq +71,evse,DC_CableCheckRes +73,ev,DC_PreChargeReq +74,evse,DC_PreChargeRes +76,ev,DC_PreChargeReq +77,evse,DC_PreChargeRes +79,ev,PowerDeliveryReq +80,evse,PowerDeliveryRes +82,ev,PowerDeliveryReq +83,evse,PowerDeliveryRes +85,ev,PowerDeliveryReq +86,evse,PowerDeliveryRes +88,ev,PowerDeliveryReq +89,evse,PowerDeliveryRes +91,ev,PowerDeliveryReq +92,evse,PowerDeliveryRes +94,ev,DC_ChargeLoopReq +95,evse,DC_ChargeLoopRes +97,ev,DC_ChargeLoopReq +98,evse,DC_ChargeLoopRes +100,ev,DC_ChargeLoopReq +101,evse,DC_ChargeLoopRes +103,ev,DC_ChargeLoopReq +104,evse,DC_ChargeLoopRes +106,ev,DC_ChargeLoopReq +107,evse,DC_ChargeLoopRes +109,ev,PowerDeliveryReq +110,evse,PowerDeliveryRes +112,ev,DC_WeldingDetectionReq +113,evse,DC_WeldingDetectionRes +115,ev,DC_WeldingDetectionReq +116,evse,DC_WeldingDetectionRes +118,ev,DC_WeldingDetectionReq +119,evse,DC_WeldingDetectionRes +121,ev,DC_WeldingDetectionReq +122,evse,DC_WeldingDetectionRes +124,ev,DC_WeldingDetectionReq +125,evse,DC_WeldingDetectionRes +127,ev,SessionStopReq +128,evse,SessionStopRes diff --git a/testing/suites/v2g/captures/iso20-dc-bpt.pcapng b/testing/suites/v2g/captures/iso20-dc-bpt.pcapng new file mode 100644 index 0000000..37e4f42 Binary files /dev/null and b/testing/suites/v2g/captures/iso20-dc-bpt.pcapng differ diff --git a/testing/suites/v2g/captures/iso20-dc.messages.csv b/testing/suites/v2g/captures/iso20-dc.messages.csv new file mode 100644 index 0000000..68bf765 --- /dev/null +++ b/testing/suites/v2g/captures/iso20-dc.messages.csv @@ -0,0 +1,75 @@ +frame,direction,message +14,ev,SupportedAppProtocolReq +16,evse,SupportedAppProtocolRes +18,ev,SessionSetupReq +20,evse,SessionSetupRes +22,ev,AuthorizationSetupReq +24,evse,AuthorizationSetupRes +26,ev,AuthorizationReq +27,evse,AuthorizationRes +29,ev,ServiceDiscoveryReq +30,evse,ServiceDiscoveryRes +32,ev,ServiceDetailReq +33,evse,ServiceDetailRes +35,ev,ServiceSelectionReq +36,evse,ServiceSelectionRes +38,ev,DC_ChargeParameterDiscoveryReq +39,evse,DC_ChargeParameterDiscoveryRes +41,ev,ScheduleExchangeReq +42,evse,ScheduleExchangeRes +44,ev,DC_CableCheckReq +45,evse,DC_CableCheckRes +47,ev,DC_CableCheckReq +48,evse,DC_CableCheckRes +50,ev,DC_CableCheckReq +51,evse,DC_CableCheckRes +53,ev,DC_CableCheckReq +54,evse,DC_CableCheckRes +56,ev,DC_CableCheckReq +57,evse,DC_CableCheckRes +60,ev,DC_CableCheckReq +61,evse,DC_CableCheckRes +64,ev,DC_CableCheckReq +65,evse,DC_CableCheckRes +67,ev,DC_CableCheckReq +68,evse,DC_CableCheckRes +70,ev,DC_CableCheckReq +71,evse,DC_CableCheckRes +73,ev,DC_PreChargeReq +74,evse,DC_PreChargeRes +76,ev,DC_PreChargeReq +77,evse,DC_PreChargeRes +79,ev,PowerDeliveryReq +80,evse,PowerDeliveryRes +82,ev,DC_ChargeLoopReq +83,evse,DC_ChargeLoopRes +85,ev,DC_ChargeLoopReq +86,evse,DC_ChargeLoopRes +88,ev,DC_ChargeLoopReq +89,evse,DC_ChargeLoopRes +91,ev,DC_ChargeLoopReq +92,evse,DC_ChargeLoopRes +94,ev,DC_ChargeLoopReq +95,evse,DC_ChargeLoopRes +97,ev,DC_ChargeLoopReq +98,evse,DC_ChargeLoopRes +100,ev,DC_ChargeLoopReq +101,evse,DC_ChargeLoopRes +103,ev,DC_ChargeLoopReq +104,evse,DC_ChargeLoopRes +106,ev,DC_ChargeLoopReq +107,evse,DC_ChargeLoopRes +109,ev,PowerDeliveryReq +110,evse,PowerDeliveryRes +112,ev,DC_WeldingDetectionReq +113,evse,DC_WeldingDetectionRes +115,ev,DC_WeldingDetectionReq +116,evse,DC_WeldingDetectionRes +118,ev,DC_WeldingDetectionReq +119,evse,DC_WeldingDetectionRes +121,ev,DC_WeldingDetectionReq +122,evse,DC_WeldingDetectionRes +124,ev,DC_WeldingDetectionReq +125,evse,DC_WeldingDetectionRes +127,ev,SessionStopReq +128,evse,SessionStopRes diff --git a/testing/suites/v2g/captures/iso20-dc.pcapng b/testing/suites/v2g/captures/iso20-dc.pcapng new file mode 100644 index 0000000..ef30c22 Binary files /dev/null and b/testing/suites/v2g/captures/iso20-dc.pcapng differ diff --git a/testing/suites/v2g/conftest.py b/testing/suites/v2g/conftest.py new file mode 100644 index 0000000..0394d7f --- /dev/null +++ b/testing/suites/v2g/conftest.py @@ -0,0 +1,232 @@ +"""An EVerest EVSE and EV charging over a veth pair, one session per run. + +The EVSE side (EvseV2G, or Evse15118D20 for ISO 15118-20, and the simulated hardware) runs under the EVerest +manager in the container's namespace on v2g-evse. The EV (PyEvJosev, which +encodes with its own EXI codec) runs standalone in a namespace of its own on +the peer, v2g-ev, so SDP and the V2G TCP connection cross the link. The two +reach one Mosquitto over a Unix socket, which no namespace hides. SLAC is +simulated in process: no HomePlug frames on the link. + +Runs in the SIL image, which carries EVerest, Mosquitto and dumpcap and has +CAP_NET_ADMIN and CAP_SYS_ADMIN. From the repository root: + + just test-v2g +""" + +import contextlib +import json +import os +import shutil +import signal +import subprocess +import time +from collections.abc import Callable, Iterator +from dataclasses import dataclass, field +from pathlib import Path + +import pytest +import yaml + +HERE = Path(__file__).parent +PREFIX = Path("/ext/dist") +SOCKET = "/run/mqtt.sock" +EVSE_IF, EV_IF = "v2g-evse", "v2g-ev" +# EvManager: matched, start DC, wait for the EVSE's power, close the contactors. +START = "iso_wait_slac_matched;iso_start_v2g_session DC 86400 0;iso_wait_pwr_ready;iso_dc_power_on" +# AC: draw 16 A on three phases instead. +START_AC = "iso_wait_slac_matched;iso_start_v2g_session AC 86400 0;iso_wait_pwr_ready;iso_draw_power_regulated 16,3" +# Boot to a finished session, with every module's start-up. +SESSION_S = 90.0 +# Where the EVSE writes tls_session_keys.log in a TLS session. +KEYS = "/tmp/everest-keys" + + +def pytest_addoption(parser): + parser.addoption("--record", type=Path, help="Keep each session's pcapng, MQTT record and logs in this directory") + + +@dataclass +class Session: + """One run's evidence: the link's capture and the modules' MQTT variables.""" + + pcap: Path + # (topic, payload) of every module variable, in the order published. + vars: list[tuple[str, dict]] = field(default_factory=list) + # A TLS session's secrets, as the EVSE logged them (NSS key log format). + keys: Path | None = None + + def var(self, module: str, name: str) -> list: + """Every value module published for variable name.""" + return [p.get("data") for t, p in self.vars if t.startswith(f"everest/modules/{module}/") and p.get("name") == name] + + +def run(*cmd: str) -> None: + subprocess.run(cmd, check=True) + + +def wait(done: Callable[[], bool], timeout_s: float, what: str) -> None: + end = time.monotonic() + timeout_s + while not done(): + assert time.monotonic() < end, f"no {what} within {timeout_s} s" + time.sleep(0.1) + + +def link_ready(iface: str) -> bool: + """A link-local address, past duplicate address detection.""" + out = subprocess.run(["ip", "-6", "-o", "addr", "show", "dev", iface, "scope", "link"], capture_output=True, text=True).stdout + return "inet6" in out and "tentative" not in out + + +@contextlib.contextmanager +def proc(cmd: list[str], log: Path, **kw) -> Iterator[subprocess.Popen]: + """A process for the block, its output in log; TERM, then KILL after 3 s.""" + with log.open("wb") as out: + p = subprocess.Popen(cmd, stdout=out, stderr=subprocess.STDOUT, start_new_session=True, **kw) + try: + yield p + finally: + with contextlib.suppress(ProcessLookupError): + os.killpg(p.pid, signal.SIGTERM) + try: + p.wait(3) + except subprocess.TimeoutExpired: + os.killpg(p.pid, signal.SIGKILL) + p.wait() + + +@pytest.fixture(scope="session") +def broker(tmp_path_factory) -> Iterator[None]: + if shutil.which("mosquitto") is None or not (PREFIX / "bin/manager").exists(): + pytest.skip("runs in the SIL image: just test-v2g") + conf = tmp_path_factory.mktemp("mqtt") / "mosquitto.conf" + conf.write_text(f"listener 0 {SOCKET}\nallow_anonymous true\nuser root\n") + with proc(["mosquitto", "-c", str(conf)], conf.with_suffix(".log")): + wait(lambda: Path(SOCKET).exists(), 5, "broker socket") + yield + + +def config(protocol: str, commands: str, imd: dict | None) -> dict: + """protocol: "iso2", "din", or "iso20-" and the energy service: "dc", "ac", "dc-bpt", "ac-bpt". + + "iso2-tls" and "iso20-dc-tls" run over TLS (1.2 and 1.3), the EVSE logging the session's secrets. + """ + tls = protocol.endswith("-tls") + protocol = protocol.removesuffix("-tls") + iso20, _, service = protocol.partition("-") + ac = service.startswith("ac") + cfg = yaml.safe_load((HERE / ("everest-ac.yaml" if ac else "everest.yaml")).read_text()) + mods = cfg["active_modules"] + ev = mods["iso15118_car"]["config_module"] + mods["ev_manager"]["config_module"]["auto_exec_commands"] = f"{START_AC if ac else START};{commands}" + if service: + # The EV's first service is the one selected. + ev["supported_d20_energy_services"] = ",".join(s.upper().replace("-", "_") for s in (service, service.removesuffix("-bpt"))) + if tls: + ev.update(tls_active=True, enforce_tls=True, enable_tls_1_3=bool(service)) + # Josev pays by contract over TLS where the EVSE offers it, and nothing here authorizes one. + mods["evse_manager"]["config_module"]["payment_enable_contract"] = False + # The EVSE's key log: a line per secret in KEYS/tls_session_keys.log, and each in a datagram to ff02::1 on the link. + mods["iso15118_charger"]["config_module"].update(tls_security="force", tls_key_logging=True, tls_key_logging_path=KEYS) + if ac: + return cfg + ev["supported_DIN70121"], ev["supported_ISO15118_2"] = protocol == "din", protocol == "iso2" + if service: + ev["supported_ISO15118_20_DC"] = True + # Plain TCP, as EvseV2G's tls_security: prohibit. + mods["iso15118_charger"] = { + **mods["iso15118_charger"], + "module": "Evse15118D20", + "config_module": {"device": EVSE_IF, "tls_negotiation_strategy": "ENFORCE_NO_TLS", "logging_path": "/tmp/everest-logs"}, + } + if tls: + mods["iso15118_charger"]["config_module"].update( + tls_negotiation_strategy="ENFORCE_TLS", enforce_tls_1_3=True, enable_tls_key_logging=True, tls_key_logging_path=KEYS + ) + mods["imd"]["config_implementation"]["main"].update(imd or {}) + return cfg + + +@pytest.fixture +def charge(broker, request, tmp_path) -> Callable[..., Session]: + """charge(protocol, commands, done, imd=None): one session, until done(session) holds. + + protocol: the one the EV offers, as config takes it. commands: EvManager's + script after START. done: the end the test expects, on MQTT variables. + """ + record = request.config.getoption("record") + out = record / request.node.name if record else tmp_path + out.mkdir(parents=True, exist_ok=True) + + def charge(protocol: str, commands: str, done: Callable[[Session], bool], imd: dict | None = None) -> Session: + (out / "everest.yaml").write_text(yaml.safe_dump(config(protocol, commands, imd))) + session = Session(out / f"{protocol}.pcapng") + keylog = Path(KEYS) / "tls_session_keys.log" + keylog.parent.mkdir(exist_ok=True) + keylog.unlink(missing_ok=True) + run("ip", "link", "add", EVSE_IF, "type", "veth", "peer", "name", EV_IF) + try: + with contextlib.ExitStack() as stack: + # The EV's namespace lives as long as this shell. It starts the + # module once its link is up and the manager can configure it. + pidfile, go = out / "ev.pid", out / "ev.go" + pidfile.unlink(missing_ok=True) + go.unlink(missing_ok=True) + ev_env = { + **os.environ, + "PYTHONPATH": str(PREFIX / "lib/everest/everestpy"), + "EV_MODULE": "iso15118_car", + "EV_PREFIX": str(PREFIX), + "EV_LOG_CONF_FILE": str(PREFIX / "etc/everest/default_logging.cfg"), + "EV_MQTT_EVEREST_PREFIX": "everest/", + "EV_MQTT_EXTERNAL_PREFIX": "", + "EV_MQTT_BROKER_SOCKET_PATH": SOCKET, + } + script = ( + f"echo $$ > {pidfile}; until ip link show {EV_IF} >/dev/null 2>&1; do sleep 0.1; done; " + f"ip link set lo up && ip link set {EV_IF} up && " + f"until ip -6 -o addr show dev {EV_IF} scope link | grep -v tentative | grep -q inet6; do sleep 0.1; done; " + f"until [ -e {go} ]; do sleep 0.1; done; exec python3 {PREFIX}/libexec/everest/modules/PyEvJosev/module.py" + ) + ev = stack.enter_context(proc(["unshare", "-n", "bash", "-c", script], out / "ev.log", env=ev_env)) + wait(lambda: pidfile.exists() and pidfile.read_text().strip(), 5, "EV namespace") + run("ip", "link", "set", EV_IF, "netns", pidfile.read_text().strip()) + run("ip", "link", "set", EVSE_IF, "up") + wait(lambda: link_ready(EVSE_IF), 10, f"{EVSE_IF} address") + + mqtt = out / "vars.txt" + stack.enter_context(proc(["mosquitto_sub", "--unix", SOCKET, "-v", "-t", "everest/modules/+/impl/+/var"], mqtt)) + stack.enter_context(proc(["dumpcap", "-q", "-i", EVSE_IF, "-w", str(session.pcap)], out / "dumpcap.log")) + wait(lambda: session.pcap.exists(), 5, "capture") + env = {**os.environ, "LD_LIBRARY_PATH": str(PREFIX / "lib")} + log = out / "manager.log" + manager = stack.enter_context(proc([str(PREFIX / "bin/manager"), "--prefix", str(PREFIX), "--conf", str(out / "everest.yaml")], log, env=env)) + wait(lambda: b"Not starting standalone module" in log.read_bytes(), 30, "manager up") + go.touch() + + def over() -> bool: + assert manager.poll() is None, f"manager exited {manager.returncode}: {out / 'manager.log'}" + assert ev.poll() is None, f"EV exited {ev.returncode}: {out / 'ev.log'}" + session.vars = read_vars(mqtt) + return done(session) + + wait(over, SESSION_S, "session end") + # The connection's last segments. + time.sleep(1.0) + finally: + subprocess.run(["ip", "link", "del", EVSE_IF], stderr=subprocess.DEVNULL) + session.vars = read_vars(out / "vars.txt") + if keylog.exists(): + session.keys = Path(shutil.copy(keylog, session.pcap.with_suffix(".keys"))) + return session + + return charge + + +def read_vars(path: Path) -> list[tuple[str, dict]]: + """mosquitto_sub -v lines: topic, a space, the JSON payload. A line still being written is left.""" + got = [] + for line in path.read_text().splitlines(): + topic, _, payload = line.partition(" ") + with contextlib.suppress(json.JSONDecodeError): + got.append((topic, json.loads(payload))) + return got diff --git a/testing/suites/v2g/everest-ac.yaml b/testing/suites/v2g/everest-ac.yaml new file mode 100644 index 0000000..d8c1e14 --- /dev/null +++ b/testing/suites/v2g/everest-ac.yaml @@ -0,0 +1,145 @@ +# EVerest 2025.10.0: a simulated AC EVSE and EV over ISO 15118-20, from the +# image's config-sil-ac-d20.yaml. The broker, the standalone EV and the veth +# are everest.yaml's. conftest.py sets, per run, the energy services the EV +# offers and EvManager's script. +settings: + mqtt_broker_socket_path: /run/mqtt.sock +active_modules: + iso15118_charger: + module: Evse15118D20 + config_module: + device: v2g-evse + # Plain TCP: the capture's EXI is readable. + tls_negotiation_strategy: ENFORCE_NO_TLS + logging_path: /tmp/everest-logs + connections: + security: + - module_id: evse_security + implementation_id: main + iso15118_car: + module: PyEvJosev + standalone: true + config_module: + device: v2g-ev + supported_ISO15118_20_AC: true + supported_d20_energy_services: set by conftest.py + tls_active: false + evse_manager: + module: EvseManager + config_module: + connector_id: 1 + evse_id: DE*PNX*E12345*1 + session_logging: true + session_logging_xml: false + session_logging_path: /tmp/everest-logs + charge_mode: AC + ac_hlc_enabled: true + ac_hlc_use_5percent: false + ac_enforce_hlc: false + ac_nominal_voltage: 230 + supported_iso_ac_bpt: true + has_ventilation: true + max_current_import_A: 32 + max_current_export_A: 32 + payment_enable_contract: false + payment_enable_eim: true + bpt_channel: Unified + bpt_generator_mode: GridFollowing + bpt_grid_code_island_method: Passive + connections: + bsp: + - module_id: yeti_driver + implementation_id: board_support + powermeter_car_side: + - module_id: yeti_driver + implementation_id: powermeter + slac: + - module_id: slac + implementation_id: evse + hlc: + - module_id: iso15118_charger + implementation_id: charger + ac_rcd: + - module_id: yeti_driver + implementation_id: rcd + connector_lock: + - module_id: yeti_driver + implementation_id: connector_lock + yeti_driver: + module: YetiSimulator + config_module: + connector_id: 1 + # SLAC in process: no HomePlug frames on the link. + slac: + module: SlacSimulator + ev_manager: + module: EvManager + config_module: + connector_id: 1 + auto_enable: true + auto_exec: true + auto_exec_commands: set by conftest.py + connections: + ev_board_support: + - module_id: yeti_driver + implementation_id: ev_board_support + ev: + - module_id: iso15118_car + implementation_id: ev + slac: + - module_id: slac + implementation_id: ev + auth: + module: Auth + config_module: + connection_timeout: 10 + selection_algorithm: FindFirst + connections: + token_provider: + - module_id: token_provider + implementation_id: main + token_validator: + - module_id: token_validator + implementation_id: main + evse_manager: + - module_id: evse_manager + implementation_id: evse + token_provider: + module: DummyTokenProvider + config_implementation: + main: + token: TOKEN1 + connections: + evse: + - module_id: evse_manager + implementation_id: evse + token_validator: + module: DummyTokenValidator + config_implementation: + main: + validation_result: Accepted + validation_reason: Token seems valid + sleep: 0.25 + evse_security: + module: EvseSecurity + config_module: + private_key_password: "123456" + energy_manager: + module: EnergyManager + connections: + energy_trunk: + - module_id: grid_connection_point + implementation_id: energy_grid + grid_connection_point: + module: EnergyNode + config_module: + fuse_limit_A: 40.0 + phase_count: 3 + connections: + price_information: [] + energy_consumer: + - module_id: evse_manager + implementation_id: energy_grid + powermeter: + - module_id: yeti_driver + implementation_id: powermeter diff --git a/testing/suites/v2g/everest.yaml b/testing/suites/v2g/everest.yaml new file mode 100644 index 0000000..2fc0d4a --- /dev/null +++ b/testing/suites/v2g/everest.yaml @@ -0,0 +1,150 @@ +# EVerest 2025.10.0: a simulated DC EVSE and EV, from the image's +# config-sil-dc.yaml. conftest.py sets, per run, the protocol the EV offers, +# EvManager's script and the isolation monitor's reading. +# +# The broker is a Unix socket, so the EV reaches it from its own network +# namespace. The EV (iso15118_car) is standalone: conftest.py starts it in that +# namespace on v2g-ev. The EVSE listens on v2g-evse, the other end of the veth. +settings: + mqtt_broker_socket_path: /run/mqtt.sock +active_modules: + iso15118_charger: + module: EvseV2G + config_module: + device: v2g-evse + # Plain TCP: the capture's EXI is readable. + tls_security: prohibit + connections: + security: + - module_id: evse_security + implementation_id: main + iso15118_car: + module: PyEvJosev + standalone: true + config_module: + device: v2g-ev + supported_DIN70121: false + supported_ISO15118_2: true + tls_active: false + evse_manager: + module: EvseManager + config_module: + connector_id: 1 + evse_id: DE*PNX*E12345*1 + evse_id_din: 49A80737A45678 + session_logging: true + session_logging_xml: false + session_logging_path: /tmp/everest-logs + charge_mode: DC + connections: + bsp: + - module_id: yeti_driver + implementation_id: board_support + powermeter_car_side: + - module_id: powersupply_dc + implementation_id: powermeter + slac: + - module_id: slac + implementation_id: evse + hlc: + - module_id: iso15118_charger + implementation_id: charger + powersupply_DC: + - module_id: powersupply_dc + implementation_id: main + imd: + - module_id: imd + implementation_id: main + over_voltage_monitor: + - module_id: ovm + implementation_id: main + powersupply_dc: + module: DCSupplySimulator + yeti_driver: + module: YetiSimulator + config_module: + connector_id: 1 + # SLAC in process: no HomePlug frames on the link. + slac: + module: SlacSimulator + imd: + module: IMDSimulator + config_implementation: + main: + selftest_success: true + resistance_F_Ohm: 900000 + ovm: + module: OVMSimulator + ev_manager: + module: EvManager + config_module: + connector_id: 1 + auto_enable: true + auto_exec: true + auto_exec_commands: set by conftest.py + dc_target_current: 20 + dc_target_voltage: 400 + connections: + ev_board_support: + - module_id: yeti_driver + implementation_id: ev_board_support + ev: + - module_id: iso15118_car + implementation_id: ev + slac: + - module_id: slac + implementation_id: ev + auth: + module: Auth + config_module: + connection_timeout: 10 + selection_algorithm: FindFirst + connections: + token_provider: + - module_id: token_provider + implementation_id: main + token_validator: + - module_id: token_validator + implementation_id: main + evse_manager: + - module_id: evse_manager + implementation_id: evse + token_provider: + module: DummyTokenProvider + config_implementation: + main: + token: TOKEN1 + connections: + evse: + - module_id: evse_manager + implementation_id: evse + token_validator: + module: DummyTokenValidator + config_implementation: + main: + validation_result: Accepted + validation_reason: Token seems valid + sleep: 0.25 + evse_security: + module: EvseSecurity + config_module: + private_key_password: "123456" + energy_manager: + module: EnergyManager + connections: + energy_trunk: + - module_id: grid_connection_point + implementation_id: energy_grid + grid_connection_point: + module: EnergyNode + config_module: + fuse_limit_A: 40.0 + phase_count: 3 + connections: + price_information: [] + energy_consumer: + - module_id: evse_manager + implementation_id: energy_grid + powermeter: + - module_id: yeti_driver + implementation_id: powermeter diff --git a/testing/suites/v2g/test_session.py b/testing/suites/v2g/test_session.py new file mode 100644 index 0000000..0c9122b --- /dev/null +++ b/testing/suites/v2g/test_session.py @@ -0,0 +1,296 @@ +"""Charging sessions between EVerest's EVSE and EV, DC over ISO 15118-2 and +DIN 70121, DC and AC over ISO 15118-20, checked on the link they crossed. + +The capture is walked at the V2GTP layer (ISO 15118-2 clause 7.8): SDP on UDP +15118, then each direction of the TCP connection split into V2GTP frames with +nothing left over. EXI is not decoded here. Each frame is named by the EVSE's +own record of it (the v2g_messages variable). EvseV2G's carries the frame's +bytes and is accepted only where they match; Evse15118D20's is the name alone, +accepted where it fits the frame's direction and payload type. The EV encodes +with another codec (EXIficient, in Josev), so a session that completes is two +codecs agreeing. + + just test-v2g # every test + just v2g-record # re-record captures/ from the sessions +""" + +import csv +import itertools +import re +import shutil +import struct +import subprocess +from dataclasses import dataclass +from pathlib import Path + +import pytest + +HERE = Path(__file__).parent +V2G_PORT = 15118 +SDP_REQ, SDP_RES, EXI = 0x9000, 0x9001, 0x8001 +# ISO 15118-20 names a message's schema in its payload type: common, AC, DC. +ISO20 = {"AC_": 0x8003, "DC_": 0x8004, "": 0x8002} +# What the EV's script does after START (conftest), and the end each test waits for. +STOP_AFTER_S = 5 +EV_STOP = f"sleep {STOP_AFTER_S};iso_stop_charging;iso_wait_v2g_session_stopped;unplug" + + +@dataclass +class Protocol: + # The EVSE's selected_protocol, and the committed capture's name. + selected: str + capture: str + # The session's first exchanges, its charge sequence ending in the loop, and its last. + setup: list[str] + charge: list[str] + stop: list[str] + + +SETUP = ["SupportedAppProtocol", "SessionSetup", "ServiceDiscovery"] +CHARGE = ["CableCheck", "PreCharge", "PowerDelivery", "CurrentDemand"] +STOP = ["PowerDelivery", "WeldingDetection", "SessionStop"] +SETUP20 = ["SupportedAppProtocol", "SessionSetup", "AuthorizationSetup", "Authorization", "ServiceDiscovery"] +DC20 = (SETUP20, ["DC_CableCheck", "DC_PreCharge", "PowerDelivery", "DC_ChargeLoop"], ["PowerDelivery", "DC_WeldingDetection", "SessionStop"]) +AC20 = (SETUP20, ["AC_ChargeParameterDiscovery", "ScheduleExchange", "PowerDelivery", "AC_ChargeLoop"], ["AC_ChargeLoop", "PowerDelivery", "SessionStop"]) +PROTOCOLS = { + "iso2": Protocol("ISO15118-2-2013", "iso2-dc", SETUP, CHARGE, STOP), + "din": Protocol("DIN70121", "din-dc", SETUP, CHARGE, STOP), + "iso20-dc": Protocol("ISO15118-20:DC", "iso20-dc", *DC20), + "iso20-dc-bpt": Protocol("ISO15118-20:DC", "iso20-dc-bpt", *DC20), + "iso20-ac": Protocol("ISO15118-20:AC", "iso20-ac", *AC20), + "iso20-ac-bpt": Protocol("ISO15118-20:AC", "iso20-ac-bpt", *AC20), + # Over TLS (1.2, and 1.3 for ISO 15118-20), walked through tshark's decryption. No committed capture. + "iso2-tls": Protocol("ISO15118-2-2013", "", SETUP, CHARGE, STOP), + "iso20-dc-tls": Protocol("ISO15118-20:DC", "", *DC20), +} + + +@dataclass +class Frame: + t: float + # The capture's frame number of the segment holding the V2GTP frame's first byte. + number: int + from_ev: bool + type: int + payload: bytes + raw: bytes + + +def fields(pcap: Path, *names: str, keys: Path | None = None) -> list[list[str]]: + """keys: a TLS key log file to decrypt with.""" + out = subprocess.run( + ["tshark", "-r", str(pcap), *(["-o", f"tls.keylog_file:{keys}"] if keys else []), "-T", "fields", "-E", "separator=|", *itertools.chain.from_iterable(("-e", n) for n in names)], + check=True, + capture_output=True, + text=True, + ).stdout + return [line.split("|") for line in out.splitlines()] + + +def v2gtp(data: bytes) -> list[tuple[int, bytes, bytes]]: + """(payload type, payload, frame) of each V2GTP frame in data, which they must fill exactly.""" + got, i = [], 0 + while i < len(data): + assert len(data) - i >= 8, f"{len(data) - i} bytes left over" + version, inverse, ptype, n = struct.unpack_from("!BBHI", data, i) + assert (version, inverse) == (0x01, 0xFE), data[i : i + 8].hex() + assert i + 8 + n <= len(data), f"frame of {n} bytes, {len(data) - i - 8} left" + got.append((ptype, data[i + 8 : i + 8 + n], data[i : i + 8 + n])) + i += 8 + n + return got + + +def sdp(pcap: Path) -> list[tuple[str, int, int, bytes]]: + """(source, source port, payload type, payload) of each SDP datagram.""" + rows = fields(pcap, "ipv6.src", "udp.srcport", "udp.dstport", "udp.payload") + got = [] + for src, sport, dport, payload in rows: + if V2G_PORT in (int(sport or 0), int(dport or 0)): + ((ptype, body, _),) = v2gtp(bytes.fromhex(payload)) + got.append((src, int(sport), ptype, body)) + return got + + +def tcp(pcap: Path, keys: Path | None = None) -> tuple[tuple[str, int], list[Frame], set[str]]: + """The one connection's server (address, port), its V2GTP frames in time order, and its flags seen. + + keys: the connection is TLS, and the frames are in what tshark decrypts with this key log file. + """ + data = "data.data" if keys else "tcp.payload" + rows = fields(pcap, "frame.number", "frame.time_epoch", "ipv6.src", "ipv6.dst", "tcp.srcport", "tcp.dstport", "tcp.seq_raw", "tcp.len", "tcp.flags.str", data, keys=keys) + rows = [r[1:] + r[:1] for r in rows if r[4]] + syn = [r for r in rows if "S" in r[7] and "A" not in r[7].replace("ยท", "")] + assert len(syn) == 1, f"{len(syn)} connections" + ev, server = (syn[0][1], int(syn[0][3])), (syn[0][2], int(syn[0][4])) + flags = set() + streams: dict[bool, list[tuple[float, int, int, bytes, int]]] = {True: [], False: []} + for t, src, _, sport, _, seq, n, f, payload, number in rows: + from_ev = (src, int(sport)) == ev + assert from_ev or (src, int(sport)) == server, f"a second peer {src}:{sport}" + flags.update(c for c in f if c.isalpha()) + if int(n): + # A segment's TLS records, each decrypted, come comma separated. + streams[from_ev].append((float(t), int(seq), int(n), bytes.fromhex(payload.replace(",", "")), int(number))) + frames = [] + for from_ev, segs in streams.items(): + # A veth loses and reorders nothing: each segment follows the last. + for (_, a, n, _, _), (_, b, _, _, _) in itertools.pairwise(segs): + assert b == (a + n) % 2**32, "a gap or retransmission in the stream" + # A frame starts in the segment holding its first byte. + starts, data = [], b"" + for t, _, _, p, number in segs: + starts.append((len(data), t, number)) + data += p + at = 0 + for ptype, body, raw in v2gtp(data): + _, t, number = max(s for s in starts if s[0] <= at) + frames.append(Frame(t, number, from_ev, ptype, body, raw)) + at += len(raw) + frames.sort(key=lambda f: f.t) + return server, frames, flags + + +def names(session, frames: list[Frame]) -> list[str]: + """Each frame's message name, from the EVSE's record of the same bytes. + + A request the EVSE never read, sent as the link went, is the one frame it + may lack: the last, named "?". + """ + record = session.var("iso15118_charger", "v2g_messages") + unread = len(frames) - len(record) + assert unread == 0 or (unread == 1 and frames[-1].from_ev), f"{len(record)} recorded, {len(frames)} on the wire" + got = [] + for f, r in zip(frames, record, strict=False): + assert r["id"].endswith("Req") == f.from_ev, r["id"] + if "exi" not in r: + # Evse15118D20 records the name alone, DcChargeLoopReq for DC_ChargeLoopReq. + name = re.sub("^(Ac|Dc)", lambda m: m[1].upper() + "_", r["id"]) + ptype = EXI if name.startswith("SupportedAppProtocol") else ISO20.get(name[:3], ISO20[""]) + assert f.type == ptype, (name, hex(f.type)) + got.append(name) + continue + exi = bytes.fromhex(r["exi"]) + if f.from_ev: + assert exi == f.raw, f"{r['id']}: recorded {exi.hex()}, wire {f.raw.hex()}" + else: + # EvseV2G 2025.10 records a response in its request's frame: the + # request's header and length, the response's EXI cut or padded to it. + n = min(len(exi) - 8, len(f.payload)) + assert exi[8 : 8 + n] == f.payload[:n], f"{r['id']}: recorded {exi.hex()}, wire {f.raw.hex()}" + got.append(r["id"]) + return got + ["?"] * unread + + +def exchanges(msgs: list[str]) -> list[str]: + """Request/response pairs, as one name each; asserts each request is answered by its response. + + An unanswered last request is left out. + """ + got = [] + for req, res in zip(msgs[::2], msgs[1::2], strict=False): + assert req.endswith("Req") and res == req[:-3] + "Res", (req, res) + got.append(req[:-3]) + return got + + +def runs(seq: list[str]) -> list[str]: + return [k for k, _ in itertools.groupby(seq)] + + +def check_link(pcap: Path, keys: Path | None = None) -> tuple[list[Frame], set[str]]: + """SDP found the EVSE that served the connection; every frame is EXI, of one protocol. + + keys: the session is over TLS, decrypted with this key log file. + """ + found = sdp(pcap) + reqs = [(s, b) for s, _, t, b in found if t == SDP_REQ] + res = [(s, b) for s, _, t, b in found if t == SDP_RES] + assert reqs and res, found + # Request: security, transport (0x10 no TLS, 0x00 TLS; 0x00 TCP). Response: + # the EVSE's address and port, then the same two. + security = bytes([0x00 if keys else 0x10, 0x00]) + assert all(b == security for _, b in reqs), reqs + server, frames, flags = tcp(pcap, keys) + for src, b in res: + assert len(b) == 20 and b[18:] == security, b.hex() + assert (src, struct.unpack_from("!H", b, 16)[0]) == server + assert all(f.type == EXI for f in frames) or (all(f.type == EXI for f in frames[:2]) and all(f.type in ISO20.values() for f in frames[2:])) + # Request, response, request, ... + assert [f.from_ev for f in frames] == [i % 2 == 0 for i in range(len(frames))] + return frames, flags + + +def write_messages(path: Path, frames: list[Frame], msgs: list[str]) -> None: + """The capture's sidecar: each V2GTP frame's frame number, direction and message name.""" + with path.open("w", newline="") as f: + w = csv.writer(f) + w.writerow(["frame", "direction", "message"]) + w.writerows((fr.number, "ev" if fr.from_ev else "evse", m) for fr, m in zip(frames, msgs, strict=True)) + + +def ended(s) -> bool: + """The EV's V2G session is over, however it ended.""" + return bool(s.var("iso15118_car", "v2g_session_finished")) + + +def unplugged(s) -> bool: + return any(e.get("event") == "SessionFinished" for e in s.var("evse_manager", "session_event")) + + +@pytest.mark.parametrize("protocol", PROTOCOLS) +def test_session(charge, protocol): + """The EV charges STOP_AFTER_S in CurrentDemand, then ends the session itself.""" + p = PROTOCOLS[protocol] + s = charge(protocol, EV_STOP, ended) + assert (s.keys is not None) == protocol.endswith("-tls") + frames, flags = check_link(s.pcap, s.keys) + msgs = names(s, frames) + write_messages(s.pcap.with_suffix(".messages.csv"), frames, msgs) + seq = exchanges(msgs) + assert s.var("iso15118_charger", "selected_protocol") == [p.selected] + assert runs(seq)[: len(p.setup)] == p.setup, seq + assert runs(seq)[-3:] == p.stop, seq + # The charge sequence, in order, with the loop between. + it = iter(runs(seq)) + assert all(m in it for m in p.charge), seq + # Some of the loop, not a single exchange: Josev sends about two a second, + # fewer over ISO 15118-20, where PowerDelivery can repeat first. + assert seq.count(p.charge[-1]) >= (STOP_AFTER_S if p.setup is SETUP else 3), seq + # Over TLS the EVSE closes first and resets on the EV's close_notify. + assert "F" in flags and (s.keys or "R" not in flags), flags + # Evse15118D20 publishes no start of an AC loop. + assert s.var("iso15118_charger", "current_demand_started") or "AC_ChargeLoop" in seq + assert s.var("iso15118_charger", "current_demand_finished") + + +def test_ev_unplug_mid_current_demand(charge): + """Unplugged in CurrentDemand: no PowerDelivery stop, no SessionStop, and the link ends.""" + s = charge("iso2", "sleep 3;unplug", unplugged) + frames, _ = check_link(s.pcap) + seq = runs(exchanges(names(s, frames))) + assert seq[-1] == "CurrentDemand", seq + assert "SessionStop" not in seq and "WeldingDetection" not in seq + + +def test_isolation_fault(charge): + """The isolation monitor reads a fault: no PreCharge, so no power.""" + s = charge("iso2", EV_STOP, ended, imd={"resistance_F_Ohm": 10000}) + frames, _ = check_link(s.pcap) + seq = runs(exchanges(names(s, frames))) + assert "CableCheck" in seq and "PreCharge" not in seq and "CurrentDemand" not in seq, seq + + +@pytest.mark.parametrize("protocol", [p for p in PROTOCOLS if PROTOCOLS[p].capture]) +def test_capture_fixture(protocol): + """The committed demo capture holds the session test_session checks: SDP, then one + connection of whole frames, each named in its sidecar at the frame it starts in.""" + if shutil.which("tshark") is None: + pytest.skip("needs tshark") + p = PROTOCOLS[protocol] + frames, flags = check_link(HERE / "captures" / f"{p.capture}.pcapng") + assert len(frames) >= 2 * (len(p.setup) + len(p.charge) + len(p.stop)) and "F" in flags + with (HERE / "captures" / f"{p.capture}.messages.csv").open(newline="") as f: + rows = list(csv.DictReader(f)) + assert [(int(r["frame"]), r["direction"]) for r in rows] == [(fr.number, "ev" if fr.from_ev else "evse") for fr in frames] + seq = exchanges([r["message"] for r in rows]) + assert runs(seq)[: len(p.setup)] == p.setup and runs(seq)[-3:] == p.stop, seq