use std::fs::File;
use std::io;
use std::io::{Read, Write};
const PATH: &str = "/sys/class/gpio";
#[derive(Debug, Copy, Clone)]
pub struct Gpio {
pin: u32,
}
impl Gpio {
pub fn new(pin: u32) -> Result<Self, io::Error> {
assert!(pin <= 40, "Invalid GPIO pin identifier (must be < 40)");
Self { pin: pin }.init()
}
pub fn write(&self, value: bool) -> Result<(), io::Error> {
let mut stream = File::create(self.gpio_file("value"))?;
write!(stream, "{}", value as i8)
}
pub fn read(&self) -> Result<bool, io::Error> {
let mut stream = File::open(self.gpio_file("value"))?;
let mut retrieved = String::new();
stream.read_to_string(&mut retrieved)?;
Ok(retrieved.parse::<bool>().expect("Invalid GPIO file value"))
}
pub fn pin(&self) -> u32 {
self.pin
}
}
impl Gpio {
fn init(self) -> Result<Self, io::Error> {
let mut stream = File::create(format!("{}/export", PATH))?;
write!(stream, "{}", self.pin)?;
let mut stream = File::create(self.gpio_file("direction"))?;
write!(stream, "out")?;
Ok(self)
}
fn gpio_file(&self, filename: &str) -> String {
match filename {
"value" => {}
"direction" => {}
_ => panic!(),
}
format!("{}/gpio{}/{}", PATH, self.pin, filename)
}
}