diff --git a/README.md b/README.md index 5960ff4..0aaae12 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Switch or power-cycle smart plugs from scripts, CI jobs and Rust: one binary, no Python or .NET at run time. Built for power-cycling hardware under test, where switching the wrong plug, or switching it back on too soon, is the thing to avoid. -TP-Link Kasa plugs come first, including firmware that only accepts KLAP (the encrypted HTTP protocol that needs the TP-Link account login). Other brands can be added behind the same `Brand` and `Plug` traits. +TP-Link Kasa plugs come first, including firmware that only accepts KLAP (the encrypted HTTP protocol that needs the TP-Link account login). Kasa bulbs work too, for on, off, state and cycle only: no brightness or colour. Other brands can be added behind the same `Brand` and `Plug` traits. - Plugs are identified by **MAC**, so a DHCP move cannot make it switch the wrong device: the MAC the plug reports is checked before anything is sent. - **Protected** plugs refuse `off` and `cycle` without `--allow-protected`, however they are addressed. diff --git a/crates/plugctl/src/kasa.rs b/crates/plugctl/src/kasa.rs index becb594..a226613 100644 --- a/crates/plugctl/src/kasa.rs +++ b/crates/plugctl/src/kasa.rs @@ -1,4 +1,4 @@ -//! TP-Link Kasa plugs over KLAP, through the `kasa-core` crate. +//! TP-Link Kasa plugs and bulbs over KLAP, through the `kasa-core` crate. //! //! KLAP is the HTTP protocol (port 80) that current Kasa firmware requires: a two-step handshake //! proves both sides know a hash of the TP-Link account login, then each request is AES-CBC @@ -7,10 +7,11 @@ use std::collections::BTreeMap; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::sync::OnceLock; use std::time::Duration; use async_trait::async_trait; -use kasa_core::transport::{KlapTransport, TransportExt}; +use kasa_core::transport::{KlapTransport, Transport}; use tokio::net::UdpSocket; @@ -60,7 +61,11 @@ impl Brand for Kasa { let transport = KlapTransport::connect(&host, addr.port(), creds, self.timeout, false) .await .map_err(|e| device_error(addr, &e))?; - Ok(Box::new(KasaPlug { addr, transport })) + Ok(Box::new(KasaPlug { + addr, + transport, + kind: OnceLock::new(), + })) } async fn discover(&self, broadcast: &[Ipv4Addr], timeout: Duration) -> Result> { @@ -76,34 +81,154 @@ impl Brand for Kasa { struct KasaPlug { addr: SocketAddr, transport: KlapTransport, + /// What kind of device this is, learned from the first sysinfo read. + kind: OnceLock, +} + +/// Kasa devices share the sysinfo command but switch through different modules. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + /// Plugs, power strips' main relay, wall switches: `relay_state`. + Relay, + /// Bulbs: `light_state.on_off`, switched through the lighting service. + Bulb, + /// Light strips: like a bulb, through their own service. Not tested on a real strip. + LightStrip, +} + +impl Kind { + /// The module a switch command goes to, and the method within it. + fn switch_target(self) -> (&'static str, &'static str) { + match self { + Self::Relay => ("system", "set_relay_state"), + Self::Bulb => ( + "smartlife.iot.smartbulb.lightingservice", + "transition_light_state", + ), + Self::LightStrip => ("smartlife.iot.lightStrip", "transition_light_state"), + } + } + + /// The JSON command that switches a device of this kind. + fn switch_command(self, on: bool) -> String { + let (module, method) = self.switch_target(); + let on = u8::from(on); + let args = match self { + Self::Relay => serde_json::json!({ "state": on }), + // No fade, so an off is an off straight away, as on a plug. + Self::Bulb | Self::LightStrip => { + serde_json::json!({ "on_off": on, "transition_period": 0 }) + } + }; + serde_json::json!({ module: { method: args } }).to_string() + } +} + +/// Reads the device's identity, state and kind from a `get_sysinfo` reply. +fn parse_sysinfo(reply: &str) -> std::result::Result<(PlugInfo, Kind), String> { + let v: serde_json::Value = serde_json::from_str(reply).map_err(|e| e.to_string())?; + let s = v + .pointer("/system/get_sysinfo") + .ok_or("reply has no system.get_sysinfo")?; + let text = |k: &str| { + s.get(k) + .and_then(serde_json::Value::as_str) + .unwrap_or_default() + .to_owned() + }; + let int = |v: Option<&serde_json::Value>| v.and_then(serde_json::Value::as_i64); + // Bulbs report on/off in light_state and have no relay_state, which a plug's reading + // would take as off. + let (kind, on) = match s.get("light_state") { + Some(light) => { + let kind = if s.get("length").is_some() { + Kind::LightStrip + } else { + Kind::Bulb + }; + (kind, int(light.get("on_off")) == Some(1)) + } + None => (Kind::Relay, int(s.get("relay_state")) == Some(1)), + }; + let mac = Some(text("mac")) + .filter(|m| !m.is_empty()) + .unwrap_or_else(|| text("mic_mac")); + let on_time = int(s.get("on_time")).and_then(|t| u64::try_from(t).ok()); + let rssi = int(s.get("rssi")).and_then(|r| i32::try_from(r).ok()); + let info = PlugInfo { + alias: text("alias"), + model: text("model"), + mac: mac.parse().map_err(|e: Error| e.to_string())?, + on, + // Bulbs do not say how long they have been on. + on_for: if on { + on_time.map(Duration::from_secs) + } else { + None + }, + firmware: text("sw_ver"), + rssi: rssi.filter(|r| *r != 0), + }; + Ok((info, kind)) +} + +/// Checks the `err_code` in a switch reply. A device without the module answers with a +/// non-zero code rather than failing the request, so without this a plug command sent to a +/// bulb would look like it worked. +fn check_switch_reply(kind: Kind, reply: &str) -> std::result::Result<(), String> { + let (module, method) = kind.switch_target(); + let v: serde_json::Value = serde_json::from_str(reply).map_err(|e| e.to_string())?; + let r = v + .get(module) + .and_then(|m| m.get(method)) + .ok_or_else(|| format!("reply has no {module}.{method}: {reply}"))?; + match r.get("err_code").and_then(serde_json::Value::as_i64) { + Some(0) => Ok(()), + Some(code) => Err(format!( + "{module}.{method} failed with err_code {code}: {}", + r.get("err_msg") + .and_then(serde_json::Value::as_str) + .unwrap_or("no message") + )), + None => Err(format!("{module}.{method} reply has no err_code: {reply}")), + } } #[async_trait] impl Plug for KasaPlug { async fn info(&self) -> Result { - let s = self + let reply = self .transport - .get_sysinfo() + .send(SYSINFO_COMMAND) .await .map_err(|e| device_error(self.addr, &e))?; - let mac = s.mac_address().parse()?; - let on = s.relay_state == 1; - Ok(PlugInfo { - alias: s.alias, - model: s.model, - mac, - on, - on_for: on.then(|| Duration::from_secs(s.on_time)), - firmware: s.sw_ver, - rssi: (s.rssi != 0).then_some(s.rssi), - }) + let (info, kind) = parse_sysinfo(&reply).map_err(|m| self.error(m))?; + let _ = self.kind.set(kind); + Ok(info) } async fn set_on(&self, on: bool) -> Result<()> { - self.transport - .set_relay_state(on) + let kind = if let Some(k) = self.kind.get() { + *k + } else { + self.info().await?; + self.kind.get().copied().unwrap_or(Kind::Relay) + }; + let reply = self + .transport + .send(&kind.switch_command(on)) .await - .map_err(|e| device_error(self.addr, &e)) + .map_err(|e| device_error(self.addr, &e))?; + check_switch_reply(kind, &reply).map_err(|m| self.error(m)) + } +} + +impl KasaPlug { + fn error(&self, message: String) -> Error { + Error::Device { + host: self.addr.to_string(), + message, + } } } @@ -123,7 +248,8 @@ const TDP_DISCOVERY_PORT: u16 = 20002; const TDP_PROBE: [u8; 16] = [ 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x3c, 0xb5, 0xd3, ]; -const SYSINFO: &[u8] = br#"{"system":{"get_sysinfo":{}}}"#; +const SYSINFO_COMMAND: &str = r#"{"system":{"get_sysinfo":{}}}"#; +const SYSINFO: &[u8] = SYSINFO_COMMAND.as_bytes(); /// A public key for the TDP probe that current firmware (KLAP-only HS103 among it) needs before /// it answers. The plug encrypts part of its reply to this key; plugctl only reads the plain /// part, so the private half was thrown away when this was generated. @@ -303,6 +429,59 @@ mod tests { assert!(String::from_utf8_lossy(&q[16..]).contains("BEGIN PUBLIC KEY")); } + const BULB: &str = r#"{"system":{"get_sysinfo":{"sw_ver":"1.1.1 Build 1","model":"KL125(US)","alias":"Lamp","mic_type":"IOT.SMARTBULB","mic_mac":"00005E005301","rssi":-50,"light_state":{"on_off":1,"mode":"normal","hue":0,"saturation":0,"color_temp":2700,"brightness":100},"err_code":0}}}"#; + const PLUG: &str = r#"{"system":{"get_sysinfo":{"sw_ver":"1.1.4","model":"HS103(US)","alias":"Bench","mac":"00:00:5E:00:53:02","relay_state":1,"on_time":42,"rssi":-60,"err_code":0}}}"#; + + #[test] + fn reads_a_bulb() { + let (info, kind) = parse_sysinfo(BULB).unwrap(); + assert_eq!(kind, Kind::Bulb); + assert!(info.on); + assert_eq!(info.on_for, None); + assert_eq!(info.mac.to_string(), "00:00:5E:00:53:01"); + assert_eq!((info.model.as_str(), info.rssi), ("KL125(US)", Some(-50))); + + let off = BULB.replace(r#""on_off":1"#, r#""on_off":0"#); + assert!(!parse_sysinfo(&off).unwrap().0.on); + let strip = BULB.replace(r#""rssi""#, r#""length":16,"rssi""#); + assert_eq!(parse_sysinfo(&strip).unwrap().1, Kind::LightStrip); + } + + #[test] + fn reads_a_plug() { + let (info, kind) = parse_sysinfo(PLUG).unwrap(); + assert_eq!(kind, Kind::Relay); + assert!(info.on); + assert_eq!(info.on_for, Some(Duration::from_secs(42))); + let off = PLUG.replace(r#""relay_state":1"#, r#""relay_state":0"#); + assert!(!parse_sysinfo(&off).unwrap().0.on); + } + + #[test] + fn switch_commands() { + let v = |s: String| serde_json::from_str::(&s).unwrap(); + assert_eq!( + v(Kind::Relay.switch_command(false)), + serde_json::json!({"system":{"set_relay_state":{"state":0}}}) + ); + assert_eq!( + v(Kind::Bulb.switch_command(true)), + serde_json::json!({"smartlife.iot.smartbulb.lightingservice":{"transition_light_state":{"on_off":1,"transition_period":0}}}) + ); + } + + #[test] + fn checks_switch_replies() { + let ok = r#"{"smartlife.iot.smartbulb.lightingservice":{"transition_light_state":{"on_off":0,"err_code":0}}}"#; + assert!(check_switch_reply(Kind::Bulb, ok).is_ok()); + // A non-zero code, as a device gives for a method it does not have. + let wrong = + r#"{"system":{"set_relay_state":{"err_code":-2,"err_msg":"member not support"}}}"#; + let e = check_switch_reply(Kind::Relay, wrong).unwrap_err(); + assert!(e.contains("err_code -2"), "{e}"); + assert!(check_switch_reply(Kind::Bulb, wrong).is_err()); + } + #[test] fn parses_replies() { let ip: IpAddr = "192.0.2.10".parse().unwrap(); diff --git a/docs/manual-tests.md b/docs/manual-tests.md index a68ce64..44af8d0 100644 --- a/docs/manual-tests.md +++ b/docs/manual-tests.md @@ -13,6 +13,7 @@ These need a real plug, so CI does not run them. Run them after changing the Kas 1. Remove `host` from a plug behind an SSH route; `plugctl state -v` logs `looked up MAC ... found=Some(...)` and still reaches it. 1. `plugctl state --via --json` shows the configured name and `protected` for that plug's MAC. 1. Compare with python-kasa: `uvx --from python-kasa kasa --host --device-family IOT.SMARTPLUGSWITCH --encrypt-type KLAP --login-version 2 state` agrees on the state. +1. For a bulb, `plugctl state ` agrees with python-kasa's `--device-family IOT.SMARTBULB` on/off, both while it is on and while it is off. The opt-in test does the first check from Rust: @@ -44,6 +45,7 @@ After changing the Dockerfile or the image job, with an image built from the rel 1. `plugctl cycle ` prints the off time, and the plug comes back on after it; python-kasa reports the new on time. 1. `plugctl off `, then `plugctl on ` straight away: `on` prints that it is waiting out `min_off`, and python-kasa's "on since" is at least `min_off` after the off. +1. On a bulb, `plugctl off ` and `plugctl on ` switch it at once, with no fade, and it comes back at the brightness and colour it had. The opt-in test cycles the plug: