Home Assistant Command-line Interface

repository·dev·Indexed 17 days ago

https://github.com/home-assistant-ecosystem/home-assistant-cli

A command-line tool (hass-cli) for interacting with local or remote Home Assistant instances. It enables automation, state management, and system administration via the terminal, featuring a plugin-based architecture, support for multiple output formats (JSON, YAML, table), and shell autocompletion for services, entities, events, and areas. Version 1.0.1.

Tokens
16.9K
Snippets
43
Records
61
Agent score
69%

What's inside home-assistant-cli

  1. Configure hass-cli with Server and Token

    dev

    To interact with your Home Assistant instance, you must provide a server URL and a Long-Lived Access Token.

    1. Generate a Token: Go to your Home Assistant profile page (e.g., http://homeassistant.local:8123/profile), scroll to "Long-Lived Access Tokens", and generate one.
    2. Set Credentials: You can pass --server and --token as parameters to every command, but it is recommended to set them as environment variables:
    $ export HASS_SERVER=http://homeassistant.local:8123
    $ export HASS_TOKEN=<your_secret_token>
    $ export HASS_SERVER=http://homeassistant.local:8123
    $ export HASS_TOKEN=<secret>
  2. Access the Supervisor API via Remote API Proxy

    dev

    For users of the Home Assistant Operating System, certain commands (like ha commands) require access to the Supervisor API.

    1. Install and start the Remote API proxy add-on.
    2. Retrieve your Supervisor API key from the add-on logs.
    3. Set the HASS_SUPERVISOR_TOKEN environment variable:
    $ export HASS_SUPERVISOR_TOKEN=<supervisor_secret>
  3. List and Call Services

    dev

    Use the service command to interact with Home Assistant services.

    List Services

    You can list services and filter them using regular expressions.

    # List services matching a pattern
    $ hass-cli service list 'home.*toggle'
    
    # Get detailed service information in YAML format
    $ hass-cli -o yaml service list homeassistant.toggle

    Call a Service

    To trigger a service (e.g., creating a backup), use service call:

    # Example: Create a backup
    $ hass-cli service call backup.create
    $ hass-cli service list 'home.*toggle'
  4. Manage and Query States

    dev

    The state command allows you to list, get, edit, and view history for entities.

    List States

    Use state list to see current states. Use --no-headers to suppress headers or --columns to select specific data using JSONPath.

    # List all states
    $ hass-cli state list
    
    # List specific columns (e.g., entity_id and all attributes)
    $ hass-cli --columns=ENTITY="entity_id,ATTRIBUTES=attributes[*]" state list zone

    Get Detailed State

    Use -o yaml or -o json to get the full data structure for a specific entity.

    $ hass-cli -o yaml state get light.guestroom_light

    Edit States

    You can edit a state using your default text editor:

    $ hass-cli state edit light.guestroom_light

    Or explicitly via JSON:

    $ hass-cli state edit sensor.test --json='{ "state":"off"}'

    View State History

    Use state history with the --since flag to see changes over a duration.

    # Get history for the last 50 minutes
    $ hass-cli state history --since 50m light.kitchen_light_1
    
    # Sort history by a specific attribute (e.g., last_changed)
    $ hass-cli --sort-by last_changed state history --since 50m light.kitchen_light_1

    Note: --sort-by refers to the attribute name in the underlying JSON/YAML, not the display column name.

    $ hass-cli state list
  5. Install the Home Assistant CLI (hass-cli)

    dev

    You can install hass-cli using several methods depending on your environment:

    Python (pip)

    To install the latest stable release:

    $ pip install homeassistant-cli

    To install the latest pre-release from the dev branch:

    $ pip install git+https://github.com/home-assistant-ecosystem/home-assistant-cli@dev

    System Package Managers

    • Fedora/EPEL: sudo dnf -y install home-assistant-cli
    • macOS (Homebrew): brew install homeassistant-cli
    • NixOS: nix-env -iA nixos.home-assistant-cli (Note: latest release may require the unstable channel).

    Docker

    If you prefer not to use a local Python setup, you can run it via Docker:

    $ docker run homeassistant/home-assistant-cli

    To enable auto-completion and environment variable access in Docker, download the wrapper script:

    $ curl https://raw.githubusercontent.com/home-assistant/home-assistant-cli/master/docker-hass-cli > hass-cli
    $ chmod +x hass-cli

    Place the hass-cli script in your PATH. Note that this method does not support commands requiring local file system access (e.g., hass-cli template).

  6. Enable Automatic Completion for hass-cli

    dev

    You can enable shell autocompletion for hass-cli commands using the following commands depending on your shell:

    • Bash: source <(_HASS_CLI_COMPLETE=bash_source hass-cli)
    • Zsh: source <(_HASS_CLI_COMPLETE=zsh_source hass-cli)
    • Fish: eval (_HASS_CLI_COMPLETE=fish_source hass-cli)
    $ source <(_HASS_CLI_COMPLETE=bash_source hass-cli) # for bash
    $ source <(_HASS_CLI_COMPLETE=zsh_source hass-cli)  # for zsh
    $ eval (_HASS_CLI_COMPLETE=fish_source hass-cli)    # for fish
  7. Setup a Development Environment for hass-cli

    dev

    To develop on hass-cli, it is recommended to use a Python virtual environment to ensure isolation. Follow these steps:

    1. Clone the repository.
    2. Create and activate a virtual environment.
    3. Run the provided setup script.
    4. Install the package in editable mode.

    After setup, you can run hass-cli directly from your terminal to test changes.

    # Create and activate virtual environment
    python3 -m venv .
    source bin/activate
    
    # Run setup script
    script/setup
    
    # Install in editable mode
    pip3 install --editable .
    
    # Run the CLI
    $ hass-cli
  8. Configure Auto-completion for hass-cli

    dev

    To enable tab-completion for commands and entity attributes (like light.<TAB>), add the following to your shell configuration file. This method is recommended as it uses eval to avoid triggering a full hass-cli run every time a shell starts.

    Zsh

    Add this to your .zshrc:

    eval "$(_HASS_CLI_COMPLETE=source_zsh hass-cli)"

    Bash

    Add this to your .bashrc:

    eval "$(_HASS_CLI_COMPLETE=source hass-cli)"

    Note: If your Home Assistant instance is secured or remote, you must set the HASS_SERVER and HASS_TOKEN environment variables for autocompletion to fetch entity lists.

    # Required for remote/secured instances to enable entity autocompletion
    export HASS_SERVER=http://homeassistant.local:8123
    export HASS_TOKEN=your_bearer_token_here
  9. How hass-cli loads commands via plugins

    dev

    The hass-cli uses a plugin-based architecture. Instead of a static list of commands, it dynamically discovers and loads commands from a plugins directory.

    When you run a command, the HomeAssistantCli class (which inherits from click.MultiCommand) performs the following:

    1. Discovery: It scans the plugins folder for .py files (excluding those starting with __).
    2. Loading: It imports the module and looks for a cli object within that module.
    3. Execution: It invokes the imported cli object as the command group or command.

    This allows the CLI to be easily extended with new functionality by adding new plugin files.

  10. Resolve the Home Assistant server URL

    dev

    The CLI can automatically locate a Home Assistant instance on the local network using mDNS (Zeroconf).

    When server is set to auto:

    1. If HASSIO_TOKEN is in the environment but HASS_TOKEN is not, it uses const.DEFAULT_SERVER_MDNS.
    2. Otherwise, it attempts to locate the instance via Zeroconf by looking for _home-assistant._tcp.local. services.
    3. If multiple instances are found, resolution fails and the user should use the --server flag to specify one explicitly.
    4. If no instance is found and no explicit server is provided, the CLI exits with code 3.
  11. Reference: hass-cli Global Options and Commands

    dev

    The following are the global options and primary command groups available for hass-cli.

    Options:
    
    -l, --loglevel LVL              Either CRITICAL, ERROR, WARNING, INFO or DEBUG
    --version                       Show the version and exit.
    -s, --server TEXT               The server URL or `auto` for automatic detection. Can also be set with the environment variable HASS_SERVER.  [default: auto]
    --token TEXT                    The Bearer token for Home Assistant instance. Can also be set with the environment variable HASS_TOKEN.
    --supervisor-token TEXT         The Bearer token for Home Assistant supervisor.
    --password TEXT                 The API password for Home Assistant instance. Can also be set with the environment variable HASS_PASSWORD.
    --timeout INTEGER               Timeout for network operations.  [default: 5]
    -o, --output [json|yaml|table|auto|ndjson] Output format.  [default: auto]
    -v, --verbose                   Enables verbose mode.
    -x                              Print backtraces when exception occurs.
    --cert TEXT                     Path to client certificate file (.pem) to use when connecting.
    --insecure                      Ignore SSL Certificates. Allow to connect to servers with self-signed certificates. Be careful!
    --debug                         Enables debug mode.
    --columns TEXT                  Custom columns key=value list. Example: ENTITY=entity_id, NAME=attributes.friendly_name
    --no-headers                    When printing tables don't use headers (default: print headers)
    --table-format TEXT             Which table format to use.
    --sort-by TEXT                  Sort table by the jsonpath expression. Example: last_changed
    --help                          Show this message and exit.
    
    Commands:
    
    area         Get info and operate on areas from Home Assistant...
    config       Get configuration from a Home Assistant instance.
    device       Get info and operate on devices from Home Assistant.
    discover     Discovery for the local network.
    entity       Get info on entities from Home Assistant.
    event        Interact with events.
    ha           Home Assistant Operating System commands.
    info         Show information about Home Assistant CLI.
    integration  Get info and operate on integrations (config entries) from...
    map          Show the location of the config or an entity on a map.
    raw          Call the raw API (advanced).
    service      Call and work with services.
    state        Get info on entity state from Home Assistant.
    system       System details and operations for Home Assistant.
    template     Render templates on server or locally.
  12. Reference: hass-cli Output and Formatting Options

    dev

    Control how hass-cli displays data using the following flags:

    • --output=yaml or -o yaml: Output data in YAML format.
    • --output=json or -o json: Output data in JSON format.
    • --no-headers: Suppress the table header in output.
    • --table-format <format>: Select a table format. Supported formats (via tabulate) include: plain, simple, github, grid, fancy_grid, pipe, orgtbl, rst, mediawiki, html, latex, latex_raw, latex_booktabs, or tsv. Default is simple.
    • --columns=<NAME>=<JSONPATH>,...: Control which columns are shown. For entities, the default is: --columns=ENTITY=entity_id,DESCRIPTION=attributes.friendly_name,STATE=state,CHANGED=last_changed.
    • --sort-by <attribute>: Sort the output by a specific attribute found in the underlying JSON/YAML data.