enody 0.1.9

SDK for Enody Lighting devices
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
use clap::{Parser, Subcommand};
use enody::{
    environment::{DiscoveryEnvironment, Environment},
    usb::UsbEnvironment,
};
use std::path::PathBuf;

macro_rules! vprintln {
    ($verbose:expr, $($arg:tt)*) => {
        if $verbose {
            println!($($arg)*);
        }
    };
}

#[derive(Parser)]
#[command(name = "enody")]
#[command(about = "Enody Host SDK CLI", long_about = None)]
struct EnodyCLI {
    /// Enable verbose output
    #[arg(short, long, global = true)]
    verbose: bool,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// List all attached Enody devices
    List,

    /// Display detailed information about all attached devices
    Info,

    /// Monitor log output from all attached devices
    Monitor,

    /// Monitor USB hotplug events (arrived/left)
    Hotplug,

    /// Set all fixtures to a blackbody configuration
    SetBlackbody {
        /// Correlated color temperature in Kelvin
        cct: f32,

        /// Target relative flux (0.0 to 1.0, default: 0.5)
        #[arg(short, long, default_value_t = 0.5)]
        flux: f32,
    },

    /// Set all fixtures to a chromaticity configuration
    SetChromaticity {
        /// CIE 1931 x coordinate
        x: f32,

        /// CIE 1931 y coordinate
        y: f32,

        /// Target relative flux (0.0 to 1.0, default: 0.5)
        #[arg(short, long, default_value_t = 0.5)]
        flux: f32,
    },

    /// Strobe all fixtures between off and a target flux at a given CCT
    Strobe {
        /// Correlated color temperature in Kelvin
        cct: f32,

        /// Target relative flux (0.0 to 1.0, default: 0.5)
        #[arg(short, long, default_value_t = 0.5)]
        flux: f32,

        /// Duration in seconds (default: 1.0)
        #[arg(short, long, default_value_t = 1.0)]
        duration: f32,

        /// Target framerate in fps (default: 60, max: 240)
        #[arg(short, long, default_value_t = 60.0)]
        rate: f32,
    },

    /// Linear fade between two blackbody CCT/flux settings
    Fade {
        /// Starting CCT in Kelvin (default: 3200)
        #[arg(long, default_value_t = 3200.0)]
        from_cct: f32,

        /// Ending CCT in Kelvin (default: 1000)
        #[arg(long, default_value_t = 1000.0)]
        to_cct: f32,

        /// Starting relative flux (default: 0.5)
        #[arg(long, default_value_t = 0.5)]
        from_flux: f32,

        /// Ending relative flux (default: 0.5)
        #[arg(long, default_value_t = 0.5)]
        to_flux: f32,

        /// Duration in seconds (default: 1.0)
        #[arg(short, long, default_value_t = 1.0)]
        duration: f32,

        /// Target framerate in fps (default: 60, max: 240)
        #[arg(short, long, default_value_t = 60.0)]
        rate: f32,
    },

    /// Scan each emitter individually, activating one at a time
    Scan {
        /// Relative flux for each emitter (0.0 to 1.0, default: 0.5)
        #[arg(short, long, default_value_t = 0.5)]
        flux: f32,

        /// Duration each emitter is held on, in milliseconds (default: 200)
        #[arg(short, long, default_value_t = 200)]
        duration: u64,
    },

    /// Download spectral data from all emitters and save as JSON
    DownloadSpectralData {
        /// Output file path
        #[arg(short, long, default_value = "spectral-data.json")]
        output: String,
    },

    /// Update selected device to newest firmware
    Update {
        /// Path to an offline firmware image (.bin)
        #[arg(short, long, value_name = "FILE")]
        firmware: Option<PathBuf>,
        /// Force update even if device does not respond to host identification
        #[arg(long)]
        force: bool,
    },
    SettingGet {
        key: String,
    },
    SettingSet {
        key: String,
        value: String,
    },
    SettingDelete {
        key: String,
    },
}

