1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
extern crate kawaii;

use std::time::Duration;
use std::thread;
use std::thread::JoinHandle;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use self::kawaii::gpio::{AsyncPort, Edge, Value};

#[cfg(feature = "measure")]
use self::kawaii::Measure;

#[derive(Debug)]
pub struct EmergencyStop {
    thread: Option<JoinHandle<()>>,
    pub state: Arc<AtomicBool>,
}

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));
        let mut port = AsyncPort::new(stop_port, Edge::Both)?;

        let state_clone = state.clone();
        let thread = thread::Builder::new()
            .name(name)
            .spawn(move || EmergencyStop::thread(&mut port, state_clone))?;

        Ok(EmergencyStop {
            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));

        // clear first value
        port.poll(Some(Duration::new(0, 0))).is_ok();

        while !state.load(Ordering::Relaxed) {
            #[cfg(feature = "measure")]
            measure.start();

            let timeout = Some(Duration::new(1, 0));

            #[cfg(not(feature = "measure"))]
            let value = port.poll(timeout);

            #[cfg(feature = "measure")]
            let value = port.poll_measure(timeout, &mut measure);

            // continue on timeout
            match value {
                Ok(value) => {
                    if let Some(value) = value {
                        match value {
                            Value::High => {
                                #[cfg(debug_assertions)]
                                println!("EmergencyStop! ({:?})", value);

                                state.store(true, Ordering::Relaxed);
                            }
                            _ => {
                                #[cfg(debug_assertions)]
                                println!("EmergencyStop ignored: ({:?})", value);
                            }
                        }
                    }
                }
                Err(e) => {
                    #[cfg(debug_assertions)]
                    println!("EmergencyStop! ({:?})", e);

                    state.store(true, Ordering::Relaxed);
                }
            }

            #[cfg(feature = "measure")]
            measure.stop();
        }
    }
}

impl Drop for EmergencyStop {
    /// Set emergency stop and join poll thread.
    fn drop(&mut self) {
        self.state.store(true, Ordering::Relaxed);

        if let Some(thread) = self.thread.take() {
            thread.join().is_ok();
        }
    }
}