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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
use crate::error::Error;
use crate::{FtInner, PinUse};
use ftdi_mpsse::{ClockData, ClockDataOut, MpsseCmdBuilder, MpsseCmdExecutor};
use std::sync::{Arc, Mutex, MutexGuard};

/// FTDI SPI polarity.
///
/// This is a helper type to support multiple embedded-hal versions simultaneously.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Polarity {
    /// MPSSE command used to clock data in and out simultaneously.
    ///
    /// This is set by [`Spi::set_clock_polarity`].
    clk: ClockData,
    /// MPSSE command used to clock data out.
    ///
    /// This is set by [`Spi::set_clock_polarity`].
    clk_out: ClockDataOut,
}

impl From<eh0::spi::Polarity> for Polarity {
    fn from(cpol: eh0::spi::Polarity) -> Self {
        match cpol {
            eh0::spi::Polarity::IdleLow => Polarity {
                clk: ClockData::MsbPosIn,
                clk_out: ClockDataOut::MsbNeg,
            },
            eh0::spi::Polarity::IdleHigh => Polarity {
                clk: ClockData::MsbNegIn,
                clk_out: ClockDataOut::MsbPos,
            },
        }
    }
}

impl From<eh1::spi::Polarity> for Polarity {
    fn from(cpol: eh1::spi::Polarity) -> Self {
        match cpol {
            eh1::spi::Polarity::IdleLow => Polarity {
                clk: ClockData::MsbPosIn,
                clk_out: ClockDataOut::MsbNeg,
            },
            eh1::spi::Polarity::IdleHigh => Polarity {
                clk: ClockData::MsbNegIn,
                clk_out: ClockDataOut::MsbPos,
            },
        }
    }
}

impl Default for Polarity {
    fn default() -> Self {
        Self {
            clk: ClockData::MsbPosIn,
            clk_out: ClockDataOut::MsbNeg,
        }
    }
}

/// FTDI SPI bus.
///
/// In embedded-hal version 1 this represents an exclusive SPI bus.
///
/// This is created by calling [`FtHal::spi`].
///
/// [`FtHal::spi`]: crate::FtHal::spi
#[derive(Debug)]
pub struct Spi<Device: MpsseCmdExecutor> {
    /// Parent FTDI device.
    mtx: Arc<Mutex<FtInner<Device>>>,
    /// SPI polarity
    pol: Polarity,
}

impl<Device, E> Spi<Device>
where
    Device: MpsseCmdExecutor<Error = E>,
    E: std::error::Error,
    Error<E>: From<E>,
{
    pub(crate) fn new(mtx: Arc<Mutex<FtInner<Device>>>) -> Result<Spi<Device>, Error<E>> {
        {
            let mut lock = mtx.lock().expect("Failed to aquire FTDI mutex");
            lock.allocate_pin(0, PinUse::Spi);
            lock.allocate_pin(1, PinUse::Spi);
            lock.allocate_pin(2, PinUse::Spi);

            // clear direction of first 3 pins
            lock.direction &= !0x07;
            // set SCK (AD0) and MOSI (AD1) as output pins
            lock.direction |= 0x03;

            // set GPIO pins to new state
            let cmd: MpsseCmdBuilder = MpsseCmdBuilder::new()
                .set_gpio_lower(lock.value, lock.direction)
                .send_immediate();
            lock.ft.send(cmd.as_slice())?;
        }

        Ok(Spi {
            mtx,
            pol: Default::default(),
        })
    }

    /// Set the SPI clock polarity.
    ///
    /// FTD2XX devices only supports [SPI mode] 0 and 2, clock phase is fixed.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use eh1::spi::Polarity;
    /// use ftdi_embedded_hal as hal;
    ///
    /// # #[cfg(feature = "libftd2xx")]
    /// # {
    /// let device = libftd2xx::Ft2232h::with_description("Dual RS232-HS A")?;
    /// let hal = hal::FtHal::init_freq(device, 3_000_000)?;
    /// let mut spi = hal.spi()?;
    /// spi.set_clock_polarity(Polarity::IdleLow);
    /// # }
    /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// [SPI mode]: https://en.wikipedia.org/wiki/Serial_Peripheral_Interface#Mode_numbers
    pub fn set_clock_polarity<P: Into<Polarity>>(&mut self, cpol: P) {
        self.pol = cpol.into()
    }
}

impl<Device, E> eh0::blocking::spi::Write<u8> for Spi<Device>
where
    Device: MpsseCmdExecutor<Error = E>,
    E: std::error::Error,
    Error<E>: From<E>,
{
    type Error = Error<E>;

    fn write(&mut self, words: &[u8]) -> Result<(), Error<E>> {
        let cmd: MpsseCmdBuilder = MpsseCmdBuilder::new()
            .clock_data_out(self.pol.clk_out, words)
            .send_immediate();

        let mut lock = self.mtx.lock().expect("Failed to aquire FTDI mutex");
        lock.ft.send(cmd.as_slice())?;

        Ok(())
    }
}

