Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Periodic discovery #61

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 25 additions & 4 deletions watchmate/src/ui.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use infinitime::{bluer, bt};
use std::{sync::Arc, path::PathBuf, env};
use std::{env, path::PathBuf, sync::Arc, time::Duration};
use futures::{pin_mut, StreamExt};
use gtk::{gio, glib, prelude::{ApplicationExt, BoxExt, GtkWindowExt, SettingsExt, WidgetExt}};
use relm4::{
Expand Down Expand Up @@ -50,7 +50,8 @@ enum Input {
label: &'static str,
url: &'static str,
},
WindowShown, // Temporary hack
WindowShown,
WindowHidden,
About,
Close,
Quit,
Expand Down Expand Up @@ -86,8 +87,8 @@ impl Component for Model {
set_default_height: 720,
set_hide_on_close: settings.boolean(SETTING_BACKGROUND),

// Temporary hack
connect_show => Input::WindowShown,
connect_hide => Input::WindowHidden,

#[local]
toast_overlay -> adw::ToastOverlay {
Expand Down Expand Up @@ -309,9 +310,29 @@ impl Component for Model {
// main window visible upon gtk::Application::activate signal
if self.hide_on_startup {
root.set_visible(false);
self.hide_on_startup = false;
}
self.hide_on_startup = false;

if root.is_visible() {
self.devices_page.emit(
devices_page::Input::DiscoveryMode(
devices_page::DiscoveryMode::Continuous
)
)
}
}

Input::WindowHidden => {
self.devices_page.emit(
devices_page::Input::DiscoveryMode(
devices_page::DiscoveryMode::Periodic {
active: Duration::from_secs(5),
pause: Duration::from_secs(60),
}
)
);
}

Input::About => {
adw::AboutWindow::builder()
.transient_for(root)
Expand Down
83 changes: 79 additions & 4 deletions watchmate/src/ui/devices_page.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,33 @@
use crate::ui;
use std::str::FromStr;
use std::{str::FromStr, time::Duration};
use infinitime::{ bluer, bt };
use std::sync::Arc;
use futures::{pin_mut, StreamExt};
use gtk::{gio, prelude::{BoxExt, ButtonExt, OrientableExt, ListBoxRowExt, WidgetExt, SettingsExt}};
use relm4::{
adw, gtk,
tokio::time::{sleep, timeout},
factory::{FactoryComponent, FactorySender, FactoryVecDeque, DynamicIndex},
ComponentParts, ComponentSender, Component, JoinHandle, RelmWidgetExt,
};


#[derive(Debug, Clone, PartialEq)]
pub enum DiscoveryMode {
Periodic { active: Duration, pause: Duration },
Continuous,
}

impl DiscoveryMode {
pub fn is_continous(&self) -> bool {
self == &Self::Continuous
}

pub fn is_periodic(&self) -> bool {
!self.is_continous()
}
}

#[derive(Debug)]
pub enum Input {
InitSession,
Expand All @@ -20,6 +37,8 @@ pub enum Input {
StartDiscovery,
StopDiscovery,
DiscoveryFailed,
DiscoveryPaused(bool),
DiscoveryMode(DiscoveryMode),
DeviceInfoReady(DeviceInfo),
DeviceAdded(bluer::Address),
DeviceRemoved(bluer::Address),
Expand Down Expand Up @@ -52,7 +71,8 @@ pub struct Model {
adapter: Option<Arc<bluer::Adapter>>,
gatt_server: Option<bluer::gatt::local::ApplicationHandle>,
discovery_task: Option<JoinHandle<()>>,

discovery_mode: DiscoveryMode,
discovery_paused: bool,
saved_address: Option<bluer::Address>,
autoconnect_address: Option<bluer::Address>,
disconnecting_address: Option<bluer::Address>,
Expand Down Expand Up @@ -111,6 +131,24 @@ impl Model {
}
}
}

async fn run_periodic_discovery(
adapter: Arc<bluer::Adapter>,
sender: ComponentSender<Self>,
active_duration: Duration,
pause_duration: Duration
) {
let mut finished = false;
while !finished {
// Active interval
sender.input(Input::DiscoveryPaused(false));
let discovery = Self::run_discovery(adapter.clone(), sender.clone());
finished = timeout(active_duration, discovery).await.is_ok();
// Pause interval
sender.input(Input::DiscoveryPaused(true));
sleep(pause_duration).await;
}
}
}


Expand Down Expand Up @@ -153,7 +191,8 @@ impl Component for Model {
gtk::Spinner {
#[watch]
set_visible: model.discovery_task.is_some(),
set_spinning: true,
#[watch]
set_spinning: !model.discovery_paused,
}
},

Expand Down Expand Up @@ -232,6 +271,8 @@ impl Component for Model {
adapter: None,
gatt_server: None,
discovery_task: None,
discovery_mode: DiscoveryMode::Continuous,
discovery_paused: false,
autoconnect_address: saved_address.clone(),
saved_address,
disconnecting_address: None,
Expand Down Expand Up @@ -278,8 +319,17 @@ impl Component for Model {
if self.discovery_task.is_none() {
if let Some(adapter) = self.adapter.clone() {
self.devices.guard().clear();
let discovery_mode = self.discovery_mode.clone();
self.discovery_paused = false;
self.discovery_task = Some(relm4::spawn(async move {
Self::run_discovery(adapter.clone(), sender.clone()).await;
match discovery_mode {
DiscoveryMode::Periodic { active, pause } => {
Self::run_periodic_discovery(adapter, sender.clone(), active, pause).await;
}
DiscoveryMode::Continuous => {
Self::run_discovery(adapter, sender.clone()).await;
}
}
sender.input(Input::DiscoveryFailed);
}));
log::info!("Device discovery started");
Expand All @@ -299,6 +349,30 @@ impl Component for Model {
self.discovery_task = None;
}

Input::DiscoveryPaused(paused) => {
if !paused {
self.devices.guard().clear();
}
self.discovery_paused = paused;
}

Input::DiscoveryMode(mode) => {
match &mode {
DiscoveryMode::Periodic { active, pause } => {
log::info!("Setting discovery mode to periodic: {}s scan | {}s pause", active.as_secs(), pause.as_secs());
}
DiscoveryMode::Continuous => {
log::info!("Setting discovery mode to continuous");
}
}
self.discovery_mode = mode;
// Restart ongoing discovery
if self.discovery_task.is_some() {
sender.input(Input::StopDiscovery);
sender.input(Input::StartDiscovery);
}
}

Input::DeviceInfoReady(info) => {
let address = info.address;
let mut devices = self.devices.guard();
Expand Down Expand Up @@ -477,6 +551,7 @@ impl Component for Model {
if let Some((i, d)) = devices_guard.iter().enumerate().find(
|(_, d)| Some(d.address) == self.autoconnect_address
) {
// If saved device is available, try to connect to it
log::info!("Trying to connect to InfiniTime ({})", d.address.to_string());
devices_guard.send(i, DeviceInput::Connect);
} else {
Expand Down