aranet-cli 0.2.0

Command-line interface for Aranet environmental sensors
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! Reusable UI components for the Aranet GUI.
//!
//! This module provides styled, consistent UI components that can be used
//! throughout the application.

use eframe::egui::{self, Color32, RichText, Sense, Ui};

use super::theme::{ButtonStyle, Theme};
use super::types::Trend;

/// Render a styled metric card with value, unit, and optional trend.
pub fn metric_card(
    ui: &mut Ui,
    theme: &Theme,
    label: &str,
    value: &str,
    unit: &str,
    trend: Option<Trend>,
    accent: Color32,
) {
    egui::Frame::new()
        .fill(theme.bg_card)
        .inner_margin(egui::Margin::same(theme.spacing.card_padding as i8))
        .corner_radius(egui::CornerRadius::same(theme.rounding.md as u8))
        .stroke(egui::Stroke::new(1.0, theme.border_subtle))
        .show(ui, |ui| {
            ui.set_min_width(100.0);
            ui.vertical(|ui| {
                ui.label(
                    RichText::new(label)
                        .color(theme.text_muted)
                        .size(theme.typography.caption),
                );
                ui.add_space(theme.spacing.xs);
                ui.horizontal(|ui| {
                    ui.label(
                        RichText::new(value)
                            .color(accent)
                            .size(theme.typography.display)
                            .strong(),
                    );
                    ui.label(
                        RichText::new(unit)
                            .color(theme.text_muted)
                            .size(theme.typography.body),
                    );
                    if let Some(t) = trend {
                        let trend_color = match t {
                            Trend::Rising => theme.caution,
                            Trend::Falling => theme.info,
                            Trend::Stable => theme.text_muted,
                        };
                        ui.label(
                            RichText::new(t.indicator())
                                .color(trend_color)
                                .size(theme.typography.subheading),
                        );
                    }
                });
            });
        });
}

/// Kind of empty state for visual differentiation.
#[derive(Debug, Clone, Copy, Default)]
pub enum EmptyStateKind {
    /// No data available (neutral)
    #[default]
    NoData,
    /// No matches for current filters
    NoMatch,
}

/// Render an empty state with icon and message.
pub fn empty_state(ui: &mut Ui, theme: &Theme, title: &str, description: &str) {
    empty_state_with_kind(ui, theme, title, description, EmptyStateKind::NoData);
}

/// Render an empty state with a specific visual kind.
pub fn empty_state_with_kind(
    ui: &mut Ui,
    theme: &Theme,
    title: &str,
    description: &str,
    kind: EmptyStateKind,
) {
    let (icon, icon_color, title_color) = match kind {
        EmptyStateKind::NoData => ("", theme.text_muted, theme.text_secondary),
        EmptyStateKind::NoMatch => ("", theme.info, theme.text_secondary),
    };

    ui.vertical_centered(|ui| {
        ui.add_space(theme.spacing.xl * 2.0);
        ui.label(
            RichText::new(icon)
                .color(icon_color)
                .size(theme.typography.display),
        );
        ui.add_space(theme.spacing.md);
        ui.label(
            RichText::new(title)
                .color(title_color)
                .size(theme.typography.subheading)
                .strong(),
        );
        ui.add_space(theme.spacing.xs);
        ui.label(
            RichText::new(description)
                .color(theme.text_secondary)
                .size(theme.typography.body),
        );
    });
}

/// Render a section header with left accent border for visual separation.
pub fn section_header(ui: &mut Ui, theme: &Theme, title: &str) {
    ui.horizontal(|ui| {
        // Left accent bar
        let bar_height = theme.typography.subheading + 4.0;
        let (rect, _) = ui.allocate_exact_size(egui::vec2(3.0, bar_height), egui::Sense::hover());
        ui.painter()
            .rect_filled(rect, egui::CornerRadius::same(1), theme.accent);
        ui.add_space(theme.spacing.sm);
        ui.label(
            RichText::new(title)
                .color(theme.text_primary)
                .size(theme.typography.subheading)
                .strong(),
        );
    });
    ui.add_space(theme.spacing.sm);
}

/// Render a styled status badge (pill-shaped).
pub fn status_badge(ui: &mut Ui, theme: &Theme, text: &str, color: Color32) {
    let bg = theme.tint_medium(color);
    egui::Frame::new()
        .fill(bg)
        .inner_margin(egui::Margin::symmetric(
            theme.spacing.sm as i8,
            theme.spacing.xs as i8,
        ))
        .corner_radius(egui::CornerRadius::same(theme.rounding.full as u8))
        .show(ui, |ui| {
            ui.label(
                RichText::new(text)
                    .color(color)
                    .size(theme.typography.caption),
            );
        });
}

/// Render a themed button using the shared button style tokens.
pub fn themed_button(
    ui: &mut Ui,
    theme: &Theme,
    text: &str,
    style: ButtonStyle,
    text_size: f32,
) -> egui::Response {
    let stroke = if style.border == Color32::TRANSPARENT {
        egui::Stroke::NONE
    } else {
        egui::Stroke::new(1.0, style.border)
    };

    ui.add(
        egui::Button::new(RichText::new(text).color(style.text).size(text_size))
            .fill(style.fill)
            .stroke(stroke)
            .corner_radius(egui::CornerRadius::same(theme.rounding.sm as u8))
            .min_size(egui::vec2(0.0, theme.spacing.lg + 2.0)),
    )
}

/// Render a pill-shaped toggle chip for tabs and filters.
pub fn toggle_chip(
    ui: &mut Ui,
    theme: &Theme,
    text: &str,
    selected: bool,
    active_color: Color32,
) -> egui::Response {
    let fill = if selected {
        theme.tint_medium(active_color)
    } else {
        theme.bg_card
    };
    let text_color = if selected {
        active_color
    } else {
        theme.text_secondary
    };
    let stroke = if selected {
        active_color
    } else {
        theme.border_subtle
    };

    ui.add(
        egui::Button::new(
            RichText::new(text)
                .color(text_color)
                .size(theme.typography.caption + 1.0),
        )
        .fill(fill)
        .stroke(egui::Stroke::new(1.0, stroke))
        .corner_radius(egui::CornerRadius::same(theme.rounding.full as u8))
        .min_size(egui::vec2(0.0, theme.spacing.lg + 2.0)),
    )
}

/// Render a prominent navigation tab button.
pub fn nav_tab(ui: &mut Ui, theme: &Theme, text: &str, selected: bool) -> egui::Response {
    let fill = if selected {
        theme.tint_medium(theme.accent)
    } else {
        Color32::TRANSPARENT
    };
    let text_color = if selected {
        theme.accent
    } else {
        theme.text_secondary
    };
    let stroke = if selected {
        theme.accent
    } else {
        theme.border_subtle
    };

    ui.add(
        egui::Button::new(
            RichText::new(text)
                .color(text_color)
                .size(theme.typography.body),
        )
        .fill(fill)
        .stroke(egui::Stroke::new(1.0, stroke))
        .corner_radius(egui::CornerRadius::same(theme.rounding.md as u8))
        .min_size(egui::vec2(84.0, theme.spacing.xl)),
    )
}

/// Render a connection status indicator dot.
pub fn status_dot(ui: &mut Ui, color: Color32, tooltip: &str) -> egui::Response {
    let size = 8.0;
    let (rect, response) = ui.allocate_exact_size(egui::vec2(size, size), Sense::hover());
    if ui.is_rect_visible(rect) {
        let painter = ui.painter();
        painter.circle_filled(rect.center(), size / 2.0, color);
    }
    response.on_hover_text(tooltip)
}

/// Render a CO2 level gauge bar with current value indicator.
pub fn co2_gauge(ui: &mut Ui, theme: &Theme, co2: u16) {
    let max_ppm = 2500.0_f32;
    let pct = (co2 as f32 / max_ppm).min(1.0);

    let available_width = ui.available_width();
    let bar_height = 14.0;
    let indicator_height = 20.0; // Space above bar for value indicator
    let label_height = 18.0;
    let (rect, _) = ui.allocate_exact_size(
        egui::vec2(
            available_width,
            indicator_height + bar_height + label_height,
        ),
        Sense::hover(),
    );

    let painter = ui.painter();
    let bar_rect = egui::Rect::from_min_size(
        rect.min + egui::vec2(0.0, indicator_height),
        egui::vec2(available_width, bar_height),
    );

    // Draw zone backgrounds
    let zones = [
        (800.0 / max_ppm, theme.success),
        (200.0 / max_ppm, theme.warning),
        (500.0 / max_ppm, theme.caution),
        (1.0 - 1500.0 / max_ppm, theme.danger),
    ];
    let mut x_offset = 0.0;
    for (width_pct, color) in zones {
        let width = width_pct * available_width;
        painter.rect_filled(
            egui::Rect::from_min_size(
                bar_rect.min + egui::vec2(x_offset, 0.0),
                egui::vec2(width, bar_height),
            ),
            egui::CornerRadius::ZERO,
            color.gamma_multiply(0.2),
        );
        x_offset += width;
    }

    // Draw border
    painter.rect_stroke(
        bar_rect,
        egui::CornerRadius::same(theme.rounding.sm as u8),
        egui::Stroke::new(1.0, theme.border),
        egui::StrokeKind::Outside,
    );

    // Draw filled portion
    let fill_width = pct * available_width;
    let fill_color = theme.co2_color(co2);
    painter.rect_filled(
        egui::Rect::from_min_size(bar_rect.min, egui::vec2(fill_width, bar_height)),
        egui::CornerRadius::same(theme.rounding.sm as u8),
        fill_color.gamma_multiply(0.85),
    );

    // Draw current value indicator (triangle pointer + value label above bar)
    let indicator_x = bar_rect.min.x + pct * available_width;

    // Draw triangle pointer pointing down at the bar
    let triangle_size = 6.0;
    let triangle_y = bar_rect.min.y - 2.0;
    painter.add(egui::Shape::convex_polygon(
        vec![
            egui::pos2(indicator_x, triangle_y),
            egui::pos2(
                indicator_x - triangle_size / 2.0,
                triangle_y - triangle_size,
            ),
            egui::pos2(
                indicator_x + triangle_size / 2.0,
                triangle_y - triangle_size,
            ),
        ],
        fill_color,
        egui::Stroke::NONE,
    ));

    // Draw value label above the triangle
    painter.text(
        egui::pos2(indicator_x, triangle_y - triangle_size - 2.0),
        egui::Align2::CENTER_BOTTOM,
        format!("{}", co2),
        egui::FontId::proportional(theme.typography.caption),
        fill_color,
    );

    // Draw tick marks and labels below bar
    let label_y = bar_rect.max.y + 3.0;
    let ticks = [(800.0, "800"), (1000.0, "1k"), (1500.0, "1.5k")];
    for (ppm, label) in ticks {
        let x = bar_rect.min.x + (ppm / max_ppm) * available_width;
        painter.line_segment(
            [egui::pos2(x, bar_rect.min.y), egui::pos2(x, bar_rect.max.y)],
            egui::Stroke::new(1.0, theme.text_muted.gamma_multiply(0.4)),
        );
        painter.text(
            egui::pos2(x, label_y),
            egui::Align2::CENTER_TOP,
            label,
            egui::FontId::proportional(theme.typography.caption),
            theme.text_muted,
        );
    }
}

