跳轉到內容

Home Assistant 完全指南:Docker 部署與智能家居自動化教程(2026版)

Home Assistant 智能家居

Home Assistant 是一款開源的智能家居平臺,能夠統一管理和控制各種智能設備。它支持 2000+ 種設備和平臺,讓您擺脫廠商鎖定,實現真正的智能家居自動化。本教程將帶您從零開始,通過 Docker 部署 Home Assistant,並構建完整的智能家居系統。

目錄

  1. 什麼是 Home Assistant?
  2. 為什麼選擇 Home Assistant?
  3. 系統要求與準備
  4. Docker 部署方案
  5. 初始配置與設置
  6. 設備接入與集成
  7. 自動化配置
  8. Dashboard 定製
  9. 遠程訪問與安全
  10. 高級功能與優化

1. 什麼是 Home Assistant?

1.1 Home Assistant 簡介

Home Assistant(簡稱 HA)是由 Paulus Schoutsen 於 2013 年發起的開源智能家居項目。它的核心理念是:本地優先、隱私保護、開放標準。所有數據處理都在本地完成,不依賴雲端服務,確保您的數據安全和隱私。

核心特點

  • 🏠 本地運行:數據存儲在本地,無需雲端
  • 🔒 隱私保護:您的數據完全屬於您
  • 🔌 廣泛兼容:支持 2000+ 設備和平臺
  • ⚙️ 高度可定製:YAML 配置 + 可視化界面
  • 🤖 強大自動化:基於條件、觸發器和動作
  • 📱 多平臺客戶端:Web、iOS、Android
  • 🆓 完全免費:開源軟件,無訂閱費用
  • 👥 活躍社區:全球開發者貢獻

1.2 架構組成

┌─────────────────────────────────────┐
│         Home Assistant Core         │
│                                     │
│  ┌──────────┬──────────┬─────────┐  │
│  │ Integrations │ Automations │   │  │
│  │ (集成層)  │ (自動化層) │       │  │
│  └──────────┴──────────┴─────────┘  │
│                                     │
│  ┌──────────────────────────────┐   │
│  │      State Machine           │   │
│  │      (狀態機)                │   │
│  └──────────────────────────────┘   │
└─────────────────────────────────────┘
           ↓         ↓         ↓
    ┌────────┐ ┌────────┐ ┌────────┐
    │ Zigbee │ │  WiFi  │ │  BLE   │
    │ 設備   │ │ 設備   │ │ 設備   │
    └────────┘ └────────┘ └────────┘

主要組件

  1. Core(核心)

    • 狀態管理
    • 事件總線
    • 服務調用
  2. Integrations(集成)

    • 設備驅動
    • 平臺適配
    • 協議支持
  3. Automations(自動化)

    • 觸發器(Triggers)
    • 條件(Conditions)
    • 動作(Actions)
  4. Frontend(前端)

    • Lovelace UI
    • Dashboard
    • 移動端 App

1.3 與其他平臺對比

特性Home AssistantSmartThingsApple HomeKitGoogle Home
價格🆓 免費💰 部分付費💰 需要 Apple 設備🆓 免費
本地運行✅ 完全本地⚠️ 依賴雲端✅ 本地⚠️ 依賴雲端
隱私保護⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
設備支持⭐⭐⭐⭐⭐ 2000+⭐⭐⭐ 有限⭐⭐⭐ 有限⭐⭐⭐ 有限
自定義程度⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
自動化能力⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
學習曲線⭐⭐⭐ 中等⭐ 簡單⭐ 簡單⭐ 簡單
開源✅ 是❌ 否❌ 否❌ 否
離線可用✅ 完全支持❌ 不可用✅ 部分支持❌ 不可用

2. 為什麼選擇 Home Assistant?

2.1 核心優勢

優勢一:真正的本地控制

雲端方案的痛點

傳統智能家居:
設備 → 廠商雲端 → 手機 App

問題:
❌ 斷網即癱瘓
❌ 廠商倒閉 = 設備變磚
❌ 隱私數據上傳雲端
❌ 響應延遲高
❌ 持續訂閱費用

Home Assistant 方案

HA 本地方案:
設備 ←→ Home Assistant ←→ 手機 App

優勢:
✅ 斷網仍可控制
✅ 設備永遠可用
✅ 數據完全本地
✅ 毫秒級響應
✅ 一次部署,永久使用

實際案例

某用戶使用了小米智能家居,當小米服務器維護時,整個家裡的智能設備都無法使用,包括基本的燈光控制。

切換到 Home Assistant 後,即使外網斷開,局域網內的所有設備仍然正常工作。

優勢二:打破生態壁壘

傳統困境

小米設備 ↔️ 只能用米家
Philips Hue ↔️ 只能用 Hue App
TP-Link ↔️ 只能用 Kasa
Aqara ↔️ 只能用 Aqara Home

結果:
- 多個 App 切換
- 無法聯動不同品牌
- 體驗割裂

Home Assistant 統一平臺

所有設備 → Home Assistant → 統一控制

