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
/* serialport.rs
 *
 * Developed by Tim Walls <tim.walls@snowgoons.com>
 * Copyright (c) All Rights Reserved, Tim Walls
 */
//! Abstractions for serial I/O devices, implementing the Read/Write interfaces
//! provided by [`avr_oxide::io`].
//!
//! The SerialPort implementation supports the port multiplexing of the AVR
//! controller, meaning that an underlying USART may be connected to different
//! pins of the controller at runtime.  Thus the device must be instantiated
//! with both the USART device to use, and the pins which will be used for
//! receive and transmit.
//!
//! # Usage
//! ```no_run
//! # #![no_std]
//! # #![no_main]
//! #
//! # use avr_oxide::alloc::boxed::Box;
//! # use avr_oxide::devices::UsesPin;
//! # use avr_oxide::devices::debouncer::Debouncer;
//! # use avr_oxide::devices::{ OxideLed, OxideButton, OxideSerialPort };
//! # use avr_oxide::hal::generic::serial::{BaudRate, DataBits, Parity, SerialPortMode, StopBits};
//! # use avr_oxide::io::Write;
//! # use avr_oxide::boards::board;
//! # use avr_oxide::StaticWrap;
//! #
//! # #[avr_oxide::main(chip="atmega4809")]
//! # pub fn main() {
//! #   let supervisor = avr_oxide::oxide::instance();
//!
//!   // Configure the serial port early so we can get any panic!() messages
//!   let mut serial= OxideSerialPort::using_port_and_pins(board::usb_serial(),
//!                                                        board::usb_serial_pins().0,
//!                                                        board::usb_serial_pins().1).mode(SerialPortMode::Asynch(BaudRate::Baud9600, DataBits::Bits8, Parity::None, StopBits::Bits1));
//!   serial.write(b"Welcome to AVRoxide\n");
//!
//! #    supervisor.run();
//! # }
//! ```


// Imports ===================================================================
use avr_oxide::hal::generic::serial::{SerialRxTx, ReadHandlerResult, SerialError, SerialPortMode, SerialPortIdentity, SerialWriteEventCallback, SerialReadEventCallback, SerialErrorEventCallback};
use avr_oxide::event::{EventSink, EventSource, OxideEvent, OxideEventEnvelope};
use core::marker::PhantomData;
use core::cell::RefCell;
use core::ops::DerefMut;
use ufmt::derive::uDebug;
use oxide_macros::Persist;
use avr_oxide::alloc::boxed::Box;
use avr_oxide::hal::generic::port::{InterruptMode, Pin, PinMode};
use avr_oxide::panic_if_none;
use avr_oxide::sync::Mutex;
use avr_oxide::util::datatypes::{BitField, BitFieldAccess, BitIndex};
use avr_oxide::OxideResult::{Ok};


// Declarations ===============================================================
pub trait SerialCallback = FnMut(SerialPortIdentity, SerialState) -> ();

/**
 * State of the serial port sent with Oxide events.
 */
#[derive(PartialEq,Eq,Clone,Copy,uDebug,Persist)]
pub enum SerialState {
  /// There is data waiting in the buffer for someone to read it
  ReadAvailable,

  /// A serial error has been detected (framing, parity etc.)
  SerialCommsError,

  /// A *break* condition on the receive line has been detected
  BreakDetected,

  /// The receive buffer has overflowed (data was not consumed quickly
  /// enough...)
  ReadBufferOverflow
}

/**
 * Options for controlling how data is transmitted by the serial port device.
 */
pub type SerialOptions = BitField;


/**
 * Encapsulation of a serial port exposing the standard io::Read/io::Write
 * traits.  Also generates Oxide event notifications.
 */
pub struct SerialPort<'sp,S>
where
  S: EventSink
{
  port: &'static mut dyn SerialRxTx,
  tx: &'static dyn Pin,
  _rx: &'static dyn Pin,
  phantom: PhantomData<S>,

  serial_options: Mutex<SerialOptions>,

  rx_lock: Mutex<()>,
  tx_lock: Mutex<()>,

  on_event: RefCell<Option<Box<dyn SerialCallback + 'sp>>>
}

