This commit is contained in:
2026-01-19 09:42:16 +01:00
parent 45c332e610
commit 251d245aeb
6 changed files with 43 additions and 89 deletions

View File

@@ -1,4 +1,20 @@
#[axum::debug_handler]
pub async fn create_alarm() -> String {
"hello world".to_string()
use axum::{Json, extract::State};
use serde::{Deserialize, Serialize};
use crate::{AppState};
#[derive(Deserialize, Serialize)]
pub struct CreateAlarmRequest {
hour: String,
minute: String,
}
#[axum::debug_handler]
pub async fn create_alarm(State(state): State<AppState>, Json(alarm): Json<CreateAlarmRequest>) -> String {
let result = state.scheduler.add_alarm(alarm.hour.as_str(), alarm.minute.as_str());
match result {
Ok(_) => "Alarm created".to_string(),
Err(e) => e.to_string(),
}
}

View File

@@ -2,6 +2,7 @@ use std::{
sync::{Arc, Mutex},
};
use chrono::{DateTime, Local};
use cron_tab::Cron;
use gpio_cdev::Chip;
@@ -12,6 +13,11 @@ mod router;
mod scheduler;
mod ringer;
struct Alarm {
enabled: bool,
time: DateTime<Local>
}
#[derive(Clone)]
struct AppState {
scheduler: Arc<Scheduler<BeepRinger>>
@@ -30,10 +36,8 @@ fn app_state() -> AppState {
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let static_time = "0 30 7 * * *";
let app_state = app_state();
app_state.scheduler.schedule(static_time)?;
app_state.scheduler.start();
start_server(app_state).await;

View File

@@ -9,11 +9,16 @@ use crate::ringer::Ringer;
pub struct Scheduler<T: Ringer + 'static> {
ringer: Arc<Mutex<T>>,
cron: Arc<Mutex<Cron<Local>>>,
alarms: Arc<Mutex<Vec<String>>>,
}
impl<T: Ringer> Scheduler<T> {
pub fn new(ringer: Arc<Mutex<T>>, cron: Arc<Mutex<Cron<Local>>>) -> Self {
Self { ringer, cron }
Self {
ringer,
cron,
alarms: Arc::new(Mutex::new(Vec::new())),
}
}
pub fn schedule(&self, cron_schedule: &str) -> Result<(), String> {
@@ -34,6 +39,15 @@ impl<T: Ringer> Scheduler<T> {
todo!()
}
pub fn add_alarm(&self, hour: &str, minute: &str) -> Result<(), String> {
let mut alarms = self.alarms.lock().map_err(|e| e.to_string())?;
let cron_schedule = format!("{} {} {} * * *", "*", minute, hour);
alarms.push(cron_schedule.clone());
println!("Added alarm {}", cron_schedule);
Ok(())
}
pub fn start(&self) {
self.cron.lock().expect("Failed to lock cron").start();
}