支持的協議:
- Zigbee(通過 Zigbee2MQTT / ZHA)
- Z-Wave
- WiFi(MQTT、HTTP API)
- Bluetooth/BLE
- Matter(最新標準)
- 以及 2000+ 集成

實際效果

yaml
# 跨品牌自動化示例
automation:
  - alias: "回家模式"
    trigger:
      - platform: state
        entity_id: binary_sensor.front_door
        to: "on"
    action:
      # 打開小米燈
      - service: light.turn_on
        target:
          entity_id: light.xiaomi_lamp
      # 調整 Philips Hue 色溫
      - service: light.turn_on
        target:
          entity_id: light.hue_living_room
        data:
          color_temp: 300
      # 播放 Spotify
      - service: media_player.play_media
        target:
          entity_id: media_player.spotify
        data:
          media_content_id: "spotify:playlist:xxx"

優勢三:強大的自動化引擎

基礎自動化

yaml
# 簡單示例:天黑開燈
automation:
  - alias: "天黑自動開燈"
    trigger:
      - platform: sun
        event: sunset
    action:
      - service: light.turn_on
        target:
          entity_id: light.living_room

高級自動化

yaml
# 複雜示例:智能照明系統
automation:
  - alias: "智能照明"
    trigger:
      # 有人移動
      - platform: state
        entity_id: binary_sensor.motion_sensor
        to: "on"
      
      # 或手動開關
      - platform: state
        entity_id: input_boolean.guest_mode
        to: "on"
    
    condition:
      # 且在天黑後
      - condition: sun
        after: sunset
      
      # 且在工作日
      - condition: time
        weekday:
          - mon
          - tue
          - wed
          - thu
          - fri
      
      # 且亮度低於閾值
      - condition: numeric_state
        entity_id: sensor.light_level
        below: 100
    
    action:
      # 根據時間調整亮度和色溫
      - choose:
          # 晚上 6-9 點:明亮暖光
          - conditions:
              - condition: time
                after: "18:00"
                before: "21:00"
            sequence:
              - service: light.turn_on
                target:
                  entity_id: light.living_room
                data:
                  brightness_pct: 80
                  color_temp: 2700
          
          # 晚上 9-11 點:柔和暖光
          - conditions:
              - condition: time
                after: "21:00"
                before: "23:00"
            sequence:
              - service: light.turn_on
                target:
                  entity_id: light.living_room
                data:
                  brightness_pct: 50
                  color_temp: 2200
          
          # 深夜:微光
          - conditions:
              - condition: time
                after: "23:00"
            sequence:
              - service: light.turn_on
                target:
                  entity_id: light.hallway
                data:
                  brightness_pct: 10
                  color_temp: 2000
        
        # 默認:關閉
        default:
          - service: light.turn_off
            target:
              entity_id: all

優勢四:豐富的生態系統

官方集成(內置):

  • 主流品牌:Philips Hue、TP-Link、Sonos、Ring 等
  • 雲服務:Google、Amazon、Apple、Microsoft
  • 協議:MQTT、Zigbee、Z-Wave、Bluetooth
  • 平臺:HomeKit、Alexa、Google Assistant

社區插件(HACS):

  • Xiaomi Miio(小米設備)
  • Tuya(塗鴉智能)
  • IKEA Tradfri
  • Aqara
  • 以及數百個其他集成

硬件支持

控制器:
- Raspberry Pi(最流行)
- Intel NUC
- 舊電腦/筆記本
- NAS(Synology、QNAP)
- Docker(任何支持 Docker 的設備)

無線電適配器:
- Zigbee:CC2531、ConBee II、Sonoff Zigbee Dongle
- Z-Wave:Aeotec Gen5、Zooz ZST10
- Bluetooth:內置或 USB 適配器

2.2 適用場景

場景 1:全屋智能照明

yaml
# 自動化示例
automation:
  # 日出漸亮
  - alias: "日出喚醒"
    trigger:
      - platform: time
        at: "06:30"
    action:
      - service: light.turn_on
        target:
          entity_id: light.bedroom
        data:
          transition: 1800  # 30 分鐘漸變
          brightness_pct: 100
          color_temp: 4000
  
  # 離家關燈
  - alias: "離家關閉所有燈"
    trigger:
      - platform: state
        entity_id: device_tracker.phone_user1
        from: "home"
        to: "not_home"
    action:
      - service: homeassistant.turn_off
        target:
          entity_id: group.all_lights

場景 2:智能溫控

yaml
# 溫度自動化
automation:
  # 冬季取暖
  - alias: "冬季取暖"
    trigger:
      - platform: numeric_state
        entity_id: sensor.living_room_temperature
        below: 20
    condition:
      - condition: state
        entity_id: input_boolean.winter_mode
        state: "on"
    action:
      - service: climate.set_temperature
        target:
          entity_id: climate.thermostat
        data:
          temperature: 22
  
  # 夏季製冷
  - alias: "夏季製冷"
    trigger:
      - platform: numeric_state
        entity_id: sensor.living_room_temperature
        above: 28
    condition:
      - condition: state
        entity_id: input_boolean.summer_mode
        state: "on"
    action:
      - service: climate.set_temperature
        target:
          entity_id: climate.ac
        data:
          temperature: 24

