garage44.eu/jeroen/pinnacle

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

.. /hid/src/tests.rs

raw

use crate::i2c::{self, Bringup, Error, HidDescriptor, I2cBus, Step};
use crate::{Field, Pointer, PointerEvent, layouts, parse, parse_relative};
use alloc::collections::VecDeque;
use alloc::vec;
use alloc::vec::Vec;

/// A USB boot mouse's descriptor: no report ID, three buttons, relative
/// X, Y and wheel.
const MOUSE: &[u8] = &[
    0x05, 0x01, 0x09, 0x02, 0xa1, 0x01, 0x09, 0x01, 0xa1, 0x00, //
    0x05, 0x09, 0x19, 0x01, 0x29, 0x03, 0x15, 0x00, 0x25, 0x01, 0x95, 0x03, 0x75, 0x01, 0x81, 0x02, //
    0x95, 0x01, 0x75, 0x05, 0x81, 0x03, //
    0x05, 0x01, 0x09, 0x30, 0x09, 0x31, 0x09, 0x38, 0x15, 0x81, 0x25, 0x7f, 0x75, 0x08, 0x95, 0x03, 0x81,
    0x06, //
    0xc0, 0xc0,
];

/// QEMU's USB tablet: one button, absolute 15-bit X and Y.
const TABLET: &[u8] = &[
    0x05, 0x01, 0x09, 0x02, 0xa1, 0x01, 0x09, 0x01, 0xa1, 0x00, //
    0x05, 0x09, 0x19, 0x01, 0x29, 0x03, 0x15, 0x00, 0x25, 0x01, 0x95, 0x03, 0x75, 0x01, 0x81, 0x02, //
    0x95, 0x01, 0x75, 0x05, 0x81, 0x01, //
    0x05, 0x01, 0x09, 0x30, 0x09, 0x31, 0x15, 0x00, 0x26, 0xff, 0x7f, 0x35, 0x00, 0x46, 0xff, 0x7f, 0x75,
    0x10, 0x95, 0x02, 0x81, 0x02, //
    0xc0, 0xc0,
];

/// The mouse collection an ELAN or Synaptics touchpad sends until told
/// otherwise: report 1, two buttons, relative 8-bit X and Y.
const TOUCHPAD_MOUSE: &[u8] = &[
    0x05, 0x01, 0x09, 0x02, 0xa1, 0x01, 0x85, 0x01, 0x09, 0x01, 0xa1, 0x00, //
    0x05, 0x09, 0x19, 0x01, 0x29, 0x02, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x02, 0x81, 0x02, //
    0x95, 0x06, 0x81, 0x03, //
    0x05, 0x01, 0x09, 0x30, 0x09, 0x31, 0x15, 0x81, 0x25, 0x7f, 0x75, 0x08, 0x95, 0x02, 0x81, 0x06, //
    0xc0, 0xc0,
];

