shelly-cli 0.1.11

CLI for managing and controlling Shelly devices
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
use std::io::{self, Write};
use std::time::Duration;

use anyhow::Result;
use crossterm::{
    cursor,
    event::{self, Event, KeyCode, KeyModifiers},
    execute,
    terminal::{self, ClearType},
};
use owo_colors::OwoColorize;

use crate::api;
use crate::model::DeviceInfo;
use crate::output::format_duration_short;

/// RAII guard that restores terminal state on drop, even if the watch loop panics.
struct TerminalGuard;

impl Drop for TerminalGuard {
    fn drop(&mut self) {
        let _ = execute!(io::stdout(), cursor::Show, terminal::LeaveAlternateScreen);
        let _ = terminal::disable_raw_mode();
    }
}

struct DeviceSnapshot {
    name: String,
    online: bool,
    switches: Vec<SwitchSnapshot>,
    temperature_c: Option<f64>,
    rssi: Option<i32>,
    uptime: Option<u64>,
}

struct SwitchSnapshot {
    id: u8,
    output: bool,
    power_watts: Option<f64>,
    voltage: Option<f64>,
    total_energy_wh: Option<f64>,
}

/// A selectable row in the watch table, mapping to a device + switch.
struct SelectableRow {
    device_index: usize,
    switch_id: u8,
    is_online: bool,
    has_switch: bool,
}

pub async fn run(
    devices: &[DeviceInfo],
    client: &reqwest::Client,
    password: Option<String>,
    interval: Duration,
) -> Result<()> {
    terminal::enable_raw_mode()?;
    let _guard = TerminalGuard;
    let mut stdout = io::stdout();
    execute!(stdout, terminal::EnterAlternateScreen, cursor::Hide)?;

    watch_loop(devices, client, &password, interval, &mut stdout).await
}

async fn watch_loop(
    devices: &[DeviceInfo],
    client: &reqwest::Client,
    password: &Option<String>,
    interval: Duration,
    stdout: &mut io::Stdout,
) -> Result<()> {
    let mut selected: usize = 0;
    let mut status_msg: Option<(String, tokio::time::Instant)> = None;

    loop {
        let snapshots = poll_all(devices, client, password).await;
        let rows = build_selectable_rows(&snapshots);

        // Clamp selection
        let row_count = rows.len();
        if row_count > 0 && selected >= row_count {
            selected = row_count - 1;
        }

        render(stdout, &snapshots, selected, &status_msg)?;

        // Wait for interval or keypress
        let deadline = tokio::time::Instant::now() + interval;
        loop {
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            if remaining.is_zero() {
                break;
            }

            // Clear expired status messages
            if let Some((_, expires)) = &status_msg
                && tokio::time::Instant::now() >= *expires
            {
                status_msg = None;
                render(stdout, &snapshots, selected, &status_msg)?;
            }

            if event::poll(remaining.min(Duration::from_millis(100)))?
                && let Event::Key(key) = event::read()?
            {
                match key.code {
                    KeyCode::Char('q') | KeyCode::Esc => return Ok(()),
                    KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                        return Ok(());
                    }
                    KeyCode::Up | KeyCode::Char('k') if selected > 0 => {
                        selected -= 1;
                        render(stdout, &snapshots, selected, &status_msg)?;
                    }
                    KeyCode::Down | KeyCode::Char('j')
                        if row_count > 0 && selected < row_count - 1 =>
                    {
                        selected += 1;
                        render(stdout, &snapshots, selected, &status_msg)?;
                    }
                    KeyCode::Home => {
                        selected = 0;
                        render(stdout, &snapshots, selected, &status_msg)?;
                    }
                    KeyCode::End => {
                        if row_count > 0 {
                            selected = row_count - 1;
                        }
                        render(stdout, &snapshots, selected, &status_msg)?;
                    }
                    KeyCode::Enter | KeyCode::Char(' ') => {
                        if let Some(row) = rows.get(selected) {
                            if !row.is_online {
                                status_msg = Some((
                                    "device is offline".to_string(),
                                    tokio::time::Instant::now() + Duration::from_secs(3),
                                ));
                            } else if !row.has_switch {
                                status_msg = Some((
                                    "device has no switch".to_string(),
                                    tokio::time::Instant::now() + Duration::from_secs(3),
                                ));
                            } else {
                                let info = &devices[row.device_index];
                                let device = api::create_device(
                                    info.clone(),
                                    client.clone(),
                                    password.clone(),
                                );
                                let switch_id = row.switch_id;
                                match device.switch_toggle(switch_id).await {
                                    Ok(result) => {
                                        let new_state = if result.was_on { "OFF" } else { "ON" };
                                        status_msg = Some((
                                            format!(
                                                "toggled {}{}",
                                                info.display_name(),
                                                new_state
                                            ),
                                            tokio::time::Instant::now() + Duration::from_secs(3),
                                        ));
                                    }
                                    Err(e) => {
                                        status_msg = Some((
                                            format!("toggle failed: {e}"),
                                            tokio::time::Instant::now() + Duration::from_secs(5),
                                        ));
                                    }
                                }
                                // Break to refresh immediately after toggle
                                break;
                            }
                            render(stdout, &snapshots, selected, &status_msg)?;
                        }
                    }
                    KeyCode::Char(c @ '1'..='9') => {
                        let idx = (c as usize) - ('1' as usize);
                        if idx < row_count {
                            selected = idx;
                            render(stdout, &snapshots, selected, &status_msg)?;
                        }
                    }
                    _ => {}
                }
            }
        }
    }
}

fn build_selectable_rows(snapshots: &[DeviceSnapshot]) -> Vec<SelectableRow> {
    let mut rows = Vec::new();
    for (device_index, snap) in snapshots.iter().enumerate() {
        if !snap.online {
            rows.push(SelectableRow {
                device_index,
                switch_id: 0,
                is_online: false,
                has_switch: false,
            });
        } else if snap.switches.is_empty() {
            rows.push(SelectableRow {
                device_index,
                switch_id: 0,
                is_online: true,
                has_switch: false,
            });
        } else {
            for sw in &snap.switches {
                rows.push(SelectableRow {
                    device_index,
                    switch_id: sw.id,
                    is_online: true,
                    has_switch: true,
                });
            }
        }
    }
    rows
}

async fn poll_all(
    devices: &[DeviceInfo],
    client: &reqwest::Client,
    password: &Option<String>,
) -> Vec<DeviceSnapshot> {
    let mut snapshots = Vec::with_capacity(devices.len());

    let handles: Vec<_> = devices
        .iter()
        .map(|info| {
            let device = api::create_device(info.clone(), client.clone(), password.clone());
            let name = info.display_name().to_string();

            tokio::spawn(async move {
                match device.status().await {
                    Ok(status) => DeviceSnapshot {
                        name,
                        online: true,
                        switches: status
                            .switches
                            .iter()
                            .map(|sw| SwitchSnapshot {
                                id: sw.id,
                                output: sw.output,
                                power_watts: sw.power_watts,
                                voltage: sw.voltage,
                                total_energy_wh: sw.total_energy_wh,
                            })
                            .collect(),
                        temperature_c: status.temperature_c,
                        rssi: status.wifi.as_ref().and_then(|w| w.rssi),
                        uptime: status.uptime,
                    },
                    Err(_) => DeviceSnapshot {
                        name,
                        online: false,
                        switches: Vec::new(),
                        temperature_c: None,
                        rssi: None,
                        uptime: None,
                    },
                }
            })
        })
        .collect();

    for handle in handles {
        if let Ok(snapshot) = handle.await {
            snapshots.push(snapshot);
        }
    }

    snapshots
}

fn render(
    stdout: &mut io::Stdout,
    snapshots: &[DeviceSnapshot],
    selected: usize,
    status_msg: &Option<(String, tokio::time::Instant)>,
) -> Result<()> {
    execute!(
        stdout,
        cursor::MoveTo(0, 0),
        terminal::Clear(ClearType::All)
    )?;

    let now = chrono::Local::now().format("%H:%M:%S");
    writeln!(
        stdout,
        " {}  |  {now}  |  {} select  {} toggle  {} quit\r",
        "shelly watch".bold(),
        "↑↓".bold(),
        "".bold(),
        "q".bold(),
    )?;

    // Show status message if active
    if let Some((msg, _)) = status_msg {
        writeln!(stdout, " {}\r", msg.yellow())?;
    } else {
        writeln!(stdout, "\r")?;
    }

    let header = format!(
        "   {:<30} {:<5} {:>8} {:>8} {:>7} {:>10} {:>6} Uptime",
        "Device", "State", "Power", "Voltage", "Temp", "Energy", "RSSI"
    );
    writeln!(stdout, "{}\r", header.bold())?;

    writeln!(stdout, "   {}\r", "-".repeat(93).dimmed())?;

    let mut total_power = 0.0;
    let mut on_count = 0u32;
    let mut total_count = 0u32;
    let mut online_count = 0u32;
    let mut row_idx = 0usize;

    for snap in snapshots {
        if !snap.online {
            let indicator = if row_idx == selected {
                ">".bold().cyan().to_string()
            } else {
                " ".to_string()
            };
            let line = format!(
                " {} {:<30} {:<5} {:>8} {:>8} {:>7} {:>10} {:>6} -",
                indicator,
                snap.name.red(),
                "OFFLINE".red().bold(),
                "-".dimmed(),
                "-".dimmed(),
                "-".dimmed(),
                "-".dimmed(),
                "-".dimmed()
            );
            if row_idx == selected {
                writeln!(stdout, "{}\r", line.on_bright_black())?;
            } else {
                writeln!(stdout, "{line}\r")?;
            }
            total_count += 1;
            row_idx += 1;
            continue;
        }

        online_count += 1;

        if snap.switches.is_empty() {
            let indicator = if row_idx == selected {
                ">".bold().cyan().to_string()
            } else {
                " ".to_string()
            };
            let temp = snap
                .temperature_c
                .map(|t| format!("{t:.0}°C"))
                .unwrap_or_else(|| "-".into());
            let rssi = snap
                .rssi
                .map(|r| format!("{r}"))
                .unwrap_or_else(|| "-".into());
            let uptime = snap
                .uptime
                .map(format_duration_short)
                .unwrap_or_else(|| "-".into());

            let line = format!(
                " {} {:<30} {:<5} {:>8} {:>8} {:>7} {:>10} {:>6} {}",
                indicator,
                snap.name,
                "-".dimmed(),
                "-".dimmed(),
                "-".dimmed(),
                temp,
                "-".dimmed(),
                rssi,
                uptime,
            );
            if row_idx == selected {
                writeln!(stdout, "{}\r", line.on_bright_black())?;
            } else {
                writeln!(stdout, "{line}\r")?;
            }
            total_count += 1;
            row_idx += 1;
        } else {
            for sw in &snap.switches {
                total_count += 1;
                let indicator = if row_idx == selected {
                    ">".bold().cyan().to_string()
                } else {
                    " ".to_string()
                };

                let label = if snap.switches.len() > 1 {
                    format!("{} [{}]", snap.name, sw.id)
                } else {
                    snap.name.clone()
                };

                let (state, state_padded): (String, String) = if sw.output {
                    on_count += 1;
                    let s = "ON".green().to_string();
                    (s.clone(), format!("{s}   "))
                } else {
                    let s = "OFF".dimmed().to_string();
                    (s.clone(), format!("{s}  "))
                };
                let _ = state; // used via state_padded

                let power = sw
                    .power_watts
                    .map(|p| {
                        total_power += p;
                        format!("{p:.1}W")
                    })
                    .unwrap_or_else(|| "-".into());

                let voltage = sw
                    .voltage
                    .map(|v| format!("{v:.0}V"))
                    .unwrap_or_else(|| "-".into());

                let temp = snap
                    .temperature_c
                    .map(|t| format!("{t:.0}°C"))
                    .unwrap_or_else(|| "-".into());

                let energy = sw
                    .total_energy_wh
                    .map(|e| format!("{:.1}kWh", e / 1000.0))
                    .unwrap_or_else(|| "-".into());

                let rssi = snap
                    .rssi
                    .map(|r| format!("{r}"))
                    .unwrap_or_else(|| "-".into());

                let uptime = snap
                    .uptime
                    .map(format_duration_short)
                    .unwrap_or_else(|| "-".into());

                let line = format!(
                    " {} {:<30} {} {:>8} {:>8} {:>7} {:>10} {:>6} {}",
                    indicator, label, state_padded, power, voltage, temp, energy, rssi, uptime,
                );
                if row_idx == selected {
                    writeln!(stdout, "{}\r", line.on_bright_black())?;
                } else {
                    writeln!(stdout, "{line}\r")?;
                }
                row_idx += 1;
            }
        }
    }

    writeln!(stdout, "   {}\r", "-".repeat(93).dimmed())?;

    let power_display = format!("{total_power:.1}W").bold().to_string();
    writeln!(
        stdout,
        "   Total: {power_display}  |  {on_count}/{total_count} ON  |  {online_count}/{} online\r",
        snapshots.len()
    )?;

    stdout.flush()?;
    Ok(())
}