Skip to content

Commit

Permalink
Use iso8601
Browse files Browse the repository at this point in the history
  • Loading branch information
fangpenlin committed Jan 6, 2025
1 parent 0958d79 commit 808f23b
Show file tree
Hide file tree
Showing 4 changed files with 105 additions and 49 deletions.
64 changes: 54 additions & 10 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ embassy-sync = "0.6.1"
anyhow = "1.0.95"
futures = "0.3.31"
serde = { version = "1.0.217", features = ["derive"] }
serde_millis = "0.1.1"
serde_json = "1.0.134"
time = { version = "0.3.37", features = ["std", "serde-human-readable"] }

[[package.metadata.esp-idf-sys.extra_components]]
remote_component = { name = "espressif/esp_tinyusb", version = "96cbb5b308f92d2493a0c714f097dcfc51add807", git = "https://github.com/LaunchPlatform/esp-usb.git", path = "device/esp_tinyusb" }
Expand Down
50 changes: 25 additions & 25 deletions src/api/processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ use esp_idf_svc::ping::Info;
use serde::{Deserialize, Serialize};
use std::io::{Read, Seek};
use std::mem::MaybeUninit;
use std::time;
use std::time::Instant;
use std::time::SystemTime;
use time::serde::iso8601;
use time::OffsetDateTime;

#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(tag = "type")]
Expand All @@ -22,21 +23,21 @@ pub enum Command {
pub struct File {
path: String,
size: u64,
#[serde(with = "serde_millis")]
modified_at: Instant,
#[serde(with = "serde_millis")]
created_at: Instant,
#[serde(with = "iso8601")]
modified_at: OffsetDateTime,
#[serde(with = "iso8601")]
created_at: OffsetDateTime,
is_dir: bool,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DeviceInfo {
version: String,
wifi_ip: String,
#[serde(with = "serde_millis")]
local_time: time::Instant,
disk_size: u64,
disk_usage: u64,
pub version: String,
pub wifi_ip: String,
#[serde(with = "iso8601")]
pub local_time: OffsetDateTime,
pub disk_size: u64,
pub disk_usage: u64,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
Expand Down Expand Up @@ -72,13 +73,15 @@ pub struct CommandResponse<'a> {
pub response: Response<'a>,
}

pub type DeviceInfoProducer = Box<dyn Fn() -> anyhow::Result<DeviceInfo>>;

pub struct Processor {
pub info_producer: Box<dyn Fn() -> anyhow::Result<DeviceInfo>>,
pub device_info_producer: DeviceInfoProducer,
}

impl Processor {
fn get_info(&self) -> anyhow::Result<Response> {
let result = (self.info_producer)();
let result = (self.device_info_producer)();
if let Ok(device_info) = &result {
log::info!("Get device info {device_info:#?}");
}
Expand Down Expand Up @@ -151,8 +154,13 @@ impl Processor {
}
}

pub async fn process_events(mut client: WebSocketSession<'_>) {
let mut processor: Option<Box<Processor>> = None;
pub async fn process_events(
mut client: WebSocketSession<'_>,
device_info_producer: DeviceInfoProducer,
) {
let mut processor: Option<Box<Processor>> = Some(Box::new(Processor {
device_info_producer,
}));
client.connect();

loop {
Expand All @@ -165,15 +173,7 @@ pub async fn process_events(mut client: WebSocketSession<'_>) {
..
} => {
processor = Some(Box::new(Processor {
info_producer: Box::new(|| {
Ok(DeviceInfo {
version: "".to_string(),
wifi_ip: "".to_string(),
local_time: Instant::now(),
disk_size: 0,
disk_usage: 0,
})
}),
device_info_producer: processor.map(|p| p.device_info_producer).unwrap(),
}));
}
SessionEvent::ReceiveText { text } => {
Expand Down
38 changes: 25 additions & 13 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ mod api;
mod usb;
mod wifi;

use crate::api::websocket::{WebSocketSession, SessionEvent, ConnectionState};
use crate::api::processor::{process_events, DeviceInfo, DeviceInfoProducer};
use crate::api::websocket::{ConnectionState, SessionEvent, WebSocketSession};
use crate::usb::msc_device::MSCDevice;
use crate::wifi::session::WifiSession;
use embedded_svc::wifi::AuthMethod;
Expand All @@ -11,21 +12,22 @@ use esp_idf_svc::hal::gpio::{PinDriver, Pull};
use esp_idf_svc::hal::prelude::Peripherals;
use futures::executor::{LocalPool, LocalSpawner};
use futures::task::LocalSpawnExt;
use std::{thread, time};
use crate::api::processor::process_events;
use std::rc::Rc;
use std::thread;
use std::time::Duration;
use time::OffsetDateTime;

const PKG_NAME: &str = env!("CARGO_PKG_NAME");
const VERSION: &str = env!("CARGO_PKG_VERSION");

const SSID: &str = env!("WIFI_SSID");
const PASSWORD: &str = env!("WIFI_PASS");
const API_ENDPOINT: &str = env!("API_ENDPOINT");

async fn run_async(spawner: LocalSpawner) -> Result<(), anyhow::Error> {
log::info!(
"Start {} - {}",
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_VERSION")
);
log::info!("Start {} - {}", PKG_NAME, VERSION,);

let peripherals = Peripherals::take().expect("@@@ Take Peripherals failed");
let peripherals = Peripherals::take()?;
let mut wifi = WifiSession::new(SSID, PASSWORD, AuthMethod::WPA2Personal, peripherals.modem)?;
wifi.connect().await?;
log::info!("Connected wifi: {:#?}", wifi.get_ip_info());
Expand All @@ -36,14 +38,24 @@ async fn run_async(spawner: LocalSpawner) -> Result<(), anyhow::Error> {
let mut button = PinDriver::input(peripherals.pins.gpio14)?;
button.set_pull(Pull::Up)?;

let mut client = WebSocketSession::new(API_ENDPOINT, time::Duration::from_secs(30));
let mut client = WebSocketSession::new(API_ENDPOINT, Duration::from_secs(30));

let device_info_producer: DeviceInfoProducer = Box::new(move || {
Ok(DeviceInfo {
version: VERSION.to_string(),
// TODO: maybe pass in Rc of wifi instead?
wifi_ip: wifi.get_ip_info().unwrap().ip.to_string(),
local_time: OffsetDateTime::now_utc(),
// TODO:
disk_size: 0,
disk_usage: 0,
})
});

// Asynchronously wait for GPIO events, allowing other tasks
// to run, or the core to sleep.
button.wait_for_low().await?;
log::info!("Button pressed!");

spawner.spawn_local(process_events(client))?;
spawner.spawn_local(process_events(client, device_info_producer))?;

loop {
// Asynchronously wait for GPIO events, allowing other tasks
Expand Down

0 comments on commit 808f23b

Please sign in to comment.