/// Its precision touchpad (Windows' PTP) collection: report 3, a
/// finger's confidence, tip, contact ID, absolute X and Y with physical
/// units; the scan time, contact count and the pad's button; then the
/// feature reports Windows asks (contact count maximum, the pad's kind;
/// report 4, the input mode).
const TOUCHPAD_PTP: &[u8] = &[
    0x05, 0x0d, 0x09, 0x05, 0xa1, 0x01, 0x85, 0x03, //
    0x05, 0x0d, 0x09, 0x22, 0xa1, 0x02, //
    0x15, 0x00, 0x25, 0x01, 0x09, 0x47, 0x09, 0x42, 0x95, 0x02, 0x75, 0x01, 0x81, 0x02, //
    0x95, 0x01, 0x75, 0x03, 0x25, 0x05, 0x09, 0x51, 0x81, 0x02, //
    0x75, 0x01, 0x95, 0x03, 0x81, 0x03, //
    0x05, 0x01, 0x15, 0x00, 0x26, 0xaf, 0x04, 0x75, 0x10, 0x55, 0x0e, 0x65, 0x11, 0x09, 0x30, 0x35, 0x00,
    0x46, 0xe8, 0x03, 0x95, 0x01, 0x81, 0x02, //
    0x26, 0x7b, 0x02, 0x46, 0x12, 0x02, 0x09, 0x31, 0x81, 0x02, //
    0xc0, //
    0x05, 0x0d, 0x55, 0x0c, 0x66, 0x01, 0x10, 0x47, 0xff, 0xff, 0x00, 0x00, 0x27, 0xff, 0xff, 0x00, 0x00,
    0x75, 0x10, 0x95, 0x01, 0x09, 0x56, 0x81, 0x02, //
    0x09, 0x54, 0x25, 0x7f, 0x95, 0x01, 0x75, 0x08, 0x81, 0x02, //
    0x05, 0x09, 0x09, 0x01, 0x25, 0x01, 0x75, 0x01, 0x95, 0x01, 0x81, 0x02, //
    0x95, 0x07, 0x81, 0x03, //
    0x05, 0x0d, 0x85, 0x02, 0x09, 0x55, 0x09, 0x59, 0x75, 0x04, 0x95, 0x02, 0x25, 0x0f, 0xb1, 0x02, //
    0xc0, //
    0x05, 0x0d, 0x09, 0x0e, 0xa1, 0x01, 0x85, 0x04, 0x09, 0x22, 0xa1, 0x02, //
    0x09, 0x52, 0x15, 0x00, 0x25, 0x0a, 0x75, 0x08, 0x95, 0x01, 0xb1, 0x02, //
    0xc0, 0xc0,
];

fn touchpad_descriptor() -> Vec<u8> {
    [TOUCHPAD_MOUSE, TOUCHPAD_PTP].concat()
}

#[test]
fn a_boot_mouse_has_relative_x_y_and_wheel() {
    let l = parse(MOUSE).unwrap();
    assert_eq!(l.report_id, None);
    assert_eq!(
        l.x,
        Some(Field {
            offset: 8,
            size: 8,
            min: -127,
            max: 127,
            relative: true
        })
    );
    assert_eq!(l.y.unwrap().offset, 16);
    assert_eq!(l.wheel.unwrap().offset, 24);
    assert_eq!(l.buttons.len(), 3);
    assert_eq!(l.buttons[2].offset, 2);
}

#[test]
fn a_field_reads_signed_when_its_range_is() {
    let f = Field {
        offset: 8,
        size: 8,
        min: -127,
        max: 127,
        relative: true,
    };
    assert_eq!(f.read(&[0, 0xfd]), -3);
    assert_eq!(f.read(&[0, 5]), 5);
    let u = Field {
        offset: 4,
        size: 12,
        min: 0,
        max: 4095,
        relative: false,
    };
    assert_eq!(u.read(&[0xf0, 0xff]), 4095);
}

#[test]
fn a_tablet_points_where_it_points() {
    let l = parse(TABLET).unwrap();
    assert!(!l.relative());
    let mut p = Pointer {
        x: 0,
        y: 0,
        buttons: 0,
    };
    let mut out = Vec::new();
    // The middle, button down.
    p.report(&l, &[1, 0x00, 0x40, 0x00, 0x40], (1000, 800), &mut out);
    assert_eq!(
        out,
        [
            PointerEvent::Move {
                x: 500,
                y: 400,
                relative: false
            },
            PointerEvent::Press {
                down: true,
                x: 500,
                y: 400
            }
        ]
    );
}

#[test]
fn a_mouse_moves_the_pointer_and_stays_on_the_screen() {
    let l = parse(MOUSE).unwrap();
    let mut p = Pointer::new(100, 50);
    let mut out = Vec::new();
    p.report(&l, &[0, 10, 0xfb, 0], (100, 50), &mut out);
    assert_eq!(
        out,
        [PointerEvent::Move {
            x: 60,
            y: 20,
            relative: true
        }]
    );
    out.clear();
    p.report(&l, &[0, 127, 127, 0], (100, 50), &mut out);
    assert_eq!((p.x, p.y), (99, 49));
    // Nothing moved, nothing pressed: no event.
    out.clear();
    p.report(&l, &[0, 0, 0, 0], (100, 50), &mut out);
    assert!(out.is_empty());
}

