跳转至

物联网系统

概述

物联网(IoT)将物理世界的设备通过网络连接起来,实现数据采集、远程控制和智能决策。本文涵盖 IoT 架构、通信协议、边缘计算、设备管理和安全。


1. IoT 系统架构

┌──────────────────────────────────────────┐
│              云平台 (Cloud)                │
│  ┌──────┐ ┌──────┐ ┌──────┐ ┌─────────┐  │
│  │数据存储│ │分析引擎│ │规则引擎│ │ 应用/仪表盘│  │
│  └──────┘ └──────┘ └──────┘ └─────────┘  │
└────────────────┬─────────────────────────┘
                 │ MQTT/HTTPS/AMQP
┌────────────────┴─────────────────────────┐
│           网关层 (Gateway)                 │
│  协议转换、数据聚合、本地缓存、边缘计算      │
└────────────────┬─────────────────────────┘
                 │ BLE/Zigbee/LoRa/WiFi
┌────────────────┴─────────────────────────┐
│         设备层 (Edge Devices)              │
│  ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐         │
│  │传感器│ │执行器│ │摄像头│ │ MCU │         │
│  └─────┘ └─────┘ └─────┘ └─────┘         │
└──────────────────────────────────────────┘

三层架构

层次 角色 代表
感知层 采集数据、执行动作 传感器、MCU、执行器
网络层 数据传输、协议转换 网关、路由器
应用层 存储、分析、展示 云平台、应用

2. 通信协议

2.1 MQTT

MQTT(Message Queuing Telemetry Transport)是最流行的 IoT 协议,基于发布/订阅模型。

Publisher                Broker               Subscriber
   │                       │                      │
   │── CONNECT ──────→     │                      │
   │← CONNACK ────────     │                      │
   │                       │    ←── SUBSCRIBE ─── │
   │                       │       (topic: temp)   │
   │── PUBLISH ──────→     │                      │
   │  (topic: temp,        │── PUBLISH ─────────→ │
   │   payload: 25.5)      │   (topic: temp,       │
   │                       │    payload: 25.5)     │

QoS 级别

QoS 名称 保证 适用
0 At most once 最多一次(可能丢失) 传感器遥测
1 At least once 至少一次(可能重复) 报警通知
2 Exactly once 恰好一次 计费数据

MQTT 主题设计

# 层级结构
building/floor1/room101/temperature
building/floor1/room101/humidity
building/floor1/+/temperature    # + 匹配单层
building/#                        # # 匹配多层

# 最佳实践
{project}/{site}/{device_type}/{device_id}/{telemetry_type}
factory/shanghai/sensor/temp-001/temperature
# Python MQTT 客户端
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")
    client.subscribe("sensors/+/temperature")

def on_message(client, userdata, msg):
    print(f"{msg.topic}: {msg.payload.decode()}")

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.tls_set()  # 启用 TLS
client.username_pw_set("device01", "secret")
client.connect("broker.example.com", 8883)
client.loop_forever()

2.2 CoAP

CoAP(Constrained Application Protocol)是为资源受限设备设计的 REST 风格协议。

特性 CoAP HTTP
传输层 UDP TCP
头部开销 4 字节 几百字节
方法 GET/POST/PUT/DELETE
发现 /.well-known/core 无标准
观察 Observe 选项 长轮询/WebSocket
适用 受限设备 通用 Web

2.3 其他协议

协议 特点 适用场景
HTTP/HTTPS 通用,开销大 非受限设备,云 API
WebSocket 全双工,实时 实时监控仪表盘
BLE 低功耗,短距离 可穿戴设备
Zigbee 网状网络,低功耗 智能家居
LoRa/LoRaWAN 长距离(数公里) 农业、环境监测
NB-IoT 蜂窝网络,低功耗 智慧城市、表计

3. 边缘计算

3.1 为什么需要边缘计算

需求 云计算问题 边缘计算方案
低延迟 网络往返延迟 本地处理
带宽 大量原始数据上传昂贵 本地过滤/压缩
隐私 敏感数据上云有风险 本地处理,只传结果
离线 网络不稳定时无法工作 本地自主运行

3.2 边缘推理

在边缘设备上运行 AI 模型:

# TensorFlow Lite 在树莓派上运行推理
import tflite_runtime.interpreter as tflite
import numpy as np

# 加载量化后的模型
interpreter = tflite.Interpreter(model_path="model_quant.tflite")
interpreter.allocate_tensors()

input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# 推理
input_data = np.array(sensor_reading, dtype=np.float32).reshape(1, -1)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
result = interpreter.get_tensor(output_details[0]['index'])

if result[0] > 0.8:
    send_alert("Anomaly detected!")  # 只在异常时上报

边缘 AI 硬件:

