aboutsummaryrefslogtreecommitdiffstats
path: root/src/cirque.rs
blob: 99de2879730bc51e6a9618a1e941fa3258580be2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
/// Support for the Cirque Pinnacle 1CA027.
use core::cmp::{max, min};
use embedded_hal::{
    digital::v2::{InputPin, OutputPin},
    spi,
};
use nb;
use stm32f1xx_hal::rcc::Clocks;

/// Default I²C address.
#[allow(unused)]
const I2C_ADDR: u8 = 0x2a;

// the maximum reportable units
const MAX_X: u16 = 2048;
const MAX_Y: u16 = 1536;

// the lowest reachable units
const CLAMP_X_MIN: u16 = 127;
const CLAMP_Y_MIN: u16 = 63;

// the highest reachable units
const CLAMP_X_MAX: u16 = 1919;
const CLAMP_Y_MAX: u16 = 1471;

// masks for register access protocol
const WRITE_MASK: u8 = 0x80;
const READ_MASK: u8 = 0xa0;

fn clamp<T: Ord>(val: T, low: T, high: T) -> T {
    min(max(low, val), high)
}

/// Register Access Protocol addresses.
#[allow(unused)]
#[repr(u8)]
enum RAPAddress {
    FirmwareID = 0x00,
    FirmwareVersion = 0x01,
    Status1 = 0x02,
    SysConfig1 = 0x03,
    FeedConfig1 = 0x04,
    FeedConfig2 = 0x05,
    FeedConfig3 = 0x06,
    CalConfig1 = 0x07,
    PS2AuxControl = 0x08,
    SampleRate = 0x09,
    ZIdle = 0x0a,
    ZScaler = 0x0b,
    SleepInterval = 0x0c,
    SleepTimer = 0x0d,
    DynamicEMIAdjustThreshold = 0x0e,
    Reserved1 = 0x0f,
    Reserved2 = 0x10,
    Reserved3 = 0x11,
    PacketByte0 = 0x12,
    PacketByte1 = 0x13,
    PacketByte2 = 0x14,
    PacketByte3 = 0x15,
    PacketByte4 = 0x16,
    PacketByte5 = 0x17,
    PortAGPIOControl = 0x18,
    PortAGPIOData = 0x19,
    PortBGPIOControlAndData = 0x1a,
    ExtendedRegisterAccessValue = 0x1b,
    ExtendedRegisterAccessHigh = 0x1c,
    ExtendedRegisterAccessLow = 0x1d,
    ExtendedRegisterAccessControl = 0x1e,
    ProductID = 0x1f,
}

// TODO: figure out how to use the
// embedded_hal::blocking::spi::{Transfer, Write} traits instead of
// doing it ourselves.
trait SPIWriter<Word>: spi::FullDuplex<Word> {
    fn write(&mut self, buf: &[Word]) -> nb::Result<(), Self::Error>;
    fn transfer(&mut self, buf: &mut [Word]) -> nb::Result<(), Self::Error>;
}

impl<T, Word> SPIWriter<Word> for T
where
    T: spi::FullDuplex<Word>,
    Word: Copy,
{
    fn write(&mut self, buf: &[Word]) -> nb::Result<(), Self::Error> {
        for i in buf {
            nb::block!(self.send(*i))?;
            _ = nb::block!(self.read())?;
        }
        Ok(())
    }

    fn transfer(&mut self, buf: &mut [Word]) -> nb::Result<(), Self::Error> {
        for i in buf.iter_mut() {
            nb::block!(self.send(*i))?;
            *i = nb::block!(self.read())?;
        }
        Ok(())
    }
}

#[allow(unused)]
#[derive(Debug)]
pub struct TouchData {
    x: u16,
    y: u16,
    z: u8,
    buttons: u8,
    is_pressed: bool,
}

impl TouchData {
    pub fn clamp(&mut self) {
        self.x = clamp(self.x, CLAMP_X_MIN, CLAMP_X_MAX);
        self.y = clamp(self.y, CLAMP_Y_MIN, CLAMP_Y_MAX);
    }

