anker_solix 0.2.1

Library and CLI for monitoring/controlling Anker SOLIX power stations over Bluetooth LE
Documentation
//! Async BLE session with a SOLIX power station: discovery, the ECDH
//! negotiation handshake, encrypted command transmission and telemetry receive.

use crate::crypto::{decrypt, derive_shared_secret, encrypt};
use crate::error::{AnkerError, Result};
use crate::model::{Model, Telemetry};
use crate::protocol::*;
use btleplug::api::{Central, Manager as _, Peripheral as _, ScanFilter, WriteType};
use btleplug::platform::{Adapter, Manager, Peripheral};
use futures_util::{Stream, StreamExt};
use std::pin::Pin;
use std::time::{Duration, Instant};
use uuid::Uuid;

/// A discovered SOLIX device advertisement.
#[derive(Debug, Clone)]
pub struct Discovered {
    pub name: String,
    pub address: String,
    pub rssi: Option<i16>,
    pub model: Model,
    peripheral: Peripheral,
}

type NotifStream = Pin<Box<dyn Stream<Item = btleplug::api::ValueNotification> + Send>>;

/// A negotiated session with a power station.
pub struct Device {
    peripheral: Peripheral,
    cmd_char: btleplug::api::Characteristic,
    notifications: NotifStream,
    model: Model,
    name: String,
    shared_secret: [u8; 32],
    /// Reference instant for the replay-protection timestamp (set at stage 3).
    negotiated_at: Instant,
    fragmenter: Fragmenter,
}

async fn first_adapter() -> Result<Adapter> {
    let manager = Manager::new().await?;
    let adapters = manager.adapters().await?;
    adapters.into_iter().next().ok_or(AnkerError::NoAdapter)
}

fn uuid(s: &str) -> Uuid {
    Uuid::parse_str(s).expect("static UUID is valid")
}

/// Scan for nearby SOLIX / Prime devices for `secs` seconds.
pub async fn scan(secs: u64) -> Result<Vec<Discovered>> {
    let adapter = first_adapter().await?;
    adapter.start_scan(ScanFilter::default()).await?;
    tokio::time::sleep(Duration::from_secs(secs)).await;

    let identifier = uuid(UUID_IDENTIFIER);
    let mut found = Vec::new();
    for p in adapter.peripherals().await? {
        let props = match p.properties().await? {
            Some(props) => props,
            None => continue,
        };
        let advertises_anker = props.services.contains(&identifier);
        let name = props.local_name.clone().unwrap_or_default();
        // Some stacks don't surface the service UUID; fall back to name hints.
        let looks_anker = advertises_anker
            || name.to_ascii_uppercase().contains("ANKER")
            || name.to_ascii_uppercase().contains("SOLIX");
        if !looks_anker {
            continue;
        }
        found.push(Discovered {
            model: Model::detect(&name),
            name,
            address: p.address().to_string(),
            rssi: props.rssi,
            peripheral: p,
        });
    }
    let _ = adapter.stop_scan().await;
    Ok(found)
}

impl Discovered {
    /// Connect and run the full encryption handshake, returning a ready session.
    pub async fn connect(self) -> Result<Device> {
        Device::connect(self.peripheral, self.name, self.model).await
    }
}

impl Device {
    pub fn model(&self) -> Model {
        self.model
    }
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Find a device by name substring (case-insensitive) or MAC address and connect.
    pub async fn find_and_connect(target: &str, scan_secs: u64) -> Result<Device> {
        let want = target.to_ascii_lowercase();
        let devices = scan(scan_secs).await?;
        let chosen = devices
            .into_iter()
            .find(|d| {
                d.address.to_ascii_lowercase() == want
                    || d.name.to_ascii_lowercase().contains(&want)
            })
            .ok_or_else(|| AnkerError::DeviceNotFound(target.to_string()))?;
        chosen.connect().await
    }

    async fn connect(peripheral: Peripheral, name: String, model: Model) -> Result<Device> {
        if !peripheral.is_connected().await? {
            peripheral.connect().await?;
        }
        peripheral.discover_services().await?;

        let chars = peripheral.characteristics();
        let cmd_char = chars
            .iter()
            .find(|c| c.uuid == uuid(UUID_COMMAND))
            .cloned()
            .ok_or(AnkerError::CharacteristicNotFound("command"))?;
        let telemetry_char = chars
            .iter()
            .find(|c| c.uuid == uuid(UUID_TELEMETRY))
            .cloned()
            .ok_or(AnkerError::CharacteristicNotFound("telemetry"))?;

        peripheral.subscribe(&telemetry_char).await?;
        let notifications = peripheral.notifications().await?;

        let mut dev = Device {
            peripheral,
            cmd_char,
            notifications,
            model,
            name,
            shared_secret: [0u8; 32],
            negotiated_at: Instant::now(),
            fragmenter: Fragmenter::new(),
        };

        dev.negotiate().await?;

        // Gen 2 streams nothing until subscribed.
        if let Some((cmd, payload)) = dev.model.subscribe_command() {
            dev.send_command(cmd, payload).await?;
        }

        Ok(dev)
    }

    // Takes `&mut self` (not `&self`) so the returned future captures `&mut
    // Device` rather than `&Device`; the latter would require `Device: Sync`,
    // which fails because the boxed notification stream is `Send` but not `Sync`.
    async fn write_raw(&mut self, bytes: &[u8]) -> Result<()> {
        self.peripheral
            .write(&self.cmd_char, bytes, WriteType::WithResponse)
            .await?;
        Ok(())
    }

    /// Run the fixed ECDH handshake until an encrypted session is established.
    async fn negotiate(&mut self) -> Result<()> {
        self.write_raw(&hex::decode(NEGOTIATION_COMMAND_0).unwrap())
            .await?;

        let overall = Duration::from_secs(90);
        let start = Instant::now();

        loop {
            if start.elapsed() > overall {
                return Err(AnkerError::NegotiationTimeout);
            }
            let notif = match tokio::time::timeout(
                Duration::from_secs(15),
                self.notifications.next(),
            )
            .await
            {
                Ok(Some(n)) => n,
                Ok(None) => return Err(AnkerError::NegotiationTimeout),
                Err(_) => return Err(AnkerError::NegotiationTimeout),
            };

            let packet = match split_packet(&notif.value) {
                Ok(p) => p,
                Err(e) => {
                    log::debug!("ignoring malformed packet during negotiation: {e}");
                    continue;
                }
            };

            if packet.pattern != PATTERN_NEGOTIATION {
                log::debug!("non-negotiation packet {:02x?} ignored", packet.pattern);
                continue;
            }

            if self.handle_negotiation_stage(&packet).await? {
                log::info!("encrypted session negotiated with '{}'", self.name);
                return Ok(());
            }
        }
    }

    /// Handle one negotiation packet. Returns `true` once the session is ready.
    async fn handle_negotiation_stage(&mut self, packet: &Packet) -> Result<bool> {
        match packet.cmd {
            [0x08, 0x01] => {
                self.write_raw(&hex::decode(NEGOTIATION_COMMAND_1).unwrap())
                    .await?;
            }
            [0x08, 0x03] => {
                self.write_raw(&hex::decode(NEGOTIATION_COMMAND_2).unwrap())
                    .await?;
            }
            [0x08, 0x29] => {
                // Timestamp reference for replay protection is set here.
                self.negotiated_at = Instant::now();
                self.write_raw(&hex::decode(NEGOTIATION_COMMAND_3).unwrap())
                    .await?;
            }
            [0x08, 0x05] => {
                self.write_raw(&hex::decode(NEGOTIATION_COMMAND_4).unwrap())
                    .await?;
            }
            [0x08, 0x21] => {
                let params = parse_params(&packet.payload);
                let pubkey = params
                    .get("a1")
                    .ok_or_else(|| AnkerError::Crypto("stage 5 missing device pubkey".into()))?;
                self.shared_secret = derive_shared_secret(pubkey)?;
                self.write_raw(&hex::decode(NEGOTIATION_COMMAND_5).unwrap())
                    .await?;
                return Ok(true);
            }
            other => {
                log::debug!("unexpected negotiation cmd {:02x?}", other);
            }
        }
        Ok(false)
    }

    /// Send an encrypted command. The replay-protection timestamp and trailer
    /// are appended before encryption.
    ///
    /// Takes `&mut self` so that the returned future is `Send` even though the
    /// notification stream is not `Sync`; this lets `Device` be driven from
    /// `Send` async contexts (e.g. trait objects).
    pub async fn send_command(&mut self, cmd: [u8; 2], payload: &[u8]) -> Result<()> {
        let elapsed = self.negotiated_at.elapsed().as_secs() as u32;
        let timestamp = BASE_TIMESTAMP_LE.wrapping_add(elapsed);

        let mut full = Vec::with_capacity(payload.len() + 7);
        full.extend_from_slice(payload);
        full.extend_from_slice(&[0xfe, 0x05, 0x03]);
        full.extend_from_slice(&timestamp.to_le_bytes());

        let ciphertext = encrypt(&self.shared_secret, &full);
        let packet = build_packet(PATTERN_ENCRYPTED_TX, cmd, &ciphertext);
        self.write_raw(&packet).await
    }

    /// Wait for the next decoded telemetry snapshot (up to `timeout`).
    pub async fn next_telemetry(&mut self, timeout: Duration) -> Result<Telemetry> {
        let deadline = Instant::now() + timeout;
        loop {
            let remaining = deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                return Err(AnkerError::ResponseTimeout);
            }
            let notif =
                match tokio::time::timeout(remaining, self.notifications.next()).await {
                    Ok(Some(n)) => n,
                    _ => return Err(AnkerError::ResponseTimeout),
                };
            if let Some(t) = self.process_session_packet(&notif.value)? {
                return Ok(t);
            }
        }
    }

    /// Decode a session (telemetry) notification, returning telemetry when a
    /// complete, decrypted snapshot is available.
    fn process_session_packet(&mut self, raw: &[u8]) -> Result<Option<Telemetry>> {
        let packet = match split_packet(raw) {
            Ok(p) => p,
            Err(e) => {
                log::debug!("ignoring malformed telemetry packet: {e}");
                return Ok(None);
            }
        };

        let is_session =
            packet.pattern == PATTERN_SESSION_A || packet.pattern == PATTERN_SESSION_B;
        if !is_session {
            return Ok(None);
        }

        // Plaintext telemetry (older firmware).
        if packet.cmd == [0x03, 0x00] {
            let params = parse_params(&packet.payload);
            return Ok(Some(Telemetry::from_params(self.model, &params)));
        }

        // Encrypted telemetry on a model-specific command code.
        if self.model.telemetry_commands().contains(&packet.cmd) {
            if let Some(body) = self.fragmenter.push(packet.cmd, &packet.payload) {
                let plaintext = decrypt(&self.shared_secret, &body)?;
                let params = parse_params(&plaintext);
                return Ok(Some(Telemetry::from_params(self.model, &params)));
            }
        } else {
            log::debug!("unhandled session cmd {:02x?}", packet.cmd);
        }
        Ok(None)
    }

    /// Turn the AC output on or off.
    pub async fn set_ac(&mut self, on: bool) -> Result<()> {
        self.send_command(self.model.cmd_ac_output(), crate::model::on_off_payload(on))
            .await
    }

    /// Turn the DC (12 V) output on or off.
    pub async fn set_dc(&mut self, on: bool) -> Result<()> {
        self.send_command(self.model.cmd_dc_output(), crate::model::on_off_payload(on))
            .await
    }

    /// Disconnect from the device.
    pub async fn disconnect(&self) -> Result<()> {
        self.peripheral.disconnect().await?;
        Ok(())
    }
}