場景 3:安防監控

yaml
# 安防自動化
automation:
  # 佈防模式
  - alias: "離家佈防"
    trigger:
      - platform: state
        entity_id: alarm_control_panel.home_alarm
        to: "armed_away"
    action:
      # 開啟攝像頭錄製
      - service: camera.record
        target:
          entity_id: camera.front_door
        data:
          duration: 300
          lookback: 10
      
      # 啟用運動檢測通知
      - service: notify.mobile_app
        data:
          message: "安防系統已佈防"
  
  # 檢測到入侵
  - alias: "入侵警報"
    trigger:
      - platform: state
        entity_id: binary_sensor.motion_outside
        to: "on"
    condition:
      - condition: state
        entity_id: alarm_control_panel.home_alarm
        state: "armed_away"
    action:
      # 發送通知
      - service: notify.mobile_app
        data:
          message: "⚠️ 檢測到運動!"
          data:
            attachment:
              url: "{{ states.camera.front_door.attributes.entity_picture }}"
      
      # 開啟所有燈
      - service: light.turn_on
        target:
          entity_id: group.outside_lights
      
      # 播放警報聲
      - service: media_player.play_media
        target:
          entity_id: media_player.speaker
        data:
          media_content_id: "/local/alarm.mp3"

場景 4:能源管理

yaml
# 能源監控
sensor:
  - platform: integration
    source: sensor.power_consumption
    name: energy_total
    unit_prefix: k
    round: 2

automation:
  # 高耗電提醒
  - alias: "高耗電提醒"
    trigger:
      - platform: numeric_state
        entity_id: sensor.current_power
        above: 3000  # 3kW
    action:
      - service: notify.mobile_app
        data:
          message: "⚡ 當前功耗過高:{{ states('sensor.current_power') }}W"
  
  # 太陽能優化
  - alias: "太陽能充電優化"
    trigger:
      - platform: numeric_state
        entity_id: sensor.solar_production
        above: 2000
    action:
      # 啟動洗衣機
      - service: switch.turn_on
        target:
          entity_id: switch.washing_machine
      
      # 給電動車充電
      - service: switch.turn_on
        target:
          entity_id: switch.ev_charger

3. 系統要求與準備

3.1 硬件要求

最低配置

CPU: ARM Cortex-A53 1GHz 或 x86 1GHz
RAM: 1GB
存儲: 8GB(建議 16GB+)
網絡: 以太網或 WiFi

推薦配置

CPU: Quad-core 1.5GHz+
RAM: 2-4GB
存儲: 32GB SSD
網絡: 千兆以太網

常用硬件平臺

Raspberry Pi(最流行)

Raspberry Pi 4 Model B

優點:
✅ 功耗低(5-10W)
✅ 體積小
✅ 社區支持好
✅ 價格便宜($35-75)

缺點:
⚠️ SD 卡易損壞
⚠️ 性能有限

建議配置:
- RAM: 4GB 或 8GB
- 存儲: 高質量 microSD 卡(Samsung EVO Plus)
- 電源: 官方電源適配器
- 散熱: 散熱片或風扇外殼

Raspberry Pi 5(2024 新款):

性能提升 2-3 倍
適合大型部署
價格稍高

Intel NUC / Mini PC

優點

✅ 性能強大
✅ 可擴展性好
✅ 更穩定
✅ 可以運行其他服務

推薦型號

入門:Intel NUC i3 / Celeron J4125
中端:Intel NUC i5
高端:Intel NUC i7

二手選擇:
- Dell OptiPlex Micro
- HP ProDesk Mini
- Lenovo ThinkCentre Tiny

NAS

Synology / QNAP

優點:
✅ 已有設備,無需額外購買
✅ 存儲空間大
✅ 可以同時運行其他服務

缺點:
⚠️ 性能可能不足
⚠️ 配置較複雜

3.2 軟件準備

必需軟件

1. Docker 和 Docker Compose
2. 文本編輯器(VS Code 推薦)
3. SSH 客戶端(用於遠程管理)
4. 瀏覽器(Chrome/Firefox)

可選軟件

- MQTT Broker(Mosquitto)
- Database(MariaDB/PostgreSQL)
- Zigbee2MQTT
- Node-RED(可視化自動化)

3.3 網絡規劃

IP 地址分配

建議為 HA 分配靜態 IP:

路由器設置:
- DHCP Reservation(DHCP 保留)
- 或 Static IP(靜態 IP)

示例:
Home Assistant: 192.168.1.100
Zigbee Gateway: 192.168.1.101
MQTT Broker: 192.168.1.102

端口需求

Home Assistant: 8123 (TCP)
MQTT: 1883 (TCP), 8883 (TLS)
Zigbee2MQTT: 8080 (Web UI)
Node-RED: 1880 (Web UI)

防火牆規則

