> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/home-assistant/core/llms.txt
> Use this file to discover all available pages before exploring further.

# Automations

> Understanding automations in Home Assistant Core

Automations are the heart of Home Assistant's smart home capabilities. They allow you to automatically respond to events and conditions in your home by executing actions.

## What is an Automation?

An automation is a rule that consists of three main components:

1. **Triggers**: What starts the automation
2. **Conditions**: Optional checks that must pass for actions to execute
3. **Actions**: What happens when triggered (and conditions pass)

<CodeGroup>
  ```yaml Example Automation theme={null}
  automation:
    - alias: "Turn on lights at sunset"
      trigger:
        - platform: sun
          event: sunset
      condition:
        - condition: state
          entity_id: binary_sensor.someone_home
          state: "on"
      action:
        - service: light.turn_on
          target:
            entity_id: light.living_room
  ```
</CodeGroup>

## Automation Structure

Automations in Home Assistant are represented as entities with the domain `automation`. The automation component is implemented in `homeassistant/components/automation/`.

### Automation Entity

Each automation is an entity that extends `ToggleEntity` and `RestoreEntity`:

<CodeGroup>
  ```python homeassistant/components/automation/__init__.py:1-40 theme={null}
  """Allow to set up simple automation rules via the config file."""

  from homeassistant.helpers.entity import ToggleEntity
  from homeassistant.helpers.entity_component import EntityComponent
  from homeassistant.helpers.restore_state import RestoreEntity

  class BaseAutomationEntity(ToggleEntity, RestoreEntity, ABC):
      """Base class for automation entities."""
  ```
</CodeGroup>

### Key Properties

* `entity_id`: Format is `automation.<automation_name>`
* `state`: Either "on" (enabled) or "off" (disabled)
* `last_triggered`: Timestamp of last execution
* `mode`: Execution mode (single, restart, queued, parallel)

## Triggers

Triggers define when an automation should run. Common trigger types include:

### State Triggers

Fire when an entity changes state:

```yaml theme={null}
trigger:
  - platform: state
    entity_id: sensor.temperature
    from: "20"
    to: "25"
```

### Time Triggers

Fire at specific times:

```yaml theme={null}
trigger:
  - platform: time
    at: "07:00:00"
```

### Event Triggers

Fire when an event occurs:

```yaml theme={null}
trigger:
  - platform: event
    event_type: custom_event
```

### Numeric State Triggers

Fire when a numeric value crosses a threshold:

```yaml theme={null}
trigger:
  - platform: numeric_state
    entity_id: sensor.temperature
    above: 25
```

<Info>
  Home Assistant supports many more trigger types including sun, zone, template, webhook, and more.
</Info>

## Conditions

Conditions are optional checks that must evaluate to true for the automation's actions to execute.

### Common Condition Types

```yaml theme={null}
condition:
  # State condition
  - condition: state
    entity_id: light.living_room
    state: "off"
  
  # Numeric state condition
  - condition: numeric_state
    entity_id: sensor.temperature
    below: 20
  
  # Time condition
  - condition: time
    after: "22:00:00"
    before: "07:00:00"
  
  # Template condition
  - condition: template
    value_template: "{{ state_attr('climate.living_room', 'temperature') > 20 }}"
```

## Actions

Actions define what happens when the automation is triggered (and conditions pass).

### Service Calls

```yaml theme={null}
action:
  - service: light.turn_on
    target:
      entity_id: light.living_room
    data:
      brightness: 255
      color_temp: 400
```

### Sequences

Actions can include delays and multiple steps:

```yaml theme={null}
action:
  - service: light.turn_on
    target:
      entity_id: light.hallway
  - delay: "00:01:00"
  - service: light.turn_off
    target:
      entity_id: light.hallway
```

### Conditional Actions

Use `choose` for conditional action execution:

```yaml theme={null}
action:
  - choose:
      - conditions:
          - condition: state
            entity_id: sun.sun
            state: "below_horizon"
        sequence:
          - service: light.turn_on
            data:
              brightness: 255
    default:
      - service: light.turn_on
        data:
          brightness: 128
```

## Automation Modes

Automations support different execution modes when triggered while already running:

| Mode       | Behavior                                        |
| ---------- | ----------------------------------------------- |
| `single`   | Don't start a new run (default)                 |
| `restart`  | Stop current run and start new one              |
| `queued`   | Queue new run to execute after current finishes |
| `parallel` | Start new run in parallel with existing runs    |

```yaml theme={null}
automation:
  - alias: "Example"
    mode: restart
    max: 10  # Maximum parallel or queued runs
    trigger:
      # ...
```

## Variables

Automations can use variables for dynamic behavior:

```yaml theme={null}
automation:
  - alias: "Variable Example"
    trigger:
      - platform: state
        entity_id: sensor.temperature
    variables:
      threshold: 25
      notify: true
    action:
      - service: notify.notify
        data:
          message: "Temperature is {{ trigger.to_state.state }}°C"
```

### Trigger Variables

Variables available in automation context:

* `trigger.platform`: Trigger platform that fired
* `trigger.entity_id`: Entity that triggered
* `trigger.from_state`: Previous state object
* `trigger.to_state`: New state object
* `trigger.event`: Event object (for event triggers)

## Managing Automations

### Services

Automations respond to standard services:

```yaml theme={null}
# Turn on (enable) automation
service: automation.turn_on
target:
  entity_id: automation.my_automation

# Turn off (disable) automation
service: automation.turn_off
target:
  entity_id: automation.my_automation

# Toggle automation
service: automation.toggle
target:
  entity_id: automation.my_automation

# Trigger automation manually
service: automation.trigger
target:
  entity_id: automation.my_automation
data:
  skip_condition: true
```

### Reload Automations

```yaml theme={null}
service: automation.reload
```

## Automation Helper Functions

The automation component provides helper functions for working with automations:

<CodeGroup>
  ```python homeassistant/components/automation/__init__.py:238-296 theme={null}
  @callback
  def automations_with_entity(hass: HomeAssistant, entity_id: str) -> list[str]:
      """Return all automations that reference the entity."""
      return _automations_with_x(hass, entity_id, "referenced_entities")

  @callback
  def automations_with_device(hass: HomeAssistant, device_id: str) -> list[str]:
      """Return all automations that reference the device."""
      return _automations_with_x(hass, device_id, "referenced_devices")

  @callback
  def automations_with_area(hass: HomeAssistant, area_id: str) -> list[str]:
      """Return all automations that reference the area."""
      return _automations_with_x(hass, area_id, "referenced_areas")
  ```
</CodeGroup>

## Tracing and Debugging

Home Assistant provides tracing capabilities for automations:

```yaml theme={null}
automation:
  - alias: "Debug Example"
    trace:
      stored_traces: 10  # Number of traces to store
    trigger:
      # ...
```

Traces show:

* Execution path through the automation
* Trigger data
* Variable values at each step
* Action results
* Timing information

## Blueprints

Blueprints allow you to create reusable automation templates:

```yaml theme={null}
blueprint:
  name: Motion-activated Light
  description: Turn on a light when motion is detected
  domain: automation
  input:
    motion_entity:
      name: Motion Sensor
      selector:
        entity:
          domain: binary_sensor
    light_target:
      name: Light
      selector:
        target:
          entity:
            domain: light

automation:
  trigger:
    - platform: state
      entity_id: !input motion_entity
      to: "on"
  action:
    - service: light.turn_on
      target: !input light_target
```

## Creating Automations Programmatically

```python theme={null}
from homeassistant.components import automation

# Check if automation is enabled
is_enabled = automation.is_on(hass, "automation.my_automation")

# Get entities referenced by automation
entities = automation.entities_in_automation(
    hass, "automation.my_automation"
)

# Get automations that reference an entity
automations = automation.automations_with_entity(
    hass, "light.living_room"
)
```

## Best Practices

<Card title="Meaningful Names" icon="tag">
  Use descriptive aliases that explain what the automation does.
</Card>

<Card title="Use Conditions" icon="filter">
  Avoid unnecessary action executions by using appropriate conditions.
</Card>

<Card title="Choose the Right Mode" icon="play">
  Select an execution mode that matches your automation's behavior requirements.
</Card>

<Card title="Enable Tracing" icon="bug">
  Use trace storage for debugging complex automations.
</Card>

<Card title="Test Thoroughly" icon="vial">
  Test automations manually using the trigger service before relying on them.
</Card>

## Events

Automations fire events that can be used for monitoring:

* `automation_triggered`: Fired when an automation is triggered
* `automation_reloaded`: Fired when automations are reloaded

```python theme={null}
EVENT_AUTOMATION_TRIGGERED = "automation_triggered"
EVENT_AUTOMATION_RELOADED = "automation_reloaded"
```

## Related Resources

<CardGroup cols={2}>
  <Card title="Scripts" icon="scroll" href="/concepts/scripts">
    Learn about reusable action sequences
  </Card>

  <Card title="Scenes" icon="image" href="/concepts/scenes">
    Understand scene activation and management
  </Card>

  <Card title="Triggers" icon="bolt" href="/integrations/triggers">
    Explore available trigger platforms
  </Card>

  <Card title="Conditions" icon="filter" href="/integrations/conditions">
    Learn about condition types
  </Card>
</CardGroup>