#[tokio::main]
async fn main() -> Result<(), enody::Error> {
    env_logger::Builder::from_default_env()
        .format_timestamp_millis()
        .init();

    let cli = EnodyCLI::parse();
    match cli.command {
        Commands::List => list_devices().await?,
        Commands::Info => info_devices().await?,
        Commands::Monitor => monitor_devices().await?,
        Commands::Hotplug => hotplug_monitor().await?,
        Commands::SetBlackbody { cct, flux } => set_blackbody(cct, flux, cli.verbose).await?,
        Commands::SetChromaticity { x, y, flux } => {
            set_chromaticity(x, y, flux, cli.verbose).await?
        }
        Commands::Strobe {
            cct,
            flux,
            duration,
            rate,
        } => strobe(cct, flux, duration, rate, cli.verbose).await?,
        Commands::Fade {
            from_cct,
            to_cct,
            from_flux,
            to_flux,
            duration,
            rate,
        } => {
            fade(
                from_cct,
                to_cct,
                from_flux,
                to_flux,
                duration,
                rate,
                cli.verbose,
            )
            .await?
        }
        Commands::Scan { flux, duration } => scan(flux, duration).await?,
        Commands::DownloadSpectralData { output } => download_spectral_data(&output).await?,
        Commands::Update { firmware, force } => {
            enody::update::update_remote_host(firmware, force).await?
        }
        Commands::SettingGet { key } => setting_get(&key).await?,
        Commands::SettingSet { key, value } => setting_set(&key, &value, cli.verbose).await?,
        Commands::SettingDelete { key } => setting_delete(&key, cli.verbose).await?,
    }

    Ok(())
}

async fn list_devices() -> Result<(), enody::Error> {
    // Create a USB environment - this automatically enumerates attached devices
    let environment = UsbEnvironment::new();

    // Get runtimes and create hosts via RemoteRuntime
    let runtimes = environment.runtimes();
    if runtimes.is_empty() {
        println!("No Enody devices found.");
    } else {
        for runtime in runtimes {
            let Ok(host) = runtime.host().await else {
                println!("Failed to query host.");
                continue;
            };
            println!("Device {}", host.identifier());
            println!("\tVersion: {}", host.version());
        }
    }

    Ok(())
}

async fn info_devices() -> Result<(), enody::Error> {
    let environment = UsbEnvironment::new();
    let runtimes = environment.runtimes();

    if runtimes.is_empty() {
        println!("No Enody devices found.");
        return Ok(());
    }

    for (device_idx, runtime) in runtimes.iter().enumerate() {
        if device_idx > 0 {
            println!();
        }

        println!("══════════════════════════════════════════════════════════════");
        println!("Device {}", device_idx + 1);
        println!("══════════════════════════════════════════════════════════════");

        // Query host information
        let Ok(host) = runtime.host().await else {
            println!("  Failed to query host");
            continue;
        };

        println!();
        println!("Host");
        println!("────────────────────────────────────────────────────────────────");
        println!("  Identifier: {}", host.identifier());
        println!("  Version:    {}", host.version());

        // Discover fixtures and display their info
        let Ok(fixtures) = host.fixtures().await else {
            println!("  Failed to discover fixtures");
            continue;
        };
        println!("  Fixtures:   {}", fixtures.len());

        for (fixture_idx, fixture) in fixtures.iter().enumerate() {
            println!();
            println!("Fixture {}", fixture_idx + 1);
            println!("────────────────────────────────────────────────────────────────");
            println!("  Identifier: {}", fixture.identifier());

            // Discover sources for this fixture
            let sources = fixture.sources().await;
            let Ok(sources) = sources else {
                println!(
                    "  Sources:    (failed to discover: {:?})",
                    sources.err().unwrap()
                );
                continue;
            };
            println!("  Sources:    {}", sources.len());

            for (source_idx, source) in sources.iter().enumerate() {
                println!();
                println!("  Source {}", source_idx + 1);
                println!("  ──────────────────────────────────────────────────────────");
                println!("    Identifier: {}", source.identifier());

                match source.emitter_count().await {
                    Ok(count) => println!("    Emitters:   {}", count),
                    Err(e) => println!("    Emitters:   (failed to query: {:?})", e),
                }
            }
        }
    }

    Ok(())
}

