Cleaning up USB code, getting nearer to BBB mass storage.
[goodfet] / client / GoodFETMAXUSB.py
1 #!/usr/bin/env python
2 # GoodFET Client Library for Maxim USB Chips.
3
4 # (C) 2012 Travis Goodspeed <travis at radiantmachines.com>
5 #
6 # This code is being rewritten and refactored.  You've been warned!
7
8
9 import sys, time, string, cStringIO, struct, glob, os;
10
11 from GoodFET import GoodFET;
12
13 #Handy registers.
14 rEP0FIFO=0
15 rEP1OUTFIFO=1
16 rEP2INFIFO=2
17 rEP3INFIFO=3
18 rSUDFIFO=4
19 rEP0BC=5
20 rEP1OUTBC=6
21 rEP2INBC=7
22 rEP3INBC=8
23 rEPSTALLS=9
24 rCLRTOGS=10
25 rEPIRQ=11
26 rEPIEN=12
27 rUSBIRQ=13
28 rUSBIEN=14
29 rUSBCTL=15
30 rCPUCTL=16
31 rPINCTL=17
32 rREVISION=18
33 rFNADDR=19
34 rIOPINS=20
35 rIOPINS1=20  #Same as rIOPINS
36 rIOPINS2=21
37 rHIRQ=25
38 rHIEN=26
39 rMODE=27
40 rPERADDR=28
41 rHCTL=29
42 rHXFR=30
43 rHRSL=31
44
45 #Host mode registers.
46 rRCVFIFO =1
47 rSNDFIFO =2
48 rRCVBC   =6
49 rSNDBC   =7
50 rHIRQ    =25
51
52
53 # R11 EPIRQ register bits
54 bmSUDAVIRQ =0x20
55 bmIN3BAVIRQ =0x10
56 bmIN2BAVIRQ =0x08
57 bmOUT1DAVIRQ= 0x04
58 bmOUT0DAVIRQ= 0x02
59 bmIN0BAVIRQ =0x01
60
61 # R12 EPIEN register bits
62 bmSUDAVIE   =0x20
63 bmIN3BAVIE  =0x10
64 bmIN2BAVIE  =0x08
65 bmOUT1DAVIE =0x04
66 bmOUT0DAVIE =0x02
67 bmIN0BAVIE  =0x01
68
69
70
71
72 # ************************
73 # Standard USB Requests
74 SR_GET_STATUS           =0x00   # Get Status
75 SR_CLEAR_FEATURE        =0x01   # Clear Feature
76 SR_RESERVED             =0x02   # Reserved
77 SR_SET_FEATURE          =0x03   # Set Feature
78 SR_SET_ADDRESS          =0x05   # Set Address
79 SR_GET_DESCRIPTOR       =0x06   # Get Descriptor
80 SR_SET_DESCRIPTOR       =0x07   # Set Descriptor
81 SR_GET_CONFIGURATION    =0x08   # Get Configuration
82 SR_SET_CONFIGURATION    =0x09   # Set Configuration
83 SR_GET_INTERFACE        =0x0a   # Get Interface
84 SR_SET_INTERFACE        =0x0b   # Set Interface
85
86 # Get Descriptor codes  
87 GD_DEVICE               =0x01   # Get device descriptor: Device
88 GD_CONFIGURATION        =0x02   # Get device descriptor: Configuration
89 GD_STRING               =0x03   # Get device descriptor: String
90 GD_HID                  =0x21   # Get descriptor: HID
91 GD_REPORT               =0x22   # Get descriptor: Report
92
93 # SETUP packet header offsets
94 bmRequestType           =0
95 bRequest                =1
96 wValueL                 =2
97 wValueH                 =3
98 wIndexL                 =4
99 wIndexH                 =5
100 wLengthL                =6
101 wLengthH                =7
102
103 # HID bRequest values
104 GET_REPORT              =1
105 GET_IDLE                =2
106 GET_PROTOCOL            =3
107 SET_REPORT              =9
108 SET_IDLE                =0x0A
109 SET_PROTOCOL            =0x0B
110 INPUT_REPORT            =1
111
112 # PINCTL bits
113 bmEP3INAK   =0x80
114 bmEP2INAK   =0x40
115 bmEP1INAK   =0x20
116 bmFDUPSPI   =0x10
117 bmINTLEVEL  =0x08
118 bmPOSINT    =0x04
119 bmGPXB      =0x02
120 bmGPXA      =0x01
121
122 # rUSBCTL bits
123 bmHOSCSTEN  =0x80
124 bmVBGATE    =0x40
125 bmCHIPRES   =0x20
126 bmPWRDOWN   =0x10
127 bmCONNECT   =0x08
128 bmSIGRWU    =0x04
129
130 # USBIRQ bits
131 bmURESDNIRQ =0x80
132 bmVBUSIRQ   =0x40
133 bmNOVBUSIRQ =0x20
134 bmSUSPIRQ   =0x10
135 bmURESIRQ   =0x08
136 bmBUSACTIRQ =0x04
137 bmRWUDNIRQ  =0x02
138 bmOSCOKIRQ  =0x01
139
140 # MODE bits
141 bmHOST          =0x01
142 bmLOWSPEED      =0x02
143 bmHUBPRE        =0x04
144 bmSOFKAENAB     =0x08
145 bmSEPIRQ        =0x10
146 bmDELAYISO      =0x20
147 bmDMPULLDN      =0x40
148 bmDPPULLDN      =0x80
149
150 # PERADDR/HCTL bits
151 bmBUSRST        =0x01
152 bmFRMRST        =0x02
153 bmSAMPLEBUS     =0x04
154 bmSIGRSM        =0x08
155 bmRCVTOG0       =0x10
156 bmRCVTOG1       =0x20
157 bmSNDTOG0       =0x40
158 bmSNDTOG1       =0x80
159
160 # rHXFR bits
161 # Host XFR token values for writing the HXFR register (R30).
162 # OR this bit field with the endpoint number in bits 3:0
163 tokSETUP  =0x10  # HS=0, ISO=0, OUTNIN=0, SETUP=1
164 tokIN     =0x00  # HS=0, ISO=0, OUTNIN=0, SETUP=0
165 tokOUT    =0x20  # HS=0, ISO=0, OUTNIN=1, SETUP=0
166 tokINHS   =0x80  # HS=1, ISO=0, OUTNIN=0, SETUP=0
167 tokOUTHS  =0xA0  # HS=1, ISO=0, OUTNIN=1, SETUP=0 
168 tokISOIN  =0x40  # HS=0, ISO=1, OUTNIN=0, SETUP=0
169 tokISOOUT =0x60  # HS=0, ISO=1, OUTNIN=1, SETUP=0
170
171 # rRSL bits
172 bmRCVTOGRD   =0x10
173 bmSNDTOGRD   =0x20
174 bmKSTATUS    =0x40
175 bmJSTATUS    =0x80
176 # Host error result codes, the 4 LSB's in the HRSL register.
177 hrSUCCESS   =0x00
178 hrBUSY      =0x01
179 hrBADREQ    =0x02
180 hrUNDEF     =0x03
181 hrNAK       =0x04
182 hrSTALL     =0x05
183 hrTOGERR    =0x06
184 hrWRONGPID  =0x07
185 hrBADBC     =0x08
186 hrPIDERR    =0x09
187 hrPKTERR    =0x0A
188 hrCRCERR    =0x0B
189 hrKERR      =0x0C
190 hrJERR      =0x0D
191 hrTIMEOUT   =0x0E
192 hrBABBLE    =0x0F
193
194 # HIRQ bits
195 bmBUSEVENTIRQ   =0x01   # indicates BUS Reset Done or BUS Resume     
196 bmRWUIRQ        =0x02
197 bmRCVDAVIRQ     =0x04
198 bmSNDBAVIRQ     =0x08
199 bmSUSDNIRQ      =0x10
200 bmCONDETIRQ     =0x20
201 bmFRAMEIRQ      =0x40
202 bmHXFRDNIRQ     =0x80
203
204 class GoodFETMAXUSB(GoodFET):
205     MAXUSBAPP=0x40;
206     
207     def service_irqs(self):
208         """Handle USB interrupt events."""
209         epirq=self.rreg(rEPIRQ);
210         usbirq=self.rreg(rUSBIRQ);
211         
212         
213         # Note *very* well that these interrupts are handled in order.
214         # You might need to alter the order or swap the elif
215         # statements for if statements.
216         
217         #Are we being asked for setup data?
218         if(epirq&bmSUDAVIRQ): #Setup Data Requested
219             self.wreg(rEPIRQ,bmSUDAVIRQ); #Clear the bit
220             self.do_SETUP();
221         if(epirq&bmOUT1DAVIRQ): #OUT1-OUT packet
222             self.do_OUT1();
223             self.wregAS(rEPIRQ,bmOUT1DAVIRQ); #Clear the bit *AFTER* servicing.
224         if(epirq&bmIN3BAVIRQ): #IN3-IN packet
225             self.do_IN3();
226             self.wreg(rEPIRQ,bmIN3BAVIRQ); #Clear the bit
227         if(epirq&bmIN2BAVIRQ): #IN2 packet
228             self.do_IN2();
229             self.wreg(rEPIRQ,bmIN2BAVIRQ); #Clear the bit
230         #else:
231         #    print "No idea how to service this IRQ: %02x" % epirq;
232     def do_IN2(self):
233         """Overload this."""
234     def do_IN3(self):
235         """Overload this."""
236     def do_OUT1(self):
237         """Overload this."""
238         print "Ignoring an OUT1 interrupt.";
239     def setup2str(self,SUD):
240         """Converts the header of a setup packet to a string."""
241         return "bmRequestType=0x%02x, bRequest=0x%02x, wValue=0x%04x, wIndex=0x%04x, wLength=0x%04x" % (
242                 ord(SUD[0]), ord(SUD[1]),
243                 ord(SUD[2])+(ord(SUD[3])<<8),
244                 ord(SUD[4])+(ord(SUD[5])<<8),
245                 ord(SUD[6])+(ord(SUD[7])<<8)
246                 );
247     
248     def MAXUSBsetup(self):
249         """Move the FET into the MAXUSB application."""
250         self.writecmd(self.MAXUSBAPP,0x10,0,self.data); #MAXUSB/SETUP
251         print "Connected to MAX342x Rev. %x" % (self.rreg(rREVISION));
252         self.wreg(rPINCTL,0x18); #Set duplex and negative INT level.
253         
254     def MAXUSBtrans8(self,byte):
255         """Read and write 8 bits by MAXUSB."""
256         data=self.MAXUSBtrans([byte]);
257         return ord(data[0]);
258     
259     def MAXUSBtrans(self,data):
260         """Exchange data by MAXUSB."""
261         self.data=data;
262         self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
263         return self.data;
264
265     def rreg(self,reg):
266         """Peek 8 bits from a register."""
267         data=[reg<<3,0];
268         self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
269         return ord(self.data[1]);
270     def rregAS(self,reg):
271         """Peek 8 bits from a register, setting AS."""
272         data=[(reg<<3)|1,0];
273         self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
274         return ord(self.data[1]);
275     def wreg(self,reg,value):
276         """Poke 8 bits into a register."""
277         data=[(reg<<3)|2,value];
278         self.writecmd(self.MAXUSBAPP,0x00,len(data),data);        
279         return value;
280     def wregAS(self,reg,value):
281         """Poke 8 bits into a register, setting AS."""
282         data=[(reg<<3)|3,value];
283         self.writecmd(self.MAXUSBAPP,0x00,len(data),data);        
284         return value;
285     def readbytes(self,reg,length):
286         """Peek some bytes from a register."""
287         data=[(reg<<3)]+range(0,length);
288         self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
289         toret=self.data[1:len(self.data)];
290         ashex="";
291         for foo in toret:
292             ashex=ashex+(" %02x"%ord(foo));
293         print "GET %02x==%s" % (reg,ashex);
294         return toret;
295     def readbytesAS(self,reg,length):
296         """Peek some bytes from a register, acking prior transfer."""
297         data=[(reg<<3)|1]+range(0,length);
298         self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
299         toret=self.data[1:len(self.data)];
300         ashex="";
301         for foo in toret:
302             ashex=ashex+(" %02x"%ord(foo));
303         print "GET %02x==%s" % (reg,ashex);
304         return toret;
305     def ctl_write_nd(self,request):
306         """Control Write with no data stage.  Assumes PERADDR is set
307         and the SUDFIFO contains the 8 setup bytes.  Returns with
308         result code = HRSLT[3:0] (HRSL register).  If there is an
309         error, the 4MSBits of the returned value indicate the stage 1
310         or 2."""
311         
312         # 1. Send the SETUP token and 8 setup bytes. 
313         # Should ACK immediately.
314         self.writebytes(rSUDFIFO,request);
315         resultcode=self.send_packet(tokSETUP,0); #SETUP packet to EP0.
316         if resultcode: return resultcode;
317         
318         # 2. No data stage, so the last operation is to send an IN
319         # token to the peripheral as the STATUS (handhsake) stage of
320         # this control transfer.  We should get NAK or the DATA1 PID.
321         # When we get back to the DATA1 PID the 3421 automatically
322         # sends the closing NAK.
323         resultcode=self.send_packet(tokINHS,0); #Function takes care of retries.
324         if resultcode: return resultcode;
325         
326         return 0;
327         
328         
329     def ctl_read(self,request):
330         """Control read transfer, used in Host mode."""
331         resultcode=0;
332         bytes_to_read=request[6]+256*request[7];
333         
334         ##SETUP packet
335         self.writebytes(rSUDFIFO,request);     #Load the FIFO
336         resultcode=self.send_packet(tokSETUP,0); #SETUP packet to EP0
337         if resultcode:
338             print "Failed to get ACK on SETUP request in ctl_read()."
339             return resultcode;
340         
341         self.wreg(rHCTL,bmRCVTOG1);              #FIRST data packet in CTL transfer uses DATA1 toggle.
342         resultcode=self.IN_Transfer(0,bytes_to_read);
343         if resultcode:
344             print "Failed on IN Transfer in ctl_read()";
345             return resultcode;
346         
347         self.IN_nak_count=self.nak_count;
348         
349         #The OUT status stage.
350         resultcode=self.send_packet(tokOUTHS,0);
351         if resultcode:
352             print "Failed on OUT Status stage in ctl_read()";
353             return resultcode;
354         
355         return 0; #Success
356     
357     xfrdata=[]; #Ugly variable used only by a few functions.  FIXME
358     def IN_Transfer(self,endpoint,INbytes):
359         """Does an IN transfer to an endpoint, used for Host mode."""
360         xfrsize=INbytes;
361         xfrlen=0;
362         self.xfrdata=[];
363         
364         while 1:
365             resultcode=self.send_packet(tokIN,endpoint); #IN packet to EP. NAKS taken care of.
366             if resultcode: return resultcode;
367             
368             pktsize=self.rreg(rRCVBC); #Numer of RXed bytes.
369             
370             #Very innefficient, move this to C if performance is needed.
371             for j in range(0,pktsize):
372                 self.xfrdata=self.xfrdata+[self.rreg(rRCVFIFO)];
373             xfrsize=self.xfrdata[0];
374             self.wreg(rHIRQ,bmRCVDAVIRQ); #Clear IRQ
375             xfrlen=xfrlen+pktsize; #Add byte count to total transfer length.
376             
377             print "%i / %i" % (xfrlen,xfrsize)
378             
379             #Packet is complete if:
380             # 1. The device sent a short packet, <maxPacketSize
381             # 2. INbytes have been transfered.
382             if (pktsize<self.maxPacketSize) or (xfrlen>=xfrsize):
383                 self.last_transfer_size=xfrlen;
384                 ashex="";
385                 for foo in self.xfrdata:
386                     ashex=ashex+(" %02x"%foo);
387                 print "INPACKET EP%i==%s (0x%02x bytes remain)" % (endpoint,ashex,xfrsize);
388                 return resultcode;
389
390     RETRY_LIMIT=3;
391     NAK_LIMIT=300;
392     def send_packet(self,token,endpoint):
393         """Send a packet to an endpoint as the Host, taking care of NAKs.
394         Don't use this for device code."""
395         self.retry_count=0;
396         self.nak_count=0;
397         
398         #Repeat until NAK_LIMIT or RETRY_LIMIT is reached.
399         while self.nak_count<self.NAK_LIMIT and self.retry_count<self.RETRY_LIMIT:
400             self.wreg(rHXFR,(token|endpoint)); #launch the transfer
401             while not (self.rreg(rHIRQ) & bmHXFRDNIRQ):
402                 # wait for the completion IRQ
403                 pass;
404             self.wreg(rHIRQ,bmHXFRDNIRQ);           #Clear IRQ
405             resultcode = (self.rreg(rHRSL) & 0x0F); # get the result
406             if (resultcode==hrNAK):
407                 self.nak_count=self.nak_count+1;
408             elif (resultcode==hrTIMEOUT):
409                 self.retry_count=self.retry_count+1;
410             else:
411                 #Success!
412                 return resultcode;
413         return resultcode;
414             
415     def writebytes(self,reg,tosend):
416         """Poke some bytes into a register."""
417         data="";
418         if type(tosend)==str:
419             data=chr((reg<<3)|3)+tosend;
420             print "PUT %02x:=%s (0x%02x bytes)" % (reg,tosend,len(data))
421         else:
422             data=[(reg<<3)|3]+tosend;
423             ashex="";
424             for foo in tosend:
425                 ashex=ashex+(" %02x"%foo);
426             print "PUT %02x:=%s (0x%02x bytes)" % (reg,ashex,len(data))
427         self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
428     def usb_connect(self):
429         """Connect the USB port."""
430         
431         #disconnect D+ pullup if host turns off VBUS
432         self.wreg(rUSBCTL,bmVBGATE|bmCONNECT);
433     def usb_disconnect(self):
434         """Disconnect the USB port."""
435         self.wreg(rUSBCTL,bmVBGATE);
436     def STALL_EP0(self,SUD=None):
437         """Stall for an unknown SETUP event."""
438         if SUD==None:
439             print "Stalling EP0.";
440         else:
441             print "Stalling EPO for %s" % self.setup2str(SUD);
442         self.wreg(rEPSTALLS,0x23); #All three stall bits.
443     def SETBIT(self,reg,val):
444         """Set a bit in a register."""
445         self.wreg(reg,self.rreg(reg)|val);
446     def vbus_on(self):
447         """Turn on the target device."""
448         self.wreg(rIOPINS2,(self.rreg(rIOPINS2)|0x08));
449     def vbus_off(self):
450         """Turn off the target device's power."""
451         self.wreg(rIOPINS2,0x00);
452     def reset_host(self):
453         """Resets the chip into host mode."""
454         self.wreg(rUSBCTL,bmCHIPRES); #Stop the oscillator.
455         self.wreg(rUSBCTL,0x00);      #restart it.
456         while self.rreg(rUSBIRQ)&bmOSCOKIRQ:
457             #Hang until the PLL stabilizes.
458             pass;
459
460 class GoodFETMAXUSBHost(GoodFETMAXUSB):
461     """This is a class for implemented a minimal USB host.
462     It's intended for fuzzing, rather than for daily use."""
463     def hostinit(self):
464         """Initialize the MAX3421 as a USB Host."""
465         self.usb_connect();
466         self.wreg(rPINCTL,(bmFDUPSPI|bmPOSINT));
467         self.reset_host();
468         self.vbus_off();
469         time.sleep(0.2);
470         self.vbus_on();
471         
472         #self.hostrun();
473     def hostrun(self):
474         """Run as a minimal host and dump the config tables."""
475         while 1:
476             self.detect_device();
477             time.sleep(0.2);
478             self.enumerate_device();
479             self.wait_for_disconnect();
480     def detect_device(self):
481         """Waits for a device to be inserted and then returns."""
482         busstate=0;
483         
484         #Activate host mode and turn on 15K pulldown resistors on D+ and D-.
485         self.wreg(rMODE,(bmDPPULLDN|bmDMPULLDN|bmHOST));
486         #Clear connection detect IRQ.
487         self.wreg(rHIRQ,bmCONDETIRQ);
488         
489         print "Waiting for a device connection.";
490         while busstate==0:
491             self.wreg(rHCTL,bmSAMPLEBUS); #Update JSTATUS and KSTATUS bits.
492             busstate=self.rreg(rHRSL) & (bmJSTATUS|bmKSTATUS);
493             
494         if busstate==bmJSTATUS:
495             print "Detected Full-Speed Device.";
496             self.wreg(rMODE,(bmDPPULLDN|bmDMPULLDN|bmHOST|bmSOFKAENAB));
497         elif busstate==bmKSTATUS:
498             print "Detected Low-Speed Device.";
499             self.wreg(rMODE,(bmDPPULLDN|bmDMPULLDN|bmHOST|bmLOWSPEED|bmSOFKAENAB));
500         else:
501             print "Not sure whether this is Full-Speed or Low-Speed.  Please investigate.";
502     def wait_for_disconnect(self):
503         """Wait for a device to be disconnected."""
504         print "Waiting for a device disconnect.";
505         
506         self.wreg(rHIRQ,bmCONDETIRQ); #Clear disconnect IRQ
507         while not (self.rreg(rHIRQ) & bmCONDETIRQ):
508             #Wait for IRQ to change.
509             pass;
510         
511         #Turn off markers.
512         self.wreg(rMODE,bmDPPULLDN|bmDMPULLDN|bmHOST);
513         print "Device disconnected.";
514         self.wreg(rIOPINS2,(self.rreg(rIOPINS2) & ~0x04)); #HL1_OFF
515         self.wreg(rIOPINS1,(self.rreg(rIOPINS1) & ~0x02)); #HL4_OFF
516
517     def enumerate_device(self):
518         """Enumerates a device on the present port."""
519         
520         Set_Address_to_7 = [0x00,0x05,0x07,0x00,0x00,0x00,0x00,0x00];
521         Get_Descriptor_Device = [0x80,0x06,0x00,0x01,0x00,0x00,0x00,0x00]; #len filled in
522         Get_Descriptor_Config = [0x80,0x06,0x00,0x02,0x00,0x00,0x00,0x00];
523         
524         
525         print "Issuing USB bus reset.";
526         self.wreg(rHCTL,bmBUSRST);
527         while self.rreg(rHCTL) & bmBUSRST:
528             #Wait for reset to complete.
529             pass;
530         
531         time.sleep(0.2);
532         
533         #Get the device descriptor.
534         self.wreg(rPERADDR,0); #First request to address 0.
535         self.maxPacketSize=8; #Only safe value for first check.
536         Get_Descriptor_Device[6]=8; # wLengthL
537         Get_Descriptor_Device[7]=0; # wLengthH
538         
539         print "Fetching 8 bytes of Device Descriptor.";
540         self.ctl_read(Get_Descriptor_Device); # Get device descriptor into self.xfrdata;
541         self.maxPacketSize=self.xfrdata[7];
542         print "EP0 maxPacketSize is %02i bytes." % self.maxPacketSize;
543         
544         # Issue another USB bus reset
545         print "Resetting the bus again."
546         self.wreg(rHCTL,bmBUSRST);
547         while self.rreg(rHCTL) & bmBUSRST:
548             #Wait for reset to complete.
549             pass;
550         time.sleep(0.2);
551         
552         # Set_Address to 7 (Note: this request goes to address 0, already set in PERADDR register).
553         print "Setting address to 0x07";
554         HR = self.ctl_write_nd(Set_Address_to_7);   # CTL-Write, no data stage
555         #if(print_error(HR)) return;
556         
557         time.sleep(0.002);           # Device gets 2 msec recovery time
558         self.wreg(rPERADDR,7);       # now all transfers go to addr 7
559         
560         
561         #Get the device descriptor at the assigned address.
562         Get_Descriptor_Device[6]=0x12; #Fill in real descriptor length.
563         print "Fetching Device Descriptor."
564         self.ctl_read(Get_Descriptor_Device); #Result in self.xfrdata;
565         
566         self.descriptor=self.xfrdata;
567         self.VID        = self.xfrdata[8] + 256*self.xfrdata[9];
568         self.PID        = self.xfrdata[10]+ 256*self.xfrdata[11];
569         iMFG    = self.xfrdata[14];
570         iPROD   = self.xfrdata[15];
571         iSERIAL = self.xfrdata[16];
572         
573         self.manufacturer=self.getDescriptorString(iMFG);
574         self.product=self.getDescriptorString(iPROD);
575         self.serial=self.getDescriptorString(iSERIAL);
576         
577         self.printstrings();
578         
579     def printstrings(self):
580         print "Vendor  ID is %04x." % self.VID;
581         print "Product ID is %04x." % self.PID;
582         print "Manufacturer: %s" % self.manufacturer;
583         print "Product:      %s" % self.product;
584         print "Serial:       %s" % self.serial;
585         
586     def getDescriptorString(self, index):
587         """Grabs a string from the descriptor string table."""
588         # Get_Descriptor-String template. Code fills in idx at str[2].
589         Get_Descriptor_String = [0x80,0x06,index,0x03,0x00,0x00,0x40,0x00];
590         
591         if index==0: return "MISSING STRING";
592         
593         status=self.ctl_read(Get_Descriptor_String);
594         if status: return None;
595         
596         #Since we've got a string
597         toret="";
598         for c in self.xfrdata[2:len(self.xfrdata)]:
599             if c>0: toret=toret+chr(c);
600         return toret;
601         
602 class GoodFETMAXUSBHID(GoodFETMAXUSB):
603     """This is an example HID keyboard driver, loosely based on the
604     MAX3420 examples."""
605     def hidinit(self):
606         """Initialize a USB HID device."""
607         self.usb_disconnect();
608         self.usb_connect();
609         
610         self.hidrun();
611         
612     def hidrun(self):
613         """Main loop of the USB HID emulator."""
614         print "Starting a HID device.  This won't return.";
615         while 1:
616             self.service_irqs();
617     def do_SETUP(self):
618         """Handle USB Enumeration"""
619         
620         #Grab the SETUP packet from the buffer.
621         SUD=self.readbytes(rSUDFIFO,8);
622         
623         #Parse the SETUP packet
624         print "Handling a setup packet of %s" % self.setup2str(SUD);
625         
626         setuptype=(ord(SUD[bmRequestType])&0x60);
627         if setuptype==0x00:
628             self.std_request(SUD);
629         elif setuptype==0x20:
630             self.class_request(SUD);
631         elif setuptype==0x40:
632             self.vendor_request(SUD);
633         else:
634             print "Unknown request type 0x%02x." % ord(SUD[bmRequestType])
635             self.STALL_EP0(SUD);
636     def class_request(self,SUD):
637         """Handle a class request."""
638         print "Stalling a class request.";
639         self.STALL_EP0(SUD);
640     def vendor_request(self,SUD):
641         print "Stalling a vendor request.";
642         self.STALL_EP0(SUD);
643     def std_request(self,SUD):
644         """Handles a standard setup request."""
645         setuptype=ord(SUD[bRequest]);
646         if setuptype==SR_GET_DESCRIPTOR: self.send_descriptor(SUD);
647         #elif setuptype==SR_SET_FEATURE:
648         #    self.rregAS(rFNADDR);
649         #    # self.feature(1);
650         elif setuptype==SR_SET_CONFIGURATION: self.set_configuration(SUD);
651         elif setuptype==SR_GET_STATUS: self.get_status(SUD);
652         elif setuptype==SR_SET_ADDRESS: self.rregAS(rFNADDR);
653         elif setuptype==SR_GET_INTERFACE: self.get_interface(SUD);
654         else:
655             print "Stalling Unknown standard setup request type %02x" % setuptype;
656             self.STALL_EP0(SUD);
657     
658     def get_interface(self,SUD):
659         """Handles a setup request for SR_GET_INTERFACE."""
660         if ord(SUD[wIndexL]==0):
661             self.wreg(rEP0FIFO,0);
662             self.wregAS(rEP0BC,1);
663         else:
664             self.STALL_EP0(SUD);
665     
666 #Device Descriptor
667     DD=[0x12,                   # bLength = 18d
668         0x01,                   # bDescriptorType = Device (1)
669         0x00,0x01,              # bcdUSB(L/H) USB spec rev (BCD)
670         0x00,0x00,0x00,         # bDeviceClass, bDeviceSubClass, bDeviceProtocol
671         0x40,                   # bMaxPacketSize0 EP0 is 64 bytes
672         0x6A,0x0B,              # idVendor(L/H)--Maxim is 0B6A
673         0x46,0x53,              # idProduct(L/H)--5346
674         0x34,0x12,              # bcdDevice--1234
675         1,2,3,                  # iManufacturer, iProduct, iSerialNumber
676         1];
677 #Configuration Descriptor
678     CD=[0x09,                   # bLength
679         0x02,                   # bDescriptorType = Config
680         0x22,0x00,              # wTotalLength(L/H) = 34 bytes
681         0x01,                   # bNumInterfaces
682         0x01,                   # bConfigValue
683         0x00,                   # iConfiguration
684         0xE0,                   # bmAttributes. b7=1 b6=self-powered b5=RWU supported
685         0x01,                   # MaxPower is 2 ma
686 # INTERFACE Descriptor
687         0x09,                   # length = 9
688         0x04,                   # type = IF
689         0x00,                   # IF #0
690         0x00,                   # bAlternate Setting
691         0x01,                   # bNum Endpoints
692         0x03,                   # bInterfaceClass = HID
693         0x00,0x00,              # bInterfaceSubClass, bInterfaceProtocol
694         0x00,                   # iInterface
695 # HID Descriptor--It's at CD[18]
696         0x09,                   # bLength
697         0x21,                   # bDescriptorType = HID
698         0x10,0x01,              # bcdHID(L/H) Rev 1.1
699         0x00,                   # bCountryCode (none)
700         0x01,                   # bNumDescriptors (one report descriptor)
701         0x22,                   # bDescriptorType       (report)
702         43,0,                   # CD[25]: wDescriptorLength(L/H) (report descriptor size is 43 bytes)
703 # Endpoint Descriptor
704         0x07,                   # bLength
705         0x05,                   # bDescriptorType (Endpoint)
706         0x83,                   # bEndpointAddress (EP3-IN)             
707         0x03,                   # bmAttributes  (interrupt)
708         64,0,                   # wMaxPacketSize (64)
709         10];
710     strDesc=[
711 # STRING descriptor 0--Language string
712 "\x04\x03\x09\x04",
713 # [
714 #         0x04,                 # bLength
715 #       0x03,                   # bDescriptorType = string
716 #       0x09,0x04               # wLANGID(L/H) = English-United Sates
717 # ],
718 # STRING descriptor 1--Manufacturer ID
719 "\x0c\x03M\x00a\x00x\x00i\x00m\x00",
720 # [
721 #         12,                   # bLength
722 #       0x03,                   # bDescriptorType = string
723 #       'M',0,'a',0,'x',0,'i',0,'m',0 # text in Unicode
724 # ], 
725 # STRING descriptor 2 - Product ID
726 "\x18\x03M\x00A\x00X\x003\x004\x002\x000\x00E\x00 \x00E\x00n\x00u\x00m\x00 \x00C\x00o\x00d\x00e\x00",
727 # [     24,                     # bLength
728 #       0x03,                   # bDescriptorType = string
729 #       'M',0,'A',0,'X',0,'3',0,'4',0,'2',0,'0',0,'E',0,' ',0,
730 #         'E',0,'n',0,'u',0,'m',0,' ',0,'C',0,'o',0,'d',0,'e',0
731 # ],
732
733
734 # STRING descriptor 3 - Serial Number ID
735 "\x14\x03S\x00/\x00N\x00 \x003\x004\x002\x000\x00E\x00"
736 # [       20,                   # bLength
737 #       0x03,                   # bDescriptorType = string
738 #       'S',0,                          
739 #       '/',0,
740 #       'N',0,
741 #       ' ',0,
742 #       '3',0,
743 #       '4',0,
744 #       '2',0,
745 #       '0',0,
746 #         'E',0,
747 # ]
748 ];
749     RepD=[
750         0x05,0x01,              # Usage Page (generic desktop)
751         0x09,0x06,              # Usage (keyboard)
752         0xA1,0x01,              # Collection
753         0x05,0x07,              #   Usage Page 7 (keyboard/keypad)
754         0x19,0xE0,              #   Usage Minimum = 224
755         0x29,0xE7,              #   Usage Maximum = 231
756         0x15,0x00,              #   Logical Minimum = 0
757         0x25,0x01,              #   Logical Maximum = 1
758         0x75,0x01,              #   Report Size = 1
759         0x95,0x08,              #   Report Count = 8
760         0x81,0x02,              #  Input(Data,Variable,Absolute)
761         0x95,0x01,              #   Report Count = 1
762         0x75,0x08,              #   Report Size = 8
763         0x81,0x01,              #  Input(Constant)
764         0x19,0x00,              #   Usage Minimum = 0
765         0x29,0x65,              #   Usage Maximum = 101
766         0x15,0x00,              #   Logical Minimum = 0,
767         0x25,0x65,              #   Logical Maximum = 101
768         0x75,0x08,              #   Report Size = 8
769         0x95,0x01,              #   Report Count = 1
770         0x81,0x00,              #  Input(Data,Variable,Array)
771         0xC0]
772     def send_descriptor(self,SUD):
773         """Send the USB descriptors based upon the setup data."""
774         desclen=0;
775         reqlen=ord(SUD[wLengthL])+256*ord(SUD[wLengthH]); #16-bit length
776         desctype=ord(SUD[wValueH]);
777         
778         if desctype==GD_DEVICE:
779             desclen=self.DD[0];
780             ddata=self.DD;
781         elif desctype==GD_CONFIGURATION:
782             desclen=self.CD[2];
783             ddata=self.CD;
784         elif desctype==GD_STRING:
785             desclen=self.strDesc[ord(SUD[wValueL])][0];
786             ddata=self.strDesc[ord(SUD[wValueL])];
787         elif desctype==GD_REPORT:
788             desclen=self.CD[25];
789             ddata=self.RepD;
790         
791         #TODO Configuration, String, Hid, and Report
792         
793         if desclen>0:
794             sendlen=min(reqlen,desclen);
795             self.writebytes(rEP0FIFO,ddata);
796             self.wregAS(rEP0BC,sendlen);
797         else:
798             print "Stalling in send_descriptor() for lack of handler for %02x." % desctype;
799             self.STALL_EP0(SUD);
800     def set_configuration(self,SUD):
801         """Set the configuration."""
802         bmSUSPIE=0x10;
803         configval=ord(SUD[wValueL]);
804         if(configval>0):
805             self.SETBIT(rUSBIEN,bmSUSPIE);
806         self.rregAS(rFNADDR);
807     def get_status(self,SUD):
808         """Get the USB Setup Status."""
809         testbyte=ord(SUD[bmRequestType])
810         
811         #Toward Device
812         if testbyte==0x80:
813             self.wreg(rEP0FIFO,0x03); #Enable RWU and self-powered
814             self.wreg(rEP0FIFO,0x00); #Second byte is always zero.
815             self.wregAS(rEP0BC,2);    #Load byte count, arm transfer, and ack CTL.
816         #Toward Interface
817         elif testbyte==0x81:
818             self.wreg(rEP0FIFO,0x00);
819             self.wreg(rEP0FIFO,0x00); #Second byte is always zero.
820             self.wregAS(rEP0BC,2);
821         #Toward Endpoint
822         elif testbyte==0x82:
823             if(ord(SUD[wIndexL])==0x83):
824                 self.wreg(rEP0FIFO,0x01); #Stall EP3
825                 self.wreg(rEP0FIFO,0x00); #Second byte is always zero.
826                 self.wregAS(rEP0BC,2);
827             else:
828                 self.STALL_EP0(SUD);
829         else:
830             self.STALL_EP0(SUD);
831
832     
833     
834     typephase=0;
835     typestring="                      Python does USB HID!";
836     typepos=0;
837     
838     def asc2hid(self,ascii):
839         """Translate ASCII to an USB keycode."""
840         a=ascii;
841         if a>='a' and a<='z':
842             return ord(a)-ord('a')+4;
843         elif a>='A' and a<='Z':
844             return ord(a)-ord('A')+4;
845         elif a==' ':
846             return 0x2C; #space
847         else:
848             return 0; #key-up
849     def type_IN3(self):
850         """Type next letter in buffer."""
851         if self.typepos>=len(self.typestring):
852             self.typeletter(0);
853         elif self.typephase==0:
854             self.typephase=1;
855             self.typeletter(0);
856         else:
857             typephase=0;
858             self.typeletter(self.typestring[self.typepos]);
859             self.typepos=self.typepos+1;
860         return;
861     def typeletter(self,key):
862         """Type a letter on IN3.  Zero for keyup."""
863         #if type(key)==str: key=ord(key);
864         #Send a key-up.
865         self.wreg(rEP3INFIFO,0);
866         self.wreg(rEP3INFIFO,0);
867         self.wreg(rEP3INFIFO,self.asc2hid(key));
868         self.wreg(rEP3INBC,3);
869     def do_IN3(self):
870         """Handle IN3 event."""
871         #Don't bother clearing interrupt flag, that's done by sending the reply.
872         self.type_IN3();
873