Skip to main content

usb_stack/device/class/hid/
power.rs

1//! HID Power Device (UPS, power supply, battery system).
2//!
3//! Implements the *Universal Serial Bus Usage Tables for HID Power Devices*
4//! (Power Device page `0x84` and Battery System page `0x85`).  A power device is
5//! an ordinary HID device: it uses the HID descriptors and endpoints, and only
6//! differs in its report descriptor and report layout.
7//!
8//! # Reports
9//!
10//! | Report ID | Type | Direction | Payload |
11//! |-----------|------|-----------|---------|
12//! | 1 | Input | device → host | [`PowerStatus`] present + changed status |
13//! | 2 | Input | device → host | [`PowerMeasures`] voltage, current, … |
14//! | 3 | Input | device → host | [`BatteryState`] battery flags and charge |
15//! | 4 | Feature | both | [`PowerConfig`] configuration values |
16//! | 5 | Output | host → device | [`PowerControls`] switch commands |
17//!
18//! Input reports are pushed to the interrupt IN endpoint by
19//! [`PowerDevice::poll`], which the [`HidClass`](super::HidClass) calls on every
20//! device poll.  A report whose contents did not change is not re-sent, so the
21//! host sees a new input report whenever something actually changed.
22//!
23//! Feature writes (report 4) and output reports (report 5) are buffered and
24//! picked up by the application through [`PowerDevice::take_config_write`] and
25//! [`PowerDevice::take_controls`].  Feature reads return the values last passed
26//! to [`PowerDevice::set_config`] — i.e. what the device actually applied, not
27//! what the host requested.
28//!
29//! # Units
30//!
31//! Values follow the units in the specification's HID unit table:
32//!
33//! | Field | Unit | Scale |
34//! |-------|------|-------|
35//! | Voltage, transfer voltages | Volt (unit exponent −2) | centivolt |
36//! | Current | Amp (unit exponent −2) | centiamp |
37//! | Frequency | Hertz | hertz |
38//! | Percent load, state of charge | none | percent |
39//! | Temperature | Kelvin | kelvin |
40//! | Delays | second | second |
41//! | Runtime to empty | none | minute (as in Smart Battery) |
42//!
43//! Numeric fields are clamped to the logical range `0..=32767` declared in the
44//! report descriptor.
45//!
46//! # Example
47//!
48//! ```ignore
49//! use my_hal_usb::{UsbBusAllocator, UsbDeviceBuilder};
50//! use my_hal_usb::class::hid::{HidClass, power::{PowerConfig, PowerDevice, PowerStatus}};
51//! use my_hal_usb::MyBus;
52//!
53//! let alloc = UsbBusAllocator::new(MyBus::new(/* peripheral */));
54//! let mut power = HidClass::new(&alloc, PowerDevice::power_supply());
55//! let mut dev = UsbDeviceBuilder::new(&alloc, 0x2E8A, 0x000D)
56//!     .product("Bench Power Supply")
57//!     .build();
58//!
59//! power.device_mut().set_config(PowerConfig::default());
60//! power.device_mut().set_status(
61//!     PowerStatus::PRESENT | PowerStatus::GOOD | PowerStatus::USED,
62//!     PowerStatus::NONE,
63//! );
64//!
65//! loop {
66//!     dev.poll(&mut [&mut power]);
67//!
68//!     if let Some(controls) = power.device_mut().take_controls() {
69//!         // host pressed a switch in the output report
70//!     }
71//! }
72//! ```
73
74use crate::device::bus::UsbBus;
75use crate::device::class::hid::{HidDevice, HidSpec, ReportType};
76use crate::device::endpoint::EndpointIn;
77
78// ─── Usage tables ─────────────────────────────────────────────────────────────
79
80/// Power Device page (`0x84`) usage IDs.
81pub mod power_usage {
82    /// Index of a string describing the object.
83    pub const I_NAME: u8 = 0x01;
84    /// Status collection (logical).
85    pub const PRESENT_STATUS: u8 = 0x02;
86    /// Status-changed collection (logical).
87    pub const CHANGED_STATUS: u8 = 0x03;
88    /// Uninterruptible Power Supply application collection.
89    pub const UPS: u8 = 0x04;
90    /// Power Supply application collection.
91    pub const POWER_SUPPLY: u8 = 0x05;
92    /// Battery (physical collection on the Battery System page).
93    pub const BATTERY: u8 = 0x12;
94    /// Measured voltage.
95    pub const VOLTAGE: u8 = 0x30;
96    /// Measured current.
97    pub const CURRENT: u8 = 0x31;
98    /// Measured frequency.
99    pub const FREQUENCY: u8 = 0x32;
100    /// Measured load relative to the rated load.
101    pub const PERCENT_LOAD: u8 = 0x35;
102    /// Measured temperature.
103    pub const TEMPERATURE: u8 = 0x36;
104    /// Number of bad (unusable) measurements.
105    pub const BAD_COUNT: u8 = 0x38;
106    /// Configured (nominal) voltage.
107    pub const CONFIG_VOLTAGE: u8 = 0x40;
108    /// Configured (nominal) current.
109    pub const CONFIG_CURRENT: u8 = 0x41;
110    /// Configured (nominal) frequency.
111    pub const CONFIG_FREQUENCY: u8 = 0x42;
112    /// Configured (nominal) temperature.
113    pub const CONFIG_TEMPERATURE: u8 = 0x46;
114    /// Command: switch the output on.
115    pub const SWITCH_ON_CONTROL: u8 = 0x50;
116    /// Command: switch the output off.
117    pub const SWITCH_OFF_CONTROL: u8 = 0x51;
118    /// Command: toggle the output.
119    pub const TOGGLE_CONTROL: u8 = 0x52;
120    /// Voltage below which the device transfers to battery power.
121    pub const LOW_VOLTAGE_TRANSFER: u8 = 0x53;
122    /// Voltage above which the device transfers back to line power.
123    pub const HIGH_VOLTAGE_TRANSFER: u8 = 0x54;
124    /// Grace period between a shutdown request and power removal.
125    pub const DELAY_BEFORE_SHUTDOWN: u8 = 0x57;
126    /// Command: sound the audible alarm.
127    pub const AUDIBLE_ALARM_CONTROL: u8 = 0x5A;
128    /// Status flag: a power source is connected.
129    pub const PRESENT: u8 = 0x60;
130    /// Status flag: no failure detected.
131    pub const GOOD: u8 = 0x61;
132    /// Status flag: internal failure.
133    pub const INTERNAL_FAILURE: u8 = 0x62;
134    /// Status flag: voltage out of range.
135    pub const VOLTAGE_OUT_OF_RANGE: u8 = 0x63;
136    /// Status flag: frequency out of range.
137    pub const FREQUENCY_OUT_OF_RANGE: u8 = 0x64;
138    /// Status flag: overload.
139    pub const OVERLOAD: u8 = 0x65;
140    /// Status flag: over charged.
141    pub const OVER_CHARGED: u8 = 0x66;
142    /// Status flag: over temperature.
143    pub const OVER_TEMPERATURE: u8 = 0x67;
144    /// Status flag: shutdown requested.
145    pub const SHUTDOWN_REQUESTED: u8 = 0x68;
146    /// Status flag: shutdown imminent.
147    pub const SHUTDOWN_IMMINENT: u8 = 0x69;
148    /// Status flag: output is switched on.
149    pub const SWITCH_ON_OFF: u8 = 0x6B;
150    /// Status flag: output can be switched.
151    pub const SWITCHABLE: u8 = 0x6C;
152    /// Status flag: device is in use.
153    pub const USED: u8 = 0x6D;
154    /// Status flag: boosting.
155    pub const BOOST: u8 = 0x6E;
156    /// Status flag: bucking.
157    pub const BUCK: u8 = 0x6F;
158    /// Status flag: initialized.
159    pub const INITIALIZED: u8 = 0x70;
160    /// Status flag: tested.
161    pub const TESTED: u8 = 0x71;
162    /// Status flag: awaiting power.
163    pub const AWAITING_POWER: u8 = 0x72;
164    /// Status flag: communication with a module lost.
165    pub const COMMUNICATION_LOST: u8 = 0x73;
166    /// String index of the manufacturer.
167    pub const I_MANUFACTURER: u8 = 0xFD;
168    /// String index of the product.
169    pub const I_PRODUCT: u8 = 0xFE;
170    /// String index of the serial number.
171    pub const I_SERIAL_NUMBER: u8 = 0xFF;
172}
173
174/// Battery System page (`0x85`) usage IDs.
175pub mod battery_usage {
176    /// Battery (physical collection).
177    pub const BATTERY: u8 = 0x12;
178    /// Status flag: remaining capacity below the alarm limit.
179    pub const BELOW_REMAINING_CAPACITY_LIMIT: u8 = 0x42;
180    /// Status flag: charging.
181    pub const CHARGING: u8 = 0x44;
182    /// Status flag: discharging.
183    pub const DISCHARGING: u8 = 0x45;
184    /// Status flag: fully charged.
185    pub const FULLY_CHARGED: u8 = 0x46;
186    /// Status flag: battery needs replacement.
187    pub const NEED_REPLACEMENT: u8 = 0x4B;
188    /// Remaining capacity as a percentage of full charge.
189    pub const RELATIVE_STATE_OF_CHARGE: u8 = 0x64;
190    /// Remaining capacity in the units selected by `CapacityMode`.
191    pub const REMAINING_CAPACITY: u8 = 0x66;
192    /// Remaining runtime at the present discharge rate, in minutes.
193    pub const RUN_TIME_TO_EMPTY: u8 = 0x68;
194    /// Status flag: AC (line) power present.
195    pub const AC_PRESENT: u8 = 0xD0;
196    /// Status flag: battery present.
197    pub const BATTERY_PRESENT: u8 = 0xD1;
198}
199
200/// Report IDs used by a [`PowerDevice`].
201pub mod report_id {
202    /// Input report: present and changed status.
203    pub const STATUS: u8 = 1;
204    /// Input report: measurements.
205    pub const MEASURES: u8 = 2;
206    /// Input report: battery status and charge.
207    pub const BATTERY: u8 = 3;
208    /// Feature report: configuration values.
209    pub const CONFIG: u8 = 4;
210    /// Output report: switch controls.
211    pub const CONTROLS: u8 = 5;
212}
213
214// ─── Constants ────────────────────────────────────────────────────────────────
215
216/// Largest value representable by the `Logical Maximum (32767)` fields.
217const LOGICAL_MAX_16: u16 = 0x7FFF;
218
219/// Interrupt IN endpoint size; fits the largest input report including its ID.
220const IN_ENDPOINT_SIZE: u16 = 16;
221/// Interrupt OUT endpoint size; fits the one-byte control report plus its ID.
222const OUT_ENDPOINT_SIZE: u16 = 8;
223/// Polling interval of both interrupt endpoints, in milliseconds.
224const POLL_INTERVAL_MS: u8 = 16;
225
226/// Clamp a value to the logical range declared in the descriptor.
227fn clamp16(value: u16) -> u16 {
228    if value > LOGICAL_MAX_16 {
229        LOGICAL_MAX_16
230    } else {
231        value
232    }
233}
234
235/// Clamp a percentage to `0..=100`.
236fn clamp_percent(value: u8) -> u8 {
237    if value > 100 { 100 } else { value }
238}
239
240/// Copy `report` into `buf`, truncated to what the host asked for.
241fn copy_report(report: &[u8], buf: &mut [u8]) -> usize {
242    let len = report.len().min(buf.len());
243    buf[..len].copy_from_slice(&report[..len]);
244    len
245}
246
247// ─── Report descriptor ───────────────────────────────────────────────────────
248
249/// Builds a power device report descriptor for the given application usage.
250///
251/// The only byte that depends on the device type is the application usage at
252/// offset 3, so the descriptor is generated by a macro instead of being
253/// duplicated (or patched at run time, which would prevent handing the
254/// descriptor to the control pipe as a `'static` slice).
255macro_rules! power_report_descriptor {
256    ($app_usage:expr) => {
257        &[
258            // ── Application collection ─────────────────────────────────────
259            0x05, 0x84, // Usage Page (Power Device)
260            0x09, $app_usage, // Usage (UPS / Power Supply)
261            0xA1, 0x01, // Collection (Application)
262            // ── Report ID 1: status ────────────────────────────────────────
263            0x85, 0x01, //   Report ID (1)
264            0x09, 0x02, //   Usage (PresentStatus)
265            0xA1, 0x02, //     Collection (Logical)
266            0x19, 0x60, //       Usage Minimum (Present)
267            0x29, 0x69, //       Usage Maximum (ShutdownImminent)
268            0x15, 0x00, //       Logical Minimum (0)
269            0x25, 0x01, //       Logical Maximum (1)
270            0x75, 0x01, //       Report Size (1)
271            0x95, 0x0A, //       Report Count (10)
272            0x81, 0x02, //       Input (Data, Variable, Absolute)
273            0x19, 0x6B, //       Usage Minimum (SwitchOn/Off)
274            0x29, 0x73, //       Usage Maximum (CommunicationLost)
275            0x95, 0x09, //       Report Count (9)
276            0x81, 0x02, //       Input (Data, Variable, Absolute)
277            0x75, 0x05, //       Report Size (5)
278            0x95, 0x01, //       Report Count (1)
279            0x81, 0x01, //       Input (Constant)      ; pad to 3 bytes
280            0xC0, //     End Collection
281            0x09, 0x03, //   Usage (ChangedStatus)
282            0xA1, 0x02, //     Collection (Logical)
283            0x75, 0x01, //       Report Size (1)
284            0x19, 0x60, 0x29, 0x69, //       Usage Minimum/Maximum (Present … ShutdownImminent)
285            0x95, 0x0A, 0x81, 0x02, //       Input (10 × 1 bit)
286            0x19, 0x6B, 0x29, 0x73, //       Usage Minimum/Maximum (SwitchOn/Off … CommunicationLost)
287            0x95, 0x09, 0x81, 0x02, //       Input (9 × 1 bit)
288            0x75, 0x05, 0x95, 0x01, 0x81, 0x01, //       Input (Constant)  ; pad to 3 bytes
289            0xC0, //     End Collection
290            // ── Report ID 2: measurements ──────────────────────────────────
291            0x85, 0x02, //   Report ID (2)
292            0x05, 0x84, //   Usage Page (Power Device)
293            0x09, 0x30, //   Usage (Voltage)
294            0x15, 0x00, 0x26, 0xFF, 0x7F, //     Logical 0 … 32767
295            0x75, 0x10, 0x95, 0x01, //           Report Size (16), Count (1)
296            0x67, 0x21, 0xD1, 0xF0, 0x00, //     Unit (Volt)
297            0x55, 0x0E, //                       Unit Exponent (-2)  ; centivolts
298            0x81, 0x02, //     Input (Data, Variable, Absolute)
299            0x09, 0x31, //   Usage (Current)
300            0x67, 0x01, 0x00, 0x10, 0x00, //     Unit (Amp)
301            0x55, 0x0E, //                       Unit Exponent (-2)  ; centiamps
302            0x81, 0x02, //     Input (Data, Variable, Absolute)
303            0x09, 0x32, //   Usage (Frequency)
304            0x25, 0x64, //     Logical Maximum (100)
305            0x75, 0x08, //     Report Size (8)
306            0x67, 0x01, 0xF0, 0x00, 0x00, //     Unit (Hertz)
307            0x55, 0x00, //                       Unit Exponent (0)
308            0x81, 0x02, //     Input (Data, Variable, Absolute)
309            0x09, 0x35, //   Usage (PercentLoad)
310            0x65, 0x00, //     Unit (None)
311            0x81, 0x02, //     Input (Data, Variable, Absolute)
312            0x09, 0x36, //   Usage (Temperature)
313            0x26, 0xFF, 0x7F, //     Logical Maximum (32767)
314            0x75, 0x10, //     Report Size (16)
315            0x67, 0x01, 0x00, 0x01, 0x00, //     Unit (Kelvin)
316            0x55, 0x00, //                       Unit Exponent (0)
317            0x81, 0x02, //     Input (Data, Variable, Absolute)
318            // ── Report ID 3: battery ───────────────────────────────────────
319            0x05, 0x85, //     Usage Page (Battery System)
320            0x09, 0x12, //     Usage (Battery)
321            0xA1, 0x00, //     Collection (Physical)
322            0x85, 0x03, //       Report ID (3)
323            0x05, 0x84, 0x09, 0x02, //       Usage (PresentStatus)
324            0xA1, 0x02, //         Collection (Logical)
325            0x05, 0x85, //           Usage Page (Battery System)
326            0x09, 0x44, //           Usage (Charging)
327            0x09, 0x45, //           Usage (Discharging)
328            0x09, 0x46, //           Usage (FullyCharged)
329            0x09, 0x42, //           Usage (BelowRemainingCapacityLimit)
330            0x09, 0xD0, //           Usage (ACPresent)
331            0x09, 0xD1, //           Usage (BatteryPresent)
332            0x09, 0x4B, //           Usage (NeedReplacement)
333            0x15, 0x00, 0x25, 0x01, //           Logical 0 … 1
334            0x65, 0x00, //                         Unit (None)
335            0x75, 0x01, 0x95, 0x07, //           Report Size (1), Count (7)
336            0x81, 0x02, //             Input (Data, Variable, Absolute)
337            0x95, 0x01, 0x81, 0x01, //             Input (Constant)  ; pad
338            0xC0, //         End Collection
339            0x05, 0x84, 0x09, 0x03, //       Usage (ChangedStatus)
340            0xA1, 0x02, //         Collection (Logical)
341            0x05, 0x85, //           Usage Page (Battery System)
342            0x09, 0x44, 0x09, 0x45, 0x09, 0x46, 0x09, 0x42, //  Charging … BelowRemainingCapacityLimit
343            0x09, 0xD0, 0x09, 0xD1, 0x09, 0x4B, //              ACPresent … NeedReplacement
344            0x95, 0x07, 0x81, 0x02, //             Input (7 × 1 bit)
345            0x95, 0x01, 0x81, 0x01, //             Input (Constant)  ; pad
346            0xC0, //         End Collection
347            0x05, 0x85, 0x09, 0x64, //       Usage (RelativeStateOfCharge)
348            0x15, 0x00, 0x25, 0x64, //         Logical 0 … 100
349            0x75, 0x08, 0x95, 0x01, 0x81, 0x02, //  Input (8 bits, percent)
350            0x09, 0x68, //       Usage (RunTimeToEmpty)  ; minutes
351            0x15, 0x00, 0x26, 0xFF, 0x7F, //     Logical 0 … 32767
352            0x75, 0x10, 0x95, 0x01, 0x81, 0x02, //  Input (16 bits)
353            0xC0, //     End Collection
354            // ── Report ID 4: configuration ─────────────────────────────────
355            0x85, 0x04, //   Report ID (4)
356            0x05, 0x84, //   Usage Page (Power Device)
357            0x09, 0x40, //   Usage (ConfigVoltage)
358            0x15, 0x00, 0x26, 0xFF, 0x7F, //     Logical 0 … 32767
359            0x75, 0x10, 0x95, 0x01, //           Report Size (16), Count (1)
360            0x67, 0x21, 0xD1, 0xF0, 0x00, //     Unit (Volt)
361            0x55, 0x0E, //                       Unit Exponent (-2)  ; centivolts
362            0xB1, 0x02, //     Feature (Data, Variable, Absolute)
363            0x09, 0x41, //   Usage (ConfigCurrent)
364            0x67, 0x01, 0x00, 0x10, 0x00, //     Unit (Amp)
365            0x55, 0x0E, //                       Unit Exponent (-2)  ; centiamps
366            0xB1, 0x02, //     Feature (Data, Variable, Absolute)
367            0x09, 0x42, //   Usage (ConfigFrequency)
368            0x25, 0x64, //     Logical Maximum (100)
369            0x75, 0x08, //     Report Size (8)
370            0x67, 0x01, 0xF0, 0x00, 0x00, //     Unit (Hertz)
371            0x55, 0x00, //                       Unit Exponent (0)
372            0xB1, 0x02, //     Feature (Data, Variable, Absolute)
373            0x09, 0x53, //   Usage (LowVoltageTransfer)
374            0x26, 0xFF, 0x7F, //     Logical Maximum (32767)
375            0x75, 0x10, //     Report Size (16)
376            0x67, 0x21, 0xD1, 0xF0, 0x00, //     Unit (Volt)
377            0x55, 0x0E, //                       Unit Exponent (-2)  ; centivolts
378            0xB1, 0x02, //     Feature (Data, Variable, Absolute)
379            0x09, 0x54, //   Usage (HighVoltageTransfer)
380            0xB1, 0x02, //     Feature (Data, Variable, Absolute)
381            0x09, 0x57, //   Usage (DelayBeforeShutdown)
382            0x67, 0x01, 0x10, 0x00, 0x00, //     Unit (second)
383            0x55, 0x00, //                       Unit Exponent (0)
384            0xB1, 0x02, //     Feature (Data, Variable, Absolute)
385            0x09, 0x46, //   Usage (ConfigTemperature)
386            0x67, 0x01, 0x00, 0x01, 0x00, //     Unit (Kelvin)
387            0xB1, 0x02, //     Feature (Data, Variable, Absolute)
388            // ── Report ID 5: controls ──────────────────────────────────────
389            0x85, 0x05, //   Report ID (5)
390            0x05, 0x84, //   Usage Page (Power Device)
391            0x09, 0x50, //   Usage (SwitchOnControl)
392            0x09, 0x51, //   Usage (SwitchOffControl)
393            0x09, 0x52, //   Usage (ToggleControl)
394            0x09, 0x5A, //   Usage (AudibleAlarmControl)
395            0x15, 0x00, 0x25, 0x01, //     Logical 0 … 1
396            0x65, 0x00, //                 Unit (None)
397            0x75, 0x01, 0x95, 0x04, //     Report Size (1), Count (4)
398            0x91, 0x02, //     Output (Data, Variable, Absolute)
399            0x75, 0x04, 0x95, 0x01, 0x91, 0x01, //     Output (Constant)  ; pad
400            0xC0, // End Collection (Application)
401        ]
402    };
403}
404
405/// Report descriptor of a UPS ([`PowerDeviceType::Ups`]).
406pub const UPS_REPORT_DESCRIPTOR: &[u8] = power_report_descriptor!(power_usage::UPS);
407
408/// Report descriptor of a power supply ([`PowerDeviceType::PowerSupply`]).
409pub const POWER_SUPPLY_REPORT_DESCRIPTOR: &[u8] =
410    power_report_descriptor!(power_usage::POWER_SUPPLY);
411
412/// Application collection usage — the device type the host sees.
413#[derive(Clone, Copy, PartialEq, Eq, Debug)]
414pub enum PowerDeviceType {
415    /// Uninterruptible power supply: has a battery and reports report 3.
416    Ups,
417    /// Power supply without a battery.
418    PowerSupply,
419}
420
421impl PowerDeviceType {
422    /// Power Device page usage ID of the application collection.
423    pub const fn usage(self) -> u8 {
424        match self {
425            Self::Ups => power_usage::UPS,
426            Self::PowerSupply => power_usage::POWER_SUPPLY,
427        }
428    }
429
430    /// Report descriptor for this device type.
431    pub const fn descriptor(self) -> &'static [u8] {
432        match self {
433            Self::Ups => UPS_REPORT_DESCRIPTOR,
434            Self::PowerSupply => POWER_SUPPLY_REPORT_DESCRIPTOR,
435        }
436    }
437}
438
439// ─── Report payloads ─────────────────────────────────────────────────────────
440
441/// Present-status and changed-status flags (input report 1).
442///
443/// Bit *n* maps to the *n*-th flag of the `PresentStatus` collection, which the
444/// report descriptor declares as `Usage Minimum (Present) … Usage Maximum
445/// (CommunicationLost)`.
446#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
447#[cfg_attr(feature = "defmt", derive(defmt::Format))]
448pub struct PowerStatus(u32);
449
450impl PowerStatus {
451    /// Size of the packed report field, in bytes (19 flags plus 5 pad bits).
452    pub const SIZE: usize = 3;
453
454    /// No flags set.
455    pub const NONE: Self = Self(0);
456    /// A power source is connected.
457    pub const PRESENT: Self = Self(1 << 0);
458    /// The device is working correctly.
459    pub const GOOD: Self = Self(1 << 1);
460    /// Internal failure.
461    pub const INTERNAL_FAILURE: Self = Self(1 << 2);
462    /// Voltage out of range.
463    pub const VOLTAGE_OUT_OF_RANGE: Self = Self(1 << 3);
464    /// Frequency out of range.
465    pub const FREQUENCY_OUT_OF_RANGE: Self = Self(1 << 4);
466    /// Overload.
467    pub const OVERLOAD: Self = Self(1 << 5);
468    /// Over charged.
469    pub const OVER_CHARGED: Self = Self(1 << 6);
470    /// Over temperature.
471    pub const OVER_TEMPERATURE: Self = Self(1 << 7);
472    /// Shutdown requested.
473    pub const SHUTDOWN_REQUESTED: Self = Self(1 << 8);
474    /// Shutdown imminent.
475    pub const SHUTDOWN_IMMINENT: Self = Self(1 << 9);
476    /// The output is switched on.
477    pub const SWITCH_ON_OFF: Self = Self(1 << 10);
478    /// The output can be switched.
479    pub const SWITCHABLE: Self = Self(1 << 11);
480    /// The device is in use.
481    pub const USED: Self = Self(1 << 12);
482    /// Boosting.
483    pub const BOOST: Self = Self(1 << 13);
484    /// Bucking.
485    pub const BUCK: Self = Self(1 << 14);
486    /// Initialized.
487    pub const INITIALIZED: Self = Self(1 << 15);
488    /// Tested.
489    pub const TESTED: Self = Self(1 << 16);
490    /// Awaiting power.
491    pub const AWAITING_POWER: Self = Self(1 << 17);
492    /// Communication with a module was lost.
493    pub const COMMUNICATION_LOST: Self = Self(1 << 18);
494
495    /// Mask of the 19 defined flags.
496    const MASK: u32 = (1 << 19) - 1;
497
498    /// Raw flag bits.
499    pub const fn bits(self) -> u32 {
500        self.0
501    }
502
503    /// `true` if every flag in `other` is set in `self`.
504    pub const fn contains(self, other: Self) -> bool {
505        self.0 & other.0 == other.0
506    }
507
508    /// Union of two flag sets.
509    pub const fn union(self, other: Self) -> Self {
510        Self(self.0 | other.0)
511    }
512
513    /// `self` with the flags in `other` cleared.
514    pub const fn without(self, other: Self) -> Self {
515        Self(self.0 & !other.0)
516    }
517
518    /// Flags that differ between `self` and `previous`.
519    ///
520    /// Feed the result into the `ChangedStatus` half of [`PowerDevice::set_status`].
521    pub const fn diff(self, previous: Self) -> Self {
522        Self((self.0 ^ previous.0) & Self::MASK)
523    }
524
525    /// Pack the flags into the three report bytes.
526    pub fn to_bytes(self) -> [u8; Self::SIZE] {
527        let bits = (self.0 & Self::MASK).to_le_bytes();
528        [bits[0], bits[1], bits[2]]
529    }
530
531    /// Unpack the three report bytes.
532    pub fn from_bytes(bytes: &[u8]) -> Self {
533        let mut bits = 0u32;
534        for (i, byte) in bytes.iter().take(Self::SIZE).enumerate() {
535            bits |= u32::from(*byte) << (8 * i);
536        }
537        Self(bits & Self::MASK)
538    }
539}
540
541impl core::ops::BitOr for PowerStatus {
542    type Output = Self;
543
544    fn bitor(self, rhs: Self) -> Self {
545        self.union(rhs)
546    }
547}
548
549/// Battery status flags (input report 3).
550#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
551#[cfg_attr(feature = "defmt", derive(defmt::Format))]
552pub struct BatteryStatus(u8);
553
554impl BatteryStatus {
555    /// Size of the packed report field, in bytes (7 flags plus 1 pad bit).
556    pub const SIZE: usize = 1;
557
558    /// No flags set.
559    pub const NONE: Self = Self(0);
560    /// The battery is charging.
561    pub const CHARGING: Self = Self(1 << 0);
562    /// The battery is discharging.
563    pub const DISCHARGING: Self = Self(1 << 1);
564    /// The battery is fully charged.
565    pub const FULLY_CHARGED: Self = Self(1 << 2);
566    /// Remaining capacity below the alarm limit.
567    pub const BELOW_REMAINING_CAPACITY_LIMIT: Self = Self(1 << 3);
568    /// AC (line) power is present.
569    pub const AC_PRESENT: Self = Self(1 << 4);
570    /// A battery is present.
571    pub const BATTERY_PRESENT: Self = Self(1 << 5);
572    /// The battery needs replacement.
573    pub const NEED_REPLACEMENT: Self = Self(1 << 6);
574
575    /// Mask of the 7 defined flags.
576    const MASK: u8 = (1 << 7) - 1;
577
578    /// Raw flag bits.
579    pub const fn bits(self) -> u8 {
580        self.0
581    }
582
583    /// `true` if every flag in `other` is set in `self`.
584    pub const fn contains(self, other: Self) -> bool {
585        self.0 & other.0 == other.0
586    }
587
588    /// Union of two flag sets.
589    pub const fn union(self, other: Self) -> Self {
590        Self(self.0 | other.0)
591    }
592
593    /// `self` with the flags in `other` cleared.
594    pub const fn without(self, other: Self) -> Self {
595        Self(self.0 & !other.0)
596    }
597
598    /// Flags that differ between `self` and `previous`.
599    pub const fn diff(self, previous: Self) -> Self {
600        Self((self.0 ^ previous.0) & Self::MASK)
601    }
602
603    /// Pack the flags into the report byte.
604    pub const fn to_byte(self) -> u8 {
605        self.0 & Self::MASK
606    }
607
608    /// Unpack the report byte.
609    pub const fn from_byte(byte: u8) -> Self {
610        Self(byte & Self::MASK)
611    }
612}
613
614impl core::ops::BitOr for BatteryStatus {
615    type Output = Self;
616
617    fn bitor(self, rhs: Self) -> Self {
618        self.union(rhs)
619    }
620}
621
622/// Measurements (input report 2).
623#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
624#[cfg_attr(feature = "defmt", derive(defmt::Format))]
625pub struct PowerMeasures {
626    /// Output voltage in centivolts (5.00 V → 500).
627    pub voltage_cv: u16,
628    /// Output current in centiamps (1.25 A → 125).
629    pub current_ca: u16,
630    /// Line frequency in hertz; 0 when running from a battery.
631    pub frequency_hz: u8,
632    /// Load as a percentage of the rated load (0–100).
633    pub percent_load: u8,
634    /// Temperature in kelvin (25 °C → 298).
635    pub temperature_k: u16,
636}
637
638impl PowerMeasures {
639    /// Size of the packed report, in bytes.
640    pub const SIZE: usize = 8;
641
642    /// Pack the measurements into the report bytes.
643    pub fn to_bytes(self) -> [u8; Self::SIZE] {
644        let voltage = clamp16(self.voltage_cv).to_le_bytes();
645        let current = clamp16(self.current_ca).to_le_bytes();
646        let temperature = clamp16(self.temperature_k).to_le_bytes();
647        [
648            voltage[0],
649            voltage[1],
650            current[0],
651            current[1],
652            self.frequency_hz.min(100),
653            clamp_percent(self.percent_load),
654            temperature[0],
655            temperature[1],
656        ]
657    }
658}
659
660/// Battery status and charge (input report 3).
661///
662/// Only meaningful for [`PowerDeviceType::Ups`].
663#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
664#[cfg_attr(feature = "defmt", derive(defmt::Format))]
665pub struct BatteryState {
666    /// Current flags.
667    pub status: BatteryStatus,
668    /// Flags that changed since the previous report.
669    pub changed: BatteryStatus,
670    /// Remaining capacity as a percentage of full charge (0–100).
671    pub state_of_charge_pct: u8,
672    /// Estimated runtime at the present load, in minutes.
673    pub run_time_to_empty_min: u16,
674}
675
676impl BatteryState {
677    /// Size of the packed report, in bytes.
678    pub const SIZE: usize = 5;
679
680    /// Pack the state into the report bytes.
681    pub fn to_bytes(self) -> [u8; Self::SIZE] {
682        let run_time = clamp16(self.run_time_to_empty_min).to_le_bytes();
683        [
684            self.status.to_byte(),
685            self.changed.to_byte(),
686            clamp_percent(self.state_of_charge_pct),
687            run_time[0],
688            run_time[1],
689        ]
690    }
691}
692
693/// Configuration values (feature report 4).
694#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
695#[cfg_attr(feature = "defmt", derive(defmt::Format))]
696pub struct PowerConfig {
697    /// Nominal output voltage in centivolts.
698    pub voltage_cv: u16,
699    /// Nominal output current in centiamps.
700    pub current_ca: u16,
701    /// Nominal line frequency in hertz.
702    pub frequency_hz: u8,
703    /// Voltage below which the device transfers to battery power, in centivolts.
704    pub low_voltage_transfer_cv: u16,
705    /// Voltage above which the device transfers back to line power, in centivolts.
706    pub high_voltage_transfer_cv: u16,
707    /// Grace period between a shutdown request and power removal, in seconds.
708    pub delay_before_shutdown_s: u16,
709    /// Nominal temperature in kelvin.
710    pub temperature_k: u16,
711}
712
713impl PowerConfig {
714    /// Size of the packed report, in bytes.
715    pub const SIZE: usize = 13;
716
717    /// Pack the configuration into the report bytes.
718    pub fn to_bytes(self) -> [u8; Self::SIZE] {
719        let voltage = clamp16(self.voltage_cv).to_le_bytes();
720        let current = clamp16(self.current_ca).to_le_bytes();
721        let low = clamp16(self.low_voltage_transfer_cv).to_le_bytes();
722        let high = clamp16(self.high_voltage_transfer_cv).to_le_bytes();
723        let delay = clamp16(self.delay_before_shutdown_s).to_le_bytes();
724        let temperature = clamp16(self.temperature_k).to_le_bytes();
725        [
726            voltage[0],
727            voltage[1],
728            current[0],
729            current[1],
730            self.frequency_hz.min(100),
731            low[0],
732            low[1],
733            high[0],
734            high[1],
735            delay[0],
736            delay[1],
737            temperature[0],
738            temperature[1],
739        ]
740    }
741
742    /// Unpack a configuration report written by the host.
743    ///
744    /// Returns `None` if the report is shorter than [`PowerConfig::SIZE`];
745    /// bytes past the report are ignored.
746    pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
747        if bytes.len() < Self::SIZE {
748            return None;
749        }
750        Some(Self {
751            voltage_cv: u16::from_le_bytes([bytes[0], bytes[1]]),
752            current_ca: u16::from_le_bytes([bytes[2], bytes[3]]),
753            frequency_hz: bytes[4],
754            low_voltage_transfer_cv: u16::from_le_bytes([bytes[5], bytes[6]]),
755            high_voltage_transfer_cv: u16::from_le_bytes([bytes[7], bytes[8]]),
756            delay_before_shutdown_s: u16::from_le_bytes([bytes[9], bytes[10]]),
757            temperature_k: u16::from_le_bytes([bytes[11], bytes[12]]),
758        })
759    }
760}
761
762/// Switch commands (output report 5).
763#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
764#[cfg_attr(feature = "defmt", derive(defmt::Format))]
765pub struct PowerControls(u8);
766
767impl PowerControls {
768    /// Size of the packed report, in bytes.
769    pub const SIZE: usize = 1;
770
771    /// No command.
772    pub const NONE: Self = Self(0);
773    /// Switch the output on.
774    pub const SWITCH_ON: Self = Self(1 << 0);
775    /// Switch the output off.
776    pub const SWITCH_OFF: Self = Self(1 << 1);
777    /// Toggle the output.
778    pub const TOGGLE: Self = Self(1 << 2);
779    /// Sound the audible alarm.
780    pub const AUDIBLE_ALARM: Self = Self(1 << 3);
781
782    /// Mask of the 4 defined commands.
783    const MASK: u8 = (1 << 4) - 1;
784
785    /// Raw command bits.
786    pub const fn bits(self) -> u8 {
787        self.0
788    }
789
790    /// `true` if every command in `other` is set in `self`.
791    pub const fn contains(self, other: Self) -> bool {
792        self.0 & other.0 == other.0
793    }
794
795    /// Union of two command sets.
796    pub const fn union(self, other: Self) -> Self {
797        Self(self.0 | other.0)
798    }
799
800    /// `self` with the commands in `other` cleared.
801    pub const fn without(self, other: Self) -> Self {
802        Self(self.0 & !other.0)
803    }
804
805    /// Pack the commands into the report byte.
806    pub const fn to_byte(self) -> u8 {
807        self.0 & Self::MASK
808    }
809
810    /// Unpack the report byte.
811    pub const fn from_byte(byte: u8) -> Self {
812        Self(byte & Self::MASK)
813    }
814}
815
816impl core::ops::BitOr for PowerControls {
817    type Output = Self;
818
819    fn bitor(self, rhs: Self) -> Self {
820        self.union(rhs)
821    }
822}
823
824// ─── Pending input report bits ────────────────────────────────────────────────
825
826const PENDING_STATUS: u8 = 1 << 0;
827const PENDING_MEASURES: u8 = 1 << 1;
828const PENDING_BATTERY: u8 = 1 << 2;
829const PENDING_ALL: u8 = PENDING_STATUS | PENDING_MEASURES | PENDING_BATTERY;
830
831// ─── PowerDevice ─────────────────────────────────────────────────────────────
832
833/// HID Power Device: a UPS or power supply.
834///
835/// Wrap it in a [`HidClass`](super::HidClass) to talk to the host, and update it
836/// from the main loop through
837/// [`device_mut`](super::HidClass::device_mut).
838#[derive(Debug)]
839pub struct PowerDevice {
840    device_type: PowerDeviceType,
841
842    present: PowerStatus,
843    changed: PowerStatus,
844    measures: PowerMeasures,
845    battery: BatteryState,
846    config: PowerConfig,
847
848    pending_input: u8,
849    pending_controls: PowerControls,
850    pending_config: Option<PowerConfig>,
851}
852
853impl PowerDevice {
854    /// Create a power device of the given type.
855    pub fn new(device_type: PowerDeviceType) -> Self {
856        Self {
857            device_type,
858            present: PowerStatus::NONE,
859            changed: PowerStatus::NONE,
860            measures: PowerMeasures::default(),
861            battery: BatteryState::default(),
862            config: PowerConfig::default(),
863            pending_input: 0,
864            pending_controls: PowerControls::NONE,
865            pending_config: None,
866        }
867    }
868
869    /// Create a UPS ([`PowerDeviceType::Ups`]).
870    pub fn ups() -> Self {
871        Self::new(PowerDeviceType::Ups)
872    }
873
874    /// Create a power supply without a battery ([`PowerDeviceType::PowerSupply`]).
875    pub fn power_supply() -> Self {
876        Self::new(PowerDeviceType::PowerSupply)
877    }
878
879    // ── Device information ────────────────────────────────────────────────────
880
881    /// Device type this instance was created with.
882    pub fn device_type(&self) -> PowerDeviceType {
883        self.device_type
884    }
885
886    // ── Status and measurements ───────────────────────────────────────────────
887
888    /// Present status last reported to the host.
889    pub fn status(&self) -> PowerStatus {
890        self.present
891    }
892
893    /// Configuration last applied by the application.
894    pub fn config(&self) -> PowerConfig {
895        self.config
896    }
897
898    /// Update the status flags and queue input report 1 if anything changed.
899    ///
900    /// Pass `changed` flags (see [`PowerStatus::diff`]) to tell the host which
901    /// flags just changed; pass [`PowerStatus::NONE`] for a plain refresh.
902    pub fn set_status(&mut self, present: PowerStatus, changed: PowerStatus) {
903        if present != self.present || changed != self.changed {
904            self.present = present;
905            self.changed = changed;
906            self.pending_input |= PENDING_STATUS;
907        }
908    }
909
910    /// Update the measurements and queue input report 2 if anything changed.
911    pub fn set_measures(&mut self, measures: PowerMeasures) {
912        if measures != self.measures {
913            self.measures = measures;
914            self.pending_input |= PENDING_MEASURES;
915        }
916    }
917
918    /// Update the battery state and queue input report 3 if anything changed.
919    pub fn set_battery(&mut self, battery: BatteryState) {
920        if battery != self.battery {
921            self.battery = battery;
922            self.pending_input |= PENDING_BATTERY;
923        }
924    }
925
926    /// Store the configuration the device is actually running with.
927    ///
928    /// This is what `Get Report` returns, so call it after applying a
929    /// configuration written by the host, and whenever the configuration
930    /// changes for another reason.
931    pub fn set_config(&mut self, config: PowerConfig) {
932        self.config = config;
933    }
934
935    /// Queue all three input reports, even if nothing changed.
936    pub fn request_refresh(&mut self) {
937        self.pending_input |= PENDING_ALL;
938    }
939
940    // ── Host requests ─────────────────────────────────────────────────────────
941
942    /// Take the switch commands received since the last call.
943    ///
944    /// Commands are accumulated until taken, so several reports may be coalesced
945    /// into one value.
946    pub fn take_controls(&mut self) -> Option<PowerControls> {
947        if self.pending_controls == PowerControls::NONE {
948            None
949        } else {
950            Some(core::mem::replace(
951                &mut self.pending_controls,
952                PowerControls::NONE,
953            ))
954        }
955    }
956
957    /// Take the configuration written by the host since the last call.
958    ///
959    /// The application is expected to apply the values and then publish them
960    /// with [`set_config`](Self::set_config); until it does, `Get Report` keeps
961    /// returning the previous configuration.
962    pub fn take_config_write(&mut self) -> Option<PowerConfig> {
963        self.pending_config.take()
964    }
965
966    // ── Report buffers ────────────────────────────────────────────────────────
967
968    /// Input report 1 contents, including its report ID.
969    fn status_report(&self) -> [u8; 1 + 2 * PowerStatus::SIZE] {
970        let mut report = [0u8; 1 + 2 * PowerStatus::SIZE];
971        report[0] = report_id::STATUS;
972        report[1..1 + PowerStatus::SIZE].copy_from_slice(&self.present.to_bytes());
973        report[1 + PowerStatus::SIZE..].copy_from_slice(&self.changed.to_bytes());
974        report
975    }
976
977    /// Input report 2 contents, including its report ID.
978    fn measures_report(&self) -> [u8; 1 + PowerMeasures::SIZE] {
979        let mut report = [0u8; 1 + PowerMeasures::SIZE];
980        report[0] = report_id::MEASURES;
981        report[1..].copy_from_slice(&self.measures.to_bytes());
982        report
983    }
984
985    /// Input report 3 contents, including its report ID.
986    fn battery_report(&self) -> [u8; 1 + BatteryState::SIZE] {
987        let mut report = [0u8; 1 + BatteryState::SIZE];
988        report[0] = report_id::BATTERY;
989        report[1..].copy_from_slice(&self.battery.to_bytes());
990        report
991    }
992
993    /// Feature report 4 contents, including its report ID.
994    fn config_report(&self) -> [u8; 1 + PowerConfig::SIZE] {
995        let mut report = [0u8; 1 + PowerConfig::SIZE];
996        report[0] = report_id::CONFIG;
997        report[1..].copy_from_slice(&self.config.to_bytes());
998        report
999    }
1000
1001    /// Apply an output report (either transport) to the pending commands.
1002    fn apply_controls(&mut self, data: &[u8]) -> bool {
1003        match data.first() {
1004            Some(&byte) => {
1005                self.pending_controls = self.pending_controls.union(PowerControls::from_byte(byte));
1006                true
1007            }
1008            None => false,
1009        }
1010    }
1011
1012    /// Drop everything the host asked for but the application has not taken yet.
1013    fn clear_host_requests(&mut self) {
1014        self.pending_controls = PowerControls::NONE;
1015        self.pending_config = None;
1016    }
1017}
1018
1019impl<B: UsbBus> HidDevice<B> for PowerDevice {
1020    fn spec(&self) -> HidSpec {
1021        HidSpec::new(self.device_type.descriptor(), IN_ENDPOINT_SIZE)
1022            .out_report_size(OUT_ENDPOINT_SIZE)
1023            .poll_interval_ms(POLL_INTERVAL_MS)
1024            .report_ids(true)
1025    }
1026
1027    /// Serve the reports the host reads on demand: the three input reports and
1028    /// the configuration feature report.
1029    fn get_report(
1030        &mut self,
1031        report_type: ReportType,
1032        report_id: u8,
1033        buf: &mut [u8],
1034    ) -> Option<usize> {
1035        match (report_type, report_id) {
1036            (ReportType::Input, report_id::STATUS) => Some(copy_report(&self.status_report(), buf)),
1037            (ReportType::Input, report_id::MEASURES) => {
1038                Some(copy_report(&self.measures_report(), buf))
1039            }
1040            (ReportType::Input, report_id::BATTERY) => {
1041                Some(copy_report(&self.battery_report(), buf))
1042            }
1043            (ReportType::Feature, report_id::CONFIG) => {
1044                Some(copy_report(&self.config_report(), buf))
1045            }
1046            _ => None,
1047        }
1048    }
1049
1050    /// Accept a configuration write or a switch command.
1051    fn set_report(&mut self, report_type: ReportType, report_id: u8, data: &[u8]) -> bool {
1052        match (report_type, report_id) {
1053            (ReportType::Feature, report_id::CONFIG) => match PowerConfig::from_bytes(data) {
1054                Some(config) => {
1055                    self.pending_config = Some(config);
1056                    true
1057                }
1058                None => false,
1059            },
1060            (ReportType::Output, report_id::CONTROLS) => self.apply_controls(data),
1061            _ => false,
1062        }
1063    }
1064
1065    /// Same switch commands, this time written straight to the interrupt OUT
1066    /// endpoint.
1067    fn output_report(&mut self, report_id: u8, data: &[u8]) {
1068        if report_id == report_id::CONTROLS {
1069            self.apply_controls(data);
1070        }
1071    }
1072
1073    fn reset(&mut self) {
1074        self.pending_input = 0;
1075        self.clear_host_requests();
1076    }
1077
1078    fn configure(&mut self) {
1079        // Give the host a snapshot of the current state without waiting for a
1080        // change.
1081        self.request_refresh();
1082        self.clear_host_requests();
1083    }
1084
1085    fn deconfigure(&mut self) {
1086        self.pending_input = 0;
1087        self.clear_host_requests();
1088    }
1089
1090    /// Send the queued input reports, status first.
1091    ///
1092    /// A report the endpoint cannot take yet
1093    /// ([`WouldBlock`](crate::device::error::UsbError::WouldBlock)) stays queued and is
1094    /// retried on the next poll.
1095    fn poll(&mut self, input: &EndpointIn<'_, B>) {
1096        if self.pending_input & PENDING_STATUS != 0 {
1097            if input.write(&self.status_report()).is_err() {
1098                return;
1099            }
1100            self.pending_input &= !PENDING_STATUS;
1101        }
1102
1103        if self.pending_input & PENDING_MEASURES != 0 {
1104            if input.write(&self.measures_report()).is_err() {
1105                return;
1106            }
1107            self.pending_input &= !PENDING_MEASURES;
1108        }
1109
1110        if self.pending_input & PENDING_BATTERY != 0 {
1111            if input.write(&self.battery_report()).is_err() {
1112                return;
1113            }
1114            self.pending_input &= !PENDING_BATTERY;
1115        }
1116    }
1117}