// Code ======================================================================
const TX_FLUSH_ON_EOL: BitIndex =  BitIndex::bit_c(0);
const TX_CR_TO_CRLF:   BitIndex =  BitIndex::bit_c(1);
const TX_LF_TO_CRLF:   BitIndex =  BitIndex::bit_c(2);
const INTERACTIVE:     BitIndex =  BitIndex::bit_c(3);
const ECHO:            BitIndex =  BitIndex::bit_c(4);
const RX_BLOCKING:     BitIndex =  BitIndex::bit_c(5);
const RX_TO_EOL:       BitIndex =  BitIndex::bit_c(6);
const RX_TO_EOT:       BitIndex =  BitIndex::bit_c(7);

/**
 * Configuration of various translation/usability options for the serial
 * port device.
 *
 * | Option          | Effect                                       |
 * | --------------- | -------------------------------------------- |
 * | `flush_on_eol`  | Automatically flush when an end-of-line is transmitted |
 * | `cr_to_crlf`    | Translate sent CRs to CRLF |
 * | `lf_to_crlf`    | Translate sent LFs to CRLF |
 * | `interactive`   | This is an interactive terminal, reading from the device will automatically flush the transmit buffer first |
 * | `echo`          | Echo all characters received back on the transmit line.  If interactive is set, will also flush after each. |
 * | `blocking_read` | Calls to read() should block until data is available |
 * | `read_to_eol`   | Blocking read()s will immediately return when a CR or LF ('\r' or '\n') is received |
 * | `read_to_eot`   | Blocking read()s will immediately return when an EOT character is received |
 */
impl SerialOptions {
  /// Indicate that the device should automatically flush when an end-of-line
  /// (CR or LF) character is sent
  /// is sent.
  pub fn set_flush_on_eol(&mut self, flag: bool) {
    self.set_or_clr(TX_FLUSH_ON_EOL, flag);
  }

  /// True iff the device should automatically flush when an LF character
  /// is sent.
  pub fn flush_on_eol(self) -> bool {
    self.is_set(TX_FLUSH_ON_EOL)
  }

  /// Indicate that CR should be translated to CRLF automatically
  pub fn set_cr_to_crlf(&mut self, flag: bool) {
    self.set_or_clr(TX_CR_TO_CRLF, flag);
  }

  /// True iff the device should automatically translate CR to CRLF.
  pub fn cr_to_crlf(&self) -> bool {
    self.is_set(TX_CR_TO_CRLF)
  }

  /// Indicate that LF should be translated to CRLF automatically
  pub fn set_lf_to_crlf(&mut self, flag: bool) {
    self.set_or_clr(TX_LF_TO_CRLF, flag);
  }

  /// True iff the device should automatically translate LF to CRLF.
  pub fn lf_to_crlf(&self) -> bool {
    self.is_set(TX_LF_TO_CRLF)
  }
  /// Indicate that this is an interactive terminal.  Effects:
  ///   * A call to read() will automatically flush the transmit buffer
  pub fn set_interactive(&mut self, flag: bool) {
    self.set_or_clr(INTERACTIVE, flag);
  }

  /// True iff this is an interative terminal
  pub fn interactive(&self) -> bool {
    self.is_set(INTERACTIVE)
  }

  /// Indicate that we should echo received characters back.
  /// If the device is also set to `interactive`, then we will flush() after
  /// each echoed character as well.
  pub fn set_echo(&mut self, flag: bool) {
    self.set_or_clr(ECHO, flag)
  }

  /// True iff we should echo everything we receive back on transmit
  pub fn echo(&self) -> bool {
    self.is_set(ECHO)
  }

  /// Indicate that calls to read() should block until data is available
  pub fn set_blocking_read(&mut self, flag: bool) {
    self.set_or_clr(RX_BLOCKING, flag)
  }

