|
@@ -1,14 +1,17 @@
|
|
|
-use awc::{Client, ws::{Frame, Message}};
|
|
|
|
|
|
|
+use awc::{Client, BoxedSocket, ws::{Frame, Message, Codec}};
|
|
|
|
|
+use actix_codec::Framed;
|
|
|
use futures_util::{SinkExt, StreamExt};
|
|
use futures_util::{SinkExt, StreamExt};
|
|
|
use serde_json::{Value, from_str, json};
|
|
use serde_json::{Value, from_str, json};
|
|
|
|
|
|
|
|
-pub async fn connect_to_ha(ip: String, token: String) -> Result<(), Box<dyn std::error::Error>> {
|
|
|
|
|
|
|
+pub async fn connect_to_ha(
|
|
|
|
|
+ ip: String,
|
|
|
|
|
+ token: String
|
|
|
|
|
+) -> Result<Framed<BoxedSocket, Codec>, Box<dyn std::error::Error>> {
|
|
|
let client = Client::new();
|
|
let client = Client::new();
|
|
|
let (_resp, mut connection) = client
|
|
let (_resp, mut connection) = client
|
|
|
.ws(format!("ws://{}:8123/api/websocket", ip))
|
|
.ws(format!("ws://{}:8123/api/websocket", ip))
|
|
|
.connect()
|
|
.connect()
|
|
|
.await?;
|
|
.await?;
|
|
|
- let mut message_id = 1;
|
|
|
|
|
|
|
|
|
|
while let Some(Ok(msg)) = connection.next().await {
|
|
while let Some(Ok(msg)) = connection.next().await {
|
|
|
if let Frame::Text(bytes) = msg {
|
|
if let Frame::Text(bytes) = msg {
|
|
@@ -36,14 +39,40 @@ pub async fn connect_to_ha(ip: String, token: String) -> Result<(), Box<dyn std:
|
|
|
/*let entities_msg = json!({"type": "config/entity_registry/list", "id": message_id});
|
|
/*let entities_msg = json!({"type": "config/entity_registry/list", "id": message_id});
|
|
|
connection.send(Message::Text(entities_msg.to_string().into())).await?;
|
|
connection.send(Message::Text(entities_msg.to_string().into())).await?;
|
|
|
message_id += 1;*/
|
|
message_id += 1;*/
|
|
|
|
|
+ return Ok(connection);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if parsed["type"] == "auth_invalid" {
|
|
|
|
|
+ return Err("HA authentication.failed".into());
|
|
|
}
|
|
}
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ Err("Websocket closed before authentication completed".into())
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+pub async fn listen(mut connection: Framed<BoxedSocket, Codec>) {
|
|
|
|
|
+ let mut message_id = 1;
|
|
|
|
|
+
|
|
|
|
|
+ while let Some(Ok(msg)) = connection.next().await {
|
|
|
|
|
+ if let Frame::Text(bytes) = msg {
|
|
|
|
|
+ let text = match String::from_utf8(bytes.to_vec()) {
|
|
|
|
|
+ Ok(t) => t,
|
|
|
|
|
+ Err(_) => continue
|
|
|
|
|
+ };
|
|
|
|
|
+ let parsed: Value = match from_str(&text) {
|
|
|
|
|
+ Ok(v) => v,
|
|
|
|
|
+ Err(_) => continue
|
|
|
|
|
+ };
|
|
|
|
|
|
|
|
if parsed["type"] == "result" {
|
|
if parsed["type"] == "result" {
|
|
|
println!("result");
|
|
println!("result");
|
|
|
println!("{:#?}", parsed);
|
|
println!("{:#?}", parsed);
|
|
|
}
|
|
}
|
|
|
|
|
+
|
|
|
|
|
+ let _ = message_id;
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- Ok(())
|
|
|
|
|
|
|
+ println!("HA websocket connection closed");
|
|
|
}
|
|
}
|