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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
use crossbeam_channel::{after, unbounded, Sender};
use failure::ResultExt;
use messages::{IsRequest, IsResponse, Message, MessageExt, Notification,
               Request, Response};
use serialport::SerialPort;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use {serialport, std, Error, ErrorKind, RegisteredSenders, Result,
     RxHandle, SenderRegistration};

#[derive(Default, Clone)]
pub(crate) struct SequenceHolder {
    // Once AtomicU8 is out of experimental, it can be used here
    // See: https://github.com/rust-lang/rust/issues/32976
    seq: Arc<Mutex<u8>>,
}

impl SequenceHolder {
    pub fn request_sequence_number(&mut self) -> Result<u8> {
        let mut lock = self.seq.lock().unwrap();
        let seq: u8 = *lock;
        *lock = seq + 1;
        Ok(seq)
    }
}

#[derive(Clone, Debug)]
pub(crate) enum RequestItem {
    Request {
        request: Request,
        options: u8,
        sequence: u8,
    },
    Finish,
}

#[derive(Clone, Debug)]
pub struct ResponseItem {
    pub response: Response,
    pub sequence: u8,
}

#[derive(Clone, Debug)]
pub struct NotificationItem {
    pub notification: Notification,
    pub sequence: u8,
}

pub struct Connection {
    port: Box<SerialPort>,
    tx_request_sender: Sender<RequestItem>,

    register_response_sender: Sender<SenderRegistration<ResponseItem>>,
    register_notification_sender:
        Sender<SenderRegistration<NotificationItem>>,

    rx_shutdown_sender: Sender<()>,

    tx_handle: Option<thread::JoinHandle<()>>,
    rx_handle: Option<thread::JoinHandle<()>>,

    sequence: SequenceHolder,
}

impl Drop for Connection {
    fn drop(&mut self) {
        // make the threads finish their loop
        self.rx_shutdown_sender.send(());
        self.tx_request_sender.send(RequestItem::Finish);

        // join the threads
        let tx_result = if let Some(handle) = self.tx_handle.take() {
            handle.join()
        } else {
            Ok(())
        };
        let rx_result = if let Some(handle) = self.rx_handle.take() {
            handle.join()
        } else {
            Ok(())
        };

        if tx_result.is_err() {
            warn!("Failure joining xio tx thread");
        }
        if rx_result.is_err() {
            warn!("Failure joining xio rx thread");
        }
    }
}

impl Connection {
    /// Create a Connection, and give it an identifier.
    ///
    /// The identifier gets inserted in the thread name, helping to identify
    /// threads when debugging.
    ///
    /// The resulting thread name is something like "xio_tx:<identifier>" or
    /// "xio_rx:<identifier>".
    pub fn new_with_identifier(
        port: &str,
        identifier: &str,
    ) -> Result<Self> {
        let mut settings = serialport::SerialPortSettings::default();
        settings.timeout = Duration::from_millis(100);
        let port = serialport::open_with_settings(port, &settings)?;

        let mut tx_port = port.try_clone()?;
        let mut rx_port = port.try_clone()?;

        let (register_response_sender, register_response_receiver) =
            unbounded::<SenderRegistration<ResponseItem>>();
        let (register_notification_sender, register_notification_receiver) =
            unbounded::<SenderRegistration<NotificationItem>>();

        let (tx_request_sender, tx_request_receiver) =
            unbounded::<RequestItem>();
        let (rx_shutdown_sender, rx_shutdown_receiver) = unbounded::<()>();
        let tx_handle = thread::Builder::new()
            .name(format!("xio_tx:{}", identifier))
            .spawn(move || {
                for item in tx_request_receiver {
                    match item {
                        RequestItem::Request {
                            request,
                            options,
                            sequence,
                        } => {
                            debug!("Sending request {:?}", request);
                            if let Err(e) = request.write_to(
                                &mut tx_port,
                                options,
                                sequence,
                            ) {
                                warn!(
                                    "Error writing to xio tx port, \
                                     closing down: {:?}",
                                    e
                                );
                                return;
                            }
                        }
                        RequestItem::Finish => {
                            return;
                        }
                    }
                }
            })
            .context(ErrorKind::ThreadCreation)?;

        let rx_handle = {
            thread::Builder::new()
                .name(format!("xio_rx:{}", identifier))
                .spawn(move || {
                    let mut responses =
                        RegisteredSenders::new(register_response_receiver);
                    let mut notifications = RegisteredSenders::new(
                        register_notification_receiver,
                    );

                    loop {
                        match Message::read_from(&mut rx_port) {
                            Ok((sequence, msg)) => match msg {
                                Message::Request(r) => {
                                    warn!(
                                        "Received a request message from \
                                         a xio device which should never \
                                         happen: {:?}",
                                        r
                                    );
                                }
                                Message::Response(response) => {
                                    responses.process_pending();

                                    let response = ResponseItem {
                                        sequence,
                                        response,
                                    };
                                    responses.send(response);
                                }
                                Message::Notification(notification) => {
                                    notifications.process_pending();
                                    let notification = NotificationItem {
                                        sequence,
                                        notification,
                                    };
                                    notifications.send(notification);
                                }
                            },
                            Err(e) => {
                                if let Some(()) =
                                    rx_shutdown_receiver.try_recv()
                                {
                                    return;
                                }
                                if e.kind() != std::io::ErrorKind::TimedOut
                                {
                                    // might happen if a shutdown is in progress
                                    warn!("Error received: {:?}", e);
                                }
                            }
                        }
                    }
                })
                .context(ErrorKind::ThreadCreation)?
        };
        Ok(Connection {
            port,
            tx_request_sender,
            register_response_sender,
            register_notification_sender,
            rx_shutdown_sender,
            tx_handle: Some(tx_handle),
            rx_handle: Some(rx_handle),
            sequence: SequenceHolder::default(),
        })
    }

