Metadata-Version: 2.4
Name: meta-bridge-irsl
Version: 0.1.0
Summary: Bridge Meta Quest VR ZeroMQ JSON into typed robot_msg messages, over ZeroMQ or in-process
Keywords: meta-quest,vr,teleoperation,robotics,zeromq,robot-msg
Author: SeoWook Han
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: System :: Networking
Classifier: Typing :: Typed
Requires-Dist: pyzmq>=26,<28
Requires-Dist: robot-msg-irsl==0.5.4
Requires-Python: >=3.11
Project-URL: Homepage, https://github.com/SeoWookHan/meta_bridge
Project-URL: Issues, https://github.com/SeoWookHan/meta_bridge/issues
Project-URL: Repository, https://github.com/SeoWookHan/meta_bridge
Description-Content-Type: text/markdown

# 📡 Meta Bridge

A **Meta VR message bridge** that converts incoming **ZeroMQ JSON** into typed `robot_msg` controller, tracking, and SMPL messages. Each input is published as a **single binary `MessageBatch` frame** using `robot-msg-irsl==0.5.4` (protocol 2).

---

## ✨ Features

- 🦾 **Typed conversion** — preserve controller inputs, tracked poses, and optional SMPL-X parameters.
- 📦 **Complete snapshots** — send related messages together in one binary envelope, without a topic frame.
- **Latest-frame processing** — keep the newest input and output rather than accumulating old frames.
- **Input validation** — reject malformed packets and continue processing subsequent valid input.
- 📡 **Verbose monitoring** — display complete received values and the actual input rate.
- 🐍 **In-process API** — typed `MetaFrame`s via callbacks, `latest()` or iterators, from an embedded `MetaBridge` or a `MetaSubscriber` of a running bridge.

---

## 📦 Installation

Requires **Python 3.11+**. The distribution name is **`meta-bridge-irsl`**, the import is **`meta_bridge`**, and the command is **`meta-bridge`**.

```bash
pip install meta-bridge-irsl       # or: uv add meta-bridge-irsl
```

**Read a frame from an existing bridge** (no CLI or sockets to manage in your application):

```python
from meta_bridge import MetaSubscriber

with MetaSubscriber("tcp://127.0.0.1:28420") as source:
    frame = source.next_frame(timeout=2.0)
    if frame is not None:
        print(frame.btn_a, frame.right_controller.position)
```

| Your application has… | Use |
|---|---|
| A running bridge that publishes binary frames | `MetaSubscriber(endpoint)` |
| The headset's JSON endpoint, no separate bridge process | `MetaBridge(input_endpoint, output_endpoint=None)` |
| Its own ZeroMQ receiver or stored binary batches | `decode_frame(batch_bytes)` |
| An input JSON packet to validate and convert | `convert_packet(raw_json_bytes, timestamp)` |

The only runtime dependencies are PyZMQ and `robot-msg-irsl==0.5.4`. No headset SDK, collector, or Git checkout is required. To develop from source, clone the repository and run `uv sync`.

---

## 🚀 Usage

### Run the bridge

```bash
uv run meta-bridge
# equivalent:
uv run python -m meta_bridge
```

#### Options

| Option | Default | Description |
|---|---|---|
| `--input` | `tcp://192.168.50.215:4999` | Meta JSON endpoint; the bridge connects as a subscriber |
| `--output` | `tcp://*:28420` | Protocol-2 output endpoint; the bridge binds as a publisher |
| `--verbose` | Off | Print complete received values and input rate |
| `--version` | | Print the version and exit |

#### Examples

```bash
uv run meta-bridge --input tcp://192.168.50.215:4999 --output 'tcp://*:28420'
uv run meta-bridge --verbose
```

The output port is `robot_msg.ports.META`. Input is a single JSON frame; output is
`robot_msg.encode(MessageBatch(...))`, with no topic frame.

Every valid input is published regardless of either hand's trigger values. No
messages are published while Meta input is absent. If Meta continues sending
frames with trigger values of `0.0`, those frames are still converted and sent.

Verbose mode prints each received Meta JSON frame in aligned `SMPL / INPUT / POSE`
columns. Long arrays wrap without truncation. The actual received frame rate is
reported once per second, including `0.0 Hz` when no frames arrive.

---

## 🗂️ Message Types

| Message type (Python class) | Source Meta JSON fields |
|---|---|
| `smpl.smpl_state` (`SmplState`) | `smpl.root_orient[3]`, `pose_body[21][3]`, `left_hand_pose[15][3]`, `right_hand_pose[15][3]`, `trans[3]`, optional `betas[10]` and `gender` |
| `meta.controller_input` (`MetaControllerInput`) | `btnA/B/X/Y`, left/right `HandTrigger`, `IndexTrigger`, `TriggerForce`, `Thumbstick[2]`, and `ThumbstickClick` |
| `meta.tracking_pose` (`MetaTrackingPose`) | Head and left/right controller `Position[3]` and `Rotation[4]` (XYZW) |

