This commit is contained in:
irriden
2023-08-01 19:50:37 +00:00
parent 3503e36cf4
commit 65c94c6717
4 changed files with 101 additions and 19 deletions

View File

@@ -56,3 +56,25 @@ pub fn config_server(
server.start(&Default::default()) server.start(&Default::default())
} }
#[allow(unused_variables, deprecated)]
pub fn wifi_server(mutex: Arc<(Mutex<Option<Config>>, Condvar)>) -> Result<idf::Server> {
let server = idf::ServerRegistry::new()
.at("/config")
.post(move |request| {
let bod = &request
.query_string()
.ok_or(anyhow::anyhow!("failed to parse query string"))?;
println!("bod {:?}", bod);
let params = serde_urlencoded::from_str::<Params>(bod)?;
let config = serde_json::from_str::<Config>(&params.config)?;
let mut wait = mutex.0.lock().unwrap();
*wait = Some(config);
mutex.1.notify_one();
Ok("{\"success\":true}".to_owned().into())
})?;
server.start(&Default::default())
}

View File

@@ -111,3 +111,34 @@ pub fn start_config_server_and_wait(
config_seed_tuple.1.clone(), config_seed_tuple.1.clone(),
)) ))
} }
pub fn start_wifi_server_and_wait(
modem: impl peripheral::Peripheral<P = esp_idf_hal::modem::Modem> + 'static,
default_nvs: EspDefaultNvsPartition,
) -> Result<(BlockingWifi<EspWifi<'static>>, Config)> {
let mutex = Arc::new((Mutex::new(None), Condvar::new()));
#[allow(clippy::redundant_clone)]
#[allow(unused_mut)]
let mut wifi = conn::wifi::start_access_point(modem, default_nvs.clone())?;
let httpd = conn::http::wifi_server(mutex.clone());
let mut wait = mutex.0.lock().unwrap();
log::info!("Waiting for wifi creds from the phone!");
let config: &Config = loop {
if let Some(conf) = &*wait {
break conf;
} else {
wait = mutex
.1
.wait_timeout(wait, Duration::from_secs(1))
.unwrap()
.0;
}
};
drop(httpd);
println!("===> config! {:?}", config);
Ok((wifi, config.clone()))
}

View File

