Skip to content

Commit

Permalink
working python binding draft for hiwonder IMU
Browse files Browse the repository at this point in the history
  • Loading branch information
aaronxie0000 committed Jan 1, 2025
1 parent 9f13b24 commit 3c7dbc8
Show file tree
Hide file tree
Showing 10 changed files with 105 additions and 10 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ members = [
"imu/bindings",
"imu/hexmove",
"imu/hiwonder",
"imu/bindings_hiwonder",
]
resolver = "2"

[workspace.package]

version = "0.1.6"
authors = ["Wesley Maa <[email protected]>"]
edition = "2021"
Expand Down
21 changes: 21 additions & 0 deletions examples/hiwonder_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from bindings_hiwonder import HiwonderImu
import time

def main():
# Create IMU instance
imu = HiwonderImu("/dev/ttyUSB0", 9600)

try:
while True:
if data := imu.read_data():
acc, gyro, angle = data
print(f"\033[2J\033[H") # Clear screen
print(f"Acceleration (m/s²): {acc}")
print(f"Gyroscope (deg/s): {gyro}")
print(f"Angle (degrees): {angle}")
time.sleep(0.1) # Add small delay to make output readable
except KeyboardInterrupt:
print("\nExiting...")

if __name__ == "__main__":
main()
4 changes: 4 additions & 0 deletions imu/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,7 @@
PyHexmoveImuData as HexmoveImuData,
PyHexmoveImuReader as HexmoveImuReader,
)

from .bindings_hiwonder import (
PyHiwonderImu as HiwonderImu,
)
16 changes: 16 additions & 0 deletions imu/bindings_hiwonder/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[package]
name = "bindings_hiwonder"
version = "0.1.0"
edition = "2021"
authors = ["Aaron Xie <[email protected]>"]
description = "Python bindings for Hiwonder IMU"
license = "MIT"

[lib]
name = "bindings_hiwonder"
crate-type = ["cdylib", "rlib"]

[dependencies]
pyo3 = { version = ">= 0.21.0", features = ["extension-module"] }
pyo3-stub-gen = ">= 0.6.0"
hiwonder = { path = "../hiwonder" }
8 changes: 8 additions & 0 deletions imu/bindings_hiwonder/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[build-system]
requires = ["maturin>=1.1,<2.0"]
build-backend = "maturin"

[project]
name = "bindings_hiwonder"
version = "0.1.0"
requires-python = ">=3.9"
7 changes: 7 additions & 0 deletions imu/bindings_hiwonder/src/bin/stub_gen.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use pyo3_stub_gen::Result;

fn main() -> Result<()> {
let stub = bindings_hiwonder::stub_info()?;
stub.generate()?;
Ok(())
}
40 changes: 40 additions & 0 deletions imu/bindings_hiwonder/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use hiwonder::IMU;
use pyo3::prelude::*;
use pyo3_stub_gen::derive::{gen_stub_pyclass, gen_stub_pymethods};
use pyo3_stub_gen::define_stub_info_gatherer;
use std::sync::{Arc, Mutex};

#[gen_stub_pyclass]
#[pyclass(name = "HiwonderImu")]
struct PyHiwonderImu {
inner: Arc<Mutex<IMU>>,
}

#[gen_stub_pymethods]
#[pymethods]
impl PyHiwonderImu {
#[new]
fn new(interface: String, baud_rate: u32) -> PyResult<Self> {
let imu = IMU::new(&interface, baud_rate)
.map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))?;
Ok(PyHiwonderImu {
inner: Arc::new(Mutex::new(imu)),
})
}

fn read_data(&mut self) -> PyResult<Option<([f32; 3], [f32; 3], [f32; 3])>> {
let mut imu = self.inner
.lock()
.map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))?;
imu.read_data()
.map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))
}
}

#[pymodule]
fn bindings_hiwonder(py: Python<'_>, m: &Bound<PyModule>) -> PyResult<()> {
m.add("HiwonderImu", py.get_type::<PyHiwonderImu>())?;
Ok(())
}

define_stub_info_gatherer!(stub_info);
3 changes: 3 additions & 0 deletions imu/hiwonder/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
TODO
- [ ] Add std write for updating the data output hz
- [ ] Add python binding
5 changes: 5 additions & 0 deletions imu/hiwonder/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""Defines the top-level API for the Hiwonder IMU package."""

from bindings_hiwonder import HiwonderImu # Changed from relative import

__all__ = ['HiwonderImu']
9 changes: 0 additions & 9 deletions imu/hiwonder/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,6 @@ impl IMU {
} else {
if data == (self.checksum & 0xFF) {
self.angle = Self::get_angle(&self.angle_data);
self.print_results();
}
self.reset();
}
Expand Down Expand Up @@ -177,12 +176,4 @@ impl IMU {
]
}

fn print_results(&self) {
println!(
"acc: {:10.3} {:10.3} {:10.3}\ngyro: {:10.3} {:10.3} {:10.3}\nangle: {:10.3} {:10.3} {:10.3}",
self.acc[0], self.acc[1], self.acc[2],
self.gyro[0], self.gyro[1], self.gyro[2],
self.angle[0], self.angle[1], self.angle[2]
);
}
}

0 comments on commit 3c7dbc8

Please sign in to comment.