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