Skip to main content

usb_pd_profiles/
lib.rs

1//! Compute [USB Power Delivery] profiles and the wattage a device *actually* receives.
2//!
3//! A charger's advertised wattage is a ceiling, not a promise. Three independent limits
4//! sit between the wall and the battery — the source profile set, the cable current
5//! rating, and the device's own maximum — and the smallest one wins.
6//!
7//! # Example
8//!
9//! ```
10//! use usb_pd_profiles::{negotiate, split_budget};
11//!
12//! // 65W charger, 30W phone, plain 3A cable — the phone is the limit
13//! let r = negotiate(65.0, 30.0, 3.0);
14//! assert_eq!(r.limited_by, "device");
15//!
16//! // Same charger, a 65W laptop, still a 3A cable — now the cable is the limit,
17//! // because 3A tops out at 60W (20V x 3A) and 5A e-marking is required above that
18//! assert_eq!(negotiate(65.0, 65.0, 3.0).limited_by, "cable");
19//! assert_eq!(negotiate(65.0, 65.0, 5.0).limited_by, "device");
20//!
21//! // One 65W budget shared by a laptop and a phone
22//! assert_eq!(split_budget(65.0, &[65.0, 20.0]), vec![65.0, 0.0]);
23//! ```
24//!
25//! # Why the numbers differ from the box
26//!
27//! - **Cable e-marker** — a plain USB-C cable is rated 3A, capping the link at 60W
28//!   regardless of what charger and device negotiated. Above 60W a 5A e-marked cable
29//!   is required, and nothing on the jacket tells you which one you are holding.
30//! - **Shared budget** — on multi-port chargers the headline figure is a *total*,
31//!   allocated by a controller rather than split evenly.
32//! - **Device ceiling** — a phone that tops out at 20W requests that profile and
33//!   ignores the rest, so a higher-rated charger buys it nothing.
34//!
35//! [USB Power Delivery]: https://en.wikipedia.org/wiki/USB_hardware
36
37/// Fixed supply voltages defined by the USB Power Delivery specification.
38pub const PD_VOLTAGES: [u32; 8] = [5, 9, 12, 15, 20, 28, 36, 48];
39
40/// Current ceiling (amps) for a cable without an e-marker chip.
41pub const DEFAULT_CABLE_AMPS: f64 = 3.0;
42/// Current ceiling (amps) for a 5A e-marked cable.
43pub const EMARKED_CABLE_AMPS: f64 = 5.0;
44
45/// Highest voltage available in Standard Power Range (SPR).
46///
47/// Voltages above this belong to Extended Power Range (EPR), which the
48/// specification only permits over a 5 A e-marked EPR cable.
49pub const SPR_MAX_VOLTS: u32 = 20;
50
51/// A single negotiated power profile.
52#[derive(Debug, Clone, Copy, PartialEq)]
53pub struct Profile {
54    pub volts: u32,
55    pub amps: f64,
56    pub watts: f64,
57}
58
59/// Result of a negotiation, including which component limited the outcome.
60#[derive(Debug, Clone, PartialEq)]
61pub struct Outcome {
62    pub delivered_watts: f64,
63    /// One of `"source"`, `"cable"` or `"device"`.
64    pub limited_by: &'static str,
65    pub profile: Profile,
66}
67
68fn round1(v: f64) -> f64 {
69    (v * 10.0).round() / 10.0
70}
71
72/// Fixed PD profiles a source of the given rating can advertise.
73///
74/// Note that Extended Power Range voltages (above [`SPR_MAX_VOLTS`]) are listed
75/// here as source capability; whether they are actually usable depends on the
76/// cable — see [`profiles_over_cable`].
77pub fn source_profiles(source_watts: f64) -> Vec<Profile> {
78    PD_VOLTAGES
79        .iter()
80        .filter_map(|&v| {
81            let amps = (source_watts / v as f64).min(EMARKED_CABLE_AMPS);
82            let watts = round1(v as f64 * amps);
83            (watts >= 15.0).then_some(Profile { volts: v, amps: round1(amps), watts })
84        })
85        .collect()
86}
87
88/// Profiles actually reachable through a given cable.
89///
90/// A cable rated below 5 A cannot carry Extended Power Range voltages at all,
91/// and caps current on every remaining profile.
92pub fn profiles_over_cable(source_watts: f64, cable_amps: f64) -> Vec<Profile> {
93    let epr_ok = cable_amps >= EMARKED_CABLE_AMPS;
94    source_profiles(source_watts)
95        .into_iter()
96        .filter(|p| epr_ok || p.volts <= SPR_MAX_VOLTS)
97        .map(|p| {
98            let amps = p.amps.min(cable_amps);
99            Profile { volts: p.volts, amps: round1(amps), watts: round1(p.volts as f64 * amps) }
100        })
101        .collect()
102}
103
104/// Resolve delivered wattage and identify the limiting component.
105pub fn negotiate(source_watts: f64, device_watts: f64, cable_amps: f64) -> Outcome {
106    let fallback_amps = cable_amps.min(3.0);
107    let mut best = Profile { volts: 5, amps: fallback_amps, watts: round1(5.0 * fallback_amps) };
108
109    for p in profiles_over_cable(source_watts, cable_amps) {
110        if p.watts <= device_watts && p.watts > best.watts {
111            best = p;
112        }
113    }
114
115    // ما الذي منع الوصول لأقل رقم بين قدرة المصدر وطلب الجهاز؟
116    let target = source_watts.min(device_watts);
117    // أقصى ما يستطيع الكابل تمريره عبر أي ملف طاقة يدعمه المصدر
118    let cable_ceiling = profiles_over_cable(source_watts, cable_amps)
119        .iter()
120        .map(|p| p.watts)
121        .fold(round1(5.0 * cable_amps.min(3.0)), f64::max);
122
123    let limited_by = if cable_ceiling + 0.05 < target {
124        "cable"
125    } else if source_watts < device_watts {
126        "source"
127    } else {
128        "device"
129    };
130
131    Outcome { delivered_watts: best.watts, limited_by, profile: best }
132}
133
134/// Allocate a shared multi-port budget, highest demand claiming first.
135pub fn split_budget(total_watts: f64, demands: &[f64]) -> Vec<f64> {
136    let mut order: Vec<usize> = (0..demands.len()).collect();
137    order.sort_by(|&a, &b| demands[b].partial_cmp(&demands[a]).unwrap());
138
139    let mut left = total_watts;
140    let mut out = vec![0.0; demands.len()];
141    for i in order {
142        let give = demands[i].min(left);
143        out[i] = round1(give);
144        left = round1(left - give);
145    }
146    out
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    #[test]
154    fn cable_caps_a_65w_laptop() {
155        assert_eq!(negotiate(65.0, 65.0, 3.0).limited_by, "cable");
156        assert_eq!(negotiate(65.0, 65.0, 5.0).limited_by, "device");
157    }
158
159    #[test]
160    fn highest_demand_claims_budget_first() {
161        assert_eq!(split_budget(65.0, &[65.0, 20.0]), vec![65.0, 0.0]);
162        assert_eq!(split_budget(100.0, &[65.0, 20.0]), vec![65.0, 20.0]);
163    }
164
165    #[test]
166    fn epr_voltages_need_an_emarked_cable() {
167        // 140W source: 28V+ profiles exist, but a 3A cable cannot reach them
168        assert!(profiles_over_cable(140.0, 3.0).iter().all(|p| p.volts <= SPR_MAX_VOLTS));
169        assert!(profiles_over_cable(140.0, 5.0).iter().any(|p| p.volts > SPR_MAX_VOLTS));
170    }
171
172    #[test]
173    fn profiles_respect_minimum_wattage() {
174        assert!(source_profiles(65.0).iter().all(|p| p.watts >= 15.0));
175    }
176}