tty.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. private:
  23. Stream *_port; // Android stream
  24. public:
  25. TTY(Stream &port);
  26. ~TTY();
  27. void reset();
  28. int rxdata(void *buf, size_t len);
  29. static int rxdata(token_t me, void *buf, size_t len);
  30. inline Stream & port() { return *_port; }
  31. inline operator Stream & () { return port(); }
  32. // Global events
  33. static void init();
  34. static void ping();
  35. private:
  36. void _onrx();
  37. void _onerr();
  38. void _onbreak();
  39. void _onconnect();
  40. void _ondisconnect();
  41. // Event handler dispatchers
  42. static void usb_onevent(void *arg, esp_event_base_t event_base,
  43. int32_t event_id, void *event_data);
  44. static void uart_onrx();
  45. static void uart_onerr(hardwareSerial_error_t);
  46. enum rx_state {
  47. normal, // Normal console mode
  48. stxwait, // Waiting for header STX
  49. hdr, // Getting header
  50. data // Getting data packet
  51. };
  52. void _upload_begin();
  53. void _update_window(bool rst = false);
  54. int _decode_data(int);
  55. // Packet receive state machine
  56. struct {
  57. enum rx_state state;
  58. uint8_t b64_buf;
  59. uint8_t b64_bits;
  60. union {
  61. struct tty_packet_hdr hdr;
  62. uint8_t hdr_raw[sizeof(struct tty_packet_hdr)];
  63. };
  64. size_t rlen;
  65. uint32_t last_ack;
  66. } rx;
  67. StreamBufferHandle_t rx_sbuf;
  68. uint32_t tx_credits;
  69. volatile bool tx_credits_reset;
  70. uint8_t rx_data[256];
  71. };