.. _python_btp:
.. _btp_router:
===========================================
Python Basic Transport Protocol (BTP)
===========================================
The Basic Transport Protocol (**ETSI EN 302 636-5-1 V2.2.1**) multiplexes GeoNetworking payloads to Facilities services by port number:
* **BTP-A**: destination and source port, for interactive services.
* **BTP-B**: destination port and destination port info, used by CAM (port 2001), DENM (port 2002) and VAM (port 2018).
Architecture
============
.. mermaid::
flowchart TD
FAC["Facilities Layer
(CAM / DENM / VAM)"]
BTP["Basic Transport Protocol (BTP)
BTP-A & BTP-B port multiplexing"]
GN["GeoNetworking (GN) Router"]
FAC -->|"BTP-Data.request"| BTP
BTP -->|"BTP-Data.indication"| FAC
BTP -->|"GN-DATA.request"| GN
GN -->|"GN-DATA.indication"| BTP
style FAC fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
style BTP fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a8a
style GN fill:#fee2e2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d
Router Instantiation
====================
The BTP router is created on top of the GeoNetworking router, which delivers its indications to it:
.. code-block:: python
from flexstack.btp.router import Router as BTPRouter
btp_router = BTPRouter(gn_router)
gn_router.register_indication_callback(btp_router.btp_data_indication)
Receiving: Port Registration
============================
Services register a callback per destination port. Registration ends with ``freeze_callbacks()``, after which the port table is read-only; do it once every service has been created, before the link layer starts delivering packets:
.. code-block:: python
from flexstack.btp.service_access_point import BTPDataIndication
def on_port_4000(indication: BTPDataIndication) -> None:
print(f"Port {indication.destination_port}: {indication.length} bytes")
btp_router.register_indication_callback_btp(port=4000, callback=on_port_4000)
btp_router.freeze_callbacks()
When ``itsGnSecurity`` is enabled, unsecured packets are discarded unless the port was registered with ``accept_unsecured=True``.
Sending BTP Packets
===================
``BTPDataRequest`` is a frozen dataclass built with keyword arguments; the GeoNetworking parameters (``gn_packet_transport_type``, ``gn_area``, ``gn_destination_address``, ``gn_max_hop_limit``, ...) are passed through to the GeoNetworking request:
.. code-block:: python
from flexstack.btp.service_access_point import BTPDataRequest
from flexstack.geonet.service_access_point import CommonNH, PacketTransportType
payload = b"application payload"
request = BTPDataRequest(
btp_type=CommonNH.BTP_B,
destination_port=4000,
gn_packet_transport_type=PacketTransportType(), # single-hop broadcast
data=payload,
length=len(payload),
)
btp_router.btp_data_request(request)
The Facilities services build these requests themselves; an application only needs ``BTPDataRequest`` for its own ports.