home_assistant.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. //! Home Assistant REST API client for `power on`/`power off`.
  2. //!
  3. //! Talks to HA via `POST /api/services/<domain>/<service>` and uses
  4. //! `Authorization: Bearer <token>`. The HA domain for a switch is the
  5. //! part before the first dot in the entity_id (e.g. `switch.dgx1` →
  6. //! domain `switch`, service `turn_off` or `turn_on`).
  7. use anyhow::{Context, Result, anyhow};
  8. use serde_json::json;
  9. use std::time::Duration;
  10. use tracing::{debug, info, warn};
  11. use crate::config::{Cluster, Config, HomeAssistantConfig};
  12. /// Thin async wrapper around the HA REST API.
  13. ///
  14. /// `base_url` is the HA root URL (`http://homeassistant.local:8123`),
  15. /// `token` is the long-lived access token used as bearer auth.
  16. #[derive(Clone)]
  17. pub struct Client {
  18. base_url: String,
  19. token: String,
  20. http: reqwest::Client,
  21. }
  22. impl Client {
  23. /// Construct a new client. The reqwest client is built once and
  24. /// reused so connection pooling works across the parallel calls in
  25. /// the `power` subcommand.
  26. pub fn new(cfg: &HomeAssistantConfig) -> Result<Self> {
  27. let base_url = cfg.url.trim_end_matches('/').to_string();
  28. if base_url.is_empty() {
  29. anyhow::bail!("[home_assistant].url must be set");
  30. }
  31. let http = reqwest::Client::builder()
  32. .timeout(Duration::from_secs(10))
  33. .build()
  34. .context("building reqwest client")?;
  35. Ok(Self {
  36. base_url,
  37. token: cfg.token.clone(),
  38. http,
  39. })
  40. }
  41. /// Build `https://.../api/services/<domain>/<service>` for the given
  42. /// `entity_id`. Domain is the prefix before the first `.`; pass an
  43. /// empty fallback for ambiguous input.
  44. fn endpoint(entity_id: &str, service: &str) -> Result<(String, String)> {
  45. let (domain, entity) = entity_id.split_once('.').ok_or_else(|| {
  46. anyhow!(
  47. "entity_id '{}' has no domain (e.g. 'switch.foo')",
  48. entity_id
  49. )
  50. })?;
  51. if entity.is_empty() {
  52. anyhow::bail!("entity_id '{}' has empty entity name", entity_id);
  53. }
  54. Ok((
  55. domain.to_string(),
  56. format!("/api/services/{}/{}", domain, service),
  57. ))
  58. }
  59. /// POST `/api/services/<domain>/<service>` with `{"entity_id": ...}`.
  60. async fn call_service(&self, entity_id: &str, service: &str) -> Result<()> {
  61. let (_domain, path) = Self::endpoint(entity_id, service)?;
  62. let url = format!("{}{}", self.base_url, path);
  63. debug!("HA POST {}", url);
  64. let resp = self
  65. .http
  66. .post(&url)
  67. .bearer_auth(&self.token)
  68. .json(&json!({ "entity_id": entity_id }))
  69. .send()
  70. .await
  71. .with_context(|| format!("calling HA at {}", url))?;
  72. let status = resp.status();
  73. if !status.is_success() {
  74. let body = resp.text().await.unwrap_or_default();
  75. anyhow::bail!(
  76. "HA {} {} returned {}: {}",
  77. service,
  78. entity_id,
  79. status,
  80. body.trim()
  81. );
  82. }
  83. Ok(())
  84. }
  85. /// `switch.turn_off` for the given entity.
  86. pub async fn turn_off(&self, entity_id: &str) -> Result<()> {
  87. info!("HA turn_off {}", entity_id);
  88. self.call_service(entity_id, "turn_off").await
  89. }
  90. /// `switch.turn_on` for the given entity.
  91. pub async fn turn_on(&self, entity_id: &str) -> Result<()> {
  92. info!("HA turn_on {}", entity_id);
  93. self.call_service(entity_id, "turn_on").await
  94. }
  95. /// GET `/api/states/<entity_id>` and return the state string.
  96. /// Returns `None` if the entity doesn't exist or isn't reachable.
  97. /// Logs a warning when the HTTP request or JSON parsing fails so
  98. /// callers (e.g. `entity_is_on`) can distinguish "entity is off"
  99. /// from "HA is unreachable" via the log.
  100. pub async fn get_state(&self, entity_id: &str) -> Option<String> {
  101. let url = format!("{}/api/states/{}", self.base_url, entity_id);
  102. let resp = match self.http.get(&url).bearer_auth(&self.token).send().await {
  103. Ok(r) => r,
  104. Err(e) => {
  105. warn!("HA GET {} failed: {}", url, e);
  106. return None;
  107. }
  108. };
  109. if !resp.status().is_success() {
  110. warn!("HA GET {} returned {}", url, resp.status());
  111. return None;
  112. }
  113. let body: serde_json::Value = match resp.json().await {
  114. Ok(v) => v,
  115. Err(e) => {
  116. warn!("HA GET {} JSON parse failed: {}", url, e);
  117. return None;
  118. }
  119. };
  120. body.get("state").and_then(|s| s.as_str()).map(String::from)
  121. }
  122. }
  123. /// HA states for a cluster's `extra_entities` (parallel GETs).
  124. #[derive(Clone, Debug, Default, PartialEq)]
  125. pub struct EntityStates {
  126. /// A *blocking* entity reports anything other than "on" — including
  127. /// HA being unreachable (unknown is treated as off, same as the
  128. /// `health` command has always done). Blocking-off takes the whole
  129. /// cluster down.
  130. pub blocking_off: bool,
  131. /// Non-blocking entities (`blocks = false`) that are not "on" —
  132. /// tracked and displayed, but they never affect up/down.
  133. pub soft_off: Vec<String>,
  134. }
  135. /// Probe the cluster's `extra_entities`. No HA config and no `[mikrotik]`
  136. /// backend for an entity → that entity is "nothing to check", not off
  137. /// (legacy semantics). Mikrotik devices (exact name match from
  138. /// [`crate::config`]) are probed through the RouterOS API instead of HA:
  139. /// logged in = on, unreachable/rejected login = off (a dead router takes
  140. /// the cluster down like any other blocking switch).
  141. pub async fn extra_entities_states(config: &Config, cluster: &Cluster) -> EntityStates {
  142. if cluster.extra_entities.is_empty() {
  143. return EntityStates::default();
  144. }
  145. let ha_client: Option<Client> = config
  146. .home_assistant
  147. .as_ref()
  148. .and_then(|ha| Client::new(ha).ok());
  149. let has_ha = ha_client.is_some();
  150. let mut handles = Vec::new();
  151. for e in &cluster.extra_entities {
  152. let id = e.entity().to_string();
  153. let is_mikrotik = config
  154. .mikrotik
  155. .as_ref()
  156. .is_some_and(|m| m.devices.iter().any(|d| d.name == id.as_str()));
  157. // A non-mikrotik entity without an HA backend is "nothing to check",
  158. // not off — only entities with a configured backend flip the verdict.
  159. if !is_mikrotik && !has_ha {
  160. continue;
  161. }
  162. let config = config.clone();
  163. let client = ha_client.clone();
  164. let blocks = e.blocks();
  165. handles.push(crate::locale::spawn_with_locale(async move {
  166. (
  167. id.clone(),
  168. blocks,
  169. entity_state(&config, client.as_ref(), &id).await,
  170. )
  171. }));
  172. }
  173. let mut st = EntityStates::default();
  174. for h in futures::future::join_all(handles).await {
  175. let Ok((id, blocks, state)) = h else {
  176. continue;
  177. };
  178. let on = matches!(&state, Some(s) if s == "on");
  179. if !on {
  180. if blocks {
  181. st.blocking_off = true;
  182. } else {
  183. st.soft_off.push(id);
  184. }
  185. }
  186. }
  187. st
  188. }
  189. /// The state of one entity through the correct backend: a `[mikrotik]`
  190. /// device is probed with a RouterOS API login (logged in = "on";
  191. /// unreachable or rejected login = "off", like a switch that does not
  192. /// answer), everything else goes through HA REST.
  193. /// Returns `None` only when the entity has no configured backend at all
  194. /// (unknown — callers keep the "nothing to check ≠ off" semantics).
  195. pub async fn entity_state(
  196. config: &Config,
  197. client: Option<&Client>,
  198. entity_id: &str,
  199. ) -> Option<String> {
  200. if let Some(dev) = config
  201. .mikrotik
  202. .as_ref()
  203. .and_then(|m| m.devices.iter().find(|d| d.name == entity_id))
  204. {
  205. return match crate::mikrotik::ping_device(dev).await {
  206. Ok(()) => Some("on".to_string()),
  207. Err(e) => {
  208. warn!("RouterOS ping {entity_id} failed: {e}");
  209. Some("off".to_string())
  210. }
  211. };
  212. }
  213. let client = client?;
  214. client
  215. .get_state(entity_id)
  216. .await
  217. .map(|s| if s == "on" { "on".into() } else { "off".into() })
  218. }
  219. /// Parse `switch.dgx1` into `("switch", "dgx1")` so callers can build
  220. /// their own endpoints if needed. Exposed for the `power` subcommand
  221. /// and for tests.
  222. pub fn split_entity(entity_id: &str) -> Result<(&str, &str)> {
  223. let (domain, entity) = entity_id.split_once('.').ok_or_else(|| {
  224. anyhow!(
  225. "entity_id '{}' has no domain (e.g. 'switch.foo')",
  226. entity_id
  227. )
  228. })?;
  229. if domain.is_empty() || entity.is_empty() {
  230. anyhow::bail!("entity_id '{}' has empty domain or entity name", entity_id);
  231. }
  232. Ok((domain, entity))
  233. }
  234. /// Emit a deprecation-style warning if a HA token looks suspiciously
  235. /// short. HA tokens are typically 100+ chars; anything shorter is
  236. /// almost certainly a placeholder.
  237. pub fn warn_if_token_looks_short(token: &str) {
  238. if token.len() < 20 {
  239. warn!(
  240. "[home_assistant].token looks suspiciously short ({} chars); \
  241. did you paste a placeholder?",
  242. token.len()
  243. );
  244. }
  245. }
  246. #[cfg(test)]
  247. mod tests {
  248. use super::*;
  249. #[tokio::test]
  250. async fn mikrotik_entity_unreachable_is_blocking_off() {
  251. // A `[mikrotik]` device referenced from `extra_entities` is probed
  252. // through the RouterOS API: unreachable (closed port) = off, and a
  253. // blocking entity takes the cluster down — the r18-class "dead
  254. // entity silently skipped" failure mode must not exist.
  255. let toml = r#"
  256. ssh_user = "u"
  257. [[clusters]]
  258. name = "c1"
  259. nodes = [{ name = "n1", ssh_ip = "10.0.0.1", rank = 0 }]
  260. extra_entities = ["rt"]
  261. [mikrotik]
  262. [[mikrotik.devices]]
  263. name = "rt"
  264. address = "127.0.0.1"
  265. username = "x"
  266. password = "y"
  267. api_port = 1
  268. "#;
  269. let config: crate::config::Config = toml::from_str(toml).unwrap();
  270. let cluster = &config.clusters[0];
  271. let st = extra_entities_states(&config, cluster).await;
  272. assert!(
  273. st.blocking_off,
  274. "unreachable mikrotik device must be blocking-off"
  275. );
  276. }
  277. #[tokio::test]
  278. async fn mikrotik_device_without_backend_not_reported_off() {
  279. // No [mikrotik] section, no HA → the entity has no backend at all:
  280. // "nothing to check", not off (legacy semantics).
  281. let toml = r#"
  282. ssh_user = "u"
  283. [[clusters]]
  284. name = "c1"
  285. nodes = [{ name = "n1", ssh_ip = "10.0.0.1", rank = 0 }]
  286. extra_entities = ["rt"]
  287. "#;
  288. let config: crate::config::Config = toml::from_str(toml).unwrap();
  289. let cluster = &config.clusters[0];
  290. let st = extra_entities_states(&config, cluster).await;
  291. assert!(!st.blocking_off);
  292. assert!(st.soft_off.is_empty());
  293. }
  294. #[test]
  295. fn split_entity_basic() {
  296. assert_eq!(split_entity("switch.dgx1").unwrap(), ("switch", "dgx1"));
  297. assert_eq!(
  298. split_entity("light.living_room").unwrap(),
  299. ("light", "living_room")
  300. );
  301. }
  302. #[test]
  303. fn split_entity_no_domain_errors() {
  304. assert!(split_entity("dgx1").is_err());
  305. }
  306. #[test]
  307. fn split_entity_empty_entity_errors() {
  308. assert!(split_entity("switch.").is_err());
  309. }
  310. #[test]
  311. fn split_entity_empty_domain_errors() {
  312. assert!(split_entity(".thing").is_err());
  313. }
  314. #[test]
  315. fn endpoint_extracts_domain() {
  316. let (_d, path) = Client::endpoint("switch.dgx1", "turn_off").unwrap();
  317. assert_eq!(path, "/api/services/switch/turn_off");
  318. let (_d, path) = Client::endpoint("light.kitchen", "turn_on").unwrap();
  319. assert_eq!(path, "/api/services/light/turn_on");
  320. }
  321. #[test]
  322. fn endpoint_rejects_no_domain() {
  323. assert!(Client::endpoint("plain", "turn_off").is_err());
  324. }
  325. }