From 4a4b49b0c867b60b5c18a2a37259fe0650044bf1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Wed, 2 Nov 2022 17:11:37 +0100 Subject: [PATCH] feat: refactor preference to accomodate wifi Also setup framework to extend the main preference menu. --- services/status/src/preferences.rs | 144 +++++++++++++++++++---------- services/status/src/wifi.rs | 140 +++++++++++++--------------- 2 files changed, 157 insertions(+), 127 deletions(-) diff --git a/services/status/src/preferences.rs b/services/status/src/preferences.rs index f1ec19170..bd2111ddd 100644 --- a/services/status/src/preferences.rs +++ b/services/status/src/preferences.rs @@ -1,74 +1,77 @@ -use core::{convert::TryFrom, fmt::Display}; - -use num_traits::*; -use userprefs::{Manager, UserPrefs}; - -use std::io::Write; - +use crate::wifi; 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)] -enum PrefsManOp { +enum DevicePrefsOp { RadioOnOnBoot, ConnectKnownNetworksOnBoot, AutobacklightOnBoot, AutobacklightTimeout, + WLANMenu, } -impl Display for PrefsManOp { +impl Display for DevicePrefsOp { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { Self::AutobacklightOnBoot => write!(f, "Autobacklight enabled on boot"), Self::AutobacklightTimeout => write!(f, "Autobacklight timeout"), Self::ConnectKnownNetworksOnBoot => write!(f, "Connect to known networks on boot"), Self::RadioOnOnBoot => write!(f, "Enable WiFi on boot"), + Self::WLANMenu => write!(f, "WLAN settings"), } } } #[derive(Debug)] -enum PrefsManError { +enum DevicePrefsError { PrefsError(userprefs::Error), } -impl From for PrefsManError { +impl From for DevicePrefsError { fn from(e: userprefs::Error) -> Self { Self::PrefsError(e) } } -impl Display for PrefsManError { +impl Display for DevicePrefsError { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 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, modals: modals::Modals, + gam: gam::Gam, } -impl PrefsMan { - fn new(xns: &xous_names::XousNames) -> Self { - Self { - up: Manager::new(), - modals: modals::Modals::new(&xns).unwrap(), +impl PrefHandler for DevicePrefs { + 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 actions(&self) -> Vec { - use PrefsManOp::*; - - vec![ - RadioOnOnBoot, - ConnectKnownNetworksOnBoot, - AutobacklightOnBoot, - AutobacklightTimeout, - ] - } - fn claim_menumatic_menu(&self, cid: xous::CID) { let mut menus = self .actions() @@ -92,19 +95,42 @@ impl PrefsMan { 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 { + use DevicePrefsOp::*; + + vec![ + RadioOnOnBoot, + ConnectKnownNetworksOnBoot, + AutobacklightOnBoot, + AutobacklightTimeout, + WLANMenu, + ] + } + + fn consume_menu_action(&mut self, action: DevicePrefsOp) { let resp = match action { - PrefsManOp::AutobacklightOnBoot => self.autobacklight_on_boot(), - PrefsManOp::RadioOnOnBoot => self.radio_on_on_boot(), - PrefsManOp::ConnectKnownNetworksOnBoot => self.connect_known_networks_on_boot(), - PrefsManOp::AutobacklightTimeout => self.autobacklight_timeout(), + DevicePrefsOp::AutobacklightOnBoot => self.autobacklight_on_boot(), + DevicePrefsOp::RadioOnOnBoot => self.radio_on_on_boot(), + DevicePrefsOp::ConnectKnownNetworksOnBoot => self.connect_known_networks_on_boot(), + DevicePrefsOp::AutobacklightTimeout => self.autobacklight_timeout(), + DevicePrefsOp::WLANMenu => self.wlan_menu(), }; 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 .show_notification( format!("{}: {}", t!("wlan.error", xous::LANG), e).as_str(), @@ -114,8 +140,8 @@ impl PrefsMan { } } -impl PrefsMan { - fn autobacklight_on_boot(&mut self) -> Result<(), PrefsManError> { +impl DevicePrefs { + fn autobacklight_on_boot(&mut self) -> Result<(), DevicePrefsError> { let cv = self.up.autobacklight_on_boot_or_default()?; self.modals.add_list(vec!["Yes", "No"]).unwrap(); @@ -130,7 +156,7 @@ impl PrefsMan { Ok(self.up.set_autobacklight_on_boot(new_result)?) } - fn autobacklight_timeout(&self) -> Result<(), PrefsManError> { + fn autobacklight_timeout(&self) -> Result<(), DevicePrefsError> { let cv = { let mut res = self.up.autobacklight_timeout_or_default()?; @@ -165,7 +191,7 @@ impl PrefsMan { 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()?; self.modals.add_list(vec!["Yes", "No"]).unwrap(); @@ -180,7 +206,7 @@ impl PrefsMan { 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()?; 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)?) } + + 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 { @@ -219,23 +253,31 @@ fn run_menu_thread() { let xns = xous_names::XousNames::new().unwrap(); let sid = xous::create_server().unwrap(); - - let mut hello = PrefsMan::new(&xns); - let menu_conn = xous::connect(sid).unwrap(); - hello.claim_menumatic_menu(menu_conn); + + let mut handlers: Vec> = 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 { let msg = xous::receive_message(sid).unwrap(); log::debug!("Got message: {:?}", msg); - match FromPrimitive::from_usize(msg.body.id()) { - Some(other) => { - hello.consume_menu_action(other); - } - _ => { - log::error!("Got unknown message"); + let op = msg.body.id(); + + for handler in handlers.iter_mut() { + if handler.handle(op) { + log::debug!("handler found!"); + break; } + + log::debug!("handler not found, iterating..."); } } } diff --git a/services/status/src/wifi.rs b/services/status/src/wifi.rs index aa892af31..58b2bcf1b 100644 --- a/services/status/src/wifi.rs +++ b/services/status/src/wifi.rs @@ -1,20 +1,18 @@ +use crate::preferences::PrefHandler; use core::fmt::Display; - +use locales::t; use num_traits::*; - use std::io::Write; -use locales::t; - #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive, PartialEq, PartialOrd)] -enum WlanManOp { - ScanForNetworks = 3, +pub enum WlanManOp { + ScanForNetworks = 50, Status, AddNetworkManually, KnownNetworks, DeleteNetwork, TurnWlanOn, - TurnWlanOff = 9, + TurnWlanOff, } impl Display for WlanManOp { @@ -70,15 +68,55 @@ impl From for WLANError { } } -struct WLANMan { +pub struct WLANMan { com: com::Com, netmgr: net::NetManager, modals: modals::Modals, 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::>(); + + 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 { - fn new(xns: &xous_names::XousNames) -> Self { + pub fn new(xns: &xous_names::XousNames) -> Self { Self { com: com::Com::new(&xns).unwrap(), netmgr: net::NetManager::new(), @@ -87,7 +125,7 @@ impl WLANMan { } } - fn actions(&self) -> Vec { + pub fn actions(&self) -> Vec { use WlanManOp::*; vec![ @@ -204,10 +242,13 @@ impl WLANMan { 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) { - return Ok(()) + return Ok(()); } self.fill_password_for_ssid(&ssid) @@ -221,7 +262,10 @@ impl WLANMan { Some(t!("wlan.password", xous::LANG).to_string()), Some(|text| { 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 @@ -321,37 +365,13 @@ impl WLANMan { return Ok(()); } - self - .pddb - .delete_key(net::AP_DICT_NAME, &ssid_to_be_deleted, None).map_err(|e| WLANError::PDDBIoError(e))?; + self.pddb + .delete_key(net::AP_DICT_NAME, &ssid_to_be_deleted, None) + .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::>(); - - 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) { let resp = match action { WlanManOp::TurnWlanOff => self.set_wlan_state(false), @@ -368,7 +388,10 @@ impl WLANMan { fn show_error_modal(&self, e: WLANError) { 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() } } @@ -379,38 +402,3 @@ fn format_ip(src: [u8; 4]) -> String { .collect::>() .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"); - } - } - } -}