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
use std::ffi::c_void;
use std::io;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::io::RawFd;
use std::path::Path;

#[derive(Debug)]
enum PhyData<'a> {
    Rx {
        buffer: crate::phy::BufferHandle<'a>,
        length: usize,
    },
    Tx {
        buffer: crate::phy::BufferHandle<'a>,
        length: usize,
        cursor: usize,
    },
}

impl PhyData<'_> {
    pub fn is_rx(&self) -> bool {
        match self {
            PhyData::Rx { .. } => true,
            _ => false,
        }
    }

    pub fn is_tx(&self) -> bool {
        match self {
            PhyData::Tx { .. } => true,
            _ => false,
        }
    }

    pub fn make_rx(&mut self) {
        if let PhyData::Tx { buffer, .. } = self {
            let buffer = std::mem::replace(buffer, [].into());
            *self = PhyData::Rx { buffer, length: 0 };
        }
    }
}

/// Linux userspace PHY implementation for serial TTY devices
///
/// Available with the `phy-linux` feature.
///
/// **Important**: Due to the non-realtime nature of Linux, you must use this PHY implementation
/// with care.  You may need to decrease the baudrate or lengthen timeouts (T<sub>SLOT</sub>) to
/// get reliable communication.  You should also consider running your pogram at "real-time
/// priority" if you need higher bus speeds.  It is advisable to run tests with heavy system load
/// to ensure the bus communication stays reliable in all circumstances.
///
/// **Important 2**: If you plan to use this PHY with a USB-serial device, you have to choose your
/// bus parameters even more carefully.  Stick to very low baudrates (<= 500kbit/s) and increase
/// T<sub>SL</sub> (slot time) to deal with communication delays.  Tests have shown a slot time of
/// ~5ms to work reliably (at 500kbit/s, that would be 2500 T_bit).  Additionally, it seems to be
/// important to give the OS time to deliver received data by sleeping long enough between `poll()`
/// calls.  A minimum sleep of 2ms was needed in my tests to ensure all received data is delivered
/// in time.
///
/// # Example
/// ```no_run
/// use profirust::{Baudrate, fdl, dp, phy};
/// const BAUDRATE: Baudrate = Baudrate::B19200;
/// # let mut dp_master = dp::DpMaster::new(vec![]);
///
/// let mut fdl_master = fdl::FdlMaster::new(
///     fdl::ParametersBuilder::new(0x02, BAUDRATE)
///         // Increase T_slot (slot time)
///         .slot_bits(1920)
///         .build_verified(&dp_master)
/// );
///
/// let mut phy = phy::LinuxRs485Phy::new("/dev/ttyS0", fdl_master.parameters().baudrate);
/// ```
#[derive(Debug)]
pub struct LinuxRs485Phy<'a> {
    fd: RawFd,
    data: PhyData<'a>,
}