#[test]
fn a_truncated_descriptor_is_none() {
    assert_eq!(parse(&MOUSE[..MOUSE.len() - 3]), None);
    assert_eq!(parse(&[0x26, 0xff]), None);
}

#[test]
fn a_touchpad_is_read_as_its_mouse() {
    let d = touchpad_descriptor();
    let l = parse(&d).unwrap();
    assert_eq!(l.report_id, Some(1));
    assert!(l.relative());
    assert_eq!(l.x.unwrap().offset, 8);
    assert_eq!(l.y.unwrap().offset, 16);
    assert_eq!(l.buttons.len(), 2);
    // Its precision touchpad's report is there too, absolute: a finger's
    // X after a byte of flags, Y after it.
    let all = layouts(&d).unwrap();
    let ptp = all.iter().find(|l| l.report_id == Some(3)).unwrap();
    assert_eq!(
        ptp.x,
        Some(Field {
            offset: 8,
            size: 16,
            min: 0,
            max: 1199,
            relative: false
        })
    );
    assert_eq!(ptp.y.unwrap().max, 635);
    assert_eq!(ptp.buttons.len(), 1);
}

#[test]
fn the_mouse_is_chosen_even_after_the_touchpad() {
    let d = [TOUCHPAD_PTP, TOUCHPAD_MOUSE].concat();
    // `parse`, as USB has it, takes the first.
    assert_eq!(parse(&d).unwrap().report_id, Some(3));
    let l = parse_relative(&d).unwrap();
    assert_eq!(l.report_id, Some(1));
    // With no relative report, the absolute one.
    assert_eq!(parse_relative(TABLET), parse(TABLET));
}

#[test]
fn the_dsm_uuid_is_tou_uids_bytes() {
    let text = "3CDFF6F7-4267-4555-AD05-B30A3D8938DE";
    let hex: Vec<u8> = text
        .split('-')
        .flat_map(|g| {
            (0..g.len() / 2)
                .map(|i| u8::from_str_radix(&g[2 * i..2 * i + 2], 16).unwrap())
                .collect::<Vec<_>>()
        })
        .collect();
    let mut want = hex.clone();
    want[0..4].reverse();
    want[4..6].reverse();
    want[6..8].reverse();
    assert_eq!(i2c::DSM_UUID[..], want[..]);
}

/// A touchpad on the bus: at 0x15, its HID descriptor at register 1, as
/// ELAN's are; registers 2 (report descriptor), 3 (input), 5 (command).
struct Fake {
    address: u16,
    descriptor: [u8; 30],
    report_descriptor: Vec<u8>,
    on: bool,
    /// Answers owed: the reset's empty report.
    reset_pending: bool,
    /// The input register not acknowledged: the reset's answer never
    /// read.
    input_naks: bool,
    /// Reports waiting, the device's interrupt line low.
    reports: VecDeque<Vec<u8>>,
    /// What the host did, in order.
    log: Vec<&'static str>,
    /// Transfers to fail from the start.
    nak_first: u32,
}

impl Fake {
    fn new() -> Fake {
        let words: [u16; 13] = [30, 0x0100, 0, 2, 3, 32, 4, 0, 5, 6, 0x04f3, 0x3140, 0x0001];
        let mut descriptor = [0u8; 30];
        for (i, w) in words.iter().enumerate() {
            descriptor[2 * i..2 * i + 2].copy_from_slice(&w.to_le_bytes());
        }
        let report_descriptor = touchpad_descriptor();
        descriptor[4..6].copy_from_slice(&(report_descriptor.len() as u16).to_le_bytes());
        Fake {
            address: 0x15,
            descriptor,
            report_descriptor,
            on: false,
            reset_pending: false,
            input_naks: false,
            reports: VecDeque::new(),
            log: Vec::new(),
            nak_first: 0,
        }
    }
}

