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
extern crate std;
extern crate nix;

use std::fmt;
use std::time::Duration;
use std::io::prelude::*;
use std::io::{Error, ErrorKind, SeekFrom};
use std::fs::File;
use std::path::Path;

use std::os::unix::io::RawFd;

#[cfg(feature = "measure")]
use measure::Measure;

fn duration_to_ms(duration: Duration) -> u64 {
    duration.as_secs() * 1_000u64 + duration.subsec_nanos() as u64 / 1_000_000u64
}

#[derive(Clone, Copy, Debug)]
pub enum Direction {
    Out,
    In,
}
impl Direction {
    pub fn from_str(s: &str) -> Option<Direction> {
        match s {
            "out" => Some(Direction::Out),
            "in" => Some(Direction::In),
            _ => None,
        }
    }

    pub fn as_str(&self) -> &'static str {
        match *self {
            Direction::Out => "out",
            Direction::In => "in",
        }
    }
}

#[derive(Clone, Copy, Debug)]
pub enum Edge {
    None,
    Rising,
    Falling,
    Both,
}
impl Edge {
    pub fn from_str(s: &str) -> Option<Edge> {
        match s {
            "none" => Some(Edge::None),
            "rising" => Some(Edge::Rising),
            "falling" => Some(Edge::Falling),
            "both" => Some(Edge::Both),
            _ => None,
        }
    }

    pub fn as_str(&self) -> &'static str {
        match *self {
            Edge::None => "none",
            Edge::Rising => "rising",
            Edge::Falling => "falling",
            Edge::Both => "both",
        }
    }
}

#[derive(Clone, Copy, Debug)]
pub enum Value {
    High,
    Low,
}
impl Value {
    pub fn from_str(s: &str) -> Option<Value> {
        match s {
            "1" => Some(Value::High),
            "0" => Some(Value::Low),
            _ => None,
        }
    }

    pub fn from_buffer(b: &[u8; 1]) -> Option<Self> {
        Value::from_char(b[0])
    }

    pub fn from_char(c: u8) -> Option<Self> {
        match c {
            48 => Some(Value::Low), // '0'
            49 => Some(Value::High), // '1'
            _ => None,
        }
    }

    pub fn as_str(&self) -> &'static str {
        match *self {
            Value::High => "1",
            Value::Low => "0",
        }
    }
}

#[derive(Debug)]
pub struct Port {
    pub number: u8,
    pub direction: Direction,
}

#[derive(Debug)]
pub struct SyncPort {
    pub port: Port,
    file: File,
    buffer: [u8; 1],
}
pub struct AsyncPort {
    pub port: Port,
    pub edge: Edge,
    file: RawFd,
    fds: [nix::poll::PollFd; 1],
    buffer: [u8; 1],
}

impl fmt::Debug for AsyncPort {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f,
               "AsyncPort {{ port: {:?}, edge: {:?}, file: {:?}, fds: [?], buffer: {:?} }}",
               self.port,
               self.edge,
               self.file,
               self.buffer)
    }
}

impl Port {
    /// Constructs a new GPIO `Port`.
    ///
    /// # Parameter
    /// - `number` GPIO Port number of pin.
    /// - `direction` GPIO Port direction.
    pub fn new(number: u8, direction: Direction) -> std::io::Result<Port> {
        let port = Port {
            number: number,
            direction: direction,
        };

        port.init()?;
        Ok(port)
    }

    /// Init GPIO `Port`: export port and set direction
    fn init(&self) -> std::io::Result<()> {
        self.export().ok();
        self.set_direction()?;

        Ok(())
    }

    /// Drop GPIO `Port`: unexport
    pub fn drop(&mut self) {
        self.unexport().ok();
    }

    fn write_path(path: &str, value: &str) -> std::io::Result<()> {
        File::create(Path::new(path))?
            .write_all(value.as_bytes())
    }


    /// Export GPIO `Port`
    fn export(&self) -> std::io::Result<()> {
        Port::write_path("/sys/class/gpio/export", self.number.to_string().as_str())
    }
    /// Unexport GPIO `Port`
    fn unexport(&self) -> std::io::Result<()> {
        Port::write_path("/sys/class/gpio/unexport", self.number.to_string().as_str())
    }

    /// Set GPIO `Port` direction
    fn set_direction(&self) -> std::io::Result<()> {
        Port::write_path(format!("/sys/class/gpio/gpio{}/direction", self.number).as_str(),
                         self.direction.as_str())
    }
}

impl SyncPort {
    /// Constructs a new synchronised GPIO `Port`.
    ///
    /// # Parameter
    /// - `number` GPIO Port number of pin.
    /// - `direction` GPIO Port direction.
    pub fn new(number: u8, direction: Direction) -> std::io::Result<SyncPort> {
        Ok(SyncPort {
               port: Port::new(number, direction)?,
               file: SyncPort::open(number, direction)?,
               buffer: [0; 1],
           })
    }