  /// True iff read()s should block until data is available
  pub fn blocking_read(&self) -> bool {
    self.is_set(RX_BLOCKING)
  }

  /// Stop blocking read()s as soon as a linefeed (\n) is received
  pub fn set_read_to_eol(&mut self, flag: bool) {
    self.set_or_clr(RX_TO_EOL, flag)
  }

  /// True iff blocking reads will complete when a linefeed (\n) is received
  pub fn read_to_eol(&self) -> bool {
    self.is_set(RX_TO_EOL)
  }

  /// Stop blocking read()s as soon as an EOT is received
  pub fn set_read_to_eot(&mut self, flag: bool) {
    self.set_or_clr(RX_TO_EOT, flag)
  }

  /// True iff blocking reads will complete when an EOT is received
  pub fn read_to_eot(&self) -> bool {
    self.is_set(RX_TO_EOT)
  }



  /// Clear all settings that result in the data being translated in any
  /// way (e.g. CR to CRLF type translations.)  Use this to ensure a serial
  /// port is 'clean' for sending/receiving binary data.
  pub fn disable_translations(&mut self) {
    self.set_cr_to_crlf(false);
    self.set_lf_to_crlf(false);
  }
}

impl Default for SerialOptions {
  /**
   * Default transmit options:
   *  * DO flush automatically on End-of-Line
   *  * DO NOT translate CR to CRLF
   *  * DO NOT translate LF to CRLF
   *  * Interactive mode NOT enabled
   */
  fn default() -> Self {
    BitField::with_bits_set(&[TX_FLUSH_ON_EOL])
  }
}

impl<S> SerialPort<'_,S>
where
  S: EventSink
{
  /**
   * Create an instance of SerialPort that will communicate over the given
   * port and pins.
   */
  pub fn using_port_and_pins(port: &'static mut dyn SerialRxTx, tx: &'static dyn Pin, rx: &'static dyn Pin) -> Self {
    // Set the pins to disabled (floating) until the port is configured
    // with the mode() setting
    tx.set_mode(PinMode::InputFloating);
    rx.set_mode(PinMode::InputFloating);
    rx.set_interrupt_mode(InterruptMode::Disabled);
    tx.set_interrupt_mode(InterruptMode::Disabled);
    port.set_enable_rxtx(false);

    SerialPort {
      port, tx,
      _rx: rx,
      phantom: PhantomData::default(),

      serial_options: Mutex::new(SerialOptions::default()),

      rx_lock: Mutex::new(()),
      tx_lock: Mutex::new(()),
      on_event: RefCell::new(None)
    }
  }

  /**
   * Set the serial port comms parameters.
   */
  pub fn mode(self, mode: SerialPortMode) -> Self {
    self.port.set_mode(mode);

    // Now we can enable the transmit pin again
    self.port.set_enable_rxtx(true);
    self.tx.set_mode(PinMode::Output);

    self
  }

  /**
   * Get the currently configured transmission options.
   */
  pub fn get_options(&self) -> SerialOptions {
    let locked = self.serial_options.lock();

    (*locked).clone()
  }

  /**
   * Set the transmission options.
   */
  pub fn set_options(&mut self, options: SerialOptions) {
    let mut locked = self.serial_options.lock();

    *locked = options;
  }
}

