wavegraph-remote 0.1.1

MIDI control and live graph discovery for WaveGraph
Documentation
# wavegraph-remote

[![crates.io][crate-badge]][crate]
[![docs.rs][docs-badge]][docs]
[![Build status][ci-badge]][ci]
[![Project Chat][chat-image]][chat-link]

A Rust client and optional `wr` command for MIDI control and live graph discovery.
The same client operates an FM-1 over USB MIDI or a local
[`wavegraph` host](../wavegraph/) over a Unix socket.

The client sends MIDI notes, controllers, Start and Stop, and queries the
running graph. On the FM-1, graph discovery and Start/Stop require the matching
`wavegraph-fm1` firmware in this workspace. Ordinary note and CC commands also
work with earlier MIDI firmware.

## Features

| Features | Contents |
| --- | --- |
| `cli` (default) | `wr` and the host client, with local socket support on Unix |
| `fm1` | Adds `wr --fm1` and the `fm1-usb` MIDI transport |
| `std` | Transport-independent host client and `UnixTransport` on Unix |
| `usb` | Adds `UsbTransport` to the host library |
| `socket-cli` | Alias for `cli` |
| No features | Bounded, allocation-free `no_std` protocol types and codecs for firmware |

Terminal I/O, REPL state and note audition timing live under `src/bin/`.

## CLI

On Unix, start the local [DSP host](../wavegraph/), then install and run
`wr` from a workspace checkout.

```sh
cargo install --path wavegraph-remote --locked
wr play
wr stop
wr graph
wr --channel 3 note 36 100 250
wr
```

Both processes use `$XDG_RUNTIME_DIR/wavegraph.sock` when the runtime directory
is absolute, otherwise `~/.wavegraph.sock`. Pass `--socket PATH` to both to
select a different socket.

To control an FM-1, build with the `fm1` feature and pass `--fm1`. On
Debian/Ubuntu, install `pkg-config` and `libasound2-dev` before building
this feature. macOS uses CoreMIDI.

```sh
cargo install --path wavegraph-remote --features fm1 --locked
wr --fm1 graph
wr --fm1 --port "WaveGraph FM-1"
```

`--fm1` discovers an attached device. Add `--port` to select a MIDI port by
name or an unambiguous substring. With either transport, `--timeout 2` sets
the graph response timeout in seconds. `wr --help` and `wr help` work offline.

The local socket carries one complete MIDI message per frame. A one-byte length
prefix counts the following 1 through 112 bytes. Notes, controllers, transport
commands and graph discovery use the same MIDI bytes as the USB endpoint.

With no command, `wr` opens a REPL. Use Up and Down to recall commands from
the current terminal session, and Left and Right to edit before pressing Enter.
This FM-1 session selects the `tb303` instance listed by `nodes`.

```text
wr[ch1]> nodes
wr[ch1]> select tb303
Selected tb303 on channel 3. Selection follows the channel if its instrument changes.
wr[ch3]> note 36 100 250
wr[ch3]> cc 74 90
wr[ch3]> inspect tb303
wr[ch3]> graph
wr[ch3]> quit
```

The channel in that example depends on the running assignments. `select ALIAS`
queries the current graph, resolves the alias and selects its channel. Later
commands keep addressing that channel; swapping its instrument does not silently
move the selection to another instance. `select 3` and `channel 3` select a
channel directly. Channels are numbered **1 through 16** in the host API and CLI;
the current FM-1 binds its four tracks to channels 1–4.

| Command | Behavior |
| --- | --- |
| `graph` | Print the snapshot revision, native nodes, signal connections and outputs |
| `nodes` / `instruments` | List instance aliases, types and MIDI channels |
| `inspect ALIAS` | Print a node's identity, channel and ordered signal/message ports |
| `select ALIAS` / `select CHANNEL` | Select an instance's current channel or a channel number |
| `channel [NUMBER]` | Show or change the selected channel |
| `play` / `stop` | Send MIDI Start (restart from the beginning) / Stop |
| `note NOTE [VELOCITY] [MILLISECONDS]` | Audition a note; defaults to velocity 100 and 250 ms |
| `on NOTE [VELOCITY]` / `off NOTE` | Send an individual note-on / note-off |
| `cc CONTROLLER VALUE` | Send a MIDI control change on the selected channel |
| `panic` | Send All Notes Off (CC 123) on the selected channel |
| `help` / `quit` | Show commands / leave the REPL |

Notes and controllers use MIDI numbers 0–127; note-on velocity is 1–127.
`note` duration is timed by the host and is not sample-accurate scheduling.
MIDI Continue is not implemented. Ordinary MIDI sends report submission to the
transport, without a receipt confirming that the DSP applied the event.

On `quit`, EOF (Ctrl-D on an empty line), or Ctrl-C at the prompt, the REPL
releases the notes it started on their original channels even if the selection
changed. Abrupt process termination does not run this cleanup.
One-shot `wr on` intentionally leaves the note held for a later
`wr off` or `wr panic`. Input can also be piped into the REPL; prompts appear only
on an interactive terminal. Parse or command errors are printed and the REPL
continues; one-shot failures return a nonzero exit status.

