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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
//! Bindings for serial port I/O and futures
//!
//! This crate provides bindings between `mio_serial`, a mio crate for
//! serial port I/O, and `futures`.  The API is very similar to the
//! bindings in `mio_serial`
//!
#![deny(missing_docs)]
#![warn(rust_2018_idioms)]

// Re-export serialport types and traits from mio_serial
pub use mio_serial::{
    available_ports, new, ClearBuffer, DataBits, Error, ErrorKind, FlowControl, Parity, SerialPort,
    SerialPortBuilder, SerialPortInfo, SerialPortType, StopBits, UsbPortInfo,
};

use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};

use std::io::{Read, Result as IoResult, Write};
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;

#[cfg(feature = "codec")]
mod frame;

#[cfg(unix)]
mod os_prelude {
    pub use futures::ready;
    pub use tokio::io::unix::AsyncFd;
}

#[cfg(windows)]
mod os_prelude {
    pub use std::mem;
    pub use std::ops::{Deref, DerefMut};
    pub use std::os::windows::prelude::*;
    pub use tokio::net::windows::named_pipe;
}

use crate::os_prelude::*;

/// A type for results generated by interacting with serial ports.
pub type Result<T> = mio_serial::Result<T>;

/// Async serial port I/O
///
/// Reading and writing to a `TcpStream` is usually done using the
/// convenience methods found on the [`tokio::io::AsyncReadExt`] and [`tokio::io::AsyncWriteExt`]
/// traits.
///
/// [`AsyncReadExt`]: trait@tokio::io::AsyncReadExt
/// [`AsyncWriteExt`]: trait@tokio::io::AsyncWriteExt
///
#[derive(Debug)]
pub struct SerialStream {
    #[cfg(unix)]
    inner: AsyncFd<mio_serial::SerialStream>,
    // Named pipes and COM ports are actually two entirely different things that hardly have anything in common.
    // The only thing they share is the opaque `HANDLE` type that can be fed into `CreateFileW`, `ReadFile`, `WriteFile`, etc.
    //
    // Both `mio` and `tokio` don't yet have any code to work on arbitrary HANDLEs.
    // But they have code for dealing with named pipes, and we (ab)use that here to work on COM ports.
    #[cfg(windows)]
    inner: named_pipe::NamedPipeClient,
    // The com port is kept around for serialport related methods
    #[cfg(windows)]
    com: mem::ManuallyDrop<mio_serial::SerialStream>,
}

impl SerialStream {
    /// Open serial port from a provided path, using the default reactor.
    pub fn open(builder: &crate::SerialPortBuilder) -> crate::Result<Self> {
        let port = mio_serial::SerialStream::open(builder)?;

        #[cfg(unix)]
        {
            Ok(Self {
                inner: AsyncFd::new(port)?,
            })
        }

        #[cfg(windows)]
        {
            let handle = port.as_raw_handle();
            // Keep the com port around to use for serialport related things
            let com = mem::ManuallyDrop::new(port);
            Ok(Self {
                inner: unsafe { named_pipe::NamedPipeClient::from_raw_handle(handle)? },
                com,
            })
        }
    }

    /// Create a pair of pseudo serial terminals using the default reactor
    ///
    /// ## Returns
    /// Two connected, unnamed `Serial` objects.
    ///
    /// ## Errors
    /// Attempting any IO or parameter settings on the slave tty after the master
    /// tty is closed will return errors.
    ///
    #[cfg(unix)]
    pub fn pair() -> crate::Result<(Self, Self)> {
        let (master, slave) = mio_serial::SerialStream::pair()?;

        let master = SerialStream {
            inner: AsyncFd::new(master)?,
        };
        let slave = SerialStream {
            inner: AsyncFd::new(slave)?,
        };
        Ok((master, slave))
    }