bash
# 如果使用防火牆,開放必要端口
sudo ufw allow 8123/tcp
sudo ufw allow 1883/tcp
sudo ufw allow 8080/tcp

4. Docker 部署方案

使用 Docker 部署是最靈活和推薦的方式。

4.1 安裝 Docker

Ubuntu/Debian

bash
# 卸載舊版本
sudo apt remove docker docker-engine docker.io containerd runc

# 安裝依賴
sudo apt update
sudo apt install \
    apt-transport-https \
    ca-certificates \
    curl \
    gnupg \
    lsb-release

# 添加 GPG 密鑰
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

# 添加倉庫
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \
  $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

# 安裝 Docker
sudo apt update
sudo apt install docker-ce docker-ce-cli containerd.io

# 驗證安裝
docker --version
docker compose version

CentOS/RHEL

bash
# 添加倉庫
sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo

# 安裝
sudo yum install docker-ce docker-ce-cli containerd.io

# 啟動並開機自啟
sudo systemctl start docker
sudo systemctl enable docker

macOS

bash
# 安裝 Docker Desktop
brew install --cask docker

# 啟動 Docker Desktop
open /Applications/Docker.app

Windows

下載 Docker Desktop for Windows
https://www.docker.com/products/docker-desktop

安裝並啟動

4.2 創建目錄結構

bash
# 創建項目目錄
mkdir -p ~/homeassistant/{config,data}
cd ~/homeassistant

# 目錄說明:
# config/ - Home Assistant 配置文件
# data/ - 數據庫和其他數據

4.3 Docker Compose 配置

創建 docker-compose.yml

yaml
version: '3.8'

services:
  homeassistant:
    container_name: homeassistant
    image: ghcr.io/home-assistant/home-assistant:stable
    volumes:
      - ./config:/config
      - /etc/localtime:/etc/localtime:ro
      - /run/dbus:/run/dbus:ro
    environment:
      - TZ=Asia/Shanghai
    network_mode: host
    restart: unless-stopped
    privileged: true
    devices:
      - /dev/ttyACM0:/dev/ttyACM0  # Zigbee dongle(如果有)
  
  # MQTT Broker(可選但推薦)
  mosquitto:
    container_name: mosquitto
    image: eclipse-mosquitto:latest
    ports:
      - "1883:1883"
      - "8883:8883"
    volumes:
      - ./mosquitto/config:/mosquitto/config
      - ./mosquitto/data:/mosquitto/data
      - ./mosquitto/log:/mosquitto/log
    restart: unless-stopped
  
  # Zigbee2MQTT(如果使用 Zigbee)
  zigbee2mqtt:
    container_name: zigbee2mqtt
    image: koenkk/zigbee2mqtt:latest
    volumes:
      - ./zigbee2mqtt:/app/data
      - /run/udev:/run/udev:ro
    devices:
      - /dev/ttyACM0:/dev/ttyACM0  # Zigbee dongle
    environment:
      - TZ=Asia/Shanghai
    restart: unless-stopped
    depends_on:
      - mosquitto

  # Node-RED(可選,可視化自動化)
  nodered:
    container_name: nodered
    image: nodered/node-red:latest
    ports:
      - "1880:1880"
    volumes:
      - ./nodered:/data
    environment:
      - TZ=Asia/Shanghai
    restart: unless-stopped

4.4 MQTT 配置

創建 Mosquitto 配置文件:

bash
mkdir -p mosquitto/config
nano mosquitto/config/mosquitto.conf

添加內容:

conf
# 監聽端口
listener 1883

# 允許匿名訪問(內網安全環境下)
allow_anonymous true

# 持久化
persistence true
persistence_location /mosquitto/data/

# 日誌
log_dest file /mosquitto/log/mosquitto.log

4.5 Zigbee2MQTT 配置

如果使用 Zigbee 設備:

bash
mkdir -p zigbee2mqtt
nano zigbee2mqtt/configuration.yaml

添加內容:

yaml
# Zigbee2MQTT 配置
homeassistant: true
permit_join: false  # 首次設置為 true 以配對設備

mqtt:
  base_topic: zigbee2mqtt
  server: 'mqtt://mosquitto:1883'

serial:
  port: /dev/ttyACM0  # Zigbee dongle 路徑
  adapter: zstack  # 或 deconz, ezsp

advanced:
  log_level: info
  channel: 15
  pan_id: 0x1a62
  ext_pan_id: [0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD]
  network_key: [1, 3, 5, 7, 9, 11, 13, 15, 0, 2, 4, 6, 8, 10, 12, 13]

frontend:
  port: 8080

4.6 啟動服務

bash
# 啟動所有服務
docker compose up -d

# 查看日誌
docker compose logs -f homeassistant

# 查看運行狀態
docker ps

期望輸出:

CONTAINER ID   IMAGE                                STATUS
xxx            home-assistant/home-assistant:stable Up 2 minutes
xxx            eclipse-mosquitto:latest             Up 2 minutes
xxx            koenkk/zigbee2mqtt:latest            Up 2 minutes

4.7 訪問 Home Assistant

