Enum Order

Source
pub enum Order {
    HELLO = 0,
    SERVO = 1,
    MOTOR = 2,
    ALREADY_CONNECTED = 3,
    ERROR = 4,
    RECEIVED = 5,
    STOP = 6,
}

Variants§

§

HELLO = 0

§

SERVO = 1

§

MOTOR = 2

§

ALREADY_CONNECTED = 3

§

ERROR = 4

§

RECEIVED = 5

§

STOP = 6

Implementations§

Source§

impl Order

Shortcut for convert_i8_to_order

§Example

use robust_arduino_serial::Order;

let order: i8 = 2;  // Order::MOTOR has the index 2 in the enum
let converted_order = Order::from_i8(order).unwrap();

assert_eq!(converted_order, Order::MOTOR);
Source

pub fn from_i8(num: i8) -> Option<Order>

Examples found in repository?
examples/arduino_serial.rs (line 42)
21fn main() {
22
23    let args: Vec<String> = env::args().skip(1).collect();
24
25    if args.len() < 1
26    {
27        panic!("Please provide a serial port as argument (ex: /dev/ttyACM0)");
28    }
29    let serial_port = &args[0];
30
31    println!("Opening port: {:?}", serial_port);
32    let mut port = serial::open(&serial_port).unwrap();
33    port.configure(&SETTINGS).unwrap();
34    // timeout of 30s
35    port.set_timeout(Duration::from_secs(30)).unwrap();
36
37    loop
38    {
39        println!("Waiting for Arduino...");
40        let order = Order::HELLO as i8;
41        write_i8(&mut port, order).unwrap();
42        let received_order = Order::from_i8(read_i8(&mut port).unwrap()).unwrap();
43        if received_order == Order::ALREADY_CONNECTED
44        {
45            break;
46        }
47        thread::sleep(Duration::from_secs(1));
48    }
49
50    println!("Connected to Arduino");
51
52    let motor_order = Order::MOTOR as i8;
53    let motor_speed: i8 = -56;
54    write_i8(&mut port, motor_order).unwrap();
55    write_i8(&mut port, motor_speed).unwrap();
56
57    write_i8(&mut port, Order::SERVO as i8).unwrap();
58    write_i16(&mut port, 120_i16).unwrap();
59
60    for _ in 0..10 {
61        let order = read_i8(&mut port).unwrap();
62        println!("Order received: {:?}", order);
63
64        if let Some(received_order) = Order::from_i8(order)
65        {
66            println!("Known order: {:?}", received_order);
67        }
68        else
69        {
70            println!("Unknown order: {:?}", order);
71        }
72    }
73}
More examples
Hide additional examples
examples/file_read_write.rs (line 41)
10fn main() {
11    let args: Vec<String> = env::args().skip(1).collect();
12    if args.len() < 1
13    {
14        panic!("Please provide a filename as argument");
15    }
16    let filename = &args[0];
17    // Open file and create it if it does not exist
18    let mut file = match OpenOptions::new().read(true).write(true).create(true).open(filename)
19                    {
20                        Err(why) => panic!("Could not open file {}: {}", filename, why),
21                        Ok(file) => file
22                    };
23
24    // write_order is equivalent to write_i8
25    write_order(&mut file, Order::HELLO).unwrap();
26
27    let motor_order = Order::MOTOR as i8;
28    let motor_speed: i16 = -56;
29    write_i8(&mut file, motor_order).unwrap();
30    write_i16(&mut file, motor_speed).unwrap();
31    write_i32(&mut file, 131072).unwrap();
32
33    // Go to the beginning of the file
34    file.seek(SeekFrom::Start(0)).unwrap();
35
36    for _ in 0..2 {
37        // We could have also use read_order(&mut file).unwrap()
38        let order = read_i8(&mut file).unwrap();
39        println!("Ordered received: {:?}", order);
40
41        if let Some(received_order) = Order::from_i8(order)
42        {
43            println!("Known order: {:?}", received_order);
44            match received_order
45            {
46                Order::MOTOR => {
47                    let motor_speed = read_i16(&mut file).unwrap();
48                    println!("Motor Speed = {}", motor_speed);
49                    let test = read_i32(&mut file).unwrap();
50                    println!("test = {}", test);
51                },
52                _ => ()
53            }
54        }
55        else
56        {
57            println!("Unknown order: {:?}", order);
58        }
59    }
60}
examples/arduino_threads.rs (line 46)
25fn main() {
26
27    let args: Vec<String> = env::args().skip(1).collect();
28
29    if args.len() < 1
30    {
31        panic!("Please provide a serial port as argument (ex: /dev/ttyACM0)");
32    }
33    let serial_port = &args[0];
34
35    println!("Opening port: {:?}", serial_port);
36    let mut port = serial::open(&serial_port).unwrap();
37    port.configure(&SETTINGS).unwrap();
38    // timeout of 1ms
39    port.set_timeout(Duration::from_millis(1)).unwrap();
40
41    loop
42    {
43        println!("Waiting for Arduino...");
44        write_order(&mut port, Order::HELLO).unwrap();
45        let received_order = match read_i8(&mut port) {
46            Ok(order) => Order::from_i8(order).unwrap(),
47            Err(ref e) if e.kind() == ErrorKind::TimedOut => {
48                // If we have a read timeout, wait a bit
49                thread::sleep(Duration::from_secs(2));
50                continue
51                }
52            Err(e) => {
53                    panic!("An error occured reading serial port: {}", e)
54                }
55
56        };
57
58        if received_order == Order::ALREADY_CONNECTED
59        {
60            break;
61        }
62        thread::sleep(Duration::from_secs(1));
63    }
64
65    println!("Connected to Arduino");
66
67    // Channel to send and receive commands
68    let (command_sender, command_receiver) = mpsc::channel();
69    let command_queue = mpsc::Sender::clone(&command_sender);
70
71    // Wrap the serial to use it in the threads
72    let serial_arc = Arc::new(Mutex::new(port));
73    let serial_command = serial_arc.clone();
74
75    // Exit event to notify thread when they should exit
76    let exit_event = false;
77    // Wrap the boolean to use it in the threads
78    let exit_arc = Arc::new(Mutex::new(exit_event));
79    let exit_listener = exit_arc.clone();
80    let exit_command = exit_arc.clone();
81
82    // Semaphore to avoid Arduino buffer overflow:
83    // Do not send new order if the Arduino did not aknowledge
84    // the previous message
85    let n_allowed_messages = 2;
86    let semaphore = Arc::new(Semaphore::new(n_allowed_messages));
87    let semaphore_command = semaphore.clone();
88
89    let mut threads = vec![];
90
91    // Command thread listen to the command Channel
92    // and send orders to the Arduino
93    let command_thread = thread::spawn(move || {
94        let mut exit = false;
95        while !exit
96        {
97            // Decrement the semaphore counter
98            // each time we send an order
99            semaphore.acquire();
100            let (order, num) = command_receiver.recv().unwrap();
101
102            println!("Sending: {:?}, {}", order, num);
103
104            // Acquire lock on the buffer
105            let mut buffer = serial_command.lock().unwrap();
106
107            write_order(&mut *buffer, order).unwrap();
108            match order {
109                Order::MOTOR => write_i8(&mut *buffer, num as i8).unwrap(),
110                Order::SERVO => write_i16(&mut *buffer, num as i16).unwrap(),
111                _ => 0  // Write 0 bytes
112            };
113            exit = *exit_command.lock().unwrap();
114        }
115        println!("Command Thread exiting...");
116    });
117
118    threads.push(command_thread);
119
120    // Listener thread listens to the Arduino
121    // it release the semaphore when an aknowledgement is received
122    let listener_thread = thread::spawn(move || {
123
124        let mut exit = false;
125        let mut wait = false;
126        while !exit
127        {
128            // Wait a bit so the command thread can acquire the lock
129            if wait
130            {
131                thread::sleep(Duration::from_millis(100));
132            }
133
134            // Acquire lock on the serial object
135            let mut buffer = serial_arc.lock().unwrap();
136
137            // Receive order from arduino
138            let received_order = match read_i8(&mut *buffer) {
139                Ok(order) => Order::from_i8(order).unwrap(),
140                Err(_) => {
141                        wait = true;
142                        continue
143                    }
144
145            };
146            wait = false;
147
148            println!("Received: {:?}", received_order);
149
150            match received_order {
151                Order::RECEIVED => semaphore_command.release(),
152                _ => ()
153            }
154
155            exit = *exit_listener.lock().unwrap();
156        }
157        println!("Listener Thread exiting...");
158    });
159
160    threads.push(listener_thread);
161
162    thread::sleep(Duration::from_secs(1));
163    // Send Orders to the Arduino
164    command_queue.send((Order::MOTOR, 42_i32)).unwrap();
165    command_queue.send((Order::SERVO, 120_i32)).unwrap();
166
167    // Wait a bit before shutting down the threads
168    thread::sleep(Duration::from_secs(2));
169
170    // Stop the motor
171    command_queue.send((Order::MOTOR, 0_i32)).unwrap();
172
173
174    // Notify the threads that they should exit
175    {
176        *exit_arc.lock().unwrap() = true;
177    }
178
179    // Send dummy orders to exit the command thread
180    command_queue.send((Order::HELLO, 0_i32)).unwrap();
181
182    for t in threads
183    {
184        t.join().unwrap();
185    }
186}

Trait Implementations§

Source§

impl Clone for Order

Source§

fn clone(&self) -> Order

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Order

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for Order

Source§

fn eq(&self, other: &Order) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Copy for Order

Source§

impl StructuralPartialEq for Order

Auto Trait Implementations§

§

impl Freeze for Order

§

impl RefUnwindSafe for Order

§

impl Send for Order

§

impl Sync for Order

§

impl Unpin for Order

§

impl UnwindSafe for Order

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.