燈具裝置會使用標準 Matter 特性來識別燈具、切換電源狀態,以及調整亮度等級。
最基本的燈具裝置類型是 OnOffLightDeviceType,使用 OnOffTrait 和 IdentifyTrait 特性實作,並可選擇支援 LevelControlTrait 特性和 LightEffectsTrait 特性。
其他燈具類型提供額外功能,並透過不同特徵實作:
| Home API 裝置類型 | 特徵 | Swift 範例應用程式 | 用途 |
|---|---|---|---|
|
色溫燈
可開啟或關閉、調整光線強度和色溫的照明裝置。 |
必要特徵 Matter IdentifyTrait Matter OnOffTrait Matter LevelControlTrait Matter ColorControlTrait |
輕度 | |
|
可調光燈具
可開啟或關閉、調整亮度,以及透過繫結的活動情形感應器切換的照明裝置。 |
必要特徵 matter IdentifyTrait matter OnOffTrait matter LevelControlTrait |
輕度 | |
|
Extended Color Light
可開啟或關閉、調整亮度、調整色溫,以及透過繫結的活動情形感應器切換的照明裝置。 |
必要特徵 Matter IdentifyTrait Matter OnOffTrait Matter LevelControlTrait Matter ColorControlTrait |
輕度 | |
|
開關燈
可開啟或關閉的照明裝置。 |
必要特徵 matter IdentifyTrait matter OnOffTrait |
輕度 |
使用任何功能或嘗試更新屬性前,請務必確認裝置是否支援該屬性和指令。詳情請參閱「在iOS上控制裝置」。
必要條件
使用照明裝置和照明曲線前,請確認應用程式已初始化 Home SDK,並包含必要的匯入項目:
import Foundation import GoogleHomeSDK import GoogleHomeTypes import Network
尋找燈具裝置
如要尋找住家中的照明裝置,請依裝置類型篩選裝置清單,例如 OnOffLightDeviceType 和 DimmableLightDeviceType。
let allDevices = try await home.devices().list() // Get all On/Off Light devices in the structure let onOffLights = allDevices.filter { $0.types.contains(OnOffLightDeviceType.self) } // Get all Dimmable Light devices in the structure let dimmableLights = allDevices.filter { $0.types.contains(DimmableLightDeviceType.self) } // Retrieve a specific device type instance to access its traits let onOffLightDeviceType = await onOffLights.first?.types.get(OnOffLightDeviceType.self) let dimmableLightDeviceType = await dimmableLights.first?.types.get(DimmableLightDeviceType.self)
您也可以在單一篩選器中,擷取多種照明裝置類型的所有照明裝置:
// Get a list of devices with similar device types (lights) let lightDevices = try await self.home.devices().list().compactMap { $0.types.contains(DimmableLightDeviceType.self) || $0.types.contains(OnOffLightDeviceType.self) || $0.types.contains(ColorTemperatureLightDeviceType.self) || $0.types.contains(ExtendedColorLightDeviceType.self) }
取得裝置的基本資訊
BasicInformation 特性包含裝置的供應商名稱、供應商 ID、產品 ID、產品名稱 (包含型號資訊) 和軟體版本等資訊:
let vendorName = basicInfoTrait.attributes.vendorName! let vendorID = basicInfoTrait.attributes.vendorID! let productID = basicInfoTrait.attributes.productID! let productName = basicInfoTrait.attributes.productName! let softwareVersion = basicInfoTrait.attributes.softwareVersion!
辨識照明裝置
如果房間內有多盞燈,你可以觸發視覺辨識狀態 (例如讓燈閃爍幾秒),協助使用者找到特定實體燈具。這四種燈具裝置類型都必須具備 Matter.IdentifyTrait 特性。
呼叫 identify 指令,並以秒為單位指定 identifyTime 持續時間,即可啟動辨識狀態。傳遞 0 會立即停止辨識狀態。您也可以呼叫 triggerEffect 來執行特定視覺效果,例如 Blink 或 Breathe。
func identifyLight(lightDeviceType: DimmableLightDeviceType) async throws {
guard let identifyTrait = lightDeviceType.matterTraits.identifyTrait else {
return
}
// Blink the light for 10 seconds so the user can locate it
if identifyTrait.supportsIdentifyCommand {
try await identifyTrait.identify(identifyTime: 10)
}
// Or trigger a specific visual identification effect
if identifyTrait.supportsTriggerEffectCommand {
try await identifyTrait.triggerEffect(
effectIdentifier: .blink,
effectVariant: .default
)
}
}
檢查照明裝置的連線
系統實際上會檢查裝置類型層級的裝置連線能力,因為部分裝置支援多種裝置類型。傳回的狀態是該裝置所有特性的連線狀態組合。
let lightConnectivity = dimmableLightDeviceType.metadata.sourceConnectivity .connectivityState
如果裝置類型不一,且沒有網際網路連線,可能會看到 partiallyOnline 狀態。由於本機路由,Matter 標準特徵可能仍會上線,但雲端式特徵會離線。
取得裝置的 IP 位址
如要找出裝置的 IP 位址,請使用 GeneralDiagnosticsTrait 的 networkInterfaces 屬性。位址會以 Data 物件的形式傳回,您可以使用 Network 架構將其格式化為標準 IPv4 或 IPv6 字串:
func getIpAddresses(trait: Matter.GeneralDiagnosticsTrait) -> [String] {
let interfaces = trait.attributes.networkInterfaces ?? []
var ipAddresses: [String] = []
for interface in interfaces {
for data in interface.iPv4Addresses {
if let ipv4 = IPv4Address(data) {
ipAddresses.append(String(describing: ipv4))
}
}
for data in interface.iPv6Addresses {
if let ipv6 = IPv6Address(data) {
ipAddresses.append(String(describing: ipv6))
}
}
}
return ipAddresses
}
控制照明裝置
OnOffLight 和 DimmableLight 裝置類型會使用標準 Matter 特性,識別燈具、切換電源狀態,以及調整亮度等級。
開啟或關閉燈具
使用 OnOffTrait 特性讀取 OnOffLight 或 DimmableLight 的目前電源狀態,以及開啟或關閉燈光。
讀取 onOff 屬性前,請先確認裝置是否支援。部分裝置僅能做為指令端點,不會回報狀態。
// Check if the OnOff trait supports the onOff attribute. if onOffTrait.attributes.$onOff.isSupported { print("onOffTrait supports onOff state") } else { print("onOffTrait is for a command only device!") }
onOff為true時,指示燈會亮起。當 onOff 為 false 時,燈會關閉。
如要變更燈具的電源狀態,請確認特性能支援預期指令,然後呼叫 on()、off() 或 toggle()。
// Check if the OnOff trait supports the toggle command. if onOffTraitTest.supportsToggleCommand { print("onOffTrait supports toggle command") } else { print("onOffTrait does not support stateful toggle command") }
// Calling a command on a trait. do { try await onOffTraitTest.toggle() } catch let _ as HomeError { // Code for handling the exception }
您也可以直接呼叫 on() 和 off(),設定明確狀態:
do { try await onOffTraitTest.off() try await onOffTraitTest.on() } catch let _ as HomeError { // Code for handling the exception }
如要關閉燈具,並逐漸轉換視覺效果,請呼叫 offWithEffect() 並指定 EffectIdentifierEnum 值:
// Turn off the light using the DyingLight effect. do { try await onOffTraitTest.offWithEffect( effectIdentifier: Matter.OnOffTrait.EffectIdentifierEnum.dyingLight, effectVariant: 0 ) } catch let _ as HomeError { // Code for handling the exception }
調整亮度
DimmableLight 必須具備 LevelControlTrait 特性,OnOffLight 則可選擇是否支援。這項特徵可用於讀取及控制燈具的亮度。
currentLevel 屬性會回報目前的亮度等級,範圍為 0 至 254。您也可以檢查 minLevel 和 maxLevel,判斷硬體支援的有效亮度範圍。
如要將亮度設為特定值,請呼叫 moveToLevel()。請注意,除非您使用 executeIfOff 設定 optionsOverride,否則 moveToLevel() 只會在燈光開啟時變更目前亮度。如要在設定非零亮度等級時自動開啟燈光 (或在設定最低等級時關閉燈光),請使用 moveToLevelWithOnOff()。
// Change the brightness of the light to 50% do { try await levelControlTraitTest.moveToLevel( level: UInt8(127), transitionTime: 0, optionsMask: Matter.LevelControlTrait.OptionsBitmap(), optionsOverride: Matter.LevelControlTrait.OptionsBitmap() ) } catch let _ as HomeError { // Code for handling the exception }
以下範例會讀取目前的亮度等級,並使用 moveToLevelWithOnOff() 將可調光燈具的亮度設為 75% (190),轉換時間為 1 秒 (10 秒):
func setLightBrightness(lightDeviceType: DimmableLightDeviceType) async throws { guard let levelControl = lightDeviceType.matterTraits.levelControlTrait else { return } // Read the current brightness level (0 to 254) let currentLevel: UInt8? = levelControl.attributes.currentLevel print("Current brightness level: \(String(describing: currentLevel))") // Move to ~75% brightness (190 out of 254) and turn on the light if it is off if levelControl.supportsMoveToLevelWithOnOffCommand { try await levelControl.moveToLevelWithOnOff( level: UInt8(190), transitionTime: 10, optionsMask: Matter.LevelControlTrait.OptionsBitmap(), optionsOverride: Matter.LevelControlTrait.OptionsBitmap() ) } }
您也可以呼叫 stepWithOnOff(),並使用 .up 或 .down 和 stepSize,相對於目前等級增加或減少亮度。
控制項顏色
ColorControlTrait 特性適用於 ColorTemperatureLightDeviceType 和 ExtendedColorLightDeviceType。這項特性能以微倒數度或邁爾德為單位調整色溫。
guard let colorControlTrait = colorTempLightDeviceType.matterTraits.colorControlTrait else { return } // Read the current color temperature and hardware limits in mireds // (Mireds = 1,000,000 / Kelvin; e.g., 370 mireds ≈ 2700K warm white, 250 mireds = 4000K cool white) let currentMireds = colorControlTrait.attributes.colorTemperatureMireds let minMireds = colorControlTrait.attributes.colorTempPhysicalMinMireds ?? 153 let maxMireds = colorControlTrait.attributes.colorTempPhysicalMaxMireds ?? 500 // Clamp target (370 mireds ≈ 2700K) to the device's physical bounds let targetMireds = min(max(UInt16(370), minMireds), maxMireds) if colorControlTrait.supportsMoveToColorTemperatureCommand { try await colorControlTrait.moveToColorTemperature( colorTemperatureMireds: targetMireds, transitionTime: 20, // 2.0 seconds (in 0.1s units) optionsMask: Matter.ColorControlTrait.OptionsBitmap(), optionsOverride: Matter.ColorControlTrait.OptionsBitmap() ) }
您也可以使用 CIE 1931 色度座標和 16 位元色相和飽和度值設定顏色。
guard let colorControlTrait = extendedColorLightDeviceType.matterTraits.colorControlTrait else { return } // 1. Move to CIE 1931 xy chromaticity coordinates (scaled 0..65279) // Example: x = 0.3127 (20493), y = 0.3290 (21561) for D65 white point if colorControlTrait.supportsMoveToColorCommand { try await colorControlTrait.moveToColor( colorX: 20493, colorY: 21561, transitionTime: 10, // 1.0 second (in 0.1s units) optionsMask: Matter.ColorControlTrait.OptionsBitmap(), optionsOverride: Matter.ColorControlTrait.OptionsBitmap() ) } let currentX = colorControlTrait.attributes.currentX let currentY = colorControlTrait.attributes.currentY // 2. Move to 16-bit Enhanced Hue (0..65534) and 8-bit Saturation (0..254) if colorControlTrait.supportsEnhancedMoveToHueAndSaturationCommand { try await colorControlTrait.enhancedMoveToHueAndSaturation( enhancedHue: 43690, // ~240° (Blue) on the 0..65534 scale saturation: 254, // Full saturation transitionTime: 15, // 1.5 seconds (in 0.1s units) optionsMask: Matter.ColorControlTrait.OptionsBitmap(), optionsOverride: Matter.ColorControlTrait.OptionsBitmap() ) } // 3. Start a hardware color loop across the device's hue range if colorControlTrait.supportsColorLoopSetCommand { try await colorControlTrait.colorLoopSet( updateFlags: [ .updateAction, .updateDirection, .updateTime, .updateStartHue ], action: .activateFromColorLoopStartEnhancedHue, direction: .increment, time: 30, // 30 seconds per full cycle startHue: 0, optionsMask: Matter.ColorControlTrait.OptionsBitmap(), optionsOverride: Matter.ColorControlTrait.OptionsBitmap() ) }
Google.ExtendedColorControlTrait 是 ExtendedColorLightDevice 的選用 Google 特性,可接受顏色名稱、RGB 值或統一浮點 HSV 值 (將顏色和亮度合併為單一單位),簡化顏色控制。guard let extendedColorControlTrait = extendedColorLightDeviceType.googleTraits.extendedColorControlTrait else { return } // 1. Set color by name if extendedColorControlTrait.supportsMoveToColorNameCommand { try await extendedColorControlTrait.moveToColorName(colorName: "Lavender") } let currentColorName = extendedColorControlTrait.attributes.currentName // 2. Set color using 8-bit RGB values (0..255 per channel) // Automatically coordinates brightness (LevelControl) and color (ColorControl) if extendedColorControlTrait.supportsMoveToColorRGBCommand { try await extendedColorControlTrait.moveToColorRGB( red: 255, green: 128, blue: 0 ) } let currentRed = extendedColorControlTrait.attributes.currentRed let currentGreen = extendedColorControlTrait.attributes.currentGreen let currentBlue = extendedColorControlTrait.attributes.currentBlue // 3. Set color and brightness together using floating-point HSV // hue: 0.0...360.0, saturation: 0.0...1.0, value (brightness): 0.0...1.0 if extendedColorControlTrait.supportsMoveToColorHSVCommand { try await extendedColorControlTrait.moveToColorHSV( hue: 210.0, saturation: 0.85, value: 0.75 ) } let currentHue = extendedColorControlTrait.attributes.currentHue let currentSaturation = extendedColorControlTrait.attributes.currentSaturation let currentValue = extendedColorControlTrait.attributes.currentValue
管理光照曲線
照明曲線可定義自動化時間表,在一天中平順地轉換目標燈具的亮度和選用色溫。舉例來說,照明曲線可以在早上逐漸調亮燈光,並在晚上調暗燈光,呈現較溫暖的色調。僅支援亮度的燈具裝置類型 (例如可調光燈具) 會遵循亮度曲線,並忽略色溫。
Google.LightingCurveTrait 特性是住家層級的 Google Home platform (GHP) 特性。您是透過 Structure 執行個體存取,而非個別照明裝置。
特性的每個時間表都以 LightingCurveSetting 表示,其中不重複的 settingId 會與 LightingCurveConfig 配對。下表說明 LightingCurveConfig 的設定欄位:
| 欄位 | 說明 |
|---|---|
curvePointsArray |
至少兩個時間不同的 CurvePoint 項目序列。每個點都會指定 time (CurveTimeOfDay,hours 介於 0 到 23 之間,minutes 介於 0 到 59 之間)、brightnessPercent (0 到 100),以及選用的 colorTemperature (以克耳文為單位)。如果為任何點指定 colorTemperature,則所有點的值都必須為正值。 |
roomId |
目標房間的 ID (例如 room@{uuid}),系統會將照明曲線套用至該房間內相容的可調光和色溫燈具。指定 roomId 或 devices。 |
devices |
TargetDevices 物件,包含 TargetDevice 項目清單,每個項目都有裝置 id 和裝置 type ID (例如 DimmableLight 的 home.matter.0000.types.0101 或 ColorTemperatureLight 的 home.matter.0000.types.010c)。請指定 devices 或 roomId。 |
daysOfWeekArray |
執行照明曲線的星期幾 (Locale.Weekday)。如果清單空白,則每天都會執行照明曲線。 |
adaptive |
選用布林值,指出照明曲線是否為自動調整,也就是說,目標燈具在可預約時間範圍內開啟時,會恢復為有效曲線等級。false時,如果手動調整燈具,該燈具在當天剩餘時間內就會脫離照明曲線。當 true 時,在時間表期間關閉再開啟的燈具會重新與照明曲線連結,使燈具符合曲線目前的亮度和色溫,並從該處開始遵循曲線。 |
enabled |
選用布林值,指出是否啟用光線曲線設定。建立新設定時,預設值為 true。如果更新指令省略 enabled,enabled 的狀態就不會變更。 |
讀取亮度曲線設定
如要檢查為住家設定的照明曲線,請從 Structure 擷取 Google.LightingCurveTrait 特性,並讀取其 lightingCurveSettingsArray 屬性。
func readLightingCurves(structure: Structure) async {
guard let lightingCurve = await structure.traits.get(
Google.LightingCurveTrait.self
) else {
return
}
for setting in lightingCurve.attributes.lightingCurveSettingsArray {
let settingId = setting.settingId
let config = setting.config
print(
"Setting ID: \(String(describing: settingId)), " +
"enabled: \(String(describing: config?.enabled))"
)
for point in config?.curvePointsArray ?? [] {
print(
" Time: \(point.time?.hours ?? 0):\(point.time?.minutes ?? 0), " +
"Brightness: \(point.brightnessPercent ?? 0)%, " +
"ColorTemp: \(point.colorTemperature ?? 0)K"
)
}
}
}
建立光線曲線設定
如要在住家建立新的照明曲線時間表,請建構 LightingCurveConfig,其中至少包含兩個 CurvePoint 項目、目標燈具 (由 roomId 或 devices 指定),以及一週中的有效日期。然後將設定傳遞至 createLightingCurveSetting()。指令會傳回指派給新亮度曲線設定的不重複 settingId。
以下範例會為房間建立平日照明曲線,亮度從上午 7:00 的 30% 提高到上午 9:00 的 80%,並在晚上 9:00 調暗至 20%:
func createRoomLightingCurve(
structure: Structure,
targetRoomId: String
) async throws -> String? {
guard let lightingCurve = await structure.traits.get(
Google.LightingCurveTrait.self
) else {
return nil
}
let curvePoints = [
Google.LightingCurveTrait.CurvePoint(
time: Google.LightingCurveTrait.CurveTimeOfDay(hours: 7, minutes: 0),
brightnessPercent: 30,
colorTemperature: 2700
),
Google.LightingCurveTrait.CurvePoint(
time: Google.LightingCurveTrait.CurveTimeOfDay(hours: 9, minutes: 0),
brightnessPercent: 80,
colorTemperature: 4000
),
Google.LightingCurveTrait.CurvePoint(
time: Google.LightingCurveTrait.CurveTimeOfDay(hours: 21, minutes: 0),
brightnessPercent: 20,
colorTemperature: 2200
),
]
let config = Google.LightingCurveTrait.LightingCurveConfig(
curvePointsArray: curvePoints,
roomId: targetRoomId,
daysOfWeekArray: [
.monday,
.tuesday,
.wednesday,
.thursday,
.friday,
],
adaptive: true,
enabled: true
)
let response = try await lightingCurve.createLightingCurveSetting(
config: config
)
return response.settingId
}
如要指定特定照明裝置,而非整個房間,請使用 Google.LightingCurveTrait.TargetDevices 提供 devices 參數:
let targetDevices = Google.LightingCurveTrait.TargetDevices(
devicesArray: [
Google.LightingCurveTrait.TargetDevice(
id: dimmableLight.id,
type: DimmableLightDeviceType.identifier
)
]
)
let deviceCurveConfig = Google.LightingCurveTrait.LightingCurveConfig(
curvePointsArray: curvePoints,
devices: targetDevices,
daysOfWeekArray: [.saturday, .sunday],
adaptive: true,
enabled: true
)
let response = try await lightingCurve.createLightingCurveSetting(
config: deviceCurveConfig
)
let settingId = response.settingId
更新亮度曲線設定
如要修改現有的光照曲線 (例如變更曲線點、更新一週中的有效天數,或啟用/停用時間表),請使用目標 settingId 和更新後的 LightingCurveConfig 呼叫 updateLightingCurveSetting()。
func updateLightingCurve(
structure: Structure,
settingId: String,
updatedConfig: Google.LightingCurveTrait.LightingCurveConfig
) async throws {
guard let lightingCurve = await structure.traits.get(
Google.LightingCurveTrait.self
) else {
return
}
_ = try await lightingCurve.updateLightingCurveSetting(
settingId: settingId,
config: updatedConfig
)
}
刪除亮度曲線設定
如要從住家結構體中移除照明曲線設定,請呼叫 deleteLightingCurveSetting(),並提供要刪除的設定 settingId。
func deleteLightingCurve(
structure: Structure,
settingId: String
) async throws {
guard let lightingCurve = await structure.traits.get(
Google.LightingCurveTrait.self
) else {
return
}
_ = try await lightingCurve.deleteLightingCurveSetting(settingId: settingId)
}