#request #mqtt #configuration #no-std

no-std minireq

Lightweight support for MQTT-based request/response handling interfaces

4 releases (2 breaking)

0.3.0 Nov 1, 2023
0.2.0 Jun 22, 2023
0.1.1 Dec 6, 2022
0.1.0 Mar 28, 2022

#1039 in Embedded development


Used in booster

MIT license

19KB
291 lines

minireq

Minimal MQTT-based request/response library


lib.rs:

MQTT Request/response Handling

Overview

This library is intended to be an easy way to handle inbound requests automatically.

Handler functions can be associated with the library to be automatically called whenever a specified request is received, and the handler will automatically be invoked with the request data.

Limitations

  • The poll() function has a somewhat odd signature (using a function to provide the Context and call the handler) due to required compatibility with RTIC and unlocked resources.

  • Handlers may only be closures that do not capture any local resources. Instead, move local captures into the Context, which will be provided to the handler in the function call.

Example

use embedded_io::Write;

#[derive(Copy, Clone)]
struct Context {}

#[derive(serde::Serialize, serde::Deserialize)]
struct Request {
    data: u32,
}

// Handler function for processing an incoming request.
pub fn handler(
    context: &mut Context,
    cmd: &str,
    data: &[u8],
    mut output_buffer: &mut [u8]
) -> Result<usize, minireq::NoErrors> {
    // Deserialize the request.
    let mut request: Request = serde_json_core::from_slice(data).unwrap().0;

    let response = request.data.wrapping_add(1);
    let start = output_buffer.len();

    write!(output_buffer, "{}", response).unwrap();
    Ok(start - output_buffer.len())
}

let mqtt: minimq::Minimq<'_, _, _, minimq::broker::IpBroker> = minireq::minimq::Minimq::new(
// Constructor
);

// Construct the client
let mut handlers = [None; 10];
let mut client: minireq::Minireq<Context, _, _, _> = minireq::Minireq::new(
    "prefix/device",
    mqtt,
    &mut handlers[..],
)
.unwrap();

// Whenever the `/test` command is received, call the associated handler.
// You may add as many handlers as you would like.
client.register("/test", handler).unwrap();

// ...

loop {
    // In your main execution loop, continually poll the client to process incoming requests.
    client.poll(|handler, command, data, buffer| {
        let mut context = Context {};
        handler(&mut context, command, data, buffer)
    }).unwrap();
}

Dependencies

~2.1–2.9MB
~58K SLoC