ht32-panel-daemon 0.8.0

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
//! D-Bus interface implementation using zbus.
//!
//! Provides the `org.ht32panel.Daemon1` interface.

use std::sync::Arc;

use ht32_panel_hw::{lcd::parse_hex_color, Orientation};
use tokio::sync::broadcast;
use tracing::{debug, info, warn};
use zbus::{interface, Connection};

use crate::config::DbusBusType;
use crate::state::AppState;

/// D-Bus signal types for state change notifications.
#[derive(Clone, Debug)]
#[allow(clippy::enum_variant_names)]
pub enum DaemonSignals {
    /// Orientation was changed.
    OrientationChanged,
    /// LED settings changed.
    LedChanged,
    /// Display settings (theme, face, etc.) changed.
    DisplaySettingsChanged,
    /// Complication option changed.
    ComplicationOptionChanged,
}

/// D-Bus interface implementation for the HT32 Panel Daemon.
pub struct Daemon1Interface {
    state: Arc<AppState>,
    signal_tx: broadcast::Sender<DaemonSignals>,
    shutdown_tx: tokio::sync::mpsc::Sender<()>,
}

impl Daemon1Interface {
    /// Creates a new D-Bus interface.
    pub fn new(
        state: Arc<AppState>,
        signal_tx: broadcast::Sender<DaemonSignals>,
        shutdown_tx: tokio::sync::mpsc::Sender<()>,
    ) -> Self {
        Self {
            state,
            signal_tx,
            shutdown_tx,
        }
    }
}

#[interface(name = "org.ht32panel.Daemon1")]
impl Daemon1Interface {
    /// Sets the display orientation.
    async fn set_orientation(&self, orientation: &str) -> zbus::fdo::Result<()> {
        let orientation: Orientation = orientation
            .parse()
            .map_err(|_| zbus::fdo::Error::InvalidArgs("Invalid orientation".to_string()))?;

        self.state
            .set_orientation(orientation)
            .map_err(|e| zbus::fdo::Error::Failed(e.to_string()))?;

        // Emit signal
        let _ = self.signal_tx.send(DaemonSignals::OrientationChanged);

        debug!("D-Bus: SetOrientation({})", orientation);
        Ok(())
    }

    /// Gets the current orientation.
    fn get_orientation(&self) -> String {
        self.state.orientation().to_string()
    }

    /// Clears the display to a solid color.
    fn clear_display(&self, color: &str) -> zbus::fdo::Result<()> {
        let color_u16 = parse_hex_color(color)
            .ok_or_else(|| zbus::fdo::Error::InvalidArgs("Invalid color format".to_string()))?;

        self.state
            .clear_display(color_u16)
            .map_err(|e| zbus::fdo::Error::Failed(e.to_string()))?;

        debug!("D-Bus: ClearDisplay({})", color);
        Ok(())
    }

    /// Sets the display face.
    fn set_face(&self, face: &str) -> zbus::fdo::Result<()> {
        self.state
            .set_face(face)
            .map_err(|e| zbus::fdo::Error::InvalidArgs(e.to_string()))?;

        let _ = self.signal_tx.send(DaemonSignals::DisplaySettingsChanged);
        debug!("D-Bus: SetFace({})", face);
        Ok(())
    }

    /// Gets the current face name.
    fn get_face(&self) -> String {
        self.state.face_name()
    }

    /// Gets the current color theme name.
    fn get_theme(&self) -> String {
        self.state.theme_name()
    }

    /// Sets the color theme by name.
    fn set_theme(&self, name: &str) -> zbus::fdo::Result<()> {
        self.state
            .set_theme(name)
            .map_err(|e| zbus::fdo::Error::InvalidArgs(e.to_string()))?;

        let _ = self.signal_tx.send(DaemonSignals::DisplaySettingsChanged);
        debug!("D-Bus: SetTheme({})", name);
        Ok(())
    }

