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.

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