iOS용 Home API를 통해 기기 API에 액세스할 수 있습니다. 앱에 다음 패키지를 가져옵니다.
import GoogleHomeSDK
import GoogleHomeTypes
자세한 내용은 iOS의 데이터 모델을 참고하세요.
오류 처리
Home API의 일부 메서드는 HomeError을 발생시키므로 do-catch 블록을 사용하여 이러한 호출에서 HomeError을 포착하는 것이 좋습니다.
HomeError를 처리할 때 code 및 message 필드를 확인하여 무엇이 잘못되었는지 확인합니다.
처리되지 않은 오류가 있으면 앱이 비정상 종료됩니다.
자세한 내용은 오류 처리를 참고하세요.
예시는 기기에 명령어 전송을 참조하세요.
샘플 호출
기기 목록 가져오기
Home 객체에 대한 참조를 사용하여 devices()를 호출하여 액세스 가능한 기기의 Query를 가져옵니다.
Query의 batched() 메서드를 호출합니다. 이 메서드는 기기 메타데이터가 변경될 때마다 홈의 현재 상태를 반영하는 집합을 내보냅니다. 또는 Query.list()를 호출하여 사용 가능한 기기의 스냅샷을 가져옵니다. 이는 batched() 스트림을 구독하고 첫 번째로 내보낸 값을 반환하는 편의 메서드입니다.
Query.stream()는 이름, 방, 구조와 같은 기기 메타데이터 변경 시 새 값을 내보내는 스트림을 생성합니다. 내부적으로는 batched()를 사용하며 변경된 속성만 내보냅니다.
// Get a list of all devices accessible to the user let homeDevices = try await self.home.devices().list()
여기에서 각 기기의 상태에 액세스하고 기기에 명령어를 전송할 수 있습니다.
Home API 버전 1.8에서는 devices() 메서드의 enableMultipartDevices 매개변수를 true로 설정하여 API가 각 멀티파트 기기를 단일 기기로 나타내도록 할 수 있습니다. 자세한 내용은 iOS의 멀티파트 기기를 참고하세요.
기기 유형 가져오기
기기와 연결된 기기 유형을 가져오려면 기기의 types 속성을 읽습니다. 이 속성은 DeviceTypeController를 반환합니다.
DeviceTypeController.subscribe(_:)를 호출하여 특정 기기 유형의 업데이트를 구독합니다.
let devices = try await self.home.devices().list() if let device = devices.first(where: { $0.id == myDeviceId }) { var receivedUpdate1 = false var receivedUpdate2 = false device.types.subscribe(OnOffLightDeviceType.self) .assertNoFailure() .sink { device in if !receivedUpdate1 { receivedUpdate1 = true Task { try await device.matterTraits.onOffTrait?.on() } return } if !receivedUpdate2 { receivedUpdate2 = true return } fatalError("Received unexpected update") } }
기기가 지정된 기기 유형을 지원하지 않으면 즉시 완료되는 Empty
Publisher를 반환합니다.
기기가 특정 기기 유형을 지원하는 경우 get()를 호출하여 해당 유형의 핸들을 가져올 수 있습니다.
if let device = devices.first(where: { $0.id == myDeviceId }) { let _ = await device.types.get(OnOffLightDeviceType.self) }
기기가 지정된 유형을 지원하지 않으면 nil를 반환합니다.
DeviceTypeController.subscribeAll()를 호출하여 DeviceTypeCollection의 Publisher를 가져옵니다.
이 클래스를 사용하면 기기에 특정 기기 유형이 있는지 확인할 수 있습니다.
if let device = devices.first(where: { $0.id == myDeviceId }) { device.types.subscribeAll() .assertNoFailure() .sink { types in let lightDeviceType = types[OnOffLightDeviceType.self] let fanDeviceType = types[FanDeviceType.self] } }
기기 유형 특성 가져오기
기기 유형은 기기를 기능적 부분 (예: Matter의 엔드포인트)으로 분해하므로 특성을 읽는 진입점입니다.
또한 기기에 두 가지 기기 유형이 있고 두 유형 모두에 동일한 특성이 있을 수 있는 경우 특성 충돌을 고려합니다. 예를 들어 기기가 스피커이자 조광 조명인 경우 On/Off 및 Level Control 특성이 각각 두 개씩 있습니다.
기기에 이름이 같은 특성이 두 개 있는 경우에도 특성 충돌이 발생할 수 있습니다. 예를 들어 onOff는 표준 OnOff 특성의 인스턴스를 참조하거나 제조업체에서 정의한 OnOff 특성의 인스턴스를 참조할 수 있습니다. 어떤 특성이 의도되었는지에 관한 잠재적인 모호성을 없애려면 각 기기 유형의 두 특성 컬렉션 중 하나를 통해 특성을 참조하세요.
표준 특성, 즉 Matter 표준 클러스터와 유사한 특성의 경우 matterTraits을 사용합니다. 예를 들어 Dimmable Light 기기 유형의 특정 특성을 가져오려면 다음을 실행합니다.
if let dimmableLightDeviceType = await device.types.get(DimmableLightDeviceType.self) { // Accessing standard trait on the type. let levelControlTrait = dimmableLightDeviceType.matterTraits.levelControlTrait.self }
Google 특성의 경우 googleTraits를 사용합니다.
if let doorbellDeviceType = await device.types.get(GoogleDoorbellDeviceType.self) { // Accessing Google trait on the type. let doorbellPressTrait = doorbellDeviceType.traits[Google.DoorbellPressTrait.self] }
제조업체별 특성에 액세스하려면 traits 속성을 통해 참조하되 제조업체의 패키지 이름을 앞에 붙입니다.
let deviceType = await device1?.types.get(OnOffLightDeviceType.self) // Accessing custom trait on the type. if let spinnerTrait = deviceType?.traits[ExampleOrganization.SpinnerTrait.self] { let rpmVal = spinnerTrait.attributes.rpm }
기기 상태 읽기
기기의 On/Off 특성에서 OnOff 속성을 확인하는 다음 예를 참고하세요.
let lightDevices = devices.filter { $0.types.contains(OnOffLightDeviceType.self) } let light1 = lightDevices.first let lightDeviceTypeOptional = await light1?.types.get(OnOffLightDeviceType.self) if let onOffTrait = lightDeviceTypeOptional?.matterTraits.onOffTrait { let onOffVal = onOffTrait.attributes.onOff }
특정 특성이 있는 기기 목록 가져오기
특정 특성이 있는 기기 목록을 가져오려면 기기, 각 기기의 기기 유형, 각 기기 유형의 특성을 반복해야 합니다. 예를 들어 홈에서 On/Off 특성이 있는 모든 기기의 목록을 가져오려면 다음을 실행합니다.
// Get all light devices that support levelControl var levelControlDevices: [HomeDevice] = [] let allDevices = try await home.devices().list() for device in allDevices { if let deviceType = await device.types.get(OnOffLightDeviceType.self) { if deviceType.traits.contains(Matter.LevelControlTrait.self) { levelControlDevices.append(device) } } }
Home API에서 사용할 수 있는 전체 특성 목록은 iOS의 특성 색인을 참고하세요.
유사한 기기 유형의 기기 목록 가져오기
집에 있는 모든 조명을 나타내는 기기 목록을 가져오려면 다음 단계를 따르세요.
// 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) }
Home API에는 핵심 기기 유형을 나타낼 수 있는 여러 기기 유형이 있습니다. 예를 들어 '조명' 기기 유형은 없습니다. 대신 앞의 예와 같이 조명을 나타낼 수 있는 네 가지 기기 유형이 있습니다. 따라서 홈에 있는 상위 수준의 기기 유형을 포괄적으로 보려면 여러 기기 유형을 포함해야 합니다.
Home API에서 사용할 수 있는 기기 유형 및 특성의 전체 목록은 iOS에서 지원되는 기기 유형을 참고하세요.
기기의 공급업체 이름, 공급업체 ID 또는 제품 ID 가져오기
BasicInformationTrait 특성에는 기기의 공급업체 ID, 제품 ID, 제품 이름, 일련번호와 같은 정보가 포함됩니다.
guard let vendorName = basicInfoTrait.attributes.vendorName else { fatalError("Failed to get vendorName") } guard let vendorID = basicInfoTrait.attributes.vendorID else { fatalError("Failed to get vendorID") } guard let productID = basicInfoTrait.attributes.productID else { fatalError("Failed to get productID") }
기기 제조업체를 위한 클라우드 간 기기 식별
기기 제조업체이고 Cloud-to-cloud 기기를 빌드하는 경우 BasicInformation 특성을 통해 Cloud-to-cloud 기기를 식별하려면 SYNC 응답에 다음 문자열 필드를 포함하면 됩니다.
Connectivity Standards Alliance (Alliance)에서 발급한 공급업체 ID:
"matterOriginalVendorId": "0xfff1",공급업체의 제품을 고유하게 식별하는 제품 식별자:
"matterOriginalProductId": "0x1234",제조업체별 방식으로 구성된 기기의 고유 식별자입니다.
"matterUniqueId": "matter-device-id",
이러한 문자열 필드를 입력할 때 Matter 공급업체 및 제품 ID가 있으면 이를 사용합니다. Alliance 회원이 아니며 이러한 ID가 할당되지 않은 경우 matterOriginalVendorId 및 matterOriginalProductId 필드를 비워두고 matterUniqueId를 식별자로 제공할 수 있습니다.
다음 SYNC 응답 예시에서는 이러한 필드의 사용을 보여줍니다.
{
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"payload": {
"agentUserId": "1836.15267389",
"devices": [
{
"id": "456",
"type": "action.devices.types.LIGHT",
"traits": [
"action.devices.traits.OnOff",
"action.devices.traits.Brightness",
"action.devices.traits.ColorSetting",
],
"willReportState": true,
"deviceInfo": { ... },
"matterOriginalVendorId": "0xfff1",
"matterOriginalProductId": "0x1234",
"matterUniqueId": "matter-device-id",
"otherDeviceIds": [
{
"deviceId": "local-device-id",
}
]
}
]
}
}
자세한 내용은 Cloud-to-cloud SYNC 문서를 참조하세요.
기기 및 특성 메타데이터
Home API의 기기 및 특성에는 연결된 메타데이터가 있으며, 이는 앱에서 사용자 환경을 관리하는 데 도움이 될 수 있습니다.
Home API의 각 특성에는 특성의 온라인 상태 및 지역성(로컬 또는 원격 라우팅)에 관한 정보가 포함된 sourceConnectivity 속성이 포함되어 있습니다.
기기의 기본 유형 가져오기
일부 기기는 Home API를 통해 여러 기기 유형을 표시할 수 있습니다. 사용자에게 기기에 적합한 앱 옵션 (예: 기기 제어 및 추천 자동화)이 표시되도록 하려면 기기 유형이 기기의 기본 유형인지 확인하는 것이 좋습니다.
if let deviceType = await device?.types.get(HumiditySensorDeviceType.self) { if deviceType.metadata.isPrimaryType { print("Humidity Sensor is the primary type on this device.") } else { print("Humidity Sensor isn't the primary type on this device.") } }
특성이 온라인 상태인지 확인하기
connectivityState 속성을 읽어 특성의 연결 상태를 확인합니다.
let levelControlConnectivity = levelControlTrait.metadata.sourceConnectivity .connectivityState
기기에 인터넷 연결이 없는 경우 일부 특성(일반적으로 Google smart home 특성)이 오프라인으로 표시될 수 있습니다. 이러한 특성은 클라우드 기반이며 로컬 라우팅이 없기 때문입니다.
기기 연결 확인
일부 기기는 여러 기기 유형을 지원하므로 기기의 연결은 실제로 기기 유형 수준에서 확인됩니다. 반환되는 상태는 해당 기기의 모든 특성에 대한 연결 상태의 조합입니다.
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
}
특성의 네트워크 라우팅 확인
특성의 지역성은 Home API에서도 사용할 수 있습니다. dataSourceLocality는 특성이 원격으로 (클라우드를 통해), 로컬로 (로컬 허브를 통해) 또는 P2P로 (허브 없이 기기 간 직접) 라우팅되는지 여부를 나타냅니다.
알 수 없는 지역 값 unspecified은 예를 들어 앱이 부팅 중이고 아직 기기 연결을 위한 허브나 서버에 도달하지 않은 경우에 가능합니다. 이러한 기기는 연결할 수 없으며 명령어 또는 이벤트의 상호작용 요청이 실패합니다. 이러한 기기를 처리하는 방법은 클라이언트가 결정합니다.
let levelControlLocality = levelControlTrait.metadata.sourceConnectivity .dataSourceLocality
기기의 네트워크 라우팅 확인하기
연결과 마찬가지로 지역성은 기기 유형 수준에서 확인됩니다. 반환되는 상태는 해당 기기의 모든 특성에 대한 지역성의 조합입니다.
let lightLocality = dimmableLightDeviceType.metadata.sourceConnectivity.dataSourceLocality
mixed 상태는 partiallyOnline 연결과 유사한 시나리오에서 관찰될 수 있습니다. 일부 특성은 클라우드 기반이고 다른 특성은 로컬입니다.
기기 이름 변경하기
setName(_:) 메서드를 호출하여 기기 이름을 변경합니다.
let updatedDevice = try await theDevice.setName("new device name")
기기 이름을 변경하면 원래 HomeDevice 구조체는 동일하게 유지되고 변경사항은 반환된 업데이트된 HomeDevice 객체에 반영됩니다.
이름이 유니코드 코드 포인트(문자) 한도인 60자를 초과하면 잘리고 오류가 발생하지 않습니다. 개발자는 긴 이름을 처리할 책임이 있으며, 예를 들어 이름이 잘린다는 사실을 사용자에게 알릴지 여부를 결정할 수 있습니다.
기기의 그룹 멤버십 확인
실제 기기는 하나 이상의 기기 그룹에 속할 수 있습니다. 기기가 속한 그룹을 검사하려면 기기에서 GroupMembershipTrait를 확인합니다.
if let trait = await device.traits.get(Google.GroupMembershipTrait.self) {
for groupId in trait.attributes.groupObjectIdsArray {
print("Device belongs to group: \(groupId)")
}
}
DeviceGroup에서 지원하는 기기 유형을 검사하고 그룹에 명령어를 단일 항목으로 전송하려면 기기 그룹 제어를 참고하세요.