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):
208 def service_irqs(self):
209 """Handle USB interrupt events."""
210 epirq=self.rreg(rEPIRQ);
211 usbirq=self.rreg(rUSBIRQ);
214 #Are we being asked for setup data?
215 if(epirq&bmSUDAVIRQ): #Setup Data Requested
216 self.wreg(rEPIRQ,bmSUDAVIRQ); #Clear the bit
218 if(epirq&bmOUT1DAVIRQ): #OUT1-OUT packet
220 self.wreg(rEPIRQ,bmOUT1DAVIRQ); #Clear the bit *AFTER* servicing.
221 if(epirq&bmIN3BAVIRQ): #IN3-IN packet
223 #self.wreg(rEPIRQ,bmIN3BAVIRQ); #Clear the bit
224 if(epirq&bmIN2BAVIRQ): #IN2 packet
226 #self.wreg(rEPIRQ,bmIN2BAVIRQ); #Clear the bit
228 # print "No idea how to service this IRQ: %02x" % epirq;
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)
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.
251 def MAXUSBtrans8(self,byte):
252 """Read and write 8 bits by MAXUSB."""
253 data=self.MAXUSBtrans([byte]);
256 def MAXUSBtrans(self,data):
257 """Exchange data by MAXUSB."""
259 self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
263 """Peek 8 bits from a register."""
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."""
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);
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);
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)];
289 ashex=ashex+(" %02x"%ord(foo));
290 if self.usbverbose: print "GET %02x==%s" % (reg,ashex);
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)];
299 ashex=ashex+(" %02x"%ord(foo));
300 if self.usbverbose: print "GETAS %02x==%s" % (reg,ashex);
302 def fifo_ep3in_tx(self,data):
303 """Sends the data out of EP3 in 64-byte chunks."""
304 #Wait for the buffer to be free before starting.
305 while not(self.rreg(rEPIRQ)&bmIN3BAVIRQ): pass;
310 #Send 64-byte chunks or the remainder.
312 self.writebytes(rEP3INFIFO,
314 self.wregAS(rEP3INBC,c);
318 #Wait for the buffer to be free before continuing.
319 while not(self.rreg(rEPIRQ)&bmIN3BAVIRQ): pass;
323 def ctl_write_nd(self,request):
324 """Control Write with no data stage. Assumes PERADDR is set
325 and the SUDFIFO contains the 8 setup bytes. Returns with
326 result code = HRSLT[3:0] (HRSL register). If there is an
327 error, the 4MSBits of the returned value indicate the stage 1
330 # 1. Send the SETUP token and 8 setup bytes.
331 # Should ACK immediately.
332 self.writebytes(rSUDFIFO,request);
333 resultcode=self.send_packet(tokSETUP,0); #SETUP packet to EP0.
334 if resultcode: return resultcode;
336 # 2. No data stage, so the last operation is to send an IN
337 # token to the peripheral as the STATUS (handhsake) stage of
338 # this control transfer. We should get NAK or the DATA1 PID.
339 # When we get back to the DATA1 PID the 3421 automatically
340 # sends the closing NAK.
341 resultcode=self.send_packet(tokINHS,0); #Function takes care of retries.
342 if resultcode: return resultcode;
347 def ctl_read(self,request):
348 """Control read transfer, used in Host mode."""
350 bytes_to_read=request[6]+256*request[7];
353 self.writebytes(rSUDFIFO,request); #Load the FIFO
354 resultcode=self.send_packet(tokSETUP,0); #SETUP packet to EP0
356 print "Failed to get ACK on SETUP request in ctl_read()."
359 self.wreg(rHCTL,bmRCVTOG1); #FIRST data packet in CTL transfer uses DATA1 toggle.
360 resultcode=self.IN_Transfer(0,bytes_to_read);
362 print "Failed on IN Transfer in ctl_read()";
365 self.IN_nak_count=self.nak_count;
367 #The OUT status stage.
368 resultcode=self.send_packet(tokOUTHS,0);
370 print "Failed on OUT Status stage in ctl_read()";
375 xfrdata=[]; #Ugly variable used only by a few functions. FIXME
376 def IN_Transfer(self,endpoint,INbytes):
377 """Does an IN transfer to an endpoint, used for Host mode."""
383 resultcode=self.send_packet(tokIN,endpoint); #IN packet to EP. NAKS taken care of.
384 if resultcode: return resultcode;
386 pktsize=self.rreg(rRCVBC); #Numer of RXed bytes.
388 #Very innefficient, move this to C if performance is needed.
389 for j in range(0,pktsize):
390 self.xfrdata=self.xfrdata+[self.rreg(rRCVFIFO)];
391 xfrsize=self.xfrdata[0];
392 self.wreg(rHIRQ,bmRCVDAVIRQ); #Clear IRQ
393 xfrlen=xfrlen+pktsize; #Add byte count to total transfer length.
395 print "%i / %i" % (xfrlen,xfrsize)
397 #Packet is complete if:
398 # 1. The device sent a short packet, <maxPacketSize
399 # 2. INbytes have been transfered.
400 if (pktsize<self.maxPacketSize) or (xfrlen>=xfrsize):
401 self.last_transfer_size=xfrlen;
403 for foo in self.xfrdata:
404 ashex=ashex+(" %02x"%foo);
405 print "INPACKET EP%i==%s (0x%02x bytes remain)" % (endpoint,ashex,xfrsize);
410 def send_packet(self,token,endpoint):
411 """Send a packet to an endpoint as the Host, taking care of NAKs.
412 Don't use this for device code."""
416 #Repeat until NAK_LIMIT or RETRY_LIMIT is reached.
417 while self.nak_count<self.NAK_LIMIT and self.retry_count<self.RETRY_LIMIT:
418 self.wreg(rHXFR,(token|endpoint)); #launch the transfer
419 while not (self.rreg(rHIRQ) & bmHXFRDNIRQ):
420 # wait for the completion IRQ
422 self.wreg(rHIRQ,bmHXFRDNIRQ); #Clear IRQ
423 resultcode = (self.rreg(rHRSL) & 0x0F); # get the result
424 if (resultcode==hrNAK):
425 self.nak_count=self.nak_count+1;
426 elif (resultcode==hrTIMEOUT):
427 self.retry_count=self.retry_count+1;
433 def writebytes(self,reg,tosend):
434 """Poke some bytes into a register."""
436 if type(tosend)==str:
437 data=chr((reg<<3)|3)+tosend;
438 if self.usbverbose: print "PUT %02x:=%s (0x%02x bytes)" % (reg,tosend,len(data))
440 data=[(reg<<3)|3]+tosend;
443 ashex=ashex+(" %02x"%foo);
444 if self.usbverbose: print "PUT %02x:=%s (0x%02x bytes)" % (reg,ashex,len(data))
445 self.writecmd(self.MAXUSBAPP,0x00,len(data),data);
446 def usb_connect(self):
447 """Connect the USB port."""
449 #disconnect D+ pullup if host turns off VBUS
450 self.wreg(rUSBCTL,bmVBGATE|bmCONNECT);
451 def usb_disconnect(self):
452 """Disconnect the USB port."""
453 self.wreg(rUSBCTL,bmVBGATE);
454 def STALL_EP0(self,SUD=None):
455 """Stall for an unknown SETUP event."""
457 print "Stalling EP0.";
459 print "Stalling EPO for %s" % self.setup2str(SUD);
460 self.wreg(rEPSTALLS,0x23); #All three stall bits.
461 def SETBIT(self,reg,val):
462 """Set a bit in a register."""
463 self.wreg(reg,self.rreg(reg)|val);
465 """Turn on the target device."""
466 self.wreg(rIOPINS2,(self.rreg(rIOPINS2)|0x08));
468 """Turn off the target device's power."""
469 self.wreg(rIOPINS2,0x00);
470 def reset_host(self):
471 """Resets the chip into host mode."""
472 self.wreg(rUSBCTL,bmCHIPRES); #Stop the oscillator.
473 self.wreg(rUSBCTL,0x00); #restart it.
474 while self.rreg(rUSBIRQ)&bmOSCOKIRQ:
475 #Hang until the PLL stabilizes.
478 class GoodFETMAXUSBHost(GoodFETMAXUSB):
479 """This is a class for implemented a minimal USB host.
480 It's intended for fuzzing, rather than for daily use."""
482 """Initialize the MAX3421 as a USB Host."""
484 self.wreg(rPINCTL,(bmFDUPSPI|bmPOSINT));
492 """Run as a minimal host and dump the config tables."""
494 self.detect_device();
496 self.enumerate_device();
497 self.wait_for_disconnect();
498 def detect_device(self):
499 """Waits for a device to be inserted and then returns."""
502 #Activate host mode and turn on 15K pulldown resistors on D+ and D-.
503 self.wreg(rMODE,(bmDPPULLDN|bmDMPULLDN|bmHOST));
504 #Clear connection detect IRQ.
505 self.wreg(rHIRQ,bmCONDETIRQ);
507 print "Waiting for a device connection.";
509 self.wreg(rHCTL,bmSAMPLEBUS); #Update JSTATUS and KSTATUS bits.
510 busstate=self.rreg(rHRSL) & (bmJSTATUS|bmKSTATUS);
512 if busstate==bmJSTATUS:
513 print "Detected Full-Speed Device.";
514 self.wreg(rMODE,(bmDPPULLDN|bmDMPULLDN|bmHOST|bmSOFKAENAB));
515 elif busstate==bmKSTATUS:
516 print "Detected Low-Speed Device.";
517 self.wreg(rMODE,(bmDPPULLDN|bmDMPULLDN|bmHOST|bmLOWSPEED|bmSOFKAENAB));
519 print "Not sure whether this is Full-Speed or Low-Speed. Please investigate.";
520 def wait_for_disconnect(self):
521 """Wait for a device to be disconnected."""
522 print "Waiting for a device disconnect.";
524 self.wreg(rHIRQ,bmCONDETIRQ); #Clear disconnect IRQ
525 while not (self.rreg(rHIRQ) & bmCONDETIRQ):
526 #Wait for IRQ to change.
530 self.wreg(rMODE,bmDPPULLDN|bmDMPULLDN|bmHOST);
531 print "Device disconnected.";
532 self.wreg(rIOPINS2,(self.rreg(rIOPINS2) & ~0x04)); #HL1_OFF
533 self.wreg(rIOPINS1,(self.rreg(rIOPINS1) & ~0x02)); #HL4_OFF
535 def enumerate_device(self):
536 """Enumerates a device on the present port."""
538 Set_Address_to_7 = [0x00,0x05,0x07,0x00,0x00,0x00,0x00,0x00];
539 Get_Descriptor_Device = [0x80,0x06,0x00,0x01,0x00,0x00,0x00,0x00]; #len filled in
540 Get_Descriptor_Config = [0x80,0x06,0x00,0x02,0x00,0x00,0x00,0x00];
543 print "Issuing USB bus reset.";
544 self.wreg(rHCTL,bmBUSRST);
545 while self.rreg(rHCTL) & bmBUSRST:
546 #Wait for reset to complete.
551 #Get the device descriptor.
552 self.wreg(rPERADDR,0); #First request to address 0.
553 self.maxPacketSize=8; #Only safe value for first check.
554 Get_Descriptor_Device[6]=8; # wLengthL
555 Get_Descriptor_Device[7]=0; # wLengthH
557 print "Fetching 8 bytes of Device Descriptor.";
558 self.ctl_read(Get_Descriptor_Device); # Get device descriptor into self.xfrdata;
559 self.maxPacketSize=self.xfrdata[7];
560 print "EP0 maxPacketSize is %02i bytes." % self.maxPacketSize;
562 # Issue another USB bus reset
563 print "Resetting the bus again."
564 self.wreg(rHCTL,bmBUSRST);
565 while self.rreg(rHCTL) & bmBUSRST:
566 #Wait for reset to complete.
570 # Set_Address to 7 (Note: this request goes to address 0, already set in PERADDR register).
571 print "Setting address to 0x07";
572 HR = self.ctl_write_nd(Set_Address_to_7); # CTL-Write, no data stage
573 #if(print_error(HR)) return;
575 time.sleep(0.002); # Device gets 2 msec recovery time
576 self.wreg(rPERADDR,7); # now all transfers go to addr 7
579 #Get the device descriptor at the assigned address.
580 Get_Descriptor_Device[6]=0x12; #Fill in real descriptor length.
581 print "Fetching Device Descriptor."
582 self.ctl_read(Get_Descriptor_Device); #Result in self.xfrdata;
584 self.descriptor=self.xfrdata;
585 self.VID = self.xfrdata[8] + 256*self.xfrdata[9];
586 self.PID = self.xfrdata[10]+ 256*self.xfrdata[11];
587 iMFG = self.xfrdata[14];
588 iPROD = self.xfrdata[15];
589 iSERIAL = self.xfrdata[16];
591 self.manufacturer=self.getDescriptorString(iMFG);
592 self.product=self.getDescriptorString(iPROD);
593 self.serial=self.getDescriptorString(iSERIAL);
597 def printstrings(self):
598 print "Vendor ID is %04x." % self.VID;
599 print "Product ID is %04x." % self.PID;
600 print "Manufacturer: %s" % self.manufacturer;
601 print "Product: %s" % self.product;
602 print "Serial: %s" % self.serial;
604 def getDescriptorString(self, index):
605 """Grabs a string from the descriptor string table."""
606 # Get_Descriptor-String template. Code fills in idx at str[2].
607 Get_Descriptor_String = [0x80,0x06,index,0x03,0x00,0x00,0x40,0x00];
609 if index==0: return "MISSING STRING";
611 status=self.ctl_read(Get_Descriptor_String);
612 if status: return None;
614 #Since we've got a string
616 for c in self.xfrdata[2:len(self.xfrdata)]:
617 if c>0: toret=toret+chr(c);
619 class GoodFETMAXUSBDevice(GoodFETMAXUSB):
621 def send_descriptor(self,SUD):
622 """Send the USB descriptors based upon the setup data."""
624 reqlen=ord(SUD[wLengthL])+256*ord(SUD[wLengthH]); #16-bit length
625 desctype=ord(SUD[wValueH]);
627 if desctype==GD_DEVICE:
630 elif desctype==GD_CONFIGURATION:
633 elif desctype==GD_STRING:
634 desclen=ord(self.strDesc[ord(SUD[wValueL])][0]);
635 ddata=self.strDesc[ord(SUD[wValueL])];
636 elif desctype==GD_HID:
637 #Don't know how to do this yet.
639 elif desctype==GD_REPORT:
642 #TODO Configuration, String, Hid, and Report
645 #Reduce desclen if asked for fewer bytes.
646 desclen=min(reqlen,desclen);
648 self.writebytes(rEP0FIFO,ddata[0:desclen]);
649 self.wregAS(rEP0BC,desclen);
651 print "Stalling in send_descriptor() for lack of handler for %02x." % desctype;
653 def set_configuration(self,SUD):
654 """Set the configuration."""
656 configval=ord(SUD[wValueL]);
658 self.SETBIT(rUSBIEN,bmSUSPIE);
659 self.rregAS(rFNADDR);
660 class GoodFETMAXUSBHID(GoodFETMAXUSBDevice):
661 """This is an example HID keyboard driver, loosely based on the
664 """Initialize a USB HID device."""
665 self.usb_disconnect();
671 """Main loop of the USB HID emulator."""
672 print "Starting a HID device. This won't return.";
676 """Handle USB Enumeration"""
678 #Grab the SETUP packet from the buffer.
679 SUD=self.readbytes(rSUDFIFO,8);
681 #Parse the SETUP packet
682 print "Handling a setup packet of %s" % self.setup2str(SUD);
684 self.OsLastConfigType=ord(SUD[bmRequestType]);
686 setuptype=(ord(SUD[bmRequestType])&0x60);
688 self.std_request(SUD);
689 elif setuptype==0x20:
690 self.class_request(SUD);
691 elif setuptype==0x40:
692 self.vendor_request(SUD);
694 print "Unknown request type 0x%02x." % ord(SUD[bmRequestType])
696 def class_request(self,SUD):
697 """Handle a class request."""
698 print "Stalling a class request.";
700 def vendor_request(self,SUD):
701 print "Stalling a vendor request.";
703 def std_request(self,SUD):
704 """Handles a standard setup request."""
705 setuptype=ord(SUD[bRequest]);
706 if setuptype==SR_GET_DESCRIPTOR: self.send_descriptor(SUD);
707 #elif setuptype==SR_SET_FEATURE:
708 # self.rregAS(rFNADDR);
710 elif setuptype==SR_SET_CONFIGURATION: self.set_configuration(SUD);
711 elif setuptype==SR_GET_STATUS: self.get_status(SUD);
712 elif setuptype==SR_SET_ADDRESS: self.rregAS(rFNADDR);
713 elif setuptype==SR_GET_INTERFACE: self.get_interface(SUD);
715 print "Stalling Unknown standard setup request type %02x" % setuptype;
718 def get_interface(self,SUD):
719 """Handles a setup request for SR_GET_INTERFACE."""
720 if ord(SUD[wIndexL]==0):
721 self.wreg(rEP0FIFO,0);
722 self.wregAS(rEP0BC,1);
728 DD=[0x12, # bLength = 18d
729 0x01, # bDescriptorType = Device (1)
730 0x00,0x01, # bcdUSB(L/H) USB spec rev (BCD)
731 0x00,0x00,0x00, # bDeviceClass, bDeviceSubClass, bDeviceProtocol
732 0x40, # bMaxPacketSize0 EP0 is 64 bytes
733 0x6A,0x0B, # idVendor(L/H)--Maxim is 0B6A
734 0x46,0x53, # idProduct(L/H)--5346
735 0x34,0x12, # bcdDevice--1234
736 1,2,3, # iManufacturer, iProduct, iSerialNumber
738 #Configuration Descriptor
740 0x02, # bDescriptorType = Config
741 0x22,0x00, # wTotalLength(L/H) = 34 bytes
742 0x01, # bNumInterfaces
744 0x00, # iConfiguration
745 0xE0, # bmAttributes. b7=1 b6=self-powered b5=RWU supported
746 0x01, # MaxPower is 2 ma
747 # INTERFACE Descriptor
751 0x00, # bAlternate Setting
752 0x01, # bNum Endpoints
753 0x03, # bInterfaceClass = HID
754 0x00,0x00, # bInterfaceSubClass, bInterfaceProtocol
756 # HID Descriptor--It's at CD[18]
758 0x21, # bDescriptorType = HID
759 0x10,0x01, # bcdHID(L/H) Rev 1.1
760 0x00, # bCountryCode (none)
761 0x01, # bNumDescriptors (one report descriptor)
762 0x22, # bDescriptorType (report)
763 43,0, # CD[25]: wDescriptorLength(L/H) (report descriptor size is 43 bytes)
764 # Endpoint Descriptor
766 0x05, # bDescriptorType (Endpoint)
767 0x83, # bEndpointAddress (EP3-IN)
768 0x03, # bmAttributes (interrupt)
769 64,0, # wMaxPacketSize (64)
772 # STRING descriptor 0--Language string
776 # 0x03, # bDescriptorType = string
777 # 0x09,0x04 # wLANGID(L/H) = English-United Sates
779 # STRING descriptor 1--Manufacturer ID
780 "\x0c\x03M\x00a\x00x\x00i\x00m\x00",
783 # 0x03, # bDescriptorType = string
784 # 'M',0,'a',0,'x',0,'i',0,'m',0 # text in Unicode
786 # STRING descriptor 2 - Product ID
787 "\x18\x03M\x00A\x00X\x003\x004\x002\x000\x00E\x00 \x00E\x00n\x00u\x00m\x00 \x00C\x00o\x00d\x00e\x00",
789 # 0x03, # bDescriptorType = string
790 # 'M',0,'A',0,'X',0,'3',0,'4',0,'2',0,'0',0,'E',0,' ',0,
791 # 'E',0,'n',0,'u',0,'m',0,' ',0,'C',0,'o',0,'d',0,'e',0
795 # STRING descriptor 3 - Serial Number ID
796 "\x14\x03S\x00/\x00N\x00 \x003\x004\x002\x000\x00E\x00"
798 # 0x03, # bDescriptorType = string
811 0x05,0x01, # Usage Page (generic desktop)
812 0x09,0x06, # Usage (keyboard)
813 0xA1,0x01, # Collection
814 0x05,0x07, # Usage Page 7 (keyboard/keypad)
815 0x19,0xE0, # Usage Minimum = 224
816 0x29,0xE7, # Usage Maximum = 231
817 0x15,0x00, # Logical Minimum = 0
818 0x25,0x01, # Logical Maximum = 1
819 0x75,0x01, # Report Size = 1
820 0x95,0x08, # Report Count = 8
821 0x81,0x02, # Input(Data,Variable,Absolute)
822 0x95,0x01, # Report Count = 1
823 0x75,0x08, # Report Size = 8
824 0x81,0x01, # Input(Constant)
825 0x19,0x00, # Usage Minimum = 0
826 0x29,0x65, # Usage Maximum = 101
827 0x15,0x00, # Logical Minimum = 0,
828 0x25,0x65, # Logical Maximum = 101
829 0x75,0x08, # Report Size = 8
830 0x95,0x01, # Report Count = 1
831 0x81,0x00, # Input(Data,Variable,Array)
834 def get_status(self,SUD):
835 """Get the USB Setup Status."""
836 testbyte=ord(SUD[bmRequestType])
840 self.wreg(rEP0FIFO,0x03); #Enable RWU and self-powered
841 self.wreg(rEP0FIFO,0x00); #Second byte is always zero.
842 self.wregAS(rEP0BC,2); #Load byte count, arm transfer, and ack CTL.
845 self.wreg(rEP0FIFO,0x00);
846 self.wreg(rEP0FIFO,0x00); #Second byte is always zero.
847 self.wregAS(rEP0BC,2);
850 if(ord(SUD[wIndexL])==0x83):
851 self.wreg(rEP0FIFO,0x01); #Stall EP3
852 self.wreg(rEP0FIFO,0x00); #Second byte is always zero.
853 self.wregAS(rEP0BC,2);
861 -1 : "Python does USB HID!\n", # Unidentified OS. This is the default typestring.
862 0x00 : "OSX Hosts don't recognize Maxim keyboards.\n", # We have to identify as an Apple keyboard to get arround the unknown keyboard error.
863 0xA1 : "Python does USB HID on Linux!\n",
864 0x81 : " Python does USB HID on Windows!\n", # Windows requires a bit of a delay. Maybe we can watch for a keyboard reset command?
866 def typestring(self):
867 if self.typestrings.has_key(self.OsLastConfigType):
868 return self.typestrings[self.OsLastConfigType];
870 return self.typestrings[-1];
871 # http://www.win.tue.nl/~aeb/linux/kbd/scancodes-14.html
872 # Escape=0x29 Backsp=0x2A Space=0x2C CapsLock=0x39 Menu=0x65
874 'en_US' :[ ' abcdefghijklmnopqrstuvwxyz1234567890\n
\e\7f\t -=[]\\\\;\'`,./',
875 '''
\ 1\ 2\ 3\ 4\ 5\ 6\a\b \v\f\r\ e\ f\10 \12 \14\15\16\17\18\19\1a''', # LeftCtrl
876 ' ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*() {}?+||:"~<>?', # LeftShift
877 '', # LeftCtrl & LeftShift
878 '
\ea
\eb
\ec'], # LeftAlt
879 'Dvorak' :[ ' axje.uidchtnmbrl\'poygk,qf;1234567890\n
\e\7f\t []/=\\\\s-`wvz',
880 '''
\ 1\18 \ 5 \15 \ 4\ 3\b\14\ e\r\ 2\12\f \10\ f\19\a\v \ 6 \17\16\1a''', # LeftCtrl
881 ' AXJE UIDCHTNMBRL"POYGK<QF:!@#$%^&*() {}?+||S_~WVZ', # LeftShift
882 '', # LeftCtrl & LeftShift
883 '
\ea
\ex
\ej'], # LeftAlt
887 return self.keymaps[self.layout];
890 'LeftCtrl': 0b00000001,
891 'LeftShift': 0b00000010,
892 'LeftAlt': 0b00000100,
893 'LeftGUI': 0b00001000,
894 'RightCtrl': 0b00010000,
895 'RightShift': 0b00100000,
896 'RightAlt': 0b01000000,
897 'RightGUI': 0b10000000
900 def asc2hid(self,ascii):
901 """Translate ASCII to an USB keycode."""
903 return (0,0); # Send NoEvent if not passed a character
905 return (0,0x2C); # space
906 for modset in self.keymap():
907 keycode=modset.find(ascii);
909 modifier = self.keymap().index(modset)
910 return (modifier, keycode);
913 """Type next letter in buffer."""
914 string=self.typestring();
915 if self.typepos>=len(string):
916 self.typeletter(0); # Send NoEvent to indicate key-up
918 self.typepos=0; # Repeat typestring forever!
919 # This would be a great place to enable a typethrough mode so the host operator can control the target
922 sys.stdout.write(string[self.typepos]);
924 self.typeletter(string[self.typepos]);
927 def typeletter(self,key):
928 """Type a letter on IN3. Zero for keyup."""
931 (mod, key) = self.asc2hid(key);
932 self.wreg(rEP3INFIFO,mod);
933 self.wreg(rEP3INFIFO,0);
934 self.wreg(rEP3INFIFO,key);
935 self.wreg(rEP3INBC,3);
937 """Handle IN3 event."""
938 #Don't bother clearing interrupt flag, that's done by sending the reply.
939 if self.OsLastConfigType != -1: # Wait for some configuration before stuffing keycodes down the pipe