Created
April 12, 2015 23:35
-
-
Save wrl/a9c61e213e23913879dd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::env; | |
use std::path::Path; | |
extern crate nix; | |
use nix::fcntl::{O_RDWR, O_NONBLOCK}; | |
use nix::{fcntl,sys}; | |
extern crate mio; | |
use mio::{TryRead, TryWrite}; | |
mod devices; | |
fn read_from_device(dev: &mut mio::Io) { | |
let mut buf = [0u8; 128]; | |
let nbytes = match dev.read(&mut mio::buf::MutSliceBuf::wrap(&mut buf)) { | |
Err(why) => panic!("read failed: ???"), | |
Ok(nbytes) => nbytes.unwrap() | |
}; | |
let report_nr = buf[0]; | |
match report_nr { | |
_ => println!(" :: {:2X}: got {} bytes", report_nr, nbytes) | |
} | |
} | |
const DEVICE: mio::Token = mio::Token(0); | |
struct MaschineHandler<'a> { | |
dev: &'a mut mio::Io | |
} | |
impl<'a> mio::Handler for MaschineHandler<'a> { | |
type Timeout = (); | |
type Message = u32; | |
fn readable(&mut self, event_loop: &mut mio::EventLoop<MaschineHandler>, | |
token: mio::Token, _: mio::ReadHint) { | |
match token { | |
DEVICE => read_from_device(self.dev), | |
_ => panic!("unexpected token") | |
} | |
} | |
} | |
fn ev_loop(dev: &mut mio::Io) { | |
let mut event_loop = mio::EventLoop::new().unwrap(); | |
let mut handler = MaschineHandler { | |
dev: dev | |
}; | |
event_loop.register(dev, DEVICE).unwrap(); | |
event_loop.run(&mut handler); | |
} | |
fn usage(prog_name: &String) { | |
println!("usage: {} <hidraw device>", prog_name); | |
} | |
fn main() { | |
let args: Vec<_> = env::args().collect(); | |
if args.len() != 2 { | |
usage(&args[0]); | |
panic!("missing hidraw device path"); | |
} | |
let mut dev = match fcntl::open(Path::new(&args[1]), O_RDWR | O_NONBLOCK, | |
sys::stat::Mode::empty()) { | |
Err(why) => panic!("couldn't open {}: ????", args[1]), | |
Ok(file) => file | |
}; | |
let mut dev_io = mio::Io::new(dev); | |
ev_loop(&mut dev_io); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment