조명 기기는 표준 Matter 특성을 사용하여 조명 기구를 식별하고, 전원 상태를 전환하고, 밝기 수준을 조정합니다.
가장 기본적인 조명 기기 유형은 OnOffLight이며, OnOff 및 Identify 특성으로 구현되고 선택적으로 LevelControl 특성 및 LightEffects 특성을 지원합니다.
다른 조명 유형은 추가 기능을 제공하며 다양한 특성으로 구현됩니다.
| Home API 기기 유형 | 특성 | Kotlin 샘플 앱 | 사용 사례 |
|---|---|---|---|
|
색상 온도 조명
켜거나 끌 수 있고, 조명 강도를 조정할 수 있으며, 색상 온도를 조정할 수 있는 조명 기기입니다. |
필수 특성 matter Identify matter OnOff matter LevelControl matter ColorControl |
켜기/끄기, 밝기 |
밝게 |
|
밝기 조절 조명
켜거나 끌 수 있고, 조도를 조정할 수 있으며, 바인딩된 사람 감지 센서를 통해 전환할 수 있는 조명 기기입니다. |
필수 특성 matter Identify matter OnOff matter LevelControl |
켜기/끄기, 밝기 |
밝게 |
|
확장된 색상 조명
켜거나 끌 수 있고, 조명의 강도를 조정할 수 있고, 색상 온도를 조정할 수 있으며, 바인딩된 사람 감지 센서를 통해 전환할 수 있는 조명 기기입니다. |
필수 특성 matter Identify matter OnOff matter LevelControl matter ColorControl |
켜기/끄기, 밝기 |
밝게 |
|
조명 켜기/끄기
켜거나 끌 수 있는 조명 기기입니다. |
필수 특성 matter Identify matter OnOff |
켜기/끄기, 밝기 |
밝게 |
기능을 사용하거나 속성을 업데이트하기 전에 항상 기기의 속성 및 명령어 지원을 확인하세요. 자세한 내용은 Android에서 기기 제어를 참고하세요.
기본 요건
조명 기기 및 조명 곡선을 사용하기 전에 앱이 Home SDK를 초기화하고 필요한 가져오기를 포함하는지 확인하세요.
import com.google.home.HomeDevice import com.google.home.Structure import com.google.home.google.DayOfWeek import com.google.home.google.ExtendedColorControl import com.google.home.google.ExtendedColorControlTrait import com.google.home.google.LightingCurve import com.google.home.google.LightingCurveTrait import com.google.home.matter.standard.ColorControl import com.google.home.matter.standard.ColorControlTrait import com.google.home.matter.standard.ColorTemperatureLightDevice import com.google.home.matter.standard.DimmableLightDevice import com.google.home.matter.standard.ExtendedColorLightDevice import com.google.home.matter.standard.GeneralDiagnostics import com.google.home.matter.standard.Identify import com.google.home.matter.standard.IdentifyTrait import com.google.home.matter.standard.LevelControl import com.google.home.matter.standard.LevelControlTrait import com.google.home.matter.standard.OnOff import com.google.home.matter.standard.OnOffLightDevice import com.google.home.matter.standard.OnOffTrait import com.google.home.matter.standard.RootNodeDevice import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.firstOrNull
조명 기기 찾기
구조에서 조명 기기를 찾으려면 기기 유형(예: OnOffLightDevice 및 DimmableLightDevice)별로 기기 목록을 필터링합니다.
// Get all On/Off Light devices in the structure val onOffLights: List<HomeDevice> = home.devices().list().filter { it.has(OnOffLightDevice) } // Get all Dimmable Light devices in the structure val dimmableLights: List<HomeDevice> = home.devices().list().filter { it.has(DimmableLightDevice) } // Retrieve a specific device type instance to access its traits val onOffLightDevice: OnOffLightDevice? = onOffLights.firstOrNull()?.type(OnOffLightDevice)?.firstOrNull() val dimmableLightDevice: DimmableLightDevice? = dimmableLights.firstOrNull()?.type(DimmableLightDevice)?.firstOrNull()
단일 필터에서 여러 조명 기기 유형의 모든 조명 기기를 가져올 수도 있습니다.
// Get a list of devices with similar device types (lights) val lightDevices = home.devices().map { devices -> devices.filter { it.has(DimmableLightDevice) || it.has(OnOffLightDevice) || it.has(ColorTemperatureLightDevice) || it.has(ExtendedColorLightDevice) } }
기기에 관한 기본 정보 가져오기
BasicInformation 특성에는 기기의 공급업체 이름, 공급업체 ID, 제품 ID, 제품 이름 (모델 정보 포함), 소프트웨어 버전과 같은 정보가 포함됩니다.
// Get device basic information. All general information traits are on the RootNodeDevice type. device.type(RootNodeDevice).first().standardTraits.basicInformation?.let { basicInformation -> println("vendorName ${basicInformation.vendorName}") println("vendorId ${basicInformation.vendorId}") println("productId ${basicInformation.productId}") println("productName ${basicInformation.productName}") println("softwareVersion ${basicInformation.softwareVersion}") }
조명 기기 식별
방에 조명이 여러 개 있는 경우 몇 초 동안 조명을 깜박이는 것과 같은 시각적 식별 상태를 트리거하여 사용자가 특정 물리적 조명 기구를 찾도록 도울 수 있습니다. 네 가지 조명 기기 유형 모두 Identify 특성이 필요합니다.
identify 명령어를 identifyTime 기간(초)과 함께 호출하여 식별 상태를 시작합니다. 0를 전달하면 식별 상태가 즉시 중지됩니다. triggerEffect를 호출하여 Blink 또는 Breathe와 같은 특정 시각 효과를 실행할 수도 있습니다.
suspend fun identifyLight(lightDevice: DimmableLightDevice) {
val identifyTrait = lightDevice.standardTraits.identify ?: return
// Blink the light for 10 seconds so the user can locate it
if (identifyTrait.supports(Identify.Command.Identify)) {
identifyTrait.identify(identifyTime = 10u)
}
// Or trigger a specific visual identification effect
if (identifyTrait.supports(Identify.Command.TriggerEffect)) {
identifyTrait.triggerEffect(
effectIdentifier = IdentifyTrait.EffectIdentifierEnum.Blink,
effectVariant = IdentifyTrait.EffectVariantEnum.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 특성을 사용하여 조명 기구를 식별하고, 전원 상태를 전환하고, 밝기 수준을 조정합니다.
조명 켜기 또는 끄기
OnOff 속성을 사용하여 OnOffLight 또는 DimmableLight의 현재 전원 상태를 읽고 조명을 켜거나 끕니다.
onOff 속성을 읽기 전에 기기에서 이 속성을 지원하는지 확인합니다. 일부 기기는 명령어 전용 엔드포인트로 작동하며 상태를 보고하지 않습니다.
// Check if the OnOff trait supports the onOff attribute. if (onOffTrait.supports(OnOff.Attribute.onOff)) { println("onOffTrait supports onOff state") } else { println("onOffTrait is for a command only device!") }
onOff이 true이면 조명이 켜집니다. onOff가 false이면 표시등이 꺼집니다.
조명의 전원 상태를 변경하려면 특성이 원하는 명령어를 지원하는지 확인한 후 on(), off() 또는 toggle()를 호출합니다.
// Check if the OnOff trait supports the toggle command. if (onOffTrait.supports(OnOff.Command.Toggle)) { println("onOffTrait supports toggle command") } else { println("onOffTrait does not support stateful toggle command") }
// Calling a command on a trait. try { onOffTrait.toggle() } catch (e: HomeException) { // Code for handling the exception }
on() 및 off()를 직접 호출하여 명시적 상태를 설정할 수도 있습니다.
onOffTrait.off() onOffTrait.on()
점진적인 시각적 전환으로 조명을 끄려면 offWithEffect()를 호출하고 EffectIdentifierEnum 값을 지정합니다.
// Turn off the light using the DyingLight effect. onOffTrait.offWithEffect( effectIdentifier = OnOffTrait.EffectIdentifierEnum.DyingLight, effectVariant = 0u, )
밝기 수준 조정
DimmableLight에는 LevelControl 속성이 필요하며 OnOffLight는 선택적으로 이를 지원할 수 있습니다. 이 특성을 사용하여 조명의 밝기 수준을 읽고 제어합니다.
currentLevel 속성은 현재 밝기 수준을 0에서 254까지의 범위로 보고합니다. minLevel 및 maxLevel를 검사하여 하드웨어에서 지원하는 유효한 밝기 범위를 확인할 수도 있습니다.
밝기를 특정 값으로 설정하려면 moveToLevel()를 호출합니다. executeIfOff로 optionsOverride를 구성하지 않는 한 moveToLevel()는 조명이 이미 켜져 있을 때만 현재 수준을 변경합니다. 0이 아닌 밝기 수준을 설정할 때 조명을 자동으로 켜거나 (또는 수준을 최소로 설정할 때 조명을 끄려면) moveToLevelWithOnOff()를 사용합니다.
// Change the brightness of the light to 50% levelControlTrait.moveToLevel( level = 127u.toUByte(), transitionTime = null, optionsMask = LevelControlTrait.OptionsBitmap(), optionsOverride = LevelControlTrait.OptionsBitmap(), )
다음 예시에서는 현재 밝기 수준을 읽고 moveToLevelWithOnOff()를 사용하여 1초 (10u 1/10초) 전환 동안 조광 가능한 조명을 75% 밝기 (190u)로 설정합니다.
suspend fun setLightBrightness(lightDevice: DimmableLightDevice) { val levelControl = lightDevice.standardTraits.levelControl ?: return // Read the current brightness level (0 to 254) val currentLevel: UByte? = levelControl.currentLevel println("Current brightness level: $currentLevel") // Move to ~75% brightness (190 out of 254) and turn on the light if it is off if (levelControl.supports(LevelControl.Command.MoveToLevelWithOnOff)) { levelControl.moveToLevelWithOnOff( level = 190u, transitionTime = 10u, optionsMask = LevelControlTrait.OptionsBitmap(), optionsOverride = LevelControlTrait.OptionsBitmap() ) } }
StepModeEnum.Up 또는 StepModeEnum.Down 및 stepSize를 사용하여 stepWithOnOff()를 호출하여 현재 수준을 기준으로 밝기를 늘리거나 줄일 수도 있습니다.
컨트롤 색상
ColorControl 특성은 ColorTemperatureLightDevice 및 ExtendedColorLightDevice에서 모두 사용할 수 있습니다.
이 특성을 사용하면 색상 온도를 마이크로 역도 또는 마이어드로 조정할 수 있습니다.
val colorControlTrait = colorTempLightDevice.standardTraits.colorControl ?: 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) val currentMireds = colorControlTrait.colorTemperatureMireds val minMireds = colorControlTrait.colorTempPhysicalMinMireds ?: 153u // ~6500K (coolest) val maxMireds = colorControlTrait.colorTempPhysicalMaxMireds ?: 500u // 2000K (warmest) // Clamp target (370 mireds ≈ 2700K) to the device's physical bounds val targetMireds = 370u.toUShort().coerceIn(minMireds, maxMireds) if ( colorControlTrait.supports( ColorControl.Command.MoveToColorTemperature ) ) { colorControlTrait.moveToColorTemperature( colorTemperatureMireds = targetMireds, transitionTime = 20u, // 2.0 seconds (in 0.1s units) optionsMask = ColorControlTrait.OptionsBitmap(), optionsOverride = ColorControlTrait.OptionsBitmap() ) }
CIE 1931 색도 좌표와 16비트 색조 및 채도 값을 사용하여 색상을 설정할 수도 있습니다.
val colorControlTrait = extendedColorLightDevice.standardTraits.colorControl ?: 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.supports(ColorControl.Command.MoveToColor)) { colorControlTrait.moveToColor( colorX = 20493u, colorY = 21561u, transitionTime = 10u, // 1.0 second (in 0.1s units) optionsMask = ColorControlTrait.OptionsBitmap(), optionsOverride = ColorControlTrait.OptionsBitmap() ) } val currentX = colorControlTrait.currentX val currentY = colorControlTrait.currentY // 2. Move to 16-bit Enhanced Hue (0..65534) and 8-bit Saturation (0..254) if ( colorControlTrait.supports( ColorControl.Command.EnhancedMoveToHueAndSaturation ) ) { colorControlTrait.enhancedMoveToHueAndSaturation( enhancedHue = 43690u, // ~240° (Blue) on the 0..65534 scale saturation = 254u, // Full saturation transitionTime = 15u, // 1.5 seconds (in 0.1s units) optionsMask = ColorControlTrait.OptionsBitmap(), optionsOverride = ColorControlTrait.OptionsBitmap() ) } // 3. Start a hardware color loop across the device's hue range if (colorControlTrait.supports(ColorControl.Command.ColorLoopSet)) { colorControlTrait.colorLoopSet( updateFlags = ColorControlTrait.UpdateFlagsBitmap( updateAction = true, updateDirection = true, updateTime = true, updateStartHue = true ), action = ColorControlTrait.ColorLoopActionEnum .ActivateFromColorLoopStartEnhancedHue, direction = ColorControlTrait.ColorLoopDirectionEnum.Increment, time = 30u, // 30 seconds per full cycle startHue = 0u, optionsMask = ColorControlTrait.OptionsBitmap(), optionsOverride = ColorControlTrait.OptionsBitmap() ) }
ExtendedColorControl는 ExtendedColorLightDevice의 선택사항인 Google 특성으로, 색상 이름, RGB 값 또는 색상과 밝기를 단일 단위로 결합하는 통합 부동 소수점 HSV 값을 허용하여 색상 제어를 간소화합니다.
val extendedColorControlTrait = extendedColorLightDevice.googleTraits.extendedColorControl ?: return // 1. Set color by name if ( extendedColorControlTrait.supports( ExtendedColorControl.Command.MoveToColorName ) ) { extendedColorControlTrait.moveToColorName(colorName = "Lavender") } val currentColorName = extendedColorControlTrait.currentName // 2. Set color using 8-bit RGB values (0..255 per channel) // Automatically coordinates brightness (LevelControl) and color (ColorControl) if ( extendedColorControlTrait.supports( ExtendedColorControl.Command.MoveToColorRgb ) ) { extendedColorControlTrait.moveToColorRgb( red = 255u, green = 128u, blue = 0u ) } val currentRed = extendedColorControlTrait.currentRed val currentGreen = extendedColorControlTrait.currentGreen val currentBlue = extendedColorControlTrait.currentBlue // 3. Set color and brightness together using floating-point HSV // hue: 0.0f..360.0f, saturation: 0.0f..1.0f, value (brightness): 0.0f..1.0f if ( extendedColorControlTrait.supports( ExtendedColorControl.Command.MoveToColorHsv ) ) { extendedColorControlTrait.moveToColorHsv( hue = 210.0f, saturation = 0.85f, value = 0.75f ) } val currentHue = extendedColorControlTrait.currentHue val currentSaturation = extendedColorControlTrait.currentSaturation val currentValue = extendedColorControlTrait.currentValue
조명 곡선 관리
조명 곡선은 하루 종일 대상 조명의 밝기와 선택적 색상 온도를 부드럽게 전환하는 자동 일정을 정의합니다. 예를 들어 조명 곡선은 아침에는 조명을 점차 밝게 하고 저녁에는 더 따뜻한 톤으로 어둡게 할 수 있습니다. 밝기만 지원하는 조명 기기 유형(예: 조광 가능 조명)은 밝기 곡선을 따르고 색상 온도를 무시합니다.
LightingCurve
특성은 구조 수준의
Google Home platform 특성입니다. 개별 조명 기기가 아닌 Structure 인스턴스에서 액세스합니다.
특성의 각 일정은 고유한 settingId를 LightingCurveConfig와 페어링하는 LightingCurveSetting로 표현됩니다. 다음 표에서는 LightingCurveConfig의 구성 필드를 설명합니다.
| 필드 | 설명 |
|---|---|
curvePointsList |
시간이 서로 다른 2개 이상의 CurvePoint 항목 시퀀스입니다. 각 지점은 time(CurveTimeOfDay, hours: 0~23, minutes: 0~59), brightnessPercent(0~100), 선택적 colorTemperature(켈빈)을 지정합니다. 특정 지점에 colorTemperature가 지정된 경우 모든 지점에 양수여야 합니다. |
roomId |
대상 방의 ID입니다 (예: room@{uuid}). 해당 방의 호환되는 조광 및 색상 온도 조명에 조명 곡선을 적용합니다. roomId 또는 devices를 지정합니다. |
devices |
TargetDevice 항목 목록이 포함된 TargetDevices 객체입니다. 각 항목에는 기기 id 및 기기 type ID (예: DimmableLight의 경우 home.matter.0000.types.0101, ColorTemperatureLight의 경우 home.matter.0000.types.010c)가 있습니다. devices 또는 roomId를 지정합니다. |
daysOfWeekList |
조명 곡선이 실행되는 요일 (DayOfWeek)입니다. 목록이 비어 있으면 조명 곡선이 매일 실행됩니다. |
adaptive |
조명 곡선이 적응형인지 여부를 나타내는 선택적 불리언입니다. 즉, 일정 예약 기간 동안 켜져 있을 때 대상 조명이 활성 곡선 수준을 재개합니다. false인 경우 조명을 수동으로 변경하면 그날의 나머지 시간 동안 조명이 조명 곡선에서 분리됩니다. true인 경우 일정 예약 기간 동안 조명이 꺼졌다가 다시 켜지면 조명이 조명 곡선에 다시 연결되어 곡선의 현재 밝기와 색상 온도에 맞게 조정되고 그 시점부터 곡선을 따릅니다. |
enabled |
조명 곡선 설정이 활성 상태인지 나타내는 불리언입니다(선택사항). 새 설정을 만들 때 기본값은 true입니다. 업데이트 명령어에서 enabled를 생략하면 enabled 상태가 변경되지 않습니다. |
조명 곡선 설정 읽기
구조에 구성된 조명 곡선을 검사하려면 Structure에서 LightingCurve 특성을 가져와 lightingCurveSettingsList 속성을 읽습니다.
suspend fun readLightingCurves(structure: Structure) {
val lightingCurve = structure.trait(LightingCurve).firstOrNull() ?: return
for (setting in lightingCurve.lightingCurveSettingsList) {
val settingId = setting.settingId
val config = setting.config
println("Setting ID: $settingId, enabled: ${config?.enabled}")
config?.curvePointsList?.forEach { point ->
println(
" Time: ${point.time?.hours}:${point.time?.minutes}, " +
"Brightness: ${point.brightnessPercent}%, " +
"ColorTemp: ${point.colorTemperature}K"
)
}
}
}
조명 곡선 설정 만들기
구조에 새 조명 곡선 일정을 만들려면 CurvePoint 항목이 2개 이상인 LightingCurveConfig, 타겟 조명(roomId 또는 devices로 지정됨), 활성 요일을 구성합니다. 그런 다음 구성을 createLightingCurveSetting()에 전달합니다. 이 명령어는 새 조명 곡선 설정에 할당된 고유한 settingId를 반환합니다.
다음 예에서는 방의 평일 조명 곡선을 만듭니다. 오전 7시에는 따뜻한 2700K에서 30% 밝기로 시작하여 오전 9시에는 더 차가운 4000K에서 80% 로 증가한 다음 오후 9시에는 매우 따뜻한 2200K에서 20% 로 어두워집니다.
suspend fun createRoomLightingCurve(
structure: Structure,
targetRoomId: String
): String? {
val lightingCurve = structure.trait(LightingCurve).firstOrNull() ?: return null
val curvePoints = listOf(
LightingCurveTrait.CurvePoint(
time = LightingCurveTrait.CurveTimeOfDay(hours = 7, minutes = 0),
brightnessPercent = 30,
colorTemperature = 2700
),
LightingCurveTrait.CurvePoint(
time = LightingCurveTrait.CurveTimeOfDay(hours = 9, minutes = 0),
brightnessPercent = 80,
colorTemperature = 4000
),
LightingCurveTrait.CurvePoint(
time = LightingCurveTrait.CurveTimeOfDay(hours = 21, minutes = 0),
brightnessPercent = 20,
colorTemperature = 2200
)
)
val config = LightingCurveTrait.LightingCurveConfig(
curvePointsList = curvePoints,
roomId = targetRoomId,
daysOfWeekList = listOf(
DayOfWeek.MONDAY,
DayOfWeek.TUESDAY,
DayOfWeek.WEDNESDAY,
DayOfWeek.THURSDAY,
DayOfWeek.FRIDAY
),
adaptive = true,
enabled = true
)
// Returns the newly created settingId
return lightingCurve.createLightingCurveSetting(config = config)
}
전체 방 대신 특정 조명 기기를 타겟팅하려면 LightingCurveTrait.TargetDevices를 사용하여 devices 매개변수를 제공합니다.
val targetDevices = LightingCurveTrait.TargetDevices(
devicesList = listOf(
LightingCurveTrait.TargetDevice(
id = dimmableLight.id.id,
type = DimmableLightDevice.TYPE_ID
)
)
)
val deviceCurveConfig = LightingCurveTrait.LightingCurveConfig(
curvePointsList = curvePoints,
devices = targetDevices,
daysOfWeekList = listOf(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY),
adaptive = true,
enabled = true
)
val settingId = lightingCurve.createLightingCurveSetting(
config = deviceCurveConfig
)
조명 곡선 설정 업데이트
기존 조명 곡선을 수정하려면(예: 곡선 지점 변경, 활성 요일 업데이트, 일정 사용 설정 및 중지) 타겟 settingId 및 업데이트된 LightingCurveConfig를 사용하여 updateLightingCurveSetting()를 호출합니다.
suspend fun updateLightingCurve(
structure: Structure,
settingId: String,
updatedConfig: LightingCurveTrait.LightingCurveConfig
) {
val lightingCurve = structure.trait(LightingCurve).firstOrNull() ?: return
lightingCurve.updateLightingCurveSetting(
settingId = settingId,
config = updatedConfig
)
}
조명 곡선 설정 삭제
구조에서 조명 곡선 설정을 삭제하려면 삭제하려는 설정의 settingId를 사용하여 deleteLightingCurveSetting()를 호출합니다.
suspend fun deleteLightingCurve(
structure: Structure,
settingId: String
) {
val lightingCurve = structure.trait(LightingCurve).firstOrNull() ?: return
lightingCurve.deleteLightingCurveSetting(settingId = settingId)
}