aboutsummaryrefslogtreecommitdiffstats
path: root/src/cirque.rs
blob: b4a2255bb20f887061575786db3c71b22353fbcf (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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/// Support for the Cirque Pinnacle 1CA027.
use core::cmp::{max, min};
use embedded_hal::{digital::v2::OutputPin, spi};
use nb;

/// 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 {
    pub x: u16,
    pub y: u16,
    pub z: u8,
    pub buttons: u8,
    pub 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: f32 = f32::from(width) / f32::from(CLAMP_X_MAX - CLAMP_X_MIN);
        let height_factor: f32 = f32::from(height) / f32::from(CLAMP_Y_MAX - CLAMP_Y_MIN);

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

        assert!(!width_factor.is_nan() && width_factor.is_finite());
        assert!(!height_factor.is_nan() && height_factor.is_finite());
        unsafe {
            self.x = (f32::from(self.x) * width_factor).to_int_unchecked();
            self.y = (f32::from(self.y) * height_factor).to_int_unchecked();
        }
    }
}

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

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

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

        // let mut b = [0xfbu8];
        // nb::block!(self.rd(spi, RAPAddress::SysConfig1, &mut b))?;
        // logln!("b-reset: {:?}", b);

        // self.reset(spi)?;

        // let mut b = [0xfbu8];
        // nb::block!(self.rd(spi, RAPAddress::SysConfig1, &mut b))?;
        // logln!("a-reset: {:?}", b);

        // nb::block!(self.wr(spi, RAPAddress::SysConfig1, 0x00))?;
        nb::block!(self.clear_flags(spi))?;

        // let mut b = [0xfbu8];
        // nb::block!(self.rd(spi, RAPAddress::SysConfig1, &mut b))?;
        // logln!("a-reset: {:?}", b);

        nb::block!(self.wr(spi, RAPAddress::FeedConfig2, 0x1e))?;
        nb::block!(self.wr(spi, RAPAddress::FeedConfig1, 0x03))?;
        nb::block!(self.wr(spi, RAPAddress::ZIdle, 0x05))?;

        Ok(())
    }

    // fn reset<S>(&mut self, spi: &mut S) -> Result<(), S::Error>
    // where
    //     S: spi::FullDuplex<u8>
    // {
    //     nb::block!(self.wr(spi, RAPAddress::SysConfig1, 0x01))?;
    //     while nb::block!(self.read_flags(spi))? & 0x8 != 0x8 {}
    //     nb::block!(self.clear_flags(spi))?;
    //     Ok(())
    // }

    // clears the hardware data ready flag
    fn clear_flags<S>(&mut self, spi: &mut S) -> nb::Result<(), S::Error>
    where
        S: spi::FullDuplex<u8>,
    {
        self.wr(spi, RAPAddress::Status1, 0x00)?;

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

        Ok(())
    }

    fn read_flags<S>(&mut self, spi: &mut S) -> nb::Result<u8, S::Error>
    where
        S: spi::FullDuplex<u8>,
    {
        let mut flags: [u8; 1] = [0xfb; 1];
        self.rd(spi, RAPAddress::Status1, &mut flags)?;
        Ok(flags[0])
    }

    pub fn poll<S>(&mut self, spi: &mut S) -> nb::Result<TouchData, S::Error>
    where
        S: spi::FullDuplex<u8>,
    {
        if self.read_flags(spi)? & 0x4 == 0x4 {
            Ok(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, RAPAddress::PacketByte0, &mut buf)?;
        self.clear_flags(spi)?;

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

        // assert!(x < MAX_X);
        // assert!(y < MAX_Y);
        if x >= MAX_X || y >= MAX_Y {
            x = 0;
            y = 0;
            z = 0;
        }
        let is_pressed = z != 0;

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

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

        res
    }

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

        res
    }
}