diff --git a/examples/python_receive/main.py b/examples/python_receive/main.py index e5434e0..b0f677f 100644 --- a/examples/python_receive/main.py +++ b/examples/python_receive/main.py @@ -9,5 +9,6 @@ while True: f = bus.receive() print(str(f)) + print(f.data) diff --git a/jcan-python/src/lib.rs b/jcan-python/src/lib.rs index 59c613c..263e952 100644 --- a/jcan-python/src/lib.rs +++ b/jcan-python/src/lib.rs @@ -106,17 +106,51 @@ impl PyJBus { impl PyJFrame { #[new] fn new(id: u32, data: Vec) -> PyResult { - Ok(PyJFrame { - frame: new_jframe(id, data).map_err(|e| { - PyOSError::new_err(format!("Error creating frame: {}", e)) - })?, - }) + // First build a JFrame from the id and data, using new _jframe. + // This method runs some data validation, so we need to use it. + let frame = new_jframe(id, data).map_err(|e| { + PyOSError::new_err(format!("Error creating frame: {}", e)) + })?; + + // Then convert JFrame to PyJFrame, using the From<> trait + Ok(frame.into()) } // Implement string representation using the to_string method fn __str__(&self) -> PyResult { Ok(self.frame.to_string()) } + + // Implement the id property + #[getter] + fn id(&self) -> PyResult { + Ok(self.frame.id) + } + + // Implement the data property + #[getter] + fn data(&self) -> PyResult> { + // Cannot return this since Vec doesn't implent Copy + // Ok(self.frame.data) + Ok(self.frame.data.clone()) + } +} + +// Implement conversion from PyJFrame to JFrame +impl From for ffi::JFrame { + fn from(py_frame: PyJFrame) -> Self { + // Unbox the PyJFrame, and return the JFrame + py_frame.frame + } +} + +// Implement conversion from JFrame to PyJFrame +impl From for PyJFrame { + fn from(frame: ffi::JFrame) -> Self { + PyJFrame { + frame, + } + } } #[pymodule]