Skip to main content

Python CLI and library for managing Home Assistant automations

Project description

Home Assistant Automation Management

A Python CLI and library for managing Home Assistant automations programmatically.

Designed for AI Assistants: This toolkit provides clean APIs that AI assistants (like Claude Code, GitHub Copilot) can use to help users create and manage Home Assistant automations from natural language descriptions.

Architecture

User (natural language) โ†’ AI Assistant โ†’ Python Toolkit โ†’ Home Assistant

The AI assistant understands what the user wants, and this toolkit provides the APIs to discover devices, generate automation configurations, and manage automations.

Features

Device Discovery & Search

  • ๐Ÿ” Discover all devices in your Home Assistant
  • ๐Ÿ”Ž Search devices by name (supports Chinese and English)
  • ๐Ÿท๏ธ Filter by domain (light, sensor, switch, etc.)
  • ๐Ÿ“ Filter by area/room
  • ๐Ÿ’พ Smart caching for performance

Automation Creation & Management (Primary Feature)

  • ๐Ÿš€ Create automations directly via Home Assistant REST API
  • ๐Ÿค– AI-friendly API for automation configuration
  • โœ… Validate automation structure
  • โšก Immediate feedback and error handling
  • ๐ŸŒ Support for Chinese and English
  • ๐Ÿ”„ Automatic reload after changes

Automation Management

  • ๐Ÿ“‹ List and view automations with detailed information
  • โšก Enable/disable automations
  • ๐Ÿ”„ Toggle automation states
  • โ–ถ๏ธ Manually trigger automations
  • ๐Ÿ”„ Reload automations from YAML

Developer Experience

  • ๐ŸŽจ Beautiful terminal output with Rich
  • ๐Ÿ“Š JSON output for scripting
  • ๐Ÿ Python API for programmatic access
  • ๐Ÿ“š Comprehensive documentation for AI assistants

Installation

  1. Clone or download this repository

  2. Install dependencies:

pip install -r requirements.txt
  1. Install the package in development mode:
pip install -e .

Once installed, the ha-automation CLI command will be available globally.

Configuration

Create ~/.config/ha-automation/config with your Home Assistant credentials:

HA_URL=http://192.168.1.100:8123
HA_TOKEN=your_long_lived_access_token

You can also use a .env file in the current working directory (overrides the config file).

Getting a Long-Lived Access Token

  1. Navigate to your Home Assistant profile page: http://your-ha-url:8123/profile
  2. Scroll to the bottom to "Long-Lived Access Tokens"
  3. Click "Create Token"
  4. Give it a name (e.g., "ha-automation")
  5. Copy the token and add it to ~/.config/ha-automation/config

CLI Usage

Test Connection

ha-automation test

Device Discovery

# Discover and cache all devices
ha-automation discover

# Force refresh (ignore cache)
ha-automation discover --force

# Search for devices
ha-automation devices "motion"
ha-automation devices "่ตฐๅปŠ"  # Chinese search supported

# Filter by domain
ha-automation devices --type light
ha-automation devices --type sensor
ha-automation devices --type switch

# Filter by area
ha-automation devices --area "Living Room"

# JSON output
ha-automation devices --json

# Limit results
ha-automation devices --type light --limit 20

List Automations

# List all automations
ha-automation list

# Filter by state
ha-automation list --state on
ha-automation list --state off

# Output as JSON
ha-automation list --json

Show Automation Details

ha-automation show automation.my_automation

Enable/Disable Automations

# Enable an automation
ha-automation enable automation.my_automation

# Disable an automation
ha-automation disable automation.my_automation

# Toggle automation state
ha-automation toggle automation.my_automation

Trigger Automation

# Manually trigger an automation
ha-automation trigger automation.my_automation

# Trigger and skip conditions
ha-automation trigger automation.my_automation --skip-condition

Delete Automation

# Delete automation (requires automation ID, not entity_id)
# Use 'show' command to find the automation ID first
ha-automation delete 1234567890

# Force delete without confirmation
ha-automation delete 1234567890 --force

Create Automations

# Run a Python automation script (uses API to create automation)
ha-automation run ~/.config/ha-automation/automations/door_unlock_lights.py

# Sync scripts in the default user directory:
# ~/.config/ha-automation/automations
ha-automation sync

# Preview what would be synced without making changes
ha-automation sync --dry-run

# Sync and remove orphaned automations
ha-automation sync --clean

# Use a custom scripts directory
ha-automation sync --directory /path/to/your/automations

# Or configure default scripts directory with env var
export HA_AUTOMATION_SCRIPTS_DIR=/path/to/your/automations
ha-automation sync

# Create automation from template (interactive, uses API)
ha-automation create-from-template motion-light
ha-automation create-from-template time-based

# Available templates: motion-light, time-based, temperature-control, door-alert, auto-off

Update Automation

# Show current automation configuration
ha-automation update my_automation_123

Validate YAML

# Validate automation YAML file (for reference only)
ha-automation validate my_automation.yaml