硬件 算力 功耗 适用
Raspberry Pi CPU 通用 5-15W 原型、轻量推理
NVIDIA Jetson GPU 加速 5-30W 视觉、复杂模型
Google Coral TPU 加速 2W 分类、检测
MCU (STM32) 有限 mW 级 关键词检测、手势

3.3 数据过滤与聚合

class EdgeDataProcessor:
    def __init__(self, window_size=60):
        self.buffer = []
        self.window_size = window_size

    def process(self, reading):
        self.buffer.append(reading)

        if len(self.buffer) >= self.window_size:
            # 本地聚合,减少上传数据量
            summary = {
                "mean": np.mean(self.buffer),
                "max": np.max(self.buffer),
                "min": np.min(self.buffer),
                "std": np.std(self.buffer),
                "anomaly_count": sum(1 for x in self.buffer if self._is_anomaly(x))
            }
            self.buffer.clear()
            return summary  # 只上传摘要
        return None

4. 设备管理

4.1 设备生命周期

注册/预配置 → 激活 → 正常运行 → 维护/更新 → 退役
(Provisioning)  (Activation)  (Operation)  (Maintenance)  (Decommission)

4.2 设备注册(Provisioning)

# 设备首次连接:自动注册
device_info = {
    "device_id": get_unique_id(),      # 硬件唯一标识
    "firmware_version": "1.2.0",
    "model": "sensor-v3",
    "capabilities": ["temperature", "humidity"],
    "certificate": load_device_cert()   # X.509 证书
}

# 向云平台注册
response = requests.post(
    "https://iot.example.com/api/devices/register",
    json=device_info,
    cert=("device.crt", "device.key")  # 双向 TLS
)

4.3 OTA 固件更新

云平台 → 通知设备有新固件
设备 → 下载固件(分块、断点续传)
设备 → 验证固件(CRC + 数字签名)
设备 → 安装到备用分区
设备 → 重启,运行新固件
设备 → 自检成功 → 上报云平台
                 → 失败 → 回滚

4.4 设备监控

监控指标:

指标 说明
在线状态 心跳检测(MQTT Last Will)
固件版本 确认更新状态
电池电量 低电量预警
信号强度 网络质量
错误日志 远程故障诊断
资源使用 CPU、内存、存储

5. IoT 安全

5.1 威胁模型

威胁 描述 防护
窃听 截获通信数据 TLS/DTLS 加密
伪造 冒充合法设备 设备证书认证
篡改 修改传输数据 消息完整性校验
固件提取 读取设备固件 安全启动、加密存储
物理攻击 物理接触设备 防篡改硬件、安全元件
DDoS 大量设备被劫持 流量监控、设备认证

5.2 TLS/DTLS

设备 ←────── TLS 1.3 ──────→ MQTT Broker
      双向证书认证 (mTLS)

设备证书链:
Root CA → Intermediate CA → Device Certificate

5.3 设备证书管理

# 设备端:使用 X.509 证书连接
import ssl

context = ssl.create_default_context()
context.load_cert_chain(
    certfile="/certs/device.crt",
    keyfile="/certs/device.key"
)
context.load_verify_locations(cafile="/certs/root_ca.crt")

# 连接 MQTT broker
client.tls_set_context(context)
client.connect("broker.example.com", 8883)

6. IoT 云平台

6.1 主流平台对比

平台 协议支持 边缘能力 特色
AWS IoT Core MQTT, HTTP, WebSocket Greengrass 规则引擎、Shadow
Azure IoT Hub MQTT, AMQP, HTTP IoT Edge Digital Twins
Google Cloud IoT MQTT, HTTP Edge TPU AI/ML 集成
阿里云 IoT MQTT, CoAP Link Edge 物模型、一站式

6.2 设备影子(Device Shadow/Twin)

设备影子是设备状态的云端镜像,允许在设备离线时操作:

{
    "state": {
        "desired": {
            "temperature_threshold": 30,
            "report_interval": 60
        },
        "reported": {
            "temperature": 25.5,
            "firmware_version": "1.2.0",
            "battery": 85
        }
    },
    "metadata": {
        "timestamp": "2024-01-15T10:30:00Z"
    }
}

工作流程:

  1. 应用修改 desired 状态
  2. 设备上线后收到 desiredreported 的差异
  3. 设备执行操作后更新 reported 状态
  4. 差异消除,同步完成

与其他主题的关系

  • 参见 嵌入式软件开发,理解设备端固件、传感器与实时控制逻辑
  • 参见 云服务,理解设备影子、消息代理与云端控制台如何部署
  • 参见 分布式系统,理解消息传递、最终一致性与离线同步问题
  • 参见 计算机网络,理解 MQTT、CoAP 与网络协议栈的通信基础

参考文献

  • "Designing the Internet of Things" - Adrian McEwen
  • MQTT 规范:https://mqtt.org
  • AWS IoT 开发者指南
  • "IoT Inc" - Bruce Sinclair

评论 #