impl<S> EventSource for SerialPort<'_,S>
where
  S: EventSink
{
  fn listen(&'static self) {
    // We won't send any events on write.
    self.port.set_write_complete_callback(SerialWriteEventCallback::Nop(()));

    // When the serial port receives a byte, send a ReadAvailable message
    self.port.set_read_callback(SerialReadEventCallback::WithData(|isotoken, src,byte, udata|{
      S::event(isotoken, OxideEventEnvelope::to(unsafe {&*(panic_if_none!(udata, avr_oxide::oserror::OsError::InternalError) as *const SerialPort<S> as *const dyn EventSource)},
                                                OxideEvent::SerialEvent(src, SerialState::ReadAvailable)));
      ReadHandlerResult::Buffer(byte)
    },self as *const dyn core::any::Any));

    // When the serial port generates an error, send a suitable message
    self.port.set_error_callback(SerialErrorEventCallback::WithData(|isotoken, src,error, udata|{
      S::event(isotoken, OxideEventEnvelope::to(unsafe {&*(panic_if_none!(udata, avr_oxide::oserror::OsError::InternalError) as *const SerialPort<S> as *const dyn EventSource)},
                                                OxideEvent::SerialEvent(src, match error {
                                                  SerialError::BufferOverflow => SerialState::ReadBufferOverflow,
                                                  SerialError::Break => SerialState::BreakDetected,
                                                  _ => SerialState::SerialCommsError
                                                })));
    }, self as *const dyn core::any::Any));
  }

  fn process_event(&self, evt: OxideEvent) {
    match (self.on_event.borrow_mut().deref_mut(), evt) {
      (Some(f), OxideEvent::SerialEvent(source, state)) => {
        (*f)(source,state)
      },
      _ => {}
    }
  }
}

impl<S> avr_oxide::io::Read for SerialPort<'_,S>
where
  S: EventSink
{
  fn read(&mut self, buf: &mut [u8]) -> avr_oxide::io::Result<usize> {
    let options = self.get_options();

    let rx_lock = self.rx_lock.lock();

    let mut cnt = 0usize;

    if options.interactive() {
      let tx_lock = self.tx_lock.lock();
      self.port.flush();
      drop(tx_lock);
    }

    while cnt < buf.len() {
      let character = {
        if options.blocking_read() {
          Some(self.port.read_u8())
        } else {
          self.port.try_read_u8()
        }
      };

      match character {
        Some(c) => {
          buf[cnt] = c;
          cnt += 1;

          if options.echo() {
            let tx_lock = self.tx_lock.lock();
            self.port.write_u8(c);
            self.port.flush();
            drop(tx_lock);
          }

          // Determine if we should stop reading early
          if match c {
            b'\n' | b'\r' => {
              options.read_to_eol()
            },
            0x04u8 => {
              options.read_to_eot()
            },
            b'x' => {
              true
            }
            _ => false
          } {
            return Ok(cnt);
          }
        },
        None => {
          return Ok(cnt);
        }
      }
    }

    drop(rx_lock);
    Ok(cnt)
  }
}

impl<S> avr_oxide::io::Write for SerialPort<'_,S>
where
  S: EventSink
{
  fn write_buffered(&mut self, buf: &[u8]) -> avr_oxide::io::Result<usize> {
    let options = self.get_options();

    let tx_lock = self.tx_lock.lock();
    let cnt : usize = 0;

    for byte in buf {

      // Special handling before we send the character
      match byte {
        b'\n' => {
          if options.lf_to_crlf() {
            self.port.write_u8(b'\r');
          }
        },
        _ => {}
      }

      // Send the character
      self.port.write_u8(*byte);

      // Special handling after we send the character
      match byte {
        b'\r' => {
          if options.cr_to_crlf() {
            self.port.write_u8(b'\n');
          }
          if options.flush_on_eol() {
            self.port.flush();
          }
        },
        b'\n' => {
          if options.flush_on_eol() {
            self.port.flush();
          }
        },
        _ => {}
      }
    }

    drop(tx_lock);
    Ok(cnt)
  }

  fn flush(&mut self) -> avr_oxide::io::Result<()> {
    self.port.flush();
    Ok(())
  }
}

impl<S> ufmt_write::uWrite for SerialPort<'_,S>
where
  S: EventSink
{
  type Error = core::convert::Infallible;

  fn write_str(&mut self, s: &str) -> core::result::Result<(), Self::Error> {
    let _ignore = avr_oxide::io::Write::write(self, s.as_bytes());
    core::result::Result::Ok(())
  }
}

unsafe impl <S> Send for SerialPort<'_,S>
where
  S: EventSink
{}

unsafe impl <S> Sync for SerialPort<'_,S>
where
  S: EventSink
{}