V2X Protocol Testing: DSRC, C-V2X, and ETSI ITS-G5 Validation

V2X Protocol Testing: DSRC, C-V2X, and ETSI ITS-G5 Validation

V2X (Vehicle-to-Everything) communication is the safety-critical backbone of connected vehicle infrastructure. A message that arrives 20ms late, with an incorrect position, or with a malformed security certificate doesn't just fail a test — in a real deployment, it means a vehicle doesn't know that a truck has run a red light ahead. Testing V2X is not like testing a REST API. The tolerance for errors is essentially zero.

This post covers the full V2X testing stack: protocol differences between DSRC and C-V2X, message validation for BSM/CAM/DENM, latency and reliability testing, ETSI ITS-G5 conformance, and the tools you'll use in practice.

DSRC vs C-V2X: What You're Actually Testing

Before writing a single test, understand the protocol stack you're validating.

DSRC (Dedicated Short-Range Communications) uses IEEE 802.11p (WAVE) at the PHY/MAC layer, operating in the 5.9 GHz band. It's a WiFi derivative without association or authentication delay — packets are broadcast ad-hoc. The full stack:

Application: BSM / SPAT / MAP / TIM
  ↓
Facilities: IEEE 1609.3 (WSMP), IPv6
  ↓
Security: IEEE 1609.2 (SCMS certificates)
  ↓
Network: IEEE 1609.3 (WAVE)
  ↓
MAC/PHY: IEEE 802.11p (10 MHz channels)

C-V2X (Cellular V2X) uses LTE/5G-NR air interfaces in two modes:

  • PC5 (sidelink): Direct device-to-device, no network infrastructure required. LTE-V (3GPP Rel-14), NR-V2X (Rel-16)
  • Uu (uplink/downlink): Via cellular base station. Lower latency with 5G, but requires network coverage

ETSI ITS-G5 is the European standard built on DSRC/802.11p, defining CAM, DENM, and MAPEM/SPATEM messages. If you're testing in Europe, ITS-G5 is your compliance target. In North America, DSRC with SAE J2735 (BSM format) is primary. C-V2X is gaining ground globally.

Key Protocol Differences That Affect Testing

Parameter DSRC/ITS-G5 C-V2X PC5 C-V2X Uu (5G)
Latency (one-way) 5-20ms 10-30ms 5-15ms (5G NR)
Range 300-1000m 300-500m Network-dependent
Infrastructure None needed None needed Requires 5G coverage
Reliability (PDR) >90% at 300m >90% at 300m >99.9% (5G URLLC)
Security IEEE 1609.2 3GPP-based 3GPP-based
Test tool Cohda MK5/MK6 Autotalks TEKTON Simulated via 5G test bed

BSM/CAM/DENM Message Validation

SAE J2735 BSM Structure

The Basic Safety Message (BSM) is broadcast at 10 Hz by every vehicle in North American DSRC deployments. A single corrupt field — like a wrong latitude — propagates to every vehicle within range.

BSM Part I (mandatory, every message):
  - msgCnt: uint8 (0-127, wraps)
  - id: 4-byte temporary ID (changes periodically for privacy)
  - secMark: milliseconds within current minute (0-60999)
  - lat: latitude in 1/10 microdegree units (-900000000 to 900000000)
  - long: longitude in 1/10 microdegree units
  - elev: elevation in 0.1m units (-4096 to 61439)
  - accuracy: positional accuracy
  - speed: 0.02 m/s units (0 to 8191)
  - heading: 0.0125 degree units (0 to 28799)
  - accel: longitudinal/lateral/vertical acceleration
  - brakes: brake system status
  - size: vehicle dimensions

BSM Part II (optional extensions):
  - VehicleSafetyExtension: lights, wipers, exterior lights
  - SpecialVehicleExtension: emergency vehicles, transit
  - SupplementalVehicleExtension: class, fuel type

ETSI ITS-G5 CAM Structure

The Cooperative Awareness Message (CAM) is the European equivalent of BSM. Key differences: CAMs include a complete ITS-PDU header with station ID, generation time (from UTC), and station type.

-- ETSI EN 302 637-2
CAM ::= SEQUENCE {
    header ItsPduHeader,
    cam    CoopAwareness
}

ItsPduHeader ::= SEQUENCE {
    protocolVersion INTEGER (0..255),  -- Currently 2
    messageID       INTEGER (0..255),  -- CAM = 2
    stationID       StationID          -- 0..4294967295
}

CoopAwareness ::= SEQUENCE {
    generationDeltaTime GenerationDeltaTime,  -- ms mod 65536
    camParameters       CamParameters
}

Message Validation Code

Python is the most practical language for V2X message validation in test environments. Use asn1tools for ASN.1 decoding and scapy for packet capture.

#!/usr/bin/env python3
"""
V2X Message Validator
Validates CAM/DENM messages captured from ITS-G5 interface.
"""

import asn1tools
import struct
import time
import math
from dataclasses import dataclass
from typing import Optional, List
from datetime import datetime, timezone

# Load ETSI ASN.1 schemas
# Download from: https://forge.etsi.org/rep/ITS/asn1
cam_schema = asn1tools.compile_files([
    'asn1/IEEE1609dot2.asn',
    'asn1/ETSI-ITS-CDD.asn',
    'asn1/CAM-PDU-Descriptions.asn'
], codec='uper')  # Unaligned PER encoding

denm_schema = asn1tools.compile_files([
    'asn1/DENM-PDU-Descriptions.asn'
], codec='uper')


@dataclass
class ValidationResult:
    valid: bool
    errors: List[str]
    warnings: List[str]
    message_type: str
    station_id: Optional[int] = None
    age_ms: Optional[float] = None


