From 807cdba84cec99618c9d83f4a753ae589a6646dd Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sat, 19 Sep 2026 12:00:33 +0200 Subject: [PATCH 01/26] --power: Extract functions to return data Signed-off-by: Daniel Schaefer --- framework_lib/src/chromium_ec/mod.rs | 46 ++++++++++++++++------------ framework_lib/src/power.rs | 33 +++++++++++++++++++- 2 files changed, 58 insertions(+), 21 deletions(-) diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index d19c3629..51adfa09 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -1689,31 +1689,20 @@ impl CrosEc { } } - pub fn get_charge_state(&self, power_info: &power::PowerInfo) -> EcResult<()> { + /// Read the current state of the charger + pub fn get_charge_state(&self) -> EcResult { let res = EcRequestChargeStateGetV0 { cmd: ChargeStateCmd::GetState as u8, param: 0, } .send_command(self)?; - println!("Charger Status"); - println!( - " AC is: {}", - if res.ac == 1 { - "connected" - } else { - "not connected" - } - ); - println!(" Charger Voltage: {}mV", { res.chg_voltage }); - println!(" Charger Current: {}mA", { res.chg_current }); - if let Some(battery) = &power_info.battery { - let charge_rate = (res.chg_current as f32) / (battery.design_capacity as f32); - println!(" {:.2}C", charge_rate); - } - println!(" Chg Input Current:{}mA", { res.chg_input_current }); - println!(" Battery SoC: {}%", { res.batt_state_of_charge }); - - Ok(()) + Ok(ChargeState { + ac_present: res.ac == 1, + charger_voltage: res.chg_voltage, + charger_current: res.chg_current, + charger_input_current: res.chg_input_current, + battery_soc: res.batt_state_of_charge, + }) } pub fn set_ec_hib_delay(&self, seconds: u32) -> EcResult<()> { @@ -2234,6 +2223,23 @@ pub fn print_err(something: EcResult) -> Option { something.ok() } +/// Current state of the charger, as reported by EC_CMD_CHARGE_STATE +/// +/// Use [`CrosEc::get_charge_state`] to read it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ChargeState { + /// Whether the charger reports AC as connected + pub ac_present: bool, + /// Charger output voltage in mV + pub charger_voltage: u32, + /// Charger output current in mA + pub charger_current: u32, + /// Charger input current limit in mA + pub charger_input_current: u32, + /// Battery state of charge in percent + pub battery_soc: u32, +} + /// Which of the two EC images is currently in-use #[derive(PartialEq, Debug)] pub enum EcCurrentImage { diff --git a/framework_lib/src/power.rs b/framework_lib/src/power.rs index 7fb80482..398b0c80 100644 --- a/framework_lib/src/power.rs +++ b/framework_lib/src/power.rs @@ -787,7 +787,11 @@ pub fn get_and_print_power_info(ec: &CrosEc) -> i32 { } if let Some(power_info) = power_info(ec) { - print_err_ref(&ec.get_charge_state(&power_info)); + let charge_state = ec.get_charge_state(); + print_err_ref(&charge_state); + if let Ok(charge_state) = charge_state { + print_charge_state(&charge_state, &power_info); + } print_battery_information(&power_info); if let Some(_battery) = &power_info.battery { return 0; @@ -796,6 +800,33 @@ pub fn get_and_print_power_info(ec: &CrosEc) -> i32 { 1 } +/// Print the charger state like the commandline tool does +/// +/// The battery information is used to show the charge current relative to +/// the battery's design capacity (C-rate). +pub fn print_charge_state(charge_state: &ChargeState, power_info: &PowerInfo) { + println!("Charger Status"); + println!( + " AC is: {}", + if charge_state.ac_present { + "connected" + } else { + "not connected" + } + ); + println!(" Charger Voltage: {}mV", charge_state.charger_voltage); + println!(" Charger Current: {}mA", charge_state.charger_current); + if let Some(battery) = &power_info.battery { + let charge_rate = (charge_state.charger_current as f32) / (battery.design_capacity as f32); + println!(" {:.2}C", charge_rate); + } + println!( + " Chg Input Current:{}mA", + charge_state.charger_input_current + ); + println!(" Battery SoC: {}%", charge_state.battery_soc); +} + fn print_battery_information(power_info: &PowerInfo) { println!("Battery Status"); print!(" AC is: "); From 930f3865df3b31b89df79514f203334db19dd63f Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sat, 19 Sep 2026 12:04:16 +0200 Subject: [PATCH 02/26] --pdports: Extract functions to return data Signed-off-by: Daniel Schaefer --- framework_lib/src/commandline/mod.rs | 2 +- framework_lib/src/power.rs | 347 ++++++++++++++++++--------- 2 files changed, 241 insertions(+), 108 deletions(-) diff --git a/framework_lib/src/commandline/mod.rs b/framework_lib/src/commandline/mod.rs index 44d8e702..3783bfce 100644 --- a/framework_lib/src/commandline/mod.rs +++ b/framework_lib/src/commandline/mod.rs @@ -1764,7 +1764,7 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { } else if let Some(None) = args.autofanctrl { print_err(ec.autofanctrl(None)); } else if args.pdports { - power::get_and_print_cypd_pd_info(&ec); + power::print_cypd_pd_info(&ec); } else if args.pdports_chromebook { power::get_and_print_pd_info(&ec); } else if args.info { diff --git a/framework_lib/src/power.rs b/framework_lib/src/power.rs index 398b0c80..e3d5a827 100644 --- a/framework_lib/src/power.rs +++ b/framework_lib/src/power.rs @@ -999,8 +999,9 @@ pub fn get_pd_info(ec: &CrosEc, ports: u8) -> Vec> { info } -#[derive(Debug)] -enum CypdTypeCState { +/// Type-C connection state of a PD port +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CypdTypeCState { Nothing, Sink, Source, @@ -1026,8 +1027,9 @@ impl From for CypdTypeCState { } } -#[derive(Debug, PartialEq)] -enum CypdPdPowerRole { +/// PD power role of a port +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CypdPdPowerRole { Sink, Source, Unknown, @@ -1043,8 +1045,9 @@ impl From for CypdPdPowerRole { } } -#[derive(Debug)] -enum CypdPdDataRole { +/// PD data role of a port +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CypdPdDataRole { Ufp, Dfp, Disconnected, @@ -1062,117 +1065,211 @@ impl From for CypdPdDataRole { } } -pub fn get_and_print_cypd_pd_info(ec: &CrosEc) { - // All of our systems have a maximum of 4 PD enabled ports - let ports = 4u8; +/// Which CC line the port partner is connected on +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CcPolarity { + Cc1, + Cc2, + Cc1Debug, + Cc2Debug, + Unknown(u8), +} - for port in 0..ports { - let result = EcRequestGetPdPortState { port }.send_command(ec); +impl From for CcPolarity { + fn from(v: u8) -> Self { + match v { + 0 => CcPolarity::Cc1, + 1 => CcPolarity::Cc2, + 2 => CcPolarity::Cc1Debug, + 3 => CcPolarity::Cc2Debug, + v => CcPolarity::Unknown(v), + } + } +} - let info = match result { - Ok(info) => info, - Err(EcError::Response(EcResponseStatus::InvalidParameter)) => { - debug!("Port {port} does not exist"); - continue; - } - Err(e) => { - print_err::<()>(Err(e)); - continue; - } - }; +impl fmt::Display for CcPolarity { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + CcPolarity::Cc1 => write!(f, "CC1"), + CcPolarity::Cc2 => write!(f, "CC2"), + CcPolarity::Cc1Debug => write!(f, "CC1 (Debug)"), + CcPolarity::Cc2Debug => write!(f, "CC2 (Debug)"), + CcPolarity::Unknown(_) => write!(f, "Unknown"), + } + } +} + +/// Names of the DP alt mode status bits, lowest bit first +const DP_ALT_MODE_STATUS_NAMES: [&str; 8] = [ + "DFP_D Connected", + "UFP_D Connected", + "Power Low", + "Enabled", + "Multi-Function", + "USB Config", + "Exit Request", + "HPD High", +]; + +/// State of a single USB-C port as reported by the Cypress PD controller +/// +/// Use [`get_cypd_pd_info`] to read it and [`print_cypd_pd_info`] to show it +/// like the commandline tool does. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CypdPortInfo { + /// Port number, 0-3 + pub port: u8, + /// Type-C connection state, [`CypdTypeCState::Nothing`] if nothing is connected + pub c_state: CypdTypeCState, + /// Whether a PD contract has been negotiated + pub pd_contract: bool, + pub power_role: CypdPdPowerRole, + pub data_role: CypdPdDataRole, + /// Whether this port supplies VCONN + pub vconn: bool, + /// Negotiated voltage in mV + pub voltage: u16, + /// Negotiated current in mA + pub current: u16, + pub cc_polarity: CcPolarity, + /// Whether an EPR (Extended Power Range) contract is active + pub epr_active: bool, + /// Whether the port partner supports EPR + pub epr_support: bool, + /// Whether this port is the one the system currently charges from + pub sink_active: bool, + /// Raw DP alt mode status bits, see [`CypdPortInfo::dp_alt_modes`] + pub dp_alt_mode_status: u8, +} + +impl CypdPortInfo { + /// Whether anything is connected to the port + pub fn connected(&self) -> bool { + !matches!(self.c_state, CypdTypeCState::Nothing) + } + + /// Negotiated power in mW + pub fn power_mw(&self) -> u32 { + self.voltage as u32 * self.current as u32 / 1000 + } + + /// Whether DP alt mode is active (DFP_D/TBT or UFP_D connected) + pub fn dp_alt_mode_active(&self) -> bool { + self.dp_alt_mode_status & 0x03 != 0 + } - println!("USB-C Port {}:", port); - let c_state = CypdTypeCState::from(info.c_state); - let connected = !matches!(c_state, CypdTypeCState::Nothing); - let power_role = CypdPdPowerRole::from(info.power_role); - let data_role = CypdPdDataRole::from(info.data_role); - let voltage = { info.voltage }; - let current = { info.current }; - let watts_mw = voltage as u32 * current as u32 / 1000; - let has_pd_contract = info.pd_state != 0; + /// Names of all set DP alt mode status bits + pub fn dp_alt_modes(&self) -> Vec<&'static str> { + DP_ALT_MODE_STATUS_NAMES + .iter() + .enumerate() + .filter(|(bit, _)| self.dp_alt_mode_status & (1 << bit) != 0) + .map(|(_, name)| *name) + .collect() + } +} +/// Read the state of a single USB-C port from the Cypress PD controller +/// +/// Returns `Ok(None)` if the port does not exist on this system. +pub fn get_cypd_port_info(ec: &CrosEc, port: u8) -> EcResult> { + let info = match (EcRequestGetPdPortState { port }).send_command(ec) { + Ok(info) => info, + Err(EcError::Response(EcResponseStatus::InvalidParameter)) => { + debug!("Port {port} does not exist"); + return Ok(None); + } + Err(e) => return Err(e), + }; + + Ok(Some(CypdPortInfo { + port, + c_state: CypdTypeCState::from(info.c_state), + pd_contract: info.pd_state != 0, + power_role: CypdPdPowerRole::from(info.power_role), + data_role: CypdPdDataRole::from(info.data_role), + vconn: info.vconn != 0, + voltage: { info.voltage }, + current: { info.current }, + cc_polarity: CcPolarity::from(info.cc_polarity), + epr_active: info.epr_active != 0, + epr_support: info.epr_support != 0, + sink_active: info.active_port != 0, + dp_alt_mode_status: info.pd_alt_mode_status, + })) +} + +/// Read the state of all USB-C ports from the Cypress PD controller +/// +/// Ports that do not exist on this system are left out, ports that failed +/// to respond are kept as errors. +pub fn get_cypd_pd_info(ec: &CrosEc) -> Vec> { + // All of our systems have a maximum of 4 PD enabled ports + let ports = 4u8; + + (0..ports) + .filter_map(|port| get_cypd_port_info(ec, port).transpose()) + .collect() +} + +/// Print the state of a single USB-C port like the commandline tool does +pub fn print_cypd_port_info(info: &CypdPortInfo) { + println!("USB-C Port {}:", info.port); + println!( + " PD Contract: {}", + if info.pd_contract { "Yes" } else { "No" } + ); + println!(" Power Role: {:?}", info.power_role); + println!(" Data Role: {:?}", info.data_role); + if info.connected() { + println!(" VCONN: {}", if info.vconn { "On" } else { "Off" }); + let watts_mw = info.power_mw(); println!( - " PD Contract: {}", - if info.pd_state != 0 { "Yes" } else { "No" } + " Negotiated: {}.{:03} V, {} mA, {}.{} W", + info.voltage / 1000, + info.voltage % 1000, + info.current, + watts_mw / 1000, + watts_mw % 1000, ); - println!(" Power Role: {:?}", power_role); - println!(" Data Role: {:?}", data_role); - if connected { - println!( - " VCONN: {}", - if info.vconn != 0 { "On" } else { "Off" } - ); - println!( - " Negotiated: {}.{:03} V, {} mA, {}.{} W", - voltage / 1000, - voltage % 1000, - current, - watts_mw / 1000, - watts_mw % 1000, - ); - println!( - " CC Polarity: {}", - match info.cc_polarity { - 0 => "CC1", - 1 => "CC2", - 2 => "CC1 (Debug)", - 3 => "CC2 (Debug)", - _ => "Unknown", - } - ); - } - if has_pd_contract { - println!(" Port Partner: {:?}", c_state); + println!(" CC Polarity: {}", info.cc_polarity); + } + if info.pd_contract { + println!(" Port Partner: {:?}", info.c_state); + println!( + " EPR: {}{}", + if info.epr_active { + "Active" + } else { + "Inactive" + }, + if info.epr_support { " (Supported)" } else { "" } + ); + if info.power_role == CypdPdPowerRole::Sink { println!( - " EPR: {}{}", - if info.epr_active != 0 { - "Active" - } else { - "Inactive" - }, - if info.epr_support != 0 { - " (Supported)" - } else { - "" - } + " Sink Active: {}", + if info.sink_active { "Yes" } else { "No" } ); - if power_role == CypdPdPowerRole::Sink { - println!( - " Sink Active: {}", - if info.active_port != 0 { "Yes" } else { "No" } - ); - } } - let alt = info.pd_alt_mode_status; - // Bits 0-1 indicate DP alt mode is active (bit 0 = DFP_D/TBT, - // bit 1 = UFP_D). Only show when actually in DP alt mode. - if connected && (alt & 0x03) != 0 { - let mut modes = vec![]; - if alt & 0x01 != 0 { - modes.push("DFP_D Connected"); - } - if alt & 0x02 != 0 { - modes.push("UFP_D Connected"); - } - if alt & 0x04 != 0 { - modes.push("Power Low"); - } - if alt & 0x08 != 0 { - modes.push("Enabled"); - } - if alt & 0x10 != 0 { - modes.push("Multi-Function"); - } - if alt & 0x20 != 0 { - modes.push("USB Config"); - } - if alt & 0x40 != 0 { - modes.push("Exit Request"); - } - if alt & 0x80 != 0 { - modes.push("HPD High"); + } + // Only show when actually in DP alt mode + if info.connected() && info.dp_alt_mode_active() { + println!( + " DP Alt Mode: {} (0x{:02X})", + info.dp_alt_modes().join(", "), + info.dp_alt_mode_status + ); + } +} + +/// Print the state of all USB-C ports like the commandline tool does +pub fn print_cypd_pd_info(ec: &CrosEc) { + for info in get_cypd_pd_info(ec) { + match info { + Ok(info) => print_cypd_port_info(&info), + Err(e) => { + print_err::<()>(Err(e)); } - println!(" DP Alt Mode: {} (0x{:02X})", modes.join(", "), alt); } } } @@ -1327,6 +1424,42 @@ pub fn standalone_mode(ec: &CrosEc) -> bool { mod tests { use super::*; + #[test] + fn decode_dp_alt_modes() { + let mut info = CypdPortInfo { + port: 0, + c_state: CypdTypeCState::Sink, + pd_contract: true, + power_role: CypdPdPowerRole::Source, + data_role: CypdPdDataRole::Dfp, + vconn: true, + voltage: 20000, + current: 3000, + cc_polarity: CcPolarity::from(1), + epr_active: false, + epr_support: false, + sink_active: false, + dp_alt_mode_status: 0x00, + }; + assert!(info.connected()); + assert_eq!(info.power_mw(), 60000); + assert_eq!(info.cc_polarity, CcPolarity::Cc2); + assert!(!info.dp_alt_mode_active()); + assert!(info.dp_alt_modes().is_empty()); + + // Bit 2 (Power Low) alone doesn't mean DP alt mode is active + info.dp_alt_mode_status = 0x04; + assert!(!info.dp_alt_mode_active()); + assert_eq!(info.dp_alt_modes(), vec!["Power Low"]); + + info.dp_alt_mode_status = 0x99; + assert!(info.dp_alt_mode_active()); + assert_eq!( + info.dp_alt_modes(), + vec!["DFP_D Connected", "Enabled", "Multi-Function", "HPD High"] + ); + } + #[test] fn decode_fan_speed() { assert_eq!(FanSpeed::from(0), FanSpeed::Rpm(0)); From 48064c41bd68ab08ec9320b01e2135bb4eb156a3 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sat, 19 Sep 2026 12:12:02 +0200 Subject: [PATCH 03/26] --pdports-chromebook: Extract data functions Signed-off-by: Daniel Schaefer --- framework_lib/src/commandline/mod.rs | 2 +- framework_lib/src/power.rs | 136 +++++++++++++++++---------- 2 files changed, 85 insertions(+), 53 deletions(-) diff --git a/framework_lib/src/commandline/mod.rs b/framework_lib/src/commandline/mod.rs index 3783bfce..b05555e1 100644 --- a/framework_lib/src/commandline/mod.rs +++ b/framework_lib/src/commandline/mod.rs @@ -1766,7 +1766,7 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { } else if args.pdports { power::print_cypd_pd_info(&ec); } else if args.pdports_chromebook { - power::get_and_print_pd_info(&ec); + power::print_pd_info(&ec); } else if args.info { smbios_info(); } else if let Some(dump_path) = &args.meinfo { diff --git a/framework_lib/src/power.rs b/framework_lib/src/power.rs index e3d5a827..db2e3ebe 100644 --- a/framework_lib/src/power.rs +++ b/framework_lib/src/power.rs @@ -908,7 +908,7 @@ pub fn check_update_ready(power_info: &PowerInfo) -> bool { } } -#[derive(Debug, PartialEq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum UsbChargingType { None = 0, PD = 1, @@ -921,7 +921,7 @@ pub enum UsbChargingType { VBus = 8, Unknown = 9, } -#[derive(Debug, PartialEq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum UsbPowerRoles { Disconnected = 0, Source = 1, @@ -929,6 +929,8 @@ pub enum UsbPowerRoles { SinkNotCharging = 3, } +/// Voltage and current measurements of a USB-C port, in mV and mA +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct UsbChargeMeasures { pub voltage_max: u16, pub voltage_now: u16, @@ -936,6 +938,11 @@ pub struct UsbChargeMeasures { pub current_lim: u16, } +/// Power state of a USB-C port as reported by EC_CMD_USB_PD_POWER_INFO +/// +/// Use [`get_pd_info`] to read it and [`print_pd_info`] to show it like the +/// commandline tool does. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct UsbPdPowerInfo { pub role: UsbPowerRoles, pub charging_type: UsbChargingType, @@ -1274,63 +1281,44 @@ pub fn print_cypd_pd_info(ec: &CrosEc) { } } -pub fn get_and_print_pd_info(ec: &CrosEc) { - let fl16 = Some(PlatformFamily::Framework16) == smbios::get_family(); +/// Physical location of a USB-C port, as the user sees it +/// +/// The port numbering does not match diagrams you might see elsewhere. +pub fn pd_port_name(port: usize, family: Option) -> &'static str { + let fl16 = family == Some(PlatformFamily::Framework16); + match port { + 0 => "Right Back", + 1 => { + if fl16 { + "Right Middle" + } else { + "Right Front" + } + } + 2 => { + if fl16 { + "Left Middle" + } else { + "Left Front" + } + } + 3 => "Left Back", + _ => "??", + } +} + +/// Print the power state of all USB-C ports like the commandline tool does +pub fn print_pd_info(ec: &CrosEc) { + let family = smbios::get_family(); let ports = 4; // All our platforms have 4 PD ports so far let infos = get_pd_info(ec, ports); for (port, info) in infos.iter().enumerate().take(ports.into()) { - println!( - "USB-C Port {} ({}):", - port, - match port { - 0 => "Right Back", - 1 => - if fl16 { - "Right Middle" - } else { - "Right Front" - }, - 2 => - if fl16 { - "Left Middle" - } else { - "Left Front" - }, - 3 => "Left Back", - _ => "??", - } - ); + println!("USB-C Port {} ({}):", port, pd_port_name(port, family)); print_err_ref(info); // TODO: I haven't checked the encoding/endianness of these numbers. They're likely incorrectly decoded if let Ok(info) = info { - println!(" Role: {:?}", info.role); - - println!(" Charging Type: {:?}", info.charging_type); - - let volt_max = { info.meas.voltage_max }; - let volt_now = { info.meas.voltage_now }; - println!( - " Voltage Now: {}.{} V, Max: {}.{} V", - volt_now / 1000, - volt_now % 1000, - volt_max / 1000, - volt_max % 1000, - ); - - let cur_lim = { info.meas.current_lim }; - let cur_max = { info.meas.current_max }; - println!(" Current Lim: {} mA, Max: {} mA", cur_lim, cur_max); - println!( - " Dual Role: {}", - if info.dualrole { "DRP" } else { "Charger" } - ); - let max_power_mw = { info.max_power } / 1000; - println!( - " Max Power: {}.{} W", - max_power_mw / 1000, - max_power_mw % 1000 - ); + print_pd_port_info(info); } else { println!(" Role: Unknown"); println!(" Charging Type: Unknown"); @@ -1343,6 +1331,37 @@ pub fn get_and_print_pd_info(ec: &CrosEc) { } } +/// Print the power state of a single USB-C port like the commandline tool does +pub fn print_pd_port_info(info: &UsbPdPowerInfo) { + println!(" Role: {:?}", info.role); + + println!(" Charging Type: {:?}", info.charging_type); + + let volt_max = info.meas.voltage_max; + let volt_now = info.meas.voltage_now; + println!( + " Voltage Now: {}.{} V, Max: {}.{} V", + volt_now / 1000, + volt_now % 1000, + volt_max / 1000, + volt_max % 1000, + ); + + let cur_lim = info.meas.current_lim; + let cur_max = info.meas.current_max; + println!(" Current Lim: {} mA, Max: {} mA", cur_lim, cur_max); + println!( + " Dual Role: {}", + if info.dualrole { "DRP" } else { "Charger" } + ); + let max_power_mw = info.max_power / 1000; + println!( + " Max Power: {}.{} W", + max_power_mw / 1000, + max_power_mw % 1000 + ); +} + // TODO: Improve return type to be more obvious // (right, left) pub fn is_charging(ec: &CrosEc) -> EcResult<(bool, bool)> { @@ -1460,6 +1479,19 @@ mod tests { ); } + #[test] + fn pd_port_names() { + let fl13 = Some(PlatformFamily::Framework13); + let fl16 = Some(PlatformFamily::Framework16); + assert_eq!(pd_port_name(0, fl13), "Right Back"); + assert_eq!(pd_port_name(1, fl13), "Right Front"); + assert_eq!(pd_port_name(1, fl16), "Right Middle"); + assert_eq!(pd_port_name(2, None), "Left Front"); + assert_eq!(pd_port_name(2, fl16), "Left Middle"); + assert_eq!(pd_port_name(3, fl16), "Left Back"); + assert_eq!(pd_port_name(4, fl16), "??"); + } + #[test] fn decode_fan_speed() { assert_eq!(FanSpeed::from(0), FanSpeed::Rpm(0)); From c722a51c79d7b33d245b0f4b5acc744ceeb0e09b Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sat, 19 Sep 2026 12:13:59 +0200 Subject: [PATCH 04/26] --swiches: Extract data functions Signed-off-by: Daniel Schaefer --- framework_lib/src/power.rs | 62 ++++++++++++++++++++++++++++++++------ 1 file changed, 52 insertions(+), 10 deletions(-) diff --git a/framework_lib/src/power.rs b/framework_lib/src/power.rs index db2e3ebe..70292688 100644 --- a/framework_lib/src/power.rs +++ b/framework_lib/src/power.rs @@ -375,21 +375,53 @@ pub fn set_thermal_thresholds(ec: &CrosEc, sensor: u32, values: &[i32]) -> EcRes ec.set_thermal_threshold(sensor, cfg) } +/// Current positions of the EC switches (lid, power button, ...) +/// +/// Use [`get_switches`] to read it and [`print_switches`] to show it like the +/// commandline tool does. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Switches { + /// Raw switch bits as read from the EC memory map + pub raw: u8, + /// Whether the lid is open + pub lid_open: bool, + /// Whether the power button is currently pressed + pub power_button_pressed: bool, + /// Whether EC firmware write protect is disabled + pub write_protect_disabled: bool, + /// Whether the dedicated recovery switch is enabled + pub dedicated_recovery: bool, +} + +impl From for Switches { + fn from(switches: u8) -> Self { + Switches { + raw: switches, + lid_open: switches & EC_SWITCH_LID_OPEN != 0, + power_button_pressed: switches & EC_SWITCH_POWER_BUTTON_PRESSED != 0, + write_protect_disabled: switches & EC_SWITCH_WRITE_PROTECT_DISABLED != 0, + dedicated_recovery: switches & EC_SWITCH_DEDICATED_RECOVERY != 0, + } + } +} + +/// Read the current EC switch positions (lid, power button, ...) +pub fn get_switches(ec: &CrosEc) -> Option { + let switches = *ec.read_memory(EC_MEMMAP_SWITCHES, 1)?.first()?; + Some(Switches::from(switches)) +} + /// Print the current EC switch positions (lid, power button, ...) pub fn print_switches(ec: &CrosEc) -> Option<()> { - let switches = *ec.read_memory(EC_MEMMAP_SWITCHES, 1)?.first()?; - println!("Current switches: {:#04x}", switches); + let switches = get_switches(ec)?; + println!("Current switches: {:#04x}", switches.raw); println!( "Lid switch: {}", - if switches & EC_SWITCH_LID_OPEN != 0 { - "OPEN" - } else { - "CLOSED" - } + if switches.lid_open { "OPEN" } else { "CLOSED" } ); println!( "Power button: {}", - if switches & EC_SWITCH_POWER_BUTTON_PRESSED != 0 { + if switches.power_button_pressed { "DOWN" } else { "UP" @@ -397,7 +429,7 @@ pub fn print_switches(ec: &CrosEc) -> Option<()> { ); println!( "Write protect: {}ABLED", - if switches & EC_SWITCH_WRITE_PROTECT_DISABLED != 0 { + if switches.write_protect_disabled { "DIS" } else { "EN" @@ -405,7 +437,7 @@ pub fn print_switches(ec: &CrosEc) -> Option<()> { ); println!( "Dedicated recovery: {}ABLED", - if switches & EC_SWITCH_DEDICATED_RECOVERY != 0 { + if switches.dedicated_recovery { "EN" } else { "DIS" @@ -1492,6 +1524,16 @@ mod tests { assert_eq!(pd_port_name(4, fl16), "??"); } + #[test] + fn decode_switches() { + let switches = Switches::from(EC_SWITCH_LID_OPEN | EC_SWITCH_WRITE_PROTECT_DISABLED); + assert!(switches.lid_open); + assert!(!switches.power_button_pressed); + assert!(switches.write_protect_disabled); + assert!(!switches.dedicated_recovery); + assert_eq!(switches.raw, 0x05); + } + #[test] fn decode_fan_speed() { assert_eq!(FanSpeed::from(0), FanSpeed::Rpm(0)); From 5bbd759374f32a49f93e0cc97b3748a9786c0e93 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sat, 19 Sep 2026 12:16:58 +0200 Subject: [PATCH 05/26] --sensors: Extract data functions Signed-off-by: Daniel Schaefer --- framework_lib/src/chromium_ec/commands.rs | 2 +- framework_lib/src/power.rs | 140 +++++++++++++++++----- 2 files changed, 111 insertions(+), 31 deletions(-) diff --git a/framework_lib/src/chromium_ec/commands.rs b/framework_lib/src/chromium_ec/commands.rs index 900383b8..1a21aed7 100644 --- a/framework_lib/src/chromium_ec/commands.rs +++ b/framework_lib/src/chromium_ec/commands.rs @@ -424,7 +424,7 @@ pub enum MotionSenseType { LightRgb = 8, } -#[derive(Debug, FromPrimitive)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive)] pub enum MotionSenseLocation { Base = 0, Lid = 1, diff --git a/framework_lib/src/power.rs b/framework_lib/src/power.rs index 70292688..5a573c5a 100644 --- a/framework_lib/src/power.rs +++ b/framework_lib/src/power.rs @@ -481,7 +481,40 @@ pub fn get_accel_data(ec: &CrosEc) -> (AccelData, AccelData, LidAngle) { ) } -pub fn print_sensors(ec: &CrosEc) { +/// A single accelerometer and its current reading +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Accelerometer { + /// Where the sensor is mounted + pub location: MotionSenseLocation, + pub data: AccelData, +} + +/// All accelerometer data the EC reports in its memory map +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AccelInfo { + /// Whether the EC was updating the data while we read it + pub busy: bool, + pub lid_angle: LidAngle, + /// Present accelerometers, usually lid and base + pub sensors: Vec, +} + +/// All sensor readings the EC reports at once +/// +/// Use [`get_sensors`] to read it and [`print_sensors`] to show it like the +/// commandline tool does. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SensorInfo { + /// Ambient light in Lux, `None` if the system has no ambient light sensor + pub als: Option, + /// `None` if the system has no accelerometers + pub accel: Option, +} + +/// Read ambient light and accelerometer sensors from the EC +/// +/// Returns `None` if the EC memory map could not be read. +pub fn get_sensors(ec: &CrosEc) -> Option { let mut has_als = false; let mut accel_locations = vec![]; @@ -513,44 +546,74 @@ pub fn print_sensors(ec: &CrosEc) { Some(PlatformFamily::Framework13) | Some(PlatformFamily::Framework16) | None ); - if has_als || als_family { - let als_int = get_als_reading(ec, 0).unwrap(); - println!("ALS: {:>4} Lux", als_int); - } + let als = if has_als || als_family { + Some(get_als_reading(ec, 0)?) + } else { + None + }; // bit 4 = busy // bit 7 = present // #define EC_MEMMAP_ACC_STATUS_SAMPLE_ID_MASK 0x0f - let acc_status = ec.read_memory(EC_MEMMAP_ACC_STATUS, 0x01).unwrap()[0]; + let acc_status = *ec.read_memory(EC_MEMMAP_ACC_STATUS, 0x01)?.first()?; // While busy, keep reading - let lid_angle = ec.read_memory(EC_MEMMAP_ACC_DATA, 0x02).unwrap(); - let lid_angle = u16::from_le_bytes([lid_angle[0], lid_angle[1]]); - let accel_1 = ec.read_memory(EC_MEMMAP_ACC_DATA + 2, 0x06).unwrap(); - let accel_2 = ec.read_memory(EC_MEMMAP_ACC_DATA + 8, 0x06).unwrap(); - let present = (acc_status & 0x80) > 0; - if present { + let busy = (acc_status & 0x8) > 0; + debug!(" Status Bit: {} 0x{:X}", acc_status, acc_status); + debug!(" Present: {}", present); + debug!(" Busy: {}", busy); + + let accel = if present { + let lid_angle = ec.read_memory(EC_MEMMAP_ACC_DATA, 0x02)?; + let lid_angle = u16::from_le_bytes([lid_angle[0], lid_angle[1]]); + let accel_1 = ec.read_memory(EC_MEMMAP_ACC_DATA + 2, 0x06)?; + let accel_2 = ec.read_memory(EC_MEMMAP_ACC_DATA + 8, 0x06)?; + + // The memory map has room for exactly two accelerometers, in the + // order motionsense lists them + let sensors = accel_locations + .into_iter() + .zip([AccelData::from(accel_1), AccelData::from(accel_2)]) + .map(|(location, data)| Accelerometer { location, data }) + .collect(); + + Some(AccelInfo { + busy, + lid_angle: LidAngle::from(lid_angle), + sensors, + }) + } else { + None + }; + + Some(SensorInfo { als, accel }) +} + +/// Print ambient light and accelerometer sensors like the commandline tool does +pub fn print_sensors(ec: &CrosEc) { + let Some(info) = get_sensors(ec) else { + println!("Failed to read sensors"); + return; + }; + + if let Some(als) = info.als { + println!("ALS: {:>4} Lux", als); + } + + if let Some(accel) = &info.accel { println!("Accelerometers:"); - debug!(" Status Bit: {} 0x{:X}", acc_status, acc_status); - debug!(" Present: {}", present); - debug!(" Busy: {}", (acc_status & 0x8) > 0); - print!(" Lid Angle: "); - if lid_angle == LID_ANGLE_UNRELIABLE { - println!("Unreliable"); - } else { - println!("{} Deg", lid_angle); + match accel.lid_angle { + LidAngle::Angle(deg) => println!(" Lid Angle: {} Deg", deg), + LidAngle::Unreliable => println!(" Lid Angle: Unreliable"), + } + for sensor in &accel.sensors { + println!( + " {:<12} {}", + format!("{:?} Sensor:", sensor.location), + sensor.data + ); } - println!( - " {:<12} {}", - format!("{:?} Sensor:", accel_locations[0]), - AccelData::from(accel_1) - ); - println!( - " {:<12} {}", - format!("{:?} Sensor:", accel_locations[1]), - AccelData::from(accel_2) - ); } } @@ -1534,6 +1597,23 @@ mod tests { assert_eq!(switches.raw, 0x05); } + #[test] + fn decode_accel_data() { + // 1G on Z, slightly negative X + let data = AccelData::from(vec![0xF0, 0xFF, 0x00, 0x00, 0xFF, 0x3F]); + assert_eq!( + data, + AccelData { + x: -16, + y: 0, + z: 16383 + } + ); + assert_eq!(data.to_string(), "X=-0.00G Y=+0.00G, Z=+1.00G"); + assert_eq!(LidAngle::from(500), LidAngle::Unreliable); + assert_eq!(LidAngle::from(118), LidAngle::Angle(118)); + } + #[test] fn decode_fan_speed() { assert_eq!(FanSpeed::from(0), FanSpeed::Rpm(0)); From 47c2318634488afd6b01cfdfe9868401b82d200c Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sat, 19 Sep 2026 12:23:22 +0200 Subject: [PATCH 06/26] --sysinfo: Extract data functions Signed-off-by: Daniel Schaefer --- framework_lib/src/chromium_ec/commands.rs | 4 +- framework_lib/src/chromium_ec/mod.rs | 116 ++++++++++++++++------ framework_lib/src/commandline/mod.rs | 4 +- 3 files changed, 91 insertions(+), 33 deletions(-) diff --git a/framework_lib/src/chromium_ec/commands.rs b/framework_lib/src/chromium_ec/commands.rs index 1a21aed7..8f437652 100644 --- a/framework_lib/src/chromium_ec/commands.rs +++ b/framework_lib/src/chromium_ec/commands.rs @@ -202,7 +202,7 @@ pub struct EcRequestSysinfo {} /// Bits of EcResponseSysinfo flags (enum sysinfo_flags) #[repr(usize)] -#[derive(Debug, FromPrimitive)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive)] pub enum SysinfoFlag { /// Write protect is asserted, debug features are disabled Locked, @@ -1139,7 +1139,7 @@ impl EcRequest for EcRequestUsbPdPowerInfo { } #[repr(usize)] -#[derive(Debug, FromPrimitive)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive)] pub enum EcResetFlag { /// Other known reason Other, diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index 51adfa09..cbc1b83b 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -2050,36 +2050,18 @@ impl CrosEc { } } - pub fn get_sysinfo(&self) -> EcResult<()> { + /// Read which image the EC runs and why it was reset + pub fn get_sysinfo(&self) -> EcResult { let res = EcRequestSysinfo {}.send_command(self)?; - let current_image = match res.current_image { - 1 => EcCurrentImage::RO, - 2 => EcCurrentImage::RW, - _ => EcCurrentImage::Unknown, - }; - println!("EC System Info"); - println!(" Current Image: {:?}", current_image); - println!(" Reset Flags: {:#010X}", { res.reset_flags }); - for flag in 0..(EcResetFlag::Count as usize) { - if ((1 << flag) & res.reset_flags) > 0 { - // Safe to unwrap unless coding mistake - println!( - " {:?}", - ::from_usize(flag).unwrap() - ); - } - } - println!(" Flags: {:#010X}", { res.flags }); - for flag in 0..(SysinfoFlag::Count as usize) { - if ((1 << flag) & res.flags) > 0 { - // Safe to unwrap unless coding mistake - println!( - " {:?}", - ::from_usize(flag).unwrap() - ); - } - } - Ok(()) + Ok(SysInfo { + current_image: match res.current_image { + 1 => EcCurrentImage::RO, + 2 => EcCurrentImage::RW, + _ => EcCurrentImage::Unknown, + }, + reset_flags: res.reset_flags, + flags: res.flags, + }) } pub fn get_uptime_info(&self) -> EcResult<()> { @@ -2241,13 +2223,62 @@ pub struct ChargeState { } /// Which of the two EC images is currently in-use -#[derive(PartialEq, Debug)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum EcCurrentImage { Unknown = 0, RO = 1, RW = 2, } +/// Decode a bitmask into the enum variants of the set bits +/// +/// Bits without a known variant are skipped. +fn decode_flags(flags: u32, count: usize) -> Vec { + (0..count) + .filter(|bit| flags & (1 << bit) != 0) + .filter_map(T::from_usize) + .collect() +} + +/// EC system information, as reported by EC_CMD_SYSINFO +/// +/// Use [`CrosEc::get_sysinfo`] to read it and [`print_sysinfo`] to show it +/// like the commandline tool does. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SysInfo { + pub current_image: EcCurrentImage, + /// Raw reset flags of the current boot, see [`SysInfo::reset_flags`] + pub reset_flags: u32, + /// Raw sysinfo flags, see [`SysInfo::flags`] + pub flags: u32, +} + +impl SysInfo { + /// Why the EC was reset + pub fn reset_flags(&self) -> Vec { + decode_flags(self.reset_flags, EcResetFlag::Count as usize) + } + + /// Decoded sysinfo flags + pub fn flags(&self) -> Vec { + decode_flags(self.flags, SysinfoFlag::Count as usize) + } +} + +/// Print EC system information like the commandline tool does +pub fn print_sysinfo(info: &SysInfo) { + println!("EC System Info"); + println!(" Current Image: {:?}", info.current_image); + println!(" Reset Flags: {:#010X}", info.reset_flags); + for flag in info.reset_flags() { + println!(" {:?}", flag); + } + println!(" Flags: {:#010X}", info.flags); + for flag in info.flags() { + println!(" {:?}", flag); + } +} + pub struct IntrusionStatus { /// Whether the chassis is currently open pub currently_open: bool, @@ -2288,3 +2319,28 @@ pub struct GpuCfgDescriptor { /// CRC of header before this value pub crc32: u32, } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn decode_sysinfo_flags() { + let info = SysInfo { + current_image: EcCurrentImage::RW, + // Bits 0 and 3 set, plus an unknown high bit + reset_flags: 0x8000_0009, + // JumpEnabled and JumpedToCurrentImage + flags: 0b1100, + }; + assert_eq!( + info.reset_flags(), + vec![EcResetFlag::Other, EcResetFlag::PowerOn] + ); + assert_eq!( + info.flags(), + vec![SysinfoFlag::JumpEnabled, SysinfoFlag::JumpedToCurrentImage] + ); + assert!(decode_flags::(0, SysinfoFlag::Count as usize).is_empty()); + } +} diff --git a/framework_lib/src/commandline/mod.rs b/framework_lib/src/commandline/mod.rs index b05555e1..739974ec 100644 --- a/framework_lib/src/commandline/mod.rs +++ b/framework_lib/src/commandline/mod.rs @@ -1621,7 +1621,9 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { } print_err(ec.get_ec_hib_delay()); } else if args.sysinfo { - print_err(ec.get_sysinfo()); + if let Some(info) = print_err(ec.get_sysinfo()) { + chromium_ec::print_sysinfo(&info); + } } else if args.uptimeinfo { print_err(ec.get_uptime_info()); } else if args.s0ix_counter { From f591b4569f2fc779860880dff29def74bb80dedd Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sat, 19 Sep 2026 12:40:09 +0200 Subject: [PATCH 07/26] --uptimeinfo: Extra data functions Signed-off-by: Daniel Schaefer --- framework_lib/src/chromium_ec/commands.rs | 2 +- framework_lib/src/chromium_ec/mod.rs | 136 +++++++++++++++------- framework_lib/src/commandline/mod.rs | 4 +- 3 files changed, 101 insertions(+), 41 deletions(-) diff --git a/framework_lib/src/chromium_ec/commands.rs b/framework_lib/src/chromium_ec/commands.rs index 8f437652..9c3f08f4 100644 --- a/framework_lib/src/chromium_ec/commands.rs +++ b/framework_lib/src/chromium_ec/commands.rs @@ -1191,7 +1191,7 @@ pub enum EcResetFlag { } #[repr(u16)] -#[derive(Debug, FromPrimitive)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive)] pub enum ResetCause { ResetUnknown = 0x0000, /// Custom reason defined by a board.c or baseboard.c file diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index cbc1b83b..bc902663 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -2064,46 +2064,26 @@ impl CrosEc { }) } - pub fn get_uptime_info(&self) -> EcResult<()> { + /// Read how long the EC has been running and how often it reset the AP + pub fn get_uptime_info(&self) -> EcResult { let res = EcRequestGetUptimeInfo {}.send_command(self)?; - let t_since_boot = Duration::from_millis(res.time_since_ec_boot.into()); - println!("EC Uptime"); - println!( - " Time since EC Boot: {}", - util::format_duration(&t_since_boot) - ); - println!(" AP Resets since EC Boot: {}", { - res.ap_resets_since_ec_boot - }); - println!(" EC Reset Flags"); - for flag in 0..(EcResetFlag::Count as usize) { - if ((1 << flag) & res.ec_reset_flags) > 0 { - // Safe to unwrap unless coding mistake - println!( - " {:?}", - ::from_usize(flag).unwrap() - ); - } - } - println!(" Recent AP Resets"); - for reset in res.recent_ap_resets { - if reset.reset_time_ms == 0 { - // Empty entry - continue; - } - let reset_time = Duration::from_millis(reset.reset_time_ms.into()); - println!( - " Reset Time: {}", - util::format_duration(&reset_time) - ); - let reset_cause: Option = FromPrimitive::from_u16(reset.reset_cause); - if let Some(cause) = reset_cause { - println!(" Cause: {:?}", cause); - } else { - println!(" Cause: Unknown"); - } - } - Ok(()) + let recent_ap_resets = res + .recent_ap_resets + .iter() + // Empty entries have a zero timestamp + .filter(|reset| reset.reset_time_ms != 0) + .map(|reset| ApReset { + time_since_ec_boot: Duration::from_millis(reset.reset_time_ms.into()), + cause: FromPrimitive::from_u16(reset.reset_cause), + raw_cause: reset.reset_cause, + }) + .collect(); + Ok(UptimeInfo { + time_since_ec_boot: Duration::from_millis(res.time_since_ec_boot.into()), + ap_resets_since_ec_boot: res.ap_resets_since_ec_boot, + ec_reset_flags: res.ec_reset_flags, + recent_ap_resets, + }) } pub fn get_ap_throttle_status(&self) -> EcResult { @@ -2265,6 +2245,69 @@ impl SysInfo { } } +/// One entry of the EC's log of AP resets +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ApReset { + /// When the reset happened, relative to EC boot + pub time_since_ec_boot: Duration, + /// Why the EC reset the AP, `None` if the cause is not known to us + pub cause: Option, + /// Raw reset cause, for causes we can't decode + pub raw_cause: u16, +} + +/// EC uptime and AP reset log, as reported by EC_CMD_GET_UPTIME_INFO +/// +/// Use [`CrosEc::get_uptime_info`] to read it and [`print_uptime_info`] to +/// show it like the commandline tool does. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UptimeInfo { + pub time_since_ec_boot: Duration, + /// How often the AP was reset by the EC since last EC boot + /// The first AP boot may count as more than one + pub ap_resets_since_ec_boot: u32, + /// Raw EC reset flags, see [`UptimeInfo::ec_reset_flags`] + pub ec_reset_flags: u32, + /// Most recent AP resets, oldest first, at most 4 + pub recent_ap_resets: Vec, +} + +impl UptimeInfo { + /// Why the EC was reset + pub fn ec_reset_flags(&self) -> Vec { + decode_flags(self.ec_reset_flags, EcResetFlag::Count as usize) + } +} + +/// Print EC uptime and AP reset log like the commandline tool does +pub fn print_uptime_info(info: &UptimeInfo) { + println!("EC Uptime"); + println!( + " Time since EC Boot: {}", + util::format_duration(&info.time_since_ec_boot) + ); + println!( + " AP Resets since EC Boot: {}", + info.ap_resets_since_ec_boot + ); + println!(" EC Reset Flags"); + for flag in info.ec_reset_flags() { + println!(" {:?}", flag); + } + println!(" Recent AP Resets"); + for reset in &info.recent_ap_resets { + println!( + " Reset Time: {}", + util::format_duration(&reset.time_since_ec_boot) + ); + if let Some(cause) = reset.cause { + println!(" Cause: {:?}", cause); + } else { + println!(" Cause: Unknown"); + } + } +} + /// Print EC system information like the commandline tool does pub fn print_sysinfo(info: &SysInfo) { println!("EC System Info"); @@ -2343,4 +2386,19 @@ mod tests { ); assert!(decode_flags::(0, SysinfoFlag::Count as usize).is_empty()); } + + #[test] + fn decode_uptime_reset_flags() { + let info = UptimeInfo { + time_since_ec_boot: Duration::from_millis(1234), + ap_resets_since_ec_boot: 1, + // Brownout and Watchdog + ec_reset_flags: 0b10100, + recent_ap_resets: vec![], + }; + assert_eq!( + info.ec_reset_flags(), + vec![EcResetFlag::Brownout, EcResetFlag::Watchdog] + ); + } } diff --git a/framework_lib/src/commandline/mod.rs b/framework_lib/src/commandline/mod.rs index 739974ec..5582e113 100644 --- a/framework_lib/src/commandline/mod.rs +++ b/framework_lib/src/commandline/mod.rs @@ -1625,7 +1625,9 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { chromium_ec::print_sysinfo(&info); } } else if args.uptimeinfo { - print_err(ec.get_uptime_info()); + if let Some(info) = print_err(ec.get_uptime_info()) { + chromium_ec::print_uptime_info(&info); + } } else if args.s0ix_counter { if let Some(counter) = print_err(ec.get_s0ix_counter()) { println!("s0ix_counter: {}", counter); From 49c0bd9b2d69840208ded8718efa8991a2fe30da Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sat, 19 Sep 2026 12:42:00 +0200 Subject: [PATCH 08/26] --features: Extract data functions Signed-off-by: Daniel Schaefer --- framework_lib/src/chromium_ec/commands.rs | 2 +- framework_lib/src/chromium_ec/mod.rs | 90 +++++++++++++++++++---- framework_lib/src/commandline/mod.rs | 4 +- 3 files changed, 78 insertions(+), 18 deletions(-) diff --git a/framework_lib/src/chromium_ec/commands.rs b/framework_lib/src/chromium_ec/commands.rs index 9c3f08f4..39d4fae6 100644 --- a/framework_lib/src/chromium_ec/commands.rs +++ b/framework_lib/src/chromium_ec/commands.rs @@ -886,7 +886,7 @@ impl EcRequest for EcRequestS0ixCounter { } /// Supported features -#[derive(Debug, FromPrimitive)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive)] pub enum EcFeatureCode { /// This image contains a limited set of features. Another image /// in RW partition may support more features. diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index bc902663..0c88e080 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -1847,23 +1847,9 @@ impl CrosEc { } /// Check features supported by the firmware - pub fn get_features(&self) -> EcResult<()> { + pub fn get_features(&self) -> EcResult { let data = EcRequestGetFeatures {}.send_command(self)?; - println!(" ID | Name | Enabled?"); - println!(" -- | --------------------------- | --------"); - for i in 0..64 { - let byte = i / 32; - let bit = i % 32; - let val = (data.flags[byte] & (1 << bit)) > 0; - let feat: Option = FromPrimitive::from_usize(i); - - if let Some(feat) = feat { - let name = format!("{:?}", feat); - println!(" {:>2} | {:<27} | {:>5}", i, name, val); - } - } - - Ok(()) + Ok(EcFeatures { flags: data.flags }) } /// Instantly reboot EC and host @@ -2245,6 +2231,59 @@ impl SysInfo { } } +/// Features supported by the EC firmware, as reported by EC_CMD_GET_FEATURES +/// +/// Use [`CrosEc::get_features`] to read it and [`print_features`] to show it +/// like the commandline tool does. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct EcFeatures { + /// Raw feature bitmask, bit N is feature N + pub flags: [u32; 2], +} + +impl EcFeatures { + /// Number of bits in the feature bitmask + const BITS: usize = 64; + + fn bit(&self, i: usize) -> bool { + self.flags[i / 32] & (1 << (i % 32)) != 0 + } + + /// Whether the firmware supports a feature + pub fn is_enabled(&self, feature: EcFeatureCode) -> bool { + self.bit(feature as usize) + } + + /// All features known to us and whether the firmware supports them + pub fn known(&self) -> Vec<(EcFeatureCode, bool)> { + (0..Self::BITS) + .filter_map(|i| { + let feature: EcFeatureCode = FromPrimitive::from_usize(i)?; + Some((feature, self.bit(i))) + }) + .collect() + } + + /// All features known to us that the firmware supports + pub fn enabled(&self) -> Vec { + self.known() + .into_iter() + .filter(|(_, enabled)| *enabled) + .map(|(feature, _)| feature) + .collect() + } +} + +/// Print supported EC features like the commandline tool does +pub fn print_features(features: &EcFeatures) { + println!(" ID | Name | Enabled?"); + println!(" -- | --------------------------- | --------"); + for (feature, enabled) in features.known() { + let name = format!("{:?}", feature); + println!(" {:>2} | {:<27} | {:>5}", feature as usize, name, enabled); + } +} + /// One entry of the EC's log of AP resets #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ApReset { @@ -2387,6 +2426,25 @@ mod tests { assert!(decode_flags::(0, SysinfoFlag::Count as usize).is_empty()); } + #[test] + fn decode_features() { + let features = EcFeatures { + // Limited (bit 0) and UcsiPpm (bit 54) + flags: [0x1, 1 << (54 - 32)], + }; + assert!(features.is_enabled(EcFeatureCode::Limited)); + assert!(features.is_enabled(EcFeatureCode::UcsiPpm)); + assert!(!features.is_enabled(EcFeatureCode::Dp21)); + assert_eq!( + features.enabled(), + vec![EcFeatureCode::Limited, EcFeatureCode::UcsiPpm] + ); + // Every known feature shows up exactly once + let known = features.known(); + assert!(known.len() > 2); + assert!(known.contains(&(EcFeatureCode::Dp21, false))); + } + #[test] fn decode_uptime_reset_flags() { let info = UptimeInfo { diff --git a/framework_lib/src/commandline/mod.rs b/framework_lib/src/commandline/mod.rs index 5582e113..82523ecd 100644 --- a/framework_lib/src/commandline/mod.rs +++ b/framework_lib/src/commandline/mod.rs @@ -1408,7 +1408,9 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { } else if args.version { print_tool_version(); } else if args.features { - print_err(ec.get_features()); + if let Some(features) = print_err(ec.get_features()) { + chromium_ec::print_features(&features); + } } else if args.esrt { print_esrt(); } else if let Some(compare_version_ver) = &args.compare_version { From 61714d67078945dec79834dd0e2ac7bbbb1c735b Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sat, 19 Sep 2026 12:49:52 +0200 Subject: [PATCH 09/26] --inputdeck: Return data instead of only printing it --- framework_lib/src/chromium_ec/input_deck.rs | 224 ++++++++++++++++++++ framework_lib/src/chromium_ec/mod.rs | 124 +---------- framework_lib/src/commandline/mod.rs | 27 +-- framework_lib/src/util.rs | 2 +- 4 files changed, 229 insertions(+), 148 deletions(-) diff --git a/framework_lib/src/chromium_ec/input_deck.rs b/framework_lib/src/chromium_ec/input_deck.rs index 68920688..b65a6cb3 100644 --- a/framework_lib/src/chromium_ec/input_deck.rs +++ b/framework_lib/src/chromium_ec/input_deck.rs @@ -1,4 +1,10 @@ +use alloc::format; +use alloc::string::{String, ToString}; + use super::commands::EcResponseDeckState; +use super::{CrosEc, EcResult, Framework12Adc, Framework13Adc, FrameworkHx20Hx30Adc}; +use crate::smbios; +use crate::util::{Platform, PlatformFamily}; /// The number of slots on the input deck, where modules can be connected to pub const INPUT_DECK_SLOTS: usize = 8; @@ -221,3 +227,221 @@ pub struct TopRowPositions { /// C1 all the way right pub pos4: InputModuleType, } + +/// A daughterboard connected to the input deck +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Daughterboard { + /// Board ID, `None` if the board is not connected + pub board_id: Option, + /// Raw reading of the board ID ADC channel in mV, `None` if it couldn't be read + pub adc_mv: Option, +} + +impl Daughterboard { + pub fn present(&self) -> bool { + self.board_id.is_some() + } +} + +/// Everything we know about the input deck +/// +/// Which fields are filled depends on the platform family. Use +/// [`CrosEc::get_inputdeck_status`] to read it and [`print_inputdeck_status`] +/// to show it like the commandline tool does. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct InputDeckInfo { + /// Platform family the layout was decoded for, `None` if unknown + pub family: Option, + /// Whether the chassis intrusion switch reports the chassis as closed + pub chassis_closed: Option, + /// Framework 12 only + pub power_button_board: Option, + /// Framework 12 and 13 + pub audio_board: Option, + /// Framework 12 and 13 + pub touchpad_board: Option, + /// State of the input deck, `None` if the EC doesn't report it + pub deck_status: Option, + /// Framework 16 only, whether the SLEEP# GPIO is high + pub sleep_l: Option, +} + +impl CrosEc { + fn daughterboard(&self, board_id: Option, adc_channel: u8) -> Daughterboard { + Daughterboard { + board_id, + adc_mv: self.adc_read(adc_channel).ok(), + } + } + + /// Read the state of the input deck and the boards connected to it + /// + /// If the platform family is unknown, tries to detect a Framework 16 by + /// its SLEEP# GPIO and otherwise only reads the generic deck state. + pub fn get_inputdeck_status(&self) -> EcResult { + let family = match smbios::get_family() { + family @ Some( + PlatformFamily::Framework12 + | PlatformFamily::Framework13 + | PlatformFamily::Framework16, + ) => family, + // If we don't know which platform it is, we can use some heuristics + // Only Framework Laptop 16 has this GPIO + _ if self.get_gpio("sleep_l").is_ok() => Some(PlatformFamily::Framework16), + _ => None, + }; + + let mut info = InputDeckInfo { + family, + chassis_closed: None, + power_button_board: None, + audio_board: None, + touchpad_board: None, + deck_status: None, + sleep_l: None, + }; + + match family { + Some(PlatformFamily::Framework12) => { + info.chassis_closed = Some(!self.get_intrusion_status()?.currently_open); + let pwrbtn = self.read_board_id_npc_db(Framework12Adc::PowerButtonBoardId as u8)?; + let audio = self.read_board_id_npc_db(Framework12Adc::AudioBoardId as u8)?; + let tp = self.read_board_id_npc_db(Framework12Adc::TouchpadBoardId as u8)?; + info.power_button_board = + Some(self.daughterboard(pwrbtn, Framework12Adc::PowerButtonBoardId as u8)); + info.audio_board = + Some(self.daughterboard(audio, Framework12Adc::AudioBoardId as u8)); + info.touchpad_board = + Some(self.daughterboard(tp, Framework12Adc::TouchpadBoardId as u8)); + info.deck_status = self.get_input_deck_status().ok(); + } + Some(PlatformFamily::Framework13) => { + info.chassis_closed = Some(!self.get_intrusion_status()?.currently_open); + let (audio, tp) = match smbios::get_platform() { + Some(Platform::IntelGen11) + | Some(Platform::IntelGen12) + | Some(Platform::IntelGen13) => ( + self.read_board_id(FrameworkHx20Hx30Adc::AudioBoardId as u8)?, + self.read_board_id(FrameworkHx20Hx30Adc::TouchpadBoardId as u8)?, + ), + + _ => ( + self.read_board_id_npc_db(Framework13Adc::AudioBoardId as u8)?, + self.read_board_id_npc_db(Framework13Adc::TouchpadBoardId as u8)?, + ), + }; + // TODO: On Intel 11th-13th Gen the ADC channels differ, the + // raw reading below comes from the wrong channel there + info.audio_board = + Some(self.daughterboard(audio, Framework13Adc::AudioBoardId as u8)); + info.touchpad_board = + Some(self.daughterboard(tp, Framework13Adc::TouchpadBoardId as u8)); + info.deck_status = self.get_input_deck_status().ok(); + } + Some(PlatformFamily::Framework16) => { + info.chassis_closed = Some(!self.get_intrusion_status()?.currently_open); + info.deck_status = Some(self.get_input_deck_status()?); + info.sleep_l = Some(self.get_gpio("sleep_l")?); + } + Some(PlatformFamily::FrameworkDesktop) | None => { + info.deck_status = self.get_input_deck_status().ok(); + } + } + + Ok(info) + } +} + +/// Format a daughterboard like the commandline tool does +fn format_daughterboard(board: &Daughterboard) -> String { + if let Some(board_id) = board.board_id { + format!("Present ({})", board_id) + } else { + "Missing".to_string() + } +} + +fn print_daughterboard(label: &str, board: &Daughterboard) { + println!(" {:<20} {}", label, format_daughterboard(board)); + if let Some(adc) = board.adc_mv { + println!(" ADC Value {:04}mV", adc); + } +} + +/// Print the state of the input deck like the commandline tool does +pub fn print_inputdeck_status(info: &InputDeckInfo) { + match info.family { + Some(PlatformFamily::Framework16) => { + if let Some(closed) = info.chassis_closed { + println!("Chassis Closed: {}", closed); + } + if let Some(status) = &info.deck_status { + println!("Input Deck State: {:?}", status.state); + println!("Touchpad present: {}", status.touchpad_present); + } + if let Some(sleep_l) = info.sleep_l { + println!("SLEEP# GPIO high: {}", sleep_l); + } + if let Some(status) = &info.deck_status { + println!("Positions:"); + println!(" Pos 0: {:?}", status.top_row.pos0); + println!(" Pos 1: {:?}", status.top_row.pos1); + println!(" Pos 2: {:?}", status.top_row.pos2); + println!(" Pos 3: {:?}", status.top_row.pos3); + println!(" Pos 4: {:?}", status.top_row.pos4); + } + } + Some(PlatformFamily::Framework12) | Some(PlatformFamily::Framework13) => { + println!("Input Deck"); + if let Some(closed) = info.chassis_closed { + println!(" Chassis Closed: {}", closed); + } + if let Some(board) = &info.power_button_board { + print_daughterboard("Power Button Board:", board); + } + if let Some(board) = &info.audio_board { + print_daughterboard("Audio Daughterboard:", board); + } + if let Some(board) = &info.touchpad_board { + print_daughterboard("Touchpad:", board); + } + if let Some(status) = &info.deck_status { + println!(" Deck State: {:?}", status.state); + println!(" Touchpad present: {}", status.touchpad_present); + } + } + Some(PlatformFamily::FrameworkDesktop) | None => { + if let Some(status) = &info.deck_status { + println!(" Deck State: {:?}", status.state); + println!( + " Touchpad present: {} ({})", + status.touchpad_present, status.touchpad_id + ); + } else { + println!(" Unable to tell"); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn format_daughterboards() { + let present = Daughterboard { + board_id: Some(7), + adc_mv: Some(1056), + }; + assert!(present.present()); + assert_eq!(format_daughterboard(&present), "Present (7)"); + + let missing = Daughterboard { + board_id: None, + adc_mv: None, + }; + assert!(!missing.present()); + assert_eq!(format_daughterboard(&missing), "Missing"); + } +} diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index 0c88e080..c33353fd 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -14,7 +14,7 @@ use crate::fw_uefi::shell_get_execution_break_flag; use crate::os_specific; use crate::power; use crate::smbios; -use crate::util::{self, Platform}; +use crate::util; use no_std_compat::time::Duration; @@ -652,128 +652,6 @@ impl CrosEc { Ok(InputDeckStatus::from(status)) } - pub fn print_fw12_inputdeck_status(&self) -> EcResult<()> { - let intrusion = self.get_intrusion_status()?; - let pwrbtn = self.read_board_id_npc_db(Framework12Adc::PowerButtonBoardId as u8)?; - let audio = self.read_board_id_npc_db(Framework12Adc::AudioBoardId as u8)?; - let tp = self.read_board_id_npc_db(Framework12Adc::TouchpadBoardId as u8)?; - - let is_present = |p| if p { "Present" } else { "Missing" }; - - println!("Input Deck"); - println!(" Chassis Closed: {}", !intrusion.currently_open); - println!( - " Power Button Board: {}", - if let Some(pwrbtn) = pwrbtn { - format!("{} ({})", is_present(true), pwrbtn) - } else { - is_present(false).to_string() - } - ); - if let Ok(adc) = self.adc_read(Framework12Adc::PowerButtonBoardId as u8) { - println!(" ADC Value {:04}mV", adc); - } - println!( - " Audio Daughterboard: {}", - if let Some(audio) = audio { - format!("{} ({})", is_present(true), audio) - } else { - is_present(false).to_string() - } - ); - if let Ok(adc) = self.adc_read(Framework12Adc::AudioBoardId as u8) { - println!(" ADC Value {:04}mV", adc); - } - println!( - " Touchpad: {}", - if let Some(tp) = tp { - format!("{} ({})", is_present(true), tp) - } else { - is_present(false).to_string() - } - ); - if let Ok(adc) = self.adc_read(Framework12Adc::TouchpadBoardId as u8) { - println!(" ADC Value {:04}mV", adc); - } - - if let Ok(status) = self.get_input_deck_status() { - println!(" Deck State: {:?}", status.state); - println!(" Touchpad present: {}", status.touchpad_present); - } - - Ok(()) - } - - pub fn print_fw13_inputdeck_status(&self) -> EcResult<()> { - let intrusion = self.get_intrusion_status()?; - - let (audio, tp) = match smbios::get_platform() { - Some(Platform::IntelGen11) - | Some(Platform::IntelGen12) - | Some(Platform::IntelGen13) => ( - self.read_board_id(FrameworkHx20Hx30Adc::AudioBoardId as u8)?, - self.read_board_id(FrameworkHx20Hx30Adc::TouchpadBoardId as u8)?, - ), - - _ => ( - self.read_board_id_npc_db(Framework13Adc::AudioBoardId as u8)?, - self.read_board_id_npc_db(Framework13Adc::TouchpadBoardId as u8)?, - ), - }; - - let is_present = |p| if p { "Present" } else { "Missing" }; - - println!("Input Deck"); - println!(" Chassis Closed: {}", !intrusion.currently_open); - - println!( - " Audio Daughterboard: {}", - if let Some(audio) = audio { - format!("{} ({})", is_present(true), audio) - } else { - is_present(false).to_string() - } - ); - if let Ok(adc) = self.adc_read(Framework13Adc::AudioBoardId as u8) { - println!(" ADC Value {:04}mV", adc); - } - println!( - " Touchpad: {}", - if let Some(tp) = tp { - format!("{} ({})", is_present(true), tp) - } else { - is_present(false).to_string() - } - ); - if let Ok(adc) = self.adc_read(Framework13Adc::TouchpadBoardId as u8) { - println!(" ADC Value {:04}mV", adc); - } - - if let Ok(status) = self.get_input_deck_status() { - println!(" Deck State: {:?}", status.state); - println!(" Touchpad present: {}", status.touchpad_present); - } - - Ok(()) - } - - pub fn print_fw16_inputdeck_status(&self) -> EcResult<()> { - let intrusion = self.get_intrusion_status()?; - let status = self.get_input_deck_status()?; - let sleep_l = self.get_gpio("sleep_l")?; - println!("Chassis Closed: {}", !intrusion.currently_open); - println!("Input Deck State: {:?}", status.state); - println!("Touchpad present: {}", status.touchpad_present); - println!("SLEEP# GPIO high: {}", sleep_l); - println!("Positions:"); - println!(" Pos 0: {:?}", status.top_row.pos0); - println!(" Pos 1: {:?}", status.top_row.pos1); - println!(" Pos 2: {:?}", status.top_row.pos2); - println!(" Pos 3: {:?}", status.top_row.pos3); - println!(" Pos 4: {:?}", status.top_row.pos4); - Ok(()) - } - pub fn set_input_deck_mode(&self, mode: DeckStateMode) -> EcResult { let status = EcRequestDeckState { mode }.send_command(self)?; diff --git a/framework_lib/src/commandline/mod.rs b/framework_lib/src/commandline/mod.rs index 82523ecd..77c7a6aa 100644 --- a/framework_lib/src/commandline/mod.rs +++ b/framework_lib/src/commandline/mod.rs @@ -1435,30 +1435,9 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { println!(" Unable to tell"); } } else if args.inputdeck { - let res = match smbios::get_platform().and_then(Platform::which_family) { - Some(PlatformFamily::Framework12) => ec.print_fw12_inputdeck_status(), - Some(PlatformFamily::Framework13) => ec.print_fw13_inputdeck_status(), - Some(PlatformFamily::Framework16) => ec.print_fw16_inputdeck_status(), - // If we don't know which platform it is, we can use some heuristics - _ => { - // Only Framework Laptop 16 has this GPIO - if ec.get_gpio("sleep_l").is_ok() { - ec.print_fw16_inputdeck_status() - } else { - if let Ok(status) = ec.get_input_deck_status() { - println!(" Deck State: {:?}", status.state); - println!( - " Touchpad present: {} ({})", - status.touchpad_present, status.touchpad_id - ); - } else { - println!(" Unable to tell"); - } - Ok(()) - } - } - }; - print_err(res); + if let Some(info) = print_err(ec.get_inputdeck_status()) { + chromium_ec::input_deck::print_inputdeck_status(&info); + } } else if let Some(mode) = &args.inputdeck_mode { if *mode == InputDeckModeArg::Reset { println!("Resetting input deck (off => auto)"); diff --git a/framework_lib/src/util.rs b/framework_lib/src/util.rs index f102d5ca..40429434 100644 --- a/framework_lib/src/util.rs +++ b/framework_lib/src/util.rs @@ -50,7 +50,7 @@ pub enum Platform { UnknownSystem, } -#[derive(Debug, PartialEq, Clone, Copy)] +#[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum PlatformFamily { Framework12, Framework13, From 27ebd888d6714002ee5ad0ba5ae820fd9ca4bccc Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sat, 19 Sep 2026 12:51:32 +0200 Subject: [PATCH 10/26] --expansion-bay: Return data instead of only printing it --- framework_lib/src/chromium_ec/commands.rs | 8 +- framework_lib/src/chromium_ec/mod.rs | 96 +++++++++++++++-------- framework_lib/src/commandline/mod.rs | 5 +- 3 files changed, 72 insertions(+), 37 deletions(-) diff --git a/framework_lib/src/chromium_ec/commands.rs b/framework_lib/src/chromium_ec/commands.rs index 39d4fae6..9887815a 100644 --- a/framework_lib/src/chromium_ec/commands.rs +++ b/framework_lib/src/chromium_ec/commands.rs @@ -1590,14 +1590,14 @@ pub enum ExpansionByStates { ModuleFault = 0x02, HatchSwitchClosed = 0x04, } -#[derive(Debug)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ExpansionBayBoard { DualInterposer, SingleInterposer, UmaFans, } -#[derive(Debug)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ExpansionBayIssue { NoModule, BadConnection(u8, u8), @@ -1869,7 +1869,7 @@ impl EcRequest for EcRequestGetGpuSerial { pub struct EcRequestGetGpuPcie {} #[repr(u8)] -#[derive(Debug, FromPrimitive)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive)] pub enum GpuPcieConfig { /// PCIe 8x1 Pcie8x1 = 0, @@ -1880,7 +1880,7 @@ pub enum GpuPcieConfig { } #[repr(u8)] -#[derive(Debug, FromPrimitive, PartialEq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive)] pub enum GpuVendor { Initializing = 0x00, FanOnly = 0x01, diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index c33353fd..e7b00382 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -1252,39 +1252,22 @@ impl CrosEc { res } - pub fn check_bay_status(&self) -> EcResult<()> { - println!("Expansion Bay"); - + /// Read the state of the expansion bay (Framework 16) + pub fn get_bay_status(&self) -> EcResult { let info = EcRequestExpansionBayStatus {}.send_command(self)?; - println!(" Enabled: {}", info.module_enabled()); - println!(" No fault: {}", !info.module_fault()); - println!(" Door closed: {}", info.hatch_switch_closed()); - match info.expansion_bay_board() { - Ok(board) => println!(" Board: {:?}", board), - Err(err) => println!(" Board: {:?}", err), - } - - if let Ok(sn) = self.get_gpu_serial() { - println!(" Serial Number: {}", sn); - } else { - println!(" Serial Number: Unknown"); - } - + let serial = self.get_gpu_serial().ok(); let res = EcRequestGetGpuPcie {}.send_command(self)?; - let config: Option = FromPrimitive::from_u8(res.gpu_pcie_config); - let vendor: Option = FromPrimitive::from_u8(res.gpu_vendor); - if let Some(config) = config { - println!(" Config: {:?}", config); - } else { - println!(" Config: Unknown ({})", res.gpu_pcie_config); - } - if let Some(vendor) = vendor { - println!(" Vendor: {:?}", vendor); - } else { - println!(" Vendor: Unknown ({})", res.gpu_vendor); - } - - Ok(()) + Ok(ExpansionBayInfo { + enabled: info.module_enabled(), + fault: info.module_fault(), + door_closed: info.hatch_switch_closed(), + board: info.expansion_bay_board(), + serial, + pcie_config: FromPrimitive::from_u8(res.gpu_pcie_config), + raw_pcie_config: res.gpu_pcie_config, + vendor: FromPrimitive::from_u8(res.gpu_vendor), + raw_vendor: res.gpu_vendor, + }) } /// Get the GPU Serial @@ -2109,6 +2092,57 @@ impl SysInfo { } } +/// State of the expansion bay (Framework 16) +/// +/// Use [`CrosEc::get_bay_status`] to read it and [`print_bay_status`] to +/// show it like the commandline tool does. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ExpansionBayInfo { + /// Whether the module in the bay is powered + pub enabled: bool, + /// Whether the EC detected a fault with the module + pub fault: bool, + /// Whether the bay door is closed + pub door_closed: bool, + /// Which board is connected, or why none could be identified + pub board: Result, + /// Serial number of the module, `None` if it has none or can't be read + pub serial: Option, + /// PCIe lane configuration, `None` if unknown to us + pub pcie_config: Option, + pub raw_pcie_config: u8, + /// Kind of module, `None` if unknown to us + pub vendor: Option, + pub raw_vendor: u8, +} + +/// Print the state of the expansion bay like the commandline tool does +pub fn print_bay_status(info: &ExpansionBayInfo) { + println!("Expansion Bay"); + println!(" Enabled: {}", info.enabled); + println!(" No fault: {}", !info.fault); + println!(" Door closed: {}", info.door_closed); + match &info.board { + Ok(board) => println!(" Board: {:?}", board), + Err(err) => println!(" Board: {:?}", err), + } + if let Some(serial) = &info.serial { + println!(" Serial Number: {}", serial); + } else { + println!(" Serial Number: Unknown"); + } + if let Some(config) = info.pcie_config { + println!(" Config: {:?}", config); + } else { + println!(" Config: Unknown ({})", info.raw_pcie_config); + } + if let Some(vendor) = info.vendor { + println!(" Vendor: {:?}", vendor); + } else { + println!(" Vendor: Unknown ({})", info.raw_vendor); + } +} + /// Features supported by the EC firmware, as reported by EC_CMD_GET_FEATURES /// /// Use [`CrosEc::get_features`] to read it and [`print_features`] to show it diff --git a/framework_lib/src/commandline/mod.rs b/framework_lib/src/commandline/mod.rs index 77c7a6aa..696ab56e 100644 --- a/framework_lib/src/commandline/mod.rs +++ b/framework_lib/src/commandline/mod.rs @@ -1450,8 +1450,9 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { ec.set_input_deck_mode((*mode).into()).unwrap(); } } else if args.expansion_bay { - if let Err(err) = ec.check_bay_status() { - error!("{:?}", err); + match ec.get_bay_status() { + Ok(info) => chromium_ec::print_bay_status(&info), + Err(err) => error!("{:?}", err), } if let Ok(header) = ec.read_gpu_desc_header() { println!(" Expansion Bay EEPROM"); From defb52b05270d3422bd945f8a8abb415cdc08994 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sat, 19 Sep 2026 12:51:37 +0200 Subject: [PATCH 11/26] --ec-hib-delay: Don't print in the getter --- framework_lib/src/chromium_ec/mod.rs | 2 +- framework_lib/src/commandline/mod.rs | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index e7b00382..4ae819fc 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -1571,11 +1571,11 @@ impl CrosEc { Ok(()) } + /// Read after how many seconds in G3 the EC hibernates pub fn get_ec_hib_delay(&self) -> EcResult { let res = EcRequesetHibernationDelay { seconds: 0 }.send_command(self)?; debug!("Time in G3: {:?}", { res.time_g3 }); debug!("Time remaining: {:?}", { res.time_remaining }); - println!("EC Hibernation Delay: {:?}s", { res.hibernation_delay }); Ok(res.hibernation_delay) } diff --git a/framework_lib/src/commandline/mod.rs b/framework_lib/src/commandline/mod.rs index 696ab56e..3678b93b 100644 --- a/framework_lib/src/commandline/mod.rs +++ b/framework_lib/src/commandline/mod.rs @@ -1601,7 +1601,9 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { if let Some(delay) = delay { print_err(ec.set_ec_hib_delay(*delay)); } - print_err(ec.get_ec_hib_delay()); + if let Some(delay) = print_err(ec.get_ec_hib_delay()) { + println!("EC Hibernation Delay: {:?}s", delay); + } } else if args.sysinfo { if let Some(info) = print_err(ec.get_sysinfo()) { chromium_ec::print_sysinfo(&info); From dba85105073fdfadf8147465570f587836acce5a Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sat, 19 Sep 2026 12:51:41 +0200 Subject: [PATCH 12/26] --pd-info: Print firmware versions from get_fw_versions --- framework_lib/src/ccgx/device.rs | 27 ++++++--------------------- 1 file changed, 6 insertions(+), 21 deletions(-) diff --git a/framework_lib/src/ccgx/device.rs b/framework_lib/src/ccgx/device.rs index 2771ecfa..5bf2a507 100644 --- a/framework_lib/src/ccgx/device.rs +++ b/framework_lib/src/ccgx/device.rs @@ -348,42 +348,27 @@ impl PdController { }) } + /// Print the versions of all firmware images like the commandline tool does pub fn print_fw_info(&self) { - let data = self.ccgx_read(ControlRegisters::BootLoaderVersion, 8); - let data = match data { - Ok(data) => data, + let versions = match self.get_fw_versions() { + Ok(versions) => versions, Err(err) => { println!("Failed to get PD Info: {:?}", err); return; } }; - assert_eq!(data.len(), 8); - let base_ver = BaseVersion::from(&data[..4]); - let app_ver = AppVersion::from(&data[4..]); println!( " Bootloader Version: Base: {}, App: {}", - base_ver, app_ver + versions.bootloader.base, versions.bootloader.app ); - - let data = self.ccgx_read(ControlRegisters::Firmware1Version, 8); - let data = data.unwrap(); - assert_eq!(data.len(), 8); - let base_ver = BaseVersion::from(&data[..4]); - let app_ver = AppVersion::from(&data[4..]); println!( " FW1 (Backup) Version: Base: {}, App: {}", - base_ver, app_ver + versions.backup_fw.base, versions.backup_fw.app ); - - let data = self.ccgx_read(ControlRegisters::Firmware2Version, 8); - let data = data.unwrap(); - assert_eq!(data.len(), 8); - let base_ver = BaseVersion::from(&data[..4]); - let app_ver = AppVersion::from(&data[4..]); println!( " FW2 (Main) Version: Base: {}, App: {}", - base_ver, app_ver + versions.main_fw.base, versions.main_fw.app ); } From 0c8ce9c3a00f6b930790bb28a920ae27f5010bf8 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sat, 19 Sep 2026 12:53:32 +0200 Subject: [PATCH 13/26] --panicinfo: Return data instead of only printing it --- framework_lib/src/chromium_ec/panic.rs | 364 ++++++++++++++++++------- 1 file changed, 270 insertions(+), 94 deletions(-) diff --git a/framework_lib/src/chromium_ec/panic.rs b/framework_lib/src/chromium_ec/panic.rs index 48afacb6..22f43451 100644 --- a/framework_lib/src/chromium_ec/panic.rs +++ b/framework_lib/src/chromium_ec/panic.rs @@ -108,36 +108,70 @@ fn print_reg(regnum: usize, value: Option) { } } -/// Print a textual representation of the fault registers -fn print_fault(cfsr: u32, hfsr: u32, dfsr: u32) { - let mut names = CFSR_NAME - .iter() - .filter(|(bit, _)| cfsr & (1 << bit) != 0) - .map(|(_, name)| *name) - .collect::>(); - if hfsr & CPU_NVIC_HFSR_DEBUGEVT != 0 { - names.push("Debug event"); - } - if hfsr & CPU_NVIC_HFSR_FORCED != 0 { - names.push("Forced hard fault"); +/// Decoded registers of a Cortex-M EC panic +/// +/// Port of the register handling in panic_data_print() in the EC's +/// core/cortex-m/panic.c, with handling for the older struct version 1 +/// (missing MSP, LR at another position) like the EC's util/ec_panicinfo.c. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CortexMPanic { + /// Exception number (IPSR) + pub exception: u32, + /// Whether the exception happened in handler mode, otherwise process mode + pub handler_mode: bool, + /// r0-r12, sp, lr, pc. Registers from the exception stack frame + /// (r0-r3, r12, lr, pc) are `None` if the frame is not valid. + pub regs: [Option; 16], + /// xPSR from the exception stack frame, `None` if the frame is not valid + pub xpsr: Option, + pub cfsr: u32, + pub bfar: u32, + pub mfar: u32, + pub shcsr: u32, + pub hfsr: u32, + pub dfsr: u32, +} + +impl CortexMPanic { + /// Textual representation of the set bits in the fault registers + pub fn fault_names(&self) -> Vec<&'static str> { + let mut names = CFSR_NAME + .iter() + .filter(|(bit, _)| self.cfsr & (1 << bit) != 0) + .map(|(_, name)| *name) + .collect::>(); + if self.hfsr & CPU_NVIC_HFSR_DEBUGEVT != 0 { + names.push("Debug event"); + } + if self.hfsr & CPU_NVIC_HFSR_FORCED != 0 { + names.push("Forced hard fault"); + } + if self.hfsr & CPU_NVIC_HFSR_VECTTBL != 0 { + names.push("Vector table bus fault"); + } + for (bit, name) in DFSR_NAME.iter().enumerate() { + if self.dfsr & (1 << bit) != 0 { + names.push(name); + } + } + names } - if hfsr & CPU_NVIC_HFSR_VECTTBL != 0 { - names.push("Vector table bus fault"); + + /// Whether the bus fault address register holds a valid address + pub fn bfar_valid(&self) -> bool { + self.cfsr & CPU_NVIC_CFSR_BFARVALID != 0 } - for (bit, name) in DFSR_NAME.iter().enumerate() { - if dfsr & (1 << bit) != 0 { - names.push(name); - } + + /// Whether the memory management fault address register holds a valid address + pub fn mfar_valid(&self) -> bool { + self.cfsr & CPU_NVIC_CFSR_MFARVALID != 0 } - print!("{}", names.join(", ")); } -/// Print panic data of a Cortex-M EC +/// Parse panic data of a Cortex-M EC /// -/// Port of panic_data_print() in the EC's core/cortex-m/panic.c, with -/// handling for the older struct version 1 (missing MSP, LR at another -/// position) like the EC's util/ec_panicinfo.c. -fn print_panic_info_cm(data: &[u8], struct_version: u8, flags: u8) -> Option<()> { +/// Returns `None` if the data is too short to hold all registers. +fn parse_panic_info_cm(data: &[u8], struct_version: u8, flags: u8) -> Option { // Register offsets into the data blob. Registers not saved on the // exception stack frame come first (lregs), the stack frame follows // (sregs). See struct cortex_panic_data(_v1) in the EC. @@ -162,122 +196,210 @@ fn print_panic_info_cm(data: &[u8], struct_version: u8, flags: u8) -> Option<()> let sreg = |i: usize| frame_valid.then(|| u32_at(data, frame_offset + 4 * i)); let exc_lr = lreg(exc_lr_idx); + // v1 does not save the MSP, fall back to the PSP + let sp = if struct_version != 1 && is_frame_in_handler_stack(exc_lr) { + lreg(2) // msp + } else { + lreg(0) // psp + }; + + let mut regs = [None; 16]; + for (i, reg) in regs.iter_mut().enumerate().take(4) { + *reg = sreg(i); + } + for (i, reg) in regs.iter_mut().enumerate().take(10).skip(4) { + *reg = Some(lreg(i - 1)); + } + regs[10] = Some(lreg(9)); + regs[11] = Some(lreg(10)); + regs[12] = sreg(4); + regs[13] = Some(sp); + regs[14] = sreg(5); + regs[15] = sreg(6); + + Some(CortexMPanic { + exception: lreg(1) & 0xff, + handler_mode: is_exception_from_handler_mode(exc_lr), + regs, + xpsr: sreg(7), + cfsr: u32_at(data, fault_offset), + bfar: u32_at(data, fault_offset + 4), + mfar: u32_at(data, fault_offset + 8), + shcsr: u32_at(data, fault_offset + 12), + hfsr: u32_at(data, fault_offset + 16), + dfsr: u32_at(data, fault_offset + 20), + }) +} + +/// Print panic data of a Cortex-M EC like the EC's console does +fn print_panic_info_cm(panic: &CortexMPanic) { println!( "=== {} EXCEPTION: {:02x} ====== xPSR: {:08x} ===", - if is_exception_from_handler_mode(exc_lr) { + if panic.handler_mode { "HANDLER" } else { "PROCESS" }, - lreg(1) & 0xff, - sreg(7).unwrap_or(0xffffffff), + panic.exception, + panic.xpsr.unwrap_or(0xffffffff), ); - for i in 0..4 { - print_reg(i, sreg(i)); - } - for i in 4..10 { - print_reg(i, Some(lreg(i - 1))); + for (i, reg) in panic.regs.iter().enumerate() { + print_reg(i, *reg); } - print_reg(10, Some(lreg(9))); - print_reg(11, Some(lreg(10))); - print_reg(12, sreg(4)); - // v1 does not save the MSP, fall back to the PSP - let sp = if struct_version != 1 && is_frame_in_handler_stack(exc_lr) { - lreg(2) // msp - } else { - lreg(0) // psp - }; - print_reg(13, Some(sp)); - print_reg(14, sreg(5)); - print_reg(15, sreg(6)); - - let cfsr = u32_at(data, fault_offset); - let bfar = u32_at(data, fault_offset + 4); - let mfar = u32_at(data, fault_offset + 8); - let shcsr = u32_at(data, fault_offset + 12); - let hfsr = u32_at(data, fault_offset + 16); - let dfsr = u32_at(data, fault_offset + 20); - - print_fault(cfsr, hfsr, dfsr); - if cfsr & CPU_NVIC_CFSR_BFARVALID != 0 { - print!(", bfar = {:x}", bfar); + + print!("{}", panic.fault_names().join(", ")); + if panic.bfar_valid() { + print!(", bfar = {:x}", panic.bfar); } - if cfsr & CPU_NVIC_CFSR_MFARVALID != 0 { - print!(", mfar = {:x}", mfar); + if panic.mfar_valid() { + print!(", mfar = {:x}", panic.mfar); } println!(); println!( "cfsr = {:x}, shcsr = {:x}, hfsr = {:x}, dfsr = {:x}", - cfsr, shcsr, hfsr, dfsr + panic.cfsr, panic.shcsr, panic.hfsr, panic.dfsr ); +} - Some(()) +/// Decoded EC panic data (struct panic_data) +/// +/// Use [`parse_panic_info`] to decode it and [`print_panic_info`] to show it +/// like the commandline tool does. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PanicInfo { + /// Architecture of the EC, see [`PanicInfo::cortex_m`] + pub arch: u8, + pub struct_version: u8, + /// Raw flags, see [`PanicInfo::flag_names`] + pub flags: u8, + /// Size of the struct as recorded by the EC + pub struct_size: u32, + /// Should be [`PANIC_DATA_MAGIC`] + pub magic: u32, + /// Length of the data we actually received + pub data_len: usize, + /// Decoded registers, `None` if the architecture is unknown or the + /// data is too short + pub cortex_m: Option, } -/// Parse and print panic data as returned by EC_CMD_GET_PANIC_INFO +impl PanicInfo { + pub fn magic_valid(&self) -> bool { + self.magic == PANIC_DATA_MAGIC + } + + /// Whether the recorded struct size matches the data we received + pub fn size_consistent(&self) -> bool { + self.struct_size as usize == self.data_len + } + + pub fn version_known(&self) -> bool { + self.struct_version <= 2 + } + + /// Whether this panic was already reported via host command before + pub fn already_reported(&self) -> bool { + self.flags & PANIC_DATA_FLAG_OLD_HOSTCMD != 0 + } + + /// Whether the EC is a Cortex-M, the only architecture we can decode + pub fn is_cortex_m(&self) -> bool { + self.arch == PANIC_ARCH_CORTEX_M + } + + /// Names of the set flags + pub fn flag_names(&self) -> Vec<&'static str> { + FLAG_NAMES + .iter() + .filter(|(bit, _)| self.flags & bit != 0) + .map(|(_, name)| *name) + .collect() + } +} + +/// Parse panic data as returned by EC_CMD_GET_PANIC_INFO /// -/// The data must not be empty. Prints warnings if the data looks -/// implausible and falls back to a hex dump if it cannot be decoded. -pub fn print_panic_info(data: &[u8]) { +/// Returns `None` if the data is too short to hold the header and trailer. +/// Implausible data is not rejected, check the `PanicInfo` methods. +pub fn parse_panic_info(data: &[u8]) -> Option { // arch, struct_version, flags, reserved const HEADER_SIZE: usize = 4; // struct_size, magic - at the very end of the struct const TRAILER_SIZE: usize = 8; if data.len() < HEADER_SIZE + TRAILER_SIZE { - println!("Panic data too short ({} bytes), hex dump:", data.len()); - util::print_multiline_buffer(data, 0); - return; + return None; } let arch = data[0]; let struct_version = data[1]; let flags = data[2]; - let struct_size = u32_at(data, data.len() - 8); - let magic = u32_at(data, data.len() - 4); + let cortex_m = if arch == PANIC_ARCH_CORTEX_M { + parse_panic_info_cm(data, struct_version, flags) + } else { + None + }; + + Some(PanicInfo { + arch, + struct_version, + flags, + struct_size: u32_at(data, data.len() - 8), + magic: u32_at(data, data.len() - 4), + data_len: data.len(), + cortex_m, + }) +} - if magic != PANIC_DATA_MAGIC { +/// Parse and print panic data as returned by EC_CMD_GET_PANIC_INFO +/// +/// The data must not be empty. Prints warnings if the data looks +/// implausible and falls back to a hex dump if it cannot be decoded. +pub fn print_panic_info(data: &[u8]) { + let Some(info) = parse_panic_info(data) else { + println!("Panic data too short ({} bytes), hex dump:", data.len()); + util::print_multiline_buffer(data, 0); + return; + }; + + if !info.magic_valid() { println!( "WARNING: Incorrect panic magic ({:#010x}), following data may be incorrect!", - magic + info.magic ); } - if struct_size as usize != data.len() { + if !info.size_consistent() { println!( "WARNING: Panic struct size inconsistent ({} vs {}), following data may be incorrect!", - struct_size, - data.len() + info.struct_size, info.data_len ); } - if struct_version > 2 { + if !info.version_known() { println!( "WARNING: Unknown panic data version ({}), following data may be incorrect!", - struct_version + info.struct_version ); } println!( "Saved panic data:{}", - if flags & PANIC_DATA_FLAG_OLD_HOSTCMD != 0 { + if info.already_reported() { "" } else { " (NEW)" } ); - let flag_names = FLAG_NAMES - .iter() - .filter(|(bit, _)| flags & bit != 0) - .map(|(_, name)| *name) - .collect::>(); - println!("Flags: {:#04x} ({})", flags, flag_names.join(" | ")); - - let decoded = match arch { - PANIC_ARCH_CORTEX_M => print_panic_info_cm(data, struct_version, flags), - _ => { - println!("Unknown architecture ({})", arch); - None - } - }; - if decoded.is_none() { + println!( + "Flags: {:#04x} ({})", + info.flags, + info.flag_names().join(" | ") + ); + + if !info.is_cortex_m() { + println!("Unknown architecture ({})", info.arch); + } + if let Some(cortex_m) = &info.cortex_m { + print_panic_info_cm(cortex_m); + } else { println!("Cannot decode panic data, hex dump:"); util::print_multiline_buffer(data, 0); } @@ -294,8 +416,20 @@ mod tests { data[0] = PANIC_ARCH_CORTEX_M; data[1] = 2; // struct_version data[2] = PANIC_DATA_FLAG_FRAME_VALID; + // psp (lregs[0]) + data[4..8].copy_from_slice(&0x2000_1000u32.to_le_bytes()); + // ipsr (lregs[1]): exception 3 (hard fault) + data[8..12].copy_from_slice(&3u32.to_le_bytes()); // exc_lr (lregs[11]): exception from process mode, PSP used data[4 + 4 * 11..4 + 4 * 12].copy_from_slice(&0xfffffffdu32.to_le_bytes()); + // pc (sregs[6]) + let frame_offset = 4 + 4 * 12; + data[frame_offset + 4 * 6..frame_offset + 4 * 7] + .copy_from_slice(&0x0800_1234u32.to_le_bytes()); + // hfsr: forced hard fault + let fault_offset = frame_offset + 4 * 8; + data[fault_offset + 16..fault_offset + 20] + .copy_from_slice(&CPU_NVIC_HFSR_FORCED.to_le_bytes()); let len = data.len(); data[len - 8..len - 4].copy_from_slice(&116u32.to_le_bytes()); data[len - 4..].copy_from_slice(&PANIC_DATA_MAGIC.to_le_bytes()); @@ -305,12 +439,50 @@ mod tests { #[test] fn decode_cm_v2() { let data = cm_v2_blob(); - assert!(print_panic_info_cm(&data, data[1], data[2]).is_some()); - // Must not panic, falls back to hex dump on unknown arch + let info = parse_panic_info(&data).unwrap(); + assert!(info.magic_valid()); + assert!(info.size_consistent()); + assert!(info.version_known()); + assert!(!info.already_reported()); + assert!(info.is_cortex_m()); + assert_eq!(info.flag_names(), vec!["FRAME_VALID"]); + + let cm = info.cortex_m.as_ref().unwrap(); + assert_eq!(cm.exception, 3); + assert!(!cm.handler_mode); + assert_eq!(cm.regs[13], Some(0x2000_1000)); // sp = psp + assert_eq!(cm.regs[15], Some(0x0800_1234)); // pc + assert_eq!(cm.xpsr, Some(0)); + assert_eq!(cm.fault_names(), vec!["Forced hard fault"]); + assert!(!cm.bfar_valid()); + + // Must not panic print_panic_info(&data); + } + + #[test] + fn invalid_frame_has_no_stack_registers() { + let mut data = cm_v2_blob(); + data[2] = 0; // no FRAME_VALID + let info = parse_panic_info(&data).unwrap(); + let cm = info.cortex_m.as_ref().unwrap(); + assert_eq!(cm.regs[0], None); + assert_eq!(cm.regs[4], Some(0)); // r4 comes from lregs, always valid + assert_eq!(cm.regs[15], None); + assert_eq!(cm.xpsr, None); + } + + #[test] + fn unknown_arch_and_short_data() { let mut unknown_arch = cm_v2_blob(); unknown_arch[0] = 42; + let info = parse_panic_info(&unknown_arch).unwrap(); + assert!(!info.is_cortex_m()); + assert!(info.cortex_m.is_none()); + // Must not panic, falls back to hex dump print_panic_info(&unknown_arch); + + assert!(parse_panic_info(&[1, 2, 3]).is_none()); print_panic_info(&[1, 2, 3]); } @@ -319,6 +491,10 @@ mod tests { // Valid header/trailer but not enough space for Cortex-M registers let mut data = cm_v2_blob(); data.truncate(50); - assert!(print_panic_info_cm(&data, 2, 0).is_none()); + assert!(parse_panic_info_cm(&data, 2, 0).is_none()); + let info = parse_panic_info(&data).unwrap(); + assert!(info.is_cortex_m()); + assert!(info.cortex_m.is_none()); + print_panic_info(&data); } } From 3ebf4f46da8b3a133190ce2d27a573e11b3d6589 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sat, 19 Sep 2026 15:52:43 +0200 Subject: [PATCH 14/26] framework_lib: Add optional serde Serialize derives Add a `serde` feature (on by default, off for UEFI) that derives Serialize for the data types the getters return: power, battery, PD ports, thermal, sensors, switches, sysinfo, uptime, features, input deck, expansion bay and panic info. Types with decode helpers (SysInfo, UptimeInfo, EcFeatures, CypdPortInfo, PanicInfo, CortexMPanic) implement Serialize by hand so the output carries both the raw values and the decoded names. Durations serialize as whole milliseconds. Also add PowerStatus and get_power_status, which bundle battery cutoff, charger and battery state the way --power shows them. --- Cargo.lock | 37 ++++++++++ framework_lib/Cargo.toml | 6 +- framework_lib/src/chromium_ec/commands.rs | 11 +++ framework_lib/src/chromium_ec/input_deck.rs | 8 +++ framework_lib/src/chromium_ec/mod.rs | 76 +++++++++++++++++++++ framework_lib/src/chromium_ec/panic.rs | 58 ++++++++++++++++ framework_lib/src/power.rs | 76 +++++++++++++++++++++ framework_lib/src/util.rs | 3 + 8 files changed, 274 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 776a6be1..3060e6f0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -451,6 +451,8 @@ dependencies = [ "rand", "regex", "rusb", + "serde", + "serde_json", "sha1", "sha2", "smartmon", @@ -621,6 +623,12 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + [[package]] name = "jiff" version = "0.2.37" @@ -1051,6 +1059,16 @@ version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + [[package]] name = "serde_core" version = "1.0.229" @@ -1071,6 +1089,19 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + [[package]] name = "serde_spanned" version = "1.1.1" @@ -1706,3 +1737,9 @@ dependencies = [ "quote", "syn 2.0.119", ] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/framework_lib/Cargo.toml b/framework_lib/Cargo.toml index 83b730ff..ffb33a05 100644 --- a/framework_lib/Cargo.toml +++ b/framework_lib/Cargo.toml @@ -13,7 +13,7 @@ rust-version = "1.89" build = "build.rs" [features] -default = ["hidapi", "rusb"] +default = ["hidapi", "rusb", "serde"] readonly = [ ] rusb = ["dep:rusb"] hidapi = ["dep:hidapi"] @@ -21,6 +21,8 @@ uefi = [ "lazy_static/spin_no_std" ] nvidia = ["dep:nvml-wrapper"] # Needs libsmartmon (GPL-2.0-or-later), see README smartmontools = ["dep:smartmon"] +# Serialize the data structures, e.g. for JSON output. Not available in UEFI +serde = ["dep:serde", "dep:serde_json"] [build-dependencies] built = { version = "0.8", features = ["chrono", "git2"] } @@ -42,6 +44,8 @@ rusb = { version = "0.9.4", optional = true } guid-create = { version = "0.5.0", default-features = false } zerocopy = { version = "0.8", default-features = false, features = ["derive"] } smartmon = { version = "0.1", optional = true } +serde = { version = "1", features = ["derive"], optional = true } +serde_json = { version = "1", optional = true } [target.'cfg(target_os = "uefi")'.dependencies] uefi = { version = "0.41", features = ["alloc", "global_allocator", "panic_handler", "logger"] } diff --git a/framework_lib/src/chromium_ec/commands.rs b/framework_lib/src/chromium_ec/commands.rs index 9887815a..b6610360 100644 --- a/framework_lib/src/chromium_ec/commands.rs +++ b/framework_lib/src/chromium_ec/commands.rs @@ -1,6 +1,8 @@ use core::fmt; use num_derive::FromPrimitive; +#[cfg(feature = "serde")] +use serde::Serialize; use super::{command::*, input_deck::INPUT_DECK_SLOTS}; #[cfg(feature = "uefi")] @@ -203,6 +205,7 @@ pub struct EcRequestSysinfo {} /// Bits of EcResponseSysinfo flags (enum sysinfo_flags) #[repr(usize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum SysinfoFlag { /// Write protect is asserted, debug features are disabled Locked, @@ -425,6 +428,7 @@ pub enum MotionSenseType { } #[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum MotionSenseLocation { Base = 0, Lid = 1, @@ -887,6 +891,7 @@ impl EcRequest for EcRequestS0ixCounter { /// Supported features #[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum EcFeatureCode { /// This image contains a limited set of features. Another image /// in RW partition may support more features. @@ -1140,6 +1145,7 @@ impl EcRequest for EcRequestUsbPdPowerInfo { #[repr(usize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum EcResetFlag { /// Other known reason Other, @@ -1192,6 +1198,7 @@ pub enum EcResetFlag { #[repr(u16)] #[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum ResetCause { ResetUnknown = 0x0000, /// Custom reason defined by a board.c or baseboard.c file @@ -1591,6 +1598,7 @@ pub enum ExpansionByStates { HatchSwitchClosed = 0x04, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum ExpansionBayBoard { DualInterposer, SingleInterposer, @@ -1598,6 +1606,7 @@ pub enum ExpansionBayBoard { } #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum ExpansionBayIssue { NoModule, BadConnection(u8, u8), @@ -1870,6 +1879,7 @@ pub struct EcRequestGetGpuPcie {} #[repr(u8)] #[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum GpuPcieConfig { /// PCIe 8x1 Pcie8x1 = 0, @@ -1881,6 +1891,7 @@ pub enum GpuPcieConfig { #[repr(u8)] #[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum GpuVendor { Initializing = 0x00, FanOnly = 0x01, diff --git a/framework_lib/src/chromium_ec/input_deck.rs b/framework_lib/src/chromium_ec/input_deck.rs index b65a6cb3..812cad6e 100644 --- a/framework_lib/src/chromium_ec/input_deck.rs +++ b/framework_lib/src/chromium_ec/input_deck.rs @@ -1,5 +1,7 @@ use alloc::format; use alloc::string::{String, ToString}; +#[cfg(feature = "serde")] +use serde::Serialize; use super::commands::EcResponseDeckState; use super::{CrosEc, EcResult, Framework12Adc, Framework13Adc, FrameworkHx20Hx30Adc}; @@ -38,6 +40,7 @@ enum InputDeckMux { #[repr(u8)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum InputModuleType { Short, Reserved1, @@ -106,6 +109,7 @@ impl InputModuleType { } #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum InputDeckState { /// Manual workaround during EVT Off, @@ -138,6 +142,7 @@ impl From for InputDeckState { } #[derive(Clone, PartialEq, Eq, Debug)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct InputDeckStatus { pub state: InputDeckState, pub hubboard_present: bool, @@ -210,6 +215,7 @@ impl From for InputDeckStatus { } #[derive(Clone, PartialEq, Eq, Debug)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct TopRowPositions { /// C1 all the way left /// B1 all the way left @@ -230,6 +236,7 @@ pub struct TopRowPositions { /// A daughterboard connected to the input deck #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct Daughterboard { /// Board ID, `None` if the board is not connected pub board_id: Option, @@ -249,6 +256,7 @@ impl Daughterboard { /// [`CrosEc::get_inputdeck_status`] to read it and [`print_inputdeck_status`] /// to show it like the commandline tool does. #[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct InputDeckInfo { /// Platform family the layout was decoded for, `None` if unknown pub family: Option, diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index 4ae819fc..639d9185 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -20,6 +20,8 @@ use no_std_compat::time::Duration; use log::Level; use num_derive::FromPrimitive; +#[cfg(feature = "serde")] +use serde::Serialize; pub mod command; pub mod commands; @@ -2036,6 +2038,7 @@ pub fn print_err(something: EcResult) -> Option { /// /// Use [`CrosEc::get_charge_state`] to read it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct ChargeState { /// Whether the charger reports AC as connected pub ac_present: bool, @@ -2051,12 +2054,64 @@ pub struct ChargeState { /// Which of the two EC images is currently in-use #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum EcCurrentImage { Unknown = 0, RO = 1, RW = 2, } +/// Serialize a duration as whole milliseconds +#[cfg(feature = "serde")] +fn duration_ms( + duration: &Duration, + serializer: S, +) -> Result { + serializer.serialize_u64(duration.as_millis() as u64) +} + +#[cfg(feature = "serde")] +impl Serialize for SysInfo { + fn serialize(&self, serializer: S) -> Result { + use serde::ser::SerializeStruct; + let mut s = serializer.serialize_struct("SysInfo", 5)?; + s.serialize_field("current_image", &self.current_image)?; + s.serialize_field("reset_flags_raw", &self.reset_flags)?; + s.serialize_field("reset_flags", &self.reset_flags())?; + s.serialize_field("flags_raw", &self.flags)?; + s.serialize_field("flags", &self.flags())?; + s.end() + } +} + +#[cfg(feature = "serde")] +impl Serialize for UptimeInfo { + fn serialize(&self, serializer: S) -> Result { + use serde::ser::SerializeStruct; + let mut s = serializer.serialize_struct("UptimeInfo", 5)?; + s.serialize_field( + "time_since_ec_boot_ms", + &(self.time_since_ec_boot.as_millis() as u64), + )?; + s.serialize_field("ap_resets_since_ec_boot", &self.ap_resets_since_ec_boot)?; + s.serialize_field("ec_reset_flags_raw", &self.ec_reset_flags)?; + s.serialize_field("ec_reset_flags", &self.ec_reset_flags())?; + s.serialize_field("recent_ap_resets", &self.recent_ap_resets)?; + s.end() + } +} + +#[cfg(feature = "serde")] +impl Serialize for EcFeatures { + fn serialize(&self, serializer: S) -> Result { + use serde::ser::SerializeStruct; + let mut s = serializer.serialize_struct("EcFeatures", 2)?; + s.serialize_field("flags", &self.flags)?; + s.serialize_field("enabled", &self.enabled())?; + s.end() + } +} + /// Decode a bitmask into the enum variants of the set bits /// /// Bits without a known variant are skipped. @@ -2097,6 +2152,7 @@ impl SysInfo { /// Use [`CrosEc::get_bay_status`] to read it and [`print_bay_status`] to /// show it like the commandline tool does. #[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct ExpansionBayInfo { /// Whether the module in the bay is powered pub enabled: bool, @@ -2198,8 +2254,13 @@ pub fn print_features(features: &EcFeatures) { /// One entry of the EC's log of AP resets #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct ApReset { /// When the reset happened, relative to EC boot + #[cfg_attr( + feature = "serde", + serde(rename = "time_since_ec_boot_ms", serialize_with = "duration_ms") + )] pub time_since_ec_boot: Duration, /// Why the EC reset the AP, `None` if the cause is not known to us pub cause: Option, @@ -2338,6 +2399,21 @@ mod tests { assert!(decode_flags::(0, SysinfoFlag::Count as usize).is_empty()); } + #[cfg(feature = "serde")] + #[test] + fn serialize_sysinfo() { + let info = SysInfo { + current_image: EcCurrentImage::RW, + reset_flags: 0x9, + flags: 0b1100, + }; + let json: serde_json::Value = serde_json::to_value(info).unwrap(); + assert_eq!(json["current_image"], "RW"); + assert_eq!(json["reset_flags_raw"], 9); + assert_eq!(json["reset_flags"][1], "PowerOn"); + assert_eq!(json["flags"][0], "JumpEnabled"); + } + #[test] fn decode_features() { let features = EcFeatures { diff --git a/framework_lib/src/chromium_ec/panic.rs b/framework_lib/src/chromium_ec/panic.rs index 22f43451..ca457bbe 100644 --- a/framework_lib/src/chromium_ec/panic.rs +++ b/framework_lib/src/chromium_ec/panic.rs @@ -5,6 +5,8 @@ use alloc::vec::Vec; use core::convert::TryInto; +#[cfg(feature = "serde")] +use serde::Serialize; use crate::util; @@ -168,6 +170,28 @@ impl CortexMPanic { } } +#[cfg(feature = "serde")] +impl Serialize for CortexMPanic { + fn serialize(&self, serializer: S) -> Result { + use serde::ser::SerializeStruct; + let mut s = serializer.serialize_struct("CortexMPanic", 13)?; + s.serialize_field("exception", &self.exception)?; + s.serialize_field("handler_mode", &self.handler_mode)?; + s.serialize_field("regs", &self.regs)?; + s.serialize_field("xpsr", &self.xpsr)?; + s.serialize_field("cfsr", &self.cfsr)?; + s.serialize_field("bfar", &self.bfar)?; + s.serialize_field("bfar_valid", &self.bfar_valid())?; + s.serialize_field("mfar", &self.mfar)?; + s.serialize_field("mfar_valid", &self.mfar_valid())?; + s.serialize_field("shcsr", &self.shcsr)?; + s.serialize_field("hfsr", &self.hfsr)?; + s.serialize_field("dfsr", &self.dfsr)?; + s.serialize_field("fault_names", &self.fault_names())?; + s.end() + } +} + /// Parse panic data of a Cortex-M EC /// /// Returns `None` if the data is too short to hold all registers. @@ -317,6 +341,28 @@ impl PanicInfo { } } +#[cfg(feature = "serde")] +impl Serialize for PanicInfo { + fn serialize(&self, serializer: S) -> Result { + use serde::ser::SerializeStruct; + let mut s = serializer.serialize_struct("PanicInfo", 13)?; + s.serialize_field("arch", &self.arch)?; + s.serialize_field("is_cortex_m", &self.is_cortex_m())?; + s.serialize_field("struct_version", &self.struct_version)?; + s.serialize_field("version_known", &self.version_known())?; + s.serialize_field("flags", &self.flags)?; + s.serialize_field("flag_names", &self.flag_names())?; + s.serialize_field("already_reported", &self.already_reported())?; + s.serialize_field("struct_size", &self.struct_size)?; + s.serialize_field("data_len", &self.data_len)?; + s.serialize_field("size_consistent", &self.size_consistent())?; + s.serialize_field("magic", &self.magic)?; + s.serialize_field("magic_valid", &self.magic_valid())?; + s.serialize_field("cortex_m", &self.cortex_m)?; + s.end() + } +} + /// Parse panic data as returned by EC_CMD_GET_PANIC_INFO /// /// Returns `None` if the data is too short to hold the header and trailer. @@ -460,6 +506,18 @@ mod tests { print_panic_info(&data); } + #[cfg(feature = "serde")] + #[test] + fn serialize_cm_v2() { + let info = parse_panic_info(&cm_v2_blob()).unwrap(); + let json: serde_json::Value = serde_json::to_value(info).unwrap(); + assert_eq!(json["magic_valid"], true); + assert_eq!(json["flag_names"][0], "FRAME_VALID"); + assert_eq!(json["cortex_m"]["exception"], 3); + assert_eq!(json["cortex_m"]["regs"][13], 0x2000_1000); + assert_eq!(json["cortex_m"]["fault_names"][0], "Forced hard fault"); + } + #[test] fn invalid_frame_has_no_stack_registers() { let mut data = cm_v2_blob(); diff --git a/framework_lib/src/power.rs b/framework_lib/src/power.rs index 5a573c5a..c40c7ff7 100644 --- a/framework_lib/src/power.rs +++ b/framework_lib/src/power.rs @@ -8,6 +8,8 @@ use core::convert::TryInto; use core::fmt; use core::prelude::v1::derive; use log::Level; +#[cfg(feature = "serde")] +use serde::Serialize; use crate::ccgx::{AppVersion, Application, BaseVersion, ControllerVersion, MainPdVersions}; use crate::chromium_ec::command::EcRequestRaw; @@ -84,6 +86,7 @@ const EC_FAN_SPEED_NOT_PRESENT: u16 = 0xFFFF; /// Reading of a single temperature sensor #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum TempSensor { Ok(u8), NotPresent, @@ -113,6 +116,7 @@ impl fmt::Display for TempSensor { } #[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct BatteryInformation { pub present_voltage: u32, pub present_rate: u32, @@ -137,12 +141,14 @@ pub struct BatteryInformation { } #[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct PowerInfo { pub ac_present: bool, pub battery: Option, } #[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct ReducedBatteryInformation { pub cycle_count: u32, pub charge_percentage: u32, // Calculated based on Remaining Capacity / LFCC @@ -155,6 +161,7 @@ pub struct ReducedBatteryInformation { /// Some of them (e.g. present_voltage) will vary with a high frequency, so it's not good to /// compare two PowerInfo structs to see whether the battery status has changed. #[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct ReducedPowerInfo { pub ac_present: bool, pub battery: Option, @@ -177,6 +184,7 @@ impl From for ReducedPowerInfo { } #[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct AccelData { pub x: i16, pub y: i16, @@ -202,6 +210,7 @@ impl fmt::Display for AccelData { } #[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum LidAngle { Angle(u16), Unreliable, @@ -255,6 +264,7 @@ pub fn print_memmap_version_info(ec: &CrosEc) { /// /// All temperatures are in degrees Celsius, `None` means the threshold is disabled. #[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct ThermalThresholds { /// Index of the sensor in the EC memory map pub index: u32, @@ -380,6 +390,7 @@ pub fn set_thermal_thresholds(ec: &CrosEc, sensor: u32, values: &[i32]) -> EcRes /// Use [`get_switches`] to read it and [`print_switches`] to show it like the /// commandline tool does. #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct Switches { /// Raw switch bits as read from the EC memory map pub raw: u8, @@ -483,6 +494,7 @@ pub fn get_accel_data(ec: &CrosEc) -> (AccelData, AccelData, LidAngle) { /// A single accelerometer and its current reading #[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct Accelerometer { /// Where the sensor is mounted pub location: MotionSenseLocation, @@ -491,6 +503,7 @@ pub struct Accelerometer { /// All accelerometer data the EC reports in its memory map #[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct AccelInfo { /// Whether the EC was updating the data while we read it pub busy: bool, @@ -504,6 +517,7 @@ pub struct AccelInfo { /// Use [`get_sensors`] to read it and [`print_sensors`] to show it like the /// commandline tool does. #[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct SensorInfo { /// Ambient light in Lux, `None` if the system has no ambient light sensor pub als: Option, @@ -622,6 +636,7 @@ pub fn print_sensors(ec: &CrosEc) { /// Use [`get_thermal`] to read it and [`print_thermal`] to show it like the /// commandline tool does. #[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct ThermalInfo { /// All temperature sensors that are present pub sensors: Vec, @@ -633,6 +648,7 @@ pub struct ThermalInfo { /// A single temperature sensor and its current reading #[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct TempSensorInfo { /// Index of the sensor in the EC memory map pub index: u8, @@ -644,6 +660,7 @@ pub struct TempSensorInfo { /// A single fan and its current speed #[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct FanInfo { /// Index of the fan in the EC memory map pub index: usize, @@ -655,6 +672,7 @@ pub struct FanInfo { /// Current speed of a single fan #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum FanSpeed { /// Current speed in RPM Rpm(u16), @@ -675,6 +693,7 @@ impl From for FanSpeed { /// Whether the EC is throttling the AP #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct ApThrottleInfo { pub soft: bool, pub hard: bool, @@ -873,6 +892,29 @@ pub fn get_cutoff_status(ec: &CrosEc) -> Option { .map(|res| res.status != 0) } +/// Everything `--power` reports at once +/// +/// Use [`get_power_status`] to read it. +#[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] +pub struct PowerStatus { + /// Whether the battery is cut off (ship mode), `None` if the EC doesn't report it + pub cutoff: Option, + /// Charger state, `None` if the EC doesn't report it + pub charger: Option, + /// AC and battery state, `None` if the memory map couldn't be read + pub power: Option, +} + +/// Read battery cutoff, charger and battery state +pub fn get_power_status(ec: &CrosEc) -> PowerStatus { + PowerStatus { + cutoff: get_cutoff_status(ec), + charger: ec.get_charge_state().ok(), + power: power_info(ec), + } +} + pub fn get_and_print_power_info(ec: &CrosEc) -> i32 { print!("Battery Cutoff: "); match get_cutoff_status(ec) { @@ -1004,6 +1046,7 @@ pub fn check_update_ready(power_info: &PowerInfo) -> bool { } #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum UsbChargingType { None = 0, PD = 1, @@ -1017,6 +1060,7 @@ pub enum UsbChargingType { Unknown = 9, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum UsbPowerRoles { Disconnected = 0, Source = 1, @@ -1026,6 +1070,7 @@ pub enum UsbPowerRoles { /// Voltage and current measurements of a USB-C port, in mV and mA #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct UsbChargeMeasures { pub voltage_max: u16, pub voltage_now: u16, @@ -1038,6 +1083,7 @@ pub struct UsbChargeMeasures { /// Use [`get_pd_info`] to read it and [`print_pd_info`] to show it like the /// commandline tool does. #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct UsbPdPowerInfo { pub role: UsbPowerRoles, pub charging_type: UsbChargingType, @@ -1103,6 +1149,7 @@ pub fn get_pd_info(ec: &CrosEc, ports: u8) -> Vec> { /// Type-C connection state of a PD port #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum CypdTypeCState { Nothing, Sink, @@ -1131,6 +1178,7 @@ impl From for CypdTypeCState { /// PD power role of a port #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum CypdPdPowerRole { Sink, Source, @@ -1149,6 +1197,7 @@ impl From for CypdPdPowerRole { /// PD data role of a port #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum CypdPdDataRole { Ufp, Dfp, @@ -1169,6 +1218,7 @@ impl From for CypdPdDataRole { /// Which CC line the port partner is connected on #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum CcPolarity { Cc1, Cc2, @@ -1271,6 +1321,32 @@ impl CypdPortInfo { } } +#[cfg(feature = "serde")] +impl Serialize for CypdPortInfo { + fn serialize(&self, serializer: S) -> Result { + use serde::ser::SerializeStruct; + let mut s = serializer.serialize_struct("CypdPortInfo", 17)?; + s.serialize_field("port", &self.port)?; + s.serialize_field("connected", &self.connected())?; + s.serialize_field("c_state", &self.c_state)?; + s.serialize_field("pd_contract", &self.pd_contract)?; + s.serialize_field("power_role", &self.power_role)?; + s.serialize_field("data_role", &self.data_role)?; + s.serialize_field("vconn", &self.vconn)?; + s.serialize_field("voltage_mv", &self.voltage)?; + s.serialize_field("current_ma", &self.current)?; + s.serialize_field("power_mw", &self.power_mw())?; + s.serialize_field("cc_polarity", &self.cc_polarity)?; + s.serialize_field("epr_active", &self.epr_active)?; + s.serialize_field("epr_support", &self.epr_support)?; + s.serialize_field("sink_active", &self.sink_active)?; + s.serialize_field("dp_alt_mode_status", &self.dp_alt_mode_status)?; + s.serialize_field("dp_alt_mode_active", &self.dp_alt_mode_active())?; + s.serialize_field("dp_alt_modes", &self.dp_alt_modes())?; + s.end() + } +} + /// Read the state of a single USB-C port from the Cypress PD controller /// /// Returns `Ok(None)` if the port does not exist on this system. diff --git a/framework_lib/src/util.rs b/framework_lib/src/util.rs index 40429434..ef695940 100644 --- a/framework_lib/src/util.rs +++ b/framework_lib/src/util.rs @@ -1,5 +1,7 @@ //! Miscellaneous utility functions to use across modules +#[cfg(feature = "serde")] +use serde::Serialize; use std::prelude::v1::*; #[cfg(feature = "uefi")] @@ -51,6 +53,7 @@ pub enum Platform { } #[derive(Debug, PartialEq, Eq, Clone, Copy)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum PlatformFamily { Framework12, Framework13, From 1363679030bbace5c498a8385a71529c855d2b87 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sat, 19 Sep 2026 15:54:36 +0200 Subject: [PATCH 15/26] --json: Add JSON output for read-only info commands Add a --json flag that prints the result of the information commands as pretty JSON instead of text, so scripts and other programs can consume it without parsing the human readable output. Supported are --power, --thermal, --thermalget, --sensors, --switches, --pdports, --pdports-chromebook, --sysinfo, --uptimeinfo, --features, --inputdeck, --expansion-bay and --panicinfo. Other commands reject the flag with an error. Only JSON goes to stdout, errors go to the log on stderr. Exit codes match the text output. Not available in UEFI, the flag is always off there. --- EXAMPLES.md | 18 +++ README.md | 1 + framework_lib/src/commandline/clap_std.rs | 5 + framework_lib/src/commandline/mod.rs | 134 ++++++++++++++++-- framework_lib/src/commandline/uefi.rs | 1 + .../completions/bash/framework_tool | 2 +- .../completions/fish/framework_tool.fish | 1 + .../completions/zsh/_framework_tool | 1 + framework_tool/framework_tool.1 | 5 +- 9 files changed, 154 insertions(+), 14 deletions(-) diff --git a/EXAMPLES.md b/EXAMPLES.md index e685c95b..b74f4fe3 100644 --- a/EXAMPLES.md +++ b/EXAMPLES.md @@ -137,6 +137,24 @@ Options: Print help ``` +## JSON output + +Read-only information commands can print their result as JSON instead of +text by adding `--json`, for use in scripts or by other programs: + +``` +> sudo framework_tool --thermal --json +> sudo framework_tool --power --json +``` + +Supported: `--power`, `--thermal`, `--thermalget`, `--sensors`, `--switches`, +`--pdports`, `--pdports-chromebook`, `--sysinfo`, `--uptimeinfo`, `--features`, +`--inputdeck`, `--expansion-bay`, `--panicinfo`. + +Only the JSON goes to stdout, errors are logged to stderr. Values that come +from a bitmask are included both raw (`*_raw` or `flags`) and decoded into +names. Other commands reject `--json` with an error. + ## Check firmware versions ### BIOS (Mainboard, UEFI, EC, PD, Retimer) diff --git a/README.md b/README.md index 7cc2de5f..38c83cf6 100644 --- a/README.md +++ b/README.md @@ -126,6 +126,7 @@ On UEFI and FreeBSD raw port I/O is used - on Linux this can also be used as a f ###### Firmware Information - [x] Show system information + - [x] As JSON for scripting (`--json`, not on UEFI) - [x] ESRT table (UEFI, Linux, FreeBSD only) (`--esrt`) - [x] SMBIOS - [x] Get firmware version from binary file diff --git a/framework_lib/src/commandline/clap_std.rs b/framework_lib/src/commandline/clap_std.rs index 615d6bf3..ed5e0dbc 100644 --- a/framework_lib/src/commandline/clap_std.rs +++ b/framework_lib/src/commandline/clap_std.rs @@ -26,6 +26,10 @@ struct ClapCli { #[command(flatten)] verbosity: clap_verbosity_flag::Verbosity, + /// Print the result as JSON instead of text (read-only info commands only) + #[arg(long)] + json: bool, + /// List current firmware versions #[arg(long)] versions: bool, @@ -627,6 +631,7 @@ pub fn parse(args: &[String]) -> Cli { Cli { verbosity: LogLevel(args.verbosity.log_level_filter()), + json: args.json, versions: args.versions, version: args.version, features: args.features, diff --git a/framework_lib/src/commandline/mod.rs b/framework_lib/src/commandline/mod.rs index 3678b93b..1cd37bf0 100644 --- a/framework_lib/src/commandline/mod.rs +++ b/framework_lib/src/commandline/mod.rs @@ -184,6 +184,7 @@ impl Default for LogLevel { #[derive(Debug, Default)] pub struct Cli { pub verbosity: LogLevel, + pub json: bool, pub versions: bool, pub version: bool, pub features: bool, @@ -287,6 +288,7 @@ pub fn parse(args: &[String]) -> Cli { // TODO: Instead of silently ignoring blocked command, we should remind the user Cli { verbosity: cli.verbosity, + json: cli.json, versions: cli.versions, version: cli.version, features: cli.features, @@ -1356,6 +1358,37 @@ fn compare_version(device: Option, version: String, ec: &Cro 1 } +/// Print a value as pretty JSON, for --json +#[cfg(feature = "serde")] +fn print_json(value: &T) { + match serde_json::to_string_pretty(value) { + Ok(json) => println!("{}", json), + Err(err) => error!("Failed to serialize to JSON: {}", err), + } +} + +#[cfg(not(feature = "serde"))] +fn print_json(_value: &T) { + error!("Not built with JSON support"); +} + +/// Whether the command selected by the arguments supports --json +fn supports_json(args: &Cli) -> bool { + args.features + || args.inputdeck + || args.expansion_bay + || args.sysinfo + || args.uptimeinfo + || args.switches + || args.panicinfo + || args.power + || args.thermal + || args.thermalget + || args.sensors + || args.pdports + || args.pdports_chromebook +} + pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { #[cfg(feature = "uefi")] { @@ -1397,6 +1430,11 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { enable_page_break(); } + if args.json && !supports_json(args) { + error!("--json is not supported for this command"); + return 1; + } + if args.help { // Only print with uefi feature here because without clap will already // have printed the help by itself. @@ -1409,7 +1447,11 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { print_tool_version(); } else if args.features { if let Some(features) = print_err(ec.get_features()) { - chromium_ec::print_features(&features); + if args.json { + print_json(&features); + } else { + chromium_ec::print_features(&features); + } } } else if args.esrt { print_esrt(); @@ -1436,7 +1478,11 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { } } else if args.inputdeck { if let Some(info) = print_err(ec.get_inputdeck_status()) { - chromium_ec::input_deck::print_inputdeck_status(&info); + if args.json { + print_json(&info); + } else { + chromium_ec::input_deck::print_inputdeck_status(&info); + } } } else if let Some(mode) = &args.inputdeck_mode { if *mode == InputDeckModeArg::Reset { @@ -1451,10 +1497,13 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { } } else if args.expansion_bay { match ec.get_bay_status() { + Ok(info) if args.json => print_json(&info), Ok(info) => chromium_ec::print_bay_status(&info), Err(err) => error!("{:?}", err), } - if let Ok(header) = ec.read_gpu_desc_header() { + if args.json { + // TODO: The EEPROM header is not part of the JSON output yet + } else if let Ok(header) = ec.read_gpu_desc_header() { println!(" Expansion Bay EEPROM"); println!( " Valid: {:?}", @@ -1606,11 +1655,19 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { } } else if args.sysinfo { if let Some(info) = print_err(ec.get_sysinfo()) { - chromium_ec::print_sysinfo(&info); + if args.json { + print_json(&info); + } else { + chromium_ec::print_sysinfo(&info); + } } } else if args.uptimeinfo { if let Some(info) = print_err(ec.get_uptime_info()) { - chromium_ec::print_uptime_info(&info); + if args.json { + print_json(&info); + } else { + chromium_ec::print_uptime_info(&info); + } } } else if args.s0ix_counter { if let Some(counter) = print_err(ec.get_s0ix_counter()) { @@ -1650,7 +1707,12 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { return 1; } } else if args.switches { - if power::print_switches(&ec).is_none() { + let switches = if args.json { + power::get_switches(&ec).map(|switches| print_json(&switches)) + } else { + power::print_switches(&ec) + }; + if switches.is_none() { println!("Failed to read EC switch state"); return 1; } @@ -1665,7 +1727,10 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { } else if args.panicinfo { match ec.get_panic_info() { Ok(data) => { - if data.is_empty() { + if args.json { + // null if there is no panic data + print_json(&chromium_ec::panic::parse_panic_info(&data)); + } else if data.is_empty() { println!("No panic data."); } else { chromium_ec::panic::print_panic_info(&data); @@ -1691,6 +1756,13 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { } else if args.boardid { print_board_ids(&ec); } else if args.power { + if args.json { + let status = power::get_power_status(&ec); + print_json(&status); + // Same exit code as the text output: 0 only if a battery is present + let has_battery = status.power.is_some_and(|power| power.battery.is_some()); + return if has_battery { 0 } else { 1 }; + } return power::get_and_print_power_info(&ec); } else if let Some(smartbattery_arg) = &args.smartbattery { #[cfg(not(feature = "uefi"))] @@ -1722,9 +1794,20 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { print_err(bat.interactive_authenticate(&ec)); } } else if args.thermal { - power::print_thermal(&ec); + if args.json { + if let Some(info) = print_err(power::get_thermal(&ec)) { + print_json(&info); + } + } else { + power::print_thermal(&ec); + } } else if args.thermalget { - if power::print_thermal_thresholds(&ec).is_none() { + let thresholds = if args.json { + power::get_thermal_thresholds(&ec).map(|thresholds| print_json(&thresholds)) + } else { + power::print_thermal_thresholds(&ec) + }; + if thresholds.is_none() { println!("Failed to read thermal thresholds"); return 1; } @@ -1742,7 +1825,16 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { // Show the resulting configuration let _ = power::print_thermal_thresholds(&ec); } else if args.sensors { - power::print_sensors(&ec); + if args.json { + if let Some(info) = power::get_sensors(&ec) { + print_json(&info); + } else { + println!("Failed to read sensors"); + return 1; + } + } else { + power::print_sensors(&ec); + } } else if let Some((fan, percent)) = args.fansetduty { print_err(ec.fan_set_duty(fan, percent)); } else if let Some((fan, rpm)) = args.fansetrpm { @@ -1752,9 +1844,27 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { } else if let Some(None) = args.autofanctrl { print_err(ec.autofanctrl(None)); } else if args.pdports { - power::print_cypd_pd_info(&ec); + if args.json { + // Ports that failed to respond are left out, the error is logged + let ports: Vec<_> = power::get_cypd_pd_info(&ec) + .into_iter() + .filter_map(print_err) + .collect(); + print_json(&ports); + } else { + power::print_cypd_pd_info(&ec); + } } else if args.pdports_chromebook { - power::print_pd_info(&ec); + if args.json { + // Ports that failed to respond are null, the error is logged + let ports: Vec<_> = power::get_pd_info(&ec, 4) + .into_iter() + .map(print_err) + .collect(); + print_json(&ports); + } else { + power::print_pd_info(&ec); + } } else if args.info { smbios_info(); } else if let Some(dump_path) = &args.meinfo { diff --git a/framework_lib/src/commandline/uefi.rs b/framework_lib/src/commandline/uefi.rs index f6a31232..3cde4406 100644 --- a/framework_lib/src/commandline/uefi.rs +++ b/framework_lib/src/commandline/uefi.rs @@ -32,6 +32,7 @@ pub fn get_args() -> Vec { pub fn parse(args: &[String]) -> Cli { let mut cli = Cli { verbosity: LogLevel(log::LevelFilter::Error), + json: false, paginate: false, versions: false, version: false, diff --git a/framework_tool/completions/bash/framework_tool b/framework_tool/completions/bash/framework_tool index 518b31ab..99dcfff3 100755 --- a/framework_tool/completions/bash/framework_tool +++ b/framework_tool/completions/bash/framework_tool @@ -23,7 +23,7 @@ _framework_tool() { case "${cmd}" in framework_tool) - opts="-v -q -t -f -h --flash-gpu-descriptor --verbose --quiet --versions --version --features --esrt --device --compare-version --power --smartbattery --smartbattery-auth --thermal --thermalget --thermalset --sensors --fansetduty --fansetrpm --autofanctrl --pdports --pdports-chromebook --info --meinfo --pd-info --pd-reset --pd-disable --pd-enable --dp-hdmi-info --dp-hdmi-update --audio-card-info --privacy --pd-bin --ec-bin --capsule --dump --h2o-capsule --dump-ec-flash --flash-full-ec --flash-ec --flash-ro-ec --flash-rw-ec --intrusion --inputdeck --inputdeck-mode --expansion-bay --charge-limit --charge-current-limit --charge-rate-limit --get-gpio --fp-led-level --fp-brightness --kblight --remap-key --rgbkbd --ps2-enable --tablet-mode --touchscreen-enable --haptic-intensity --click-force --stylus-battery --console --reboot-ec --ec-hib-delay --sysinfo --uptimeinfo --s0ix-counter --hello --protoinfo --switches --port80read --panicinfo --hash --driver --pd-addrs --pd-ports --test --test-retimer --boardid --force --dry-run --flash-gpu-descriptor-file --dump-gpu-descriptor-file --validate-gpu-descriptor-file --nvidia --host-command --generate-completions --generate-manpage --help" + opts="-v -q -t -f -h --flash-gpu-descriptor --verbose --quiet --json --versions --version --features --esrt --device --compare-version --power --smartbattery --smartbattery-auth --thermal --thermalget --thermalset --sensors --fansetduty --fansetrpm --autofanctrl --pdports --pdports-chromebook --info --meinfo --pd-info --pd-reset --pd-disable --pd-enable --dp-hdmi-info --dp-hdmi-update --audio-card-info --privacy --pd-bin --ec-bin --capsule --dump --h2o-capsule --dump-ec-flash --flash-full-ec --flash-ec --flash-ro-ec --flash-rw-ec --intrusion --inputdeck --inputdeck-mode --expansion-bay --charge-limit --charge-current-limit --charge-rate-limit --get-gpio --fp-led-level --fp-brightness --kblight --remap-key --rgbkbd --ps2-enable --tablet-mode --touchscreen-enable --haptic-intensity --click-force --stylus-battery --console --reboot-ec --ec-hib-delay --sysinfo --uptimeinfo --s0ix-counter --hello --protoinfo --switches --port80read --panicinfo --hash --driver --pd-addrs --pd-ports --test --test-retimer --boardid --force --dry-run --flash-gpu-descriptor-file --dump-gpu-descriptor-file --validate-gpu-descriptor-file --nvidia --host-command --generate-completions --generate-manpage --help" if [[ ${cur} == -* || ${COMP_CWORD} -eq 1 ]] ; then COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") ) return 0 diff --git a/framework_tool/completions/fish/framework_tool.fish b/framework_tool/completions/fish/framework_tool.fish index b46a6cb0..a7dcde3b 100644 --- a/framework_tool/completions/fish/framework_tool.fish +++ b/framework_tool/completions/fish/framework_tool.fish @@ -85,6 +85,7 @@ powershell\t'' zsh\t''" complete -c framework_tool -s v -l verbose -d 'Increase logging verbosity' complete -c framework_tool -s q -l quiet -d 'Decrease logging verbosity' +complete -c framework_tool -l json -d 'Print the result as JSON instead of text (read-only info commands only)' complete -c framework_tool -l versions -d 'List current firmware versions' complete -c framework_tool -l version -d 'Show tool version information (Add -vv for more details)' complete -c framework_tool -l features -d 'Show features support by the firmware' diff --git a/framework_tool/completions/zsh/_framework_tool b/framework_tool/completions/zsh/_framework_tool index 1495920b..317321d2 100644 --- a/framework_tool/completions/zsh/_framework_tool +++ b/framework_tool/completions/zsh/_framework_tool @@ -69,6 +69,7 @@ _framework_tool() { '*--verbose[Increase logging verbosity]' \ '(-v --verbose)*-q[Decrease logging verbosity]' \ '(-v --verbose)*--quiet[Decrease logging verbosity]' \ +'--json[Print the result as JSON instead of text (read-only info commands only)]' \ '--versions[List current firmware versions]' \ '--version[Show tool version information (Add -vv for more details)]' \ '--features[Show features support by the firmware]' \ diff --git a/framework_tool/framework_tool.1 b/framework_tool/framework_tool.1 index 0a3c8476..ed6fa87e 100644 --- a/framework_tool/framework_tool.1 +++ b/framework_tool/framework_tool.1 @@ -8,7 +8,7 @@ framework_tool \- Swiss army knife for Framework laptops .ie \n(.g .ds Aq \(aq .el .ds Aq ' .SH SYNOPSIS -\fBframework_tool\fR [\fB\-\-flash\-gpu\-descriptor\fR] [\fB\-v\fR|\fB\-\-verbose\fR]... [\fB\-q\fR|\fB\-\-quiet\fR]... [\fB\-\-versions\fR] [\fB\-\-version\fR] [\fB\-\-features\fR] [\fB\-\-esrt\fR] [\fB\-\-device\fR] [\fB\-\-compare\-version\fR] [\fB\-\-power\fR] [\fB\-\-smartbattery\fR] [\fB\-\-smartbattery\-auth\fR] [\fB\-\-thermal\fR] [\fB\-\-thermalget\fR] [\fB\-\-thermalset\fR] [\fB\-\-sensors\fR] [\fB\-\-fansetduty\fR] [\fB\-\-fansetrpm\fR] [\fB\-\-autofanctrl\fR] [\fB\-\-pdports\fR] [\fB\-\-pdports\-chromebook\fR] [\fB\-\-info\fR] [\fB\-\-meinfo\fR] [\fB\-\-pd\-info\fR] [\fB\-\-pd\-reset\fR] [\fB\-\-pd\-disable\fR] [\fB\-\-pd\-enable\fR] [\fB\-\-dp\-hdmi\-info\fR] [\fB\-\-dp\-hdmi\-update\fR] [\fB\-\-audio\-card\-info\fR] [\fB\-\-privacy\fR] [\fB\-\-pd\-bin\fR] [\fB\-\-ec\-bin\fR] [\fB\-\-capsule\fR] [\fB\-\-dump\fR] [\fB\-\-h2o\-capsule\fR] [\fB\-\-dump\-ec\-flash\fR] [\fB\-\-flash\-full\-ec\fR] [\fB\-\-flash\-ec\fR] [\fB\-\-flash\-ro\-ec\fR] [\fB\-\-flash\-rw\-ec\fR] [\fB\-\-intrusion\fR] [\fB\-\-inputdeck\fR] [\fB\-\-inputdeck\-mode\fR] [\fB\-\-expansion\-bay\fR] [\fB\-\-charge\-limit\fR] [\fB\-\-charge\-current\-limit\fR] [\fB\-\-charge\-rate\-limit\fR] [\fB\-\-get\-gpio\fR] [\fB\-\-fp\-led\-level\fR] [\fB\-\-fp\-brightness\fR] [\fB\-\-kblight\fR] [\fB\-\-remap\-key\fR] [\fB\-\-rgbkbd\fR] [\fB\-\-tablet\-mode\fR] [\fB\-\-touchscreen\-enable\fR] [\fB\-\-haptic\-intensity\fR] [\fB\-\-click\-force\fR] [\fB\-\-stylus\-battery\fR] [\fB\-\-console\fR] [\fB\-\-reboot\-ec\fR] [\fB\-\-ec\-hib\-delay\fR] [\fB\-\-sysinfo\fR] [\fB\-\-uptimeinfo\fR] [\fB\-\-s0ix\-counter\fR] [\fB\-\-hello\fR] [\fB\-\-protoinfo\fR] [\fB\-\-switches\fR] [\fB\-\-port80read\fR] [\fB\-\-panicinfo\fR] [\fB\-\-hash\fR] [\fB\-\-driver\fR] [\fB\-\-pd\-addrs\fR] [\fB\-\-pd\-ports\fR] [\fB\-t\fR|\fB\-\-test\fR] [\fB\-\-test\-retimer\fR] [\fB\-\-boardid\fR] [\fB\-f\fR|\fB\-\-force\fR] [\fB\-\-dry\-run\fR] [\fB\-\-flash\-gpu\-descriptor\-file\fR] [\fB\-\-dump\-gpu\-descriptor\-file\fR] [\fB\-\-validate\-gpu\-descriptor\-file\fR] [\fB\-\-nvidia\fR] [\fB\-\-host\-command\fR] [\fB\-h\fR|\fB\-\-help\fR] +\fBframework_tool\fR [\fB\-\-flash\-gpu\-descriptor\fR] [\fB\-v\fR|\fB\-\-verbose\fR]... [\fB\-q\fR|\fB\-\-quiet\fR]... [\fB\-\-json\fR] [\fB\-\-versions\fR] [\fB\-\-version\fR] [\fB\-\-features\fR] [\fB\-\-esrt\fR] [\fB\-\-device\fR] [\fB\-\-compare\-version\fR] [\fB\-\-power\fR] [\fB\-\-smartbattery\fR] [\fB\-\-smartbattery\-auth\fR] [\fB\-\-thermal\fR] [\fB\-\-thermalget\fR] [\fB\-\-thermalset\fR] [\fB\-\-sensors\fR] [\fB\-\-fansetduty\fR] [\fB\-\-fansetrpm\fR] [\fB\-\-autofanctrl\fR] [\fB\-\-pdports\fR] [\fB\-\-pdports\-chromebook\fR] [\fB\-\-info\fR] [\fB\-\-meinfo\fR] [\fB\-\-pd\-info\fR] [\fB\-\-pd\-reset\fR] [\fB\-\-pd\-disable\fR] [\fB\-\-pd\-enable\fR] [\fB\-\-dp\-hdmi\-info\fR] [\fB\-\-dp\-hdmi\-update\fR] [\fB\-\-audio\-card\-info\fR] [\fB\-\-privacy\fR] [\fB\-\-pd\-bin\fR] [\fB\-\-ec\-bin\fR] [\fB\-\-capsule\fR] [\fB\-\-dump\fR] [\fB\-\-h2o\-capsule\fR] [\fB\-\-dump\-ec\-flash\fR] [\fB\-\-flash\-full\-ec\fR] [\fB\-\-flash\-ec\fR] [\fB\-\-flash\-ro\-ec\fR] [\fB\-\-flash\-rw\-ec\fR] [\fB\-\-intrusion\fR] [\fB\-\-inputdeck\fR] [\fB\-\-inputdeck\-mode\fR] [\fB\-\-expansion\-bay\fR] [\fB\-\-charge\-limit\fR] [\fB\-\-charge\-current\-limit\fR] [\fB\-\-charge\-rate\-limit\fR] [\fB\-\-get\-gpio\fR] [\fB\-\-fp\-led\-level\fR] [\fB\-\-fp\-brightness\fR] [\fB\-\-kblight\fR] [\fB\-\-remap\-key\fR] [\fB\-\-rgbkbd\fR] [\fB\-\-tablet\-mode\fR] [\fB\-\-touchscreen\-enable\fR] [\fB\-\-haptic\-intensity\fR] [\fB\-\-click\-force\fR] [\fB\-\-stylus\-battery\fR] [\fB\-\-console\fR] [\fB\-\-reboot\-ec\fR] [\fB\-\-ec\-hib\-delay\fR] [\fB\-\-sysinfo\fR] [\fB\-\-uptimeinfo\fR] [\fB\-\-s0ix\-counter\fR] [\fB\-\-hello\fR] [\fB\-\-protoinfo\fR] [\fB\-\-switches\fR] [\fB\-\-port80read\fR] [\fB\-\-panicinfo\fR] [\fB\-\-hash\fR] [\fB\-\-driver\fR] [\fB\-\-pd\-addrs\fR] [\fB\-\-pd\-ports\fR] [\fB\-t\fR|\fB\-\-test\fR] [\fB\-\-test\-retimer\fR] [\fB\-\-boardid\fR] [\fB\-f\fR|\fB\-\-force\fR] [\fB\-\-dry\-run\fR] [\fB\-\-flash\-gpu\-descriptor\-file\fR] [\fB\-\-dump\-gpu\-descriptor\-file\fR] [\fB\-\-validate\-gpu\-descriptor\-file\fR] [\fB\-\-nvidia\fR] [\fB\-\-host\-command\fR] [\fB\-h\fR|\fB\-\-help\fR] .ie \n(.g .ds Aq \(aq .el .ds Aq ' .SH DESCRIPTION @@ -30,6 +30,9 @@ Increase logging verbosity \fB\-q\fR, \fB\-\-quiet\fR Decrease logging verbosity .TP +\fB\-\-json\fR +Print the result as JSON instead of text (read\-only info commands only) +.TP \fB\-\-versions\fR List current firmware versions .TP From c6979074295f1207299c93b40c7be728bd0713f4 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sun, 20 Sep 2026 17:06:52 +0200 Subject: [PATCH 16/26] smbios: Log failures instead of printing them The SMBIOS helpers printed their failure messages to stdout, which mixes them into the regular output of whatever command called them and breaks programs that parse stdout, like the upcoming MCP server whose stdout is the protocol stream. Log them as errors instead, so they go to stderr with the other diagnostics. Co-Authored-By: Claude Fable 5.1 --- framework_lib/src/smbios.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/framework_lib/src/smbios.rs b/framework_lib/src/smbios.rs index dad72bcf..ab728130 100644 --- a/framework_lib/src/smbios.rs +++ b/framework_lib/src/smbios.rs @@ -136,7 +136,7 @@ pub fn get_product_name() -> Option { } let Some(smbios) = get_smbios() else { - println!("Failed to find SMBIOS"); + error!("Failed to find SMBIOS"); return None; }; smbios.structures().find_map(|result| match result { @@ -220,7 +220,7 @@ pub fn get_platform() -> Option { if let Some(platform) = platform { Config::set(platform); } else { - println!("Failed to find PlatformFamily"); + warn!("Failed to find PlatformFamily"); } assert!(cached_platform.is_none()); @@ -267,18 +267,18 @@ pub fn get_smbios() -> Option { let ep_bytes = match std::fs::read("/sys/firmware/dmi/tables/smbios_entry_point") { Ok(data) => data, Err(ref e) if e.kind() == std::io::ErrorKind::PermissionDenied => { - println!("Must be root to get SMBIOS data."); + error!("Must be root to get SMBIOS data."); return None; } Err(err) => { - println!("Failed to get SMBIOS: {:?}", err); + error!("Failed to get SMBIOS: {:?}", err); return None; } }; let table_data = match std::fs::read("/sys/firmware/dmi/tables/DMI") { Ok(data) => data, Err(err) => { - println!("Failed to read SMBIOS table: {:?}", err); + error!("Failed to read SMBIOS table: {:?}", err); return None; } }; @@ -295,14 +295,14 @@ pub fn get_smbios() -> Option { let signature = FIRMWARE_TABLE_PROVIDER(u32::from_be_bytes(*b"RSMB")); let size = unsafe { GetSystemFirmwareTable(signature, 0, None) }; if size == 0 { - println!("Failed to get SMBIOS table size"); + error!("Failed to get SMBIOS table size"); return None; } let mut buf = vec![0u8; size as usize]; let written = unsafe { GetSystemFirmwareTable(signature, 0, Some(&mut buf)) }; if written == 0 { - println!("Failed to read SMBIOS table data"); + error!("Failed to read SMBIOS table data"); return None; } From 48a64010809fcd2658b1ef41082daf5dee29d30d Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sun, 20 Sep 2026 17:07:23 +0200 Subject: [PATCH 17/26] framework_lib: Export Platform types and serialize intrusion status Platform and PlatformFamily are returned by public functions but lived in a private module, so other crates could not name them. Re-export them from the crate root and derive Serialize for Platform. IntrusionStatus gets the usual derives and Serialize as well, so the MCP server can report it. Co-Authored-By: Claude Fable 5.1 --- framework_lib/src/chromium_ec/mod.rs | 3 +++ framework_lib/src/lib.rs | 1 + framework_lib/src/util.rs | 1 + 3 files changed, 5 insertions(+) diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index 639d9185..fe699713 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -2334,6 +2334,9 @@ pub fn print_sysinfo(info: &SysInfo) { } } +/// Chassis intrusion status, as reported by the EC +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct IntrusionStatus { /// Whether the chassis is currently open pub currently_open: bool, diff --git a/framework_lib/src/lib.rs b/framework_lib/src/lib.rs index 64d6cb5f..cea0ba4d 100644 --- a/framework_lib/src/lib.rs +++ b/framework_lib/src/lib.rs @@ -65,6 +65,7 @@ pub mod power; pub mod smart_battery; pub mod smbios; mod util; +pub use util::{Platform, PlatformFamily}; pub mod built_info { // The file has been placed there by the build script. diff --git a/framework_lib/src/util.rs b/framework_lib/src/util.rs index ef695940..828ebc7c 100644 --- a/framework_lib/src/util.rs +++ b/framework_lib/src/util.rs @@ -19,6 +19,7 @@ use no_std_compat::time::Duration; use crate::smbios; #[derive(Debug, PartialEq, Clone, Copy)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub enum Platform { /// Framework Laptop 12 Framework12IntelGen13, From 99afcae7df1160f972528dc21d53f44de4ba8886 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sun, 20 Sep 2026 17:13:34 +0200 Subject: [PATCH 18/26] framework_lib: Recover poisoned platform caches If a thread panics while holding the config or platform cache mutex, every later access panicked with a PoisonError, even from threads that could have carried on. The caches hold plain values that are safe to read after a panic, so take the inner value instead. This matters for long-running users of the library like the MCP server, where one failed request must not take the whole server down. Co-Authored-By: Claude Fable 5.1 --- framework_lib/src/smbios.rs | 4 +++- framework_lib/src/util.rs | 16 ++++++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/framework_lib/src/smbios.rs b/framework_lib/src/smbios.rs index ab728130..a25eaa85 100644 --- a/framework_lib/src/smbios.rs +++ b/framework_lib/src/smbios.rs @@ -178,7 +178,9 @@ pub fn get_platform() -> Option { #[cfg(feature = "uefi")] let mut cached_platform = CACHED_PLATFORM.lock(); #[cfg(not(feature = "uefi"))] - let mut cached_platform = CACHED_PLATFORM.lock().unwrap(); + let mut cached_platform = CACHED_PLATFORM + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); if let Some(platform) = *cached_platform { return platform; diff --git a/framework_lib/src/util.rs b/framework_lib/src/util.rs index 828ebc7c..56982297 100644 --- a/framework_lib/src/util.rs +++ b/framework_lib/src/util.rs @@ -121,7 +121,9 @@ pub struct Config { impl Config { pub fn set(platform: Platform) { #[cfg(not(feature = "uefi"))] - let mut config = CONFIG.lock().unwrap(); + let mut config = CONFIG + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); #[cfg(feature = "uefi")] let mut config = CONFIG.lock(); @@ -134,7 +136,9 @@ impl Config { } pub fn is_set() -> bool { #[cfg(not(feature = "uefi"))] - let config = CONFIG.lock().unwrap(); + let config = CONFIG + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); #[cfg(feature = "uefi")] let config = CONFIG.lock(); @@ -145,7 +149,9 @@ impl Config { trace!("Config::get() entry"); let unset = { #[cfg(not(feature = "uefi"))] - let config = CONFIG.lock().unwrap(); + let config = CONFIG + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); #[cfg(feature = "uefi")] let config = CONFIG.lock(); (*config).is_none() @@ -162,7 +168,9 @@ impl Config { }; #[cfg(not(feature = "uefi"))] - let mut config = CONFIG.lock().unwrap(); + let mut config = CONFIG + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); #[cfg(feature = "uefi")] let mut config = CONFIG.lock(); From 925149ecf9a6a8cfd2d3acfcda9ab99d22e0eedc Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sun, 20 Sep 2026 17:13:34 +0200 Subject: [PATCH 19/26] Add framework_mcp: MCP server for hardware information An MCP (Model Context Protocol) server that lets AI assistants read the hardware state of a Framework Computer system: battery and charger, USB-C PD ports, temperatures and fans, sensors, switches, firmware versions and EC diagnostics. It is built on framework_lib and every tool returns the same data as the matching framework_tool command, as JSON. 20 read-only tools, no arguments, plus system_snapshot that gathers everything at once for diagnosing a problem. Hardware failures are returned as tool errors so the assistant sees what went wrong. The server speaks MCP over stdio, so stdout is the protocol stream and all logging goes to stderr. It needs root for EC access and refuses to start otherwise, or if the EC does not respond, so the client shows a clear error. --skip-checks overrides that. framework_mcp is a workspace member but not a default member, so `cargo build` and `cargo run` behave as before. CI builds and lints it explicitly. It needs Rust 1.88 for rmcp. Co-Authored-By: Claude Fable 5.1 --- .github/workflows/ci.yml | 8 +- Cargo.lock | 426 ++++++++++++++++++++++++++- Cargo.toml | 4 + README.md | 1 + framework_mcp/Cargo.toml | 29 ++ framework_mcp/README.md | 86 ++++++ framework_mcp/src/main.rs | 78 +++++ framework_mcp/src/server.rs | 561 ++++++++++++++++++++++++++++++++++++ 8 files changed, 1182 insertions(+), 11 deletions(-) create mode 100644 framework_mcp/Cargo.toml create mode 100644 framework_mcp/README.md create mode 100644 framework_mcp/src/main.rs create mode 100644 framework_mcp/src/server.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dad703ac..8071b80f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -49,6 +49,12 @@ jobs: - name: Check if Linux tool can start run: cargo run -- --help + - name: Build MCP server + run: cargo build -p framework_mcp + + - name: Check if MCP server can start + run: ./target/debug/framework_mcp --help + - name: Upload Linux App uses: actions/upload-artifact@v7 with: @@ -209,7 +215,7 @@ jobs: run: cargo fmt --all -- --check - name: Run cargo clippy - run: cargo clippy -p framework_lib -p framework_tool -- -D warnings + run: cargo clippy -p framework_lib -p framework_tool -p framework_mcp -- -D warnings - name: Check shell completions are up to date run: | diff --git a/Cargo.lock b/Cargo.lock index 3060e6f0..77b49576 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -76,6 +76,12 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "bit_field" version = "0.10.3" @@ -103,6 +109,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "built" version = "0.8.1" @@ -119,6 +134,12 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + [[package]] name = "cc" version = "1.6.0" @@ -162,6 +183,7 @@ checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" dependencies = [ "iana-time-zone", "num-traits", + "serde", "windows-link 0.2.1", ] @@ -249,6 +271,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -283,14 +311,33 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "darling" version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" dependencies = [ - "darling_core", - "darling_macro", + "darling_core 0.20.11", + "darling_macro 0.20.11", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core 0.24.1", + "darling_macro 0.24.1", ] [[package]] @@ -307,17 +354,41 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.6", +] + [[package]] name = "darling_macro" version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" dependencies = [ - "darling_core", + "darling_core 0.20.11", "quote", "syn 2.0.119", ] +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core 0.24.1", + "quote", + "syn 3.0.6", +] + [[package]] name = "defmt" version = "1.1.1" @@ -355,8 +426,19 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", ] [[package]] @@ -369,6 +451,12 @@ dependencies = [ "uuid", ] +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + [[package]] name = "embed-resource" version = "3.0.11" @@ -441,7 +529,7 @@ dependencies = [ "lazy_static", "libc", "log", - "nix", + "nix 0.31.3", "no-std-compat", "num", "num-derive", @@ -454,7 +542,7 @@ dependencies = [ "serde", "serde_json", "sha1", - "sha2", + "sha2 0.10.9", "smartmon", "spin 0.12.3", "uefi", @@ -465,6 +553,22 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "framework_mcp" +version = "0.6.5" +dependencies = [ + "clap", + "dmidecode", + "env_logger", + "framework_lib", + "log", + "nix 0.30.1", + "rmcp", + "serde", + "serde_json", + "tokio", +] + [[package]] name = "framework_tool" version = "0.6.6" @@ -485,12 +589,71 @@ dependencies = [ "uefi", ] +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + [[package]] name = "futures-core" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + [[package]] name = "futures-task" version = "0.3.34" @@ -503,8 +666,13 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ + "futures-channel", "futures-core", + "futures-io", + "futures-macro", + "futures-sink", "futures-task", + "memchr", "pin-project-lite", "slab", ] @@ -577,6 +745,15 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -615,6 +792,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown", + "serde", + "serde_core", ] [[package]] @@ -769,6 +948,29 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nix" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nix" version = "0.31.3" @@ -893,6 +1095,12 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -987,6 +1195,26 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "regex" version = "1.13.1" @@ -1016,6 +1244,44 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "rmcp" +version = "3.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d24a7e92f4bcaa36b97fa93c4fa7ca8f3e669eced949345b3462dba333c7f909" +dependencies = [ + "base64", + "chrono", + "futures", + "indexmap", + "libc", + "pastey", + "pin-project-lite", + "rmcp-macros", + "schemars", + "serde", + "serde_json", + "sha2 0.11.1", + "thiserror 2.0.21", + "tokio", + "tokio-util", + "tracing", + "uuid", +] + +[[package]] +name = "rmcp-macros" +version = "3.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3140f24a766f80f9ec1607bde85680959a69b83d46fa9ce87dadab7e67ab029" +dependencies = [ + "darling 0.24.1", + "proc-macro2", + "quote", + "serde_json", + "syn 3.0.6", +] + [[package]] name = "roff" version = "1.1.1" @@ -1047,6 +1313,32 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "chrono", + "dyn-clone", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 3.0.6", +] + [[package]] name = "scopeguard" version = "1.2.0" @@ -1089,6 +1381,17 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "serde_json" version = "1.0.151" @@ -1119,7 +1422,7 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", ] [[package]] @@ -1130,7 +1433,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -1154,6 +1468,16 @@ dependencies = [ "cc", ] +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "spin" version = "0.9.9" @@ -1249,6 +1573,46 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + [[package]] name = "toml" version = "1.1.6+spec-1.1.0" @@ -1288,6 +1652,37 @@ version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + [[package]] name = "typenum" version = "1.20.1" @@ -1363,6 +1758,11 @@ name = "uuid" version = "1.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97277d36b9c3ace13e58fa6e753f8b0bbbf302a18dd193240d70f9e29681059a" +dependencies = [ + "getrandom", + "js-sys", + "wasm-bindgen", +] [[package]] name = "vcpkg" @@ -1396,6 +1796,12 @@ dependencies = [ "libc", ] +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasm-bindgen" version = "0.2.129" @@ -1712,7 +2118,7 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a76ff259533532054cfbaefb115c613203c73707017459206380f03b3b3f266e" dependencies = [ - "darling", + "darling 0.20.11", "proc-macro2", "quote", "syn 2.0.119", diff --git a/Cargo.toml b/Cargo.toml index 66801a46..e19beefb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,11 +9,15 @@ members = [ "framework_tool", # UEFI tool to inspect and customize the system "framework_uefi", + # MCP server to expose hardware information to AI assistants + "framework_mcp", # Catchall library that we'll probably want to split up further "framework_lib", ] # Don't build UEFI by default. Needs special cargo invocation +# framework_mcp is not a default member either, so `cargo run` keeps +# starting framework_tool. Build it with `cargo build -p framework_mcp`. default-members = [ "framework_lib", "framework_tool", diff --git a/README.md b/README.md index 38c83cf6..792b0d52 100644 --- a/README.md +++ b/README.md @@ -127,6 +127,7 @@ On UEFI and FreeBSD raw port I/O is used - on Linux this can also be used as a f - [x] Show system information - [x] As JSON for scripting (`--json`, not on UEFI) + - [x] As MCP server for AI assistants (`framework_mcp`, see [framework_mcp/README.md](framework_mcp/README.md)) - [x] ESRT table (UEFI, Linux, FreeBSD only) (`--esrt`) - [x] SMBIOS - [x] Get firmware version from binary file diff --git a/framework_mcp/Cargo.toml b/framework_mcp/Cargo.toml new file mode 100644 index 00000000..4b0c6ba6 --- /dev/null +++ b/framework_mcp/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "framework_mcp" +version = "0.6.5" +description = "MCP server that exposes Framework Computer hardware information to AI assistants" +homepage = "https://github.com/FrameworkComputer/framework-system" +repository = "https://github.com/FrameworkComputer/framework-system" +readme = "README.md" +license = "BSD-3-Clause" +edition = "2021" +# rmcp needs a newer compiler than framework_lib +rust-version = "1.88" + +[[bin]] +name = "framework_mcp" +path = "src/main.rs" + +[dependencies] +framework_lib = { path = "../framework_lib", version = "0.6.5" } +rmcp = { version = "3.4", features = ["server", "macros", "transport-io"] } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +log = "0.4" +env_logger = "0.11" +clap = { version = "4.5", features = ["derive"] } +dmidecode = { version = "1", default-features = false } + +[target.'cfg(unix)'.dependencies] +nix = { version = "0.30", features = ["user"] } diff --git a/framework_mcp/README.md b/framework_mcp/README.md new file mode 100644 index 00000000..05e648d0 --- /dev/null +++ b/framework_mcp/README.md @@ -0,0 +1,86 @@ +# framework_mcp + +An [MCP](https://modelcontextprotocol.io) server that gives AI assistants +read-only access to the hardware state of a Framework Computer system: +battery and charger, USB-C PD ports, temperatures and fans, sensors, +switches, firmware versions and Embedded Controller diagnostics. + +It is built on the same `framework_lib` as `framework_tool`, so every tool +returns the data the matching `framework_tool` command shows, as JSON. + +## Tools + +| Tool | framework_tool equivalent | +|----------------------|---------------------------| +| `system_snapshot` | everything below at once, for diagnosing a problem | +| `platform` | `--info` (which system this is) | +| `versions` | `--versions` (BIOS, EC, PD controllers) | +| `power_status` | `--power` | +| `charge_limit` | `--charge-limit` | +| `thermal` | `--thermal` | +| `thermal_thresholds` | `--thermalget` | +| `sensors` | `--sensors` | +| `switches` | `--switches` | +| `chassis_intrusion` | `--intrusion` | +| `privacy_switches` | `--privacy` | +| `keyboard_backlight` | `--kblight` | +| `pd_ports` | `--pdports` | +| `pd_power_info` | `--pdports-chromebook` | +| `ec_sysinfo` | `--sysinfo` | +| `ec_uptime` | `--uptimeinfo` | +| `ec_features` | `--features` | +| `inputdeck` | `--inputdeck` | +| `expansion_bay` | `--expansion-bay` (Laptop 16) | +| `ec_panic_info` | `--panicinfo` | + +All tools are read-only and take no arguments. Nothing here changes any +setting on the system. + +## Running + +The server talks to the Embedded Controller, which needs root, and speaks +MCP over stdin/stdout. It refuses to start if it is not root or cannot reach +the EC, so the client shows a clear error. Logs go to stderr, controlled by +`RUST_LOG` (default `warn`). + +``` +cargo build -p framework_mcp +sudo ./target/debug/framework_mcp +``` + +Because MCP clients start the server themselves, `sudo` must not ask for a +password. Either run the client as root, or allow the binary in sudoers: + +``` +# /etc/sudoers.d/framework_mcp +yourname ALL=(root) NOPASSWD: /usr/bin/framework_mcp +``` + +### Claude Code + +``` +claude mcp add framework -- sudo /usr/bin/framework_mcp +``` + +### Claude Desktop and other clients + +```json +{ + "mcpServers": { + "framework": { + "command": "sudo", + "args": ["/usr/bin/framework_mcp"] + } + } +} +``` + +On Windows, run the client elevated and point it at `framework_mcp.exe` +directly. + +## Options + +``` +--driver Force a specific EC driver +--skip-checks Start even if not root or the EC does not respond +``` diff --git a/framework_mcp/src/main.rs b/framework_mcp/src/main.rs new file mode 100644 index 00000000..ec5fdf3f --- /dev/null +++ b/framework_mcp/src/main.rs @@ -0,0 +1,78 @@ +//! MCP server for Framework Computer hardware +//! +//! Exposes the read-only information framework_tool can show (battery, +//! charger, PD ports, temperatures, fans, sensors, EC state, ...) as tools +//! for AI assistants that speak the Model Context Protocol. Talks to the +//! client over stdio, so stdout must stay clean: everything else goes to +//! the log on stderr. + +mod server; + +use clap::Parser; +use framework_lib::chromium_ec::{CrosEc, CrosEcDriverType}; +use rmcp::transport::stdio; +use rmcp::ServiceExt; + +use crate::server::FrameworkServer; + +/// MCP server for Framework Computer hardware information +#[derive(Parser)] +#[command(version, about)] +struct Args { + /// Force a specific driver to talk to the EC + #[arg(long, value_enum)] + driver: Option, + + /// Start even if not running as root or the EC does not respond + /// + /// By default the server refuses to start in that case, so the MCP + /// client shows a clear error instead of every tool failing. + #[arg(long)] + skip_checks: bool, +} + +fn main() -> Result<(), Box> { + // stdout is the MCP transport, all logging goes to stderr + env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("warn")) + .format_target(false) + .format_timestamp(None) + .init(); + + let args = Args::parse(); + + #[cfg(unix)] + if !args.skip_checks && !nix::unistd::Uid::effective().is_root() { + eprintln!("framework_mcp must run as root to access the Embedded Controller."); + eprintln!("Configure your MCP client to start it with sudo."); + std::process::exit(1); + } + + let ec = match args.driver { + Some(driver) => match CrosEc::with(driver) { + Some(ec) => ec, + None => { + eprintln!("EC driver {:?} is not available on this system.", driver); + std::process::exit(1); + } + }, + None => CrosEc::new(), + }; + + if !args.skip_checks { + if let Err(err) = ec.version_info() { + eprintln!("Cannot talk to the Embedded Controller: {:?}", err); + eprintln!("Is this a Framework Computer system? Pass --skip-checks to start anyway."); + std::process::exit(1); + } + } + + tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build()? + .block_on(async { + let service = FrameworkServer::new(ec).serve(stdio()).await?; + log::info!("framework_mcp connected"); + service.waiting().await?; + Ok(()) + }) +} diff --git a/framework_mcp/src/server.rs b/framework_mcp/src/server.rs new file mode 100644 index 00000000..252d5d6e --- /dev/null +++ b/framework_mcp/src/server.rs @@ -0,0 +1,561 @@ +//! The MCP tools, one per piece of hardware information +//! +//! Every tool reads from the EC through framework_lib and returns the +//! result as JSON, both as text and as structured content. Hardware +//! failures are reported as tool errors (`is_error`), so the assistant +//! sees what went wrong, protocol errors are reserved for bugs. + +use dmidecode::Structure; +use framework_lib::ccgx::{self, ControllerFirmwares, PdVersions}; +use framework_lib::chromium_ec::{CrosEc, EcError}; +use framework_lib::{power, smbios, Platform, PlatformFamily}; +use rmcp::model::{CallToolResult, ContentBlock}; +use rmcp::{tool, tool_handler, tool_router, ErrorData, ServerHandler}; +use serde::Serialize; +use serde_json::{json, Value}; + +type ToolResult = Result; + +/// Format an EC error for the assistant +fn ec_err(err: EcError) -> String { + format!("EC error: {:?}", err) +} + +/// Serialize a value, or explain why it could not be read +fn section(result: Result) -> Value { + match result { + Ok(value) => serde_json::to_value(value) + .unwrap_or_else(|err| json!({ "error": format!("Failed to serialize: {}", err) })), + Err(err) => json!({ "error": err }), + } +} + +/// Turn a read result into a tool result +/// +/// Successful reads carry the JSON both as pretty text and as structured +/// content, failed reads become tool errors. +fn to_tool_result(result: Result) -> ToolResult { + match result { + Ok(value) => { + let value = serde_json::to_value(value).map_err(|err| { + ErrorData::internal_error(format!("Failed to serialize: {}", err), None) + })?; + let text = serde_json::to_string_pretty(&value).unwrap_or_else(|_| value.to_string()); + let mut result = CallToolResult::structured(value); + result.content = vec![ContentBlock::text(text)]; + Ok(result) + } + Err(err) => Ok(CallToolResult::error(vec![ContentBlock::text(err)])), + } +} + +/// Which system this is +#[derive(Debug, Serialize)] +struct PlatformInfo { + /// Whether this looks like a Framework Computer system at all + is_framework: bool, + /// Mainboard, e.g. Framework 13 with AMD Ryzen AI 300 + platform: Option, + /// Product family, e.g. Framework 13 + family: Option, + /// Product name from SMBIOS + product_name: Option, + /// Mainboard revision from SMBIOS + baseboard_version: Option, +} + +fn platform_info() -> PlatformInfo { + PlatformInfo { + is_framework: smbios::is_framework(), + platform: smbios::get_platform(), + family: smbios::get_family(), + product_name: smbios::get_product_name(), + baseboard_version: smbios::get_baseboard_version().map(|v| format!("{:?}", v)), + } +} + +#[derive(Debug, Serialize)] +struct BiosVersion { + version: String, + release_date: String, +} + +#[derive(Debug, Serialize)] +struct EcVersions { + /// Full build string of the running firmware + build: String, + /// Version of the read-only image + ro: Option, + /// Version of the read-write image + rw: Option, + /// Which image is running, RO or RW + current_image: Option, +} + +#[derive(Debug, Serialize)] +struct FwVersion { + /// Version of the silicon vendor's base firmware + base: String, + /// Version of Framework's application firmware, this is what --versions shows + app: String, +} + +impl From for FwVersion { + fn from(version: ccgx::ControllerVersion) -> Self { + FwVersion { + base: version.base.to_string(), + app: version.app.to_string(), + } + } +} + +#[derive(Debug, Serialize)] +struct PdControllerVersions { + /// Which controller, e.g. "Right (01)" + controller: String, + /// Which image is running: MainFw, BackupFw or BootLoader + active_image: String, + /// Version of the running image, formatted like --versions does + active_version: String, + main: FwVersion, + backup: FwVersion, + bootloader: FwVersion, +} + +impl PdControllerVersions { + fn new(controller: &str, fw: &ControllerFirmwares) -> Self { + PdControllerVersions { + controller: controller.to_string(), + active_image: format!("{:?}", fw.active_fw), + active_version: fw.active_fw_ver(), + main: fw.main_fw.into(), + backup: fw.backup_fw.into(), + bootloader: fw.bootloader.into(), + } + } +} + +#[derive(Debug, Serialize)] +struct Versions { + bios: Option, + /// EcVersions, or an object with an "error" field + ec: Value, + /// List of PdControllerVersions, or an object with an "error" field + pd_controllers: Value, +} + +fn versions(ec: &CrosEc) -> Versions { + let bios = smbios::get_smbios().and_then(|smbios| { + smbios.structures().find_map(|s| match s { + Ok(Structure::Bios(bios)) => Some(BiosVersion { + version: bios.bios_version.to_string(), + release_date: bios.bios_release_date.to_string(), + }), + _ => None, + }) + }); + + let ec_versions = ec.version_info().map_err(ec_err).map(|build| { + let flash = ec.flash_version(); + EcVersions { + build, + ro: flash.as_ref().map(|(ro, _, _)| ro.clone()), + rw: flash.as_ref().map(|(_, rw, _)| rw.clone()), + current_image: flash + .as_ref() + .map(|(_, _, current)| format!("{:?}", current)), + } + }); + + // Locating the PD controllers needs to know the platform, the library + // panics otherwise + let pd_controllers = if smbios::get_platform().is_none() { + Err("Unknown platform, can't locate the PD controllers".to_string()) + } else { + ccgx::get_pd_controller_versions(ec).map_err(ec_err) + } + .map(|versions| match versions { + PdVersions::RightLeft((right, left)) => vec![ + PdControllerVersions::new("Right (01)", &right), + PdControllerVersions::new("Left (23)", &left), + ], + PdVersions::Single(pd) => vec![PdControllerVersions::new("PD", &pd)], + PdVersions::Many(pds) => pds + .iter() + .enumerate() + .map(|(i, pd)| PdControllerVersions::new(&format!("PD {}", i), pd)) + .collect(), + }); + + Versions { + bios, + ec: section(ec_versions), + pd_controllers: section(pd_controllers), + } +} + +#[derive(Debug, Serialize)] +struct ChargeLimit { + /// Charging starts below this percentage + min_percent: u8, + /// Charging stops at this percentage + max_percent: u8, +} + +#[derive(Debug, Serialize)] +struct PrivacySwitches { + /// Whether the microphone is connected (hardware privacy switch) + microphone_connected: bool, + /// Whether the camera is connected (hardware privacy switch) + camera_connected: bool, +} + +/// The MCP server, one instance per client connection +#[derive(Clone)] +pub struct FrameworkServer { + ec: CrosEc, +} + +impl FrameworkServer { + pub fn new(ec: CrosEc) -> Self { + FrameworkServer { ec } + } + + /// Run a synchronous hardware read off the async runtime and turn the + /// result into a tool result + async fn read(&self, read: F) -> ToolResult + where + T: Serialize + Send + 'static, + F: FnOnce(&CrosEc) -> Result + Send + 'static, + { + let ec = self.ec.clone(); + match tokio::task::spawn_blocking(move || read(&ec)).await { + Ok(result) => to_tool_result(result), + Err(err) => Err(ErrorData::internal_error( + format!("Hardware access failed: {}", err), + None, + )), + } + } +} + +// Every tool has a matching framework_tool command, named in the description +// so a user can reproduce what the assistant saw. +#[tool_router] +impl FrameworkServer { + #[tool( + description = "Which Framework Computer system this is: platform, product family, product name and mainboard revision from SMBIOS.", + annotations(title = "Platform", read_only_hint = true) + )] + async fn platform(&self) -> ToolResult { + self.read(|_ec| Ok(platform_info())).await + } + + #[tool( + description = "Firmware versions of BIOS, Embedded Controller (RO/RW image) and the USB-C PD controllers. Same data as `framework_tool --versions`.", + annotations(title = "Firmware Versions", read_only_hint = true) + )] + async fn versions(&self) -> ToolResult { + self.read(|ec| Ok(versions(ec))).await + } + + #[tool( + description = "Battery and charger state: AC present, battery cutoff (ship mode), charge percentage, remaining/full/design capacity in mAh, voltage in mV, charge/discharge rate in mA, cycle count, charger voltage/current and input current limit. Same as `framework_tool --power`.", + annotations(title = "Power Status", read_only_hint = true) + )] + async fn power_status(&self) -> ToolResult { + self.read(|ec| Ok(power::get_power_status(ec))).await + } + + #[tool( + description = "Battery charge limit in percent: charging stops at max and only resumes below min. Same as `framework_tool --charge-limit`.", + annotations(title = "Charge Limit", read_only_hint = true) + )] + async fn charge_limit(&self) -> ToolResult { + self.read(|ec| { + ec.get_charge_limit() + .map(|(min, max)| ChargeLimit { + min_percent: min, + max_percent: max, + }) + .map_err(ec_err) + }) + .await + } + + #[tool( + description = "Temperature sensors in degrees Celsius, fan speeds in RPM (or Stalled/NotPresent) and whether the EC throttles the CPU. Same as `framework_tool --thermal`.", + annotations(title = "Thermal", read_only_hint = true) + )] + async fn thermal(&self) -> ToolResult { + self.read(|ec| power::get_thermal(ec).map_err(ec_err)).await + } + + #[tool( + description = "Per-sensor thermal thresholds in degrees Celsius: warn, high (CPU throttle), halt (shutdown), fan_off and fan_max. null means the threshold is disabled. Same as `framework_tool --thermalget`.", + annotations(title = "Thermal Thresholds", read_only_hint = true) + )] + async fn thermal_thresholds(&self) -> ToolResult { + self.read(|ec| { + power::get_thermal_thresholds(ec) + .ok_or_else(|| "Failed to read thermal thresholds from the EC".to_string()) + }) + .await + } + + #[tool( + description = "Ambient light sensor in lux and accelerometers (lid and base, in raw units where 16384 is 1G) with the lid angle in degrees. Sensors the system doesn't have are null. Same as `framework_tool --sensors`.", + annotations(title = "Sensors", read_only_hint = true) + )] + async fn sensors(&self) -> ToolResult { + self.read(|ec| { + power::get_sensors(ec).ok_or_else(|| "Failed to read sensors from the EC".to_string()) + }) + .await + } + + #[tool( + description = "EC switch positions: lid open, power button pressed, firmware write protect disabled, dedicated recovery switch. Same as `framework_tool --switches`.", + annotations(title = "Switches", read_only_hint = true) + )] + async fn switches(&self) -> ToolResult { + self.read(|ec| { + power::get_switches(ec).ok_or_else(|| "Failed to read switches from the EC".to_string()) + }) + .await + } + + #[tool( + description = "Chassis intrusion: whether the case is currently open, has ever been opened, how often, and whether the coin cell was ever removed. Same as `framework_tool --intrusion`.", + annotations(title = "Chassis Intrusion", read_only_hint = true) + )] + async fn chassis_intrusion(&self) -> ToolResult { + self.read(|ec| ec.get_intrusion_status().map_err(ec_err)) + .await + } + + #[tool( + description = "Hardware privacy switches: whether microphone and camera are connected. Same as `framework_tool --privacy`.", + annotations(title = "Privacy Switches", read_only_hint = true) + )] + async fn privacy_switches(&self) -> ToolResult { + self.read(|ec| { + ec.get_privacy_info() + .map(|(microphone, camera)| PrivacySwitches { + microphone_connected: microphone, + camera_connected: camera, + }) + .map_err(ec_err) + }) + .await + } + + #[tool( + description = "Keyboard backlight brightness in percent. Same as `framework_tool --kblight`.", + annotations(title = "Keyboard Backlight", read_only_hint = true) + )] + async fn keyboard_backlight(&self) -> ToolResult { + self.read(|ec| { + ec.get_keyboard_backlight() + .map(|percent| json!({ "percent": percent })) + .map_err(ec_err) + }) + .await + } + + #[tool( + description = "USB-C port state from the PD controller, per port: connection state, PD contract, power/data role, negotiated voltage (mV), current (mA) and power (mW), CC polarity, EPR, whether it is the active charging port and DP alt mode. Port 0 is right back, 3 is left back. Ports that don't exist are left out. Same as `framework_tool --pdports`.", + annotations(title = "USB-C PD Ports", read_only_hint = true) + )] + async fn pd_ports(&self) -> ToolResult { + self.read(|ec| { + let mut ports = vec![]; + for port in power::get_cypd_pd_info(ec) { + ports.push(port.map_err(ec_err)?); + } + Ok(ports) + }) + .await + } + + #[tool( + description = "USB-C power info as the EC sees it (ChromeOS EC_CMD_USB_PD_POWER_INFO), per port: role, charging type, voltage now/max (mV), current limit/max (mA), dual role and max power (uW). Ports that failed to respond are null. Same as `framework_tool --pdports-chromebook`.", + annotations(title = "USB-C Power Info", read_only_hint = true) + )] + async fn pd_power_info(&self) -> ToolResult { + self.read(|ec| { + let ports: Vec> = power::get_pd_info(ec, 4) + .into_iter() + .map(|port| port.ok()) + .collect(); + Ok(ports) + }) + .await + } + + #[tool( + description = "EC system info: which image runs (RO/RW), why the EC was last reset and its sysinfo flags, raw and decoded. Same as `framework_tool --sysinfo`.", + annotations(title = "EC System Info", read_only_hint = true) + )] + async fn ec_sysinfo(&self) -> ToolResult { + self.read(|ec| ec.get_sysinfo().map_err(ec_err)).await + } + + #[tool( + description = "EC uptime in ms, how often the EC reset the AP since it booted, EC reset flags and the most recent AP resets with cause. Same as `framework_tool --uptimeinfo`.", + annotations(title = "EC Uptime", read_only_hint = true) + )] + async fn ec_uptime(&self) -> ToolResult { + self.read(|ec| ec.get_uptime_info().map_err(ec_err)).await + } + + #[tool( + description = "Features the EC firmware supports, as raw bitmask and list of enabled feature names. Same as `framework_tool --features`.", + annotations(title = "EC Features", read_only_hint = true) + )] + async fn ec_features(&self) -> ToolResult { + self.read(|ec| ec.get_features().map_err(ec_err)).await + } + + #[tool( + description = "Input deck status: chassis closed, connected daughterboards with board ID (Laptop 12/13), deck state and touchpad presence, top row module positions and SLEEP# GPIO (Laptop 16). Same as `framework_tool --inputdeck`.", + annotations(title = "Input Deck", read_only_hint = true) + )] + async fn inputdeck(&self) -> ToolResult { + self.read(|ec| ec.get_inputdeck_status().map_err(ec_err)) + .await + } + + #[tool( + description = "Expansion bay status (Laptop 16 only): module enabled, fault, door closed, board type, serial number, PCIe config and vendor. Same as `framework_tool --expansion-bay`.", + annotations(title = "Expansion Bay", read_only_hint = true) + )] + async fn expansion_bay(&self) -> ToolResult { + self.read(|ec| ec.get_bay_status().map_err(ec_err)).await + } + + #[tool( + description = "Saved EC panic (crash) data, null if the EC never panicked: architecture, flags, plausibility checks and for Cortex-M the exception, registers (r0-r12, sp, lr, pc as array index 0-15) and decoded fault names. Same as `framework_tool --panicinfo`.", + annotations(title = "EC Panic Info", read_only_hint = true) + )] + async fn ec_panic_info(&self) -> ToolResult { + self.read(|ec| { + ec.get_panic_info() + .map(|data| framework_lib::chromium_ec::panic::parse_panic_info(&data)) + .map_err(ec_err) + }) + .await + } + + #[tool( + description = "Everything at once for debugging: platform, versions, power, charge limit, thermal, thresholds, sensors, switches, chassis, privacy, keyboard backlight, PD ports, EC sysinfo/uptime/features, input deck, expansion bay (Laptop 16) and panic info. Sections that could not be read contain an \"error\" field. Call this first when diagnosing a problem.", + annotations(title = "System Snapshot", read_only_hint = true) + )] + async fn system_snapshot(&self) -> ToolResult { + self.read(|ec| Ok(snapshot(ec))).await + } +} + +/// Collect every read-only tool into one object +fn snapshot(ec: &CrosEc) -> Value { + let mut snapshot = serde_json::Map::new(); + let mut add = |name: &str, value: Value| { + snapshot.insert(name.to_string(), value); + }; + + add("platform", section(Ok(platform_info()))); + add("versions", section(Ok(versions(ec)))); + add("power", section(Ok(power::get_power_status(ec)))); + add( + "charge_limit", + section( + ec.get_charge_limit() + .map_err(ec_err) + .map(|(min, max)| ChargeLimit { + min_percent: min, + max_percent: max, + }), + ), + ); + add("thermal", section(power::get_thermal(ec).map_err(ec_err))); + add( + "thermal_thresholds", + section(power::get_thermal_thresholds(ec).ok_or_else(|| "Failed to read".to_string())), + ); + add( + "sensors", + section(power::get_sensors(ec).ok_or_else(|| "Failed to read".to_string())), + ); + add( + "switches", + section(power::get_switches(ec).ok_or_else(|| "Failed to read".to_string())), + ); + add( + "chassis_intrusion", + section(ec.get_intrusion_status().map_err(ec_err)), + ); + add( + "privacy_switches", + section( + ec.get_privacy_info() + .map_err(ec_err) + .map(|(microphone, camera)| PrivacySwitches { + microphone_connected: microphone, + camera_connected: camera, + }), + ), + ); + add( + "keyboard_backlight", + section( + ec.get_keyboard_backlight() + .map_err(ec_err) + .map(|percent| json!({ "percent": percent })), + ), + ); + add( + "pd_ports", + section( + power::get_cypd_pd_info(ec) + .into_iter() + .map(|port| port.map_err(ec_err)) + .collect::, _>>(), + ), + ); + add( + "pd_power_info", + section(Ok(power::get_pd_info(ec, 4) + .into_iter() + .map(|port| port.ok()) + .collect::>>())), + ); + add("ec_sysinfo", section(ec.get_sysinfo().map_err(ec_err))); + add("ec_uptime", section(ec.get_uptime_info().map_err(ec_err))); + add("ec_features", section(ec.get_features().map_err(ec_err))); + add( + "inputdeck", + section(ec.get_inputdeck_status().map_err(ec_err)), + ); + if smbios::get_family() == Some(PlatformFamily::Framework16) { + add( + "expansion_bay", + section(ec.get_bay_status().map_err(ec_err)), + ); + } + add( + "ec_panic_info", + section( + ec.get_panic_info() + .map_err(ec_err) + .map(|data| framework_lib::chromium_ec::panic::parse_panic_info(&data)), + ), + ); + + Value::Object(snapshot) +} + +#[tool_handler( + name = "framework_mcp", + instructions = "Read-only access to the hardware state of this Framework Computer system through its Embedded Controller: battery and charger, USB-C PD ports, temperatures and fans, sensors, switches, firmware versions and EC diagnostics. Start with system_snapshot for an overview, then use the specific tools to re-read values that change. Units are in the field names or tool descriptions (degrees Celsius, mV, mA, mW, percent). Values decoded from bitmasks come both raw and as names. Some tools only apply to certain models, e.g. expansion_bay to the Laptop 16. Every tool names the framework_tool command that shows the same data, so the user can reproduce it." +)] +impl ServerHandler for FrameworkServer {} From a183f21879c55f9aefd0fd603800d1e2f550a06d Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sun, 20 Sep 2026 17:19:51 +0200 Subject: [PATCH 20/26] framework_mcp: Always return structured content as an object MCP requires structuredContent to be a JSON object, but pd_ports, pd_power_info and thermal_thresholds returned arrays and ec_panic_info returned null when there is no panic. Clients that validate the result rejected them. Wrap those in {"ports": ...}, {"sensors": ...} and {"panic": ...} and make the result helper wrap any other non-object in {"value": ...} so this can't happen again. Co-Authored-By: Claude Fable 5.1 --- framework_mcp/src/server.rs | 42 ++++++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 8 deletions(-) diff --git a/framework_mcp/src/server.rs b/framework_mcp/src/server.rs index 252d5d6e..b283907a 100644 --- a/framework_mcp/src/server.rs +++ b/framework_mcp/src/server.rs @@ -33,13 +33,19 @@ fn section(result: Result) -> Value { /// Turn a read result into a tool result /// /// Successful reads carry the JSON both as pretty text and as structured -/// content, failed reads become tool errors. +/// content, failed reads become tool errors. Structured content must be a +/// JSON object, so anything else is wrapped in one. fn to_tool_result(result: Result) -> ToolResult { match result { Ok(value) => { let value = serde_json::to_value(value).map_err(|err| { ErrorData::internal_error(format!("Failed to serialize: {}", err), None) })?; + let value = if value.is_object() { + value + } else { + json!({ "value": value }) + }; let text = serde_json::to_string_pretty(&value).unwrap_or_else(|_| value.to_string()); let mut result = CallToolResult::structured(value); result.content = vec![ContentBlock::text(text)]; @@ -194,6 +200,23 @@ fn versions(ec: &CrosEc) -> Versions { } } +/// Wrapper because structured tool results must be JSON objects, not arrays +#[derive(Debug, Serialize)] +struct Ports { + ports: Vec, +} + +#[derive(Debug, Serialize)] +struct Thresholds { + sensors: Vec, +} + +#[derive(Debug, Serialize)] +struct Panic { + /// null if the EC never panicked + panic: Option, +} + #[derive(Debug, Serialize)] struct ChargeLimit { /// Charging starts below this percentage @@ -292,12 +315,13 @@ impl FrameworkServer { } #[tool( - description = "Per-sensor thermal thresholds in degrees Celsius: warn, high (CPU throttle), halt (shutdown), fan_off and fan_max. null means the threshold is disabled. Same as `framework_tool --thermalget`.", + description = "Per-sensor thermal thresholds in degrees Celsius: warn, high (CPU throttle), halt (shutdown), fan_off and fan_max. null means the threshold is disabled. Returns {\"sensors\": [...]}. Same as `framework_tool --thermalget`.", annotations(title = "Thermal Thresholds", read_only_hint = true) )] async fn thermal_thresholds(&self) -> ToolResult { self.read(|ec| { power::get_thermal_thresholds(ec) + .map(|sensors| Thresholds { sensors }) .ok_or_else(|| "Failed to read thermal thresholds from the EC".to_string()) }) .await @@ -364,7 +388,7 @@ impl FrameworkServer { } #[tool( - description = "USB-C port state from the PD controller, per port: connection state, PD contract, power/data role, negotiated voltage (mV), current (mA) and power (mW), CC polarity, EPR, whether it is the active charging port and DP alt mode. Port 0 is right back, 3 is left back. Ports that don't exist are left out. Same as `framework_tool --pdports`.", + description = "USB-C port state from the PD controller, per port: connection state, PD contract, power/data role, negotiated voltage (mV), current (mA) and power (mW), CC polarity, EPR, whether it is the active charging port and DP alt mode. Port 0 is right back, 3 is left back. Ports that don't exist are left out. Returns {\"ports\": [...]}. Same as `framework_tool --pdports`.", annotations(title = "USB-C PD Ports", read_only_hint = true) )] async fn pd_ports(&self) -> ToolResult { @@ -373,13 +397,13 @@ impl FrameworkServer { for port in power::get_cypd_pd_info(ec) { ports.push(port.map_err(ec_err)?); } - Ok(ports) + Ok(Ports { ports }) }) .await } #[tool( - description = "USB-C power info as the EC sees it (ChromeOS EC_CMD_USB_PD_POWER_INFO), per port: role, charging type, voltage now/max (mV), current limit/max (mA), dual role and max power (uW). Ports that failed to respond are null. Same as `framework_tool --pdports-chromebook`.", + description = "USB-C power info as the EC sees it (ChromeOS EC_CMD_USB_PD_POWER_INFO), per port: role, charging type, voltage now/max (mV), current limit/max (mA), dual role and max power (uW). Ports that failed to respond are null. Returns {\"ports\": [...]}. Same as `framework_tool --pdports-chromebook`.", annotations(title = "USB-C Power Info", read_only_hint = true) )] async fn pd_power_info(&self) -> ToolResult { @@ -388,7 +412,7 @@ impl FrameworkServer { .into_iter() .map(|port| port.ok()) .collect(); - Ok(ports) + Ok(Ports { ports }) }) .await } @@ -435,13 +459,15 @@ impl FrameworkServer { } #[tool( - description = "Saved EC panic (crash) data, null if the EC never panicked: architecture, flags, plausibility checks and for Cortex-M the exception, registers (r0-r12, sp, lr, pc as array index 0-15) and decoded fault names. Same as `framework_tool --panicinfo`.", + description = "Saved EC panic (crash) data as {\"panic\": ...}, null if the EC never panicked: architecture, flags, plausibility checks and for Cortex-M the exception, registers (r0-r12, sp, lr, pc as array index 0-15) and decoded fault names. Same as `framework_tool --panicinfo`.", annotations(title = "EC Panic Info", read_only_hint = true) )] async fn ec_panic_info(&self) -> ToolResult { self.read(|ec| { ec.get_panic_info() - .map(|data| framework_lib::chromium_ec::panic::parse_panic_info(&data)) + .map(|data| Panic { + panic: framework_lib::chromium_ec::panic::parse_panic_info(&data), + }) .map_err(ec_err) }) .await From ffd6c052ef6c43243aede33efd8c2731518be29b Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sun, 20 Sep 2026 17:53:49 +0200 Subject: [PATCH 21/26] framework_lib: Decode input deck board IDs per platform family The EC reports the board ID array of EC_CMD_CHECK_DECK_STATE differently per family, but we decoded it as InputModuleType everywhere. Framework 16 (lotus/src/input_module.c) fills all 8 slots with the type of the connected input module. Framework 13 (src/input_module_13.c, only built for sakura) zeroes the array and fills only the touchpad position, with the board version of the touchpad board. So on Framework 13 we reported the board version as a module type. With no touchpad connected the position reads board version 11, which we decoded as InputModuleType::KeyboardB and, because the presence check only excluded Short and Disconnected, reported as "Touchpad present: true". The zeroed slots were reported as a top row of Short modules and a missing hubboard, none of which the EC ever filled in. Decode the array based on the platform family instead: - Framework 13 reports touchpad_board_version, and presence mirrors input_c_deck_detect(): the EC compares against a different threshold depending on whether the input modules are powered. Additionally treat BOARD_VERSION_NOT_INSTALLED and above as absent, which also covers BOARD_VERSION_UNKNOWN (-1) truncated to u8. - The module type fields are None there, rather than reporting the zeroed slots as data. - Framework 16 requires InputModuleType::Touchpad in the touchpad position, like the EC does, instead of accepting any module type. Tested on sakura with no touchpad, a touchpad reporting board version 7 and an older one reporting board version 9. Co-Authored-By: Claude Opus 5 (1M context) --- framework_lib/src/chromium_ec/input_deck.rs | 261 ++++++++++++++++---- framework_lib/src/chromium_ec/mod.rs | 10 +- 2 files changed, 220 insertions(+), 51 deletions(-) diff --git a/framework_lib/src/chromium_ec/input_deck.rs b/framework_lib/src/chromium_ec/input_deck.rs index 812cad6e..48a0fe11 100644 --- a/framework_lib/src/chromium_ec/input_deck.rs +++ b/framework_lib/src/chromium_ec/input_deck.rs @@ -126,6 +126,13 @@ pub enum InputDeckState { /// Manual override: Input deck will follow power sequence, no present check NoDetection, } +impl InputDeckState { + /// Whether the EC is powering the input modules in this state + pub fn modules_powered(&self) -> bool { + matches!(self, InputDeckState::On | InputDeckState::ForceOn) + } +} + impl From for InputDeckState { fn from(item: u8) -> Self { match item { @@ -141,25 +148,75 @@ impl From for InputDeckState { } } +/// Board version that means no board is installed +/// +/// See `BOARD_VERSION_NOT_INSTALLED` in the EC. Values above it can't be a +/// board version at all, they're `BOARD_VERSION_UNKNOWN` (-1) truncated to u8, +/// which the EC returns when it can't decode the ADC channel. +const BOARD_VERSION_NOT_INSTALLED: u8 = 15; +/// Lowest touchpad board version that counts as connected, while the input +/// modules are powered +/// +/// Mirrors `input_c_deck_detect` in the EC. +const TOUCHPAD_BOARD_VERSION_MIN_POWERED: u8 = 1; +/// Highest touchpad board version that counts as connected, while the input +/// modules are not powered +/// +/// Mirrors `input_c_deck_detect` in the EC. An empty connector reads 11. +const TOUCHPAD_BOARD_VERSION_MAX_UNPOWERED: u8 = 10; + +/// Whether a Framework 13 touchpad board counts as connected +/// +/// On Framework 13 the EC reports the board version of the touchpad board and +/// compares it against a different threshold depending on whether the input +/// modules are currently powered, because the board ID pin is pulled +/// differently in each case. +fn touchpad_present_13(board_version: u8, state: InputDeckState) -> bool { + if board_version >= BOARD_VERSION_NOT_INSTALLED { + return false; + } + + if state.modules_powered() { + board_version >= TOUCHPAD_BOARD_VERSION_MIN_POWERED + } else { + board_version <= TOUCHPAD_BOARD_VERSION_MAX_UNPOWERED + } +} + +/// State of the input deck +/// +/// Which fields are filled depends on the platform family, because the EC +/// reports the board ID array differently. Only Framework 16 populates all +/// slots with [`InputModuleType`]. Framework 13 zeroes the array and fills in +/// the board version of the touchpad board at the touchpad position, so the +/// module-type fields would be meaningless there and are left as `None`. #[derive(Clone, PartialEq, Eq, Debug)] #[cfg_attr(feature = "serde", derive(Serialize))] pub struct InputDeckStatus { pub state: InputDeckState, - pub hubboard_present: bool, + /// Whether a touchpad is connected pub touchpad_present: bool, - pub touchpad_id: u8, - pub top_row: TopRowPositions, + /// Framework 16 only, the module type reported for the touchpad position + pub touchpad_module: Option, + /// Framework 13 only, the board version of the touchpad board, `None` if + /// the EC couldn't read it + pub touchpad_board_version: Option, + /// Framework 16 only, whether the hubboard is connected + pub hubboard_present: Option, + /// Framework 16 only, the modules in the five top row positions + pub top_row: Option, } impl InputDeckStatus { - pub fn top_row_to_array(&self) -> [InputModuleType; TOP_ROW_SLOTS] { - [ - self.top_row.pos0, - self.top_row.pos1, - self.top_row.pos2, - self.top_row.pos3, - self.top_row.pos4, - ] + pub fn top_row_to_array(&self) -> Option<[InputModuleType; TOP_ROW_SLOTS]> { + let top_row = self.top_row.as_ref()?; + Some([ + top_row.pos0, + top_row.pos1, + top_row.pos2, + top_row.pos3, + top_row.pos4, + ]) } /// Whether the input deck is fully populated pub fn fully_populated(&self) -> bool { @@ -167,7 +224,7 @@ impl InputDeckStatus { return false; } - if !self.hubboard_present { + if self.hubboard_present != Some(true) { return false; } @@ -180,36 +237,57 @@ impl InputDeckStatus { pub fn top_row_fully_populated(&self) -> bool { self.top_row_to_array() - .iter() - .map(InputModuleType::size) - .sum::() - == INPUT_DECK_SLOTS + .map(|top_row| { + top_row.iter().map(InputModuleType::size).sum::() == INPUT_DECK_SLOTS + }) + .unwrap_or(false) } -} -impl From for InputDeckStatus { - fn from(item: EcResponseDeckState) -> Self { - let tp_id = InputModuleType::from(item.board_id[InputDeckMux::Touchpad as usize]); - let tp_present = !matches!( - tp_id, - InputModuleType::Short | InputModuleType::Disconnected - ); + /// Decode the EC response for a platform family + /// + /// The board ID array means different things per family, see + /// [`InputDeckStatus`]. + pub fn from_response(item: EcResponseDeckState, family: Option) -> Self { + let state = InputDeckState::from(item.deck_state); + let tp_raw = item.board_id[InputDeckMux::Touchpad as usize]; - InputDeckStatus { - state: InputDeckState::from(item.deck_state), - hubboard_present: matches!( - InputModuleType::from(item.board_id[InputDeckMux::HubBoard as usize],), - InputModuleType::HubBoard - ), - touchpad_present: tp_present, - touchpad_id: item.board_id[InputDeckMux::Touchpad as usize], - top_row: TopRowPositions { - pos0: InputModuleType::from(item.board_id[InputDeckMux::TopRow0 as usize]), - pos1: InputModuleType::from(item.board_id[InputDeckMux::TopRow1 as usize]), - pos2: InputModuleType::from(item.board_id[InputDeckMux::TopRow2 as usize]), - pos3: InputModuleType::from(item.board_id[InputDeckMux::TopRow3 as usize]), - pos4: InputModuleType::from(item.board_id[InputDeckMux::TopRow4 as usize]), - }, + match family { + // Of the Framework 12 and 13 systems only sakura implements the + // host command at all. It reports a board version, not a module + // type, and leaves every other slot zeroed. + Some(PlatformFamily::Framework12) | Some(PlatformFamily::Framework13) => { + InputDeckStatus { + state, + touchpad_present: touchpad_present_13(tp_raw, state), + touchpad_module: None, + touchpad_board_version: (tp_raw <= BOARD_VERSION_NOT_INSTALLED).then_some(tp_raw), + hubboard_present: None, + top_row: None, + } + } + _ => { + let tp_module = InputModuleType::from(tp_raw); + + InputDeckStatus { + state, + // The EC only powers the deck when this position reports a + // touchpad, anything else is a module in the wrong slot + touchpad_present: matches!(tp_module, InputModuleType::Touchpad), + touchpad_module: Some(tp_module), + touchpad_board_version: None, + hubboard_present: Some(matches!( + InputModuleType::from(item.board_id[InputDeckMux::HubBoard as usize],), + InputModuleType::HubBoard + )), + top_row: Some(TopRowPositions { + pos0: InputModuleType::from(item.board_id[InputDeckMux::TopRow0 as usize]), + pos1: InputModuleType::from(item.board_id[InputDeckMux::TopRow1 as usize]), + pos2: InputModuleType::from(item.board_id[InputDeckMux::TopRow2 as usize]), + pos3: InputModuleType::from(item.board_id[InputDeckMux::TopRow3 as usize]), + pos4: InputModuleType::from(item.board_id[InputDeckMux::TopRow4 as usize]), + }), + } + } } } } @@ -390,13 +468,13 @@ pub fn print_inputdeck_status(info: &InputDeckInfo) { if let Some(sleep_l) = info.sleep_l { println!("SLEEP# GPIO high: {}", sleep_l); } - if let Some(status) = &info.deck_status { + if let Some(top_row) = info.deck_status.as_ref().and_then(|s| s.top_row.as_ref()) { println!("Positions:"); - println!(" Pos 0: {:?}", status.top_row.pos0); - println!(" Pos 1: {:?}", status.top_row.pos1); - println!(" Pos 2: {:?}", status.top_row.pos2); - println!(" Pos 3: {:?}", status.top_row.pos3); - println!(" Pos 4: {:?}", status.top_row.pos4); + println!(" Pos 0: {:?}", top_row.pos0); + println!(" Pos 1: {:?}", top_row.pos1); + println!(" Pos 2: {:?}", top_row.pos2); + println!(" Pos 3: {:?}", top_row.pos3); + println!(" Pos 4: {:?}", top_row.pos4); } } Some(PlatformFamily::Framework12) | Some(PlatformFamily::Framework13) => { @@ -416,15 +494,22 @@ pub fn print_inputdeck_status(info: &InputDeckInfo) { if let Some(status) = &info.deck_status { println!(" Deck State: {:?}", status.state); println!(" Touchpad present: {}", status.touchpad_present); + if let Some(board_version) = status.touchpad_board_version { + println!(" Board Version {}", board_version); + } } } Some(PlatformFamily::FrameworkDesktop) | None => { if let Some(status) = &info.deck_status { println!(" Deck State: {:?}", status.state); - println!( - " Touchpad present: {} ({})", - status.touchpad_present, status.touchpad_id - ); + if let Some(module) = status.touchpad_module { + println!( + " Touchpad present: {} ({:?})", + status.touchpad_present, module + ); + } else { + println!(" Touchpad present: {}", status.touchpad_present); + } } else { println!(" Unable to tell"); } @@ -436,6 +521,84 @@ pub fn print_inputdeck_status(info: &InputDeckInfo) { mod tests { use super::*; + fn deck_response(touchpad: u8, deck_state: u8) -> EcResponseDeckState { + let mut board_id = [0; INPUT_DECK_SLOTS]; + board_id[InputDeckMux::Touchpad as usize] = touchpad; + EcResponseDeckState { + board_id, + deck_state, + } + } + + /// Framework 13 reports the board version of the touchpad board, not a + /// module type, and zeroes every other slot + #[test] + fn decode_deck_state_13() { + let family = Some(PlatformFamily::Framework13); + + // Touchpad removed. The empty connector reads board version 11 while + // the modules aren't powered, which the EC treats as not connected. + let removed = InputDeckStatus::from_response(deck_response(11, 1), family); + assert_eq!(removed.state, InputDeckState::Disconnected); + assert!(!removed.touchpad_present); + assert_eq!(removed.touchpad_board_version, Some(11)); + + // Touchpad installed, modules powered, reads board version 7 + let installed = InputDeckStatus::from_response(deck_response(7, 3), family); + assert_eq!(installed.state, InputDeckState::On); + assert!(installed.touchpad_present); + assert_eq!(installed.touchpad_board_version, Some(7)); + + // The module type fields are meaningless on Framework 13 + for status in [&removed, &installed] { + assert_eq!(status.touchpad_module, None); + assert_eq!(status.hubboard_present, None); + assert_eq!(status.top_row, None); + assert!(!status.top_row_fully_populated()); + assert!(!status.fully_populated()); + } + + // Undefined board version, below the powered threshold + let undefined = InputDeckStatus::from_response(deck_response(0, 3), family); + assert!(!undefined.touchpad_present); + + // Not installed, and the EC failing to decode the ADC channel, which + // it reports as BOARD_VERSION_UNKNOWN (-1) truncated to u8 + for (raw, expected) in [(15, Some(15)), (255, None)] { + let status = InputDeckStatus::from_response(deck_response(raw, 3), family); + assert!(!status.touchpad_present); + assert_eq!(status.touchpad_board_version, expected); + } + } + + /// Framework 16 reports the type of the connected module in every slot + #[test] + fn decode_deck_state_16() { + let family = Some(PlatformFamily::Framework16); + + let installed = InputDeckStatus::from_response(deck_response(13, 3), family); + assert!(installed.touchpad_present); + assert_eq!(installed.touchpad_module, Some(InputModuleType::Touchpad)); + assert_eq!(installed.touchpad_board_version, None); + assert_eq!(installed.hubboard_present, Some(false)); + + // Only a touchpad counts, a module in the wrong slot doesn't. 11 is + // what a Framework 13 reads with no touchpad connected. + for raw in [0, 11, 15] { + let status = InputDeckStatus::from_response(deck_response(raw, 3), family); + assert!(!status.touchpad_present); + } + + let mut response = deck_response(13, 3); + response.board_id[InputDeckMux::HubBoard as usize] = InputModuleType::HubBoard as u8; + let status = InputDeckStatus::from_response(response, family); + assert_eq!(status.hubboard_present, Some(true)); + assert_eq!( + status.top_row_to_array(), + Some([InputModuleType::Short; TOP_ROW_SLOTS]) + ); + } + #[test] fn format_daughterboards() { let present = Daughterboard { diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index fe699713..2c7828dd 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -651,13 +651,19 @@ impl CrosEc { } .send_command(self)?; - Ok(InputDeckStatus::from(status)) + Ok(InputDeckStatus::from_response( + status, + crate::smbios::get_family(), + )) } pub fn set_input_deck_mode(&self, mode: DeckStateMode) -> EcResult { let status = EcRequestDeckState { mode }.send_command(self)?; - Ok(InputDeckStatus::from(status)) + Ok(InputDeckStatus::from_response( + status, + crate::smbios::get_family(), + )) } /// Change the keyboard baclight brightness From 0fea2f963e80195d7aa5e30c5b00c2bfd56b4cd8 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sun, 20 Sep 2026 17:57:21 +0200 Subject: [PATCH 22/26] framework_lib: Read board ID ADC channels only once We sampled a daughterboard's board ID channel twice: once to decode the board ID and a second time in daughterboard() for the raw reading. With no board connected the pin floats, so the two samples differed and we printed a board ID next to millivolts it wasn't decoded from. On a Framework 13 with the touchpad removed: Touchpad: Present (3) ADC Value 0000mV Split decoding out of reading into decode_board_id() and read the channel once, so the reported board ID and the reported millivolts always come from the same sample. The same case now reads: Touchpad: Missing ADC Value 0000mV This also fixes the raw reading on Intel 11th-13th Gen, which selected the channel from FrameworkHx20Hx30Adc but then read the millivolts from the Framework13Adc channel. Channel and threshold table are now picked together. Note that a board ID that can't be decoded no longer fails the whole command. It's logged and reported as missing, so the reading that couldn't be decoded is still shown. Tested on sakura with no touchpad, a touchpad reporting board version 7 and an older one reporting board version 9. Co-Authored-By: Claude Opus 5 (1M context) --- framework_lib/src/chromium_ec/input_deck.rs | 64 +++++++++------ framework_lib/src/chromium_ec/mod.rs | 90 ++++++++++++--------- 2 files changed, 91 insertions(+), 63 deletions(-) diff --git a/framework_lib/src/chromium_ec/input_deck.rs b/framework_lib/src/chromium_ec/input_deck.rs index 48a0fe11..63513d0a 100644 --- a/framework_lib/src/chromium_ec/input_deck.rs +++ b/framework_lib/src/chromium_ec/input_deck.rs @@ -4,7 +4,10 @@ use alloc::string::{String, ToString}; use serde::Serialize; use super::commands::EcResponseDeckState; -use super::{CrosEc, EcResult, Framework12Adc, Framework13Adc, FrameworkHx20Hx30Adc}; +use super::{ + decode_board_id, CrosEc, EcResult, Framework12Adc, Framework13Adc, FrameworkHx20Hx30Adc, + BOARD_VERSION, BOARD_VERSION_COUNT, BOARD_VERSION_NPC_DB, +}; use crate::smbios; use crate::util::{Platform, PlatformFamily}; @@ -353,10 +356,24 @@ pub struct InputDeckInfo { } impl CrosEc { - fn daughterboard(&self, board_id: Option, adc_channel: u8) -> Daughterboard { + /// Read a daughterboard's board ID channel + /// + /// Reads the channel once and decodes that same reading, so that board_id + /// and adc_mv can't disagree. They did when the channel was sampled twice: + /// a disconnected board leaves the pin floating, so the two samples + /// differed and we reported a board ID next to millivolts it didn't come + /// from. + fn daughterboard(&self, adc_channel: u8, table: [i32; BOARD_VERSION_COUNT]) -> Daughterboard { + let adc_mv = self.adc_read(adc_channel).ok(); Daughterboard { - board_id, - adc_mv: self.adc_read(adc_channel).ok(), + board_id: adc_mv.and_then(|mv| match decode_board_id(mv, table) { + Ok(board_id) => board_id, + Err(err) => { + log::debug!("ADC channel {}: {:?}", adc_channel, err); + None + } + }), + adc_mv, } } @@ -390,38 +407,37 @@ impl CrosEc { match family { Some(PlatformFamily::Framework12) => { info.chassis_closed = Some(!self.get_intrusion_status()?.currently_open); - let pwrbtn = self.read_board_id_npc_db(Framework12Adc::PowerButtonBoardId as u8)?; - let audio = self.read_board_id_npc_db(Framework12Adc::AudioBoardId as u8)?; - let tp = self.read_board_id_npc_db(Framework12Adc::TouchpadBoardId as u8)?; - info.power_button_board = - Some(self.daughterboard(pwrbtn, Framework12Adc::PowerButtonBoardId as u8)); - info.audio_board = - Some(self.daughterboard(audio, Framework12Adc::AudioBoardId as u8)); - info.touchpad_board = - Some(self.daughterboard(tp, Framework12Adc::TouchpadBoardId as u8)); + info.power_button_board = Some(self.daughterboard( + Framework12Adc::PowerButtonBoardId as u8, + BOARD_VERSION_NPC_DB, + )); + info.audio_board = Some( + self.daughterboard(Framework12Adc::AudioBoardId as u8, BOARD_VERSION_NPC_DB), + ); + info.touchpad_board = Some( + self.daughterboard(Framework12Adc::TouchpadBoardId as u8, BOARD_VERSION_NPC_DB), + ); info.deck_status = self.get_input_deck_status().ok(); } Some(PlatformFamily::Framework13) => { info.chassis_closed = Some(!self.get_intrusion_status()?.currently_open); - let (audio, tp) = match smbios::get_platform() { + let (audio_channel, touchpad_channel, table) = match smbios::get_platform() { Some(Platform::IntelGen11) | Some(Platform::IntelGen12) | Some(Platform::IntelGen13) => ( - self.read_board_id(FrameworkHx20Hx30Adc::AudioBoardId as u8)?, - self.read_board_id(FrameworkHx20Hx30Adc::TouchpadBoardId as u8)?, + FrameworkHx20Hx30Adc::AudioBoardId as u8, + FrameworkHx20Hx30Adc::TouchpadBoardId as u8, + BOARD_VERSION, ), _ => ( - self.read_board_id_npc_db(Framework13Adc::AudioBoardId as u8)?, - self.read_board_id_npc_db(Framework13Adc::TouchpadBoardId as u8)?, + Framework13Adc::AudioBoardId as u8, + Framework13Adc::TouchpadBoardId as u8, + BOARD_VERSION_NPC_DB, ), }; - // TODO: On Intel 11th-13th Gen the ADC channels differ, the - // raw reading below comes from the wrong channel there - info.audio_board = - Some(self.daughterboard(audio, Framework13Adc::AudioBoardId as u8)); - info.touchpad_board = - Some(self.daughterboard(tp, Framework13Adc::TouchpadBoardId as u8)); + info.audio_board = Some(self.daughterboard(audio_channel, table)); + info.touchpad_board = Some(self.daughterboard(touchpad_channel, table)); info.deck_status = self.get_input_deck_status().ok(); } Some(PlatformFamily::Framework16) => { diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index 2c7828dd..acc82eca 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -228,6 +228,40 @@ const BOARD_VERSION_NPC_DB: [i32; BOARD_VERSION_COUNT] = [ 85, 233, 360, 492, 649, 844, 965, 1094, 1380, 1562, 1710, 2040, 2197, 2557, 2766, 2814, ]; +/// Decode a board ID ADC reading in mV into a board version +/// +/// `Ok(None)` means no board is connected. Split out from reading the channel +/// so that a caller can report the reading it decoded, instead of sampling the +/// same channel twice and reporting two different samples. +pub(crate) fn decode_board_id( + mv: i32, + table: [i32; BOARD_VERSION_COUNT], +) -> EcResult> { + if mv < 0 { + return Err(EcError::DeviceError(format!( + "Failed to read board ID ADC, got {}mv", + mv + ))); + } + + for (board_id, board_id_res) in table.iter().enumerate() { + if mv < *board_id_res { + debug!("Board ID {} from {}mv", board_id, mv); + // 15 is not present, less than 2 is undefined + return Ok(if board_id == 15 || board_id < 2 { + None + } else { + Some(board_id as u8) + }); + } + } + + Err(EcError::DeviceError(format!( + "Unknown board id. ADC mv: {}", + mv + ))) +} + pub trait CrosEcDriver { fn read_memory(&self, offset: u16, length: u16) -> Option>; fn send_command(&self, command: u16, command_version: u8, data: &[u8]) -> EcResult>; @@ -1833,45 +1867,6 @@ impl CrosEc { Ok(res.adc_value) } - fn read_board_id(&self, channel: u8) -> EcResult> { - self.read_board_id_raw(channel, BOARD_VERSION) - } - fn read_board_id_npc_db(&self, channel: u8) -> EcResult> { - self.read_board_id_raw(channel, BOARD_VERSION_NPC_DB) - } - - fn read_board_id_raw( - &self, - channel: u8, - table: [i32; BOARD_VERSION_COUNT], - ) -> EcResult> { - let mv = self.adc_read(channel)?; - if mv < 0 { - return Err(EcError::DeviceError(format!( - "Failed to read ADC channel {}", - channel - ))); - } - - debug!("ADC Channel {} - Measured {}mv", channel, mv); - for (board_id, board_id_res) in table.iter().enumerate() { - if mv < *board_id_res { - debug!("ADC Channel {} - Board ID {}", channel, board_id); - // 15 is not present, less than 2 is undefined - return Ok(if board_id == 15 || board_id < 2 { - None - } else { - Some(board_id as u8) - }); - } - } - - Err(EcError::DeviceError(format!( - "Unknown board id. ADC mv: {}", - mv - ))) - } - pub fn rgbkbd_set_color(&self, start_key: u8, colors: Vec) -> EcResult<()> { for (chunk, colors) in colors.chunks(EC_RGBKBD_MAX_KEY_COUNT).enumerate() { let mut request = EcRequestRgbKbdSetColor { @@ -2456,4 +2451,21 @@ mod tests { vec![EcResetFlag::Brownout, EcResetFlag::Watchdog] ); } + + #[test] + fn board_id_from_adc() { + // Readings measured on a Framework 13 (sakura) + assert_eq!(decode_board_id(1042, BOARD_VERSION_NPC_DB), Ok(Some(7))); + assert_eq!(decode_board_id(1058, BOARD_VERSION_NPC_DB), Ok(Some(7))); + // An older touchpad + assert_eq!(decode_board_id(1471, BOARD_VERSION_NPC_DB), Ok(Some(9))); + + // Nothing connected, the pin floats. Board ID 0 and 1 are undefined. + assert_eq!(decode_board_id(0, BOARD_VERSION_NPC_DB), Ok(None)); + assert_eq!(decode_board_id(200, BOARD_VERSION_NPC_DB), Ok(None)); + + // Above the whole table, and a failed read + assert!(decode_board_id(3300, BOARD_VERSION_NPC_DB).is_err()); + assert!(decode_board_id(-1, BOARD_VERSION_NPC_DB).is_err()); + } } From 28ca27b56e69e2ea5c14a9ae038c9fa47a6e3c09 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Mon, 21 Sep 2026 13:26:08 +0200 Subject: [PATCH 23/26] --boardid: Print voltage Signed-off-by: Daniel Schaefer --- framework_lib/src/chromium_ec/input_deck.rs | 53 +++++++----------- framework_lib/src/chromium_ec/mod.rs | 59 +++++++++++++++++++-- framework_lib/src/commandline/mod.rs | 42 ++++++++++----- 3 files changed, 103 insertions(+), 51 deletions(-) diff --git a/framework_lib/src/chromium_ec/input_deck.rs b/framework_lib/src/chromium_ec/input_deck.rs index 63513d0a..2cccb2d5 100644 --- a/framework_lib/src/chromium_ec/input_deck.rs +++ b/framework_lib/src/chromium_ec/input_deck.rs @@ -3,13 +3,10 @@ use alloc::string::{String, ToString}; #[cfg(feature = "serde")] use serde::Serialize; -use super::commands::EcResponseDeckState; -use super::{ - decode_board_id, CrosEc, EcResult, Framework12Adc, Framework13Adc, FrameworkHx20Hx30Adc, - BOARD_VERSION, BOARD_VERSION_COUNT, BOARD_VERSION_NPC_DB, -}; +use super::commands::{BoardIdType, EcResponseDeckState}; +use super::{board_id_adc_channel, board_version_table, decode_board_id, CrosEc, EcResult}; use crate::smbios; -use crate::util::{Platform, PlatformFamily}; +use crate::util::PlatformFamily; /// The number of slots on the input deck, where modules can be connected to pub const INPUT_DECK_SLOTS: usize = 8; @@ -263,7 +260,8 @@ impl InputDeckStatus { state, touchpad_present: touchpad_present_13(tp_raw, state), touchpad_module: None, - touchpad_board_version: (tp_raw <= BOARD_VERSION_NOT_INSTALLED).then_some(tp_raw), + touchpad_board_version: (tp_raw <= BOARD_VERSION_NOT_INSTALLED) + .then_some(tp_raw), hubboard_present: None, top_row: None, } @@ -363,7 +361,14 @@ impl CrosEc { /// a disconnected board leaves the pin floating, so the two samples /// differed and we reported a board ID next to millivolts it didn't come /// from. - fn daughterboard(&self, adc_channel: u8, table: [i32; BOARD_VERSION_COUNT]) -> Daughterboard { + fn daughterboard(&self, board_id_type: BoardIdType) -> Daughterboard { + let Some(adc_channel) = board_id_adc_channel(board_id_type) else { + return Daughterboard { + board_id: None, + adc_mv: None, + }; + }; + let table = board_version_table(); let adc_mv = self.adc_read(adc_channel).ok(); Daughterboard { board_id: adc_mv.and_then(|mv| match decode_board_id(mv, table) { @@ -407,37 +412,15 @@ impl CrosEc { match family { Some(PlatformFamily::Framework12) => { info.chassis_closed = Some(!self.get_intrusion_status()?.currently_open); - info.power_button_board = Some(self.daughterboard( - Framework12Adc::PowerButtonBoardId as u8, - BOARD_VERSION_NPC_DB, - )); - info.audio_board = Some( - self.daughterboard(Framework12Adc::AudioBoardId as u8, BOARD_VERSION_NPC_DB), - ); - info.touchpad_board = Some( - self.daughterboard(Framework12Adc::TouchpadBoardId as u8, BOARD_VERSION_NPC_DB), - ); + info.power_button_board = Some(self.daughterboard(BoardIdType::PowerButtonBoard)); + info.audio_board = Some(self.daughterboard(BoardIdType::AudioBoard)); + info.touchpad_board = Some(self.daughterboard(BoardIdType::Touchpad)); info.deck_status = self.get_input_deck_status().ok(); } Some(PlatformFamily::Framework13) => { info.chassis_closed = Some(!self.get_intrusion_status()?.currently_open); - let (audio_channel, touchpad_channel, table) = match smbios::get_platform() { - Some(Platform::IntelGen11) - | Some(Platform::IntelGen12) - | Some(Platform::IntelGen13) => ( - FrameworkHx20Hx30Adc::AudioBoardId as u8, - FrameworkHx20Hx30Adc::TouchpadBoardId as u8, - BOARD_VERSION, - ), - - _ => ( - Framework13Adc::AudioBoardId as u8, - Framework13Adc::TouchpadBoardId as u8, - BOARD_VERSION_NPC_DB, - ), - }; - info.audio_board = Some(self.daughterboard(audio_channel, table)); - info.touchpad_board = Some(self.daughterboard(touchpad_channel, table)); + info.audio_board = Some(self.daughterboard(BoardIdType::AudioBoard)); + info.touchpad_board = Some(self.daughterboard(BoardIdType::Touchpad)); info.deck_status = self.get_input_deck_status().ok(); } Some(PlatformFamily::Framework16) => { diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index acc82eca..2a1f1fc4 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -15,6 +15,7 @@ use crate::os_specific; use crate::power; use crate::smbios; use crate::util; +use crate::util::{Platform, PlatformFamily}; use no_std_compat::time::Duration; @@ -228,15 +229,65 @@ const BOARD_VERSION_NPC_DB: [i32; BOARD_VERSION_COUNT] = [ 85, 233, 360, 492, 649, 844, 965, 1094, 1380, 1562, 1710, 2040, 2197, 2557, 2766, 2814, ]; +/// ADC channel a board ID type is wired to on this platform +/// +/// The host command decodes the board ID itself, but not the voltage it came +/// from. To report both, we have to know which channel the EC read, and the +/// channel numbering differs per platform. `None` means the platform has no +/// such board, or we don't know which platform this is. +pub fn board_id_adc_channel(board_id_type: BoardIdType) -> Option { + match smbios::get_family()? { + PlatformFamily::Framework12 => match board_id_type { + BoardIdType::Mainboard => Some(Framework12Adc::MainboardBoardId as u8), + BoardIdType::PowerButtonBoard => Some(Framework12Adc::PowerButtonBoardId as u8), + BoardIdType::Touchpad => Some(Framework12Adc::TouchpadBoardId as u8), + BoardIdType::AudioBoard => Some(Framework12Adc::AudioBoardId as u8), + _ => None, + }, + PlatformFamily::Framework13 => { + let hx = matches!( + smbios::get_platform(), + Some(Platform::IntelGen11 | Platform::IntelGen12 | Platform::IntelGen13) + ); + match (board_id_type, hx) { + (BoardIdType::Mainboard, true) => { + Some(FrameworkHx20Hx30Adc::MainboardBoardId as u8) + } + (BoardIdType::Touchpad, true) => Some(FrameworkHx20Hx30Adc::TouchpadBoardId as u8), + (BoardIdType::AudioBoard, true) => Some(FrameworkHx20Hx30Adc::AudioBoardId as u8), + (BoardIdType::Mainboard, false) => Some(Framework13Adc::MainboardBoardId as u8), + (BoardIdType::Touchpad, false) => Some(Framework13Adc::TouchpadBoardId as u8), + (BoardIdType::AudioBoard, false) => Some(Framework13Adc::AudioBoardId as u8), + _ => None, + } + } + PlatformFamily::Framework16 => match board_id_type { + BoardIdType::Mainboard => Some(Framework16Adc::MainboardBoardId as u8), + BoardIdType::DGpu0 => Some(Framework16Adc::GpuBoardId0 as u8), + BoardIdType::DGpu1 => Some(Framework16Adc::GpuBoardId1 as u8), + _ => None, + }, + PlatformFamily::FrameworkDesktop => None, + } +} + +/// Thresholds for decoding a board ID ADC reading on this platform +/// +/// The hx20/hx30 EC uses an evenly spaced ladder, every Zephyr EC since uses +/// the table in `zephyr/program/framework/src/adc.c`. +pub(crate) fn board_version_table() -> [i32; BOARD_VERSION_COUNT] { + match smbios::get_platform() { + Some(Platform::IntelGen11 | Platform::IntelGen12 | Platform::IntelGen13) => BOARD_VERSION, + _ => BOARD_VERSION_NPC_DB, + } +} + /// Decode a board ID ADC reading in mV into a board version /// /// `Ok(None)` means no board is connected. Split out from reading the channel /// so that a caller can report the reading it decoded, instead of sampling the /// same channel twice and reporting two different samples. -pub(crate) fn decode_board_id( - mv: i32, - table: [i32; BOARD_VERSION_COUNT], -) -> EcResult> { +pub(crate) fn decode_board_id(mv: i32, table: [i32; BOARD_VERSION_COUNT]) -> EcResult> { if mv < 0 { return Err(EcError::DeviceError(format!( "Failed to read board ID ADC, got {}mv", diff --git a/framework_lib/src/commandline/mod.rs b/framework_lib/src/commandline/mod.rs index 1cd37bf0..f1d5c1ba 100644 --- a/framework_lib/src/commandline/mod.rs +++ b/framework_lib/src/commandline/mod.rs @@ -2292,31 +2292,49 @@ fn hash(data: &[u8]) { util::print_buffer(sha512); } +/// Format a board ID together with the ADC voltage it was decoded from +/// +/// The voltage is a second sample of the same channel, so it can differ from +/// the one the EC decoded, but it's what tells apart a solid reading from one +/// sitting on a threshold. +fn format_board_id(ec: &CrosEc, board_id_type: BoardIdType) -> String { + let board_id = match ec.read_board_id_hc(board_id_type) { + Ok(Some(board_id)) => format!("{}", board_id), + Ok(None) => "Not present".to_string(), + Err(err) => return format!("{:?}", err), + }; + + match chromium_ec::board_id_adc_channel(board_id_type).map(|ch| ec.adc_read(ch)) { + Some(Ok(mv)) => format!("{} ({}mV)", board_id, mv), + _ => board_id, + } +} + fn print_board_ids(ec: &CrosEc) { println!("Board IDs"); println!( - " Mainboard: {:?}", - ec.read_board_id_hc(BoardIdType::Mainboard) + " Mainboard: {}", + format_board_id(ec, BoardIdType::Mainboard) ); println!( - " PowerButton: {:?}", - ec.read_board_id_hc(BoardIdType::PowerButtonBoard) + " PowerButton: {}", + format_board_id(ec, BoardIdType::PowerButtonBoard) ); println!( - " Touchpad: {:?}", - ec.read_board_id_hc(BoardIdType::Touchpad) + " Touchpad: {}", + format_board_id(ec, BoardIdType::Touchpad) ); println!( - " AudioBoard: {:?}", - ec.read_board_id_hc(BoardIdType::AudioBoard) + " AudioBoard: {}", + format_board_id(ec, BoardIdType::AudioBoard) ); println!( - " dGPU0: {:?}", - ec.read_board_id_hc(BoardIdType::DGpu0) + " dGPU0: {}", + format_board_id(ec, BoardIdType::DGpu0) ); println!( - " dGPU1: {:?}", - ec.read_board_id_hc(BoardIdType::DGpu1) + " dGPU1: {}", + format_board_id(ec, BoardIdType::DGpu1) ); } From 61a1a70862d7b6ce725c755293ae34e5b51c985c Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 22 Sep 2026 13:15:49 +0200 Subject: [PATCH 24/26] nix: Add framework_mcp packages Parametrize the tool build functions by cargo package so the MCP server can reuse them, and add mcp, mcp-debug and mcp-windows outputs plus a `nix run .#mcp` app. The release build is part of `nix flake check`. Co-Authored-By: Claude Fable 5.1 --- flake.nix | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/flake.nix b/flake.nix index fe8d0731..8b0b2fc3 100644 --- a/flake.nix +++ b/flake.nix @@ -68,6 +68,7 @@ "framework_lib" "framework_tool" "framework_uefi" + "framework_mcp" "res" ".cargo" ]; @@ -83,14 +84,15 @@ isIncludedRoot || builtins.elem baseName includedFiles; }; - # Build function for the CLI tool (Linux/macOS) - buildFrameworkTool = { release ? false, features ? [] }: + # Build function for the CLI tool and the MCP server (Linux/macOS) + # `package` is the cargo package and binary name + buildFrameworkTool = { release ? false, features ? [], package ? "framework_tool" }: let profile = if release then "release" else "debug"; featuresStr = if features == [] then "" else "--features ${builtins.concatStringsSep "," features}"; in rustPlatform.buildRustPackage { - pname = "framework_tool"; + pname = package; version = "0.6.6"; src = buildSrc; @@ -101,12 +103,12 @@ buildType = profile; - # Build only the tool, not the UEFI package + # Build only the requested package, not the UEFI package buildPhase = '' runHook preBuild cargo build \ ${if release then "--release" else ""} \ - -p framework_tool \ + -p ${package} \ ${featuresStr} runHook postBuild ''; @@ -121,7 +123,7 @@ installPhase = '' runHook preInstall mkdir -p $out/bin - cp target/${profile}/framework_tool $out/bin/ + cp target/${profile}/${package} $out/bin/ runHook postInstall ''; @@ -138,12 +140,12 @@ mingwPthreads = pkgs.pkgsCross.mingwW64.windows.pthreads; # Build function for Windows cross-compilation (Linux -> Windows) - buildFrameworkToolWindows = { release ? false }: + buildFrameworkToolWindows = { release ? false, package ? "framework_tool" }: let profile = if release then "release" else "debug"; in rustPlatformWindows.buildRustPackage { - pname = "framework_tool"; + pname = package; version = "0.6.6"; src = buildSrc; @@ -163,7 +165,7 @@ cargo build \ ${if release then "--release" else ""} \ --target x86_64-pc-windows-gnu \ - -p framework_tool + -p ${package} runHook postBuild ''; @@ -173,7 +175,7 @@ installPhase = '' runHook preInstall mkdir -p $out/bin - cp target/x86_64-pc-windows-gnu/${profile}/framework_tool.exe $out/bin/ + cp target/x86_64-pc-windows-gnu/${profile}/${package}.exe $out/bin/ runHook postInstall ''; @@ -244,6 +246,9 @@ framework-uefi-release = buildFrameworkUefi { release = true; }; framework-tool-windows = buildFrameworkToolWindows { release = true; }; framework-tool-windows-debug = buildFrameworkToolWindows { release = false; }; + framework-mcp-debug = buildFrameworkTool { release = false; package = "framework_mcp"; }; + framework-mcp-release = buildFrameworkTool { release = true; package = "framework_mcp"; }; + framework-mcp-windows = buildFrameworkToolWindows { release = true; package = "framework_mcp"; }; # Wrapper script to run the UEFI build in an emulator run-qemu = pkgs.writeShellScriptBin "run-framework-uefi-qemu" '' @@ -310,7 +315,7 @@ in { checks = { - inherit framework-tool-release framework-uefi-release; + inherit framework-tool-release framework-uefi-release framework-mcp-release; }; packages = { @@ -321,6 +326,9 @@ uefi-debug = framework-uefi-debug; windows = framework-tool-windows; windows-debug = framework-tool-windows-debug; + mcp = framework-mcp-release; + mcp-debug = framework-mcp-debug; + mcp-windows = framework-mcp-windows; run-qemu = run-qemu; run-qemu-release = run-qemu-release; }; @@ -329,6 +337,7 @@ apps = { default = flake-utils.lib.mkApp { drv = framework-tool-release; exePath = "/bin/framework_tool"; }; tool = flake-utils.lib.mkApp { drv = framework-tool-release; exePath = "/bin/framework_tool"; }; + mcp = flake-utils.lib.mkApp { drv = framework-mcp-release; exePath = "/bin/framework_mcp"; }; qemu = flake-utils.lib.mkApp { drv = run-qemu; }; qemu-release = flake-utils.lib.mkApp { drv = run-qemu-release; }; }; From f91f5aa6ef9d9a050c6434058febe8ef43439816 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 22 Sep 2026 13:15:49 +0200 Subject: [PATCH 25/26] framework_mcp: Add deb, rpm and snap packaging Package the MCP server as framework-mcp .deb and .rpm alongside the framework-tool packages, with the README and license as documentation, and ship it in the snap as the framework-tool.mcp app. On Windows the release build statically links vcruntime and carries the Framework icon, like framework_tool. Co-Authored-By: Claude Fable 5.1 --- .github/workflows/package.yml | 23 +++++++++++++++-------- Cargo.lock | 2 ++ framework_mcp/Cargo.toml | 34 ++++++++++++++++++++++++++++++++++ framework_mcp/build.rs | 18 ++++++++++++++++++ snap/snapcraft.yaml | 5 +++++ 5 files changed, 74 insertions(+), 8 deletions(-) create mode 100644 framework_mcp/build.rs diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml index 8fc71c61..7a4f0199 100644 --- a/.github/workflows/package.yml +++ b/.github/workflows/package.yml @@ -29,7 +29,10 @@ jobs: - name: Build .deb package run: cargo deb -p framework_tool - - name: Upload .deb package + - name: Build MCP server .deb package + run: cargo deb -p framework_mcp + + - name: Upload .deb packages uses: actions/upload-artifact@v7 with: name: framework-tool-deb @@ -54,16 +57,20 @@ jobs: - name: Install cargo-generate-rpm run: cargo install cargo-generate-rpm - - name: Build release binary - run: cargo build -p framework_tool --release --features nvidia + - name: Build release binaries + run: | + cargo build -p framework_tool --release --features nvidia + cargo build -p framework_mcp --release - - name: Strip binary - run: strip -s target/release/framework_tool + - name: Strip binaries + run: strip -s target/release/framework_tool target/release/framework_mcp - - name: Build .rpm package - run: cargo generate-rpm -p framework_tool + - name: Build .rpm packages + run: | + cargo generate-rpm -p framework_tool + cargo generate-rpm -p framework_mcp - - name: Upload .rpm package + - name: Upload .rpm packages uses: actions/upload-artifact@v7 with: name: framework-tool-rpm diff --git a/Cargo.lock b/Cargo.lock index 77b49576..dce16d62 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -566,7 +566,9 @@ dependencies = [ "rmcp", "serde", "serde_json", + "static_vcruntime", "tokio", + "winresource", ] [[package]] diff --git a/framework_mcp/Cargo.toml b/framework_mcp/Cargo.toml index 4b0c6ba6..983c7ddc 100644 --- a/framework_mcp/Cargo.toml +++ b/framework_mcp/Cargo.toml @@ -9,6 +9,7 @@ license = "BSD-3-Clause" edition = "2021" # rmcp needs a newer compiler than framework_lib rust-version = "1.88" +build = "build.rs" [[bin]] name = "framework_mcp" @@ -27,3 +28,36 @@ dmidecode = { version = "1", default-features = false } [target.'cfg(unix)'.dependencies] nix = { version = "0.30", features = ["user"] } + +[build-dependencies] +static_vcruntime = "3.0" +winresource = "0.1.17" + +[package.metadata.deb] +name = "framework-mcp" +maintainer = "Framework Computer Inc " +depends = "libudev1" +section = "utils" +priority = "optional" +extended-description = """\ +MCP (Model Context Protocol) server that gives AI assistants read-only \ +access to the hardware state of a Framework Computer system: battery and \ +charger, USB-C PD ports, temperatures and fans, sensors, switches, firmware \ +versions and Embedded Controller diagnostics. Needs root, see the README \ +for how to configure your MCP client.""" +assets = [ + ["target/release/framework_mcp", "usr/bin/", "755"], + ["README.md", "usr/share/doc/framework-mcp/README.md", "644"], + ["../LICENSE.md", "usr/share/doc/framework-mcp/LICENSE.md", "644"], +] + +[package.metadata.generate-rpm] +name = "framework-mcp" +assets = [ + { source = "target/release/framework_mcp", dest = "/usr/bin/framework_mcp", mode = "755" }, + { source = "README.md", dest = "/usr/share/doc/framework-mcp/README.md", mode = "644", doc = true }, + { source = "../LICENSE.md", dest = "/usr/share/doc/framework-mcp/LICENSE.md", mode = "644", doc = true }, +] + +[package.metadata.generate-rpm.requires] +systemd-libs = "*" diff --git a/framework_mcp/build.rs b/framework_mcp/build.rs new file mode 100644 index 00000000..dda2dd3e --- /dev/null +++ b/framework_mcp/build.rs @@ -0,0 +1,18 @@ +fn main() { + // Add app icon + if std::env::var_os("CARGO_CFG_WINDOWS").is_some() { + winresource::WindowsResource::new() + .set_icon("../res/framework_startmenuicon.ico") + .compile() + .unwrap(); + } + + let is_msvc = std::env::var("CARGO_CFG_TARGET_ENV") + .map(|v| v == "msvc") + .unwrap_or(false); + + if !cfg!(debug_assertions) && is_msvc { + // Statically link vcruntime to allow running on clean install + static_vcruntime::metabuild(); + } +} diff --git a/snap/snapcraft.yaml b/snap/snapcraft.yaml index f34094eb..a20fa071 100644 --- a/snap/snapcraft.yaml +++ b/snap/snapcraft.yaml @@ -12,6 +12,7 @@ description: | - Expansion card management (HDMI/DP/audio cards) - Framework 16 specific features (input deck, expansion bay) - NVIDIA GPU support + - MCP server for AI assistants (framework-tool.mcp) . Note: Most features require root privileges (sudo framework-tool ...). @@ -42,7 +43,9 @@ parts: override-build: | cd "${CRAFT_PART_SRC}" cargo build --release -p framework_tool --features nvidia + cargo build --release -p framework_mcp install -Dm755 target/release/framework_tool "${CRAFT_PART_INSTALL}/bin/framework_tool" + install -Dm755 target/release/framework_mcp "${CRAFT_PART_INSTALL}/bin/framework_mcp" install -Dm644 "${CRAFT_PART_SRC}/framework_tool/completions/bash/framework_tool" \ "${CRAFT_PART_INSTALL}/share/bash-completion/completions/framework_tool" install -Dm644 "${CRAFT_PART_SRC}/framework_tool/completions/zsh/_framework_tool" \ @@ -53,3 +56,5 @@ parts: apps: framework-tool: command: bin/framework_tool + mcp: + command: bin/framework_mcp From 11de8329b0d6fc55354b1a209772fe6372b6a5f5 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 22 Sep 2026 13:15:49 +0200 Subject: [PATCH 26/26] ci: Build framework_mcp on all platforms Build the MCP server in the Linux, Windows and FreeBSD CI jobs, upload the release binaries as artifacts, and list it in the release checklist and the README installation section. Co-Authored-By: Claude Fable 5.1 --- .github/workflows/ci.yml | 22 ++++++++++++++++++++++ README.md | 2 ++ contrib/release.md | 7 +++++-- 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8071b80f..01bf53af 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,6 +23,7 @@ jobs: run: | cargo build -p framework_lib cargo build -p framework_tool + cargo build -p framework_mcp build: name: Build Linux @@ -70,6 +71,15 @@ jobs: name: framework_tool path: target/release/framework_tool + - name: Build MCP server (Release) + run: cargo build -p framework_mcp --release + + - name: Upload MCP server + uses: actions/upload-artifact@v6 + with: + name: framework_mcp + path: target/release/framework_mcp + - name: Make sure nothing changed (e.g. Cargo.lock) run: git diff --exit-code @@ -174,6 +184,18 @@ jobs: name: framework_tool.exe path: target/release/framework_tool.exe + - name: Build Windows MCP server + run: cargo build -p framework_mcp --release + + - name: Check if Windows MCP server can start + run: ./target/release/framework_mcp.exe --help + + - name: Upload Windows MCP server + uses: actions/upload-artifact@v6 + with: + name: framework_mcp.exe + path: target/release/framework_mcp.exe + test: name: Test Suite diff --git a/README.md b/README.md index 792b0d52..6fd76dc4 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,8 @@ You can find lots of examples in [EXAMPLES.md](./EXAMPLES.md). - Others - Build from source - Or download [latest binary](https://github.com/FrameworkComputer/framework-system/releases/latest/download/framework_tool) +- MCP server for AI assistants (`framework_mcp`, see [framework_mcp/README.md](framework_mcp/README.md)) + - Ships in the .deb/.rpm/snap packages from this repo (`framework-mcp`, `framework-tool.mcp`), `nix run .#mcp`, or `cargo install --locked framework_mcp` - ChromeOS - Build from source - Homebrew diff --git a/contrib/release.md b/contrib/release.md index acb98720..fb6f2a17 100644 --- a/contrib/release.md +++ b/contrib/release.md @@ -2,8 +2,8 @@ 1. Make sure to update all versions in Cargo.toml and Cargo.lock files 2. Tag -3. Download binaries from github action run on tag -4. Sign windows exe with EV cert +3. Download binaries from github action run on tag (framework_tool, framework_mcp, both also .exe, .deb, .rpm) +4. Sign windows exe with EV cert (framework_tool.exe and framework_mcp.exe) 5. Create release on GitHub with release notes and upload binaries 6. Notify distribution maintainers (See README) 7. Do winget release (See below) @@ -41,8 +41,10 @@ Dry run and review included files ``` cargo publish -p framework_lib --dry-run cargo publish -p framework_tool --dry-run +cargo publish -p framework_mcp --dry-run cargo package --list -p framework_lib cargo package --list -p framework_tool +cargo package --list -p framework_mcp ``` Publish @@ -50,6 +52,7 @@ Publish ``` cargo publish -p framework_lib cargo publish -p framework_tool +cargo publish -p framework_mcp ``` ## FreeBSD