impl<Device, E> eh0::blocking::spi::Transfer<u8> for Spi<Device>
where
    Device: MpsseCmdExecutor<Error = E>,
    E: std::error::Error,
    Error<E>: From<E>,
{
    type Error = Error<E>;

    fn transfer<'w>(&mut self, words: &'w mut [u8]) -> Result<&'w [u8], Error<E>> {
        let cmd: MpsseCmdBuilder = MpsseCmdBuilder::new()
            .clock_data(self.pol.clk, words)
            .send_immediate();

        let mut lock = self.mtx.lock().expect("Failed to aquire FTDI mutex");
        lock.ft.send(cmd.as_slice())?;
        lock.ft.recv(words)?;

        Ok(words)
    }
}

impl<Device, E> eh0::spi::FullDuplex<u8> for Spi<Device>
where
    Device: MpsseCmdExecutor<Error = E>,
    E: std::error::Error,
    Error<E>: From<E>,
{
    type Error = Error<E>;

    fn read(&mut self) -> nb::Result<u8, Error<E>> {
        let mut buf: [u8; 1] = [0];
        let cmd: MpsseCmdBuilder = MpsseCmdBuilder::new()
            .clock_data(self.pol.clk, &buf)
            .send_immediate();

        let mut lock = self.mtx.lock().expect("Failed to aquire FTDI mutex");
        match lock.ft.xfer(cmd.as_slice(), &mut buf) {
            Ok(()) => Ok(buf[0]),
            Err(e) => Err(nb::Error::Other(Error::from(e))),
        }
    }

    fn send(&mut self, byte: u8) -> nb::Result<(), Error<E>> {
        let cmd: MpsseCmdBuilder = MpsseCmdBuilder::new()
            .clock_data_out(self.pol.clk_out, &[byte])
            .send_immediate();

        let mut lock = self.mtx.lock().expect("Failed to aquire FTDI mutex");
        match lock.ft.send(cmd.as_slice()) {
            Ok(()) => Ok(()),
            Err(e) => Err(nb::Error::Other(Error::from(e))),
        }
    }
}

impl<E> eh1::spi::Error for Error<E>
where
    E: std::error::Error,
    Error<E>: From<E>,
{
    fn kind(&self) -> eh1::spi::ErrorKind {
        eh1::spi::ErrorKind::Other
    }
}

impl<Device, E> eh1::spi::ErrorType for Spi<Device>
where
    Device: MpsseCmdExecutor<Error = E>,
    E: std::error::Error,
    Error<E>: From<E>,
{
    type Error = Error<E>;
}

impl<Device, E> eh1::spi::SpiBusFlush for Spi<Device>
where
    Device: MpsseCmdExecutor<Error = E>,
    E: std::error::Error,
    Error<E>: From<E>,
{
    fn flush(&mut self) -> Result<(), Self::Error> {
        Ok(())
    }
}

impl<Device, E> eh1::spi::SpiBusWrite<u8> for Spi<Device>
where
    Device: MpsseCmdExecutor<Error = E>,
    E: std::error::Error,
    Error<E>: From<E>,
{
    fn write(&mut self, words: &[u8]) -> Result<(), Error<E>> {
        let cmd: MpsseCmdBuilder = MpsseCmdBuilder::new()
            .clock_data_out(self.pol.clk_out, words)
            .send_immediate();

        let mut lock = self.mtx.lock().expect("Failed to aquire FTDI mutex");
        lock.ft.send(cmd.as_slice())?;

        Ok(())
    }
}

impl<Device, E> eh1::spi::SpiBusRead<u8> for Spi<Device>
where
    Device: MpsseCmdExecutor<Error = E>,
    E: std::error::Error,
    Error<E>: From<E>,
{
    fn read(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
        let data_out: Vec<u8> = vec![0; words.len()];
        let cmd: MpsseCmdBuilder = MpsseCmdBuilder::new()
            .clock_data(self.pol.clk, &data_out)
            .send_immediate();

        let mut lock = self.mtx.lock().expect("Failed to aquire FTDI mutex");
        lock.ft.send(cmd.as_slice())?;
        lock.ft.recv(words)?;

        Ok(())
    }
}