impl I2cBus for Fake {
    fn write_read(&mut self, addr: u16, write: &[u8], read: &mut [u8]) -> bool {
        if addr != self.address {
            return false;
        }
        if self.nak_first > 0 {
            self.nak_first -= 1;
            return false;
        }
        match (write, read.len()) {
            // A plain read: the input register.
            ([], n) if n > 0 => {
                read.fill(0);
                if !self.on || self.input_naks {
                    return false;
                }
                // A report from before the reset comes first.
                if let Some(r) = self.reports.pop_front() {
                    let len = (r.len() + 2) as u16;
                    read[..2].copy_from_slice(&len.to_le_bytes());
                    read[2..2 + r.len()].copy_from_slice(&r);
                    return true;
                }
                if core::mem::take(&mut self.reset_pending) {
                    self.log.push("reset answer");
                }
                true
            }
            ([1, 0], _) => {
                self.log.push("hid descriptor");
                let n = read.len().min(30);
                read[..n].copy_from_slice(&self.descriptor[..n]);
                true
            }
            ([2, 0], n) if self.on => {
                self.log.push("report descriptor");
                read.copy_from_slice(&self.report_descriptor[..n]);
                true
            }
            ([5, 0, 0, 0x08], 0) => {
                self.log.push("power on");
                self.on = true;
                true
            }
            ([5, 0, 0, 0x01], 0) if self.on => {
                self.log.push("reset");
                self.reset_pending = true;
                true
            }
            _ => false,
        }
    }
}

#[test]
fn the_hid_descriptor_says_where_everything_is() {
    let d = HidDescriptor::parse(&Fake::new().descriptor).unwrap();
    assert_eq!((d.vendor, d.product), (0x04f3, 0x3140));
    assert_eq!((d.input_register, d.command_register), (3, 5));
    assert_eq!(d.report_descriptor_length as usize, touchpad_descriptor().len());
    let mut bad = Fake::new().descriptor;
    bad[2] = 0x02;
    assert_eq!(HidDescriptor::parse(&bad), None);
    assert_eq!(HidDescriptor::parse(&bad[..10]), None);
}

#[test]
fn a_touchpad_is_woken_reset_and_described_in_that_order() {
    let mut bus = Fake::new();
    let mut waited = 0;
    let d = i2c::bring_up(&mut bus, 0x15, 1, |ms| waited += ms).unwrap();
    assert_eq!(
        bus.log,
        [
            "hid descriptor",
            "power on",
            "reset",
            "reset answer",
            "report descriptor"
        ]
    );
    assert!(d.reset_answered);
    assert_eq!((d.descriptor.vendor, d.descriptor.product), (0x04f3, 0x3140));
    assert_eq!(d.layout.report_id, Some(1));
    assert!(d.layout.relative());
    assert!(waited > 0);
}

#[test]
fn a_moved_finger_moves_the_pointer_and_a_click_presses() {
    let mut bus = Fake::new();
    let mut d = i2c::bring_up(&mut bus, 0x15, 1, |_| {}).unwrap();
    let mut p = Pointer::new(1920, 1080);
    let mut out = Vec::new();
    // Nothing to say: a length of 0.
    assert_eq!(d.poll(&mut bus, &mut p, (1920, 1080), &mut out), Ok(false));
    assert!(out.is_empty());
    // Report 1: left button, 5 right, 3 up.
    bus.reports.push_back(vec![1, 0b01, 5, 0xfd]);
    // A precision touchpad's report: not followed.
    bus.reports
        .push_back(vec![3, 0x03, 0x10, 0x00, 0x20, 0x00, 0, 0, 1, 0]);
    // The button let go.
    bus.reports.push_back(vec![1, 0, 0, 0]);
    for _ in 0..3 {
        assert_eq!(d.poll(&mut bus, &mut p, (1920, 1080), &mut out), Ok(true));
    }
    assert_eq!(
        out,
        [
            PointerEvent::Move {
                x: 965,
                y: 537,
                relative: true
            },
            PointerEvent::Press {
                down: true,
                x: 965,
                y: 537
            },
            PointerEvent::Press {
                down: false,
                x: 965,
                y: 537
            },
        ]
    );
}

#[test]
fn read_input_gives_the_report_with_its_id() {
    let mut bus = Fake::new();
    let mut d = i2c::bring_up(&mut bus, 0x15, 1, |_| {}).unwrap();
    bus.reports.push_back(vec![1, 2, 3, 4]);
    assert_eq!(d.read_input(&mut bus), Ok(Some(&[1u8, 2, 3, 4][..])));
    assert_eq!(d.read_input(&mut bus), Ok(None));
    bus.address = 0x2c;
    assert_eq!(d.read_input(&mut bus), Err(Error::Input));
}

