gearvr-controller 0.1.1

Read the Samsung Gear VR Controller (ET-YO324) over Bluetooth LE: packet decoding, orientation tracking and a btleplug transport
Documentation
# gearvr-controller

<!-- Pictures and links to files in this repository are written as full addresses, because
     crates.io shows this file from the library's folder and would resolve relative ones there. -->

Use a Samsung Gear VR Controller (model ET-YO324) from a computer. The controller speaks
Bluetooth LE with its own protocol, so no operating system treats it as a gamepad. This
repository reads it directly:

- **`gearvr-controller`** is a Rust library: packet decoding, orientation tracking, a
  simulated controller, and a Bluetooth connection that reconnects by itself.
- **`gearvr-demo`** is a terminal app built on the library. It shows the controller turning
  in 3D, the touchpad, the buttons and live sensor traces.
- **`gearvr-viewer`** is a graphical app built on the library, drawn with
  [wgpu]https://wgpu.rs. The controller turns in 3D and paints where you point it. It
  runs as a desktop window and, built for WebAssembly, in a web page.
- **`web/`** holds two browser pages: a readout of the controller's sensors over Web
  Bluetooth, and the page the graphical app runs in.

**Try it in your browser**, with nothing to install:
[the graphical demo](https://bagobor.github.io/gearvr-controller/viewer.html) and
[the sensor readout](https://bagobor.github.io/gearvr-controller/). Both run a simulated
controller if you do not have one. Connecting a real one needs Chrome or Edge on a
computer.

![The terminal demo: a wireframe of the controller turning in 3D, the touchpad with a finger on it, the six buttons, and live traces of acceleration, rotation and magnetic field](https://raw.githubusercontent.com/bagobor/gearvr-controller/main/docs/terminal-demo.svg)

The terminal demo, here showing the built-in simulated controller. The picture is drawn
from the program's own output.

## What has been tested

- The browser demo has been used with a real controller, in Chrome on macOS.
- The Rust packet decoder is checked against a packet captured from that controller.
- The orientation filter, the simulator, the terminal view and the graphical demo's scene
  are covered by tests.
- The graphical demo has been run on macOS with the simulated controller only: as a
  desktop window, and as a web page in Chrome. The web page's Bluetooth code is copied from
  the browser demo's, but that copy has not yet been run with a real controller.
- **The Rust Bluetooth connection has not yet been run against a real controller.** It
  compiles and follows the same steps as the browser demo. Treat it as untested until you
  have seen it connect.

## Run the terminal demo

You need [Rust](https://rustup.rs). No controller is needed to try it:

```bash
cargo run -p gearvr-demo -- --simulate
```

With a controller, press any button on it to wake it, then:

```bash
cargo run -p gearvr-demo
```

`q` quits. `r` makes the direction the controller points the new "straight ahead"; the Home
button on the controller does the same. Add `--plain` to print readings as lines of text
instead of the full-screen view.

On macOS the terminal you run this in needs the Bluetooth permission. macOS asks the first
time; you can also turn it on in System Settings → Privacy & Security → Bluetooth. On Linux
the program talks to BlueZ, which needs `libdbus-1-dev` and `pkg-config` to build.

## Run the graphical demo

![The graphical demo: a 3D model of the controller seen from behind, pointing a thin ray at a grid dome with five coloured brush strokes painted on it](https://raw.githubusercontent.com/bagobor/gearvr-controller/main/docs/viewer.png)

The controller sits inside a dome and you paint on it by pointing. Try it without a
controller:

```bash
cargo run --release -p gearvr-viewer -- --simulate
```

With a controller, press any button on it to wake it, then:

```bash
cargo run --release -p gearvr-viewer
```

| On the controller | |
|---|---|
| Trigger | Paint while held |
| Touchpad click | Next colour |
| Volume up, volume down | Bigger brush, smaller brush |
| Back, held for a moment | Wipe the drawing |
| Home | Make the direction it points the new "straight ahead" |

In the window, `r` recenters, `c` wipes the drawing, and `q` or Esc quits. The window's
title shows the connection, the battery and the brush. The Bluetooth permission note above
applies here too.

### In a web page

The same app builds for the browser. It draws with WebGPU, which current Chrome, Edge and
Safari have. The published copy is at
<https://bagobor.github.io/gearvr-controller/viewer.html>.

To run your own copy, build it once, and again after changing the code:

```bash
./web/build.sh
```

The script needs the `wasm32-unknown-unknown` target (`rustup target add
wasm32-unknown-unknown`). It installs the matching `wasm-bindgen` tool into `target/` if
you do not have it, and writes the result to `web/pkg`. Then serve the `web` folder:

```bash
python3 -m http.server 8712 --bind 127.0.0.1 --directory web
```

Open <http://localhost:8712/viewer.html>. The page starts with the simulated controller.
**Connect controller** switches to a real one; that needs Web Bluetooth, so Chrome or Edge
on a computer. The page's JavaScript holds the Bluetooth connection and hands each packet
to the Rust code, which is the same scene the desktop window shows.

## Run the browser demo

The published copy is at <https://bagobor.github.io/gearvr-controller/>. To run your own
copy, serve the folder locally. Web Bluetooth only works in Chrome or Edge, and only on
`localhost` or HTTPS:

```bash
python3 -m http.server 8712 --bind 127.0.0.1 --directory web
```

Then open <http://localhost:8712> in Chrome and choose **Connect controller**, or **Run
simulation** to see it without one.

## Use the library

```toml
[dependencies]
gearvr-controller = "0.1"
tokio = { version = "1", features = ["macros", "rt"] }
```

The crate is on [crates.io](https://crates.io/crates/gearvr-controller) and its
documentation is on [docs.rs](https://docs.rs/gearvr-controller). To follow `main` instead
of a release, depend on the repository:
`gearvr-controller = { git = "https://github.com/bagobor/gearvr-controller" }`.

```rust
use gearvr_controller::{ble, Orientation};

#[tokio::main(flavor = "current_thread")]
async fn main() {
    let mut orientation = Orientation::new();
    let mut events = ble::events(); // finds the controller, reconnects when it sleeps

    while let Some(event) = events.recv().await {
        match event {
            ble::Event::Packet(packet) => {
                orientation.update(&packet);
                let e = orientation.euler();
                println!(
                    "yaw {:.0}°  touch {:?}  buttons {:?}",
                    e.yaw.to_degrees(),
                    packet.touch,
                    packet.buttons
                );
            }
            other => println!("{other:?}"),
        }
    }
}
```

`ble::Controller` gives direct control if you would rather manage the connection yourself.

Decoding and orientation tracking have no dependencies. To use them with your own Bluetooth
code, or on a platform btleplug does not cover, turn the default feature off:

```toml
gearvr-controller = { version = "0.1", default-features = false }
```

```rust
use gearvr_controller::{Orientation, Packet};

fn on_notification(bytes: &[u8], orientation: &mut Orientation) {
    if let Ok(packet) = Packet::parse(bytes) {
        orientation.update(&packet);
    }
}
```

`sim::Simulator` produces the same bytes a controller sends, so you can build and test
without the hardware.

Without the feature the crate also builds for WebAssembly. `Event`, the type the Bluetooth
connection reports with, stays available, so another transport can report the same way.
The graphical demo's web page does exactly that.

## How the controller talks

| | |
|---|---|
| Advertised name | `Gear VR Controller(XXXX)` |
| Service | `4f63756c-7573-2054-6872-65656d6f7465` |
| Data (notify) | `c8c51726-81bc-483b-a052-f7a14ea3d281` |
| Commands (write) | `c8c51726-81bc-483b-a052-f7a14ea3d282` |
| Battery | standard battery service, `0x2A19` |

Commands are two bytes:

| Bytes | Meaning |
|---|---|
| `01 00` | Start sending data ("sensor mode") |
| `00 00` | Stop sending data |
| `04 00` | Keep-alive |
| `08 00` | "VR mode". It does not work from a computer, so nothing here uses it |

In sensor mode the controller sends a 60-byte packet about 69 times a second. Values are
little-endian.

| Bytes | Content |
|---|---|
| 0–15 | Motion sample 1: `u32` time in µs, then accelerometer x y z and gyroscope x y z as `i16` |
| 16–31 | Motion sample 2, same layout, about 4850 µs later |
| 32–47 | Motion sample 3 |
| 48–53 | Magnetometer as `i16`, stored in y, x, z order |
| 54–56 | Touchpad: two 10-bit numbers, x then y, 0–315; both 0 means not touched |
| 57 | Temperature |
| 58 | Buttons: 1 trigger, 2 home, 4 back, 8 touchpad click, 16 volume up, 32 volume down. 64 is set while nothing is pressed |
| 59 | Unknown |

Scale factors: accelerometer × 9.80665 / 2048 gives m/s², gyroscope × 0.017453292 / 14.285
gives rad/s, magnetometer × 0.06 gives µT.

Axes: x points right, y points forward out of the tip, z points up out of the touchpad face.

## Things to know

- **It falls asleep.** Left still for about a minute, the controller drops the connection.
  The keep-alive command does not prevent this. Press any button to wake it; the library
  and both demos reconnect by themselves.
- **One connection at a time.** If a phone, a browser tab or another program holds the
  controller, nothing else will find it.
- **Heading drifts.** Pitch and roll are anchored by gravity, but nothing anchors the
  heading, so it wanders slowly. Recenter when it matters. The magnetometer could fix this
  but its readings are uncalibrated, so it is not used.
- **The model's handedness is assumed.** The axis directions above match other open
  implementations and a captured packet, but have not been checked by eye against the real
  controller. If the picture turns the wrong way, that is where to look.

## Development

```bash
cargo test --workspace
```

```bash
cargo clippy --workspace --all-targets -- -D warnings
```

The graphical demo has code that only the browser build compiles. Check that too:

```bash
cargo clippy -p gearvr-viewer --lib --target wasm32-unknown-unknown -- -D warnings
```

Every push to `main` rebuilds the browser version and publishes the `web` folder to GitHub
Pages. The steps are in [.github/workflows/pages.yml](https://github.com/bagobor/gearvr-controller/blob/main/.github/workflows/pages.yml).

Both pictures on this page are generated. After changing the terminal view or the
graphical demo, redraw them:

```bash
cargo run -p gearvr-demo --example screenshot -- docs/terminal-demo.svg
```

```bash
cargo run --release -p gearvr-viewer -- --screenshot docs/viewer.png
```

## Credits

The protocol was worked out by others. This project leans on
[jsyang/gearvr-controller-webbluetooth](https://github.com/jsyang/gearvr-controller-webbluetooth)
and [uutzinger/gearVRC](https://github.com/uutzinger/gearVRC).

## License

MIT. See [LICENSE](https://github.com/bagobor/gearvr-controller/blob/main/LICENSE).