garage44.eu/jeroen/pinnacle

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

cartopolis-agent · 2026-11-30T16:44:52Z

test(xtask): the simulated keyboard pairs by code and types into Notes

The air's keyboard serves the HID service, waits for the code its person
types (SimAir::type_passkey) and types text a boot report a step
(SimAir::type_text). bluetooth-demo pairs it with the code the app shows
and types a note in Notes, three screenshots more.
xtask/src/main.rs | 127 +++++++++++++++++++++++++++++++++++++++++++++++++++---
 1 file changed, 120 insertions(+), 7 deletions(-)

diff --git a/xtask/src/main.rs b/xtask/src/main.rs
index 8764cc3..c55005f 100644
--- a/xtask/src/main.rs
+++ b/xtask/src/main.rs
@@ -6604,8 +6604,10 @@ fn air_irk(n: u8) -> [u8; 16] {
 /// The air a guest's Bluetooth controller is in: a simulated controller
 /// behind the guest's serial port (a Unix socket QEMU serves), and devices
 /// of our own beside it, each a host of its own: "Pinnacle Test" with its
-/// name, a battery at 87 % and a contact card; a keyboard; a heart-rate
-/// sensor whose rate ticks. Several guests may share one air (`pair`).
+/// name, a battery at 87 % and a contact card; a keyboard (HID over GATT,
+/// pairing by a code typed on it, [`SimAir::type_passkey`], then typing,
+/// [`SimAir::type_text`]); a heart-rate sensor whose rate ticks. Several
+/// guests may share one air (`pair`).
 struct SimAir {
     inner: std::sync::Arc<std::sync::Mutex<AirInner>>,
 }
@@ -6620,6 +6622,30 @@ struct AirInner {
     beats: u32,
     /// The Pinnacle's controller index and its own card.
     devices_card: (usize, Vec<u8>),
+    /// The keyboard's pairing waiting for its code: its connection.
+    passkey_wanted: Option<u16>,
+    /// Boot reports the keyboard is still to send, one a step.
+    reports: std::collections::VecDeque<[u8; 8]>,
+}
+
+/// The keyboard, of the air's own devices (from 0).
+const AIR_KEYBOARD: usize = 1;
+
+/// A character as a keyboard's boot report holds it: Shift and its usage
+/// (US layout, the one Pinnacle starts with).
+fn boot_usage(c: char) -> Option<(bool, u8)> {
+    Some(match c {
+        'a'..='z' => (false, 4 + (c as u8 - b'a')),
+        'A'..='Z' => (true, 4 + (c as u8 - b'A')),
+        '1'..='9' => (false, 0x1e + (c as u8 - b'1')),
+        '0' => (false, 0x27),
+        '\n' => (false, 0x28),
+        ' ' => (false, 0x2c),
+        '.' => (false, 0x37),
+        ',' => (false, 0x36),
+        '!' => (true, 0x1e),
+        _ => return None,
+    })
 }
 
 impl SimAir {
@@ -6670,10 +6696,7 @@ impl SimAir {
             &mut air,
             2,
             "Keyboard K380",
-            vec![
-                Service::new(Uuid::Short(gatt::HUMAN_INTERFACE_DEVICE), Vec::new()),
-                battery(62),
-            ],
+            vec![pinnacle_bt::hogp::keyboard_service(), battery(62)],
             pinnacle_bt::smp::KEYBOARD_ONLY,
         );
         add(
@@ -6702,6 +6725,8 @@ impl SimAir {
             start: Instant::now(),
             beats: 0,
             devices_card: (pinnacle_index, test_card.to_bytes().to_vec()),
+            passkey_wanted: None,
+            reports: std::collections::VecDeque::new(),
         }));
         let worker = inner.clone();
         std::thread::spawn(move || {
@@ -6732,6 +6757,30 @@ impl SimAir {
         Ok(address)
     }
 
+    /// The keyboard's person types the code the guest shows, then Enter.
+    fn type_passkey(&self, passkey: u32) -> Result {
+        let mut inner = self.inner.lock().map_err(|e| e.to_string())?;
+        let connection = inner
+            .passkey_wanted
+            .take()
+            .ok_or("the keyboard asks for no code")?;
+        inner.devices[AIR_KEYBOARD].1.enter_passkey(connection, passkey);
+        Ok(())
+    }
+
+    /// Types `text` on the keyboard: a press and a release a character.
+    fn type_text(&self, text: &str) -> Result {
+        let mut inner = self.inner.lock().map_err(|e| e.to_string())?;
+        for c in text.chars() {
+            let (shift, usage) = boot_usage(c).ok_or_else(|| format!("no key for {c:?}"))?;
+            inner
+                .reports
+                .push_back([u8::from(shift) << 1, 0, usage, 0, 0, 0, 0, 0]);
+            inner.reports.push_back([0; 8]);
+        }
+        Ok(())
+    }
+
     /// The socket path for a new guest; QEMU serves it, this connects.
     fn socket_for_guest(&self) -> PathBuf {
         let n = SOCKETS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
@@ -6797,10 +6846,27 @@ impl AirInner {
                     pinnacle_bt::Event::Changed { handle, .. } if *i == self.devices_card.0 => {
                         host.set_value(handle, &self.devices_card.1);
                     }
+                    // The keyboard waits for its person to type the code.
+                    pinnacle_bt::Event::Passkey {
+                        connection,
+                        passkey: None,
+                        ..
+                    } => self.passkey_wanted = Some(connection),
                     _ => {}
                 }
             }
         }
+        // The keyboard's keys, a report a step.
+        if let Some(report) = self.reports.pop_front() {
+            let keyboard = &mut self.devices[AIR_KEYBOARD].1;
+            let input = keyboard.table().value_handle(
+                pinnacle_bt::Uuid::Short(pinnacle_bt::gatt::HUMAN_INTERFACE_DEVICE),
+                pinnacle_bt::Uuid::Short(pinnacle_bt::gatt::BOOT_KEYBOARD_INPUT),
+            );
+            if let Some(input) = input {
+                keyboard.set_value(input, &report);
+            }
+        }
         // The heart-rate sensor's measurement, once a second.
         if now / 1000 > u64::from(self.beats) {
             self.beats = (now / 1000) as u32;
@@ -6822,7 +6888,8 @@ impl AirInner {
 /// simulated air's), one of them opened (a keyboard: its make, model and
 /// battery), then the Pinnacle nearby, added as a contact and paired (the
 /// number compared, the link private), found again first in the list, and
-/// private again when opened, with no question.
+/// private again when opened, with no question; then the keyboard, paired
+/// by the code shown typed on it, typing a note in Notes.
 fn bluetooth_demo(s: &mut Session, dir: &Path) -> Result {
     const B: &str = "bluetooth: button ";
     s.tap_named("launcher: tile ", "Bluetooth")?;
@@ -6880,6 +6947,52 @@ fn bluetooth_demo(s: &mut Session, dir: &Path) -> Result {
     s.shot(&dir.join("bt-10-moved-private.png"))?;
     s.tap_named(B, "disconnect")?;
     std::thread::sleep(Duration::from_millis(400));
+    // The keyboard, paired by a code shown here and typed on it, then
+    // typing into Notes. Its row behind the paired one depends on the order
+    // heard since Pinnacle Test moved: the one that opens as the keyboard.
+    let mut found = false;
+    for row in ["device-1", "device-2"] {
+        s.tap_named(B, row)?;
+        let line = s.wait_any(&["bluetooth: connecting to "], boot_timeout())?;
+        s.wait_for("bt: connected to")?;
+        if line.ends_with("Keyboard K380") {
+            found = true;
+            break;
+        }
+        s.tap_named(B, "back")?;
+        std::thread::sleep(Duration::from_millis(600));
+    }
+    if !found {
+        return Err("the keyboard is not in the list".into());
+    }
+    std::thread::sleep(Duration::from_millis(800));
+    s.tap_named(B, "pair")?;
+    let line = s.wait_any(&["bt: pairing with Keyboard K380: type "], boot_timeout())?;
+    let passkey: u32 = line
+        .trim_start_matches("bt: pairing with Keyboard K380: type ")
+        .split(' ')
+        .next()
+        .and_then(|digits| digits.parse().ok())
+        .ok_or_else(|| format!("no code in {line:?}"))?;
+    std::thread::sleep(Duration::from_millis(600));
+    s.shot(&dir.join("bt-11-keyboard-code.png"))?;
+    air().type_passkey(passkey)?;
+    s.wait_for("bt: paired with Keyboard K380")?;
+    s.wait_for("bt: keys from")?;
+    std::thread::sleep(Duration::from_millis(600));
+    s.shot(&dir.join("bt-12-keyboard-paired.png"))?;
+    // Back to the list and out of the app: the keyboard stays connected.
+    s.tap_named(B, "back")?;
+    std::thread::sleep(Duration::from_millis(400));
+    s.home()?;
+    s.tap_named("launcher: tile ", "Notes")?;
+    s.wait_for("display: Notes connected")?;
+    s.tap_named("notes: button ", "new")?;
+    s.wait_for("notes: new ")?;
+    air().type_text("Typed on a Bluetooth keyboard, paired by a code.")?;
+    s.wait_for("notes: saved ")?;
+    std::thread::sleep(Duration::from_millis(600));
+    s.shot(&dir.join("bt-13-notes.png"))?;
     s.home()
 }