garage44.eu/jeroen/pinnacle

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

.. /wifi/src/protocol.rs

raw

//! What the `wifi` service and its clients (Settings) say to each other.
//! A message is a kind byte, then its body. The service answers [`STATE`]
//! with the whole [`State`], and sends it to every client again whenever
//! it changes: a client draws what it was last told.

use crate::host::{Failure, Network, Security};
use alloc::string::String;
use alloc::vec::Vec;

// Client → service.
/// Listen for the networks nearby now (no body).
pub const SCAN: u8 = 1;
/// Ask for the state (answered with [`STATE_IS`]).
pub const STATE: u8 = 2;
/// Join a network (body: the name's length u8, the name, the password;
/// none for a network kept, which is joined with the password kept).
pub const JOIN: u8 = 3;
/// Leave the network it is on.
pub const LEAVE: u8 = 4;
/// Forget a network joined before (body: its name).
pub const FORGET: u8 = 5;
// Service → client.
/// The [`State`], as [`State::to_bytes`] writes it.
pub const STATE_IS: u8 = 0x80;

pub fn message(kind: u8, body: &[u8]) -> Vec<u8> {
    let mut m = alloc::vec![kind];
    m.extend_from_slice(body);
    m
}

/// [`JOIN`]'s body.
pub fn join_body(ssid: &str, password: &str) -> Vec<u8> {
    let mut b = Vec::new();
    put(&mut b, ssid);
    b.extend_from_slice(password.as_bytes());
    b
}

/// [`JOIN`]'s name and password.
pub fn join_from(body: &[u8]) -> Option<(String, String)> {
    let mut at = 0;
    let ssid = take(body, &mut at)?;
    let password = core::str::from_utf8(&body[at..]).ok()?;
    Some((ssid, password.into()))
}

/// A network heard, and whether it was joined before.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Nearby {
    pub network: Network,
    pub saved: bool,
}

/// Everything a client shows.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct State {
    /// Whether there is a radio, set up.
    pub ready: bool,
    pub scanning: bool,
    /// The network it is on.
    pub joined: Option<String>,
    /// The network a join is under way to.
    pub joining: Option<String>,
    /// The last join that failed, and why: until the next join.
    pub failed: Option<(String, Failure)>,
    /// What the last scan heard, the strongest first.
    pub nearby: Vec<Nearby>,
    /// Every network joined before, the most recent last.
    pub saved: Vec<String>,
}

fn put(b: &mut Vec<u8>, text: &str) {
    let text = &text.as_bytes()[..text.len().min(255)];
    b.push(text.len() as u8);
    b.extend_from_slice(text);
}

fn take(b: &[u8], at: &mut usize) -> Option<String> {
    let len = *b.get(*at)? as usize;
    let text = b.get(*at + 1..*at + 1 + len)?;
    *at += 1 + len;
    Some(String::from_utf8_lossy(text).into_owned())
}

fn byte(b: &[u8], at: &mut usize) -> Option<u8> {
    let v = *b.get(*at)?;
    *at += 1;
    Some(v)
}

fn maybe(b: &[u8], at: &mut usize) -> Option<Option<String>> {
    match byte(b, at)? {
        0 => Some(None),
        _ => Some(Some(take(b, at)?)),
    }
}

impl State {
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut b = alloc::vec![u8::from(self.ready), u8::from(self.scanning)];
        for name in [&self.joined, &self.joining] {
            match name {
                Some(n) => {
                    b.push(1);
                    put(&mut b, n);
                }
                None => b.push(0),
            }
        }
        match &self.failed {
            Some((ssid, failure)) => {
                b.push(failure.code());
                put(&mut b, ssid);
            }
            None => b.push(0),
        }
        b.push(self.nearby.len().min(255) as u8);
        for n in self.nearby.iter().take(255) {
            put(&mut b, &n.network.ssid);
            b.extend_from_slice(&n.network.bssid);
            b.push(n.network.rssi.clamp(-128, 127) as i8 as u8);
            b.push(n.network.channel);
            b.push(n.network.security.ecn());
            b.push(u8::from(n.saved));
        }
        b.push(self.saved.len().min(255) as u8);
        for s in self.saved.iter().take(255) {
            put(&mut b, s);
        }
        b
    }

    pub fn from_bytes(b: &[u8]) -> Option<State> {
        let mut at = 0;
        let ready = byte(b, &mut at)? != 0;
        let scanning = byte(b, &mut at)? != 0;
        let joined = maybe(b, &mut at)?;
        let joining = maybe(b, &mut at)?;
        let failed = match byte(b, &mut at)? {
            0 => None,
            code => Some((take(b, &mut at)?, Failure::from_code(code))),
        };
        let mut nearby = Vec::new();
        for _ in 0..byte(b, &mut at)? {
            let ssid = take(b, &mut at)?;
            let bssid = b.get(at..at + 6)?.try_into().ok()?;
            at += 6;
            let rssi = i16::from(byte(b, &mut at)? as i8);
            let channel = byte(b, &mut at)?;
            let security = Security::from_ecn(byte(b, &mut at)?)?;
            let saved = byte(b, &mut at)? != 0;
            nearby.push(Nearby {
                network: Network {
                    ssid,
                    bssid,
                    rssi,
                    channel,
                    security,
                },
                saved,
            });
        }
        let mut saved = Vec::new();
        for _ in 0..byte(b, &mut at)? {
            saved.push(take(b, &mut at)?);
        }
        Some(State {
            ready,
            scanning,
            joined,
            joining,
            failed,
            nearby,
            saved,
        })
    }
}

/// Which network joined before to join again: of those `heard` (the
/// strongest first, as a scan gives them), the one with the strongest
/// signal.
pub fn rejoin<'a>(saved: &'a [(String, String)], heard: &[Network]) -> Option<&'a (String, String)> {
    heard
        .iter()
        .find_map(|n| saved.iter().find(|(ssid, _)| *ssid == n.ssid))
}

/// The networks joined before, as the service keeps them: each name and
/// its password, length-prefixed, the most recent last.
pub fn saved_to_bytes(saved: &[(String, String)]) -> Vec<u8> {
    let mut b = Vec::new();
    for (ssid, password) in saved {
        put(&mut b, ssid);
        put(&mut b, password);
    }
    b
}

pub fn saved_from_bytes(b: &[u8]) -> Vec<(String, String)> {
    let mut out = Vec::new();
    let mut at = 0;
    while let (Some(ssid), Some(password)) = (take(b, &mut at), take(b, &mut at)) {
        out.push((ssid, password));
    }
    out
}