garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /wifi/src/host.rs

raw

//! The radio's driver: one AT command in flight at a time, the lines that
//! come back sorted into each command's answer and what the radio says of
//! its own accord (the network lost).
//!
//! Set up with echo off, as a station (`AT+CWMODE=1`), nothing kept in the
//! radio's flash (`AT+SYSSTORE=0`), and scan results strongest first with
//! their security, name, signal, address and channel (`AT+CWLAPOPT=1,31`).
//! A scan is `AT+CWLAP`, a line `+CWLAP:(<ecn>,"<ssid>",<rssi>,"<mac>",<channel>)`
//! per access point and `OK`. A join is `AT+CWJAP="<ssid>","<password>"`
//! (`\` before a `"`, `,` or `\` in either), answered `WIFI CONNECTED`,
//! `WIFI GOT IP` and `OK`, or `+CWJAP:<code>` and `ERROR` (or `FAIL`).

use alloc::collections::VecDeque;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

/// How long a command may go unanswered before it is taken as failed.
const COMMAND_MS: u64 = 3000;
/// How long a scan may take: every channel listened on in turn.
const SCAN_MS: u64 = 15_000;
/// How long a join may take: association, WPA's handshake, then DHCP.
const JOIN_MS: u64 = 20_000;

/// How a network is protected, as `AT+CWLAP` numbers it (`<ecn>`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Security {
    Open,
    Wep,
    Wpa,
    Wpa2,
    WpaWpa2,
    /// WPA2 with an account per person (802.1X): not joinable by password.
    Enterprise,
    Wpa3,
    Wpa2Wpa3,
}

impl Security {
    pub fn from_ecn(ecn: u8) -> Option<Security> {
        Some(match ecn {
            0 => Security::Open,
            1 => Security::Wep,
            2 => Security::Wpa,
            3 => Security::Wpa2,
            4 => Security::WpaWpa2,
            5 => Security::Enterprise,
            6 => Security::Wpa3,
            7 => Security::Wpa2Wpa3,
            _ => return None,
        })
    }

    pub fn ecn(self) -> u8 {
        self as u8
    }

    /// Whether joining asks for a password.
    pub fn needs_password(self) -> bool {
        self != Security::Open
    }

    /// As Settings names it.
    pub fn text(self) -> &'static str {
        match self {
            Security::Open => "Open",
            Security::Wep => "WEP",
            Security::Wpa => "WPA",
            Security::Wpa2 | Security::WpaWpa2 => "WPA2",
            Security::Enterprise => "WPA2 Enterprise",
            Security::Wpa3 | Security::Wpa2Wpa3 => "WPA3",
        }
    }
}

/// An access point heard in a scan.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Network {
    pub ssid: String,
    pub bssid: [u8; 6],
    /// Signal strength, in dBm.
    pub rssi: i16,
    pub channel: u8,
    pub security: Security,
}

impl Network {
    /// The signal as bars, 0 to 4: four from -55 dBm, none under -85.
    pub fn bars(&self) -> u8 {
        match self.rssi {
            r if r >= -55 => 4,
            r if r >= -67 => 3,
            r if r >= -75 => 2,
            r if r >= -85 => 1,
            _ => 0,
        }
    }
}

/// Why a join failed: `+CWJAP:<code>`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Failure {
    /// 1: no answer from the access point in time.
    Timeout,
    /// 2: the password was refused.
    WrongPassword,
    /// 3: no access point of that name is in reach.
    NotFound,
    /// 4, or no code: it did not get on, for another reason.
    Failed,
}

impl Failure {
    pub fn from_code(code: u8) -> Failure {
        match code {
            1 => Failure::Timeout,
            2 => Failure::WrongPassword,
            3 => Failure::NotFound,
            _ => Failure::Failed,
        }
    }

    pub fn code(self) -> u8 {
        match self {
            Failure::Timeout => 1,
            Failure::WrongPassword => 2,
            Failure::NotFound => 3,
            Failure::Failed => 4,
        }
    }

    /// As Settings says it.
    pub fn text(self) -> &'static str {
        match self {
            Failure::Timeout => "The network did not answer",
            Failure::WrongPassword => "Wrong password",
            Failure::NotFound => "The network is out of reach",
            Failure::Failed => "Could not join",
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Event {
    /// The radio is set up and answers.
    Ready,
    /// A scan ended: one entry per network name, the strongest first.
    Scanned(Vec<Network>),
    /// A scan did not end well.
    ScanFailed,
    /// On the network.
    Joined { ssid: String },
    /// Not on it, and why.
    JoinFailed { ssid: String, failure: Failure },
    /// Left the network, as asked ([`Wifi::leave`]).
    Left,
    /// The network went (out of reach, or the access point dropped us).
    Lost { ssid: String },
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum Kind {
    Setup,
    Scan,
    Join(String),
    Leave,
}

struct Command {
    line: String,
    kind: Kind,
}

pub struct Wifi {
    queue: VecDeque<Command>,
    in_flight: Option<(Command, u64)>,
    out: VecDeque<Vec<u8>>,
    events: VecDeque<Event>,
    partial: Vec<u8>,
    ready: bool,
    /// What the scan in flight heard so far.
    heard: Vec<Network>,
    /// The `+CWJAP:<code>` of the join in flight.
    join_code: Option<u8>,
    joined: Option<String>,
}

impl Default for Wifi {
    fn default() -> Wifi {
        Wifi::new()
    }
}

/// `text` as an AT command's quoted parameter: `\` before `"`, `,` and `\`.
fn quoted(text: &str) -> String {
    let mut s = String::from("\"");
    for c in text.chars() {
        if matches!(c, '"' | ',' | '\\') {
            s.push('\\');
        }
        s.push(c);
    }
    s.push('"');
    s
}

/// A `+CWLAP:(…)` line's access point, its fields in `AT+CWLAPOPT`'s order.
/// The name is the only field that may hold a comma or a quote, so the
/// others are taken from both ends around it.
fn parse_cwlap(rest: &str) -> Option<Network> {
    let inner = rest.strip_prefix('(')?.strip_suffix(')')?;
    let mut tail = inner.rsplitn(4, ',');
    let channel = tail.next()?.trim().parse().ok()?;
    let mac = tail.next()?.trim().trim_matches('"');
    let rssi = tail.next()?.trim().parse().ok()?;
    let (ecn, ssid) = tail.next()?.split_once(',')?;
    let security = Security::from_ecn(ecn.trim().parse().ok()?)?;
    let ssid = ssid.strip_prefix('"')?.strip_suffix('"')?;
    let mut bssid = [0u8; 6];
    let mut parts = mac.split(':');
    for b in &mut bssid {
        *b = u8::from_str_radix(parts.next()?, 16).ok()?;
    }
    Some(Network {
        ssid: ssid.into(),
        bssid,
        rssi,
        channel,
        security,
    })
}

/// Whether `password` can protect a network of `security`: none for an
/// open one, else a WPA passphrase (8 to 63 characters) or its key in hex.
pub fn password_fits(security: Security, password: &str) -> bool {
    match security {
        Security::Open => password.is_empty(),
        Security::Enterprise => false,
        Security::Wep => matches!(password.len(), 5 | 13 | 10 | 26),
        _ => {
            (8..=63).contains(&password.chars().count())
                || (password.len() == 64 && password.bytes().all(|b| b.is_ascii_hexdigit()))
        }
    }
}

impl Wifi {
    /// A driver that starts setting the radio up.
    pub fn new() -> Wifi {
        let mut w = Wifi {
            queue: VecDeque::new(),
            in_flight: None,
            out: VecDeque::new(),
            events: VecDeque::new(),
            partial: Vec::new(),
            ready: false,
            heard: Vec::new(),
            join_code: None,
            joined: None,
        };
        w.setup();
        w
    }

    fn setup(&mut self) {
        for line in ["ATE0", "AT+CWMODE=1", "AT+SYSSTORE=0", "AT+CWLAPOPT=1,31"] {
            self.command(line, Kind::Setup);
        }
    }

    /// Whether the radio is set up and answers.
    pub fn ready(&self) -> bool {
        self.ready
    }

    /// The network it is on.
    pub fn joined(&self) -> Option<&str> {
        self.joined.as_deref()
    }

    /// Whether a scan is asked for or under way.
    pub fn scanning(&self) -> bool {
        self.commands().any(|k| *k == Kind::Scan)
    }

    /// The network a join is under way to.
    pub fn joining(&self) -> Option<&str> {
        self.commands().find_map(|k| match k {
            Kind::Join(ssid) => Some(ssid.as_str()),
            _ => None,
        })
    }

    fn commands(&self) -> impl Iterator<Item = &Kind> {
        self.in_flight
            .iter()
            .map(|(c, _)| &c.kind)
            .chain(self.queue.iter().map(|c| &c.kind))
    }

    /// The next bytes for the radio.
    pub fn transmit(&mut self) -> Option<Vec<u8>> {
        self.out.pop_front()
    }

    /// The next thing that happened.
    pub fn event(&mut self) -> Option<Event> {
        self.events.pop_front()
    }

    /// Listens for the networks nearby; [`Event::Scanned`] follows. A scan
    /// already asked for is not asked again.
    pub fn scan(&mut self, now: u64) {
        if !self.scanning() {
            self.command("AT+CWLAP", Kind::Scan);
        }
        self.send_next(now);
    }

    /// Joins network `ssid` with `password` (empty for an open one),
    /// leaving the one it is on. False when the name or password could not
    /// be any network's (see [`password_fits`] for what fits which).
    pub fn join(&mut self, ssid: &str, password: &str, now: u64) -> bool {
        if ssid.is_empty() || ssid.len() > 32 || password.len() > 64 {
            return false;
        }
        let line = alloc::format!("AT+CWJAP={},{}", quoted(ssid), quoted(password));
        self.queue.retain(|c| !matches!(c.kind, Kind::Join(_)));
        self.command(&line, Kind::Join(ssid.into()));
        self.send_next(now);
        true
    }

    /// Leaves the network it is on; [`Event::Left`] follows.
    pub fn leave(&mut self, now: u64) {
        self.queue.retain(|c| !matches!(c.kind, Kind::Join(_)));
        self.command("AT+CWQAP", Kind::Leave);
        self.send_next(now);
    }

    /// When [`poll`](Wifi::poll) is due next.
    pub fn next_deadline(&self) -> Option<u64> {
        self.in_flight.as_ref().map(|(c, sent)| sent + limit(&c.kind))
    }

    /// Timers: a command unanswered is failed. A radio that never answered
    /// its setup is set up again: on QEMU the other end of the port may
    /// connect after we spoke.
    pub fn poll(&mut self, now: u64) {
        if let Some((c, sent)) = &self.in_flight
            && now.saturating_sub(*sent) >= limit(&c.kind)
        {
            if c.kind == Kind::Setup && !self.ready {
                self.in_flight = None;
                self.queue.retain(|c| c.kind != Kind::Setup);
                self.setup();
            } else {
                self.finish(false);
            }
        }
        self.send_next(now);
    }

    /// Bytes from the radio.
    pub fn receive(&mut self, bytes: &[u8], now: u64) {
        for &b in bytes {
            if b == b'\n' {
                let raw = core::mem::take(&mut self.partial);
                let line = String::from_utf8_lossy(&raw);
                let line = line.trim();
                if !line.is_empty() {
                    let line = line.to_string();
                    self.line(&line);
                }
            } else {
                self.partial.push(b);
            }
        }
        self.send_next(now);
    }

    fn line(&mut self, line: &str) {
        let kind = self.in_flight.as_ref().map(|(c, _)| c.kind.clone());
        match line {
            "OK" => self.finish(true),
            "ERROR" | "FAIL" => self.finish(false),
            "WIFI CONNECTED" | "WIFI GOT IP" => {}
            "WIFI DISCONNECT" => {
                // Of its own accord, not as part of a join or a leave.
                if !matches!(kind, Some(Kind::Join(_) | Kind::Leave))
                    && let Some(ssid) = self.joined.take()
                {
                    self.events.push_back(Event::Lost { ssid });
                }
            }
            _ => {
                if let Some(rest) = line.strip_prefix("+CWLAP:") {
                    if kind == Some(Kind::Scan)
                        && let Some(n) = parse_cwlap(rest)
                    {
                        self.heard.push(n);
                    }
                } else if let Some(code) = line.strip_prefix("+CWJAP:") {
                    self.join_code = code.trim().parse().ok();
                }
                // Anything else (the echo of a command before `ATE0`
                // took, `busy p...`) is not news.
            }
        }
    }

    fn finish(&mut self, ok: bool) {
        let Some((command, _)) = self.in_flight.take() else {
            return;
        };
        match command.kind {
            Kind::Setup => {
                if !self.queue.iter().any(|c| c.kind == Kind::Setup) && !self.ready {
                    self.ready = true;
                    self.events.push_back(Event::Ready);
                }
            }
            Kind::Scan => {
                let heard = core::mem::take(&mut self.heard);
                if ok {
                    self.events.push_back(Event::Scanned(strongest(heard)));
                } else {
                    self.events.push_back(Event::ScanFailed);
                }
            }
            Kind::Join(ssid) => {
                let code = self.join_code.take();
                if ok {
                    self.joined = Some(ssid.clone());
                    self.events.push_back(Event::Joined { ssid });
                } else {
                    // A failed join leaves the radio on no network.
                    self.joined = None;
                    let failure = code.map_or(Failure::Failed, Failure::from_code);
                    self.events.push_back(Event::JoinFailed { ssid, failure });
                }
            }
            Kind::Leave => {
                self.joined = None;
                self.events.push_back(Event::Left);
            }
        }
    }

    fn command(&mut self, line: &str, kind: Kind) {
        self.queue.push_back(Command {
            line: line.into(),
            kind,
        });
    }

    fn send_next(&mut self, now: u64) {
        if self.in_flight.is_some() {
            return;
        }
        if let Some(c) = self.queue.pop_front() {
            if c.kind == Kind::Scan {
                self.heard.clear();
            }
            if matches!(c.kind, Kind::Join(_)) {
                self.join_code = None;
            }
            let mut bytes = c.line.clone().into_bytes();
            bytes.extend_from_slice(b"\r\n");
            self.out.push_back(bytes);
            self.in_flight = Some((c, now));
        }
    }
}

fn limit(kind: &Kind) -> u64 {
    match kind {
        Kind::Scan => SCAN_MS,
        Kind::Join(_) => JOIN_MS,
        _ => COMMAND_MS,
    }
}

/// One entry per name, the strongest access point of each, strongest first;
/// hidden networks (no name) left out.
fn strongest(heard: Vec<Network>) -> Vec<Network> {
    let mut out: Vec<Network> = Vec::new();
    for n in heard {
        if n.ssid.is_empty() {
            continue;
        }
        match out.iter_mut().find(|o| o.ssid == n.ssid) {
            Some(o) if o.rssi < n.rssi => *o = n,
            Some(_) => {}
            None => out.push(n),
        }
    }
    out.sort_by_key(|a| core::cmp::Reverse(a.rssi));
    out
}