/// Render a loading indicator with optional message.
pub fn loading_indicator(ui: &mut Ui, theme: &Theme, message: Option<&str>) {
    ui.horizontal(|ui| {
        ui.spinner();
        if let Some(msg) = message {
            ui.add_space(theme.spacing.sm);
            ui.label(RichText::new(msg).color(theme.text_muted));
        }
    });
}

/// Render a banner for cached/offline data.
///
/// Shows a warning banner indicating that the displayed readings are from cache
/// and not live from the device, along with the timestamp of when the data was captured.
pub fn cached_data_banner(
    ui: &mut Ui,
    theme: &Theme,
    captured_at: Option<time::OffsetDateTime>,
    is_stale: bool,
) {
    let (bg_color, border_color, icon, message) = if is_stale {
        (
            theme.tint_light(theme.warning),
            theme.warning,
            "",
            "Cached data - reading may be outdated",
        )
    } else {
        (
            theme.tint_light(theme.info),
            theme.info,
            "",
            "Showing cached data - device offline",
        )
    };

    egui::Frame::new()
        .fill(bg_color)
        .inner_margin(egui::Margin::symmetric(
            theme.spacing.md as i8,
            theme.spacing.sm as i8,
        ))
        .corner_radius(egui::CornerRadius::same(theme.rounding.md as u8))
        .stroke(egui::Stroke::new(2.0, border_color))
        .show(ui, |ui| {
            ui.horizontal(|ui| {
                let icon_color = if is_stale { theme.warning } else { theme.info };
                ui.label(
                    RichText::new(icon)
                        .color(icon_color)
                        .size(theme.typography.subheading),
                );
                ui.add_space(theme.spacing.sm);

                ui.vertical(|ui| {
                    ui.label(
                        RichText::new(message)
                            .color(theme.text_primary)
                            .size(theme.typography.body)
                            .strong(),
                    );

                    if let Some(ts) = captured_at {
                        let age = format_reading_age(ts);
                        ui.label(
                            RichText::new(format!("Last reading: {}", age))
                                .color(theme.text_secondary)
                                .size(theme.typography.caption),
                        );
                    }
                });
            });
        });
}

/// Format the age of a reading in human-readable form.
fn format_reading_age(captured_at: time::OffsetDateTime) -> String {
    let now = time::OffsetDateTime::now_utc();
    let duration = now - captured_at;

    let total_seconds = duration.whole_seconds();
    if total_seconds < 0 {
        return "just now".to_string();
    }

    let minutes = duration.whole_minutes();
    let hours = duration.whole_hours();
    let days = duration.whole_days();

    if days > 0 {
        if days == 1 {
            "1 day ago".to_string()
        } else {
            format!("{} days ago", days)
        }
    } else if hours > 0 {
        if hours == 1 {
            "1 hour ago".to_string()
        } else {
            format!("{} hours ago", hours)
        }
    } else if minutes > 0 {
        if minutes == 1 {
            "1 minute ago".to_string()
        } else {
            format!("{} minutes ago", minutes)
        }
    } else {
        "just now".to_string()
    }
}

/// Check if a reading is considered stale (older than threshold).
///
/// A reading is stale if it's older than 2x the measurement interval,
/// or older than 30 minutes if no interval is known.
pub fn is_reading_stale(captured_at: Option<time::OffsetDateTime>, interval_secs: u16) -> bool {
    let Some(ts) = captured_at else {
        return false; // Can't determine staleness without timestamp
    };

    let now = time::OffsetDateTime::now_utc();
    let age_secs = (now - ts).whole_seconds();

    if age_secs < 0 {
        return false;
    }

    // Stale if older than 2x the interval, or 30 minutes if no interval
    let threshold = if interval_secs > 0 {
        (interval_secs as i64) * 2
    } else {
        30 * 60 // 30 minutes default
    };

    age_secs > threshold
}