use crate::fat_error::{FatError, FatResult}; use crate::webserver::read_up_to_bytes_from_request; use crate::BOARD_ACCESS; use alloc::borrow::ToOwned; use alloc::string::{String, ToString}; use chrono::DateTime; use edge_http::io::server::Connection; use edge_nal::io::{Read, Write}; use log::info; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, PartialEq, Debug)] pub struct WebBackupHeader { timestamp: String, size: u16, } pub(crate) async fn get_backup_config( conn: &mut Connection<'_, T, { N }>, ) -> FatResult> where T: Read + Write, { let mut board = BOARD_ACCESS.get().await.lock().await; let backup = board.board_hal.read_backup().await?; // Second pass: stream data conn.initiate_response( 200, Some("OK"), &[ ("Access-Control-Allow-Origin", "*"), ("Access-Control-Allow-Headers", "*"), ("Access-Control-Allow-Methods", "*"), ], ) .await?; conn.write_all(serde_json::to_string(&backup)?.as_bytes()) .await?; Ok(Some(200)) } pub(crate) async fn backup_config( conn: &mut Connection<'_, T, N>, ) -> FatResult> where T: Read + Write, { let input = read_up_to_bytes_from_request(conn, Some(4096)).await?; info!("Read input with length {}", input.len()); let mut board = BOARD_ACCESS.get().await.lock().await; let config_to_backup = serde_json::from_slice(&input)?; info!("Parsed send config to object"); board.board_hal.backup_config(&config_to_backup).await?; Ok(Some("saved".to_owned())) } pub(crate) async fn backup_info( _request: &mut Connection<'_, T, N>, ) -> Result, FatError> where T: Read + Write, { let mut board = BOARD_ACCESS.get().await.lock().await; let info = board.board_hal.backup_info().await; let json = match info { Ok(h) => { info!("Got backup info: {:?}", h); let timestamp = DateTime::from_timestamp_millis(h.timestamp).unwrap_or_default(); let wbh = WebBackupHeader { timestamp: timestamp.to_rfc3339(), size: h.size, }; serde_json::to_string(&wbh)? } Err(err) => { info!("Error getting backup info: {:?}", err); let wbh = WebBackupHeader { timestamp: err.to_string(), size: 0, }; serde_json::to_string(&wbh)? } }; Ok(Some(json)) }