Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 25 additions & 13 deletions framework_lib/src/chromium_ec/input_deck.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use super::commands::EcResponseDeckState;
use super::{EcError, EcResult};
use alloc::format;

/// The number of slots on the input deck, where modules can be connected to
pub const INPUT_DECK_SLOTS: usize = 8;
Expand Down Expand Up @@ -49,6 +51,9 @@ pub enum InputModuleType {
Touchpad,
Reserved15,
Disconnected,
/// Board ID that we don't recognize.
/// The EC reports 0xFF if it failed to read the board ID.
Unknown(u8),
}
impl From<u8> for InputModuleType {
fn from(item: u8) -> Self {
Expand All @@ -69,7 +74,7 @@ impl From<u8> for InputModuleType {
13 => Self::Touchpad,
14 => Self::Reserved15,
15 => Self::Disconnected,
_ => panic!("Invalid module type"),
x => Self::Unknown(x),
}
}
}
Expand All @@ -95,6 +100,7 @@ impl InputModuleType {
Self::Touchpad => 0,
Self::Reserved15 => 0,
Self::Disconnected => 0,
Self::Unknown(_) => 0,
}
}
}
Expand All @@ -116,18 +122,20 @@ pub enum InputDeckState {
/// Manual override: Input deck will follow power sequence, no present check
NoDetection,
}
impl From<u8> for InputDeckState {
fn from(item: u8) -> Self {
match item {
impl TryFrom<u8> for InputDeckState {
/// The unknown value
type Error = u8;
fn try_from(item: u8) -> Result<Self, Self::Error> {
Ok(match item {
0 => InputDeckState::Off,
1 => InputDeckState::Disconnected,
2 => InputDeckState::TurningOn,
3 => InputDeckState::On,
4 => InputDeckState::ForceOff,
5 => InputDeckState::ForceOn,
6 => InputDeckState::NoDetection,
_ => panic!("Invalid value"),
}
x => return Err(x),
})
}
}

Expand Down Expand Up @@ -176,18 +184,22 @@ impl InputDeckStatus {
}
}

impl From<EcResponseDeckState> for InputDeckStatus {
fn from(item: EcResponseDeckState) -> Self {
impl TryFrom<EcResponseDeckState> for InputDeckStatus {
type Error = EcError;
fn try_from(item: EcResponseDeckState) -> EcResult<Self> {
let state = InputDeckState::try_from(item.deck_state).map_err(|x| {
EcError::DeviceError(format!("EC reported invalid input deck state {x}"))
})?;
let tp_id = InputModuleType::from(item.board_id[InputDeckMux::Touchpad as usize]);
let tp_present = !matches!(
tp_id,
InputModuleType::Short | InputModuleType::Disconnected
InputModuleType::Short | InputModuleType::Disconnected | InputModuleType::Unknown(_)
);

InputDeckStatus {
state: InputDeckState::from(item.deck_state),
Ok(InputDeckStatus {
state,
hubboard_present: matches!(
InputModuleType::from(item.board_id[InputDeckMux::HubBoard as usize],),
InputModuleType::from(item.board_id[InputDeckMux::HubBoard as usize]),
InputModuleType::HubBoard
),
touchpad_present: tp_present,
Expand All @@ -199,7 +211,7 @@ impl From<EcResponseDeckState> for InputDeckStatus {
pos3: InputModuleType::from(item.board_id[InputDeckMux::TopRow3 as usize]),
pos4: InputModuleType::from(item.board_id[InputDeckMux::TopRow4 as usize]),
},
}
})
}
}

Expand Down
4 changes: 2 additions & 2 deletions framework_lib/src/chromium_ec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -651,7 +651,7 @@ impl CrosEc {
}
.send_command(self)?;

Ok(InputDeckStatus::from(status))
InputDeckStatus::try_from(status)
}

pub fn print_fw12_inputdeck_status(&self) -> EcResult<()> {
Expand Down Expand Up @@ -779,7 +779,7 @@ impl CrosEc {
pub fn set_input_deck_mode(&self, mode: DeckStateMode) -> EcResult<InputDeckStatus> {
let status = EcRequestDeckState { mode }.send_command(self)?;

Ok(InputDeckStatus::from(status))
InputDeckStatus::try_from(status)
}

/// Change the keyboard baclight brightness
Expand Down
8 changes: 5 additions & 3 deletions framework_lib/src/commandline/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1765,13 +1765,15 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 {
} else if let Some(mode) = &args.inputdeck_mode {
if *mode == InputDeckModeArg::Reset {
println!("Resetting input deck (off => auto)");
ec.set_input_deck_mode(DeckStateMode::ForceOff).unwrap();
// Even if decoding the response fails, the EC has applied the
// mode, so keep going and turn it back to auto
print_err(ec.set_input_deck_mode(DeckStateMode::ForceOff));
// Make sure it has time to fully turn off
os_specific::sleep(100);
ec.set_input_deck_mode(DeckStateMode::Required).unwrap();
print_err(ec.set_input_deck_mode(DeckStateMode::Required));
} else {
println!("Set mode to: {:?}", mode);
ec.set_input_deck_mode((*mode).into()).unwrap();
print_err(ec.set_input_deck_mode((*mode).into()));
}
} else if args.expansion_bay {
if let Err(err) = ec.check_bay_status() {
Expand Down
114 changes: 65 additions & 49 deletions framework_lib/src/power.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,10 @@ pub struct AccelData {
}
impl From<Vec<u8>> for AccelData {
fn from(t: Vec<u8>) -> Self {
let Some(t) = t.get(..6) else {
error!("Accelerometer data too short: {} bytes", t.len());
return Self { x: 0, y: 0, z: 0 };
};
Self {
x: i16::from_le_bytes([t[0], t[1]]),
y: i16::from_le_bytes([t[2], t[3]]),
Expand Down Expand Up @@ -225,23 +229,27 @@ impl fmt::Display for LidAngle {
}
}

fn read_string(ec: &CrosEc, address: u16) -> String {
let bytes = ec.read_memory(address, EC_MEMMAP_TEXT_MAX).unwrap();
String::from_utf8_lossy(bytes.as_slice()).replace(['\0'], "")
fn read_string(ec: &CrosEc, address: u16) -> Option<String> {
let bytes = ec.read_memory(address, EC_MEMMAP_TEXT_MAX)?;
Some(String::from_utf8_lossy(bytes.as_slice()).replace(['\0'], ""))
}

fn read_u8(ec: &CrosEc, address: u16) -> Option<u8> {
ec.read_memory(address, 1)?.first().copied()
}

fn read_u32(ec: &CrosEc, address: u16) -> u32 {
let bytes = ec.read_memory(address, 4).unwrap();
fn read_u32(ec: &CrosEc, address: u16) -> Option<u32> {
let bytes = ec.read_memory(address, 4)?;
if bytes.len() != 4 {
debug_assert!(
bytes.len() == 4,
"Tried to read 4 bytes but got {}",
bytes.len()
);
error!("Unexpected length returned: {:?} instead of 4", bytes.len());
return 0;
return None;
}
u32::from_ne_bytes(bytes[0..4].try_into().unwrap())
Some(u32::from_ne_bytes(bytes[0..4].try_into().unwrap()))
}

pub fn print_memmap_version_info(ec: &CrosEc) {
Expand Down Expand Up @@ -433,13 +441,20 @@ pub fn get_accel_data(ec: &CrosEc) -> (AccelData, AccelData, LidAngle) {
// 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];
// 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();
// 0x92-0x93: Lid angle, 0x94-0x99: 1st accel, 0x9a-0x9f: 2nd accel
let Some(data) = ec
.read_memory(EC_MEMMAP_ACC_DATA, 14)
.filter(|d| d.len() == 14)
else {
error!("Failed to read accelerometer data");
let zero = AccelData { x: 0, y: 0, z: 0 };
return (zero.clone(), zero, LidAngle::Unreliable);
};
let lid_angle = u16::from_le_bytes([data[0], data[1]]);
let accel_1 = data[2..8].to_vec();
let accel_2 = data[8..14].to_vec();

// TODO: Make sure we got a new sample
// println!(" Status Bit: {} 0x{:X}", acc_status, acc_status);
Expand Down Expand Up @@ -494,13 +509,13 @@ pub fn print_sensors(ec: &CrosEc) {
// 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 Some(acc_status) = read_u8(ec, EC_MEMMAP_ACC_STATUS) else {
println!("Accelerometers: Failed to read");
return;
};
// 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 (accel_1, accel_2, lid_angle) = get_accel_data(ec);

let present = (acc_status & 0x80) > 0;
if present {
Expand All @@ -509,21 +524,19 @@ pub fn print_sensors(ec: &CrosEc) {
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 lid_angle {
LidAngle::Angle(deg) => println!("{} Deg", deg),
LidAngle::Unreliable => println!("Unreliable"),
}
println!(
" {:<12} {}",
format!("{:?} Sensor:", accel_locations[0]),
AccelData::from(accel_1)
);
println!(
" {:<12} {}",
format!("{:?} Sensor:", accel_locations[1]),
AccelData::from(accel_2)
);
// The EC might not report the location of every sensor
let location = |i: usize| {
accel_locations
.get(i)
.map(|l| format!("{:?} Sensor:", l))
.unwrap_or_else(|| format!("Sensor {}:", i + 1))
};
println!(" {:<12} {}", location(0), accel_1);
println!(" {:<12} {}", location(1), accel_2);
}
}

Expand Down Expand Up @@ -696,7 +709,10 @@ pub fn print_thermal(ec: &CrosEc) {
}

pub fn get_fan_num(ec: &CrosEc) -> EcResult<usize> {
let fans = ec.read_memory(EC_MEMMAP_FAN, 0x08).unwrap();
let fans = ec
.read_memory(EC_MEMMAP_FAN, 2 * EC_FAN_SPEED_ENTRIES as u16)
.filter(|f| f.len() == 2 * EC_FAN_SPEED_ENTRIES)
.ok_or_else(|| EcError::DeviceError("Failed to read fan speeds".to_string()))?;

let mut count = 0;
for i in 0..EC_FAN_SPEED_ENTRIES {
Expand All @@ -711,24 +727,24 @@ pub fn get_fan_num(ec: &CrosEc) -> EcResult<usize> {

// TODO: Use Result
pub fn power_info(ec: &CrosEc) -> Option<PowerInfo> {
let battery_flag = ec.read_memory(EC_MEMMAP_BATT_FLAG, 1)?[0];
let battery_flag = read_u8(ec, EC_MEMMAP_BATT_FLAG)?;
debug!("AC/Battery flag: {:#X}", battery_flag);
let battery_lfcc = read_u32(ec, EC_MEMMAP_BATT_LFCC);
let battery_cap = read_u32(ec, EC_MEMMAP_BATT_CAP);

let present_voltage = read_u32(ec, EC_MEMMAP_BATT_VOLT);
let present_rate = read_u32(ec, EC_MEMMAP_BATT_RATE);
let _remaining_capacity = read_u32(ec, EC_MEMMAP_BATT_CAP); // TODO: Why didn't I use this?
let battery_count = ec.read_memory(EC_MEMMAP_BATT_COUNT, 1).unwrap()[0]; // 8 bit
let current_battery_index = ec.read_memory(EC_MEMMAP_BATT_INDEX, 1).unwrap()[0]; // 8 bit
let design_capacity = read_u32(ec, EC_MEMMAP_BATT_DCAP);
let design_voltage = read_u32(ec, EC_MEMMAP_BATT_DVLT);
let cycle_count = read_u32(ec, EC_MEMMAP_BATT_CCNT);

let manufacturer = read_string(ec, EC_MEMMAP_BATT_MFGR);
let model_number = read_string(ec, EC_MEMMAP_BATT_MODEL);
let serial_number = read_string(ec, EC_MEMMAP_BATT_SERIAL);
let battery_type = read_string(ec, EC_MEMMAP_BATT_TYPE);
let battery_lfcc = read_u32(ec, EC_MEMMAP_BATT_LFCC)?;
let battery_cap = read_u32(ec, EC_MEMMAP_BATT_CAP)?;

let present_voltage = read_u32(ec, EC_MEMMAP_BATT_VOLT)?;
let present_rate = read_u32(ec, EC_MEMMAP_BATT_RATE)?;
let _remaining_capacity = read_u32(ec, EC_MEMMAP_BATT_CAP)?; // TODO: Why didn't I use this?
let battery_count = read_u8(ec, EC_MEMMAP_BATT_COUNT)?;
let current_battery_index = read_u8(ec, EC_MEMMAP_BATT_INDEX)?;
let design_capacity = read_u32(ec, EC_MEMMAP_BATT_DCAP)?;
let design_voltage = read_u32(ec, EC_MEMMAP_BATT_DVLT)?;
let cycle_count = read_u32(ec, EC_MEMMAP_BATT_CCNT)?;

let manufacturer = read_string(ec, EC_MEMMAP_BATT_MFGR)?;
let model_number = read_string(ec, EC_MEMMAP_BATT_MODEL)?;
let serial_number = read_string(ec, EC_MEMMAP_BATT_SERIAL)?;
let battery_type = read_string(ec, EC_MEMMAP_BATT_TYPE)?;

Some(PowerInfo {
ac_present: 0 != (battery_flag & EC_BATT_FLAG_AC_PRESENT),
Expand Down
Loading