Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

1209 lines
44KB

  1. /* USB EHCI Host for Teensy 3.6
  2. * Copyright 2017 Paul Stoffregen (paul@pjrc.com)
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the
  6. * "Software"), to deal in the Software without restriction, including
  7. * without limitation the rights to use, copy, modify, merge, publish,
  8. * distribute, sublicense, and/or sell copies of the Software, and to
  9. * permit persons to whom the Software is furnished to do so, subject to
  10. * the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included
  13. * in all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  18. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  19. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  20. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  21. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. #ifndef USB_HOST_TEENSY36_
  24. #define USB_HOST_TEENSY36_
  25. #include <stdint.h>
  26. #if !defined(__MK66FX1M0__)
  27. #error "USBHost_t36 only works with Teensy 3.6. Please select it in Tools > Boards"
  28. #endif
  29. // Dear inquisitive reader, USB is a complex protocol defined with
  30. // very specific terminology. To have any chance of understand this
  31. // source code, you absolutely must have solid knowledge of specific
  32. // USB terms such as host, device, endpoint, pipe, enumeration....
  33. // You really must also have at least a basic knowledge of the
  34. // different USB transfers: control, bulk, interrupt, isochronous.
  35. //
  36. // The USB 2.0 specification explains these in chapter 4 (pages 15
  37. // to 24), and provides more detail in the first part of chapter 5
  38. // (pages 25 to 55). The USB spec is published for free at
  39. // www.usb.org. Here is a convenient link to just the main PDF:
  40. //
  41. // https://www.pjrc.com/teensy/beta/usb20.pdf
  42. //
  43. // This is a huge file, but chapter 4 is short and easy to read.
  44. // If you're not familiar with the USB lingo, please do yourself
  45. // a favor by reading at least chapter 4 to get up to speed on the
  46. // meaning of these important USB concepts and terminology.
  47. //
  48. // If you wish to ask questions (which belong on the forum, not
  49. // github issues) or discuss development of this library, you
  50. // ABSOLUTELY MUST know the basic USB terminology from chapter 4.
  51. // Please repect other people's valuable time & effort by making
  52. // your best effort to read chapter 4 before asking USB questions!
  53. //#define USBHOST_PRINT_DEBUG
  54. /************************************************/
  55. /* Data Types */
  56. /************************************************/
  57. // These 6 types are the key to understanding how this USB Host
  58. // library really works.
  59. // USBHost is a static class controlling the hardware.
  60. // All common USB functionality is implemented here.
  61. class USBHost;
  62. // These 3 structures represent the actual USB entities
  63. // USBHost manipulates. One Device_t is created for
  64. // each active USB device. One Pipe_t is create for
  65. // each endpoint. Transfer_t structures are created
  66. // when any data transfer is added to the EHCI work
  67. // queues, and then returned to the free pool after the
  68. // data transfer completes and the driver has processed
  69. // the results.
  70. typedef struct Device_struct Device_t;
  71. typedef struct Pipe_struct Pipe_t;
  72. typedef struct Transfer_struct Transfer_t;
  73. // All USB device drivers inherit use these classes.
  74. // Drivers build user-visible functionality on top
  75. // of these classes, which receive USB events from
  76. // USBHost.
  77. class USBDriver;
  78. class USBDriverTimer;
  79. /************************************************/
  80. /* Added Defines */
  81. /************************************************/
  82. // Keyboard special Keys
  83. #define KEYD_UP 0xDA
  84. #define KEYD_DOWN 0xD9
  85. #define KEYD_LEFT 0xD8
  86. #define KEYD_RIGHT 0xD7
  87. #define KEYD_INSERT 0xD1
  88. #define KEYD_DELETE 0xD4
  89. #define KEYD_PAGE_UP 0xD3
  90. #define KEYD_PAGE_DOWN 0xD6
  91. #define KEYD_HOME 0xD2
  92. #define KEYD_END 0xD5
  93. #define KEYD_F1 0xC2
  94. #define KEYD_F2 0xC3
  95. #define KEYD_F3 0xC4
  96. #define KEYD_F4 0xC5
  97. #define KEYD_F5 0xC6
  98. #define KEYD_F6 0xC7
  99. #define KEYD_F7 0xC8
  100. #define KEYD_F8 0xC9
  101. #define KEYD_F9 0xCA
  102. #define KEYD_F10 0xCB
  103. #define KEYD_F11 0xCC
  104. #define KEYD_F12 0xCD
  105. // USBSerial formats - Lets encode format into bits
  106. // Bits: 0-4 - Number of data bits
  107. // Bits: 5-7 - Parity (0=none, 1=odd, 2 = even)
  108. // bits: 8-9 - Stop bits. 0=1, 1=2
  109. #define USBHOST_SERIAL_7E1 0x047
  110. #define USBHOST_SERIAL_7O1 0x027
  111. #define USBHOST_SERIAL_8N1 0x08
  112. #define USBHOST_SERIAL_8N2 0x108
  113. #define USBHOST_SERIAL_8E1 0x048
  114. #define USBHOST_SERIAL_8O1 0x028
  115. /************************************************/
  116. /* Data Structure Definitions */
  117. /************************************************/
  118. // setup_t holds the 8 byte USB SETUP packet data.
  119. // These unions & structs allow convenient access to
  120. // the setup fields.
  121. typedef union {
  122. struct {
  123. union {
  124. struct {
  125. uint8_t bmRequestType;
  126. uint8_t bRequest;
  127. };
  128. uint16_t wRequestAndType;
  129. };
  130. uint16_t wValue;
  131. uint16_t wIndex;
  132. uint16_t wLength;
  133. };
  134. struct {
  135. uint32_t word1;
  136. uint32_t word2;
  137. };
  138. } setup_t;
  139. typedef struct {
  140. enum {STRING_BUF_SIZE=50};
  141. enum {STR_ID_MAN=0, STR_ID_PROD, STR_ID_SERIAL, STR_ID_CNT};
  142. uint8_t iStrings[STR_ID_CNT]; // Index into array for the three indexes
  143. uint8_t buffer[STRING_BUF_SIZE];
  144. } strbuf_t;
  145. #define DEVICE_STRUCT_STRING_BUF_SIZE 50
  146. // Device_t holds all the information about a USB device
  147. struct Device_struct {
  148. Pipe_t *control_pipe;
  149. Pipe_t *data_pipes;
  150. Device_t *next;
  151. USBDriver *drivers;
  152. strbuf_t *strbuf;
  153. uint8_t speed; // 0=12, 1=1.5, 2=480 Mbit/sec
  154. uint8_t address;
  155. uint8_t hub_address;
  156. uint8_t hub_port;
  157. uint8_t enum_state;
  158. uint8_t bDeviceClass;
  159. uint8_t bDeviceSubClass;
  160. uint8_t bDeviceProtocol;
  161. uint8_t bmAttributes;
  162. uint8_t bMaxPower;
  163. uint16_t idVendor;
  164. uint16_t idProduct;
  165. uint16_t LanguageID;
  166. };
  167. // Pipe_t holes all information about each USB endpoint/pipe
  168. // The first half is an EHCI QH structure for the pipe.
  169. struct Pipe_struct {
  170. // Queue Head (QH), EHCI page 46-50
  171. struct { // must be aligned to 32 byte boundary
  172. volatile uint32_t horizontal_link;
  173. volatile uint32_t capabilities[2];
  174. volatile uint32_t current;
  175. volatile uint32_t next;
  176. volatile uint32_t alt_next;
  177. volatile uint32_t token;
  178. volatile uint32_t buffer[5];
  179. } qh;
  180. Device_t *device;
  181. uint8_t type; // 0=control, 1=isochronous, 2=bulk, 3=interrupt
  182. uint8_t direction; // 0=out, 1=in (changes for control, others fixed)
  183. uint8_t start_mask;
  184. uint8_t complete_mask;
  185. Pipe_t *next;
  186. void (*callback_function)(const Transfer_t *);
  187. uint16_t periodic_interval;
  188. uint16_t periodic_offset;
  189. uint32_t unused1;
  190. uint32_t unused2;
  191. uint32_t unused3;
  192. uint32_t unused4;
  193. uint32_t unused5;
  194. uint32_t unused6;
  195. uint32_t unused7;
  196. };
  197. // Transfer_t represents a single transaction on the USB bus.
  198. // The first portion is an EHCI qTD structure. Transfer_t are
  199. // allocated as-needed from a memory pool, loaded with pointers
  200. // to the actual data buffers, linked into a followup list,
  201. // and placed on ECHI Queue Heads. When the ECHI interrupt
  202. // occurs, the followup lists are used to find the Transfer_t
  203. // in memory. Callbacks are made, and then the Transfer_t are
  204. // returned to the memory pool.
  205. struct Transfer_struct {
  206. // Queue Element Transfer Descriptor (qTD), EHCI pg 40-45
  207. struct { // must be aligned to 32 byte boundary
  208. volatile uint32_t next;
  209. volatile uint32_t alt_next;
  210. volatile uint32_t token;
  211. volatile uint32_t buffer[5];
  212. } qtd;
  213. // Linked list of queued, not-yet-completed transfers
  214. Transfer_t *next_followup;
  215. Transfer_t *prev_followup;
  216. Pipe_t *pipe;
  217. // Data to be used by callback function. When a group
  218. // of Transfer_t are created, these fields and the
  219. // interrupt-on-complete bit in the qTD token are only
  220. // set in the last Transfer_t of the list.
  221. void *buffer;
  222. uint32_t length;
  223. setup_t setup;
  224. USBDriver *driver;
  225. };
  226. /************************************************/
  227. /* Main USB EHCI Controller */
  228. /************************************************/
  229. class USBHost {
  230. public:
  231. static void begin();
  232. static void Task();
  233. protected:
  234. static Pipe_t * new_Pipe(Device_t *dev, uint32_t type, uint32_t endpoint,
  235. uint32_t direction, uint32_t maxlen, uint32_t interval=0);
  236. static bool queue_Control_Transfer(Device_t *dev, setup_t *setup,
  237. void *buf, USBDriver *driver);
  238. static bool queue_Data_Transfer(Pipe_t *pipe, void *buffer,
  239. uint32_t len, USBDriver *driver);
  240. static Device_t * new_Device(uint32_t speed, uint32_t hub_addr, uint32_t hub_port);
  241. static void disconnect_Device(Device_t *dev);
  242. static void enumeration(const Transfer_t *transfer);
  243. static void driver_ready_for_device(USBDriver *driver);
  244. static void contribute_Devices(Device_t *devices, uint32_t num);
  245. static void contribute_Pipes(Pipe_t *pipes, uint32_t num);
  246. static void contribute_Transfers(Transfer_t *transfers, uint32_t num);
  247. static void contribute_String_Buffers(strbuf_t *strbuf, uint32_t num);
  248. static volatile bool enumeration_busy;
  249. private:
  250. static void isr();
  251. static void convertStringDescriptorToASCIIString(uint8_t string_index, Device_t *dev, const Transfer_t *transfer);
  252. static void claim_drivers(Device_t *dev);
  253. static uint32_t assign_address(void);
  254. static bool queue_Transfer(Pipe_t *pipe, Transfer_t *transfer);
  255. static void init_Device_Pipe_Transfer_memory(void);
  256. static Device_t * allocate_Device(void);
  257. static void delete_Pipe(Pipe_t *pipe);
  258. static void free_Device(Device_t *q);
  259. static Pipe_t * allocate_Pipe(void);
  260. static void free_Pipe(Pipe_t *q);
  261. static Transfer_t * allocate_Transfer(void);
  262. static void free_Transfer(Transfer_t *q);
  263. static strbuf_t * allocate_string_buffer(void);
  264. static void free_string_buffer(strbuf_t *strbuf);
  265. static bool allocate_interrupt_pipe_bandwidth(Pipe_t *pipe,
  266. uint32_t maxlen, uint32_t interval);
  267. static void add_qh_to_periodic_schedule(Pipe_t *pipe);
  268. static bool followup_Transfer(Transfer_t *transfer);
  269. static void followup_Error(void);
  270. protected:
  271. #ifdef USBHOST_PRINT_DEBUG
  272. static void print_(const Transfer_t *transfer);
  273. static void print_(const Transfer_t *first, const Transfer_t *last);
  274. static void print_token(uint32_t token);
  275. static void print_(const Pipe_t *pipe);
  276. static void print_driverlist(const char *name, const USBDriver *driver);
  277. static void print_qh_list(const Pipe_t *list);
  278. static void print_hexbytes(const void *ptr, uint32_t len);
  279. static void print_(const char *s) { Serial.print(s); }
  280. static void print_(int n) { Serial.print(n); }
  281. static void print_(unsigned int n) { Serial.print(n); }
  282. static void print_(long n) { Serial.print(n); }
  283. static void print_(unsigned long n) { Serial.print(n); }
  284. static void println_(const char *s) { Serial.println(s); }
  285. static void println_(int n) { Serial.println(n); }
  286. static void println_(unsigned int n) { Serial.println(n); }
  287. static void println_(long n) { Serial.println(n); }
  288. static void println_(unsigned long n) { Serial.println(n); }
  289. static void println_() { Serial.println(); }
  290. static void print_(uint32_t n, uint8_t b) { Serial.print(n, b); }
  291. static void println_(uint32_t n, uint8_t b) { Serial.println(n, b); }
  292. static void print_(const char *s, int n, uint8_t b = DEC) {
  293. Serial.print(s); Serial.print(n, b); }
  294. static void print_(const char *s, unsigned int n, uint8_t b = DEC) {
  295. Serial.print(s); Serial.print(n, b); }
  296. static void print_(const char *s, long n, uint8_t b = DEC) {
  297. Serial.print(s); Serial.print(n, b); }
  298. static void print_(const char *s, unsigned long n, uint8_t b = DEC) {
  299. Serial.print(s); Serial.print(n, b); }
  300. static void println_(const char *s, int n, uint8_t b = DEC) {
  301. Serial.print(s); Serial.println(n, b); }
  302. static void println_(const char *s, unsigned int n, uint8_t b = DEC) {
  303. Serial.print(s); Serial.println(n, b); }
  304. static void println_(const char *s, long n, uint8_t b = DEC) {
  305. Serial.print(s); Serial.println(n, b); }
  306. static void println_(const char *s, unsigned long n, uint8_t b = DEC) {
  307. Serial.print(s); Serial.println(n, b); }
  308. friend class USBDriverTimer; // for access to print & println
  309. #else
  310. static void print_(const Transfer_t *transfer) {}
  311. static void print_(const Transfer_t *first, const Transfer_t *last) {}
  312. static void print_token(uint32_t token) {}
  313. static void print_(const Pipe_t *pipe) {}
  314. static void print_driverlist(const char *name, const USBDriver *driver) {}
  315. static void print_qh_list(const Pipe_t *list) {}
  316. static void print_hexbytes(const void *ptr, uint32_t len) {}
  317. static void print_(const char *s) {}
  318. static void print_(int n) {}
  319. static void print_(unsigned int n) {}
  320. static void print_(long n) {}
  321. static void print_(unsigned long n) {}
  322. static void println_(const char *s) {}
  323. static void println_(int n) {}
  324. static void println_(unsigned int n) {}
  325. static void println_(long n) {}
  326. static void println_(unsigned long n) {}
  327. static void println_() {}
  328. static void print_(uint32_t n, uint8_t b) {}
  329. static void println_(uint32_t n, uint8_t b) {}
  330. static void print_(const char *s, int n, uint8_t b = DEC) {}
  331. static void print_(const char *s, unsigned int n, uint8_t b = DEC) {}
  332. static void print_(const char *s, long n, uint8_t b = DEC) {}
  333. static void print_(const char *s, unsigned long n, uint8_t b = DEC) {}
  334. static void println_(const char *s, int n, uint8_t b = DEC) {}
  335. static void println_(const char *s, unsigned int n, uint8_t b = DEC) {}
  336. static void println_(const char *s, long n, uint8_t b = DEC) {}
  337. static void println_(const char *s, unsigned long n, uint8_t b = DEC) {}
  338. #endif
  339. static void mk_setup(setup_t &s, uint32_t bmRequestType, uint32_t bRequest,
  340. uint32_t wValue, uint32_t wIndex, uint32_t wLength) {
  341. s.word1 = bmRequestType | (bRequest << 8) | (wValue << 16);
  342. s.word2 = wIndex | (wLength << 16);
  343. }
  344. };
  345. /************************************************/
  346. /* USB Device Driver Common Base Class */
  347. /************************************************/
  348. // All USB device drivers inherit from this base class.
  349. class USBDriver : public USBHost {
  350. public:
  351. operator bool() { return (device != nullptr); }
  352. uint16_t idVendor() { return (device != nullptr) ? device->idVendor : 0; }
  353. uint16_t idProduct() { return (device != nullptr) ? device->idProduct : 0; }
  354. const uint8_t *manufacturer()
  355. { return ((device == nullptr) || (device->strbuf == nullptr)) ? nullptr : &device->strbuf->buffer[device->strbuf->iStrings[strbuf_t::STR_ID_MAN]]; }
  356. const uint8_t *product()
  357. { return ((device == nullptr) || (device->strbuf == nullptr)) ? nullptr : &device->strbuf->buffer[device->strbuf->iStrings[strbuf_t::STR_ID_PROD]]; }
  358. const uint8_t *serialNumber()
  359. { return ((device == nullptr) || (device->strbuf == nullptr)) ? nullptr : &device->strbuf->buffer[device->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]]; }
  360. // TODO: user-level functions
  361. // check if device is bound/active/online
  362. // query vid, pid
  363. // query string: manufacturer, product, serial number
  364. protected:
  365. USBDriver() : next(NULL), device(NULL) {}
  366. // Check if a driver wishes to claim a device or interface or group
  367. // of interfaces within a device. When this function returns true,
  368. // the driver is considered bound or loaded for that device. When
  369. // new devices are detected, enumeration.cpp calls this function on
  370. // all unbound driver objects, to give them an opportunity to bind
  371. // to the new device.
  372. // device has its vid&pid, class/subclass fields initialized
  373. // type is 0 for device level, 1 for interface level, 2 for IAD
  374. // descriptors points to the specific descriptor data
  375. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  376. // When an unknown (not chapter 9) control transfer completes, this
  377. // function is called for all drivers bound to the device. Return
  378. // true means this driver originated this control transfer, so no
  379. // more drivers need to be offered an opportunity to process it.
  380. // This function is optional, only needed if the driver uses control
  381. // transfers and wishes to be notified when they complete.
  382. virtual void control(const Transfer_t *transfer) { }
  383. // When any of the USBDriverTimer objects a driver creates generates
  384. // a timer event, this function is called.
  385. virtual void timer_event(USBDriverTimer *whichTimer) { }
  386. // When the user calls USBHost::Task, this Task function for all
  387. // active drivers is called, so they may update state and/or call
  388. // any attached user callback functions.
  389. virtual void Task() { }
  390. // When a device disconnects from the USB, this function is called.
  391. // The driver must free all resources it allocated and update any
  392. // internal state necessary to deal with the possibility of user
  393. // code continuing to call its API. However, pipes and transfers
  394. // are the handled by lower layers, so device drivers do not free
  395. // pipes they created or cancel transfers they had in progress.
  396. virtual void disconnect();
  397. // Drivers are managed by this single-linked list. All inactive
  398. // (not bound to any device) drivers are linked from
  399. // available_drivers in enumeration.cpp. When bound to a device,
  400. // drivers are linked from that Device_t drivers list.
  401. USBDriver *next;
  402. // The device this object instance is bound to. In words, this
  403. // is the specific device this driver is using. When not bound
  404. // to any device, this must be NULL. Drivers may set this to
  405. // any non-NULL value if they are in a state where they do not
  406. // wish to claim any device or interface (eg, if getting data
  407. // from the HID parser).
  408. Device_t *device;
  409. friend class USBHost;
  410. };
  411. // Device drivers may create these timer objects to schedule a timer call
  412. class USBDriverTimer {
  413. public:
  414. USBDriverTimer() { }
  415. USBDriverTimer(USBDriver *d) : driver(d) { }
  416. void init(USBDriver *d) { driver = d; };
  417. void start(uint32_t microseconds);
  418. void stop();
  419. void *pointer;
  420. uint32_t integer;
  421. uint32_t started_micros; // testing only
  422. private:
  423. USBDriver *driver;
  424. uint32_t usec;
  425. USBDriverTimer *next;
  426. USBDriverTimer *prev;
  427. friend class USBHost;
  428. };
  429. // Device drivers may inherit from this base class, if they wish to receive
  430. // HID input data fully decoded by the USBHIDParser driver
  431. class USBHIDInput {
  432. public:
  433. operator bool() { return (mydevice != nullptr); }
  434. uint16_t idVendor() { return (mydevice != nullptr) ? mydevice->idVendor : 0; }
  435. uint16_t idProduct() { return (mydevice != nullptr) ? mydevice->idProduct : 0; }
  436. const uint8_t *manufacturer()
  437. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_MAN]]; }
  438. const uint8_t *product()
  439. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_PROD]]; }
  440. const uint8_t *serialNumber()
  441. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]]; }
  442. private:
  443. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  444. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  445. virtual void hid_input_data(uint32_t usage, int32_t value);
  446. virtual void hid_input_end();
  447. virtual void disconnect_collection(Device_t *dev);
  448. void add_to_list();
  449. USBHIDInput *next;
  450. friend class USBHIDParser;
  451. protected:
  452. Device_t *mydevice = NULL;
  453. };
  454. /************************************************/
  455. /* USB Device Drivers */
  456. /************************************************/
  457. class USBHub : public USBDriver {
  458. public:
  459. USBHub(USBHost &host) : debouncetimer(this), resettimer(this) { init(); }
  460. USBHub(USBHost *host) : debouncetimer(this), resettimer(this) { init(); }
  461. // Hubs with more more than 7 ports are built from two tiers of hubs
  462. // using 4 or 7 port hub chips. While the USB spec seems to allow
  463. // hubs to have up to 255 ports, in practice all hub chips on the
  464. // market are only 2, 3, 4 or 7 ports.
  465. enum { MAXPORTS = 7 };
  466. typedef uint8_t portbitmask_t;
  467. enum {
  468. PORT_OFF = 0,
  469. PORT_DISCONNECT = 1,
  470. PORT_DEBOUNCE1 = 2,
  471. PORT_DEBOUNCE2 = 3,
  472. PORT_DEBOUNCE3 = 4,
  473. PORT_DEBOUNCE4 = 5,
  474. PORT_DEBOUNCE5 = 6,
  475. PORT_RESET = 7,
  476. PORT_RECOVERY = 8,
  477. PORT_ACTIVE = 9
  478. };
  479. protected:
  480. virtual bool claim(Device_t *dev, int type, const uint8_t *descriptors, uint32_t len);
  481. virtual void control(const Transfer_t *transfer);
  482. virtual void timer_event(USBDriverTimer *whichTimer);
  483. virtual void disconnect();
  484. void init();
  485. bool can_send_control_now();
  486. void send_poweron(uint32_t port);
  487. void send_getstatus(uint32_t port);
  488. void send_clearstatus_connect(uint32_t port);
  489. void send_clearstatus_enable(uint32_t port);
  490. void send_clearstatus_suspend(uint32_t port);
  491. void send_clearstatus_overcurrent(uint32_t port);
  492. void send_clearstatus_reset(uint32_t port);
  493. void send_setreset(uint32_t port);
  494. static void callback(const Transfer_t *transfer);
  495. void status_change(const Transfer_t *transfer);
  496. void new_port_status(uint32_t port, uint32_t status);
  497. void start_debounce_timer(uint32_t port);
  498. void stop_debounce_timer(uint32_t port);
  499. private:
  500. Device_t mydevices[MAXPORTS];
  501. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  502. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  503. strbuf_t mystring_bufs[1];
  504. USBDriverTimer debouncetimer;
  505. USBDriverTimer resettimer;
  506. setup_t setup;
  507. Pipe_t *changepipe;
  508. Device_t *devicelist[MAXPORTS];
  509. uint32_t changebits;
  510. uint32_t statusbits;
  511. uint8_t hub_desc[16];
  512. uint8_t endpoint;
  513. uint8_t interval;
  514. uint8_t numports;
  515. uint8_t characteristics;
  516. uint8_t powertime;
  517. uint8_t sending_control_transfer;
  518. uint8_t port_doing_reset;
  519. uint8_t port_doing_reset_speed;
  520. uint8_t portstate[MAXPORTS];
  521. portbitmask_t send_pending_poweron;
  522. portbitmask_t send_pending_getstatus;
  523. portbitmask_t send_pending_clearstatus_connect;
  524. portbitmask_t send_pending_clearstatus_enable;
  525. portbitmask_t send_pending_clearstatus_suspend;
  526. portbitmask_t send_pending_clearstatus_overcurrent;
  527. portbitmask_t send_pending_clearstatus_reset;
  528. portbitmask_t send_pending_setreset;
  529. portbitmask_t debounce_in_use;
  530. static volatile bool reset_busy;
  531. };
  532. //--------------------------------------------------------------------------
  533. class USBHIDParser : public USBDriver {
  534. public:
  535. USBHIDParser(USBHost &host) { init(); }
  536. static void driver_ready_for_hid_collection(USBHIDInput *driver);
  537. protected:
  538. enum { TOPUSAGE_LIST_LEN = 4 };
  539. enum { USAGE_LIST_LEN = 24 };
  540. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  541. virtual void control(const Transfer_t *transfer);
  542. virtual void disconnect();
  543. static void in_callback(const Transfer_t *transfer);
  544. static void out_callback(const Transfer_t *transfer);
  545. void in_data(const Transfer_t *transfer);
  546. void out_data(const Transfer_t *transfer);
  547. bool check_if_using_report_id();
  548. void parse();
  549. USBHIDInput * find_driver(uint32_t topusage);
  550. void parse(uint16_t type_and_report_id, const uint8_t *data, uint32_t len);
  551. void init();
  552. private:
  553. Pipe_t *in_pipe;
  554. Pipe_t *out_pipe;
  555. static USBHIDInput *available_hid_drivers_list;
  556. //uint32_t topusage_list[TOPUSAGE_LIST_LEN];
  557. USBHIDInput *topusage_drivers[TOPUSAGE_LIST_LEN];
  558. uint16_t in_size;
  559. uint16_t out_size;
  560. setup_t setup;
  561. uint8_t descriptor[512];
  562. uint8_t report[64];
  563. uint16_t descsize;
  564. bool use_report_id;
  565. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  566. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  567. strbuf_t mystring_bufs[1];
  568. };
  569. //--------------------------------------------------------------------------
  570. class KeyboardController : public USBDriver /* , public USBHIDInput */ {
  571. public:
  572. typedef union {
  573. struct {
  574. uint8_t numLock : 1;
  575. uint8_t capsLock : 1;
  576. uint8_t scrollLock : 1;
  577. uint8_t compose : 1;
  578. uint8_t kana : 1;
  579. uint8_t reserved : 3;
  580. };
  581. uint8_t byte;
  582. } KBDLeds_t;
  583. public:
  584. KeyboardController(USBHost &host) { init(); }
  585. KeyboardController(USBHost *host) { init(); }
  586. int available();
  587. int read();
  588. uint16_t getKey() { return keyCode; }
  589. uint8_t getModifiers() { return modifiers; }
  590. uint8_t getOemKey() { return keyOEM; }
  591. void attachPress(void (*f)(int unicode)) { keyPressedFunction = f; }
  592. void attachRelease(void (*f)(int unicode)) { keyReleasedFunction = f; }
  593. void LEDS(uint8_t leds);
  594. uint8_t LEDS() {return leds_.byte;}
  595. void updateLEDS(void);
  596. bool numLock() {return leds_.numLock;}
  597. bool capsLock() {return leds_.capsLock;}
  598. bool scrollLock() {return leds_.scrollLock;}
  599. void numLock(bool f);
  600. void capsLock(bool f);
  601. void scrollLock(bool f);
  602. protected:
  603. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  604. virtual void control(const Transfer_t *transfer);
  605. virtual void disconnect();
  606. static void callback(const Transfer_t *transfer);
  607. void new_data(const Transfer_t *transfer);
  608. void init();
  609. private:
  610. void update();
  611. uint16_t convert_to_unicode(uint32_t mod, uint32_t key);
  612. void key_press(uint32_t mod, uint32_t key);
  613. void key_release(uint32_t mod, uint32_t key);
  614. void (*keyPressedFunction)(int unicode);
  615. void (*keyReleasedFunction)(int unicode);
  616. Pipe_t *datapipe;
  617. setup_t setup;
  618. uint8_t report[8];
  619. uint16_t keyCode;
  620. uint8_t modifiers;
  621. uint8_t keyOEM;
  622. uint8_t prev_report[8];
  623. KBDLeds_t leds_ = {0};
  624. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  625. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  626. strbuf_t mystring_bufs[1];
  627. };
  628. //--------------------------------------------------------------------------
  629. class KeyboardHIDExtrasController : public USBHIDInput {
  630. public:
  631. KeyboardHIDExtrasController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  632. void clear() { event_ = false;}
  633. bool available() { return event_; }
  634. void attachPress(void (*f)(uint32_t top, uint16_t code)) { keyPressedFunction = f; }
  635. void attachRelease(void (*f)(uint32_t top, uint16_t code)) { keyReleasedFunction = f; }
  636. enum {MAX_KEYS_DOWN=4};
  637. // uint32_t buttons() { return buttons_; }
  638. protected:
  639. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  640. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  641. virtual void hid_input_data(uint32_t usage, int32_t value);
  642. virtual void hid_input_end();
  643. virtual void disconnect_collection(Device_t *dev);
  644. private:
  645. void (*keyPressedFunction)(uint32_t top, uint16_t code);
  646. void (*keyReleasedFunction)(uint32_t top, uint16_t code);
  647. uint32_t topusage_ = 0; // What top report am I processing?
  648. uint8_t collections_claimed_ = 0;
  649. volatile bool event_ = false;
  650. volatile bool hid_input_begin_ = false;
  651. volatile bool hid_input_data_ = false; // did we receive any valid data with report?
  652. uint8_t count_keys_down_ = 0;
  653. uint16_t keys_down[MAX_KEYS_DOWN];
  654. };
  655. //--------------------------------------------------------------------------
  656. class MouseController : public USBHIDInput {
  657. public:
  658. MouseController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  659. bool available() { return mouseEvent; }
  660. void mouseDataClear();
  661. uint8_t getButtons() { return buttons; }
  662. int getMouseX() { return mouseX; }
  663. int getMouseY() { return mouseY; }
  664. int getWheel() { return wheel; }
  665. int getWheelH() { return wheelH; }
  666. protected:
  667. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  668. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  669. virtual void hid_input_data(uint32_t usage, int32_t value);
  670. virtual void hid_input_end();
  671. virtual void disconnect_collection(Device_t *dev);
  672. private:
  673. uint8_t collections_claimed = 0;
  674. volatile bool mouseEvent = false;
  675. volatile bool hid_input_begin_ = false;
  676. uint8_t buttons = 0;
  677. int mouseX = 0;
  678. int mouseY = 0;
  679. int wheel = 0;
  680. int wheelH = 0;
  681. };
  682. //--------------------------------------------------------------------------
  683. class JoystickController : public USBHIDInput {
  684. public:
  685. JoystickController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  686. bool available() { return joystickEvent; }
  687. void joystickDataClear();
  688. uint32_t getButtons() { return buttons; }
  689. int getAxis(uint32_t index) { return (index < (sizeof(axis)/sizeof(axis[0]))) ? axis[index] : 0; }
  690. protected:
  691. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  692. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  693. virtual void hid_input_data(uint32_t usage, int32_t value);
  694. virtual void hid_input_end();
  695. virtual void disconnect_collection(Device_t *dev);
  696. private:
  697. uint8_t collections_claimed = 0;
  698. bool anychange = false;
  699. volatile bool joystickEvent = false;
  700. uint32_t buttons = 0;
  701. int16_t axis[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  702. };
  703. //--------------------------------------------------------------------------
  704. class MIDIDevice : public USBDriver {
  705. public:
  706. enum { SYSEX_MAX_LEN = 60 };
  707. MIDIDevice(USBHost &host) { init(); }
  708. MIDIDevice(USBHost *host) { init(); }
  709. bool read(uint8_t channel=0, uint8_t cable=0);
  710. uint8_t getType(void) {
  711. return msg_type;
  712. };
  713. uint8_t getChannel(void) {
  714. return msg_channel;
  715. };
  716. uint8_t getData1(void) {
  717. return msg_data1;
  718. };
  719. uint8_t getData2(void) {
  720. return msg_data2;
  721. };
  722. void setHandleNoteOff(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  723. handleNoteOff = f;
  724. };
  725. void setHandleNoteOn(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  726. handleNoteOn = f;
  727. };
  728. void setHandleVelocityChange(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  729. handleVelocityChange = f;
  730. };
  731. void setHandleControlChange(void (*f)(uint8_t channel, uint8_t control, uint8_t value)) {
  732. handleControlChange = f;
  733. };
  734. void setHandleProgramChange(void (*f)(uint8_t channel, uint8_t program)) {
  735. handleProgramChange = f;
  736. };
  737. void setHandleAfterTouch(void (*f)(uint8_t channel, uint8_t pressure)) {
  738. handleAfterTouch = f;
  739. };
  740. void setHandlePitchChange(void (*f)(uint8_t channel, int pitch)) {
  741. handlePitchChange = f;
  742. };
  743. void setHandleSysEx(void (*f)(const uint8_t *data, uint16_t length, bool complete)) {
  744. handleSysEx = (void (*)(const uint8_t *, uint16_t, uint8_t))f;
  745. }
  746. void setHandleRealTimeSystem(void (*f)(uint8_t realtimebyte)) {
  747. handleRealTimeSystem = f;
  748. };
  749. void setHandleTimeCodeQuarterFrame(void (*f)(uint16_t data)) {
  750. handleTimeCodeQuarterFrame = f;
  751. };
  752. void sendNoteOff(uint32_t note, uint32_t velocity, uint32_t channel) {
  753. write_packed(0x8008 | (((channel - 1) & 0x0F) << 8)
  754. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  755. }
  756. void sendNoteOn(uint32_t note, uint32_t velocity, uint32_t channel) {
  757. write_packed(0x9009 | (((channel - 1) & 0x0F) << 8)
  758. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  759. }
  760. void sendPolyPressure(uint32_t note, uint32_t pressure, uint32_t channel) {
  761. write_packed(0xA00A | (((channel - 1) & 0x0F) << 8)
  762. | ((note & 0x7F) << 16) | ((pressure & 0x7F) << 24));
  763. }
  764. void sendControlChange(uint32_t control, uint32_t value, uint32_t channel) {
  765. write_packed(0xB00B | (((channel - 1) & 0x0F) << 8)
  766. | ((control & 0x7F) << 16) | ((value & 0x7F) << 24));
  767. }
  768. void sendProgramChange(uint32_t program, uint32_t channel) {
  769. write_packed(0xC00C | (((channel - 1) & 0x0F) << 8)
  770. | ((program & 0x7F) << 16));
  771. }
  772. void sendAfterTouch(uint32_t pressure, uint32_t channel) {
  773. write_packed(0xD00D | (((channel - 1) & 0x0F) << 8)
  774. | ((pressure & 0x7F) << 16));
  775. }
  776. void sendPitchBend(uint32_t value, uint32_t channel) {
  777. write_packed(0xE00E | (((channel - 1) & 0x0F) << 8)
  778. | ((value & 0x7F) << 16) | ((value & 0x3F80) << 17));
  779. }
  780. void sendSysEx(uint32_t length, const void *data);
  781. void sendRealTime(uint32_t type) {
  782. switch (type) {
  783. case 0xF8: // Clock
  784. case 0xFA: // Start
  785. case 0xFC: // Stop
  786. case 0xFB: // Continue
  787. case 0xFE: // ActiveSensing
  788. case 0xFF: // SystemReset
  789. write_packed((type << 8) | 0x0F);
  790. break;
  791. default: // Invalid Real Time marker
  792. break;
  793. }
  794. }
  795. void sendTimeCodeQuarterFrame(uint32_t type, uint32_t value) {
  796. uint32_t data = ( ((type & 0x07) << 4) | (value & 0x0F) );
  797. sendTimeCodeQuarterFrame(data);
  798. }
  799. void sendTimeCodeQuarterFrame(uint32_t data) {
  800. write_packed(0xF108 | ((data & 0x7F) << 16));
  801. }
  802. protected:
  803. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  804. virtual void disconnect();
  805. static void rx_callback(const Transfer_t *transfer);
  806. static void tx_callback(const Transfer_t *transfer);
  807. void rx_data(const Transfer_t *transfer);
  808. void tx_data(const Transfer_t *transfer);
  809. void init();
  810. void write_packed(uint32_t data);
  811. void sysex_byte(uint8_t b);
  812. private:
  813. Pipe_t *rxpipe;
  814. Pipe_t *txpipe;
  815. enum { MAX_PACKET_SIZE = 64 };
  816. enum { RX_QUEUE_SIZE = 80 }; // must be more than MAX_PACKET_SIZE/4
  817. uint32_t rx_buffer[MAX_PACKET_SIZE/4];
  818. uint32_t tx_buffer[MAX_PACKET_SIZE/4];
  819. uint16_t rx_size;
  820. uint16_t tx_size;
  821. uint32_t rx_queue[RX_QUEUE_SIZE];
  822. bool rx_packet_queued;
  823. uint16_t rx_head;
  824. uint16_t rx_tail;
  825. uint8_t rx_ep;
  826. uint8_t tx_ep;
  827. uint8_t msg_channel;
  828. uint8_t msg_type;
  829. uint8_t msg_data1;
  830. uint8_t msg_data2;
  831. uint8_t msg_sysex[SYSEX_MAX_LEN];
  832. uint8_t msg_sysex_len;
  833. void (*handleNoteOff)(uint8_t ch, uint8_t note, uint8_t vel);
  834. void (*handleNoteOn)(uint8_t ch, uint8_t note, uint8_t vel);
  835. void (*handleVelocityChange)(uint8_t ch, uint8_t note, uint8_t vel);
  836. void (*handleControlChange)(uint8_t ch, uint8_t control, uint8_t value);
  837. void (*handleProgramChange)(uint8_t ch, uint8_t program);
  838. void (*handleAfterTouch)(uint8_t ch, uint8_t pressure);
  839. void (*handlePitchChange)(uint8_t ch, int pitch);
  840. void (*handleSysEx)(const uint8_t *data, uint16_t length, uint8_t complete);
  841. void (*handleRealTimeSystem)(uint8_t rtb);
  842. void (*handleTimeCodeQuarterFrame)(uint16_t data);
  843. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  844. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  845. strbuf_t mystring_bufs[1];
  846. };
  847. //--------------------------------------------------------------------------
  848. class USBSerial: public USBDriver, public Stream {
  849. public:
  850. // FIXME: need different USBSerial, with bigger buffers for 480 Mbit & faster speed
  851. enum { BUFFER_SIZE = 648 }; // must hold at least 6 max size packets, plus 2 extra bytes
  852. enum { DEFAULT_WRITE_TIMEOUT = 3500};
  853. USBSerial(USBHost &host) : txtimer(this) { init(); }
  854. void begin(uint32_t baud, uint32_t format=USBHOST_SERIAL_8N1);
  855. void end(void);
  856. uint32_t writeTimeout() {return write_timeout_;}
  857. void writeTimeOut(uint32_t write_timeout) {write_timeout_ = write_timeout;} // Will not impact current ones.
  858. virtual int available(void);
  859. virtual int peek(void);
  860. virtual int read(void);
  861. virtual int availableForWrite();
  862. virtual size_t write(uint8_t c);
  863. virtual void flush(void);
  864. using Print::write;
  865. protected:
  866. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  867. virtual void control(const Transfer_t *transfer);
  868. virtual void disconnect();
  869. virtual void timer_event(USBDriverTimer *whichTimer);
  870. private:
  871. static void rx_callback(const Transfer_t *transfer);
  872. static void tx_callback(const Transfer_t *transfer);
  873. void rx_data(const Transfer_t *transfer);
  874. void tx_data(const Transfer_t *transfer);
  875. void rx_queue_packets(uint32_t head, uint32_t tail);
  876. void init();
  877. static bool check_rxtx_ep(uint32_t &rxep, uint32_t &txep);
  878. bool init_buffers(uint32_t rsize, uint32_t tsize);
  879. void ch341_setBaud(uint8_t byte_index);
  880. private:
  881. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  882. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  883. strbuf_t mystring_bufs[1];
  884. USBDriverTimer txtimer;
  885. uint32_t bigbuffer[(BUFFER_SIZE+3)/4];
  886. setup_t setup;
  887. uint8_t setupdata[16]; //
  888. uint32_t baudrate;
  889. uint32_t format_;
  890. uint32_t write_timeout_ = DEFAULT_WRITE_TIMEOUT;
  891. Pipe_t *rxpipe;
  892. Pipe_t *txpipe;
  893. uint8_t *rx1; // location for first incoming packet
  894. uint8_t *rx2; // location for second incoming packet
  895. uint8_t *rxbuf; // receive circular buffer
  896. uint8_t *tx1; // location for first outgoing packet
  897. uint8_t *tx2; // location for second outgoing packet
  898. uint8_t *txbuf;
  899. volatile uint16_t rxhead;// receive head
  900. volatile uint16_t rxtail;// receive tail
  901. volatile uint16_t txhead;
  902. volatile uint16_t txtail;
  903. uint16_t rxsize;// size of receive circular buffer
  904. uint16_t txsize;// size of transmit circular buffer
  905. volatile uint8_t rxstate;// bitmask: which receive packets are queued
  906. volatile uint8_t txstate;
  907. uint8_t pending_control;
  908. uint8_t setup_state; // PL2303 - has several steps... Could use pending control?
  909. uint8_t pl2303_v1; // Which version do we have
  910. uint8_t pl2303_v2;
  911. uint8_t interface;
  912. bool control_queued;
  913. typedef enum { UNKNOWN=0, CDCACM, FTDI, PL2303, CH341, CP210X } sertype_t;
  914. sertype_t sertype;
  915. typedef struct {
  916. uint16_t idVendor;
  917. uint16_t idProduct;
  918. sertype_t sertype;
  919. } product_vendor_mapping_t;
  920. static product_vendor_mapping_t pid_vid_mapping[];
  921. };
  922. //--------------------------------------------------------------------------
  923. class AntPlus: public USBDriver {
  924. // Please post any AntPlus feedback or contributions on this forum thread:
  925. // https://forum.pjrc.com/threads/43110-Ant-libarary-and-USB-driver-for-Teensy-3-5-6
  926. public:
  927. AntPlus(USBHost &host) : /* txtimer(this),*/ updatetimer(this) { init(); }
  928. void begin(const uint8_t key=0);
  929. void onStatusChange(void (*function)(int channel, int status)) {
  930. user_onStatusChange = function;
  931. }
  932. void onDeviceID(void (*function)(int channel, int devId, int devType, int transType)) {
  933. user_onDeviceID = function;
  934. }
  935. void onHeartRateMonitor(void (*f)(int bpm, int msec, int seqNum), uint32_t devid=0) {
  936. profileSetup_HRM(&ant.dcfg[PROFILE_HRM], devid);
  937. memset(&hrm, 0, sizeof(hrm));
  938. user_onHeartRateMonitor = f;
  939. }
  940. void onSpeedCadence(void (*f)(float speed, float distance, float rpm), uint32_t devid=0) {
  941. profileSetup_SPDCAD(&ant.dcfg[PROFILE_SPDCAD], devid);
  942. memset(&spdcad, 0, sizeof(spdcad));
  943. user_onSpeedCadence = f;
  944. }
  945. void onSpeed(void (*f)(float speed, float distance), uint32_t devid=0) {
  946. profileSetup_SPEED(&ant.dcfg[PROFILE_SPEED], devid);
  947. memset(&spd, 0, sizeof(spd));
  948. user_onSpeed = f;
  949. }
  950. void onCadence(void (*f)(float rpm), uint32_t devid=0) {
  951. profileSetup_CADENCE(&ant.dcfg[PROFILE_CADENCE], devid);
  952. memset(&cad, 0, sizeof(cad));
  953. user_onCadence = f;
  954. }
  955. void setWheelCircumference(float meters) {
  956. wheelCircumference = meters * 1000.0f;
  957. }
  958. protected:
  959. virtual void Task();
  960. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  961. virtual void disconnect();
  962. virtual void timer_event(USBDriverTimer *whichTimer);
  963. private:
  964. static void rx_callback(const Transfer_t *transfer);
  965. static void tx_callback(const Transfer_t *transfer);
  966. void rx_data(const Transfer_t *transfer);
  967. void tx_data(const Transfer_t *transfer);
  968. void init();
  969. size_t write(const void *data, const size_t size);
  970. int read(void *data, const size_t size);
  971. void transmit();
  972. private:
  973. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  974. Transfer_t mytransfers[3] __attribute__ ((aligned(32)));
  975. strbuf_t mystring_bufs[1];
  976. //USBDriverTimer txtimer;
  977. USBDriverTimer updatetimer;
  978. Pipe_t *rxpipe;
  979. Pipe_t *txpipe;
  980. bool first_update;
  981. uint8_t txbuffer[240];
  982. uint8_t rxpacket[64];
  983. volatile uint16_t txhead;
  984. volatile uint16_t txtail;
  985. volatile bool txready;
  986. volatile uint8_t rxlen;
  987. volatile bool do_polling;
  988. private:
  989. enum _eventi {
  990. EVENTI_MESSAGE = 0,
  991. EVENTI_CHANNEL,
  992. EVENTI_TOTAL
  993. };
  994. enum _profiles {
  995. PROFILE_HRM = 0,
  996. PROFILE_SPDCAD,
  997. PROFILE_POWER,
  998. PROFILE_STRIDE,
  999. PROFILE_SPEED,
  1000. PROFILE_CADENCE,
  1001. PROFILE_TOTAL
  1002. };
  1003. typedef struct {
  1004. uint8_t channel;
  1005. uint8_t RFFreq;
  1006. uint8_t networkNumber;
  1007. uint8_t stub;
  1008. uint8_t searchTimeout;
  1009. uint8_t channelType;
  1010. uint8_t deviceType;
  1011. uint8_t transType;
  1012. uint16_t channelPeriod;
  1013. uint16_t searchWaveform;
  1014. uint32_t deviceNumber; // deviceId
  1015. struct {
  1016. uint8_t chanIdOnce;
  1017. uint8_t keyAccepted;
  1018. uint8_t profileValid;
  1019. uint8_t channelStatus;
  1020. uint8_t channelStatusOld;
  1021. } flags;
  1022. } TDCONFIG;
  1023. struct {
  1024. uint8_t initOnce;
  1025. uint8_t key; // key index
  1026. int iDevice; // index to the antplus we're interested in, if > one found
  1027. TDCONFIG dcfg[PROFILE_TOTAL]; // channel config, we're using one channel per device
  1028. } ant;
  1029. void (*user_onStatusChange)(int channel, int status);
  1030. void (*user_onDeviceID)(int channel, int devId, int devType, int transType);
  1031. void (*user_onHeartRateMonitor)(int beatsPerMinute, int milliseconds, int sequenceNumber);
  1032. void (*user_onSpeedCadence)(float speed, float distance, float cadence);
  1033. void (*user_onSpeed)(float speed, float distance);
  1034. void (*user_onCadence)(float cadence);
  1035. void dispatchPayload(TDCONFIG *cfg, const uint8_t *payload, const int len);
  1036. static const uint8_t *getAntKey(const uint8_t keyIdx);
  1037. static uint8_t calcMsgChecksum (const uint8_t *buffer, const uint8_t len);
  1038. static uint8_t * findStreamSync(uint8_t *stream, const size_t rlen, int *pos);
  1039. static int msgCheckIntegrity(uint8_t *stream, const int len);
  1040. static int msgGetLength(uint8_t *stream);
  1041. int handleMessages(uint8_t *buffer, int tBytes);
  1042. void sendMessageChannelStatus(TDCONFIG *cfg, const uint32_t channelStatus);
  1043. void message_channel(const int chan, const int eventId,
  1044. const uint8_t *payload, const size_t dataLength);
  1045. void message_response(const int chan, const int msgId,
  1046. const uint8_t *payload, const size_t dataLength);
  1047. void message_event(const int channel, const int msgId,
  1048. const uint8_t *payload, const size_t dataLength);
  1049. int ResetSystem();
  1050. int RequestMessage(const int channel, const int message);
  1051. int SetNetworkKey(const int netNumber, const uint8_t *key);
  1052. int SetChannelSearchTimeout(const int channel, const int searchTimeout);
  1053. int SetChannelPeriod(const int channel, const int period);
  1054. int SetChannelRFFreq(const int channel, const int freq);
  1055. int SetSearchWaveform(const int channel, const int wave);
  1056. int OpenChannel(const int channel);
  1057. int CloseChannel(const int channel);
  1058. int AssignChannel(const int channel, const int channelType, const int network);
  1059. int SetChannelId(const int channel, const int deviceNum, const int deviceType,
  1060. const int transmissionType);
  1061. int SendBurstTransferPacket(const int channelSeq, const uint8_t *data);
  1062. int SendBurstTransfer(const int channel, const uint8_t *data, const int nunPackets);
  1063. int SendBroadcastData(const int channel, const uint8_t *data);
  1064. int SendAcknowledgedData(const int channel, const uint8_t *data);
  1065. int SendExtAcknowledgedData(const int channel, const int devNum, const int devType,
  1066. const int TranType, const uint8_t *data);
  1067. int SendExtBroadcastData(const int channel, const int devNum, const int devType,
  1068. const int TranType, const uint8_t *data);
  1069. int SendExtBurstTransferPacket(const int chanSeq, const int devNum,
  1070. const int devType, const int TranType, const uint8_t *data);
  1071. int SendExtBurstTransfer(const int channel, const int devNum, const int devType,
  1072. const int tranType, const uint8_t *data, const int nunPackets);
  1073. static void profileSetup_HRM(TDCONFIG *cfg, const uint32_t deviceId);
  1074. static void profileSetup_SPDCAD(TDCONFIG *cfg, const uint32_t deviceId);
  1075. static void profileSetup_POWER(TDCONFIG *cfg, const uint32_t deviceId);
  1076. static void profileSetup_STRIDE(TDCONFIG *cfg, const uint32_t deviceId);
  1077. static void profileSetup_SPEED(TDCONFIG *cfg, const uint32_t deviceId);
  1078. static void profileSetup_CADENCE(TDCONFIG *cfg, const uint32_t deviceId);
  1079. struct {
  1080. struct {
  1081. uint8_t bpm;
  1082. uint8_t sequence;
  1083. uint16_t time;
  1084. } previous;
  1085. } hrm;
  1086. void payload_HRM(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1087. struct {
  1088. struct {
  1089. uint16_t cadenceTime;
  1090. uint16_t cadenceCt;
  1091. uint16_t speedTime;
  1092. uint16_t speedCt;
  1093. } previous;
  1094. float distance;
  1095. } spdcad;
  1096. void payload_SPDCAD(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1097. /* struct {
  1098. struct {
  1099. uint8_t sequence;
  1100. uint16_t pedalPowerContribution;
  1101. uint8_t pedalPower;
  1102. uint8_t instantCadence;
  1103. uint16_t sumPower;
  1104. uint16_t instantPower;
  1105. } current;
  1106. struct {
  1107. uint16_t stub;
  1108. } previous;
  1109. } pwr; */
  1110. void payload_POWER(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1111. /* struct {
  1112. struct {
  1113. uint16_t speed;
  1114. uint16_t cadence;
  1115. uint8_t strides;
  1116. } current;
  1117. struct {
  1118. uint8_t strides;
  1119. uint16_t speed;
  1120. uint16_t cadence;
  1121. } previous;
  1122. } stride; */
  1123. void payload_STRIDE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1124. struct {
  1125. struct {
  1126. uint16_t speedTime;
  1127. uint16_t speedCt;
  1128. } previous;
  1129. float distance;
  1130. } spd;
  1131. void payload_SPEED(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1132. struct {
  1133. struct {
  1134. uint16_t cadenceTime;
  1135. uint16_t cadenceCt;
  1136. } previous;
  1137. } cad;
  1138. void payload_CADENCE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1139. uint16_t wheelCircumference; // default is WHEEL_CIRCUMFERENCE (2122cm)
  1140. };
  1141. #endif