use crate::bus::SpiDevice;
use std::any::Any;
pub const RAW_MAX: u16 = 0x0fff;
pub const COMMAND_X: u8 = 0xd0;
pub const COMMAND_Y: u8 = 0x90;
pub const COMMAND_PRESSURE: u8 = 0xb0;
pub const COMMAND_AUX: u8 = 0xc0;
pub struct Xpt2046 {
x: u16,
y: u16,
down: bool,
selected: bool,
}
impl Xpt2046 {
pub fn new() -> Self {
Self {
x: 0,
y: 0,
down: false,
selected: false,
}
}
pub fn touch(&mut self, x: u16, y: u16, down: bool) {
self.x = x.min(RAW_MAX);
self.y = y.min(RAW_MAX);
self.down = down;
}
pub fn touched(&self) -> bool {
self.down
}
pub fn position(&self) -> (u16, u16) {
(self.x, self.y)
}
fn channel(&self, command: u8) -> u16 {
match command & 0xf8 {
x if x == COMMAND_X => self.x,
y if y == COMMAND_Y => self.y,
_ => 0,
}
}
}
impl Default for Xpt2046 {
fn default() -> Self {
Self::new()
}
}
impl SpiDevice for Xpt2046 {
fn select(&mut self, selected: bool) {
self.selected = selected;
}
fn transfer(&mut self, tx: &[u8], rx_len: usize) -> Vec<u8> {
if !self.selected {
return vec![0xff; rx_len];
}
let mut out = vec![0u8; rx_len];
let Some(&command) = tx.first() else {
return out;
};
let word = self.channel(command) << 4;
for (index, slot) in out.iter_mut().enumerate().skip(1) {
*slot = match index {
1 => (word >> 8) as u8,
2 => word as u8,
_ => 0,
};
}
out
}
fn as_any(&self) -> Option<&dyn Any> {
Some(self)
}
fn as_any_mut(&mut self) -> Option<&mut dyn Any> {
Some(self)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn transaction(controller: &mut Xpt2046, command: u8) -> u16 {
controller.select(true);
let rx = controller.transfer(&[command, 0x00, 0x00], 3);
controller.select(false);
((u16::from(rx[1]) << 8) | u16::from(rx[2])) >> 4
}
#[test]
fn the_x_and_y_channels_report_the_contact_point() {
let mut controller = Xpt2046::new();
controller.touch(1200, 800, true);
assert_eq!(transaction(&mut controller, COMMAND_X), 1200);
assert_eq!(transaction(&mut controller, COMMAND_Y), 800);
}
#[test]
fn the_pressure_and_aux_channels_read_zero() {
let mut controller = Xpt2046::new();
controller.touch(4000, 3000, true);
assert_eq!(transaction(&mut controller, COMMAND_PRESSURE), 0);
assert_eq!(transaction(&mut controller, COMMAND_AUX), 0);
}
#[test]
fn touch_clamps_to_the_twelve_bit_range() {
let mut controller = Xpt2046::new();
controller.touch(50_000, 9_000, true);
assert_eq!(controller.position(), (RAW_MAX, RAW_MAX));
assert_eq!(transaction(&mut controller, COMMAND_X), RAW_MAX);
}
#[test]
fn an_unselected_device_floats_its_output() {
let mut controller = Xpt2046::new();
assert_eq!(controller.transfer(&[COMMAND_X, 0, 0], 3), vec![0xff; 3]);
}
}