Automazioni di più dispositivi su iOS

Un'automazione può fare riferimento a dispositivi multipart in modo simile a un'automazione che non utilizza dispositivi multipart.

Innanzitutto, ottieni le parti componenti come faresti normalmente. Per scoprire come utilizzare i dispositivi multipart, consulta la pagina Dispositivi multipart.

Poi, per ogni parte che vuoi utilizzare nell'automazione, crea un AutomationPartPath, che ti consente di fare riferimento alla parte negli avviatori, nelle condizioni e nelle azioni.

//  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)

Un'altra cosa da notare è che le azioni di automazione in genere accettano un dispositivo e un tipo di dispositivo come parametri. Tuttavia, un'azione di automazione che fa riferimento a un dispositivo parte componente, utilizzando di nuovo un AutomationPartPath, richiede solo l' AutomationPartPath, perché quest'ultimo contiene già un riferimento al tipo di dispositivo oltre al riferimento al dispositivo componente.AutomationPartPath

Ad esempio, nell'API Automation, un tipo di dispositivo Refrigerator può essere trattato come un dispositivo multipart. È costituito da un RefrigeratorDevice root che può contenere più armadietti secondari, come congelatori o armadietti standard di tipo TemperatureControlledCabinetDevice.

Per creare automazioni per il frigorifero, interagisci principalmente con due tratti Matter standard:

  • RefrigeratorAlarm: espone gli allarmi di stato della porta tramite l'attributo doorOpen del campo state.
  • RefrigeratorAndTemperatureControlledCabinetMode: consente di leggere e comandare le modalità. Ad esempio, l'esecuzione di comandi come changeToMode per passare a modalità come LowEnergy, RapidCool o LowNoise.

Questa automazione di esempio viene attivata quando viene aperta la porta del frigorifero. Se la porta rimane aperta per più di due minuti, l'automazione trasmette una notifica vocale sugli smart speaker, accende le luci della cucina e invia una notifica push. Tieni presente che questa automazione influisce solo sul vano frigorifero del dispositivo, ignorando il vano congelatore (se presente):

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"]
      )
    }
  }
}

L'esempio seguente passa il frigorifero alla modalità a basso consumo energetico quando rileva che non c'è nessuno in casa.

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)
  }
}