feat: refactor preference to accomodate wifi

Also setup framework to extend the main preference menu.
This commit is contained in:
Gianguido Sorà 2022-11-02 17:11:37 +01:00
parent 87cdfe5530
commit 4a4b49b0c8
2 changed files with 157 additions and 127 deletions

View file

@ -1,74 +1,77 @@
use core::{convert::TryFrom, fmt::Display}; use crate::wifi;
use num_traits::*;
use userprefs::{Manager, UserPrefs};
use std::io::Write;
use locales::t; use locales::t;
use num_traits::*;
use std::fmt::Display;
use userprefs::Manager;
pub trait PrefHandler {
// If handle() returns true, it has handled the operation.
fn handle(&mut self, op: usize) -> bool;
fn claim_menumatic_menu(&self, cid: xous::CID);
}
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive, PartialEq, PartialOrd)] #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive, PartialEq, PartialOrd)]
enum PrefsManOp { enum DevicePrefsOp {
RadioOnOnBoot, RadioOnOnBoot,
ConnectKnownNetworksOnBoot, ConnectKnownNetworksOnBoot,
AutobacklightOnBoot, AutobacklightOnBoot,
AutobacklightTimeout, AutobacklightTimeout,
WLANMenu,
} }
impl Display for PrefsManOp { impl Display for DevicePrefsOp {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self { match self {
Self::AutobacklightOnBoot => write!(f, "Autobacklight enabled on boot"), Self::AutobacklightOnBoot => write!(f, "Autobacklight enabled on boot"),
Self::AutobacklightTimeout => write!(f, "Autobacklight timeout"), Self::AutobacklightTimeout => write!(f, "Autobacklight timeout"),
Self::ConnectKnownNetworksOnBoot => write!(f, "Connect to known networks on boot"), Self::ConnectKnownNetworksOnBoot => write!(f, "Connect to known networks on boot"),
Self::RadioOnOnBoot => write!(f, "Enable WiFi on boot"), Self::RadioOnOnBoot => write!(f, "Enable WiFi on boot"),
Self::WLANMenu => write!(f, "WLAN settings"),
} }
} }
} }
#[derive(Debug)] #[derive(Debug)]
enum PrefsManError { enum DevicePrefsError {
PrefsError(userprefs::Error), PrefsError(userprefs::Error),
} }
impl From<userprefs::Error> for PrefsManError { impl From<userprefs::Error> for DevicePrefsError {
fn from(e: userprefs::Error) -> Self { fn from(e: userprefs::Error) -> Self {
Self::PrefsError(e) Self::PrefsError(e)
} }
} }
impl Display for PrefsManError { impl Display for DevicePrefsError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self { match self {
PrefsManError::PrefsError(e) => write!(f, "Preferences engine error: {:?}", e), DevicePrefsError::PrefsError(e) => write!(f, "Preferences engine error: {:?}", e),
} }
} }
} }
struct PrefsMan { struct DevicePrefs {
up: Manager, up: Manager,
modals: modals::Modals, modals: modals::Modals,
gam: gam::Gam,
} }
impl PrefsMan { impl PrefHandler for DevicePrefs {
fn new(xns: &xous_names::XousNames) -> Self { fn handle(&mut self, op: usize) -> bool {
Self { match FromPrimitive::from_usize(op) {
up: Manager::new(), Some(other) => {
modals: modals::Modals::new(&xns).unwrap(), self.consume_menu_action(other);
true
}
_ => {
log::error!("Got unknown message");
false
}
} }
} }
fn actions(&self) -> Vec<PrefsManOp> {
use PrefsManOp::*;
vec![
RadioOnOnBoot,
ConnectKnownNetworksOnBoot,
AutobacklightOnBoot,
AutobacklightTimeout,
]
}
fn claim_menumatic_menu(&self, cid: xous::CID) { fn claim_menumatic_menu(&self, cid: xous::CID) {
let mut menus = self let mut menus = self
.actions() .actions()
@ -92,19 +95,42 @@ impl PrefsMan {
gam::menu_matic(menus, gam::PREFERENCES_MENU_NAME, None); gam::menu_matic(menus, gam::PREFERENCES_MENU_NAME, None);
} }
}
fn consume_menu_action(&mut self, action: PrefsManOp) { impl DevicePrefs {
fn new(xns: &xous_names::XousNames) -> Self {
Self {
up: Manager::new(),
modals: modals::Modals::new(&xns).unwrap(),
gam: gam::Gam::new(&xns).unwrap(),
}
}
fn actions(&self) -> Vec<DevicePrefsOp> {
use DevicePrefsOp::*;
vec![
RadioOnOnBoot,
ConnectKnownNetworksOnBoot,
AutobacklightOnBoot,
AutobacklightTimeout,
WLANMenu,
]
}
fn consume_menu_action(&mut self, action: DevicePrefsOp) {
let resp = match action { let resp = match action {
PrefsManOp::AutobacklightOnBoot => self.autobacklight_on_boot(), DevicePrefsOp::AutobacklightOnBoot => self.autobacklight_on_boot(),
PrefsManOp::RadioOnOnBoot => self.radio_on_on_boot(), DevicePrefsOp::RadioOnOnBoot => self.radio_on_on_boot(),
PrefsManOp::ConnectKnownNetworksOnBoot => self.connect_known_networks_on_boot(), DevicePrefsOp::ConnectKnownNetworksOnBoot => self.connect_known_networks_on_boot(),
PrefsManOp::AutobacklightTimeout => self.autobacklight_timeout(), DevicePrefsOp::AutobacklightTimeout => self.autobacklight_timeout(),
DevicePrefsOp::WLANMenu => self.wlan_menu(),
}; };
resp.unwrap_or_else(|error| self.show_error_modal(error)); resp.unwrap_or_else(|error| self.show_error_modal(error));
} }
fn show_error_modal(&self, e: PrefsManError) { fn show_error_modal(&self, e: DevicePrefsError) {
self.modals self.modals
.show_notification( .show_notification(
format!("{}: {}", t!("wlan.error", xous::LANG), e).as_str(), format!("{}: {}", t!("wlan.error", xous::LANG), e).as_str(),
@ -114,8 +140,8 @@ impl PrefsMan {
} }
} }
impl PrefsMan { impl DevicePrefs {
fn autobacklight_on_boot(&mut self) -> Result<(), PrefsManError> { fn autobacklight_on_boot(&mut self) -> Result<(), DevicePrefsError> {
let cv = self.up.autobacklight_on_boot_or_default()?; let cv = self.up.autobacklight_on_boot_or_default()?;
self.modals.add_list(vec!["Yes", "No"]).unwrap(); self.modals.add_list(vec!["Yes", "No"]).unwrap();
@ -130,7 +156,7 @@ impl PrefsMan {
Ok(self.up.set_autobacklight_on_boot(new_result)?) Ok(self.up.set_autobacklight_on_boot(new_result)?)
} }
fn autobacklight_timeout(&self) -> Result<(), PrefsManError> { fn autobacklight_timeout(&self) -> Result<(), DevicePrefsError> {
let cv = { let cv = {
let mut res = self.up.autobacklight_timeout_or_default()?; let mut res = self.up.autobacklight_timeout_or_default()?;
@ -165,7 +191,7 @@ impl PrefsMan {
Ok(self.up.set_autobacklight_timeout(new_timeout)?) Ok(self.up.set_autobacklight_timeout(new_timeout)?)
} }
fn radio_on_on_boot(&mut self) -> Result<(), PrefsManError>{ fn radio_on_on_boot(&mut self) -> Result<(), DevicePrefsError> {
let cv = self.up.radio_on_on_boot_or_default()?; let cv = self.up.radio_on_on_boot_or_default()?;
self.modals.add_list(vec!["Yes", "No"]).unwrap(); self.modals.add_list(vec!["Yes", "No"]).unwrap();
@ -180,7 +206,7 @@ impl PrefsMan {
Ok(self.up.set_radio_on_on_boot(new_result)?) Ok(self.up.set_radio_on_on_boot(new_result)?)
} }
fn connect_known_networks_on_boot(&mut self) -> Result<(), PrefsManError>{ fn connect_known_networks_on_boot(&mut self) -> Result<(), DevicePrefsError> {
let cv = self.up.connect_known_networks_on_boot_or_default()?; let cv = self.up.connect_known_networks_on_boot_or_default()?;
self.modals.add_list(vec!["Yes", "No"]).unwrap(); self.modals.add_list(vec!["Yes", "No"]).unwrap();
@ -194,6 +220,14 @@ impl PrefsMan {
Ok(self.up.set_connect_known_networks_on_boot(new_result)?) Ok(self.up.set_connect_known_networks_on_boot(new_result)?)
} }
fn wlan_menu(&self) -> Result<(), DevicePrefsError> {
log::info!("wlan menu invoked");
std::thread::sleep(std::time::Duration::from_millis(100));
self.gam.raise_menu(gam::WIFI_MENU_NAME).unwrap();
Ok(())
}
} }
fn yes_no_to_bool(val: &str) -> bool { fn yes_no_to_bool(val: &str) -> bool {
@ -219,23 +253,31 @@ fn run_menu_thread() {
let xns = xous_names::XousNames::new().unwrap(); let xns = xous_names::XousNames::new().unwrap();
let sid = xous::create_server().unwrap(); let sid = xous::create_server().unwrap();
let mut hello = PrefsMan::new(&xns);
let menu_conn = xous::connect(sid).unwrap(); let menu_conn = xous::connect(sid).unwrap();
hello.claim_menumatic_menu(menu_conn);
let mut handlers: Vec<Box<dyn PrefHandler>> = vec![
Box::new(DevicePrefs::new(&xns)),
Box::new(wifi::WLANMan::new(&xns)),
];
// claim menumatic's on all prefhandlers for this thread
for handler in handlers.iter_mut() {
handler.claim_menumatic_menu(menu_conn);
}
loop { loop {
let msg = xous::receive_message(sid).unwrap(); let msg = xous::receive_message(sid).unwrap();
log::debug!("Got message: {:?}", msg); log::debug!("Got message: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) { let op = msg.body.id();
Some(other) => {
hello.consume_menu_action(other); for handler in handlers.iter_mut() {
} if handler.handle(op) {
_ => { log::debug!("handler found!");
log::error!("Got unknown message"); break;
} }
log::debug!("handler not found, iterating...");
} }
} }
} }

View file

@ -1,20 +1,18 @@
use crate::preferences::PrefHandler;
use core::fmt::Display; use core::fmt::Display;
use locales::t;
use num_traits::*; use num_traits::*;
use std::io::Write; use std::io::Write;
use locales::t;
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive, PartialEq, PartialOrd)] #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive, PartialEq, PartialOrd)]
enum WlanManOp { pub enum WlanManOp {
ScanForNetworks = 3, ScanForNetworks = 50,
Status, Status,
AddNetworkManually, AddNetworkManually,
KnownNetworks, KnownNetworks,
DeleteNetwork, DeleteNetwork,
TurnWlanOn, TurnWlanOn,
TurnWlanOff = 9, TurnWlanOff,
} }
impl Display for WlanManOp { impl Display for WlanManOp {
@ -70,15 +68,55 @@ impl From<std::io::Error> for WLANError {
} }
} }
struct WLANMan { pub struct WLANMan {
com: com::Com, com: com::Com,
netmgr: net::NetManager, netmgr: net::NetManager,
modals: modals::Modals, modals: modals::Modals,
pddb: pddb::Pddb, pddb: pddb::Pddb,
} }
impl PrefHandler for WLANMan {
fn handle(&mut self, op: usize) -> bool {
match FromPrimitive::from_usize(op) {
Some(other) => {
self.consume_menu_action(other);
true
}
_ => {
log::error!("Got unknown message");
false
}
}
}
fn claim_menumatic_menu(&self, cid: xous::CID) {
let mut menus = self
.actions()
.iter()
.map(|action| gam::MenuItem {
name: xous_ipc::String::from_str(&action.to_string()),
action_conn: Some(cid),
action_opcode: action.to_u32().unwrap(),
action_payload: gam::MenuPayload::Scalar([0, 0, 0, 0]),
close_on_select: true,
})
.collect::<Vec<gam::MenuItem>>();
menus.push(gam::MenuItem {
name: xous_ipc::String::from_str(t!("mainmenu.closemenu", xous::LANG)),
action_conn: None,
action_opcode: 0,
action_payload: gam::MenuPayload::Scalar([0, 0, 0, 0]),
close_on_select: true,
});
gam::menu_matic(menus, gam::WIFI_MENU_NAME, None);
}
}
impl WLANMan { impl WLANMan {
fn new(xns: &xous_names::XousNames) -> Self { pub fn new(xns: &xous_names::XousNames) -> Self {
Self { Self {
com: com::Com::new(&xns).unwrap(), com: com::Com::new(&xns).unwrap(),
netmgr: net::NetManager::new(), netmgr: net::NetManager::new(),
@ -87,7 +125,7 @@ impl WLANMan {
} }
} }
fn actions(&self) -> Vec<WlanManOp> { pub fn actions(&self) -> Vec<WlanManOp> {
use WlanManOp::*; use WlanManOp::*;
vec![ vec![
@ -204,10 +242,13 @@ impl WLANMan {
self.modals.add_list(networks).unwrap(); self.modals.add_list(networks).unwrap();
let ssid = self.modals.get_radiobutton(t!("wlan.ssid_choose", xous::LANG)).unwrap(); let ssid = self
.modals
.get_radiobutton(t!("wlan.ssid_choose", xous::LANG))
.unwrap();
if ssid == t!("wlan.cancel", xous::LANG) { if ssid == t!("wlan.cancel", xous::LANG) {
return Ok(()) return Ok(());
} }
self.fill_password_for_ssid(&ssid) self.fill_password_for_ssid(&ssid)
@ -221,7 +262,10 @@ impl WLANMan {
Some(t!("wlan.password", xous::LANG).to_string()), Some(t!("wlan.password", xous::LANG).to_string()),
Some(|text| { Some(|text| {
if text.as_str().is_empty() { if text.as_str().is_empty() {
return Some(xous_ipc::String::from_str(t!("wlan.password_empty", xous::LANG))); return Some(xous_ipc::String::from_str(t!(
"wlan.password_empty",
xous::LANG
)));
} }
None None
@ -321,37 +365,13 @@ impl WLANMan {
return Ok(()); return Ok(());
} }
self self.pddb
.pddb .delete_key(net::AP_DICT_NAME, &ssid_to_be_deleted, None)
.delete_key(net::AP_DICT_NAME, &ssid_to_be_deleted, None).map_err(|e| WLANError::PDDBIoError(e))?; .map_err(|e| WLANError::PDDBIoError(e))?;
self.pddb.sync().map_err(|e| WLANError::PDDBIoError(e)) self.pddb.sync().map_err(|e| WLANError::PDDBIoError(e))
} }
fn claim_menumatic_menu(&self, cid: xous::CID) {
let mut menus = self
.actions()
.iter()
.map(|action| gam::MenuItem {
name: xous_ipc::String::from_str(&action.to_string()),
action_conn: Some(cid),
action_opcode: action.to_u32().unwrap(),
action_payload: gam::MenuPayload::Scalar([0, 0, 0, 0]),
close_on_select: true,
})
.collect::<Vec<gam::MenuItem>>();
menus.push(gam::MenuItem {
name: xous_ipc::String::from_str(t!("mainmenu.closemenu", xous::LANG)),
action_conn: None,
action_opcode: 0,
action_payload: gam::MenuPayload::Scalar([0, 0, 0, 0]),
close_on_select: true,
});
gam::menu_matic(menus, gam::WIFI_MENU_NAME, None);
}
fn consume_menu_action(&mut self, action: WlanManOp) { fn consume_menu_action(&mut self, action: WlanManOp) {
let resp = match action { let resp = match action {
WlanManOp::TurnWlanOff => self.set_wlan_state(false), WlanManOp::TurnWlanOff => self.set_wlan_state(false),
@ -368,7 +388,10 @@ impl WLANMan {
fn show_error_modal(&self, e: WLANError) { fn show_error_modal(&self, e: WLANError) {
self.modals self.modals
.show_notification(format!("{}: {}", t!("wlan.error", xous::LANG), e).as_str(), None) .show_notification(
format!("{}: {}", t!("wlan.error", xous::LANG), e).as_str(),
None,
)
.unwrap() .unwrap()
} }
} }
@ -379,38 +402,3 @@ fn format_ip(src: [u8; 4]) -> String {
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(".") .join(".")
} }
pub fn start_background_thread() {
std::thread::spawn(|| run_menu_thread());
}
fn run_menu_thread() {
let xns = xous_names::XousNames::new().unwrap();
let sid = xous::create_server().unwrap();
let mut hello = WLANMan::new(&xns);
let menu_conn = xous::connect(sid).unwrap();
hello.claim_menumatic_menu(menu_conn);
loop {
let msg = xous::receive_message(sid).unwrap();
log::debug!("Got message: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) {
Some(other) => {
if other >= WlanManOp::ScanForNetworks && other <= WlanManOp::TurnWlanOff {
hello.consume_menu_action(other);
continue;
} else {
log::warn!("Received out of range opcode. Did WlanManOp get re-ordered, but the bounds check was not updated as well?");
}
}
_ => {
log::error!("Got unknown message");
}
}
}
}