首次訪問

瀏覽器打開:http://your-server-ip:8123

例如:http://192.168.1.100:8123

看到歡迎頁面

🎉 Welcome to Home Assistant!

繼續設置...

5. 初始配置與設置

5.1 創建管理員賬戶

步驟:
1. 輸入用戶名
2. 輸入密碼(強密碼)
3. 點擊 "Create Account"

5.2 設置家庭信息

Location(位置):
- 搜索或輸入地址
- 自動獲取經緯度
- 設置時區:Asia/Shanghai

Unit System(單位):
- Metric(公制):°C, km
- Imperial(英制):°F, miles

Currency(貨幣):
- CNY(人民幣)
- USD(美元)

Privacy:
- 可以選擇分享匿名統計數據(幫助改進 HA)

5.3 發現設備

Home Assistant 會自動掃描網絡中的設備:

自動發現的設備類型:
- Chromecast
- Sonos
- Philips Hue Bridge
- UPnP 設備
- mDNS 設備
- ...

操作:
- 點擊 "Configure" 配置每個設備
- 或點擊 "Skip" 稍後配置

5.4 基本設置

進入 Settings → System:

General(常規)

yaml
# configuration.yaml 示例
homeassistant:
  name: My Home
  latitude: 39.9042
  longitude: 116.4074
  elevation: 50
  unit_system: metric
  currency: CNY
  time_zone: Asia/Shanghai

Person(人員)

添加家庭成員:
1. Settings → People
2. Add Person
3. 輸入姓名
4. 關聯用戶賬戶
5. 設置追蹤設備(手機)

Areas(區域)

創建房間/區域:
1. Settings → Areas
2. Add Area
3. 命名(如:客廳、臥室、廚房)
4. 添加樓層(可選)
5. 分配設備到區域

推薦區域劃分:

一樓:
- 客廳(Living Room)
- 餐廳(Dining Room)
- 廚房(Kitchen)
- 衛生間(Bathroom)

二樓:
- 主臥(Master Bedroom)
- 次臥(Bedroom 2)
- 書房(Office)

室外:
- 花園(Garden)
- 車庫(Garage)
- 前門(Front Door)

5.5 備份配置

手動備份

Settings → System → Backups
→ Create Backup
→ 下載到本地

自動備份

yaml
# 使用 Shell Command 定時備份
shell_command:
  backup_config: >
    tar czf /config/backups/backup_$(date +%Y%m%d_%H%M%S).tar.gz /config

automation:
  - alias: "每日備份"
    trigger:
      - platform: time
        at: "03:00:00"
    action:
      - service: shell_command.backup_config

6. 設備接入與集成

6.1 集成方式概述

三種主要方式

  1. 官方集成(Built-in)

    • 在 Settings → Devices & Services 中添加
    • 支持主流品牌和協議
  2. HACS 社區集成

    • 需要先安裝 HACS
    • 支持更多設備和平臺
  3. 手動配置(YAML)

    • 編輯 configuration.yaml
    • 最靈活,但需要技術知識

6.2 安裝 HACS

HACS(Home Assistant Community Store)是社區插件商店。

安裝步驟

bash
# 方法 1:一鍵腳本
wget -O - https://get.hacs.xyz | bash -

# 方法 2:手動安裝
cd ~/homeassistant/config
mkdir custom_components
cd custom_components
wget https://github.com/hacs/integration/releases/latest/download/hacs.zip
unzip hacs.zip
rm hacs.zip

重啟 Home Assistant

Settings → System → Restart
或使用命令:
docker restart homeassistant

配置 HACS

1. 刷新瀏覽器
2. 左側出現 HACS 菜單
3. 點擊 Configure
4. 登錄 GitHub 賬號
5. 完成設置

6.3 常見設備接入

WiFi 設備

TP-Link Kasa

Settings → Devices & Services
→ Add Integration
→ 搜索 "TP-Link"
→ 輸入設備 IP 或自動發現

Xiaomi Miio(通過 HACS):

HACS → Integrations
→ 搜索 "Xiaomi Miio"
→ Install
→ 重啟 HA
→ 配置集成(需要 Token)

獲取 Token 方法:

bash
# 使用 miio 工具
pip install python-miio
miio token --ip 192.168.1.xxx

Zigbee 設備

使用 Zigbee2MQTT

  1. 允許配對
yaml
# zigbee2mqtt/configuration.yaml
permit_join: true
  1. 重啟 Zigbee2MQTT
bash
docker restart zigbee2mqtt
  1. 配對設備
按照設備說明書進入配對模式
通常是長按按鈕 5-10 秒
  1. 查看配對結果
訪問 Zigbee2MQTT Web UI: http://your-ip:8080
看到新設備即成功
  1. 禁用配對
yaml
permit_join: false

在 HA 中使用

設備會自動出現在 HA 中
可以在 Settings → Devices 查看

Bluetooth 設備

小米溫溼度傳感器