### Input mapping and geometry

CamelCase input keys map to snake_case output fields. Controller input also
accepts snake_case keys. Existing vector objects (`{x,y,z,w}` and `{x,y}`), flat
`pose_body[63]`, and `pose_hand[90]` (45 left-hand values followed by 45 right-hand
values) remain supported.

`encode_payload(payload, timestamp=None)` accepts either a flat Quest frame or a
dictionary with `controller`, `tracking`, and `smpl` sections. Coordinates,
rotations, SMPL parameters, and analog trigger values are preserved. Protocol-2
`HandTrigger` / `IndexTrigger` values are floats, not booleans.

Tracking becomes `Pose(Vec3, Quaternion)`; SMPL rotations become `RotationVector`.
Default frame IDs are `meta_tracking` and `meta_smpl`, respectively: the bridge
does **not** assume a shared world frame. The default SMPL `hand_pose_convention`
is `mean_offset`; `root_orientation_valid` and `translation_valid` default to
`True`. Explicit frame, convention, and validity values are preserved. Missing
`betas` or `gender` are not invented.

If `smpl` is absent, the batch contains only controller input and tracking poses.

### Metadata and validation

All messages from one input, including the outer batch, use the same host receipt
time in `metadata.receive_time = Timestamp(seconds=..., clock_kind="unix")`.
The outer batch's `metadata.send_time` is set to that same time.

Packets with unknown fields, duplicate JSON keys, missing required fields,
invalid types or array lengths, or nonfinite numbers are skipped in full and
logged.

---

## 📡 Receiving Messages

ZeroMQ PUB/SUB may lose frames before subscriptions connect or when consumers are
slow. The bridge retains the newest single input and output frame. Subscribers
should also set `ZMQ_CONFLATE=1` to skip older queued batches.

If Meta stops publishing, even the last batch can be stale. Consumers should
check data age using `message.metadata.receive_time.seconds`.

```python
import zmq
from robot_msg import MessageBatch, decode, ports

context = zmq.Context()
subscriber = context.socket(zmq.SUB)
subscriber.setsockopt(zmq.SUBSCRIBE, b"")
subscriber.setsockopt(zmq.CONFLATE, 1)
subscriber.connect(f"tcp://127.0.0.1:{ports.META}")
try:
    while True:
        batch = decode(subscriber.recv())
        assert isinstance(batch, MessageBatch)
        for data in batch.encoded_messages:
            message = decode(bytes(data))
            print(message.MSG_TYPE, message.metadata.receive_time.seconds)
finally:
    subscriber.close(linger=0)
    context.term()
```

---

## 🐍 Use from Python

`MetaFrame` is a typed, frozen view of a received batch. Its nested `robot_msg` objects are shared; treat them as read-only.

| Attribute | Contents |
|---|---|
| `frame.btn_a`, `btn_b`, `btn_x`, `btn_y`, `left/right_thumbstick_click` | Button **levels** (`True` while held) |
| `frame.left/right_index_trigger`, `left/right_hand_trigger`, `left/right_trigger_force` | Analog values |
| `frame.left_thumbstick`, `frame.right_thumbstick` | `(x, y)` tuples |
| `frame.head`, `frame.left_controller`, `frame.right_controller` | `Pose(position, orientation)` |
| `frame.smpl` | `SmplState` or `None` |
| `frame.receive_time` | Host receive time, unix seconds; `frame.age()` gives seconds since then |
| `frame.buttons()`, `frame.triggers()`, `frame.thumbsticks()` | Fresh `dict`s of the above |
| `frame.controller`, `frame.tracking` | The underlying `robot_msg` messages (treat them as read-only) |

There are two ways to get frames. Both are context managers that run a background thread and
offer the same consumer API: `on_frame=` / `.on_frame(cb)` callbacks, `.latest(max_age=None)`,
`.next_frame(timeout)`, and `.frames(buffer=32, timeout=None)` (or `iter(...)`), which yields
new frames from a bounded buffer that drops the oldest frame first.

* **`MetaSubscriber(endpoint="tcp://127.0.0.1:28420")`** consumes the output of a `meta-bridge`
  process that is already running. It reconnects automatically when the bridge restarts. By
  default (`conflate=True`) it keeps only the newest batch. `.connected` and `.reconnects`
  report the link state.
* **`MetaBridge(input_endpoint, output_endpoint=DEFAULT_OUTPUT)`** makes your process *the*
  bridge. Pass `output_endpoint=None` to keep frames in-process with no PUB socket and no port.
  Keep the default if other processes, such as `robot_data_collector`, should still receive
  port 28420.

