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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
#![crate_type = "lib"]
#![crate_name = "sysfs_gpio"]
#[cfg(feature = "tokio")]
extern crate futures;
#[cfg(feature = "mio-evented")]
extern crate mio;
extern crate nix;
#[cfg(feature = "tokio")]
extern crate tokio_core;
#[cfg(feature = "tokio")]
use futures::{Async, Poll, Stream};
#[cfg(feature = "mio-evented")]
use mio::Evented;
#[cfg(feature = "mio-evented")]
use mio::unix::EventedFd;
#[cfg(any(target_os = "linux", target_os = "android"))]
use nix::sys::epoll::*;
use nix::unistd::close;
use std::io::prelude::*;
use std::os::unix::prelude::*;
use std::io::{self, SeekFrom};
use std::fs;
use std::fs::File;
use std::path::Path;
#[cfg(feature = "tokio")]
use tokio_core::reactor::{Handle, PollEvented};
mod error;
pub use error::Error;
const GPIO_PATH_PREFIX: &'static str = "/sys/class/gpio/gpio";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Pin {
pin_num: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Direction {
In,
Out,
High,
Low,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Edge {
NoInterrupt,
RisingEdge,
FallingEdge,
BothEdges,
}
#[macro_export]
macro_rules! try_unexport {
($gpio:ident, $e:expr) => (match $e {
Ok(res) => res,
Err(e) => { try!($gpio.unexport()); return Err(e) },
});
}
pub type Result<T> = ::std::result::Result<T, error::Error>;
fn flush_input_from_file(dev_file: &mut File, max: usize) -> io::Result<usize> {
let mut s = String::with_capacity(max);
dev_file.read_to_string(&mut s)
}
fn get_value_from_file(dev_file: &mut File) -> Result<u8> {
let mut s = String::with_capacity(10);
dev_file.seek(SeekFrom::Start(0))?;
dev_file.read_to_string(&mut s)?;
match s[..1].parse::<u8>() {
Ok(n) => Ok(n),
Err(_) => Err(Error::Unexpected(format!("Unexpected value file contents: {:?}", s))),
}
}
impl Pin {
fn write_to_device_file(&self, dev_file_name: &str, value: &str) -> io::Result<()> {
let gpio_path = format!("/sys/class/gpio/gpio{}/{}", self.pin_num, dev_file_name);
let mut dev_file = File::create(&gpio_path)?;
dev_file.write_all(value.as_bytes())?;
Ok(())
}
fn read_from_device_file(&self, dev_file_name: &str) -> io::Result<String> {
let gpio_path = format!("/sys/class/gpio/gpio{}/{}", self.pin_num, dev_file_name);
let mut dev_file = File::open(&gpio_path)?;
let mut s = String::new();
dev_file.read_to_string(&mut s)?;
Ok(s)
}
pub fn new(pin_num: u64) -> Pin {
Pin { pin_num: pin_num }
}
pub fn from_path<T: AsRef<Path>>(path: T) -> Result<Pin> {
let pb = fs::canonicalize(path.as_ref())?;
if !fs::metadata(&pb)?.is_dir() {
return Err(Error::Unexpected("Provided path not a directory or symlink to \
a directory"
.to_owned()));
}
let num = Pin::extract_pin_from_path(&pb.to_str().unwrap_or(""))?;
Ok(Pin::new(num))
}
fn extract_pin_from_path(path: &str) -> Result<u64> {
if path.starts_with(GPIO_PATH_PREFIX) {
path.split_at(GPIO_PATH_PREFIX.len()).1.parse::<u64>().or(
Err(
Error::InvalidPath(format!("{:?}", path)),
),
)
} else {
Err(Error::InvalidPath(format!("{:?}", path)))
}
}
pub fn get_pin_num(&self) -> u64 {
self.pin_num
}
#[inline]
pub fn with_exported<F: FnOnce() -> Result<()>>(&self, closure: F) -> Result<()> {
self.export()?;
match closure() {
Ok(()) => {
try!(self.unexport());
Ok(())
}
Err(err) => {
self.unexport()?;
Err(err)
}
}
}
pub fn is_exported(&self) -> bool {
fs::metadata(&format!("/sys/class/gpio/gpio{}", self.pin_num)).is_ok()
}
pub fn export(&self) -> Result<()> {
if fs::metadata(&format!("/sys/class/gpio/gpio{}", self.pin_num)).is_err() {
let mut export_file = File::create("/sys/class/gpio/export")?;
export_file
.write_all(format!("{}", self.pin_num).as_bytes())?;
}
Ok(())
}
pub fn unexport(&self) -> Result<()> {
if fs::metadata(&format!("/sys/class/gpio/gpio{}", self.pin_num)).is_ok() {
let mut unexport_file = File::create("/sys/class/gpio/unexport")?;
unexport_file
.write_all(format!("{}", self.pin_num).as_bytes())?;
}
Ok(())
}
pub fn get_pin(&self) -> u64 {
self.pin_num
}
pub fn get_direction(&self) -> Result<Direction> {
match self.read_from_device_file("direction") {
Ok(s) => {
match s.trim() {
"in" => Ok(Direction::In),
"out" => Ok(Direction::Out),
"high" => Ok(Direction::High),
"low" => Ok(Direction::Low),
other => Err(Error::Unexpected(format!("direction file contents {}", other))),
}
}
Err(e) => Err(::std::convert::From::from(e)),
}
}
pub fn set_direction(&self, dir: Direction) -> Result<()> {
self.write_to_device_file("direction", match dir {
Direction::In => "in",
Direction::Out => "out",
Direction::High => "high",
Direction::Low => "low",
})?;
Ok(())
}
pub fn get_value(&self) -> Result<u8> {
match self.read_from_device_file("value") {
Ok(s) => {
match s.trim() {
"1" => Ok(1),
"0" => Ok(0),
other => Err(Error::Unexpected(format!("value file contents {}", other))),
}
}
Err(e) => Err(::std::convert::From::from(e)),
}
}
pub fn set_value(&self, value: u8) -> Result<()> {
self.write_to_device_file("value", match value {
0 => "0",
_ => "1",
})?;
Ok(())
}
pub fn get_edge(&self) -> Result<Edge> {
match self.read_from_device_file("edge") {
Ok(s) => {
match s.trim() {
"none" => Ok(Edge::NoInterrupt),
"rising" => Ok(Edge::RisingEdge),
"falling" => Ok(Edge::FallingEdge),
"both" => Ok(Edge::BothEdges),
other => Err(Error::Unexpected(format!("Unexpected file contents {}", other))),
}
}
Err(e) => Err(::std::convert::From::from(e)),
}
}
pub fn set_edge(&self, edge: Edge) -> Result<()> {
self.write_to_device_file("edge", match edge {
Edge::NoInterrupt => "none",
Edge::RisingEdge => "rising",
Edge::FallingEdge => "falling",
Edge::BothEdges => "both",
})?;
Ok(())
}
pub fn get_active_low(&self) -> Result<bool> {
match self.read_from_device_file("active_low") {
Ok(s) => {
match s.trim() {
"1" => Ok(true),
"0" => Ok(false),
other => Err(Error::Unexpected(format!("active_low file contents {}", other))),
}
}
Err(e) => Err(::std::convert::From::from(e)),
}
}
pub fn set_active_low(&self, active_low: bool) -> Result<()> {
self.write_to_device_file("active_low",
match active_low {
true => "1",
false => "0",
})?;
Ok(())
}
pub fn get_poller(&self) -> Result<PinPoller> {
PinPoller::new(self.pin_num)
}
#[cfg(feature = "mio-evented")]
pub fn get_async_poller(&self) -> Result<AsyncPinPoller> {
AsyncPinPoller::new(self.pin_num)
}
#[cfg(feature = "tokio")]
pub fn get_stream(&self, handle: &Handle) -> Result<PinStream> {
PinStream::init(self.clone(), handle)
}
#[cfg(feature = "tokio")]
pub fn get_value_stream(&self, handle: &Handle) -> Result<PinValueStream> {
Ok(PinValueStream(PinStream::init(self.clone(), handle)?))
}
}
#[test]
fn extract_pin_fom_path_test() {
let tok = Pin::extract_pin_from_path(&"/sys/class/gpio/gpio951");
assert_eq!(951, tok.unwrap());
let err1 = Pin::extract_pin_from_path(&"/sys/is/error/gpio/gpio111");
assert_eq!(true, err1.is_err());
let err2 = Pin::extract_pin_from_path(&"/sys/CLASS/gpio/gpio");
assert_eq!(true, err2.is_err());
let err3 = Pin::extract_pin_from_path(&"/sys/class/gpio/gpioSDS");
assert_eq!(true, err3.is_err());
}
#[derive(Debug)]
pub struct PinPoller {
pin_num: u64,
epoll_fd: RawFd,
devfile: File,
}
impl PinPoller {
pub fn get_pin(&self) -> Pin {
Pin::new(self.pin_num)
}
#[cfg(any(target_os = "linux", target_os = "android"))]
pub fn new(pin_num: u64) -> Result<PinPoller> {
let devfile: File = File::open(&format!("/sys/class/gpio/gpio{}/value", pin_num))?;
let devfile_fd = devfile.as_raw_fd();
let epoll_fd = epoll_create()?;
let mut event = EpollEvent::new(EpollFlags::EPOLLPRI | EpollFlags::EPOLLET, 0u64);
match epoll_ctl(epoll_fd, EpollOp::EpollCtlAdd, devfile_fd, &mut event) {
Ok(_) => {
Ok(PinPoller {
pin_num: pin_num,
devfile: devfile,
epoll_fd: epoll_fd,
})
}
Err(err) => {
let _ = close(epoll_fd);
Err(::std::convert::From::from(err))
}
}
}
#[cfg(not(any(target_os = "linux", target_os = "android")))]
pub fn new(pin_num: u64) -> Result<PinPoller> {
Err(Error::Unsupported("PinPoller".into()))
}
#[cfg(any(target_os = "linux", target_os = "android"))]
pub fn poll(&mut self, timeout_ms: isize) -> Result<Option<u8>> {
flush_input_from_file(&mut self.devfile, 255)?;
let dummy_event = EpollEvent::new(EpollFlags::EPOLLPRI | EpollFlags::EPOLLET, 0u64);
let mut events: [EpollEvent; 1] = [dummy_event];
let cnt = epoll_wait(self.epoll_fd, &mut events, timeout_ms)?;
Ok(match cnt {
0 => None,
_ => Some(get_value_from_file(&mut self.devfile)?),
})
}
#[cfg(not(any(target_os = "linux", target_os = "android")))]
pub fn poll(&mut self, timeout_ms: isize) -> Result<Option<u8>> {
Err(Error::Unsupported("PinPoller".into()))
}
}
impl Drop for PinPoller {
fn drop(&mut self) {
close(self.epoll_fd).unwrap();
}
}
#[cfg(feature = "mio-evented")]
#[derive(Debug)]
pub struct AsyncPinPoller {
devfile: File,
}
#[cfg(feature = "mio-evented")]
impl AsyncPinPoller {
fn new(pin_num: u64) -> Result<Self> {
let devfile = File::open(&format!("/sys/class/gpio/gpio{}/value", pin_num))?;
Ok(AsyncPinPoller { devfile: devfile })
}
}
#[cfg(feature = "mio-evented")]
impl Evented for AsyncPinPoller {
fn register(&self,
poll: &mio::Poll,
token: mio::Token,
interest: mio::Ready,
opts: mio::PollOpt)
-> io::Result<()> {
EventedFd(&self.devfile.as_raw_fd()).register(poll, token, interest, opts)
}
fn reregister(&self,
poll: &mio::Poll,
token: mio::Token,
interest: mio::Ready,
opts: mio::PollOpt)
-> io::Result<()> {
EventedFd(&self.devfile.as_raw_fd()).reregister(poll, token, interest, opts)
}
fn deregister(&self, poll: &mio::Poll) -> io::Result<()> {
EventedFd(&self.devfile.as_raw_fd()).deregister(poll)
}
}
#[cfg(feature = "tokio")]
pub struct PinStream {
evented: PollEvented<AsyncPinPoller>,
skipped_first_event: bool,
}
#[cfg(feature = "tokio")]
impl PinStream {
pub fn init(pin: Pin, handle: &Handle) -> Result<Self> {
Ok(PinStream {
evented: PollEvented::new(pin.get_async_poller()?, &handle)?,
skipped_first_event: false,
})
}
}
#[cfg(feature = "tokio")]
impl Stream for PinStream {
type Item = ();
type Error = Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
Ok(match self.evented.poll_read() {
Async::Ready(()) => {
self.evented.need_read();
if self.skipped_first_event {
Async::Ready(Some(()))
} else {
self.skipped_first_event = true;
Async::NotReady
}
}
Async::NotReady => Async::NotReady,
})
}
}
#[cfg(feature = "tokio")]
pub struct PinValueStream(PinStream);
#[cfg(feature = "tokio")]
impl PinValueStream {
#[inline]
fn get_value(&mut self) -> Result<u8> {
get_value_from_file(&mut self.0.evented.get_mut().devfile)
}
}
#[cfg(feature = "tokio")]
impl Stream for PinValueStream {
type Item = u8;
type Error = Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
match self.0.poll() {
Ok(Async::Ready(Some(()))) => {
let value = try!(self.get_value());
Ok(Async::Ready(Some(value)))
}
Ok(Async::Ready(None)) => Ok(Async::Ready(None)),
Ok(Async::NotReady) => Ok(Async::NotReady),
Err(e) => Err(e),
}
}
}