跳到主要内容

速查表

本文汇总物联网开发中常用的术语、协议、命令和最佳实践,方便快速查阅。

常用术语

术语英文说明
物联网IoT (Internet of Things)物理设备互联的网络
低功耗广域网LPWAN低功耗、长距离通信技术
边缘计算Edge Computing在网络边缘进行数据处理
数字孪生Digital Twin物理实体的数字映射
时序数据库Time Series Database存储时序数据的数据库
预测性维护Predictive Maintenance基于数据预测设备故障

通信协议

MQTT

# 订阅主题
mosquitto_sub -h broker.example.com -t "sensors/#" -v

# 发布消息
mosquitto_pub -h broker.example.com -t "sensors/temp" -m "25.5"

# 带用户名密码
mosquitto_sub -h broker.example.com -t "sensors/#" -u "user" -P "pass"

QoS 等级:

QoS说明
0最多一次,可能丢失
1至少一次,可能重复
2恰好一次,保证送达

常用主题设计:

devices/{device_id}/telemetry    # 遥测数据
devices/{device_id}/command # 下发命令
devices/{device_id}/status # 设备状态
devices/{device_id}/config # 配置更新

CoAP

# GET 请求
coap-client -m get coap://example.com/sensors/temp

# PUT 请求
coap-client -m put -e "on" coap://example.com/actuators/led

HTTP API

# 获取设备列表
curl -X GET https://api.example.com/v1/devices

# 上报数据
curl -X POST https://api.example.com/v1/devices/{id}/telemetry \
-H "Content-Type: application/json" \
-d '{"temperature": 25.5, "humidity": 60}'

# 发送命令
curl -X POST https://api.example.com/v1/devices/{id}/command \
-H "Content-Type: application/json" \
-d '{"action": "turn_on", "params": {"light_id": 1}}'

无线通信

技术对比

技术距离功耗带宽适用场景
WiFi50m智能家居
BLE100m可穿戴设备
Zigbee100m智能家居
LoRa15km极低极低广域物联网
NB-IoT10km极低智能抄表
5G数km极高工业物联网

ESP32 WiFi

#include <WiFi.h>

WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
Serial.println(WiFi.localIP());

ESP32 BLE

#include <BLEDevice.h>

BLEDevice::init("ESP32-BLE");
BLEServer *pServer = BLEDevice::createServer();
pServer->getAdvertising()->start();

传感器

常用传感器

传感器接口
DHT22 温湿度GPIODHTesp
BME280 温湿压I2CAdafruit_BME280
DS18B20 温度GPIODallasTemperature
MPU6050 运动传感器I2CMPU6050_tockn
HC-SR04 超声波GPIONewPing

DHT22 示例

#include <DHTesp.h>

DHTesp dht;
dht.setup(4, DHTesp::DHT22);

float temp = dht.getTemperature();
float humi = dht.getHumidity();

BME280 示例

#include <Wire.h>
#include <Adafruit_BME280.h>

Adafruit_BME280 bme;
bme.begin(0x76);

float temp = bme.readTemperature();
float humi = bme.readHumidity();
float pres = bme.readPressure() / 100.0F;

数据存储

InfluxDB

# 写入数据
influx write -b iot-bucket -o org "temperature,device=sensor01 value=25.5"

# 查询数据
influx query 'from(bucket:"iot-bucket") |> range(start: -1h)'

TimescaleDB

-- 创建 hypertable
SELECT create_hypertable('sensor_data', 'time');

-- 插入数据
INSERT INTO sensor_data (time, device_id, temperature)
VALUES (NOW(), 'sensor01', 25.5);

-- 查询数据
SELECT * FROM sensor_data
WHERE time > NOW() - INTERVAL '1 hour';

Redis

# 设置键值
redis-cli SET device:sensor01:status "online"

# 获取键值
redis-cli GET device:sensor01:status

# 设置过期时间
redis-cli SETEX device:sensor01:data 300 '{"temp":25.5}'

开发框架

ESP-IDF 常用命令

# 创建项目
idf.py create-project my_project

# 配置项目
idf.py menuconfig

# 编译
idf.py build

# 烧录
idf.py -p /dev/ttyUSB0 flash

# 监控
idf.py -p /dev/ttyUSB0 monitor

Arduino 常用库

用途
WiFiWiFi 连接
PubSubClientMQTT 客户端
ArduinoJsonJSON 解析
OneWire单总线设备
WireI2C 通信
SPISPI 通信

平台 API

AWS IoT

import boto3

client = boto3.client('iot-data')
client.publish(
topic='devices/sensor01/data',
payload=json.dumps({'temperature': 25.5})
)

阿里云 IoT

import paho.mqtt.client as mqtt

client = mqtt.Client()
client.username_pw_set(username, password)
client.connect(f"{product_key}.iot-as-mqtt.aliyuncs.com", 1883)
client.publish(topic, payload)

调试技巧

串口调试

Serial.begin(115200);
Serial.println("Debug message");
Serial.printf("Temperature: %.2f\n", temp);

日志级别

ESP_LOGE(TAG, "Error message");
ESP_LOGW(TAG, "Warning message");
ESP_LOGI(TAG, "Info message");
ESP_LOGD(TAG, "Debug message");
ESP_LOGV(TAG, "Verbose message");

网络调试

# 抓包
tcpdump -i wlan0 port 1883

# 查看端口
netstat -tlnp | grep 1883

# 测试连接
telnet broker.example.com 1883

安全最佳实践

设备认证

// TLS 连接
esp_mqtt_client_config_t mqtt_cfg = {
.broker.address.uri = "mqtts://broker.example.com:8883",
.broker.verification.certificate = root_ca_pem,
.credentials.authentication.certificate = device_cert_pem,
.credentials.authentication.key = device_key_pem,
};

数据加密

from cryptography.fernet import Fernet

key = Fernet.generate_key()
cipher = Fernet(key)
encrypted = cipher.encrypt(data.encode())
decrypted = cipher.decrypt(encrypted)

常见问题

连接问题

问题可能原因解决方案
WiFi 连接失败密码错误、信号弱检查密码、靠近路由器
MQTT 连接断开网络不稳定、心跳超时增加心跳间隔、重连机制
传感器读取失败接线错误、地址错误检查接线、扫描 I2C 地址

性能优化

问题解决方案
内存不足减少缓冲区、使用 PSRAM
功耗过高使用睡眠模式、降低采样频率
响应延迟使用边缘计算、优化代码

参考资源