2 # GoodFET Client Library for Maxim USB Chips.
4 # (C) 2012 Travis Goodspeed <travis at radiantmachines.com>
6 # This code is being rewritten and refactored. You've been warned!
9 import sys, time, string, cStringIO, struct, glob, os;
11 from GoodFET import GoodFET;
35 rIOPINS1=20 #Same as rIOPINS
53 # R11 EPIRQ register bits
61 # R12 EPIEN register bits
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
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
93 # SETUP packet header offsets
103 # HID bRequest values
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
176 # Host error result codes, the 4 LSB's in the HRSL register.
195 bmBUSEVENTIRQ =0x01 # indicates BUS Reset Done or BUS Resume
204 class GoodFETMAXUSB(GoodFET):
207 def setup2str(self,SUD):
208 """Converts the header of a setup packet to a string."""
209 return "bmRequestType=0x%02x, bRequest=0x%02x, wValue=0x%04x, wIndex=0x%04x, wLength=0x%04x" % (
210 ord(SUD[0]), ord(SUD[1]),
211 ord(SUD[2])+(ord(SUD[3])<<8),
212 ord(SUD[4])+(ord(SUD[5])<<8),
213 ord(SUD[6])+(ord(SUD[7])<<8)
216 def MAXUSBsetup(self):
217 """Move the FET into the MAXUSB application."""
218 self.writecmd(self.MAXUSBAPP,0x10,0,self.data); #MAXUSB/SETUP
219 print "Connected to MAX342x Rev. %x" % (self.rreg(rREVISION));
220 self.wreg(rPINCTL,0x18); #Set duplex and negative INT level.
222 def MAXUSBtrans8(self,byte):
223 """Read and write 8 bits by MAXUSB."""
224 data=self.MAXUSBtrans([byte]);
227 def MAXUSBtrans(self,data):
228 """Exchange data by MAXUSB."""
230 self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
234 """Peek 8 bits from a register."""
236 self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
237 return ord(self.data[1]);
238 def rregAS(self,reg):
239 """Peek 8 bits from a register, setting AS."""
241 self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
242 return ord(self.data[1]);
243 def wreg(self,reg,value):
244 """Poke 8 bits into a register."""
245 data=[(reg<<3)|2,value];
246 self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
248 def wregAS(self,reg,value):
249 """Poke 8 bits into a register, setting AS."""
250 data=[(reg<<3)|3,value];
251 self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
253 def readbytes(self,reg,length):
254 """Peek some bytes from a register."""
255 data=[(reg<<3)]+range(0,length);
256 self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
257 toret=self.data[1:len(self.data)];
260 ashex=ashex+(" %02x"%ord(foo));
261 print "GET %02x==%s" % (reg,ashex);
263 def readbytesAS(self,reg,length):
264 """Peek some bytes from a register, acking prior transfer."""
265 data=[(reg<<3)|1]+range(0,length);
266 self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
267 toret=self.data[1:len(self.data)];
270 ashex=ashex+(" %02x"%ord(foo));
271 print "GET %02x==%s" % (reg,ashex);
273 def ctl_write_nd(self,request):
274 """Control Write with no data stage. Assumes PERADDR is set
275 and the SUDFIFO contains the 8 setup bytes. Returns with
276 result code = HRSLT[3:0] (HRSL register). If there is an
277 error, the 4MSBits of the returned value indicate the stage 1
280 # 1. Send the SETUP token and 8 setup bytes.
281 # Should ACK immediately.
282 self.writebytes(rSUDFIFO,request);
283 resultcode=self.send_packet(tokSETUP,0); #SETUP packet to EP0.
284 if resultcode: return resultcode;
286 # 2. No data stage, so the last operation is to send an IN
287 # token to the peripheral as the STATUS (handhsake) stage of
288 # this control transfer. We should get NAK or the DATA1 PID.
289 # When we get back to the DATA1 PID the 3421 automatically
290 # sends the closing NAK.
291 resultcode=self.send_packet(tokINHS,0); #Function takes care of retries.
292 if resultcode: return resultcode;
297 def ctl_read(self,request):
298 """Control read transfer, used in Host mode."""
300 bytes_to_read=request[6]+256*request[7];
303 self.writebytes(rSUDFIFO,request); #Load the FIFO
304 resultcode=self.send_packet(tokSETUP,0); #SETUP packet to EP0
306 print "Failed to get ACK on SETUP request in ctl_read()."
309 self.wreg(rHCTL,bmRCVTOG1); #FIRST data packet in CTL transfer uses DATA1 toggle.
310 resultcode=self.IN_Transfer(0,bytes_to_read);
312 print "Failed on IN Transfer in ctl_read()";
315 self.IN_nak_count=self.nak_count;
317 #The OUT status stage.
318 resultcode=self.send_packet(tokOUTHS,0);
320 print "Failed on OUT Status stage in ctl_read()";
325 xfrdata=[]; #Ugly variable used only by a few functions. FIXME
326 def IN_Transfer(self,endpoint,INbytes):
327 """Does an IN transfer to an endpoint, used for Host mode."""
333 resultcode=self.send_packet(tokIN,endpoint); #IN packet to EP. NAKS taken care of.
334 if resultcode: return resultcode;
336 pktsize=self.rreg(rRCVBC); #Numer of RXed bytes.
338 #Very innefficient, move this to C if performance is needed.
339 for j in range(0,pktsize):
340 self.xfrdata=self.xfrdata+[self.rreg(rRCVFIFO)];
341 xfrsize=self.xfrdata[0];
342 self.wreg(rHIRQ,bmRCVDAVIRQ); #Clear IRQ
343 xfrlen=xfrlen+pktsize; #Add byte count to total transfer length.
345 print "%i / %i" % (xfrlen,xfrsize)
347 #Packet is complete if:
348 # 1. The device sent a short packet, <maxPacketSize
349 # 2. INbytes have been transfered.
350 if (pktsize<self.maxPacketSize) or (xfrlen>=xfrsize):
351 self.last_transfer_size=xfrlen;
353 for foo in self.xfrdata:
354 ashex=ashex+(" %02x"%foo);
355 print "INPACKET EP%i==%s (0x%02x bytes remain)" % (endpoint,ashex,xfrsize);
360 def send_packet(self,token,endpoint):
361 """Send a packet to an endpoint as the Host, taking care of NAKs.
362 Don't use this for device code."""
366 #Repeat until NAK_LIMIT or RETRY_LIMIT is reached.
367 while self.nak_count<self.NAK_LIMIT and self.retry_count<self.RETRY_LIMIT:
368 self.wreg(rHXFR,(token|endpoint)); #launch the transfer
369 while not (self.rreg(rHIRQ) & bmHXFRDNIRQ):
370 # wait for the completion IRQ
372 self.wreg(rHIRQ,bmHXFRDNIRQ); #Clear IRQ
373 resultcode = (self.rreg(rHRSL) & 0x0F); # get the result
374 if (resultcode==hrNAK):
375 self.nak_count=self.nak_count+1;
376 elif (resultcode==hrTIMEOUT):
377 self.retry_count=self.retry_count+1;
383 def writebytes(self,reg,tosend):
384 """Poke some bytes into a register."""
386 if type(tosend)==str:
387 data=chr((reg<<3)|3)+tosend;
388 print "PUT %02x:=%s (0x%02x bytes)" % (reg,tosend,len(data))
390 data=[(reg<<3)|3]+tosend;
393 ashex=ashex+(" %02x"%foo);
394 print "PUT %02x:=%s (0x%02x bytes)" % (reg,ashex,len(data))
395 self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
396 def usb_connect(self):
397 """Connect the USB port."""
399 #disconnect D+ pullup if host turns off VBUS
400 self.wreg(rUSBCTL,bmVBGATE|bmCONNECT);
401 def usb_disconnect(self):
402 """Disconnect the USB port."""
403 self.wreg(rUSBCTL,bmVBGATE);
404 def STALL_EP0(self,SUD=None):
405 """Stall for an unknown SETUP event."""
407 print "Stalling EP0.";
409 print "Stalling EPO for %s" % self.setup2str(SUD);
410 self.wreg(rEPSTALLS,0x23); #All three stall bits.
411 def SETBIT(self,reg,val):
412 """Set a bit in a register."""
413 self.wreg(reg,self.rreg(reg)|val);
415 """Turn on the target device."""
416 self.wreg(rIOPINS2,(self.rreg(rIOPINS2)|0x08));
418 """Turn off the target device's power."""
419 self.wreg(rIOPINS2,0x00);
420 def reset_host(self):
421 """Resets the chip into host mode."""
422 self.wreg(rUSBCTL,bmCHIPRES); #Stop the oscillator.
423 self.wreg(rUSBCTL,0x00); #restart it.
424 while self.rreg(rUSBIRQ)&bmOSCOKIRQ:
425 #Hang until the PLL stabilizes.
428 class GoodFETMAXUSBHost(GoodFETMAXUSB):
429 """This is a class for implemented a minimal USB host.
430 It's intended for fuzzing, rather than for daily use."""
432 """Initialize the MAX3421 as a USB Host."""
434 self.wreg(rPINCTL,(bmFDUPSPI|bmPOSINT));
442 """Run as a minimal host and dump the config tables."""
444 self.detect_device();
446 self.enumerate_device();
447 self.wait_for_disconnect();
448 def detect_device(self):
449 """Waits for a device to be inserted and then returns."""
452 #Activate host mode and turn on 15K pulldown resistors on D+ and D-.
453 self.wreg(rMODE,(bmDPPULLDN|bmDMPULLDN|bmHOST));
454 #Clear connection detect IRQ.
455 self.wreg(rHIRQ,bmCONDETIRQ);
457 print "Waiting for a device connection.";
459 self.wreg(rHCTL,bmSAMPLEBUS); #Update JSTATUS and KSTATUS bits.
460 busstate=self.rreg(rHRSL) & (bmJSTATUS|bmKSTATUS);
462 if busstate==bmJSTATUS:
463 print "Detected Full-Speed Device.";
464 self.wreg(rMODE,(bmDPPULLDN|bmDMPULLDN|bmHOST|bmSOFKAENAB));
465 elif busstate==bmKSTATUS:
466 print "Detected Low-Speed Device.";
467 self.wreg(rMODE,(bmDPPULLDN|bmDMPULLDN|bmHOST|bmLOWSPEED|bmSOFKAENAB));
469 print "Not sure whether this is Full-Speed or Low-Speed. Please investigate.";
470 def wait_for_disconnect(self):
471 """Wait for a device to be disconnected."""
472 print "Waiting for a device disconnect.";
474 self.wreg(rHIRQ,bmCONDETIRQ); #Clear disconnect IRQ
475 while not (self.rreg(rHIRQ) & bmCONDETIRQ):
476 #Wait for IRQ to change.
480 self.wreg(rMODE,bmDPPULLDN|bmDMPULLDN|bmHOST);
481 print "Device disconnected.";
482 self.wreg(rIOPINS2,(self.rreg(rIOPINS2) & ~0x04)); #HL1_OFF
483 self.wreg(rIOPINS1,(self.rreg(rIOPINS1) & ~0x02)); #HL4_OFF
485 def enumerate_device(self):
486 """Enumerates a device on the present port."""
488 Set_Address_to_7 = [0x00,0x05,0x07,0x00,0x00,0x00,0x00,0x00];
489 Get_Descriptor_Device = [0x80,0x06,0x00,0x01,0x00,0x00,0x00,0x00]; #len filled in
490 Get_Descriptor_Config = [0x80,0x06,0x00,0x02,0x00,0x00,0x00,0x00];
493 print "Issuing USB bus reset.";
494 self.wreg(rHCTL,bmBUSRST);
495 while self.rreg(rHCTL) & bmBUSRST:
496 #Wait for reset to complete.
501 #Get the device descriptor.
502 self.wreg(rPERADDR,0); #First request to address 0.
503 self.maxPacketSize=8; #Only safe value for first check.
504 Get_Descriptor_Device[6]=8; # wLengthL
505 Get_Descriptor_Device[7]=0; # wLengthH
507 print "Fetching 8 bytes of Device Descriptor.";
508 self.ctl_read(Get_Descriptor_Device); # Get device descriptor into self.xfrdata;
509 self.maxPacketSize=self.xfrdata[7];
510 print "EP0 maxPacketSize is %02i bytes." % self.maxPacketSize;
512 # Issue another USB bus reset
513 print "Resetting the bus again."
514 self.wreg(rHCTL,bmBUSRST);
515 while self.rreg(rHCTL) & bmBUSRST:
516 #Wait for reset to complete.
520 # Set_Address to 7 (Note: this request goes to address 0, already set in PERADDR register).
521 print "Setting address to 0x07";
522 HR = self.ctl_write_nd(Set_Address_to_7); # CTL-Write, no data stage
523 #if(print_error(HR)) return;
525 time.sleep(0.002); # Device gets 2 msec recovery time
526 self.wreg(rPERADDR,7); # now all transfers go to addr 7
529 #Get the device descriptor at the assigned address.
530 Get_Descriptor_Device[6]=0x12; #Fill in real descriptor length.
531 print "Fetching Device Descriptor."
532 self.ctl_read(Get_Descriptor_Device); #Result in self.xfrdata;
534 self.descriptor=self.xfrdata;
535 self.VID = self.xfrdata[8] + 256*self.xfrdata[9];
536 self.PID = self.xfrdata[10]+ 256*self.xfrdata[11];
537 iMFG = self.xfrdata[14];
538 iPROD = self.xfrdata[15];
539 iSERIAL = self.xfrdata[16];
541 self.manufacturer=self.getDescriptorString(iMFG);
542 self.product=self.getDescriptorString(iPROD);
543 self.serial=self.getDescriptorString(iSERIAL);
547 def printstrings(self):
548 print "Vendor ID is %04x." % self.VID;
549 print "Product ID is %04x." % self.PID;
550 print "Manufacturer: %s" % self.manufacturer;
551 print "Product: %s" % self.product;
552 print "Serial: %s" % self.serial;
554 def getDescriptorString(self, index):
555 """Grabs a string from the descriptor string table."""
556 # Get_Descriptor-String template. Code fills in idx at str[2].
557 Get_Descriptor_String = [0x80,0x06,index,0x03,0x00,0x00,0x40,0x00];
559 if index==0: return "MISSING STRING";
561 status=self.ctl_read(Get_Descriptor_String);
562 if status: return None;
564 #Since we've got a string
566 for c in self.xfrdata[2:len(self.xfrdata)]:
567 if c>0: toret=toret+chr(c);
570 class GoodFETMAXUSBHID(GoodFETMAXUSB):
571 """This is an example HID keyboard driver, loosely based on the
574 """Initialize a USB HID device."""
575 self.usb_disconnect();
581 """Main loop of the USB HID emulator."""
582 print "Starting a HID device. This won't return.";
586 """Handle USB Enumeration"""
588 #Grab the SETUP packet from the buffer.
589 SUD=self.readbytes(rSUDFIFO,8);
591 #Parse the SETUP packet
592 print "Handling a setup packet of %s" % self.setup2str(SUD);
594 setuptype=(ord(SUD[bmRequestType])&0x60);
596 self.std_request(SUD);
597 elif setuptype==0x20:
598 self.class_request(SUD);
599 elif setuptype==0x40:
600 self.vendor_request(SUD);
602 print "Unknown request type 0x%02x." % ord(SUD[bmRequestType])
604 def class_request(self,SUD):
605 """Handle a class request."""
606 print "Stalling a class request.";
608 def vendor_request(self,SUD):
609 print "Stalling a vendor request.";
611 def std_request(self,SUD):
612 """Handles a standard setup request."""
613 setuptype=ord(SUD[bRequest]);
614 if setuptype==SR_GET_DESCRIPTOR: self.send_descriptor(SUD);
615 #elif setuptype==SR_SET_FEATURE: self.feature(1);
616 elif setuptype==SR_SET_CONFIGURATION: self.set_configuration(SUD);
617 elif setuptype==SR_GET_STATUS: self.get_status(SUD);
618 elif setuptype==SR_SET_ADDRESS: self.rregAS(rFNADDR);
619 elif setuptype==SR_GET_INTERFACE: self.get_interface(SUD);
621 print "Stalling Unknown standard setup request type %02x" % setuptype;
625 def get_interface(self,SUD):
626 """Handles a setup request for SR_GET_INTERFACE."""
627 if ord(SUD[wIndexL]==0):
628 self.wreg(rEP0FIFO,0);
629 self.wregAS(rEP0BC,1);
634 DD=[0x12, # bLength = 18d
635 0x01, # bDescriptorType = Device (1)
636 0x00,0x01, # bcdUSB(L/H) USB spec rev (BCD)
637 0x00,0x00,0x00, # bDeviceClass, bDeviceSubClass, bDeviceProtocol
638 0x40, # bMaxPacketSize0 EP0 is 64 bytes
639 0x6A,0x0B, # idVendor(L/H)--Maxim is 0B6A
640 0x46,0x53, # idProduct(L/H)--5346
641 0x34,0x12, # bcdDevice--1234
642 1,2,3, # iManufacturer, iProduct, iSerialNumber
644 #Configuration Descriptor
646 0x02, # bDescriptorType = Config
647 0x22,0x00, # wTotalLength(L/H) = 34 bytes
648 0x01, # bNumInterfaces
650 0x00, # iConfiguration
651 0xE0, # bmAttributes. b7=1 b6=self-powered b5=RWU supported
652 0x01, # MaxPower is 2 ma
653 # INTERFACE Descriptor
657 0x00, # bAlternate Setting
658 0x01, # bNum Endpoints
659 0x03, # bInterfaceClass = HID
660 0x00,0x00, # bInterfaceSubClass, bInterfaceProtocol
662 # HID Descriptor--It's at CD[18]
664 0x21, # bDescriptorType = HID
665 0x10,0x01, # bcdHID(L/H) Rev 1.1
666 0x00, # bCountryCode (none)
667 0x01, # bNumDescriptors (one report descriptor)
668 0x22, # bDescriptorType (report)
669 43,0, # CD[25]: wDescriptorLength(L/H) (report descriptor size is 43 bytes)
670 # Endpoint Descriptor
672 0x05, # bDescriptorType (Endpoint)
673 0x83, # bEndpointAddress (EP3-IN)
674 0x03, # bmAttributes (interrupt)
675 64,0, # wMaxPacketSize (64)
678 # STRING descriptor 0--Language string
682 # 0x03, # bDescriptorType = string
683 # 0x09,0x04 # wLANGID(L/H) = English-United Sates
685 # STRING descriptor 1--Manufacturer ID
686 "\x0c\x03M\x00a\x00x\x00i\x00m\x00",
689 # 0x03, # bDescriptorType = string
690 # 'M',0,'a',0,'x',0,'i',0,'m',0 # text in Unicode
692 # STRING descriptor 2 - Product ID
693 "\x18\x03M\x00A\x00X\x003\x004\x002\x000\x00E\x00 \x00E\x00n\x00u\x00m\x00 \x00C\x00o\x00d\x00e\x00",
695 # 0x03, # bDescriptorType = string
696 # 'M',0,'A',0,'X',0,'3',0,'4',0,'2',0,'0',0,'E',0,' ',0,
697 # 'E',0,'n',0,'u',0,'m',0,' ',0,'C',0,'o',0,'d',0,'e',0
701 # STRING descriptor 3 - Serial Number ID
702 "\x14\x03S\x00/\x00N\x00 \x003\x004\x002\x000\x00E\x00"
704 # 0x03, # bDescriptorType = string
717 0x05,0x01, # Usage Page (generic desktop)
718 0x09,0x06, # Usage (keyboard)
719 0xA1,0x01, # Collection
720 0x05,0x07, # Usage Page 7 (keyboard/keypad)
721 0x19,0xE0, # Usage Minimum = 224
722 0x29,0xE7, # Usage Maximum = 231
723 0x15,0x00, # Logical Minimum = 0
724 0x25,0x01, # Logical Maximum = 1
725 0x75,0x01, # Report Size = 1
726 0x95,0x08, # Report Count = 8
727 0x81,0x02, # Input(Data,Variable,Absolute)
728 0x95,0x01, # Report Count = 1
729 0x75,0x08, # Report Size = 8
730 0x81,0x01, # Input(Constant)
731 0x19,0x00, # Usage Minimum = 0
732 0x29,0x65, # Usage Maximum = 101
733 0x15,0x00, # Logical Minimum = 0,
734 0x25,0x65, # Logical Maximum = 101
735 0x75,0x08, # Report Size = 8
736 0x95,0x01, # Report Count = 1
737 0x81,0x00, # Input(Data,Variable,Array)
739 def send_descriptor(self,SUD):
740 """Send the USB descriptors based upon the setup data."""
742 reqlen=ord(SUD[wLengthL])+256*ord(SUD[wLengthH]); #16-bit length
743 desctype=ord(SUD[wValueH]);
745 if desctype==GD_DEVICE:
748 elif desctype==GD_CONFIGURATION:
751 elif desctype==GD_STRING:
752 desclen=self.strDesc[ord(SUD[wValueL])][0];
753 ddata=self.strDesc[ord(SUD[wValueL])];
754 elif desctype==GD_REPORT:
758 #TODO Configuration, String, Hid, and Report
761 sendlen=min(reqlen,desclen);
762 self.writebytes(rEP0FIFO,ddata);
763 self.wregAS(rEP0BC,sendlen);
765 print "Stalling in send_descriptor() for lack of handler for %02x." % desctype;
767 def set_configuration(self,SUD):
768 """Set the configuration."""
770 configval=ord(SUD[wValueL]);
772 self.SETBIT(rUSBIEN,bmSUSPIE);
773 self.rregAS(rFNADDR);
774 def get_status(self,SUD):
775 """Get the USB Setup Status."""
776 testbyte=ord(SUD[bmRequestType])
780 self.wreg(rEP0FIFO,0x03); #Enable RWU and self-powered
781 self.wreg(rEP0FIFO,0x00); #Second byte is always zero.
782 self.wregAS(rEP0BC,2); #Load byte count, arm transfer, and ack CTL.
785 self.wreg(rEP0FIFO,0x00);
786 self.wreg(rEP0FIFO,0x00); #Second byte is always zero.
787 self.wregAS(rEP0BC,2);
790 if(ord(SUD[wIndexL])==0x83):
791 self.wreg(rEP0FIFO,0x01); #Stall EP3
792 self.wreg(rEP0FIFO,0x00); #Second byte is always zero.
793 self.wregAS(rEP0BC,2);
798 def service_irqs(self):
799 """Handle USB interrupt events."""
801 epirq=self.rreg(rEPIRQ);
802 usbirq=self.rreg(rUSBIRQ);
804 #Are we being asked for setup data?
805 if(epirq&bmSUDAVIRQ): #Setup Data Requested
806 self.wreg(rEPIRQ,bmSUDAVIRQ); #Clear the bit
808 if(epirq&bmIN3BAVIRQ): #EN3-IN packet
813 typestring=" Python does USB HID!";
816 def asc2hid(self,ascii):
817 """Translate ASCII to an USB keycode."""
819 if a>='a' and a<='z':
820 return ord(a)-ord('a')+4;
821 elif a>='A' and a<='Z':
822 return ord(a)-ord('A')+4;
828 """Type next letter in buffer."""
829 if self.typepos>=len(self.typestring):
831 elif self.typephase==0:
836 self.typeletter(self.typestring[self.typepos]);
837 self.typepos=self.typepos+1;
839 def typeletter(self,key):
840 """Type a letter on IN3. Zero for keyup."""
841 #if type(key)==str: key=ord(key);
843 self.wreg(rEP3INFIFO,0);
844 self.wreg(rEP3INFIFO,0);
845 self.wreg(rEP3INFIFO,self.asc2hid(key));
846 self.wreg(rEP3INBC,3);
848 """Handle IN3 event."""
849 #Don't bother clearing interrupt flag, that's done by sending the reply.