@@ -43,11 +43,6 @@ fn main() -> Result<()> {
// LED control thread // LED control thread
led_control_loop(pins.gpio0, peripherals.rmt.channel0, led_rx); led_control_loop(pins.gpio0, peripherals.rmt.channel0, led_rx);
// BUTTON thread
// button_loop(pins.gpio9, led_tx.clone());
// thread::sleep(Duration::from_secs(100));
led_tx.send(Status::MountingSDCard).unwrap(); led_tx.send(Status::MountingSDCard).unwrap();
println!("About to mount the sdcard..."); println!("About to mount the sdcard...");
while let Err(_e) = mount_sd_card() { while let Err(_e) = mount_sd_card() {
@@ -59,12 +54,17 @@ fn main() -> Result<()> {
// let default_nav_partition = EspDefaultNvs.take().unwrap(); // let default_nav_partition = EspDefaultNvs.take().unwrap();
let default_nvs = EspDefaultNvsPartition::take()?; let default_nvs = EspDefaultNvsPartition::take()?;
// let default_nvs = Arc::new(); // let default_nvs = Arc::new();
let mut flash = FlashPersister::new(default_nvs.clone()); let flash_per = FlashPersister::new(default_nvs.clone());
let flash_arc = Arc::new(Mutex::new(flash_per));
// BUTTON thread
button_loop(pins.gpio9, led_tx.clone(), flash_arc.clone());
let mut flash = flash_arc.lock().unwrap();
if let Ok(exist) = flash.read_config() { if let Ok(exist) = flash.read_config() {
let seed = flash.read_seed().expect("no seed..."); let seed = flash.read_seed().expect("no seed...");
let id = flash.read_id().expect("no id..."); let id = flash.read_id().expect("no id...");
let policy = flash.read_policy().unwrap_or_default(); let policy = flash.read_policy().unwrap_or_default();
let velocity = flash.read_velocity().ok(); let velocity = flash.read_velocity().ok();
drop(flash);
println!( println!(
"=============> START CLIENT NOW <============== {:?}", "=============> START CLIENT NOW <============== {:?}",
exist exist
@@ -95,7 +95,6 @@ fn main() -> Result<()> {
led_tx.send(Status::ConnectingToMqtt).unwrap(); led_tx.send(Status::ConnectingToMqtt).unwrap();
let flash_arc = Arc::new(Mutex::new(flash));
loop { loop {
if let Ok(()) = make_and_launch_client( if let Ok(()) = make_and_launch_client(
exist.clone(), exist.clone(),
@@ -116,17 +115,30 @@ fn main() -> Result<()> {
} else { } else {
led_tx.send(Status::WifiAccessPoint).unwrap(); led_tx.send(Status::WifiAccessPoint).unwrap();
println!("=============> START SERVER NOW AND WAIT <=============="); println!("=============> START SERVER NOW AND WAIT <==============");
match start_config_server_and_wait(peripherals.modem, default_nvs.clone()) { if let Ok(_) = flash.read_seed() {
Ok((_wifi, config, seed)) => { match start_wifi_server_and_wait(peripherals.modem, default_nvs.clone()) {
flash.write_config(config).expect("could not store config"); Ok((_wifi, config)) => {
flash.write_seed(seed).expect("could not store seed"); flash.write_config(config).expect("could not store config");
flash drop(flash);
.write_id(random_word(ID_LEN)) println!("CONFIG SAVED");
.expect("could not store id"); unsafe { esp_idf_sys::esp_restart() };
println!("CONFIG SAVED"); }
unsafe { esp_idf_sys::esp_restart() }; Err(msg) => log::error!("{}", msg),
}
} else {
match start_config_server_and_wait(peripherals.modem, default_nvs.clone()) {
Ok((_wifi, config, seed)) => {
flash.write_config(config).expect("could not store config");
flash.write_seed(seed).expect("could not store seed");
flash
.write_id(random_word(ID_LEN))
.expect("could not store id");
drop(flash);
println!("CONFIG SAVED");
unsafe { esp_idf_sys::esp_restart() };
}
Err(msg) => log::error!("{}", msg),
} }
Err(msg) => log::error!("{}", msg),
} }
} }

View File

@@ -1,7 +1,9 @@
use crate::status::Status; use crate::status::Status;
use crate::FlashPersister;
use esp_idf_hal::gpio; use esp_idf_hal::gpio;
use esp_idf_hal::gpio::*; use esp_idf_hal::gpio::*;
use std::sync::mpsc; use sphinx_signer::sphinx_glyph::control::ControlPersist;
use std::sync::{mpsc, Arc, Mutex};
use std::thread; use std::thread;
use std::time::Duration; use std::time::Duration;
@@ -11,7 +13,11 @@ const PAUSE: u16 = 50;
// progression is waiting -> *starting -> reset1a -> reset1 -> reset2a -> reset2 -> reset3 // progression is waiting -> *starting -> reset1a -> reset1 -> reset2a -> reset2 -> reset3
// state machine initialized at starting // state machine initialized at starting
pub fn button_loop(gpio9: gpio::Gpio9, tx: mpsc::Sender<Status>) { pub fn button_loop(
gpio9: gpio::Gpio9,
tx: mpsc::Sender<Status>,
flash_arc: Arc<Mutex<FlashPersister>>,
) {
thread::spawn(move || { thread::spawn(move || {
let mut button = PinDriver::input(gpio9).unwrap(); let mut button = PinDriver::input(gpio9).unwrap();
button.set_pull(Pull::Up).unwrap(); button.set_pull(Pull::Up).unwrap();
@@ -21,6 +27,17 @@ pub fn button_loop(gpio9: gpio::Gpio9, tx: mpsc::Sender<Status>) {
let mut machine = Machine::new(tx, Status::Starting); let mut machine = Machine::new(tx, Status::Starting);
loop { loop {
// we are using thread::sleep here to make sure the watchdog isn't triggered // we are using thread::sleep here to make sure the watchdog isn't triggered
if machine.state == Status::Reset3 {
let mut flash = flash_arc.lock().unwrap();
if let Err(_e) = flash.remove_config() {
log::error!("could not clear wifi config");
drop(flash);
} else {
log::info!("restarting esp!");
drop(flash);
unsafe { esp_idf_sys::esp_restart() };
}
}
thread::sleep(Duration::from_millis(PAUSE.into())); thread::sleep(Duration::from_millis(PAUSE.into()));
if button.is_high() { if button.is_high() {
if pressed { if pressed {