Skip to content

Closes: #25 - manually implement errors #26

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 25, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ license = "MIT OR Apache-2.0"

[dependencies]
bitflags = "1.0"
error-chain = "0.12"
libc = "0.2"
nix = "0.14"

[dev-dependencies]
quicli = "0.2"
anyhow = "1.0"
3 changes: 2 additions & 1 deletion examples/blinky.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use quicli::prelude::*;
use std::thread::sleep;
use std::time::{Duration, Instant};


#[derive(Debug, StructOpt)]
struct Cli {
/// The gpiochip device (e.g. /dev/gpiochip0)
Expand All @@ -27,7 +28,7 @@ struct Cli {
duration_ms: u64,
}

fn do_main(args: Cli) -> errors::Result<()> {
fn do_main(args: Cli) -> std::result::Result<(), errors::Error> {
let mut chip = Chip::new(args.chip)?;

// NOTE: we set the default value to the desired state so
Expand Down
2 changes: 1 addition & 1 deletion examples/driveoutput.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ struct Cli {
value: u8,
}

fn do_main(args: Cli) -> errors::Result<()> {
fn do_main(args: Cli) -> std::result::Result<(), errors::Error> {
let mut chip = Chip::new(args.chip)?;

// NOTE: we set the default value to the desired state so
Expand Down
3 changes: 2 additions & 1 deletion examples/gpioevents.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ extern crate quicli;
use gpio_cdev::*;
use quicli::prelude::*;


#[derive(Debug, StructOpt)]
struct Cli {
/// The gpiochip device (e.g. /dev/gpiochip0)
Expand All @@ -21,7 +22,7 @@ struct Cli {
line: u32,
}

fn do_main(args: Cli) -> errors::Result<()> {
fn do_main(args: Cli) -> std::result::Result<(), errors::Error> {
let mut chip = Chip::new(args.chip)?;
let line = chip.get_line(args.line)?;

Expand Down
50 changes: 32 additions & 18 deletions examples/monitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@

extern crate gpio_cdev;
extern crate nix;
#[macro_use] extern crate quicli;
#[macro_use]
extern crate quicli;
extern crate anyhow;

use gpio_cdev::*;
use quicli::prelude::*;
use nix::poll::*;
use std::os::unix::io::{AsRawFd};
use quicli::prelude::*;
use std::os::unix::io::AsRawFd;

type PollEventFlags = nix::poll::PollFlags;

Expand All @@ -25,27 +27,40 @@ struct Cli {
lines: Vec<u32>,
}

fn do_main(args: Cli) -> errors::Result<()> {
fn do_main(args: Cli) -> anyhow::Result<()> {
let mut chip = Chip::new(args.chip)?;

// Get event handles for each line to monitor.
let mut evt_handles: Vec<LineEventHandle> = args.lines.into_iter().map(|off| {
let line = chip.get_line(off).unwrap();
line.events(LineRequestFlags::INPUT, EventRequestFlags::BOTH_EDGES,
"monitor").unwrap()
}).collect();
let mut evt_handles: Vec<LineEventHandle> = args
.lines
.into_iter()
.map(|off| {
let line = chip.get_line(off).unwrap();
line.events(
LineRequestFlags::INPUT,
EventRequestFlags::BOTH_EDGES,
"monitor",
)
.unwrap()
})
.collect();

// Create a vector of file descriptors for polling
let mut pollfds: Vec<PollFd> = evt_handles.iter().map(|h| {
PollFd::new(h.as_raw_fd(), PollEventFlags::POLLIN | PollEventFlags::POLLPRI)
}).collect();
let mut pollfds: Vec<PollFd> = evt_handles
.iter()
.map(|h| {
PollFd::new(
h.as_raw_fd(),
PollEventFlags::POLLIN | PollEventFlags::POLLPRI,
)
})
.collect();

loop {
// poll for an event on any of the lines
if poll(&mut pollfds, -1)? == 0 {
println!("Timeout?!?");
}
else {
} else {
for i in 0..pollfds.len() {
if let Some(revts) = pollfds[i].revents() {
let h = &mut evt_handles[i];
Expand All @@ -58,9 +73,8 @@ fn do_main(args: Cli) -> errors::Result<()> {
// to read the value of the bit.
let val = h.get_value()?;
println!(" {}", val);
}
else if revts.contains(PollEventFlags::POLLPRI) {
println!("[{}] Got a POLLPRI", h.line().offset());
} else if revts.contains(PollEventFlags::POLLPRI) {
println!("[{}] Got a POLLPRI", h.line().offset());
}
}
}
Expand All @@ -70,7 +84,7 @@ fn do_main(args: Cli) -> errors::Result<()> {

main!(|args: Cli| {
match do_main(args) {
Ok(()) => {},
Ok(()) => {}
Err(e) => {
println!("Error: {:?}", e);
}
Expand Down
2 changes: 1 addition & 1 deletion examples/multioutput.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ struct Cli {
// to set lines 0, 1, & 3 high
// 2 & 4 low
//
fn do_main(args: Cli) -> errors::Result<()> {
fn do_main(args: Cli) -> std::result::Result<(), errors::Error> {
let mut chip = Chip::new(args.chip)?;
let mut offsets = Vec::new();
let mut values = Vec::new();
Expand Down
2 changes: 1 addition & 1 deletion examples/multiread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ struct Cli {
lines: Vec<u32>,
}

fn do_main(args: Cli) -> errors::Result<()> {
fn do_main(args: Cli) -> std::result::Result<(), errors::Error> {
let mut chip = Chip::new(args.chip)?;
let ini_vals = vec![ 0; args.lines.len() ];
let handle = chip
Expand Down
4 changes: 2 additions & 2 deletions examples/readall.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ struct Cli {
chip: String,
}

fn do_main(args: Cli) -> errors::Result<()> {
fn do_main(args: Cli) -> std::result::Result<(), errors::Error> {
let mut chip = Chip::new(args.chip)?;
let ini_vals = vec![ 0; chip.num_lines() as usize ];
let ini_vals = vec![0; chip.num_lines() as usize];
let handle = chip
.get_all_lines()?
.request(LineRequestFlags::INPUT, &ini_vals, "readall")?;
Expand Down
2 changes: 1 addition & 1 deletion examples/readinput.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ struct Cli {
line: u32,
}

fn do_main(args: Cli) -> errors::Result<()> {
fn do_main(args: Cli) -> std::result::Result<(), errors::Error> {
let mut chip = Chip::new(args.chip)?;
let handle = chip
.get_line(args.line)?
Expand Down
3 changes: 2 additions & 1 deletion examples/tit_for_tat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use quicli::prelude::*;
use std::thread::sleep;
use std::time::Duration;


#[derive(Debug, StructOpt)]
struct Cli {
/// The gpiochip device (e.g. /dev/gpiochip0)
Expand All @@ -27,7 +28,7 @@ struct Cli {
sleeptime: u64,
}

fn do_main(args: Cli) -> errors::Result<()> {
fn do_main(args: Cli) -> std::result::Result<(), errors::Error> {
let mut chip = Chip::new(args.chip)?;
let input = chip.get_line(args.inputline)?;
let output = chip.get_line(args.outputline)?;
Expand Down
118 changes: 99 additions & 19 deletions src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,101 @@
// Copyright (c) 2018 The rust-gpio-cdev Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

error_chain! {
types {
Error,
ErrorKind,
ResultExt,
Result;
}

foreign_links {
Nix(::nix::Error);
Io(::std::io::Error);
use std::error::Error as StdError;
use std::fmt;
use std::io::Error as IOError;

pub(crate) type Result<T> = std::result::Result<T, Error>;

#[derive(Debug)]
pub struct Error {
kind: ErrorKind,
}

#[derive(Debug)]
pub enum IoctlKind {
ChipInfo,
LineInfo,
LineHandle,
LineEvent,
GetLine,
SetLine,
}

#[derive(Debug)]
pub enum ErrorKind {
Event(nix::Error),
Io(IOError),
Ioctl { kind: IoctlKind, cause: nix::Error },
InvalidRequest(usize, usize),
Offset(u32),
}

pub(crate) fn ioctl_err(kind: IoctlKind, cause: nix::Error) -> Error {
Error {
kind: ErrorKind::Ioctl { kind, cause },
}
}

pub(crate) fn invalid_err(n_lines: usize, n_values: usize) -> Error {
Error {
kind: ErrorKind::InvalidRequest(n_lines, n_values),
}
}

pub(crate) fn offset_err(offset: u32) -> Error {
Error {
kind: ErrorKind::Offset(offset),
}
}

pub(crate) fn event_err(err: nix::Error) -> Error {
Error {
kind: ErrorKind::Event(err),
}
}

impl fmt::Display for IoctlKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
IoctlKind::ChipInfo => write!(f, "get chip info"),
IoctlKind::LineInfo => write!(f, "get line info"),
IoctlKind::LineHandle => write!(f, "get line handle"),
IoctlKind::LineEvent => write!(f, "get line event "),
IoctlKind::GetLine => write!(f, "get line value"),
IoctlKind::SetLine => write!(f, "set line value"),
}
}
}

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self.kind {
ErrorKind::Event(err) => write!(f, "Failed to read event: {}", err),
ErrorKind::Io(err) => err.fmt(f),
ErrorKind::Ioctl { cause, kind } => write!(f, "Ioctl to {} failed: {}", kind, cause),
ErrorKind::InvalidRequest(n_lines, n_values) => write!(
f,
"Invalid request: {} values requested to be set but only {} lines are open",
n_values, n_lines
),
ErrorKind::Offset(offset) => write!(f, "Offset {} is out of range", offset),
}
}
}

impl StdError for Error {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
match &self.kind {
ErrorKind::Event(err) => Some(err),
ErrorKind::Io(err) => Some(err),
ErrorKind::Ioctl { kind: _, cause } => Some(cause),
_ => None,
}
}
}

impl From<IOError> for Error {
fn from(err: IOError) -> Error {
Error {
kind: ErrorKind::Io(err),
}
}
}
55 changes: 49 additions & 6 deletions src/ffi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use super::errors::IoctlKind;
use libc;

pub const GPIOHANDLES_MAX: usize = 64;
Expand Down Expand Up @@ -56,10 +57,52 @@ pub struct gpioevent_data {
pub id: u32,
}

ioctl_read!(gpio_get_chipinfo_ioctl, 0xB4, 0x01, gpiochip_info);
ioctl_readwrite!(gpio_get_lineinfo_ioctl, 0xB4, 0x02, gpioline_info);
ioctl_readwrite!(gpio_get_linehandle_ioctl, 0xB4, 0x03, gpiohandle_request);
ioctl_readwrite!(gpio_get_lineevent_ioctl, 0xB4, 0x04, gpioevent_request);
macro_rules! wrap_ioctl {
($ioctl_macro:ident!($name:ident, $ioty:expr, $nr:expr, $ty:ident), $ioctl_error_type:expr) => {
mod $name {
$ioctl_macro!($name, $ioty, $nr, super::$ty);
}

ioctl_readwrite!(gpiohandle_get_line_values_ioctl, 0xB4, 0x08, gpiohandle_data);
ioctl_readwrite!(gpiohandle_set_line_values_ioctl, 0xB4, 0x09, gpiohandle_data);
pub(crate) fn $name(fd: libc::c_int, data: &mut $ty) -> crate::errors::Result<libc::c_int> {
unsafe {
$name::$name(fd, data).map_err(|e| crate::errors::ioctl_err($ioctl_error_type, e))
}
}
};
}

wrap_ioctl!(
ioctl_read!(gpio_get_chipinfo_ioctl, 0xB4, 0x01, gpiochip_info),
IoctlKind::ChipInfo
);
wrap_ioctl!(
ioctl_readwrite!(gpio_get_lineinfo_ioctl, 0xB4, 0x02, gpioline_info),
IoctlKind::LineInfo
);
wrap_ioctl!(
ioctl_readwrite!(gpio_get_linehandle_ioctl, 0xB4, 0x03, gpiohandle_request),
IoctlKind::LineHandle
);
wrap_ioctl!(
ioctl_readwrite!(gpio_get_lineevent_ioctl, 0xB4, 0x04, gpioevent_request),
IoctlKind::LineEvent
);

wrap_ioctl!(
ioctl_readwrite!(
gpiohandle_get_line_values_ioctl,
0xB4,
0x08,
gpiohandle_data
),
IoctlKind::GetLine
);
wrap_ioctl!(
ioctl_readwrite!(
gpiohandle_set_line_values_ioctl,
0xB4,
0x09,
gpiohandle_data
),
IoctlKind::SetLine
);
Loading