tty.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #pragma once
  2. #include "common.h"
  3. #include <USB.h>
  4. #include <HardwareSerial.h>
  5. #include <FreeRTOS.h>
  6. #include <freertos/stream_buffer.h>
  7. #include <atomic>
  8. void tty_init();
  9. void tty_ping();
  10. //
  11. // This is needed because there isn't a common serial device
  12. // class in Arduino, sigh...
  13. //
  14. struct tty_packet_hdr {
  15. uint8_t stx;
  16. uint8_t len;
  17. uint16_t resv;
  18. uint32_t offs;
  19. uint32_t crc;
  20. } __attribute__((packed));
  21. class TTY {
  22. public:
  23. TTY(Stream &port);
  24. ~TTY();
  25. void reset();
  26. int rxdata(void *buf, size_t len);
  27. static int rxdata(token_t me, void *buf, size_t len);
  28. // Global events
  29. static void init();
  30. static void ping();
  31. private:
  32. Stream *_port; // Android stream
  33. void _onrx();
  34. void _onerr();
  35. void _onbreak();
  36. void _onconnect();
  37. void _ondisconnect();
  38. void (*_flush)();
  39. public:
  40. inline void flush() { _flush(); }
  41. inline Stream & port() { return *_port; }
  42. inline operator Stream & () { return port(); }
  43. private:
  44. // Event handler dispatchers
  45. static void usb_onevent(void *arg, esp_event_base_t event_base,
  46. int32_t event_id, void *event_data);
  47. static void uart_onrx();
  48. static void uart_onerr(hardwareSerial_error_t);
  49. enum rx_state {
  50. normal, // Normal console mode
  51. stxwait, // Waiting for header STX
  52. hdr, // Getting header
  53. data // Getting data packet
  54. };
  55. void _upload_begin();
  56. void _update_window(bool rst = false);
  57. int _decode_data(int);
  58. // Packet receive state machine
  59. struct {
  60. enum rx_state state;
  61. uint8_t b64_buf;
  62. uint8_t b64_bits;
  63. union {
  64. struct tty_packet_hdr hdr;
  65. uint8_t hdr_raw[sizeof(struct tty_packet_hdr)];
  66. };
  67. size_t rlen;
  68. uint32_t last_ack;
  69. } rx;
  70. StreamBufferHandle_t rx_sbuf;
  71. uint32_t tx_credits;
  72. volatile bool tx_credits_reset;
  73. volatile uint32_t last_rx;
  74. uint8_t rx_data[256];
  75. };