Python Quickstart (v2xflexstack)

v2xflexstack is the Python implementation of the ETSI C-ITS protocol stack. This guide installs the package and assembles a station that sends and receives Cooperative Awareness Messages (CAMs). The same station is examples/cam_sender_and_receiver.py in the FlexStack repository.

Installation

pip install v2xflexstack==0.12.0

Prerequisites

  • Python 3.8 or later, CPython or PyPy 3.11.

  • Privileges: RawLinkLayer uses raw packet sockets, so the station must run as root or with the CAP_NET_RAW capability.

Architecture of the Example Station

  1. Location service: feeds the ego position into the stack.

  2. GeoNetworking router: ETSI TS 103 836-4-1 (here, single-hop broadcast).

  3. BTP router: delivers packets to the Facilities services by port (EN 302 636-5-1).

  4. Local Dynamic Map (LDM): stores received messages and notifies subscribers.

  5. CA basic service: generates CAMs from the position updates (TS 103 900).

  6. Link layer: sends and receives frames on a network interface.

The link layer is created last, once every service has registered with the BTP router.

Step-by-Step Walkthrough

1. Logging and identifiers

import logging
import random

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s")

POSITION = (41.386931, 2.112104)          # latitude, longitude
MAC_ADDRESS = bytes([0x02] + [random.randint(0, 255) for _ in range(5)])  # locally administered
STATION_ID = random.randint(1, 2147483647)

2. Location service

Without a GNSS receiver, ThreadStaticLocationService reports a fixed position periodically from its own thread (see Python Location & Time Utilities for gpsd):

from flexstack.utils.static_location_service import ThreadStaticLocationService

location_service = ThreadStaticLocationService(period=1000, latitude=POSITION[0], longitude=POSITION[1])

3. GeoNetworking router

The Management Information Base (MIB) is a frozen dataclass: set its fields when it is created.

from flexstack.geonet.gn_address import GNAddress, M, ST, MID
from flexstack.geonet.mib import GnIfType, MIB
from flexstack.geonet.router import Router as GNRouter

mib = MIB(
    itsGnIfType=GnIfType.ITS_G5,
    itsGnLocalGnAddr=GNAddress(m=M.GN_MULTICAST, st=ST.PASSENGER_CAR, mid=MID(MAC_ADDRESS)),
)
gn_router = GNRouter(mib=mib, sign_service=None)
location_service.add_callback(gn_router.refresh_ego_position_vector)

4. BTP router

from flexstack.btp.router import Router as BTPRouter

btp_router = BTPRouter(gn_router)
gn_router.register_indication_callback(btp_router.btp_data_indication)

5. Local Dynamic Map

Create the LDM, register an application as data consumer and subscribe it to CAMs from other stations:

from flexstack.facilities.local_dynamic_map.factory import LDMFactory
from flexstack.facilities.local_dynamic_map.ldm_constants import CAM
from flexstack.facilities.local_dynamic_map.ldm_classes import (
    AccessPermission, Circle, ComparisonOperators, Filter, FilterStatement, GeometricArea,
    Location, RegisterDataConsumerReq, RequestDataObjectsResp, SubscribeDataobjectsReq,
    TimestampIts,
)

ldm_location = Location.initializer(
    latitude=int(POSITION[0] * 10**7),
    longitude=int(POSITION[1] * 10**7),
)
ldm = LDMFactory().create_ldm(
    ldm_location,
    ldm_maintenance_type="Reactive",
    ldm_service_type="Reactive",
    ldm_database_type="Dictionary",
)
location_service.add_callback(ldm_location.location_service_callback)

ldm.if_ldm_4.register_data_consumer(
    RegisterDataConsumerReq(
        application_id=CAM,
        access_permisions=(AccessPermission.CAM,),
        area_of_interest=GeometricArea(circle=Circle(radius=5000), rectangle=None, ellipse=None),
    )
)

def on_cam(data: RequestDataObjectsResp) -> None:
    station = data.data_objects[0]["dataObject"]["header"]["stationId"]
    print(f"Received CAM from station {station}")

ldm.if_ldm_4.subscribe_data_consumer(
    SubscribeDataobjectsReq(
        application_id=CAM,
        data_object_type=(CAM,),
        priority=1,
        filter=Filter(filter_statement_1=FilterStatement(
            "header.stationId", ComparisonOperators.NOT_EQUAL, STATION_ID)),
        notify_time=TimestampIts(0),
        multiplicity=1,
        order=None,
    ),
    on_cam,
)

6. CA basic service

from flexstack.facilities.ca_basic_service.ca_basic_service import CooperativeAwarenessBasicService
from flexstack.facilities.ca_basic_service.cam_transmission_management import VehicleData

vehicle_data = VehicleData(
    station_id=STATION_ID,
    station_type=5,  # passenger car
    drive_direction="forward",
    vehicle_length={"vehicleLengthValue": 45, "vehicleLengthConfidenceIndication": "unavailable"},  # 0.1 m
    vehicle_width=18,  # 0.1 m
)
ca_service = CooperativeAwarenessBasicService(btp_router=btp_router, vehicle_data=vehicle_data, ldm=ldm)
location_service.add_callback(ca_service.cam_transmission_management.location_service_callback)
ca_service.start()

Complete Runnable Script

Run it as root in two terminals; each station prints the CAMs of the other.

import logging
import random
import time

from flexstack.btp.router import Router as BTPRouter
from flexstack.facilities.ca_basic_service.ca_basic_service import CooperativeAwarenessBasicService
from flexstack.facilities.ca_basic_service.cam_transmission_management import VehicleData
from flexstack.facilities.local_dynamic_map.factory import LDMFactory
from flexstack.facilities.local_dynamic_map.ldm_classes import Location
from flexstack.geonet.gn_address import GNAddress, M, ST, MID
from flexstack.geonet.mib import GnIfType, MIB
from flexstack.geonet.router import Router as GNRouter
from flexstack.linklayer.raw_link_layer import RawLinkLayer
from flexstack.utils.static_location_service import ThreadStaticLocationService

logging.basicConfig(level=logging.INFO)


def main() -> None:
    latitude, longitude = 41.386931, 2.112104
    mac_address = bytes([0x02] + [random.randint(0, 255) for _ in range(5)])
    station_id = random.randint(1, 2147483647)

    location_service = ThreadStaticLocationService(period=1000, latitude=latitude, longitude=longitude)

    mib = MIB(
        itsGnIfType=GnIfType.ITS_G5,
        itsGnLocalGnAddr=GNAddress(m=M.GN_MULTICAST, st=ST.PASSENGER_CAR, mid=MID(mac_address)),
    )
    gn_router = GNRouter(mib=mib, sign_service=None)
    location_service.add_callback(gn_router.refresh_ego_position_vector)

    btp_router = BTPRouter(gn_router)
    gn_router.register_indication_callback(btp_router.btp_data_indication)

    ldm_location = Location.initializer(latitude=int(latitude * 10**7), longitude=int(longitude * 10**7))
    ldm = LDMFactory().create_ldm(ldm_location, ldm_maintenance_type="Reactive",
                                  ldm_service_type="Reactive", ldm_database_type="Dictionary")
    location_service.add_callback(ldm_location.location_service_callback)

    vehicle_data = VehicleData(station_id=station_id, station_type=5, drive_direction="forward")
    ca_service = CooperativeAwarenessBasicService(btp_router=btp_router, vehicle_data=vehicle_data, ldm=ldm)
    location_service.add_callback(ca_service.cam_transmission_management.location_service_callback)
    ca_service.start()

    btp_router.freeze_callbacks()
    link_layer = RawLinkLayer("lo", mac_address, receive_callback=gn_router.gn_data_indicate)
    gn_router.link_layer = link_layer

    print(f"Station {station_id} is sending CAMs. Press Ctrl+C to stop.")
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        pass
    finally:
        ca_service.stop()
        location_service.stop_event.set()


if __name__ == "__main__":
    main()