Skip to content

Commit f9ee6b4

Browse files
committed
Add asynchronous line event stream for Tokio.
1 parent 1e69adc commit f9ee6b4

File tree

4 files changed

+202
-0
lines changed

4 files changed

+202
-0
lines changed

Cargo.toml

+12
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,23 @@ readme = "README.md"
99
categories = ["embedded", "hardware-support", "os", "os::unix-apis"]
1010
keywords = ["linux", "gpio", "gpiochip", "embedded"]
1111
license = "MIT OR Apache-2.0"
12+
edition = "2018"
13+
14+
[features]
15+
default = []
16+
async-tokio = ["tokio", "futures", "mio"]
17+
18+
[[example]]
19+
name = "async_tokio"
20+
required-features = ["async-tokio"]
1221

1322
[dependencies]
1423
bitflags = "1.0"
1524
libc = "0.2"
1625
nix = "0.14"
26+
tokio = { version = "0.2", features = ["io-driver", "rt-threaded", "macros"], optional = true }
27+
futures = { version = "0.3", optional = true }
28+
mio = { version = "0.6", optional = true }
1729

1830
[dev-dependencies]
1931
quicli = "0.2"

examples/async_tokio.rs

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Copyright (c) 2018 The rust-gpio-cdev Project Developers.
2+
//
3+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6+
// option. This file may not be copied, modified, or distributed
7+
// except according to those terms.
8+
9+
use futures::stream::StreamExt;
10+
use gpio_cdev::*;
11+
use quicli::prelude::*;
12+
13+
#[derive(Debug, StructOpt)]
14+
struct Cli {
15+
/// The gpiochip device (e.g. /dev/gpiochip0)
16+
chip: String,
17+
/// The offset of the GPIO line for the provided chip
18+
line: u32,
19+
}
20+
21+
async fn do_main(args: Cli) -> std::result::Result<(), errors::Error> {
22+
let mut chip = Chip::new(args.chip)?;
23+
let line = chip.get_line(args.line)?;
24+
let mut events = AsyncLineEventHandle::new(line.events(
25+
LineRequestFlags::INPUT,
26+
EventRequestFlags::BOTH_EDGES,
27+
"gpioevents",
28+
)?)?;
29+
30+
loop {
31+
match events.next().await {
32+
Some(event) => println!("{:?}", event?),
33+
None => break,
34+
};
35+
}
36+
37+
Ok(())
38+
}
39+
40+
#[tokio::main]
41+
async fn main() {
42+
let args = Cli::from_args();
43+
do_main(args).await.unwrap();
44+
}

src/async_tokio.rs