impl<Device, E> eh1::spi::SpiBus<u8> for Spi<Device>
where
    Device: MpsseCmdExecutor<Error = E>,
    E: std::error::Error,
    Error<E>: From<E>,
{
    fn transfer_in_place(&mut self, words: &mut [u8]) -> Result<(), Error<E>> {
        let cmd: MpsseCmdBuilder = MpsseCmdBuilder::new()
            .clock_data(self.pol.clk, words)
            .send_immediate();

        let mut lock = self.mtx.lock().expect("Failed to aquire FTDI mutex");

        lock.ft.send(cmd.as_slice())?;
        lock.ft.recv(words)?;

        Ok(())
    }

    fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), Error<E>> {
        let cmd: MpsseCmdBuilder = MpsseCmdBuilder::new()
            .clock_data(self.pol.clk, write)
            .send_immediate();

        let mut lock = self.mtx.lock().expect("Failed to aquire FTDI mutex");
        lock.ft.send(cmd.as_slice())?;
        lock.ft.recv(read)?;

        Ok(())
    }
}

impl<Device, E> ehnb1::spi::FullDuplex<u8> for Spi<Device>
where
    Device: MpsseCmdExecutor<Error = E>,
    E: std::error::Error,
    Error<E>: From<E>,
{
    fn read(&mut self) -> nb::Result<u8, Error<E>> {
        let mut buf: [u8; 1] = [0];
        let cmd: MpsseCmdBuilder = MpsseCmdBuilder::new()
            .clock_data(self.pol.clk, &buf)
            .send_immediate();

        let mut lock = self.mtx.lock().expect("Failed to aquire FTDI mutex");
        match lock.ft.xfer(cmd.as_slice(), &mut buf) {
            Ok(()) => Ok(buf[0]),
            Err(e) => Err(nb::Error::Other(Error::from(e))),
        }
    }

    fn write(&mut self, byte: u8) -> nb::Result<(), Error<E>> {
        let cmd: MpsseCmdBuilder = MpsseCmdBuilder::new()
            .clock_data_out(self.pol.clk_out, &[byte])
            .send_immediate();

        let mut lock = self.mtx.lock().expect("Failed to aquire FTDI mutex");
        match lock.ft.send(cmd.as_slice()) {
            Ok(()) => Ok(()),
            Err(e) => Err(nb::Error::Other(Error::from(e))),
        }
    }
}

pub struct SpiDeviceBus<'a, Device: MpsseCmdExecutor> {
    lock: MutexGuard<'a, FtInner<Device>>,
    pol: Polarity,
}

impl<'a, Device, E> eh1::spi::ErrorType for SpiDeviceBus<'a, Device>
where
    Device: MpsseCmdExecutor<Error = E>,
    E: std::error::Error,
    Error<E>: From<E>,
{
    type Error = Error<E>;
}

impl<'a, Device, E> eh1::spi::SpiBusFlush for SpiDeviceBus<'a, Device>
where
    Device: MpsseCmdExecutor<Error = E>,
    E: std::error::Error,
    Error<E>: From<E>,
{
    fn flush(&mut self) -> Result<(), Self::Error> {
        Ok(())
    }
}

impl<'a, Device, E> eh1::spi::SpiBusRead<u8> for SpiDeviceBus<'a, Device>
where
    Device: MpsseCmdExecutor<Error = E>,
    E: std::error::Error,
    Error<E>: From<E>,
{
    fn read(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
        self.lock.ft.xfer(
            MpsseCmdBuilder::new()
                .clock_data(self.pol.clk, words)
                .send_immediate()
                .as_slice(),
            words,
        )?;
        Ok(())
    }
}

impl<'a, Device, E> eh1::spi::SpiBusWrite<u8> for SpiDeviceBus<'a, Device>
where
    Device: MpsseCmdExecutor<Error = E>,
    E: std::error::Error,
    Error<E>: From<E>,
{
    fn write(&mut self, words: &[u8]) -> Result<(), Self::Error> {
        self.lock.ft.send(
            MpsseCmdBuilder::new()
                .clock_data_out(self.pol.clk_out, words)
                .send_immediate()
                .as_slice(),
        )?;
        Ok(())
    }
}

impl<'a, Device, E> eh1::spi::SpiBus<u8> for SpiDeviceBus<'a, Device>
where
    Device: MpsseCmdExecutor<Error = E>,
    E: std::error::Error,
    Error<E>: From<E>,
{
    fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), Self::Error> {
        self.lock.ft.xfer(
            MpsseCmdBuilder::new()
                .clock_data(self.pol.clk, write)
                .send_immediate()
                .as_slice(),
            read,
        )?;
        Ok(())
    }

    fn transfer_in_place(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
        self.lock.ft.xfer(
            MpsseCmdBuilder::new()
                .clock_data(self.pol.clk, words)
                .send_immediate()
                .as_slice(),
            words,
        )?;
        Ok(())
    }
}