async fn monitor_devices() -> Result<(), enody::Error> {
    let environment = UsbEnvironment::new();
    let runtimes = environment.runtimes();

    if runtimes.is_empty() {
        println!("No Enody devices found.");
        return Ok(());
    }

    println!(
        "Monitoring {} device(s). Press Ctrl+C to exit.",
        runtimes.len()
    );

    // Enable logging on all runtimes
    for runtime in &runtimes {
        runtime.enable_logging();
    }

    // Wait for Ctrl+C
    tokio::signal::ctrl_c()
        .await
        .expect("Failed to listen for Ctrl+C");

    println!("\nShutting down...");
    Ok(())
}

async fn hotplug_monitor() -> Result<(), enody::Error> {
    use enody::environment::EnvironmentRuntimeEvent;

    let mut environment = UsbEnvironment::new();
    environment.start_discovery().await?;

    let initial_runtimes = environment.runtimes();
    println!("Hotplug monitor active. Press Ctrl+C to exit.");
    println!("Currently connected: {}", initial_runtimes.len());
    for runtime in &initial_runtimes {
        if let Ok(host) = runtime.host().await {
            println!("  {}", host.identifier());
        }
    }

    loop {
        tokio::select! {
            _ = tokio::signal::ctrl_c() => {
                println!("\nStopping hotplug monitor...");
                break;
            }
            event = environment.next_runtime_event() => {
                match event? {
                    EnvironmentRuntimeEvent::Arrived(runtime) => {
                        println!("Arrived: {}", runtime.connection().identifier());
                    }
                    EnvironmentRuntimeEvent::Left(runtime) => {
                        println!("Left: {}", runtime.connection().identifier());
                    }
                }
            }
        }
    }

    environment.stop_discovery().await?;
    Ok(())
}

async fn set_blackbody(cct: f32, flux: f32, verbose: bool) -> Result<(), enody::Error> {
    use enody::message::{Configuration, Flux};

    let environment = UsbEnvironment::new();
    let runtimes = environment.runtimes();

    if runtimes.is_empty() {
        vprintln!(verbose, "No Enody devices found.");
        return Ok(());
    }

    let config = Configuration::Blackbody(cct);
    let target_flux = Flux::Relative(flux);

    for runtime in &runtimes {
        let Ok(host) = runtime.host().await else {
            vprintln!(verbose, "Failed to query host");
            continue;
        };

        let Ok(fixtures) = host.fixtures().await else {
            vprintln!(verbose, "Failed to discover fixtures");
            continue;
        };

        for fixture in &fixtures {
            match fixture.display(config.clone(), target_flux.clone()).await {
                Ok((result_config, result_flux)) => {
                    vprintln!(
                        verbose,
                        "Fixture {} set to {:?} at {:?}",
                        fixture.identifier(),
                        result_config,
                        result_flux
                    );
                }
                Err(e) => {
                    vprintln!(
                        verbose,
                        "Failed to set fixture {}: {:?}",
                        fixture.identifier(),
                        e
                    );
                }
            }
        }
    }

    Ok(())
}

