garage44.eu/jeroen/pinnacle

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

.. /programs/src/bin/bluetooth.rs

raw

//! Bluetooth: the devices around, and what one of them tells. Found
//! devices are listed as the `bt` service hears them; a tap connects and
//! reads what is known to show (its name, make and model, battery, heart
//! rate as it ticks), and a Pinnacle nearby can be added as a contact: its
//! card is read, ours is handed over, no network in between.
//!
//! A connected device can be paired: where both have a screen each shows
//! a six-digit number and the person says whether they match. A paired
//! device stays in the list, first, whether it is nearby or not; its link
//! is encrypted again on every connection, and Forget drops the pairing.
//! A keyboard shows no number: this device shows a code to type on it,
//! then Enter; once paired, what is typed on it goes to the app in front,
//! and it stays connected when the app goes back to the list.

#![no_std]
#![no_main]

extern crate alloc;

use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_bt::gatt::{self, Service, Uuid};
use pinnacle_bt::smp;
use pinnacle_p2p::identity::Card;
use pinnacle_ui::bluetooth::{self as bt, Client, Device, Paired, Said};
use pinnacle_ui::{App, Event, p2p};
use pinnacle_view::{IntoView, Screen, Signal, View, el, signal};

/// What is known about the device looked at: label and value a row.
struct Page {
    device: Device,
    connection: Option<u16>,
    services: Vec<Service>,
    rows: Vec<(String, String)>,
    /// The peer's card, read from its Pinnacle service, and its card handle.
    card: Option<(Card, u16)>,
    added: bool,
    /// The link is encrypted; a pairing is under way.
    private: bool,
    pairing: bool,
    /// What the last pairing came to, in words.
    note: Option<String>,
    /// It paired by a code typed on it; it types into this device.
    typed: bool,
    keyboard: bool,
}

/// Pairing's question to the person: the connection, who, the number to
/// compare or, with `typed`, the code to type on the device.
struct Ask {
    connection: u16,
    who: String,
    code: Option<u32>,
    typed: bool,
}

/// A row of the list: a paired device (nearby or not) or one found.
struct Row {
    device: Device,
    line: String,
}

/// The paired devices first, then the others found.
fn rows(devices: &[Device], paired: &[Paired]) -> Vec<Row> {
    let mut out = Vec::new();
    for p in paired {
        let near = devices.iter().find(|d| d.address == p.address);
        let line = match near {
            Some(d) => alloc::format!("Paired · {} dBm, {}", d.rssi, strength(d.rssi)),
            None => String::from("Paired · not nearby"),
        };
        out.push(Row {
            device: Device {
                address: p.address,
                rssi: near.map_or(-127, |d| d.rssi),
                name: p.name.clone().or_else(|| near.and_then(|d| d.name.clone())),
            },
            line,
        });
    }
    for d in devices
        .iter()
        .filter(|d| !paired.iter().any(|p| p.address == d.address))
    {
        out.push(Row {
            device: d.clone(),
            line: alloc::format!("{} · {} dBm, {}", d.address.text(), d.rssi, strength(d.rssi)),
        });
    }
    out
}

enum Shown {
    List,
    Page(Box<Page>),
}

fn strength(rssi: i8) -> &'static str {
    match rssi {
        r if r > -50 => "strong",
        r if r > -70 => "good",
        _ => "weak",
    }
}

/// The page open, when it is the one for `connection`.
fn mine(shown: &mut Shown, connection: u16) -> Option<&mut Page> {
    match shown {
        Shown::Page(page) if page.connection == Some(connection) => Some(page),
        _ => None,
    }
}

/// Six digits as people read them: "042 917".
fn digits(code: u32) -> String {
    alloc::format!("{:03} {:03}", code / 1000, code % 1000)
}

/// How it says where its named controls are (`Screen::announce`), for
/// `cargo xtask` to tap them.
const ANNOUNCE: &str = "bluetooth: button ";

/// What a tap asked for.
#[derive(Clone, Copy, PartialEq)]
enum Tap {
    Device(usize),
    Back,
    Disconnect,
    /// Pair, or Forget a paired one.
    Pair,
    AddContact,
    Answer(bool),
}

