extern crate ultrasonic_irq;

use std::mem::transmute;
use std::ptr::null_mut;
use std::sync::atomic::Ordering;

use self::ultrasonic_irq::Ultrasonic;

#[no_mangle]
pub extern "C" fn ultrasonic_init(trigger: u8, echo: u8, temperature: u8) -> *mut Ultrasonic {
    match Ultrasonic::new(trigger, echo, temperature) {
        Err(_) => null_mut(),
        Ok(ultrasonic) => unsafe { transmute(Box::new(ultrasonic)) },
    }
}

#[no_mangle]
pub extern "C" fn ultrasonic_clean(ultrasonic: *mut Ultrasonic) {
    let _ultrasonic: Box<Ultrasonic> = unsafe { transmute(ultrasonic) };
}

#[no_mangle]
pub extern "C" fn ultrasonic_get_distance(ultrasonic: *mut Ultrasonic) -> u32 {
    let ultrasonic = unsafe { &mut *ultrasonic };

    ultrasonic.distance.load(Ordering::Relaxed)
}
