Merge 25Q1 (ab/12770256) to aosp-main-future Bug: 385190204 Merged-In: If3465d3d2f2465ae33d8a3e1a80262d319e4f90c Change-Id: I431e605655574d8e696e07ce46e2bccdce90aad8
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..dcdc1c9 --- /dev/null +++ b/.gitignore
@@ -0,0 +1,8 @@ +# Generated by Cargo +target/ +debug/ +Cargo.lock +Cargo.toml +rustfmt.toml +.vscode/ +.idea/ \ No newline at end of file
diff --git a/OWNERS b/OWNERS new file mode 100644 index 0000000..b2c0733 --- /dev/null +++ b/OWNERS
@@ -0,0 +1,4 @@ +jthies@google.com +bleung@google.com +raduvele@google.com +danielgeorgem@google.com
diff --git a/PREUPLOAD.cfg b/PREUPLOAD.cfg new file mode 100644 index 0000000..b856309 --- /dev/null +++ b/PREUPLOAD.cfg
@@ -0,0 +1,10 @@ +# Copyright 2024 Google LLC +[Builtin Hooks] +bpfmt = true +rustfmt = true +aidl_format = true +clang_format = true + +[Builtin Hooks Options] +rustfmt = --config-path=${REPO_ROOT}/build/soong/scripts/rustfmt.toml +clang_format = --commit ${PREUPLOAD_COMMIT} --style file --extensions c,h,hpp,cc,cpp
diff --git a/typec_connector_class_helper/Android.bp b/typec_connector_class_helper/Android.bp new file mode 100644 index 0000000..a54abc6 --- /dev/null +++ b/typec_connector_class_helper/Android.bp
@@ -0,0 +1,47 @@ +// Copyright 2024 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package { + default_team: "trendy_team_android_usb", +} + +rust_defaults { + name: "typec_connector_class_helper_defaults", + rustlibs: [ + "libregex", + "liblog_rust", + "liblogger", + "libanyhow", + ], +} + +rust_binary { + name: "typec_connector_class", + crate_name: "typec_connector_class_helper", + srcs: ["src/main.rs"], + defaults: ["typec_connector_class_helper_defaults"], + prefer_rlib: true, +} + +rust_test { + name: "typec_connector_class_test", + crate_name: "typec_connector_class_test", + srcs: ["src/main.rs"], + defaults: ["typec_connector_class_helper_defaults"], + test_suites: ["general-tests"], + auto_gen_config: true, + // Required to access /dev/cros_ec. + require_root: true, + rustlibs: ["libtempfile"], +}
diff --git a/typec_connector_class_helper/src/main.rs b/typec_connector_class_helper/src/main.rs new file mode 100644 index 0000000..34baa11 --- /dev/null +++ b/typec_connector_class_helper/src/main.rs
@@ -0,0 +1,48 @@ +// Copyright 2024 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! main + +mod typec_class_utils; +mod usb_pd_utils; + +#[cfg(test)] +mod typec_class_utils_tests; + +use anyhow::{anyhow, Result}; +use std::{env, io::stdout, path::Path}; +use typec_class_utils::{ + parse_dirs_and_execute, print_port_info, OutputWriter, PORT_REGEX, TYPEC_SYSFS_PATH, +}; + +fn main() -> Result<()> { + logger::init( + logger::Config::default() + .with_tag_on_device("usb_info") + .with_max_level(log::LevelFilter::Info), + ); + + let args: Vec<String> = env::args().collect(); + if args.len() > 1 { + return Err(anyhow!("typec_connector_class_helper does not accept any arguments.")); + } + + let mut out_writer = OutputWriter::new(stdout(), 0); + parse_dirs_and_execute( + Path::new(TYPEC_SYSFS_PATH), + &mut out_writer, + PORT_REGEX, + print_port_info, + ) +}
diff --git a/typec_connector_class_helper/src/typec_class_utils.rs b/typec_connector_class_helper/src/typec_class_utils.rs new file mode 100644 index 0000000..a4017dc --- /dev/null +++ b/typec_connector_class_helper/src/typec_class_utils.rs
@@ -0,0 +1,684 @@ +// Copyright 2024 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! typec_class_utils + +use crate::usb_pd_utils::*; +use anyhow::{bail, Context, Result}; +use log::warn; +use regex::Regex; +use std::{ + fs, + io::Write, + path::{Path, PathBuf}, +}; + +pub const TYPEC_SYSFS_PATH: &str = "/sys/class/typec"; + +pub const MODE_REGEX: &str = "^mode[0-9]+$"; +pub const PLUG_ALT_MODE_REGEX: &str = "^port[0-9]+\\-plug[0-9]+\\.[0-9]+$"; +pub const PLUG_REGEX: &str = "^port[0-9]+\\-plug[0-9]+$"; +pub const PORT_REGEX: &str = "^port[0-9]+$"; +pub const PARTNER_ALT_MODE_REGEX: &str = "^port[0-9]+-partner\\.[0-9]+$"; +pub const PARTNER_PDO_REGEX: &str = "^pd[0-9]+$"; +pub const PDO_CAPABILITIES_REGEX: &str = "^(sink|source)-capabilities$"; +pub const PDO_TYPE_REGEX: &str = + "^[0-9]+:(battery|fixed_supply|programmable_supply|variable_supply)$"; +pub const USB_PORT_REGEX: &str = "^usb[0-9]+\\-port[0-9]+$"; +pub const USB_DEVICE_REGEX: &str = "^[0-9]+\\-[0-9]+(\\.[0-9]+)*$"; + +pub const INDENT_STEP: usize = 2; + +const ERR_READ_DIR: &str = "Failed to iterate over files in directory"; +const ERR_READ_FILE: &str = "Cannot read file from path"; +const ERR_FILE_NAME_FROM_PATH: &str = "Cannot get file name at path"; +const ERR_FILE_NAME_UTF_INVALID: &str = "The file name is UTF-8 invalid at path"; +const ERR_DIR_ENTRY_ACCESS: &str = "Cannot access entry in directory"; +const ERR_WRITE_TO_BUFFER: &str = "Cannot write to output buffer. Attempted to print"; +const ERR_PATH_NOT_DIR_OR_SYMLINK: &str = "The path is not a directory or a symbolic link"; + +pub struct OutputWriter<W: Write> { + buffer: W, + indent: usize, +} + +impl<W: Write> OutputWriter<W> { + pub fn new(buffer: W, indent: usize) -> Self { + Self { buffer, indent } + } + + /// Prints a string with indentation. + fn print_str_indent(&mut self, str_to_print: &str) -> Result<()> { + writeln!(self.buffer, "{:indent$}{str_to_print}", "", indent = self.indent) + .with_context(|| format!("{ERR_WRITE_TO_BUFFER} {:?}", str_to_print))?; + Ok(()) + } + + /// Prints a file's contents in a "name: content" format and also adds indentation to multiline strings. + fn print_file_formatted(&mut self, file_path: &Path) -> Result<()> { + let file_name = get_path_basename(file_path)?; + let file_contents = fs::read_to_string(file_path) + .with_context(|| format!("{ERR_READ_FILE} {:?}", file_path))?; + let formatted_contents = file_contents + .trim_ascii_end() + .replace("\n", format!("\n{:indent$}", "", indent = self.indent).as_str()); + writeln!( + self.buffer, + "{:indent$}{file_name}: {formatted_contents}", + "", + indent = self.indent + ) + .with_context(|| format!("{ERR_WRITE_TO_BUFFER} {:?}", formatted_contents))?; + Ok(()) + } + + /// Prints the name of the directory followed by all the files in it in a "name: content" format. + /// The files are sorted alphabetically by path to ensure consistency. + pub fn print_dir_files(&mut self, dir_path: &Path) -> Result<()> { + let dir_name = get_path_basename(dir_path)?; + self.print_str_indent(dir_name)?; + + for path in get_sorted_paths_from_dir(dir_path, |path| path.is_file())? { + self.indent += INDENT_STEP; + let _ = self.print_file_formatted(&path).inspect_err(|err| warn!("{:?}: {err}", path)); + self.indent -= INDENT_STEP; + } + + Ok(()) + } +} + +/// Retrieves a sorted vector of paths in the given directory. Filters the paths according to `path_filter`. +/// Logs the errors and ignores faulty entries/paths. +fn get_sorted_paths_from_dir( + dir_path: &Path, + path_filter: fn(&PathBuf) -> bool, +) -> Result<Vec<PathBuf>> { + let mut sorted_paths: Vec<PathBuf> = fs::read_dir(dir_path) + .with_context(|| format!("{ERR_READ_DIR} {:?}", dir_path))? + .filter_map(|entry| { + entry + .inspect_err(|err| warn!("{ERR_DIR_ENTRY_ACCESS} {:?}: {err}", dir_path)) + .map(|entry| entry.path()) + .ok() + }) + .filter(path_filter) + .collect(); + sorted_paths.sort(); + Ok(sorted_paths) +} + +/// Returns the rightmost element of a path. +fn get_path_basename(path: &Path) -> Result<&str> { + let basename = path + .file_name() + .with_context(|| format!("{ERR_FILE_NAME_FROM_PATH} {:?}", path))? + .to_str() + .with_context(|| format!("{ERR_FILE_NAME_UTF_INVALID} {:?}", path))?; + Ok(basename) +} + +/// Decodes and prints VDOs from the files specified relative to `identity_path_buf` path. +/// * `filename_vdo_fields_arr` - Is an array of tuples containing the name of the file where the VDO can be found and the VDO description array (`&[VdoField]`). +pub fn print_decoded_vdos_from_files<W: Write>( + identity_path_buf: &mut PathBuf, + filename_vdo_fields_arr: &[(&str, &[VdoField])], + out_writer: &mut OutputWriter<W>, +) { + for (filename, vdo_fields) in filename_vdo_fields_arr { + identity_path_buf.push(filename); + let _ = print_vdo(identity_path_buf, vdo_fields, out_writer) + .inspect_err(|err| warn!("{:#}", err)); + identity_path_buf.pop(); + } +} + +/// Prints the identity information of a USB device. +/// This function reads and decodes the identity descriptors of a USB device, +/// including its ID header, certification status, and product information. +/// The output is formatted and written using the provided `OutputWriter`. +/// # Arguments +/// * `dev_path` - A reference to the Path of the device's directory. +/// * `out_writer` - A mutable reference to an OutputWriter for writing the output. +/// # Returns +/// * `Result<()>` - A Result indicating success or failure of the printing operation. +pub fn print_identity<W: Write>(dev_path: &Path, out_writer: &mut OutputWriter<W>) -> Result<()> { + out_writer.print_str_indent("identity").inspect_err(|err| warn!("{:#}", err)).ok(); + + out_writer.indent += INDENT_STEP; + + let filename_vdo_fields_arr: &[(&str, &[VdoField]); 3] = match get_pd_revision(dev_path) { + PdRev::Pd20 => &[ + ("id_header", pd20_data::ID_HEADER_VDO), + ("cert_stat", pd20_data::CERT_STAT_VDO), + ("product", pd20_data::PRODUCT_VDO), + ], + PdRev::Pd30 => &[ + ("id_header", pd30_data::ID_HEADER_VDO), + ("cert_stat", pd30_data::CERT_STAT_VDO), + ("product", pd30_data::PRODUCT_VDO), + ], + PdRev::Pd31 => &[ + ("id_header", pd31_data::ID_HEADER_VDO), + ("cert_stat", pd31_data::CERT_STAT_VDO), + ("product", pd31_data::PRODUCT_VDO), + ], + PdRev::None => &[("id_header", &[]), ("cert_stat", &[]), ("product", &[])], + }; + print_decoded_vdos_from_files( + &mut dev_path.join("identity"), + filename_vdo_fields_arr, + out_writer, + ); + out_writer.indent -= INDENT_STEP; + + Ok(()) +} + +/// Prints the contents of an identity directory including VDO fields which are determined by product type. +pub fn print_partner_identity<W: Write>( + partner_path: &Path, + out_writer: &mut OutputWriter<W>, +) -> Result<()> { + let mut identity_path_buf: PathBuf = partner_path.join("identity"); + if !(identity_path_buf.is_dir() | identity_path_buf.is_symlink()) { + bail!("{ERR_PATH_NOT_DIR_OR_SYMLINK}: {:?}", identity_path_buf); + } + + let _ = print_identity(partner_path, out_writer).inspect_err(|err| warn!("{:#}", err)); + + out_writer.indent += INDENT_STEP; + + let pd_rev = get_pd_revision(partner_path); + + let vdo_fields_arr: [&[VdoField]; 3] = match get_partner_product_type(partner_path, pd_rev) { + ProductType::Ama(PdRev::Pd20) => [pd20_data::AMA_VDO, &[], &[]], + ProductType::Vpd(PdRev::Pd30) => [pd30_data::VPD_VDO, &[], &[]], + ProductType::Ama(PdRev::Pd30) => [pd30_data::AMA_VDO, &[], &[]], + ProductType::Port((PortType::Ufp, PdRev::Pd30)) => { + [pd30_data::UFP_VDO1, pd30_data::UFP_VDO2, &[]] + } + ProductType::Port((PortType::Dfp, PdRev::Pd30)) => [pd30_data::DFP_VDO, &[], &[]], + ProductType::Port((PortType::Drd, PdRev::Pd30)) => { + [pd30_data::UFP_VDO1, pd30_data::UFP_VDO2, pd30_data::DFP_VDO] + } + ProductType::Port((PortType::Ufp, PdRev::Pd31)) => [pd31_data::UFP_VDO, &[], &[]], + ProductType::Port((PortType::Dfp, PdRev::Pd31)) => [pd31_data::DFP_VDO, &[], &[]], + ProductType::Port((PortType::Drd, PdRev::Pd31)) => { + [pd31_data::UFP_VDO, &[], pd31_data::DFP_VDO] + } + _ => [&[], &[], &[]], + }; + let filenames = ["product_type_vdo1", "product_type_vdo2", "product_type_vdo3"]; + let filename_vdo_fields_arr: Vec<(&str, &[VdoField])> = + filenames.into_iter().zip(vdo_fields_arr).collect(); + + print_decoded_vdos_from_files(&mut identity_path_buf, &filename_vdo_fields_arr, out_writer); + + out_writer.indent -= INDENT_STEP; + + Ok(()) +} + +/// Reads the usb_power_delivery_revision file in a given directory +/// and returns a PdRev enum noting the supported PD Revision. +pub fn get_pd_revision(dir_path: &Path) -> PdRev { + let pd_path: PathBuf = dir_path.join("usb_power_delivery_revision"); + let pd_revision_str = fs::read_to_string(&pd_path) + .inspect_err(|err| warn!("{ERR_READ_FILE} {:?} {:#}", &pd_path, err)) + .unwrap_or_default(); + match pd_revision_str.trim_ascii() { + "2.0" => PdRev::Pd20, + "3.0" => PdRev::Pd30, + "3.1" => PdRev::Pd31, + _ => PdRev::None, + } +} + +/// Uses the id_header VDO and USB PD revision to decode what type of device is being parsed. +/// In case of failure returns ProductType::Other. +pub fn get_partner_product_type(partner_dir: &Path, pd_rev: PdRev) -> ProductType { + let id_header_vdo_path: PathBuf = partner_dir.join("identity").join("id_header"); + + let id_header_vdo = match read_vdo(&id_header_vdo_path) { + Ok(vdo) => vdo, + Err(err) => { + warn!("{:#}", err); + return ProductType::Other; + } + }; + + match pd_rev { + PdRev::Pd20 => { + // Alternate Mode Adapter (AMA) is the only partner product type in the + // USB PD 2.0 specification. + match id_header_vdo & UFP_PRODUCT_TYPE_MASK { + pd20_data::AMA_COMP => ProductType::Ama(PdRev::Pd20), + _ => ProductType::Other, + } + } + PdRev::Pd30 => { + // In USB PD 3.0 a partner can be an upstream facing port (UFP), + // downstream facing port (DFP), or a dual-role data port (DRD). + // Information about UFP/DFP are in different fields, so they are checked + // separately then compared to determine a partner's product type. + // Separate from UFP/DFP, they can support AMA/VPD as a UFP type. + + let ufp_supported = match id_header_vdo & UFP_PRODUCT_TYPE_MASK { + pd30_data::HUB_COMP => true, + pd30_data::PERIPHERAL_COMP => true, + pd30_data::AMA_COMP => return ProductType::Ama(PdRev::Pd30), + pd30_data::VPD_COMP => return ProductType::Vpd(PdRev::Pd30), + _ => false, + }; + + let dfp_supported = matches!( + id_header_vdo & DFP_PRODUCT_TYPE_MASK, + pd30_data::DFP_HUB_COMP | pd30_data::DFP_HOST_COMP | pd30_data::POWER_BRICK_COMP + ); + + match (ufp_supported, dfp_supported) { + (true, true) => ProductType::Port((PortType::Drd, PdRev::Pd30)), + (true, false) => ProductType::Port((PortType::Ufp, PdRev::Pd30)), + (false, true) => ProductType::Port((PortType::Dfp, PdRev::Pd30)), + _ => ProductType::Other, + } + } + PdRev::Pd31 => { + // Similar to USB PD 3.0, USB PD 3.1 can have a partner which is both UFP + // and DFP (DRD). AMA product type is no longer present in PD 3.1. + let ufp_supported = matches!( + id_header_vdo & UFP_PRODUCT_TYPE_MASK, + pd31_data::HUB_COMP | pd31_data::PERIPHERAL_COMP + ); + + let dfp_supported = matches!( + id_header_vdo & DFP_PRODUCT_TYPE_MASK, + pd31_data::DFP_HOST_COMP | pd31_data::DFP_HUB_COMP | pd31_data::POWER_BRICK_COMP + ); + + match (ufp_supported, dfp_supported) { + (true, true) => ProductType::Port((PortType::Drd, PdRev::Pd31)), + (true, false) => ProductType::Port((PortType::Ufp, PdRev::Pd31)), + (false, true) => ProductType::Port((PortType::Dfp, PdRev::Pd31)), + _ => ProductType::Other, + } + } + _ => ProductType::Other, + } +} + +/// Reads a vdo value from a text file and converts it to a u32 variable. Then, prints out the values of each field according to the vdo_description. +pub fn print_vdo<W: Write>( + vdo_path: &Path, + vdo_description: &[VdoField], + out_writer: &mut OutputWriter<W>, +) -> Result<()> { + let vdo = read_vdo(vdo_path)?; + let vdo_str = format!("{}: 0x{:x}", get_path_basename(vdo_path)?, vdo); + let _ = out_writer.print_str_indent(&vdo_str).inspect_err(|err| warn!("{:#}", err)); + out_writer.indent += INDENT_STEP; + for vdo_field in vdo_description { + let _ = out_writer + .print_str_indent(&vdo_field.decode_vdo(vdo)) + .inspect_err(|err| warn!("{:#}", err)); // log error but continue iterating. + } + out_writer.indent -= INDENT_STEP; + Ok(()) +} + +/// Reads a file containing a 32 bit VDO value and loads it into a u32. +pub fn read_vdo(vdo_path: &Path) -> Result<u32> { + let vdo_str = + fs::read_to_string(vdo_path).with_context(|| format!("{ERR_READ_FILE} {:?}", vdo_path))?; + let vdo_str = vdo_str.trim_ascii(); + let vdo: u32 = + u32::from_str_radix(vdo_str.trim_start_matches("0x"), 16).with_context(|| { + format!("Cannot convert string read from path: {:?} to u32: {vdo_str}", vdo_path) + })?; + Ok(vdo) +} + +// Prints the immediate files in an alternate mode directory, then prints the files in each mode subdirectory. +pub fn print_alt_mode<W: Write>(alt_mode_dir_path: &Path, out_writer: &mut OutputWriter<W>) { + if !(alt_mode_dir_path.is_dir() | alt_mode_dir_path.is_symlink()) { + warn!("{ERR_PATH_NOT_DIR_OR_SYMLINK}: {:?}", alt_mode_dir_path); + return; + } + + let _ = out_writer.print_dir_files(alt_mode_dir_path).inspect_err(|err| warn!("{:#}", err)); + out_writer.indent += INDENT_STEP; + let _ = parse_dirs_and_execute( + alt_mode_dir_path, + out_writer, + MODE_REGEX, + |path: &Path, out_writer: &mut OutputWriter<W>| { + let _ = out_writer.print_dir_files(path).inspect_err(|err| warn!("{:#}", err)); + }, + ) + .inspect_err(|err| warn!("{:#}", err)); + out_writer.indent -= INDENT_STEP; +} + +// Prints detailed information about the PDOs given at capabilities_dir_path, including available voltages and currents. +pub fn print_pdo_capabilities<W: Write>(capabilities: &Path, out_writer: &mut OutputWriter<W>) { + let _ = out_writer.print_dir_files(capabilities).inspect_err(|err| warn!("{:#}", err)); + out_writer.indent += INDENT_STEP; + let _ = parse_dirs_and_execute( + capabilities, + out_writer, + PDO_TYPE_REGEX, + |path: &Path, out_writer: &mut OutputWriter<W>| { + let _ = out_writer.print_dir_files(path).inspect_err(|err| warn!("{:#}", err)); + }, + ) + .inspect_err(|err| warn!("{:#}", err)); + out_writer.indent -= INDENT_STEP; +} + +// Prints the immediate files in a PDO data directory, then call +// print_pdo_capabilities to print more detailed PDO information. +pub fn print_pdos<W: Write>(pdo_dir_path: &Path, out_writer: &mut OutputWriter<W>) { + if !(pdo_dir_path.is_dir() | pdo_dir_path.is_symlink()) { + warn!("{ERR_PATH_NOT_DIR_OR_SYMLINK}: {:?}", pdo_dir_path); + return; + } + + let _ = out_writer.print_dir_files(pdo_dir_path).inspect_err(|err| warn!("{:#}", err)); + out_writer.indent += INDENT_STEP; + let _ = parse_dirs_and_execute( + pdo_dir_path, + out_writer, + PDO_CAPABILITIES_REGEX, + print_pdo_capabilities, + ) + .inspect_err(|err| warn!("{:#}", err)); + out_writer.indent -= INDENT_STEP; +} + +/// Prints the immediate information in the partner directory, then prints identity, alternate mode, and power data objects (PDO) information. +pub fn print_partner<W: Write>(port_path: &Path, out_writer: &mut OutputWriter<W>) -> Result<()> { + let partner_dir_name = [get_path_basename(port_path)?, "-partner"].concat(); + let partner_path_buf: PathBuf = port_path.join(partner_dir_name); + + if !(partner_path_buf.is_dir() | partner_path_buf.is_symlink()) { + bail!("{ERR_PATH_NOT_DIR_OR_SYMLINK}: {:?}", partner_path_buf); + } + + let _ = out_writer.print_dir_files(&partner_path_buf).inspect_err(|err| warn!("{:#}", err)); + + out_writer.indent += INDENT_STEP; + + let _ = + print_partner_identity(&partner_path_buf, out_writer).inspect_err(|err| warn!("{:#}", err)); + + let _ = parse_dirs_and_execute( + &partner_path_buf, + out_writer, + PARTNER_ALT_MODE_REGEX, + print_alt_mode, + ) + .inspect_err(|err| warn!("{:#}", err)); + + let _ = parse_dirs_and_execute(&partner_path_buf, out_writer, PARTNER_PDO_REGEX, print_pdos) + .inspect_err(|err| warn!("{:#}", err)); + + out_writer.indent -= INDENT_STEP; + Ok(()) +} + +/// Determines the product type of a USB cable by reading its identity descriptors. +/// This function reads the "id_header" file within the "identity" directory of the cable's path +/// to determine its product type based on the USB PD revision and product mask. +/// # Arguments +/// * `dir` - A reference to the Path of the cable's directory. +/// # Returns +/// * `ProductType` - The determined product type of the cable. +pub fn get_cable_product_type(dir: &Path) -> ProductType { + let id_header = match read_vdo(&dir.join("identity").join("id_header")) { + Err(err) => { + warn!("get cable type failed to read vdo: {:#}", err); + return ProductType::Other; + } + Ok(id_header) => id_header, + }; + + let pd = get_pd_revision(dir); + let prod_mask = id_header & UFP_PRODUCT_TYPE_MASK; + + // All USB PD 3.1/3.0/2.0 support passive cables. + if pd == PdRev::Pd20 && prod_mask == pd20_data::PASSIVE_CABLE_COMP + || pd == PdRev::Pd30 && prod_mask == pd30_data::PASSIVE_CABLE_COMP + || pd == PdRev::Pd31 && prod_mask == pd31_data::PASSIVE_CABLE_COMP + { + return ProductType::Cable((CableType::Passive, pd)); + } + + // All USB PD 3.1/3.0/2.0 support active cables. + if pd == PdRev::Pd20 && prod_mask == pd20_data::ACTIVE_CABLE_COMP + || pd == PdRev::Pd30 && prod_mask == pd30_data::ACTIVE_CABLE_COMP + || pd == PdRev::Pd31 && prod_mask == pd31_data::ACTIVE_CABLE_COMP + { + return ProductType::Cable((CableType::Active, pd)); + } + + // USB PD 3.1 also supports Vconn Powered Devices (VPD). + if pd == PdRev::Pd31 && prod_mask == pd31_data::VPD_COMP { + return ProductType::Cable((CableType::Vpd, pd)); + } + + ProductType::Other +} + +/// Prints the identity information of a USB cable. +/// This function prints the identity information of a USB cable, including its product type and +/// decoded VDOs (Vendor-Defined Objects) based on its PD revision. +/// # Arguments +/// * `cable` - A reference to the Path of the cable's directory. +/// * `out_writer` - A mutable reference to an OutputWriter for writing the output. +pub fn print_cable_identity<W: Write>(cable: &Path, out_writer: &mut OutputWriter<W>) { + let mut identity = cable.join("identity"); + if !(identity.is_dir() | identity.is_symlink()) { + warn!("{ERR_PATH_NOT_DIR_OR_SYMLINK}: {:?}", identity); + return; + } + + let _ = print_identity(cable, out_writer).inspect_err(|err| warn!("{:#}", err)); + + out_writer.indent += INDENT_STEP; + + let vdos: [&[VdoField]; 3] = match get_cable_product_type(cable) { + ProductType::Cable(cable_type) => match cable_type { + (CableType::Passive, PdRev::Pd20) => [pd20_data::PASSIVE_VDO, &[], &[]], + (CableType::Active, PdRev::Pd20) => [pd20_data::ACTIVE_VDO, &[], &[]], + (CableType::Passive, PdRev::Pd30) => [pd30_data::PASSIVE_VDO, &[], &[]], + (CableType::Active, PdRev::Pd30) => { + [pd30_data::ACTIVE_VDO1, pd30_data::ACTIVE_VDO2, &[]] + } + (CableType::Passive, PdRev::Pd31) => [pd31_data::PASSIVE_VDO, &[], &[]], + (CableType::Active, PdRev::Pd31) => { + [pd31_data::ACTIVE_VDO1, pd31_data::ACTIVE_VDO2, &[]] + } + (CableType::Vpd, PdRev::Pd31) => [pd31_data::VPD_VDO, &[], &[]], + _ => [&[], &[], &[]], + }, + _ => [&[], &[], &[]], + }; + + let descriptions = ["product_type_vdo1", "product_type_vdo2", "product_type_vdo3"]; + let to_print: Vec<(&str, &[VdoField])> = descriptions.into_iter().zip(vdos).collect(); + + print_decoded_vdos_from_files(&mut identity, &to_print, out_writer); + + out_writer.indent -= INDENT_STEP; +} + +/// Prints information about a USB cable plug. +/// This function prints information about a USB cable plug, including its alternate modes. +/// # Arguments +/// * `plug` - A reference to the Path of the plug's directory. +/// * `out_writer` - A mutable reference to an OutputWriter for writing the output. +pub fn print_plug_info<W: Write>(plug: &Path, out_writer: &mut OutputWriter<W>) { + if !(plug.is_dir() | plug.is_symlink()) { + warn!("{ERR_PATH_NOT_DIR_OR_SYMLINK}: {:?}", plug); + return; + } + + let _ = out_writer.print_dir_files(plug); + out_writer.indent += INDENT_STEP; + let _ = parse_dirs_and_execute(plug, out_writer, PLUG_ALT_MODE_REGEX, print_alt_mode) + .inspect_err(|err| warn!("{:#}", err)); + out_writer.indent -= INDENT_STEP; +} + +/// Prints information about a USB cable connected to a port. +/// This function prints information about a USB cable connected to a port, including its identity, +/// plug information, and alternate modes. +/// # Arguments +/// * `port` - A reference to the Path of the port's directory. +/// * `out_writer` - A mutable reference to an OutputWriter for writing the output. +/// # Returns +/// * `Result<()>` - A Result indicating success or failure. +pub fn print_cable<W: Write>(port: &Path, out_writer: &mut OutputWriter<W>) -> Result<()> { + let cable_path = format!("{}-cable", get_path_basename(port)?); + let cable_dir = port.join(cable_path); + + if !(cable_dir.is_dir() | cable_dir.is_symlink()) { + bail!("{ERR_PATH_NOT_DIR_OR_SYMLINK}: {:?}", cable_dir); + } + + out_writer.print_dir_files(&cable_dir).inspect_err(|err| warn!("{:#}", err)).ok(); + + out_writer.indent += INDENT_STEP; + print_cable_identity(&cable_dir, out_writer); + let _ = parse_dirs_and_execute(&cable_dir, out_writer, PLUG_REGEX, print_plug_info) + .inspect_err(|err| warn!("{:#}", err)); + out_writer.indent -= INDENT_STEP; + + Ok(()) +} + +/// Prints the panel and horizontal_position in the physical_location directory of a port. +pub fn print_physical_location<W: Write>( + port_path: &Path, + out_writer: &mut OutputWriter<W>, +) -> Result<()> { + let physical_location_dir = port_path.join("physical_location"); + if !(physical_location_dir.is_dir() | physical_location_dir.is_symlink()) { + bail!("{ERR_PATH_NOT_DIR_OR_SYMLINK}: {:?}", physical_location_dir); + } + out_writer.print_str_indent("physical_location")?; + + out_writer.indent += INDENT_STEP; + out_writer.print_file_formatted(&physical_location_dir.join("panel"))?; + out_writer.print_file_formatted(&physical_location_dir.join("horizontal_position"))?; + out_writer.indent -= INDENT_STEP; + + Ok(()) +} + +// Prints the `busnum`, `devnum`, `devpath` in the usb device directory, which are minimal +// info needed to map to corresponding peripheral. +pub fn print_usb_device_info<W: Write>(usb_device: &Path, out_writer: &mut OutputWriter<W>) { + out_writer.print_str_indent("usb_device").inspect_err(|err| warn!("{:#}", err)).ok(); + + out_writer.indent += INDENT_STEP; + out_writer + .print_file_formatted(&usb_device.join("busnum")) + .inspect_err(|err| warn!("{:#}", err)) + .ok(); + out_writer + .print_file_formatted(&usb_device.join("devnum")) + .inspect_err(|err| warn!("{:#}", err)) + .ok(); + out_writer + .print_file_formatted(&usb_device.join("devpath")) + .inspect_err(|err| warn!("{:#}", err)) + .ok(); + parse_dirs_and_execute(usb_device, out_writer, USB_DEVICE_REGEX, print_usb_device_info) + .inspect_err(|err| warn!("{:#}", err)) + .ok(); + out_writer.indent -= INDENT_STEP; +} + +// Finds and prints information about the usb device in the usb port directory. +pub fn print_usb_device<W: Write>(usb_port: &Path, out_writer: &mut OutputWriter<W>) { + let usb_device_dir = usb_port.join("device"); + if !(usb_device_dir.is_dir() | usb_device_dir.is_symlink()) { + warn!("{ERR_PATH_NOT_DIR_OR_SYMLINK}: {:?}", usb_device_dir); + return; + } + + print_usb_device_info(&usb_device_dir, out_writer); +} + +/// Finds the type-c port's linked usb ports and print relevant usb subsystem information. +pub fn print_usb_subsystem<W: Write>( + port_path: &Path, + out_writer: &mut OutputWriter<W>, +) -> Result<()> { + let _ = parse_dirs_and_execute(port_path, out_writer, USB_PORT_REGEX, print_usb_device); + Ok(()) +} + +/// Prints `connector_id` and `status` in the drm_connector directory which is a symlink +/// to the corresponding DP connector. +pub fn print_drm_subsystem<W: Write>( + port_path: &Path, + out_writer: &mut OutputWriter<W>, +) -> Result<()> { + let drm_path = port_path.join("drm_connector"); + if !(drm_path.is_dir() | drm_path.is_symlink()) { + bail!("{ERR_PATH_NOT_DIR_OR_SYMLINK}: {:?}", drm_path); + } + out_writer.print_str_indent("dp_connector")?; + + out_writer.indent += INDENT_STEP; + out_writer.print_file_formatted(&drm_path.join("connector_id"))?; + out_writer.print_file_formatted(&drm_path.join("status"))?; + out_writer.indent -= INDENT_STEP; + + Ok(()) +} + +/// Prints relevant type-c connector class information for the port located at the sysfs path "port_path". +pub fn print_port_info<W: Write>(port_path: &Path, out_writer: &mut OutputWriter<W>) { + let _ = out_writer.print_dir_files(port_path).inspect_err(|err| warn!("{:#}", err)); + out_writer.indent += INDENT_STEP; + let _ = print_partner(port_path, out_writer).inspect_err(|err| warn!("{:#}", err)); + print_cable(port_path, out_writer).inspect_err(|err| warn!("{:#}", err)).ok(); + print_physical_location(port_path, out_writer).inspect_err(|err| warn!("{:#}", err)).ok(); + print_usb_subsystem(port_path, out_writer).inspect_err(|err| warn!("{:#}", err)).ok(); + print_drm_subsystem(port_path, out_writer).inspect_err(|err| warn!("{:#}", err)).ok(); + out_writer.indent -= INDENT_STEP; +} + +/// Looks at subdirectories of a given directory and executes a passed function on directories matching a given regular expression. +/// Directories are sorted alphabetically by path to ensure consistency in the order of processing. +pub fn parse_dirs_and_execute<W: Write>( + dir_path: &Path, + out_writer: &mut OutputWriter<W>, + regex: &str, + func: fn(&Path, &mut OutputWriter<W>), +) -> Result<()> { + let re = Regex::new(regex).unwrap(); + for path in get_sorted_paths_from_dir(dir_path, |path| path.is_dir() | path.is_symlink())? { + // Assumption: all the symlinks created by the Type-C connector class point to directories. + get_path_basename(&path) + .inspect_err(|err| warn!("{:#}", err)) + .is_ok_and(|file_name| re.is_match(file_name)) + .then(|| func(&path, out_writer)); + } + Ok(()) +}
diff --git a/typec_connector_class_helper/src/typec_class_utils_tests.rs b/typec_connector_class_helper/src/typec_class_utils_tests.rs new file mode 100644 index 0000000..2ddbbfd --- /dev/null +++ b/typec_connector_class_helper/src/typec_class_utils_tests.rs
@@ -0,0 +1,489 @@ +// Copyright 2024 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! typec_class_utils_tests + +use std::path::PathBuf; +use std::{fs, io::Write}; + +use std::io::Cursor; + +use tempfile::tempdir; + +use crate::typec_class_utils::*; +use crate::usb_pd_utils::*; + +/// Creates a temporary hierarchy of directories and files with content. +/// The dir_paths_files_content array param expects the following format: +/// * `[(dir_path, [array of (file_name, file_content)])]` +/// +/// ### Example +/// To create the following directory hierarchy: +/// ``` +/// /port1 +/// /port1/file1: content1 +/// /port1/file2: content2 +/// /port1/subport1 +/// /port2/file1: content1 +/// ``` +/// The dir_paths_files_content parameter should receive the value: +/// ``` +/// [ +/// ( +/// "port1", +/// &[("file1", "content1"), ("file2", "content2")], +/// ), +/// ( +/// "port1/subport1", +/// &[("file1", "content1")], +/// ) +/// ] +/// ``` +fn create_temp_dir_with_dirs_files_content( + dir_paths_files_content: &[(&str, &[(&str, &str)])], +) -> PathBuf { + let root_dir = tempdir().expect("Cannot create temporary directory"); + for (dir_path, files_content) in dir_paths_files_content { + let full_dir_path = root_dir.path().join(dir_path); + println!("FULL: {:?}", &full_dir_path); + fs::create_dir(&full_dir_path).expect("Cannot create directory"); + + for (file_name, file_content) in files_content.iter() { + let mut file = fs::File::create(full_dir_path.join(file_name)) + .expect("Cannot create temporary file"); + writeln!(file, "{file_content}").expect("Could not write to temporary file"); + } + } + root_dir.into_path() +} + +/// Creates a hierarchy of directories and files similar to the one created by the Type-C Connector Class. +fn create_full_typec_connector_class_temp_file_hierarchy() -> PathBuf { + create_temp_dir_with_dirs_files_content(&[ + ( + "port0", + &[ + ("uevent", "DEVTYPE=typec_port\nTYPEC_PORT=port0"), + ("vconn_source", "yes"), + ("data_role", "[host] device"), + ], + ), + ( + "port0/port0-partner", + &[("usb_power_delivery_revision", "3.0"), ("number_of_alternate_modes", "1")], + ), + ( + "port0/port0-partner/identity", + &[ + ("id_header", "0x4c4018d1"), + ("product", "0x50490001"), + ("cert_stat", "0x0"), + ("product_type_vdo1", "0x45800012"), + ("product_type_vdo2", "0x0"), + ("product_type_vdo3", "0x0"), + ], + ), + ( + "port0/port0-partner/port0-partner.0", + &[("description", "DisplayPort"), ("vdo", "0x001c0045")], + ), + ( + "port0/port0-partner/port0-partner.0/mode1", + &[("description", "DisplayPort"), ("vdo", "0x001c0045")], + ), + ("port0/port0-partner/port0-partner.0/ignored", &[("ignored", "ignored content")]), + ("port0/port0-partner/pd0", &[("revision", "3.0")]), + ("port0/port0-partner/pd0/sink-capabilities", &[("uevent", "")]), + ( + "port0/port0-partner/pd0/sink-capabilities/1:fixed_supply", + &[("operational_current", "0mA"), ("voltage", "5000mV")], + ), + ("port0/port0-partner/pd0/source-capabilities", &[("uevent", "")]), + ( + "port0/port0-partner/pd0/source-capabilities/4:fixed_supply", + &[("maximum_current", "3000mA"), ("voltage", "20000mV")], + ), + ( + "port0/port0-partner/pd0/source-capabilities/2:fixed_supply", + &[("maximum_current", "3000mA"), ("voltage", "9000mV")], + ), + ("port0/port0-cable", &[("usb_power_delivery_revision", "3.0")]), + ( + "port0/port0-cable/identity", + &[ + ("cert_stat", "0x290"), + ("id_header", "0x1800228a"), + ("product", "0x94880001"), + ("product_type_vdo1", "0x11082043"), + ("product_type_vdo2", "0x00000000"), + ("product_type_vdo3", "0x00000000"), + ], + ), + ("port0/port0-cable/port0-plug0", &[("number_of_alternate_modes", "2")]), + ("port0/port0-cable/port0-plug0/port0-plug0.0", &[("mode", "1"), ("svid", "1e4e")]), + ( + "port0/port0-cable/port0-plug0/port0-plug0.0/mode1", + &[("active", "no"), ("vdo", "0x9031011c")], + ), + ("port0/port0-cable/port0-plug0/port0-plug0.1", &[("mode", "1"), ("svid", "8087")]), + ( + "port0/port0-cable/port0-plug0/port0-plug0.1/mode1", + &[("active", "no"), ("vdo", "0x00030001")], + ), + ("port0/port0-cable/port0-plug0/port0-plug0.ignore", &[("ignored", "ignored content")]), + ( + "port0/physical_location", + &[ + ("panel", "right"), + ("horizontal_position", "right"), + ("vertical_position", "ignored"), + ], + ), + ("port0/usb3-port1", &[]), + ("port0/usb3-port1/device", &[("busnum", "3"), ("devnum", "9"), ("devpath", "1")]), + ("port0/usb3-port1/device/3-1.1", &[("busnum", "3"), ("devnum", "10"), ("devpath", "1.1")]), + ("port0/usb3-port1/device/3-1.2", &[("busnum", "3"), ("devnum", "11"), ("devpath", "1.2")]), + ( + "port0/usb3-port1/device/3-1.2/3-1.2.4", + &[("busnum", "3"), ("devnum", "12"), ("devpath", "1.2.4")], + ), + ("port0/drm_connector", &[("connector_id", "258"), ("status", "disconnected")]), + ("port1", &[]), + ("portignored", &[("ignored", "ignored content")]), + ]) +} + +#[test] +fn test_print_dir_files() { + let temp_dir_path = create_full_typec_connector_class_temp_file_hierarchy(); + let mut outp_buffer: Cursor<Vec<u8>> = Cursor::new(Vec::new()); + let mut outp_writer = OutputWriter::new(&mut outp_buffer, 0); + let expected_outp = "port0 + data_role: [host] device + uevent: DEVTYPE=typec_port + TYPEC_PORT=port0 + vconn_source: yes +"; + + outp_writer + .print_dir_files(&temp_dir_path.join("port0")) + .expect("Could not execute print_dir_files"); + + assert_eq!( + &String::from_utf8(outp_buffer.into_inner()).expect("Cannot decode output buffer"), + expected_outp + ); +} + +#[test] +fn test_print_vdo() { + let temp_dir_path = create_full_typec_connector_class_temp_file_hierarchy(); + let mut outp_buffer: Cursor<Vec<u8>> = Cursor::new(Vec::new()); + let mut outp_writer = OutputWriter::new(&mut outp_buffer, 0); + let expected_outp = "id_header: 0x4c4018d1 + USB Vendor ID: 0x18d1 + Reserved: 0x40 + Product Type (DFP): 0x0 + Modal Operation Supported: 0x1 + Product Type (UFP/Cable Plug): 0x1 + USB Capable as a USB Device: 0x1 + USB Capable as a USB Host: 0x0 +"; + + let _ = print_vdo( + &temp_dir_path.join("port0/port0-partner/identity/id_header"), + pd30_data::ID_HEADER_VDO, + &mut outp_writer, + ); + + assert_eq!( + &String::from_utf8(outp_buffer.into_inner()).expect("Cannot decode output buffer"), + expected_outp + ); +} + +#[test] +fn test_read_vdo() { + let temp_dir_path = + create_temp_dir_with_dirs_files_content(&[("identity", &[("id_header", "0x4c4018d1")])]); + + let vdo = + read_vdo(&temp_dir_path.join("identity/id_header")).expect("read_vdo returned an error"); + assert_eq!(vdo, 0x4c4018d1); +} + +#[test] +fn test_get_pd_revision() { + let temp_dir_path = create_temp_dir_with_dirs_files_content(&[( + "port0-partner", + &[("usb_power_delivery_revision", "3.0")], + )]); + let pd_rev = get_pd_revision(&temp_dir_path.join("port0-partner")); + assert_eq!(pd_rev, PdRev::Pd30); +} + +#[test] +fn test_parse_dirs_and_execute() { + let temp_dir_path = create_full_typec_connector_class_temp_file_hierarchy(); + let mut outp_buffer: Cursor<Vec<u8>> = Cursor::new(Vec::new()); + let mut outp_writer = OutputWriter::new(&mut outp_buffer, 0); + let expected_outp = "port0 + data_role: [host] device + uevent: DEVTYPE=typec_port + TYPEC_PORT=port0 + vconn_source: yes +port1 +"; + + let _ = parse_dirs_and_execute(&temp_dir_path, &mut outp_writer, PORT_REGEX, |path, out_wr| { + let _ = out_wr.print_dir_files(path); + }); + + assert_eq!( + &String::from_utf8(outp_buffer.into_inner()).expect("Cannot decode output buffer"), + expected_outp + ) +} + +#[test] +fn test_get_partner_product_type_pd30_ufp() { + let temp_dir_path = + create_temp_dir_with_dirs_files_content(&[("identity", &[("id_header", "0x4c4018d1")])]); + let prod_type = get_partner_product_type(&temp_dir_path, PdRev::Pd30); + + assert_eq!(prod_type, ProductType::Port((PortType::Ufp, PdRev::Pd30))); +} + +#[test] +fn test_get_partner_product_type_pd31_drd() { + let temp_dir_path = + create_temp_dir_with_dirs_files_content(&[("identity", &[("id_header", "0x08800000")])]); + let prod_type = get_partner_product_type(&temp_dir_path, PdRev::Pd31); + + assert_eq!(prod_type, ProductType::Port((PortType::Drd, PdRev::Pd31))); +} + +#[test] +fn test_get_partner_product_type_other() { + let temp_dir_path = create_temp_dir_with_dirs_files_content(&[]); + let prod_type = get_partner_product_type(&temp_dir_path, PdRev::Pd20); + + assert_eq!(prod_type, ProductType::Other); +} + +#[test] +fn test_print_alt_mode() { + let temp_dir_path = create_full_typec_connector_class_temp_file_hierarchy(); + let mut outp_buffer: Cursor<Vec<u8>> = Cursor::new(Vec::new()); + let mut outp_writer = OutputWriter::new(&mut outp_buffer, 0); + let expected_outp = "port0-partner.0 + description: DisplayPort + vdo: 0x001c0045 + mode1 + description: DisplayPort + vdo: 0x001c0045 +"; + + print_alt_mode( + &temp_dir_path.join("port0").join("port0-partner").join("port0-partner.0"), + &mut outp_writer, + ); + assert_eq!( + &String::from_utf8(outp_buffer.into_inner()).expect("Cannot decode output buffer"), + expected_outp + ) +} + +#[test] +fn test_print_pdos() { + let temp_dir_path = create_full_typec_connector_class_temp_file_hierarchy(); + let mut outp_buffer: Cursor<Vec<u8>> = Cursor::new(Vec::new()); + let mut outp_writer = OutputWriter::new(&mut outp_buffer, 0); + let expected_outp = "pd0 + revision: 3.0 + sink-capabilities + uevent:\x20 + 1:fixed_supply + operational_current: 0mA + voltage: 5000mV + source-capabilities + uevent:\x20 + 2:fixed_supply + maximum_current: 3000mA + voltage: 9000mV + 4:fixed_supply + maximum_current: 3000mA + voltage: 20000mV +"; + + print_pdos(&temp_dir_path.join("port0").join("port0-partner").join("pd0"), &mut outp_writer); + + assert_eq!( + &String::from_utf8(outp_buffer.into_inner()).expect("Cannot decode output buffer"), + expected_outp + ) +} + +#[test] +fn test_get_cable_product_type() { + let temp_dir_path = create_temp_dir_with_dirs_files_content(&[ + ("port0-cable", &[("usb_power_delivery_revision", "3.0")]), + ("port0-cable/identity", &[("id_header", "0x1c6003f0")]), + ]); + let expected_outp: ProductType = ProductType::Cable((CableType::Passive, PdRev::Pd30)); + + let prod_type = get_cable_product_type(&temp_dir_path.join("port0-cable")); + + assert_eq!(prod_type, expected_outp) +} + +#[test] +fn test_full_command_output() { + let temp_dir_path = create_full_typec_connector_class_temp_file_hierarchy(); + let mut outp_buffer: Cursor<Vec<u8>> = Cursor::new(Vec::new()); + let mut outp_writer = OutputWriter::new(&mut outp_buffer, 0); + let expected_outp = "port0 + data_role: [host] device + uevent: DEVTYPE=typec_port + TYPEC_PORT=port0 + vconn_source: yes + port0-partner + number_of_alternate_modes: 1 + usb_power_delivery_revision: 3.0 + identity + id_header: 0x4c4018d1 + USB Vendor ID: 0x18d1 + Reserved: 0x40 + Product Type (DFP): 0x0 + Modal Operation Supported: 0x1 + Product Type (UFP/Cable Plug): 0x1 + USB Capable as a USB Device: 0x1 + USB Capable as a USB Host: 0x0 + cert_stat: 0x0 + XID: 0x0 + product: 0x50490001 + bcdDevice: 0x1 + USB Product ID: 0x5049 + product_type_vdo1: 0x45800012 + USB Highest Speed: 0x2 + Alternate Modes: 0x2 + Reserved: 0x20000 + Device Capability: 0x5 + Reserved: 0x0 + UFP VDO Version: 0x2 + product_type_vdo2: 0x0 + USB3 Max Power: 0x0 + USB3 Min Power: 0x0 + Reserved: 0x0 + USB4 Max Power: 0x0 + USB4 Min Power: 0x0 + Reserved: 0x0 + product_type_vdo3: 0x0 + port0-partner.0 + description: DisplayPort + vdo: 0x001c0045 + mode1 + description: DisplayPort + vdo: 0x001c0045 + pd0 + revision: 3.0 + sink-capabilities + uevent:\x20 + 1:fixed_supply + operational_current: 0mA + voltage: 5000mV + source-capabilities + uevent:\x20 + 2:fixed_supply + maximum_current: 3000mA + voltage: 9000mV + 4:fixed_supply + maximum_current: 3000mA + voltage: 20000mV + port0-cable + usb_power_delivery_revision: 3.0 + identity + id_header: 0x1800228a + USB Vendor ID: 0x228a + Reserved: 0x0 + Product Type (DFP): 0x0 + Modal Operation Supported: 0x0 + Product Type (UFP/Cable Plug): 0x3 + USB Capable as a USB Device: 0x0 + USB Capable as a USB Host: 0x0 + cert_stat: 0x290 + XID: 0x290 + product: 0x94880001 + bcdDevice: 0x1 + USB Product ID: 0x9488 + product_type_vdo1: 0x11082043 + USB Speed: 0x3 + Reserved: 0x0 + Vbus Current Handling: 0x2 + Reserved: 0x0 + Maximum Vbus Voltage: 0x0 + Cable Termination Type: 0x0 + Cable Latency: 0x1 + Reserved: 0x0 + USB Type-C Plug to USB Type: 0x2 + Reserved: 0x0 + VDO Version: 0x0 + Firmware Version: 0x1 + HW Version: 0x1 + product_type_vdo2: 0x0 + product_type_vdo3: 0x0 + port0-plug0 + number_of_alternate_modes: 2 + port0-plug0.0 + mode: 1 + svid: 1e4e + mode1 + active: no + vdo: 0x9031011c + port0-plug0.1 + mode: 1 + svid: 8087 + mode1 + active: no + vdo: 0x00030001 + physical_location + panel: right + horizontal_position: right + usb_device + busnum: 3 + devnum: 9 + devpath: 1 + usb_device + busnum: 3 + devnum: 10 + devpath: 1.1 + usb_device + busnum: 3 + devnum: 11 + devpath: 1.2 + usb_device + busnum: 3 + devnum: 12 + devpath: 1.2.4 + dp_connector + connector_id: 258 + status: disconnected +port1 +"; + let _ = parse_dirs_and_execute(&temp_dir_path, &mut outp_writer, PORT_REGEX, print_port_info); + assert_eq!( + &String::from_utf8(outp_buffer.into_inner()).expect("Cannot decode output buffer"), + expected_outp + ) +}
diff --git a/typec_connector_class_helper/src/usb_pd_utils.rs b/typec_connector_class_helper/src/usb_pd_utils.rs new file mode 100644 index 0000000..35f51fb --- /dev/null +++ b/typec_connector_class_helper/src/usb_pd_utils.rs
@@ -0,0 +1,415 @@ +// Copyright 2024 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! usb_pd_utils + +/// Contains information for decoding a specific piece of data from a +/// Vendor Data Object (VDO). +pub struct VdoField { + pub index: i32, + pub mask: u32, + pub description: &'static str, +} + +impl VdoField { + /// Returns the "description: field_value" string for a VDO field. + pub fn decode_vdo(&self, vdo: u32) -> String { + let field_val: u32 = (vdo & self.mask) >> self.index; + [self.description, &format!(": 0x{:x}", field_val)].concat() + } +} + +// Masks for id_header fields. +pub const UFP_PRODUCT_TYPE_MASK: u32 = 0x38000000; +pub const DFP_PRODUCT_TYPE_MASK: u32 = 0x03800000; + +#[derive(Debug, PartialEq)] +pub enum PdRev { + None, + Pd20, + Pd30, + Pd31, +} + +#[derive(Debug, PartialEq)] +pub enum CableType { + Passive, + Active, + Vpd, +} + +#[derive(Debug, PartialEq)] +pub enum PortType { + Ufp, + Dfp, + Drd, +} + +#[derive(Debug, PartialEq)] +pub enum ProductType { + Cable((CableType, PdRev)), + Ama(PdRev), + Vpd(PdRev), + Port((PortType, PdRev)), + Other, +} + +/// Constants specific to USB PD revision 2.0. +pub mod pd20_data { + use super::VdoField; + + // Expected product identifiers extracted from id_header VDO. + pub const AMA_COMP: u32 = 0x28000000; + // Expected id_header field results. + pub const PASSIVE_CABLE_COMP: u32 = 0x20000000; + pub const ACTIVE_CABLE_COMP: u32 = 0x18000000; + + // Vendor Data Objects (VDO) decoding information (source: USB PD spec). + pub const ID_HEADER_VDO: &[VdoField] = &[ + VdoField { index: 0, mask: 0x0000ffff, description: "USB Vendor ID" }, + VdoField { index: 16, mask: 0x03ff0000, description: "Reserved" }, + VdoField { index: 26, mask: 0x04000000, description: "Modal Operation Supported" }, + VdoField { index: 27, mask: 0x38000000, description: "Product Type" }, + VdoField { index: 30, mask: 0x40000000, description: "USB Capable as a USB Device" }, + VdoField { index: 31, mask: 0x80000000, description: "USB Capable as a USB Host" }, + ]; + + pub const CERT_STAT_VDO: &[VdoField] = + &[VdoField { index: 0, mask: 0xffffffff, description: "XID" }]; + + pub const PRODUCT_VDO: &[VdoField] = &[ + VdoField { index: 0, mask: 0x0000ffff, description: "bcdDevice" }, + VdoField { index: 16, mask: 0xffff0000, description: "USB Product ID" }, + ]; + + pub const AMA_VDO: &[VdoField] = &[ + VdoField { index: 0, mask: 0x00000007, description: "USB SS Signaling Support" }, + VdoField { index: 3, mask: 0x00000008, description: "Vbus Required" }, + VdoField { index: 4, mask: 0x00000010, description: "Vconn Required" }, + VdoField { index: 5, mask: 0x000000e0, description: "Vconn Power" }, + VdoField { index: 8, mask: 0x00000100, description: "SSRX2 Directionality Support" }, + VdoField { index: 9, mask: 0x00000200, description: "SSRX1 Directionality Support" }, + VdoField { index: 10, mask: 0x00000400, description: "SSTX2 Directionality Support" }, + VdoField { index: 11, mask: 0x00000800, description: "SSTX1 Directionality Support" }, + VdoField { index: 12, mask: 0x00fff000, description: "Reserved" }, + VdoField { index: 24, mask: 0x0f000000, description: "Firmware Version" }, + VdoField { index: 28, mask: 0xf0000000, description: "Hardware Version" }, + ]; + + pub const PASSIVE_VDO: &[VdoField] = &[ + VdoField { index: 0, mask: 0x00000007, description: "USB Speed" }, + VdoField { index: 3, mask: 0x00000008, description: "Reserved" }, + VdoField { index: 4, mask: 0x00000010, description: "Vbus Through Cable" }, + VdoField { index: 5, mask: 0x00000060, description: "Vbus Current Handling" }, + VdoField { index: 7, mask: 0x00000080, description: "SSRX2 Directionality Support" }, + VdoField { index: 8, mask: 0x00000100, description: "SSRX1 Directionality Support" }, + VdoField { index: 9, mask: 0x00000200, description: "SSTX2 Directionality Support" }, + VdoField { index: 10, mask: 0x00000400, description: "SSTX1 Directionality Support" }, + VdoField { index: 11, mask: 0x00001800, description: "Cable Termination Type" }, + VdoField { index: 13, mask: 0x0001e000, description: "Cable Latency" }, + VdoField { index: 17, mask: 0x00020000, description: "Reserved" }, + VdoField { index: 18, mask: 0x000c0000, description: "USB Type-C Plug to USB Type" }, + VdoField { index: 20, mask: 0x00f00000, description: "Reserved" }, + VdoField { index: 24, mask: 0x0f000000, description: "Firmware Version" }, + VdoField { index: 28, mask: 0xf0000000, description: "HW Version" }, + ]; + + pub const ACTIVE_VDO: &[VdoField] = &[ + VdoField { index: 0, mask: 0x00000007, description: "USB Speed" }, + VdoField { index: 3, mask: 0x00000008, description: "SOP'' Controller Present" }, + VdoField { index: 4, mask: 0x00000010, description: "Vbus Through Cable" }, + VdoField { index: 5, mask: 0x00000060, description: "Vbus Current Handling" }, + VdoField { index: 7, mask: 0x00000080, description: "SSRX2 Directionality Support" }, + VdoField { index: 8, mask: 0x00000100, description: "SSRX1 Directionality Support" }, + VdoField { index: 9, mask: 0x00000200, description: "SSTX2 Directionality Support" }, + VdoField { index: 10, mask: 0x00000400, description: "SSTX1 Directionality Support" }, + VdoField { index: 11, mask: 0x00001800, description: "Cable Termination Type" }, + VdoField { index: 13, mask: 0x0001e000, description: "Cable Latency" }, + VdoField { index: 17, mask: 0x00020000, description: "Reserved" }, + VdoField { index: 18, mask: 0x000c0000, description: "USB Type-C Plug to USB Type" }, + VdoField { index: 20, mask: 0x00f00000, description: "Reserved" }, + VdoField { index: 24, mask: 0x0f000000, description: "Firmware Version" }, + VdoField { index: 28, mask: 0xf0000000, description: "HW Version" }, + ]; +} + +/// Constants specific to USB PD revision 3.0. +pub mod pd30_data { + use super::VdoField; + + pub const AMA_COMP: u32 = 0x28000000; + pub const VPD_COMP: u32 = 0x30000000; + pub const HUB_COMP: u32 = 0x08000000; + pub const PERIPHERAL_COMP: u32 = 0x10000000; + pub const DFP_HUB_COMP: u32 = 0x00800000; + pub const DFP_HOST_COMP: u32 = 0x01000000; + pub const POWER_BRICK_COMP: u32 = 0x01800000; + // Expected id_header field results. + pub const PASSIVE_CABLE_COMP: u32 = 0x18000000; + pub const ACTIVE_CABLE_COMP: u32 = 0x20000000; + + pub const ID_HEADER_VDO: &[VdoField] = &[ + VdoField { index: 0, mask: 0x0000ffff, description: "USB Vendor ID" }, + VdoField { index: 16, mask: 0x007f0000, description: "Reserved" }, + VdoField { index: 23, mask: 0x03800000, description: "Product Type (DFP)" }, + VdoField { index: 26, mask: 0x04000000, description: "Modal Operation Supported" }, + VdoField { index: 27, mask: 0x38000000, description: "Product Type (UFP/Cable Plug)" }, + VdoField { index: 30, mask: 0x40000000, description: "USB Capable as a USB Device" }, + VdoField { index: 31, mask: 0x80000000, description: "USB Capable as a USB Host" }, + ]; + + pub const CERT_STAT_VDO: &[VdoField] = + &[VdoField { index: 0, mask: 0xffffffff, description: "XID" }]; + + pub const PRODUCT_VDO: &[VdoField] = &[ + VdoField { index: 0, mask: 0x0000ffff, description: "bcdDevice" }, + VdoField { index: 16, mask: 0xffff0000, description: "USB Product ID" }, + ]; + + pub const AMA_VDO: &[VdoField] = &[ + VdoField { index: 0, mask: 0x00000007, description: "USB Highest Speed" }, + VdoField { index: 3, mask: 0x00000008, description: "Vbus Required" }, + VdoField { index: 4, mask: 0x00000010, description: "Vconn Required" }, + VdoField { index: 5, mask: 0x000000e0, description: "Vconn Power" }, + VdoField { index: 8, mask: 0x001fff00, description: "Reserved" }, + VdoField { index: 21, mask: 0x00e00000, description: "VDO Version" }, + VdoField { index: 24, mask: 0x0f000000, description: "Firmware Version" }, + VdoField { index: 28, mask: 0xf0000000, description: "Hardware Version" }, + ]; + + pub const VPD_VDO: &[VdoField] = &[ + VdoField { index: 0, mask: 0x00000001, description: "Charge Through Support" }, + VdoField { index: 1, mask: 0x0000007e, description: "Ground Impedance" }, + VdoField { index: 7, mask: 0x00001f80, description: "Vbus Impedance" }, + VdoField { index: 13, mask: 0x00002000, description: "Reserved" }, + VdoField { index: 14, mask: 0x00004000, description: "Charge Through Current Support" }, + VdoField { index: 15, mask: 0x00018000, description: "Maximum Vbus Voltage" }, + VdoField { index: 17, mask: 0x001e0000, description: "Reserved" }, + ]; + + pub const PASSIVE_VDO: &[VdoField] = &[ + VdoField { index: 0, mask: 0x00000007, description: "USB Speed" }, + VdoField { index: 3, mask: 0x00000018, description: "Reserved" }, + VdoField { index: 5, mask: 0x00000060, description: "Vbus Current Handling" }, + VdoField { index: 7, mask: 0x00000180, description: "Reserved" }, + VdoField { index: 9, mask: 0x00000600, description: "Maximum Vbus Voltage" }, + VdoField { index: 11, mask: 0x00001800, description: "Cable Termination Type" }, + VdoField { index: 13, mask: 0x0001e000, description: "Cable Latency" }, + VdoField { index: 17, mask: 0x00020000, description: "Reserved" }, + VdoField { index: 18, mask: 0x000c0000, description: "USB Type-C Plug to USB Type" }, + VdoField { index: 20, mask: 0x00100000, description: "Reserved" }, + VdoField { index: 21, mask: 0x00e00000, description: "VDO Version" }, + VdoField { index: 24, mask: 0x0f000000, description: "Firmware Version" }, + VdoField { index: 28, mask: 0xf0000000, description: "HW Version" }, + ]; + + pub const UFP_VDO1: &[VdoField] = &[ + VdoField { index: 0, mask: 0x00000007, description: "USB Highest Speed" }, + VdoField { index: 3, mask: 0x00000038, description: "Alternate Modes" }, + VdoField { index: 6, mask: 0x00ffffc0, description: "Reserved" }, + VdoField { index: 24, mask: 0x0f000000, description: "Device Capability" }, + VdoField { index: 28, mask: 0x10000000, description: "Reserved" }, + VdoField { index: 29, mask: 0xe0000000, description: "UFP VDO Version" }, + ]; + + pub const UFP_VDO2: &[VdoField] = &[ + VdoField { index: 0, mask: 0x0000007f, description: "USB3 Max Power" }, + VdoField { index: 7, mask: 0x00003f80, description: "USB3 Min Power" }, + VdoField { index: 14, mask: 0x0000c000, description: "Reserved" }, + VdoField { index: 16, mask: 0x007f0000, description: "USB4 Max Power" }, + VdoField { index: 23, mask: 0x3f800000, description: "USB4 Min Power" }, + VdoField { index: 30, mask: 0xc0000000, description: "Reserved" }, + ]; + + pub const DFP_VDO: &[VdoField] = &[ + VdoField { index: 0, mask: 0x0000001f, description: "Port Number" }, + VdoField { index: 5, mask: 0x00ffffe0, description: "Reserved" }, + VdoField { index: 24, mask: 0x07000000, description: "Host Capability" }, + VdoField { index: 27, mask: 0x18000000, description: "Reserved" }, + VdoField { index: 29, mask: 0xe0000000, description: "DFP VDO Version" }, + VdoField { index: 21, mask: 0x00e00000, description: "VDO Version" }, + VdoField { index: 24, mask: 0x0f000000, description: "Firmware Version" }, + VdoField { index: 28, mask: 0xf0000000, description: "HW Version" }, + ]; + + pub const ACTIVE_VDO1: &[VdoField] = &[ + VdoField { index: 0, mask: 0x00000007, description: "USB Speed" }, + VdoField { index: 3, mask: 0x00000008, description: "SOP'' Controller Present" }, + VdoField { index: 4, mask: 0x00000010, description: "Vbus Through Cable" }, + VdoField { index: 5, mask: 0x00000060, description: "Vbus Current Handling" }, + VdoField { index: 7, mask: 0x00000080, description: "SBU Type" }, + VdoField { index: 8, mask: 0x00000100, description: "SBU Supported" }, + VdoField { index: 9, mask: 0x00000600, description: "Maximum Vbus Voltage" }, + VdoField { index: 11, mask: 0x00001800, description: "Cable Termination Type" }, + VdoField { index: 13, mask: 0x0001e000, description: "Cable Latency" }, + VdoField { index: 17, mask: 0x00020000, description: "Reserved" }, + VdoField { index: 18, mask: 0x000c0000, description: "Connector Type" }, + VdoField { index: 20, mask: 0x00100000, description: "Reserved" }, + ]; + + pub const ACTIVE_VDO2: &[VdoField] = &[ + VdoField { index: 0, mask: 0x00000001, description: "USB Gen" }, + VdoField { index: 1, mask: 0x00000002, description: "Reserved" }, + VdoField { index: 2, mask: 0x00000004, description: "Optically Insulated Active Cable" }, + VdoField { index: 3, mask: 0x00000008, description: "USB Lanes Supported" }, + VdoField { index: 4, mask: 0x00000010, description: "USB 3.2 Supported" }, + VdoField { index: 5, mask: 0x00000020, description: "USB 2.0 Supported" }, + VdoField { index: 6, mask: 0x000000c0, description: "USB 2.0 Hub Hops Command" }, + VdoField { index: 8, mask: 0x00000100, description: "USB4 Supported" }, + VdoField { index: 9, mask: 0x00000200, description: "Active Element" }, + VdoField { index: 10, mask: 0x00000400, description: "Physical Connection" }, + VdoField { index: 11, mask: 0x00000800, description: "U3 to U0 Transition Mode" }, + VdoField { index: 12, mask: 0x00007000, description: "U3/CLd Power" }, + VdoField { index: 15, mask: 0x00008000, description: "Reserved" }, + VdoField { index: 16, mask: 0x00ff0000, description: "Shutdown Tempurature" }, + VdoField { index: 24, mask: 0xff000000, description: "Max Operating Tempurature" }, + ]; +} + +/// Constants specific to USB PD revision 3.1. +pub mod pd31_data { + use super::VdoField; + + pub const HUB_COMP: u32 = 0x08000000; + pub const PERIPHERAL_COMP: u32 = 0x10000000; + pub const DFP_HUB_COMP: u32 = 0x00800000; + pub const DFP_HOST_COMP: u32 = 0x01000000; + pub const POWER_BRICK_COMP: u32 = 0x01800000; + // Expected id_header field results. + pub const PASSIVE_CABLE_COMP: u32 = 0x18000000; + pub const ACTIVE_CABLE_COMP: u32 = 0x20000000; + pub const VPD_COMP: u32 = 0x30000000; + + pub const ID_HEADER_VDO: &[VdoField] = &[ + VdoField { index: 0, mask: 0x0000ffff, description: "USB Vendor ID" }, + VdoField { index: 16, mask: 0x001f0000, description: "Reserved" }, + VdoField { index: 21, mask: 0x00600000, description: "Connector Type" }, + VdoField { index: 23, mask: 0x03800000, description: "Product Type (DFP)" }, + VdoField { index: 26, mask: 0x04000000, description: "Modal Operation Supported" }, + VdoField { index: 27, mask: 0x38000000, description: "Product Type (UFP/Cable Plug)" }, + VdoField { index: 30, mask: 0x40000000, description: "USB Capable as a USB Device" }, + VdoField { index: 31, mask: 0x80000000, description: "USB Capable as a USB Host" }, + ]; + + pub const CERT_STAT_VDO: &[VdoField] = + &[VdoField { index: 0, mask: 0xffffffff, description: "XID" }]; + + pub const PRODUCT_VDO: &[VdoField] = &[ + VdoField { index: 0, mask: 0x0000ffff, description: "bcdDevice" }, + VdoField { index: 16, mask: 0xffff0000, description: "USB Product ID" }, + ]; + + pub const UFP_VDO: &[VdoField] = &[ + VdoField { index: 0, mask: 0x00000007, description: "USB Highest Speed" }, + VdoField { index: 3, mask: 0x00000038, description: "Alternate Modes" }, + VdoField { index: 6, mask: 0x00000040, description: "Vbus Required" }, + VdoField { index: 7, mask: 0x00000080, description: "Vconn Required" }, + VdoField { index: 8, mask: 0x00000700, description: "Vconn Power" }, + VdoField { index: 11, mask: 0x003ff800, description: "Reserved" }, + VdoField { index: 22, mask: 0x00c00000, description: "Connector Type (Legacy)" }, + VdoField { index: 24, mask: 0x0f000000, description: "Device Capability" }, + VdoField { index: 28, mask: 0x10000000, description: "Reserved" }, + VdoField { index: 29, mask: 0xe0000000, description: "UFP VDO Version" }, + ]; + + pub const DFP_VDO: &[VdoField] = &[ + VdoField { index: 0, mask: 0x0000001f, description: "Port Number" }, + VdoField { index: 5, mask: 0x003fffe0, description: "Reserved" }, + VdoField { index: 22, mask: 0x00c00000, description: "Connector Type (Legacy)" }, + VdoField { index: 24, mask: 0x07000000, description: "Host Capability" }, + VdoField { index: 27, mask: 0x18000000, description: "Reserved" }, + VdoField { index: 29, mask: 0xe0000000, description: "DFP VDO Version" }, + ]; + + pub const PASSIVE_VDO: &[VdoField] = &[ + VdoField { index: 0, mask: 0x00000007, description: "USB Speed" }, + VdoField { index: 3, mask: 0x00000018, description: "Reserved" }, + VdoField { index: 5, mask: 0x00000060, description: "Vbus Current Handling" }, + VdoField { index: 7, mask: 0x00000180, description: "Reserved" }, + VdoField { index: 9, mask: 0x00000600, description: "Maximum Vbus Voltage" }, + VdoField { index: 11, mask: 0x00001800, description: "Cable Termination Type" }, + VdoField { index: 13, mask: 0x0001e000, description: "Cable Latency" }, + VdoField { index: 17, mask: 0x00020000, description: "EPR Mode Cable" }, + VdoField { index: 18, mask: 0x000c0000, description: "USB Type-C Plug to USB Type" }, + VdoField { index: 20, mask: 0x00100000, description: "Reserved" }, + VdoField { index: 21, mask: 0x00e00000, description: "VDO Version" }, + VdoField { index: 24, mask: 0x0f000000, description: "Firmware Version" }, + VdoField { index: 28, mask: 0xf0000000, description: "HW Version" }, + ]; + + pub const ACTIVE_VDO1: &[VdoField] = &[ + VdoField { index: 0, mask: 0x00000007, description: "USB Speed" }, + VdoField { index: 3, mask: 0x00000008, description: "SOP'' Controller Present" }, + VdoField { index: 4, mask: 0x00000010, description: "Vbus Through Cable" }, + VdoField { index: 5, mask: 0x00000060, description: "Vbus Current Handling" }, + VdoField { index: 7, mask: 0x00000080, description: "SBU Type" }, + VdoField { index: 8, mask: 0x00000100, description: "SBU Supported" }, + VdoField { index: 9, mask: 0x00000600, description: "Maximum Vbus Voltage" }, + VdoField { index: 11, mask: 0x00001800, description: "Cable Termination Type" }, + VdoField { index: 13, mask: 0x0001e000, description: "Cable Latency" }, + VdoField { index: 17, mask: 0x00020000, description: "EPR Mode Cable" }, + VdoField { index: 18, mask: 0x000c0000, description: "USB Type-C Plug to USB Type" }, + VdoField { index: 20, mask: 0x00100000, description: "Reserved" }, + VdoField { index: 21, mask: 0x00e00000, description: "VDO Version" }, + VdoField { index: 24, mask: 0x0f000000, description: "Firmware Version" }, + VdoField { index: 28, mask: 0xf0000000, description: "HW Version" }, + ]; + + pub const ACTIVE_VDO2: &[VdoField] = &[ + VdoField { index: 0, mask: 0x00000001, description: "USB Gen" }, + VdoField { index: 1, mask: 0x00000002, description: "Reserved" }, + VdoField { index: 2, mask: 0x00000004, description: "Optically Insulated Active Cable" }, + VdoField { index: 3, mask: 0x00000008, description: "USB Lanes Supported" }, + VdoField { index: 4, mask: 0x00000010, description: "USB 3.2 Supported" }, + VdoField { index: 5, mask: 0x00000020, description: "USB 2.0 Supported" }, + VdoField { index: 6, mask: 0x000000c0, description: "USB 2.0 Hub Hops Command" }, // Corrected mask + VdoField { index: 8, mask: 0x00000100, description: "USB4 Supported" }, + VdoField { index: 9, mask: 0x00000200, description: "Active Element" }, + VdoField { index: 10, mask: 0x00000400, description: "Physical Connection" }, + VdoField { index: 11, mask: 0x00000800, description: "U3 to U0 Transition Mode" }, + VdoField { index: 12, mask: 0x00007000, description: "U3/CLd Power" }, + VdoField { index: 15, mask: 0x00008000, description: "Reserved" }, + VdoField { index: 16, mask: 0x00ff0000, description: "Shutdown Tempurature" }, + VdoField { index: 24, mask: 0xff000000, description: "Max Operating Tempurature" }, + ]; + + pub const VPD_VDO: &[VdoField] = &[ + VdoField { index: 0, mask: 0x00000001, description: "Charge Through Support" }, + VdoField { index: 1, mask: 0x0000007e, description: "Ground Impedance" }, + VdoField { index: 7, mask: 0x00001f80, description: "Vbus Impedance" }, + VdoField { index: 13, mask: 0x00002000, description: "Reserved" }, + VdoField { index: 14, mask: 0x00004000, description: "Charge Through Current Support" }, + VdoField { index: 15, mask: 0x00018000, description: "Maximum Vbus Voltage" }, + VdoField { index: 17, mask: 0x001e0000, description: "Reserved" }, + VdoField { index: 21, mask: 0x00e00000, description: "VDO Version" }, + VdoField { index: 24, mask: 0x0f000000, description: "Firmware Version" }, + VdoField { index: 28, mask: 0xf0000000, description: "HW Version" }, + ]; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_decode_vdo() { + let vdo: u32 = 0x12341234; + let field = VdoField { + index: 4, + mask: 0x000000f0, + description: "Value of the 2nd least significant byte", + }; + assert_eq!(field.decode_vdo(vdo), "Value of the 2nd least significant byte: 0x3") + } +}