garage44.eu/jeroen/pinnacle

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

.. /programs/src/bin/wifi.rs

raw

//! The Wi-Fi service: the driver (`pinnacle_wifi`) over the kernel's port
//! to the radio, offered to Settings as the service `wifi`
//! (`pinnacle_wifi::protocol` has the messages). It scans when the radio
//! is ready, when asked, and every half minute while a client listens;
//! joins what Settings asks with the password typed; and keeps each
//! network joined, its password with it, in the data vault
//! (`data:/wifi/networks`), joining the strongest of them it hears again
//! by itself: after a start, and after a network is lost.

#![no_std]
#![no_main]

extern crate alloc;

use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_rt::{Channel, Received, fs, println};
use pinnacle_wifi::protocol::{self, Nearby, State};
use pinnacle_wifi::{Event, Network, Wifi};

/// How often to scan while a client is there to see it.
const SCAN_EVERY_MS: u64 = 30_000;

/// Where the networks joined are kept: in the vault, once there is one.
fn saved_path() -> &'static str {
    if fs::disk("data").is_some() {
        "data:/wifi/networks"
    } else {
        "system:/wifi-networks"
    }
}

fn save(saved: &[(String, String)]) {
    let path = saved_path();
    fs::create_dir(path.rsplit_once('/').map_or("system:/", |(dir, _)| dir));
    fs::write(path, &protocol::saved_to_bytes(saved));
}

fn state(
    wifi: &Wifi,
    heard: &[Network],
    saved: &[(String, String)],
    failed: &Option<(String, pinnacle_wifi::Failure)>,
) -> State {
    State {
        ready: wifi.ready(),
        scanning: wifi.scanning(),
        joined: wifi.joined().map(String::from),
        joining: wifi.joining().map(String::from),
        failed: failed.clone(),
        nearby: heard
            .iter()
            .map(|n| Nearby {
                network: n.clone(),
                saved: saved.iter().any(|(s, _)| *s == n.ssid),
            })
            .collect(),
        saved: saved.iter().map(|(s, _)| s.clone()).collect(),
    }
}

#[unsafe(no_mangle)]
fn main(_argument: u64) -> u64 {
    let Some(port) = pinnacle_rt::wifi_port() else {
        println!("wifi: no radio");
        return 1;
    };
    let mut wifi = Wifi::new();
    let mut saved = protocol::saved_from_bytes(&fs::read(saved_path()).unwrap_or_default());
    let mut heard: Vec<Network> = Vec::new();
    let mut failed = None;
    // The password of the join under way, kept once it lets us on.
    let mut pending: Option<(String, String)> = None;
    let service = pinnacle_rt::register("wifi").expect("could not register wifi");
    let mut clients: Vec<Channel> = Vec::new();
    let mut told: Vec<u8> = Vec::new();
    let mut buffer = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE];
    let mut last_scan = 0;
    wifi.poll(pinnacle_rt::time());
    loop {
        while let Some(bytes) = wifi.transmit() {
            port.send(&bytes, Vec::new());
        }
        // Every change, to every client.
        let now_state = state(&wifi, &heard, &saved, &failed).to_bytes();
        if now_state != told {
            let m = protocol::message(protocol::STATE_IS, &now_state);
            for c in &clients {
                c.send(&m, Vec::new());
            }
            told = now_state;
        }
        let rescan = (wifi.ready() && !clients.is_empty()).then_some(last_scan + SCAN_EVERY_MS);
        let deadline = wifi.next_deadline().into_iter().chain(rescan).min();
        let mut channels: Vec<&Channel> = alloc::vec![&service, &port];
        channels.extend(clients.iter());
        let received = pinnacle_rt::receive(&channels, &mut buffer, deadline);
        drop(channels);
        let now = pinnacle_rt::time();
        match received {
            Received::Timeout => {
                wifi.poll(now);
                if wifi.ready() && !clients.is_empty() && now >= last_scan + SCAN_EVERY_MS {
                    last_scan = now;
                    wifi.scan(now);
                }
            }
            Received::Message {
                index: 0,
                mut handles,
                ..
            } if !handles.is_empty() => {
                let client = Channel(handles.remove(0));
                client.send(&protocol::message(protocol::STATE_IS, &told), Vec::new());
                clients.push(client);
            }
            Received::Message { index: 1, len, .. } => wifi.receive(&buffer[..len], now),
            Received::Closed { index: 1 } => {
                println!("wifi: the radio's port closed");
                return 1;
            }
            Received::Message { index, len, .. } if index >= 2 && len > 0 => {
                let body = &buffer[1..len];
                match buffer[0] {
                    protocol::SCAN => {
                        last_scan = now;
                        wifi.scan(now);
                    }
                    protocol::STATE => {
                        clients[index - 2].send(&protocol::message(protocol::STATE_IS, &told), Vec::new());
                    }
                    protocol::JOIN => {
                        // No password given for a network kept: its own.
                        // Settings never sees a password kept.
                        let asked = protocol::join_from(body).map(|(ssid, password)| {
                            match saved.iter().find(|(s, _)| password.is_empty() && *s == ssid) {
                                Some(kept) => kept.clone(),
                                None => (ssid, password),
                            }
                        });
                        if let Some((ssid, password)) = asked
                            && wifi.join(&ssid, &password, now)
                        {
                            println!("wifi: joining {ssid}");
                            failed = None;
                            pending = Some((ssid, password));
                        }
                    }
                    protocol::LEAVE => wifi.leave(now),
                    protocol::FORGET => {
                        let ssid = String::from_utf8_lossy(body).into_owned();
                        saved.retain(|(s, _)| *s != ssid);
                        save(&saved);
                        println!("wifi: forgot {ssid}");
                        if wifi.joined() == Some(ssid.as_str()) {
                            wifi.leave(now);
                        }
                    }
                    _ => {}
                }
            }
            Received::Closed { index } if index >= 2 => {
                clients.remove(index - 2);
            }
            _ => {}
        }
        while let Some(event) = wifi.event() {
            match event {
                Event::Ready => {
                    println!("wifi: the radio is ready");
                    last_scan = now;
                    wifi.scan(now);
                }
                Event::Scanned(found) => {
                    println!("wifi: {} networks nearby", found.len());
                    heard = found;
                    if wifi.joined().is_none()
                        && wifi.joining().is_none()
                        && failed.is_none()
                        && let Some((ssid, password)) = protocol::rejoin(&saved, &heard).cloned()
                    {
                        println!("wifi: joining {ssid} again");
                        wifi.join(&ssid, &password, now);
                        pending = Some((ssid, password));
                    }
                }
                Event::ScanFailed => println!("wifi: the scan failed"),
                Event::Joined { ssid } => {
                    println!("wifi: joined {ssid}");
                    if let Some((s, password)) = pending.take()
                        && s == ssid
                    {
                        // Kept, the most recent last.
                        saved.retain(|(s, _)| *s != ssid);
                        saved.push((ssid, password));
                        save(&saved);
                    }
                }
                Event::JoinFailed { ssid, failure } => {
                    println!("wifi: could not join {ssid}: {}", failure.text());
                    pending = None;
                    failed = Some((ssid, failure));
                }
                Event::Left => println!("wifi: left the network"),
                Event::Lost { ssid } => {
                    println!("wifi: lost {ssid}");
                    last_scan = now;
                    wifi.scan(now);
                }
            }
        }
    }
}