yaml
# configuration.yaml
sensor:
  - platform: mitemp_bt
    mac: 'AA:BB:CC:DD:EE:FF'
    name: "Living Room Sensor"
    force_update: false
    median: 3
    decimals: 1
    monitored_conditions:
      - temperature
      - humidity
      - battery

6.4 MQTT 設備

通用 MQTT 設備

yaml
# configuration.yaml
mqtt:
  sensor:
    - name: "Temperature"
      state_topic: "home/living_room/temperature"
      unit_of_measurement: "°C"
      value_template: "{{ value_json.temperature }}"
  
  switch:
    - name: "Smart Plug"
      command_topic: "home/plug/set"
      state_topic: "home/plug/state"
      payload_on: "ON"
      payload_off: "OFF"

發佈測試消息

bash
# 使用 mosquitto_pub
docker exec mosquitto mosquitto_pub \
  -t "home/living_room/temperature" \
  -m '{"temperature": 25.5}'

6.5 ESPHome 設備

ESPHome 用於 DIY ESP32/ESP8266 設備。

安裝 ESPHome(HACS):

HACS → Integrations
→ 搜索 "ESPHome"
→ Install

創建配置

yaml
# living_room_light.yaml
esphome:
  name: living-room-light

esp32:
  board: esp32dev

wifi:
  ssid: "YourWiFi"
  password: "YourPassword"

api:

ota:

light:
  - platform: neopixelbus
    type: GRB
    variant: WS2812
    pin: GPIO2
    num_leds: 30
    name: "LED Strip"
    effects:
      - random:
      - pulse:
      - strobe:

編譯和上傳

ESPHome Dashboard
→ New Device
→ 編輯配置
→ Validate
→ Install
→ 選擇上傳方式(OTA 或 USB)

7. 自動化配置

7.1 自動化基礎

三個核心要素

yaml
automation:
  - alias: "自動化名稱"
    
    # 觸發器:什麼情況下執行
    trigger:
      - platform: state
        entity_id: binary_sensor.motion
        to: "on"
    
    # 條件:滿足什麼條件才執行(可選)
    condition:
      - condition: time
        after: "18:00"
        before: "23:00"
    
    # 動作:執行什麼操作
    action:
      - service: light.turn_on
        target:
          entity_id: light.living_room

7.2 觸發器類型

狀態觸發

yaml
trigger:
  - platform: state
    entity_id: light.living_room
    from: "off"
    to: "on"

時間觸發

yaml
trigger:
  - platform: time
    at: "07:00:00"
  
  - platform: time_pattern
    minutes: "/15"  # 每 15 分鐘

太陽觸發

yaml
trigger:
  - platform: sun
    event: sunrise
    offset: "-00:30:00"  # 日出前 30 分鐘
  
  - platform: sun
    event: sunset
    offset: "+01:00:00"  # 日落後 1 小時

數值觸發

yaml
trigger:
  - platform: numeric_state
    entity_id: sensor.temperature
    above: 30
  
  - platform: numeric_state
    entity_id: sensor.humidity
    below: 40
    above: 60

地理圍欄觸發

yaml
trigger:
  - platform: zone
    entity_id: device_tracker.phone
    zone: zone.home
    event: enter  # 或 leave

Webhook 觸發

yaml
trigger:
  - platform: webhook
    webhook_id: my_webhook_id

7.3 條件類型

狀態條件

yaml
condition:
  - condition: state
    entity_id: input_boolean.vacation_mode
    state: "off"

時間條件

yaml
condition:
  - condition: time
    weekday:
      - mon
      - tue
      - wed
      - thu
      - fri
    after: "09:00"
    before: "17:00"

數值條件

yaml
condition:
  - condition: numeric_state
    entity_id: sensor.brightness
    below: 100

模板條件

yaml
condition:
  - condition: template
    value_template: >
      {{ states('sensor.temperature') | float > 25 }}

AND/OR 條件

yaml
condition:
  - condition: and
    conditions:
      - condition: state
        entity_id: input_boolean.night_mode
        state: "on"
      - condition: numeric_state
        entity_id: sensor.temperature
        below: 20
  
  - condition: or
    conditions:
      - condition: state
        entity_id: person.john
        state: "home"
      - condition: state
        entity_id: person.jane
        state: "home"

7.4 動作類型

調用服務

yaml
action:
  - service: light.turn_on
    target:
      entity_id: light.living_room
    data:
      brightness_pct: 80
      color_temp: 3000

延遲

yaml
action:
  - delay: "00:05:00"  # 等待 5 分鐘

等待觸發

yaml
action:
  - wait_for_trigger:
      - platform: state
        entity_id: binary_sensor.door
        to: "off"
    timeout: "00:10:00"  # 最多等待 10 分鐘

條件分支

yaml
action:
  - choose:
      - conditions:
          - condition: state
            entity_id: input_boolean.movie_mode
            state: "on"
        sequence:
          - service: light.turn_off
            target:
              entity_id: all
      
      - conditions:
          - condition: state
            entity_id: input_boolean.reading_mode
            state: "on"
        sequence:
          - service: light.turn_on
            target:
              entity_id: light.reading_lamp
            data:
              brightness_pct: 100
    
    default:
      - service: light.turn_on
        target:
          entity_id: light.living_room

