Metadata-Version: 2.4
Name: bs2g4phy
Version: 0.1.1
Summary: Python interface and runtime for the BabbleSim 2.4 GHz PHY
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/XiaoMi/bsworld/tree/main/components/bs2g4phy
Project-URL: Issues, https://github.com/XiaoMi/bsworld/issues
Classifier: Operating System :: POSIX :: Linux
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: test
Requires-Dist: pytest>=8.4; extra == "test"
Requires-Dist: pytest-asyncio>=1.4; extra == "test"
Requires-Dist: ruff==0.14.10; extra == "test"
Requires-Dist: build>=1; extra == "test"
Dynamic: license-file

# BS2G4PHY

BS2G4PHY lets Python programs participate in a [BabbleSim](https://babblesim.github.io/) 2.4 GHz radio simulation. Use it to prototype a radio adapter, send raw frames from a test peer, or put an existing firmware radio model and a Python device on the same PHY. Each participant has its own device ID and can request a time grant, transmit, or listen for a frame.

## Build the native PHY

Use Linux and Python 3.11 or newer. If you already have a BabbleSim build with the required PHY, modem, and channel model, set `BSIM_OUT_PATH` to its output directory containing `bin/` and `lib/`. To build them on Ubuntu 24.04 x86-64, install the tools and fetch BabbleSim.

```sh
sudo apt-get update
sudo apt-get install -y git repo build-essential gcc-multilib g++-multilib gawk python3-venv

mkdir -p "$HOME/babblesim"
cd "$HOME/babblesim"
repo init -u https://github.com/BabbleSim/manifest.git -m everything.xml -b master
repo sync

export BSIM_COMPONENTS_PATH="$PWD/components"
export BSIM_OUT_PATH="$PWD/build"
make -j"$(nproc)" ext_2G4_phy_v1 ext_2G4_modem_BLE_simple ext_2G4_channel_NtNcable
```

This builds the PHY, the BLE modem, and the default `NtNcable` channel used by the sample. Build `ext_2G4_channel_multiatt` when using configurable path attenuation. Keep `BSIM_OUT_PATH` exported when running Python. Other checkout and build options are in the BabbleSim [fetching guide](https://babblesim.github.io/fetching.html) and [building guide](https://babblesim.github.io/building.html).

## Install the Python package

```sh
python3 -m venv .venv
. .venv/bin/activate
python -m pip install bs2g4phy
```

The Python package uses the standard library. The PHY and its models are loaded from the native build above.

## Send and receive a frame

Download [tx_rx.py](https://github.com/XiaoMi/bsworld/blob/main/components/bs2g4phy/samples/tx_rx.py) or use the copy at `samples/tx_rx.py` in the source distribution. It starts a PHY, registers two Python devices, sends a raw frame at 100 µs, and checks the bytes returned to the receiving device. Run it from the directory containing the script.

```sh
python tx_rx.py
```

```text
RX matched the address at 139 us
TX ended at 180 us
RX frame: 0000555555
PHY log: tx-rx-logs/phy.log
```

## Python API

| Entry point | Use |
| --- | --- |
| `PhySimulation` | Allocate device IDs, manage native processes, and synchronize startup. |
| `PhyProcess` | Start a native PHY with an explicitly configured device count. |
| `find_phy()`, `phy_command()` | Locate the executable and prepare its arguments when your application owns the subprocess. |
| `PhyEndpoint`, `PhyConnection` | Allocate a participant with `add_device()` and open its transport with `endpoint.connection()`. |
| `BabbleSimClock` | Join as a time-only participant. `advance_to_us()` updates the clock after the PHY grants the requested time. |
| `wait()`, `wait_sync()` | Request a PHY grant at an absolute simulation time. Choose the async or blocking call to suit the participant's loop. |
| `request(start_us)` | Acquire a turn for TX or RX and release it when the async block exits. |
| `transmit_frame()`, `receive_frame()`, `receive_frame_v2()` | Exchange frames using explicit carrier frequency, modulation, and timing. The radio model supplies the bytes and chooses when to send or listen. |

Use `async with connection.request(start_us) as limit:` for a radio transaction. The block yields the scheduler's next deadline or `None`. Keep all segments and responses of a transaction inside the same block, including both segments of a coded frame. Times are integer microseconds. A transmit end time is exclusive, and completion timestamps report the last occupied PHY tick.

Requests time out if the PHY stops responding. With a scheduler gate, the gate enforces the I/O deadline. Ungated participants use their event loop's timer and should run on wall time. An exception or cancellation after writing a request closes the transport. When a received frame falls outside the requested size range, the methods reject it at the PHY and return the address response with `RxStatus.IN_PROGRESS` and an empty `packet`. The connection remains ready for the next request.

`bs2g4phy.ble` maps LE Coded frames to the BLE modem's two native transactions. Call `transmit_coded()` or `receive_coded()` inside a single `connection.request()` block. Pass the LE timing and frame bounds from your radio model. TX accepts S=2 or S=8, and RX decodes CI before continuing with a prelocked receive. The `on_time` callback reports the last PHY tick of each transaction. A successful receive returns the frame's `Reception` and its coding.

### Manage PHY startup and shutdown

Use `PhySimulation` to run several Python radios, external radio models, or native interference sources on one PHY. Reserve slots in order with `add_device()`, `add_interference(source)`, and, if needed, `add_clock()` before entering the async context. The allocation order fixes the device IDs for the run. `add_device()` returns a `PhyEndpoint` for a participant you start yourself. For an external simulator, use `simulation.sim_id` and `endpoint.dev_id` as launch arguments.

Entering the context starts the PHY and connects its clock and interference participants. Inside the context, connect the participants you own and call `await simulation.synchronize()`. It waits for all devices to register and obtains the first time grant when a clock is present. A scheduler can bind the returned clock. Unbind the clock and close your participants before leaving the context. For a complete example, see [raw TX and RX](https://github.com/XiaoMi/bsworld/blob/main/components/bs2g4phy/samples/tx_rx.py).

To start just the PHY with an explicit device count, use the `PhyProcess` context manager. It accepts the same modem and channel settings as `phy_command()`. With no attenuation settings, the PHY uses its default channel model.

Use these functions when your application starts the PHY in its own process manager. All are available directly from `bs2g4phy`.

| Entry point | Use |
| --- | --- |
| `phy_binary(directory)`, `missing_outputs(directory, required)` | Locate the executable and check the build-relative artifact paths selected by your application. Use `find_phy()` to locate and verify the executable alone. |
| `phy_ready_path(sim_dir)`, `device_lock_paths(sim_dir, device_count)` | Locate the readiness and registration files to wait for during startup. Device IDs range from zero to `device_count - 1`. |
| `simulation_directory(sim_id)`, `simulation_results_directory(build_dir, sim_id)` | Locate the state and output directories for a simulation. |

### Configure path attenuation and interference

Use `StaticAttenuation` for a fixed loss and `TimedAttenuation` for attenuation values at successive simulation times. Both describe a directed path between device IDs. Pass a `ChannelAttenuation` to `PhySimulation`, or use `configure_channel()` after resolving device IDs and before startup. For direct use of `phy_command()`, `write_attenuation_matrix()` serializes the paths to a matrix file.

Register `BurstInterference`, `WlanInterference`, or `PlaybackInterference` from `bs2g4phy.interference` with `add_interference()`. The simulation owns the process and returns its numeric PHY device ID for attenuation paths. Build `ext_2G4_device_burst_interferer`, `ext_2G4_device_WLAN_actmod`, or `ext_2G4_device_playbackv2` for the sources you use.

### Integrate a scheduler

Import `PhyRequestGate` from `bs2g4phy` and assign an object that implements it to `connection.request_gate` before issuing requests. The gate is optional.

- `before_phy_request(start_us)` runs when entering `request()`, before accessing the PHY. Return the next software timer deadline in absolute simulation microseconds, or `None` when no deadline applies. `request()` yields the deadline, and `wait()` uses it to cap its target.
- `wait_for_phy_io(fd, *, write, deadline)` waits synchronously when an admitted request needs FIFO I/O and during `wait_sync()`. Wait for writability when `write` is true and readability otherwise. Return when the descriptor is ready, or raise `TimeoutError` if the deadline expires. The absolute deadline uses `time.monotonic()` in seconds. Keep scheduler callbacks out of this blocking wait so the admitted transaction retains its turn.

## Develop from source

From `components/bs2g4phy` in the repository checkout, run the unit tests and build the distributions.

```sh
python -m pip install -e '.[test]'
python -m pytest
python -m build
```

The `bs2g4phy-v<version>` release tag selects this package in the PyPI workflow. Its version must match `pyproject.toml`, and the workflow uses the `pypi-bs2g4phy` Trusted Publisher environment.
