Skip to main content
← PSoXide SDK guides and examples · SDK 80d1c329e977 · All Cargo features enabled; check feature gates before use.

psx_pad/
lib.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! Digital, DualShock and neGcon pad polling via SIO0.
3//!
4//! Talks directly to the SIO0 hardware (no BIOS syscalls) so the
5//! same code works whether we side-load a homebrew (HLE BIOS) or
6//! boot through the real BIOS. The controller protocol is simple
7//! enough that a hand-rolled select + four-byte exchange beats
8//! opening events and waiting on them.
9//!
10//! Typical use from a game loop. The controller port has one owner, the
11//! `ControllerPort` token from `psx_rt::Peripherals::take()`, which every pad
12//! poll and memory-card transfer borrows for the length of its transaction:
13//!
14//! ```text
15//! let mut port = peripherals.controller_port;
16//! let mut reader = psx_pad::PadReader::port1();
17//! let pad = reader.poll_on(&mut port);
18//! if pad.buttons.is_held(psx_pad::button::START) {
19//!     // …
20//! }
21//! ```
22//!
23//! The protocol spec, reproduced from nocash PSX-SPX:
24//!
25//! | `TX` | `RX` | Meaning                            |
26//! |------|------|------------------------------------|
27//! | `01` | `FF` | Address byte / select controller   |
28//! | `42` | `41` | Poll command / digital pad ID low  |
29//! | `00` | `5A` | Fill byte / ID high                |
30//! | `00` | `b0` | Buttons group 1 (active-low)       |
31//! | `00` | `b1` | Buttons group 2 (active-low)       |
32//!
33//! DualShock analog mode uses the same first four bytes but reports
34//! ID low `0x73` and appends four stick bytes:
35//! right X/Y, then left X/Y. Fresh DualShocks boot digital, so games
36//! that require sticks should either call [`enable_analog_on`] or
37//! show an "enable analog mode" prompt when [`PadState::is_analog`]
38//! is false. Programs that require a DualShock call
39//! [`require_analog_on`] at boot: it locks the pad in analog mode, so
40//! the Analog button cannot switch it back, and says whether an
41//! analog-capable pad is there at all (`sdk/docs/PAD-ANALOG.md`).
42//!
43//! Every poll is a complete, ACK-paced packet whose length follows the ID it
44//! reports, so a 0x41 digital frame and a 0x73 analog frame decode the same
45//! buttons. A packet that fails part way reports [`PadMode::Unknown`]; read
46//! through a [`PadReader`] to get the last clean state instead.
47//!
48//! Our [`ButtonState`] stores active-high so `buttons.is_held` feels
49//! natural in game code.
50
51#![no_std]
52#![cfg_attr(
53    all(feature = "irq-engine", target_arch = "mips"),
54    feature(asm_experimental_arch)
55)]
56#![deny(unsafe_op_in_unsafe_fn)]
57#![warn(missing_docs)]
58
59use psx_hw::sio::sio0;
60use psx_io::controller_port::{ExchangeError, Timing, Transport};
61use psx_io::periph::ControllerPort;
62
63pub use psx_io::controller_port::Port;
64
65#[cfg(all(feature = "irq-engine", target_arch = "mips"))]
66pub mod console;
67pub mod engine;
68pub mod tracker;
69pub use tracker::PadTracker;
70
71// Under test the driver talks to a controller model, not the registers.
72#[cfg(test)]
73mod engine_tests;
74#[cfg(test)]
75mod mock_sio;
76#[cfg(test)]
77mod transport_tests;
78
79/// Named button bitmasks (active-high in this representation).
80/// Hardware's active-low wire format is hidden inside [`poll_port1`].
81pub mod button {
82    /// SELECT.
83    pub const SELECT: u16 = 1 << 0;
84    /// Left stick click (DualShock L3).
85    pub const L3: u16 = 1 << 1;
86    /// Right stick click (DualShock R3).
87    pub const R3: u16 = 1 << 2;
88    /// START.
89    pub const START: u16 = 1 << 3;
90    /// D-pad up.
91    pub const UP: u16 = 1 << 4;
92    /// D-pad right.
93    pub const RIGHT: u16 = 1 << 5;
94    /// D-pad down.
95    pub const DOWN: u16 = 1 << 6;
96    /// D-pad left.
97    pub const LEFT: u16 = 1 << 7;
98    /// L2 shoulder.
99    pub const L2: u16 = 1 << 8;
100    /// R2 shoulder.
101    pub const R2: u16 = 1 << 9;
102    /// L1 shoulder.
103    pub const L1: u16 = 1 << 10;
104    /// R1 shoulder.
105    pub const R1: u16 = 1 << 11;
106    /// Triangle face button.
107    pub const TRIANGLE: u16 = 1 << 12;
108    /// Circle face button.
109    pub const CIRCLE: u16 = 1 << 13;
110    /// Cross (X) face button.
111    pub const CROSS: u16 = 1 << 14;
112    /// Square face button.
113    pub const SQUARE: u16 = 1 << 15;
114}
115
116/// Result of one pad poll. `bits()` gives the raw active-high mask;
117/// [`ButtonState::is_held`] is the ergonomic per-button check.
118#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
119pub struct ButtonState(u16);
120
121impl ButtonState {
122    /// Empty -- nothing held.
123    pub const NONE: Self = Self(0);
124
125    /// Construct from an active-high mask.
126    pub const fn from_bits(bits: u16) -> Self {
127        Self(bits)
128    }
129
130    /// Raw bitmask.
131    #[inline]
132    pub const fn bits(self) -> u16 {
133        self.0
134    }
135
136    /// True when any masked button is down now and none was down previously.
137    /// For multi-button masks this is a group edge, not a per-button edge.
138    #[inline]
139    pub const fn pressed_since(self, previous: Self, mask: u16) -> bool {
140        self.is_held(mask) && !previous.is_held(mask)
141    }
142
143    /// `true` when `mask` (any single-bit [`button`] constant or an
144    /// OR of several) is currently pressed.
145    #[inline]
146    pub const fn is_held(self, mask: u16) -> bool {
147        self.0 & mask != 0
148    }
149}
150
151/// Default analog-stick reading. `0x80` = centred, `0x00` = full
152/// negative, `0xFF` = full positive.
153pub const STICK_CENTER: u8 = 0x80;
154
155/// Controller operating mode inferred from the poll ID byte.
156#[derive(Copy, Clone, Debug, PartialEq, Eq)]
157pub enum PadMode {
158    /// No controller answered the poll.
159    Disconnected,
160    /// SCPH-1080 digital-pad shape: ID `0x41`, buttons only.
161    Digital,
162    /// DualShock analog shape: ID `0x73`, buttons plus stick bytes.
163    Analog,
164    /// neGcon-compatible racing controller: ID `0x23`, twist and three pressures.
165    Negcon,
166    /// DualShock config/escape shape: ID `0xF3`.
167    Config,
168    /// A controller answered with an ID this SDK does not classify yet.
169    Unknown,
170}
171
172impl PadMode {
173    /// `true` when a controller answered the poll.
174    #[inline]
175    pub const fn is_connected(self) -> bool {
176        !matches!(self, Self::Disconnected)
177    }
178
179    /// `true` when the controller is currently reporting stick bytes.
180    #[inline]
181    pub const fn has_sticks(self) -> bool {
182        matches!(self, Self::Analog | Self::Config)
183    }
184
185    const fn has_axes(self) -> bool {
186        self.has_sticks() || matches!(self, Self::Negcon)
187    }
188}
189
190/// Read-only neGcon wire inputs. No calibration, thresholds or button synthesis
191/// are applied. Compatible wheels sharing ID `0x23` have the same packet shape.
192#[derive(Copy, Clone, Debug, PartialEq, Eq)]
193pub struct NegconState {
194    /// Active-high digital switches: START, directions, R1 (R), TRIANGLE (B), CIRCLE (A).
195    pub buttons: ButtonState,
196    /// Raw steering/twist axis; nominal center is `0x80`.
197    pub twist: u8,
198    /// Analog I button, `0` released through `255` fully pressed.
199    pub i: u8,
200    /// Analog II button, `0` released through `255` fully pressed.
201    pub ii: u8,
202    /// Analog left shoulder, `0` released through `255` fully pressed.
203    pub left_shoulder: u8,
204}
205
206/// Raw DualShock stick bytes from one poll.
207#[derive(Copy, Clone, Debug, PartialEq, Eq)]
208pub struct AnalogSticks {
209    /// Right stick horizontal axis.
210    pub right_x: u8,
211    /// Right stick vertical axis.
212    pub right_y: u8,
213    /// Left stick horizontal axis.
214    pub left_x: u8,
215    /// Left stick vertical axis.
216    pub left_y: u8,
217}
218
219impl AnalogSticks {
220    /// Centred sticks.
221    pub const CENTERED: Self = Self {
222        right_x: STICK_CENTER,
223        right_y: STICK_CENTER,
224        left_x: STICK_CENTER,
225        left_y: STICK_CENTER,
226    };
227
228    /// Left stick as signed deltas from centre.
229    #[inline]
230    pub const fn left_centered(self) -> (i16, i16) {
231        (
232            self.left_x as i16 - STICK_CENTER as i16,
233            self.left_y as i16 - STICK_CENTER as i16,
234        )
235    }
236
237    /// Right stick as signed deltas from centre.
238    #[inline]
239    pub const fn right_centered(self) -> (i16, i16) {
240        (
241            self.right_x as i16 - STICK_CENTER as i16,
242            self.right_y as i16 - STICK_CENTER as i16,
243        )
244    }
245}
246
247/// A radial dead region around stick centre, with the scaled response the
248/// literature settles on.
249///
250/// Three games on the PSoXide demo disc had grown one of these and they did not
251/// agree. hl-psx tests `x*x + y*y` against a squared radius. VoXide gates each
252/// axis separately, which makes its dead region a square: a stick pushed gently
253/// along a diagonal clears the threshold on one axis and not the other, so the
254/// input snaps to a cardinal instead of going where it was pushed. Sutphin's
255/// write-up calls that the axial dead zone and its snapping is the classic
256/// complaint about it.
257///
258/// A stick's centre drift is radial, so the region that ignores it is a circle,
259/// and [`Deadzone::scaled`] is the scaled-radial form: remapped so the first
260/// real reading starts from zero rather than jumping to the boundary magnitude.
261/// That is the recommended default. [`Deadzone::gate`] is the plain radial one,
262/// kept because the games being replaced were tuned against it.
263///
264/// This is for two-axis input. A single-axis control is a different question
265/// and a scalar threshold is right for it: NitroXide steers on the left stick's
266/// X alone, and folding Y into the test there would let noise on an axis it
267/// does not read enable steering. See [`Deadzone::is_outside_axis`].
268#[derive(Copy, Clone, Debug, PartialEq, Eq)]
269pub struct Deadzone {
270    inner_squared: i32,
271    inner: i16,
272    outer: i16,
273}
274
275/// Full deflection on one axis, from a stick that reads 0..=255 about 128.
276pub const STICK_FULL: i16 = 127;
277
278/// Fine-aim response shared by first-person games.
279///
280/// The centre is deliberately gentle while full deflection remains near the
281/// full input range: 45% linear plus 55% cubic. This is the response used by
282/// `hl-psx`, promoted here so other PSoXide games do not grow subtly different
283/// controller curves.
284#[inline]
285pub const fn aim_curve(value: i16) -> i16 {
286    let value = if value < -128 {
287        -128
288    } else if value > 127 {
289        127
290    } else {
291        value
292    };
293    aim_curve_symmetric(value)
294}
295
296/// Fine-aim curve accepting both -128 and +128, for axes inverted after
297/// centering. Uses the same sequential integer rounding as [`aim_curve`].
298#[inline]
299pub const fn aim_curve_symmetric(value: i16) -> i16 {
300    let value = if value < -128 {
301        -128
302    } else if value > 128 {
303        128
304    } else {
305        value
306    };
307    let sign = if value < 0 { -1 } else { 1 };
308    let magnitude = if value < 0 {
309        -(value as i32)
310    } else {
311        value as i32
312    };
313    let cubic = magnitude * magnitude / 128 * magnitude / 128;
314    (sign * ((magnitude * 45 + cubic * 55) / 100)) as i16
315}
316
317impl Deadzone {
318    /// A dead region of `radius` counts around centre. Typical radii are 12 to
319    /// 30 of the 127 counts a healthy stick reaches. A negative radius is no
320    /// dead region (zero): the squared test would otherwise treat it as its
321    /// absolute value while [`scaled`](Self::scaled) divided by a zero length.
322    pub const fn new(radius: i16) -> Self {
323        let radius = if radius < 0 { 0 } else { radius };
324        Self {
325            inner_squared: (radius as i32) * (radius as i32),
326            inner: radius,
327            outer: STICK_FULL,
328        }
329    }
330
331    /// Treat any deflection at or beyond `outer` as full scale.
332    ///
333    /// A worn stick often cannot reach its corners, so without this the player
334    /// simply never gets full input. Sutphin recommends exposing it as a
335    /// setting for anything where magnitude matters.
336    pub const fn with_outer(mut self, outer: i16) -> Self {
337        self.outer = outer;
338        self
339    }
340
341    /// The inner radius this was built with.
342    pub const fn radius(self) -> i16 {
343        self.inner
344    }
345
346    /// Is this reading real input rather than centre drift?
347    ///
348    /// Strictly outside, matching the boundary behaviour of the games this
349    /// replaces.
350    #[inline]
351    pub const fn is_outside(self, x: i16, y: i16) -> bool {
352        let (x, y) = (x as i32, y as i32);
353        x * x + y * y > self.inner_squared
354    }
355
356    /// The reading unchanged if it is real input, or `None` inside the dead
357    /// region. The plain radial form: direction is preserved, but magnitude
358    /// jumps from zero to the boundary the moment it is crossed.
359    #[inline]
360    pub const fn gate(self, x: i16, y: i16) -> Option<(i16, i16)> {
361        if self.is_outside(x, y) {
362            Some((x, y))
363        } else {
364            None
365        }
366    }
367
368    /// Scaled radial: `None` inside the dead region, otherwise the reading with
369    /// its magnitude remapped from the dead edge onto full scale, keeping
370    /// direction.
371    ///
372    /// The result is clamped to [`STICK_FULL`] per axis. Without that a full
373    /// diagonal, which is 179 counts long rather than 127, remaps to 138 on
374    /// each axis and hands the game 9% more than it believes the stick can
375    /// produce.
376    #[inline]
377    pub fn scaled(self, x: i16, y: i16) -> Option<(i16, i16)> {
378        let (fx, fy) = (x as i32, y as i32);
379        let magnitude = psx_math::int32::isqrt_i32(fx * fx + fy * fy);
380        let inner = self.inner as i32;
381        if magnitude <= inner {
382            return None;
383        }
384        let span = (self.outer as i32 - inner).max(1);
385        let scaled = (((magnitude - inner) * STICK_FULL as i32) / span).min(STICK_FULL as i32);
386        Some((
387            ((fx * scaled) / magnitude) as i16,
388            ((fy * scaled) / magnitude) as i16,
389        ))
390    }
391
392    /// The one-axis form, for a control that reads a single axis.
393    #[inline]
394    pub const fn is_outside_axis(self, v: i16) -> bool {
395        let v = v as i32;
396        v * v > self.inner_squared
397    }
398
399    /// The one-axis form of [`Deadzone::scaled`].
400    #[inline]
401    pub const fn scaled_axis(self, v: i16) -> Option<i16> {
402        if !self.is_outside_axis(v) {
403            return None;
404        }
405        let span = if self.outer > self.inner {
406            (self.outer - self.inner) as i32
407        } else {
408            1
409        };
410        let magnitude = if v < 0 { -(v as i32) } else { v as i32 };
411        let scaled = (magnitude - self.inner as i32) * STICK_FULL as i32 / span;
412        let scaled = if scaled > STICK_FULL as i32 {
413            STICK_FULL as i32
414        } else {
415            scaled
416        };
417        Some(if v < 0 { -scaled as i16 } else { scaled as i16 })
418    }
419}
420
421impl Default for AnalogSticks {
422    fn default() -> Self {
423        Self::CENTERED
424    }
425}
426
427/// Result of one controller poll.
428#[derive(Copy, Clone, Debug, PartialEq, Eq)]
429pub struct PadState {
430    /// Active-high button state.
431    pub buttons: ButtonState,
432    /// Inferred controller mode.
433    pub mode: PadMode,
434    /// Stick bytes. Centred when the controller is not reporting sticks.
435    pub sticks: AnalogSticks,
436    /// Raw low ID byte returned by the controller.
437    pub id_low: u8,
438    /// Typed neGcon input from a complete packet, absent for every other device.
439    pub negcon: Option<NegconState>,
440}
441
442impl PadState {
443    /// No controller connected / no response.
444    pub const NONE: Self = Self {
445        buttons: ButtonState::NONE,
446        mode: PadMode::Disconnected,
447        sticks: AnalogSticks::CENTERED,
448        id_low: 0xff,
449        negcon: None,
450    };
451
452    /// `true` when a controller answered the poll.
453    #[inline]
454    pub const fn is_connected(self) -> bool {
455        self.mode.is_connected()
456    }
457
458    /// `true` when the controller is in DualShock analog mode.
459    #[inline]
460    pub const fn is_analog(self) -> bool {
461        matches!(self.mode, PadMode::Analog)
462    }
463}
464
465/// What the two motors of a DualShock are asked to do on a poll.
466///
467/// The small motor is on or off, the large motor has a level. The request
468/// rides in two bytes of every poll once the motors are mapped
469/// ([`enable_rumble_on`]); a pad that is not a DualShock in analog mode
470/// ignores it, and the driver sends it zeros.
471#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
472pub struct Rumble {
473    /// The small (high-frequency) motor: on or off.
474    pub small: bool,
475    /// The large (low-frequency) motor's level; below about 0x40 it does not
476    /// spin.
477    pub large: u8,
478}
479
480impl Rumble {
481    /// Both motors off.
482    pub const OFF: Rumble = Rumble {
483        small: false,
484        large: 0,
485    };
486
487    /// A request for the two motors.
488    pub const fn new(small: bool, large: u8) -> Self {
489        Rumble { small, large }
490    }
491
492    /// Whether both motors are off.
493    pub const fn is_off(self) -> bool {
494        !self.small && self.large == 0
495    }
496
497    /// The two poll bytes: the small motor's (bit 0) and the large motor's
498    /// level, in the order [`MOTOR_MAP_PACKET`] maps them.
499    pub(crate) const fn bytes(self) -> (u8, u8) {
500        (self.small as u8, self.large)
501    }
502}
503
504/// One logical game action bound to up to two physical button masks.
505///
506/// A mask may contain more than one button; any held bit activates the
507/// binding. Zero means that binding slot is unused.
508#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
509pub struct ActionBinding {
510    /// Primary physical button mask.
511    pub primary: u16,
512    /// Optional secondary physical button mask.
513    pub secondary: u16,
514}
515
516impl ActionBinding {
517    /// An action with no physical button assigned.
518    pub const UNBOUND: Self = Self::new(0, 0);
519
520    /// Bind an action to primary and secondary button masks.
521    pub const fn new(primary: u16, secondary: u16) -> Self {
522        Self { primary, secondary }
523    }
524
525    #[inline]
526    const fn mask(self) -> u16 {
527        self.primary | self.secondary
528    }
529}
530
531/// Fixed, allocation-free mapping from game-defined action indices to pads.
532#[derive(Copy, Clone, Debug, PartialEq, Eq)]
533pub struct ActionMap<const ACTIONS: usize> {
534    bindings: [ActionBinding; ACTIONS],
535}
536
537impl<const ACTIONS: usize> ActionMap<ACTIONS> {
538    /// Construct a map in the same order as the game's action enum.
539    pub const fn new(bindings: [ActionBinding; ACTIONS]) -> Self {
540        Self { bindings }
541    }
542
543    /// Read the complete binding table.
544    pub const fn bindings(&self) -> &[ActionBinding; ACTIONS] {
545        &self.bindings
546    }
547
548    /// Replace one binding. Out-of-range indices are ignored.
549    pub fn set(&mut self, action: usize, binding: ActionBinding) {
550        if let Some(slot) = self.bindings.get_mut(action) {
551            *slot = binding;
552        }
553    }
554
555    /// Read one binding, returning [`ActionBinding::UNBOUND`] out of range.
556    pub const fn binding(&self, action: usize) -> ActionBinding {
557        if action < ACTIONS {
558            self.bindings[action]
559        } else {
560            ActionBinding::UNBOUND
561        }
562    }
563
564    /// Interpret current and previous pad states through this map.
565    pub const fn input<'a>(
566        &'a self,
567        current: PadState,
568        previous: PadState,
569    ) -> ActionInput<'a, ACTIONS> {
570        ActionInput {
571            map: self,
572            current,
573            previous,
574        }
575    }
576}
577
578/// Per-tick logical action view over a pair of pad samples.
579#[derive(Copy, Clone, Debug)]
580pub struct ActionInput<'a, const ACTIONS: usize> {
581    map: &'a ActionMap<ACTIONS>,
582    current: PadState,
583    previous: PadState,
584}
585
586impl<const ACTIONS: usize> ActionInput<'_, ACTIONS> {
587    /// Whether an action is held now.
588    #[inline]
589    pub fn is_held(self, action: usize) -> bool {
590        let mask = self.map.binding(action).mask();
591        mask != 0 && self.current.buttons.is_held(mask)
592    }
593
594    /// Whether an action transitioned from released to pressed this tick.
595    #[inline]
596    pub fn just_pressed(self, action: usize) -> bool {
597        let mask = self.map.binding(action).mask();
598        mask != 0 && self.current.buttons.is_held(mask) && !self.previous.buttons.is_held(mask)
599    }
600
601    /// Whether an action transitioned from pressed to released this tick.
602    #[inline]
603    pub fn just_released(self, action: usize) -> bool {
604        let mask = self.map.binding(action).mask();
605        mask != 0 && !self.current.buttons.is_held(mask) && self.previous.buttons.is_held(mask)
606    }
607}
608
609/// How a transaction paces its bytes across the serial link.
610#[derive(Copy, Clone, Debug, PartialEq, Eq)]
611pub enum Pacing {
612    /// Wait only for the RX FIFO between bytes; never wait for `/ACK`. This is
613    /// the legacy timing: it works with fast (often third-party) controllers and
614    /// in emulation, but desyncs slower original units (e.g. SCPH-1200) that
615    /// pull `/ACK` low later. Exposed so a diagnostic can reproduce the failure
616    /// side-by-side with [`Pacing::AckWait`].
617    NoAckWait,
618    /// Wait for the device's `/ACK` (DSR) pulse after each non-final byte before
619    /// clocking the next one. Matches the BIOS pacing, but corrupted frames on a
620    /// third-party clone pad, so this IRQ-latched path remains diagnostic.
621    /// Production polling observes live ACK without rewriting CTRL between
622    /// bytes; the analog-enable handshake retains its separate fixed timing.
623    /// Kept so on-console diagnostics can compare the legacy pacings.
624    AckWait,
625}
626
627/// Raw wire result of one poll, before active-low button inversion. Carries the
628/// per-byte `/ACK` observations so a diagnostic can show whether the controller
629/// acknowledges each byte, and which pacing produced a clean handshake.
630#[derive(Copy, Clone, Debug, PartialEq, Eq)]
631pub struct RawPoll {
632    /// ID low byte: 0x41 digital, 0x73 analog, 0xF3 config, 0xFF none.
633    pub id_low: u8,
634    /// ID high byte; 0x5A on a valid controller, anything else is a desync.
635    pub id_high: u8,
636    /// First button byte, raw active-low wire value.
637    pub buttons_low: u8,
638    /// Second button byte, raw active-low wire value.
639    pub buttons_high: u8,
640    /// Raw four-axis bytes. For neGcon these contain twist/I/II/L in wire order;
641    /// use [`RawPoll::negcon`] for the typed view. These are not DualShock sticks.
642    pub sticks: AnalogSticks,
643    /// Mode inferred from the ID bytes (`Unknown` when the 0x5A magic is wrong).
644    pub mode: PadMode,
645    /// Bit `i` set if exchange `i` observed an `/ACK` pulse (bit 0 = select byte).
646    pub ack_seen: u16,
647    /// Number of exchanges performed (select byte + payload bytes).
648    pub exchanges: u8,
649}
650
651impl RawPoll {
652    /// A poll where nothing answered (id_low `0xFF`). Useful as a const seed.
653    pub const NONE: Self = Self::disconnected(0xff);
654
655    /// A poll where nothing answered.
656    const fn disconnected(id_low: u8) -> Self {
657        Self {
658            id_low,
659            id_high: 0xff,
660            buttons_low: 0xff,
661            buttons_high: 0xff,
662            sticks: AnalogSticks::CENTERED,
663            mode: PadMode::Disconnected,
664            ack_seen: 0,
665            exchanges: 0,
666        }
667    }
668
669    /// `true` when every payload exchange that should have been acknowledged
670    /// was. The select byte (bit 0) and all bytes up to (but not including) the
671    /// final, never-acknowledged byte must each show an `/ACK`.
672    #[inline]
673    pub fn is_fully_acknowledged(self) -> bool {
674        if self.exchanges < 2 {
675            return false;
676        }
677        // The last exchange is the final packet byte; the device does not ACK
678        // it. Every earlier exchange must have been acknowledged.
679        let acked_needed = self.exchanges - 1;
680        let mask = (1u16 << acked_needed) - 1;
681        self.ack_seen & mask == mask
682    }
683
684    /// Convert to the cleaned [`PadState`] used by game code.
685    pub fn to_state(self) -> PadState {
686        let negcon = self.negcon();
687        if self.mode == PadMode::Negcon && negcon.is_none() {
688            return PadState {
689                mode: PadMode::Unknown,
690                ..PadState::NONE
691            };
692        }
693        PadState {
694            buttons: decode_buttons(self.buttons_low, self.buttons_high),
695            mode: self.mode,
696            sticks: if self.mode == PadMode::Negcon {
697                AnalogSticks::CENTERED
698            } else {
699                self.sticks
700            },
701            id_low: self.id_low,
702            negcon,
703        }
704    }
705
706    /// Decode only a complete neGcon packet, including its ID and response length.
707    /// Production pollers additionally reject byte/ACK timeouts before publishing.
708    pub fn negcon(self) -> Option<NegconState> {
709        if self.mode != PadMode::Negcon
710            || self.id_low != 0x23
711            || self.id_high != 0x5a
712            || self.exchanges != 9
713        {
714            return None;
715        }
716        Some(NegconState {
717            buttons: decode_buttons(self.buttons_low, self.buttons_high),
718            twist: self.sticks.right_x,
719            i: self.sticks.right_y,
720            ii: self.sticks.left_x,
721            left_shoulder: self.sticks.left_y,
722        })
723    }
724}
725
726// The driver talks to the port through `psx_io::controller_port::Transport`: the
727// production poll and the configuration sequence use its select / exchange /
728// finish steps, the diagnostic pacings below use its register accesses. A
729// transaction needs the port for its whole length, so every entry point takes
730// the `ControllerPort` token by `&mut` (a memory-card transfer borrows it the
731// same way), and `PadReader` keeps no hardware state of its own.
732
733// The controller IRQ stays masked in `I_MASK` (the runtime only unmasks VBlank),
734// but arming it in CTRL is what latches `STAT` bit 9 on the `/ACK` edge for the
735// diagnostic ack-wait pacing.
736const CTRL_ACK: u16 = sio0::ctrl::ACK;
737
738const STAT_TX_READY: u32 = sio0::stat::TX_READY;
739const STAT_RX_NOT_EMPTY: u32 = sio0::stat::RX_NOT_EMPTY;
740const STAT_DSR_LEVEL: u32 = sio0::stat::DSR_LEVEL;
741const STAT_IRQ: u32 = sio0::stat::IRQ;
742
743/// Spin budget waiting for the byte shift itself (TX-ready / RX-not-empty).
744const EXCHANGE_WAIT_SPINS: u32 = Timing::PAD.byte_spins;
745/// Spin budget waiting for the `/ACK` pulse. Comfortably exceeds the kernel's
746/// ~100us DSR timeout on hardware and the emulator's ~1k-cycle ACK deadline,
747/// so a genuinely slow original controller is still given time to answer.
748const ACK_WAIT_SPINS: u32 = Timing::PAD.ack_spins;
749/// Setup delay (bounded STAT reads) after asserting the select line, before the
750/// first clock. The original SCPH-1200 gives NO response without it and a clean
751/// `5A41` digital read with it; fast clones tolerate it either way (silicon,
752/// 2026-06-22). The on-console sweep put the floor between 384 (no response) and
753/// 768 (clean) under a 5-polls-per-frame stress harder than the in-game one poll
754/// per frame, so 1024 is a comfortable margin while keeping the per-poll
755/// busy-wait small. Production retains this measured setup margin and also
756/// waits for each non-final byte's ACK readiness; the BIOS likewise paces bytes.
757pub const DEFAULT_SETUP_SPINS: u32 = Timing::PAD.setup_spins;
758
759/// Spin budget for the address byte's `/ACK`, about 7,000 cycles at 6.9 cycles
760/// a spin on silicon. A socket with nothing in it never pulses `/ACK`, so this
761/// is what finding it empty costs after the setup delay. [`Timing::PAD`]'s
762/// 2,048 reads, which a slow byte part way through a packet may need, would
763/// cost twice as much. The console measured the pad's `/ACK` rising 1,627 to
764/// 1,712 cycles after the write, the address byte slowest (v2.1, one pad), so
765/// 512 spins (about 3,550 cycles) was only 2.07 times the slowest answer seen;
766/// 1,024 gives the margin to other pads and to a transaction that starts late.
767const ADDRESS_ACK_SPINS: u32 = 1024;
768
769/// Poll the controller in `socket` once.
770///
771/// The returned [`PadState`] always contains active-high buttons; in
772/// analog mode it also contains the four DualShock stick bytes. A packet
773/// that cannot be completed after bounded retries reports [`PadMode::Unknown`]
774/// rather than synthetic button bytes. A consistently absent device reports
775/// [`PadMode::Disconnected`] after the bounded acquisition attempts.
776///
777/// `port` is the [`ControllerPort`](psx_io::periph::ControllerPort) token; it
778/// stays borrowed for the length of the poll.
779#[doc(alias = "PadRead")]
780pub fn poll_on<T: Transport>(port: &mut T, socket: Port) -> PadState {
781    poll_state(port, socket, false, Rumble::OFF)
782}
783
784/// [`poll_on`] with the motors asked for `rumble`. A pad that is not a
785/// DualShock reporting analog mode is sent zeros; the request takes effect on
786/// one that has been through [`enable_rumble_on`].
787pub fn poll_rumble_on<T: Transport>(port: &mut T, socket: Port, rumble: Rumble) -> PadState {
788    poll_state(port, socket, false, rumble)
789}
790
791/// Poll port 1 once.
792#[deprecated(note = "use `poll_on` with the `ControllerPort` token")]
793pub fn poll_port1() -> PadState {
794    poll_on(&mut steal_port(), Port::One)
795}
796
797/// Poll port 2 once.
798#[deprecated(note = "use `poll_on` with the `ControllerPort` token")]
799pub fn poll_port2() -> PadState {
800    poll_on(&mut steal_port(), Port::Two)
801}
802
803/// The token for a deprecated forwarder that never took one.
804fn steal_port() -> ControllerPort {
805    // SAFETY: a token is a logic guard, not a memory-safety one (see
806    // `psx_io::periph`), and the old free functions never took one.
807    unsafe { ControllerPort::steal() }
808}
809
810/// Poll `socket` once and return the raw wire bytes plus `/ACK` observations,
811/// using the requested [`Pacing`]. Intended for diagnostics that want to show
812/// the unfiltered handshake (or reproduce the legacy [`Pacing::NoAckWait`]
813/// failure); normal game code should use [`poll_on`].
814pub fn poll_raw_on<T: Transport>(port: &mut T, socket: Port, pacing: Pacing) -> RawPoll {
815    poll_once_raw(port, socket, pacing)
816}
817
818/// Poll `socket` once with explicit fixed timing, for hardware diagnostics:
819/// `setup_spins` of delay after asserting the select line, plus `interbyte_spins`
820/// of fixed delay after each byte (bounded STAT reads -- no CTRL writes, no
821/// `/ACK` wait, no DSR IRQ). This isolates the two timings a strict original pad
822/// (SCPH-1200) might need -- setup time after `/CS`, and an inter-byte gap --
823/// without the machinery that corrupted the ack-wait path on silicon.
824pub fn poll_diagnostics_on<T: Transport>(
825    port: &mut T,
826    socket: Port,
827    setup_spins: u32,
828    interbyte_spins: u32,
829) -> RawPoll {
830    poll_once_timed(port, socket, setup_spins, interbyte_spins)
831}
832
833/// Poll port 1 once with fixed timing.
834#[deprecated(note = "use `poll_diagnostics_on` with the `ControllerPort` token")]
835pub fn poll_port1_diagnostics(setup_spins: u32, interbyte_spins: u32) -> RawPoll {
836    poll_diagnostics_on(&mut steal_port(), Port::One, setup_spins, interbyte_spins)
837}
838
839/// Ask the controller in `socket` to enter DualShock analog mode. Returns
840/// `true` when a follow-up poll reports analog mode.
841///
842/// Digital-only controllers simply keep reporting digital mode, so
843/// callers should still gate analog-only controls on
844/// [`PadState::is_analog`].
845pub fn enable_analog_on<T: Transport>(port: &mut T, socket: Port) -> bool {
846    enable_analog(port, socket)
847}
848
849/// Ask the port-1 controller to enter analog mode.
850#[deprecated(note = "use `enable_analog_on` with the `ControllerPort` token")]
851pub fn enable_analog_port1() -> bool {
852    enable_analog_on(&mut steal_port(), Port::One)
853}
854
855/// Ask the port-2 controller to enter analog mode.
856#[deprecated(note = "use `enable_analog_on` with the `ControllerPort` token")]
857pub fn enable_analog_port2() -> bool {
858    enable_analog_on(&mut steal_port(), Port::Two)
859}
860
861/// What a port held after [`require_analog_on`] asked it for analog mode.
862#[derive(Copy, Clone, Debug, PartialEq, Eq)]
863pub enum AnalogRequirement {
864    /// A DualShock answered in analog mode, now locked there: the Analog
865    /// button no longer switches it back to digital.
866    Analog,
867    /// A controller answered but did not settle in analog mode: an original
868    /// digital pad, or a DualShock that refused or ignored the request.
869    DigitalOnly,
870    /// No controller gave a clean reply.
871    Absent,
872}
873
874impl AnalogRequirement {
875    /// Classify the mode a pad reported after the analog request.
876    pub const fn from_mode(mode: PadMode) -> Self {
877        match mode {
878            PadMode::Analog => Self::Analog,
879            PadMode::Digital | PadMode::Config | PadMode::Negcon => Self::DigitalOnly,
880            PadMode::Disconnected | PadMode::Unknown => Self::Absent,
881        }
882    }
883}
884
885/// Put the controller in `socket` in analog mode, lock it there, and report
886/// what it settled on. For programs that need sticks and must not let the
887/// Analog button flip the pad back to digital mid-session. Call it at boot (a
888/// chain-loaded program starts from whatever the previous one left) and
889/// again while the answer is not [`AnalogRequirement::Analog`], so a pad
890/// plugged in later is picked up.
891pub fn require_analog_on<T: Transport>(port: &mut T, socket: Port) -> AnalogRequirement {
892    AnalogRequirement::from_mode(request_analog(port, socket, REQUIRE_ANALOG_GAP_SPINS).mode)
893}
894
895/// [`require_analog_on`] for port 1.
896#[deprecated(note = "use `require_analog_on` with the `ControllerPort` token")]
897pub fn require_analog_port1() -> AnalogRequirement {
898    require_analog_on(&mut steal_port(), Port::One)
899}
900
901/// A port reader that never hands a garbled packet to the game.
902///
903/// A poll that fails validation reports [`PadMode::Unknown`] with every
904/// button released. Taken at face value, a held button would read as released
905/// for that one frame and then as a fresh press on the next, so a held Select
906/// or Cross fires twice. The reader returns the last clean state instead.
907/// A clean report of an empty port is accepted as it is: unplugging a pad
908/// does release its buttons.
909#[derive(Copy, Clone, Debug)]
910pub struct PadReader {
911    socket: Port,
912    last: PadState,
913    /// What the motors are asked for on every poll.
914    rumble: Rumble,
915}
916
917impl PadReader {
918    /// A reader for port 1 that has seen nothing yet.
919    pub const fn port1() -> Self {
920        Self {
921            socket: Port::One,
922            last: PadState::NONE,
923            rumble: Rumble::OFF,
924        }
925    }
926
927    /// A reader for port 2 that has seen nothing yet.
928    pub const fn port2() -> Self {
929        Self {
930            socket: Port::Two,
931            last: PadState::NONE,
932            rumble: Rumble::OFF,
933        }
934    }
935
936    /// Poll the port once and return the latest clean state.
937    pub fn poll_on<T: Transport>(&mut self, port: &mut T) -> PadState {
938        // A pad that was there a moment ago has its absence confirmed before
939        // the reader believes it; a socket that was already empty is told so
940        // at once.
941        let polled = poll_state(port, self.socket, self.last.is_connected(), self.rumble);
942        self.accept(polled)
943    }
944
945    /// What the motors are asked to do on every poll from now on. Takes effect
946    /// on a DualShock in analog mode that has been through
947    /// [`enable_rumble_on`](Self::enable_rumble_on).
948    pub fn set_rumble(&mut self, rumble: Rumble) {
949        self.rumble = rumble;
950    }
951
952    /// What the motors are asked for now.
953    pub const fn rumble(&self) -> Rumble {
954        self.rumble
955    }
956
957    /// Map the motors on this reader's pad. See [`enable_rumble_on`].
958    pub fn enable_rumble_on<T: Transport>(&mut self, port: &mut T) -> bool {
959        enable_rumble_on(port, self.socket)
960    }
961
962    /// Stop both motors now: ask for none and poll once so the pad hears it.
963    /// For a pause, a menu, an exit; an unplugged pad has nothing to stop.
964    pub fn stop_motors_on<T: Transport>(&mut self, port: &mut T) -> PadState {
965        self.rumble = Rumble::OFF;
966        self.poll_on(port)
967    }
968
969    /// Poll the port once and return the latest clean state.
970    #[deprecated(note = "use `poll_on` with the `ControllerPort` token")]
971    pub fn poll(&mut self) -> PadState {
972        self.poll_on(&mut steal_port())
973    }
974
975    /// Fold one poll result into the reader and return the latest clean
976    /// state. [`PadReader::poll_on`] calls this; it is public so a caller that
977    /// polls some other way gets the same rule.
978    pub fn accept(&mut self, state: PadState) -> PadState {
979        if state.mode != PadMode::Unknown {
980            self.last = state;
981        }
982        self.last
983    }
984
985    /// The latest clean state without polling.
986    pub const fn last(&self) -> PadState {
987        self.last
988    }
989}
990
991/// Poll a port, retrying a garbled response.
992///
993/// On real hardware a poll occasionally desyncs -- a stale byte lingering in
994/// the RX FIFO from the previous transaction, or a slipped /ACK between bytes --
995/// and the ID handshake comes back wrong. A single such frame reads as "every
996/// button released", which makes a *held* button (jump, Start) look like a fresh
997/// press the next frame. So: when a controller answered but the DualShock ID
998/// handshake didn't validate, retry a few times and take the first clean read.
999/// Transport failures are retried as whole transactions, and a failure at any
1000/// stage after the address byte reports Unknown instead of accepting partial
1001/// button bytes.
1002///
1003/// An address byte that is not acknowledged and answered `0xFF` is an empty
1004/// socket, and a poll that finds one returns at once: the setup delay and one
1005/// short wait are all it costs, where four attempts cost a hundred thousand
1006/// cycles a frame for a game that polls an empty port 2. `confirm_absent` is
1007/// for a caller that saw a pad on this socket last time: one such reply could
1008/// be a glitch on a pad that is still there, so it takes four before it says
1009/// the pad is gone.
1010fn poll_state<T: Transport>(
1011    bus: &mut T,
1012    socket: Port,
1013    confirm_absent: bool,
1014    rumble: Rumble,
1015) -> PadState {
1016    let mut last = PadState::NONE;
1017    let mut all_absent = true;
1018    let mut tries = 0;
1019    while tries < 4 {
1020        let s = poll_once(bus, socket, rumble).to_state();
1021        if matches!(
1022            s.mode,
1023            PadMode::Digital | PadMode::Analog | PadMode::Config | PadMode::Negcon
1024        ) {
1025            return s;
1026        }
1027        if s.mode == PadMode::Disconnected && !confirm_absent {
1028            return s;
1029        }
1030        all_absent &= s.mode == PadMode::Disconnected;
1031        last = s;
1032        tries += 1;
1033    }
1034    // Four complete address-byte replies of FF without ACK establish an
1035    // absent device. Any other failed stage means an invalid transaction.
1036    if !all_absent {
1037        last.mode = PadMode::Unknown;
1038    }
1039    last
1040}
1041
1042fn poll_once_raw<T: Transport>(bus: &mut T, socket: Port, pacing: Pacing) -> RawPoll {
1043    // Raise JOYN so the device's state machine starts from idle, then drain
1044    // any stale RX byte. Only the ack-wait path arms the DSR IRQ.
1045    bus.select_with(socket, matches!(pacing, Pacing::AckWait));
1046    bus.drain_receive();
1047
1048    let mut ack = 0u16;
1049    let mut i = 0u8;
1050
1051    // The select byte and the poll command are never the final byte of any
1052    // packet, so they are always `/ACK`-paced under `AckWait`.
1053    let _select = ex(bus, socket, pacing, 0x01, false, &mut ack, &mut i);
1054    let id_low = ex(bus, socket, pacing, 0x42, false, &mut ack, &mut i);
1055    let mut mode = mode_from_id_low(id_low);
1056    if !mode.is_connected() {
1057        bus.deselect();
1058        return RawPoll {
1059            exchanges: i,
1060            ack_seen: ack,
1061            ..RawPoll::disconnected(id_low)
1062        };
1063    }
1064
1065    let analog = mode.has_axes();
1066    let id_high = ex(bus, socket, pacing, 0x00, false, &mut ack, &mut i);
1067    if id_high != 0x5a {
1068        // Garbled handshake -- treat as Unknown and stop after the two
1069        // button bytes (we can no longer trust the reported length).
1070        mode = PadMode::Unknown;
1071    }
1072
1073    // For a digital pad the second button byte is the final byte (no `/ACK`
1074    // follows). For an analog pad the four stick bytes come after it.
1075    let read_sticks = analog && mode != PadMode::Unknown;
1076    let b0 = ex(bus, socket, pacing, 0x00, false, &mut ack, &mut i);
1077    let b1 = ex(bus, socket, pacing, 0x00, !read_sticks, &mut ack, &mut i);
1078
1079    let sticks = if read_sticks {
1080        let right_x = ex(bus, socket, pacing, 0x00, false, &mut ack, &mut i);
1081        let right_y = ex(bus, socket, pacing, 0x00, false, &mut ack, &mut i);
1082        let left_x = ex(bus, socket, pacing, 0x00, false, &mut ack, &mut i);
1083        let left_y = ex(bus, socket, pacing, 0x00, true, &mut ack, &mut i);
1084        AnalogSticks {
1085            right_x,
1086            right_y,
1087            left_x,
1088            left_y,
1089        }
1090    } else {
1091        AnalogSticks::CENTERED
1092    };
1093
1094    bus.deselect();
1095
1096    RawPoll {
1097        id_low,
1098        id_high,
1099        buttons_low: b0,
1100        buttons_high: b1,
1101        sticks,
1102        mode,
1103        ack_seen: ack,
1104        exchanges: i,
1105    }
1106}
1107
1108/// Clock one byte of a transaction under the given pacing, recording whether the
1109/// device acknowledged it. `is_last` marks the final byte of the packet, which
1110/// the device never acknowledges, so it is always sent without an `/ACK` wait.
1111#[inline]
1112fn ex<T: Transport>(
1113    bus: &mut T,
1114    socket: Port,
1115    pacing: Pacing,
1116    tx: u8,
1117    is_last: bool,
1118    ack_seen: &mut u16,
1119    idx: &mut u8,
1120) -> u8 {
1121    let i = *idx;
1122    *idx = idx.wrapping_add(1);
1123    match pacing {
1124        Pacing::NoAckWait => exchange_nowait(bus, tx),
1125        Pacing::AckWait if is_last => exchange_nowait(bus, tx),
1126        Pacing::AckWait => {
1127            let (byte, acked) = exchange_ack(bus, socket, tx);
1128            if acked && i < 16 {
1129                *ack_seen |= 1u16 << i;
1130            }
1131            byte
1132        }
1133    }
1134}
1135
1136/// The production poll: retain the measured post-select setup delay, then
1137/// wait for each non-final byte's live ACK assertion and release. RX-ready
1138/// only establishes that the current byte arrived, not that the controller
1139/// is ready for the next one. No IRQ enable or CTRL rewrite is needed.
1140fn poll_once<T: Transport>(bus: &mut T, socket: Port, rumble: Rumble) -> RawPoll {
1141    // A previous aborted transaction may have left ACK asserted: `begin` waits
1142    // for it to release, so an old pulse never counts as the new address
1143    // byte's ACK.
1144    let result = if bus.begin(socket, Timing::PAD) {
1145        poll_selected(bus, rumble)
1146    } else {
1147        None
1148    };
1149    // End the peripheral transaction on every path. On a failed byte, also
1150    // reset the deselected UART: deselect alone need not cancel a late RX byte
1151    // still in its shifter/FIFO. The next select restores MODE and BAUD before
1152    // asserting the port again.
1153    bus.finish(result.is_some());
1154    result.unwrap_or(RawPoll {
1155        mode: PadMode::Unknown,
1156        ..RawPoll::NONE
1157    })
1158}
1159
1160/// A complete selected-port poll, or no usable packet. The current ID
1161/// determines the length; a mode toggle never reuses an earlier length.
1162fn poll_selected<T: Transport>(bus: &mut T, rumble: Rumble) -> Option<RawPoll> {
1163    // The address byte is the one that tells a pad from an empty socket, so it
1164    // gets the BIOS's own limit for a device to answer, not the longer budget
1165    // for a slow byte part way through a packet.
1166    let address = Timing {
1167        ack_spins: ADDRESS_ACK_SPINS,
1168        ..Timing::PAD
1169    };
1170    match bus.exchange(0x01, false, address) {
1171        Ok(_) => {}
1172        Err(ExchangeError::AckTimeout { reply: 0xff }) => return Some(RawPoll::NONE),
1173        Err(_) => return None,
1174    }
1175    let id_low = bus.exchange(0x42, false, Timing::PAD).ok()?;
1176    let mode = mode_from_id_low(id_low);
1177    if matches!(mode, PadMode::Unknown | PadMode::Disconnected) {
1178        return None;
1179    }
1180    let id_high = bus.exchange(0x00, false, Timing::PAD).ok()?;
1181    if id_high != 0x5a {
1182        return None;
1183    }
1184    let analog = mode.has_axes();
1185    // The two bytes the motors ride in, for a DualShock reporting analog
1186    // mode; every other pad (a neGcon included), and a pad parked in
1187    // configuration mode, gets zeros.
1188    let (small, large) = if mode == PadMode::Analog {
1189        rumble.bytes()
1190    } else {
1191        (0, 0)
1192    };
1193    let buttons_low = bus.exchange(small, false, Timing::PAD).ok()?;
1194    let buttons_high = bus.exchange(large, !analog, Timing::PAD).ok()?;
1195    let sticks = if analog {
1196        AnalogSticks {
1197            right_x: bus.exchange(0x00, false, Timing::PAD).ok()?,
1198            right_y: bus.exchange(0x00, false, Timing::PAD).ok()?,
1199            left_x: bus.exchange(0x00, false, Timing::PAD).ok()?,
1200            left_y: bus.exchange(0x00, true, Timing::PAD).ok()?,
1201        }
1202    } else {
1203        AnalogSticks::CENTERED
1204    };
1205    Some(RawPoll {
1206        id_low,
1207        id_high,
1208        buttons_low,
1209        buttons_high,
1210        sticks,
1211        mode,
1212        ack_seen: if analog { 0xff } else { 0x0f },
1213        exchanges: if analog { 9 } else { 5 },
1214    })
1215}
1216
1217/// Poll with fixed setup and inter-byte delays (no `/ACK` wait). Mirrors
1218/// [`poll_once_raw`]'s byte sequence but paces purely with time. Always inlined
1219/// so each caller above is specialised on its own timing.
1220#[inline(always)]
1221fn poll_once_timed<T: Transport>(
1222    bus: &mut T,
1223    socket: Port,
1224    setup_spins: u32,
1225    interbyte_spins: u32,
1226) -> RawPoll {
1227    bus.select(socket);
1228    // Setup time after asserting /CS, before the first clock -- the strict
1229    // original pad may need this where a fast clone does not.
1230    bus.delay(setup_spins);
1231    bus.drain_receive();
1232
1233    let mut i = 0u8;
1234    let _select = exchange_delayed(bus, 0x01, interbyte_spins);
1235    i += 1;
1236    let id_low = exchange_delayed(bus, 0x42, interbyte_spins);
1237    i += 1;
1238    let mut mode = mode_from_id_low(id_low);
1239    if !mode.is_connected() {
1240        bus.deselect();
1241        return RawPoll {
1242            exchanges: i,
1243            ..RawPoll::disconnected(id_low)
1244        };
1245    }
1246
1247    let analog = mode.has_axes();
1248    let id_high = exchange_delayed(bus, 0x00, interbyte_spins);
1249    i += 1;
1250    if id_high != 0x5a {
1251        mode = PadMode::Unknown;
1252    }
1253    let read_sticks = analog && mode != PadMode::Unknown;
1254    let b0 = exchange_delayed(bus, 0x00, interbyte_spins);
1255    i += 1;
1256    let b1 = exchange_delayed(bus, 0x00, interbyte_spins);
1257    i += 1;
1258
1259    let sticks = if read_sticks {
1260        let right_x = exchange_delayed(bus, 0x00, interbyte_spins);
1261        let right_y = exchange_delayed(bus, 0x00, interbyte_spins);
1262        let left_x = exchange_delayed(bus, 0x00, interbyte_spins);
1263        let left_y = exchange_delayed(bus, 0x00, interbyte_spins);
1264        i += 4;
1265        AnalogSticks {
1266            right_x,
1267            right_y,
1268            left_x,
1269            left_y,
1270        }
1271    } else {
1272        AnalogSticks::CENTERED
1273    };
1274
1275    bus.deselect();
1276
1277    RawPoll {
1278        id_low,
1279        id_high,
1280        buttons_low: b0,
1281        buttons_high: b1,
1282        sticks,
1283        mode,
1284        ack_seen: 0,
1285        exchanges: i,
1286    }
1287}
1288
1289/// Spins between the configuration commands of [`enable_analog`], a few
1290/// milliseconds each. Sony's libpad spaces configuration commands one per
1291/// video frame; issuing the three back to back left an SCPH-110 (PS one
1292/// DualShock) parked in configuration mode on a console, answering ID 0xF3
1293/// with buttons and sticks intact but never analog (controller-test capture,
1294/// 2026-08-16), while an SCPH-1200 took the same burst fine. Not yet
1295/// re-measured on silicon.
1296const CONFIG_COMMAND_GAP_SPINS: u32 = 8 * DEFAULT_SETUP_SPINS;
1297
1298/// Spins between the configuration commands of [`require_analog_on`]:
1299/// about one video frame, the spacing Sony's libpad uses, so the request
1300/// that a program must win (the SCPH-110 is the pad that needed spacing at
1301/// all) uses the reference pacing rather than the shorter, unmeasured one
1302/// above. A spin costs about 6.7 CPU cycles on silicon (the 2026-07-26
1303/// setup-delay sweep: 192 spins polled in 8587 cycles, 1536 in 17615), so
1304/// this is about 660k cycles, a little over one 60 Hz frame. Only boot-time
1305/// and redetect callers pay it; [`enable_analog_on`] keeps its short gap
1306/// because games call it from their frame loops.
1307const REQUIRE_ANALOG_GAP_SPINS: u32 = 96 * DEFAULT_SETUP_SPINS;
1308
1309/// Exit-config retries when a pad is still answering ID 0xF3 after the
1310/// analog request. Each costs one gap; a pad left in configuration mode
1311/// still reports buttons, but never analog, and ignores the Analog lock.
1312const CONFIG_EXIT_RETRIES: u32 = 3;
1313
1314/// The config-mode packet that maps the motors: the first mapping byte (`0x00`)
1315/// puts the small motor on the first byte after the poll command's two, the
1316/// second (`0x01`) the large motor on the next, and `0xFF` leaves a slot
1317/// unused. A DualShock forgets it when it loses power.
1318pub const MOTOR_MAP_PACKET: [u8; 8] = [0x4d, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xff];
1319
1320/// Put a DualShock's motors under the poll: enter configuration mode, map the
1321/// small motor to the first motor byte and the large motor to the second
1322/// ([`MOTOR_MAP_PACKET`]), and leave configuration mode, spaced a video frame
1323/// apart as [`require_analog_on`] spaces its commands. Returns whether the pad
1324/// took the mapping from configuration mode and then reports DualShock analog
1325/// mode, which is the only mode a poll sends motor bytes in; a digital pad, a
1326/// pad that refuses configuration mode, or one that drops out part way returns
1327/// `false` and is polled as before. The pad's analog or digital
1328/// mode is left as it was. Call it again after a pad is plugged in.
1329///
1330/// This blocks for a few frames; the interrupt engine does the same without
1331/// blocking (`console::enable_rumble`).
1332pub fn enable_rumble_on<T: Transport>(port: &mut T, socket: Port) -> bool {
1333    let (state, mapped) = request_rumble(port, socket, REQUIRE_ANALOG_GAP_SPINS);
1334    mapped && state.is_analog()
1335}
1336
1337/// Send the mapping sequence and return the state the pad settled on, and
1338/// whether the pad answered the mapping packet from configuration mode (ID
1339/// `0xF3`, magic `0x5A`): one that refused to enter it, or dropped out, did not
1340/// take the mapping.
1341fn request_rumble<T: Transport>(bus: &mut T, socket: Port, gap: u32) -> (PadState, bool) {
1342    transaction(
1343        bus,
1344        socket,
1345        [0x43, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00],
1346    );
1347    bus.delay(gap);
1348    let answer = transaction(bus, socket, MOTOR_MAP_PACKET);
1349    let mapped = answer[0] == 0xf3 && answer[1] == 0x5a;
1350    bus.delay(gap);
1351    transaction(
1352        bus,
1353        socket,
1354        [0x43, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
1355    );
1356    bus.delay(gap);
1357    let mut state = poll_state(bus, socket, true, Rumble::OFF);
1358    let mut retries = 0;
1359    while state.mode == PadMode::Config && retries < CONFIG_EXIT_RETRIES {
1360        transaction(
1361            bus,
1362            socket,
1363            [0x43, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
1364        );
1365        bus.delay(gap);
1366        state = poll_state(bus, socket, true, Rumble::OFF);
1367        retries += 1;
1368    }
1369    (state, mapped)
1370}
1371
1372fn enable_analog<T: Transport>(bus: &mut T, socket: Port) -> bool {
1373    request_analog(bus, socket, CONFIG_COMMAND_GAP_SPINS).is_analog()
1374}
1375
1376/// Send the analog-and-lock request, spacing the commands by `gap` spins,
1377/// and return the state the pad settled on. A pad still parked in
1378/// configuration mode (ID 0xF3, the SCPH-110 failure) is sent the exit
1379/// command again, a bounded number of times, before its state is reported.
1380fn request_analog<T: Transport>(bus: &mut T, socket: Port, gap: u32) -> PadState {
1381    // Enter config mode.
1382    transaction(
1383        bus,
1384        socket,
1385        [0x43, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00],
1386    );
1387    bus.delay(gap);
1388    // Request analog mode and lock it so the pad cannot toggle
1389    // back underneath analog-only game controls.
1390    transaction(
1391        bus,
1392        socket,
1393        [0x44, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00],
1394    );
1395    bus.delay(gap);
1396    // Exit config mode, restoring the requested analog mode.
1397    transaction(
1398        bus,
1399        socket,
1400        [0x43, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
1401    );
1402    bus.delay(gap);
1403    let mut state = poll_state(bus, socket, true, Rumble::OFF);
1404    let mut retries = 0;
1405    while state.mode == PadMode::Config && retries < CONFIG_EXIT_RETRIES {
1406        // The exit did not take: leave the pad in a playable mode rather
1407        // than parked in configuration, then re-read what it settled on.
1408        transaction(
1409            bus,
1410            socket,
1411            [0x43, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
1412        );
1413        bus.delay(gap);
1414        state = poll_state(bus, socket, true, Rumble::OFF);
1415        retries += 1;
1416    }
1417    state
1418}
1419
1420#[inline]
1421fn mode_from_id_low(id_low: u8) -> PadMode {
1422    match id_low {
1423        0x41 => PadMode::Digital,
1424        0x23 => PadMode::Negcon,
1425        0x73 => PadMode::Analog,
1426        0xf3 => PadMode::Config,
1427        0xff => PadMode::Disconnected,
1428        _ => PadMode::Unknown,
1429    }
1430}
1431
1432#[inline]
1433fn decode_buttons(b0: u8, b1: u8) -> ButtonState {
1434    // Wire bytes are active-low; invert to match our active-high
1435    // ButtonState convention.
1436    ButtonState::from_bits(!((b0 as u16) | ((b1 as u16) << 8)))
1437}
1438
1439/// CTRL value held while a port is selected: JOYN asserted, TX enabled, and
1440/// normal receive supplied implicitly by the active `/CS`,
1441/// (only when `ack_irq`) the DSR (`/ACK`) interrupt armed so STAT bit 9 latches
1442/// each pulse. The default no-wait poll leaves the DSR IRQ off -- enabling it
1443/// turned out to disturb real-hardware transfers (the official SCPH-1200 stopped
1444/// answering, the clone's bytes corrupted), so it is reserved for the opt-in
1445/// ack-wait diagnostic only.
1446#[inline]
1447const fn active_ctrl(socket: Port, ack_irq: bool) -> u16 {
1448    sio0::selected_ctrl(socket.is_two(), ack_irq)
1449}
1450
1451/// Run a fixed eight-byte DualShock command after the port-level controller
1452/// select byte, using the default no-wait timing (matching the reverted poll
1453/// path).
1454///
1455/// Never inlined: `request_analog` runs it four times, and four copies of the byte loop made
1456/// `enable_analog_on` the largest one-shot function of a game (4.3 KB, against 1.6 KB with one shared copy).
1457#[inline(never)]
1458fn transaction<T: Transport>(bus: &mut T, socket: Port, bytes: [u8; 8]) -> [u8; 8] {
1459    bus.select(socket);
1460    bus.delay(DEFAULT_SETUP_SPINS);
1461    let mut ack = 0u16;
1462    let mut idx = 0u8;
1463    let _select = ex(
1464        bus,
1465        socket,
1466        Pacing::NoAckWait,
1467        0x01,
1468        false,
1469        &mut ack,
1470        &mut idx,
1471    );
1472    let mut out = [0u8; 8];
1473    let mut i = 0;
1474    while i < bytes.len() {
1475        let is_last = i == bytes.len() - 1;
1476        out[i] = ex(
1477            bus,
1478            socket,
1479            Pacing::NoAckWait,
1480            bytes[i],
1481            is_last,
1482            &mut ack,
1483            &mut idx,
1484        );
1485        i += 1;
1486    }
1487    bus.deselect();
1488    out
1489}
1490
1491/// Clock one byte across the serial link without waiting for `/ACK`: wait for
1492/// TX-ready, write the byte, wait for RX to fill, read it. This is the legacy
1493/// timing -- correct for the final byte of a packet (which is never
1494/// acknowledged) and for the [`Pacing::NoAckWait`] diagnostic path.
1495///
1496/// The STAT register layout (from PSX-SPX):
1497/// - bit 0: TX-ready-1 (FIFO can accept a byte)
1498/// - bit 1: RX FIFO not empty
1499/// - bit 7: `/ACK` (DSR) live input level
1500/// - bit 9: latched DSR/ACK interrupt
1501#[inline]
1502fn exchange_nowait<T: Transport>(bus: &mut T, tx: u8) -> u8 {
1503    if !bus.wait_status_set(STAT_TX_READY, EXCHANGE_WAIT_SPINS) {
1504        return 0xff;
1505    }
1506    bus.transmit(tx);
1507    if !bus.wait_status_set(STAT_RX_NOT_EMPTY, EXCHANGE_WAIT_SPINS) {
1508        return 0xff;
1509    }
1510    bus.receive()
1511}
1512
1513/// One no-wait byte exchange followed by a fixed inter-byte delay, giving a
1514/// strict pad time to be ready for the next byte without any `/ACK`/CTRL games.
1515#[inline]
1516fn exchange_delayed<T: Transport>(bus: &mut T, tx: u8, interbyte_spins: u32) -> u8 {
1517    let rx = exchange_nowait(bus, tx);
1518    bus.delay(interbyte_spins);
1519    rx
1520}
1521
1522/// Clock one byte, then wait for the device's `/ACK` (DSR) pulse before
1523/// returning so the caller does not clock the next byte until the controller is
1524/// ready. Returns `(rx_byte, ack_observed)`.
1525///
1526/// The wait is non-fatal: on timeout we still return the received byte (the
1527/// byte shift itself already completed), so a device that never `/ACK`s degrades
1528/// to legacy timing rather than dropping the poll entirely.
1529#[inline]
1530fn exchange_ack<T: Transport>(bus: &mut T, socket: Port, tx: u8) -> (u8, bool) {
1531    if !bus.wait_status_set(STAT_TX_READY, EXCHANGE_WAIT_SPINS) {
1532        return (0xff, false);
1533    }
1534    bus.transmit(tx);
1535    if !bus.wait_status_set(STAT_RX_NOT_EMPTY, EXCHANGE_WAIT_SPINS) {
1536        return (0xff, false);
1537    }
1538    let rx = bus.receive();
1539    // Wait for the latched `/ACK` interrupt (STAT bit 9). The latch cannot be
1540    // missed, unlike the brief live level; the controller IRQ is masked in
1541    // `I_MASK`, so this never reaches the CPU.
1542    let acked = bus.wait_status_set(STAT_IRQ, ACK_WAIT_SPINS);
1543    if acked {
1544        // SIO0 STAT.9 is not edge-triggered: it can only be cleared once the
1545        // live `/ACK` line has released (STAT.7 low). Wait for that, then
1546        // pulse CTRL.ACK while keeping JOYN asserted so the device stays
1547        // selected for the next byte.
1548        let _ = bus.wait_status_clear(STAT_DSR_LEVEL, ACK_WAIT_SPINS);
1549        bus.set_control(active_ctrl(socket, true) | CTRL_ACK);
1550    }
1551    (rx, acked)
1552}
1553
1554#[cfg(test)]
1555mod tests {
1556
1557    #[test]
1558    fn symmetric_aim_and_group_edges_preserve_axis_policy() {
1559        for v in -128..=128 {
1560            assert_eq!(aim_curve_symmetric(v), -aim_curve_symmetric(-v));
1561        }
1562        assert_eq!(aim_curve_symmetric(128), 128);
1563        assert_eq!(aim_curve(128), 125);
1564        let a = ButtonState::from_bits(1);
1565        let b = ButtonState::from_bits(2);
1566        assert!(a.pressed_since(ButtonState::NONE, 3));
1567        assert!(!a.pressed_since(b, 3));
1568        assert!(a.pressed_since(b, 1));
1569    }
1570
1571    #[test]
1572    fn a_radial_deadzone_is_a_circle_not_a_square() {
1573        // The whole reason this exists. A per-axis threshold of 24, which is
1574        // what NitroXide used, passes (20, 20) because neither axis clears it
1575        // on its own -- so a gentle diagonal push reads as nothing, and the
1576        // moment one axis does clear it the input snaps to a cardinal. Radially
1577        // (20, 20) is 28.3 counts out and is real input.
1578        let dz = Deadzone::new(24);
1579        assert!(dz.is_outside(20, 20), "diagonal push must count as input");
1580        assert!(
1581            !dz.is_outside(20, 0),
1582            "same magnitude per axis is still drift"
1583        );
1584        assert!(!dz.is_outside(0, 0));
1585        assert!(dz.is_outside(25, 0));
1586    }
1587
1588    #[test]
1589    fn a_negative_deadzone_radius_is_no_deadzone_not_a_division_by_zero() {
1590        // `scaled(0, 0)` passed the `magnitude <= inner` test with inner = -1
1591        // and divided by a zero magnitude.
1592        for radius in [-1, -24, i16::MIN] {
1593            let dz = Deadzone::new(radius);
1594            assert_eq!(dz.radius(), 0);
1595            assert_eq!(dz, Deadzone::new(0));
1596            assert_eq!(dz.scaled(0, 0), None);
1597            assert_eq!(dz.scaled_axis(0), None);
1598            assert!(!dz.is_outside(0, 0));
1599            // A real deflection behaves as it does with a radius of zero.
1600            assert_eq!(dz.scaled(60, 0), Deadzone::new(0).scaled(60, 0));
1601            assert!(dz.is_outside(1, 0));
1602        }
1603    }
1604
1605    #[test]
1606    fn the_one_axis_form_ignores_the_other_axis() {
1607        // NitroXide's steering: Y is not read, so it must not gate X.
1608        let dz = Deadzone::new(24);
1609        assert!(dz.is_outside_axis(30));
1610        assert!(!dz.is_outside_axis(20));
1611        // Rescaled onto full span like the two-axis form, not merely offset:
1612        // (30 - 24) of the 103 counts left maps to 7 of 127.
1613        assert_eq!(dz.scaled_axis(30), Some(7), "starts from zero, not 30");
1614        assert_eq!(dz.scaled_axis(-30), Some(-7), "sign survives");
1615        assert_eq!(dz.scaled_axis(127), Some(STICK_FULL), "full stays full");
1616        assert_eq!(dz.scaled_axis(10), None);
1617    }
1618
1619    #[test]
1620    fn the_gate_hands_back_the_reading_unchanged() {
1621        let dz = Deadzone::new(16);
1622        assert_eq!(dz.gate(4, 4), None);
1623        assert_eq!(dz.gate(100, -40), Some((100, -40)));
1624    }
1625
1626    #[test]
1627    fn scaling_starts_real_input_from_zero_instead_of_the_boundary() {
1628        // Ungated, a reading one count outside a radius of 30 arrives at
1629        // magnitude 31: a lurch. Scaled, it starts near zero and keeps its
1630        // direction.
1631        let dz = Deadzone::new(30);
1632        let (x, y) = dz.scaled(31, 0).expect("just outside is real input");
1633        assert!(x < 5, "expected a small first step, got {x}");
1634        assert_eq!(dz.scaled(127, 0), Some((STICK_FULL, 0)), "full stays full");
1635        assert_eq!(y, 0, "direction must survive the rescale");
1636        assert_eq!(dz.scaled(10, 10), None);
1637    }
1638
1639    #[test]
1640    fn a_full_diagonal_does_not_exceed_full_scale() {
1641        // A diagonal is 179 counts long, not 127. Remapping that onto full
1642        // scale without a clamp hands the game 138 on each axis and it has no
1643        // reason to expect anything over 127.
1644        let dz = Deadzone::new(30);
1645        let (x, y) = dz.scaled(127, 127).expect("full deflection is input");
1646        assert!(x <= STICK_FULL && y <= STICK_FULL, "got ({x}, {y})");
1647        assert_eq!(x, y, "a diagonal must stay a diagonal");
1648    }
1649
1650    #[test]
1651    fn an_outer_zone_lets_a_worn_stick_reach_full_scale() {
1652        // A stick that only manages 100 counts never gives full input without
1653        // this, which is the tip Sutphin gives for anything where magnitude
1654        // matters.
1655        let worn = Deadzone::new(20).with_outer(100);
1656        assert_eq!(worn.scaled(100, 0), Some((STICK_FULL, 0)));
1657        // And past the outer edge it saturates rather than overshooting.
1658        assert_eq!(worn.scaled(120, 0), Some((STICK_FULL, 0)));
1659    }
1660
1661    #[test]
1662    fn aim_curve_is_gentle_at_center_and_near_full_at_the_edge() {
1663        assert_eq!(aim_curve(0), 0);
1664        assert_eq!(aim_curve(16), 7);
1665        assert_eq!(aim_curve(-16), -7);
1666        assert_eq!(aim_curve(127), 125);
1667        assert_eq!(aim_curve(-128), -128);
1668        assert!(aim_curve(64) < 64);
1669        assert_eq!(aim_curve(-64), -aim_curve(64));
1670    }
1671
1672    use super::*;
1673
1674    #[test]
1675    fn mode_ids_match_dualshock_wire_values() {
1676        assert_eq!(mode_from_id_low(0x41), PadMode::Digital);
1677        assert_eq!(mode_from_id_low(0x73), PadMode::Analog);
1678        assert_eq!(mode_from_id_low(0xf3), PadMode::Config);
1679        assert_eq!(mode_from_id_low(0xff), PadMode::Disconnected);
1680        assert_eq!(mode_from_id_low(0x12), PadMode::Unknown);
1681    }
1682
1683    #[test]
1684    fn decode_buttons_converts_active_low_to_active_high() {
1685        let state = decode_buttons(0xef, 0xbf);
1686        assert!(state.is_held(button::UP));
1687        assert!(state.is_held(button::CROSS));
1688        assert!(!state.is_held(button::DOWN));
1689    }
1690
1691    #[test]
1692    fn centred_stick_helpers_return_zero() {
1693        assert_eq!(AnalogSticks::CENTERED.left_centered(), (0, 0));
1694        assert_eq!(AnalogSticks::CENTERED.right_centered(), (0, 0));
1695    }
1696
1697    #[test]
1698    fn raw_poll_to_state_inverts_buttons() {
1699        let raw = RawPoll {
1700            id_low: 0x41,
1701            id_high: 0x5a,
1702            buttons_low: 0xef,  // UP pressed (active-low)
1703            buttons_high: 0xbf, // CROSS pressed (active-low)
1704            sticks: AnalogSticks::CENTERED,
1705            mode: PadMode::Digital,
1706            ack_seen: 0,
1707            exchanges: 5,
1708        };
1709        let state = raw.to_state();
1710        assert!(state.buttons.is_held(button::UP));
1711        assert!(state.buttons.is_held(button::CROSS));
1712        assert_eq!(state.mode, PadMode::Digital);
1713        assert_eq!(state.id_low, 0x41);
1714    }
1715
1716    #[test]
1717    fn ack_complete_requires_every_non_final_byte_acked() {
1718        // Digital poll: 5 exchanges (select, cmd, id_hi, b0, b1). The first four
1719        // must ACK; the final b1 does not.
1720        let mut raw = RawPoll {
1721            id_low: 0x41,
1722            id_high: 0x5a,
1723            buttons_low: 0xff,
1724            buttons_high: 0xff,
1725            sticks: AnalogSticks::CENTERED,
1726            mode: PadMode::Digital,
1727            ack_seen: 0b0_1111, // exchanges 0..=3 acked
1728            exchanges: 5,
1729        };
1730        assert!(raw.is_fully_acknowledged());
1731
1732        // Drop one ACK in the middle -> incomplete handshake.
1733        raw.ack_seen = 0b0_1011;
1734        assert!(!raw.is_fully_acknowledged());
1735
1736        // A no-ack poll (legacy / slow original under NoAckWait) is incomplete.
1737        raw.ack_seen = 0;
1738        assert!(!raw.is_fully_acknowledged());
1739    }
1740
1741    #[test]
1742    fn pacing_round_trips() {
1743        assert_ne!(Pacing::NoAckWait, Pacing::AckWait);
1744    }
1745
1746    #[test]
1747    fn action_map_unifies_primary_secondary_and_edges() {
1748        let map = ActionMap::new([
1749            ActionBinding::new(button::CROSS, button::CIRCLE),
1750            ActionBinding::new(button::START, 0),
1751        ]);
1752        let previous = PadState {
1753            buttons: ButtonState::from_bits(button::CROSS),
1754            mode: PadMode::Digital,
1755            sticks: AnalogSticks::CENTERED,
1756            id_low: 0x41,
1757            negcon: None,
1758        };
1759        let current = PadState {
1760            buttons: ButtonState::from_bits(button::CIRCLE | button::START),
1761            ..previous
1762        };
1763        let input = map.input(current, previous);
1764        assert!(input.is_held(0));
1765        assert!(!input.just_pressed(0), "the logical action stayed held");
1766        assert!(input.just_pressed(1));
1767        assert!(!input.just_released(0));
1768        assert!(!input.is_held(99));
1769    }
1770
1771    fn state(mode: PadMode, buttons: u16) -> PadState {
1772        PadState {
1773            buttons: ButtonState::from_bits(buttons),
1774            mode,
1775            sticks: AnalogSticks::CENTERED,
1776            id_low: match mode {
1777                PadMode::Digital => 0x41,
1778                PadMode::Analog => 0x73,
1779                PadMode::Config => 0xf3,
1780                _ => 0xff,
1781            },
1782            negcon: None,
1783        }
1784    }
1785
1786    #[test]
1787    fn analog_requirement_classifies_every_mode() {
1788        use AnalogRequirement as R;
1789        assert_eq!(R::from_mode(PadMode::Analog), R::Analog);
1790        assert_eq!(R::from_mode(PadMode::Digital), R::DigitalOnly);
1791        assert_eq!(R::from_mode(PadMode::Config), R::DigitalOnly);
1792        assert_eq!(R::from_mode(PadMode::Disconnected), R::Absent);
1793        assert_eq!(R::from_mode(PadMode::Unknown), R::Absent);
1794    }
1795
1796    #[test]
1797    fn analog_and_digital_frames_decode_the_same_buttons() {
1798        let digital = RawPoll {
1799            id_low: 0x41,
1800            id_high: 0x5a,
1801            buttons_low: 0xfe,  // SELECT (active-low)
1802            buttons_high: 0xbf, // CROSS
1803            sticks: AnalogSticks::CENTERED,
1804            mode: PadMode::Digital,
1805            ack_seen: 0x0f,
1806            exchanges: 5,
1807        };
1808        let sticks = AnalogSticks {
1809            right_x: 0x80,
1810            right_y: 0x80,
1811            left_x: 0x00,
1812            left_y: 0xff,
1813        };
1814        let analog = RawPoll {
1815            id_low: 0x73,
1816            sticks,
1817            mode: PadMode::Analog,
1818            ack_seen: 0xff,
1819            exchanges: 9,
1820            ..digital
1821        };
1822        let (d, a) = (digital.to_state(), analog.to_state());
1823        assert_eq!(d.buttons, a.buttons);
1824        assert_eq!(a.buttons.bits(), button::SELECT | button::CROSS);
1825        assert!(a.is_analog() && !d.is_analog());
1826        assert_eq!(a.sticks, sticks);
1827        assert_eq!(d.sticks, AnalogSticks::CENTERED);
1828    }
1829
1830    #[test]
1831    fn a_packet_slipped_by_one_byte_reads_as_select_and_both_directions() {
1832        // Why every packet must be complete and paced: an analog packet that
1833        // slips one byte delivers the ID's 0x5A as the first button byte.
1834        // That decodes as Select, R3, Left and Right held together, the
1835        // phantom-Select pattern seen on a console in analog mode.
1836        let slipped = decode_buttons(0x5a, 0xff);
1837        assert_eq!(
1838            slipped.bits(),
1839            button::SELECT | button::R3 | button::LEFT | button::RIGHT
1840        );
1841    }
1842
1843    #[test]
1844    fn reader_keeps_the_last_clean_state_across_a_garbled_poll() {
1845        let mut reader = PadReader::port1();
1846        let mut tracker = PadTracker::new();
1847        let held = state(PadMode::Analog, button::SELECT);
1848        tracker.update(reader.accept(held).buttons.bits());
1849        assert!(tracker.just_pressed(button::SELECT));
1850        // The failed packet must neither release nor re-press Select.
1851        let garbled = PadState {
1852            mode: PadMode::Unknown,
1853            ..PadState::NONE
1854        };
1855        let seen = reader.accept(garbled);
1856        assert_eq!(seen, held);
1857        tracker.update(seen.buttons.bits());
1858        assert!(!tracker.just_released(button::SELECT));
1859        tracker.update(reader.accept(held).buttons.bits());
1860        assert!(!tracker.just_pressed(button::SELECT), "no second press");
1861    }
1862
1863    #[test]
1864    fn reader_accepts_every_clean_mode_including_an_empty_port() {
1865        let mut reader = PadReader::port1();
1866        assert_eq!(reader.last(), PadState::NONE);
1867        for clean in [
1868            state(PadMode::Digital, button::CROSS),
1869            state(PadMode::Analog, button::START),
1870            state(PadMode::Config, 0),
1871            PadState::NONE,
1872        ] {
1873            assert_eq!(reader.accept(clean), clean);
1874        }
1875        assert_eq!(reader.last(), PadState::NONE, "unplugging releases");
1876    }
1877}