Reload Automations

# Reload all automations from YAML files
ha-automation reload

Python API Usage

Device Discovery

from ha_automation import HAClient, DeviceDiscovery

# Initialize
client = HAClient()  # Reads from ~/.config/ha-automation/config automatically
discovery = DeviceDiscovery(client)

# Discover all devices
devices = discovery.discover_all()
print(f"Found {len(devices)} devices")

# Search devices (supports Chinese and English)
motion_sensors = discovery.search("่ตฐๅปŠ motion")
hallway_lights = discovery.search("hallway light")

# Get devices by domain
all_lights = discovery.get_lights()
all_sensors = discovery.get_sensors()
all_switches = discovery.get_switches()

# Get specific device types
motion_sensors = discovery.get_motion_sensors()
door_sensors = discovery.get_door_sensors()
temp_sensors = discovery.get_temperature_sensors()

# Filter by area
living_room_devices = discovery.get_by_area("Living Room")

# Access device information
for device in all_lights[:5]:
    print(f"{device.friendly_name}")
    print(f"  Entity ID: {device.entity_id}")
    print(f"  State: {device.state}")
    print(f"  Domain: {device.domain}")

Automation Management

from ha_automation import HAClient, AutomationManager

# Initialize client (reads from ~/.config/ha-automation/config automatically)
client = HAClient()
manager = AutomationManager(client)

# List all automations
automations = manager.list_automations()
for auto in automations:
    print(f"{auto.entity_id}: {auto.state} - {auto.friendly_name}")

# Filter by state
enabled = manager.list_automations(state_filter="on")
disabled = manager.list_automations(state_filter="off")

# Get specific automation
auto = manager.get_automation("automation.my_automation")
print(f"State: {auto.state}")
print(f"Last triggered: {auto.last_triggered}")

# Enable/disable
manager.turn_on_automation("automation.my_automation")
manager.turn_off_automation("automation.my_automation")

# Toggle
manager.toggle_automation("automation.my_automation")

# Trigger manually
manager.trigger_automation("automation.my_automation", skip_condition=True)

# Delete (requires automation ID)
automation_id = auto.automation_id
if automation_id:
    manager.delete_automation(automation_id)

# Reload all automations
manager.reload_automations()

Create Automation via API (Recommended Method)

import time
from ha_automation import HAClient, DeviceDiscovery, AutomationManager

# Initialize
client = HAClient()
discovery = DeviceDiscovery(client)
manager = AutomationManager(client)

# Discover devices
discovery.discover_all()

# Find devices
motion = discovery.search("hallway motion")[0]
light = discovery.search("hallway light")[0]

# Build automation configuration
config = {
    "id": f"night_hallway_light_{int(time.time())}",  # Unique ID
    "alias": "ๅคœ้—ด่ตฐๅปŠ็…งๆ˜Ž",
    "description": "Turn on hallway light when motion detected at night",
    "trigger": [{
        "platform": "state",
        "entity_id": motion.entity_id,
        "to": "on"
    }],
    "condition": [{
        "condition": "time",
        "after": "22:00:00",
        "before": "06:00:00"
    }],
    "action": [{
        "service": "light.turn_on",
        "target": {"entity_id": light.entity_id},
        "data": {"brightness_pct": 30}
    }],
    "mode": "single"
}

# Create automation via API
try:
    automation_id = manager.create_automation(config)
    print(f"โœ… Created automation: {automation_id}")

    # Verify it was created
    auto = manager.get_automation(f"automation.{automation_id}")
    print(f"โœ… Status: {auto.state}")
    print(f"โœ… Name: {auto.friendly_name}")
except Exception as e:
    print(f"โŒ Error: {e}")

Custom Connection

# Specify credentials manually (instead of .env)
client = HAClient(
    url="http://192.168.1.100:8123",
    token="your_token_here"
)
manager = AutomationManager(client)

Documentation

  • README.md - Overview and quick start (this file)
  • AGENTS.md - โญ Complete guide for AI assistants with API workflow

Project Structure

ha-automation/
โ”‚   # Config lives in ~/.config/ha-automation/config (not in repo)
โ”œโ”€โ”€ .gitignore                    # Git ignore rules
โ”œโ”€โ”€ requirements.txt              # Python dependencies
โ”œโ”€โ”€ pyproject.toml               # Package configuration
โ”œโ”€โ”€ README.md                     # This file
โ”œโ”€โ”€ AGENTS.md                   # Guide for AI assistants
โ”œโ”€โ”€ ha_automation/
โ”‚   โ”œโ”€โ”€ __init__.py              # Package exports
โ”‚   โ”œโ”€โ”€ client.py                # Home Assistant API client wrapper
โ”‚   โ”œโ”€โ”€ models.py                # Data models (Pydantic)
โ”‚   โ”œโ”€โ”€ device_discovery.py      # Device discovery and search
โ”‚   โ”œโ”€โ”€ automation_manager.py   # Core automation operations
โ”‚   โ””โ”€โ”€ cli.py                   # CLI interface
โ”œโ”€โ”€ examples/                     # General examples (templates & demos)
โ”‚   โ”œโ”€โ”€ example_automations.py   # Example usage scripts
โ”‚   โ”œโ”€โ”€ generate_automation_yaml.py  # YAML generation example
โ”‚   โ”œโ”€โ”€ improved_yaml_workflow.py    # Complete workflow examples
โ”‚   โ”œโ”€โ”€ ai_usage_example.py      # AI assistant usage example
โ”‚   โ””โ”€โ”€ lock_event_monitor.py    # Lock event monitoring and testing tool
โ””โ”€โ”€ my_automations/               # Optional local workspace/symlink for AI convenience

