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
// Copyright lowRISC contributors (OpenTitan project).
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

use super::board::Board;
use anyhow::Result;
use std::cell::RefCell;
use std::rc::Rc;

use crate::io::gpio::{GpioError, GpioPin, PinMode, PullMode};
use crate::transport::chip_whisperer::usb::Backend;

pub struct Pin<B: Board> {
    device: Rc<RefCell<Backend<B>>>,
    pinname: String,
}

impl<B: Board> Pin<B> {
    pub fn open(backend: Rc<RefCell<Backend<B>>>, pinname: String) -> Result<Self> {
        Ok(Self {
            device: backend,
            pinname,
        })
    }
}

impl<B: Board> GpioPin for Pin<B> {
    fn read(&self) -> Result<bool> {
        let usb = self.device.borrow();
        let pin = usb.pin_get_state(&self.pinname)?;
        Ok(pin != 0)
    }

    fn write(&self, value: bool) -> Result<()> {
        let usb = self.device.borrow();
        usb.pin_set_state(&self.pinname, value)?;
        Ok(())
    }

    fn set_mode(&self, mode: PinMode) -> Result<()> {
        let usb = self.device.borrow();
        match mode {
            PinMode::Input => usb.pin_set_output(&self.pinname, false)?,
            PinMode::PushPull => usb.pin_set_output(&self.pinname, true)?,
            _ => return Err(GpioError::UnsupportedPinMode(mode).into()),
        }
        Ok(())
    }

    fn set_pull_mode(&self, mode: PullMode) -> Result<()> {
        match mode {
            PullMode::None => Ok(()),
            _ => Err(GpioError::UnsupportedPullMode(mode).into()),
        }
    }

    fn get_internal_pin_name(&self) -> Option<&str> {
        Some(&self.pinname)
    }
}