The example below starts and stops something on A and B:

```python
import time

from meta_bridge import MetaFrame, MetaSubscriber


class StartStopButtons:
    """Rising-edge detector for A and B. It re-baselines after a gap, so no phantom press fires."""

    def __init__(self, stale_after: float = 0.5) -> None:
        self.previous: dict[str, bool] = {}
        self.last_time = float("-inf")
        self.stale_after = stale_after

    def __call__(self, frame: MetaFrame) -> None:
        buttons = frame.buttons()
        if frame.receive_time - self.last_time > self.stale_after:
            self.previous = buttons  # first frame, or the headset came back
        self.last_time = frame.receive_time
        if buttons["btn_a"] and not self.previous["btn_a"]:
            print("A pressed: start recording")
        if buttons["btn_b"] and not self.previous["btn_b"]:
            print("B pressed: stop recording")
        self.previous = buttons


with MetaSubscriber("tcp://127.0.0.1:28420", on_frame=StartStopButtons()) as meta:
    while True:  # your teleoperation loop
        frame = meta.latest(max_age=0.2)  # None while the headset or the bridge is silent
        if frame is not None:
            pass  # e.g. follow frame.right_controller
        time.sleep(0.01)
```

To embed the bridge instead of running `meta-bridge` separately, replace the `with` line:

```python
from meta_bridge import MetaBridge

with MetaBridge("tcp://192.168.50.215:4999", output_endpoint=None, on_frame=StartStopButtons()) as meta:
    ...
```

`decode_frame(data)` turns one raw batch from port 28420 into a `MetaFrame` if you manage your
own socket. `run_bridge(..., on_frame=cb, output_endpoint=None)` is the blocking equivalent of
`MetaBridge`.

**Callbacks** run on the bridge or subscriber thread, in registration order, after the batch
has been published. Keep them short and hand slow work to another thread or a non-blocking API.
An exception from a callback is logged (rate-limited) and counted in `callback_errors`. It never
stops the bridge, and the other callbacks still run. `close()` is idempotent and may be called from inside a callback. Slow callbacks delay shutdown and subsequent input, so use a queue or an async command for longer work. Use `with source.frames(...) as frames:` if you stop iterating early. `latest(max_age=...)` and `next_frame(timeout=...)` return `None` when no qualifying frame is available.

**Buttons are levels, not events.** A press spans many frames at 72-90 Hz. Packets simply stop
when the headset disconnects, so no "released" frame arrives. Edge detection, debouncing,
chords and holds are therefore the consumer's job, and so is re-baselining after a gap.

### With robot_data_collector

Install the [collector](https://pypi.org/project/robot-data-collector-irsl/) only if you want to record episodes:

```bash
pip install meta-bridge-irsl robot-data-collector-irsl==0.1.0
```

With the bridge and the configured recording sources running, this program uses A to start, B to save, and X+Y held for 0.5 s to discard. `RecordingButtons` handles edges and debouncing and queues commands without blocking the subscriber thread. Keep the `__main__` guard: the collector spawns its capture service.

```python
from threading import Event

from meta_bridge import MetaSubscriber
from robot_data_collector import Collector, CollectorConfig
from robot_data_collector.triggers import RecordingButtons


def main():
    with Collector(CollectorConfig.from_toml("teleop.toml"), on_exit="discard") as rec:
        rec.wait_ready(timeout=10)
        buttons = RecordingButtons(rec, task="pick_cube")
        with MetaSubscriber(on_frame=buttons.update):
            Event().wait()  # or run your teleoperation loop here


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        pass  # the Collector already applied its exit policy
```

---

## 🧪 Testing

```bash
uv sync
uv run pytest
# Alternatively, the same suite uses the standard-library test runner:
uv run python -m unittest discover -s tests -v
```

Tests use the public types and codecs from the installed `robot-msg-irsl==0.5.4`
package. The default `dev` dependency group includes pytest. Coverage includes
binary round trips using that package's own decoder, receipt metadata, default
ports, preserved frame IDs and SMPL enums, invalid-packet rejection, and real
ZeroMQ delivery and recovery. `tests/test_api.py` covers the in-process API
(`decode_frame`, callback isolation, `MetaBridge`, `MetaSubscriber` reconnects,
no-PUB mode) and both CLI entry points. Live ZeroMQ tests use loopback ports
22700-22799.

To run against another interpreter without touching `.venv`:

```bash
UV_PROJECT_ENVIRONMENT=/tmp/meta-bridge-py311 uv run --python 3.11 pytest
```

---

## 🛠️ Dependencies

| Package | Purpose |
|---|---|
| `pyzmq>=26,<28` | ZeroMQ input and output transport |
| `robot-msg-irsl==0.5.4` | Protocol-2 message definitions and codecs (`import robot_msg`) |
