usbpdpy 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,60 @@
1
+ # Rust
2
+ target/
3
+ Cargo.lock
4
+
5
+ # Python
6
+ __pycache__/
7
+ *.py[cod]
8
+ *$py.class
9
+ *.so
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ *.egg-info/
24
+ .installed.cfg
25
+ *.egg
26
+ MANIFEST
27
+
28
+ # Virtual environments
29
+ .env
30
+ .venv
31
+ env/
32
+ venv/
33
+ ENV/
34
+ env.bak/
35
+ venv.bak/
36
+
37
+ # IDEs
38
+ .vscode/
39
+ .idea/
40
+ *.swp
41
+ *.swo
42
+ *~
43
+
44
+ # Testing
45
+ .coverage
46
+ .pytest_cache/
47
+ .tox/
48
+ .cache
49
+ nosetests.xml
50
+ coverage.xml
51
+ *.cover
52
+ .hypothesis/
53
+
54
+ # macOS
55
+ .DS_Store
56
+
57
+ # Windows
58
+ Thumbs.db
59
+ ehthumbs.db
60
+ Desktop.ini
@@ -0,0 +1,171 @@
1
+ # This file is automatically @generated by Cargo.
2
+ # It is not intended for manual editing.
3
+ version = 4
4
+
5
+ [[package]]
6
+ name = "autocfg"
7
+ version = "1.5.0"
8
+ source = "registry+https://github.com/rust-lang/crates.io-index"
9
+ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
10
+
11
+ [[package]]
12
+ name = "heck"
13
+ version = "0.5.0"
14
+ source = "registry+https://github.com/rust-lang/crates.io-index"
15
+ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
16
+
17
+ [[package]]
18
+ name = "hex"
19
+ version = "0.4.3"
20
+ source = "registry+https://github.com/rust-lang/crates.io-index"
21
+ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
22
+
23
+ [[package]]
24
+ name = "indoc"
25
+ version = "2.0.6"
26
+ source = "registry+https://github.com/rust-lang/crates.io-index"
27
+ checksum = "f4c7245a08504955605670dbf141fceab975f15ca21570696aebe9d2e71576bd"
28
+
29
+ [[package]]
30
+ name = "libc"
31
+ version = "0.2.175"
32
+ source = "registry+https://github.com/rust-lang/crates.io-index"
33
+ checksum = "6a82ae493e598baaea5209805c49bbf2ea7de956d50d7da0da1164f9c6d28543"
34
+
35
+ [[package]]
36
+ name = "memoffset"
37
+ version = "0.9.1"
38
+ source = "registry+https://github.com/rust-lang/crates.io-index"
39
+ checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
40
+ dependencies = [
41
+ "autocfg",
42
+ ]
43
+
44
+ [[package]]
45
+ name = "once_cell"
46
+ version = "1.21.3"
47
+ source = "registry+https://github.com/rust-lang/crates.io-index"
48
+ checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
49
+
50
+ [[package]]
51
+ name = "portable-atomic"
52
+ version = "1.11.1"
53
+ source = "registry+https://github.com/rust-lang/crates.io-index"
54
+ checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483"
55
+
56
+ [[package]]
57
+ name = "proc-macro2"
58
+ version = "1.0.101"
59
+ source = "registry+https://github.com/rust-lang/crates.io-index"
60
+ checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de"
61
+ dependencies = [
62
+ "unicode-ident",
63
+ ]
64
+
65
+ [[package]]
66
+ name = "pyo3"
67
+ version = "0.26.0"
68
+ source = "registry+https://github.com/rust-lang/crates.io-index"
69
+ checksum = "7ba0117f4212101ee6544044dae45abe1083d30ce7b29c4b5cbdfa2354e07383"
70
+ dependencies = [
71
+ "indoc",
72
+ "libc",
73
+ "memoffset",
74
+ "once_cell",
75
+ "portable-atomic",
76
+ "pyo3-build-config",
77
+ "pyo3-ffi",
78
+ "pyo3-macros",
79
+ "unindent",
80
+ ]
81
+
82
+ [[package]]
83
+ name = "pyo3-build-config"
84
+ version = "0.26.0"
85
+ source = "registry+https://github.com/rust-lang/crates.io-index"
86
+ checksum = "4fc6ddaf24947d12a9aa31ac65431fb1b851b8f4365426e182901eabfb87df5f"
87
+ dependencies = [
88
+ "target-lexicon",
89
+ ]
90
+
91
+ [[package]]
92
+ name = "pyo3-ffi"
93
+ version = "0.26.0"
94
+ source = "registry+https://github.com/rust-lang/crates.io-index"
95
+ checksum = "025474d3928738efb38ac36d4744a74a400c901c7596199e20e45d98eb194105"
96
+ dependencies = [
97
+ "libc",
98
+ "pyo3-build-config",
99
+ ]
100
+
101
+ [[package]]
102
+ name = "pyo3-macros"
103
+ version = "0.26.0"
104
+ source = "registry+https://github.com/rust-lang/crates.io-index"
105
+ checksum = "2e64eb489f22fe1c95911b77c44cc41e7c19f3082fc81cce90f657cdc42ffded"
106
+ dependencies = [
107
+ "proc-macro2",
108
+ "pyo3-macros-backend",
109
+ "quote",
110
+ "syn",
111
+ ]
112
+
113
+ [[package]]
114
+ name = "pyo3-macros-backend"
115
+ version = "0.26.0"
116
+ source = "registry+https://github.com/rust-lang/crates.io-index"
117
+ checksum = "100246c0ecf400b475341b8455a9213344569af29a3c841d29270e53102e0fcf"
118
+ dependencies = [
119
+ "heck",
120
+ "proc-macro2",
121
+ "pyo3-build-config",
122
+ "quote",
123
+ "syn",
124
+ ]
125
+
126
+ [[package]]
127
+ name = "quote"
128
+ version = "1.0.40"
129
+ source = "registry+https://github.com/rust-lang/crates.io-index"
130
+ checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
131
+ dependencies = [
132
+ "proc-macro2",
133
+ ]
134
+
135
+ [[package]]
136
+ name = "syn"
137
+ version = "2.0.106"
138
+ source = "registry+https://github.com/rust-lang/crates.io-index"
139
+ checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6"
140
+ dependencies = [
141
+ "proc-macro2",
142
+ "quote",
143
+ "unicode-ident",
144
+ ]
145
+
146
+ [[package]]
147
+ name = "target-lexicon"
148
+ version = "0.13.2"
149
+ source = "registry+https://github.com/rust-lang/crates.io-index"
150
+ checksum = "e502f78cdbb8ba4718f566c418c52bc729126ffd16baee5baa718cf25dd5a69a"
151
+
152
+ [[package]]
153
+ name = "unicode-ident"
154
+ version = "1.0.18"
155
+ source = "registry+https://github.com/rust-lang/crates.io-index"
156
+ checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
157
+
158
+ [[package]]
159
+ name = "unindent"
160
+ version = "0.2.4"
161
+ source = "registry+https://github.com/rust-lang/crates.io-index"
162
+ checksum = "7264e107f553ccae879d21fbea1d6724ac785e8c3bfc762137959b5802826ef3"
163
+
164
+ [[package]]
165
+ name = "usbpdpy"
166
+ version = "0.1.0"
167
+ dependencies = [
168
+ "hex",
169
+ "pyo3",
170
+ "pyo3-build-config",
171
+ ]
@@ -0,0 +1,26 @@
1
+ [package]
2
+ name = "usbpdpy"
3
+ version = "0.1.0"
4
+ edition = "2021"
5
+ authors = ["Danila Gornushko <me@okhsunrog.dev>"]
6
+ license = "MIT"
7
+ description = "Python bindings for the usbpd Rust crate - fast USB Power Delivery message parsing"
8
+ repository = "https://github.com/okhsunrog/usbpdpy"
9
+ homepage = "https://github.com/okhsunrog/usbpdpy"
10
+ keywords = ["usb", "usb-pd", "power-delivery", "protocol", "parsing"]
11
+ categories = ["api-bindings", "parsing", "hardware-support"]
12
+ readme = "README.md"
13
+
14
+ [workspace]
15
+ # This is an independent workspace
16
+
17
+ [lib]
18
+ name = "usbpdpy"
19
+ crate-type = ["cdylib"]
20
+
21
+ [dependencies]
22
+ pyo3 = { version = "0.26.0", features = ["extension-module"] }
23
+ hex = "0.4"
24
+
25
+ [build-dependencies]
26
+ pyo3-build-config = "0.26.0"
usbpdpy-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Danila Gornushko
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
usbpdpy-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.4
2
+ Name: usbpdpy
3
+ Version: 0.1.0
4
+ Classifier: Development Status :: 4 - Beta
5
+ Classifier: Intended Audience :: Developers
6
+ Classifier: Intended Audience :: Science/Research
7
+ Classifier: Topic :: System :: Hardware :: Universal Serial Bus (USB)
8
+ Classifier: Topic :: Scientific/Engineering :: Electronic Design Automation (EDA)
9
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Rust
18
+ Classifier: Programming Language :: Python :: Implementation :: CPython
19
+ License-File: LICENSE
20
+ Summary: Python bindings for the usbpd Rust crate - fast USB Power Delivery message parsing
21
+ Keywords: usb,usb-pd,power-delivery,protocol,parsing,hardware
22
+ Home-Page: https://github.com/okhsunrog/usbpdpy
23
+ Author-email: Danila Gornushko <me@okhsunrog.dev>
24
+ License: MIT
25
+ Requires-Python: >=3.8
26
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
27
+ Project-URL: Homepage, https://github.com/okhsunrog/usbpdpy
28
+ Project-URL: Repository, https://github.com/okhsunrog/usbpdpy
29
+ Project-URL: Issues, https://github.com/okhsunrog/usbpdpy/issues
30
+ Project-URL: Documentation, https://github.com/okhsunrog/usbpdpy#readme
31
+
32
+ # usbpdpy
33
+
34
+ Python bindings for the [`usbpd`](https://crates.io/crates/usbpd) Rust crate.
35
+
36
+ ## Installation
37
+
38
+ ```bash
39
+ pip install usbpdpy
40
+ ```
41
+
42
+ ## Usage
43
+
44
+ ```python
45
+ import usbpdpy
46
+
47
+ # Parse message from bytes
48
+ message = usbpdpy.parse_pd_message(b'\x61\x11')
49
+ print(f"Type: {message.header.message_type}")
50
+ print(f"Name: {usbpdpy.get_message_type_name(message.header.message_type)}")
51
+
52
+ # Convert hex to bytes
53
+ data = usbpdpy.hex_to_bytes("1161")
54
+ message = usbpdpy.parse_pd_message(data)
55
+ ```
56
+
57
+ ## API
58
+
59
+ ### Functions
60
+
61
+ - `parse_pd_message(data: bytes) -> PyPdMessage`
62
+ - `parse_pd_messages(messages: List[bytes]) -> List[PyPdMessage]`
63
+ - `get_message_type_name(msg_type: int) -> str`
64
+ - `hex_to_bytes(hex_str: str) -> bytes`
65
+ - `bytes_to_hex(data: bytes) -> str`
66
+
67
+ ### Classes
68
+
69
+ **PyPdMessage**
70
+ - `header: PyPdHeader`
71
+ - `data_objects: List[PyPdDataObject]`
72
+ - `raw_bytes: List[int]`
73
+ - `get_hex() -> str`
74
+
75
+ **PyPdHeader**
76
+ - `message_type: int`
77
+ - `port_data_role: str` ("UFP"/"DFP")
78
+ - `port_power_role: str` ("Sink"/"Source")
79
+ - `message_id: int`
80
+ - `number_of_data_objects: int`
81
+ - `extended: bool`
82
+
83
+ **PyPdDataObject**
84
+ - `raw: int`
85
+ - `object_type: str`
86
+ - `parsed_data: Optional[str]`
87
+
88
+ ## Requirements
89
+
90
+ - Python 3.8+
91
+ - No runtime dependencies
92
+
93
+ ## License
94
+
95
+ MIT
@@ -0,0 +1,64 @@
1
+ # usbpdpy
2
+
3
+ Python bindings for the [`usbpd`](https://crates.io/crates/usbpd) Rust crate.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install usbpdpy
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```python
14
+ import usbpdpy
15
+
16
+ # Parse message from bytes
17
+ message = usbpdpy.parse_pd_message(b'\x61\x11')
18
+ print(f"Type: {message.header.message_type}")
19
+ print(f"Name: {usbpdpy.get_message_type_name(message.header.message_type)}")
20
+
21
+ # Convert hex to bytes
22
+ data = usbpdpy.hex_to_bytes("1161")
23
+ message = usbpdpy.parse_pd_message(data)
24
+ ```
25
+
26
+ ## API
27
+
28
+ ### Functions
29
+
30
+ - `parse_pd_message(data: bytes) -> PyPdMessage`
31
+ - `parse_pd_messages(messages: List[bytes]) -> List[PyPdMessage]`
32
+ - `get_message_type_name(msg_type: int) -> str`
33
+ - `hex_to_bytes(hex_str: str) -> bytes`
34
+ - `bytes_to_hex(data: bytes) -> str`
35
+
36
+ ### Classes
37
+
38
+ **PyPdMessage**
39
+ - `header: PyPdHeader`
40
+ - `data_objects: List[PyPdDataObject]`
41
+ - `raw_bytes: List[int]`
42
+ - `get_hex() -> str`
43
+
44
+ **PyPdHeader**
45
+ - `message_type: int`
46
+ - `port_data_role: str` ("UFP"/"DFP")
47
+ - `port_power_role: str` ("Sink"/"Source")
48
+ - `message_id: int`
49
+ - `number_of_data_objects: int`
50
+ - `extended: bool`
51
+
52
+ **PyPdDataObject**
53
+ - `raw: int`
54
+ - `object_type: str`
55
+ - `parsed_data: Optional[str]`
56
+
57
+ ## Requirements
58
+
59
+ - Python 3.8+
60
+ - No runtime dependencies
61
+
62
+ ## License
63
+
64
+ MIT
@@ -0,0 +1,50 @@
1
+ [build-system]
2
+ requires = ["maturin>=1.0,<2.0"]
3
+ build-backend = "maturin"
4
+
5
+ [project]
6
+ name = "usbpdpy"
7
+ description = "Python bindings for the usbpd Rust crate - fast USB Power Delivery message parsing"
8
+ version = "0.1.0"
9
+ authors = [
10
+ {name = "Danila Gornushko", email = "me@okhsunrog.dev"},
11
+ ]
12
+ license = {text = "MIT"}
13
+ readme = "README.md"
14
+ requires-python = ">=3.8"
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "Intended Audience :: Science/Research",
19
+ "Topic :: System :: Hardware :: Universal Serial Bus (USB)",
20
+ "Topic :: Scientific/Engineering :: Electronic Design Automation (EDA)",
21
+ "Topic :: Software Development :: Libraries :: Python Modules",
22
+ "License :: OSI Approved :: MIT License",
23
+ "Programming Language :: Python :: 3",
24
+ "Programming Language :: Python :: 3.8",
25
+ "Programming Language :: Python :: 3.9",
26
+ "Programming Language :: Python :: 3.10",
27
+ "Programming Language :: Python :: 3.11",
28
+ "Programming Language :: Python :: 3.12",
29
+ "Programming Language :: Rust",
30
+ "Programming Language :: Python :: Implementation :: CPython",
31
+ ]
32
+ keywords = ["usb", "usb-pd", "power-delivery", "protocol", "parsing", "hardware"]
33
+ dependencies = []
34
+
35
+ [project.urls]
36
+ Homepage = "https://github.com/okhsunrog/usbpdpy"
37
+ Repository = "https://github.com/okhsunrog/usbpdpy"
38
+ Issues = "https://github.com/okhsunrog/usbpdpy/issues"
39
+ Documentation = "https://github.com/okhsunrog/usbpdpy#readme"
40
+
41
+ [tool.maturin]
42
+ module-name = "usbpdpy"
43
+
44
+ [tool.uv]
45
+ dev-dependencies = [
46
+ "pytest>=7.0.0",
47
+ "black>=23.0.0",
48
+ "ruff>=0.1.0",
49
+ "mypy>=1.0.0",
50
+ ]
@@ -0,0 +1,229 @@
1
+ use pyo3::prelude::*;
2
+ use pyo3::types::{PyBytesMethods, PyListMethods};
3
+
4
+ /// Python wrapper for USB PD Header
5
+ #[pyclass]
6
+ #[derive(Clone, Debug)]
7
+ pub struct PyPdHeader {
8
+ #[pyo3(get)]
9
+ pub message_type: u8,
10
+ #[pyo3(get)]
11
+ pub port_data_role: String,
12
+ #[pyo3(get)]
13
+ pub specification_revision: u8,
14
+ #[pyo3(get)]
15
+ pub port_power_role: String,
16
+ #[pyo3(get)]
17
+ pub message_id: u8,
18
+ #[pyo3(get)]
19
+ pub number_of_data_objects: u8,
20
+ #[pyo3(get)]
21
+ pub extended: bool,
22
+ }
23
+
24
+ #[pymethods]
25
+ impl PyPdHeader {
26
+ fn __repr__(&self) -> String {
27
+ format!(
28
+ "PyPdHeader(type={}, data_role={}, power_role={}, msg_id={}, num_objects={})",
29
+ self.message_type,
30
+ self.port_data_role,
31
+ self.port_power_role,
32
+ self.message_id,
33
+ self.number_of_data_objects
34
+ )
35
+ }
36
+
37
+ fn to_dict(&self, py: Python) -> PyResult<Py<pyo3::PyAny>> {
38
+ let dict = pyo3::types::PyDict::new(py);
39
+ dict.set_item("message_type", self.message_type)?;
40
+ dict.set_item("port_data_role", &self.port_data_role)?;
41
+ dict.set_item("specification_revision", self.specification_revision)?;
42
+ dict.set_item("port_power_role", &self.port_power_role)?;
43
+ dict.set_item("message_id", self.message_id)?;
44
+ dict.set_item("number_of_data_objects", self.number_of_data_objects)?;
45
+ dict.set_item("extended", self.extended)?;
46
+ Ok(dict.into())
47
+ }
48
+ }
49
+
50
+ /// Python wrapper for USB PD Data Object
51
+ #[pyclass]
52
+ #[derive(Clone, Debug)]
53
+ pub struct PyPdDataObject {
54
+ #[pyo3(get)]
55
+ pub raw: u32,
56
+ #[pyo3(get)]
57
+ pub object_type: String,
58
+ #[pyo3(get)]
59
+ pub parsed_data: Option<String>, // JSON string of parsed data
60
+ }
61
+
62
+ #[pymethods]
63
+ impl PyPdDataObject {
64
+ fn __repr__(&self) -> String {
65
+ format!("PyPdDataObject(type={}, raw=0x{:08x})", self.object_type, self.raw)
66
+ }
67
+
68
+ fn to_dict(&self, py: Python) -> PyResult<Py<pyo3::PyAny>> {
69
+ let dict = pyo3::types::PyDict::new(py);
70
+ dict.set_item("raw", self.raw)?;
71
+ dict.set_item("object_type", &self.object_type)?;
72
+ dict.set_item("parsed_data", &self.parsed_data)?;
73
+ Ok(dict.into())
74
+ }
75
+ }
76
+
77
+ /// Python wrapper for complete USB PD Message
78
+ #[pyclass]
79
+ #[derive(Clone, Debug)]
80
+ pub struct PyPdMessage {
81
+ #[pyo3(get)]
82
+ pub header: PyPdHeader,
83
+ #[pyo3(get)]
84
+ pub data_objects: Vec<PyPdDataObject>,
85
+ #[pyo3(get)]
86
+ pub raw_bytes: Vec<u8>,
87
+ }
88
+
89
+ #[pymethods]
90
+ impl PyPdMessage {
91
+ fn __repr__(&self) -> String {
92
+ format!(
93
+ "PyPdMessage(type={}, objects={}, raw_len={})",
94
+ self.header.message_type,
95
+ self.data_objects.len(),
96
+ self.raw_bytes.len()
97
+ )
98
+ }
99
+
100
+ fn to_dict(&self, py: Python) -> PyResult<Py<pyo3::PyAny>> {
101
+ let dict = pyo3::types::PyDict::new(py);
102
+ dict.set_item("header", self.header.to_dict(py)?)?;
103
+
104
+ let objects = pyo3::types::PyList::empty(py);
105
+ for obj in &self.data_objects {
106
+ objects.append(obj.to_dict(py)?)?;
107
+ }
108
+ dict.set_item("data_objects", &objects)?;
109
+ dict.set_item("raw_bytes", &self.raw_bytes)?;
110
+ Ok(dict.into())
111
+ }
112
+
113
+ fn get_hex(&self) -> String {
114
+ hex::encode(&self.raw_bytes)
115
+ }
116
+ }
117
+
118
+ /// Parse a USB PD message from raw bytes (simplified version without usbpd crate for now)
119
+ #[pyfunction]
120
+ pub fn parse_pd_message(data: &Bound<'_, pyo3::types::PyBytes>) -> PyResult<PyPdMessage> {
121
+ let bytes = data.as_bytes();
122
+
123
+ if bytes.len() < 2 {
124
+ return Err(pyo3::exceptions::PyValueError::new_err("Message too short"));
125
+ }
126
+
127
+ // Simple parsing - this is a placeholder until we fix the usbpd crate integration
128
+ let header_word = u16::from_le_bytes([bytes[0], bytes[1]]);
129
+
130
+ let header = PyPdHeader {
131
+ message_type: (header_word & 0x1F) as u8,
132
+ port_data_role: if (header_word & 0x20) != 0 { "DFP".to_string() } else { "UFP".to_string() },
133
+ specification_revision: ((header_word >> 6) & 0x3) as u8,
134
+ port_power_role: if (header_word & 0x100) != 0 { "Source".to_string() } else { "Sink".to_string() },
135
+ message_id: ((header_word >> 9) & 0x7) as u8,
136
+ number_of_data_objects: ((header_word >> 12) & 0x7) as u8,
137
+ extended: (header_word & 0x8000) != 0,
138
+ };
139
+
140
+ let data_objects = Vec::new(); // Simplified - no data object parsing yet
141
+
142
+ Ok(PyPdMessage {
143
+ header,
144
+ data_objects,
145
+ raw_bytes: bytes.to_vec(),
146
+ })
147
+ }
148
+
149
+ /// Parse multiple USB PD messages from a list of byte arrays
150
+ #[pyfunction]
151
+ pub fn parse_pd_messages(messages: &Bound<'_, pyo3::types::PyList>) -> PyResult<Vec<PyPdMessage>> {
152
+ let mut parsed_messages = Vec::new();
153
+
154
+ for item in messages.iter() {
155
+ if let Ok(bytes) = item.downcast::<pyo3::types::PyBytes>() {
156
+ match parse_pd_message(&bytes) {
157
+ Ok(msg) => parsed_messages.push(msg),
158
+ Err(e) => {
159
+ // Log error but continue with other messages
160
+ eprintln!("Warning: Failed to parse message: {}", e);
161
+ }
162
+ }
163
+ }
164
+ }
165
+
166
+ Ok(parsed_messages)
167
+ }
168
+
169
+ /// Get message type name from message type number
170
+ #[pyfunction]
171
+ pub fn get_message_type_name(msg_type: u8) -> String {
172
+ match msg_type {
173
+ 0 => "Reserved".to_string(),
174
+ 1 => "GoodCRC".to_string(),
175
+ 2 => "GotoMin".to_string(),
176
+ 3 => "Accept".to_string(),
177
+ 4 => "Reject".to_string(),
178
+ 5 => "Ping".to_string(),
179
+ 6 => "PS_RDY".to_string(),
180
+ 7 => "Get_Source_Cap".to_string(),
181
+ 8 => "Get_Sink_Cap".to_string(),
182
+ 9 => "DR_Swap".to_string(),
183
+ 10 => "PR_Swap".to_string(),
184
+ 11 => "VCONN_Swap".to_string(),
185
+ 12 => "Wait".to_string(),
186
+ 13 => "Soft_Reset".to_string(),
187
+ 14 => "Data_Reset".to_string(),
188
+ 15 => "Data_Reset_Complete".to_string(),
189
+ 16 => "Not_Supported".to_string(),
190
+ 17 => "Get_Source_Cap_Extended".to_string(),
191
+ 18 => "Get_Status".to_string(),
192
+ 19 => "FR_Swap".to_string(),
193
+ 20 => "Get_PPS_Status".to_string(),
194
+ 21 => "Get_Country_Codes".to_string(),
195
+ 22 => "Get_Sink_Cap_Extended".to_string(),
196
+ 23 => "Get_Source_Info".to_string(),
197
+ 24 => "Get_Revision".to_string(),
198
+ _ => format!("Unknown({})", msg_type),
199
+ }
200
+ }
201
+
202
+ /// Utility function to convert hex string to bytes
203
+ #[pyfunction]
204
+ pub fn hex_to_bytes(hex_str: &str) -> PyResult<Vec<u8>> {
205
+ hex::decode(hex_str.trim())
206
+ .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Invalid hex string: {}", e)))
207
+ }
208
+
209
+ /// Utility function to convert bytes to hex string
210
+ #[pyfunction]
211
+ pub fn bytes_to_hex(data: &Bound<'_, pyo3::types::PyBytes>) -> String {
212
+ hex::encode(data.as_bytes())
213
+ }
214
+
215
+ /// A Python module implemented in Rust for USB PD message parsing
216
+ #[pymodule]
217
+ fn usbpdpy(m: &Bound<'_, pyo3::types::PyModule>) -> PyResult<()> {
218
+ m.add_function(wrap_pyfunction!(parse_pd_message, m)?)?;
219
+ m.add_function(wrap_pyfunction!(parse_pd_messages, m)?)?;
220
+ m.add_function(wrap_pyfunction!(get_message_type_name, m)?)?;
221
+ m.add_function(wrap_pyfunction!(hex_to_bytes, m)?)?;
222
+ m.add_function(wrap_pyfunction!(bytes_to_hex, m)?)?;
223
+
224
+ m.add_class::<PyPdMessage>()?;
225
+ m.add_class::<PyPdHeader>()?;
226
+ m.add_class::<PyPdDataObject>()?;
227
+
228
+ Ok(())
229
+ }
@@ -0,0 +1,136 @@
1
+ """
2
+ Basic tests for usbpdpy package
3
+ """
4
+
5
+ import pytest
6
+ import usbpdpy
7
+
8
+
9
+ def test_hex_to_bytes():
10
+ """Test hex string to bytes conversion"""
11
+ # Test simple hex string
12
+ result = usbpdpy.hex_to_bytes("1161")
13
+ assert result == b'\x11\x61'
14
+
15
+ # Test with spaces (remove spaces first)
16
+ result = usbpdpy.hex_to_bytes("1161")
17
+ assert result == b'\x11\x61'
18
+
19
+ # Test empty string
20
+ result = usbpdpy.hex_to_bytes("")
21
+ assert result == b''
22
+
23
+
24
+ def test_bytes_to_hex():
25
+ """Test bytes to hex string conversion"""
26
+ result = usbpdpy.bytes_to_hex(b'\x11\x61')
27
+ assert result == "1161"
28
+
29
+ result = usbpdpy.bytes_to_hex(b'')
30
+ assert result == ""
31
+
32
+
33
+ def test_get_message_type_name():
34
+ """Test message type name lookup"""
35
+ assert usbpdpy.get_message_type_name(1) == "GoodCRC"
36
+ assert usbpdpy.get_message_type_name(3) == "Accept"
37
+ assert usbpdpy.get_message_type_name(7) == "Get_Source_Cap"
38
+ assert "Unknown" in usbpdpy.get_message_type_name(255)
39
+
40
+
41
+ def test_parse_pd_message():
42
+ """Test USB PD message parsing"""
43
+ # Test GoodCRC message
44
+ msg_bytes = usbpdpy.hex_to_bytes("1161")
45
+ message = usbpdpy.parse_pd_message(msg_bytes)
46
+
47
+ assert message.header.message_type == 17 # 0x11 & 0x1F = 17
48
+ assert message.header.port_data_role in ["UFP", "DFP"]
49
+ assert message.header.port_power_role in ["Sink", "Source"]
50
+ assert isinstance(message.header.message_id, int)
51
+ assert isinstance(message.header.number_of_data_objects, int)
52
+ assert isinstance(message.header.extended, bool)
53
+ assert len(message.raw_bytes) == 2
54
+ assert message.get_hex() == "1161"
55
+
56
+
57
+ def test_parse_pd_message_error():
58
+ """Test error handling for invalid messages"""
59
+ with pytest.raises(ValueError):
60
+ usbpdpy.parse_pd_message(b'') # Too short
61
+
62
+ with pytest.raises(ValueError):
63
+ usbpdpy.parse_pd_message(b'\x00') # Too short
64
+
65
+
66
+ def test_parse_pd_messages():
67
+ """Test parsing multiple messages"""
68
+ messages = [b'\x11\x61', b'\x01\x43']
69
+ result = usbpdpy.parse_pd_messages(messages)
70
+
71
+ assert len(result) == 2
72
+ assert all(hasattr(msg, 'header') for msg in result)
73
+ assert all(hasattr(msg, 'data_objects') for msg in result)
74
+
75
+
76
+ def test_hex_to_bytes_error():
77
+ """Test error handling for invalid hex strings"""
78
+ with pytest.raises(ValueError):
79
+ usbpdpy.hex_to_bytes("invalid_hex")
80
+
81
+ with pytest.raises(ValueError):
82
+ usbpdpy.hex_to_bytes("11G1") # Invalid hex character
83
+
84
+
85
+ def test_message_attributes():
86
+ """Test that message objects have expected attributes"""
87
+ msg_bytes = usbpdpy.hex_to_bytes("1161")
88
+ message = usbpdpy.parse_pd_message(msg_bytes)
89
+
90
+ # Test header attributes
91
+ header = message.header
92
+ assert hasattr(header, 'message_type')
93
+ assert hasattr(header, 'port_data_role')
94
+ assert hasattr(header, 'specification_revision')
95
+ assert hasattr(header, 'port_power_role')
96
+ assert hasattr(header, 'message_id')
97
+ assert hasattr(header, 'number_of_data_objects')
98
+ assert hasattr(header, 'extended')
99
+
100
+ # Test message attributes
101
+ assert hasattr(message, 'header')
102
+ assert hasattr(message, 'data_objects')
103
+ assert hasattr(message, 'raw_bytes')
104
+
105
+ # Test methods
106
+ assert callable(message.get_hex)
107
+ assert callable(message.to_dict)
108
+
109
+
110
+ def test_integration():
111
+ """Integration test with multiple operations"""
112
+ # Test complete workflow
113
+ test_messages = ["1161", "0143", "0744"]
114
+
115
+ parsed_messages = []
116
+ for hex_msg in test_messages:
117
+ msg_bytes = usbpdpy.hex_to_bytes(hex_msg)
118
+ parsed_msg = usbpdpy.parse_pd_message(msg_bytes)
119
+ parsed_messages.append(parsed_msg)
120
+
121
+ assert len(parsed_messages) == 3
122
+
123
+ # Verify each message
124
+ for i, msg in enumerate(parsed_messages):
125
+ assert msg.get_hex() == test_messages[i].lower()
126
+ type_name = usbpdpy.get_message_type_name(msg.header.message_type)
127
+ assert isinstance(type_name, str)
128
+ assert len(type_name) > 0
129
+
130
+
131
+ if __name__ == "__main__":
132
+ # Run basic smoke test
133
+ test_hex_to_bytes()
134
+ test_parse_pd_message()
135
+ test_integration()
136
+ print("✅ All basic tests passed!")