feat: Create GPIO monitor and basic callback functionality to print
This commit is contained in:
parent
9b74fb2b8c
commit
18aa3dfaa8
7 changed files with 616 additions and 0 deletions
49
src/gpio.rs
Normal file
49
src/gpio.rs
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
use std::time::Duration;
|
||||
|
||||
use anyhow::Result;
|
||||
use rppal::gpio::{Gpio, InputPin, Level};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CircuitEvent {
|
||||
Open,
|
||||
Closed,
|
||||
}
|
||||
|
||||
pub struct GpioMonitor {
|
||||
pin: InputPin,
|
||||
poll_interval: Duration,
|
||||
}
|
||||
|
||||
impl GpioMonitor {
|
||||
pub fn new(pin_number: u8, poll_interval: Duration) -> Result<Self> {
|
||||
let gpio = Gpio::new()?;
|
||||
let pin = gpio.get(pin_number)?.into_input_pullup();
|
||||
|
||||
Ok(Self { pin, poll_interval })
|
||||
}
|
||||
|
||||
pub async fn monitor<F>(&mut self, mut callback: F) -> Result<()>
|
||||
where
|
||||
F: FnMut(CircuitEvent) + Send + 'static,
|
||||
{
|
||||
let mut previous_state = self.get_current_state();
|
||||
|
||||
loop {
|
||||
let current_state = self.get_current_state();
|
||||
|
||||
if current_state != previous_state {
|
||||
callback(current_state);
|
||||
previous_state = current_state;
|
||||
}
|
||||
|
||||
tokio::time::sleep(self.poll_interval).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_current_state(&self) -> CircuitEvent {
|
||||
match self.pin.read() {
|
||||
Level::High => CircuitEvent::Open,
|
||||
Level::Low => CircuitEvent::Closed,
|
||||
}
|
||||
}
|
||||
}
|
||||
33
src/main.rs
Normal file
33
src/main.rs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
mod gpio;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Result;
|
||||
use tracing::{error, info};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
// Initialize logging
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
// Initialize GPIO monitor
|
||||
const DEFAULT_GPIO_PIN: u8 = 17;
|
||||
let gpio_pin = std::env::var("GPIO_PIN")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(DEFAULT_GPIO_PIN);
|
||||
|
||||
let mut gpio_monitor = gpio::GpioMonitor::new(gpio_pin, Duration::from_millis(100))?;
|
||||
|
||||
// Simple callback function that just logs the event
|
||||
let callback = |event: gpio::CircuitEvent| {
|
||||
info!("Circuit state changed: {:?}", event);
|
||||
};
|
||||
|
||||
// Start GPIO monitoring
|
||||
if let Err(e) = gpio_monitor.monitor(callback).await {
|
||||
error!("GPIO monitoring error: {}", e);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue