2
0

tty.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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_task_handler(void *);
  46. static void usb_onevent(void *arg, esp_event_base_t event_base,
  47. int32_t event_id, void *event_data);
  48. static void uart_onrx();
  49. static void uart_onerr(hardwareSerial_error_t);
  50. enum rx_state {
  51. normal, // Normal console mode
  52. stxwait, // Waiting for header STX
  53. hdr, // Getting header
  54. data // Getting data packet
  55. };
  56. void _upload_begin();
  57. void _update_window(bool rst = false);
  58. int _decode_data(int);
  59. // Packet receive state machine
  60. struct {
  61. enum rx_state state;
  62. uint8_t b64_buf;
  63. uint8_t b64_bits;
  64. union {
  65. struct tty_packet_hdr hdr;
  66. uint8_t hdr_raw[sizeof(struct tty_packet_hdr)];
  67. };
  68. size_t rlen;
  69. uint32_t last_ack;
  70. } rx;
  71. StreamBufferHandle_t rx_sbuf;
  72. uint32_t tx_credits;
  73. volatile bool tx_credits_reset;
  74. volatile uint32_t last_rx;
  75. uint8_t rx_data[256];
  76. };