rust-iot

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

IoT Development

IoT 开发

Domain Constraints

领域约束

Domain RuleDesign ConstraintRust Implication
Unreliable networkOffline-firstLocal buffering
Power constraintsEfficient codeSleep modes, minimal alloc
Resource limitsSmall footprintno_std where needed
SecurityEncrypted commsTLS, signed firmware
ReliabilitySelf-recoveryWatchdog, error handling
OTA updatesSafe upgradesRollback capability
领域规则设计约束Rust 相关实现
不可靠网络离线优先本地缓冲
电源限制高效代码睡眠模式、最小化内存分配
资源受限小内存占用必要时使用no_std
安全性加密通信TLS、签名固件
可靠性自我恢复看门狗、错误处理
OTA更新安全升级回滚能力

Critical Rules

关键规则

  • Network can fail at any time — design offline-first with local queue and retry with backoff.
  • Minimize power consumption — use sleep modes and efficient algorithms for battery life.
  • All communication encrypted — physical access is possible, use TLS and signed messages.
  • 网络随时可能故障 —— 采用离线优先设计,搭配本地队列和退避重试机制。
  • 最小化功耗 —— 使用睡眠模式和高效算法以延长电池寿命。
  • 所有通信均加密 —— 设备可能被物理访问,需使用TLS和签名消息。

Environment Comparison

环境对比

EnvironmentStackCrates
Linux gatewaytokio + stdrumqttc, reqwest
MCU deviceembassy + no_stdembedded-hal
HybridSplit workloadsBoth
环境技术栈依赖库(Crates)
Linux网关tokio + stdrumqttc, reqwest
MCU设备embassy + no_stdembedded-hal
混合环境拆分工作负载以上两者

Key Crates

核心依赖库(Key Crates)

PurposeCrate
MQTT (std)rumqttc, paho-mqtt
Embeddedembedded-hal, embassy
Async (std)tokio
Async (no_std)embassy
Logging (no_std)defmt
Logging (std)tracing
用途Crate
MQTT(std环境)rumqttc, paho-mqtt
嵌入式开发embedded-hal, embassy
异步(std环境)tokio
异步(no_std环境)embassy
日志(no_std环境)defmt
日志(std环境)tracing

Design Patterns

设计模式

PatternPurposeImplementation
Pub/SubDevice commsMQTT topics
Edge computeLocal processingFilter before upload
OTA updatesFirmware upgradeSigned + rollback
Power mgmtBattery lifeSleep + wake events
Store & forwardNetwork reliabilityLocal queue
模式用途实现方式
发布/订阅(Pub/Sub)设备通信MQTT主题
边缘计算本地数据处理上传前过滤数据
OTA更新固件升级签名固件 + 回滚机制
电源管理延长电池寿命睡眠 + 唤醒事件
存储转发网络可靠性保障本地队列

MQTT Client Pattern

MQTT客户端实现示例

rust
use rumqttc::{AsyncClient, MqttOptions, QoS};

async fn run_mqtt() -> anyhow::Result<()> {
    let mut options = MqttOptions::new("device-1", "broker.example.com", 1883);
    options.set_keep_alive(Duration::from_secs(30));

    let (client, mut eventloop) = AsyncClient::new(options, 10);

    // Subscribe to commands
    client.subscribe("devices/device-1/commands", QoS::AtLeastOnce).await?;

    // Publish telemetry
    tokio::spawn(async move {
        loop {
            let data = read_sensor().await;
            client.publish("devices/device-1/telemetry", QoS::AtLeastOnce, false, data).await.ok();
            tokio::time::sleep(Duration::from_secs(60)).await;
        }
    });

    // Process events with reconnection
    loop {
        match eventloop.poll().await {
            Ok(event) => handle_event(event).await,
            Err(e) => {
                tracing::error!("MQTT error: {}", e);
                tokio::time::sleep(Duration::from_secs(5)).await;
            }
        }
    }
}
rust
use rumqttc::{AsyncClient, MqttOptions, QoS};

async fn run_mqtt() -> anyhow::Result<()> {
    let mut options = MqttOptions::new("device-1", "broker.example.com", 1883);
    options.set_keep_alive(Duration::from_secs(30));

    let (client, mut eventloop) = AsyncClient::new(options, 10);

    // Subscribe to commands
    client.subscribe("devices/device-1/commands", QoS::AtLeastOnce).await?;

    // Publish telemetry
    tokio::spawn(async move {
        loop {
            let data = read_sensor().await;
            client.publish("devices/device-1/telemetry", QoS::AtLeastOnce, false, data).await.ok();
            tokio::time::sleep(Duration::from_secs(60)).await;
        }
    });

    // Process events with reconnection
    loop {
        match eventloop.poll().await {
            Ok(event) => handle_event(event).await,
            Err(e) => {
                tracing::error!("MQTT error: {}", e);
                tokio::time::sleep(Duration::from_secs(5)).await;
            }
        }
    }
}

Common Mistakes

常见错误

MistakeDomain ViolationFix
No retry logicLost dataExponential backoff
Always-on radioBattery drainSleep between sends
Unencrypted MQTTSecurity riskTLS
No local bufferNetwork outage = data lossPersist locally
错误违反的领域规则修复方案
无重试逻辑数据丢失指数退避重试
无线模块始终开启电池耗尽发送间隔期间睡眠
未加密的MQTT通信安全风险使用TLS
无本地缓冲网络中断导致数据丢失本地持久化数据