added rust documentation comments

This commit is contained in:
Simon Wörner
2017-07-10 15:20:14 +02:00
parent 088867352c
commit fe8806a4d5
12 changed files with 100 additions and 10 deletions

View File

@@ -4,7 +4,7 @@ version = "0.1.0"
authors = ["Simon Wörner <git@simon-woerner.de>"]
[lib]
name = "kawaii"
name = "kawaii_api"
crate-type = ["staticlib"]
[features]

View File

@@ -3,6 +3,10 @@ name = "emergency_stop"
version = "0.1.0"
authors = ["Simon Wörner <git@simon-woerner.de>"]
[[bin]]
name = "emergency_stop-test"
doc = false
[features]
measure = ["kawaii/measure"]

View File

@@ -18,6 +18,10 @@ pub struct EmergencyStop {
}
impl EmergencyStop {
/// Constructs a new `EmergencyStop` and starts poll thread.
///
/// # Parameter
/// - `stop_port` GPIO Port number of emergency stop pin.
pub fn new(stop_port: u8) -> std::io::Result<Self> {
let name = format!("EmergencyStop(port = {})", stop_port);
let state = Arc::new(AtomicBool::new(false));
@@ -29,11 +33,12 @@ impl EmergencyStop {
.spawn(move || EmergencyStop::thread(&mut port, state_clone))?;
Ok(EmergencyStop {
thread: Some(thread),
state: state,
})
thread: Some(thread),
state: state,
})
}
/// Emergency stop poll thread
fn thread(port: &mut AsyncPort, state: Arc<AtomicBool>) {
#[cfg(feature = "measure")]
let mut measure = Measure::new(format!("EmergencyStop(port = {})", port.port.number));
@@ -86,6 +91,7 @@ impl EmergencyStop {
}
impl Drop for EmergencyStop {
/// Set emergency stop and join poll thread.
fn drop(&mut self) {
self.state.store(true, Ordering::Relaxed);

View File

@@ -3,6 +3,10 @@ name = "kawaii"
version = "0.1.0"
authors = ["Simon Wörner <git@simon-woerner.de>"]
[[bin]]
name = "kawaii-test"
doc = false
[features]
measure = []

View File

@@ -133,6 +133,11 @@ impl fmt::Debug for AsyncPort {
}
impl Port {
/// Constructs a new GPIO `Port`.
///
/// # Parameter
/// - `number` GPIO Port number of pin.
/// - `direction` GPIO Port direction.
pub fn new(number: u8, direction: Direction) -> std::io::Result<Port> {
let port = Port {
number: number,
@@ -143,6 +148,7 @@ impl Port {
Ok(port)
}
/// Init GPIO `Port`: export port and set direction
fn init(&self) -> std::io::Result<()> {
self.export().ok();
self.set_direction()?;
@@ -150,6 +156,7 @@ impl Port {
Ok(())
}
/// Drop GPIO `Port`: unexport
pub fn drop(&mut self) {
self.unexport().ok();
}
@@ -159,13 +166,17 @@ impl Port {
.write_all(value.as_bytes())
}
/// Export GPIO `Port`
fn export(&self) -> std::io::Result<()> {
Port::write_path("/sys/class/gpio/export", self.number.to_string().as_str())
}
/// Unexport GPIO `Port`
fn unexport(&self) -> std::io::Result<()> {
Port::write_path("/sys/class/gpio/unexport", self.number.to_string().as_str())
}
/// Set GPIO `Port` direction
fn set_direction(&self) -> std::io::Result<()> {
Port::write_path(format!("/sys/class/gpio/gpio{}/direction", self.number).as_str(),
self.direction.as_str())
@@ -173,6 +184,11 @@ impl Port {
}
impl SyncPort {
/// Constructs a new synchronised GPIO `Port`.
///
/// # Parameter
/// - `number` GPIO Port number of pin.
/// - `direction` GPIO Port direction.
pub fn new(number: u8, direction: Direction) -> std::io::Result<SyncPort> {
Ok(SyncPort {
port: Port::new(number, direction)?,
@@ -181,6 +197,7 @@ impl SyncPort {
})
}
/// Open GPIO `SyncPort` sysfs file
fn open(number: u8, direction: Direction) -> std::io::Result<File> {
let path = format!("/sys/class/gpio/gpio{}/value", number);
let path = Path::new(path.as_str());
@@ -191,6 +208,7 @@ impl SyncPort {
})
}
/// Read from GPIO `SyncPort` sysfs file
pub fn read(&mut self) -> std::io::Result<Value> {
self.file.seek(SeekFrom::Start(0))?;
self.file.read_exact(&mut self.buffer)?;
@@ -199,12 +217,18 @@ impl SyncPort {
"Unrecognized GPIO Value"))
}
/// Write to GPIO `SyncPort` sysfs file
pub fn write(&mut self, value: Value) -> std::io::Result<()> {
self.file.write_all(value.as_str().as_bytes())
}
}
impl AsyncPort {
/// Constructs a new asynchronous GPIO `Port`.
///
/// # Parameter
/// - `number` GPIO Port number of pin.
/// - `edge` GPIO Port edge detection setting.
pub fn new(number: u8, edge: Edge) -> std::io::Result<AsyncPort> {
let port = Port::new(number, Direction::In)?;
let file = AsyncPort::open(number)?;
@@ -219,12 +243,15 @@ impl AsyncPort {
port.init()?;
Ok(port)
}
/// Init GPIO `Port`: set edge detection
fn init(&self) -> std::io::Result<()> {
self.set_edge()?;
Ok(())
}
/// Open GPIO `AsyncPort` sysfs file with posix API
fn open(number: u8) -> std::io::Result<RawFd> {
nix::fcntl::open(format!("/sys/class/gpio/gpio{}/value", number).as_str(),
nix::fcntl::O_RDONLY,
@@ -239,10 +266,12 @@ impl AsyncPort {
}
}
/// Posix poll on sysfs file
fn nix_poll(&mut self, timeout: i32) -> nix::Result<i32> {
nix::poll::poll(&mut self.fds, timeout)
}
/// Read from GPIO `AsyncPort` sysfs file with posix poll
fn poll_read(&mut self, poll: nix::Result<i32>) -> std::io::Result<Option<Value>> {
let poll = poll.or(Err(Error::new(ErrorKind::Other, "poll failed")))?;
@@ -261,12 +290,14 @@ impl AsyncPort {
|v| Ok(Some(v)))
}
/// Read asynchronous from GPIO `AsyncPort` sysfs file
pub fn poll(&mut self, timeout: Option<Duration>) -> std::io::Result<Option<Value>> {
let poll = self.nix_poll(Self::get_timeout(timeout));
self.poll_read(poll)
}
/// Read asynchronous from GPIO `AsyncPort` sysfs file with measure support (ignore poll time)
#[cfg(feature = "measure")]
pub fn poll_measure(&mut self,
timeout: Option<Duration>,
@@ -281,6 +312,7 @@ impl AsyncPort {
self.poll_read(poll)
}
/// Set GPIO `Port` edge detection
fn set_edge(&self) -> std::io::Result<()> {
Port::write_path(format!("/sys/class/gpio/gpio{}/edge", self.port.number).as_str(),
self.edge.as_str())

View File

@@ -4,4 +4,4 @@ pub mod gpio;
mod measure;
#[cfg(feature = "measure")]
pub use measure::Measure;
pub use measure::Measure;

View File

@@ -22,6 +22,10 @@ pub struct Measure {
}
impl Measure {
/// Constructs a new `Measure`.
///
/// # Parameter
/// - `name` Name of measured component.
pub fn new(name: String) -> Self {
Measure {
min: u64::max_value(),
@@ -33,10 +37,12 @@ impl Measure {
}
}
/// Start measurement
pub fn start(&mut self) {
self.last = precise_time_ns();
}
/// Pause measurement
pub fn pause(&mut self) {
if self.last == 0 {
#[cfg(debug_assertions)]
@@ -48,6 +54,7 @@ impl Measure {
self.time += self.time_diff();
}
/// Stop measurement and calculate time difference
pub fn stop(&mut self) {
if self.last == 0 {
#[cfg(debug_assertions)]
@@ -98,6 +105,7 @@ impl Measure {
}
impl Drop for Measure {
/// Print measure results and write times to file
fn drop(&mut self) {
println!("{}:\n\tmin: {} ns\n\tmax: {} ns",
self.name,

View File

@@ -3,6 +3,10 @@ name = "ultrasonic_irq"
version = "0.1.0"
authors = ["kawaii <root@kawaii.home.lost-in-space.net>"]
[[bin]]
name = 'ultrasonic_irq-test'
doc = false
[features]
measure = ["kawaii/measure"]

View File

@@ -47,8 +47,20 @@ pub struct Ultrasonic {
}
impl Ultrasonic {
/// Constructs a new `Ultrasonic` and start threads.
///
/// # Threads
/// - `UltrasonicTrigger`
/// - `UltrasonicEcho`
///
/// # Parameter
/// - `trigger_port` GPIO Port number of trigger pin.
/// - `echo_port` GPIO Port number of echo pin.
/// - `temperature` Room temperature in °C.
pub fn new(trigger_port: u8, echo_port: u8, temperature: u8) -> std::io::Result<Ultrasonic> {
let distance = Arc::new(AtomicU32::new(u32::max_value()));
/// Create `UltrasonicEcho` thread with sync channel.
let echo = UltrasonicEcho {
echo: AsyncPort::new(echo_port, Edge::Both)?,
temperature: temperature,
@@ -64,6 +76,7 @@ impl Ultrasonic {
tx: tx,
};
/// Create `UltrasonicTrigger` thread with sync channel.
let trigger = UltrasonicTrigger { trigger: SyncPort::new(trigger_port, Direction::Out)? };
let (tx, rx): (Sender<()>, Receiver<()>) = mpsc::channel();
let name = format!("Ultrasonic::trigger(port = {})", trigger_port);
@@ -83,6 +96,7 @@ impl Ultrasonic {
}
impl Drop for Ultrasonic {
/// Drop sync channels and join threads.
fn drop(&mut self) {
if let Some(echo) = self.echo.take() {
echo.tx.send(()).is_ok();
@@ -97,9 +111,11 @@ impl Drop for Ultrasonic {
}
impl UltrasonicTrigger {
/// `UltrasonicTrigger` thread function.
fn thread(mut self, stop_rx: Receiver<()>) {
#[cfg(feature = "measure")]
let mut measure = Measure::new(format!("Ultrasonic::trigger(port = {})", self.trigger.port.number));
let mut measure = Measure::new(format!("Ultrasonic::trigger(port = {})",
self.trigger.port.number));
while stop_rx.try_recv().is_err() {
#[cfg(feature = "measure")]
@@ -124,9 +140,11 @@ impl UltrasonicTrigger {
}
impl UltrasonicEcho {
/// `UltrasonicEcho` thread function.
fn thread(mut self, stop_rx: Receiver<()>) {
#[cfg(feature = "measure")]
let mut measure = Measure::new(format!("Ultrasonic::echo(port = {})", self.echo.port.number));
let mut measure = Measure::new(format!("Ultrasonic::echo(port = {})",
self.echo.port.number));
while stop_rx.try_recv().is_err() {
#[cfg(feature = "measure")]
@@ -136,7 +154,8 @@ impl UltrasonicEcho {
let value = self.echo.poll(Some(Duration::new(1, 0)));
#[cfg(feature = "measure")]
let value = self.echo.poll_measure(Some(Duration::new(1, 0)), &mut measure);
let value = self.echo
.poll_measure(Some(Duration::new(1, 0)), &mut measure);
match value {
Ok(value) => {
@@ -155,6 +174,7 @@ impl UltrasonicEcho {
}
}
/// Start time measure or calculates distance based on port value
fn on_value_changed(&mut self, value: Value) {
match value {
Value::High => {
@@ -167,7 +187,7 @@ impl UltrasonicEcho {
self.calc_distance();
}
self.timestamp = precise_time_ns()
self.timestamp = precise_time_ns();
}
Value::Low => {
// Switched from Value::Low to Value::Low
@@ -181,6 +201,7 @@ impl UltrasonicEcho {
}
}
/// Calculates distance based on time measurement and `temperature` and stores it in `distance`
fn calc_distance(&mut self) {
let time_diff = precise_time_ns() - self.timestamp;
let distance = (3315 + self.temperature as u64 * 6) * time_diff / 20_000_000;

View File

@@ -6,6 +6,7 @@ use std::mem::transmute;
use std::ptr::null_mut;
use std::sync::atomic::Ordering;
/// Constructs a new `EmergencyStop` on heap and returns pointer.
#[no_mangle]
pub extern "C" fn emergency_stop_init(stop: u8) -> *mut EmergencyStop {
match EmergencyStop::new(stop) {
@@ -14,11 +15,13 @@ pub extern "C" fn emergency_stop_init(stop: u8) -> *mut EmergencyStop {
}
}
/// Drops a `EmergencyStop` pointer on heap.
#[no_mangle]
pub extern "C" fn emergency_stop_clean(emergency_stop: *mut EmergencyStop) {
let _emergency_stop: Box<EmergencyStop> = unsafe { transmute(emergency_stop) };
}
/// Returns `EmergencyStop` pointer state.
#[no_mangle]
pub extern "C" fn emergency_stop_get_state(emergency_stop: *mut EmergencyStop) -> bool {
let emergency_stop = unsafe { &mut *emergency_stop };

View File

@@ -7,6 +7,7 @@ use std::ptr::null_mut;
use std::mem::transmute;
use std::os::raw::c_char;
/// Constructs a new `Measure` on heap and returns pointer.
#[no_mangle]
pub extern "C" fn measure_init(name: *const c_char) -> *mut Measure {
if name.is_null() {
@@ -21,11 +22,13 @@ pub extern "C" fn measure_init(name: *const c_char) -> *mut Measure {
}
}
/// Drops a `Measure` pointer on heap.
#[no_mangle]
pub extern "C" fn measure_clean(measure: *mut Measure) {
let _measure: Box<Measure> = unsafe { transmute(measure) };
}
/// Starts measure on `Measure` pointer.
#[no_mangle]
pub extern "C" fn measure_start(measure: *mut Measure) {
let measure = unsafe { &mut *measure };
@@ -33,6 +36,7 @@ pub extern "C" fn measure_start(measure: *mut Measure) {
measure.start();
}
/// Pause measure on `Measure` pointer.
#[no_mangle]
pub extern "C" fn measure_pause(measure: *mut Measure) {
let measure = unsafe { &mut *measure };
@@ -40,9 +44,10 @@ pub extern "C" fn measure_pause(measure: *mut Measure) {
measure.pause();
}
/// Stop measure on `Measure` pointer.
#[no_mangle]
pub extern "C" fn measure_stop(measure: *mut Measure) {
let measure = unsafe { &mut *measure };
measure.stop();
}
}

View File

@@ -6,6 +6,7 @@ use std::sync::atomic::Ordering;
use self::ultrasonic_irq::Ultrasonic;
/// Constructs a new `Ultrasonic` on heap and returns pointer.
#[no_mangle]
pub extern "C" fn ultrasonic_init(trigger: u8, echo: u8, temperature: u8) -> *mut Ultrasonic {
match Ultrasonic::new(trigger, echo, temperature) {
@@ -14,11 +15,13 @@ pub extern "C" fn ultrasonic_init(trigger: u8, echo: u8, temperature: u8) -> *mu
}
}
/// Drops a `Ultrasonic` pointer on heap.
#[no_mangle]
pub extern "C" fn ultrasonic_clean(ultrasonic: *mut Ultrasonic) {
let _ultrasonic: Box<Ultrasonic> = unsafe { transmute(ultrasonic) };
}
/// Returns `Ultrasonic` pointer distance.
#[no_mangle]
pub extern "C" fn ultrasonic_get_distance(ultrasonic: *mut Ultrasonic) -> u32 {
let ultrasonic = unsafe { &mut *ultrasonic };