Skip to main content

openlogi_core/
device.rs

1//! Serializable device-model types.
2//!
3//! These mirror the HID++ types from the `hidpp` crate but live here so the
4//! CLI and any future GUI can depend on them without dragging in the protocol
5//! crate or its async transport.
6
7use serde::{Deserialize, Serialize};
8
9mod light;
10
11pub use light::{LightCapabilities, LightValueRange, LightValueRangeError, LightValueUnit};
12
13/// What a paired peripheral is. Mirrors `hidpp::receiver::bolt::BoltDeviceKind`
14/// but is owned by us so consumers don't depend on `hidpp`.
15///
16/// Several upstream "device type" vocabularies feed this one enum, and they do
17/// **not** agree on numbers: the Bolt pairing register uses `Unknown=0,
18/// Keyboard=1, Mouse=2, …`, while the HID++ `0x0005` feature uses
19/// `Keyboard=0, …, Mouse=3, …` (no `Unknown` at all). The asset registry adds a
20/// third, free-form *string* type (`"mouse"`, case-inconsistently `"MOUSE"`).
21/// They are converted to this enum at their respective boundaries — never by
22/// reinterpreting one source's raw byte with another's table — so the numeric
23/// mismatch can't leak past those mappers.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
25#[serde(rename_all = "lowercase")]
26pub enum DeviceKind {
27    /// Mice — the family OpenLogi's binding/DPI panels primarily target.
28    Mouse,
29    /// Keyboards, including lighting-capable ones.
30    Keyboard,
31    /// Standalone numeric keypads.
32    Numpad,
33    /// Presentation remotes (slide clickers).
34    Presenter,
35    /// Remote controls; the registry's `"remotecontrol"` string also folds here.
36    Remote,
37    /// Trackballs — treated like mice for presumed capabilities.
38    Trackball,
39    /// External touchpads; the registry's `"trackpad"` string also folds here.
40    Touchpad,
41    /// Pen/graphics tablets.
42    Tablet,
43    /// Game controllers, mirrored from the Bolt pairing vocabulary.
44    Gamepad,
45    /// Joysticks, mirrored from the Bolt pairing vocabulary.
46    Joystick,
47    /// Audio headsets paired through a receiver.
48    Headset,
49    /// Logitech webcam (UVC), configured through `openlogi-camera`.
50    Camera,
51    /// Not classified by any source — also the "no asset opinion" value
52    /// [`DeviceKind::from_registry_type`] returns for unmodelled strings.
53    Unknown,
54    /// Standalone light or other illumination device controlled outside HID++.
55    ///
56    /// This is an identity hint only. UI controls are gated by the dedicated
57    /// light capability descriptor, never by this variant alone.
58    Light,
59}
60
61impl DeviceKind {
62    /// Parse the OpenLogi asset registry's `type` string into a [`DeviceKind`].
63    ///
64    /// The registry field is free-form and case-inconsistent (both `"mouse"`
65    /// and `"MOUSE"` ship), so we case-fold before matching. Values we don't
66    /// model map to [`DeviceKind::Unknown`], which callers treat as "no asset
67    /// opinion" and fall back to the HID++ classification.
68    #[must_use]
69    pub fn from_registry_type(raw: &str) -> Self {
70        match raw.trim().to_ascii_lowercase().as_str() {
71            "mouse" => Self::Mouse,
72            "keyboard" => Self::Keyboard,
73            "numpad" => Self::Numpad,
74            "presenter" => Self::Presenter,
75            "remote" | "remotecontrol" => Self::Remote,
76            "trackball" => Self::Trackball,
77            "touchpad" | "trackpad" => Self::Touchpad,
78            "tablet" => Self::Tablet,
79            "gamepad" => Self::Gamepad,
80            "joystick" => Self::Joystick,
81            "headset" => Self::Headset,
82            "camera" => Self::Camera,
83            "light" | "lighting" | "illumination_light" => Self::Light,
84            _ => Self::Unknown,
85        }
86    }
87}
88
89/// What a device can be *configured* to do, derived from the HID++ feature
90/// table it reports (feature `0x0001`). This is the source of truth for which
91/// configuration panels the UI offers — a panel shows iff the device exposes
92/// the feature that drives it. Gating on capability rather than on
93/// [`DeviceKind`] is what keeps a misclassified device from losing its panels
94/// (issue #127): kind is an identity guess, capability is what the firmware
95/// actually announced.
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
97#[allow(
98    clippy::struct_excessive_bools,
99    reason = "capabilities is a serialized feature-bit DTO; independent booleans keep the IPC/config shape explicit"
100)]
101pub struct Capabilities {
102    /// Reprogrammable buttons — HID++ `0x1b00`–`0x1b04` (ReprogControls).
103    pub buttons: bool,
104    /// Adjustable pointer resolution — HID++ `0x2201` / `0x2202` (AdjustableDpi).
105    pub pointer: bool,
106    /// Solid-colour RGB the lighting panel can actually drive — HID++
107    /// `ColorLedEffects` (`0x8070`) or `PerKeyLighting` (`0x8080`), the features
108    /// `set_keyboard_color` writes. Backlight-only families aren't driven by the
109    /// panel, so they don't flip this and don't earn an inert Lighting tab.
110    pub lighting: bool,
111    /// Native vertical wheel inversion — HID++ `0x2121 HiResWheel` with the
112    /// firmware-reported `has_invert` capability.
113    pub scroll_inversion: bool,
114    /// HID++ `0x2121 HiResWheel` is present, so the wheel reporting resolution
115    /// can be read and changed independently of inversion support.
116    #[serde(default)]
117    pub hires_wheel: bool,
118}
119
120impl Capabilities {
121    /// Derive capabilities from the set of HID++ feature IDs a device reports.
122    /// Membership of a driving feature ID flips the corresponding flag.
123    #[must_use]
124    pub fn from_feature_ids(ids: &[u16]) -> Self {
125        const BUTTONS: [u16; 5] = [0x1b00, 0x1b01, 0x1b02, 0x1b03, 0x1b04];
126        const POINTER: [u16; 2] = [0x2201, 0x2202];
127        // PerKeyLighting (0x8080) and ColorLedEffects (0x8070) — both now driven
128        // by `set_keyboard_color` (it prefers 0x8070's fixed effect to override a
129        // running onboard profile, falling back to 0x8080 per-key). Other families
130        // (backlight 0x198x) stay out so they don't earn a tab the panel can't drive.
131        const LIGHTING: [u16; 2] = [0x8080, 0x8070];
132        let has = |family: &[u16]| ids.iter().any(|id| family.contains(id));
133        Self {
134            buttons: has(&BUTTONS),
135            pointer: has(&POINTER),
136            lighting: has(&LIGHTING),
137            scroll_inversion: false,
138            hires_wheel: ids.contains(&0x2121),
139        }
140    }
141
142    /// Best-effort capabilities for a device we could not probe (offline /
143    /// never reached), guessed from its [`DeviceKind`]. Used only as a fallback
144    /// when no measured [`Capabilities`] exist — a sleeping mouse should still
145    /// show its button/pointer panels so its bindings (host-side) stay
146    /// configurable.
147    #[must_use]
148    pub fn presumed_from_kind(kind: DeviceKind) -> Self {
149        match kind {
150            DeviceKind::Mouse | DeviceKind::Trackball => Self {
151                buttons: true,
152                pointer: true,
153                lighting: false,
154                scroll_inversion: false,
155                hires_wheel: false,
156            },
157            DeviceKind::Keyboard => Self {
158                lighting: true,
159                ..Self::default()
160            },
161            _ => Self::default(),
162        }
163    }
164}
165
166/// Coarse battery bucket reported by the device firmware.
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
168#[serde(rename_all = "lowercase")]
169pub enum BatteryLevel {
170    /// Almost depleted — the firmware's most urgent bucket.
171    Critical,
172    /// Running low; worth surfacing a charge hint.
173    Low,
174    /// Comfortable middle range, no user action needed.
175    Good,
176    /// At or near full charge.
177    Full,
178    /// The firmware did not report a level, or reported one we don't model.
179    Unknown,
180}
181
182/// Charging state. Mirrors `hidpp 0.2`'s `BatteryStatus` plus `Unknown` for
183/// values added in future protocol versions.
184#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
185#[serde(rename_all = "snake_case")]
186pub enum BatteryStatus {
187    /// Running on battery.
188    Discharging,
189    /// Charging at the normal rate.
190    Charging,
191    /// Charging at reduced current (e.g. from a weak power source).
192    ChargingSlow,
193    /// Charge complete while still connected to power.
194    Full,
195    /// The device reported a charging fault.
196    Error,
197    /// A status value this build doesn't model (future protocol additions).
198    Unknown,
199}
200
201/// Battery snapshot for one paired device, as last polled over HID++.
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203pub struct BatteryInfo {
204    /// Reported charge percentage (`0..=100`).
205    pub percentage: u8,
206    /// Coarse bucket for UI that doesn't want the raw percentage.
207    pub level: BatteryLevel,
208    /// Charging state at poll time.
209    pub status: BatteryStatus,
210}
211
212/// Identity of an enumerated receiver — no paired-device state (that lives
213/// in [`DeviceInventory::paired`]). For a direct (Bluetooth/wired) device,
214/// a synthetic entry mirroring the device's own HID identity fills this role.
215#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
216pub struct ReceiverInfo {
217    /// Product string from the HID enumeration (e.g. `"Logi Bolt Receiver"`).
218    pub name: String,
219    /// USB vendor ID (`0x046d` for Logitech).
220    pub vendor_id: u16,
221    /// USB product ID distinguishing the receiver model.
222    pub product_id: u16,
223    /// Platform-reported serial, when one is exposed. Deliberately excluded
224    /// from diagnostics (see [`crate::diagnostics::ReceiverDiag`]).
225    pub unique_id: Option<String>,
226}
227
228/// HID++ `DeviceInformation` (feature 0x0003) snapshot used to identify a
229/// device against external registries (e.g. the OpenLogi asset index).
230///
231/// `model_ids` is the per-transport PID array reported by the firmware,
232/// ordered to match the transports flagged in [`Self::transports`] (USB,
233/// eQuad, BTLE, Bluetooth) — slots that aren't enabled stay `0`. The Logi
234/// Options+ asset registry's `modelId` (e.g. `"6b023"`) is the concatenation
235/// of an extended-model byte and one of these PIDs, so callers usually want
236/// to format `extended_model_id` + `model_ids[N]` to match.
237#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
238pub struct DeviceModelInfo {
239    /// Number of firmware entities (main firmware, bootloader, …) the
240    /// device reports.
241    pub entity_count: u8,
242    /// HID++ DeviceInformation serial number, when the device supports the
243    /// optional serial-number function.
244    pub serial_number: Option<String>,
245    /// Per-unit ID bytes — unique to the physical unit, unlike the
246    /// model-level fields around it.
247    pub unit_id: [u8; 4],
248    /// Which transports the firmware supports; defines the slot order of
249    /// [`Self::model_ids`].
250    pub transports: DeviceTransports,
251    /// Per-transport PIDs ordered to match [`Self::transports`] (USB, eQuad,
252    /// BTLE, Bluetooth); slots for disabled transports stay `0`.
253    pub model_ids: [u16; 3],
254    /// Extra model byte prefixed to a PID to form the asset registry's
255    /// `modelId` — see [`Self::config_key`].
256    pub extended_model_id: u8,
257}
258
259impl DeviceModelInfo {
260    /// Stable identifier used to key per-device configuration (button
261    /// bindings, etc.) and to look up assets in the OpenLogi asset registry.
262    ///
263    /// Format: `{extended_model_id:x}{model_ids[0]:04x}` — the same string
264    /// the depot `manifest.json` uses for its `modelId` field. Example: an
265    /// MX Master 4 with `extended_model_id = 0x02` and `model_ids[0] = 0xb042`
266    /// resolves to `"2b042"`.
267    #[must_use]
268    pub fn config_key(&self) -> String {
269        format!("{:x}{:04x}", self.extended_model_id, self.model_ids[0])
270    }
271}
272
273/// Mirror of hidpp's `DeviceTransport` bitfield — one bool per protocol the
274/// device firmware exposes. The shape is dictated by HID++ feature 0x0003;
275/// a state machine doesn't fit since a single device can announce multiple
276/// transports simultaneously.
277#[allow(
278    clippy::struct_excessive_bools,
279    reason = "bitfield mirroring HID++ DeviceInformation; transports are independent flags"
280)]
281#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
282pub struct DeviceTransports {
283    /// Wired USB.
284    pub usb: bool,
285    /// Logitech eQuad — the Unifying/Bolt receiver RF protocol.
286    pub equad: bool,
287    /// Bluetooth Low Energy.
288    pub btle: bool,
289    /// Classic Bluetooth.
290    pub bluetooth: bool,
291}
292
293/// One device in the agent's inventory snapshot: a receiver pairing slot,
294/// or a direct (Bluetooth/wired) attachment under its synthetic
295/// [`ReceiverInfo`]. Embedded in [`DeviceInventory`], so its field order is
296/// IPC wire format — see that type's contract.
297#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
298pub struct PairedDevice {
299    /// Receiver-assigned slot (1..=6 for Bolt).
300    pub slot: u8,
301    /// Firmware codename (e.g. `"MX Master 3S"`), when reported.
302    pub codename: Option<String>,
303    /// Wireless product ID. `None` for offline / unreachable devices on hidpp 0.2.
304    pub wpid: Option<u16>,
305    /// Best-guess classification. Identity only — panel gating uses
306    /// [`Self::capabilities`] instead, so a misread kind can't hide panels
307    /// (issue #127).
308    pub kind: DeviceKind,
309    /// Whether the device was reachable at enumeration time; offline devices
310    /// keep their slot with reduced detail.
311    pub online: bool,
312    /// Last battery reading, `None` when offline or the device doesn't
313    /// report battery.
314    pub battery: Option<BatteryInfo>,
315    /// Output of HID++ feature 0x0003 — populated for online devices that
316    /// expose the feature. Drives asset-registry lookups in the GUI.
317    pub model_info: Option<DeviceModelInfo>,
318    /// Configuration capabilities derived from the device's HID++ feature
319    /// table. `None` for devices we couldn't probe (offline / unreachable);
320    /// the GUI then falls back to [`Capabilities::presumed_from_kind`].
321    pub capabilities: Option<Capabilities>,
322}
323
324/// Address of a standalone raw-HID interface.
325///
326/// The identity is an opaque transport-generated string. It is deliberately
327/// kept separate from the HID++ receiver/slot address so a raw device cannot
328/// accidentally enter the HID++ `Direct` path.
329#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
330pub struct RawDeviceAddress {
331    /// HID vendor ID.
332    pub vendor_id: u16,
333    /// HID product ID.
334    pub product_id: u16,
335    /// HID usage page.
336    pub usage_page: u16,
337    /// HID usage ID.
338    pub usage_id: u16,
339    /// Identity chosen by the transport: a serial when available, otherwise
340    /// an explicitly transient OS-node identity. It is never an enumeration
341    /// index and a transient value is not persisted as a physical key.
342    pub identity: String,
343}
344
345/// A standalone device that is not a HID++ receiver pairing slot.
346///
347/// This is the inventory bridge for Litra and future non-HID++ categories.
348/// Receiver-backed devices continue to use [`PairedDevice`] inside
349/// [`DeviceInventory`].
350#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
351pub struct StandaloneDevice {
352    /// Raw HID address used to re-find the interface.
353    pub address: RawDeviceAddress,
354    /// Human-readable name supplied by the OS/HID descriptor.
355    pub display_name: String,
356    /// Human-readable manufacturer, when available.
357    pub manufacturer: Option<String>,
358    /// Device serial, when the HID backend exposes one.
359    pub serial_number: Option<String>,
360    /// Stable four-byte identity when the protocol/driver provides one.
361    /// Raw HID drivers may use zeroes when no such field exists.
362    pub unit_id: [u8; 4],
363    /// Identity classification. Capability fields gate controls.
364    pub kind: DeviceKind,
365    /// Whether this interface was present in the latest completed scan.
366    pub online: bool,
367    /// HID++ capabilities are absent for a non-HID++ device.
368    pub capabilities: Option<Capabilities>,
369    /// Standalone capability descriptor, if the selected driver recognizes it.
370    pub light_capabilities: Option<LightCapabilities>,
371    /// Stable identifier of the driver family that owns this raw interface.
372    /// This is deliberately separate from the product ID so a future family
373    /// can share a protocol driver across several product variants.
374    pub driver_id: String,
375    /// Optional model-level identity in the OpenLogi asset registry.
376    ///
377    /// This is deliberately appended: `StandaloneDevice` crosses the
378    /// append-only GUI↔agent bincode wire format.
379    #[serde(default, skip_serializing_if = "Option::is_none")]
380    pub registry_model_id: Option<String>,
381}
382
383/// One receiver and its paired devices — the unit the agent's inventory
384/// snapshot is made of.
385///
386/// Crosses the agent↔GUI IPC (everything it embeds too: [`ReceiverInfo`],
387/// [`PairedDevice`], battery/model-info/capability types). bincode encodes
388/// field and variant *order*, so reordering, retyping, or wrapping any field
389/// in this tree is a wire-format change and requires a `PROTOCOL_VERSION`
390/// bump (guarded by `openlogi-agent-core/tests/wire_format.rs`).
391#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
392pub struct DeviceInventory {
393    /// The receiver's identity — synthetic (mirroring the device itself)
394    /// for a direct Bluetooth/wired attachment.
395    pub receiver: ReceiverInfo,
396    /// The devices reached through this receiver; a direct attachment
397    /// carries exactly one entry.
398    pub paired: Vec<PairedDevice>,
399}
400
401#[cfg(test)]
402mod tests {
403    #![allow(
404        clippy::expect_used,
405        reason = "range fixture construction is intentionally asserted in tests"
406    )]
407
408    use super::{
409        BatteryInfo, BatteryLevel, BatteryStatus, Capabilities, DeviceInventory, DeviceKind,
410        DeviceModelInfo, DeviceTransports, LightValueRange, LightValueUnit, PairedDevice,
411        ReceiverInfo,
412    };
413
414    fn inventory(slot: u8, wpid: Option<u16>, battery_percentage: u8) -> DeviceInventory {
415        DeviceInventory {
416            receiver: ReceiverInfo {
417                name: "Logi Bolt Receiver".to_string(),
418                vendor_id: 0x046d,
419                product_id: 0xc548,
420                unique_id: Some("receiver-1".to_string()),
421            },
422            paired: vec![PairedDevice {
423                slot,
424                codename: Some("MX Test".to_string()),
425                wpid,
426                kind: DeviceKind::Mouse,
427                online: true,
428                battery: Some(BatteryInfo {
429                    percentage: battery_percentage,
430                    level: BatteryLevel::Good,
431                    status: BatteryStatus::Discharging,
432                }),
433                model_info: Some(DeviceModelInfo {
434                    entity_count: 1,
435                    serial_number: Some("serial-1".to_string()),
436                    unit_id: [1, 2, 3, 4],
437                    transports: DeviceTransports {
438                        usb: true,
439                        equad: true,
440                        btle: false,
441                        bluetooth: false,
442                    },
443                    model_ids: [0xb023, 0, 0],
444                    extended_model_id: 0x02,
445                }),
446                capabilities: Some(Capabilities {
447                    buttons: true,
448                    pointer: true,
449                    lighting: false,
450                    scroll_inversion: false,
451                    hires_wheel: false,
452                }),
453            }],
454        }
455    }
456
457    #[test]
458    fn device_inventory_equality_includes_nested_device_fields() {
459        let base = inventory(1, Some(0xb023), 86);
460        assert_eq!(base, base.clone());
461
462        assert_ne!(
463            base,
464            inventory(2, Some(0xb023), 86),
465            "slot changes must affect inventory equality"
466        );
467        assert_ne!(
468            base,
469            inventory(1, Some(0xb024), 86),
470            "wireless product id changes must affect inventory equality"
471        );
472        assert_ne!(
473            base,
474            inventory(1, Some(0xb023), 87),
475            "nested battery changes must affect inventory equality"
476        );
477    }
478
479    #[test]
480    fn registry_type_is_case_folded() {
481        // The registry ships both `"mouse"` and `"MOUSE"`; both must resolve so
482        // the asset cross-check can't silently miss a depot.
483        assert_eq!(DeviceKind::from_registry_type("mouse"), DeviceKind::Mouse);
484        assert_eq!(DeviceKind::from_registry_type("MOUSE"), DeviceKind::Mouse);
485        assert_eq!(
486            DeviceKind::from_registry_type("  Keyboard "),
487            DeviceKind::Keyboard
488        );
489    }
490
491    #[test]
492    fn unknown_registry_type_defers_to_the_caller() {
493        // Unmodelled / empty → Unknown, i.e. "no asset opinion".
494        assert_eq!(
495            DeviceKind::from_registry_type("webcam"),
496            DeviceKind::Unknown
497        );
498        assert_eq!(DeviceKind::from_registry_type(""), DeviceKind::Unknown);
499    }
500
501    #[test]
502    fn capabilities_track_the_driving_feature_ids() {
503        use super::Capabilities;
504        // A typical MX mouse: ReprogControls (0x1b04) + ExtendedAdjustableDpi
505        // (0x2202), no lighting.
506        let mouse = Capabilities::from_feature_ids(&[0x0003, 0x1b04, 0x2121, 0x2202, 0x2110]);
507        assert_eq!(
508            mouse,
509            Capabilities {
510                buttons: true,
511                pointer: true,
512                lighting: false,
513                scroll_inversion: false,
514                hires_wheel: true,
515            }
516        );
517        // A wired G-series keyboard: PerKeyLighting (0x8080), no DPI/buttons.
518        let keyboard = Capabilities::from_feature_ids(&[0x0001, 0x8080]);
519        assert_eq!(
520            keyboard,
521            Capabilities {
522                buttons: false,
523                pointer: false,
524                lighting: true,
525                scroll_inversion: false,
526                hires_wheel: false,
527            }
528        );
529        // No driving features → nothing offered.
530        assert_eq!(
531            Capabilities::from_feature_ids(&[0x0000, 0x0003]),
532            Capabilities::default()
533        );
534    }
535
536    #[test]
537    fn persisted_capabilities_without_hires_wheel_load_as_unsupported()
538    -> Result<(), toml::de::Error> {
539        use super::Capabilities;
540
541        let capabilities: Capabilities = toml::from_str(
542            r"
543                buttons = true
544                pointer = true
545                lighting = false
546                scroll_inversion = true
547            ",
548        )?;
549
550        assert!(!capabilities.hires_wheel);
551        assert!(capabilities.scroll_inversion);
552        Ok(())
553    }
554
555    #[test]
556    fn presumed_capabilities_keep_an_unprobed_mouse_configurable() {
557        use super::Capabilities;
558        let mouse = Capabilities::presumed_from_kind(DeviceKind::Mouse);
559        assert!(mouse.buttons && mouse.pointer && !mouse.lighting);
560        assert!(Capabilities::presumed_from_kind(DeviceKind::Keyboard).lighting);
561        // An unidentified device presumes nothing — it must be measured.
562        assert_eq!(
563            Capabilities::presumed_from_kind(DeviceKind::Unknown),
564            Capabilities::default()
565        );
566    }
567
568    #[test]
569    fn light_ranges_reject_invalid_grids_and_units() {
570        assert!(LightValueRange::new(10, 1, 1, LightValueUnit::Lumens).is_err());
571        assert!(LightValueRange::new(0, 10, 0, LightValueUnit::Lumens).is_err());
572        assert!(LightValueRange::new(0, 10, 3, LightValueUnit::Lumens).is_err());
573        assert!(LightValueRange::new(0, 101, 1, LightValueUnit::Percent).is_err());
574    }
575
576    #[test]
577    fn light_ranges_quantize_without_leaving_the_advertised_grid() {
578        let range = LightValueRange::new(20, 250, 10, LightValueUnit::Lumens).expect("valid range");
579        assert_eq!(range.native_for_percent(0), Some(20));
580        assert_eq!(range.native_for_percent(50), Some(140));
581        assert_eq!(range.native_for_percent(100), Some(250));
582        assert_eq!(range.quantize(249), 250);
583        assert!(range.contains(range.native_for_percent(65).expect("mapped value")));
584    }
585
586    #[test]
587    fn invalid_light_ranges_fail_toml_deserialization() {
588        let result = toml::from_str::<LightValueRange>(
589            "min = 2700\nmax = 6500\nstep = 0\nunit = 'kelvin'\n",
590        );
591        assert!(result.is_err());
592    }
593}