本页译自英文,由模型翻译。若与英文原文存在差异,以英文原文为准。
在设备上入门
设备服务没有堆。
Broker 的内存是开发板声明的 static,投递从这块内存的接收缓冲区借用载荷,回复则编码进其中的发送缓冲区。
本指南构建一块阀门开发板,它执行发布到 valves/v1/set 的命令,并报告所达到的状态。
服务由三部分组成:处理器和应用,持有 MQTT 连接的 runner 任务,以及启动二者的开发板 main。
所需的 crate
cargo add ruststream --no-default-features --features embassy,macros
cargo add ruststream-rust-mqtt --features embassy
cargo add embassy-executor embassy-net static_cell
Broker crate 的 embassy 特性提供 EmbassyNetwork,即基于 embassy-net 栈的 runner 网络。
Broker crate 在 alloc 特性开启之前是设备变体,框架随之而定:ruststream 中需要堆的特性(例如 json)会开启框架的 alloc,此时 Broker crate 也要开启自己的 alloc 特性。
带有堆的设备以同样的方式使用堆变体。
处理器和应用
处理器接收 Command 并返回所达到的 State。
Command 是以到达时的字节表示的载荷:它从 Broker 的接收缓冲区借用这些字节,所以读取命令不复制任何内容。
State 是发出的字节,回复被直接编码进发送缓冲区。
#[ruststream::app(runtime = embassy)] 把应用函数变成一个 embassy 任务 app::task。
- 宏
- 手写
/// 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()))
}
/// A command as the controller sends its bytes, borrowed from the broker's receive buffer.
struct Command<'a>(&'a [u8]);
// `#[derive(Deserialized)]` by hand: the view borrows the payload, and `&Command<'_>` takes the
// lane that reads no codec.
impl Deserialized for Command<'_> {
type Output<'a> = Command<'a>;
type Error = Infallible;
fn from_payload(payload: &[u8]) -> Result<Command<'_>, Self::Error> {
Ok(Command(payload))
}
}
impl Input for Command<'_> {
type Axis = SoloDeserialized<Command<'static>>;
}
/// The state the valve reports, as the bytes that leave.
struct State(&'static [u8]);
// `#[derive(Serialized)]` by hand: the bytes, the wire of a typed publish, the shape of a reply.
impl Serialized for State {
type Error = Infallible;
fn wire_bytes(&self, _buf: &mut EncodeBuf) -> Result<WireBytes<'_>, Infallible> {
Ok(WireBytes::Own(self.0))
}
}
impl MessageWire for State {
type Wire = SerializedWire;
}
impl ReplyShape for State {
type Body = Self;
type Headers = ();
type Wire = SerializedReply;
}
// `#[derive(Outgoing)]` with no `name`, by hand: the mount names the destination.
impl OutgoingDestination for State {
type Form = CallerName;
}
impl MessageHeaders for State {
type Contract = NoHeaders;
}
/// Moves the valve and reports where it is.
struct Set;
impl<'p> Handle<Command<'p>, State> for Set {
fn handle(
&self,
command: &Command<'p>,
_outs: &(),
_ctx: &mut Context<'_>,
) -> impl Future<Output = Result<State, HandlerOutcome>> {
ready(Ok(match command.0 {
b"open" => State(b"opened"),
_ => State(b"closed"),
}))
}
}
fn app(broker: MqttBroker) -> EmbeddedApp<impl Mounts> {
EmbeddedApp::new().with_broker(broker, |b| {
b.include(
subscriber("valves/v1/set", Set)
.map_source(|_| MqttTopic::new("valves/v1/set"))
.reply()
.to("valves/v1/state")
.build(),
)
.out_reply(MqttPublish::default())
})
}
内存、runner 和开发板
MqttState 是 Broker 拥有的全部内存:投递借用的接收缓冲区、发送缓冲区和订阅表。
开发板把它声明为 static,并一次性交给 MqttBroker::new,后者返回 Broker 及其 runner。
Runner 持有连接:应用连接 Broker 时由它打开连接,所有读、写和确认都经过它。
因此开发板启动两个任务:基于网络栈的 runner,以及带着 Broker 的应用。
套接字缓冲区位于 runner 的任务中,大小由开发板决定。
- 宏
- 手写
/// 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"));
}
/// 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
}
/// The app's control: `stop` asks it to shut down, and `health` reads where it is.
static CONTROL: Control = Control::new();
/// Runs the app until the control stops it.
#[embassy_executor::task]
async fn service(broker: MqttBroker) {
let _ = app(broker).run(&CONTROL).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(service(broker).expect("the pool holds the app's task"));
}
MqttState 的默认值是四条投递,每条最多 1 KiB,以及八个订阅。
地址、客户端 ID、凭据和会话是 MqttConfig 的设置。
在固件到达开发板之前,请先在主机上测试服务:测试声明自己的内存,不需要 runner。