use std::fmt;
use std::sync::{Mutex, PoisonError};
use crate::board;
use crate::error;
#[derive(Clone, PartialEq, Eq)]
pub struct Credentials {
pub ssid: String,
pub psk: String,
}
impl fmt::Debug for Credentials {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Credentials")
.field("ssid", &self.ssid)
.field("psk", &format_args!("<{} bytes>", self.psk.len()))
.finish()
}
}
static ACTIVE: Mutex<Option<String>> = Mutex::new(None);
pub fn begin(name: &str) -> bool {
let ok = error::ok(board::with(|b| b.provision_begin(name)));
if ok {
*ACTIVE.lock().unwrap_or_else(PoisonError::into_inner) = Some(name.to_owned());
}
ok
}
#[must_use]
pub fn active() -> bool {
ACTIVE
.lock()
.unwrap_or_else(PoisonError::into_inner)
.is_some()
}
#[must_use]
pub fn poll() -> Option<Credentials> {
board::with(|b| b.provision_poll())
.ok()
.flatten()
.map(|(ssid, psk)| Credentials { ssid, psk })
}
pub fn report(joined: bool) -> bool {
let ok = error::ok(board::with(|b| b.provision_report(joined)));
if ok && joined {
*ACTIVE.lock().unwrap_or_else(PoisonError::into_inner) = None;
}
ok
}
pub fn store(credentials: &Credentials) -> bool {
error::ok(board::with(|b| {
b.store_settings(&credentials.ssid, &credentials.psk)
}))
}