async fn set_chromaticity(x: f32, y: f32, flux: f32, verbose: bool) -> Result<(), enody::Error> {
    use enody::message::{Chromaticity, Configuration, Flux};

    let environment = UsbEnvironment::new();
    let runtimes = environment.runtimes();

    if runtimes.is_empty() {
        vprintln!(verbose, "No Enody devices found.");
        return Ok(());
    }

    let config = Configuration::Chromatic(Chromaticity { x, y });
    let target_flux = Flux::Relative(flux);

    for runtime in &runtimes {
        let Ok(host) = runtime.host().await else {
            vprintln!(verbose, "Failed to query host");
            continue;
        };

        let Ok(fixtures) = host.fixtures().await else {
            vprintln!(verbose, "Failed to discover fixtures");
            continue;
        };

        for fixture in &fixtures {
            match fixture.display(config.clone(), target_flux.clone()).await {
                Ok((result_config, result_flux)) => {
                    vprintln!(
                        verbose,
                        "Fixture {} set to {:?} at {:?}",
                        fixture.identifier(),
                        result_config,
                        result_flux
                    );
                }
                Err(e) => {
                    vprintln!(
                        verbose,
                        "Failed to set fixture {}: {:?}",
                        fixture.identifier(),
                        e
                    );
                }
            }
        }
    }

    Ok(())
}

async fn scan(flux: f32, duration_ms: u64) -> Result<(), enody::Error> {
    use enody::message::{Configuration, Flux};
    use std::time::Duration;

    let environment = UsbEnvironment::new();
    let runtimes = environment.runtimes();

    if runtimes.is_empty() {
        println!("No Enody devices found.");
        return Ok(());
    }

    // Collect all (fixture, emitter_label, emitter) tuples across all devices
    let mut scan_entries = Vec::new();

    for runtime in &runtimes {
        let Ok(host) = runtime.host().await else {
            println!("Failed to query host");
            continue;
        };
        println!("Host: {} (v{})", host.identifier(), host.version());

        let Ok(fixtures) = host.fixtures().await else {
            println!("  Failed to discover fixtures");
            continue;
        };

        for (fi, fixture) in fixtures.into_iter().enumerate() {
            println!("Fixture {}: {}", fi, fixture.identifier());

            let Ok(sources) = fixture.sources().await else {
                println!("  Failed to discover sources");
                continue;
            };

            for (si, source) in sources.iter().enumerate() {
                println!("  Source {}: {}", si, source.identifier());

                let Ok(emitters) = source.emitters().await else {
                    println!("    Failed to discover emitters");
                    continue;
                };

                for (ei, emitter) in emitters.into_iter().enumerate() {
                    let label = format!("F{}S{}E{}", fi, si, ei);
                    println!("    Emitter {} ({}): {}", ei, label, emitter.identifier());
                    scan_entries.push((fixture.clone(), label, emitter));
                }
            }
        }
    }

    println!(
        "\nScanning {} emitters (flux {:.2} / {}ms each)...\n",
        scan_entries.len(),
        flux,
        duration_ms,
    );

    let flux_on = Flux::Relative(flux);
    let flux_off = Flux::Relative(0.0);

    for (fixture, label, emitter) in &scan_entries {
        print!("  {} ({})... ", label, emitter.identifier());

        emitter.set_flux(flux_on.clone()).await?;
        fixture
            .display(Configuration::Manual, Flux::Relative(0.5))
            .await?;

        tokio::time::sleep(Duration::from_millis(duration_ms)).await;

        emitter.set_flux(flux_off.clone()).await?;
        fixture
            .display(Configuration::Manual, Flux::Relative(0.5))
            .await?;

        println!("done");
    }

    println!("\nScan complete.");
    Ok(())
}