## Library

```rust,no_run
# #[cfg(feature = "usb")]
# fn main() -> std::io::Result<()> {
use core::time::Duration;
use wavegraph_remote::{Client, MidiCommand, UsbTransport};

let timeout = Duration::from_secs(2);
let transport = UsbTransport::connect(None, timeout)?;
let mut remote = Client::new(transport);
let graph = remote.graph(timeout)?;

for node in &graph.nodes {
    println!("{}: {} ({:?})", node.alias, node.kind, node.midi_channel);
}
if let Some(channel) = graph.node("tb303").and_then(|node| node.midi_channel) {
    remote.send(MidiCommand::ControlChange {
        channel,
        controller: 74,
        value: 90,
    })?;
}
for edge in graph.connections()? {
    println!("{} -> {}", edge.source, edge.destination);
}
# Ok(())
# }
# #[cfg(not(feature = "usb"))]
# fn main() {}
```

`Client<T>` owns any implementation of `Transport`. Its two operations send a
complete MIDI message and receive a complete message with a bounded wait.
Disable default features and enable `std` for the library alone, or `usb`
to include the FM-1 transport. Each transport handles its own framing,
connection lifetime and receive timeout.

## What a snapshot describes

The firmware publishes a topology revision only after an audio block using that
configuration is accepted by the DAC. Each query retains one coherent copy for
its entire response, even if the panel changes assignments during the transfer.
The snapshot contains the nine native processes: four instrument players, the
insert rack, mixer, reverb, delay and stereo master. Internal DSP inside each
native process remains opaque.

Instrument aliases are short alphanumeric labels such as `tb303`, `organ` and
`tr909`. Duplicate types receive numeric suffixes (`tb303`, `tb3032`, ...), in
channel order. Aliases are unique in a snapshot and can change after a swap.
`Node::id` is the object-table index; `generation` distinguishes instrument
assignments within the session. Neither an alias nor a channel is a persistent
instrument identity.

`Graph::connections()` reconstructs the signal connections from the actual
bytecode and ordered native port declarations. Port numbers include message
ports, so a signal after a message port keeps its true local index. Built-in
gain and mix operations get synthetic `@gainN` / `@mixN` labels. The active
output bindings include the firmware's optional half-gain path. MIDI channels
are listed separately; arbitrary message-cord topology is not encoded in v1.

`session` is the target's USB connection epoch, not a globally unique boot ID.
`revision` changes on instrument assignment/generation or signal-routing changes,
including half gain; CC values and playback do not increment it. `first_frame`
identifies the first accepted audio block for that revision, not the current
playhead. Reconnect and query again after losing the transport.

## Protocol and scope

Performance commands use ordinary MIDI messages. Discovery uses versioned SysEx
records in the development/noncommercial `0x7d` namespace, prefixed with `WG`.
Each record carries a 32-bit request ID. The record sequence is Query, Begin,
Node records, contiguous bytecode chunks, then End; Error reports a target
rejection. Binary payloads use seven-bit packing. `protocol` exposes the shared
types and codecs so firmware and host use the same wire format.

The firmware uses fixed buffers and preserves partially accepted USB writes.
Other outgoing MIDI and logs can run between complete discovery records. The
client applies a total query deadline and rejects incomplete, duplicated,
reordered or malformed snapshots. It ignores ordinary MIDI and other requests'
replies. The USB receive queue is bounded and reports overflow rather than
returning a partial graph. Current bounds are 80 decoded payload bytes per
record, 4,096 signal-bytecode bytes per snapshot and 16 physical outputs.

This version provides snapshots, MIDI parameter/event control and a stateful CLI.
The local host compiles its text patch at startup. Graph editing, automatic
reconnect and subscriptions remain future work.
Snapshot identities and revisions provide a starting point for change
notifications; v1 does not claim persistent identity, replay or pub/sub semantics.

## License

The Rust code is licensed under either of

- [Apache License, Version 2.0][apache]
- [MIT License][mit]

at your option.

### Contribution

Unless you explicitly state otherwise, you license any contribution you
intentionally submit for inclusion in this work (as defined in the Apache-2.0
license) under both licenses above, without additional terms or conditions.

[crate-badge]: https://img.shields.io/crates/v/wavegraph-remote?logo=rust
[crate]: https://crates.io/crates/wavegraph-remote
[docs-badge]: https://docs.rs/wavegraph-remote/badge.svg
[docs]: https://docs.rs/wavegraph-remote/
[ci-badge]: https://github.com/fm1-rust/wavegraph/actions/workflows/wavegraph-remote.yml/badge.svg?branch=main&event=push
[ci]: https://github.com/fm1-rust/wavegraph/actions/workflows/wavegraph-remote.yml
[chat-image]: https://img.shields.io/badge/discord-join_chat-blue.svg
[chat-link]: https://discord.gg/bq8NYQWzm5
[apache]: https://github.com/fm1-rust/wavegraph/blob/main/wavegraph-remote/LICENSE-APACHE
[mit]: https://github.com/fm1-rust/wavegraph/blob/main/wavegraph-remote/LICENSE-MIT