    pub fn scale_to(&mut self, width: u16, height: u16) {
        let width_factor = width / (CLAMP_X_MAX - CLAMP_X_MIN);
        let height_factor = height / (CLAMP_Y_MAX - CLAMP_Y_MIN);

        self.clamp();
        self.x -= CLAMP_X_MIN;
        self.y -= CLAMP_Y_MIN;

        self.x *= width_factor;
        self.y *= height_factor;
    }
}

pub struct Cirque<C, D>
where
    C: OutputPin,
    D: InputPin,
{
    cs_pin: C,
    dr_pin: D,
    sysclk_speed: u32,
}

impl<C, D> Cirque<C, D>
where
    C: OutputPin,
    D: InputPin,
{
    pub fn new<S>(cs_pin: C, dr_pin: D, spi: &mut S, clocks: Clocks) -> nb::Result<Self, S::Error>
    where
        S: spi::FullDuplex<u8>,
    {
        let sysclk_speed = clocks.sysclk().raw();
        let mut res = Self {
            cs_pin,
            dr_pin,
            sysclk_speed,
        };
        res.init(spi)?;
        Ok(res)
    }

    fn init<S>(&mut self, spi: &mut S) -> nb::Result<(), S::Error>
    where
        S: spi::FullDuplex<u8>,
    {
        self.cs_pin.set_high().ok();
        self.clear_flags(spi)?;

        // SysConfig
        self.wr(spi, 0x03, 0x00)?;
        // FeedConfig2
        self.wr(spi, 0x05, 0x1f)?;
        // FeedConfig1
        self.wr(spi, 0x04, 0x03)?;
        // ZIdleCount
        self.wr(spi, 0x0a, 0x05)?;

        Ok(())
    }

    fn clear_flags<S>(&mut self, spi: &mut S) -> nb::Result<(), S::Error>
    where
        S: spi::FullDuplex<u8>,
    {
        self.wr(spi, 0x02, 0x00)?;

        cortex_m::asm::delay(50 * self.sysclk_speed / 1_000_000);

        Ok(())
    }

    pub fn poll<S>(&mut self, spi: &mut S) -> nb::Result<TouchData, S::Error>
    where
        S: spi::FullDuplex<u8>,
    {
        if self.dr_pin.is_high().unwrap_or(false) {
            self.read_coords(spi)
        } else {
            Err(nb::Error::WouldBlock)
        }
    }

    fn read_coords<S>(&mut self, spi: &mut S) -> nb::Result<TouchData, S::Error>
    where
        S: spi::FullDuplex<u8>,
    {
        let mut buf: [u8; 6] = [0xfc; 6];
        self.rd(spi, 0x12, &mut buf)?;
        self.clear_flags(spi)?;

        let x = buf[2] as u16 | ((buf[4] as u16 & 0x0f) << 8);
        let y = buf[3] as u16 | ((buf[4] as u16 & 0xf0) << 4);
        let z = buf[5] & 0x3f;
        let buttons = buf[0] & 0x3f;
        let is_pressed = x != 0;

        assert!(x < MAX_X);
        assert!(y < MAX_Y);

        Ok(TouchData {
            x,
            y,
            z,
            buttons,
            is_pressed,
        })
    }

    fn rd<S>(&mut self, spi: &mut S, cmd: u8, buf: &mut [u8]) -> nb::Result<(), S::Error>
    where
        S: spi::FullDuplex<u8>,
    {
        let cmd = cmd | READ_MASK;
        self.cs_pin.set_low().ok();
        let res = spi
            .write(&[cmd, 0xfc, 0xfc])
            .and_then(|_| spi.transfer(buf));
        self.cs_pin.set_high().ok();

        res
    }

    fn wr<S>(&mut self, spi: &mut S, addr: u8, data: u8) -> nb::Result<(), S::Error>
    where
        S: spi::FullDuplex<u8>,
    {
        let cmd = addr | WRITE_MASK;
        self.cs_pin.set_low().ok();
        let res = spi.write(&[cmd, data]);
        self.cs_pin.set_high().ok();

        res
    }
}