Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

1206 Zeilen
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 0x027
  110. #define USBHOST_SERIAL_7O1 0x047
  111. #define USBHOST_SERIAL_8N1 0x08
  112. #define USBHOST_SERIAL_8N2 0x108
  113. #define USBHOST_SERIAL_8E1 0x028
  114. #define USBHOST_SERIAL_8O1 0x048
  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. bool update_leds_ = false;
  625. bool processing_new_data_ = false;
  626. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  627. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  628. strbuf_t mystring_bufs[1];
  629. };
  630. //--------------------------------------------------------------------------
  631. class KeyboardHIDExtrasController : public USBHIDInput {
  632. public:
  633. KeyboardHIDExtrasController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  634. void clear() { event_ = false;}
  635. bool available() { return event_; }
  636. void attachPress(void (*f)(uint32_t top, uint16_t code)) { keyPressedFunction = f; }
  637. void attachRelease(void (*f)(uint32_t top, uint16_t code)) { keyReleasedFunction = f; }
  638. enum {MAX_KEYS_DOWN=4};
  639. // uint32_t buttons() { return buttons_; }
  640. protected:
  641. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  642. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  643. virtual void hid_input_data(uint32_t usage, int32_t value);
  644. virtual void hid_input_end();
  645. virtual void disconnect_collection(Device_t *dev);
  646. private:
  647. void (*keyPressedFunction)(uint32_t top, uint16_t code);
  648. void (*keyReleasedFunction)(uint32_t top, uint16_t code);
  649. uint32_t topusage_ = 0; // What top report am I processing?
  650. uint8_t collections_claimed_ = 0;
  651. volatile bool event_ = false;
  652. volatile bool hid_input_begin_ = false;
  653. volatile bool hid_input_data_ = false; // did we receive any valid data with report?
  654. uint8_t count_keys_down_ = 0;
  655. uint16_t keys_down[MAX_KEYS_DOWN];
  656. };
  657. //--------------------------------------------------------------------------
  658. class MouseController : public USBHIDInput {
  659. public:
  660. MouseController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  661. bool available() { return mouseEvent; }
  662. void mouseDataClear();
  663. uint8_t getButtons() { return buttons; }
  664. int getMouseX() { return mouseX; }
  665. int getMouseY() { return mouseY; }
  666. int getWheel() { return wheel; }
  667. int getWheelH() { return wheelH; }
  668. protected:
  669. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  670. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  671. virtual void hid_input_data(uint32_t usage, int32_t value);
  672. virtual void hid_input_end();
  673. virtual void disconnect_collection(Device_t *dev);
  674. private:
  675. uint8_t collections_claimed = 0;
  676. volatile bool mouseEvent = false;
  677. volatile bool hid_input_begin_ = false;
  678. uint8_t buttons = 0;
  679. int mouseX = 0;
  680. int mouseY = 0;
  681. int wheel = 0;
  682. int wheelH = 0;
  683. };
  684. //--------------------------------------------------------------------------
  685. class JoystickController : public USBHIDInput {
  686. public:
  687. JoystickController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  688. bool available() { return joystickEvent; }
  689. void joystickDataClear();
  690. uint32_t getButtons() { return buttons; }
  691. int getAxis(uint32_t index) { return (index < (sizeof(axis)/sizeof(axis[0]))) ? axis[index] : 0; }
  692. protected:
  693. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  694. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  695. virtual void hid_input_data(uint32_t usage, int32_t value);
  696. virtual void hid_input_end();
  697. virtual void disconnect_collection(Device_t *dev);
  698. private:
  699. uint8_t collections_claimed = 0;
  700. bool anychange = false;
  701. volatile bool joystickEvent = false;
  702. uint32_t buttons = 0;
  703. int16_t axis[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  704. };
  705. //--------------------------------------------------------------------------
  706. class MIDIDevice : public USBDriver {
  707. public:
  708. enum { SYSEX_MAX_LEN = 60 };
  709. MIDIDevice(USBHost &host) { init(); }
  710. MIDIDevice(USBHost *host) { init(); }
  711. bool read(uint8_t channel=0, uint8_t cable=0);
  712. uint8_t getType(void) {
  713. return msg_type;
  714. };
  715. uint8_t getChannel(void) {
  716. return msg_channel;
  717. };
  718. uint8_t getData1(void) {
  719. return msg_data1;
  720. };
  721. uint8_t getData2(void) {
  722. return msg_data2;
  723. };
  724. void setHandleNoteOff(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  725. handleNoteOff = f;
  726. };
  727. void setHandleNoteOn(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  728. handleNoteOn = f;
  729. };
  730. void setHandleVelocityChange(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  731. handleVelocityChange = f;
  732. };
  733. void setHandleControlChange(void (*f)(uint8_t channel, uint8_t control, uint8_t value)) {
  734. handleControlChange = f;
  735. };
  736. void setHandleProgramChange(void (*f)(uint8_t channel, uint8_t program)) {
  737. handleProgramChange = f;
  738. };
  739. void setHandleAfterTouch(void (*f)(uint8_t channel, uint8_t pressure)) {
  740. handleAfterTouch = f;
  741. };
  742. void setHandlePitchChange(void (*f)(uint8_t channel, int pitch)) {
  743. handlePitchChange = f;
  744. };
  745. void setHandleSysEx(void (*f)(const uint8_t *data, uint16_t length, bool complete)) {
  746. handleSysEx = (void (*)(const uint8_t *, uint16_t, uint8_t))f;
  747. }
  748. void setHandleRealTimeSystem(void (*f)(uint8_t realtimebyte)) {
  749. handleRealTimeSystem = f;
  750. };
  751. void setHandleTimeCodeQuarterFrame(void (*f)(uint16_t data)) {
  752. handleTimeCodeQuarterFrame = f;
  753. };
  754. void sendNoteOff(uint32_t note, uint32_t velocity, uint32_t channel) {
  755. write_packed(0x8008 | (((channel - 1) & 0x0F) << 8)
  756. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  757. }
  758. void sendNoteOn(uint32_t note, uint32_t velocity, uint32_t channel) {
  759. write_packed(0x9009 | (((channel - 1) & 0x0F) << 8)
  760. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  761. }
  762. void sendPolyPressure(uint32_t note, uint32_t pressure, uint32_t channel) {
  763. write_packed(0xA00A | (((channel - 1) & 0x0F) << 8)
  764. | ((note & 0x7F) << 16) | ((pressure & 0x7F) << 24));
  765. }
  766. void sendControlChange(uint32_t control, uint32_t value, uint32_t channel) {
  767. write_packed(0xB00B | (((channel - 1) & 0x0F) << 8)
  768. | ((control & 0x7F) << 16) | ((value & 0x7F) << 24));
  769. }
  770. void sendProgramChange(uint32_t program, uint32_t channel) {
  771. write_packed(0xC00C | (((channel - 1) & 0x0F) << 8)
  772. | ((program & 0x7F) << 16));
  773. }
  774. void sendAfterTouch(uint32_t pressure, uint32_t channel) {
  775. write_packed(0xD00D | (((channel - 1) & 0x0F) << 8)
  776. | ((pressure & 0x7F) << 16));
  777. }
  778. void sendPitchBend(uint32_t value, uint32_t channel) {
  779. write_packed(0xE00E | (((channel - 1) & 0x0F) << 8)
  780. | ((value & 0x7F) << 16) | ((value & 0x3F80) << 17));
  781. }
  782. void sendSysEx(uint32_t length, const void *data);
  783. void sendRealTime(uint32_t type) {
  784. switch (type) {
  785. case 0xF8: // Clock
  786. case 0xFA: // Start
  787. case 0xFC: // Stop
  788. case 0xFB: // Continue
  789. case 0xFE: // ActiveSensing
  790. case 0xFF: // SystemReset
  791. write_packed((type << 8) | 0x0F);
  792. break;
  793. default: // Invalid Real Time marker
  794. break;
  795. }
  796. }
  797. void sendTimeCodeQuarterFrame(uint32_t type, uint32_t value) {
  798. uint32_t data = ( ((type & 0x07) << 4) | (value & 0x0F) );
  799. sendTimeCodeQuarterFrame(data);
  800. }
  801. void sendTimeCodeQuarterFrame(uint32_t data) {
  802. write_packed(0xF108 | ((data & 0x7F) << 16));
  803. }
  804. protected:
  805. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  806. virtual void disconnect();
  807. static void rx_callback(const Transfer_t *transfer);
  808. static void tx_callback(const Transfer_t *transfer);
  809. void rx_data(const Transfer_t *transfer);
  810. void tx_data(const Transfer_t *transfer);
  811. void init();
  812. void write_packed(uint32_t data);
  813. void sysex_byte(uint8_t b);
  814. private:
  815. Pipe_t *rxpipe;
  816. Pipe_t *txpipe;
  817. enum { MAX_PACKET_SIZE = 64 };
  818. enum { RX_QUEUE_SIZE = 80 }; // must be more than MAX_PACKET_SIZE/4
  819. uint32_t rx_buffer[MAX_PACKET_SIZE/4];
  820. uint32_t tx_buffer[MAX_PACKET_SIZE/4];
  821. uint16_t rx_size;
  822. uint16_t tx_size;
  823. uint32_t rx_queue[RX_QUEUE_SIZE];
  824. bool rx_packet_queued;
  825. uint16_t rx_head;
  826. uint16_t rx_tail;
  827. uint8_t rx_ep;
  828. uint8_t tx_ep;
  829. uint8_t msg_channel;
  830. uint8_t msg_type;
  831. uint8_t msg_data1;
  832. uint8_t msg_data2;
  833. uint8_t msg_sysex[SYSEX_MAX_LEN];
  834. uint8_t msg_sysex_len;
  835. void (*handleNoteOff)(uint8_t ch, uint8_t note, uint8_t vel);
  836. void (*handleNoteOn)(uint8_t ch, uint8_t note, uint8_t vel);
  837. void (*handleVelocityChange)(uint8_t ch, uint8_t note, uint8_t vel);
  838. void (*handleControlChange)(uint8_t ch, uint8_t control, uint8_t value);
  839. void (*handleProgramChange)(uint8_t ch, uint8_t program);
  840. void (*handleAfterTouch)(uint8_t ch, uint8_t pressure);
  841. void (*handlePitchChange)(uint8_t ch, int pitch);
  842. void (*handleSysEx)(const uint8_t *data, uint16_t length, uint8_t complete);
  843. void (*handleRealTimeSystem)(uint8_t rtb);
  844. void (*handleTimeCodeQuarterFrame)(uint16_t data);
  845. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  846. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  847. strbuf_t mystring_bufs[1];
  848. };
  849. //--------------------------------------------------------------------------
  850. class USBSerial: public USBDriver, public Stream {
  851. public:
  852. // FIXME: need different USBSerial, with bigger buffers for 480 Mbit & faster speed
  853. enum { BUFFER_SIZE = 648 }; // must hold at least 6 max size packets, plus 2 extra bytes
  854. USBSerial(USBHost &host) : txtimer(this) { init(); }
  855. void begin(uint32_t baud, uint32_t format=USBHOST_SERIAL_8N1);
  856. void end(void);
  857. virtual int available(void);
  858. virtual int peek(void);
  859. virtual int read(void);
  860. virtual int availableForWrite();
  861. virtual size_t write(uint8_t c);
  862. using Print::write;
  863. protected:
  864. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  865. virtual void control(const Transfer_t *transfer);
  866. virtual void disconnect();
  867. virtual void timer_event(USBDriverTimer *whichTimer);
  868. private:
  869. static void rx_callback(const Transfer_t *transfer);
  870. static void tx_callback(const Transfer_t *transfer);
  871. void rx_data(const Transfer_t *transfer);
  872. void tx_data(const Transfer_t *transfer);
  873. void rx_queue_packets(uint32_t head, uint32_t tail);
  874. void init();
  875. static bool check_rxtx_ep(uint32_t &rxep, uint32_t &txep);
  876. bool init_buffers(uint32_t rsize, uint32_t tsize);
  877. void ch341_setBaud(uint8_t byte_index);
  878. private:
  879. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  880. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  881. strbuf_t mystring_bufs[1];
  882. USBDriverTimer txtimer;
  883. uint32_t bigbuffer[(BUFFER_SIZE+3)/4];
  884. setup_t setup;
  885. uint8_t setupdata[8];
  886. uint32_t baudrate;
  887. uint32_t format_;
  888. Pipe_t *rxpipe;
  889. Pipe_t *txpipe;
  890. uint8_t *rx1; // location for first incoming packet
  891. uint8_t *rx2; // location for second incoming packet
  892. uint8_t *rxbuf; // receive circular buffer
  893. uint8_t *tx1; // location for first outgoing packet
  894. uint8_t *tx2; // location for second outgoing packet
  895. uint8_t *txbuf;
  896. volatile uint16_t rxhead;// receive head
  897. volatile uint16_t rxtail;// receive tail
  898. volatile uint16_t txhead;
  899. volatile uint16_t txtail;
  900. uint16_t rxsize;// size of receive circular buffer
  901. uint16_t txsize;// size of transmit circular buffer
  902. volatile uint8_t rxstate;// bitmask: which receive packets are queued
  903. volatile uint8_t txstate;
  904. uint8_t pending_control;
  905. uint8_t setup_state; // PL2303 - has several steps... Could use pending control?
  906. uint8_t pl2303_v1; // Which version do we have
  907. uint8_t pl2303_v2;
  908. uint8_t interface;
  909. bool control_queued;
  910. typedef enum { UNKNOWN=0, CDCACM, FTDI, PL2303, CH341 } sertype_t;
  911. sertype_t sertype;
  912. typedef struct {
  913. uint16_t idVendor;
  914. uint16_t idProduct;
  915. sertype_t sertype;
  916. } product_vendor_mapping_t;
  917. static product_vendor_mapping_t pid_vid_mapping[];
  918. };
  919. //--------------------------------------------------------------------------
  920. class AntPlus: public USBDriver {
  921. // Please post any AntPlus feedback or contributions on this forum thread:
  922. // https://forum.pjrc.com/threads/43110-Ant-libarary-and-USB-driver-for-Teensy-3-5-6
  923. public:
  924. AntPlus(USBHost &host) : /* txtimer(this),*/ updatetimer(this) { init(); }
  925. void begin(const uint8_t key=0);
  926. void onStatusChange(void (*function)(int channel, int status)) {
  927. user_onStatusChange = function;
  928. }
  929. void onDeviceID(void (*function)(int channel, int devId, int devType, int transType)) {
  930. user_onDeviceID = function;
  931. }
  932. void onHeartRateMonitor(void (*f)(int bpm, int msec, int seqNum), uint32_t devid=0) {
  933. profileSetup_HRM(&ant.dcfg[PROFILE_HRM], devid);
  934. memset(&hrm, 0, sizeof(hrm));
  935. user_onHeartRateMonitor = f;
  936. }
  937. void onSpeedCadence(void (*f)(float speed, float distance, float rpm), uint32_t devid=0) {
  938. profileSetup_SPDCAD(&ant.dcfg[PROFILE_SPDCAD], devid);
  939. memset(&spdcad, 0, sizeof(spdcad));
  940. user_onSpeedCadence = f;
  941. }
  942. void onSpeed(void (*f)(float speed, float distance), uint32_t devid=0) {
  943. profileSetup_SPEED(&ant.dcfg[PROFILE_SPEED], devid);
  944. memset(&spd, 0, sizeof(spd));
  945. user_onSpeed = f;
  946. }
  947. void onCadence(void (*f)(float rpm), uint32_t devid=0) {
  948. profileSetup_CADENCE(&ant.dcfg[PROFILE_CADENCE], devid);
  949. memset(&cad, 0, sizeof(cad));
  950. user_onCadence = f;
  951. }
  952. void setWheelCircumference(float meters) {
  953. wheelCircumference = meters * 1000.0f;
  954. }
  955. protected:
  956. virtual void Task();
  957. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  958. virtual void disconnect();
  959. virtual void timer_event(USBDriverTimer *whichTimer);
  960. private:
  961. static void rx_callback(const Transfer_t *transfer);
  962. static void tx_callback(const Transfer_t *transfer);
  963. void rx_data(const Transfer_t *transfer);
  964. void tx_data(const Transfer_t *transfer);
  965. void init();
  966. size_t write(const void *data, const size_t size);
  967. int read(void *data, const size_t size);
  968. void transmit();
  969. private:
  970. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  971. Transfer_t mytransfers[3] __attribute__ ((aligned(32)));
  972. strbuf_t mystring_bufs[1];
  973. //USBDriverTimer txtimer;
  974. USBDriverTimer updatetimer;
  975. Pipe_t *rxpipe;
  976. Pipe_t *txpipe;
  977. bool first_update;
  978. uint8_t txbuffer[240];
  979. uint8_t rxpacket[64];
  980. volatile uint16_t txhead;
  981. volatile uint16_t txtail;
  982. volatile bool txready;
  983. volatile uint8_t rxlen;
  984. volatile bool do_polling;
  985. private:
  986. enum _eventi {
  987. EVENTI_MESSAGE = 0,
  988. EVENTI_CHANNEL,
  989. EVENTI_TOTAL
  990. };
  991. enum _profiles {
  992. PROFILE_HRM = 0,
  993. PROFILE_SPDCAD,
  994. PROFILE_POWER,
  995. PROFILE_STRIDE,
  996. PROFILE_SPEED,
  997. PROFILE_CADENCE,
  998. PROFILE_TOTAL
  999. };
  1000. typedef struct {
  1001. uint8_t channel;
  1002. uint8_t RFFreq;
  1003. uint8_t networkNumber;
  1004. uint8_t stub;
  1005. uint8_t searchTimeout;
  1006. uint8_t channelType;
  1007. uint8_t deviceType;
  1008. uint8_t transType;
  1009. uint16_t channelPeriod;
  1010. uint16_t searchWaveform;
  1011. uint32_t deviceNumber; // deviceId
  1012. struct {
  1013. uint8_t chanIdOnce;
  1014. uint8_t keyAccepted;
  1015. uint8_t profileValid;
  1016. uint8_t channelStatus;
  1017. uint8_t channelStatusOld;
  1018. } flags;
  1019. } TDCONFIG;
  1020. struct {
  1021. uint8_t initOnce;
  1022. uint8_t key; // key index
  1023. int iDevice; // index to the antplus we're interested in, if > one found
  1024. TDCONFIG dcfg[PROFILE_TOTAL]; // channel config, we're using one channel per device
  1025. } ant;
  1026. void (*user_onStatusChange)(int channel, int status);
  1027. void (*user_onDeviceID)(int channel, int devId, int devType, int transType);
  1028. void (*user_onHeartRateMonitor)(int beatsPerMinute, int milliseconds, int sequenceNumber);
  1029. void (*user_onSpeedCadence)(float speed, float distance, float cadence);
  1030. void (*user_onSpeed)(float speed, float distance);
  1031. void (*user_onCadence)(float cadence);
  1032. void dispatchPayload(TDCONFIG *cfg, const uint8_t *payload, const int len);
  1033. static const uint8_t *getAntKey(const uint8_t keyIdx);
  1034. static uint8_t calcMsgChecksum (const uint8_t *buffer, const uint8_t len);
  1035. static uint8_t * findStreamSync(uint8_t *stream, const size_t rlen, int *pos);
  1036. static int msgCheckIntegrity(uint8_t *stream, const int len);
  1037. static int msgGetLength(uint8_t *stream);
  1038. int handleMessages(uint8_t *buffer, int tBytes);
  1039. void sendMessageChannelStatus(TDCONFIG *cfg, const uint32_t channelStatus);
  1040. void message_channel(const int chan, const int eventId,
  1041. const uint8_t *payload, const size_t dataLength);
  1042. void message_response(const int chan, const int msgId,
  1043. const uint8_t *payload, const size_t dataLength);
  1044. void message_event(const int channel, const int msgId,
  1045. const uint8_t *payload, const size_t dataLength);
  1046. int ResetSystem();
  1047. int RequestMessage(const int channel, const int message);
  1048. int SetNetworkKey(const int netNumber, const uint8_t *key);
  1049. int SetChannelSearchTimeout(const int channel, const int searchTimeout);
  1050. int SetChannelPeriod(const int channel, const int period);
  1051. int SetChannelRFFreq(const int channel, const int freq);
  1052. int SetSearchWaveform(const int channel, const int wave);
  1053. int OpenChannel(const int channel);
  1054. int CloseChannel(const int channel);
  1055. int AssignChannel(const int channel, const int channelType, const int network);
  1056. int SetChannelId(const int channel, const int deviceNum, const int deviceType,
  1057. const int transmissionType);
  1058. int SendBurstTransferPacket(const int channelSeq, const uint8_t *data);
  1059. int SendBurstTransfer(const int channel, const uint8_t *data, const int nunPackets);
  1060. int SendBroadcastData(const int channel, const uint8_t *data);
  1061. int SendAcknowledgedData(const int channel, const uint8_t *data);
  1062. int SendExtAcknowledgedData(const int channel, const int devNum, const int devType,
  1063. const int TranType, const uint8_t *data);
  1064. int SendExtBroadcastData(const int channel, const int devNum, const int devType,
  1065. const int TranType, const uint8_t *data);
  1066. int SendExtBurstTransferPacket(const int chanSeq, const int devNum,
  1067. const int devType, const int TranType, const uint8_t *data);
  1068. int SendExtBurstTransfer(const int channel, const int devNum, const int devType,
  1069. const int tranType, const uint8_t *data, const int nunPackets);
  1070. static void profileSetup_HRM(TDCONFIG *cfg, const uint32_t deviceId);
  1071. static void profileSetup_SPDCAD(TDCONFIG *cfg, const uint32_t deviceId);
  1072. static void profileSetup_POWER(TDCONFIG *cfg, const uint32_t deviceId);
  1073. static void profileSetup_STRIDE(TDCONFIG *cfg, const uint32_t deviceId);
  1074. static void profileSetup_SPEED(TDCONFIG *cfg, const uint32_t deviceId);
  1075. static void profileSetup_CADENCE(TDCONFIG *cfg, const uint32_t deviceId);
  1076. struct {
  1077. struct {
  1078. uint8_t bpm;
  1079. uint8_t sequence;
  1080. uint16_t time;
  1081. } previous;
  1082. } hrm;
  1083. void payload_HRM(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1084. struct {
  1085. struct {
  1086. uint16_t cadenceTime;
  1087. uint16_t cadenceCt;
  1088. uint16_t speedTime;
  1089. uint16_t speedCt;
  1090. } previous;
  1091. float distance;
  1092. } spdcad;
  1093. void payload_SPDCAD(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1094. /* struct {
  1095. struct {
  1096. uint8_t sequence;
  1097. uint16_t pedalPowerContribution;
  1098. uint8_t pedalPower;
  1099. uint8_t instantCadence;
  1100. uint16_t sumPower;
  1101. uint16_t instantPower;
  1102. } current;
  1103. struct {
  1104. uint16_t stub;
  1105. } previous;
  1106. } pwr; */
  1107. void payload_POWER(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1108. /* struct {
  1109. struct {
  1110. uint16_t speed;
  1111. uint16_t cadence;
  1112. uint8_t strides;
  1113. } current;
  1114. struct {
  1115. uint8_t strides;
  1116. uint16_t speed;
  1117. uint16_t cadence;
  1118. } previous;
  1119. } stride; */
  1120. void payload_STRIDE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1121. struct {
  1122. struct {
  1123. uint16_t speedTime;
  1124. uint16_t speedCt;
  1125. } previous;
  1126. float distance;
  1127. } spd;
  1128. void payload_SPEED(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1129. struct {
  1130. struct {
  1131. uint16_t cadenceTime;
  1132. uint16_t cadenceCt;
  1133. } previous;
  1134. } cad;
  1135. void payload_CADENCE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1136. uint16_t wheelCircumference; // default is WHEEL_CIRCUMFERENCE (2122cm)
  1137. };
  1138. #endif