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 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<userprefs::Error> for PrefsManError {
impl From<userprefs::Error> 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<PrefsManOp> {
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<DevicePrefsOp> {
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<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 {
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...");
}
}
}

View file

@ -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<std::io::Error> 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::<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 {
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<WlanManOp> {
pub fn actions(&self) -> Vec<WlanManOp> {
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::<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) {
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::<Vec<String>>()
.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");
}
}
}
}