garage44.eu/jeroen/pinnacle

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

.. /modem/src/host.rs

raw

//! The modem's driver: one AT command in flight at a time, the lines that
//! come back sorted into each command's answer and what the modem says of
//! its own accord (a ring, who rings, a call ended, the network).
//!
//! Outgoing calls are dialled with `AT+COLP=1` set, so `ATD` answers only
//! when the call is settled: `OK` once the other side picks up, or `BUSY`,
//! `NO ANSWER` or `NO CARRIER`. An incoming call is `RING` (again every few
//! seconds) and `+CLIP` with the caller's number; a call the other side
//! ends is `NO CARRIER`.
//!
//! A text goes as `AT+CMGS=<length>`, a part at a time: the modem asks
//! for the PDU with `> ` (which ends no line), takes it in hex ended by
//! ctrl-Z, and answers `+CMGS: <reference>` and `OK` once the network took
//! it. One that comes is `+CMT: ,<length>` and its PDU on the next line.

use crate::{number, pdu};
use alloc::collections::VecDeque;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

/// How long a command may go unanswered before it is taken as failed.
const COMMAND_MS: u64 = 5000;
/// How long `ATD` may take: the network gives up on an unanswered call
/// first (after about a minute), and says so.
const DIAL_MS: u64 = 90_000;
/// How long after `RING` a call is told without the caller's number, when
/// no `+CLIP` follows (the modem does not send one, or it came first).
const CLIP_WAIT_MS: u64 = 1000;
/// How long `+CMGS` may take: the network answers within seconds, or
/// tens of them on a weak signal.
const TEXT_MS: u64 = 60_000;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Event {
    /// The modem is set up and its SIM open; whether it is on a network.
    Ready { registered: bool },
    /// The SIM wants its PIN ([`Modem::unlock`]).
    SimLocked,
    /// The PIN given was wrong; the SIM is still locked.
    PinRefused,
    /// There is no SIM, or the modem cannot read it.
    NoSim,
    /// On a network (home or roaming), or no longer.
    Registered(bool),
    /// A call rings in; the caller's number when the network gives it.
    Incoming { number: Option<String> },
    /// The call is up: the other side picked up, or this side answered.
    Connected,
    /// The call is over, or never came about.
    Ended(End),
    /// The network took text `id` ([`Modem::send_text`]), every part.
    TextSent(u32),
    /// Text `id` did not go: no network, a wrong number, refused.
    TextFailed(u32),
    /// A text came, whole (a long one once all its parts are in).
    TextReceived { from: String, text: String },
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum End {
    /// One side hung up (this one: [`Modem::hang_up`]).
    HungUp,
    /// The number called is busy, or declined.
    Busy,
    /// Nobody picked up.
    NoAnswer,
    /// A call that rang in stopped before it was answered.
    Missed,
    /// It did not go through: no network, a wrong number, the modem silent.
    Failed,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
    Setup,
    PinQuery,
    Pin,
    Register,
    Dial,
    Answer,
    HangUp,
    /// One part of text `id`; `last` its last.
    Text {
        id: u32,
        last: bool,
    },
}

struct Command {
    line: String,
    kind: Kind,
    /// What follows the modem's `> ` prompt (a PDU in hex, then ctrl-Z).
    body: Option<Vec<u8>>,
}

/// A command's final result.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Final {
    Ok,
    Error,
    NoCarrier,
    Busy,
    NoAnswer,
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum State {
    Idle,
    Dialling,
    Ringing {
        since: u64,
        number: Option<String>,
        told: bool,
    },
    Active,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Sim {
    Unknown,
    Ready,
    Locked,
}

pub struct Modem {
    queue: VecDeque<Command>,
    in_flight: Option<(Command, u64)>,
    out: VecDeque<Vec<u8>>,
    events: VecDeque<Event>,
    partial: Vec<u8>,
    state: State,
    sim: Sim,
    ready: bool,
    registered: bool,
    /// `ATD` was aborted by a hang-up: its final result is not news.
    dial_aborted: bool,
    /// A `+CMT` came: the next line is its PDU.
    cmt: bool,
    parts: pdu::Parts,
    next_text: u32,
}

impl Default for Modem {
    fn default() -> Modem {
        Modem::new()
    }
}

impl Modem {
    /// A driver that starts setting the modem up: echo off, errors as
    /// numbers, the SIM asked about.
    pub fn new() -> Modem {
        let mut m = Modem {
            queue: VecDeque::new(),
            in_flight: None,
            out: VecDeque::new(),
            events: VecDeque::new(),
            partial: Vec::new(),
            state: State::Idle,
            sim: Sim::Unknown,
            ready: false,
            registered: false,
            dial_aborted: false,
            cmt: false,
            parts: pdu::Parts::default(),
            next_text: 0,
        };
        m.command("ATE0", Kind::Setup);
        m.command("AT+CMEE=1", Kind::Setup);
        m.command("AT+CPIN?", Kind::PinQuery);
        m
    }

    /// Whether calls can be made: set up, the SIM open, on a network.
    pub fn ready(&self) -> bool {
        self.ready && self.registered
    }

    /// Whether a call is dialling, ringing in or up.
    pub fn busy(&self) -> bool {
        self.state != State::Idle
    }

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

    /// The next thing that happened.
    pub fn event(&mut self) -> Option<Event> {
        self.events.pop_front()
    }

    /// Calls `written` (as a person wrote it: see [`number::dialable`]).
    /// False when no call can be made now, or it is not a number.
    pub fn dial(&mut self, written: &str, now: u64) -> bool {
        let Some(n) = number::dialable(written) else {
            return false;
        };
        if !self.ready() || self.busy() {
            return false;
        }
        self.state = State::Dialling;
        self.dial_aborted = false;
        self.command(&alloc::format!("ATD{n};"), Kind::Dial);
        self.send_next(now);
        true
    }

    /// Answers the call ringing in.
    pub fn answer(&mut self, now: u64) -> bool {
        if !matches!(self.state, State::Ringing { .. }) {
            return false;
        }
        self.command("ATA", Kind::Answer);
        self.send_next(now);
        true
    }

    /// Ends the call: hangs up, declines one ringing in, or stops dialling.
    /// [`Event::Ended`] follows at once.
    pub fn hang_up(&mut self, now: u64) {
        match self.state {
            State::Idle => return,
            State::Dialling => {
                if let Some(i) = self.queue.iter().position(|c| c.kind == Kind::Dial) {
                    self.queue.remove(i);
                } else if matches!(&self.in_flight, Some((c, _)) if c.kind == Kind::Dial) {
                    // Any character aborts a dial in progress (V.250 6.3.1);
                    // its answer is then not news.
                    self.dial_aborted = true;
                    self.out.push_back(b"AT\r".to_vec());
                }
            }
            State::Ringing { .. } | State::Active => self.command("AT+CHUP", Kind::HangUp),
        }
        self.state = State::Idle;
        self.events.push_back(Event::Ended(End::HungUp));
        self.send_next(now);
    }

    /// Sends `text` to `written` (a number as a person wrote it), in as
    /// many parts as it takes: its id, which [`Event::TextSent`] or
    /// [`Event::TextFailed`] names once the network said. `None` when no
    /// text can go now (no network), or it is not a number. A text waits
    /// behind a call being dialled; during a call it goes.
    pub fn send_text(&mut self, written: &str, text: &str, now: u64) -> Option<u32> {
        let n = number::dialable(written)?;
        if !self.ready() || text.is_empty() {
            return None;
        }
        let id = self.next_text;
        self.next_text = self.next_text.wrapping_add(1);
        let pdus = pdu::submit(&n, text, id as u8);
        let count = pdus.len();
        for (i, p) in pdus.into_iter().enumerate() {
            // The length leaves the (empty) service centre address out.
            let mut body = pdu::hex(&p).into_bytes();
            body.push(0x1a);
            self.queue.push_back(Command {
                line: alloc::format!("AT+CMGS={}", p.len() - 1),
                kind: Kind::Text {
                    id,
                    last: i + 1 == count,
                },
                body: Some(body),
            });
        }
        self.send_next(now);
        Some(id)
    }

    /// Gives the SIM its PIN, after [`Event::SimLocked`].
    pub fn unlock(&mut self, pin: &str, now: u64) -> bool {
        if self.sim != Sim::Locked || pin.is_empty() || !pin.bytes().all(|b| b.is_ascii_digit()) {
            return false;
        }
        self.command(&alloc::format!("AT+CPIN=\"{pin}\""), Kind::Pin);
        self.send_next(now);
        true
    }

    /// Timers: a command unanswered, a ring whose caller is not told.
    pub fn poll(&mut self, now: u64) {
        if let Some((c, sent)) = &self.in_flight {
            let limit = match c.kind {
                Kind::Dial => DIAL_MS,
                Kind::Text { .. } => TEXT_MS,
                _ => COMMAND_MS,
            };
            if now.saturating_sub(*sent) > limit {
                self.finish(Final::Error, now);
            }
        }
        if let State::Ringing { since, number, told } = &mut self.state
            && !*told
            && now.saturating_sub(*since) >= CLIP_WAIT_MS
        {
            *told = true;
            let number = number.clone();
            self.events.push_back(Event::Incoming { number });
        }
        self.send_next(now);
    }

    /// Bytes from the modem.
    pub fn receive(&mut self, bytes: &[u8], now: u64) {
        for &b in bytes {
            if b == b'\n' {
                let raw = core::mem::take(&mut self.partial);
                let line = String::from_utf8_lossy(&raw);
                let line = line.trim();
                if !line.is_empty() {
                    let line = line.to_string();
                    self.line(&line, now);
                }
            } else {
                self.partial.push(b);
                // `+CMGS` asks for its PDU with `> `, which ends no line.
                if self.partial.ends_with(b"> ")
                    && self.partial.trim_ascii() == b">"
                    && let Some((c, _)) = &mut self.in_flight
                    && let Some(body) = c.body.take()
                {
                    self.partial.clear();
                    self.out.push_back(body);
                }
            }
        }
        self.send_next(now);
    }

    fn command(&mut self, line: &str, kind: Kind) {
        self.queue.push_back(Command {
            line: line.into(),
            kind,
            body: None,
        });
    }

    fn send_next(&mut self, now: u64) {
        if self.in_flight.is_some() {
            return;
        }
        if let Some(c) = self.queue.pop_front() {
            let mut bytes = c.line.as_bytes().to_vec();
            bytes.push(b'\r');
            self.out.push_back(bytes);
            self.in_flight = Some((c, now));
        }
    }

    /// Whether `ATD` or `ATA` waits: `NO CARRIER` and the like are then
    /// their answer (`ATA` with nothing left to answer is `NO CARRIER`).
    fn call_in_flight(&self) -> bool {
        matches!(&self.in_flight, Some((c, _)) if matches!(c.kind, Kind::Dial | Kind::Answer))
    }

    fn line(&mut self, line: &str, now: u64) {
        // An echo of the command (before `ATE0` takes).
        if matches!(&self.in_flight, Some((c, _)) if c.line == line) {
            return;
        }
        if core::mem::take(&mut self.cmt) {
            // `+CMT`'s PDU; one that does not read is dropped.
            if let Some(part) = pdu::from_hex(line).and_then(|p| pdu::parse_deliver(&p))
                && let Some((from, text)) = self.parts.add(part)
            {
                self.events.push_back(Event::TextReceived { from, text });
            }
            return;
        }
        if line.starts_with("+CMT:") {
            self.cmt = true;
            return;
        }
        let result = match line {
            "OK" | "CONNECT" => Some(Final::Ok),
            "ERROR" => Some(Final::Error),
            "NO CARRIER" | "NO DIALTONE" => Some(Final::NoCarrier),
            "BUSY" => Some(Final::Busy),
            "NO ANSWER" => Some(Final::NoAnswer),
            _ if line.starts_with("+CME ERROR") || line.starts_with("+CMS ERROR") => Some(Final::Error),
            _ => None,
        };
        if let Some(result) = result {
            let call_result = matches!(result, Final::NoCarrier | Final::Busy | Final::NoAnswer);
            if self.in_flight.is_some() && (!call_result || self.call_in_flight()) {
                self.finish(result, now);
            } else if call_result {
                // Said of its own accord: the call ended at the other side.
                self.ended_elsewhere();
            }
            return;
        }
        if line == "RING" || line.starts_with("+CRING") {
            if self.state == State::Idle {
                self.state = State::Ringing {
                    since: now,
                    number: None,
                    told: false,
                };
            }
        } else if let Some(rest) = line.strip_prefix("+CLIP:") {
            let n = rest.trim().split(',').next().unwrap_or("").trim_matches('"');
            if let State::Ringing { number, told, .. } = &mut self.state
                && !*told
            {
                *told = true;
                *number = number::dialable(n);
                let number = number.clone();
                self.events.push_back(Event::Incoming { number });
            }
        } else if let Some(rest) = line.strip_prefix("+CPIN:") {
            self.sim = if rest.trim() == "READY" {
                Sim::Ready
            } else {
                Sim::Locked
            };
        } else if let Some(rest) = line.strip_prefix("+CREG:") {
            // `+CREG: <n>,<stat>` answers a query; `+CREG: <stat>` comes alone.
            let stat = rest.split(',').next_back().unwrap_or("").trim();
            let registered = matches!(stat, "1" | "5");
            if registered != self.registered {
                self.registered = registered;
                if self.ready {
                    self.events.push_back(Event::Registered(registered));
                }
            }
        }
    }

    /// The call ended without this side asking.
    fn ended_elsewhere(&mut self) {
        let end = match self.state {
            State::Ringing { .. } => End::Missed,
            State::Active => End::HungUp,
            State::Idle | State::Dialling => return,
        };
        self.state = State::Idle;
        self.events.push_back(Event::Ended(end));
    }

    fn finish(&mut self, result: Final, now: u64) {
        let Some((command, _)) = self.in_flight.take() else {
            return;
        };
        match command.kind {
            Kind::Setup | Kind::HangUp => {}
            Kind::Text { id, last } => {
                if result != Final::Ok {
                    // The parts after it are not sent.
                    self.queue
                        .retain(|c| !matches!(c.kind, Kind::Text { id: i, .. } if i == id));
                    self.events.push_back(Event::TextFailed(id));
                } else if last {
                    self.events.push_back(Event::TextSent(id));
                }
            }
            Kind::PinQuery => match (result, self.sim) {
                (Final::Ok, Sim::Ready) => self.sim_open(),
                (Final::Ok, Sim::Locked) => self.events.push_back(Event::SimLocked),
                _ => self.events.push_back(Event::NoSim),
            },
            Kind::Pin => {
                if result == Final::Ok {
                    self.sim = Sim::Ready;
                    self.sim_open();
                } else {
                    self.events.push_back(Event::PinRefused);
                }
            }
            Kind::Register => {
                self.ready = true;
                self.events.push_back(Event::Ready {
                    registered: self.registered,
                });
            }
            Kind::Dial => {
                if core::mem::take(&mut self.dial_aborted) || self.state != State::Dialling {
                    // Hung up while dialling: already told.
                } else if result == Final::Ok {
                    self.state = State::Active;
                    self.events.push_back(Event::Connected);
                } else {
                    self.state = State::Idle;
                    self.events.push_back(Event::Ended(match result {
                        Final::Busy => End::Busy,
                        Final::NoAnswer => End::NoAnswer,
                        _ => End::Failed,
                    }));
                }
            }
            Kind::Answer => {
                if !matches!(self.state, State::Ringing { .. }) {
                    // Hung up meanwhile.
                } else if result == Final::Ok {
                    self.state = State::Active;
                    self.events.push_back(Event::Connected);
                } else {
                    // The caller gave up as it was answered.
                    self.state = State::Idle;
                    self.events.push_back(Event::Ended(End::Missed));
                }
            }
        }
        self.send_next(now);
    }

    /// The SIM is open: callers' numbers, dialling that waits for the
    /// answer, texts as PDUs and handed over as they come (`+CMT`, not
    /// kept on the SIM), the network followed.
    fn sim_open(&mut self) {
        self.command("AT+CLIP=1", Kind::Setup);
        self.command("AT+COLP=1", Kind::Setup);
        self.command("AT+CMGF=0", Kind::Setup);
        self.command("AT+CNMI=2,2,0,0,0", Kind::Setup);
        self.command("AT+CREG=1", Kind::Setup);
        self.command("AT+CREG?", Kind::Register);
    }
}