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
use std::fs::File;
use std::io;
use std::io::prelude::*;

pub use embedded_hal::digital::v2::OutputPin;

pub struct OutPin {
    num: u32,
}

type Error = io::Error;

impl OutPin {
    /// Calculates the pins number for usage with the export and unexport files found on the linux
    /// system
    fn convert_to_absolute(port: u8, index: u8) -> u32 {
        let port = port as u32;
        let index = index as u32;
        let outnum = (port - 1) * 32 + index;
        outnum
    }

    /// Resets the pins by unexporting the pins from userspace through its file interface, to reset its state, then configures a new
    /// pin. This should make sure that the pin is usable.
    ///
    /// Note: It does not take into account if other
    /// applications are using the pins or anything like that.
    pub fn force_new(port: u8, index: u8) -> Result<Self, Error> {
        let num = Self::convert_to_absolute(port, index);
        if let Ok(mut export) = File::create("/sys/class/gpio/unexport") {
            let _e = export.write(num.to_string().as_bytes());
        }

        Self::new(port, index)
    }

    /// Tries to export and configure a new output pin, this can error out due to the pin already
    /// configured, usually with a device or resource busy
    pub fn new(port: u8, index: u8) -> Result<Self, Error> {
        let num = Self::convert_to_absolute(port, index);
        let mut export = File::create("/sys/class/gpio/export")?;
        export.write(num.to_string().as_bytes())?;

        let mut direction = File::create(format!("/sys/class/gpio/gpio{}/direction", num))?;
        direction.write("out".as_bytes())?;

        Ok(OutPin { num })
    }
}

impl OutputPin for OutPin {
    type Error = io::Error;

    fn set_low(&mut self) -> Result<(), Error> {
        let mut direction = File::create(format!("/sys/class/gpio/gpio{}/value", self.num))?;
        direction.write("0".as_bytes())?;
        Ok(())
    }

    fn set_high(&mut self) -> Result<(), Error> {
        let mut direction = File::create(format!("/sys/class/gpio/gpio{}/value", self.num))?;
        direction.write("1".as_bytes())?;
        Ok(())
    }
}
// Implement drop so that we can remove the pin from memory and setup once it is not to be used
// anymore
impl Drop for OutPin {
    fn drop(&mut self) {
        if let Ok(mut unexport) = File::create("/sys/class/gpio/unexport") {
            let _e = unexport.write(self.num.to_string().as_bytes());
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}