Examples

See the examples directory for more detailed usage examples.

Automation Scripts Directory

By default, automation scripts are stored in your user config directory:

~/.config/ha-automation/automations

This keeps personal automation data isolated from the repository (delete/reset/update repo without losing scripts).

Directory resolution priority for ha-automation sync:

  1. --directory option
  2. HA_AUTOMATION_SCRIPTS_DIR environment variable
  3. Default path: ~/.config/ha-automation/automations

Quick Start:

# Directory is created automatically on first use, or create it manually:
mkdir -p ~/.config/ha-automation/automations

# Sync all scripts from default user directory
ha-automation sync

# Run a single script
ha-automation run ~/.config/ha-automation/automations/door_unlock_lights.py

# Automations are created directly in Home Assistant via API!

For AI Assistants

This toolkit is designed to be used by AI assistants to help users create and manage Home Assistant automations from natural language descriptions.

See AGENTS.md for comprehensive documentation including:

  • Quick start guide for AI assistants
  • Common automation patterns with code examples
  • Home Assistant trigger/condition/action reference
  • Error handling and best practices
  • Full workflow examples

Example workflow:

  1. User describes automation in natural language (Chinese or English)
  2. AI assistant uses DeviceDiscovery to find relevant devices
  3. AI assistant generates automation configuration dictionary
  4. AI assistant calls manager.create_automation(config) to create via API
  5. Automation is automatically created and reloaded in Home Assistant
  6. AI assistant verifies success and reports to user

Requirements

  • Python 3.8+
  • Home Assistant instance with REST API enabled
  • Long-lived access token

Dependencies

  • python-dotenv - Environment variable management
  • click - CLI framework
  • rich - Beautiful terminal output
  • pydantic - Data validation and models
  • requests - HTTP library

How It Works

This toolkit uses the Home Assistant REST API to create and manage automations programmatically.

What this toolkit does:

  • โœ… Device discovery and intelligent search
  • โœ… Create automations directly via API
  • โœ… Manage existing automations (list, enable/disable, trigger, reload)
  • โœ… Validate automation configurations
  • โœ… Provide AI-friendly APIs for natural language โ†’ automation conversion

What you get:

  • ๐Ÿš€ Fully automated automation creation
  • โšก Immediate feedback on success/failure
  • ๐Ÿ”„ Automatic reload after changes
  • ๐ŸŽฏ No manual YAML editing required

Troubleshooting

Connection Issues

If you get connection errors:

  1. Verify your HA_URL is correct and accessible
  2. Check that your access token is valid
  3. Ensure Home Assistant's REST API is enabled
  4. Test with: ha-automation test

Authentication Errors

If you get 401 Unauthorized:

  1. Verify your token hasn't expired (tokens last 10 years)
  2. Try generating a new long-lived access token
  3. Check that the token is correctly set in ~/.config/ha-automation/config

Automation Not Found

If an automation isn't found:

  1. Check the entity_id is correct (should start with automation.)
  2. Run ha-automation list to see all available automations
  3. Verify the automation exists in Home Assistant

License

MIT License

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ha_automation-1.0.0.tar.gz (35.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ha_automation-1.0.0-py3-none-any.whl (29.3 kB view details)

Uploaded Python 3

File details

Details for the file ha_automation-1.0.0.tar.gz.

File metadata

  • Download URL: ha_automation-1.0.0.tar.gz
  • Upload date:
  • Size: 35.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.7

File hashes

Hashes for ha_automation-1.0.0.tar.gz
Algorithm Hash digest
SHA256 bc2383a75edbc68a32b28c0a1f0cc1d125f733a151bce688321eb1f3be7476ba
MD5 8791e603f371a8adfcf567ae8be0a10f
BLAKE2b-256 77e0c5a63677d888c89ae33deb94809de3ae8fe48b666d01f02bd5a482d41be4

See more details on using hashes here.

File details

Details for the file ha_automation-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: ha_automation-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 29.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.7

File hashes

Hashes for ha_automation-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 3b22767a17ac6df4ff0b6c1b5b5453170ad729f380a47cf5c56a9f8c8cf64d38
MD5 c1ac3112c1384dd188d42f770c78d470
BLAKE2b-256 a457cc20dac1045a69d756f9be699ccd3cbfdd8840dddaffae6d6dfe41532b5b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page