[][src]Struct hass_rs::client::HassClient

pub struct HassClient { /* fields omitted */ }

Established connection with a Home Assistant WebSocket server.

Backed by async_tungstenite, that provides async Websocket bindings, that can be used with non-blocking/asynchronous TcpStreams. It Supports both "async-std" and "tokio" runtimes.

Requests are issued using the various methods of Client.

Implementations

impl HassClient[src]

pub async fn auth_with_longlivedtoken<'_, '_>(
    &'_ mut self,
    token: &'_ str
) -> HassResult<()>
[src]

authenticate the session using a long-lived access token

When a client connects to the server, the server sends out auth_required. The first message from the client should be an auth message. You can authorize with an access token. If the client supplies valid authentication, the authentication phase will complete by the server sending the auth_ok message. If the data is incorrect, the server will reply with auth_invalid message and disconnect the session.

Examples

Demonstrates basic usage.

use hass_rs::client;

#[async_std::main]
async fn main() -> Result<(), Box<dyn std::error::Error>>{
    let mut client = client::connect("localhost", 8123).await?;
    client.auth_with_longlivedtoken("your_token").await?;
    println!("WebSocket connection and authethication works");
    Ok(())
}

pub async fn ping<'_>(&'_ mut self) -> HassResult<String>[src]

The API supports receiving a ping from the client and returning a pong. This serves as a heartbeat to ensure the connection is still alive.

Examples

Demonstrates basic usage.

use hass_rs::client;

#[async_std::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

    let mut client = client::connect("localhost", 8123).await?;
    client.auth_with_longlivedtoken("your_token").await?;

    match client.ping().await? {
        pong if pong == String::from("pong") => {
            println!("Great the Hass Websocket Server responds to ping")
        }
        _ => println!("Ooops, I was expecting pong"),
    };
    Ok(())
}

pub async fn subscribe_event<F, '_, '_>(
    &'_ mut self,
    event_name: &'_ str,
    callback: F
) -> HassResult<String> where
    F: Fn(WSEvent) + Send + 'static, 
[src]

The command subscribe_event will subscribe your client to the event bus.

You can either listen to all events or to a specific event type. If you want to listen to multiple event types, you will have to send multiple subscribe_events commands. The server will respond with a result message to indicate that the subscription is active. For each event that matches, the server will send a message of type event. The id in the message will point at the original id of the listen_event command.

Examples

Demonstrates basic usage.

use hass_rs::client;
use hass_rs::WSEvent;

#[async_std::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

    let mut client = client::connect("localhost", 8123).await?;
    client.auth_with_longlivedtoken("your_token").await?;

    let pet = |item: WSEvent| {
        println!(
        "Closure is executed when the Event with the id: {} has been received, it was fired at {}", item.id,
        item.event.time_fired );
    };
    match client.subscribe_event("state_changed", pet).await {
        Ok(v) => println!("Event subscribed: {}", v),
        Err(err) => println!("Oh no, an error: {}", err),
    }
    Ok(())
}

pub async fn unsubscribe_event<'_>(
    &'_ mut self,
    subscription_id: u64
) -> HassResult<String>
[src]

The command unsubscribe_event will unsubscribe your client from the event bus.

You can unsubscribe from previously created subscription events. Pass the id of the original subscription command as value to the subscription field.

Examples

Demonstrates basic usage.

use hass_rs::client;

#[async_std::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

    let mut client = client::connect("localhost", 8123).await?;
    client.auth_with_longlivedtoken("your_token").await?;

//assuming the event subscription is present
    match client.unsubscribe_event(2).await {
        Ok(v) => println!("Succefully unsubscribed: {}", v),
        Err(err) => println!("Oh no, an error: {}", err),
    }
    Ok(())
}

pub async fn get_config<'_>(&'_ mut self) -> HassResult<HassConfig>[src]

This will get a dump of the current config in Home Assistant.

The server will respond with a result message containing the config.

Examples

Demonstrates basic usage.

use hass_rs::client;

#[async_std::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

    let mut client = client::connect("localhost", 8123).await?;
    client.auth_with_longlivedtoken("your_token").await?;

    println!("Get Hass Config");
    match client.get_config().await {
        Ok(v) => println!("{:?}", v),
        Err(err) => println!("Oh no, an error: {}", err),
    }
    Ok(())
}

pub async fn get_states<'_>(&'_ mut self) -> HassResult<Vec<HassEntity>>[src]

This will get a dump of all the current states in Home Assistant.

The server will respond with a result message containing the states.

Examples

Demonstrates basic usage.

use hass_rs::client;

#[async_std::main]
async fn main() -> Result<(), Box<dyn std::error::Error>>{

    let mut client = client::connect("localhost", 8123).await?;
    client.auth_with_longlivedtoken("your_token").await?;

    println!("Get Hass States");
    match client.get_states().await {
        Ok(v) => println!("{:?}", v),
        Err(err) => println!("Oh no, an error: {}", err),
    }
    Ok(())
}

pub async fn get_services<'_>(&'_ mut self) -> HassResult<HassServices>[src]

This will get a dump of the current services in Home Assistant.

The server will respond with a result message containing the services.

Examples

Demonstrates basic usage.

use hass_rs::client;

#[async_std::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

    let mut client = client::connect("localhost", 8123).await?;
    client.auth_with_longlivedtoken("your_token").await?;

    println!("Get Hass Services");
    match client.get_services().await {
        Ok(v) => println!("{:?}", v),
        Err(err) => println!("Oh no, an error: {}", err),
    }
    Ok(())
}

pub async fn call_service<'_>(
    &'_ mut self,
    domain: String,
    service: String,
    service_data: Option<Value>
) -> HassResult<String>
[src]

This will call a service in Home Assistant. Right now there is no return value. The client can listen to state_changed events if it is interested in changed entities as a result of a service call.

The server will indicate with a message indicating that the service is done executing.

Examples

Demonstrates basic usage.

use hass_rs::client;
use serde_json::json;

#[async_std::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

    let mut client = client::connect("localhost", 8123).await?;
    client.auth_with_longlivedtoken("your_token").await?;

    let value = json!({
        "entity_id": "sun.sun"
    });

    match client
        .call_service(
            "homeassistant".to_owned(),
            "update_entity".to_owned(),
            Some(value),
        )
        .await
    {
        Ok(done) if done == String::from("command executed successfully") => {
            println!("Good, your command was executed")
        }
        Ok(_) => println!("Ooops, I got strange result"),
        Err(error) => println!("Ooops, I got this error {}", error),
    }
    Ok(())
}

Auto Trait Implementations

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> Same<T> for T

type Output = T

Should always be Self

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.

impl<V, T> VZip<V> for T where
    V: MultiLane<T>,