    /// Open GPIO `SyncPort` sysfs file
    fn open(number: u8, direction: Direction) -> std::io::Result<File> {
        let path = format!("/sys/class/gpio/gpio{}/value", number);
        let path = Path::new(path.as_str());

        Ok(match direction {
               Direction::Out => File::create(path)?,
               Direction::In => File::open(path)?,
           })
    }

    /// Read from GPIO `SyncPort` sysfs file
    pub fn read(&mut self) -> std::io::Result<Value> {
        self.file.seek(SeekFrom::Start(0))?;
        self.file.read_exact(&mut self.buffer)?;

        Value::from_buffer(&self.buffer).ok_or(Error::new(ErrorKind::InvalidData,
                                                          "Unrecognized GPIO Value"))
    }

    /// Write to GPIO `SyncPort` sysfs file
    pub fn write(&mut self, value: Value) -> std::io::Result<()> {
        self.file.write_all(value.as_str().as_bytes())
    }
}

impl AsyncPort {
    /// Constructs a new asynchronous GPIO `Port`.
    ///
    /// # Parameter
    /// - `number` GPIO Port number of pin.
    /// - `edge` GPIO Port edge detection setting.
    pub fn new(number: u8, edge: Edge) -> std::io::Result<AsyncPort> {
        let port = Port::new(number, Direction::In)?;
        let file = AsyncPort::open(number)?;
        let port = AsyncPort {
            port: port,
            edge: edge,
            file: file,
            fds: [nix::poll::PollFd::new(file, nix::poll::POLLPRI, nix::poll::EventFlags::empty())],
            buffer: [0; 1],
        };

        port.init()?;
        Ok(port)
    }

    /// Init GPIO `Port`: set edge detection
    fn init(&self) -> std::io::Result<()> {
        self.set_edge()?;

        Ok(())
    }

    /// Open GPIO `AsyncPort` sysfs file with posix API
    fn open(number: u8) -> std::io::Result<RawFd> {
        nix::fcntl::open(format!("/sys/class/gpio/gpio{}/value", number).as_str(),
                         nix::fcntl::O_RDONLY,
                         nix::sys::stat::Mode::empty())
                .or(Err(Error::new(ErrorKind::Other, "open failed")))
    }

    fn get_timeout(timeout: Option<Duration>) -> i32 {
        match timeout {
            None => -1,
            Some(t) => duration_to_ms(t) as i32,
        }
    }

    /// Posix poll on sysfs file
    fn nix_poll(&mut self, timeout: i32) -> nix::Result<i32> {
        nix::poll::poll(&mut self.fds, timeout)
    }

    /// Read from GPIO `AsyncPort` sysfs file with posix poll
    fn poll_read(&mut self, poll: nix::Result<i32>) -> std::io::Result<Option<Value>> {
        let poll = poll.or(Err(Error::new(ErrorKind::Other, "poll failed")))?;

        if poll == 0 {
            return Ok(None);
        }

        nix::unistd::lseek(self.file, 0, nix::unistd::Whence::SeekSet)
            .or(Err(Error::new(ErrorKind::Other, "lseek failed")))?;

        nix::unistd::read(self.file, &mut self.buffer)
            .or(Err(Error::new(ErrorKind::Other, "read failed")))?;

        Value::from_buffer(&self.buffer).map_or(Err(Error::new(ErrorKind::InvalidData,
                                                               "Unrecognized GPIO Value")),
                                                |v| Ok(Some(v)))
    }

    /// Read asynchronous from GPIO `AsyncPort` sysfs file
    pub fn poll(&mut self, timeout: Option<Duration>) -> std::io::Result<Option<Value>> {
        let poll = self.nix_poll(Self::get_timeout(timeout));

        self.poll_read(poll)
    }

    /// Read asynchronous from GPIO `AsyncPort` sysfs file with measure support (ignore poll time)
    #[cfg(feature = "measure")]
    pub fn poll_measure(&mut self,
                        timeout: Option<Duration>,
                        measure: &mut Measure)
                        -> std::io::Result<Option<Value>> {
        let timeout = Self::get_timeout(timeout);

        measure.pause();
        let poll = self.nix_poll(timeout);
        measure.start();

        self.poll_read(poll)
    }

    /// Set GPIO `Port` edge detection
    fn set_edge(&self) -> std::io::Result<()> {
        Port::write_path(format!("/sys/class/gpio/gpio{}/edge", self.port.number).as_str(),
                         self.edge.as_str())
    }
}