Skip to main content

Getting started on a compio host

On a compio host the service is the handler and the app. MqttBroker::compio starts the runner on the core that connects the broker, over the TCP stream of compio, so nothing is spawned by hand.

The heap variant​

A host has a heap, and the crate's heap variant uses it: the alloc feature, which compio turns on. The broker runs over the rust-mqtt client, the settings hold owned strings, and handlers decode their payload with the codec of the framework, json among them. The broker needs no MqttState, because the client allocates what it receives.

A device that has a heap takes the same variant with alloc and embassy. It builds the broker with MqttBroker::new(config) and spawns the runner as a task, as in getting started on a device, and the handlers use serde types. A device without a heap takes the device variant.

The crates​

cargo add ruststream --no-default-features --features compio,macros,json
cargo add ruststream-rust-mqtt --features compio

The service​

/// Takes every reading the sensors publish.
#[subscriber(MqttTopic::new("sensors/temp"))]
async fn store(reading: &Reading) -> HandlerOutcome {
let _ = reading.celsius;
HandlerOutcome::ack()
}

#[ruststream::app(runtime = compio, cores = 1)]
fn app() -> impl App {
let config = MqttConfig::new("mqtt://localhost:1883").client_id("collector");
RustStream::new(AppInfo::new("collector", "0.1.0"))
.with_broker(MqttBroker::compio(config), |b| b.include(store))
}

#[ruststream::app(runtime = compio, cores = 1)] writes the main of the binary, which understands the command run. cargo run -- run starts the service against the server named in the config. The subscription, the acknowledgement and the publish work as on a device: only the network, the runtime and the memory differ. Testing a compio service shows the test of this app.

A device with a heap​

The runner is a task of the board, and the broker takes the config alone.

/// The runner owns the connection, and the app starts only while it runs.
#[embassy_executor::task]
async fn mqtt(runner: MqttRunner, stack: Stack<'static>) -> ! {
let mut rx = [0; 1024];
let mut tx = [0; 1024];
runner
.run(EmbassyNetwork::new(stack, &mut rx, &mut tx))
.await
}

/// What the board's `main` does once its network stack is up.
fn start(spawner: Spawner, stack: Stack<'static>) {
let config = MqttConfig::new("192.168.1.10:1883").client_id("sensor-7");
let (broker, runner) = MqttBroker::new(config);
spawner.spawn(mqtt(runner, stack).expect("the pool holds the runner's task"));
spawner.spawn(app::task(broker).expect("the pool holds the app's task"));
}