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