trmnl 0.1.0

BYOS (Bring Your Own Server) framework for TRMNL e-ink displays
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Refresh rate scheduling based on time of day and day of week.
//!
//! This module allows you to configure different refresh rates for different times,
//! helping optimize battery life while keeping displays fresh when needed.
//!
//! # Example Schedule (YAML)
//!
//! ```yaml
//! timezone: "America/New_York"
//! default_refresh_rate: 300  # 5 minutes
//!
//! schedule:
//!   # Sleep hours - very infrequent updates
//!   - days: all
//!     start: "23:00"
//!     end: "06:00"
//!     refresh_rate: 1800  # 30 minutes
//!
//!   # Morning routine - frequent updates
//!   - days: weekdays
//!     start: "06:00"
//!     end: "09:00"
//!     refresh_rate: 60  # 1 minute
//!
//!   # Work hours - moderate updates
//!   - days: weekdays
//!     start: "09:00"
//!     end: "18:00"
//!     refresh_rate: 120  # 2 minutes
//! ```
//!
//! # Usage
//!
//! ```rust,ignore
//! use trmnl::schedule::RefreshSchedule;
//!
//! // Load schedule from YAML file
//! let schedule = RefreshSchedule::load("config/schedule.yaml")?;
//!
//! // Get current refresh rate based on time
//! let refresh_rate = schedule.get_refresh_rate();
//!
//! // Use in your display response
//! DisplayResponse::new(url, filename).with_refresh_rate(refresh_rate)
//! ```

use chrono::{DateTime, Datelike, NaiveTime, Timelike, Utc, Weekday};
use chrono_tz::Tz;
use serde::Deserialize;
use std::path::Path;

use crate::Error;

/// A refresh rate schedule configuration.
///
/// Loads from YAML and provides time-based refresh rate lookup.
#[derive(Debug, Clone, Deserialize)]
pub struct RefreshSchedule {
    /// Timezone for interpreting times (e.g., "America/New_York")
    pub timezone: String,
    /// Default refresh rate if no rule matches (seconds)
    pub default_refresh_rate: u32,
    /// List of schedule rules (evaluated in order, first match wins)
    pub schedule: Vec<ScheduleRule>,
}

/// A single schedule rule.
#[derive(Debug, Clone, Deserialize)]
pub struct ScheduleRule {
    /// Days this rule applies to
    pub days: DaySelector,
    /// Start time (HH:MM, 24-hour format)
    pub start: String,
    /// End time (HH:MM, 24-hour format)
    pub end: String,
    /// Refresh rate in seconds
    pub refresh_rate: u32,
}

/// Day selector for schedule rules.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum DaySelector {
    /// A specific list of days (e.g., ["mon", "tue", "wed"])
    List(Vec<String>),
    /// A named group: "all", "weekdays", "weekends", or a single day name
    Named(String),
}

impl RefreshSchedule {
    /// Load schedule from a YAML file.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let schedule = RefreshSchedule::load("config/schedule.yaml")?;
    /// ```
    pub fn load<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
        let content = std::fs::read_to_string(path.as_ref()).map_err(|e| {
            Error::Config(format!(
                "Failed to read schedule file '{}': {}",
                path.as_ref().display(),
                e
            ))
        })?;
        Self::from_yaml(&content)
    }

    /// Parse schedule from a YAML string.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let yaml = r#"
    /// timezone: "UTC"
    /// default_refresh_rate: 300
    /// schedule: []
    /// "#;
    /// let schedule = RefreshSchedule::from_yaml(yaml)?;
    /// ```
    pub fn from_yaml(yaml: &str) -> Result<Self, Error> {
        serde_yaml::from_str(yaml)
            .map_err(|e| Error::Config(format!("Invalid schedule YAML: {}", e)))
    }

    /// Get the refresh rate for the current time.
    ///
    /// Evaluates rules in order and returns the first match,
    /// or `default_refresh_rate` if no rules match.
    pub fn get_refresh_rate(&self) -> u32 {
        let tz: Tz = self
            .timezone
            .parse()
            .unwrap_or(chrono_tz::America::New_York);
        let now = Utc::now().with_timezone(&tz);
        self.get_refresh_rate_for_time(now)
    }

    /// Get the refresh rate for a specific time.
    ///
    /// Useful for testing or for pre-calculating schedules.
    pub fn get_refresh_rate_for_time<T: chrono::TimeZone>(&self, dt: DateTime<T>) -> u32 {
        let weekday = dt.weekday();
        let time = NaiveTime::from_hms_opt(dt.hour(), dt.minute(), 0).unwrap_or_default();

        for rule in &self.schedule {
            if rule.matches(weekday, time) {
                tracing::debug!(
                    "Schedule rule matched: {:?} {} -> {} refresh_rate={}",
                    rule.days,
                    rule.start,
                    rule.end,
                    rule.refresh_rate
                );
                return rule.refresh_rate;
            }
        }

        tracing::debug!(
            "No schedule rule matched, using default: {}",
            self.default_refresh_rate
        );
        self.default_refresh_rate
    }
}

impl ScheduleRule {
    /// Check if this rule matches the given day and time.
    fn matches(&self, weekday: Weekday, time: NaiveTime) -> bool {
        // Check if the day matches
        if !self.day_matches(weekday) {
            return false;
        }

        // Parse start and end times
        let start = parse_time(&self.start);
        let end = parse_time(&self.end);

        match (start, end) {
            (Some(s), Some(e)) => {
                if s <= e {
                    // Normal range (e.g., 09:00 - 17:00)
                    time >= s && time < e
                } else {
                    // Overnight range (e.g., 23:00 - 06:00)
                    time >= s || time < e
                }
            }
            _ => false,
        }
    }

    /// Check if this rule applies to the given weekday.
    fn day_matches(&self, weekday: Weekday) -> bool {
        match &self.days {
            DaySelector::Named(name) => match name.to_lowercase().as_str() {
                "all" => true,
                "weekdays" => matches!(
                    weekday,
                    Weekday::Mon | Weekday::Tue | Weekday::Wed | Weekday::Thu | Weekday::Fri
                ),
                "weekends" => matches!(weekday, Weekday::Sat | Weekday::Sun),
                _ => {
                    // Single day name
                    weekday_from_str(name) == Some(weekday)
                }
            },
            DaySelector::List(days) => days.iter().any(|d| weekday_from_str(d) == Some(weekday)),
        }
    }
}

/// Parse a time string (HH:MM) into NaiveTime.
fn parse_time(s: &str) -> Option<NaiveTime> {
    let parts: Vec<&str> = s.split(':').collect();
    if parts.len() != 2 {
        return None;
    }
    let hour: u32 = parts[0].parse().ok()?;
    let minute: u32 = parts[1].parse().ok()?;
    NaiveTime::from_hms_opt(hour, minute, 0)
}

/// Convert a day name to Weekday.
fn weekday_from_str(s: &str) -> Option<Weekday> {
    match s.to_lowercase().as_str() {
        "mon" | "monday" => Some(Weekday::Mon),
        "tue" | "tuesday" => Some(Weekday::Tue),
        "wed" | "wednesday" => Some(Weekday::Wed),
        "thu" | "thursday" => Some(Weekday::Thu),
        "fri" | "friday" => Some(Weekday::Fri),
        "sat" | "saturday" => Some(Weekday::Sat),
        "sun" | "sunday" => Some(Weekday::Sun),
        _ => None,
    }
}

// =============================================================================
// Global Schedule (optional convenience pattern)
// =============================================================================

use std::sync::OnceLock;

/// Global schedule instance, loaded once at startup.
static SCHEDULE: OnceLock<Option<RefreshSchedule>> = OnceLock::new();

/// Initialize the global schedule from a file.
///
/// Call this once at application startup. If the file doesn't exist
/// or is invalid, a warning is logged and the default rate will be used.
///
/// # Example
///
/// ```rust,ignore
/// trmnl::schedule::init_global_schedule("config/schedule.yaml");
///
/// // Later, in handlers:
/// let rate = trmnl::schedule::get_global_refresh_rate();
/// ```
pub fn init_global_schedule(path: &str) {
    let schedule = match RefreshSchedule::load(path) {
        Ok(s) => {
            tracing::info!(
                "Loaded TRMNL schedule with {} rules, default={}s",
                s.schedule.len(),
                s.default_refresh_rate
            );
            Some(s)
        }
        Err(e) => {
            tracing::warn!("Failed to load TRMNL schedule: {}", e);
            None
        }
    };
    let _ = SCHEDULE.set(schedule);
}