class ItsG5MessageValidator:
    """
    Validates ITS-G5 CAM and DENM messages for:
    1. ASN.1 schema conformance (correct encoding, all mandatory fields)
    2. Value range constraints (coordinates, speed, heading)
    3. Temporal freshness (message age relative to generationDeltaTime)
    4. Consistency (speed/acceleration cross-check, position plausibility)
    """

    MAX_CAM_AGE_MS = 1100  # CAM must be fresh (generation rate: 1-10 Hz)
    MAX_SPEED_MS = 55.0    # 200 kph maximum plausible vehicle speed
    MAX_LATERAL_ACCEL = 10.0  # m/s², hard limit for road vehicles

    def validate_cam(self, raw_bytes: bytes,
                     rx_timestamp_ms: float) -> ValidationResult:
        errors = []
        warnings = []

        # 1. ASN.1 decode
        try:
            decoded = cam_schema.decode('CAM', raw_bytes)
        except asn1tools.errors.DecodeError as e:
            return ValidationResult(
                valid=False,
                errors=[f"ASN.1 decode failure: {e}"],
                warnings=[],
                message_type='CAM'
            )

        header = decoded['header']
        cam_params = decoded['cam']['camParameters']
        basic_container = cam_params['basicContainer']
        hfc = cam_params['highFrequencyContainer']

        # 2. Protocol version
        if header['protocolVersion'] != 2:
            errors.append(
                f"Unexpected protocol version: {header['protocolVersion']} (expected 2)"
            )

        # 3. Message ID must be 2 for CAM
        if header['messageID'] != 2:
            errors.append(
                f"Wrong messageID: {header['messageID']} (expected 2 for CAM)"
            )

        station_id = header['stationID']

        # 4. Position validation
        ref_pos = basic_container['referencePosition']
        lat_deg = ref_pos['latitude'] / 10_000_000.0
        lon_deg = ref_pos['longitude'] / 10_000_000.0

        if not (-90.0 <= lat_deg <= 90.0):
            errors.append(f"Latitude out of range: {lat_deg:.7f}")
        if not (-180.0 <= lon_deg <= 180.0):
            errors.append(f"Longitude out of range: {lon_deg:.7f}")

        # Semi-axis confidence should indicate valid GPS fix
        semi_major = ref_pos['positionConfidenceEllipse']['semiMajorConfidence']
        if semi_major > 4095:  # 4096 = unavailable
            warnings.append(f"Position confidence unavailable (semi_major={semi_major})")
        elif semi_major > 100:  # > 10m accuracy
            warnings.append(f"Poor position accuracy: {semi_major * 0.1:.1f}m")

        # 5. Speed validation
        if 'vehicleHFContainer' in hfc:
            vhf = hfc['vehicleHFContainer']
            speed_raw = vhf['speed']['speedValue']
            if speed_raw != 16383:  # 16383 = unavailable
                speed_ms = speed_raw * 0.01  # 0.01 m/s units
                if speed_ms > self.MAX_SPEED_MS:
                    errors.append(
                        f"Implausible speed: {speed_ms:.2f} m/s ({speed_ms * 3.6:.1f} kph)"
                    )

            # 6. Heading validation
            heading_raw = vhf['heading']['headingValue']
            if heading_raw != 3601:  # 3601 = unavailable
                heading_deg = heading_raw * 0.1
                if not (0.0 <= heading_deg < 360.0):
                    errors.append(f"Heading out of range: {heading_deg:.1f}°")

            # 7. Longitudinal acceleration cross-check with speed
            if 'longitudinalAcceleration' in vhf:
                lon_acc_raw = vhf['longitudinalAcceleration']['longitudinalAccelerationValue']
                if lon_acc_raw != 161:  # 161 = unavailable
                    lon_acc_ms2 = lon_acc_raw * 0.1
                    if speed_ms < 0.5 and lon_acc_ms2 > 2.0:
                        warnings.append(
                            f"High acceleration ({lon_acc_ms2:.1f} m/s²) at near-zero speed"
                        )

        # 8. Temporal freshness
        generation_delta = decoded['cam']['generationDeltaTime']
        now_ms_mod = int(rx_timestamp_ms) % 65536
        age_ms = (now_ms_mod - generation_delta) % 65536
        if age_ms > self.MAX_CAM_AGE_MS:
            errors.append(
                f"CAM too old: {age_ms}ms (limit: {self.MAX_CAM_AGE_MS}ms)"
            )

        return ValidationResult(
            valid=len(errors) == 0,
            errors=errors,
            warnings=warnings,
            message_type='CAM',
            station_id=station_id,
            age_ms=age_ms
        )

    def validate_denm(self, raw_bytes: bytes) -> ValidationResult:
        errors = []
        warnings = []

        try:
            decoded = denm_schema.decode('DENM', raw_bytes)
        except asn1tools.errors.DecodeError as e:
            return ValidationResult(
                valid=False,
                errors=[f"ASN.1 decode failure: {e}"],
                warnings=[],
                message_type='DENM'
            )

        mgmt = decoded['denm']['management']

        # Action ID uniqueness validation (sequence_number must increment)
        action_id = mgmt['actionID']
        seq_number = action_id['sequenceNumber']
        station_id = action_id['originatingStationID']

        # Validity duration check
        if 'validityDuration' in mgmt:
            validity_s = mgmt['validityDuration']
            if validity_s > 86400:  # Max 24 hours
                warnings.append(f"Unusually long validity duration: {validity_s}s")

        # Cause code validation
        if 'situation' in decoded['denm']:
            cause = decoded['denm']['situation']['eventType']['causeCode']
            valid_cause_codes = {1, 2, 3, 6, 9, 10, 11, 12, 14, 15, 17,
                                  18, 19, 26, 27, 91, 92, 93, 94, 95, 96}
            if cause not in valid_cause_codes:
                errors.append(f"Invalid cause code: {cause}")

        return ValidationResult(
            valid=len(errors) == 0,
            errors=errors,
            warnings=warnings,
            message_type='DENM',
            station_id=station_id
        )

Latency and Reliability Testing

V2X safety applications have hard latency budgets. ETSI TR 101 607 defines:

Application Max End-to-End Latency Min PDR
Pre-crash sensing 20ms 90%
Emergency vehicle approaching 50ms 90%
Intersection collision warning 100ms 90%
Hazardous location warning (DENM) 500ms 80%

Measuring Latency with Cohda MK6C Hardware

"""
Latency test using Cohda MK6C RSU and OBU units.
Requires: cohda-sdk Python bindings (proprietary, from Cohda Wireless)
"""

import cohda_sdk as cohda
import statistics
import time

def measure_cam_latency(obu_interface: str = 'dsrc0',
                         rsu_interface: str = 'dsrc1',
                         num_messages: int = 1000) -> dict:
    """
    Measure one-way CAM delivery latency using GPS-synchronized timestamps.
    OBU transmits CAMs; RSU captures and records RX timestamp.
    Both units must have valid GPS PPS signal for sub-millisecond sync.
    """
    obu = cohda.Device(obu_interface)
    rsu = cohda.Device(rsu_interface)

    # Configure channel: ETSI ITS-G5 CCH (Channel 180, 5.9 GHz)
    obu.configure(channel=180, data_rate=6, tx_power_dbm=23)
    rsu.configure(channel=180, mode='monitor')

    latencies_ms = []
    lost_packets = 0

    obu.start_cam_tx(rate_hz=10)  # 10 Hz CAM broadcast

    for i in range(num_messages):
        tx_time = obu.get_last_tx_timestamp_us()

        # Wait for RSU to receive (20ms window)
        rx_event = rsu.wait_for_cam(timeout_ms=20, station_id=obu.station_id)

        if rx_event is None:
            lost_packets += 1
            continue

        latency_us = rx_event.timestamp_us - tx_time
        if 0 < latency_us < 50000:  # Sanity: 0-50ms
            latencies_ms.append(latency_us / 1000.0)

    obu.stop_cam_tx()

    pdr = (num_messages - lost_packets) / num_messages

    return {
        'pdr': pdr,
        'mean_latency_ms': statistics.mean(latencies_ms),
        'p50_latency_ms': statistics.median(latencies_ms),
        'p95_latency_ms': sorted(latencies_ms)[int(len(latencies_ms) * 0.95)],
        'p99_latency_ms': sorted(latencies_ms)[int(len(latencies_ms) * 0.99)],
        'max_latency_ms': max(latencies_ms),
        'lost_packets': lost_packets,
        'sample_count': len(latencies_ms)
    }

# Example test assertion
result = measure_cam_latency(num_messages=1000)
assert result['pdr'] >= 0.90, f"PDR {result['pdr']:.3f} below 90% threshold"
assert result['p95_latency_ms'] < 50.0, (
    f"P95 latency {result['p95_latency_ms']:.1f}ms exceeds 50ms limit"
)
print(f"Mean: {result['mean_latency_ms']:.1f}ms, "
      f"P99: {result['p99_latency_ms']:.1f}ms, "
      f"PDR: {result['pdr']*100:.1f}%")

ETSI ITS-G5 Conformance Testing

Conformance testing is mandatory for type approval in EU markets. The ETSI TC ITS test specifications define test purposes and test verdicts. Tools like the TTCN-3-based ETSI conformance test suite are used by certification labs, but you can run a subset of conformance checks in-house.

Wireshark V2X Dissection

Wireshark's V2X dissectors decode ETSI ITS and SAE J2735 messages. Capture from a DSRC interface:

# Capture V2X traffic on DSRC interface (requires 802.11p driver)
sudo wireshark -i dsrc0 -k -Y "its" \
  -o "uat:user_dlts:\"User 0 (DLT=147)\",\"its\",\"0\",\"\",\"0\",\"\""

# Or tcpdump for CI integration
sudo tcpdump -i dsrc0 -w capture.pcap

# Offline analysis with tshark
tshark -r capture.pcap \
  -Y "its.cam" \
  -T fields \
  -e its.cam.coop_awareness.cam_params.basic_container.reference_position.latitude \
  -e its.cam.coop_awareness.cam_params.basic_container.reference_position.longitude \
  -e its.cam.generation_delta_time \
  -E header=y \
  -E separator=, > cam_positions.csv

# Check for messages with invalid coordinates (should be empty)
tshark -r capture.pcap \
  -Y "its.cam && (its.cam.coop_awareness.cam_params.basic_container.reference_position.latitude > 900000000)" \
  -T text

Autotalks TEKTON C-V2X Test Suite

For C-V2X PC5 testing with Autotalks hardware:

