Перейти к основному содержимому
Эта страница ещё не переведена

Ниже показан английский оригинал.

MqttBroker

MqttBroker connects a service to an MQTT 5 server, and the MqttRunner that comes with it owns the connection.

On a device, MqttBroker::new takes the MqttState the board declared as a static and a MqttConfig, and returns the broker with its runner. The state is taken for the life of the program, so one state serves one broker. Building the broker performs no I/O, so the whole service fits the synchronous app builder. The runner performs every read and write on the connection, and the handles of the service (subscriptions, publishers, acknowledgements) talk to it. It waits until the app connects the broker, opens the connection over a network, serves it until the app shuts the broker down or the connection is lost, and then waits for the next connect.

A device spawns the runner as a task of its own, next to the task of the app. The app starts only while the runner runs, because connecting the broker waits for the runner to open the connection.

The broker moves through three types. connect consumes the broker and returns a ConnectedMqttBroker, and shutdown consumes that and returns a ClosedMqttBroker. A publisher the service kept across the shutdown answers MqttError::NotConnected.

The two variants​

The crate has two variants, chosen by its alloc feature, and each fits one kind of build.

The device variant is the default and needs no heap. The crate speaks the protocol itself: a PUBLISH is read into a receive buffer of the state, and the delivery borrows its topic and payload from that buffer. Its settings and descriptors hold &'static str, so they are constants of the firmware. A handler reads the payload as bytes it borrows, with #[derive(Deserialized)], and a reply leaves as the bytes it returns, with #[derive(Serialized)].

The heap variant is the alloc feature, which compio turns on. The broker runs over the rust-mqtt client, which keeps every field it receives in a heap buffer of its own, and the settings hold owned strings. MqttBroker::new(config) takes no state, and on a compio host MqttBroker::compio starts the runner on the core that connects the broker, so the host spawns nothing. A device that has a heap takes this variant too, with alloc and embassy. The guide for a compio host shows it.

The features, all off by default: embassy adds the network of a device, alloc selects the heap variant, compio adds the network of a compio host and MqttBroker::compio (and alloc), and testing adds the in-process transport a TestApp connects.

Example​

A device service: the handler and the app, then the memory, the runner's task and the start function the board's main calls once its network stack is up.

/// A command as the controller sends its bytes, borrowed from the broker's receive buffer.
#[derive(Deserialized)]
struct Command<'a>(&'a [u8]);

/// The state the valve reports, as the bytes that leave.
#[derive(Outgoing, Serialized)]
#[outgoing(name = "valves/v1/state")]
struct State(&'static [u8]);

/// Moves the valve and reports where it is.
#[subscriber(MqttTopic::new("valves/v1/set"), reply)]
async fn set(command: &Command<'_>) -> State {
match command.0 {
b"open" => State(b"opened"),
_ => State(b"closed"),
}
}

#[ruststream::app(runtime = embassy)]
fn app(broker: MqttBroker) -> EmbeddedApp<impl Mounts> {
EmbeddedApp::new().with_broker(broker, |b| b.include(set).out_reply(MqttPublish::default()))
}

The runner's task​

/// The broker's memory: four deliveries of up to 1 KiB, and eight subscriptions.
static MQTT: ConstStaticCell<MqttState> = ConstStaticCell::new(MqttState::new());

/// 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("valve-1");
let (broker, runner) = MqttBroker::new(MQTT.take(), 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"));
}