# wavegraph-remote
[![Build status][build-image]][build-link]
[![Project Chat][chat-image]][chat-link]
A Rust client and optional `wr` command for MIDI control and live graph discovery.
The library has no terminal interface. `fm1-usb` is the first transport adapter;
the `Transport` trait also accepts in-process or future local IPC implementations.
This first version sends MIDI notes, controllers, Start and Stop, and queries a
coherent snapshot of the graph most recently accepted by the FM-1 audio output.
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.
The macOS audio backend does not yet expose this remote protocol.
## Features
| `usb` (default) | `UsbTransport`, `fm1-usb`, and the host client |
| `std` with default features disabled | Transport-independent host client, with no native MIDI dependencies |
| `cli` | `wr`, its argument parser and the USB adapter |
| No features | Bounded, allocation-free `no_std` protocol types and codecs for firmware |
The binary has `required-features = ["cli"]`. Terminal I/O, REPL state and note
audition timing live under `src/bin/`; the library does not depend on the CLI.
## CLI
```sh
cargo install wavegraph-remote --features cli --locked
wr play
wr stop
wr graph
wr --channel 3 note 36 100 250
wr
```
On Debian/Ubuntu, install `pkg-config` and `libasound2-dev` before building the USB adapter.
macOS uses CoreMIDI through `fm1-usb`.
By default, `wr` discovers the attached FM-1 using `fm1-usb`. Use
`wr --port "WaveGraph FM-1"` to select a MIDI port by name or an unambiguous
substring. `--timeout 2` sets the graph response timeout in seconds. `wr --help`
and `wr help` work without a device.
With no command, `wr` opens a line-oriented REPL. For example, after `nodes`
shows an instance named `tb303`:
```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.
| `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` or EOF, 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. A
future Unix socket adapter can frame the same messages with lengths; it does not
need to implement terminal behavior. Disable default features and enable `std`
to use the client without `fm1-usb`. The transport's framing, connection lifetime
and receive timeout remain its responsibility.
## 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.
Graph editing/upload, host compilation of a text patch language, automatic
reconnect, subscriptions and Unix socket/CoreAudio endpoints are 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
Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or
[MIT License](LICENSE-MIT), at your option.
[build-image]: https://github.com/fm1-rust/wavegraph/actions/workflows/wavegraph-remote.yml/badge.svg?branch=main&event=push
[build-link]: 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/df6wwm5Kfd