ht32-panel-daemon 0.8.1

Daemon with web UI for HT32 panel control
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! ASCII text-only face with ASCII art graphs.
//!
//! Portrait layout (135x240):
//! ```text
//! endeavour         18:45
//! Up: 5d 12h 34m    2025-01-31
//! IP:
//! 192.168.1.100
//! Temp:                  45°C
//! CPU: 45%
//! [########...............]
//! RAM: 67%
//! [##########..............]
//! DSK:             R:12M W:5M
//! [_._.-=+*##*+=-._.____..]
//! NET:           D:1.2M U:0.8M
//! [__..--==++**##**++==..]
//! ```
//!
//! Landscape layout (320x170):
//! ```text
//! endeavour               18:45
//! Up: 5d 12h 34m
//! IP: 192.168.1.100
//! CPU [########........] 45%
//! RAM [##########......] 67%
//! DSK  R:12M W:5M
//! [_._.-=+*##*+=-._.____..]
//! NET  D:1.2M U:0.8M
//! [__..--==++**##**++==..]
//! ```

use super::{
    complication_names, complication_options, complications, date_formats, draw_mini_analog_clock,
    time_formats, Complication, EnabledComplications, Face, Theme,
};
use crate::rendering::Canvas;
use crate::sensors::data::SystemData;

/// Dim a color by mixing it toward the background.
fn dim_color(color: u32, background: u32, factor: f32) -> u32 {
    let r1 = ((color >> 16) & 0xFF) as f32;
    let g1 = ((color >> 8) & 0xFF) as f32;
    let b1 = (color & 0xFF) as f32;
    let r2 = ((background >> 16) & 0xFF) as f32;
    let g2 = ((background >> 8) & 0xFF) as f32;
    let b2 = (background & 0xFF) as f32;

    let r = (r1 * factor + r2 * (1.0 - factor)) as u32;
    let g = (g1 * factor + g2 * (1.0 - factor)) as u32;
    let b = (b1 * factor + b2 * (1.0 - factor)) as u32;

    (r << 16) | (g << 8) | b
}

/// Derive colors from theme for the ASCII face.
struct FaceColors {
    /// Primary highlight color (hostname, interface name)
    highlight: u32,
    /// Main text color
    text: u32,
    /// Dimmed text color (uptime, IPs)
    dim: u32,
    /// Graph background
    bar_bg: u32,
    /// Disk graph fill color
    bar_disk: u32,
    /// Network graph fill color
    bar_net: u32,
}

impl FaceColors {
    fn from_theme(theme: &Theme) -> Self {
        Self {
            highlight: theme.primary,
            text: theme.text,
            dim: dim_color(theme.text, theme.background, 0.7), // Higher for better contrast
            bar_bg: dim_color(theme.primary, theme.background, 0.2),
            bar_disk: dim_color(theme.primary, theme.secondary, 0.5),
            bar_net: theme.secondary,
        }
    }
}

/// Font sizes.
const FONT_LARGE: f32 = 16.0;
const FONT_NORMAL: f32 = 14.0;
const FONT_SMALL: f32 = 12.0;

/// Creates an ASCII progress bar string.
/// Returns something like "[########........]"
fn ascii_bar(percent: f64, width: usize) -> String {
    let filled = ((percent / 100.0) * width as f64).round() as usize;
    let filled = filled.min(width);
    let empty = width - filled;
    format!("[{}{}]", "#".repeat(filled), ".".repeat(empty))
}

/// Creates an ASCII sparkline from historical data.
/// Uses ASCII characters to represent different heights:
/// `_` (lowest), `.`, `-`, `=`, `+`, `*`, `#` (highest)
fn ascii_sparkline(data: &std::collections::VecDeque<f64>, max_value: f64, width: usize) -> String {
    const CHARS: [char; 7] = ['_', '.', '-', '=', '+', '*', '#'];

    if data.is_empty() || max_value <= 0.0 {
        return "_".repeat(width);
    }

    // Sample data to fit width
    let num_points = data.len();
    let mut result = String::with_capacity(width);

    for i in 0..width {
        // Map output position to data index
        let data_idx = if width <= num_points {
            // More data than width: sample from recent data
            num_points - width + i
        } else {
            // Less data than width: stretch or pad
            (i * num_points) / width
        };

        let value = data.get(data_idx).copied().unwrap_or(0.0);
        let normalized = (value / max_value).clamp(0.0, 1.0);
        let level = (normalized * (CHARS.len() - 1) as f64).round() as usize;
        result.push(CHARS[level.min(CHARS.len() - 1)]);
    }

    result
}

