garage44.eu/jeroen/pinnacle

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

.. /programs/src/bin/phone.rs

raw

//! The phone service: the modem driver (`pinnacle_modem`) over the
//! kernel's port to the cellular modem, offered to apps as the service
//! `phone` (`pinnacle_ui::phone` has the messages). Ordinary calls and
//! texts are how people the p2p service cannot reach are reached: Calls
//! dials their number here, Messages texts it. A call ringing in starts
//! Calls when no client is there to be told; it asks for the state and
//! finds the call. A text that comes is kept and shown as a notification.
//!
//! Texts are kept in the data vault (`data:/phone/texts/<number>`, on the
//! system disk on a device without one), a file a number as it is
//! dialled, records as the p2p service keeps its messages: direction (0
//! in, 1 out), time (u64 ms since 1970), length (u16), text. A text sent
//! is kept once the network took it.

#![no_std]
#![no_main]

extern crate alloc;

use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_modem::{End, Event, Modem, number};
use pinnacle_rt::{Channel, Received, fs, println};
use pinnacle_ui::phone::{self as protocol, Call, Ended, Modem as State};

const POLL_MS: u64 = 250;
/// A modem that has not said where its SIM is within this long is set up
/// again: on QEMU the other end of the port may connect after we spoke.
const SETUP_RETRY_MS: u64 = 5000;

struct Phone {
    modem: Modem,
    state: State,
    call: Call,
    /// The other side's number, during a call.
    number: String,
    clients: Vec<Channel>,
    /// Texts the modem is sending: their id, number and text.
    sending: Vec<(u32, String, String)>,
    /// The display server, for notifications, once connected.
    display: Option<Channel>,
}

/// The folder texts are kept in.
fn texts_folder() -> &'static str {
    if fs::disk("data").is_some() {
        "data:/phone/texts"
    } else {
        "system:/texts"
    }
}

/// The file of the conversation with `written`: the one kept for that
/// number however it was written, or a new one under its dialled form.
fn conversation(written: &str) -> Option<String> {
    let dialled = number::dialable(written)?;
    let folder = texts_folder();
    let name = fs::list(folder)
        .unwrap_or_default()
        .into_iter()
        .find(|n| number::same(n, &dialled))
        .unwrap_or(dialled);
    Some(alloc::format!("{folder}/{name}"))
}

fn now_wall() -> u64 {
    match pinnacle_rt::clock() {
        0 => pinnacle_rt::time(),
        s => s * 1000 + pinnacle_rt::time() % 1000,
    }
}

/// Appends a text to the conversation with `number`.
fn keep(number: &str, outgoing: bool, text: &str) {
    let Some(path) = conversation(number) else {
        return;
    };
    let mut log = fs::read(&path).unwrap_or_default();
    log.push(u8::from(outgoing));
    log.extend_from_slice(&now_wall().to_le_bytes());
    let text = &text.as_bytes()[..text.len().min(u16::MAX as usize)];
    log.extend_from_slice(&(text.len() as u16).to_le_bytes());
    log.extend_from_slice(text);
    if fs::disk("data").is_some() {
        fs::create_dir("data:/phone");
    }
    fs::create_dir(texts_folder());
    fs::write(&path, &log);
}

/// The newest texts with `number` that fit one message, whole and
/// oldest first.
fn newest(number: &str) -> Vec<u8> {
    let log = conversation(number)
        .and_then(|p| fs::read(&p))
        .unwrap_or_default();
    let mut starts = Vec::new();
    let mut at = 0;
    while at + 11 <= log.len() {
        starts.push(at);
        at += 11 + usize::from(u16::from_le_bytes([log[at + 9], log[at + 10]]));
    }
    let end = at.min(log.len());
    let room = pinnacle_rt::abi::MAX_MESSAGE - 1;
    let from = starts.into_iter().find(|&s| end - s <= room).unwrap_or(end);
    log[from..end].to_vec()
}