#[test]
fn an_unanswered_reset_is_waited_for_and_then_gone_on_from() {
    let mut bus = Fake::new();
    // A report already waiting is not the reset's answer: the next read
    // is.
    bus.reports.push_back(vec![1, 0, 1, 1]);
    let mut waits = 0;
    let d = i2c::bring_up(&mut bus, 0x15, 1, |_| waits += 1).unwrap();
    assert!(d.reset_answered);
    assert_eq!(waits, 3);
    let mut bus = Fake::new();
    bus.input_naks = true;
    let mut waits = 0;
    let d = i2c::bring_up(&mut bus, 0x15, 1, |_| waits += 1).unwrap();
    assert!(!d.reset_answered);
    // About a second of 10 ms waits, and no more.
    assert!((100..=103).contains(&waits), "{waits}");
}

#[test]
fn a_device_that_does_not_answer_fails_after_a_few_tries() {
    let mut bus = Fake::new();
    assert_eq!(i2c::bring_up(&mut bus, 0x2c, 1, |_| {}), Err(Error::NoDescriptor));
    // The first two asks not acknowledged: the third is.
    let mut bus = Fake::new();
    bus.nak_first = 2;
    assert!(i2c::bring_up(&mut bus, 0x15, 1, |_| {}).is_ok());
    let mut bus = Fake::new();
    bus.descriptor[2] = 0x02;
    assert_eq!(
        i2c::bring_up(&mut bus, 0x15, 1, |_| {}),
        Err(Error::BadDescriptor)
    );
}

#[test]
fn the_state_machine_steps_one_transfer_at_a_time() {
    let mut bus = Fake::new();
    let mut b = Bringup::new(0x15, 1);
    assert_eq!(b.step(&mut bus), Step::Again(0));
    assert_eq!(bus.log, ["hid descriptor"]);
    assert!(matches!(b.step(&mut bus), Step::Again(ms) if ms > 0));
    assert_eq!(bus.log.last(), Some(&"power on"));
    assert!(matches!(b.step(&mut bus), Step::Again(ms) if ms > 0));
    assert_eq!(bus.log.last(), Some(&"reset"));
    assert_eq!(b.step(&mut bus), Step::Again(0));
    assert!(matches!(b.step(&mut bus), Step::Ready(_)));
}

#[test]
fn a_descriptor_with_no_pointer_is_refused() {
    let mut bus = Fake::new();
    // Only the precision touchpad's configuration collection: no X, Y.
    let config = &TOUCHPAD_PTP[TOUCHPAD_PTP.len() - 26..];
    assert_eq!(config[0..4], [0x05, 0x0d, 0x09, 0x0e]);
    bus.report_descriptor = config.to_vec();
    bus.descriptor[4..6].copy_from_slice(&(config.len() as u16).to_le_bytes());
    assert_eq!(i2c::bring_up(&mut bus, 0x15, 1, |_| {}), Err(Error::NoPointer));
}

/// A boot report's keys: "a" down, Shift with it, "a" up, all up; a
/// report saying too many keys are held changes nothing.
#[test]
fn a_boot_keyboard_report_becomes_presses_and_releases() {
    use crate::{Key, Keyboard};
    const A: u16 = 30;
    const SHIFT: u16 = 42;
    let key = |code, down| Key { code, down };
    let mut k = Keyboard::default();
    assert_eq!(k.report(&[0, 0, 4, 0, 0, 0, 0, 0]), [key(A, true)]);
    assert_eq!(k.report(&[0x02, 0, 4, 0, 0, 0, 0, 0]), [key(SHIFT, true)]);
    assert!(k.report(&[0x02, 0, 1, 1, 1, 1, 1, 1]).is_empty());
    assert_eq!(k.report(&[0x02, 0, 0, 0, 0, 0, 0, 0]), [key(A, false)]);
    assert_eq!(k.release_all(), [key(SHIFT, false)]);
    assert_eq!(crate::usage(A), Some(4));
    assert_eq!(crate::key_code(0x28), 28, "Enter");
}