1
0
Fork 0
spaceapi-tuerpie-nix/src/main.rs

77 lines
2.5 KiB
Rust
Raw Normal View History

use std::env;
use std::thread::sleep;
use std::time::Duration;
use rppal::gpio::{Gpio, InputPin, Level};
use spaceapi_dezentrale_client::Client;
// set your scripts for opening and closing the space here
static DOOR_PIN: u8 = 27;
// delays in seconds
static RECHECK_DELAY: u64 = 5;
static ANTI_BOUNCE_DELAY: u64 = 1;
2023-04-21 17:10:17 +00:00
2024-01-05 00:14:41 +00:00
#[tokio::main]
async fn main() {
// setup
2023-04-21 17:10:17 +00:00
let gpio = Gpio::new().unwrap();
let pin = gpio.get(DOOR_PIN).unwrap().into_input();
2023-04-21 17:10:17 +00:00
let spaceapi_client = spaceapi_dezentrale_client::ClientBuilder::new()
.api_key(&env::var("API_KEY").unwrap())
.base_url(&env::var("SPACEAPI_URL").unwrap())
.build()
.unwrap();
// get initial door status
let mut door_status_old = check_door(&pin);
2024-01-05 00:14:41 +00:00
let _ = push_door_status(&spaceapi_client, door_status_old).await;
2023-04-21 17:10:17 +00:00
loop {
// maybe not the best solution but the pi isn't doing anything else
log::debug!("Waiting {} secs to read the door status", RECHECK_DELAY);
sleep(Duration::from_secs(RECHECK_DELAY));
// read new status
let door_status_new = check_door(&pin);
log::debug!("Read {}", door_status_new);
// if the new status isn't the old one
if door_status_old != door_status_new {
// wait for the switch to stop bouncing around
log::debug!("Waiting {} secs for recheck", ANTI_BOUNCE_DELAY);
sleep(Duration::from_secs(ANTI_BOUNCE_DELAY));
// the new read status is still the same after a minute then push it to the api
if door_status_new == check_door(&pin) {
log::debug!("Check passed, applying new status");
log::debug!("Pushing space status: Open = {}", door_status_new);
2024-01-05 00:14:41 +00:00
let _ = push_door_status(&spaceapi_client, door_status_new)
.await
.map_err(|err| format!("Problem while pushing door status: {err}")) ;
log::debug!("Saving space status: {}", door_status_new);
door_status_old = door_status_new;
} else {
log::debug!("Check wasn't successful")
}
2023-04-21 17:10:17 +00:00
}
}
}
fn check_door(pin: &InputPin) -> bool {
// reading space status from door
pin.read() == Level::Low
}
2024-01-05 00:14:41 +00:00
async fn push_door_status(spaceapi: &Client, open: bool) -> Result<(), String> {
if open {
2024-01-05 00:14:41 +00:00
spaceapi
.keep_open()
.await
2024-01-05 00:14:41 +00:00
.map(|_| ())
} else {
spaceapi
.close()
.await
}
}