Skip to content

Commit

Permalink
Merge pull request #10 from leighleighleigh/fix/python-data-attribute
Browse files Browse the repository at this point in the history
Add the missing ID and data attributes for Frames in Python
  • Loading branch information
leighleighleigh authored Feb 7, 2023
2 parents c3efd2b + 4e48048 commit 67fbc4c
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
1 change: 1 addition & 0 deletions examples/python_receive/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@
while True:
f = bus.receive()
print(str(f))
print(f.data)


44 changes: 39 additions & 5 deletions jcan-python/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,17 +106,51 @@ impl PyJBus {
impl PyJFrame {
#[new]
fn new(id: u32, data: Vec<u8>) -> PyResult<Self> {
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<String> {
Ok(self.frame.to_string())
}

// Implement the id property
#[getter]
fn id(&self) -> PyResult<u32> {
Ok(self.frame.id)
}

// Implement the data property
#[getter]
fn data(&self) -> PyResult<Vec<u8>> {
// Cannot return this since Vec<u8> doesn't implent Copy
// Ok(self.frame.data)
Ok(self.frame.data.clone())
}
}

// Implement conversion from PyJFrame to JFrame
impl From<PyJFrame> 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<ffi::JFrame> for PyJFrame {
fn from(frame: ffi::JFrame) -> Self {
PyJFrame {
frame,
}
}
}

#[pymodule]
Expand Down

0 comments on commit 67fbc4c

Please sign in to comment.