hass_rs/types/
response.rs1use crate::types::HassEvent;
2use crate::HassResult;
3
4use serde::Deserialize;
5use serde_json::Value;
6
7#[derive(Debug, Deserialize)]
10#[serde(tag = "type", rename_all = "snake_case")]
11pub enum Response {
12 AuthRequired(AuthRequired),
14 #[allow(unused)]
16 AuthOk(AuthOk),
17 AuthInvalid(AuthInvalid),
19 Result(WSResult),
21 Pong(WSPong),
23 Event(WSEvent),
25 #[allow(unused)]
27 Close(String),
28}
29
30impl Response {
31 pub fn id(&self) -> Option<u64> {
32 match self {
33 Self::AuthRequired(_) | Self::AuthOk(_) | Self::AuthInvalid(_) | Self::Close(_) => None,
34 Self::Pong(pong) => Some(pong.id),
35 Self::Result(result) => Some(result.id),
36 Self::Event(event) => Some(event.id),
37 }
38 }
39}
40
41#[derive(Debug, Deserialize, PartialEq)]
44#[serde(rename_all = "snake_case")]
45pub struct AuthRequired {
46 pub ha_version: String,
47}
48
49#[derive(Debug, Deserialize, PartialEq)]
51#[serde(rename_all = "snake_case")]
52pub struct AuthOk {
53 pub ha_version: String,
54}
55
56#[derive(Debug, Deserialize, PartialEq)]
58#[serde(rename_all = "snake_case")]
59pub struct AuthInvalid {
60 pub message: String,
61}
62
63#[derive(Debug, Deserialize, PartialEq)]
65pub struct WSPong {
66 pub id: u64,
67}
68
69#[derive(Debug, Deserialize, PartialEq, Clone)]
74pub struct WSEvent {
75 pub id: u64,
76 pub event: HassEvent,
77}
78
79#[derive(Debug, Deserialize, PartialEq)]
84pub struct WSResult {
85 pub id: u64,
86 success: bool,
87 result: Option<Value>,
88 error: Option<ErrorCode>,
89}
90
91impl WSResult {
92 pub fn is_ok(&self) -> bool {
93 self.success
94 }
95
96 pub fn is_err(&self) -> bool {
97 !self.success
98 }
99
100 pub fn result(self) -> HassResult<Value> {
101 if self.success {
102 if let Some(result) = self.result {
103 return Ok(result);
104 }
105 }
106 Err(crate::HassError::ResponseError(self))
107 }
108}
109
110#[derive(Debug, Deserialize, PartialEq)]
111pub struct ErrorCode {
112 pub code: String,
113 pub message: String,
114}