-
Notifications
You must be signed in to change notification settings - Fork 87
/
USBHost_t36.h
2895 lines (2594 loc) · 117 KB
/
USBHost_t36.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* USB EHCI Host for Teensy 3.6
* Copyright 2017 Paul Stoffregen ([email protected])
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef USB_HOST_TEENSY36_
#define USB_HOST_TEENSY36_
#include <stdint.h>
#include <FS.h>
#if !defined(__MK66FX1M0__) && !defined(__IMXRT1052__) && !defined(__IMXRT1062__)
#error "USBHost_t36 only works with Teensy 3.6 or Teensy 4.x. Please select it in Tools > Boards"
#endif
#include "utility/imxrt_usbhs.h"
#include "utility/msc.h"
// Dear inquisitive reader, USB is a complex protocol defined with
// very specific terminology. To have any chance of understand this
// source code, you absolutely must have solid knowledge of specific
// USB terms such as host, device, endpoint, pipe, enumeration....
// You really must also have at least a basic knowledge of the
// different USB transfers: control, bulk, interrupt, isochronous.
//
// The USB 2.0 specification explains these in chapter 4 (pages 15
// to 24), and provides more detail in the first part of chapter 5
// (pages 25 to 55). The USB spec is published for free at
// www.usb.org. Here is a convenient link to just the main PDF:
//
// https://www.pjrc.com/teensy/beta/usb20.pdf
//
// This is a huge file, but chapter 4 is short and easy to read.
// If you're not familiar with the USB lingo, please do yourself
// a favor by reading at least chapter 4 to get up to speed on the
// meaning of these important USB concepts and terminology.
//
// If you wish to ask questions (which belong on the forum, not
// github issues) or discuss development of this library, you
// ABSOLUTELY MUST know the basic USB terminology from chapter 4.
// Please repect other people's valuable time & effort by making
// your best effort to read chapter 4 before asking USB questions!
// Uncomment this line to see lots of debugging info!
//#define USBHOST_PRINT_DEBUG
// This can let you control where to send the debugging messages
//#define USBHDBGSerial Serial1
#ifndef USBHDBGSerial
#define USBHDBGSerial Serial
#endif
/************************************************/
/* Data Types */
/************************************************/
// These 6 types are the key to understanding how this USB Host
// library really works.
// USBHost is a static class controlling the hardware.
// All common USB functionality is implemented here.
class USBHost;
// These 3 structures represent the actual USB entities
// USBHost manipulates. One Device_t is created for
// each active USB device. One Pipe_t is create for
// each endpoint. Transfer_t structures are created
// when any data transfer is added to the EHCI work
// queues, and then returned to the free pool after the
// data transfer completes and the driver has processed
// the results.
typedef struct Device_struct Device_t;
typedef struct Pipe_struct Pipe_t;
typedef struct Transfer_struct Transfer_t;
typedef enum { CLAIM_NO = 0, CLAIM_REPORT, CLAIM_INTERFACE} hidclaim_t;
// All USB device drivers inherit use these classes.
// Drivers build user-visible functionality on top
// of these classes, which receive USB events from
// USBHost.
class USBDriver;
class USBDriverTimer;
class USBHIDInput;
/************************************************/
/* Added Defines */
/************************************************/
// Keyboard special Keys
#define KEYD_UP 0xDA
#define KEYD_DOWN 0xD9
#define KEYD_LEFT 0xD8
#define KEYD_RIGHT 0xD7
#define KEYD_INSERT 0xD1
#define KEYD_DELETE 0xD4
#define KEYD_PAGE_UP 0xD3
#define KEYD_PAGE_DOWN 0xD6
#define KEYD_HOME 0xD2
#define KEYD_END 0xD5
#define KEYD_F1 0xC2
#define KEYD_F2 0xC3
#define KEYD_F3 0xC4
#define KEYD_F4 0xC5
#define KEYD_F5 0xC6
#define KEYD_F6 0xC7
#define KEYD_F7 0xC8
#define KEYD_F8 0xC9
#define KEYD_F9 0xCA
#define KEYD_F10 0xCB
#define KEYD_F11 0xCC
#define KEYD_F12 0xCD
// USBSerial formats - Lets encode format into bits
// Bits: 0-4 - Number of data bits
// Bits: 5-7 - Parity (0=none, 1=odd, 2 = even)
// bits: 8-9 - Stop bits. 0=1, 1=2
#define USBHOST_SERIAL_7E1 0x047
#define USBHOST_SERIAL_7O1 0x027
#define USBHOST_SERIAL_8N1 0x08
#define USBHOST_SERIAL_8N2 0x108
#define USBHOST_SERIAL_8E1 0x048
#define USBHOST_SERIAL_8O1 0x028
/************************************************/
/* Data Structure Definitions */
/************************************************/
// setup_t holds the 8 byte USB SETUP packet data.
// These unions & structs allow convenient access to
// the setup fields.
typedef union {
struct {
union {
struct {
uint8_t bmRequestType;
uint8_t bRequest;
};
uint16_t wRequestAndType;
};
uint16_t wValue;
uint16_t wIndex;
uint16_t wLength;
};
struct {
uint32_t word1;
uint32_t word2;
};
} setup_t;
typedef struct {
enum {STRING_BUF_SIZE = 50};
enum {STR_ID_MAN = 0, STR_ID_PROD, STR_ID_SERIAL, STR_ID_CNT};
uint8_t iStrings[STR_ID_CNT]; // Index into array for the three indexes
uint8_t buffer[STRING_BUF_SIZE];
} strbuf_t;
#define DEVICE_STRUCT_STRING_BUF_SIZE 50
// Device_t holds all the information about a USB device
struct Device_struct {
Pipe_t *control_pipe;
Pipe_t *data_pipes;
Device_t *next;
USBDriver *drivers;
strbuf_t *strbuf;
uint8_t speed; // 0=12, 1=1.5, 2=480 Mbit/sec
uint8_t address;
uint8_t hub_address;
uint8_t hub_port;
uint8_t enum_state;
uint8_t bDeviceClass;
uint8_t bDeviceSubClass;
uint8_t bDeviceProtocol;
uint8_t bmAttributes;
uint8_t bMaxPower;
uint16_t idVendor;
uint16_t idProduct;
uint16_t LanguageID;
};
// Pipe_t holes all information about each USB endpoint/pipe
// The first half is an EHCI QH structure for the pipe.
struct Pipe_struct {
// Queue Head (QH), EHCI page 46-50
struct { // must be aligned to 32 byte boundary
volatile uint32_t horizontal_link;
volatile uint32_t capabilities[2];
volatile uint32_t current;
volatile uint32_t next;
volatile uint32_t alt_next;
volatile uint32_t token;
volatile uint32_t buffer[5];
} qh;
Device_t *device;
uint8_t type; // 0=control, 1=isochronous, 2=bulk, 3=interrupt
uint8_t direction; // 0=out, 1=in (changes for control, others fixed)
uint8_t start_mask;
uint8_t complete_mask;
Pipe_t *next;
void (*callback_function)(const Transfer_t *);
uint16_t periodic_interval;
uint16_t periodic_offset;
uint16_t bandwidth_interval;
uint16_t bandwidth_offset;
uint16_t bandwidth_shift;
uint8_t bandwidth_stime;
uint8_t bandwidth_ctime;
uint32_t unused1;
uint32_t unused2;
uint32_t unused3;
uint32_t unused4;
uint32_t unused5;
};
// Transfer_t represents a single transaction on the USB bus.
// The first portion is an EHCI qTD structure. Transfer_t are
// allocated as-needed from a memory pool, loaded with pointers
// to the actual data buffers, linked into a followup list,
// and placed on ECHI Queue Heads. When the ECHI interrupt
// occurs, the followup lists are used to find the Transfer_t
// in memory. Callbacks are made, and then the Transfer_t are
// returned to the memory pool.
struct Transfer_struct {
// Queue Element Transfer Descriptor (qTD), EHCI pg 40-45
struct { // must be aligned to 32 byte boundary
volatile uint32_t next;
volatile uint32_t alt_next;
volatile uint32_t token;
volatile uint32_t buffer[5];
} qtd;
// Linked list of queued, not-yet-completed transfers
Transfer_t *next_followup;
Transfer_t *prev_followup;
Pipe_t *pipe;
// Data to be used by callback function. When a group
// of Transfer_t are created, these fields and the
// interrupt-on-complete bit in the qTD token are only
// set in the last Transfer_t of the list.
void *buffer;
uint32_t length;
setup_t setup;
USBDriver *driver;
};
/************************************************/
/* Main USB EHCI Controller */
/************************************************/
class USBHost {
public:
static void begin();
static void Task();
static void countFree(uint32_t &devices, uint32_t &pipes, uint32_t &trans, uint32_t &strs);
protected:
static Pipe_t * new_Pipe(Device_t *dev, uint32_t type, uint32_t endpoint,
uint32_t direction, uint32_t maxlen, uint32_t interval = 0);
static bool queue_Control_Transfer(Device_t *dev, setup_t *setup,
void *buf, USBDriver *driver);
static bool queue_Data_Transfer(Pipe_t *pipe, void *buffer,
uint32_t len, USBDriver *driver);
static Device_t * new_Device(uint32_t speed, uint32_t hub_addr, uint32_t hub_port);
static void disconnect_Device(Device_t *dev);
static void enumeration(const Transfer_t *transfer);
static void driver_ready_for_device(USBDriver *driver);
static volatile bool enumeration_busy;
public: // Maybe others may want/need to contribute memory example HID devices may want to add transfers.
static void contribute_Devices(Device_t *devices, uint32_t num);
static void contribute_Pipes(Pipe_t *pipes, uint32_t num);
static void contribute_Transfers(Transfer_t *transfers, uint32_t num);
static void contribute_String_Buffers(strbuf_t *strbuf, uint32_t num);
private:
static void isr();
static void convertStringDescriptorToASCIIString(uint8_t string_index, Device_t *dev, const Transfer_t *transfer);
static void claim_drivers(Device_t *dev);
static uint32_t assign_address(void);
static bool queue_Transfer(Pipe_t *pipe, Transfer_t *transfer);
static void init_Device_Pipe_Transfer_memory(void);
static Device_t * allocate_Device(void);
static void delete_Pipe(Pipe_t *pipe);
static void free_Device(Device_t *q);
static Pipe_t * allocate_Pipe(void);
static void free_Pipe(Pipe_t *q);
static Transfer_t * allocate_Transfer(void);
static void free_Transfer(Transfer_t *q);
static strbuf_t * allocate_string_buffer(void);
static void free_string_buffer(strbuf_t *strbuf);
static bool allocate_interrupt_pipe_bandwidth(Pipe_t *pipe,
uint32_t maxlen, uint32_t interval);
static void add_qh_to_periodic_schedule(Pipe_t *pipe);
static bool followup_Transfer(Transfer_t *transfer);
static void followup_Error(void);
public: // Maybe others may want/need to contribute memory example HID devices may want to add transfers.
#ifdef USBHOST_PRINT_DEBUG
static void print_(const Transfer_t *transfer);
static void print_(const Transfer_t *first, const Transfer_t *last);
static void print_token(uint32_t token);
static void print_(const Pipe_t *pipe);
static void print_driverlist(const char *name, const USBDriver *driver);
static void print_qh_list(const Pipe_t *list);
static void print_device_descriptor(const uint8_t *p);
static void print_config_descriptor(const uint8_t *p, uint32_t maxlen);
static void print_string_descriptor(const char *name, const uint8_t *p);
static void print_hexbytes(const void *ptr, uint32_t len);
static void print_(const char *s) { USBHDBGSerial.print(s); }
static void print_(int n) { USBHDBGSerial.print(n); }
static void print_(unsigned int n) { USBHDBGSerial.print(n); }
static void print_(long n) { USBHDBGSerial.print(n); }
static void print_(unsigned long n) { USBHDBGSerial.print(n); }
static void println_(const char *s) { USBHDBGSerial.println(s); }
static void println_(int n) { USBHDBGSerial.println(n); }
static void println_(unsigned int n) { USBHDBGSerial.println(n); }
static void println_(long n) { USBHDBGSerial.println(n); }
static void println_(unsigned long n) { USBHDBGSerial.println(n); }
static void println_() { USBHDBGSerial.println(); }
static void print_(uint32_t n, uint8_t b) { USBHDBGSerial.print(n, b); }
static void println_(uint32_t n, uint8_t b) { USBHDBGSerial.println(n, b); }
static void print_(const char *s, int n, uint8_t b = DEC) {
USBHDBGSerial.print(s); USBHDBGSerial.print(n, b);
}
static void print_(const char *s, unsigned int n, uint8_t b = DEC) {
USBHDBGSerial.print(s); USBHDBGSerial.print(n, b);
}
static void print_(const char *s, long n, uint8_t b = DEC) {
USBHDBGSerial.print(s); USBHDBGSerial.print(n, b);
}
static void print_(const char *s, unsigned long n, uint8_t b = DEC) {
USBHDBGSerial.print(s); USBHDBGSerial.print(n, b);
}
static void println_(const char *s, int n, uint8_t b = DEC) {
USBHDBGSerial.print(s); USBHDBGSerial.println(n, b);
}
static void println_(const char *s, unsigned int n, uint8_t b = DEC) {
USBHDBGSerial.print(s); USBHDBGSerial.println(n, b);
}
static void println_(const char *s, long n, uint8_t b = DEC) {
USBHDBGSerial.print(s); USBHDBGSerial.println(n, b);
}
static void println_(const char *s, unsigned long n, uint8_t b = DEC) {
USBHDBGSerial.print(s); USBHDBGSerial.println(n, b);
}
friend class USBDriverTimer; // for access to print & println
#else
static void print_(const Transfer_t *transfer) {}
static void print_(const Transfer_t *first, const Transfer_t *last) {}
static void print_token(uint32_t token) {}
static void print_(const Pipe_t *pipe) {}
static void print_driverlist(const char *name, const USBDriver *driver) {}
static void print_qh_list(const Pipe_t *list) {}
static void print_device_descriptor(const uint8_t *p) {}
static void print_config_descriptor(const uint8_t *p, uint32_t maxlen) {}
static void print_string_descriptor(const char *name, const uint8_t *p) {}
static void print_hexbytes(const void *ptr, uint32_t len) {}
static void print_(const char *s) {}
static void print_(int n) {}
static void print_(unsigned int n) {}
static void print_(long n) {}
static void print_(unsigned long n) {}
static void println_(const char *s) {}
static void println_(int n) {}
static void println_(unsigned int n) {}
static void println_(long n) {}
static void println_(unsigned long n) {}
static void println_() {}
static void print_(uint32_t n, uint8_t b) {}
static void println_(uint32_t n, uint8_t b) {}
static void print_(const char *s, int n, uint8_t b = DEC) {}
static void print_(const char *s, unsigned int n, uint8_t b = DEC) {}
static void print_(const char *s, long n, uint8_t b = DEC) {}
static void print_(const char *s, unsigned long n, uint8_t b = DEC) {}
static void println_(const char *s, int n, uint8_t b = DEC) {}
static void println_(const char *s, unsigned int n, uint8_t b = DEC) {}
static void println_(const char *s, long n, uint8_t b = DEC) {}
static void println_(const char *s, unsigned long n, uint8_t b = DEC) {}
#endif
protected:
static void mk_setup(setup_t &s, uint32_t bmRequestType, uint32_t bRequest,
uint32_t wValue, uint32_t wIndex, uint32_t wLength) {
s.word1 = bmRequestType | (bRequest << 8) | (wValue << 16);
s.word2 = wIndex | (wLength << 16);
}
};
/************************************************/
/* USB Device Driver Common Base Class */
/************************************************/
// All USB device drivers inherit from this base class.
class USBDriver : public USBHost {
public:
operator bool() {
Device_t *dev = *(Device_t * volatile *)&device;
return dev != nullptr;
}
uint16_t idVendor() {
Device_t *dev = *(Device_t * volatile *)&device;
return (dev != nullptr) ? dev->idVendor : 0;
}
uint16_t idProduct() {
Device_t *dev = *(Device_t * volatile *)&device;
return (dev != nullptr) ? dev->idProduct : 0;
}
const uint8_t *manufacturer() {
Device_t *dev = *(Device_t * volatile *)&device;
if (dev == nullptr || dev->strbuf == nullptr) return nullptr;
return &dev->strbuf->buffer[dev->strbuf->iStrings[strbuf_t::STR_ID_MAN]];
}
const uint8_t *product() {
Device_t *dev = *(Device_t * volatile *)&device;
if (dev == nullptr || dev->strbuf == nullptr) return nullptr;
return &dev->strbuf->buffer[dev->strbuf->iStrings[strbuf_t::STR_ID_PROD]];
}
const uint8_t *serialNumber() {
Device_t *dev = *(Device_t * volatile *)&device;
if (dev == nullptr || dev->strbuf == nullptr) return nullptr;
return &dev->strbuf->buffer[dev->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]];
}
protected:
USBDriver() : next(NULL), device(NULL) {}
// Check if a driver wishes to claim a device or interface or group
// of interfaces within a device. When this function returns true,
// the driver is considered bound or loaded for that device. When
// new devices are detected, enumeration.cpp calls this function on
// all unbound driver objects, to give them an opportunity to bind
// to the new device.
// device has its vid&pid, class/subclass fields initialized
// type is 0 for device level, 1 for interface level, 2 for IAD
// descriptors points to the specific descriptor data
virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len) = 0;
// When an unknown (not chapter 9) control transfer completes, this
// function is called for all drivers bound to the device. Return
// true means this driver originated this control transfer, so no
// more drivers need to be offered an opportunity to process it.
// This function is optional, only needed if the driver uses control
// transfers and wishes to be notified when they complete.
virtual void control(const Transfer_t *transfer) { }
// When any of the USBDriverTimer objects a driver creates generates
// a timer event, this function is called.
virtual void timer_event(USBDriverTimer *whichTimer) { }
// When the user calls USBHost::Task, this Task function for all
// active drivers is called, so they may update state and/or call
// any attached user callback functions.
virtual void Task() { }
// When a device disconnects from the USB, this function is called.
// The driver must free all resources it allocated and update any
// internal state necessary to deal with the possibility of user
// code continuing to call its API. However, pipes and transfers
// are the handled by lower layers, so device drivers do not free
// pipes they created or cancel transfers they had in progress.
virtual void disconnect() = 0;
// Drivers are managed by this single-linked list. All inactive
// (not bound to any device) drivers are linked from
// available_drivers in enumeration.cpp. When bound to a device,
// drivers are linked from that Device_t drivers list.
USBDriver *next;
// The device this object instance is bound to. In words, this
// is the specific device this driver is using. When not bound
// to any device, this must be NULL. Drivers may set this to
// any non-NULL value if they are in a state where they do not
// wish to claim any device or interface (eg, if getting data
// from the HID parser).
Device_t *device;
friend class USBHost;
};
// Device drivers may create these timer objects to schedule a timer call
class USBDriverTimer {
public:
USBDriverTimer() { }
USBDriverTimer(USBDriver *d) : driver(d) { }
void init(USBDriver *d) { driver = d; };
void start(uint32_t microseconds);
void stop();
void *pointer;
uint32_t integer;
uint32_t started_micros; // testing only
private:
USBDriver *driver;
uint32_t usec;
USBDriverTimer *next;
USBDriverTimer *prev;
friend class USBHost;
};
// Device drivers may inherit from this base class, if they wish to receive
// HID input data fully decoded by the USBHIDParser driver
class USBHIDParser;
class USBHIDInput {
public:
operator bool() { return (mydevice != nullptr); }
uint16_t idVendor() { return (mydevice != nullptr) ? mydevice->idVendor : 0; }
uint16_t idProduct() { return (mydevice != nullptr) ? mydevice->idProduct : 0; }
const uint8_t *manufacturer()
{ return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_MAN]]; }
const uint8_t *product()
{ return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_PROD]]; }
const uint8_t *serialNumber()
{ return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]]; }
private:
virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage) = 0;
virtual bool hid_process_in_data(const Transfer_t *transfer) {return false;}
virtual bool hid_process_out_data(const Transfer_t *transfer) {return false;}
virtual bool hid_process_control(const Transfer_t *transfer) {return false;}
virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax) { }
virtual void hid_input_data(uint32_t usage, int32_t value) { }
virtual void hid_input_end() { }
virtual void disconnect_collection(Device_t *dev) { }
virtual void hid_timer_event(USBDriverTimer *whichTimer) { }
USBHIDInput *next = NULL;
friend class USBHIDParser;
friend class BTHIDSupport;
protected:
Device_t *mydevice = NULL;
};
// Device drivers may inherit from this base class, if they wish to receive
// HID input like data from Bluetooth HID device.
class BluetoothController;
class BluetoothConnection;
class BTHIDInput {
public:
operator bool() { return (btdevice != nullptr); } // experiment to see if overriding makes sense here
uint16_t idVendor() { return (btdevice != nullptr) ? btdevice->idVendor : 0; }
uint16_t idProduct() { return (btdevice != nullptr) ? btdevice->idProduct : 0; }
const uint8_t *manufacturer();
const uint8_t *product();
const uint8_t *serialNumber();
private:
virtual bool claim_bluetooth(BluetoothController *driver, uint32_t bluetooth_class, uint8_t *remoteName) {return false;}
// newer version that will allow called code to know when it is being called (0 - At the connect, 1 if NO HID...)
// not sure if I should overload the return or not, but...
virtual hidclaim_t claim_bluetooth(BluetoothConnection *btconnection, uint32_t bluetooth_class, uint8_t *remoteName, int type);
virtual bool process_bluetooth_HID_data(const uint8_t *data, uint16_t length) {return false;}
virtual void release_bluetooth() {};
virtual bool remoteNameComplete(const uint8_t *remoteName) {return true;}
virtual void connectionComplete(void) {};
virtual void sdp_command_completed (bool success) {};
virtual hidclaim_t bt_claim_collection(BluetoothConnection *btconnection, uint32_t bluetooth_class, uint32_t topusage) {return CLAIM_NO;}
virtual void bt_hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax) {};
virtual void bt_hid_input_data(uint32_t usage, int32_t value) {};
virtual void bt_hid_input_end() {};
virtual void bt_disconnect_collection(Device_t *dev) {};
virtual void bt_hid_timer_event(USBDriverTimer *whichTimer) { }
BTHIDInput *next = NULL;
friend class BluetoothController;
friend class BluetoothConnection;
enum { TOPUSAGE_LIST_LEN = 6 };
enum { USAGE_LIST_LEN = 24 };
protected:
enum {SP_NEED_CONNECT = 0x1, SP_DONT_NEED_CONNECT = 0x02, SP_PS3_IDS = 0x4};
uint8_t special_process_required = 0;
Device_t *btdevice = NULL;
BluetoothConnection *btconnect = nullptr;
};
/************************************************/
/* USB Device Drivers */
/************************************************/
class USBHub : public USBDriver {
public:
USBHub(USBHost &host) : debouncetimer(this), resettimer(this) { init(); }
USBHub(USBHost *host) : debouncetimer(this), resettimer(this) { init(); }
// Hubs with more more than 7 ports are built from two tiers of hubs
// using 4 or 7 port hub chips. While the USB spec seems to allow
// hubs to have up to 255 ports, in practice all hub chips on the
// market are only 2, 3, 4 or 7 ports.
enum { MAXPORTS = 7 };
typedef uint8_t portbitmask_t;
enum {
PORT_OFF = 0,
PORT_DISCONNECT = 1,
PORT_DEBOUNCE1 = 2,
PORT_DEBOUNCE2 = 3,
PORT_DEBOUNCE3 = 4,
PORT_DEBOUNCE4 = 5,
PORT_DEBOUNCE5 = 6,
PORT_RESET = 7,
PORT_RECOVERY = 8,
PORT_ACTIVE = 9
};
protected:
virtual bool claim(Device_t *dev, int type, const uint8_t *descriptors, uint32_t len);
virtual void control(const Transfer_t *transfer);
virtual void timer_event(USBDriverTimer *whichTimer);
virtual void disconnect();
void init();
bool can_send_control_now();
void send_poweron(uint32_t port);
void send_getstatus(uint32_t port);
void send_clearstatus_connect(uint32_t port);
void send_clearstatus_enable(uint32_t port);
void send_clearstatus_suspend(uint32_t port);
void send_clearstatus_overcurrent(uint32_t port);
void send_clearstatus_reset(uint32_t port);
void send_setreset(uint32_t port);
void send_setinterface();
static void callback(const Transfer_t *transfer);
void status_change(const Transfer_t *transfer);
void new_port_status(uint32_t port, uint32_t status);
void start_debounce_timer(uint32_t port);
void stop_debounce_timer(uint32_t port);
private:
Device_t mydevices[MAXPORTS];
Pipe_t mypipes[2] __attribute__ ((aligned(32)));
Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
strbuf_t mystring_bufs[1];
USBDriverTimer debouncetimer;
USBDriverTimer resettimer;
setup_t setup;
Pipe_t *changepipe;
Device_t *devicelist[MAXPORTS];
uint32_t changebits;
uint32_t statusbits;
uint8_t hub_desc[16];
uint8_t interface_count;
uint8_t interface_number;
uint8_t altsetting;
uint8_t protocol;
uint8_t endpoint;
uint8_t interval;
uint8_t numports;
uint8_t characteristics;
uint8_t powertime;
uint8_t sending_control_transfer;
uint8_t port_doing_reset;
uint8_t port_doing_reset_speed;
uint8_t portstate[MAXPORTS];
portbitmask_t send_pending_poweron;
portbitmask_t send_pending_getstatus;
portbitmask_t send_pending_clearstatus_connect;
portbitmask_t send_pending_clearstatus_enable;
portbitmask_t send_pending_clearstatus_suspend;
portbitmask_t send_pending_clearstatus_overcurrent;
portbitmask_t send_pending_clearstatus_reset;
portbitmask_t send_pending_setreset;
portbitmask_t debounce_in_use;
static volatile bool reset_busy;
};
//--------------------------------------------------------------------------
class USBHIDParser : public USBDriver {
public:
USBHIDParser(USBHost &host) : hidTimer(this) { init(); }
static void driver_ready_for_hid_collection(USBHIDInput *driver);
bool sendPacket(const uint8_t *buffer, int cb=-1);
void setTXBuffers(uint8_t *buffer1, uint8_t *buffer2, uint8_t cb,
// extended to optionaly allow more buffers.
uint8_t *buffer3=nullptr, uint8_t* buffer4=nullptr);
void setRXBuffers(uint8_t *buffer1, uint8_t *buffer2, uint8_t cb,
// extended to optionaly allow more buffers.
uint8_t *buffer3=nullptr, uint8_t* buffer4=nullptr);
bool sendControlPacket(uint32_t bmRequestType, uint32_t bRequest,
uint32_t wValue, uint32_t wIndex, uint32_t wLength, void *buf);
// Atempt for RAWhid and SEREMU to take over processing of data
//
uint16_t inSize(void) {return in_size;}
uint16_t outSize(void) {return out_size;}
uint8_t interfaceSubClass(void) { return bInterfaceSubClass; }
uint8_t interfaceProtocol(void) { return bInterfaceProtocol; }
void startTimer(uint32_t microseconds) {hidTimer.start(microseconds);}
void stopTimer() {hidTimer.stop();}
uint8_t interfaceNumber() { return bInterfaceNumber;}
const uint8_t * getHIDReportDescriptor() {return _bigBuffer;}
uint16_t getHIDReportDescriptorSize() { return descsize;}
protected:
enum { TOPUSAGE_LIST_LEN = 6 };
enum { USAGE_LIST_LEN = 24 };
virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
virtual void control(const Transfer_t *transfer);
virtual void disconnect();
static void in_callback(const Transfer_t *transfer);
static void out_callback(const Transfer_t *transfer);
virtual void timer_event(USBDriverTimer *whichTimer);
void in_data(const Transfer_t *transfer);
void out_data(const Transfer_t *transfer);
bool check_if_using_report_id();
void parse();
USBHIDInput * find_driver(uint32_t topusage);
void parse(uint16_t type_and_report_id, const uint8_t *data, uint32_t len);
void init();
uint8_t activeSendMask(void) {return _tx_state;}
private:
Pipe_t *in_pipe;
Pipe_t *out_pipe;
static USBHIDInput *available_hid_drivers_list;
//uint32_t topusage_list[TOPUSAGE_LIST_LEN];
USBHIDInput *topusage_drivers[TOPUSAGE_LIST_LEN];
uint16_t in_size;
uint16_t out_size;
uint8_t bInterfaceSubClass;
uint8_t bInterfaceProtocol;
setup_t setup;
uint8_t report[64];
uint8_t report2[64];
uint16_t descsize;
bool use_report_id;
Pipe_t mypipes[3] __attribute__ ((aligned(32)));
Transfer_t mytransfers[5] __attribute__ ((aligned(32)));
strbuf_t mystring_bufs[1];
uint8_t *_rx1 = nullptr;
uint8_t *_rx2 = nullptr;
uint8_t *_rx3 = nullptr;
uint8_t *_rx4 = nullptr;
uint8_t *_tx[4] = {nullptr, nullptr, nullptr, nullptr};
uint8_t _tx_state = 0;
uint8_t _tx_mask = 3;
bool hid_driver_claimed_control_ = false;
USBDriverTimer hidTimer;
uint8_t _bigBuffer[800 + 64+64];
uint8_t *_bigBufferEnd = _bigBuffer + sizeof(_bigBuffer);
uint16_t _big_buffer_size = sizeof(_bigBuffer);
uint8_t bInterfaceNumber = 0;
};
//--------------------------------------------------------------------------
class KeyboardController : public USBHIDInput, public BTHIDInput {
public:
typedef union {
struct {
uint8_t numLock : 1;
uint8_t capsLock : 1;
uint8_t scrollLock : 1;
uint8_t compose : 1;
uint8_t kana : 1;
uint8_t reserved : 3;
};
uint8_t byte;
} KBDLeds_t;
public:
KeyboardController(USBHost &host) { init(); }
KeyboardController(USBHost *host) { init(); }
// need their own versions as both USBDriver and USBHIDInput provide
uint16_t idVendor();
uint16_t idProduct();
const uint8_t *manufacturer();
const uint8_t *product();
const uint8_t *serialNumber();
operator bool() { return ((btdevice != nullptr) || (mydevice != nullptr)); }
// Main boot keyboard functions.
uint16_t getKey() { return keyCode; }
uint8_t getModifiers() { return modifiers_; }
uint8_t getOemKey() { return keyOEM_; }
void attachPress(void (*f)(int unicode)) { keyPressedFunction = f; }
void attachRelease(void (*f)(int unicode)) { keyReleasedFunction = f; }
void attachRawPress(void (*f)(uint8_t keycode)) { rawKeyPressedFunction = f; }
void attachRawRelease(void (*f)(uint8_t keycode)) { rawKeyReleasedFunction = f; }
void LEDS(uint8_t leds);
uint8_t LEDS() {return leds_.byte;}
void updateLEDS(void);
bool numLock() {return leds_.numLock;}
bool capsLock() {return leds_.capsLock;}
bool scrollLock() {return leds_.scrollLock;}
void numLock(bool f);
void capsLock(bool f);
void scrollLock(bool f);
// return battery level in percentage. 0xff implies we don't know.
uint8_t batteryLevel() {return battery_level_;}
// Added for extras information.
void attachExtrasPress(void (*f)(uint32_t top, uint16_t code)) { extrasKeyPressedFunction = f; }
void attachExtrasRelease(void (*f)(uint32_t top, uint16_t code)) { extrasKeyReleasedFunction = f; }
void forceBootProtocol();
void forceHIDProtocol();
enum {MAX_KEYS_DOWN = 4};
protected:
void init();
// Bluetooth data
virtual hidclaim_t claim_bluetooth(BluetoothConnection *btconnection, uint32_t bluetooth_class, uint8_t *remoteName, int type);
//virtual bool claim_bluetooth(BluetoothController *driver, uint32_t bluetooth_class, uint8_t *remoteName);
virtual bool process_bluetooth_HID_data(const uint8_t *data, uint16_t length);
virtual bool remoteNameComplete(const uint8_t *remoteName);
virtual void release_bluetooth();
virtual void connectionComplete(void);
virtual void sdp_command_completed (bool success);
protected: // HID functions for extra keyboard data.
virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
virtual void hid_input_data(uint32_t usage, int32_t value);
virtual void hid_input_end();
virtual void disconnect_collection(Device_t *dev);
virtual bool hid_process_in_data(const Transfer_t *transfer);
void process_boot_keyboard_format(const uint8_t *report, bool process_mod_keys);
virtual hidclaim_t bt_claim_collection(BluetoothConnection *btconnection, uint32_t bluetooth_class, uint32_t topusage);
virtual void bt_hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
virtual void bt_hid_input_data(uint32_t usage, int32_t value);
virtual void bt_hid_input_end();
virtual void bt_disconnect_collection(Device_t *dev);
private:
void update();
uint16_t convert_to_unicode(uint32_t mod, uint32_t key);
void key_press(uint32_t mod, uint32_t key);
void key_release(uint32_t mod, uint32_t key);
bool process_hid_keyboard_data(uint32_t usage, int32_t value);
void (*keyPressedFunction)(int unicode);
void (*keyReleasedFunction)(int unicode);
void (*rawKeyPressedFunction)(uint8_t keycode) = nullptr;
void (*rawKeyReleasedFunction)(uint8_t keycode) = nullptr;
Pipe_t *datapipe;
setup_t setup;
// Need two sets of structures to properly support some keyboards
// that do N key roll-over. They use the Boot report up to
// 6 keys down and then they go to other format for additional
// keys.
// Boot format
uint8_t report_[8];
uint8_t prev_report_[8];
// N Key reollover
uint8_t key_states_[16];
uint16_t keyCode;
uint8_t modifiers_ = 0;
uint8_t keyOEM_;
KBDLeds_t leds_ = {0};
// Added to process secondary HID data.
void (*extrasKeyPressedFunction)(uint32_t top, uint16_t code);
void (*extrasKeyReleasedFunction)(uint32_t top, uint16_t code);
uint32_t topusage_ = 0; // What top report am I processing?
uint32_t topusage_type_ = 0;
int lgmin_ = 0;
int lgmax_ = 0;
uint32_t topusage_index_ = 0;
uint8_t collections_claimed_ = 0;
bool keyboard_uses_boot_format_ = false;
volatile bool hid_input_begin_ = false;
volatile bool hid_input_data_ = false; // did we receive any valid data with report?
uint8_t battery_level_ = 0xff; // battery level percent 0xff is we don't know
uint8_t count_keys_down_ = 0;
uint16_t keys_down[MAX_KEYS_DOWN];
bool force_boot_protocol; // User or VID/PID said force boot protocol?
bool control_queued = false;
// keep back pointer for the three different op levels we claim
BluetoothController *btdriver_ = nullptr;
USBHIDParser *driver_[3] = {nullptr, nullptr, nullptr};
static bool s_forceHIDMode;
// Test probably temporary Bluetooth HID support object
//BTHIDSupport bthids_;
};
class MouseController : public USBHIDInput, public BTHIDInput {
public:
MouseController(USBHost &host) { init(); }
bool available() { return mouseEvent; }
void mouseDataClear();
uint8_t getButtons() { return buttons; }
int getMouseX() { return mouseX; }
int getMouseY() { return mouseY; }
int getWheel() { return wheel; }
int getWheelH() { return wheelH; }
protected:
virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
virtual void hid_input_data(uint32_t usage, int32_t value);
virtual void hid_input_end();
virtual void disconnect_collection(Device_t *dev);
// Bluetooth data
virtual hidclaim_t claim_bluetooth(BluetoothConnection *btconnection, uint32_t bluetooth_class, uint8_t *remoteName, int type);
//virtual bool claim_bluetooth(BluetoothController *driver, uint32_t bluetooth_class, uint8_t *remoteName);
virtual bool process_bluetooth_HID_data(const uint8_t *data, uint16_t length);
virtual void release_bluetooth();
virtual hidclaim_t bt_claim_collection(BluetoothConnection *btconnection, uint32_t bluetooth_class, uint32_t topusage);
virtual void bt_hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
virtual void bt_hid_input_data(uint32_t usage, int32_t value);
virtual void bt_hid_input_end();
virtual void bt_disconnect_collection(Device_t *dev);
private:
void init();
BluetoothController *btdriver_ = nullptr;
uint8_t collections_claimed = 0;
volatile bool mouseEvent = false;
volatile bool hid_input_begin_ = false;
uint8_t buttons = 0;
int mouseX = 0;
int mouseY = 0;
int wheel = 0;
int wheelH = 0;
};
//--------------------------------------------------------------------------
class DigitizerController : public USBHIDInput, public BTHIDInput {
public:
DigitizerController(USBHost &host) { init(); }
bool available() { return digitizerEvent; }
void digitizerDataClear();
uint8_t getButtons() { return buttons; }
int getMouseX() { return mouseX; }
int getMouseY() { return mouseY; }
int getWheel() { return wheel; }
int getWheelH() { return wheelH; }
int getAxis(uint32_t index) { return (index < (sizeof(digiAxes) / sizeof(digiAxes[0]))) ? digiAxes[index] : 0; }
protected:
virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
virtual void hid_input_data(uint32_t usage, int32_t value);
virtual void hid_input_end();
virtual void disconnect_collection(Device_t *dev);
private:
void init();
uint8_t collections_claimed = 0;
volatile bool digitizerEvent = false;
volatile bool hid_input_begin_ = false;
uint8_t buttons = 0;
int mouseX = 0;
int mouseY = 0;
int wheel = 0;
int wheelH = 0;
int digiAxes[16];
};
//--------------------------------------------------------------------------
class JoystickController : public USBDriver, public USBHIDInput, public BTHIDInput {
public:
JoystickController(USBHost &host) { init(); }
uint16_t idVendor();
uint16_t idProduct();
const uint8_t *manufacturer();
const uint8_t *product();
const uint8_t *serialNumber();