Mass storage emulation now works well enough to emulate a readable, mountable disk.
[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     usbverbose=True;
207     
208     def service_irqs(self):
209         """Handle USB interrupt events."""
210         epirq=self.rreg(rEPIRQ);
211         usbirq=self.rreg(rUSBIRQ);
212         
213         
214         #Are we being asked for setup data?
215         if(epirq&bmSUDAVIRQ): #Setup Data Requested
216             self.wreg(rEPIRQ,bmSUDAVIRQ); #Clear the bit
217             self.do_SETUP();
218         if(epirq&bmOUT1DAVIRQ): #OUT1-OUT packet
219             self.do_OUT1();
220             self.wreg(rEPIRQ,bmOUT1DAVIRQ); #Clear the bit *AFTER* servicing.
221         if(epirq&bmIN3BAVIRQ): #IN3-IN packet
222             self.do_IN3();
223             #self.wreg(rEPIRQ,bmIN3BAVIRQ); #Clear the bit
224         if(epirq&bmIN2BAVIRQ): #IN2 packet
225             self.do_IN2();
226             #self.wreg(rEPIRQ,bmIN2BAVIRQ); #Clear the bit
227         #else:
228         #    print "No idea how to service this IRQ: %02x" % epirq;
229     def do_IN2(self):
230         """Overload this."""
231     def do_IN3(self):
232         """Overload this."""
233     def do_OUT1(self):
234         """Overload this."""
235         if self.usbverbose: print "Ignoring an OUT1 interrupt.";
236     def setup2str(self,SUD):
237         """Converts the header of a setup packet to a string."""
238         return "bmRequestType=0x%02x, bRequest=0x%02x, wValue=0x%04x, wIndex=0x%04x, wLength=0x%04x" % (
239                 ord(SUD[0]), ord(SUD[1]),
240                 ord(SUD[2])+(ord(SUD[3])<<8),
241                 ord(SUD[4])+(ord(SUD[5])<<8),
242                 ord(SUD[6])+(ord(SUD[7])<<8)
243                 );
244     
245     def MAXUSBsetup(self):
246         """Move the FET into the MAXUSB application."""
247         self.writecmd(self.MAXUSBAPP,0x10,0,self.data); #MAXUSB/SETUP
248         print "Connected to MAX342x Rev. %x" % (self.rreg(rREVISION));
249         self.wreg(rPINCTL,0x18); #Set duplex and negative INT level.
250         
251     def MAXUSBtrans8(self,byte):
252         """Read and write 8 bits by MAXUSB."""
253         data=self.MAXUSBtrans([byte]);
254         return ord(data[0]);
255     
256     def MAXUSBtrans(self,data):
257         """Exchange data by MAXUSB."""
258         self.data=data;
259         self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
260         return self.data;
261
262     def rreg(self,reg):
263         """Peek 8 bits from a register."""
264         data=[reg<<3,0];
265         self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
266         return ord(self.data[1]);
267     def rregAS(self,reg):
268         """Peek 8 bits from a register, setting AS."""
269         data=[(reg<<3)|1,0];
270         self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
271         return ord(self.data[1]);
272     def wreg(self,reg,value):
273         """Poke 8 bits into a register."""
274         data=[(reg<<3)|2,value];
275         self.writecmd(self.MAXUSBAPP,0x00,len(data),data);        
276         return value;
277     def wregAS(self,reg,value):
278         """Poke 8 bits into a register, setting AS."""
279         data=[(reg<<3)|3,value];
280         self.writecmd(self.MAXUSBAPP,0x00,len(data),data);        
281         return value;
282     def readbytes(self,reg,length):
283         """Peek some bytes from a register."""
284         data=[(reg<<3)]+range(0,length);
285         self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
286         toret=self.data[1:len(self.data)];
287         ashex="";
288         for foo in toret:
289             ashex=ashex+(" %02x"%ord(foo));
290         if self.usbverbose: print "GET   %02x==%s" % (reg,ashex);
291         return toret;
292     def readbytesAS(self,reg,length):
293         """Peek some bytes from a register, acking prior transfer."""
294         data=[(reg<<3)|1]+range(0,length);
295         self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
296         toret=self.data[1:len(self.data)];
297         ashex="";
298         for foo in toret:
299             ashex=ashex+(" %02x"%ord(foo));
300         if self.usbverbose: print "GETAS %02x==%s" % (reg,ashex);
301         return toret;
302     def ctl_write_nd(self,request):
303         """Control Write with no data stage.  Assumes PERADDR is set
304         and the SUDFIFO contains the 8 setup bytes.  Returns with
305         result code = HRSLT[3:0] (HRSL register).  If there is an
306         error, the 4MSBits of the returned value indicate the stage 1
307         or 2."""
308         
309         # 1. Send the SETUP token and 8 setup bytes. 
310         # Should ACK immediately.
311         self.writebytes(rSUDFIFO,request);
312         resultcode=self.send_packet(tokSETUP,0); #SETUP packet to EP0.
313         if resultcode: return resultcode;
314         
315         # 2. No data stage, so the last operation is to send an IN
316         # token to the peripheral as the STATUS (handhsake) stage of
317         # this control transfer.  We should get NAK or the DATA1 PID.
318         # When we get back to the DATA1 PID the 3421 automatically
319         # sends the closing NAK.
320         resultcode=self.send_packet(tokINHS,0); #Function takes care of retries.
321         if resultcode: return resultcode;
322         
323         return 0;
324         
325         
326     def ctl_read(self,request):
327         """Control read transfer, used in Host mode."""
328         resultcode=0;
329         bytes_to_read=request[6]+256*request[7];
330         
331         ##SETUP packet
332         self.writebytes(rSUDFIFO,request);     #Load the FIFO
333         resultcode=self.send_packet(tokSETUP,0); #SETUP packet to EP0
334         if resultcode:
335             print "Failed to get ACK on SETUP request in ctl_read()."
336             return resultcode;
337         
338         self.wreg(rHCTL,bmRCVTOG1);              #FIRST data packet in CTL transfer uses DATA1 toggle.
339         resultcode=self.IN_Transfer(0,bytes_to_read);
340         if resultcode:
341             print "Failed on IN Transfer in ctl_read()";
342             return resultcode;
343         
344         self.IN_nak_count=self.nak_count;
345         
346         #The OUT status stage.
347         resultcode=self.send_packet(tokOUTHS,0);
348         if resultcode:
349             print "Failed on OUT Status stage in ctl_read()";
350             return resultcode;
351         
352         return 0; #Success
353     
354     xfrdata=[]; #Ugly variable used only by a few functions.  FIXME
355     def IN_Transfer(self,endpoint,INbytes):
356         """Does an IN transfer to an endpoint, used for Host mode."""
357         xfrsize=INbytes;
358         xfrlen=0;
359         self.xfrdata=[];
360         
361         while 1:
362             resultcode=self.send_packet(tokIN,endpoint); #IN packet to EP. NAKS taken care of.
363             if resultcode: return resultcode;
364             
365             pktsize=self.rreg(rRCVBC); #Numer of RXed bytes.
366             
367             #Very innefficient, move this to C if performance is needed.
368             for j in range(0,pktsize):
369                 self.xfrdata=self.xfrdata+[self.rreg(rRCVFIFO)];
370             xfrsize=self.xfrdata[0];
371             self.wreg(rHIRQ,bmRCVDAVIRQ); #Clear IRQ
372             xfrlen=xfrlen+pktsize; #Add byte count to total transfer length.
373             
374             print "%i / %i" % (xfrlen,xfrsize)
375             
376             #Packet is complete if:
377             # 1. The device sent a short packet, <maxPacketSize
378             # 2. INbytes have been transfered.
379             if (pktsize<self.maxPacketSize) or (xfrlen>=xfrsize):
380                 self.last_transfer_size=xfrlen;
381                 ashex="";
382                 for foo in self.xfrdata:
383                     ashex=ashex+(" %02x"%foo);
384                 print "INPACKET EP%i==%s (0x%02x bytes remain)" % (endpoint,ashex,xfrsize);
385                 return resultcode;
386
387     RETRY_LIMIT=3;
388     NAK_LIMIT=300;
389     def send_packet(self,token,endpoint):
390         """Send a packet to an endpoint as the Host, taking care of NAKs.
391         Don't use this for device code."""
392         self.retry_count=0;
393         self.nak_count=0;
394         
395         #Repeat until NAK_LIMIT or RETRY_LIMIT is reached.
396         while self.nak_count<self.NAK_LIMIT and self.retry_count<self.RETRY_LIMIT:
397             self.wreg(rHXFR,(token|endpoint)); #launch the transfer
398             while not (self.rreg(rHIRQ) & bmHXFRDNIRQ):
399                 # wait for the completion IRQ
400                 pass;
401             self.wreg(rHIRQ,bmHXFRDNIRQ);           #Clear IRQ
402             resultcode = (self.rreg(rHRSL) & 0x0F); # get the result
403             if (resultcode==hrNAK):
404                 self.nak_count=self.nak_count+1;
405             elif (resultcode==hrTIMEOUT):
406                 self.retry_count=self.retry_count+1;
407             else:
408                 #Success!
409                 return resultcode;
410         return resultcode;
411             
412     def writebytes(self,reg,tosend):
413         """Poke some bytes into a register."""
414         data="";
415         if type(tosend)==str:
416             data=chr((reg<<3)|3)+tosend;
417             if self.usbverbose: print "PUT %02x:=%s (0x%02x bytes)" % (reg,tosend,len(data))
418         else:
419             data=[(reg<<3)|3]+tosend;
420             ashex="";
421             for foo in tosend:
422                 ashex=ashex+(" %02x"%foo);
423             if self.usbverbose: print "PUT %02x:=%s (0x%02x bytes)" % (reg,ashex,len(data))
424         self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
425     def usb_connect(self):
426         """Connect the USB port."""
427         
428         #disconnect D+ pullup if host turns off VBUS
429         self.wreg(rUSBCTL,bmVBGATE|bmCONNECT);
430     def usb_disconnect(self):
431         """Disconnect the USB port."""
432         self.wreg(rUSBCTL,bmVBGATE);
433     def STALL_EP0(self,SUD=None):
434         """Stall for an unknown SETUP event."""
435         if SUD==None:
436             print "Stalling EP0.";
437         else:
438             print "Stalling EPO for %s" % self.setup2str(SUD);
439         self.wreg(rEPSTALLS,0x23); #All three stall bits.
440     def SETBIT(self,reg,val):
441         """Set a bit in a register."""
442         self.wreg(reg,self.rreg(reg)|val);
443     def vbus_on(self):
444         """Turn on the target device."""
445         self.wreg(rIOPINS2,(self.rreg(rIOPINS2)|0x08));
446     def vbus_off(self):
447         """Turn off the target device's power."""
448         self.wreg(rIOPINS2,0x00);
449     def reset_host(self):
450         """Resets the chip into host mode."""
451         self.wreg(rUSBCTL,bmCHIPRES); #Stop the oscillator.
452         self.wreg(rUSBCTL,0x00);      #restart it.
453         while self.rreg(rUSBIRQ)&bmOSCOKIRQ:
454             #Hang until the PLL stabilizes.
455             pass;
456
457 class GoodFETMAXUSBHost(GoodFETMAXUSB):
458     """This is a class for implemented a minimal USB host.
459     It's intended for fuzzing, rather than for daily use."""
460     def hostinit(self):
461         """Initialize the MAX3421 as a USB Host."""
462         self.usb_connect();
463         self.wreg(rPINCTL,(bmFDUPSPI|bmPOSINT));
464         self.reset_host();
465         self.vbus_off();
466         time.sleep(0.2);
467         self.vbus_on();
468         
469         #self.hostrun();
470     def hostrun(self):
471         """Run as a minimal host and dump the config tables."""
472         while 1:
473             self.detect_device();
474             time.sleep(0.2);
475             self.enumerate_device();
476             self.wait_for_disconnect();
477     def detect_device(self):
478         """Waits for a device to be inserted and then returns."""
479         busstate=0;
480         
481         #Activate host mode and turn on 15K pulldown resistors on D+ and D-.
482         self.wreg(rMODE,(bmDPPULLDN|bmDMPULLDN|bmHOST));
483         #Clear connection detect IRQ.
484         self.wreg(rHIRQ,bmCONDETIRQ);
485         
486         print "Waiting for a device connection.";
487         while busstate==0:
488             self.wreg(rHCTL,bmSAMPLEBUS); #Update JSTATUS and KSTATUS bits.
489             busstate=self.rreg(rHRSL) & (bmJSTATUS|bmKSTATUS);
490             
491         if busstate==bmJSTATUS:
492             print "Detected Full-Speed Device.";
493             self.wreg(rMODE,(bmDPPULLDN|bmDMPULLDN|bmHOST|bmSOFKAENAB));
494         elif busstate==bmKSTATUS:
495             print "Detected Low-Speed Device.";
496             self.wreg(rMODE,(bmDPPULLDN|bmDMPULLDN|bmHOST|bmLOWSPEED|bmSOFKAENAB));
497         else:
498             print "Not sure whether this is Full-Speed or Low-Speed.  Please investigate.";
499     def wait_for_disconnect(self):
500         """Wait for a device to be disconnected."""
501         print "Waiting for a device disconnect.";
502         
503         self.wreg(rHIRQ,bmCONDETIRQ); #Clear disconnect IRQ
504         while not (self.rreg(rHIRQ) & bmCONDETIRQ):
505             #Wait for IRQ to change.
506             pass;
507         
508         #Turn off markers.
509         self.wreg(rMODE,bmDPPULLDN|bmDMPULLDN|bmHOST);
510         print "Device disconnected.";
511         self.wreg(rIOPINS2,(self.rreg(rIOPINS2) & ~0x04)); #HL1_OFF
512         self.wreg(rIOPINS1,(self.rreg(rIOPINS1) & ~0x02)); #HL4_OFF
513
514     def enumerate_device(self):
515         """Enumerates a device on the present port."""
516         
517         Set_Address_to_7 = [0x00,0x05,0x07,0x00,0x00,0x00,0x00,0x00];
518         Get_Descriptor_Device = [0x80,0x06,0x00,0x01,0x00,0x00,0x00,0x00]; #len filled in
519         Get_Descriptor_Config = [0x80,0x06,0x00,0x02,0x00,0x00,0x00,0x00];
520         
521         
522         print "Issuing USB bus reset.";
523         self.wreg(rHCTL,bmBUSRST);
524         while self.rreg(rHCTL) & bmBUSRST:
525             #Wait for reset to complete.
526             pass;
527         
528         time.sleep(0.2);
529         
530         #Get the device descriptor.
531         self.wreg(rPERADDR,0); #First request to address 0.
532         self.maxPacketSize=8; #Only safe value for first check.
533         Get_Descriptor_Device[6]=8; # wLengthL
534         Get_Descriptor_Device[7]=0; # wLengthH
535         
536         print "Fetching 8 bytes of Device Descriptor.";
537         self.ctl_read(Get_Descriptor_Device); # Get device descriptor into self.xfrdata;
538         self.maxPacketSize=self.xfrdata[7];
539         print "EP0 maxPacketSize is %02i bytes." % self.maxPacketSize;
540         
541         # Issue another USB bus reset
542         print "Resetting the bus again."
543         self.wreg(rHCTL,bmBUSRST);
544         while self.rreg(rHCTL) & bmBUSRST:
545             #Wait for reset to complete.
546             pass;
547         time.sleep(0.2);
548         
549         # Set_Address to 7 (Note: this request goes to address 0, already set in PERADDR register).
550         print "Setting address to 0x07";
551         HR = self.ctl_write_nd(Set_Address_to_7);   # CTL-Write, no data stage
552         #if(print_error(HR)) return;
553         
554         time.sleep(0.002);           # Device gets 2 msec recovery time
555         self.wreg(rPERADDR,7);       # now all transfers go to addr 7
556         
557         
558         #Get the device descriptor at the assigned address.
559         Get_Descriptor_Device[6]=0x12; #Fill in real descriptor length.
560         print "Fetching Device Descriptor."
561         self.ctl_read(Get_Descriptor_Device); #Result in self.xfrdata;
562         
563         self.descriptor=self.xfrdata;
564         self.VID        = self.xfrdata[8] + 256*self.xfrdata[9];
565         self.PID        = self.xfrdata[10]+ 256*self.xfrdata[11];
566         iMFG    = self.xfrdata[14];
567         iPROD   = self.xfrdata[15];
568         iSERIAL = self.xfrdata[16];
569         
570         self.manufacturer=self.getDescriptorString(iMFG);
571         self.product=self.getDescriptorString(iPROD);
572         self.serial=self.getDescriptorString(iSERIAL);
573         
574         self.printstrings();
575         
576     def printstrings(self):
577         print "Vendor  ID is %04x." % self.VID;
578         print "Product ID is %04x." % self.PID;
579         print "Manufacturer: %s" % self.manufacturer;
580         print "Product:      %s" % self.product;
581         print "Serial:       %s" % self.serial;
582         
583     def getDescriptorString(self, index):
584         """Grabs a string from the descriptor string table."""
585         # Get_Descriptor-String template. Code fills in idx at str[2].
586         Get_Descriptor_String = [0x80,0x06,index,0x03,0x00,0x00,0x40,0x00];
587         
588         if index==0: return "MISSING STRING";
589         
590         status=self.ctl_read(Get_Descriptor_String);
591         if status: return None;
592         
593         #Since we've got a string
594         toret="";
595         for c in self.xfrdata[2:len(self.xfrdata)]:
596             if c>0: toret=toret+chr(c);
597         return toret;
598 class GoodFETMAXUSBDevice(GoodFETMAXUSB):
599     
600     def send_descriptor(self,SUD):
601         """Send the USB descriptors based upon the setup data."""
602         desclen=0;
603         reqlen=ord(SUD[wLengthL])+256*ord(SUD[wLengthH]); #16-bit length
604         desctype=ord(SUD[wValueH]);
605         
606         if desctype==GD_DEVICE:
607             desclen=self.DD[0];
608             ddata=self.DD;
609         elif desctype==GD_CONFIGURATION:
610             desclen=self.CD[2];
611             ddata=self.CD;
612         elif desctype==GD_STRING:
613             desclen=ord(self.strDesc[ord(SUD[wValueL])][0]);
614             ddata=self.strDesc[ord(SUD[wValueL])];
615         elif desctype==GD_HID:
616             #Don't know how to do this yet.
617             pass;
618         elif desctype==GD_REPORT:
619             desclen=self.CD[25];
620             ddata=self.RepD;
621         #TODO Configuration, String, Hid, and Report
622         
623         if desclen>0:
624             #Reduce desclen if asked for fewer bytes.
625             desclen=min(reqlen,desclen);
626             #Send those bytes.
627             self.writebytes(rEP0FIFO,ddata[0:desclen]);
628             self.wregAS(rEP0BC,desclen);
629         else:
630             print "Stalling in send_descriptor() for lack of handler for %02x." % desctype;
631             self.STALL_EP0(SUD);
632     def set_configuration(self,SUD):
633         """Set the configuration."""
634         bmSUSPIE=0x10;
635         configval=ord(SUD[wValueL]);
636         if(configval>0):
637             self.SETBIT(rUSBIEN,bmSUSPIE);
638         self.rregAS(rFNADDR);
639 class GoodFETMAXUSBHID(GoodFETMAXUSBDevice):
640     """This is an example HID keyboard driver, loosely based on the
641     MAX3420 examples."""
642     def hidinit(self):
643         """Initialize a USB HID device."""
644         self.usb_disconnect();
645         self.usb_connect();
646         
647         self.hidrun();
648         
649     def hidrun(self):
650         """Main loop of the USB HID emulator."""
651         print "Starting a HID device.  This won't return.";
652         while 1:
653             self.service_irqs();
654     def do_SETUP(self):
655         """Handle USB Enumeration"""
656         
657         #Grab the SETUP packet from the buffer.
658         SUD=self.readbytes(rSUDFIFO,8);
659         
660         #Parse the SETUP packet
661         print "Handling a setup packet of %s" % self.setup2str(SUD);
662         
663         setuptype=(ord(SUD[bmRequestType])&0x60);
664         if setuptype==0x00:
665             self.std_request(SUD);
666         elif setuptype==0x20:
667             self.class_request(SUD);
668         elif setuptype==0x40:
669             self.vendor_request(SUD);
670         else:
671             print "Unknown request type 0x%02x." % ord(SUD[bmRequestType])
672             self.STALL_EP0(SUD);
673     def class_request(self,SUD):
674         """Handle a class request."""
675         print "Stalling a class request.";
676         self.STALL_EP0(SUD);
677     def vendor_request(self,SUD):
678         print "Stalling a vendor request.";
679         self.STALL_EP0(SUD);
680     def std_request(self,SUD):
681         """Handles a standard setup request."""
682         setuptype=ord(SUD[bRequest]);
683         if setuptype==SR_GET_DESCRIPTOR: self.send_descriptor(SUD);
684         #elif setuptype==SR_SET_FEATURE:
685         #    self.rregAS(rFNADDR);
686         #    # self.feature(1);
687         elif setuptype==SR_SET_CONFIGURATION: self.set_configuration(SUD);
688         elif setuptype==SR_GET_STATUS: self.get_status(SUD);
689         elif setuptype==SR_SET_ADDRESS: self.rregAS(rFNADDR);
690         elif setuptype==SR_GET_INTERFACE: self.get_interface(SUD);
691         else:
692             print "Stalling Unknown standard setup request type %02x" % setuptype;
693             self.STALL_EP0(SUD);
694     
695     def get_interface(self,SUD):
696         """Handles a setup request for SR_GET_INTERFACE."""
697         if ord(SUD[wIndexL]==0):
698             self.wreg(rEP0FIFO,0);
699             self.wregAS(rEP0BC,1);
700         else:
701             self.STALL_EP0(SUD);
702     
703 #Device Descriptor
704     DD=[0x12,                   # bLength = 18d
705         0x01,                   # bDescriptorType = Device (1)
706         0x00,0x01,              # bcdUSB(L/H) USB spec rev (BCD)
707         0x00,0x00,0x00,         # bDeviceClass, bDeviceSubClass, bDeviceProtocol
708         0x40,                   # bMaxPacketSize0 EP0 is 64 bytes
709         0x6A,0x0B,              # idVendor(L/H)--Maxim is 0B6A
710         0x46,0x53,              # idProduct(L/H)--5346
711         0x34,0x12,              # bcdDevice--1234
712         1,2,3,                  # iManufacturer, iProduct, iSerialNumber
713         1];
714 #Configuration Descriptor
715     CD=[0x09,                   # bLength
716         0x02,                   # bDescriptorType = Config
717         0x22,0x00,              # wTotalLength(L/H) = 34 bytes
718         0x01,                   # bNumInterfaces
719         0x01,                   # bConfigValue
720         0x00,                   # iConfiguration
721         0xE0,                   # bmAttributes. b7=1 b6=self-powered b5=RWU supported
722         0x01,                   # MaxPower is 2 ma
723 # INTERFACE Descriptor
724         0x09,                   # length = 9
725         0x04,                   # type = IF
726         0x00,                   # IF #0
727         0x00,                   # bAlternate Setting
728         0x01,                   # bNum Endpoints
729         0x03,                   # bInterfaceClass = HID
730         0x00,0x00,              # bInterfaceSubClass, bInterfaceProtocol
731         0x00,                   # iInterface
732 # HID Descriptor--It's at CD[18]
733         0x09,                   # bLength
734         0x21,                   # bDescriptorType = HID
735         0x10,0x01,              # bcdHID(L/H) Rev 1.1
736         0x00,                   # bCountryCode (none)
737         0x01,                   # bNumDescriptors (one report descriptor)
738         0x22,                   # bDescriptorType       (report)
739         43,0,                   # CD[25]: wDescriptorLength(L/H) (report descriptor size is 43 bytes)
740 # Endpoint Descriptor
741         0x07,                   # bLength
742         0x05,                   # bDescriptorType (Endpoint)
743         0x83,                   # bEndpointAddress (EP3-IN)             
744         0x03,                   # bmAttributes  (interrupt)
745         64,0,                   # wMaxPacketSize (64)
746         10];
747     strDesc=[
748 # STRING descriptor 0--Language string
749 "\x04\x03\x09\x04",
750 # [
751 #         0x04,                 # bLength
752 #       0x03,                   # bDescriptorType = string
753 #       0x09,0x04               # wLANGID(L/H) = English-United Sates
754 # ],
755 # STRING descriptor 1--Manufacturer ID
756 "\x0c\x03M\x00a\x00x\x00i\x00m\x00",
757 # [
758 #         12,                   # bLength
759 #       0x03,                   # bDescriptorType = string
760 #       'M',0,'a',0,'x',0,'i',0,'m',0 # text in Unicode
761 # ], 
762 # STRING descriptor 2 - Product ID
763 "\x18\x03M\x00A\x00X\x003\x004\x002\x000\x00E\x00 \x00E\x00n\x00u\x00m\x00 \x00C\x00o\x00d\x00e\x00",
764 # [     24,                     # bLength
765 #       0x03,                   # bDescriptorType = string
766 #       'M',0,'A',0,'X',0,'3',0,'4',0,'2',0,'0',0,'E',0,' ',0,
767 #         'E',0,'n',0,'u',0,'m',0,' ',0,'C',0,'o',0,'d',0,'e',0
768 # ],
769
770
771 # STRING descriptor 3 - Serial Number ID
772 "\x14\x03S\x00/\x00N\x00 \x003\x004\x002\x000\x00E\x00"
773 # [       20,                   # bLength
774 #       0x03,                   # bDescriptorType = string
775 #       'S',0,                          
776 #       '/',0,
777 #       'N',0,
778 #       ' ',0,
779 #       '3',0,
780 #       '4',0,
781 #       '2',0,
782 #       '0',0,
783 #         'E',0,
784 # ]
785 ];
786     RepD=[
787         0x05,0x01,              # Usage Page (generic desktop)
788         0x09,0x06,              # Usage (keyboard)
789         0xA1,0x01,              # Collection
790         0x05,0x07,              #   Usage Page 7 (keyboard/keypad)
791         0x19,0xE0,              #   Usage Minimum = 224
792         0x29,0xE7,              #   Usage Maximum = 231
793         0x15,0x00,              #   Logical Minimum = 0
794         0x25,0x01,              #   Logical Maximum = 1
795         0x75,0x01,              #   Report Size = 1
796         0x95,0x08,              #   Report Count = 8
797         0x81,0x02,              #  Input(Data,Variable,Absolute)
798         0x95,0x01,              #   Report Count = 1
799         0x75,0x08,              #   Report Size = 8
800         0x81,0x01,              #  Input(Constant)
801         0x19,0x00,              #   Usage Minimum = 0
802         0x29,0x65,              #   Usage Maximum = 101
803         0x15,0x00,              #   Logical Minimum = 0,
804         0x25,0x65,              #   Logical Maximum = 101
805         0x75,0x08,              #   Report Size = 8
806         0x95,0x01,              #   Report Count = 1
807         0x81,0x00,              #  Input(Data,Variable,Array)
808         0xC0]
809
810     def get_status(self,SUD):
811         """Get the USB Setup Status."""
812         testbyte=ord(SUD[bmRequestType])
813         
814         #Toward Device
815         if testbyte==0x80:
816             self.wreg(rEP0FIFO,0x03); #Enable RWU and self-powered
817             self.wreg(rEP0FIFO,0x00); #Second byte is always zero.
818             self.wregAS(rEP0BC,2);    #Load byte count, arm transfer, and ack CTL.
819         #Toward Interface
820         elif testbyte==0x81:
821             self.wreg(rEP0FIFO,0x00);
822             self.wreg(rEP0FIFO,0x00); #Second byte is always zero.
823             self.wregAS(rEP0BC,2);
824         #Toward Endpoint
825         elif testbyte==0x82:
826             if(ord(SUD[wIndexL])==0x83):
827                 self.wreg(rEP0FIFO,0x01); #Stall EP3
828                 self.wreg(rEP0FIFO,0x00); #Second byte is always zero.
829                 self.wregAS(rEP0BC,2);
830             else:
831                 self.STALL_EP0(SUD);
832         else:
833             self.STALL_EP0(SUD);
834
835     
836     
837     typephase=0;
838     typestring="                      Python does USB HID!";
839     typepos=0;
840     
841     def asc2hid(self,ascii):
842         """Translate ASCII to an USB keycode."""
843         a=ascii;
844         if a>='a' and a<='z':
845             return ord(a)-ord('a')+4;
846         elif a>='A' and a<='Z':
847             return ord(a)-ord('A')+4;
848         elif a==' ':
849             return 0x2C; #space
850         else:
851             return 0; #key-up
852     def type_IN3(self):
853         """Type next letter in buffer."""
854         if self.typepos>=len(self.typestring):
855             self.typeletter(0);
856         elif self.typephase==0:
857             self.typephase=1;
858             self.typeletter(0);
859         else:
860             typephase=0;
861             self.typeletter(self.typestring[self.typepos]);
862             self.typepos=self.typepos+1;
863         return;
864     def typeletter(self,key):
865         """Type a letter on IN3.  Zero for keyup."""
866         #if type(key)==str: key=ord(key);
867         #Send a key-up.
868         self.wreg(rEP3INFIFO,0);
869         self.wreg(rEP3INFIFO,0);
870         self.wreg(rEP3INFIFO,self.asc2hid(key));
871         self.wreg(rEP3INBC,3);
872     def do_IN3(self):
873         """Handle IN3 event."""
874         #Don't bother clearing interrupt flag, that's done by sending the reply.
875         self.type_IN3();
876