    /// Lists available color themes (IDs only, for backwards compatibility).
    fn list_themes(&self) -> Vec<String> {
        self.state
            .available_themes()
            .iter()
            .map(|t| t.id.to_string())
            .collect()
    }

    /// Lists available color themes with display names.
    /// Returns JSON-encoded theme data.
    fn list_themes_detailed(&self) -> Vec<String> {
        self.state
            .available_themes()
            .iter()
            .map(|t| {
                serde_json::json!({
                    "id": t.id,
                    "display_name": t.display_name
                })
                .to_string()
            })
            .collect()
    }

    /// Lists available faces (IDs only).
    fn list_face_ids(&self) -> Vec<String> {
        crate::faces::available_faces()
            .iter()
            .map(|f| f.id.to_string())
            .collect()
    }

    /// Lists available faces with display names.
    /// Returns JSON-encoded face data.
    fn list_faces(&self) -> Vec<String> {
        crate::faces::available_faces()
            .iter()
            .map(|f| {
                serde_json::json!({
                    "id": f.id,
                    "display_name": f.display_name
                })
                .to_string()
            })
            .collect()
    }

    /// Returns the current framebuffer as PNG data.
    fn get_screen_png(&self) -> zbus::fdo::Result<Vec<u8>> {
        self.state
            .get_screen_png()
            .map_err(|e| zbus::fdo::Error::Failed(e.to_string()))
    }

    /// Sets LED parameters.
    async fn set_led(&self, theme: u8, intensity: u8, speed: u8) -> zbus::fdo::Result<()> {
        // Validate parameters
        if !(1..=5).contains(&theme) {
            return Err(zbus::fdo::Error::InvalidArgs(
                "Theme must be 1-5".to_string(),
            ));
        }
        if !(1..=5).contains(&intensity) {
            return Err(zbus::fdo::Error::InvalidArgs(
                "Intensity must be 1-5".to_string(),
            ));
        }
        if !(1..=5).contains(&speed) {
            return Err(zbus::fdo::Error::InvalidArgs(
                "Speed must be 1-5".to_string(),
            ));
        }

        self.state
            .set_led(theme, intensity, speed)
            .await
            .map_err(|e| zbus::fdo::Error::Failed(e.to_string()))?;

        // Emit signal
        let _ = self.signal_tx.send(DaemonSignals::LedChanged);

        debug!("D-Bus: SetLed({}, {}, {})", theme, intensity, speed);
        Ok(())
    }

    /// Turns off LEDs.
    async fn led_off(&self) -> zbus::fdo::Result<()> {
        self.state
            .led_off()
            .await
            .map_err(|e| zbus::fdo::Error::Failed(e.to_string()))?;

        // Emit signal
        let _ = self.signal_tx.send(DaemonSignals::LedChanged);

        debug!("D-Bus: LedOff");
        Ok(())
    }

    /// Gets current LED settings as (theme, intensity, speed).
    fn get_led_settings(&self) -> (u8, u8, u8) {
        self.state.led_settings()
    }

    /// Shuts down the daemon.
    async fn quit(&self) -> zbus::fdo::Result<()> {
        info!("D-Bus: Quit requested");
        self.shutdown_tx
            .send(())
            .await
            .map_err(|e| zbus::fdo::Error::Failed(e.to_string()))?;
        Ok(())
    }

    // Properties

    /// Whether the LCD device is connected.
    #[zbus(property)]
    fn connected(&self) -> bool {
        self.state.is_lcd_connected()
    }

    /// Whether the web UI is enabled.
    #[zbus(property)]
    fn web_enabled(&self) -> bool {
        self.state.is_web_enabled()
    }

    /// Current display orientation.
    #[zbus(property)]
    fn orientation(&self) -> String {
        self.state.orientation().to_string()
    }

    /// Current LED theme (1-5).
    #[zbus(property)]
    fn led_theme(&self) -> u8 {
        self.state.led_settings().0
    }