/// A button that puts `tap` in `tapped`, named for `cargo xtask`.
fn button(
    label: &str,
    name: &'static str,
    variant: Option<&'static str>,
    tap: Tap,
    tapped: &Signal<Option<Tap>>,
) -> View {
    let tapped = tapped.clone();
    el("button")
        .class("m-button")
        .attr("type", "button")
        .attr("data-variant", variant)
        .attr("data-name", name)
        .attr("style", "width: 100%")
        .on("click", move |_| tapped.set(Some(tap)))
        .child(String::from(label))
        .into_view()
}

/// The list, or the device looked at; the pairing question over either.
fn page(
    shown: &Shown,
    rows: &[Row],
    paired: &[Paired],
    me: &str,
    ask: Option<&Ask>,
    tapped: &Signal<Option<Tap>>,
) -> View {
    let mut main = el("main").attr(
        "style",
        "max-width: 720px; margin: 0 auto; padding: 24px 16px; display: flex; \
         flex-direction: column; gap: 12px",
    );
    let small = |text: String, color: &str| {
        el("p")
            .attr(
                "style",
                alloc::format!("margin: 0; font-size: 12px; color: {color}"),
            )
            .child(text)
    };
    match shown {
        Shown::List => {
            let status = match (rows.len() > paired.len(), paired.is_empty()) {
                (false, true) => "Looking for devices…",
                (_, false) => "Paired devices first, then those found",
                (true, true) => "Devices found",
            };
            main = main
                .child(
                    el("h1")
                        .attr("style", "font-size: 30px; margin: 16px 0 0")
                        .child("Bluetooth"),
                )
                .child(small(me.into(), "var(--m-text-dim)"))
                .child(small(status.into(), "var(--m-text-dim)"));
            let mut list = el("div").attr("role", "list").attr(
                "style",
                "display: flex; flex-direction: column; gap: 8px; margin-top: 8px",
            );
            for (i, row) in rows.iter().enumerate() {
                let tapped = tapped.clone();
                let color = if i < paired.len() {
                    "var(--m-success)"
                } else {
                    "var(--m-text-dim)"
                };
                list = list.child(
                    el("button")
                        .class("m-list-item")
                        .attr("type", "button")
                        .attr("role", "listitem")
                        .attr("data-name", alloc::format!("device-{i}"))
                        .on("click", move |_| tapped.set(Some(Tap::Device(i))))
                        .child(
                            el("span")
                                .class("m-list-item__body")
                                .child(el("span").class("m-list-item__title").child(row.device.label()))
                                .child(
                                    el("span")
                                        .class("m-list-item__sub")
                                        .attr("style", alloc::format!("color: {color}"))
                                        .child(row.line.clone()),
                                ),
                        ),
                );
            }
            main = main.child(list);
        }
        Shown::Page(page) => {
            let bonded = paired.iter().any(|p| p.address == page.device.address);
            // What the last pairing came to, in place of the address line.
            let state = match (page.connection, page.services.is_empty()) {
                (Some(_), _) if page.note.is_some() => page.note.clone().unwrap_or_default(),
                (None, _) => String::from("Connecting…"),
                (Some(_), true) => String::from("Connected, asking what it offers…"),
                (Some(_), false) => alloc::format!(
                    "{} · {} services",
                    page.device.address.text(),
                    page.services.len()
                ),
            };
            let tapped_back = tapped.clone();
            main = main
                .child(
                    el("div").child(
                        el("button")
                            .class("m-button")
                            .attr("type", "button")
                            .attr("data-variant", "ghost")
                            .attr("data-name", "back")
                            .on("click", move |_| tapped_back.set(Some(Tap::Back)))
                            .child("\u{2039} Back"),
                    ),
                )
                .child(
                    el("h1")
                        .attr("style", "font-size: 30px; margin: 8px 0 0")
                        .child(page.device.label()),
                )
                .child(small(state, "var(--m-text-dim)"));
            // The link first: private, or in the open for anyone nearby.
            let mut shown: Vec<(String, String, bool)> = Vec::new();
            if page.connection.is_some() {
                let link = match (page.private, page.pairing) {
                    (true, _) => "Private, encrypted",
                    (false, true) => "Pairing…",
                    (false, false) => "In the open",
                };
                shown.push(("Link".into(), link.into(), page.private));
            }
            if page.keyboard {
                shown.push(("Keyboard".into(), "Types into the app in front".into(), true));
            }
            shown.extend(page.rows.iter().map(|(l, v)| (l.clone(), v.clone(), false)));
            if !shown.is_empty() {
                let mut card = el("div").attr(
                    "style",
                    "display: flex; flex-direction: column; padding: 4px 18px; margin-top: 8px; \
                     background: var(--m-surface); border-radius: var(--m-radius-lg)",
                );
                for (label, value, good) in shown {
                    let color = if good { "var(--m-success)" } else { "var(--m-text)" };
                    card = card.child(
                        el("div")
                            .attr(
                                "style",
                                "display: flex; justify-content: space-between; gap: 12px; padding: 12px 0",
                            )
                            .child(el("span").attr("style", "color: var(--m-text-dim)").child(label))
                            .child(
                                el("span")
                                    .attr("style", alloc::format!("color: {color}; text-align: end"))
                                    .child(value),
                            ),
                    );
                }
                main = main.child(card);
            }
            let mut actions = el("div").attr(
                "style",
                "display: flex; flex-direction: column; gap: 10px; margin-top: 16px",
            );
            if page.card.is_some() {
                let (label, variant) = if page.added {
                    ("Added as contact", None)
                } else {
                    ("Add as contact", Some("primary"))
                };
                actions = actions.child(button(label, "add-contact", variant, Tap::AddContact, tapped));
            }
            if bonded {
                actions = actions.child(button("Forget this device", "pair", None, Tap::Pair, tapped));
            } else if page.connection.is_some() {
                let (label, variant) = if page.pairing {
                    ("Pairing…", None)
                } else {
                    ("Pair", Some("primary"))
                };
                actions = actions.child(button(label, "pair", variant, Tap::Pair, tapped));
            }
            // A keyboard typing stays connected; Forget drops it.
            if page.connection.is_some() && !page.keyboard {
                actions = actions.child(button("Disconnect", "disconnect", None, Tap::Disconnect, tapped));
            }
            main = main.child(actions);
        }
    }
    let mut root = el("div").attr("style", "min-height: 100vh").child(main);
    if let Some(ask) = ask {
        // The question over what is behind it, which takes no tap meanwhile.
        let (title, said, yes) = match ask.code {
            Some(code) if ask.typed => (
                alloc::format!("Type this code on {}", ask.who),
                el("div")
                    .child(
                        el("div")
                            .attr("style", "font-size: 54px; margin: 12px 0")
                            .child(digits(code)),
                    )
                    .child(
                        el("p")
                            .attr("style", "margin: 0; color: var(--m-text-dim)")
                            .child("Then press Enter on it. A device listening in cannot pair this way."),
                    ),
                None,
            ),
            Some(code) => (
                alloc::format!("Pair with {}?", ask.who),
                el("div")
                    .child(
                        el("p")
                            .attr("style", "margin: 0; color: var(--m-text-dim)")
                            .child("Does it show this number?"),
                    )
                    .child(
                        el("div")
                            .attr("style", "font-size: 54px; margin: 12px 0")
                            .child(digits(code)),
                    ),
                Some("Yes, it matches"),
            ),
            None => (
                alloc::format!("Pair with {}?", ask.who),
                el("div").child(
                    el("p")
                        .attr("style", "margin: 0; color: var(--m-text-dim)")
                        .child("It has no screen to show a number on. Pair only if you asked it to."),
                ),
                Some("Pair"),
            ),
        };
        // A code to type has only Cancel: typing it on the device answers.
        let mut answers = el("div").attr("style", "display: flex; gap: 12px").child(button(
            if yes.is_some() { "No" } else { "Cancel" },
            "ask-no",
            None,
            Tap::Answer(false),
            tapped,
        ));
        if let Some(yes) = yes {
            answers = answers.child(button(yes, "ask-yes", Some("primary"), Tap::Answer(true), tapped));
        }
        root = root.child(
            el("div")
                .attr(
                    "style",
                    "position: fixed; inset: 0; z-index: 10; display: flex; align-items: flex-end; \
                     justify-content: center; padding: 16px; background: rgb(0 0 0 / 45%)",
                )
                .child(
                    el("div")
                        .attr(
                            "style",
                            "width: 100%; max-width: 560px; padding: 20px; display: flex; \
                             flex-direction: column; gap: 12px; background: var(--m-pressed); \
                             border-radius: var(--m-radius-lg)",
                        )
                        .child(el("h2").attr("style", "margin: 0; font-size: 21px").child(title))
                        .child(said)
                        .child(answers),
                ),
        );
    }
    root.into_view()
}

