Skip to main content

cadmus_core/task/
time_sync.rs

1use std::sync::mpsc::Sender;
2
3use crate::geolocation::fetch_geolocation;
4use crate::http::Client;
5use crate::task::{BackgroundTask, ShutdownSignal, TaskId};
6use crate::time_manager::TimeManager;
7use crate::view::Event;
8
9const NTP_HOST: &str = "time.cloudflare.com:123";
10
11pub struct TimeSyncTask {
12    time_manager: &'static TimeManager,
13    manual: bool,
14}
15
16impl TimeSyncTask {
17    pub fn new(time_manager: &'static TimeManager, manual: bool) -> Self {
18        TimeSyncTask {
19            time_manager,
20            manual,
21        }
22    }
23}
24
25impl BackgroundTask for TimeSyncTask {
26    fn id(&self) -> TaskId {
27        TaskId::TimeSync
28    }
29
30    fn run(&mut self, hub: &Sender<Event>, _shutdown: &ShutdownSignal) {
31        let geo = match Client::new() {
32            Ok(client) => match fetch_geolocation(&client) {
33                Ok(geo) => Some(geo),
34                Err(e) => {
35                    tracing::error!(error = %e, "failed to fetch geolocation");
36                    None
37                }
38            },
39            Err(e) => {
40                tracing::error!(error = %e, "failed to create http client");
41                None
42            }
43        };
44
45        let coordinates = geo.as_ref().map(|geo| geo.coordinates);
46
47        if let Err(e) = self.time_manager.sync(NTP_HOST, self.manual, geo, hub) {
48            tracing::error!(error = %e, "time sync failed");
49        }
50
51        if let Some(coordinates) = coordinates {
52            hub.send(Event::AutoFrontlightCoordinates(coordinates)).ok();
53        }
54    }
55}