第25章:智能家居系统实战
本章将整合前面学到的嵌入式开发、网络通信和云平台知识,从零构建一个可用的智能家居系统。
25.1 项目需求与架构
我们不仅仅是做一个开关灯的 Demo,而是构建一个可扩展的系统架构。
- 功能:
- 环境监控:实时采集客厅温湿度。
- 灯光控制:远程控制 LED 开关,并支持 PWM 调光。
- 人体感应:有人经过自动开灯(自动化场景)。
- 硬件:ESP32 开发板 + DHT11 传感器 + PIR 人体传感器 + LED。
- 软件:
- 设备端:Arduino C++。
- 服务端:Home Assistant (运行在树莓派/PC上) + Mosquitto MQTT Broker。
25.2 设备端开发 (ESP32)
使用 PubSubClient 库连接 MQTT,采用 JSON 格式上报状态。
#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <DHT.h>
// 配置
const char* ssid = "MyWiFi";
const char* password = "password";
const char* mqtt_server = "192.168.1.100";
DHT dht(4, DHT11); // GPIO 4
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
dht.begin();
pinMode(2, OUTPUT); // LED
}
void loop() {
if (!client.connected()) reconnect();
client.loop();
// 每5秒上报一次温湿度
static unsigned long lastMsg = 0;
if (millis() - lastMsg > 5000) {
lastMsg = millis();
float h = dht.readHumidity();
float t = dht.readTemperature();
// 构建 JSON: {"temp": 25.0, "hum": 60.0}
StaticJsonDocument<200> doc;
doc["temp"] = t;
doc["hum"] = h;
char buffer[256];
serializeJson(doc, buffer);
client.publish("home/livingroom/sensor", buffer);
}
}
void callback(char* topic, byte* payload, unsigned int length) {
// 处理控制指令: {"state": "ON"}
StaticJsonDocument<200> doc;
deserializeJson(doc, payload, length);
const char* state = doc["state"];
if (strcmp(state, "ON") == 0) {
digitalWrite(2, HIGH);
} else {
digitalWrite(2, LOW);
}
}25.3 Home Assistant 集成
Home Assistant (HA) 是全球最流行的开源智能家居平台。我们通过配置 configuration.yaml 将 ESP32 接入 HA。
mqtt:
sensor:
- name: "Living Room Temperature"
state_topic: "home/livingroom/sensor"
value_template: "{{ value_json.temp }}"
unit_of_measurement: "°C"
- name: "Living Room Humidity"
state_topic: "home/livingroom/sensor"
value_template: "{{ value_json.hum }}"
unit_of_measurement: "%"
light:
- name: "Living Room Light"
state_topic: "home/livingroom/light/status"
command_topic: "home/livingroom/light/set"
schema: json25.4 自动化规则配置
在 HA 的 Web 界面配置自动化(Automation):
- **Trigger (触发)**:PIR 传感器状态变为
on。 - **Condition (条件)**:当前时间在 18:00 之后(天黑了)。
- **Action (动作)**:调用
light.turn_on服务打开客厅灯。
家庭环境相对温和,而户外环境则充满挑战。下一章我们将构建一个环境监测系统。