    /// Current LED intensity (1-5).
    #[zbus(property)]
    fn led_intensity(&self) -> u8 {
        self.state.led_settings().1
    }

    /// Current LED speed (1-5).
    #[zbus(property)]
    fn led_speed(&self) -> u8 {
        self.state.led_settings().2
    }

    /// Current color theme name.
    #[zbus(property)]
    fn theme(&self) -> String {
        self.state.theme_name()
    }

    /// Current display face name.
    #[zbus(property)]
    fn face(&self) -> String {
        self.state.face_name()
    }

    /// Lists all available network interfaces.
    fn list_network_interfaces(&self) -> Vec<String> {
        self.state.list_network_interfaces()
    }

    /// Lists available complications for the current face.
    /// Returns a list of (id, name, description, enabled) tuples.
    fn list_complications(&self) -> Vec<(String, String, String, bool)> {
        let available = self.state.available_complications();
        let enabled = self.state.enabled_complications();
        available
            .into_iter()
            .map(|c| {
                let is_enabled = enabled.contains(&c.id);
                (c.id, c.name, c.description, is_enabled)
            })
            .collect()
    }

    /// Lists available complications with full details including options.
    /// Returns JSON-encoded complication data.
    fn list_complications_detailed(&self) -> Vec<String> {
        let available = self.state.available_complications();
        let enabled = self.state.enabled_complications();
        let face_name = self.state.face_name();

        available
            .into_iter()
            .map(|c| {
                let is_enabled = enabled.contains(&c.id);
                // Get current option values
                let options: Vec<serde_json::Value> = c.options.iter().map(|opt| {
                    let current_value = self.state.get_complication_option(&c.id, &opt.id)
                        .unwrap_or_else(|| opt.default_value.clone());

                    match &opt.option_type {
                        crate::faces::ComplicationOptionType::Choice(choices) => {
                            // For network interface, dynamically get available interfaces
                            let choice_list: Vec<serde_json::Value> = if c.id == "network" && opt.id == "interface" {
                                let mut ifaces: Vec<serde_json::Value> = vec![
                                    serde_json::json!({"value": "auto", "label": "Auto-detect"})
                                ];
                                for iface in self.state.list_network_interfaces() {
                                    ifaces.push(serde_json::json!({"value": iface, "label": iface}));
                                }
                                ifaces
                            } else {
                                choices.iter().map(|ch| {
                                    serde_json::json!({"value": ch.value, "label": ch.label})
                                }).collect()
                            };
                            serde_json::json!({
                                "id": opt.id,
                                "name": opt.name,
                                "description": opt.description,
                                "current_value": current_value,
                                "type": "choice",
                                "choices": choice_list
                            })
                        }
                        crate::faces::ComplicationOptionType::Boolean => {
                            serde_json::json!({
                                "id": opt.id,
                                "name": opt.name,
                                "description": opt.description,
                                "current_value": current_value,
                                "type": "boolean",
                                "choices": [
                                    {"value": "true", "label": "Yes"},
                                    {"value": "false", "label": "No"}
                                ]
                            })
                        }
                        crate::faces::ComplicationOptionType::Range { min, max, step } => {
                            serde_json::json!({
                                "id": opt.id,
                                "name": opt.name,
                                "description": opt.description,
                                "current_value": current_value,
                                "type": "range",
                                "min": min,
                                "max": max,
                                "step": step
                            })
                        }
                    }
                }).collect();

                serde_json::json!({
                    "id": c.id,
                    "name": c.name,
                    "description": c.description,
                    "enabled": is_enabled,
                    "options": options,
                    "face": face_name
                }).to_string()
            })
            .collect()
    }

    /// Gets enabled complications for the current face.
    fn get_enabled_complications(&self) -> Vec<String> {
        self.state.enabled_complications().into_iter().collect()
    }

