iOS의 멀티파트 기기 자동화

자동화는 멀티파트 기기를 사용하지 않는 자동화와 마찬가지로 멀티파트 기기를 참조할 수 있습니다.

먼저 평소와 같이 구성요소 파트를 획득합니다. 멀티파트 기기 작업 방법은 멀티파트 기기를 참고하세요.

그런 다음 자동화에서 사용할 각 파트에 대해 자동화 시작, 조건, 작업에서 파트를 참조할 수 있는 AutomationPartPath를 만듭니다.

//  Obtain a reference to the device:
let multipartDevices = try await self.home.devices(enableMultipartDevices: true).list()

let light = multipartDevices.first(where: {
  $0.parts.contains(OnOffLightDeviceType.self) && $0.structureID == structure.id
})

let lightDeviceType = await light.parts.get(OnOffLightDeviceType.self)

let lightPartPath = light.automationPart(lightDeviceType)

자동화 작업은 일반적으로 기기와 기기 유형을 매개변수로 사용합니다. 하지만 구성요소 파트 기기를 참조하는 자동화 작업(여기서도 AutomationPartPath 사용)에는 AutomationPartPath만 필요합니다. AutomationPartPath에는 구성요소 기기 참조 외에도 기기 유형에 대한 참조가 이미 포함되어 있기 때문입니다.

예를 들어 자동화 API에서 Refrigerator 기기 유형은 멀티파트 기기로 취급될 수 있습니다. TemperatureControlledCabinetDevice 유형의 냉동고나 표준 캐비닛과 같은 여러 하위 부품 캐비닛을 포함할 수 있는 루트 RefrigeratorDevice로 구성됩니다.

냉장고 자동화를 빌드하려면 주로 다음 두 가지 표준 Matter 특성과 상호작용합니다.

  • RefrigeratorAlarm: state 필드의 doorOpen 속성을 통해 문 상태 알람을 노출합니다.
  • RefrigeratorAndTemperatureControlledCabinetMode: 모드를 읽고 명령할 수 있습니다. 예를 들어 changeToMode과 같은 명령어를 실행하여 LowEnergy, RapidCool 또는 LowNoise과 같은 모드로 전환합니다.

이 자동화 예시는 냉장고 문이 열릴 때 트리거됩니다. 문이 2분 이상 열려 있으면 자동화가 스마트 스피커에 음성 알림을 브로드캐스트하고, 주방 조명을 깜박이고, 푸시 알림을 전송합니다. 이 자동화는 기기의 냉장고 칸에만 영향을 미치며 냉동고 칸 (있는 경우)은 무시합니다.

import GoogleHomeSDK
import GoogleHomeTypes

typealias RefrigeratorAlarmTrait = Matter.RefrigeratorAlarmTrait
typealias OnOffTrait = Matter.OnOffTrait

// Fetch devices using the multipart device model.
let multipartDevices = try await self.home.devices(enableMultipartDevices: true).list()

// Obtain a reference to the refrigerator device.
guard let refrigeratorDevice = multipartDevices.first {
    $0.types.contains(TemperatureControlledCabinetDeviceType.self) &&
    $0.traits.contains(Matter.RefrigeratorAndTemperatureControlledCabinetModeTrait.self) &&
    $0.traits.contains(Matter.RefrigeratorAlarmTrait.self)
  }

let refrigeratorDeviceType = await refrigeratorDevice.parts.get(RefrigeratorDeviceType.self).first

// Get all temperature-controlled cabinet parts of the refrigerator
let cabinets = refrigeratorDeviceType.parts(type: TemperatureControlledCabinetDeviceType.self)

// Find the cabinet part with the 'refrigerator' semantic tag
let refrigeratorCabinet = cabinets.first {
  $0.metadata.tags.contains(SemanticTag.Refrigerator.refrigerator)
}
var cabinetPartPath = refrigeratorDevice.automationPart(refrigeratorCabinet)

let structure = home.structures().list().first

let speaker = multipartDevices.first(where: {
        $0.types.contains(SpeakerDeviceType.self) && $0.structureID == structure.id
      })

let refrigeratorDoorAlert = automation(
  name: "Refrigerator Door Open Alert",
  description: "Warn when the refrigerator door has been open for over 2 min."
) {
  // 1. Starter: Monitor the refrigerator door alarm trait
  let alarmStarter = starter(
    cabinetPartPath,
    RefrigeratorAlarmTrait.self
  )

  alarmStarter

  // 2. Condition: Ensure the 'doorOpen' alarm remains active for 120 seconds
  condition(for: .seconds(120)) {
    alarmStarter.state.doorOpen.equals(true)
  }

  // 3. Actions: Execute parallel reactions
  parallel {
    // Broadcast warning to household speakers
    action(speaker, SpeakerDeviceType.self) {
      Google.AssistantBroadcastTrait.broadcast(msg: "The refrigerator door has been left open!")
    }

    // Push a notification alerts to home members' mobile devices
    action(structure) {
      Google.NotificationTrait.sendNotifications(
        title: "Fridge Alert",
        body: "The refrigerator door has been open for over 2 min.",
        optInMemberEmailsArray: ["222larabrown@gmail.com"]
      )
    }
  }
}

다음 예에서는 집에 아무도 없음을 감지하면 냉장고를 저에너지 모드로 전환합니다.

import GoogleHomeSDK
import GoogleHomeTypes

typealias AreaPresenceStateTrait = Google.AreaPresenceStateTrait
typealias RefrigeratorAndTemperatureControlledCabinetModeTrait = Matter.RefrigeratorAndTemperatureControlledCabinetModeTrait

let structure = home.structures().list().first()

// Fetch devices using the multipart device model.
let devices = try await self.home.devices(enableMultipartDevices: true).list()

// Obtain a reference to the refrigerator device.
guard let refrigeratorDevice = multipartDevices.first {
    $0.types.contains(TemperatureControlledCabinetDeviceType.self) &&
    $0.traits.contains(Matter.RefrigeratorAndTemperatureControlledCabinetModeTrait.self) &&
    $0.traits.contains(Matter.RefrigeratorAlarmTrait.self)
  }

let refrigeratorDeviceType = await refrigeratorDevice.parts.get(RefrigeratorDeviceType.self)

// Get all temperature-controlled cabinet parts of the refrigerator
let cabinets = refrigeratorDeviceType.parts(type: TemperatureControlledCabinetDeviceType.self)

// Find the cabinet part with the 'refrigerator' semantic tag
let refrigeratorCabinet = cabinets.first {
  $0.metadata.tags.contains(SemanticTag.Refrigerator.refrigerator)
}

let cabinetPartPath = refrigeratorDevice.automationPart(refrigeratorCabinet)

let refrigeratorEcoMode = automation(
  name: "Refrigerator Eco Mode",
  description: "Automatically changes refrigerator to low energy mode when house is vacant."
) {
  // 1. Starter: Monitor household presence changes
  let presenceStarter = starter(structure, AreaPresenceStateTrait.self)

  presenceStarter

  // 2. Condition: Verify presence state transitions to vacant
  condition {
    presenceStarter.presenceState.equals(.presenceStateVacant)
  }
  // 3. Action: Set refrigerator cabinet Mode to 'Low Energy' (commonly option index 1)
  action(cabinetPartPath) {
    RefrigeratorAndTemperatureControlledCabinetModeTrait.changeToMode(newMode: 1)
  }
}