/// Who a number is, by the address book: their name, or the number.
fn name_of(n: &str) -> String {
    let Some(p2p) = pinnacle_ui::p2p::Client::connect(1000) else {
        return n.into();
    };
    p2p.book(&mut Vec::new())
        .into_iter()
        .find(|e| e.phones.iter().any(|p| number::same(p, n)))
        .map_or_else(|| n.into(), |e| e.name)
}

impl Phone {
    fn state_message(&self) -> Vec<u8> {
        let mut b = alloc::vec![self.state as u8, self.call as u8];
        b.extend_from_slice(self.number.as_bytes());
        protocol::message(protocol::STATE_IS, &b)
    }

    fn tell(&mut self, m: &[u8]) {
        self.clients.retain(|c| c.send(m, Vec::new()));
    }

    fn tell_state(&mut self) {
        let m = self.state_message();
        self.tell(&m);
    }

    fn event(&mut self, event: Event) {
        match event {
            Event::Ready { registered } | Event::Registered(registered) => {
                self.state = if registered {
                    State::Ready
                } else {
                    State::Searching
                };
                println!(
                    "phone: {}",
                    if registered {
                        "on the network"
                    } else {
                        "no network"
                    }
                );
            }
            Event::SimLocked | Event::PinRefused => self.state = State::Locked,
            Event::NoSim => self.state = State::NoSim,
            Event::Incoming { number } => {
                self.call = Call::Ringing;
                self.number = number.unwrap_or_default();
                println!("phone: a call from {}", self.number);
                if self.clients.is_empty() {
                    // Calls asks for the state when it starts, and finds this.
                    pinnacle_rt::spawn("calls", 2, Vec::new());
                }
                let m = protocol::message(protocol::INCOMING, self.number.as_bytes());
                self.tell(&m);
            }
            Event::Connected => {
                self.call = Call::Active;
                println!("phone: connected to {}", self.number);
                self.tell(&[protocol::CONNECTED]);
            }
            Event::Ended(end) => {
                self.call = Call::Idle;
                self.number.clear();
                let ended = match end {
                    End::HungUp => Ended::HungUp,
                    End::Busy => Ended::Busy,
                    End::NoAnswer => Ended::NoAnswer,
                    End::Missed => Ended::Missed,
                    End::Failed => Ended::Failed,
                };
                println!("phone: the call ended: {}", ended.text());
                self.tell(&protocol::message(protocol::ENDED, &[ended as u8]));
            }
            Event::TextSent(id) | Event::TextFailed(id) => {
                let Some(i) = self.sending.iter().position(|s| s.0 == id) else {
                    return;
                };
                let (_, number, text) = self.sending.remove(i);
                let kind = if matches!(event, Event::TextSent(_)) {
                    keep(&number, true, &text);
                    println!("phone: texted {number}");
                    protocol::TEXT_SENT
                } else {
                    println!("phone: the text to {number} did not go");
                    protocol::TEXT_FAILED
                };
                self.tell(&protocol::message(kind, number.as_bytes()));
                return;
            }
            Event::TextReceived { from, text } => {
                keep(&from, false, &text);
                println!("phone: a text from {from}");
                let body = alloc::format!("{from}\n{text}");
                self.tell(&protocol::message(protocol::TEXT_RECEIVED, body.as_bytes()));
                // Messages shows it itself when it is in front; the
                // display server leaves the banner out then.
                if self.display.is_none() {
                    self.display = pinnacle_rt::connect("display");
                }
                if let Some(display) = &self.display {
                    pinnacle_ui::notify(display, "messages", &name_of(&from), &text);
                }
                return;
            }
        }
        self.tell_state();
    }