/// Get the current refresh rate based on the global schedule.
///
/// Returns 60 seconds if no schedule is loaded.
pub fn get_global_refresh_rate() -> u32 {
    const DEFAULT_REFRESH_RATE: u32 = 60;

    match SCHEDULE.get() {
        Some(Some(schedule)) => schedule.get_refresh_rate(),
        _ => DEFAULT_REFRESH_RATE,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_time() {
        assert_eq!(parse_time("09:00"), NaiveTime::from_hms_opt(9, 0, 0));
        assert_eq!(parse_time("23:30"), NaiveTime::from_hms_opt(23, 30, 0));
        assert_eq!(parse_time("invalid"), None);
        assert_eq!(parse_time("12"), None);
    }

    #[test]
    fn test_weekday_from_str() {
        assert_eq!(weekday_from_str("mon"), Some(Weekday::Mon));
        assert_eq!(weekday_from_str("Monday"), Some(Weekday::Mon));
        assert_eq!(weekday_from_str("MON"), Some(Weekday::Mon));
        assert_eq!(weekday_from_str("sat"), Some(Weekday::Sat));
        assert_eq!(weekday_from_str("invalid"), None);
    }

    #[test]
    fn test_schedule_rule_day_match_named() {
        let rule = ScheduleRule {
            days: DaySelector::Named("weekdays".to_string()),
            start: "09:00".to_string(),
            end: "17:00".to_string(),
            refresh_rate: 60,
        };
        assert!(rule.day_matches(Weekday::Mon));
        assert!(rule.day_matches(Weekday::Fri));
        assert!(!rule.day_matches(Weekday::Sat));
        assert!(!rule.day_matches(Weekday::Sun));
    }

    #[test]
    fn test_schedule_rule_day_match_list() {
        let rule = ScheduleRule {
            days: DaySelector::List(vec![
                "mon".to_string(),
                "wed".to_string(),
                "fri".to_string(),
            ]),
            start: "09:00".to_string(),
            end: "17:00".to_string(),
            refresh_rate: 60,
        };
        assert!(rule.day_matches(Weekday::Mon));
        assert!(rule.day_matches(Weekday::Wed));
        assert!(rule.day_matches(Weekday::Fri));
        assert!(!rule.day_matches(Weekday::Tue));
        assert!(!rule.day_matches(Weekday::Sat));
    }

    #[test]
    fn test_schedule_rule_time_match() {
        let rule = ScheduleRule {
            days: DaySelector::Named("all".to_string()),
            start: "09:00".to_string(),
            end: "17:00".to_string(),
            refresh_rate: 60,
        };
        let time_10am = NaiveTime::from_hms_opt(10, 0, 0).unwrap();
        let time_8am = NaiveTime::from_hms_opt(8, 0, 0).unwrap();
        let time_6pm = NaiveTime::from_hms_opt(18, 0, 0).unwrap();
        let time_5pm = NaiveTime::from_hms_opt(17, 0, 0).unwrap();

        assert!(rule.matches(Weekday::Mon, time_10am));
        assert!(!rule.matches(Weekday::Mon, time_8am));
        assert!(!rule.matches(Weekday::Mon, time_6pm));
        assert!(!rule.matches(Weekday::Mon, time_5pm)); // End is exclusive
    }

    #[test]
    fn test_overnight_rule() {
        let rule = ScheduleRule {
            days: DaySelector::Named("all".to_string()),
            start: "23:00".to_string(),
            end: "06:00".to_string(),
            refresh_rate: 1800,
        };
        let time_midnight = NaiveTime::from_hms_opt(0, 0, 0).unwrap();
        let time_3am = NaiveTime::from_hms_opt(3, 0, 0).unwrap();
        let time_11pm = NaiveTime::from_hms_opt(23, 30, 0).unwrap();
        let time_noon = NaiveTime::from_hms_opt(12, 0, 0).unwrap();

        assert!(rule.matches(Weekday::Mon, time_midnight));
        assert!(rule.matches(Weekday::Mon, time_3am));
        assert!(rule.matches(Weekday::Mon, time_11pm));
        assert!(!rule.matches(Weekday::Mon, time_noon));
    }

    #[test]
    fn test_from_yaml() {
        let yaml = r#"
timezone: "America/New_York"
default_refresh_rate: 300
schedule:
  - days: weekdays
    start: "09:00"
    end: "17:00"
    refresh_rate: 60
  - days: all
    start: "23:00"
    end: "06:00"
    refresh_rate: 1800
"#;
        let schedule = RefreshSchedule::from_yaml(yaml).unwrap();
        assert_eq!(schedule.timezone, "America/New_York");
        assert_eq!(schedule.default_refresh_rate, 300);
        assert_eq!(schedule.schedule.len(), 2);
        assert_eq!(schedule.schedule[0].refresh_rate, 60);
        assert_eq!(schedule.schedule[1].refresh_rate, 1800);
    }

    #[test]
    fn test_empty_schedule_returns_default() {
        let yaml = r#"
timezone: "UTC"
default_refresh_rate: 300
schedule: []
"#;
        let schedule = RefreshSchedule::from_yaml(yaml).unwrap();
        assert_eq!(schedule.get_refresh_rate(), 300);
    }
}