    pub fn new(port: &str) -> Result<Self> {
        Self::new_with_identifier(port, port)
    }

    pub fn add_response_rx(&mut self) -> RxHandle<ResponseItem> {
        RxHandle::new(&self.register_response_sender)
    }

    pub fn add_notification_rx(&mut self) -> RxHandle<NotificationItem> {
        RxHandle::new(&self.register_notification_sender)
    }

    pub fn get_handle(&mut self) -> Result<Handle> {
        let seq = self.sequence.clone();
        let rx = Arc::new(Mutex::new(self.add_response_rx()));
        let tx = self.tx_request_sender.clone();
        Ok(Handle { seq, tx, rx })
    }
}

pub trait SendAndReceive<Q, S>
where
    Q: IsRequest<Response = S>,
    S: IsResponse<Request = Q>,
{
    type Error;
    fn send_and_receive(
        &mut self,
        request: Q,
    ) -> std::result::Result<S, Self::Error>;
}

impl SendAndReceive<Vec<Request>, Vec<Response>> for Handle {
    type Error = Error;
    fn send_and_receive(
        &mut self,
        request: Vec<Request>,
    ) -> Result<Vec<Response>> {
        let expected_sequences = request
            .into_iter()
            .map(|request| self.send(0u8, request))
            .collect::<Result<Vec<_>>>()?;

        let responses = expected_sequences
            .into_iter()
            .map(|sequence| self.receive_next(sequence))
            .collect::<Result<Vec<_>>>()?;

        Ok(responses)
    }
}

impl SendAndReceive<Request, Response> for Handle {
    type Error = Error;
    fn send_and_receive(&mut self, request: Request) -> Result<Response> {
        let mut responses = self.send_and_receive(vec![request])?;
        let response = responses.drain(..).next();
        response.ok_or_else(|| ErrorKind::ProgrammerError.into())
    }
}

impl<Q, S> SendAndReceive<Q, S> for Handle
where
    Q: Into<Request> + IsRequest<Response = S>,
    S: super::messages::TryFromResponse + IsResponse<Request = Q>,
{
    type Error = Error;
    fn send_and_receive(&mut self, request: Q) -> Result<S> {
        let response = self.send_and_receive(request.into())?;
        Ok(S::try_from_response(response)?)
    }
}

#[derive(Clone)]
pub struct Handle {
    seq: SequenceHolder,
    tx: Sender<RequestItem>,
    rx: Arc<Mutex<RxHandle<ResponseItem>>>,
}

impl Handle {
    pub fn send(&mut self, options: u8, request: Request) -> Result<u8> {
        let sequence = self.seq.request_sequence_number()?;
        self.tx.send(RequestItem::Request {
            request,
            options,
            sequence,
        });
        Ok(sequence)
    }

    fn receive_next(&self, expected_sequence: u8) -> Result<Response> {
        let timeout = Duration::from_millis(100);

        let mut i = 0usize;

        while i < 20usize {
            let rx_lock = self.rx.lock().unwrap();
            let rx = rx_lock.receiver();
            select! {
                recv(rx, item) => {
                    if let Some(ResponseItem{sequence,response}) = item {
                        if expected_sequence == sequence {
                            return Ok(response);
                        }
                    } else {
                        return Err(ErrorKind::ChannelReceiverDisconnected.into());
                    }
                }
                recv(after(timeout)) => {
                    i = i + 1usize;
                }
            }
        }
        Err(ErrorKind::Timeout.into())
    }
}