發送通知

yaml
action:
  - service: notify.mobile_app_john_phone
    data:
      title: "Home Alert"
      message: "Motion detected at front door"
      data:
        push:
          sound: "default"
        attachment:
          url: "{{ states.camera.front_door.attributes.entity_picture }}"

7.5 實用自動化示例

示例 1:智能夜燈

yaml
automation:
  - alias: "智能夜燈"
    trigger:
      - platform: state
        entity_id: binary_sensor.bedroom_motion
        to: "on"
    
    condition:
      - condition: state
        entity_id: sun.sun
        state: "below_horizon"
      - condition: time
        after: "22:00"
        before: "06:00"
    
    action:
      - service: light.turn_on
        target:
          entity_id: light.bedroom_nightlight
        data:
          brightness_pct: 10
          kelvin: 2000
      
      # 2 分鐘後自動關閉
      - delay: "00:02:00"
      
      - service: light.turn_off
        target:
          entity_id: light.bedroom_nightlight

示例 2:天氣提醒

yaml
automation:
  - alias: "雨天提醒"
    trigger:
      - platform: time
        at: "07:00:00"
    
    condition:
      - condition: state
        entity_id: weather.home
        state: "rainy"
    
    action:
      - service: notify.mobile_app
        data:
          title: "☔ 天氣提醒"
          message: "今天有雨,記得帶傘!"
      
      # 如果開車,提醒帶傘到車上
      - condition: state
        entity_id: device_tracker.car
        state: "home"
      - service: notify.mobile_app
        data:
          message: "車在家裡,可以把傘放車上"

示例 3:節能模式

yaml
automation:
  - alias: "無人節能模式"
    trigger:
      - platform: state
        entity_id: zone.home
        to: "0"  # 家中無人
        for: "00:15:00"  # 持續 15 分鐘
    
    action:
      # 關閉所有燈
      - service: homeassistant.turn_off
        target:
          entity_id: group.all_lights
      
      # 調整空調
      - service: climate.set_temperature
        target:
          entity_id: climate.thermostat
        data:
          temperature: 26  # 節能溫度
      
      # 關閉非必要電器
      - service: switch.turn_off
        target:
          entity_id: 
            - switch.tv
            - switch.gaming_console
            - switch.sound_system
      
      # 發送通知
      - service: notify.mobile_app
        data:
          message: "🏠 已啟動節能模式"

8. Dashboard 定製

8.1 Lovelace UI 基礎

Home Assistant 使用 Lovelace UI,可以通過 YAML 或可視化編輯器定製。

訪問 Dashboard

主頁即為 Dashboard
點擊右上角三個點 → Edit Dashboard

8.2 視圖和卡片

創建新視圖

Edit Dashboard
→ Add View
→ 選擇類型:
  - Panel(單列)
  - Grid(網格,推薦)
  - Masonry(瀑布流)

常用卡片類型

Entities Card(實體卡片)

yaml
type: entities
title: 客廳設備
entities:
  - entity: light.living_room
    name: 主燈
  - entity: switch.fan
    name: 風扇
  - entity: sensor.temperature
    name: 溫度
  - entity: sensor.humidity
    name: 溼度

Button Card(按鈕卡片)

yaml
type: button
entity: light.living_room
name: 客廳燈
icon: mdi:lightbulb
show_state: true
tap_action:
  action: toggle
hold_action:
  action: more-info

Picture Elements Card(圖片元素)

yaml
type: picture-elements
image: /local/floor_plan.png
elements:
  - type: state-icon
    entity: light.living_room
    style:
      top: 50%
      left: 50%
  - type: state-label
    entity: sensor.temperature
    style:
      top: 20%
      left: 20%

Gauge Card(儀表盤)

yaml
type: gauge
entity: sensor.temperature
min: 0
max: 40
severity:
  green: 0
  yellow: 25
  red: 30

History Graph Card(歷史圖表)

yaml
type: history-graph
title: 溫度趨勢
entities:
  - entity: sensor.living_room_temp
    name: 客廳
  - entity: sensor.bedroom_temp
    name: 臥室
hours_to_show: 24

8.3 主題定製

安裝主題(通過 HACS):

HACS → Frontend
→ 搜索主題(如 "Material Dark Theme")
→ Install
→ 重啟 HA
→ Profile → 選擇主題

自定義主題

yaml
# themes/custom.yaml
my_theme:
  primary-color: "#03a9f4"
  accent-color: "#ff5722"
  background-color: "#ffffff"
  card-background-color: "#fafafa"

9. 遠程訪問與安全

9.1 遠程訪問方案

方案 1:Cloudflare Tunnel(推薦)

參見本站教程:Cloudflare Tunnel 完全指南

優點

  • ✅ 免費
  • ✅ 安全
  • ✅ 無需端口轉發
  • ✅ 自動 HTTPS

方案 2:Home Assistant Cloud(Nabu Casa)