async fn download_spectral_data(output_path: &str) -> Result<(), enody::Error> {
    use enody::spectral::{
        EmitterSpectralData, FixtureSpectralData, HostSpectralData, SourceSpectralData,
    };

    if std::path::Path::new(output_path).exists() {
        return Err(enody::Error::Debug(format!(
            "Output file already exists: {}",
            output_path
        )));
    }

    let environment = UsbEnvironment::new();
    let runtimes = environment.runtimes();

    if runtimes.is_empty() {
        println!("No Enody devices found.");
        return Ok(());
    }

    // Use the first runtime
    let runtime = &runtimes[0];
    let Ok(host) = runtime.host().await else {
        println!("Failed to query host");
        return Ok(());
    };
    println!("Host: {} (v{})", host.identifier(), host.version());

    let Ok(fixtures) = host.fixtures().await else {
        println!("Failed to discover fixtures");
        return Ok(());
    };
    println!("Fixtures: {}", fixtures.len());

    let mut fixture_outputs = Vec::new();

    for (fi, fixture) in fixtures.iter().enumerate() {
        println!("  Fixture {}: {}", fi, fixture.identifier());

        let Ok(sources) = fixture.sources().await else {
            println!("    Failed to discover sources");
            continue;
        };
        println!("    Sources: {}", sources.len());

        let mut source_outputs = Vec::new();

        for (si, source) in sources.iter().enumerate() {
            println!("    Source {}: {}", si, source.identifier());

            let Ok(emitters) = source.emitters().await else {
                println!("      Failed to discover emitters");
                continue;
            };
            println!("      Emitters: {}", emitters.len());

            let mut emitter_outputs = Vec::new();

            for (ei, emitter) in emitters.iter().enumerate() {
                println!("      Emitter {}: {}", ei, emitter.identifier());

                let spectral_data = emitter.spectral_data().await?;
                println!("        Samples: {}", spectral_data.samples().len());

                emitter_outputs.push(EmitterSpectralData {
                    identifier: emitter.identifier(),
                    spectral_data,
                });
            }

            source_outputs.push(SourceSpectralData {
                identifier: source.identifier(),
                emitters: emitter_outputs,
            });
        }

        fixture_outputs.push(FixtureSpectralData {
            identifier: fixture.identifier(),
            sources: source_outputs,
        });
    }

    let output = HostSpectralData {
        host: host.info().clone(),
        fixtures: fixture_outputs,
    };

    let json = serde_json::to_string_pretty(&output)
        .map_err(|e| enody::Error::Debug(format!("JSON serialization failed: {}", e)))?;

    std::fs::write(output_path, &json)
        .map_err(|e| enody::Error::Debug(format!("Failed to write {}: {}", output_path, e)))?;

    println!("Spectral data written to {}", output_path);
    Ok(())
}

async fn strobe(
    cct: f32,
    flux: f32,
    duration: f32,
    rate: f32,
    verbose: bool,
) -> Result<(), enody::Error> {
    use enody::message::{Configuration, Flux};
    use std::time::Duration;

    let environment = UsbEnvironment::new();
    let runtimes = environment.runtimes();

    if runtimes.is_empty() {
        vprintln!(verbose, "No Enody devices found.");
        return Ok(());
    }

    let config = Configuration::Blackbody(cct);
    let flux_on = Flux::Relative(flux);
    let flux_off = Flux::Relative(0.0);
    let frame_duration = Duration::from_secs_f32(1.0 / rate.min(240.0));
    let total_frames = (duration * rate.min(240.0)) as u32;

    // Collect all fixtures across all runtimes
    let mut fixtures = Vec::new();
    for (index, runtime) in runtimes.iter().enumerate() {
        let Ok(host) = runtime.host().await else {
            vprintln!(verbose, "Failed to query host on runtime {}", index + 1);
            continue;
        };

        let Ok(f) = host.fixtures().await else {
            vprintln!(
                verbose,
                "Failed to discover fixtures on runtime {}",
                index + 1
            );
            continue;
        };
        fixtures.extend(f);
    }

    if fixtures.is_empty() {
        vprintln!(verbose, "No fixtures found.");
        return Ok(());
    }

    let mut interval = tokio::time::interval(frame_duration);
    let mut on = true;
    let mut cycles: u32 = 0;
    for _ in 0..total_frames {
        interval.tick().await;
        let target = if on { &flux_on } else { &flux_off };
        for fixture in &fixtures {
            let _ = fixture.display(config.clone(), target.clone()).await;
        }
        on = !on;
        cycles += 1;
    }

    // Ensure fixtures are left off
    for fixture in &fixtures {
        let _ = fixture.display(config.clone(), flux_off.clone()).await;
    }

    vprintln!(verbose, "{} cycles in {:.2}s", cycles, duration);

    Ok(())
}

