tty.h 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. };
  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. hdr, // Getting header
  49. data // Getting data packet
  50. };
  51. void _upload_begin();
  52. void _update_window(bool rst = false);
  53. // Packet receive state machine
  54. struct {
  55. enum rx_state state;
  56. union {
  57. struct tty_packet_hdr hdr;
  58. uint8_t hdr_raw[sizeof(struct tty_packet_hdr)];
  59. };
  60. size_t rlen;
  61. uint32_t last_ack;
  62. } rx;
  63. StreamBufferHandle_t rx_sbuf;
  64. uint32_t tx_credits_ok;
  65. uint32_t tx_credits_sent;
  66. uint8_t rx_data[256];
  67. };