    /// Sets the exclusivity of the port
    ///
    /// If a port is exclusive, then trying to open the same device path again
    /// will fail.
    ///
    /// See the man pages for the tiocexcl and tiocnxcl ioctl's for more details.
    ///
    /// ## Errors
    ///
    /// * `Io` for any error while setting exclusivity for the port.
    #[cfg(unix)]
    pub fn set_exclusive(&mut self, exclusive: bool) -> crate::Result<()> {
        self.inner.get_mut().set_exclusive(exclusive)
    }

    /// Returns the exclusivity of the port
    ///
    /// If a port is exclusive, then trying to open the same device path again
    /// will fail.
    #[cfg(unix)]
    pub fn exclusive(&self) -> bool {
        self.inner.get_ref().exclusive()
    }

    /// Borrow a reference to the underlying mio-serial::SerialStream object.
    #[inline(always)]
    fn borrow(&self) -> &mio_serial::SerialStream {
        #[cfg(unix)]
        {
            self.inner.get_ref()
        }
        #[cfg(windows)]
        {
            self.com.deref()
        }
    }

    /// Borrow a mutable reference to the underlying mio-serial::SerialStream object.
    #[inline(always)]
    fn borrow_mut(&mut self) -> &mut mio_serial::SerialStream {
        #[cfg(unix)]
        {
            self.inner.get_mut()
        }
        #[cfg(windows)]
        {
            self.com.deref_mut()
        }
    }
    /// Try to read bytes on the serial port.  On success returns the number of bytes read.
    ///
    /// The function must be called with valid byte array `buf` of sufficient
    /// size to hold the message bytes. If a message is too long to fit in the
    /// supplied buffer, excess bytes may be discarded.
    ///
    /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
    /// returned. This function is usually paired with `readable()`.
    pub fn try_read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
        #[cfg(unix)]
        {
            self.inner.get_mut().read(buf)
        }
        #[cfg(windows)]
        {
            self.inner.try_read(buf)
        }
    }

    /// Wait for the port to become readable.
    ///
    /// This function is usually paired with `try_read()`.
    ///
    /// The function may complete without the socket being readable. This is a
    /// false-positive and attempting a `try_read()` will return with
    /// `io::ErrorKind::WouldBlock`.
    pub async fn readable(&self) -> IoResult<()> {
        let _ = self.inner.readable().await?;
        Ok(())
    }

    /// Try to write bytes on the serial port.  On success returns the number of bytes written.
    ///
    /// When the write would block, `Err(io::ErrorKind::WouldBlock)` is
    /// returned. This function is usually paired with `writable()`.
    pub fn try_write(&mut self, buf: &[u8]) -> IoResult<usize> {
        #[cfg(unix)]
        {
            self.inner.get_mut().write(buf)
        }
        #[cfg(windows)]
        {
            self.inner.try_write(buf)
        }
    }

    /// Wait for the port to become writable.
    ///
    /// This function is usually paired with `try_write()`.
    ///
    /// The function may complete without the socket being readable. This is a
    /// false-positive and attempting a `try_write()` will return with
    /// `io::ErrorKind::WouldBlock`.
    pub async fn writable(&self) -> IoResult<()> {
        let _ = self.inner.writable().await?;
        Ok(())
    }
}

#[cfg(unix)]
impl AsyncRead for SerialStream {
    /// Attempts to ready bytes on the serial port.
    ///
    /// Note that on multiple calls to a `poll_*` method in the read direction, only the
    /// `Waker` from the `Context` passed to the most recent call will be scheduled to
    /// receive a wakeup.
    ///
    /// # Return value
    ///
    /// The function returns:
    ///
    /// * `Poll::Pending` if the socket is not ready to read
    /// * `Poll::Ready(Ok(()))` reads data `ReadBuf` if the socket is ready
    /// * `Poll::Ready(Err(e))` if an error is encountered.
    ///
    /// # Errors
    ///
    /// This function may encounter any standard I/O error except `WouldBlock`.
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<IoResult<()>> {
        loop {
            let mut guard = ready!(self.inner.poll_read_ready(cx))?;

            match guard.try_io(|inner| inner.get_ref().read(buf.initialize_unfilled())) {
                Ok(Ok(bytes_read)) => {
                    buf.advance(bytes_read);
                    return Poll::Ready(Ok(()));
                }
                Ok(Err(err)) => {
                    return Poll::Ready(Err(err));
                }
                Err(_would_block) => continue,
            }
        }
    }
}

#[cfg(unix)]
impl AsyncWrite for SerialStream {
    /// Attempts to send data on the serial port
    ///
    /// Note that on multiple calls to a `poll_*` method in the send direction,
    /// only the `Waker` from the `Context` passed to the most recent call will
    /// be scheduled to receive a wakeup.
    ///
    /// # Return value
    ///
    /// The function returns:
    ///
    /// * `Poll::Pending` if the socket is not available to write
    /// * `Poll::Ready(Ok(n))` `n` is the number of bytes sent
    /// * `Poll::Ready(Err(e))` if an error is encountered.
    ///
    /// # Errors
    ///
    /// This function may encounter any standard I/O error except `WouldBlock`.
    fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<IoResult<usize>> {
        loop {
            let mut guard = ready!(self.inner.poll_write_ready(cx))?;

            match guard.try_io(|inner| inner.get_ref().write(buf)) {
                Ok(result) => return Poll::Ready(result),
                Err(_would_block) => continue,
            }
        }
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> {
        loop {
            let mut guard = ready!(self.inner.poll_write_ready(cx))?;
            match guard.try_io(|inner| inner.get_ref().flush()) {
                Ok(_) => return Poll::Ready(Ok(())),
                Err(_would_block) => continue,
            }
        }
    }

    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> {
        let _ = self.poll_flush(cx)?;
        Ok(()).into()
    }
}

#[cfg(windows)]
impl AsyncRead for SerialStream {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<IoResult<()>> {
        let mut self_ = self;
        Pin::new(&mut self_.inner).poll_read(cx, buf)
    }
}

#[cfg(windows)]
impl AsyncWrite for SerialStream {
    fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<IoResult<usize>> {
        let mut self_ = self;
        Pin::new(&mut self_.inner).poll_write(cx, buf)
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> {
        let mut self_ = self;
        Pin::new(&mut self_.inner).poll_flush(cx)
    }

    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> {
        let mut self_ = self;
        Pin::new(&mut self_.inner).poll_shutdown(cx)
    }
}

impl crate::SerialPort for SerialStream {
    #[inline(always)]
    fn name(&self) -> Option<String> {
        self.borrow().name()
    }

    #[inline(always)]
    fn baud_rate(&self) -> crate::Result<u32> {
        self.borrow().baud_rate()
    }

    #[inline(always)]
    fn data_bits(&self) -> crate::Result<crate::DataBits> {
        self.borrow().data_bits()
    }

    #[inline(always)]
    fn flow_control(&self) -> crate::Result<crate::FlowControl> {
        self.borrow().flow_control()
    }

    #[inline(always)]
    fn parity(&self) -> crate::Result<crate::Parity> {
        self.borrow().parity()
    }

    #[inline(always)]
    fn stop_bits(&self) -> crate::Result<crate::StopBits> {
        self.borrow().stop_bits()
    }

    #[inline(always)]
    fn timeout(&self) -> Duration {
        Duration::from_secs(0)
    }

    #[inline(always)]
    fn set_baud_rate(&mut self, baud_rate: u32) -> crate::Result<()> {
        self.borrow_mut().set_baud_rate(baud_rate)
    }

    #[inline(always)]
    fn set_data_bits(&mut self, data_bits: crate::DataBits) -> crate::Result<()> {
        self.borrow_mut().set_data_bits(data_bits)
    }

    #[inline(always)]
    fn set_flow_control(&mut self, flow_control: crate::FlowControl) -> crate::Result<()> {
        self.borrow_mut().set_flow_control(flow_control)
    }

    #[inline(always)]
    fn set_parity(&mut self, parity: crate::Parity) -> crate::Result<()> {
        self.borrow_mut().set_parity(parity)
    }

