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
use std::io::prelude::*;
use std::io::SeekFrom;
use std::os::unix::io::{AsRawFd, RawFd};
use sys::{Edge, Selector, GPIOSelector, GPIOPinSelector};
use {Result, Error, Logic, DigitalLogic, DigitalWrite, DigitalRead, is_root};
#[derive(Debug)]
pub struct Pin {
pin: usize,
exported: bool
}
impl Pin {
pub unsafe fn new(pin: usize) -> Pin {
Pin { pin: pin, exported: false }
}
pub fn export(&mut self) -> Result<()> {
if !is_root() {
return Err(Error::RootRequired)
}
let _ = GPIOSelector::write("unexport", self.pin);
try!(GPIOSelector::write("export", self.pin));
self.exported = true;
Ok(())
}
pub fn input(&self) -> Result<PinInput> {
try!(GPIOPinSelector::write(self.pin, "direction", "in"));
let sel = try!(GPIOPinSelector::open_rd(self.pin, "value"));
Ok(PinInput { sel: sel, pin: self.pin })
}
pub fn output(&self) -> Result<PinOutput> {
try!(GPIOPinSelector::write(self.pin, "direction", "out"));
let sel = try!(GPIOPinSelector::open(self.pin, "value"));
Ok(PinOutput { sel: sel, pin: self.pin })
}
}
impl Drop for Pin {
fn drop(&mut self) {
if self.exported {
let _ = GPIOSelector::write("unexport", self.pin);
}
}
}
#[derive(Debug)]
pub struct PinInput {
sel: Selector,
pin: usize
}
impl DigitalRead for PinInput {
fn digital_read(&mut self) -> Result<Logic> {
try!(self.sel.seek(SeekFrom::Start(0)));
let mut buf = [0u8];
let len = try!(self.sel.read(&mut buf));
if len == 0 {
return Err(Error::UnexpectedError);
}
match buf[0] {
b'1' => Ok(Logic::High),
b'0' => Ok(Logic::Low),
_ => Err(Error::UnexpectedError),
}
}
}
impl PinInput {
fn set_edge(&mut self, edge: Edge) -> Result<()> {
try!(GPIOPinSelector::write(self.pin, "edge", match edge {
Edge::NoInterrupt => "none",
Edge::RisingEdge => "rising",
Edge::FallingEdge => "falling",
Edge::BothEdges => "both",
}));
Ok(())
}
}
impl AsRawFd for PinInput {
fn as_raw_fd(&self) -> RawFd {
self.sel.as_raw_fd()
}
}
#[derive(Debug)]
pub struct PinOutput {
sel: Selector,
pin: usize
}
impl DigitalWrite for PinOutput {
fn digital_write<L: DigitalLogic>(&mut self, level: L) -> Result<()> {
let buf: [u8;1] = match level.logic_level() {
Logic::High => [b'1'],
Logic::Low => [b'0'],
};
let _ = try!(self.sel.write(&buf));
Ok(())
}
}
impl AsRawFd for PinOutput {
fn as_raw_fd(&self) -> RawFd {
self.sel.as_raw_fd()
}
}