/// FTDI SPI device, a SPI bus with chip select pin.
///
/// This is created by calling [`FtHal::spi_device`].
///
/// This is specific to embedded-hal version 1.
///
/// [`FtHal::spi_device`]: crate::FtHal::spi_device
#[derive(Debug)]
pub struct SpiDevice<Device: MpsseCmdExecutor> {
    /// Parent FTDI device.
    mtx: Arc<Mutex<FtInner<Device>>>,
    /// SPI polarity
    pol: Polarity,
    /// Chip select pin index.  0-7 for the FT232H.
    cs_idx: u8,
}

impl<Device, E> SpiDevice<Device>
where
    Device: MpsseCmdExecutor<Error = E>,
    E: std::error::Error,
    Error<E>: From<E>,
{
    pub(crate) fn new(
        mtx: Arc<Mutex<FtInner<Device>>>,
        cs_idx: u8,
    ) -> Result<SpiDevice<Device>, Error<E>> {
        {
            let mut lock = mtx.lock().expect("Failed to aquire FTDI mutex");
            lock.allocate_pin(0, PinUse::Spi);
            lock.allocate_pin(1, PinUse::Spi);
            lock.allocate_pin(2, PinUse::Spi);
            lock.allocate_pin(cs_idx, PinUse::Output);

            let cs_mask: u8 = 1 << cs_idx;

            // clear direction of first 3 pins and CS
            lock.direction &= !(0x07 | cs_mask);
            // set SCK (AD0) and MOSI (AD1), and CS as output pins
            lock.direction |= 0x03 | cs_mask;

            // set GPIO pins to new state
            let cmd: MpsseCmdBuilder = MpsseCmdBuilder::new()
                .set_gpio_lower(lock.value, lock.direction)
                .send_immediate();
            lock.ft.send(cmd.as_slice())?;
        }

        Ok(Self {
            mtx,
            pol: Default::default(),
            cs_idx,
        })
    }

    pub(crate) fn cs_mask(&self) -> u8 {
        1 << self.cs_idx
    }

    /// Set the SPI clock polarity.
    ///
    /// FTD2XX devices only supports [SPI mode] 0 and 2, clock phase is fixed.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use eh1::spi::Polarity;
    /// use ftdi_embedded_hal as hal;
    ///
    /// # #[cfg(feature = "libftd2xx")]
    /// # {
    /// let device = libftd2xx::Ft2232h::with_description("Dual RS232-HS A")?;
    /// let hal = hal::FtHal::init_freq(device, 3_000_000)?;
    /// let mut spi = hal.spi_device(3)?;
    /// spi.set_clock_polarity(Polarity::IdleLow);
    /// # }
    /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// [SPI mode]: https://en.wikipedia.org/wiki/Serial_Peripheral_Interface#Mode_numbers
    pub fn set_clock_polarity<P: Into<Polarity>>(&mut self, cpol: P) {
        self.pol = cpol.into()
    }
}

impl<'a, Device, E> eh1::spi::ErrorType for &'a SpiDevice<Device>
where
    Device: MpsseCmdExecutor<Error = E>,
    E: std::error::Error,
    Error<E>: From<E>,
{
    type Error = Error<E>;
}

impl<'a, Device, E> eh1::spi::SpiDevice for &'a SpiDevice<Device>
where
    Device: MpsseCmdExecutor<Error = E>,
    E: std::error::Error,
    Error<E>: From<E>,
{
    type Bus = SpiDeviceBus<'a, Device>;

    fn transaction<R>(
        &mut self,
        f: impl FnOnce(&mut Self::Bus) -> Result<R, <Self::Bus as eh1::spi::ErrorType>::Error>,
    ) -> Result<R, Self::Error> {
        // lock the bus
        let mut lock: MutexGuard<FtInner<Device>> =
            self.mtx.lock().expect("Failed to aquire FTDI mutex");
        let direction: u8 = lock.direction;

        // assert the chip select pin
        let value_cs_asserted: u8 = lock.value & !self.cs_mask();
        lock.ft.send(
            MpsseCmdBuilder::new()
                .set_gpio_lower(value_cs_asserted, direction)
                .send_immediate()
                .as_slice(),
        )?;

        // call f with an exclusive reference to the bus
        let mut bus: SpiDeviceBus<'a, Device> = SpiDeviceBus {
            lock,
            pol: self.pol,
        };
        let bus_result = f(&mut bus);

        // flush the bus
        {
            use eh1::spi::SpiBusFlush;
            bus.flush()?;
        }

        let mut lock: MutexGuard<FtInner<Device>> = bus.lock;

        // deassert the chip select pin
        let value_cs_deasserted: u8 = lock.value | self.cs_mask();
        lock.ft.send(
            MpsseCmdBuilder::new()
                .set_gpio_lower(value_cs_deasserted, direction)
                .send_immediate()
                .as_slice(),
        )?;

        // unlocking the bus is implicit via Drop
        bus_result
    }
}