#request #mqtt #configuration #embedded-io #no-std

no-std minireq

Lightweight support for MQTT-based request/response handling interfaces

5 releases (3 breaking)

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

#702 in Embedded development

Download history 33/week @ 2024-03-31 1/week @ 2024-04-14 134/week @ 2024-06-09 23/week @ 2024-06-16 1/week @ 2024-06-23 22/week @ 2024-06-30

180 downloads per month
Used in booster

MIT license

19KB
295 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

~3.5MB
~75K SLoC