ha-rs
A Rust library and command-line interface (CLI) tool for interacting with Home Assistant.
Features
- 🦀 Pure Rust implementation with async support
- 🔌 Get entity states from Home Assistant
- 🎛️ Control devices (turn on/off)
- 🛠️ Simple and ergonomic API
- 📦 Use as a library or CLI tool
Installation
As a Library
Add this to your Cargo.toml:
[]
= "0.1.0"
= { = "1.48", = ["full"] }
As a CLI Tool
Or build from source:
Usage
As a Library
use HaClient;
async
As a CLI Tool
Set required environment variables:
Check device status:
Toggle device state:
API Reference
HaClient
The main client for interacting with Home Assistant.
Methods
new(base_url: String, token: String) -> Self
Creates a new Home Assistant client.
Parameters:
base_url: The base URL of your Home Assistant instance (e.g., "http://homeassistant.local:8123")token: Your Home Assistant long-lived access token
Example:
let client = new;
async get_state(&self, entity_id: &str) -> Result<Entity, Error>
Retrieves the current state of an entity.
Parameters:
entity_id: The entity ID (e.g., "switch.smart_plug", "light.bedroom")
Returns:
Ok(Entity): Entity information including state, attributes, and timestampsErr(Error): Network or API error
Example:
let entity = client.get_state.await?;
println!;
async set_state(&self, entity_id: &str, turn_on: bool) -> Result<String, Error>
Controls a device by turning it on or off.
Parameters:
entity_id: The entity ID (e.g., "switch.smart_plug", "light.bedroom")turn_on:trueto turn on,falseto turn off
Returns:
Ok(String): Response from Home Assistant APIErr(Error): Network or API error
Example:
// Turn on
client.set_state.await?;
// Turn off
client.set_state.await?;
Entity
Represents a Home Assistant entity with its current state and metadata.
Fields:
entity_id: String- The entity identifierstate: String- Current state (e.g., "on", "off", "unavailable")attributes: HashMap<String, serde_json::Value>- Entity attributeslast_changed: String- Timestamp of last state changelast_reported: String- Timestamp of last reportlast_updated: String- Timestamp of last updatecontext: Context- Context information
Getting a Home Assistant Token
- Log in to your Home Assistant instance
- Click on your profile (bottom left)
- Scroll down to "Long-Lived Access Tokens"
- Click "Create Token"
- Give it a name and copy the token
Requirements
- Rust 2024 edition or later
- Home Assistant instance with API access
- Valid long-lived access token
License
MIT
Author
Sachin Kumar sachinkumar.ar97@gmail.com