# Run Autotalks TEKTON conformance tests (PC5 sidelink)
tekton-cli test run \
  --device /dev/tekton0 \
  --suite V2X_PC5_CONFORMANCE_3GPP_REL14 \
  --output results/tekton_conformance.xml \
  --verbose

# Specific subtest: PC5 resource selection
tekton-cli test run \
  --device /dev/tekton0 \
  --test "SCI_Format1_Encoding" \
  --test "SubchannelAllocation_SensingBased" \
  --repeat 100

# Measure PC5 sidelink range
tekton-cli range-test \
  --tx-device /dev/tekton0 \
  --rx-device /dev/tekton1 \
  --message-type CAM \
  --tx-power 23 \
  --distances 50,100,200,300,400,500 \
  --output results/range_test.csv

Security Certificate Validation

V2X messages are signed with Pseudonym Certificates (DSRC: IEEE 1609.2, C-V2X: 3GPP-based). An attacker broadcasting unsigned or improperly signed messages must be rejected.

from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.exceptions import InvalidSignature
import binascii

def validate_ieee1609_2_signature(signed_message: bytes,
                                   certificate_bytes: bytes) -> bool:
    """
    Verify IEEE 1609.2 ECDSA-P256 signature on a DSRC message.
    In production, use a full SCMS certificate chain verifier.
    """
    # Parse the 1609.2 SignedData (simplified - real impl uses ASN.1)
    # Structure: [Tbs Data (n bytes)] [Signature r (32 bytes)] [Signature s (32 bytes)]
    signature_r = signed_message[-64:-32]
    signature_s = signed_message[-32:]
    tbs_data = signed_message[:-64]

    # Load certificate's public key (ECDSA P-256)
    try:
        public_key = serialization.load_der_public_key(certificate_bytes)
        signature_der = encode_dss_signature(
            int.from_bytes(signature_r, 'big'),
            int.from_bytes(signature_s, 'big')
        )
        public_key.verify(signature_der, tbs_data, ec.ECDSA(hashes.SHA256()))
        return True
    except InvalidSignature:
        return False
    except Exception as e:
        print(f"Certificate validation error: {e}")
        return False

# Test: Reject replayed message (same content, old timestamp)
def test_replay_attack_detection():
    """Replayed CAMs must be rejected based on generationDeltaTime."""
    validator = ItsG5MessageValidator()

    # Capture a valid CAM
    valid_cam_bytes = capture_cam_from_interface('dsrc0', timeout_ms=200)
    assert valid_cam_bytes is not None

    # Wait 2 seconds, then re-validate (message age will exceed MAX_CAM_AGE_MS)
    time.sleep(2.0)
    rx_ts = time.time() * 1000
    result = validator.validate_cam(valid_cam_bytes, rx_ts)

    assert not result.valid, "Replayed CAM should be rejected"
    assert any('too old' in e for e in result.errors), (
        f"Expected 'too old' error, got: {result.errors}"
    )

CI Test Pipeline for V2X

# .github/workflows/v2x-tests.yml
jobs:
  message-validation:
    runs-on: ubuntu-22.04
    steps:
      - name: Install ASN.1 tools
        run: pip install asn1tools scapy cryptography

      - name: Run message validation unit tests
        run: |
          pytest tests/v2x/test_cam_validation.py \
                 tests/v2x/test_denm_validation.py \
                 tests/v2x/test_security.py \
                 -v --tb=short

  conformance-replay:
    runs-on: ubuntu-22.04
    steps:
      - name: Replay captured V2X traffic against validator
        run: |
          # Use pre-captured PCAP files from conformance test lab
          python3 tests/v2x/replay_validation.py \
            --pcap tests/fixtures/etsi_conformance_captures/*.pcap \
            --expected-pass tests/fixtures/conformance_expected.yaml \
            --report results/conformance_replay_report.html

V2X testing is unforgiving because the protocol is unforgiving. Every message either arrives correctly and on time, or it doesn't — and in the latter case, the application layer must degrade gracefully. Build your validation to be strict at the message level, measure latency under realistic channel load (high vehicle density = high packet collision rate), and ensure your security validation rejects anything that doesn't carry a valid, fresh certificate.

Read more

Start now free