+125
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
// Copyright (c) 2018 The rust-gpio-cdev Project Developers.
2+
//
3+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6+
// option. This file may not be copied, modified, or distributed
7+
// except according to those terms.
8+
9+
//! Wrapper for asynchronous programming using Tokio.
10+
11+
use futures::ready;
12+
use futures::stream::Stream;
13+
use futures::task::{Context, Poll};
14+
use mio::event::Evented;
15+
use mio::unix::EventedFd;
16+
use mio::{PollOpt, Ready, Token};
17+
use tokio::io::PollEvented;
18+
19+
use std::io;
20+
use std::os::unix::io::AsRawFd;
21+
use std::pin::Pin;
22+
23+
use super::Result;
24+
use super::{LineEvent, LineEventHandle};
25+
26+
struct PollWrapper {
27+
handle: LineEventHandle,
28+
}
29+
30+
impl Evented for PollWrapper {
31+
fn register(
32+
&self,
33+
poll: &mio::Poll,
34+
token: Token,
35+
interest: Ready,
36+
opts: PollOpt,
37+
) -> io::Result<()> {
38+
EventedFd(&self.handle.file.as_raw_fd()).register(poll, token, interest, opts)
39+
}
40+
41+
fn reregister(
42+
&self,
43+
poll: &mio::Poll,
44+
token: Token,
45+
interest: Ready,
46+
opts: PollOpt,
47+
) -> io::Result<()> {
48+
EventedFd(&self.handle.file.as_raw_fd()).reregister(poll, token, interest, opts)
49+
}
50+
51+
fn deregister(&self, poll: &mio::Poll) -> io::Result<()> {
52+
EventedFd(&self.handle.file.as_raw_fd()).deregister(poll)
53+
}
54+
}
55+
56+
/// Wrapper around a `LineEventHandle` which implements a `futures::stream::Stream` for interrupts.
57+
///
58+
/// # Example
59+
///
60+
/// The following example waits for state changes on an input line.
61+
///
62+
/// ```no_run
63+
/// # type Result<T> = std::result::Result<T, gpio_cdev::errors::Error>;
64+
/// use futures::stream::StreamExt;
65+
/// use gpio_cdev::{AsyncLineEventHandle, Chip, EventRequestFlags, LineRequestFlags};
66+
///
67+
/// async fn print_events(line: u32) -> Result<()> {
68+
/// let mut chip = Chip::new("/dev/gpiochip0")?;
69+
/// let line = chip.get_line(line)?;
70+
/// let mut events = AsyncLineEventHandle::new(line.events(
71+
/// LineRequestFlags::INPUT,
72+
/// EventRequestFlags::BOTH_EDGES,
73+
/// "gpioevents",
74+
/// )?)?;
75+
///
76+
/// loop {
77+
/// match events.next().await {
78+
/// Some(event) => println!("{:?}", event?),
79+
/// None => break,
80+
/// };
81+
/// }
82+
///
83+
/// Ok(())
84+
/// }
85+
///
86+
/// # #[tokio::main]
87+
/// # async fn main() {
88+
/// # print_events(42).await.unwrap();
89+
/// # }
90+
/// ```
91+
pub struct AsyncLineEventHandle {
92+
evented: PollEvented<PollWrapper>,
93+
}
94+
95+
impl AsyncLineEventHandle {
96+
/// Wraps the specified `LineEventHandle`.
97+
///
98+
/// # Arguments
99+
///
100+
/// * `handle` - handle to be wrapped.
101+
pub fn new(handle: LineEventHandle) -> Result<AsyncLineEventHandle> {
102+
Ok(AsyncLineEventHandle {
103+
evented: PollEvented::new(PollWrapper { handle })?,
104+
})
105+
}
106+
}
107+
108+
impl Stream for AsyncLineEventHandle {
109+
type Item = Result<LineEvent>;
110+
111+
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
112+
let ready = Ready::readable();
113+
if let Err(e) = ready!(self.evented.poll_read_ready(cx, ready)) {
114+
return Poll::Ready(Some(Err(e.into())));
115+
}
116+
117+
Poll::Ready(self.evented.get_mut().handle.next())
118+
}
119+
}
120+
121+
impl AsRef<LineEventHandle> for AsyncLineEventHandle {
122+
fn as_ref(&self) -> &LineEventHandle {
123+
&self.evented.get_ref().handle
124+
}
125+
}

src/lib.rs

+21
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,12 @@ extern crate bitflags;
8989
extern crate libc;
9090
#[macro_use]
9191
extern crate nix;
92+
#[cfg(feature = "async-tokio")]
93+
extern crate futures;
94+
#[cfg(feature = "async-tokio")]
95+
extern crate mio;
96+
#[cfg(feature = "async-tokio")]
97+
extern crate tokio;
9298

9399
use std::cmp::min;
94100
use std::ffi::CStr;
@@ -101,9 +107,13 @@ use std::ptr;
101107
use std::slice;
102108
use std::sync::Arc;
103109

110+
#[cfg(feature = "async-tokio")]
111+
mod async_tokio;
104112
pub mod errors;
105113
mod ffi;
106114

115+
#[cfg(feature = "async-tokio")]
116+
pub use crate::async_tokio::AsyncLineEventHandle;
107117
use errors::*;
108118

109119
unsafe fn rstr_lcpy(dst: *mut libc::c_char, src: &str, length: usize) {
@@ -550,6 +560,17 @@ impl Line {
550560
file: unsafe { File::from_raw_fd(request.fd) },
551561
})
552562
}
563+
564+
#[cfg(feature = "async-tokio")]
565+
pub fn async_events(
566+
&self,
567+
handle_flags: LineRequestFlags,
568+
event_flags: EventRequestFlags,
569+
consumer: &str,
570+
) -> Result<AsyncLineEventHandle> {
571+
let events = self.events(handle_flags, event_flags, consumer)?;
572+
Ok(AsyncLineEventHandle::new(events)?)
573+
}
553574
}
554575

555576
impl LineInfo {

0 commit comments

Comments
 (0)