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
-
Clone or download this repository
-
Install dependencies:
pip install -r requirements.txt
- 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
- Navigate to your Home Assistant profile page:
http://your-ha-url:8123/profile - Scroll to the bottom to "Long-Lived Access Tokens"
- Click "Create Token"
- Give it a name (e.g., "ha-automation")
- 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:
--directoryoptionHA_AUTOMATION_SCRIPTS_DIRenvironment variable- 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:
- User describes automation in natural language (Chinese or English)
- AI assistant uses
DeviceDiscoveryto find relevant devices - AI assistant generates automation configuration dictionary
- AI assistant calls
manager.create_automation(config)to create via API - Automation is automatically created and reloaded in Home Assistant
- 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 managementclick- CLI frameworkrich- Beautiful terminal outputpydantic- Data validation and modelsrequests- 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:
- Verify your
HA_URLis correct and accessible - Check that your access token is valid
- Ensure Home Assistant's REST API is enabled
- Test with:
ha-automation test
Authentication Errors
If you get 401 Unauthorized:
- Verify your token hasn't expired (tokens last 10 years)
- Try generating a new long-lived access token
- Check that the token is correctly set in
~/.config/ha-automation/config
Automation Not Found
If an automation isn't found:
- Check the entity_id is correct (should start with
automation.) - Run
ha-automation listto see all available automations - 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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
bc2383a75edbc68a32b28c0a1f0cc1d125f733a151bce688321eb1f3be7476ba
|
|
| MD5 |
8791e603f371a8adfcf567ae8be0a10f
|
|
| BLAKE2b-256 |
77e0c5a63677d888c89ae33deb94809de3ae8fe48b666d01f02bd5a482d41be4
|
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3b22767a17ac6df4ff0b6c1b5b5453170ad729f380a47cf5c56a9f8c8cf64d38
|
|
| MD5 |
c1ac3112c1384dd188d42f770c78d470
|
|
| BLAKE2b-256 |
a457cc20dac1045a69d756f9be699ccd3cbfdd8840dddaffae6d6dfe41532b5b
|