/// A text-only ASCII face.
pub struct AsciiFace;

impl AsciiFace {
    /// Creates a new ASCII face.
    pub fn new() -> Self {
        Self
    }
}

impl Default for AsciiFace {
    fn default() -> Self {
        Self::new()
    }
}

impl Face for AsciiFace {
    fn name(&self) -> &str {
        "ascii"
    }

    fn available_complications(&self) -> Vec<Complication> {
        vec![
            complications::time(true),
            complications::date(true, date_formats::ISO),
            complications::ip_address(true),
            complications::network(true),
            complications::disk_io(true),
            complications::cpu_temp(true),
        ]
    }

    fn render(
        &self,
        canvas: &mut Canvas,
        data: &SystemData,
        theme: &Theme,
        complications: &EnabledComplications,
    ) {
        let colors = FaceColors::from_theme(theme);
        let (width, _height) = canvas.dimensions();
        let portrait = width < 200;
        let margin = 6;
        let mut y = 4; // Start near top
        let bar_chars = if portrait { 10 } else { 16 };

        let is_enabled = |id: &str| complications.is_enabled(self.name(), id, true);

        // Get time format option
        let time_format = complications
            .get_option(
                self.name(),
                complication_names::TIME,
                complication_options::TIME_FORMAT,
            )
            .map(|s| s.as_str())
            .unwrap_or(time_formats::DIGITAL_24H);

        // Get date format option
        let date_format = complications
            .get_option(
                self.name(),
                complication_names::DATE,
                complication_options::DATE_FORMAT,
            )
            .map(|s| s.as_str())
            .unwrap_or(date_formats::ISO);

        if portrait {
            // Portrait layout - labels on separate lines, wider graphs
            let line_height = canvas.line_height(FONT_SMALL);
            let section_spacing = 6; // Extra spacing between label/value pairs
                                     // Calculate bar width to fill most of the line (leave margin on each side)
            let bar_width = ((width as i32 - margin * 2) / 7).max(12) as usize; // ~7 pixels per char

            // Hostname (always shown)
            canvas.draw_text(margin, y, &data.hostname, FONT_LARGE, colors.highlight);

            // Complication: Time (right-aligned)
            if is_enabled(complication_names::TIME) {
                if time_format == time_formats::ANALOGUE {
                    // Draw small analog clock on the right
                    let clock_radius = 10_u32;
                    let clock_cx = width as i32 - margin - clock_radius as i32;
                    let clock_cy = y + clock_radius as i32;
                    draw_mini_analog_clock(
                        canvas,
                        clock_cx,
                        clock_cy,
                        clock_radius,
                        data.hour,
                        data.minute,
                        colors.highlight,
                        colors.text,
                    );
                } else {
                    let time_str = data.format_time(time_format);
                    let time_width = canvas.text_width(&time_str, FONT_LARGE);
                    canvas.draw_text(
                        width as i32 - margin - time_width,
                        y,
                        &time_str,
                        FONT_LARGE,
                        colors.text,
                    );
                }
            }
            y += canvas.line_height(FONT_LARGE) + 1;

            // Complication: Date (right-aligned)
            if is_enabled(complication_names::DATE) {
                if let Some(date_str) = data.format_date(date_format) {
                    let date_width = canvas.text_width(&date_str, FONT_SMALL);
                    canvas.draw_text(
                        width as i32 - margin - date_width,
                        y,
                        &date_str,
                        FONT_SMALL,
                        colors.dim,
                    );
                }
            }
            y += line_height; // Skip line for date
            y += line_height; // Extra line before Up

            // Up: on its own line (two lines below date)
            let uptime_text = format!("Up: {}", data.uptime);
            canvas.draw_text(margin, y, &uptime_text, FONT_SMALL, colors.dim);
            y += line_height + section_spacing;

            // IP: on its own line
            if is_enabled(complication_names::IP_ADDRESS) {
                if let Some(ref ip) = data.display_ip {
                    canvas.draw_text(margin, y, "IP:", FONT_SMALL, colors.dim);
                    y += line_height;
                    // IP value on next line, possibly split for IPv6
                    let max_width = width as i32 - margin * 2;
                    let ip_width = canvas.text_width(ip, FONT_SMALL);
                    if ip_width > max_width && ip.contains(':') {
                        let mid = ip.len() / 2;
                        let split_pos = ip[..mid].rfind(':').map(|p| p + 1).unwrap_or(mid);
                        let (first, second) = ip.split_at(split_pos);
                        canvas.draw_text(margin, y, first, FONT_SMALL, colors.text);
                        y += line_height;
                        canvas.draw_text(margin, y, second, FONT_SMALL, colors.text);
                    } else {
                        canvas.draw_text(margin, y, ip, FONT_SMALL, colors.text);
                    }
                    y += line_height + section_spacing * 2;
                }
            }

            // Temp: on its own line
            if is_enabled(complication_names::CPU_TEMP) {
                if let Some(temp) = data.cpu_temp {
                    canvas.draw_text(margin, y, "Temp:", FONT_SMALL, colors.dim);
                    let temp_val = format!("{:.0}°C", temp);
                    let temp_w = canvas.text_width(&temp_val, FONT_SMALL);
                    canvas.draw_text(
                        width as i32 - margin - temp_w,
                        y,
                        &temp_val,
                        FONT_SMALL,
                        colors.text,
                    );
                    y += line_height + section_spacing;
                }
            }

            // CPU: label line, then bar on next line
            let cpu_label = format!("CPU: {:2.0}%", data.cpu_percent);
            canvas.draw_text(margin, y, &cpu_label, FONT_SMALL, colors.dim);
            y += line_height;
            let cpu_bar = ascii_bar(data.cpu_percent, bar_width);
            canvas.draw_text(margin, y, &cpu_bar, FONT_SMALL, colors.text);
            y += line_height + section_spacing;

            // RAM: label line, then bar on next line
            let ram_label = format!("RAM: {:2.0}%", data.ram_percent);
            canvas.draw_text(margin, y, &ram_label, FONT_SMALL, colors.dim);
            y += line_height;
            let ram_bar = ascii_bar(data.ram_percent, bar_width);
            canvas.draw_text(margin, y, &ram_bar, FONT_SMALL, colors.text);
            y += line_height + section_spacing;

            // DSK: label line, then sparkline on next line
            if is_enabled(complication_names::DISK_IO) {
                let disk_r = SystemData::format_rate_compact(data.disk_read_rate);
                let disk_w = SystemData::format_rate_compact(data.disk_write_rate);
                canvas.draw_text(margin, y, "DSK:", FONT_SMALL, colors.dim);
                let disk_rates = format!("R:{} W:{}", disk_r, disk_w);
                let disk_rates_w = canvas.text_width(&disk_rates, FONT_SMALL);
                canvas.draw_text(
                    width as i32 - margin - disk_rates_w,
                    y,
                    &disk_rates,
                    FONT_SMALL,
                    colors.text,
                );
                y += line_height;
                let sparkline = ascii_sparkline(
                    &data.disk_history,
                    SystemData::compute_graph_scale(&data.disk_history),
                    bar_width,
                );
                canvas.draw_text(
                    margin,
                    y,
                    &format!("[{}]", sparkline),
                    FONT_SMALL,
                    colors.bar_disk,
                );
                y += line_height + section_spacing;
            }

            // NET: label line, then sparkline on next line
            if is_enabled(complication_names::NETWORK) {
                let net_rx = SystemData::format_rate_compact(data.net_rx_rate);
                let net_tx = SystemData::format_rate_compact(data.net_tx_rate);
                canvas.draw_text(margin, y, "NET:", FONT_SMALL, colors.dim);
                let net_rates = format!("D:{} U:{}", net_rx, net_tx);
                let net_rates_w = canvas.text_width(&net_rates, FONT_SMALL);
                canvas.draw_text(
                    width as i32 - margin - net_rates_w,
                    y,
                    &net_rates,
                    FONT_SMALL,
                    colors.text,
                );
                y += line_height;
                let sparkline = ascii_sparkline(
                    &data.net_history,
                    SystemData::compute_graph_scale(&data.net_history),
                    bar_width,
                );
                canvas.draw_text(
                    margin,
                    y,
                    &format!("[{}]", sparkline),
                    FONT_SMALL,
                    colors.bar_net,
                );
            }
        } else {
            // Landscape layout
            // Hostname (always shown)
            canvas.draw_text(margin, y, &data.hostname, FONT_LARGE, colors.highlight);

            // Complication: Time (right-aligned)
            if is_enabled(complication_names::TIME) {
                if time_format == time_formats::ANALOGUE {
                    // Draw small analog clock on the right
                    let clock_radius = 10_u32;
                    let clock_cx = width as i32 - margin - clock_radius as i32;
                    let clock_cy = y + clock_radius as i32;
                    draw_mini_analog_clock(
                        canvas,
                        clock_cx,
                        clock_cy,
                        clock_radius,
                        data.hour,
                        data.minute,
                        colors.highlight,
                        colors.text,
                    );
                } else {
                    let time_str = data.format_time(time_format);
                    let time_width = canvas.text_width(&time_str, FONT_LARGE);
                    canvas.draw_text(
                        width as i32 - margin - time_width,
                        y,
                        &time_str,
                        FONT_LARGE,
                        colors.text,
                    );
                }
            }
            y += canvas.line_height(FONT_LARGE) + 1;

            // Complication: Date (right-aligned, under time)
            if is_enabled(complication_names::DATE) {
                if let Some(date_str) = data.format_date(date_format) {
                    let date_width = canvas.text_width(&date_str, FONT_NORMAL);
                    canvas.draw_text(
                        width as i32 - margin - date_width,
                        y,
                        &date_str,
                        FONT_NORMAL,
                        colors.dim,
                    );
                }
            }

            // Base element: Uptime (always shown, same line as date on left)
            let uptime_text = format!("Up: {}", data.uptime);
            canvas.draw_text(margin, y, &uptime_text, FONT_NORMAL, colors.dim);
            y += canvas.line_height(FONT_NORMAL) + 1;

            // Complication: IP address
            if is_enabled(complication_names::IP_ADDRESS) {
                if let Some(ref ip) = data.display_ip {
                    canvas.draw_text(margin, y, &format!("IP: {}", ip), FONT_SMALL, colors.dim);
                    y += canvas.line_height(FONT_SMALL) + 4;
                } else {
                    y += 4;
                }
            }

            // Base element: CPU bar with optional temperature (always shown)
            let cpu_bar = ascii_bar(data.cpu_percent, bar_chars);
            let cpu_text = if is_enabled(complication_names::CPU_TEMP) {
                if let Some(temp) = data.cpu_temp {
                    format!("CPU {} {:3.0}%  {:.0}°C", cpu_bar, data.cpu_percent, temp)
                } else {
                    format!("CPU {} {:3.0}%", cpu_bar, data.cpu_percent)
                }
            } else {
                format!("CPU {} {:3.0}%", cpu_bar, data.cpu_percent)
            };
            canvas.draw_text(margin, y, &cpu_text, FONT_NORMAL, colors.text);
            y += canvas.line_height(FONT_NORMAL) + 1;

            // Base element: RAM bar (always shown)
            let ram_bar = ascii_bar(data.ram_percent, bar_chars);
            let ram_text = format!("RAM {} {:3.0}%", ram_bar, data.ram_percent);
            canvas.draw_text(margin, y, &ram_text, FONT_NORMAL, colors.text);
            y += canvas.line_height(FONT_NORMAL) + 2;

            // Complication: Disk I/O
            if is_enabled(complication_names::DISK_IO) {
                let disk_r = SystemData::format_rate_compact(data.disk_read_rate);
                let disk_w = SystemData::format_rate_compact(data.disk_write_rate);
                canvas.draw_text(margin, y, "DSK", FONT_NORMAL, colors.text);
                canvas.draw_text(
                    margin + 40,
                    y,
                    &format!("R:{} W:{}", disk_r, disk_w),
                    FONT_NORMAL,
                    colors.dim,
                );
                y += canvas.line_height(FONT_NORMAL);
                let sparkline = ascii_sparkline(
                    &data.disk_history,
                    SystemData::compute_graph_scale(&data.disk_history),
                    bar_chars + 20,
                );
                canvas.draw_text(
                    margin,
                    y,
                    &format!("[{}]", sparkline),
                    FONT_NORMAL,
                    colors.bar_disk,
                );
                y += canvas.line_height(FONT_NORMAL) + 2;
            }

            // Complication: Network
            if is_enabled(complication_names::NETWORK) {
                let net_rx = SystemData::format_rate_compact(data.net_rx_rate);
                let net_tx = SystemData::format_rate_compact(data.net_tx_rate);
                canvas.draw_text(margin, y, "NET", FONT_NORMAL, colors.text);
                canvas.draw_text(
                    margin + 40,
                    y,
                    &format!("D:{} U:{}", net_rx, net_tx),
                    FONT_NORMAL,
                    colors.dim,
                );
                y += canvas.line_height(FONT_NORMAL);
                let sparkline = ascii_sparkline(
                    &data.net_history,
                    SystemData::compute_graph_scale(&data.net_history),
                    bar_chars + 20,
                );
                canvas.draw_text(
                    margin,
                    y,
                    &format!("[{}]", sparkline),
                    FONT_NORMAL,
                    colors.bar_net,
                );
            }
        }
        let _ = y;
    }
}