使用 HomeKit 與 MatterSupport 控制智慧家庭配件並配網 Matter 裝置。適用於管理家庭/房間/配件、建立動作集(Action Sets)或觸發器(Triggers)、讀取配件特性(Characteristics)、引導 Matter 裝置配網設定,或是開發第三方智慧家庭生態系統 App。
HomeKit
控制家庭自動化配件並配網 Matter 裝置。HomeKit 負責管理家庭/房間/配件模型、動作集與觸發器;MatterSupport 則負責將 Matter 裝置配網納入您的生態系統中。
目錄
- 設定
- HomeKit 資料模型
- 管理配件
- 讀取與寫入特性
- 動作集與觸發器
- Matter 裝置配網
- MatterAddDeviceExtensionRequestHandler
- 常見錯誤
- 審查檢核表
- 參考資料
設定
HomeKit 配置
- 在 Xcode 的 Signing & Capabilities 中啟用 HomeKit Capability
- 在 Info.plist 中新增
NSHomeKitUsageDescription:
<key>NSHomeKitUsageDescription</key>
<string>This app controls your smart home accessories.</string>
MatterSupport 配置
若要將 Matter 裝置配網納入您自己的生態系統:
- 新增 MatterSupport Extension Target,並將其 Principal Class 設定為
MatterAddDeviceExtensionRequestHandler的子類別 - 為
_matter._tcp、_matterc._udp及_matterd._udp新增NSBonjourServices項目 - 僅在呼叫端以程式碼方式提供 Matter 設定 Payload 時,才新增
com.apple.developer.matter.allow-setup-payload
Framework 邊界
| 需求 | Framework |
|---|---|
| 家庭、房間、配件、特性、動作、觸發器 | HomeKit |
| 將 Matter 裝置配網納入 App 生態系統 | MatterSupport |
| 選擇並授權附近的藍牙或 Wi-Fi 配件 | AccessorySetupKit |
| 選擇配件後交換藍牙 GATT 資料 | CoreBluetooth |
| 選擇配件後加入或配置配件的 Wi-Fi 網路 | NetworkExtension |
HomeKit 資料模型
HomeKit 以階層方式組織家庭自動化:
HMHomeManager
-> HMHome (一個或多個)
-> HMRoom (家庭中的房間)
-> HMAccessory (房間內的裝置)
-> HMService (功能:燈光、恆溫器等)
-> HMCharacteristic (可讀取/寫入的數值)
-> HMZone (房間群組)
-> HMActionSet (群組化的動作)
-> HMTrigger (基於時間或事件的觸發器)
初始化 Home Manager
建立單一 HMHomeManager 實例,並實作其 Delegate 以獲知資料何時載入完成。HomeKit 為非同步載入——在 Delegate 觸發前請勿存取 homes。
import HomeKit
final class HomeStore: NSObject, HMHomeManagerDelegate {
let homeManager = HMHomeManager()
override init() {
super.init()
homeManager.delegate = self
}
func homeManagerDidUpdateHomes(_ manager: HMHomeManager) {
// 現在可以安全地存取 manager.homes
let homes = manager.homes
let primaryHome = manager.primaryHome
print("Loaded \(homes.count) homes")
}
func homeManager(
_ manager: HMHomeManager,
didUpdate status: HMHomeManagerAuthorizationStatus
) {
if status.contains(.authorized) {
print("HomeKit access granted")
}
}
}
存取房間
guard let home = homeManager.primaryHome else { return }
let rooms = home.rooms
let kitchen = rooms.first { $0.name == "Kitchen" }
// 取得未指派給特定房間的配件所屬之預設房間
let defaultRoom = home.roomForEntireHome()
管理配件
尋找與新增配件
在新增配件之前,請先參考 Framework 邊界 表格;本 Skill 僅包含 HomeKit/MatterSupport 相關作業。
// 用於配件尋找的系統 UI
home.addAndSetupAccessories { error in
if let error {
print("Setup failed: \(error)")
}
}
列出配件與服務
for accessory in home.accessories {
print("\(accessory.name) in \(accessory.room?.name ?? "unassigned")")
for service in accessory.services {
print(" Service: \(service.serviceType)")
for characteristic in service.characteristics {
print(" \(characteristic.characteristicType): \(characteristic.value ?? "nil")")
}
}
}
將配件移動至另一個房間
guard let accessory = home.accessories.first,
let bedroom = home.rooms.first(where: { $0.name == "Bedroom" }) else { return }
home.assignAccessory(accessory, to: bedroom) { error in
if let error {
print("Failed to move accessory: \(error)")
}
}
讀取與寫入特性
讀取數值
let characteristic: HMCharacteristic = // 從服務中取得
characteristic.readValue { error in
guard error == nil else { return }
if let value = characteristic.value as? Bool {
print("Power state: \(value)")
}
}
寫入數值
// 開燈
characteristic.writeValue(true) { error in
if let error {
print("Write failed: \(error)")
}
}
訂閱變更通知
啟用即時更新的通知功能:
characteristic.enableNotification(true) { error in
guard error == nil else { return }
}
// 在 HMAccessoryDelegate 中:
func accessory(
_ accessory: HMAccessory,
service: HMService,
didUpdateValueFor characteristic: HMCharacteristic
) {
print("Updated: \(characteristic.value ?? "nil")")
}
動作集與觸發器
建立動作集
HMActionSet 可將多個特性寫入操作分組,並同時執行:
home.addActionSet(withName: "Good Night") { actionSet, error in
guard let actionSet, error == nil else { return }
// 關閉客廳燈光
let lightChar = livingRoomLight.powerCharacteristic
let action = HMCharacteristicWriteAction(
characteristic: lightChar,
targetValue: false as NSCopying
)
actionSet.addAction(action) { error in
guard error == nil else { return }
print("Action added to Good Night scene")
}
}
執行動作集
home.executeActionSet(actionSet) { error in
if let error {
print("Execution failed: \(error)")
}
}
建立定時觸發器
var timeOfDay = DateComponents()
timeOfDay.hour = 22
timeOfDay.minute = 30
let firstFireDate = Calendar.current.nextDate(
after: Date(),
matching: timeOfDay,
matchingPolicy: .nextTime
)!
let trigger = HMTimerTrigger(
name: "Nightly",
fireDate: firstFireDate,
recurrence: DateComponents(day: 1) // 在 firstFireDate 之後每天重複
)
home.addTrigger(trigger) { error in
guard error == nil else { return }
// 將動作集附加到觸發器
trigger.addActionSet(goodNightActionSet) { error in
guard error == nil else { return }
trigger.enable(true) { error in
print("Trigger enabled: \(error == nil)")
}
}
}
建立事件觸發器
let motionDetected = HMCharacteristicEvent(
characteristic: motionSensorCharacteristic,
<<<DESC>>>
使用 HomeKit 與 MatterSupport 控制智慧家庭配件並配網 Matter 裝置。適用於管理家庭/房間/配件、建立動作集(Action Sets)或觸發器(Triggers)、讀取配件特性(Characteristics)、引導 Matter 裝置配網設定,或是開發第三方智慧家庭生態系統 App。
<<<CONTENT>>>
---
name: homekit
description: "使用 HomeKit 與 MatterSupport 控制智慧家庭配件並配網 Matter 裝置。適用於管理家庭/房間/配件、建立動作集(Action Sets)或觸發器(Triggers)、讀取配件特性(Characteristics)、引導 Matter 裝置配網設定,或是開發第三方智慧家庭生態系統 App。"
---
# HomeKit
控制家庭自動化配件並配網 Matter 裝置。HomeKit 負責管理家庭/房間/配件模型、動作集與觸發器;MatterSupport 則負責將 Matter 裝置配網納入您的生態系統中。
## 目錄
- [設定](#設定)
- [HomeKit 資料模型](#homekit-資料模型)
- [管理配件](#管理配件)
- [讀取與寫入特性](#讀取與寫入特性)
- [動作集與觸發器](#動作集與觸發器)
- [Matter 裝置配網](#matter-裝置配網)
- [MatterAddDeviceExtensionRequestHandler](#matteradddeviceextensionrequesthandler)
- [常見錯誤](#常見錯誤)
- [審查檢核表](#審查檢核表)
- [參考資料](#參考資料)
## 設定
### HomeKit 配置
1. 在 Xcode 的 Signing & Capabilities 中啟用 **HomeKit** Capability
2. 在 Info.plist 中新增 `NSHomeKitUsageDescription`:
```xml
<key>NSHomeKitUsageDescription</key>
<string>This app controls your smart home accessories.</string>
MatterSupport 配置
若要將 Matter 裝置配網納入您自己的生態系統:
- 新增 MatterSupport Extension Target,並將其 Principal Class 設定為
MatterAddDeviceExtensionRequestHandler的子類別 - 為
_matter._tcp、_matterc._udp及_matterd._udp新增NSBonjourServices項目 - 僅在呼叫端以程式碼方式提供 Matter 設定 Payload 時,才新增
com.apple.developer.matter.allow-setup-payload
Framework 邊界
| 需求 | Framework |
|---|---|
| 家庭、房間、配件、特性、動作、觸發器 | HomeKit |
| 將 Matter 裝置配網納入 App 生態系統 | MatterSupport |
| 選擇並授權附近的藍牙或 Wi-Fi 配件 | AccessorySetupKit |
| 選擇配件後交換藍牙 GATT 資料 | CoreBluetooth |
| 選擇配件後加入或配置配件的 Wi-Fi 網路 | NetworkExtension |
HomeKit 資料模型
HomeKit 以階層方式組織家庭自動化:
HMHomeManager
-> HMHome (一個或多個)
-> HMRoom (家庭中的房間)
-> HMAccessory (房間內的裝置)
-> HMService (功能:燈光、恆溫器等)
-> HMCharacteristic (可讀取/寫入的數值)
-> HMZone (房間群組)
-> HMActionSet (群組化的動作)
-> HMTrigger (基於時間或事件的觸發器)
初始化 Home Manager
建立單一 HMHomeManager 實例,並實作其 Delegate 以獲知資料何時載入完成。HomeKit 為非同步載入——在 Delegate 觸發前請勿存取 homes。
import HomeKit
final class HomeStore: NSObject, HMHomeManagerDelegate {
let homeManager = HMHomeManager()
override init() {
super.init()
homeManager.delegate = self
}
func homeManagerDidUpdateHomes(_ manager: HMHomeManager) {
// 現在可以安全地存取 manager.homes
let homes = manager.homes
let primaryHome = manager.primaryHome
print("Loaded \(homes.count) homes")
}
func homeManager(
_ manager: HMHomeManager,
didUpdate status: HMHomeManagerAuthorizationStatus
) {
if status.contains(.authorized) {
print("HomeKit access granted")
}
}
}
存取房間
guard let home = homeManager.primaryHome else { return }
let rooms = home.rooms
let kitchen = rooms.first { $0.name == "Kitchen" }
// 取得未指派給特定房間的配件所屬之預設房間
let defaultRoom = home.roomForEntireHome()
管理配件
尋找與新增配件
在新增配件之前,請先參考 Framework 邊界 表格;本 Skill 僅包含 HomeKit/MatterSupport 相關作業。
// 用於配件尋找的系統 UI
home.addAndSetupAccessories { error in
if let error {
print("Setup failed: \(error)")
}
}
列出配件與服務
for accessory in home.accessories {
print("\(accessory.name) in \(accessory.room?.name ?? "unassigned")")
for service in accessory.services {
print(" Service: \(service.serviceType)")
for characteristic in service.characteristics {
print(" \(characteristic.characteristicType): \(characteristic.value ?? "nil")")
}
}
}
將配件移動至另一個房間
guard let accessory = home.accessories.first,
let bedroom = home.rooms.first(where: { $0.name == "Bedroom" }) else { return }
home.assignAccessory(accessory, to: bedroom) { error in
if let error {
print("Failed to move accessory: \(error)")
}
}
讀取與寫入特性
讀取數值
let characteristic: HMCharacteristic = // 從服務中取得
characteristic.readValue { error in
guard error == nil else { return }
if let value = characteristic.value as? Bool {
print("Power state: \(value)")
}
}
寫入數值
// 開燈
characteristic.writeValue(true) { error in
if let error {
print("Write failed: \(error)")
}
}
訂閱變更通知
啟用即時更新的通知功能:
characteristic.enableNotification(true) { error in
guard error == nil else { return }
}
// 在 HMAccessoryDelegate 中:
func accessory(
_ accessory: HMAccessory,
service: HMService,
didUpdateValueFor characteristic: HMCharacteristic
) {
print("Updated: \(characteristic.value ?? "nil")")
}
動作集與觸發器
建立動作集
HMActionSet 可將多個特性寫入操作分組,並同時執行:
home.addActionSet(withName: "Good Night") { actionSet, error in
guard let actionSet, error == nil else { return }
// 關閉客廳燈光
let lightChar = livingRoomLight.powerCharacteristic
let action = HMCharacteristicWriteAction(
characteristic: lightChar,
targetValue: false as NSCopying
)
actionSet.addAction(action) { error in
guard error == nil else { return }
print("Action added to Good Night scene")
}
}
執行動作集
home.executeActionSet(actionSet) { error in
if let error {
print("Execution failed: \(error)")
}
}
建立定時觸發器
var timeOfDay = DateComponents()
timeOfDay.hour = 22
timeOfDay.minute = 30
let firstFireDate = Calendar.current.nextDate(
after: Date(),
matching: timeOfDay,
matchingPolicy: .nextTime
)!
let trigger = HMTimerTrigger(
name: "Nightly",
fireDate: firstFireDate,
recurrence: DateComponents(day: 1) // 在 firstFireDate 之後每天重複
)
home.addTrigger(trigger) { error in
guard error == nil else { return }
// 將動作集附加到觸發器
trigger.addActionSet(goodNightActionSet) { error in
guard error == nil else { return }
trigger.enable(true) { error in
print("Trigger enabled: \(error == nil)")
}
}
}
建立事件觸發器
let motionDetected = HMCharacteristicEvent(
characteristic: motionSensorCharacteristic,
triggerValue: true as NSCopying
)
let eventTrigger = HMEventTrigger(
name: "Motion Lights",
events: [motionDetected],
predicate: nil
)
home.addTrigger(eventTrigger) { error in
// 如同上述方式新增動作集
}
Matter 裝置配網
使用 MatterAddDeviceRequest 將 Matter 裝置配網納入您的生態系統。這與 HMHome 家庭自動化模型是分開的;它負責處理 Matter 的設定流程並呼叫您的 MatterSupport Extension。
基礎裝置配網
import MatterSupport
func addMatterDevice() async throws {
guard MatterAddDeviceRequest.isSupported else {
print("Matter not supported on this device")
return
}
let topology = MatterAddDeviceRequest.Topology(
ecosystemName: "My Smart Home",
homes: [
MatterAddDeviceRequest.Home(displayName: "Main House")
]
)
let request = MatterAddDeviceRequest(
topology: topology,
setupPayload: nil,
showing: .allDevices
)
// 顯示裝置配對的系統 UI
try await request.perform()
}
若直接提供設定碼(Setup Code),請匯入 Matter 並傳入 MTRSetupPayload 作為 setupPayload;此情況需要啟用 setup-payload 的 Entitlement 授權。
過濾裝置
// 僅顯示特定廠商的裝置
let criteria = MatterAddDeviceRequest.DeviceCriteria.vendorID(0x1234)
let request = MatterAddDeviceRequest(
topology: topology,
setupPayload: nil,
showing: criteria
)
使用 .all([.vendorID(...), .not(.productID(...))]) 組合條件,或在滿足任一條件即可時使用 .any(...)。
MatterAddDeviceExtensionRequestHandler
若要提供完整的生態系統支援,請建立 MatterSupport Extension。該 Extension 負責處理配網(Commissioning)回呼。請覆寫所需的方法,但切勿在這些覆寫方法中呼叫 super。
若需憑證驗證、房間選擇、配置、配網及網路關聯的覆寫方法,請參閱完整的 進階 Matter Extension 處理程序。
常見錯誤
| 錯誤 | 修正方式 |
|---|---|
| 在 Delegate 更新前讀取家庭資料 | 建立單一 Manager 實例、設定其 Delegate,並等待 homeManagerDidUpdateHomes 觸發。 |
| 使用 HomeKit 設定流程進行 Matter 生態系統配網 | 使用 MatterAddDeviceRequest 搭配配置好的 MatterSupport Extension。 |
| Matter 配置不完整 | 檢查 Principal Handler、Bonjour 服務,並僅在適用時驗證 setup-payload Entitlement。 |
多個 HMHomeManager 實例重複載入資料庫 |
共享並留存(Retain)單一 Manager/Store 實例。 |
| 寫入特性時忽略了 Metadata | 在寫入前檢查權限、格式、最小值/最大值/步階值(Min/Max/Step)以及允許的數值範圍。 |
審查檢核表
- [ ] 已在 Xcode 中啟用 HomeKit Capability
- [ ] Info.plist 中已包含
NSHomeKitUsageDescription - [ ] 全域共享單一
HMHomeManager實例 - [ ] 已實作
HMHomeManagerDelegate;且在homeManagerDidUpdateHomes觸發前未讀取家庭資料 - [ ] 已在 Home 實例上設定
HMHomeDelegate以接收配件與房間的變更通知 - [ ] 已在 Accessory 實例上設定
HMAccessoryDelegate以接收特性的更新通知 - [ ] 寫入數值前已檢查特性的 Metadata
- [ ] 所有 Completion Handler 均包含錯誤處理邏輯
- [ ] 已配置 MatterSupport Extension Target 與 Principal Handler
- [ ] 已新增 Matter 尋找所需的
NSBonjourServices項目 - [ ] 僅在提供設定碼時才使用
com.apple.developer.matter.allow-setup-payload - [ ] 執行請求前已檢查
MatterAddDeviceRequest.isSupported - [ ] Matter Extension Handler 已實作
commissionDevice(in:onboardingPayload:commissioningID:) - [ ] 發布前已使用 HomeKit Accessory Simulator 測試動作集
- [ ] 觸發器建立後已啟用 (
trigger.enable(true))
參考資料
- 延伸模式(Matter Extension、Delegate 銜接、SwiftUI):references/matter-commissioning.md
- HomeKit framework
- HMHomeManager
- HMHome
- HMAccessory
- HMRoom
- HMActionSet
- HMTrigger
- MatterSupport framework
- MatterAddDeviceRequest