    /// Enables a complication for the current face.
    fn enable_complication(&self, complication_id: &str) -> zbus::fdo::Result<()> {
        self.state
            .set_complication_enabled(complication_id, true)
            .map_err(|e| zbus::fdo::Error::InvalidArgs(e.to_string()))?;
        let _ = self.signal_tx.send(DaemonSignals::DisplaySettingsChanged);
        debug!("D-Bus: EnableComplication({})", complication_id);
        Ok(())
    }

    /// Disables a complication for the current face.
    fn disable_complication(&self, complication_id: &str) -> zbus::fdo::Result<()> {
        self.state
            .set_complication_enabled(complication_id, false)
            .map_err(|e| zbus::fdo::Error::InvalidArgs(e.to_string()))?;
        let _ = self.signal_tx.send(DaemonSignals::DisplaySettingsChanged);
        debug!("D-Bus: DisableComplication({})", complication_id);
        Ok(())
    }

    /// Gets a complication option value.
    fn get_complication_option(
        &self,
        complication_id: &str,
        option_id: &str,
    ) -> zbus::fdo::Result<String> {
        self.state
            .get_complication_option(complication_id, option_id)
            .ok_or_else(|| {
                zbus::fdo::Error::InvalidArgs(format!(
                    "Unknown option '{}' for complication '{}'",
                    option_id, complication_id
                ))
            })
    }

    /// Sets a complication option value.
    fn set_complication_option(
        &self,
        complication_id: &str,
        option_id: &str,
        value: &str,
    ) -> zbus::fdo::Result<()> {
        self.state
            .set_complication_option(complication_id, option_id, value)
            .map_err(|e| zbus::fdo::Error::InvalidArgs(e.to_string()))?;
        let _ = self
            .signal_tx
            .send(DaemonSignals::ComplicationOptionChanged);
        debug!(
            "D-Bus: SetComplicationOption({}, {}, {})",
            complication_id, option_id, value
        );
        Ok(())
    }
}

/// Connects to the appropriate D-Bus bus based on configuration.
async fn connect_to_bus(bus_type: DbusBusType) -> anyhow::Result<(Connection, &'static str)> {
    match bus_type {
        DbusBusType::Session => {
            let conn = Connection::session()
                .await
                .map_err(|e| anyhow::anyhow!("Failed to connect to session bus: {}", e))?;
            Ok((conn, "session"))
        }
        DbusBusType::System => {
            let conn = Connection::system()
                .await
                .map_err(|e| anyhow::anyhow!("Failed to connect to system bus: {}", e))?;
            Ok((conn, "system"))
        }
        DbusBusType::Auto => {
            // Try session bus first, fall back to system bus
            match Connection::session().await {
                Ok(conn) => Ok((conn, "session")),
                Err(session_err) => {
                    warn!(
                        "Session bus unavailable ({}), trying system bus",
                        session_err
                    );
                    let conn = Connection::system().await.map_err(|system_err| {
                        anyhow::anyhow!(
                            "Failed to connect to any D-Bus: session={}, system={}",
                            session_err,
                            system_err
                        )
                    })?;
                    Ok((conn, "system"))
                }
            }
        }
    }
}

/// Runs the D-Bus server.
pub async fn run_dbus_server(
    state: Arc<AppState>,
    signal_tx: broadcast::Sender<DaemonSignals>,
    shutdown_tx: tokio::sync::mpsc::Sender<()>,
    bus_type: DbusBusType,
) -> anyhow::Result<Connection> {
    let interface = Daemon1Interface::new(state, signal_tx, shutdown_tx);

    let (connection, bus_name) = connect_to_bus(bus_type).await?;

    connection
        .object_server()
        .at("/org/ht32panel/Daemon", interface)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to register object: {}", e))?;

    connection
        .request_name("org.ht32panel.Daemon")
        .await
        .map_err(|e| anyhow::anyhow!("Failed to request bus name: {}", e))?;

    info!(
        "D-Bus service registered at org.ht32panel.Daemon on {} bus",
        bus_name
    );
    Ok(connection)
}