async fn fade(
    from_cct: f32,
    to_cct: f32,
    from_flux: f32,
    to_flux: f32,
    duration: f32,
    rate: f32,
    verbose: bool,
) -> Result<(), enody::Error> {
    use enody::message::{Configuration, Flux};
    use std::time::Duration;

    let environment = UsbEnvironment::new();
    let runtimes = environment.runtimes();

    if runtimes.is_empty() {
        vprintln!(verbose, "No Enody devices found.");
        return Ok(());
    }

    let capped_rate = rate.min(240.0);
    let total_frames = (duration * capped_rate) as u32;
    let frame_duration = Duration::from_secs_f32(1.0 / capped_rate);

    let mut fixtures = Vec::new();
    for (index, runtime) in runtimes.iter().enumerate() {
        let Ok(host) = runtime.host().await else {
            vprintln!(verbose, "Failed to query host on runtime {}", index + 1);
            continue;
        };

        let Ok(f) = host.fixtures().await else {
            vprintln!(
                verbose,
                "Failed to discover fixtures on runtime {}",
                index + 1
            );
            continue;
        };
        fixtures.extend(f);
    }

    if fixtures.is_empty() {
        vprintln!(verbose, "No fixtures found.");
        return Ok(());
    }

    let mut interval = tokio::time::interval(frame_duration);
    for frame in 0..=total_frames {
        interval.tick().await;
        let t = if total_frames == 0 {
            1.0
        } else {
            frame as f32 / total_frames as f32
        };
        let cct = from_cct + (to_cct - from_cct) * t;
        let flux = from_flux + (to_flux - from_flux) * t;
        let config = Configuration::Blackbody(cct);
        let target_flux = Flux::Relative(flux);

        for fixture in &fixtures {
            let _ = fixture.display(config.clone(), target_flux.clone()).await;
        }
    }

    vprintln!(
        verbose,
        "Fade complete: {} frames in {:.2}s",
        total_frames + 1,
        duration
    );

    Ok(())
}

async fn setting_get(key: &str) -> Result<(), enody::Error> {
    let environment = UsbEnvironment::new();
    let runtimes = environment.runtimes();

    if runtimes.is_empty() {
        println!("No Enody devices found.");
        return Ok(());
    }

    for runtime in &runtimes {
        let Ok(value) = runtime.setting_get::<Vec<u8>>(key).await else {
            println!("Failed to get setting '{}'", key);
            continue;
        };
        println!("{}: {:?}", key, value);
    }

    Ok(())
}

// Action commands — verbose-gated (like set_blackbody / set_chromaticity):
async fn setting_set(key: &str, value: &str, verbose: bool) -> Result<(), enody::Error> {
    let environment = UsbEnvironment::new();
    let runtimes = environment.runtimes();

    if runtimes.is_empty() {
        vprintln!(verbose, "No Enody devices found.");
        return Ok(());
    }

    let parsed: Vec<u8> = value.as_bytes().to_vec();

    for runtime in &runtimes {
        match runtime.setting_set(key, parsed.clone()).await {
            Ok(()) => vprintln!(verbose, "Set '{}' = {:?}", key, parsed),
            Err(e) => vprintln!(verbose, "Failed to set '{}': {:?}", key, e),
        }
    }

    Ok(())
}

async fn setting_delete(key: &str, verbose: bool) -> Result<(), enody::Error> {
    let environment = UsbEnvironment::new();
    let runtimes = environment.runtimes();

    if runtimes.is_empty() {
        vprintln!(verbose, "No Enody devices found.");
        return Ok(());
    }

    for runtime in &runtimes {
        match runtime.setting_delete(key).await {
            Ok(()) => vprintln!(verbose, "Deleted '{}'", key),
            Err(e) => vprintln!(verbose, "Failed to delete '{}': {:?}", key, e),
        }
    }

    Ok(())
}