    fn request(&mut self, i: usize, m: &[u8], now: u64) {
        let body = core::str::from_utf8(&m[1..]).unwrap_or("");
        match m[0] {
            protocol::DIAL => {
                if self.modem.dial(body, now) {
                    self.call = Call::Dialling;
                    self.number = body.into();
                    println!("phone: calling {body}");
                } else {
                    self.tell(&protocol::message(protocol::ENDED, &[Ended::Failed as u8]));
                }
                self.tell_state();
            }
            protocol::ANSWER => {
                self.modem.answer(now);
            }
            protocol::HANG_UP => self.modem.hang_up(now),
            protocol::UNLOCK => {
                self.modem.unlock(body, now);
            }
            protocol::STATE => {
                let m = self.state_message();
                self.clients[i].send(&m, Vec::new());
            }
            protocol::SEND_TEXT => {
                let (number, text) = body.split_once('\n').unwrap_or((body, ""));
                match self.modem.send_text(number, text, now) {
                    Some(id) => self.sending.push((id, number.into(), text.into())),
                    None => {
                        println!("phone: no text can go to {number} now");
                        self.tell(&protocol::message(protocol::TEXT_FAILED, number.as_bytes()));
                    }
                }
            }
            protocol::TEXTS => {
                let m = protocol::message(protocol::TEXTS_ARE, &newest(body));
                self.clients[i].send(&m, Vec::new());
            }
            protocol::FORGET_TEXTS => {
                if let Some(path) = conversation(body) {
                    fs::remove(&path);
                }
            }
            protocol::FORGET_TEXT if m.len() > 10 => {
                let outgoing = m[1] == 1;
                let at = u64::from_le_bytes(m[2..10].try_into().unwrap());
                let number = core::str::from_utf8(&m[10..]).unwrap_or("");
                if let Some(path) = conversation(number)
                    && let Some(log) = fs::read(&path)
                    && let Some(rest) = pinnacle_ui::p2p::without_record(&log, outgoing, at)
                {
                    // The last text gone, the conversation goes too.
                    if rest.is_empty() {
                        fs::remove(&path);
                    } else {
                        fs::write(&path, &rest);
                    }
                }
            }
            protocol::CONVERSATIONS => {
                let names = fs::list(texts_folder()).unwrap_or_default().join("\n");
                let m = protocol::message(protocol::CONVERSATIONS_ARE, names.as_bytes());
                self.clients[i].send(&m, Vec::new());
            }
            _ => {}
        }
    }
}

#[unsafe(no_mangle)]
fn main(_argument: u64) -> u64 {
    let Some(port) = pinnacle_rt::modem_port() else {
        println!("phone: no modem");
        return 1;
    };
    let service = pinnacle_rt::register(protocol::SERVICE).expect("could not register phone");
    let mut phone = Phone {
        modem: Modem::new(),
        state: State::Absent,
        call: Call::Idle,
        number: String::new(),
        clients: Vec::new(),
        sending: Vec::new(),
        display: None,
    };
    let mut started = pinnacle_rt::time();
    let mut buffer = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE];
    loop {
        while let Some(bytes) = phone.modem.transmit() {
            port.send(&bytes, Vec::new());
        }
        let now = pinnacle_rt::time();
        if phone.state == State::Absent && now >= started + SETUP_RETRY_MS {
            phone.modem = Modem::new();
            started = now;
            continue;
        }
        let mut channels: Vec<&Channel> = alloc::vec![&service, &port];
        channels.extend(phone.clients.iter());
        let received = pinnacle_rt::receive(&channels, &mut buffer, Some(now + POLL_MS));
        drop(channels);
        let now = pinnacle_rt::time();
        match received {
            Received::Message {
                index: 0,
                mut handles,
                ..
            } if !handles.is_empty() => phone.clients.push(Channel(handles.remove(0))),
            Received::Message { index: 1, len, .. } => phone.modem.receive(&buffer[..len], now),
            Received::Closed { index: 1 } => {
                println!("phone: the modem's port closed");
                return 1;
            }
            Received::Message { index, len, .. } if index >= 2 && len >= 1 => {
                let m = buffer[..len].to_vec();
                phone.request(index - 2, &m, now);
            }
            Received::Closed { index } if index >= 2 => {
                phone.clients.remove(index - 2);
            }
            _ => {}
        }
        phone.modem.poll(now);
        while let Some(event) = phone.modem.event() {
            phone.event(event);
        }
    }
}