/// Takes what a signal holds, leaving it empty.
fn take<T: Clone + 'static>(s: &Signal<Option<T>>) -> Option<T> {
    let v = s.get_untracked();
    if v.is_some() {
        s.set(None);
    }
    v
}

/// The label a characteristic's row gets, and how its value reads.
fn row_for(uuid: Uuid, value: &[u8]) -> Option<(String, String)> {
    let text = || String::from_utf8_lossy(value).into_owned();
    Some(match uuid {
        Uuid::Short(gatt::DEVICE_NAME) => ("Name".into(), text()),
        Uuid::Short(gatt::MANUFACTURER_NAME) => ("Made by".into(), text()),
        Uuid::Short(gatt::MODEL_NUMBER) => ("Model".into(), text()),
        Uuid::Short(gatt::BATTERY_LEVEL) => ("Battery".into(), alloc::format!("{} %", value.first()?)),
        Uuid::Short(gatt::HEART_RATE_MEASUREMENT) => {
            ("Heart rate".into(), alloc::format!("{} bpm", value.get(1)?))
        }
        _ => return None,
    })
}

#[unsafe(no_mangle)]
fn main(_argument: u64) -> u64 {
    let mut app = App::new("Bluetooth");
    let Some(client) = Client::connect(5000) else {
        let mut view = Screen::new(app.width, app.height);
        view.mount(
            el("p")
                .attr("style", "margin: 0; padding: 90px 18px; color: var(--m-text-dim)")
                .child("Bluetooth is not available on this device.")
                .into_view(),
        );
        view.draw(&mut app.canvas(), true);
        app.present_all();
        loop {
            match app.next_event(None) {
                Event::Closed => return 0,
                Event::Shown(true) | Event::Resized => {
                    view.resize(app.width, app.height);
                    view.draw(&mut app.canvas(), true);
                    app.present_all();
                }
                _ => {}
            }
        }
    };
    let p2p = p2p::Client::connect(2000);
    let mut pending = Vec::new();
    let my_card = p2p.as_ref().map(|c| c.card(&mut pending)).unwrap_or_default();
    client.ask_state();
    client.ask_bonds();
    client.scan();
    client.ask_devices();
    let mut me = String::from("This device");
    let mut devices: Vec<Device> = Vec::new();
    let mut paired: Vec<Paired> = Vec::new();
    let mut shown = Shown::List;
    let mut ask: Option<Ask> = None;
    let mut buffer = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE];
    let name_of = |address: pinnacle_bt::Address, devices: &[Device], paired: &[Paired]| {
        paired
            .iter()
            .find(|p| p.address == address)
            .and_then(|p| p.name.clone())
            .or_else(|| {
                devices
                    .iter()
                    .find(|d| d.address == address)
                    .and_then(|d| d.name.clone())
            })
            .unwrap_or_else(|| address.text())
    };
    let mut view = Screen::new(app.width, app.height);
    let tapped: Signal<Option<Tap>> = signal(None);
    // The page built again from what is known, and drawn where it changed
    // (`all` after a resize): what a device says changes little of it.
    macro_rules! redraw {
        () => {
            redraw!(false)
        };
        ($all:expr) => {{
            view.resize(app.width, app.height);
            view.clear();
            view.mount(page(
                &shown,
                &rows(&devices, &paired),
                &paired,
                &me,
                ask.as_ref(),
                &tapped,
            ));
            if let Some(area) = view.draw(&mut app.canvas(), $all) {
                app.present(area);
            }
            view.announce(ANNOUNCE);
        }};
    }
    redraw!(true);
    loop {
        match app.wait(&[client.channel()], &mut buffer, None) {
            Event::Channel { len, .. } => {
                let Some(said) = bt::parse(&buffer[..len]) else {
                    continue;
                };
                match said {
                    Said::State { address, name, .. } => {
                        me = alloc::format!("This device: {name} · {}", address.text());
                    }
                    Said::Device(d) => match devices.iter_mut().find(|k| k.address == d.address) {
                        Some(k) => *k = d,
                        None => devices.push(d),
                    },
                    Said::Devices(all) => devices = all,
                    Said::Bonds(all) => paired = all,
                    Said::Connected {
                        connection, address, ..
                    } => {
                        if let Shown::Page(page) = &mut shown
                            && page.device.address == address
                        {
                            page.connection = Some(connection);
                            client.discover(connection);
                        }
                    }
                    Said::Disconnected { connection, address } => {
                        if ask.as_ref().is_some_and(|a| a.connection == connection) {
                            ask = None;
                        }
                        if let Shown::Page(page) = &mut shown
                            && page.device.address == address
                        {
                            page.connection = None;
                            shown = Shown::List;
                            client.scan();
                        }
                    }
                    Said::Ask {
                        connection,
                        address,
                        code,
                    } => {
                        ask = Some(Ask {
                            connection,
                            who: name_of(address, &devices, &paired),
                            code,
                            typed: false,
                        });
                    }
                    // This device shows the code; asked to type one, the
                    // service has refused already.
                    Said::Passkey {
                        connection,
                        address,
                        passkey: Some(passkey),
                    } => {
                        pinnacle_rt::println!(
                            "bluetooth: a code to type on {}",
                            name_of(address, &devices, &paired)
                        );
                        ask = Some(Ask {
                            connection,
                            who: name_of(address, &devices, &paired),
                            code: Some(passkey),
                            typed: true,
                        });
                        if let Some(page) = mine(&mut shown, connection) {
                            page.typed = true;
                        }
                    }
                    Said::Passkey { passkey: None, .. } => {}
                    Said::Keyboard { connection, on, .. } => {
                        if let Some(page) = mine(&mut shown, connection) {
                            page.keyboard = on;
                        }
                    }
                    Said::Paired {
                        connection, compared, ..
                    } => {
                        ask = None;
                        if let Some(page) = mine(&mut shown, connection) {
                            page.pairing = false;
                            page.note = Some(String::from(match (compared, page.typed) {
                                (true, true) => {
                                    "Paired. The code typed on it matched, so no one sits in between."
                                }
                                (true, false) => "Paired. The numbers matched, so no one sits in between.",
                                (false, _) => "Paired. It has no screen, so no numbers could be compared.",
                            }));
                        }
                    }
                    Said::PairFailed {
                        connection, reason, ..
                    } => {
                        ask = None;
                        if let Some(page) = mine(&mut shown, connection) {
                            page.pairing = false;
                            page.note = Some(alloc::format!("Not paired: {}.", smp::reason_text(reason)));
                        }
                    }
                    Said::Encrypted { connection, .. } => {
                        if let Some(page) = mine(&mut shown, connection) {
                            page.private = true;
                        }
                    }
                    Said::KeyRefused { connection, .. } => {
                        if let Some(page) = mine(&mut shown, connection) {
                            page.note = Some(String::from(
                                "It no longer knows this device. Forget it here and pair again.",
                            ));
                        }
                    }
                    Said::Services { connection, services } => {
                        if let Some(page) = mine(&mut shown, connection) {
                            // Read what there is to show, subscribe to what ticks.
                            for s in &services {
                                for c in &s.characteristics {
                                    let known = matches!(
                                        c.uuid,
                                        Uuid::Short(
                                            gatt::DEVICE_NAME
                                                | gatt::MANUFACTURER_NAME
                                                | gatt::MODEL_NUMBER
                                                | gatt::BATTERY_LEVEL
                                        ) | Uuid::Long(gatt::PINNACLE_CARD)
                                    );
                                    if known && c.properties & gatt::PROP_READ != 0 {
                                        client.read(connection, c.handle);
                                    }
                                    if let Some(configuration) = c.configuration
                                        && c.uuid == Uuid::Short(gatt::HEART_RATE_MEASUREMENT)
                                    {
                                        client.subscribe(connection, configuration, true);
                                    }
                                }
                            }
                            page.services = services;
                        }
                    }
                    Said::Value {
                        connection,
                        handle,
                        value: Ok(value),
                    }
                    | Said::Notified {
                        connection,
                        handle,
                        value,
                    } => {
                        if let Some(page) = mine(&mut shown, connection) {
                            let uuid = page
                                .services
                                .iter()
                                .flat_map(|s| &s.characteristics)
                                .find(|c| c.handle == handle)
                                .map(|c| c.uuid);
                            match uuid {
                                Some(Uuid::Long(gatt::PINNACLE_CARD)) => {
                                    if let Some(card) = Card::from_bytes(&value) {
                                        let row = ("Pinnacle contact".into(), String::from(card.name()));
                                        page.rows.retain(|(l, _)| l != "Pinnacle contact");
                                        page.rows.push(row);
                                        page.card = Some((card, handle));
                                    }
                                }
                                Some(uuid) => {
                                    if let Some((label, text)) = row_for(uuid, &value) {
                                        match page.rows.iter_mut().find(|(l, _)| *l == label) {
                                            Some(row) => row.1 = text,
                                            None => page.rows.push((label, text)),
                                        }
                                    }
                                }
                                None => {}
                            }
                        }
                    }
                    Said::Value { value: Err(_), .. } | Said::Written { .. } => {}
                }
                redraw!();
            }
            Event::Input(e) => {
                view.input(&e);
                let Some(tap) = take(&tapped) else {
                    // A press shows on what it pressed.
                    if let Some(area) = view.draw(&mut app.canvas(), false) {
                        app.present(area);
                    }
                    continue;
                };
                if let Some(a) = &ask {
                    // The question first: nothing behind it takes a tap.
                    if let Tap::Answer(yes) = tap {
                        pinnacle_rt::println!(
                            "bluetooth: pairing with {} answered {}",
                            a.who,
                            if yes { "yes" } else { "no" }
                        );
                        client.confirm(a.connection, yes);
                        ask = None;
                    }
                    redraw!();
                    continue;
                }
                match (&mut shown, tap) {
                    (Shown::List, Tap::Device(i)) => {
                        let all = rows(&devices, &paired);
                        if let Some(row) = all.get(i) {
                            let device = row.device.clone();
                            pinnacle_rt::println!("bluetooth: connecting to {}", device.label());
                            client.stop();
                            client.connect_to(device.address);
                            shown = Shown::Page(Box::new(Page {
                                device,
                                connection: None,
                                services: Vec::new(),
                                rows: Vec::new(),
                                card: None,
                                added: false,
                                private: false,
                                pairing: false,
                                note: None,
                                typed: false,
                                keyboard: false,
                            }));
                        }
                    }
                    (Shown::Page(page), Tap::Back | Tap::Disconnect) => {
                        if let Some(c) = page.connection {
                            client.disconnect(c);
                        }
                        shown = Shown::List;
                        client.scan();
                    }
                    (Shown::Page(page), Tap::Pair) => {
                        if paired.iter().any(|p| p.address == page.device.address) {
                            pinnacle_rt::println!("bluetooth: forgetting {}", page.device.label());
                            client.forget(page.device.address);
                            paired.retain(|p| p.address != page.device.address);
                            shown = Shown::List;
                            client.scan();
                        } else if let (Some(c), false) = (page.connection, page.pairing) {
                            pinnacle_rt::println!("bluetooth: pairing with {}", page.device.label());
                            client.pair(c);
                            page.pairing = true;
                            page.note = None;
                        }
                    }
                    (Shown::Page(page), Tap::AddContact) => {
                        if let (Some((card, handle)), Some(c), false) =
                            (&page.card, page.connection, page.added)
                        {
                            // Theirs becomes a contact of ours; ours goes to them.
                            if let Some(p2p) = &p2p {
                                p2p.add_contact(&card.to_bytes());
                            }
                            if my_card.len() == p2p::CARD_SIZE {
                                client.write(c, *handle, &my_card);
                            }
                            pinnacle_rt::println!("bluetooth: added {} as a contact", card.name());
                            page.added = true;
                        }
                    }
                    _ => {}
                }
                redraw!();
            }
            Event::Shown(true) | Event::Resized => redraw!(true),
            Event::Closed | Event::ChannelClosed { .. } => return 0,
            _ => {}
        }
    }
}