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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
#![cfg_attr(not(test), no_std)]

#[cfg(test)]
mod mock_peripherals;
mod types;

use embedded_hal::spi::{ErrorType, Operation, SpiDevice};
use types::{Axes, ControlBit};

#[derive(Debug, PartialEq)]
/// Struct representing a touch point on the touch screen.
pub struct TouchPoint {
    /// The x-coordinate of the touch point, ranging from 0 to 4096.
    pub x: u16,
    /// The y-coordinate of the touch point, ranging from 0 to 4096.
    pub y: u16,
    /// The pressure value of the touch point, ranging from 0.0 (max pressure) to the set touch threshold.
    pub z: f32,
}
/// Driver for the TSC2046 4-wire touch screen controller.
pub struct Tsc2046<SPI> {
    /// The SPI interface used to communicate with the TSC2046 chip.
    spi: SPI,
    /// Whether the interrupt pin is enabled or not.
    irq_on: bool,
    /// The minimum pressure value required to register a touch event.
    touch_threshold: f32,
}
impl<SPI> Tsc2046<SPI>
where
    SPI: SpiDevice,
{
    /// Creates a new instance of the `Tsc2046` driver.
    ///
    /// # Arguments
    ///
    /// * `spi` - The SPI interface used to communicate with the TSC2046 chip.
    /// * `irq_on` - Whether to enable the interrupt pin or not.
    /// * `touch_threshold` - The minimum pressure value required to register a touch event.
    ///
    /// # Returns
    ///
    /// A `Result` containing the `Tsc2046` instance or an error if the register update fails.
    pub fn new(
        spi: SPI,
        irq_on: bool,
        touch_threshold: f32,
    ) -> Result<Self, <SPI as ErrorType>::Error> {
        let mut instance = Self {
            spi,
            irq_on,
            touch_threshold,
        };
        instance.update_register()?;
        Ok(instance)
    }
    /// Updates the control register of the TSC2046 chip.
    ///
    /// # Returns
    ///
    /// A `Result` indicating whether the register update was successful or not.
    fn update_register(&mut self) -> Result<(), <SPI as ErrorType>::Error> {
        let mut control_word = ControlBit::S; //start bit always on
        control_word &= !ControlBit::MODE; // 12 bit mode
        control_word &= !ControlBit::SER; // enable differential mode
        control_word |= Axes::X.ctrl_bits();
        if self.irq_on {
            control_word &= !ControlBit::PD0;
            control_word &= !ControlBit::PD1;
        } else {
            control_word |= ControlBit::PD0;
            control_word |= ControlBit::PD1;
        }

        let mut buf = [0_u8; 2];
        self.spi.transaction(&mut [
            Operation::Write(&[control_word.bits()]),
            Operation::Read(&mut buf),
        ])
    }
    /// Reads the value of the specified axis from the TSC2046 chip.
    ///
    /// # Arguments
    ///
    /// * `axis` - The axis to read.
    ///
    /// # Returns
    ///
    /// A `Result` containing the raw value of the specified axis or an error if the read fails.
    fn read_axis(&mut self, axis: Axes) -> Result<u16, <SPI as ErrorType>::Error> {
        let mut control_word = ControlBit::S; //start bit always on
        control_word &= !ControlBit::MODE; // 12 bit mode
        control_word &= !ControlBit::SER; // enable differential mode
        control_word |= axis.ctrl_bits();

        if self.irq_on {
            control_word &= !ControlBit::PD0;
            control_word &= !ControlBit::PD1;
        } else {
            control_word |= ControlBit::PD0;
            control_word |= ControlBit::PD1;
        }

        let mut buf = [0_u8; 2];
        self.spi.transaction(&mut [
            Operation::Write(&[control_word.bits()]),
            Operation::Read(&mut buf),
        ])?;
        Ok((((buf[0] as u16) << 8 | buf[1] as u16) >> 3) & 0xFFF)
    }

    /// Enables or disables the interrupt pin.
    ///
    /// # Arguments
    ///
    /// * `enable_irq` - Whether to enable or disable the interrupt pin.
    ///
    /// # Returns
    ///
    /// A `Result` indicating whether the interrupt pin configuration was successful or not.
    pub fn set_irq(&mut self, enable_irq: bool) -> Result<(), <SPI as ErrorType>::Error> {
        self.irq_on = enable_irq;
        self.update_register()
    }

    /// Sets the minimum pressure value required to register a touch event.
    ///
    /// # Arguments
    ///
    /// * `touch_threshold` - The minimum pressure value (between 0.0 and inf).   
    pub fn set_touch_threshold(&mut self, touch_threshold: f32) {
        self.touch_threshold = touch_threshold;
    }

    /// Reads the touch point from the TSC2046 chip.
    ///
    /// # Returns
    ///
    /// A `Result` containing the `TouchPoint` struct if a touch event is detected, or `None` if no touch event is detected or an error occurs during the read operation.
    /// The `x` and `y` coordinates of the `TouchPoint` are in the range of 0 to 4096.
    pub fn get_touch(&mut self) -> Result<Option<TouchPoint>, <SPI as ErrorType>::Error> {
        let x_raw = self.read_axis(Axes::X)?;
        let y_raw = self.read_axis(Axes::Y)?;
        let z1_raw = self.read_axis(Axes::Z1)?;
        let z2_raw = self.read_axis(Axes::Z2)?;
        let z_value = x_raw as f32 / 4096_f32 * (z2_raw as f32 / z1_raw as f32 - 1.0f32);
        if z_value < self.touch_threshold {
            Ok(Some(TouchPoint {
                x: x_raw,
                y: y_raw,
                z: z_value,
            }))
        } else {
            Ok(None)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mock_peripherals::{MockOperation, MockSimpleHalSpiDevice};

    // Predefined control words for testing
    const CTRL_WORD_X_NO_IRQ: u8 = 0b11010011;
    const CTRL_WORD_Y_NO_IRQ: u8 = 0b10010011;
    const CTRL_WORD_Z1_NO_IRQ: u8 = 0b10110011;
    const CTRL_WORD_Z2_NO_IRQ: u8 = 0b11000011;

    const CTRL_WORD_X_IRQ: u8 = 0b11010000;
    const CTRL_WORD_Y_IRQ: u8 = 0b10010000;
    const CTRL_WORD_Z1_IRQ: u8 = 0b10110000;
    const CTRL_WORD_Z2_IRQ: u8 = 0b11000000;

    //Helper function to assert SPI operations
    fn assert_spi_operations<Word: std::cmp::PartialEq + std::fmt::Debug + std::marker::Copy>(
        ops: &mut [Operation<'_, Word>],
        expected_ops: &[MockOperation<'_, Word>],
    ) {
        assert_eq!(ops.len(), expected_ops.len());
        let both_ops = ops.iter_mut().zip(expected_ops.iter());
        for (op, expected_op) in both_ops {
            match expected_op {
                MockOperation::Read(expected_read_buf) => {
                    match op {
                        // In case of a reading operation, we copy the expected values into the buffer.
                        Operation::Read(op_read_buf) => {
                            assert_eq!(op_read_buf.len(), expected_read_buf.len());
                            for i in 0..op_read_buf.len() {
                                op_read_buf[i] = expected_read_buf[i];
                            }
                        }
                        _ => assert!(false),
                    }
                }
                MockOperation::Write(expected_write_buf) => {
                    match op {
                        // In case of a Writing operation, the value of the buffer is compared against the value of the expected buffer.
                        Operation::Write(op_write_buf) => {
                            assert_eq!(op_write_buf, expected_write_buf);
                        }
                        _ => assert!(false),
                    }
                }
            }
        }
    }

    static X_TOUCH_VALUE: u16 = 100;
    static Y_TOUCH_VALUE: u16 = 100;
    static Z1_TOUCH_VALUE: u16 = 5;
    static Z2_TOUCH_VALUE: u16 = 2053;

    static INIT_RETURN_BUF: [u8; 2] = [0, 0];
    static READ_X_RETURN_BUF: [u8; 2] = [(X_TOUCH_VALUE >> 5) as u8, (X_TOUCH_VALUE << 3) as u8];
    static READ_Y_RETURN_BUF: [u8; 2] = [(Y_TOUCH_VALUE >> 5) as u8, (Y_TOUCH_VALUE << 3) as u8];
    static READ_Z1_RETURN_BUF: [u8; 2] = [(Z1_TOUCH_VALUE >> 5) as u8, (Z1_TOUCH_VALUE << 3) as u8];
    static READ_Z2_RETURN_BUF: [u8; 2] = [(Z2_TOUCH_VALUE >> 5) as u8, (Z2_TOUCH_VALUE << 3) as u8];
    #[test]
    fn test_get_touch_no_irq() {
        let expected_ops_init = [
            MockOperation::Write(&[CTRL_WORD_X_NO_IRQ]),
            MockOperation::Read(&INIT_RETURN_BUF),
        ];
        let expected_ops_x = [
            MockOperation::Write(&[CTRL_WORD_X_NO_IRQ]),
            MockOperation::Read(&READ_X_RETURN_BUF),
        ];
        let expected_ops_y = [
            MockOperation::Write(&[CTRL_WORD_Y_NO_IRQ]),
            MockOperation::Read(&READ_Y_RETURN_BUF),
        ];
        let expected_ops_z1 = [
            MockOperation::Write(&[CTRL_WORD_Z1_NO_IRQ]),
            MockOperation::Read(&READ_Z1_RETURN_BUF),
        ];
        let expected_ops_z2 = [
            MockOperation::Write(&[CTRL_WORD_Z2_NO_IRQ]),
            MockOperation::Read(&READ_Z2_RETURN_BUF),
        ];
        let expected_touch_point = TouchPoint {
            x: 100,
            y: 100,
            z: 10.0f32,
        };
        let mut mock_spi_dev = MockSimpleHalSpiDevice::new();

        mock_spi_dev
            .expect_transaction()
            .times(1)
            .returning(move |operations| {
                assert_spi_operations(operations, &expected_ops_init);
                Ok(())
            });
        mock_spi_dev
            .expect_transaction()
            .times(1)
            .returning(move |operations| {
                assert_spi_operations(operations, &expected_ops_x);
                Ok(())
            });
        mock_spi_dev
            .expect_transaction()
            .times(1)
            .returning(move |operations| {
                assert_spi_operations(operations, &expected_ops_y);
                Ok(())
            });
        mock_spi_dev
            .expect_transaction()
            .times(1)
            .returning(move |operations| {
                assert_spi_operations(operations, &expected_ops_z1);
                Ok(())
            });
        mock_spi_dev
            .expect_transaction()
            .times(1)
            .returning(move |operations| {
                assert_spi_operations(operations, &expected_ops_z2);
                Ok(())
            });
        let mut test_driver =
            Tsc2046::new(mock_spi_dev, false, 100.0).expect("Could not create driver");
        assert_eq!(test_driver.get_touch(), Ok(Some(expected_touch_point)));
    }

    #[test]
    fn test_get_touch_irq() {
        let expected_ops_init = [
            MockOperation::Write(&[CTRL_WORD_X_NO_IRQ]),
            MockOperation::Read(&INIT_RETURN_BUF),
        ];
        let expected_ops_irq_set = [
            MockOperation::Write(&[CTRL_WORD_X_IRQ]),
            MockOperation::Read(&INIT_RETURN_BUF),
        ];

        let expected_ops_x = [
            MockOperation::Write(&[CTRL_WORD_X_IRQ]),
            MockOperation::Read(&READ_X_RETURN_BUF),
        ];
        let expected_ops_y = [
            MockOperation::Write(&[CTRL_WORD_Y_IRQ]),
            MockOperation::Read(&READ_Y_RETURN_BUF),
        ];
        let expected_ops_z1 = [
            MockOperation::Write(&[CTRL_WORD_Z1_IRQ]),
            MockOperation::Read(&READ_Z1_RETURN_BUF),
        ];
        let expected_ops_z2 = [
            MockOperation::Write(&[CTRL_WORD_Z2_IRQ]),
            MockOperation::Read(&READ_Z2_RETURN_BUF),
        ];
        let expected_touch_point = TouchPoint {
            x: 100,
            y: 100,
            z: 10.0f32,
        };
        let mut mock_spi_dev = MockSimpleHalSpiDevice::new();

        mock_spi_dev
            .expect_transaction()
            .times(1)
            .returning(move |operations| {
                assert_spi_operations(operations, &expected_ops_init);
                Ok(())
            });
        mock_spi_dev
            .expect_transaction()
            .times(1)
            .returning(move |operations| {
                assert_spi_operations(operations, &expected_ops_irq_set);
                Ok(())
            });
        mock_spi_dev
            .expect_transaction()
            .times(1)
            .returning(move |operations| {
                assert_spi_operations(operations, &expected_ops_x);
                Ok(())
            });
        mock_spi_dev
            .expect_transaction()
            .times(1)
            .returning(move |operations| {
                assert_spi_operations(operations, &expected_ops_y);
                Ok(())
            });
        mock_spi_dev
            .expect_transaction()
            .times(1)
            .returning(move |operations| {
                assert_spi_operations(operations, &expected_ops_z1);
                Ok(())
            });
        mock_spi_dev
            .expect_transaction()
            .times(1)
            .returning(move |operations| {
                assert_spi_operations(operations, &expected_ops_z2);
                Ok(())
            });
        let mut test_driver =
            Tsc2046::new(mock_spi_dev, false, 100.0).expect("Could not create driver");
        test_driver.set_irq(true).expect("Could not set IRQ");
        assert_eq!(test_driver.get_touch(), Ok(Some(expected_touch_point)));
    }
}