    #[inline(always)]
    fn set_stop_bits(&mut self, stop_bits: crate::StopBits) -> crate::Result<()> {
        self.borrow_mut().set_stop_bits(stop_bits)
    }

    #[inline(always)]
    fn set_timeout(&mut self, _: Duration) -> crate::Result<()> {
        Ok(())
    }

    #[inline(always)]
    fn write_request_to_send(&mut self, level: bool) -> crate::Result<()> {
        self.borrow_mut().write_request_to_send(level)
    }

    #[inline(always)]
    fn write_data_terminal_ready(&mut self, level: bool) -> crate::Result<()> {
        self.borrow_mut().write_data_terminal_ready(level)
    }

    #[inline(always)]
    fn read_clear_to_send(&mut self) -> crate::Result<bool> {
        self.borrow_mut().read_clear_to_send()
    }

    #[inline(always)]
    fn read_data_set_ready(&mut self) -> crate::Result<bool> {
        self.borrow_mut().read_data_set_ready()
    }

    #[inline(always)]
    fn read_ring_indicator(&mut self) -> crate::Result<bool> {
        self.borrow_mut().read_ring_indicator()
    }

    #[inline(always)]
    fn read_carrier_detect(&mut self) -> crate::Result<bool> {
        self.borrow_mut().read_carrier_detect()
    }

    #[inline(always)]
    fn bytes_to_read(&self) -> crate::Result<u32> {
        self.borrow().bytes_to_read()
    }

    #[inline(always)]
    fn bytes_to_write(&self) -> crate::Result<u32> {
        self.borrow().bytes_to_write()
    }

    #[inline(always)]
    fn clear(&self, buffer_to_clear: crate::ClearBuffer) -> crate::Result<()> {
        self.borrow().clear(buffer_to_clear)
    }

    /// Cloning SerialStream is not supported.
    ///
    /// # Errors
    /// Always returns `ErrorKind::Other` with a message.
    #[inline(always)]
    fn try_clone(&self) -> crate::Result<Box<dyn crate::SerialPort>> {
        Err(crate::Error::new(
            crate::ErrorKind::Io(std::io::ErrorKind::Other),
            "Cannot clone Tokio handles",
        ))
    }

    #[inline(always)]
    fn set_break(&self) -> crate::Result<()> {
        self.borrow().set_break()
    }

    #[inline(always)]
    fn clear_break(&self) -> crate::Result<()> {
        self.borrow().clear_break()
    }
}

impl Read for SerialStream {
    fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
        self.try_read(buf)
    }
}

impl Write for SerialStream {
    fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
        self.try_write(buf)
    }

    fn flush(&mut self) -> IoResult<()> {
        self.borrow_mut().flush()
    }
}

#[cfg(unix)]
mod sys {
    use super::SerialStream;
    use std::os::unix::io::{AsRawFd, RawFd};
    impl AsRawFd for SerialStream {
        fn as_raw_fd(&self) -> RawFd {
            self.inner.as_raw_fd()
        }
    }
}

#[cfg(windows)]
mod io {
    use super::SerialStream;
    use std::os::windows::io::{AsRawHandle, RawHandle};
    impl AsRawHandle for SerialStream {
        fn as_raw_handle(&self) -> RawHandle {
            self.inner.as_raw_handle()
        }
    }
}

/// An extension trait for serialport::SerialPortBuilder
///
/// This trait adds one method to SerialPortBuilder:
///
/// - open_native_async
///
/// This method mirrors the `open_native` method of SerialPortBuilder
pub trait SerialPortBuilderExt {
    /// Open a platform-specific interface to the port with the specified settings
    fn open_native_async(self) -> Result<SerialStream>;
}

impl SerialPortBuilderExt for SerialPortBuilder {
    /// Open a platform-specific interface to the port with the specified settings
    fn open_native_async(self) -> Result<SerialStream> {
        SerialStream::open(&self)
    }
}