> Documentation index: https://developers.home.google.com/apis/ios/automation/llms.txt

Automations are a way to automate tasks and device settings in a home.
Automations have been available in the Google Home ecosystem as Routines in the
Google Home app (GHA) and through the automation script editor on
Google Home for web.

Now, Automations in the Google Home ecosystem are available through the Home
APIs for iOS. They use the same basic concepts used in GHA
Routines and the script editor, but with enhanced features and
capabilities only possible through the Home APIs for iOS, including:

- Access to all Matter standard and smart home traits for a device, as presented in the Home APIs for iOS.
- Support for sequential, parallel, and select execution flows.

Automations are written using Automation DSL for iOS, a domain-specific language
designed for building automations in Swift.

> [!NOTE]
> **Note:** Automation API supports most traits in the Home APIs for iOS, but support may be limited to specific attributes, events, and commands for a given trait. See [Automation API trait support on iOS](https://developers.home.google.com/apis/ios/automation/supported-traits.md.txt) for more details.

Any traits and types that you intend to use in your app with the Automation APIs
must be registered at initialization. See
[Initialize the home](https://developers.home.google.com/apis/ios/initialize.md.txt).

## Guidance if user revokes full permissions

If the user revokes full permissions, all existing automations will
stop working. Also, if the user revokes access to specific devices, then
starters, conditions, and actions associated with those devices will
stop working.

**Each time the app starts, be sure to check that the permissions
are still in effect. If they have been revoked, then be sure that all previous
data are removed, including any data cached in the application.**

When structure access is revoked, a
[`StructureAccessRevokedEvent`](https://developers.home.google.com/partners/services/camera/cloud-events#structure_grants)
is delivered to your cloud backend. Refer to
[Structure grants](https://developers.home.google.com/partners/services/camera/cloud-events#structure_grants) for
the end-to-end partner cloud and mobile app revocation workflow.

## Developer journey

The Automation API is one portion of a larger development journey. It comes
after integrating the Structure and Device APIs to ensure that when a user wants
to use an automation, they can do so.

1. The developer plans their automation, and defines it using the Automation DSL.
2. The developer embeds the automation definition in a Swift iOS app.
3. The app presents automations to a user based on information about their devices, including traits, attributes, commands, and events, gathered using the Discovery API or Device API.
   - With the Discovery API, the app can generate a draft automation customized to the device types and traits present in the user's structure, with or without the user's input.
   - The Device API can provide most of the same information as the Discovery API, but it's not optimized for automation use cases. See Compare the [Device API and Discovery API](https://developers.home.google.com/apis/ios/automation/discovery.md.txt#compare_the_device_api_and_discovery_api) for more details.
4. The app creates the actual automation that is keyed to the selected structure.
5. The automation is now available in the user's structure and can be executed, stopped, updated, or deleted.

The user may create new instances of the automation at any time, selecting a
different structure or, depending on the app logic, perhaps a different set of
devices. Each time they do so, the app generates a new instance of the
automation.

In the most basic scenario, you might suggest to your users a predefined
automation that performs a relatively basic task. Alternatively, you could
present a skeleton of an automation that the user customizes to meet their
needs. Or you could write an open-ended automation editor that allows the user
to construct complex automations using all the building blocks available in the
Automation API.

### Create and manage automations

To create and manage automations on iOS:

1. Include all device types and traits referenced by your automations in `referencedAutomationTypes` when configuring the `GoogleHomeSDK`. For configuration details, see [Initialize the home](https://developers.home.google.com/apis/ios/initialize.md.txt).
2. Build your [`DraftAutomation`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/GoogleHomeSDK.md.txt#draftautomation) using the Automation DSL and call standard [`AutomationManager`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/Protocols/AutomationManager.md.txt) methods on the [`Structure`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/Structs/Structure.md.txt) object:
   - Call [`createAutomation(_:)`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/Protocols/AutomationManager.md.txt#createautomation_:) to create an automation in the structure.
   - Call [`listAutomations()`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/Protocols/AutomationManager.md.txt#listautomations) to list or retrieve automations created by your app in the structure.
   - Call [`update(_:)`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/Protocols/Automation.md.txt#update_:) on an [`Automation`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/Protocols/Automation.md.txt) instance to update its metadata or replace its `automationGraph`.
   - Call [`deleteAutomation(_:)`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/Protocols/AutomationManager.md.txt#deleteautomation_:) or [`deleteAutomation(id:)`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/Protocols/AutomationManager.md.txt#deleteautomationid:) to remove an automation.

```swift
let draft = automation(
  name: "Turn on light",
  description: "Turn on light2 when light1 turns on."
) {
  let starterNode = starter(
    light1, OnOffLightDeviceType.self, Matter.OnOffTrait.self)
  starterNode
  condition {
    starterNode.onOff.equals(true)
  }
  action(light2, OnOffLightDeviceType.self) {
    Matter.OnOffTrait.on()
  }
}

let createdAutomation = try await structure.createAutomation(draft)
```

For complete DSL syntax and CRUD code examples, see [Build an automation on
iOS](https://developers.home.google.com/apis/ios/automation/build).

## Automation suggestions

[Implemented in Sample App for iOS](https://developers.home.google.com/apis/ios/sample-app/build.md.txt)

The Home APIs can suggest automations for a
[`Structure`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/Structs/Structure.md.txt) based on factors such
as the device types present in the space.

Automation suggestions are represented by the
[`AutomationSuggestion`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/Structs/AutomationSuggestion.md.txt)
class.

The [`Structure`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/Structs/Structure.md.txt) interface
provides the
[`suggestions()`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/Structs/Structure.md.txt#suggestions:)
function, which returns a `Set` of all the automation suggestions.

The
[`likeSuggestion()`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/Structs/Structure.md.txt#/s:13GoogleHomeSDK9StructureV14likeSuggestion12suggestionIDySS_tYaKF)
and
[`dislikeSuggestion()`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/Structs/Structure.md.txt#/s:13GoogleHomeSDK9StructureV17dislikeSuggestion12suggestionIDySS_tYaKF)
methods are intended to be wired to
and
UI controls that the user can tap
to provide feedback.

A third method,
[`clearSuggestionFeedback`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/Structs/Structure.md.txt#clearsuggestionfeedbacksuggestionid:),
lets the user remove their feedback for a suggested automation.

User feedback influences future suggestions.

This example demonstrates how to asynchronously retrieve the list of
[`AutomationSuggestion`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/Structs/AutomationSuggestion.md.txt)
objects for a [`Structure`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/Structs/Structure.md.txt)
using `await`, and record or clear user feedback using
[`likeSuggestion(suggestionID:)`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/Structs/Structure.md.txt#/s:13GoogleHomeSDK9StructureV14likeSuggestion12suggestionIDySS_tYaKF),
[`clearSuggestionFeedback(suggestionID:)`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/Structs/Structure.md.txt#clearsuggestionfeedbacksuggestionid:),
and
[`dislikeSuggestion(suggestionID:)`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/Structs/Structure.md.txt#/s:13GoogleHomeSDK9StructureV17dislikeSuggestion12suggestionIDySS_tYaKF).

```swift
import Combine
import GoogleHomeSDK
import SwiftUI

@MainActor
public final class AutomationSuggestionsViewModel: ObservableObject {
  private let structure: Structure

  public init(structure: Structure) {
    self.structure = structure
  }

  public func loadAndGiveFeedback() {
    Task {
      do {
        // 1. Fetch suggestions from structure
        let suggestions: [AutomationSuggestion] = try await structure.suggestions()
        guard let firstSuggestion = suggestions.first else { return }

        // Extract string suggestion ID
        let suggestionID: String = firstSuggestion.id

        // 2. Like the suggestion (thumbs up)
        try await structure.likeSuggestion(suggestionID: suggestionID)

        // 3. Clear previous feedback if the user toggled it off
        try await structure.clearSuggestionFeedback(suggestionID: suggestionID)

        // 4. Dislike the suggestion (thumbs down)
        try await structure.dislikeSuggestion(suggestionID: suggestionID)
      } catch {
        // Handle HomeError if suggestion fetching or feedback submission fails
        print("Failed to update suggestion feedback: \(error)")
      }
    }
  }
}
```

## Dynamic command parameters

Dynamic command parameters allow developers to construct action parameters that
resolve dynamically at runtime rather than relying strictly on static, constant
values. This enables two primary capabilities:

- References that pass the value of a property from a starter (such as an event payload) or state reader node, or from local variables declared within the automation flow.
- Expressions that capture runtime dynamic values (such as an event property or state value) and pass the dynamic value directly into a command parameter.

### Use case

Bind a physical rotary switch that sends a multi-press event to a dimmable
light. The count of clicks is the dynamic value passed into a `LevelControl`
step command at runtime.

### How dynamic parameters work

In the Automation DSL on iOS, the
[`Parameter`](https://developers.home.google.com/reference/swift/GoogleHomeSDK/Structs/Parameter.md.txt) struct
provides initializers for static constant values (`value:`), dynamic
expressions and variable references (`expression:`), and string reference
identifiers (`reference:`):

```swift
// Static constant value
Parameter(field: field, value: constantValue)

// Dynamic expression or variable reference
Parameter(field: field, expression: dynamicExpression)
Parameter(field: field, expression: myVar.reference)

// String reference identifier
Parameter(field: field, reference: "reference_id")
```

### Validation rules

Dynamic command parameters follow these validation constraints:

- Dynamic parameters are assumed to be structurally valid during discovery because discovery APIs only evaluate concrete value constraints for static arguments.
- Reference or expression nodes must appear upstream in the automation graph before they are referenced in a downstream command action.

### Use dynamic command parameters on iOS

In Swift, construct a `Parameter` wrapper using either the `expression` or
`reference` parameter and set them inside the action command scope.

Pass dynamic expressions on event fields directly to command parameters:

```swift
import GoogleHomeSDK

let rotaryAutomation = automation(
  name: "Rotary switch dimmer",
  description: "Adjust light brightness using rotary clicks",
) {
  let rotaryStarter = starter(
    rotaryDevice,
    GenericSwitchDeviceType.self,
    Matter.SwitchTrait.MultiPressCompleteEvent.self,
  )
  rotaryStarter

  let clickCountExpression = rotaryStarter.totalNumberOfPressesCounted

  action(lightDevice, DimmableLightDeviceType.self) {
    command(Matter.LevelControlTrait.StepCommand.self) {
      $0.set(
        Parameter(
          field:
            Matter.LevelControlTrait.StepCommand.CommandRequestFields.stepMode,
          value: Matter.LevelControlTrait.StepModeEnum.up,
        )
      )
      $0.set(
        Parameter(
          field:
            Matter.LevelControlTrait.StepCommand.CommandRequestFields.stepSize,
          expression: clickCountExpression,
        )
      )
    }
  }
}
```

Alternatively, declare a local variable inside the builder block and assign the
expression using `.assign()`:

```swift
import GoogleHomeSDK

let rotaryAutomation = automation(
  name: "Rotary switch dimmer",
  description: "Adjust light brightness using rotary clicks",
) {
  let rotaryStarter = starter(
    rotaryDevice,
    GenericSwitchDeviceType.self,
    Matter.SwitchTrait.MultiPressCompleteEvent.self,
  )
  rotaryStarter

  let clickCountVarReference = variable<UInt8>()
  clickCountVarReference.assign(rotaryStarter.totalNumberOfPressesCounted)

  action(lightDevice, DimmableLightDeviceType.self) {
    command(Matter.LevelControlTrait.StepCommand.self) {
      $0.set(
        Parameter(
          field:
            Matter.LevelControlTrait.StepCommand.CommandRequestFields.stepMode,
          value: Matter.LevelControlTrait.StepModeEnum.up,
        )
      )
      $0.set(
        Parameter(
          field:
            Matter.LevelControlTrait.StepCommand.CommandRequestFields.stepSize,
          expression: clickCountVarReference.reference,
        )
      )
    }
  }
}
```

### Type constraints

Ensure that the types of variables and expressions align with the receiving
command parameter's required Matter schema type
definition (such as `UShort`, `UByte`, or `UInt8`).

## Resource limits

The following limits apply to automations in the Home APIs:

| Metric | Limit |
|---|:---:|
| Maximum number of automations per structure | 64 |
| Maximum number of nodes per automation | 128 |
| Maximum number of expression nodes per automation | 64 |
| Maximum number of automation instances per structure | 1024 |
| Maximum number of automation instances per developer per structure | 64 |
| Maximum number of executions per structure per day | 1024 |
| Maximum number of executions per developer per structure per day | 128 |
[*Table: Automation API resource limits*]

> [!NOTE]
> **Note:** These limits are the current defaults, and are subject to change by Google.

## Local automation execution

Certain automations can execute locally, allowing them to function even if the
hub loses its connection to the cloud.

For an automation to be eligible for local execution:

1. All devices that are referenced in starters, state readers, conditions, and actions must be local Matter devices in the structure. If the automation references any Cloud-to-cloud devices, it isn't eligible for local execution.
2. Only Matter device traits and the `Time` trait are supported locally. Synthetic and simplified traits aren't supported.
3. An online hub must receive the automation from the Google Home cloud before losing cloud connectivity, and all referenced devices must be locally reachable from that hub. Google Home automatically syncs automations from the cloud to an online hub when you create or update them, or when the hub connects to the cloud after startup or an outage.

> [!NOTE]
> **Note:** In a home with more than one hub, each locally executed automation runs on only one of the hubs.