impl LinuxRs485Phy<'_> {
    /// Construct and initialize a new PHY device
    ///
    /// This function will attempt to configure the TTY device `serial_port` for PROFIBUS
    /// communication (line settings via termios and RS-485 mode when available).
    #[inline]
    pub fn new<P: AsRef<Path>>(serial_port: P, baudrate: crate::Baudrate) -> Self {
        Self::new_inner(&serial_port.as_ref(), baudrate)
    }

    fn new_inner(serial_port: &Path, baudrate: crate::Baudrate) -> Self {
        // open serial port non-blocking
        let path = std::ffi::CString::new(serial_port.as_os_str().as_bytes()).unwrap();
        let fd = unsafe {
            libc::open(
                path.as_ptr() as *const i8,
                libc::O_RDWR | libc::O_NONBLOCK | libc::O_NOCTTY,
            )
        };
        if fd < 0 {
            let error = io::Error::last_os_error();
            Result::<(), _>::Err(error).unwrap();
        }

        let mut tty: libc::termios2 = unsafe { core::mem::zeroed() };
        if unsafe { libc::ioctl(fd, libc::TCGETS2, &mut tty) } < 0 {
            let error = io::Error::last_os_error();
            Result::<(), _>::Err(error).unwrap();
        }

        tty.c_iflag &= !(libc::IGNBRK
            | libc::BRKINT
            | libc::PARMRK
            | libc::ISTRIP
            | libc::INLCR
            | libc::IGNCR
            | libc::ICRNL
            | libc::IXON);
        tty.c_oflag &= !(libc::OPOST | libc::ONLCR);
        tty.c_lflag &= !(libc::ISIG
            | libc::ICANON
            | libc::IEXTEN
            | libc::ECHO
            | libc::ECHOE
            | libc::ECHOK
            | libc::ECHONL);

        tty.c_cflag &= !(libc::CSIZE
            | libc::PARODD
            | libc::CSTOPB
            | libc::CRTSCTS
            | (libc::CBAUD | libc::CBAUDEX)
            | ((libc::CBAUD | libc::CBAUDEX) << libc::IBSHIFT));
        tty.c_cflag |= libc::CS8 | libc::PARENB | libc::BOTHER | (libc::BOTHER << libc::IBSHIFT);

        // Ensure non-blocking access
        tty.c_cc[libc::VMIN] = 0;
        tty.c_cc[libc::VTIME] = 0;

        // Set speed
        let baud = baudrate.to_rate().try_into().unwrap();
        tty.c_ispeed = baud;
        tty.c_ospeed = baud;
        log::debug!("Speed: {}", tty.c_ispeed);

        if unsafe { libc::ioctl(fd, libc::TCSETS2, &tty) } < 0 {
            let error = io::Error::last_os_error();
            Result::<(), _>::Err(error).unwrap();
        }

        // Read back to ensure baudrates are correct.
        if unsafe { libc::ioctl(fd, libc::TCGETS2, &mut tty) } < 0 {
            let error = io::Error::last_os_error();
            Result::<(), _>::Err(error).unwrap();
        }

        assert_eq!(
            tty.c_ispeed, baud,
            "c_ispeed not matching expected baudrate"
        );
        assert_eq!(
            tty.c_ospeed, baud,
            "c_ospeed not matching expected baudrate"
        );

        let res = rs485::SerialRs485::new()
            .set_enabled(true)
            .set_rts_on_send(true)
            .set_rts_after_send(false)
            .set_rx_during_tx(false)
            .set_on_fd(fd);
        if let Err(e) = res {
            log::warn!("Could not configure RS485 mode: {}", e);
        }

        // TODO: Allow configuring this buffer?
        let buffer = crate::phy::BufferHandle::from(vec![0u8; 512]);

        Self {
            fd,
            data: PhyData::Rx { buffer, length: 0 },
        }
    }

    /// Wait/block until the current transmission completes.
    ///
    /// This is useful to save CPU time as the PROFIBUS stack can't do much anyway until the
    /// transmission is over.
    pub fn wait_transmit(&mut self) {
        if self.data.is_tx() {
            unsafe { libc::tcdrain(self.fd) };
        }
    }

    fn write(fd: RawFd, buffer: &[u8]) -> io::Result<usize> {
        match unsafe { libc::write(fd, buffer.as_ptr() as *const c_void, buffer.len()) } {
            -1 => {
                let err = io::Error::last_os_error();
                if err.kind() == io::ErrorKind::WouldBlock {
                    Ok(0)
                } else {
                    Err(err)
                }
            }
            written => Ok(usize::try_from(written).unwrap()),
        }
    }

    fn get_output_queue(&mut self) -> io::Result<usize> {
        let mut arg: std::ffi::c_int = 0;
        let res = unsafe { libc::ioctl(self.fd, libc::TIOCOUTQ, &mut arg) };
        if res < 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(usize::try_from(arg).unwrap())
    }

    fn read(fd: RawFd, buffer: &mut [u8]) -> io::Result<usize> {
        match unsafe { libc::read(fd, buffer.as_mut_ptr() as *mut c_void, buffer.len()) } {
            -1 => {
                let err = io::Error::last_os_error();
                if err.kind() == io::ErrorKind::WouldBlock {
                    Ok(0)
                } else {
                    Err(err)
                }
            }
            written => Ok(usize::try_from(written).unwrap()),
        }
    }
}

impl<'a> crate::phy::ProfibusPhy for LinuxRs485Phy<'a> {
    fn poll_transmission(&mut self, _now: crate::time::Instant) -> bool {
        if let PhyData::Tx {
            buffer,
            length,
            cursor,
        } = &mut self.data
        {
            if length != cursor {
                // Need to submit more data.
                let written = Self::write(self.fd, &buffer[*cursor..*length]).unwrap();
                debug_assert!(written <= *length - *cursor);
                *cursor += written;
                true
            } else {
                // Everything was submitted already.
                let queued = self.get_output_queue().unwrap();
                if queued == 0 {
                    // All data was sent.
                    self.data.make_rx();
                    false
                } else {
                    // Still sending.
                    true
                }
            }
        } else {
            false
        }
    }

    fn transmit_data<F, R>(&mut self, _now: crate::time::Instant, f: F) -> R
    where
        F: FnOnce(&mut [u8]) -> (usize, R),
    {
        match &mut self.data {
            PhyData::Tx { .. } => panic!("transmit_data() while already transmitting!"),
            PhyData::Rx {
                buffer,
                length: receive_length,
            } => {
                if *receive_length != 0 {
                    log::warn!(
                        "{} bytes in the receive buffer and we go into transmission?",
                        receive_length
                    );
                }
                let (length, res) = f(&mut buffer[..]);
                if length == 0 {
                    // Don't transmit anything.
                    return res;
                }
                let cursor = Self::write(self.fd, &buffer[..length]).unwrap();
                debug_assert!(cursor <= length);
                let buffer = std::mem::replace(buffer, [].into());
                self.data = PhyData::Tx {
                    buffer,
                    length,
                    cursor,
                };
                res
            }
        }
    }

    fn receive_data<F, R>(&mut self, _now: crate::time::Instant, f: F) -> R
    where
        F: FnOnce(&[u8]) -> (usize, R),
    {
        match &mut self.data {
            PhyData::Tx { .. } => panic!("receive_data() while transmitting!"),
            PhyData::Rx { buffer, length } => {
                *length += Self::read(self.fd, &mut buffer[*length..]).unwrap();
                debug_assert!(*length <= buffer.len());
                let (drop, res) = f(&buffer[..*length]);
                match drop {
                    0 => (),
                    d if d == *length => *length = 0,
                    d => {
                        assert!(d < *length);
                        for i in 0..(*length - d) {
                            buffer[i] = buffer[i + d];
                        }
                        *length -= d;
                    }
                }
                res
            }
        }
    }
}