付費服務:$6.5/月
優點:
- 一鍵配置
- 支持 Alexa/Google Assistant
- 資助 HA 開發

方案 3:VPN

WireGuard / OpenVPN
優點:
- 最安全
- 完全控制
缺點:
- 配置複雜
- 需要在客戶端安裝 VPN

9.2 安全加固

1. 強密碼

Settings → People
→ 為用戶設置強密碼
→ 啟用兩步驗證(2FA)

2. 限制登錄嘗試

yaml
# configuration.yaml
http:
  ip_ban_enabled: true
  login_attempts_threshold: 5

3. 使用 HTTPS

始終通過 HTTPS 訪問
Cloudflare Tunnel 自動提供

4. 定期更新

bash
# 更新 Home Assistant
docker pull ghcr.io/home-assistant/home-assistant:stable
docker compose down
docker compose up -d

5. 備份配置

定期備份 configuration.yaml 和整個 config 目錄

10. 高級功能與優化

10.1 數據庫優化

使用 MariaDB

yaml
# docker-compose.yml 添加
services:
  mariadb:
    image: mariadb:10.11
    environment:
      MYSQL_ROOT_PASSWORD: secret
      MYSQL_DATABASE: homeassistant
      MYSQL_USER: hass
      MYSQL_PASSWORD: secret
    volumes:
      - ./mariadb:/var/lib/mysql
    restart: unless-stopped

  homeassistant:
    depends_on:
      - mariadb
yaml
# configuration.yaml
recorder:
  db_url: mysql://hass:secret@mariadb/homeassistant
  purge_keep_days: 30
  commit_interval: 30

10.2 性能優化

排除不必要的實體

yaml
recorder:
  exclude:
    entities:
      - sensor.time
      - sensor.date
    domains:
      - updater
      - persistent_notification

減少歷史記錄

yaml
history:
  exclude:
    domains:
      - camera

10.3 監控和維護

系統監控

yaml
# 添加系統傳感器
sensor:
  - platform: systemmonitor
    resources:
      - type: disk_use_percent
        arg: /
      - type: memory_use_percent
      - type: processor_use
      - type: last_boot

健康檢查

yaml
binary_sensor:
  - platform: ping
    host: 8.8.8.8
    name: Internet Connection
    count: 2
    scan_interval: 60

常見問題解答

Q1: Home Assistant 需要什麼配置?

A:

  • 最低:Raspberry Pi 3,1GB RAM
  • 推薦:Raspberry Pi 4,4GB RAM
  • 更好:Intel NUC 或 Mini PC

Q2: 如何備份和恢復?

A:

bash
# 備份
tar czf ha-backup.tar.gz ~/homeassistant/config/

# 恢復
tar xzf ha-backup.tar.gz -C ~/homeassistant/
docker restart homeassistant

Q3: 支持哪些智能設備?

A: 2000+ 設備和平臺,包括:

  • Philips Hue
  • Xiaomi/Aqara
  • TP-Link
  • IKEA
  • Sonos
  • Ring
  • Nest
  • 以及通過 Zigbee、Z-Wave、MQTT 的無數設備

Q4: 可以離線使用嗎?

A: 是的!Home Assistant 完全本地運行,斷網仍可控制所有本地設備。

Q5: 學習難度大嗎?

A:

  • 基礎使用:簡單,可視化界面
  • 高級自動化:需要學習 YAML
  • 社區資源豐富,文檔完善

Q6: 如何更新?

A:

bash
docker pull ghcr.io/home-assistant/home-assistant:stable
docker compose down
docker compose up -d

Q7: 可以和 Alexa/Google 集成嗎?

A: 是的,通過 Home Assistant Cloud 或手動配置。

Q8: 數據安全嗎?

A: 非常安全:

  • 數據本地存儲
  • 可選端到端加密
  • 開源代碼可審計
  • 定期安全更新

總結

Home Assistant 是構建智能家居的最佳選擇,它提供:

🎯 核心價值

  1. 完全控制:本地運行,數據私有
  2. 無限可能:2000+ 集成,高度可定製
  3. 強大自動化:複雜的場景輕鬆實現
  4. 開放生態:不被廠商鎖定
  5. 成本效益:免費軟件,可使用舊硬件

💡 入門建議

  1. 從小開始:先接入 1-2 個設備
  2. 逐步擴展:根據需要添加功能
  3. 善用社區:論壇和 Discord 很活躍
  4. 定期備份:保護配置和數據
  5. 保持更新:獲取新功能和修復

📚 延伸閱讀

💬 獲取幫助

  • 📖 官方文檔:home-assistant.io/docs
  • 💬 社區論壇:community.home-assistant.io
  • 💬 Discord:discord.gg/c5DvZ4e
  • 🎥 YouTube:大量視頻教程
  • 💡 本站交流:歡迎在評論區分享經驗

🏠 開始構建您的智能家居,享受科技帶來的便利!

💡 提示:收藏本頁面以備將來參考。如果您覺得本教程有幫助,歡迎分享給更多朋友!

最後更新於: