garage44.eu/jeroen/pinnacle

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

.. /wifi/src/sim.rs

raw

//! A simulated radio and the access points around it: what the driver is
//! tested against, and what `cargo xtask` puts behind a QEMU's serial port
//! so Settings lists and joins networks with no radio. The [`Radio`] takes
//! AT commands ([`Radio::receive`]) and answers as ESP-AT does
//! ([`Radio::transmit`]), from the [`AccessPoint`]s it is given: those in
//! reach are heard in a scan, and a join is let on with the password each
//! was set up with.

use crate::host::{Failure, Security, password_fits};
use alloc::collections::VecDeque;
use alloc::string::String;
use alloc::vec::Vec;

/// An access point nearby.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AccessPoint {
    pub ssid: String,
    pub bssid: [u8; 6],
    pub rssi: i16,
    pub channel: u8,
    pub security: Security,
    /// What it lets on with; empty for an open one.
    pub password: String,
    /// Whether it is in reach: one out of it is not heard and not joined.
    pub in_reach: bool,
}

impl AccessPoint {
    pub fn new(ssid: &str, rssi: i16, security: Security, password: &str) -> AccessPoint {
        // An address from the name, so each is its own and stays the same.
        let mut bssid = [0x02, 0, 0, 0, 0, 0];
        for (i, b) in ssid.bytes().enumerate() {
            bssid[1 + i % 5] ^= b.wrapping_mul(31).wrapping_add(i as u8);
        }
        AccessPoint {
            ssid: ssid.into(),
            bssid,
            rssi,
            channel: 1 + (bssid[5] % 11),
            security,
            password: password.into(),
            in_reach: true,
        }
    }
}

/// `AT+CWJAP`'s two quoted parameters, `\` taking the next character as is.
fn unquote_pair(params: &str) -> Option<(String, String)> {
    let mut fields = Vec::new();
    let mut chars = params.chars();
    loop {
        if chars.next()? != '"' {
            return None;
        }
        let mut s = String::new();
        loop {
            match chars.next()? {
                '\\' => s.push(chars.next()?),
                '"' => break,
                c => s.push(c),
            }
        }
        fields.push(s);
        match chars.next() {
            Some(',') => {}
            None => break,
            Some(_) => return None,
        }
    }
    let mut fields = fields.into_iter();
    Some((fields.next()?, fields.next().unwrap_or_default()))
}

/// A radio running ESP-AT, as a station.
#[derive(Default)]
pub struct Radio {
    pub access_points: Vec<AccessPoint>,
    echo: bool,
    partial: Vec<u8>,
    out: VecDeque<Vec<u8>>,
    /// The access point it is on.
    joined: Option<usize>,
    /// Every line it was sent, for tests to look at.
    pub heard: Vec<String>,
}

impl Radio {
    /// A radio with echo on, as one starts.
    pub fn new(access_points: Vec<AccessPoint>) -> Radio {
        Radio {
            access_points,
            echo: true,
            ..Radio::default()
        }
    }

    /// The access point it is on.
    pub fn joined(&self) -> Option<&AccessPoint> {
        self.joined.map(|i| &self.access_points[i])
    }

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

    /// Takes access point `ssid` out of reach, or back; the radio on it
    /// says it is disconnected.
    pub fn set_in_reach(&mut self, ssid: &str, in_reach: bool) {
        let Some(i) = self.access_points.iter().position(|a| a.ssid == ssid) else {
            return;
        };
        self.access_points[i].in_reach = in_reach;
        if !in_reach && self.joined == Some(i) {
            self.joined = None;
            self.say("WIFI DISCONNECT");
        }
    }

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

    fn say(&mut self, line: &str) {
        let mut b = line.as_bytes().to_vec();
        b.extend_from_slice(b"\r\n");
        self.out.push_back(b);
    }

    fn command(&mut self, line: String) {
        if self.echo {
            self.say(&line);
        }
        self.heard.push(line.clone());
        let (name, params) = line.split_once('=').unwrap_or((&line, ""));
        match name {
            "AT" | "AT+CWMODE" | "AT+SYSSTORE" | "AT+CWLAPOPT" => self.say("OK"),
            "ATE0" => {
                self.echo = false;
                self.say("OK");
            }
            "AT+CWLAP" => {
                let mut heard: Vec<&AccessPoint> = self.access_points.iter().filter(|a| a.in_reach).collect();
                heard.sort_by_key(|a| core::cmp::Reverse(a.rssi));
                let lines: Vec<String> = heard
                    .iter()
                    .map(|a| {
                        let m = a.bssid;
                        alloc::format!(
                            "+CWLAP:({},\"{}\",{},\"{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}\",{})",
                            a.security.ecn(),
                            a.ssid,
                            a.rssi,
                            m[0],
                            m[1],
                            m[2],
                            m[3],
                            m[4],
                            m[5],
                            a.channel
                        )
                    })
                    .collect();
                for l in lines {
                    self.say(&l);
                }
                self.say("OK");
            }
            "AT+CWJAP" => {
                let Some((ssid, password)) = unquote_pair(params) else {
                    self.say("ERROR");
                    return;
                };
                if self.joined.take().is_some() {
                    self.say("WIFI DISCONNECT");
                }
                let found = self
                    .access_points
                    .iter()
                    .position(|a| a.ssid == ssid && a.in_reach);
                let answer = match found {
                    None => Err(Failure::NotFound),
                    Some(i) => {
                        let a = &self.access_points[i];
                        if a.security == Security::Enterprise {
                            Err(Failure::Failed)
                        } else if a.password == password && password_fits(a.security, &password) {
                            Ok(i)
                        } else {
                            Err(Failure::WrongPassword)
                        }
                    }
                };
                match answer {
                    Ok(i) => {
                        self.joined = Some(i);
                        self.say("WIFI CONNECTED");
                        self.say("WIFI GOT IP");
                        self.say("OK");
                    }
                    Err(f) => {
                        self.say(&alloc::format!("+CWJAP:{}", f.code()));
                        self.say("ERROR");
                    }
                }
            }
            "AT+CWQAP" => {
                if self.joined.take().is_some() {
                    self.say("WIFI DISCONNECT");
                }
                self.say("OK");
            }
            _ => self.say("ERROR"),
        }
    }
}