URL
https://opencores.org/ocsvn/usb_fpga_1_2/usb_fpga_1_2/trunk
Subversion Repositories usb_fpga_1_2
Compare Revisions
- This comparison shows the changes necessary to convert path
/
- from Rev 1 to Rev 2
- ↔ Reverse comparison
Rev 1 → Rev 2
/usb_fpga_1_2/trunk/java/FWLoader
0,0 → 1,2
DIR=${0%/*} |
java -cp $DIR/FWLoader.jar FWLoader $@ |
usb_fpga_1_2/trunk/java/FWLoader
Property changes :
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: usb_fpga_1_2/trunk/java/FWLoader.java
===================================================================
--- usb_fpga_1_2/trunk/java/FWLoader.java (nonexistent)
+++ usb_fpga_1_2/trunk/java/FWLoader.java (revision 2)
@@ -0,0 +1,207 @@
+/*!
+ Firmware / Bitstream loader for the ZTEX Firmware Kit
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+/*
+ Firmware Loader and FPGA Configurater
+*/
+
+import java.io.*;
+import java.util.*;
+
+import ch.ntb.usb.*;
+
+import ztex.*;
+
+class FWLoader {
+
+// ******* main ****************************************************************
+ public static void main (String args[]) {
+ LibusbJava.usb_init();
+
+ final String helpMsg = new String (
+ "Global parameters:\n"+
+ " -c Scan for Cypres EZ-USB devices without ZTEX firmware\n"+
+ " -v Scan for devices with ZTEX firmware and the given Vendor ID and Product ID\n"+
+ " -vc Equal to -v 0x4b4 0x8613\n"+
+ " -d Device Number (default: 0)\n"+
+ " -f Force uploads\n"+
+ " -p Print bus info\n"+
+ " -w Enable certain workaraounds which may be required for vmware + windows\n"+
+ " -h This help \n\n"+
+ "Ordered parameters:\n"+
+ " -i Info\n"+
+ " -ii Info + capabilities\n"+
+ " -ru Reset EZ-USB Microcontroller\n"+
+ " -uu Upload EZ-USB Firmware\n"+
+ " -rf Reset FPGA\n"+
+ " -uf Upload \n"+
+ " -re Reset EEPROM Firmware\n"+
+ " -ue Upload Firmware to EEPROM" );
+
+
+// process global parameters
+ try {
+
+ int usbVendorId = -1;
+ int usbProductId = -1;
+ boolean cypress = false;
+ int devNum = 0;
+ boolean forceUpload = false;
+ boolean printBus = false;
+ boolean workarounds = false;
+
+ for (int i=0; i=args.length)
+ throw new Exception();
+ usbVendorId = Integer.decode( args[i] );
+ }
+ catch (Exception e) {
+ System.err.println("Error: Vendor ID expected after -v");
+ System.err.println(helpMsg);
+ System.exit(1);
+ }
+ i++;
+ try {
+ if (i>=args.length)
+ throw new Exception();
+ usbProductId = Integer.decode( args[i] );
+ }
+ catch (Exception e) {
+ System.err.println("Error: Product ID expected after -v ");
+ System.err.println(helpMsg);
+ System.exit(1);
+ }
+ }
+ else if ( args[i].equals("-vc") ) {
+ usbVendorId = 0x4b4;
+ usbProductId = 0x8613;
+ }
+ else if ( args[i].equals("-f") ) {
+ forceUpload = true;
+ }
+ else if ( args[i].equals("-p") ) {
+ printBus = true;
+ }
+ else if ( args[i].equals("-w") ) {
+ workarounds = true;
+ }
+ else if ( args[i].equals("-d") ) {
+ i++;
+ try {
+ if (i>=args.length)
+ throw new Exception();
+ devNum = Integer.parseInt( args[i] );
+ }
+ catch (Exception e) {
+ System.err.println("Error: Device number expected after -d");
+ System.err.println(helpMsg);
+ System.exit(1);
+ }
+ }
+ else if ( args[i].equals("-h") ) {
+ System.err.println(helpMsg);
+ System.exit(0);
+ }
+ else if ( args[i].equals("-i") || args[i].equals("-ii") || args[i].equals("-ru") || args[i].equals("-rf") || args[i].equals("-re")) {
+ }
+ else if ( args[i].equals("-uu") || args[i].equals("-uf") || args[i].equals("-ue") ) {
+ i+=1;
+ }
+ else {
+ System.err.println("Error: Invalid Parameter: "+args[i]);
+ System.err.println(helpMsg);
+ System.exit(1);
+ }
+ }
+
+// process ordered parameters
+ ZtexScanBus1 bus = new ZtexScanBus1( usbVendorId, usbProductId, cypress, false, 1);
+ if ( bus.numberOfDevices() <= 0 ) {
+ System.err.println("No devices found");
+ System.exit(0);
+ }
+ if ( printBus )
+ bus.printBus(System.out);
+
+ Ztex1v1 ztex = new Ztex1v1 ( bus.device(devNum) );
+ ztex.certainWorkarounds = workarounds;
+
+ for (int i=0; i= args.length ) {
+ System.err.println("Error: Filename expected after -uu");
+ System.err.println(helpMsg);
+ System.exit(1);
+ }
+ System.out.println("Firmware upload time: " + ztex.uploadFirmware( args[i], forceUpload ) + " ms");
+ }
+ else if ( args[i].equals("-re") ) {
+ ztex.eepromDisable();
+ }
+ else if ( args[i].equals("-ue") ) {
+ i++;
+ if ( i >= args.length ) {
+ System.err.println("Error: Filename expected after -ue");
+ System.err.println(helpMsg);
+ System.exit(1);
+ }
+ System.out.println("Firmware to EEPROM upload time: " + ztex.eepromUpload( args[i], forceUpload ) + " ms");
+ }
+ else if ( args[i].equals("-rf") ) {
+ ztex.resetFpga();
+ }
+ else if ( args[i].equals("-uf") ) {
+ i++;
+ if ( i >= args.length ) {
+ System.err.println("Error: Filename expected after -uf");
+ System.err.println(helpMsg);
+ System.exit(1);
+ }
+ System.out.println("FPGA configuration time: " + ztex.configureFpga( args[i], forceUpload ) + " ms");
+ }
+ }
+ }
+ catch (Exception e) {
+ System.out.println("Error: "+e.getLocalizedMessage() );
+ }
+ }
+
+}
Index: usb_fpga_1_2/trunk/java/ztex/CapabilityException.java
===================================================================
--- usb_fpga_1_2/trunk/java/ztex/CapabilityException.java (nonexistent)
+++ usb_fpga_1_2/trunk/java/ztex/CapabilityException.java (revision 2)
@@ -0,0 +1,25 @@
+/*!
+ Java Driver API for the ZTEX Firmware Kit
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+package ztex;
+
+public class CapabilityException extends Exception {
+ public CapabilityException ( Ztex1 ztex, String cap) {
+ super( "bus=" + ztex.dev().dev().getBus().getDirname() + " device=" + ztex.dev().dev().getFilename() + ": " + cap + " not supported" );
+ }
+}
Index: usb_fpga_1_2/trunk/java/ztex/FirmwareUploadException.java
===================================================================
--- usb_fpga_1_2/trunk/java/ztex/FirmwareUploadException.java (nonexistent)
+++ usb_fpga_1_2/trunk/java/ztex/FirmwareUploadException.java (revision 2)
@@ -0,0 +1,29 @@
+/*!
+ Java Driver API for the ZTEX Firmware Kit
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+package ztex;
+
+public class FirmwareUploadException extends Exception {
+ public FirmwareUploadException (String msg) {
+ super( "Error uploading firmware: "+msg );
+ }
+
+ public FirmwareUploadException () {
+ super( "Error uploading firmware" );
+ }
+}
Index: usb_fpga_1_2/trunk/java/ztex/InvalidFirmwareException.java
===================================================================
--- usb_fpga_1_2/trunk/java/ztex/InvalidFirmwareException.java (nonexistent)
+++ usb_fpga_1_2/trunk/java/ztex/InvalidFirmwareException.java (revision 2)
@@ -0,0 +1,29 @@
+/*!
+ Java Driver API for the ZTEX Firmware Kit
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+package ztex;
+
+public class InvalidFirmwareException extends Exception {
+ public InvalidFirmwareException ( Ztex1 ztex, String msg) {
+ super( "bus=" + ztex.dev().dev().getBus().getDirname() + " device=" + ztex.dev().dev().getFilename() + ": Invalid Firmware: "+ msg );
+ }
+
+ public InvalidFirmwareException ( Ztex1 ztex ) {
+ super( "bus=" + ztex.dev().dev().getBus().getDirname() + " device=" + ztex.dev().dev().getFilename() + ": Invalid Firmware" );
+ }
+}
Index: usb_fpga_1_2/trunk/java/ztex/IhxParseException.java
===================================================================
--- usb_fpga_1_2/trunk/java/ztex/IhxParseException.java (nonexistent)
+++ usb_fpga_1_2/trunk/java/ztex/IhxParseException.java (revision 2)
@@ -0,0 +1,25 @@
+/*!
+ Java Driver API for the ZTEX Firmware Kit
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+package ztex;
+
+public class IhxParseException extends Exception {
+ public IhxParseException( String msg ) {
+ super( msg );
+ }
+}
Index: usb_fpga_1_2/trunk/java/ztex/BitstreamReadException.java
===================================================================
--- usb_fpga_1_2/trunk/java/ztex/BitstreamReadException.java (nonexistent)
+++ usb_fpga_1_2/trunk/java/ztex/BitstreamReadException.java (revision 2)
@@ -0,0 +1,31 @@
+/*!
+ Java Driver API for the ZTEX Firmware Kit
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+package ztex;
+
+import java.io.*;
+
+public class BitstreamReadException extends IOException {
+ public BitstreamReadException(String msg) {
+ super( "Cannot read bitstream: "+msg );
+ }
+
+ public BitstreamReadException() {
+ super( "Cannot read bitstream" );
+ }
+}
Index: usb_fpga_1_2/trunk/java/ztex/AlreadyConfiguredException.java
===================================================================
--- usb_fpga_1_2/trunk/java/ztex/AlreadyConfiguredException.java (nonexistent)
+++ usb_fpga_1_2/trunk/java/ztex/AlreadyConfiguredException.java (revision 2)
@@ -0,0 +1,29 @@
+/*!
+ Java Driver API for the ZTEX Firmware Kit
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+package ztex;
+
+public class AlreadyConfiguredException extends Exception {
+ public AlreadyConfiguredException (String msg) {
+ super( "FPGA already configured: "+msg );
+ }
+
+ public AlreadyConfiguredException() {
+ super( "FPGA already configured" );
+ }
+}
Index: usb_fpga_1_2/trunk/java/ztex/UsbException.java
===================================================================
--- usb_fpga_1_2/trunk/java/ztex/UsbException.java (nonexistent)
+++ usb_fpga_1_2/trunk/java/ztex/UsbException.java (revision 2)
@@ -0,0 +1,31 @@
+/*!
+ Java Driver API for the ZTEX Firmware Kit
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+package ztex;
+
+import ch.ntb.usb.*;
+
+public class UsbException extends Exception {
+ public UsbException(String msg) {
+ super( msg );
+ }
+
+ public UsbException(Usb_Device dev, String msg) {
+ super( "bus=" + dev.getBus().getDirname() + " device=" + dev.getFilename() + ": " + msg );
+ }
+}
Index: usb_fpga_1_2/trunk/java/ztex/ZtexDescriptorException.java
===================================================================
--- usb_fpga_1_2/trunk/java/ztex/ZtexDescriptorException.java (nonexistent)
+++ usb_fpga_1_2/trunk/java/ztex/ZtexDescriptorException.java (revision 2)
@@ -0,0 +1,31 @@
+/*!
+ Java Driver API for the ZTEX Firmware Kit
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+package ztex;
+
+import ch.ntb.usb.*;
+
+public class ZtexDescriptorException extends Exception {
+ public ZtexDescriptorException(String msg) {
+ super( msg );
+ }
+
+ public ZtexDescriptorException(Usb_Device dev, String msg) {
+ super( "bus=" + dev.getBus().getDirname() + " device=" + dev.getFilename() + ": " + msg );
+ }
+}
Index: usb_fpga_1_2/trunk/java/ztex/IhxFileDamagedException.java
===================================================================
--- usb_fpga_1_2/trunk/java/ztex/IhxFileDamagedException.java (nonexistent)
+++ usb_fpga_1_2/trunk/java/ztex/IhxFileDamagedException.java (revision 2)
@@ -0,0 +1,25 @@
+/*!
+ Java Driver API for the ZTEX Firmware Kit
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+package ztex;
+
+public class IhxFileDamagedException extends Exception {
+ public IhxFileDamagedException ( String filename, int line, String msg ) {
+ super( "ihx file " + filename + "(" + line + ") damaged: "+msg );
+ }
+}
Index: usb_fpga_1_2/trunk/java/ztex/Ztex1.java
===================================================================
--- usb_fpga_1_2/trunk/java/ztex/Ztex1.java (nonexistent)
+++ usb_fpga_1_2/trunk/java/ztex/Ztex1.java (revision 2)
@@ -0,0 +1,276 @@
+/*!
+ Java Driver API for the ZTEX Firmware Kit
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+/*
+ Functions for USB devices with ZTEX descriptor 1
+*/
+package ztex;
+
+import java.io.*;
+import java.util.*;
+
+import ch.ntb.usb.*;
+
+public class Ztex1 {
+ protected int handle;
+ protected ZtexDevice1 dev = null;
+ private boolean oldDevices[] = new boolean[128];
+ private String usbBusName = null;
+
+// ******* Ztex1 ***************************************************************
+ public Ztex1 ( ZtexDevice1 pDev ) throws UsbException {
+ dev = pDev;
+
+ handle = LibusbJava.usb_open(dev.dev());
+ if ( handle<=0 )
+ throw new UsbException(dev.dev(), "Error opening device");
+ }
+
+// ******* finalize ************************************************************
+ protected void finalize () {
+ LibusbJava.usb_close(handle);
+ }
+
+// ******* handle **************************************************************
+ public final int handle()
+ {
+ return handle;
+ }
+
+// ******* dev *****************************************************************
+ public final ZtexDevice1 dev()
+ {
+ return dev;
+ }
+
+// ******* valid ***************************************************************
+ public boolean valid ( ) {
+ return dev.valid();
+ }
+
+// ******* checkValid **********************************************************
+ public void checkValid () throws InvalidFirmwareException {
+ if ( ! dev.valid() )
+ throw new InvalidFirmwareException(this, "Can't read ZTEX descriptor 1");
+ }
+
+// ******* vendorCommand *******************************************************
+ public int vendorCommand (int cmd, String func, int value, int index, byte[] buf, int length) throws UsbException {
+ int i;
+ if ( (i=LibusbJava.usb_control_msg(handle, 0x40, cmd, value, index, buf, length, 1000)) < 0 )
+ throw new UsbException( dev.dev(), (func != null ? func + ": " : "" ) + LibusbJava.usb_strerror());
+ try {
+ Thread.sleep(1); // avoid package loss (due to interrupts ?)
+ }
+ catch ( InterruptedException e ) {
+ }
+ return i;
+ }
+
+ public int vendorCommand (int cmd, String func, int value, int index) throws UsbException {
+ byte[] buf = { 0 };
+ return vendorCommand (cmd, func, value, index, buf, 0);
+ }
+
+ public int vendorCommand (int cmd, String func) throws UsbException {
+ byte[] buf = { 0 };
+ return vendorCommand (cmd, func, 0, 0, buf, 0);
+ }
+
+// ******* vendorRequest *******************************************************
+ public int vendorRequest (int cmd, String func, int value, int index, byte[] buf, int maxlen) throws UsbException {
+ int i = LibusbJava.usb_control_msg(handle, 0xc0, cmd, value, index, buf, maxlen, 1000);
+ if ( i < 0 )
+ throw new UsbException( dev.dev(), (func != null ? func + ": " : "" ) + LibusbJava.usb_strerror());
+ try {
+ Thread.sleep(1); // avoid package loss (due to interrupts ?)
+ }
+ catch ( InterruptedException e ) {
+ }
+ return i;
+ }
+
+ public int vendorRequest (int cmd, String func, byte[] buf, int maxlen) throws UsbException {
+ return vendorRequest (cmd, func, 0, 0, buf, maxlen);
+ }
+
+// ******* vendorCommand2 ******************************************************
+ public void vendorCommand2 (int cmd, String func, int value, int index, byte[] buf, int length) throws UsbException {
+ int i = vendorCommand (cmd, func, value, index, buf, length);
+ if ( i != length )
+ throw new UsbException( dev.dev(), (func != null ? func + ": " : "" ) + "Send " + i + " byte of data instead of " + length + " bytes");
+ }
+
+ public void vendorCommand2 (int cmd, String func, int value, int index) throws UsbException {
+ byte[] buf = { 0 };
+ vendorCommand2 (cmd, func, value, index, buf, 0);
+ }
+
+ public void vendorCommand2 (int cmd, String func) throws UsbException {
+ byte[] buf = { 0 };
+ vendorCommand2 (cmd, func, 0, 0, buf, 0);
+ }
+
+// ******* vendorRequest2 ******************************************************
+ public void vendorRequest2 (int cmd, String func, int value, int index, byte[] buf, int maxlen) throws UsbException {
+ int i = vendorRequest(cmd, func, value, index, buf, maxlen);
+ if ( i != maxlen )
+ throw new UsbException( dev.dev(), (func != null ? func + ": " : "" ) + "Received " + i + " byte of data, expected "+maxlen+" bytes");
+ }
+
+ public void vendorRequest2 (int cmd, String func, byte[] buf, int maxlen) throws UsbException {
+ vendorRequest2(cmd, func, 0, 0, buf, maxlen);
+ }
+
+// ******* findOldDevices ******************************************************
+ private void findOldDevices () {
+ Usb_Bus bus = dev.dev().getBus();
+ usbBusName = bus.getDirname();
+
+ for ( int i=0; i<=127; i++ )
+ oldDevices[i] = false;
+
+ Usb_Device d = bus.getDevices();
+ while ( d != null ) {
+ byte b = d.getDevnum();
+ if ( b > 0 )
+ oldDevices[b] = true;
+ d = d.getNext();
+ }
+ oldDevices[dev.dev().getDevnum()] = false;
+ }
+
+// ******* findNewDevice *******************************************************
+ private Usb_Device findNewDevice ( String errMsg ) throws DeviceLostException {
+ Usb_Device newDev = null;
+ LibusbJava.usb_find_busses();
+ LibusbJava.usb_find_devices();
+
+ Usb_Bus bus = LibusbJava.usb_get_busses();
+ while ( bus != null && ! bus.getDirname().equals(usbBusName) )
+ bus = bus.getNext();
+
+ Usb_Device d = bus != null ? bus.getDevices() : null;
+ while ( d != null ) {
+ byte b = d.getDevnum();
+ if ( b > 0 && ! oldDevices[b] ) {
+ if ( newDev != null )
+ throw new DeviceLostException( errMsg + "More than 2 new devices found" );
+ newDev = d;
+ }
+ d = d.getNext();
+ }
+
+ return newDev;
+ }
+
+// ******* initNewDevice *******************************************************
+ private void initNewDevice ( String errBase ) throws DeviceLostException, UsbException, ZtexDescriptorException {
+// scan the bus for up to 5 s for a new device
+ Usb_Device newDev = null;
+ for ( int i=0; i<20 && newDev==null; i++ ) {
+ try {
+ Thread.sleep( 250 );
+ }
+ catch ( InterruptedException e ) {
+ }
+ newDev = findNewDevice( errBase + ": " );
+ }
+ if ( newDev == null )
+ throw new DeviceLostException( errBase + ": No new device found" );
+
+// init new device
+ Usb_Device_Descriptor dd = newDev.getDescriptor();
+ int vid = dd.getIdVendor() & 65535;
+ int pid = dd.getIdProduct() & 65535;
+ try {
+ dev = new ZtexDevice1( newDev, vid, pid );
+ }
+ catch ( ZtexDescriptorException e ) {
+ if ( vid == ZtexDevice1.cypressVendorId && pid == ZtexDevice1.cypressProductId ) {
+ dev = new ZtexDevice1( newDev, -1, -1 );
+ }
+ else {
+ throw e;
+ }
+ }
+ handle = LibusbJava.usb_open( dev.dev() );
+ }
+
+// ******* uploadFirmware ******************************************************
+// returns upload time in ms
+ public long uploadFirmware ( String ihxFileName, boolean force ) throws IncompatibleFirmwareException, FirmwareUploadException, UsbException, ZtexDescriptorException, DeviceLostException {
+// load the ihx file
+ ZtexIhxFile1 ihxFile;
+ try {
+ ihxFile = new ZtexIhxFile1( ihxFileName );
+ }
+ catch ( IOException e ) {
+ throw new FirmwareUploadException( e.getLocalizedMessage() );
+ }
+ catch ( IhxFileDamagedException e ) {
+ throw new FirmwareUploadException( e.getLocalizedMessage() );
+ }
+// ihxFile.dataInfo(System.out);
+// System.out.println(ihxFile);
+
+// check for compatibility
+ if ( ! force && dev.valid() ) {
+ if ( ihxFile.interfaceVersion() != 1 )
+ throw new IncompatibleFirmwareException("Wrong interface version: Expected 1, got " + ihxFile.interfaceVersion() );
+
+ if ( ! dev.compatible ( ihxFile.productId(0), ihxFile.productId(1), ihxFile.productId(2), ihxFile.productId(3) ) )
+ throw new IncompatibleFirmwareException("Incompatible productId's: Current firmware: " + ZtexDevice1.byteArrayString(dev.productId())
+ + " Ihx File: " + ZtexDevice1.byteArrayString(ihxFile.productId()) );
+ }
+
+// scan the bus for comparison
+ findOldDevices();
+
+// upload the firmware
+ long time = EzUsb.uploadFirmware( handle, ihxFile );
+
+// find and init new device
+ initNewDevice("Device lost after uploading Firmware");
+
+ return time;
+ }
+
+// ******* resetEzUsb **********************************************************
+ public void resetEzUsb () throws IncompatibleFirmwareException, FirmwareUploadException, UsbException, ZtexDescriptorException, DeviceLostException {
+// scan the bus for comparison
+ findOldDevices();
+
+// reset the EZ-USB
+ EzUsb.reset(handle,true);
+ try {
+ EzUsb.reset(handle,false); // error (may caused re-numeration) can be ignored
+ }
+ catch ( FirmwareUploadException e ) {
+ }
+
+// find and init new device
+ initNewDevice( "Device lost after resetting the EZ-USB" );
+ }
+
+// ******* toString ************************************************************
+ public String toString () {
+ return dev.toString();
+ }
+
+}
Index: usb_fpga_1_2/trunk/java/ztex/BitstreamUploadException.java
===================================================================
--- usb_fpga_1_2/trunk/java/ztex/BitstreamUploadException.java (nonexistent)
+++ usb_fpga_1_2/trunk/java/ztex/BitstreamUploadException.java (revision 2)
@@ -0,0 +1,29 @@
+/*!
+ Java Driver API for the ZTEX Firmware Kit
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+package ztex;
+
+public class BitstreamUploadException extends Exception {
+ public BitstreamUploadException (String msg) {
+ super( "Error uploading bitstream: "+msg );
+ }
+
+ public BitstreamUploadException () {
+ super( "Error uploading bitstream" );
+ }
+}
Index: usb_fpga_1_2/trunk/java/ztex/DeviceLostException.java
===================================================================
--- usb_fpga_1_2/trunk/java/ztex/DeviceLostException.java (nonexistent)
+++ usb_fpga_1_2/trunk/java/ztex/DeviceLostException.java (revision 2)
@@ -0,0 +1,29 @@
+/*!
+ Java Driver API for the ZTEX Firmware Kit
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+package ztex;
+
+public class DeviceLostException extends Exception {
+ public DeviceLostException (String msg) {
+ super( msg );
+ }
+
+ public DeviceLostException () {
+ super( "Device lost");
+ }
+}
Index: usb_fpga_1_2/trunk/java/ztex/IncompatibleFirmwareException.java
===================================================================
--- usb_fpga_1_2/trunk/java/ztex/IncompatibleFirmwareException.java (nonexistent)
+++ usb_fpga_1_2/trunk/java/ztex/IncompatibleFirmwareException.java (revision 2)
@@ -0,0 +1,29 @@
+/*!
+ Java Driver API for the ZTEX Firmware Kit
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+package ztex;
+
+public class IncompatibleFirmwareException extends Exception {
+ public IncompatibleFirmwareException (String msg) {
+ super( "Incompatible firmware: "+msg );
+ }
+
+ public IncompatibleFirmwareException () {
+ super( "Incompatible firmware" );
+ }
+}
Index: usb_fpga_1_2/trunk/java/ztex/Ztex1v1.java
===================================================================
--- usb_fpga_1_2/trunk/java/ztex/Ztex1v1.java (nonexistent)
+++ usb_fpga_1_2/trunk/java/ztex/Ztex1v1.java (revision 2)
@@ -0,0 +1,430 @@
+/*!
+ Java Driver API for the ZTEX Firmware Kit
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+/*
+ Functions for USB devices with ZTEX descriptor 1, Interface 1
+ Interface capabilities and vendor requests (VR) / commands (VC):
+ 0.0 : EEPROM support
+ 0.1 : FPGA Configuration
+ VR 0x31 : FPGA state
+ Returns:
+ Offs Description
+ 0 1: unconfigured, 0:configured
+ 1 checksum
+ 2-5 transfered bytes
+ 6 INIT_B state
+
+*/
+package ztex;
+
+import java.io.*;
+import java.util.*;
+
+import ch.ntb.usb.*;
+
+
+public class Ztex1v1 extends Ztex1 {
+ public static final String capabilityStrings[] = {
+ "EEPROM read/write" ,
+ "FPGA configuration"
+ };
+
+ public boolean certainWorkarounds = false; // setting to true will enable certain workarounds which may be required for vmware + windows
+
+ private boolean fpgaConfigured = false;
+ private int fpgaChecksum = 0;
+ private int fpgaBytes = 0;
+ private int fpgaInitB = 0;
+
+ public int eepromBytes = 0;
+ public int eepromChecksum = 0;
+ public boolean eepromReady = true;
+
+// ******* Ztex1v1 *************************************************************
+ public Ztex1v1 ( ZtexDevice1 pDev ) throws UsbException, ZtexDescriptorException {
+ super ( pDev );
+ certainWorkarounds = false;
+ }
+
+// ******* valid ***************************************************************
+ public boolean valid ( ) {
+ return dev.valid() && dev.interfaceVersion()==1;
+ }
+
+ public boolean valid ( int i, int j) {
+ return dev.valid() && dev.interfaceVersion()==1 && dev.interfaceCapabilities(i,j);
+ }
+
+// ******* compatible **********************************************************
+ public boolean compatible ( int productId0, int productId1, int productId2, int productId3 ) {
+ return dev.valid() && dev.compatible ( productId0, productId1, productId2, productId3 ) && dev.interfaceVersion()==1;
+ }
+
+// ******* checkValid **********************************************************
+ public void checkValid () throws InvalidFirmwareException {
+ super.checkValid();
+ if ( dev.interfaceVersion() != 1 )
+ throw new InvalidFirmwareException(this, "Wrong interface: " + dev.interfaceVersion() + ", expected: 1" );
+ }
+
+// ******* checkCapability *****************************************************
+ public void checkCapability ( int i, int j ) throws InvalidFirmwareException, CapabilityException {
+ checkValid();
+ if ( ! dev.interfaceCapabilities(i,j) ) {
+ int k = i*8 + j;
+ if ( k>=0 && k=0 && k<=capabilityStrings.length ) ? capabilityStrings[k] : ("Capabilty " + i + "," + j) );
+ }
+ }
+
+// ******* checkCompatible *****************************************************
+ public void checkCompatible ( int productId0, int productId1, int productId2, int productId3 ) throws InvalidFirmwareException {
+ checkValid();
+ if ( ! dev.compatible ( productId0, productId1, productId2, productId3 ) )
+ throw new InvalidFirmwareException(this, "Incompatible Product ID");
+ }
+
+// ******* getFpgaState ********************************************************
+ private void getFpgaState () throws UsbException, InvalidFirmwareException, CapabilityException {
+ byte[] buffer = new byte[7];
+ checkCapability(0,1);
+ vendorRequest2(0x30, "getFpgaState", buffer, 7);
+ fpgaConfigured = buffer[0] == 0;
+ fpgaChecksum = buffer[1] & 0xff;
+ fpgaBytes = ((buffer[5] & 0xff)<<24) | ((buffer[4] & 0xff)<<16) | ((buffer[3] & 0xff)<<8) | (buffer[2] & 0xff);
+ fpgaInitB = buffer[6] & 0xff;
+ }
+
+// ******* getFpgaConfiguration ************************************************
+ public boolean getFpgaConfiguration () throws UsbException, InvalidFirmwareException, CapabilityException {
+ getFpgaState ();
+ return fpgaConfigured;
+ }
+
+// ******* getFpgaConfigurationStr *********************************************
+ public String getFpgaConfigurationStr () throws UsbException, InvalidFirmwareException, CapabilityException {
+ getFpgaState ();
+ return fpgaConfigured ? "FPGA configured" : "FPGA unconfigured";
+ }
+
+// ******* resetFGPA ***********************************************************
+ public void resetFpga () throws UsbException, InvalidFirmwareException, CapabilityException {
+ checkCapability(0,1);
+ vendorCommand(0x31, "resetFpga" );
+ }
+
+// ******* configureFpga *******************************************************
+// returns configuration time in ms
+ public long configureFpga ( String fwFileName, boolean force ) throws BitstreamReadException, UsbException, BitstreamUploadException, AlreadyConfiguredException, InvalidFirmwareException, CapabilityException {
+ final int transactionBytes = certainWorkarounds ? 256 : 2048;
+ long t0 = 0;
+
+ checkCapability(0,1);
+
+ if ( !force && getFpgaConfiguration() )
+ throw new AlreadyConfiguredException();
+
+// read the bitstream file
+ byte[][] buffer = new byte[4*1024*1024/transactionBytes][];
+ int size = 0;
+ try {
+ InputStream inputStream = JInputStream.getInputStream( fwFileName );
+ int j = transactionBytes;
+ for ( int i=0; i0; tries-- ) {
+
+ resetFpga();
+
+ try {
+ t0 = -new Date().getTime();
+ int cs = 0;
+ int bs = 0;
+
+ for ( int i=0; itransactionBytes)
+ j = transactionBytes;
+ vendorCommand2(0x32, "sendFpgaData", 0,0, buffer[i], j);
+
+ bs+=j;
+ for ( int k=0; k1 )
+ System.err.println("Warning: " + e.getLocalizedMessage() +": Retrying it ...");
+ else
+ throw e;
+ }
+ }
+
+ try {
+ Thread.sleep( 200 );
+ }
+ catch ( InterruptedException e) {
+ }
+
+ return t0;
+ }
+
+// ******* eepromState *********************************************************
+// returns true if EEPROM is ready
+ public boolean eepromState ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
+ byte[] buf = new byte[4];
+ checkCapability(0,0);
+ vendorRequest2(0x3A, "EEPROM State", 0, 0, buf, 4);
+ eepromBytes = (buf[0] & 255) | (buf[1] & 255)<<8;
+ eepromChecksum = buf[2] & 255;
+ eepromReady = buf[3] == 0;
+ return eepromReady;
+ }
+
+// ******* eepromWrite *********************************************************
+ public void eepromWrite ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
+ checkCapability(0,0);
+ vendorCommand2( 0x39, "EEPROM Write", addr, 0, buf, length );
+ }
+
+// ******* eepromRead **********************************************************
+ public void eepromRead ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
+ checkCapability(0,0);
+ for ( int tries=4; tries>0; tries-- ) {
+ try {
+ vendorRequest2( 0x38, "EEPROM Read", addr, 0, buf, length ); // sometimes a little bit slow
+ tries = 0;
+ }
+ catch ( UsbException e ) {
+ if ( tries<=1 ) throw e;
+ }
+ }
+ }
+
+// ******* eepromUpload ********************************************************
+// returns upload time in ms
+ public long eepromUpload ( String ihxFileName, boolean force ) throws IncompatibleFirmwareException, FirmwareUploadException, InvalidFirmwareException, CapabilityException {
+ final int pagesMax = 256;
+ final int pageSize = 256;
+ int pages = 0;
+ byte[][] buffer = new byte[pagesMax][];
+
+ checkCapability(0,0);
+
+// load the ihx file
+ ZtexIhxFile1 ihxFile;
+ try {
+ ihxFile = new ZtexIhxFile1( ihxFileName );
+ }
+ catch ( IOException e ) {
+ throw new FirmwareUploadException( e.getLocalizedMessage() );
+ }
+ catch ( IhxFileDamagedException e ) {
+ throw new FirmwareUploadException( e.getLocalizedMessage() );
+ }
+// ihxFile.dataInfo(System.out);
+// System.out.println(ihxFile);
+
+// check for compatibility
+ if ( ! force && dev.valid() ) {
+ if ( ihxFile.interfaceVersion() != 1 )
+ throw new IncompatibleFirmwareException("Wrong interface version: Expected 1, got " + ihxFile.interfaceVersion() );
+
+ if ( ! dev.compatible ( ihxFile.productId(0), ihxFile.productId(1), ihxFile.productId(2), ihxFile.productId(3) ) )
+ throw new IncompatibleFirmwareException("Incompatible productId's: Current firmware: " + ZtexDevice1.byteArrayString(dev.productId())
+ + " Ihx File: " + ZtexDevice1.byteArrayString(ihxFile.productId()) );
+ }
+
+ Usb_Device_Descriptor dd = dev.dev().getDescriptor();
+ int vid = dd.getIdVendor() & 65535;
+ int pid = dd.getIdProduct() & 65535;
+
+ buffer[0] = new byte[pageSize];
+ buffer[0][0] = (byte) 0xc2;
+ buffer[0][1] = (byte) (vid & 255);
+ buffer[0][2] = (byte) ((vid >> 8) & 255);
+ buffer[0][3] = (byte) (pid & 255);
+ buffer[0][4] = (byte) ((pid >> 8) & 255);
+ buffer[0][5] = 0;
+ buffer[0][6] = 0;
+ buffer[0][7] = 0;
+
+ int ptr = 8, i = 0;
+
+ while ( i < ihxFile.ihxData.length ) {
+ if ( ihxFile.ihxData[i]>=0 && ihxFile.ihxData[i]<256 ) { // new data block
+ int j = 1;
+ while ( i+j=0 && ihxFile.ihxData[i+j]<255 )
+ j++;
+
+ for (int k=ptr/pageSize + 1; k < (ptr+j+4)/pageSize + 1; k++ ) // also considers 5 bytes for the last data block
+ buffer[k] = new byte[pageSize];
+
+ buffer[(ptr+0)/pageSize][(ptr+0) % pageSize] = (byte) ((j >> 8) & 255);
+ buffer[(ptr+1)/pageSize][(ptr+1) % pageSize] = (byte) (j & 255); // length
+ buffer[(ptr+2)/pageSize][(ptr+2) % pageSize] = (byte) ((i >> 8) & 255);
+ buffer[(ptr+3)/pageSize][(ptr+3) % pageSize] = (byte) (i & 255); // address
+ ptr+=4;
+ for ( int k=0; k=0; i-- ) {
+
+ int k = (i+1)*pageSize < ptr ? pageSize : ptr-i*pageSize;
+ int cs = 0;
+ for (int j=0; j0; tries-- ) {
+ try {
+ eepromWrite(i*pageSize, buffer[i], k);
+ eepromState();
+ if ( eepromBytes!=k )
+ throw new FirmwareUploadException("Error writing data to EEPROM: Wrote " + eepromBytes + " bytes instead of " + k + " bytes" );
+ if ( eepromChecksum!=cs )
+ throw new FirmwareUploadException("Error writing data to EEPROM: Checksum error");
+
+ eepromRead(i*pageSize, rbuf, k);
+ for (int j=0; j 1 ) {
+ System.err.println("Warning: " + e.getLocalizedMessage() +": Retrying it ...");
+ }
+ else {
+ throw new FirmwareUploadException(e.getLocalizedMessage());
+ }
+ }
+ }
+ }
+
+ return new Date().getTime() - t0;
+ }
+
+
+// ******* eepromDisable ********************************************************
+ public void eepromDisable ( ) throws FirmwareUploadException, InvalidFirmwareException, CapabilityException {
+ byte[] buf = { 0 };
+
+ for ( int tries=4; tries>0; tries-- ) {
+ try {
+ eepromWrite(0, buf, 1);
+
+ eepromRead(0, buf, 1);
+ if ( buf[0] != 0 )
+ throw new FirmwareUploadException("Error disabeling EEPROM firmware: Verification failed");
+ tries = 0;
+
+ }
+ catch ( Exception e ) {
+ if ( tries > 1 ) {
+ System.err.println("Warning: " + e.getLocalizedMessage() +": Retrying it ...");
+ }
+ else {
+ throw new FirmwareUploadException(e.getLocalizedMessage());
+ }
+ }
+ }
+ }
+
+// ******* toString ************************************************************
+ public String toString () {
+ String str = dev.toString();
+ try {
+ str += "\n " + getFpgaConfigurationStr();
+ }
+ catch ( Exception e ) {
+ }
+ return str;
+ }
+
+// ******* capabilityInfo ******************************************************
+ public String capabilityInfo ( String pf ) {
+ String str = "";
+ for ( int i=0; i<6; i++ )
+ for (int j=0; j<8; j++ )
+ if ( dev.interfaceCapabilities(i,j) ) {
+ if ( ! str.equals("") )
+ str+="\n";
+ if (i*8+j < capabilityStrings.length)
+ str+=pf+capabilityStrings[i*8+j];
+ else
+ str+=pf+i+"."+j;
+ }
+ return str;
+ }
+}
+
Index: usb_fpga_1_2/trunk/java/ztex/ZtexIhxFile1.java
===================================================================
--- usb_fpga_1_2/trunk/java/ztex/ZtexIhxFile1.java (nonexistent)
+++ usb_fpga_1_2/trunk/java/ztex/ZtexIhxFile1.java (revision 2)
@@ -0,0 +1,153 @@
+/*!
+ Java Driver API for the ZTEX Firmware Kit
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+/*
+ Reads an ihx file with ZTEX descriptor 1
+*/
+package ztex;
+
+import java.io.*;
+import java.util.*;
+
+public class ZtexIhxFile1 extends IhxFile {
+ private static final int defaultZtexDescriptorOffs = 0x6c;
+
+ private int ztexDescriptorOffs = defaultZtexDescriptorOffs;
+
+ private byte productId[] = { 0,0,0,0 }; // product ID from the ZTEX descpriptor, not the USB product ID
+ private byte fwVersion = 0;
+ private byte interfaceVersion = 0;
+ private byte interfaceCapabilities[] = { 0,0,0,0, 0,0 };
+ private byte moduleReserved[] = { 0,0,0,0, 0,0,0,0, 0,0,0,0 };
+ private char snString[] = new char[10];
+
+// ******* ZtexIhxFile1 ********************************************************
+ public ZtexIhxFile1( String fileName, int pZtexDescriptorOffs ) throws IOException, IhxFileDamagedException, IncompatibleFirmwareException {
+ super( fileName );
+
+ ztexDescriptorOffs = pZtexDescriptorOffs;
+
+ if ( ihxData[ztexDescriptorOffs]!=40 || ihxData[ztexDescriptorOffs+1]!=1 || ihxData[ztexDescriptorOffs+2]!='Z' || ihxData[ztexDescriptorOffs+3]!='T' || ihxData[ztexDescriptorOffs+4]!='E' || ihxData[ztexDescriptorOffs+5]!='X' )
+ throw new IncompatibleFirmwareException( "Invalid ZTEX descriptor" );
+
+ productId[0] = (byte) ihxData[ztexDescriptorOffs+6];
+ productId[1] = (byte) ihxData[ztexDescriptorOffs+7];
+ productId[2] = (byte) ihxData[ztexDescriptorOffs+8];
+ productId[3] = (byte) ihxData[ztexDescriptorOffs+9];
+ fwVersion = (byte) ihxData[ztexDescriptorOffs+10];
+ interfaceVersion = (byte) ihxData[ztexDescriptorOffs+11];
+ interfaceCapabilities[0] = (byte) ihxData[ztexDescriptorOffs+12];
+ interfaceCapabilities[1] = (byte) ihxData[ztexDescriptorOffs+13];
+ interfaceCapabilities[2] = (byte) ihxData[ztexDescriptorOffs+14];
+ interfaceCapabilities[3] = (byte) ihxData[ztexDescriptorOffs+15];
+ interfaceCapabilities[4] = (byte) ihxData[ztexDescriptorOffs+16];
+ interfaceCapabilities[5] = (byte) ihxData[ztexDescriptorOffs+17];
+ moduleReserved[0] = (byte) ihxData[ztexDescriptorOffs+18];
+ moduleReserved[1] = (byte) ihxData[ztexDescriptorOffs+19];
+ moduleReserved[2] = (byte) ihxData[ztexDescriptorOffs+20];
+ moduleReserved[3] = (byte) ihxData[ztexDescriptorOffs+21];
+ moduleReserved[4] = (byte) ihxData[ztexDescriptorOffs+22];
+ moduleReserved[5] = (byte) ihxData[ztexDescriptorOffs+23];
+ moduleReserved[6] = (byte) ihxData[ztexDescriptorOffs+24];
+ moduleReserved[7] = (byte) ihxData[ztexDescriptorOffs+25];
+ moduleReserved[8] = (byte) ihxData[ztexDescriptorOffs+26];
+ moduleReserved[9] = (byte) ihxData[ztexDescriptorOffs+27];
+ moduleReserved[10] = (byte) ihxData[ztexDescriptorOffs+28];
+ moduleReserved[11] = (byte) ihxData[ztexDescriptorOffs+29];
+
+ for (int i=0; i<10; i++ ) {
+ int b = ihxData[ztexDescriptorOffs+30+i];
+ if ( b>=0 && b<=255 ) {
+ snString[i] = (char) b;
+ }
+ else {
+ throw new IncompatibleFirmwareException( "Invalid serial number string" );
+ }
+ }
+
+ // ensure word bounded upload data
+ for ( int i=0; i+1=0 )
+ ihxData[i] = 0;
+ }
+
+ public ZtexIhxFile1( String fileName ) throws IOException, IhxFileDamagedException, IncompatibleFirmwareException {
+ this( fileName, defaultZtexDescriptorOffs );
+ }
+
+// ******* productId ***********************************************************
+ public final byte[] productId() {
+ return productId;
+ }
+
+ public int productId( int i ) {
+ return productId[i] & 255;
+ }
+
+// ******* fwVersion ***********************************************************
+ public final int fwVersion() {
+ return fwVersion & 255;
+ }
+
+// ******* interfaceVersion *****************************************************
+ public final int interfaceVersion() {
+ return interfaceVersion & 255;
+ }
+
+// ******* interfaceCapabilities ************************************************
+ public final byte[] interfaceCapabilities() {
+ return interfaceCapabilities;
+ }
+
+ public final int interfaceCapabilities( int i ) {
+ return interfaceCapabilities[i] & 255;
+ }
+
+// ******* moduleReserved ******************************************************
+ public final byte[] moduleReserved() {
+ return moduleReserved;
+ }
+
+ public final int moduleReserved( int i ) {
+ return moduleReserved[i] & 255;
+ }
+// ******* snString ************************************************************
+ public final String snString() {
+ return new String( snString );
+ }
+
+// ******* setSnString **********************************************************
+ public final void setSnString( String s ) throws IncompatibleFirmwareException {
+ if ( s.length()>10 )
+ throw new IncompatibleFirmwareException( "Serial number too long (max. 10 characters)" );
+
+ int i=0;
+ for (; i=(byte) '0' && b<=(byte) '9' )
+ return b-(byte) '0';
+ if ( b>=(byte) 'a' && b<=(byte) 'f' )
+ return 10+b-(byte) 'a';
+ if ( b>=(byte) 'A' && b<=(byte) 'F' )
+ return 10+b-(byte) 'A';
+ if ( b == -1 )
+ throw new IhxParseException( "Inexpected end of file" );
+ throw new IhxParseException( "Hex digit expected: " + (char) b );
+ }
+
+// ******* readHexByte *********************************************************
+ private static final int readHexByte(InputStream in) throws IOException, IhxParseException {
+ return (readHexDigit(in) << 4) | readHexDigit(in);
+ }
+
+// ******* IhxFile *************************************************************
+ public IhxFile ( String fileName ) throws IOException, IhxFileDamagedException {
+ InputStream in = JInputStream.getInputStream( fileName );
+ int b, len, cs, addr;
+ byte buf[] = new byte[255];
+ boolean eof = false;
+ int line = 0;
+
+ for ( int i=0; i=0 ) System.err.println ( "Warning: Memory at position " + Integer.toHexString(i) + " overwritten" );
+ ihxData[addr+i] = (short) (buf[i] & 255);
+ }
+ }
+ else if (b == 1 ) { // eof record
+ eof = true;
+ }
+ else {
+ throw new IhxParseException( "Invalid record type: " + b );
+ }
+ }
+ }
+ catch ( IhxParseException e ) {
+ throw new IhxFileDamagedException ( fileName, line, e.getLocalizedMessage() );
+ }
+
+ try {
+ in.close();
+ }
+ catch ( Exception e ) {
+ System.err.println( "Warning: Error closing file " + fileName + ": " + e.getLocalizedMessage() );
+ }
+ }
+
+// ******* dataInfo ************************************************************
+ public void dataInfo( PrintStream out ) {
+ int addr=-1;
+ for ( int i=0; i<=65536; i++ ) { // data
+ if ( (i==65536 || ihxData[i]<0) && addr>=0 ) {
+ System.out.println( i-addr + " Bytes from " + Integer.toHexString(addr) + " to " + Integer.toHexString(i-1) );
+ addr = -1;
+ }
+ if ( i<65536 && ihxData[i]>=0 && addr<0 )
+ addr = i;
+ }
+ }
+
+}
+
Index: usb_fpga_1_2/trunk/java/ztex/EzUsb.java
===================================================================
--- usb_fpga_1_2/trunk/java/ztex/EzUsb.java (nonexistent)
+++ usb_fpga_1_2/trunk/java/ztex/EzUsb.java (revision 2)
@@ -0,0 +1,86 @@
+/*!
+ Java Driver API for the ZTEX Firmware Kit
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+/*
+ Upload firmware to Cypress EZ-USB device
+*/
+package ztex;
+
+import java.io.*;
+import java.util.*;
+
+import ch.ntb.usb.*;
+
+public class EzUsb {
+// ******* reset **************************************************************
+ public static void reset ( int handle, boolean r ) throws FirmwareUploadException {
+ byte buffer[] = { (byte) (r ? 1 : 0) };
+ int k = LibusbJava.usb_control_msg(handle, 0x40, 0xA0, 0xE600, 0, buffer, 1, 1000); // upload j bytes
+ if ( k<0 )
+ throw new FirmwareUploadException( LibusbJava.usb_strerror() + ": unable to set reset="+buffer[0] );
+ else if ( k!=1 )
+ throw new FirmwareUploadException( "Unable to set reset="+buffer[0] );
+ try {
+ Thread.sleep( 50 );
+ }
+ catch ( InterruptedException e ) {
+ }
+ }
+
+// ******* uploadFirmware ******************************************************
+// returns upload time in ms
+ public static long uploadFirmware (int handle, IhxFile ihxFile ) throws FirmwareUploadException {
+ final int transactionBytes = 256;
+ byte[] buffer = new byte[transactionBytes];
+ long t0 = new Date().getTime();
+
+ reset( handle, true ); // reset = 1
+
+ int j = 0;
+ for ( int i=0; i<=ihxFile.ihxData.length; i++ ) {
+ if ( i >= ihxFile.ihxData.length || ihxFile.ihxData[i] < 0 || j >=transactionBytes ) {
+ if ( j > 0 ) {
+ int k = LibusbJava.usb_control_msg(handle, 0x40, 0xA0, i-j, 0, buffer, j, 1000); // upload j bytes
+ if ( k<0 )
+ throw new FirmwareUploadException(LibusbJava.usb_strerror());
+ else if ( k!=j )
+ throw new FirmwareUploadException();
+ try {
+ Thread.sleep( 1 ); // to avoid package loss
+ }
+ catch ( InterruptedException e ) {
+ }
+ }
+ j = 0;
+ }
+
+ if ( i < ihxFile.ihxData.length && ihxFile.ihxData[i] >= 0 && ihxFile.ihxData[i] <= 255 ) {
+ buffer[j] = (byte) ihxFile.ihxData[i];
+ j+=1;
+ }
+ }
+
+ try {
+ EzUsb.reset(handle,false); // error (may caused re-numeration) can be ignored
+ }
+ catch ( FirmwareUploadException e ) {
+ }
+ return new Date().getTime() - t0;
+ }
+}
+
Index: usb_fpga_1_2/trunk/java/ztex/ZtexScanBus1.java
===================================================================
--- usb_fpga_1_2/trunk/java/ztex/ZtexScanBus1.java (nonexistent)
+++ usb_fpga_1_2/trunk/java/ztex/ZtexScanBus1.java (revision 2)
@@ -0,0 +1,104 @@
+/*!
+ Java Driver API for the ZTEX Firmware Kit
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+/*
+ Scan bus for devices with ZTEX descriptor 1 and/or Cypress EZ-USB FX2 devices
+*/
+package ztex;
+
+import java.io.*;
+import java.util.*;
+
+import ch.ntb.usb.*;
+
+public class ZtexScanBus1 {
+ private Vector devices = new Vector();
+
+// ******* ZtexScanBus1 ********************************************************
+ public ZtexScanBus1 (int usbVendorId, int usbProductId, boolean scanCypress, boolean quiet, int interfaceVersion, int productId0, int productId1, int productId2, int productId3 ) {
+ LibusbJava.usb_find_busses();
+ LibusbJava.usb_find_devices();
+
+ Usb_Bus bus = LibusbJava.usb_get_busses();
+
+ while ( bus != null ) {
+ Usb_Device dev = bus.getDevices();
+ while ( dev != null ) {
+ try {
+ try {
+ ZtexDevice1 zdev = new ZtexDevice1( dev, usbVendorId, usbProductId );
+ if ( ( scanCypress && zdev.isCypress() ) ||
+ ( zdev.valid() && (interfaceVersion<0 || zdev.interfaceVersion()==interfaceVersion) && zdev.compatible(productId0, productId1, productId2, productId3) ) ) {
+ devices.add( zdev );
+ }
+ }
+ catch ( ZtexDescriptorException e ) {
+ if ( scanCypress && usbVendorId == ZtexDevice1.cypressVendorId && usbProductId == ZtexDevice1.cypressProductId ) {
+ try {
+ ZtexDevice1 zdev = new ZtexDevice1( dev, -1, -1 );
+ if ( zdev.isCypress() ) devices.add( zdev );
+ }
+ catch ( ZtexDescriptorException e2 ) {
+ if ( ! quiet )
+ System.err.println( e2.getLocalizedMessage() ); // should never occur
+ }
+ }
+ else {
+ if ( ! quiet )
+ System.err.println( e.getLocalizedMessage() );
+ }
+ }
+ }
+ catch ( UsbException e ) {
+ if ( ! quiet )
+ System.err.println( e.getLocalizedMessage() );
+ }
+ dev = dev.getNext();
+ }
+ bus = bus.getNext();
+ }
+ }
+
+ public ZtexScanBus1 (int usbVendorId, int usbProductId, boolean scanCypress, boolean quiet, int interfaceVersion ) {
+ this(usbVendorId, usbProductId, scanCypress, quiet, interfaceVersion, -1,-1,-1,-1 );
+ }
+
+ public ZtexScanBus1 (int usbVendorId, int usbProductId, boolean scanCypress, boolean quiet ) {
+ this(usbVendorId, usbProductId, scanCypress, quiet, -1, -1,-1,-1,-1 );
+ }
+
+// ******* printBus ************************************************************
+ public void printBus( PrintStream out ) {
+ for (int i=0; i=devices.size() )
+ throw new IndexOutOfBoundsException( "Device number out of range. Valid numbers are 0.." + (devices.size()-1) );
+ return devices.elementAt(i);
+ }
+}
+
Index: usb_fpga_1_2/trunk/java/ztex/ZtexDevice1.java
===================================================================
--- usb_fpga_1_2/trunk/java/ztex/ZtexDevice1.java (nonexistent)
+++ usb_fpga_1_2/trunk/java/ztex/ZtexDevice1.java (revision 2)
@@ -0,0 +1,236 @@
+/*!
+ Java Driver API for the ZTEX Firmware Kit
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+/*
+ USB device with ZTEX descriptor 1 and/or Cypress EZ-USB FX2 device
+*/
+package ztex;
+
+import java.io.*;
+import java.util.*;
+
+import ch.ntb.usb.*;
+
+public class ZtexDevice1 {
+ public static final int cypressVendorId = 0x4b4;
+ public static final int cypressProductId = 0x8613;
+
+ private Usb_Device dev = null;
+ private boolean isCypress = false; // true if Cypress device
+ private boolean valid = false; // true if descriptor 1 is available
+ private int usbVendorId = -1;
+ private int usbProductId = -1;
+ private String manufacturerString = null;
+ private String productString = null;
+ private String snString = null;
+ private byte productId[] = { 0,0,0,0 }; // product ID from the ZTEX descpriptor, not the USB product ID
+ private byte fwVersion = 0;
+ private byte interfaceVersion = 0;
+ private byte interfaceCapabilities[] = { 0,0,0,0, 0,0 };
+ private byte moduleReserved[] = { 0,0,0,0, 0,0,0,0, 0,0,0,0 };
+
+// ******* byteArrayString *****************************************************
+ public static String byteArrayString ( byte buf[] ) {
+ String s = new String( "" );
+ for ( int i = 0; i 0 ) {
+ if ( dd.getIManufacturer() > 0 )
+ manufacturerString = LibusbJava.usb_get_string_simple( handle, dd.getIManufacturer() );
+ if ( dd.getIProduct() > 0 )
+ productString = LibusbJava.usb_get_string_simple( handle, dd.getIProduct() );
+ if ( dd.getISerialNumber() > 0 )
+ snString = LibusbJava.usb_get_string_simple( handle, dd.getISerialNumber() );
+
+ if ( usbVendorId == pUsbVendorId && usbProductId == pUsbProductId ) {
+ if ( snString == null ) {
+ LibusbJava.usb_close(handle);
+ throw new ZtexDescriptorException( dev, "Not a ZTEX device" ); // ZTEX devices always have a SN. See also the next comment a few lines below
+ }
+
+ byte[] buf = new byte[42];
+ int i = LibusbJava.usb_control_msg(handle, 0xc0, 0x22, 0, 0, buf, 40, 500); // Failing of this may cause problems under windows. Therefore we check for the SN above.
+ if ( i < 0 ) {
+ LibusbJava.usb_close(handle);
+ throw new ZtexDescriptorException( dev, "Error reading ZTEX descriptor: " + LibusbJava.usb_strerror() );
+ }
+ else if ( i != 40 ) {
+ LibusbJava.usb_close(handle);
+ throw new ZtexDescriptorException( dev, "Error reading ZTEX descriptor: Invalid size: " + i );
+ }
+ if ( buf[0]!=40 || buf[1]!=1 || buf[2]!='Z' || buf[3]!='T' || buf[4]!='E' || buf[5]!='X' ) {
+ LibusbJava.usb_close(handle);
+ throw new ZtexDescriptorException( dev, "Invalid ZTEX descriptor" );
+ }
+ productId[0] = buf[6];
+ productId[1] = buf[7];
+ productId[2] = buf[8];
+ productId[3] = buf[9];
+ fwVersion = buf[10];
+ interfaceVersion = buf[11];
+ interfaceCapabilities[0] = buf[12];
+ interfaceCapabilities[1] = buf[13];
+ interfaceCapabilities[2] = buf[14];
+ interfaceCapabilities[3] = buf[15];
+ interfaceCapabilities[4] = buf[16];
+ interfaceCapabilities[5] = buf[17];
+ moduleReserved[0] = buf[18];
+ moduleReserved[1] = buf[19];
+ moduleReserved[2] = buf[20];
+ moduleReserved[3] = buf[21];
+ moduleReserved[4] = buf[22];
+ moduleReserved[5] = buf[23];
+ moduleReserved[6] = buf[24];
+ moduleReserved[7] = buf[25];
+ moduleReserved[8] = buf[26];
+ moduleReserved[9] = buf[27];
+ moduleReserved[10] = buf[28];
+ moduleReserved[11] = buf[29];
+
+ valid = true;
+ }
+ }
+ else {
+ throw new UsbException( dev, "Error opening device: " + LibusbJava.usb_strerror() );
+ }
+
+ LibusbJava.usb_close(handle);
+ }
+
+// ******* toString ************************************************************
+ public String toString () {
+ return "bus=" + dev.getBus().getDirname() + " device=" + dev.getFilename() +
+ "\n " + ( isCypress ? "Cypress" : "" ) +
+ ( manufacturerString == null ? "" : (" Manufacturer=\"" + manufacturerString + "\"") ) +
+ ( productString == null ? "" : (" Product=\"" + productString + "\"") ) +
+ ( snString == null ? "" : (" SerialNumber=\"" + snString + "\"") ) +
+ ( valid ? "\n productID=" + byteArrayString(productId) + " fwVer="+(fwVersion & 255) + " ifVer="+(interfaceVersion & 255) : "" );
+ }
+
+// ******* compatible **********************************************************
+ public final boolean compatible( int productId0, int productId1, int productId2, int productId3 ) {
+ return ( productId[0]==0 || productId0<=0 || (productId[0] & 255) == productId0 ) &&
+ ( productId[1]==0 || productId1<=0 || (productId[1] & 255) == productId1 ) &&
+ ( productId[2]==0 || productId2<=0 || (productId[2] & 255) == productId2 ) &&
+ ( productId[3]==0 || productId3<=0 || (productId[3] & 255) == productId3 );
+ }
+
+// ******* dev *****************************************************************
+ public final Usb_Device dev() {
+ return dev;
+ }
+
+// ******* isCypress ***********************************************************
+ public final boolean isCypress() {
+ return isCypress;
+ }
+
+// ******* valid ***************************************************************
+ public final boolean valid() {
+ return valid;
+ }
+
+// ******* usbVendorId *********************************************************
+ public final int usbVendorId() {
+ return usbVendorId;
+ }
+
+// ******* usbProductId *********************************************************
+ public final int usbProductId() {
+ return usbProductId;
+ }
+
+// ******* manufacturerString **************************************************
+ public final String manufacturerString() {
+ return manufacturerString;
+ }
+
+// ******* productString *******************************************************
+ public final String productString() {
+ return productString;
+ }
+
+// ******* snString ************************************************************
+ public final String snString() {
+ return snString;
+ }
+
+// ******* productId ***********************************************************
+ public final byte[] productId() {
+ return productId;
+ }
+
+ public int productId( int i ) {
+ return productId[i] & 255;
+ }
+
+// ******* fwVersion ***********************************************************
+ public final int fwVersion() {
+ return fwVersion & 255;
+ }
+
+// ******* interfaceVersion *****************************************************
+ public final int interfaceVersion() {
+ return interfaceVersion & 255;
+ }
+
+// ******* interfaceCapabilities ************************************************
+ public final byte[] interfaceCapabilities() {
+ return interfaceCapabilities;
+ }
+
+ public final int interfaceCapabilities( int i ) {
+ return interfaceCapabilities[i] & 255;
+ }
+
+ public final boolean interfaceCapabilities( int i, int j ) {
+ return (i>=0) && (i<=5) && (j>=0) && (j<8) &&
+ (((interfaceCapabilities[i] & 255) & (1 << j)) != 0);
+ }
+
+// ******* moduleReserved ******************************************************
+ public final byte[] moduleReserved() {
+ return moduleReserved;
+ }
+
+ public final int moduleReserved( int i ) {
+ return moduleReserved[i] & 255;
+ }
+
+}
Index: usb_fpga_1_2/trunk/java/Makefile
===================================================================
--- usb_fpga_1_2/trunk/java/Makefile (nonexistent)
+++ usb_fpga_1_2/trunk/java/Makefile (revision 2)
@@ -0,0 +1,39 @@
+#########################
+# configuration section #
+#########################
+
+ZTEXPREFIX=..
+
+JARTARGET=FWLoader.jar
+CLASSTARGETS=FWLoader.class
+
+################################
+# DO NOT CHANAGE THE FOLLOWING #
+################################
+
+.PHONY: all jar clean distclean
+
+JAVAC=javac
+CLASSPATH:=.:$(ZTEXPREFIX)/libusbJava:$(ZTEXPREFIX)/java:$(CLASSPATH)
+INCLUDES=-I $(ZTEXPREFIX)/include/
+CLASSEXTRADEPS:=$(shell echo $(ZTEXPREFIX)/java/ztex/*.java)
+
+all : jar
+
+all : $(JARTARGET)
+
+%.class: %.java $(CLASSEXTRADEPS)
+ $(JAVAC) -cp "$(CLASSPATH)" $< $(CLASSEXTRADEPS)
+
+$(JARTARGET) : $(CLASSTARGETS) $(EXTRAJARFILES)
+ jar cf $(JARTARGET) *.class $(EXTRAJARFILES) -C $(ZTEXPREFIX)/libusbJava . $(shell cd $(ZTEXPREFIX)/java; ls ztex/*.class | while read a; do echo "-C $(ZTEXPREFIX)/java $$a"; done)
+
+clean:
+ rm -f *~ *.bak *.old
+ rm -f *.class
+ rm -f *.rel *.rst *.lnk *.lst *.map *.asm *.sym *.mem *.tmp.c
+
+distclean: clean
+ rm -f $(JARTARGET)
+ rm -f ztex/*.class
+ rm -f *.ihx
Index: usb_fpga_1_2/trunk/include/ztex-descriptors.h
===================================================================
--- usb_fpga_1_2/trunk/include/ztex-descriptors.h (nonexistent)
+++ usb_fpga_1_2/trunk/include/ztex-descriptors.h (revision 2)
@@ -0,0 +1,423 @@
+/*!
+ ZTEX Firmware Kit for EZ-USB Microcontrollers
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+/*
+ Defines the USB descriptors
+*/
+
+#ifndef[ZTEX_DESCRIPTORS_H]
+#define[ZTEX_DESCRIPTORS_H]
+
+#define[ZTEX_DESCRIPTOR_OFFS][0x06c]
+#define[ZTEX_DESCRIPTOR_LEN][40]
+
+xdata at ZTEX_DESCRIPTOR_OFFS BYTE ZTEX_DESCRIPTOR;
+
+/* ZTEX descriptor version. Must be 1. */
+xdata at ZTEX_DESCRIPTOR_OFFS+1 BYTE ZTEX_DESCRIPTOR_VERSION;
+
+/* Must not be modified, ID="ZTEX" */
+xdata at ZTEX_DESCRIPTOR_OFFS+2 BYTE ZTEXID[4];
+
+/*
+ Product ID and firmware compatibility information.
+
+ A firmware can overwrite an installed one if
+ if ( INSTALLED.PRODUCTID[0]==0 || PRODUCTID[0]==0 || INSTALLED.PRODUCTID[0]==PRODUCTID[0] ) &&
+ ( INSTALLED.PRODUCTID[1]==0 || PRODUCTID[1]==0 || INSTALLED.PRODUCTID[1]==PRODUCTID[1] ) &&
+ ( INSTALLED.PRODUCTID[2]==0 || PRODUCTID[2]==0 || INSTALLED.PRODUCTID[2]==PRODUCTID[2] ) &&
+ ( INSTALLED.PRODUCTID[3]==0 || PRODUCTID[3]==0 || INSTALLED.PRODUCTID[3]==PRODUCTID[3] )
+
+ Reserved Product ID's:
+
+ 0.0.0.0 // default Product ID (no product specified)
+ 1.*.*.* // may be used for experimental purposes
+ 10.*.*.* // used for ZTEX products
+
+ Please contact me (http://www.ztex.de --> Impressum/Kontakt) if you want to register/reserve a Product ID (range).
+*/
+xdata at ZTEX_DESCRIPTOR_OFFS+6 BYTE PRODUCT_ID[4];
+
+/* Firmware version, may be used to distinguish seveveral firmware versions */
+xdata at ZTEX_DESCRIPTOR_OFFS+10 BYTE FW_VERSION;
+
+/* Interface version. Must be 1. */
+xdata at ZTEX_DESCRIPTOR_OFFS+11 BYTE INTERFACE_VERSION;
+
+/*
+ Standard interface capabilities:
+ 0.0 : EEPROM read/write, see ztex-eeprom.h
+ 0.1 : FPGA configuration, see ztex-fpga.h
+*/
+xdata at ZTEX_DESCRIPTOR_OFFS+12 BYTE INTERFACE_CAPABILITIES[6];
+
+/* Space for settings which depends on PRODUCT_ID, e.g extra capabilities */
+xdata at ZTEX_DESCRIPTOR_OFFS+18 BYTE MODULE_RESERVED[12];
+
+/*
+ Serial number string
+ default: "0000000000"
+ Should only be modified by the the firmware upload software
+*/
+xdata at ZTEX_DESCRIPTOR_OFFS+30 BYTE SN_STRING[10];
+
+/* Are Vendor ID and Product ID defined? */
+#ifndef[USB_VENDOR_ID]
+#error[No USB Vendor ID defined (you may use the Cypress Vendor ID 0x04b4 (only !) for development purposes)]
+#endif
+
+#ifndef[USB_PRODUCT_ID]
+#error[No USB Product ID defined (you may use the FX2 Product ID 0x8613 from Cypress (only !) during the development process)]
+#endif
+
+/* Prepare the Interfaces, i.e. check which interfaces are defined */
+#define[CONFIGURE_INTERFACE(][);][
+#define[CONFIG_INTERFACE$0]
+#ifeq[EP1IN_INTERFACE][$0]
+#elifeq[EP1OUT_INTERFACE][$0]
+#elifeq[EP2_INTERFACE][$0]
+#elifeq[EP4_INTERFACE][$0]
+#elifeq[EP6_INTERFACE][$0]
+#elifneq[EP8_INTERFACE][$0]
+#udefine[CONFIG_INTERFACE$0]
+#endif
+#ifdef[CONFIG_INTERFACE$0]
+//Interface $0: YES
+#else
+//Interface $0: NO
+#endif]
+
+CONFIGURE_INTERFACE(0);
+CONFIGURE_INTERFACE(1);
+CONFIGURE_INTERFACE(2);
+CONFIGURE_INTERFACE(3);
+
+/* define the ZTEX descriptor */
+void abscode_identity() _naked
+{
+ _asm
+ .area ABSCODE (ABS,CODE)
+
+ .org ZTEX_DESCRIPTOR_OFFS
+ .db ZTEX_DESCRIPTOR_LEN
+
+ .org _ZTEX_DESCRIPTOR_VERSION
+ .db 1
+
+ .org _ZTEXID
+ .ascii "ZTEX"
+
+ .org _PRODUCT_ID
+ .db PRODUCT_ID_0
+ .db PRODUCT_ID_1
+ .db PRODUCT_ID_2
+ .db PRODUCT_ID_3
+
+ .org _FW_VERSION
+ .db FWVER
+
+ .org _INTERFACE_VERSION
+ .db 1
+
+ .org _INTERFACE_CAPABILITIES
+ .db 0
+#ifdef[@CAPABILITY_EEPROM;]
+#nolf
+ + 1
+#endif
+#ifdef[@CAPABILITY_FPGA;]
+#nolf
+ + 2
+#endif
+ .db 0
+ .db 0
+ .db 0
+ .db 0
+ .db 0
+
+ .org _MODULE_RESERVED
+ .db MODULE_RESERVED_00
+ .db MODULE_RESERVED_01
+ .db MODULE_RESERVED_02
+ .db MODULE_RESERVED_03
+ .db MODULE_RESERVED_04
+ .db MODULE_RESERVED_05
+ .db MODULE_RESERVED_06
+ .db MODULE_RESERVED_07
+ .db MODULE_RESERVED_08
+ .db MODULE_RESERVED_09
+ .db MODULE_RESERVED_10
+ .db MODULE_RESERVED_11
+
+ .org _SN_STRING
+ .ascii "0000000000"
+
+ .area CSEG (CODE)
+ _endasm;
+}
+
+/* *********************************************************************
+ ***** strings *******************************************************
+ ********************************************************************* */
+code char manufacturerString[] = MANUFACTURER_STRING;
+code char productString[] = PRODUCT_STRING;
+code char configurationString[] = CONFIGURATION_STRING;
+
+
+/* *********************************************************************
+ ***** descriptors ***************************************************
+ ********************************************************************* */
+#define[EP_DESCRIPTOR(][);][
+ // Endpoint $0 descriptor
+ ,7 // 0, Descriptor length
+ ,5 // 1, Descriptor type
+#ifeq[$0][1IN]
+ ,0x81 // 2, direction=output, address=1
+#elifeq[$0][1OUT]
+ ,0x01 // 2, direction=output, address=1
+#elifeq[EP$0_DIR][IN]
+ ,0x80+$0 // 2, direction=output, address=$0
+#elifeq[EP$0_DIR][OUT]
+ ,$0 // 2, direction=input, address=$0
+#else
+#error[Invalid direction for endpoint $0 (`IN' or `ÒUT' expected)]
+#endif
+#ifeq[EP$0_TYPE][ISO]
+ ,1 // 3, ISO transferns
+#elifeq[EP$0_TYPE][BULK]
+ ,2 // 3, BULK transferns
+#elifeq[EP$0_TYPE][INT]
+ ,3 // 3, INT transferns
+#else
+#error[Invalid type for endpoint $0: `EP$0_TYPE' (`ISO', 'BULK' or `INT' expected)]
+#endif
+#ifeq[EP$0_SIZE][64] // to avoid stupid warnings
+ ,64 // 4, max. packet size (L)
+ ,0 // 5, max. packet size (H)
+#else
+#ifdef[HIGH_SPEED]
+ ,EP$0_SIZE & 0xff // 4, max. packet size (L)
+ ,EP$0_SIZE >> 8 // 5, max. packet size (H)
+#else
+ ,64 // 4, max. packet size (L)
+ ,0 // 5, max. packet size (H)
+#endif
+#endif
+#ifeq[EP$0_TYPE][ISO]
+ ,1 // 6, Polling interval
+#else
+ ,0 // 6, Polling interval
+#endif
+]
+
+#define[INTERFACE_DESCRIPTOR(][);][
+ // Interface $0 descriptor
+ ,9 // 0, Descriptor length
+ ,0x04 // 1, Descriptor type
+ ,0 // 2, Zero-based index of this interface
+#ifneq[$0][0]
+#ifdef[CONFIG_INTERFACE0]
+ +1
+#endif
+#ifneq[$0][1]
+#ifdef[CONFIG_INTERFACE1]
+ +1
+#endif
+#ifneq[$0][2]
+#ifdef[CONFIG_INTERFACE2]
+ +1
+#endif
+#endif
+#endif
+#endif
+ ,0 // 3, Alternate setting
+ ,0 // 4, Number of end points
+#ifeq[EP1IN_INTERFACE][$0]
+ +1
+#endif
+#ifeq[EP1OUT_INTERFACE][$0]
+ +1
+#endif
+#ifeq[EP2_INTERFACE][$0]
+ +1
+#endif
+#ifeq[EP4_INTERFACE][$0]
+ +1
+#endif
+#ifeq[EP6_INTERFACE][$0]
+ +1
+#endif
+#ifeq[EP8_INTERFACE][$0]
+ +1
+#endif
+ ,0xff // 5, Interface class
+ ,0xff // 6, Interface sub class
+ ,0xff // 7, Interface protocol
+ ,0 // 8, Index of interface string descriptor
+#ifeq[EP1IN_INTERFACE][$0]
+ EP_DESCRIPTOR(1IN);
+#endif
+#ifeq[EP1OUT_INTERFACE][$0]
+ EP_DESCRIPTOR(1OUT);
+#endif
+#ifeq[EP2_INTERFACE][$0]
+ EP_DESCRIPTOR(2);
+#endif
+#ifeq[EP4_INTERFACE][$0]
+ EP_DESCRIPTOR(4);
+#endif
+#ifeq[EP6_INTERFACE][$0]
+ EP_DESCRIPTOR(6);
+#endif
+#ifeq[EP8_INTERFACE][$0]
+ EP_DESCRIPTOR(8);
+#endif
+]
+
+#define[APPEND_PADBYTE(][);][code BYTE $0_PadByte[2-(sizeof($0) & 1)] = { 0 };]
+
+#ifdef[PAD_BYTE] // to ensure word alignment of the descriptors; PAD_BYTE is defined automatically by bmpsdcc script
+code BYTE PadByte = 0;
+#endif
+
+code BYTE DeviceDescriptor[] =
+ {
+ 18, // 0, Descriptor length
+ 0x01, // 1, Descriptor type
+ 0x00, // 2, Specification Version (L)
+ 0x02, // 3, Specification Version (H)
+ 0xff, // 4, Device class
+ 0xff, // 5, Device sub-class
+ 0xff, // 6, Device protocol
+ 64, // 7, Maximum packet size for EP0
+ (USB_VENDOR_ID) & 255, // 8, VENDOR_ID (L)
+ (USB_VENDOR_ID) >> 8, // 9, VENDOR_ID (H)
+ (USB_PRODUCT_ID) & 255, // 10, PRODUCT_ID (L)
+ (USB_PRODUCT_ID) >> 8, // 11, PRODUCT_ID (H)
+ 0x00, // 12, device release number (BCD, L)
+ 0x00, // 13, device release number (BCD, H)
+ 1, // 14, Manufacturer string index
+ 2, // 15, Product string index
+ 3, // 16, Serial number string index
+ 1 // 17, Number of configurations
+ };
+
+code BYTE DeviceQualifierDescriptor[] =
+ {
+ 10, // 0, Descriptor length
+ 0x06, // 1, Decriptor type
+ 0x00, // 2, Specification Version (L)
+ 0x02, // 3, Specification Version (H)
+ 0xff, // 4, Device class
+ 0xff, // 5, Device sub-class
+ 0xff, // 6, Device protocol
+ 64, // 7, Maximum packet size (EP0?)
+ 1, // 8, Number of configurations
+ 0, // 9, Reserved, must be zero
+ };
+
+code BYTE HighSpeedConfigDescriptor[] =
+ {
+#define[HIGH_SPEED]
+ 9 // 0, Descriptor length
+ ,0x02 // 1, Decriptor type
+ ,sizeof(HighSpeedConfigDescriptor) & 0xff // 2, Total length (LSB)
+// ,sizeof(HighSpeedConfigDescriptor) >> 8 // 3, Total length (MB)
+ ,0 // 3, To avoid warnings, descriptor length will never exceed 255 bytes
+ ,0 // 4, Number of Interfaces
+#ifdef[CONFIG_INTERFACE0]
+ +1
+#endif
+#ifdef[CONFIG_INTERFACE1]
+ +1
+#endif
+#ifdef[CONFIG_INTERFACE2]
+ +1
+#endif
+#ifdef[CONFIG_INTERFACE3]
+ +1
+#endif
+
+ ,1 // 5, Configuration number
+ ,4 // 6, Configuration string
+ ,0xc0 // 7, Attributes: bus and self powered
+ ,50 // Maximum bus power 100 mA
+#ifdef[CONFIG_INTERFACE0]
+ INTERFACE_DESCRIPTOR(0);
+#endif
+#ifdef[CONFIG_INTERFACE1]
+ INTERFACE_DESCRIPTOR(1);
+#endif
+#ifdef[CONFIG_INTERFACE2]
+ INTERFACE_DESCRIPTOR(2);
+#endif
+#ifdef[CONFIG_INTERFACE3]
+ INTERFACE_DESCRIPTOR(3);
+#endif
+#udefine[HIGH_SPEED]
+ };
+APPEND_PADBYTE(HighSpeedConfigDescriptor);
+
+code BYTE FullSpeedConfigDescriptor[] =
+ {
+ 9 // 0, Descriptor length
+ ,0x02 // 1, Decriptor type
+ ,sizeof(HighSpeedConfigDescriptor) & 0xff // 2, Total length (LSB)
+// ,sizeof(HighSpeedConfigDescriptor) >> 8 // 3, Total length (MSB)
+ ,0 // 3, To avoid warnings, descriptor length will never exceed 255 bytes
+ ,0 // 4, Number of Interfaces
+#ifdef[CONFIG_INTERFACE0]
+ +1
+#endif
+#ifdef[CONFIG_INTERFACE1]
+ +1
+#endif
+#ifdef[CONFIG_INTERFACE2]
+ +1
+#endif
+#ifdef[CONFIG_INTERFACE3]
+ +1
+#endif
+
+ ,1 // 5, Configuration number
+ ,4 // 6, Configuration string
+ ,0xc0 // 7, Attributes: bus and self powered
+ ,50 // Maximum bus power 100 mA
+#ifdef[CONFIG_INTERFACE0]
+ INTERFACE_DESCRIPTOR(0);
+#endif
+#ifdef[CONFIG_INTERFACE1]
+ INTERFACE_DESCRIPTOR(1);
+#endif
+#ifdef[CONFIG_INTERFACE2]
+ INTERFACE_DESCRIPTOR(2);
+#endif
+#ifdef[CONFIG_INTERFACE3]
+ INTERFACE_DESCRIPTOR(3);
+#endif
+ };
+APPEND_PADBYTE(FullSpeedConfigDescriptor);
+
+code BYTE EmptyStringDescriptor[] =
+ {
+ sizeof(EmptyStringDescriptor), // Length
+ 0x03, // Descriptor type
+ 0, 0
+ };
+
+#endif /*ZTEX_DESCRIPTORS_H*/
Index: usb_fpga_1_2/trunk/include/ztex.h
===================================================================
--- usb_fpga_1_2/trunk/include/ztex.h (nonexistent)
+++ usb_fpga_1_2/trunk/include/ztex.h (revision 2)
@@ -0,0 +1,167 @@
+/*!
+ ZTEX Firmware Kit for EZ-USB Microcontrollers
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+/*
+ Puts everything in the right order together.
+*/
+
+#ifndef[ZTEX_H]
+#define[ZTEX_H]
+
+/* *********************************************************************
+ ***** include the basic functions ***********************************
+ ********************************************************************* */
+#include[ztex-utils.h]
+
+
+/* *********************************************************************
+ ***** Flash memory support ******************************************
+ ********************************************************************* */
+#ifeq[FLASH_ENABLED][1]
+#ifeq[PRODUCT_IS][UFM-1_1]
+#include[ztex-flash1.h]
+#elifeq[PRODUCT_IS][UFM-1_2]
+#include[ztex-flash1.h]
+#else
+#warning[FLASH option is not supported by this product]
+#define[FLASH_ENABLED][0]
+#endif
+#endif
+
+
+/* *********************************************************************
+ ***** EEPROM support and some I2c helper functions ******************
+ ********************************************************************* */
+#ifneq[EEPROM_DISABLED][1]
+#include[ztex-eeprom.h]
+#endif
+
+/* *********************************************************************
+ ***** FPGA configuration support ************************************
+ ********************************************************************* */
+#ifeq[PRODUCT_IS][UFM-1_0]
+#include[ztex-fpga.h]
+#elifeq[PRODUCT_IS][UFM-1_1]
+#include[ztex-fpga.h]
+#elifeq[PRODUCT_IS][UFM-1_2]
+#include[ztex-fpga.h]
+#endif
+
+/* *********************************************************************
+ ***** define the descriptors and the interrupt routines *************
+ ********************************************************************* */
+#include[ztex-descriptors.h]
+#include[ztex-isr.h]
+
+
+/* *********************************************************************
+ ***** init_USB ******************************************************
+ ********************************************************************* */
+#define[EPXCFG(][);][ EP$0CFG =
+#ifeq[EP$0_DIR][IN]
+ bmBIT7 | bmBIT6
+#elifeq[EP$0_DIR][OUT]
+ bmBIT7
+#else
+ 0
+#endif
+#ifeq[EP$0_TYPE][BULK]
+ | bmBIT5
+#elifeq[EP$0_TYPE][ISO]
+ | bmBIT4
+#elifeq[EP$0_TYPE][INT]
+ | bmBIT5 | bmBIT4
+#endif
+#ifeq[EP$0_SIZE][1024]
+ | bmBIT3
+#endif
+#ifeq[EP$0_BUFFERS][2]
+ | bmBIT1
+#elifeq[EP$0_BUFFERS][3]
+ | bmBIT1 | bmBIT0
+#endif
+ ;
+ SYNCDELAY;
+]
+
+#define[EP1XCFG(][);][#ifeq[EP$0_TYPE][BULK]
+ EP$0CFG = bmBIT7 | bmBIT5;
+#elifeq[EP$0_TYPE][ISO]
+ EP$0CFG = bmBIT7 | bmBIT4;
+#elifeq[EP$0_TYPE][INT]
+ EP$0CFG = bmBIT7 | bmBIT5 | bmBIT4;
+#else
+ EP$0CFG = 0;
+#endif
+ SYNCDELAY;
+]
+
+void init_USB ()
+{
+
+ CPUCS = bmBIT4 | bmBIT1;
+ CKCON &= ~7;
+
+ IOA1 = 1;
+ OEA |= bmBIT1;
+
+ EA = 0;
+
+ ENABLE_AVUSB;
+
+ INIT_INTERRUPT_VECTOR(INTVEC_SUDAV, SUDAV_ISR);
+ INIT_INTERRUPT_VECTOR(INTVEC_SOF, SOF_ISR);
+ INIT_INTERRUPT_VECTOR(INTVEC_SUTOK, SUTOK_ISR);
+ INIT_INTERRUPT_VECTOR(INTVEC_SUSPEND, SUSP_ISR);
+ INIT_INTERRUPT_VECTOR(INTVEC_USBRESET, URES_ISR);
+ INIT_INTERRUPT_VECTOR(INTVEC_HISPEED, HSGRANT_ISR);
+ INIT_INTERRUPT_VECTOR(INTVEC_EP0ACK, EP0ACK_ISR);
+
+ INIT_INTERRUPT_VECTOR(INTVEC_EP0IN, EP0IN_ISR);
+ INIT_INTERRUPT_VECTOR(INTVEC_EP0OUT, EP0OUT_ISR);
+ INIT_INTERRUPT_VECTOR(INTVEC_EP1IN, EP1IN_ISR);
+ INIT_INTERRUPT_VECTOR(INTVEC_EP1OUT, EP1OUT_ISR);
+ INIT_INTERRUPT_VECTOR(INTVEC_EP2, EP2_ISR);
+ INIT_INTERRUPT_VECTOR(INTVEC_EP4, EP4_ISR);
+ INIT_INTERRUPT_VECTOR(INTVEC_EP6, EP6_ISR);
+ INIT_INTERRUPT_VECTOR(INTVEC_EP8, EP8_ISR);
+
+ EXIF &= ~bmBIT4;
+ USBIRQ = 0x7f;
+ USBIE |= 0x7f;
+ EPIRQ = 0xff;
+ EPIE = 0xff;
+
+ EUSB = 1;
+ EA = 1;
+
+ USBCS |= 0x08;
+ USBCS |= bmBIT7 | bmBIT1;
+ wait(500);
+ USBCS &= ~0x08;
+ wait(500);
+
+ EP1XCFG(1IN);
+ EP1XCFG(1OUT);
+ EPXCFG(2);
+ EPXCFG(4);
+ EPXCFG(6);
+ EPXCFG(8);
+}
+
+#endif /* ZTEX_H */
Index: usb_fpga_1_2/trunk/include/ezintavecs.h
===================================================================
--- usb_fpga_1_2/trunk/include/ezintavecs.h (nonexistent)
+++ usb_fpga_1_2/trunk/include/ezintavecs.h (revision 2)
@@ -0,0 +1,147 @@
+/*!
+ ZTEX Firmware Kit for EZ-USB Microcontrollers
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+/*
+ EZ-USB Autovectors
+*/
+
+#ifndef[EZINTAVECS_H]
+#define[EZINTAVECS_H]
+
+#include[ztex-utils.h]
+
+struct INTVEC {
+ BYTE op;
+ BYTE addrH;
+ BYTE addrL;
+};
+
+#define[INTVECS;][DEFINE_INTVEC(0x0003,INT0VEC_IE0);
+DEFINE_INTVEC(0x000b,INT1VEC_T0);
+DEFINE_INTVEC(0x0013,INT2VEC_IE1);
+DEFINE_INTVEC(0x001b,INT3VEC_T1);
+DEFINE_INTVEC(0x0023,INT4VEC_USART0);
+DEFINE_INTVEC(0x002b,INT5VEC_T2);
+DEFINE_INTVEC(0x0033,INT6VEC_RESUME);
+DEFINE_INTVEC(0x003b,INT7VEC_USART1);
+DEFINE_INTVEC(0x0043,INT8VEC_USB);
+DEFINE_INTVEC(0x004b,INT9VEC_I2C);
+DEFINE_INTVEC(0x0053,INT10VEC_GPIF);
+DEFINE_INTVEC(0x005b,INT11VEC_IE5);
+DEFINE_INTVEC(0x0063,INT12VEC_IE6);
+DEFINE_INTVEC(0x0100,INTVEC_SUDAV);
+DEFINE_INTVEC(0x0104,INTVEC_SOF);
+DEFINE_INTVEC(0x0108,INTVEC_SUTOK);
+DEFINE_INTVEC(0x010C,INTVEC_SUSPEND);
+DEFINE_INTVEC(0x0110,INTVEC_USBRESET);
+DEFINE_INTVEC(0x0114,INTVEC_HISPEED);
+DEFINE_INTVEC(0x0118,INTVEC_EP0ACK);
+DEFINE_INTVEC(0x0120,INTVEC_EP0IN);
+DEFINE_INTVEC(0x0124,INTVEC_EP0OUT);
+DEFINE_INTVEC(0x0128,INTVEC_EP1IN);
+DEFINE_INTVEC(0x012C,INTVEC_EP1OUT);
+DEFINE_INTVEC(0x0130,INTVEC_EP2);
+DEFINE_INTVEC(0x0134,INTVEC_EP4);
+DEFINE_INTVEC(0x0138,INTVEC_EP6);
+DEFINE_INTVEC(0x013C,INTVEC_EP8);
+DEFINE_INTVEC(0x0140,INTVEC_IBN);
+DEFINE_INTVEC(0x0148,INTVEC_EP0PING);
+DEFINE_INTVEC(0x014C,INTVEC_EP1PING);
+DEFINE_INTVEC(0x0150,INTVEC_EP2PING);
+DEFINE_INTVEC(0x0154,INTVEC_EP4PING);
+DEFINE_INTVEC(0x0158,INTVEC_EP6PING);
+DEFINE_INTVEC(0x015C,INTVEC_EP8PING);
+DEFINE_INTVEC(0x0160,INTVEC_ERRLIMIT);
+DEFINE_INTVEC(0x0170,INTVEC_EP2ISOERR);
+DEFINE_INTVEC(0x0174,INTVEC_EP4ISOERR);
+DEFINE_INTVEC(0x0178,INTVEC_EP6ISOERR);
+DEFINE_INTVEC(0x017C,INTVEC_EP8ISOERR);
+DEFINE_INTVEC(0x0180,INTVEC_EP2PF);
+DEFINE_INTVEC(0x0184,INTVEC_EP4PF);
+DEFINE_INTVEC(0x0188,INTVEC_EP6PF);
+DEFINE_INTVEC(0x018C,INTVEC_EP8PF);
+DEFINE_INTVEC(0x0190,INTVEC_EP2EF);
+DEFINE_INTVEC(0x0194,INTVEC_EP4EF);
+DEFINE_INTVEC(0x0198,INTVEC_EP6EF);
+DEFINE_INTVEC(0x019C,INTVEC_EP8EF);
+DEFINE_INTVEC(0x01A0,INTVEC_EP2FF);
+DEFINE_INTVEC(0x01A8,INTVEC_EP6FF);
+DEFINE_INTVEC(0x01AC,INTVEC_EP8FF);
+DEFINE_INTVEC(0x01B0,INTVEC_GPIFDONE);
+DEFINE_INTVEC(0x01B4,INTVEC_GPIFWF);]
+
+#define[DEFINE_INTVEC(][,$1);][xdata at $0 struct INTVEC $1;]
+INTVECS;
+#udefine[DEFINE_INTVEC(]
+
+void abscode_intvec() _naked
+{
+#define[DEFINE_INTVEC(][,$1);][ .org $0
+ reti]
+ _asm
+ .area ABSCODE (ABS,CODE)
+ .org 0x0000
+ENTRY:
+ ljmp #0x0200
+INTVECS;
+ .org 0x01b8
+INTVEC_DUMMY:
+ reti
+ .area CSEG (CODE)
+ _endasm;
+}
+
+#udefine[INTVECS;]
+#udefine[DEFINE_INTVEC(]
+
+
+/* Init an interrupt vector */
+#define[INIT_INTERRUPT_VECTOR(][,$1);][{
+ $0.op=0x02;
+ $0.addrH=((unsigned short)(&$1)) >> 8;
+ $0.addrL=(unsigned short)(&$1);
+}]
+
+
+/* Enable USB autovectors */
+#define[ENABLE_AVUSB;][{
+ INT8VEC_USB.op=0x02;
+ INT8VEC_USB.addrH = 0x01;
+ INT8VEC_USB.addrL = 0xb8;
+ INTSETUP |= 8;
+}]
+
+
+/* Disable USB autovectors */
+#define[DISABLE_AVUSB;][INTSETUP &= ~8;]
+
+
+/* Enable GPIF autovectors */
+#define[ENABLE_AVGPIF;][{
+ INT10VEC_GPIF.op=0x02;
+ INT10VEC_GPIF.addrH = 0x01;
+ INT10VEC_GPIF.addrL = 0xb8;
+ INTSETUP |= 3;
+}]
+
+
+/* Disable GPIF autovectors */
+#define[DISABLE_AVPGIF;][INTSETUP &= ~3;]
+
+
+#endif /* INTAVECS_H */
Index: usb_fpga_1_2/trunk/include/ztex-conf.h
===================================================================
--- usb_fpga_1_2/trunk/include/ztex-conf.h (nonexistent)
+++ usb_fpga_1_2/trunk/include/ztex-conf.h (revision 2)
@@ -0,0 +1,313 @@
+/*!
+ ZTEX Firmware Kit for EZ-USB Microcontrollers
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+/*
+ Configuration macros
+*/
+
+#ifndef[ZTEX_CONF_H]
+#define[ZTEX_CONF_H]
+
+/*
+ Don't expant macros in comments
+*/
+#define[//][
+][#noexpand[!dnapxeon!]//$0!dnapxeon!
+]
+#define[/*][*/][#noexpand[!dnapxeon!]/*$0*/!dnapxeon!]
+
+/*
+ This macro defines the USB Vendor ID and USB Product ID (not the product ID
+ from the ZTEX descriptor). The Vendor ID must be purchased from the USB-IF
+ (http://www.usb.org). The Cypress Vendor ID may only be used during the
+ develpoment process.
+ Usage:
+ SET_VPID(,);
+*/
+#define[SET_VPID(][,$1);][#define[USB_VENDOR_ID][$0]
+#define[USB_PRODUCT_ID][$1]]
+
+
+/*
+ This macro is called before FPGA Firmware is reset, e.g. to save some
+ settings. After this macro is called the I/O ports are set to default
+ states in order to avoid damage during / after the FPGA configuration.
+ To append someting to this macro use the follwing definition:
+#define[PRE_FPGA_RESET][PRE_FPGA_RESET
+...]
+*/
+#define[PRE_FPGA_RESET][]
+
+
+/*
+ This macro is called after FPGA Firmware has been configured. This is
+ usually used to configure the I/O ports.
+ To append someting to this macro use the follwing definition:
+#define[POST_FW_LOAD][POST_FW_LOAD
+...]
+*/
+#define[POST_FPGA_CONFIG][]
+
+
+/*
+ Add a vedor request for endpoint 0,
+
+ Usage:
+ ADD_EP0_VENDOR_REQUEST((,,
,,''));
+ Example:
+ ADD_EP0_VENDOR_REQUEST((0x33,,initHSFPGAConfiguration();,,));;
+...]
+*/
+#define[EP0_VENDOR_REQUESTS_SU;][]
+#define[EP0_VENDOR_REQUESTS_DAT;][]
+#define[ADD_EP0_VENDOR_REQUEST((][,,$1,,$2));;][#define[EP0_VENDOR_REQUESTS_SU;][EP0_VENDOR_REQUESTS_SU;
+case $0:
+ $1
+ break;
+]
+#define[EP0_VENDOR_REQUESTS_DAT;][EP0_VENDOR_REQUESTS_DAT;
+case $0:
+ $2
+ break;
+]]
+
+
+/*
+ Add a vedor command for endpoint 0,
+
+ Usage:
+ ADD_EP0_VENDOR_COMMAND((,,,,''));
+ Example:
+ ADD_EP0_VENDOR_COMMAND((0x33,,initHSFPGAConfiguration();,,));;
+...]
+*/
+#define[EP0_VENDOR_COMMANDS_SU;][]
+#define[EP0_VENDOR_COMMANDS_DAT;][]
+#define[ADD_EP0_VENDOR_COMMAND((][,,$1,,$2));;][#define[EP0_VENDOR_COMMANDS_SU;][EP0_VENDOR_COMMANDS_SU;
+case $0:
+ $1
+ break;
+]
+#define[EP0_VENDOR_COMMANDS_DAT;][EP0_VENDOR_COMMANDS_DAT;
+case $0:
+ $2
+ break;
+]]
+
+
+/*
+ Endoint 2,4,5,8 configuration:
+
+ EP_CONFIG(,,,,,)
+ = 2 | 4 | 6 | 8 Endpoint numer
+ = 0 | 1 | 2 | 3 To which interface this endpoint belongs
+ = BULK | ISO | INT
+ = IN | OUT
+ = 512 | 1024
+ = 1 | 2 | 3 | 4
+ Example: EP2_CONFIG(2,0,ISO,OUT,1024,4);
+ Importand note: No spaces next to the commas
+
+ Endoint 1 configuration. These Endpoints are defined by default and assigned to interface 0.
+ EP1IN_CONFIG();
+ = 0 | 1 | 2 | 3 To which interface EP1IN belongs; default: 0
+ EP1OUT_CONFIG();
+ = 0 | 1 | 2 | 3 To which interface EP1OUT belongs; default: 0
+ EP1_CONFIG();
+ = 0 | 1 | 2 | 3 To which interface EP1IN and EP1OUT belongs; default: 0
+
+ The following (maximum) configurations are possible:
+ EP2 EP4 EP6 EP8
+ 2x512 2x512 2x512 2x512
+ 2x512 2x512 4x512
+ 2x512 2x512 2x1024
+ 4x512 2x512 2x512
+ 4x512 4x512
+ 4x512 2x1024
+ 2x1024 2x512 2x512
+ 2x1024 4x512
+ 2x1024 2x1024
+ 3x512 3x512 2x512
+ 3x1024 2x512
+ 4x1024
+*/
+#define[EP_CONFIG(][,$1,$2,$3,$4,$5);][
+#ifeq[$0][1IN]
+#elifeq[$0][1OUT]
+#elifeq[$0][2]
+#elifeq[$0][4]
+#elifeq[$0][6]
+#elifneq[$0][8]
+#error[EP_CONFIG: Invalid 1st parameter: `$0'. Expected `2', `4', `6' or '8']
+#endif
+#ifeq[$1][0]
+#elifeq[$1][1]
+#elifeq[$1][2]
+#elifneq[$1][3]
+#error[EP_CONFIG: Invalid 2nd parameter: `$1'. Expected `0', `1', `2' or '3']
+#endif
+#ifeq[$2][BULK]
+#elifeq[$2][ISO]
+#elifneq[$2][INT]
+#error[EP_CONFIG: Invalid 3nd parameter: `$2'. Expected `BULK', `ISO' or 'INT']
+#endif
+#ifeq[$3][IN]
+#elifneq[$3][OUT]
+#error[EP_CONFIG: Invalid 4th parameter: `$3'. Expected `IN' or 'OUT']
+#endif
+#ifeq[$4][64]
+#elifeq[$4][512]
+#elifneq[$4][1024]
+#error[EP_CONFIG: Invalid 5th parameter: `$4'. Expected `512' or '1024']
+#endif
+#ifeq[$5][1]
+#elifeq[$5][2]
+#elifeq[$5][3]
+#elifneq[$5][4]
+#error[EP_CONFIG: Invalid 6th parameter: `$5'. Expected `1', `2', `3' or `4']
+#endif
+#define[EP$0_INTERFACE][$1]
+#define[EP$0_TYPE][$2]
+#define[EP$0_DIR][$3]
+#define[EP$0_SIZE][$4]
+#define[EP$0_BUFFERS][$5]]
+
+#define[EP1IN_CONFIG(][);][#define[EP1IN_INTERFACE][$0]]
+#define[EP1OUT_CONFIG(][);][#define[EP1OUT_INTERFACE][$0]]
+#define[EP1_CONFIG(][);][#define[EP1IN_INTERFACE][$0]
+#define[EP1OUT_INTERFACE][$0]]
+
+EP_CONFIG(1IN,0,BULK,IN,64,1);
+EP_CONFIG(1OUT,0,BULK,OUT,64,1);
+
+
+/*
+ Settings which depends PRODUCT_ID, e.g extra capabilities.
+ Overwrite this macros as desired.
+*/
+#define[MODULE_RESERVED_00][0]
+#define[MODULE_RESERVED_01][0]
+#define[MODULE_RESERVED_02][0]
+#define[MODULE_RESERVED_03][0]
+#define[MODULE_RESERVED_04][0]
+#define[MODULE_RESERVED_05][0]
+#define[MODULE_RESERVED_06][0]
+#define[MODULE_RESERVED_07][0]
+#define[MODULE_RESERVED_08][0]
+#define[MODULE_RESERVED_09][0]
+#define[MODULE_RESERVED_10][0]
+#define[MODULE_RESERVED_11][0]
+
+#define[FWVER][0]
+
+#define[PRODUCT_ID_0][0]
+#define[PRODUCT_ID_1][0]
+#define[PRODUCT_ID_2][0]
+#define[PRODUCT_ID_3][0]
+
+
+/*
+ Identify as ZTEX USB FPGA Module 1.0
+ Usage: IDENTITY_UFM_1_0(..,);
+*/
+#define[IDENTITY_UFM_1_0(][.$1.$2.$3,$4);][#define[PRODUCT_ID_0][$0]
+#define[PRODUCT_ID_1][$1]
+#define[PRODUCT_ID_2][$2]
+#define[PRODUCT_ID_3][$3]
+#define[FWVER][$4]
+#define[PRODUCT_IS][UFM-1_0]
+#define[PRODUCT_STRING]["USB-FPGA Module 1.0"]]
+
+
+/*
+ Identify as ZTEX USB FPGA Module 1.1
+ Usage: IDENTITY_UFM_1_1(..,);
+*/
+#define[IDENTITY_UFM_1_1(][.$1.$2.$3,$4);][#define[PRODUCT_ID_0][$0]
+#define[PRODUCT_ID_1][$1]
+#define[PRODUCT_ID_2][$2]
+#define[PRODUCT_ID_3][$3]
+#define[FWVER][$4]
+#define[PRODUCT_IS][UFM-1_1]
+#define[PRODUCT_STRING]["USB-FPGA Module 1.1"]]
+
+
+/*
+ Identify as ZTEX USB FPGA Module 1.2
+ Usage: IDENTITY_UFM_1_2(..,);
+*/
+#define[IDENTITY_UFM_1_2(][.$1.$2.$3,$4);][#define[PRODUCT_ID_0][$0]
+#define[PRODUCT_ID_1][$1]
+#define[PRODUCT_ID_2][$2]
+#define[PRODUCT_ID_3][$3]
+#define[FWVER][$4]
+#define[PRODUCT_IS][UFM-1_2]
+#define[PRODUCT_STRING]["USB-FPGA Module 1.2"]]
+
+
+/*
+ Identify as ZTEX USB Module 1.0
+ Usage: IDENTITY_UM_1_0(..,);
+*/
+#define[IDENTITY_UM_1_0(][.$1.$2.$3,$4);][#define[PRODUCT_ID_0][$0]
+#define[PRODUCT_ID_1][$1]
+#define[PRODUCT_ID_2][$2]
+#define[PRODUCT_ID_3][$3]
+#define[FWVER][$4]
+#define[PRODUCT_IS][UM-1_0]
+#define[PRODUCT_STRING]["USB Module 1.0"]]
+
+
+/*
+ This macro defines the Manufacturer string. Limited to 31 charcters.
+*/
+#define[MANUFACTURER_STRING]["ZTEX"]
+
+
+/*
+ This macro defines the Product string. Limited to 31 charcters.
+*/
+#define[PRODUCT_STRING]["USB-FPGA Module"]
+
+
+/*
+ This macro defines the Configuration string. Limited to 31 charcters.
+*/
+#define[CONFIGURATION_STRING]["(unknown)"]
+
+
+/*
+ This macro enables defines the Configuration string. Limited to 31 charcters.
+*/
+#define[CONFIGURATION_STRING]["(unknown)"]
+
+
+/*
+ This macro disables EEPROM interface and certain I2C functions (enabled by default)
+ Usage: DISABLE_EEPROM;
+*/
+#define[DISBALE_EEPROM;][#define[EEPROM_DISBALED][1]]
+
+
+/*
+ This macro enables the Flash interface, if available
+ Usage: ENABLE_FLASH;
+*/
+#define[ENABLE_FLASH;][#define[FLASH_ENABLED][1]]
+
+#endif
Index: usb_fpga_1_2/trunk/include/ezregs.h
===================================================================
--- usb_fpga_1_2/trunk/include/ezregs.h (nonexistent)
+++ usb_fpga_1_2/trunk/include/ezregs.h (revision 2)
@@ -0,0 +1,445 @@
+/*!
+ ZTEX Firmware Kit for EZ-USB Microcontrollers
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+/*
+ EZ-USB registers
+*/
+
+#ifndef[EZREGS_H]
+#define[EZREGS_H]
+
+#include[ztex-utils.h]
+
+/* This syncronization delay is valid if <= 5/3*,
+ i.e. if the Interface Clock is equal or greater than 28.8 MHz
+
+ The formula for the synchonization delay is:
+
+ / \
+ >= 1.5 * | ----------------- + 1 |
+ \ /
+
+ Overwrite this macro if this formula is not satisfied
+*/
+
+#ifndef[SYNCDELAY;]
+#define[SYNCDELAY;][_asm
+ nop
+ nop
+ nop
+ nop
+ _endasm;
+]
+#endif
+
+// GPIF Waveform Memories
+xdata at 0xE400 volatile BYTE GPIF_WAVE_DATA[128]; // GPIF Waveform Descriptor 0, 1, 2 3, data
+xdata at 0xE400 volatile BYTE GPIF_WAVE0_DATA[32]; // GPIF Waveform Descriptor 0 data
+xdata at 0xE420 volatile BYTE GPIF_WAVE1_DATA[32]; // GPIF Waveform Descriptor 1 data
+xdata at 0xE440 volatile BYTE GPIF_WAVE2_DATA[32]; // GPIF Waveform Descriptor 2 data
+xdata at 0xE460 volatile BYTE GPIF_WAVE3_DATA[32]; // GPIF Waveform Descriptor 3 data
+
+// General Configuration
+xdata at 0xE50D volatile BYTE GPCR2; // General Purpose Configuration Register 2
+xdata at 0xE600 volatile BYTE CPUCS; // Control & Status
+xdata at 0xE601 volatile BYTE IFCONFIG; // Interface Configuration
+xdata at 0xE602 volatile BYTE PINFLAGSAB; // FIFO FLAGA and FLAGB Assignments
+xdata at 0xE603 volatile BYTE PINFLAGSCD; // FIFO FLAGC and FLAGD Assignments
+xdata at 0xE604 volatile BYTE FIFORESET; // Restore FIFOS to default state
+xdata at 0xE605 volatile BYTE BREAKPT; // Breakpoint
+xdata at 0xE606 volatile BYTE BPADDRH; // Breakpoint Address H
+xdata at 0xE607 volatile BYTE BPADDRL; // Breakpoint Address L
+xdata at 0xE608 volatile BYTE UART230; // 230 Kbaud clock for T0,T1,T2
+xdata at 0xE609 volatile BYTE FIFOPINPOLAR; // FIFO polarities
+xdata at 0xE60A volatile BYTE REVID; // Chip Revision
+xdata at 0xE60B volatile BYTE REVCTL; // Chip Revision Control
+
+// UDMA
+xdata at 0xE60C volatile BYTE GPIFHOLDAMOUNT; // MSTB Hold Time (for UDMA)
+
+// Endpoint Configuration
+xdata at 0xE610 volatile BYTE EP1OUTCFG; // Endpoint 1-OUT Configuration
+xdata at 0xE611 volatile BYTE EP1INCFG; // Endpoint 1-IN Configuration
+xdata at 0xE612 volatile BYTE EP2CFG; // Endpoint 2 Configuration
+xdata at 0xE613 volatile BYTE EP4CFG; // Endpoint 4 Configuration
+xdata at 0xE614 volatile BYTE EP6CFG; // Endpoint 6 Configuration
+xdata at 0xE615 volatile BYTE EP8CFG; // Endpoint 8 Configuration
+xdata at 0xE618 volatile BYTE EP2FIFOCFG; // Endpoint 2 FIFO configuration
+xdata at 0xE619 volatile BYTE EP4FIFOCFG; // Endpoint 4 FIFO configuration
+xdata at 0xE61A volatile BYTE EP6FIFOCFG; // Endpoint 6 FIFO configuration
+xdata at 0xE61B volatile BYTE EP8FIFOCFG; // Endpoint 8 FIFO configuration
+xdata at 0xE620 volatile BYTE EP2AUTOINLENH; // Endpoint 2 Packet Length H (IN only)
+xdata at 0xE621 volatile BYTE EP2AUTOINLENL; // Endpoint 2 Packet Length L (IN only)
+xdata at 0xE622 volatile BYTE EP4AUTOINLENH; // Endpoint 4 Packet Length H (IN only)
+xdata at 0xE623 volatile BYTE EP4AUTOINLENL; // Endpoint 4 Packet Length L (IN only)
+xdata at 0xE624 volatile BYTE EP6AUTOINLENH; // Endpoint 6 Packet Length H (IN only)
+xdata at 0xE625 volatile BYTE EP6AUTOINLENL; // Endpoint 6 Packet Length L (IN only)
+xdata at 0xE626 volatile BYTE EP8AUTOINLENH; // Endpoint 8 Packet Length H (IN only)
+xdata at 0xE627 volatile BYTE EP8AUTOINLENL; // Endpoint 8 Packet Length L (IN only)
+xdata at 0xE628 volatile BYTE ECCCFG; // ECC Configuration
+xdata at 0xE629 volatile BYTE ECCRESET; // ECC Reset
+xdata at 0xE62A volatile BYTE ECC1B0; // ECC1 Byte 0 Address
+xdata at 0xE62B volatile BYTE ECC1B1; // ECC1 Byte 1 Address
+xdata at 0xE62C volatile BYTE ECC1B2; // ECC1 Byte 2 Address
+xdata at 0xE62D volatile BYTE ECC2B0; // ECC2 Byte 0 Address
+xdata at 0xE62E volatile BYTE ECC2B1; // ECC2 Byte 1 Address
+xdata at 0xE62F volatile BYTE ECC2B2; // ECC2 Byte 2 Address
+xdata at 0xE630 volatile BYTE EP2FIFOPFH; // EP2 Programmable Flag trigger H
+xdata at 0xE631 volatile BYTE EP2FIFOPFL; // EP2 Programmable Flag trigger L
+xdata at 0xE632 volatile BYTE EP4FIFOPFH; // EP4 Programmable Flag trigger H
+xdata at 0xE633 volatile BYTE EP4FIFOPFL; // EP4 Programmable Flag trigger L
+xdata at 0xE634 volatile BYTE EP6FIFOPFH; // EP6 Programmable Flag trigger H
+xdata at 0xE635 volatile BYTE EP6FIFOPFL; // EP6 Programmable Flag trigger L
+xdata at 0xE636 volatile BYTE EP8FIFOPFH; // EP8 Programmable Flag trigger H
+xdata at 0xE637 volatile BYTE EP8FIFOPFL; // EP8 Programmable Flag trigger L
+xdata at 0xE640 volatile BYTE EP2ISOINPKTS; // EP2 (if ISO) IN Packets per frame (1-3)
+xdata at 0xE641 volatile BYTE EP4ISOINPKTS; // EP4 (if ISO) IN Packets per frame (1-3)
+xdata at 0xE642 volatile BYTE EP6ISOINPKTS; // EP6 (if ISO) IN Packets per frame (1-3)
+xdata at 0xE643 volatile BYTE EP8ISOINPKTS; // EP8 (if ISO) IN Packets per frame (1-3)
+xdata at 0xE648 volatile BYTE INPKTEND; // Force IN Packet End
+xdata at 0xE649 volatile BYTE OUTPKTEND; // Force OUT Packet End
+
+// Interrupts
+xdata at 0xE650 volatile BYTE EP2FIFOIE; // Endpoint 2 Flag Interrupt Enable
+xdata at 0xE651 volatile BYTE EP2FIFOIRQ; // Endpoint 2 Flag Interrupt Request
+xdata at 0xE652 volatile BYTE EP4FIFOIE; // Endpoint 4 Flag Interrupt Enable
+xdata at 0xE653 volatile BYTE EP4FIFOIRQ; // Endpoint 4 Flag Interrupt Request
+xdata at 0xE654 volatile BYTE EP6FIFOIE; // Endpoint 6 Flag Interrupt Enable
+xdata at 0xE655 volatile BYTE EP6FIFOIRQ; // Endpoint 6 Flag Interrupt Request
+xdata at 0xE656 volatile BYTE EP8FIFOIE; // Endpoint 8 Flag Interrupt Enable
+xdata at 0xE657 volatile BYTE EP8FIFOIRQ; // Endpoint 8 Flag Interrupt Request
+xdata at 0xE658 volatile BYTE IBNIE; // IN-BULK-NAK Interrupt Enable
+xdata at 0xE659 volatile BYTE IBNIRQ; // IN-BULK-NAK interrupt Request
+xdata at 0xE65A volatile BYTE NAKIE; // Endpoint Ping NAK interrupt Enable
+xdata at 0xE65B volatile BYTE NAKIRQ; // Endpoint Ping NAK interrupt Request
+xdata at 0xE65C volatile BYTE USBIE; // USB Int Enables
+xdata at 0xE65D volatile BYTE USBIRQ; // USB Interrupt Requests
+xdata at 0xE65E volatile BYTE EPIE; // Endpoint Interrupt Enables
+xdata at 0xE65F volatile BYTE EPIRQ; // Endpoint Interrupt Requests
+xdata at 0xE660 volatile BYTE GPIFIE; // GPIF Interrupt Enable
+xdata at 0xE661 volatile BYTE GPIFIRQ; // GPIF Interrupt Request
+xdata at 0xE662 volatile BYTE USBERRIE; // USB Error Interrupt Enables
+xdata at 0xE663 volatile BYTE USBERRIRQ; // USB Error Interrupt Requests
+xdata at 0xE664 volatile BYTE ERRCNTLIM; // USB Error counter and limit
+xdata at 0xE665 volatile BYTE CLRERRCNT; // Clear Error Counter EC[3..0]
+xdata at 0xE666 volatile BYTE INT2IVEC; // Interupt 2 (USB) Autovector
+xdata at 0xE667 volatile BYTE INT4IVEC; // Interupt 4 (FIFOS & GPIF) Autovector
+xdata at 0xE668 volatile BYTE INTSETUP; // Interrupt 2&4 Setup
+
+// Input/Output
+xdata at 0xE670 volatile BYTE PORTACFG; // I/O PORTA Alternate Configuration
+xdata at 0xE671 volatile BYTE PORTCCFG; // I/O PORTC Alternate Configuration
+xdata at 0xE672 volatile BYTE PORTECFG; // I/O PORTE Alternate Configuration
+xdata at 0xE678 volatile BYTE I2CS; // Control & Status
+xdata at 0xE679 volatile BYTE I2DAT; // Data
+xdata at 0xE67A volatile BYTE I2CTL; // I2C Control
+xdata at 0xE67B volatile BYTE XAUTODAT1; // Autoptr1 MOVX access
+xdata at 0xE67B volatile BYTE EXTAUTODAT1; // Autoptr1 MOVX access
+xdata at 0xE67C volatile BYTE XAUTODAT2; // Autoptr2 MOVX access
+xdata at 0xE67C volatile BYTE EXTAUTODAT2; // Autoptr2 MOVX access
+
+// UDMA CRC
+xdata at 0xE67D volatile BYTE UDMACRCH; // UDMA CRC MSB
+xdata at 0xE67E volatile BYTE UDMACRCL; // UDMA CRC LSB
+xdata at 0xE67F volatile BYTE UDMACRCQUALIFIER; // UDMA CRC Qualifier
+
+// USB Control
+xdata at 0xE680 volatile BYTE USBCS; // USB Control & Status
+xdata at 0xE681 volatile BYTE SUSPEND; // Put chip into suspend
+xdata at 0xE682 volatile BYTE WAKEUPCS; // Wakeup source and polarity
+xdata at 0xE683 volatile BYTE TOGCTL; // Toggle Control
+xdata at 0xE684 volatile BYTE USBFRAMEH; // USB Frame count H
+xdata at 0xE685 volatile BYTE USBFRAMEL; // USB Frame count L
+xdata at 0xE686 volatile BYTE MICROFRAME; // Microframe count, 0-7
+xdata at 0xE687 volatile BYTE FNADDR; // USB Function address
+
+// Endpoints
+xdata at 0xE68A volatile BYTE EP0BCH; // Endpoint 0 Byte Count H
+xdata at 0xE68B volatile BYTE EP0BCL; // Endpoint 0 Byte Count L
+xdata at 0xE68D volatile BYTE EP1OUTBC; // Endpoint 1 OUT Byte Count
+xdata at 0xE68F volatile BYTE EP1INBC; // Endpoint 1 IN Byte Count
+xdata at 0xE690 volatile BYTE EP2BCH; // Endpoint 2 Byte Count H
+xdata at 0xE691 volatile BYTE EP2BCL; // Endpoint 2 Byte Count L
+xdata at 0xE694 volatile BYTE EP4BCH; // Endpoint 4 Byte Count H
+xdata at 0xE695 volatile BYTE EP4BCL; // Endpoint 4 Byte Count L
+xdata at 0xE698 volatile BYTE EP6BCH; // Endpoint 6 Byte Count H
+xdata at 0xE699 volatile BYTE EP6BCL; // Endpoint 6 Byte Count L
+xdata at 0xE69C volatile BYTE EP8BCH; // Endpoint 8 Byte Count H
+xdata at 0xE69D volatile BYTE EP8BCL; // Endpoint 8 Byte Count L
+xdata at 0xE6A0 volatile BYTE EP0CS; // Endpoint Control and Status
+xdata at 0xE6A1 volatile BYTE EP1OUTCS; // Endpoint 1 OUT Control and Status
+xdata at 0xE6A2 volatile BYTE EP1INCS; // Endpoint 1 IN Control and Status
+xdata at 0xE6A3 volatile BYTE EPXCS[4]; // Endpoint 2-8 Control and Status
+xdata at 0xE6A3 volatile BYTE EP2CS; // Endpoint 2 Control and Status
+xdata at 0xE6A4 volatile BYTE EP4CS; // Endpoint 4 Control and Status
+xdata at 0xE6A5 volatile BYTE EP6CS; // Endpoint 6 Control and Status
+xdata at 0xE6A6 volatile BYTE EP8CS; // Endpoint 8 Control and Status
+xdata at 0xE6A7 volatile BYTE EP2FIFOFLGS; // Endpoint 2 Flags
+xdata at 0xE6A8 volatile BYTE EP4FIFOFLGS; // Endpoint 4 Flags
+xdata at 0xE6A9 volatile BYTE EP6FIFOFLGS; // Endpoint 6 Flags
+xdata at 0xE6AA volatile BYTE EP8FIFOFLGS; // Endpoint 8 Flags
+xdata at 0xE6AB volatile BYTE EP2FIFOBCH; // EP2 FIFO total byte count H
+xdata at 0xE6AC volatile BYTE EP2FIFOBCL; // EP2 FIFO total byte count L
+xdata at 0xE6AD volatile BYTE EP4FIFOBCH; // EP4 FIFO total byte count H
+xdata at 0xE6AE volatile BYTE EP4FIFOBCL; // EP4 FIFO total byte count L
+xdata at 0xE6AF volatile BYTE EP6FIFOBCH; // EP6 FIFO total byte count H
+xdata at 0xE6B0 volatile BYTE EP6FIFOBCL; // EP6 FIFO total byte count L
+xdata at 0xE6B1 volatile BYTE EP8FIFOBCH; // EP8 FIFO total byte count H
+xdata at 0xE6B2 volatile BYTE EP8FIFOBCL; // EP8 FIFO total byte count L
+xdata at 0xE6B3 volatile BYTE SUDPTRH; // Setup Data Pointer high address byte
+xdata at 0xE6B4 volatile BYTE SUDPTRL; // Setup Data Pointer low address byte
+xdata at 0xE6B5 volatile BYTE SUDPTRCTL; // Setup Data Pointer Auto Mode
+xdata at 0xE6B8 volatile BYTE SETUPDAT[8]; // 8 bytes of SETUP data
+xdata at 0xE6B8 volatile BYTE bmRequestType; // Request Type, Direction, and Recipient
+xdata at 0xE6B9 volatile BYTE bRequest; // The actual request
+xdata at 0xE6BA volatile BYTE wValueL;
+xdata at 0xE6BB volatile BYTE wValueH;
+xdata at 0xE6BC volatile BYTE wIndexL;
+xdata at 0xE6BD volatile BYTE wIndexH;
+xdata at 0xE6BE volatile BYTE wLengthL; // Number of bytes to transfer if there is a data phase
+xdata at 0xE6BF volatile BYTE wLengthH;
+
+// GPIF
+xdata at 0xE6C0 volatile BYTE GPIFWFSELECT; // Waveform Selector
+xdata at 0xE6C1 volatile BYTE GPIFIDLECS; // GPIF Done, GPIF IDLE drive mode
+xdata at 0xE6C2 volatile BYTE GPIFIDLECTL; // Inactive Bus, CTL states
+xdata at 0xE6C3 volatile BYTE GPIFCTLCFG; // CTL OUT pin drive
+xdata at 0xE6C4 volatile BYTE GPIFADRH; // GPIF Address H
+xdata at 0xE6C5 volatile BYTE GPIFADRL; // GPIF Address L
+
+// FLOWSTATE
+xdata at 0xE6C6 volatile BYTE FLOWSTATE; // Flowstate Enable and Selector
+xdata at 0xE6C7 volatile BYTE FLOWLOGIC; // Flowstate Logic
+xdata at 0xE6C8 volatile BYTE FLOWEQ0CTL; // CTL-Pin States in Flowstate (when Logic = 0)
+xdata at 0xE6C9 volatile BYTE FLOWEQ1CTL; // CTL-Pin States in Flowstate (when Logic = 1)
+xdata at 0xE6CA volatile BYTE FLOWHOLDOFF; // Holdoff Configuration
+xdata at 0xE6CB volatile BYTE FLOWSTB; // Flowstate Strobe Configuration
+xdata at 0xE6CC volatile BYTE FLOWSTBEDGE; // Flowstate Rising/Falling Edge Configuration
+xdata at 0xE6CD volatile BYTE FLOWSTBHPERIOD; // Master-Strobe Half-Period
+xdata at 0xE6CE volatile BYTE GPIFTCB3; // GPIF Transaction Count Byte 3
+xdata at 0xE6CF volatile BYTE GPIFTCB2; // GPIF Transaction Count Byte 2
+xdata at 0xE6D0 volatile BYTE GPIFTCB1; // GPIF Transaction Count Byte 1
+xdata at 0xE6D1 volatile BYTE GPIFTCB0; // GPIF Transaction Count Byte 0
+xdata at 0xE6D2 volatile BYTE EP2GPIFFLGSEL; // EP2 GPIF Flag select
+xdata at 0xE6D3 volatile BYTE EP2GPIFPFSTOP; // Stop GPIF EP2 transaction on prog. flag
+xdata at 0xE6D4 volatile BYTE EP2GPIFTRIG; // EP2 FIFO Trigger
+xdata at 0xE6DA volatile BYTE EP4GPIFFLGSEL; // EP4 GPIF Flag select
+xdata at 0xE6DB volatile BYTE EP4GPIFPFSTOP; // Stop GPIF EP4 transaction on prog. flag
+xdata at 0xE6DC volatile BYTE EP4GPIFTRIG; // EP4 FIFO Trigger
+xdata at 0xE6E2 volatile BYTE EP6GPIFFLGSEL; // EP6 GPIF Flag select
+xdata at 0xE6E3 volatile BYTE EP6GPIFPFSTOP; // Stop GPIF EP6 transaction on prog. flag
+xdata at 0xE6E4 volatile BYTE EP6GPIFTRIG; // EP6 FIFO Trigger
+xdata at 0xE6EA volatile BYTE EP8GPIFFLGSEL; // EP8 GPIF Flag select
+xdata at 0xE6EB volatile BYTE EP8GPIFPFSTOP; // Stop GPIF EP8 transaction on prog. flag
+xdata at 0xE6EC volatile BYTE EP8GPIFTRIG; // EP8 FIFO Trigger
+xdata at 0xE6F0 volatile BYTE XGPIFSGLDATH; // GPIF Data H (16-bit mode only)
+xdata at 0xE6F1 volatile BYTE XGPIFSGLDATLX; // Read/Write GPIF Data L & trigger transac
+xdata at 0xE6F2 volatile BYTE XGPIFSGLDATLNOX; // Read GPIF Data L, no transac trigger
+xdata at 0xE6F3 volatile BYTE GPIFREADYCFG; // Internal RDY,Sync/Async, RDY5CFG
+xdata at 0xE6F4 volatile BYTE GPIFREADYSTAT; // RDY pin states
+xdata at 0xE6F5 volatile BYTE GPIFABORT; // Abort GPIF cycles
+
+// Endpoint Buffers
+xdata at 0xE740 volatile BYTE EP0BUF[64]; // EP0 IN-OUT buffer
+xdata at 0xE780 volatile BYTE EP1OUTBUF[64]; // EP1-OUT buffer
+xdata at 0xE7C0 volatile BYTE EP1INBUF[64]; // EP1-IN buffer
+xdata at 0xF000 volatile BYTE EP2FIFOBUF[1024]; // 512/1024-byte EP2 buffer (IN or OUT)
+xdata at 0xF400 volatile BYTE EP4FIFOBUF[1024]; // 512 byte EP4 buffer (IN or OUT)
+xdata at 0xF800 volatile BYTE EP6FIFOBUF[1024]; // 512/1024-byte EP6 buffer (IN or OUT)
+xdata at 0xFC00 volatile BYTE EP8FIFOBUF[1024]; // 512 byte EP8 buffer (IN or OUT)
+
+
+// Special Function Registers (SFRs)
+sfr at 0x80 IOA; // Port A
+sbit at 0x80+0 IOA0; // Port A bit 0
+sbit at 0x80+1 IOA1; // Port A bit 1
+sbit at 0x80+2 IOA2; // Port A bit 2
+sbit at 0x80+3 IOA3; // Port A bit 3
+sbit at 0x80+4 IOA4; // Port A bit 4
+sbit at 0x80+5 IOA5; // Port A bit 5
+sbit at 0x80+6 IOA6; // Port A bit 6
+sbit at 0x80+7 IOA7; // Port A bit 7
+sfr at 0x81 SP; // Stack Pointer
+sfr at 0x82 DPL0; // Data Pointer 0 L
+sfr at 0x83 DPH0; // Data Pointer 0 H
+sfr at 0x84 DPL1; // Data Pointer 1 L
+sfr at 0x85 DPH1; // Data Pointer 0 H
+sfr at 0x86 DPS; // Data Pointer 0/1 select
+sfr at 0x87 PCON; // Power Control
+sfr at 0x88 TCON; // Timer/Counter Control
+sbit at 0x88+0 IT0; // Interrupt 0 Type select
+sbit at 0x88+1 IE0; // Interrupt 0 Edge detect
+sbit at 0x88+2 IT1; // Interrupt 1 Type select
+sbit at 0x88+3 IE1; // Interrupt 1 Edge detect
+sbit at 0x88+4 TR0; // Timer 0 Run Control
+sbit at 0x88+5 TF0; // Timer 0 Overflow Flag
+sbit at 0x88+6 TR1; // Timer 1 Run Control
+sbit at 0x88+7 TF1; // Timer 1 Overflow Flag
+sfr at 0x89 TMOD; // Timer/Counter Mode Control
+sfr at 0x8A TL0; // Timer 0 reload L
+sfr at 0x8B TL1; // Timer 1 reload L
+sfr at 0x8C TH0; // Timer 0 reload H
+sfr at 0x8D TH1; // Timer 1 reload H
+sfr at 0x8E CKCON; // Clock Control
+sfr at 0x90 IOB; // Port B
+sbit at 0x90+0 IOB0; // Port B bit 0
+sbit at 0x90+1 IOB1; // Port B bit 1
+sbit at 0x90+2 IOB2; // Port B bit 2
+sbit at 0x90+3 IOB3; // Port B bit 3
+sbit at 0x90+4 IOB4; // Port B bit 4
+sbit at 0x90+5 IOB5; // Port B bit 5
+sbit at 0x90+6 IOB6; // Port B bit 6
+sbit at 0x90+7 IOB7; // Port B bit 7
+sfr at 0x91 EXIF; // External Interrupt Flag(s)
+sfr at 0x92 MPAGE; // Upper Addr Byte of MOVX using @R0 / @R1
+__sfr __at (0x92) _XPAGE;
+sfr at 0x98 SCON0; // Serial Port 0 Control
+sbit at 0x98+0 RI_0; // Recive Interrupt Flag
+sbit at 0x98+1 TI_0; // Transmit Interrupt Flag
+sbit at 0x98+2 RB8_0; // State of the 9th bit / Stop Bit received
+sbit at 0x98+3 TB8_0; // State of the 9th bit transmitted
+sbit at 0x98+4 REN_0; // Receive enable
+sbit at 0x98+5 SM2_0; // Multiprocessor communication enable
+sbit at 0x98+6 SM1_0; // Serial Port 0 mode bit 1
+sbit at 0x98+7 SM0_0; // Serial Port 0 mode bit 0
+sfr at 0x99 SBUF0; // Serial Port 0 Data Buffer
+sfr at 0x9A AUTOPTRH1; // Autopointer 1 Address H
+sfr at 0x9B AUTOPTRL1; // Autopointer 1 Address L
+sfr at 0x9D AUTOPTRH2; // Autopointer 2 Address H
+sfr at 0x9E AUTOPTRL2; // Autopointer 2 Address L
+sfr at 0xA0 IOC; // Port C
+sbit at 0xA0+0 IOC0; // Port C bit 0
+sbit at 0xA0+1 IOC1; // Port C bit 1
+sbit at 0xA0+2 IOC2; // Port C bit 2
+sbit at 0xA0+3 IOC3; // Port C bit 3
+sbit at 0xA0+4 IOC4; // Port C bit 4
+sbit at 0xA0+5 IOC5; // Port C bit 5
+sbit at 0xA0+6 IOC6; // Port C bit 6
+sbit at 0xA0+7 IOC7; // Port C bit 7
+sfr at 0xA1 INT2CLR; // Interrupt 2 clear
+sfr at 0xA2 INT4CLR; // Interrupt 4clear
+sfr at 0xA8 IE; // Interrupt Enable
+sbit at 0xA8+0 EX0; // Enable external interrupt 0
+sbit at 0xA8+1 ET0; // Enable Timer 0 interrupt
+sbit at 0xA8+2 EX1; // Enable external interrupt 1
+sbit at 0xA8+3 ET1; // Enable Timer 1 interrupt
+sbit at 0xA8+4 ES0; // Enable Serial Port 0 interrupt
+sbit at 0xA8+5 ET2; // Enable Timer 2 interrupt
+sbit at 0xA8+6 ES1; // Enable Serial Port 1 interrupt
+sbit at 0xA8+7 EA; // Global interrupt enable
+sfr at 0xAA EP2468STAT; // Endpoint 2,4,6,8 status flags
+sfr at 0xAB EP24FIFOFLGS; // Endpoint 2,4 slave FIFO flags
+sfr at 0xAC EP68FIFOFLGS; // Endpoint 6,8 slave FIFO flags
+sfr at 0xAF AUTOPTRSETUP; // Autopointer 1&2 set-up
+sfr at 0xB0 IOD; // Port D
+sbit at 0xB0+0 IOD0; // Port D bit 0
+sbit at 0xB0+1 IOD1; // Port D bit 1
+sbit at 0xB0+2 IOD2; // Port D bit 2
+sbit at 0xB0+3 IOD3; // Port D bit 3
+sbit at 0xB0+4 IOD4; // Port D bit 4
+sbit at 0xB0+5 IOD5; // Port D bit 5
+sbit at 0xB0+6 IOD6; // Port D bit 6
+sbit at 0xB0+7 IOD7; // Port D bit 7
+sfr at 0xB1 IOE; // Port E
+sfr at 0xB2 OEA; // Port A Output Enable
+sfr at 0xB3 OEB; // Port B Output Enable
+sfr at 0xB4 OEC; // Port C Output Enable
+sfr at 0xB5 OED; // Port D Output Enable
+sfr at 0xB6 OEE; // Port E Output Enable
+sfr at 0xB8 IP; // Interrupt priority
+sbit at 0xB8+0 PX0; // External interrupt 0 priority control
+sbit at 0xB8+1 PT0; // Timer 0 interrupt priority control
+sbit at 0xB8+2 PX1; // External interrupt 1 priority control
+sbit at 0xB8+3 PT1; // Timer 1 interrupt priority control
+sbit at 0xB8+4 PS0; // Serial Port 0 interrupt priority control
+sbit at 0xB8+5 PT2; // Timer 2 interrupt priority control
+sbit at 0xB8+6 PS1; // Serial Port 1 interrupt priority control
+sfr at 0xBA EP01STAT; // Endpoint 0&1 Status
+sfr at 0xBB GPIFTRIG; // Endpoint 2,4,6,8 GPIF slafe FIFO Trigger
+sfr at 0xBD GPIFSGLDATH; // GPIF Data H (16-bit mode only)
+sfr at 0xBE GPIFSGLDATLX; // GPIF Data L w/ Trigger
+sfr at 0xBF GPIFSGLDATLNOX; // GPIF Data L w/ No Trigger
+sfr at 0xC0 SCON1; // Serial Port 1 Control
+sbit at 0xC0+0 RI_1; // Recive Interrupt Flag
+sbit at 0xC0+1 TI_1; // Transmit Interrupt Flag
+sbit at 0xC0+2 RB8_1; // State of the 9th bit / Stop Bit received
+sbit at 0xC0+3 TB8_1; // State of the 9th bit transmitted
+sbit at 0xC0+4 REN_1; // Receive enable
+sbit at 0xC0+5 SM2_1; // Multiprocessor communication enable
+sbit at 0xC0+6 SM1_1; // Serial Port 1 mode bit 1
+sbit at 0xC0+7 SM0_1; // Serial Port 1 mode bit 0
+sfr at 0xC1 SBUF1; // Serial Port 1 Data Buffer
+sfr at 0xC8 T2CON; // Timer/Counter 2 Control
+sbit at 0xC8+0 CPRL2; // Capture/reload flag
+sbit at 0xC8+1 CT2; // Counter/Timer select
+sbit at 0xC8+2 TR2; // Timer 2 run control flag
+sbit at 0xC8+3 EXEN2; // Timer 2 external enable
+sbit at 0xC8+4 TCLK; // Transmit clock flag
+sbit at 0xC8+5 RCLK; // Receive clock flag
+sbit at 0xC8+6 EXF2; // Timer 2 external flag
+sbit at 0xC8+7 TF2; // Timer 2 overflow flag
+sfr at 0xCA RCAP2L; // Capture for Timer 2, auto-reload, up-counter L
+sfr at 0xCB RCAP2H; // Capture for Timer 2, auto-reload, up-counter H
+sfr at 0xCC TL2; // Timer 2 reload L
+sfr at 0xCD TH2; // Timer 2 reload H
+sfr at 0xD0 PSW; // Program Status Word
+sbit at 0xD0+0 PF; // Parity flag
+sbit at 0xD0+1 F1; // User flag 1
+sbit at 0xD0+2 OV; // Overflow flag
+sbit at 0xD0+3 RS0; // Register bank select bit 0
+sbit at 0xD0+4 RS1; // Register bank select bit 1
+sbit at 0xD0+5 F0; // User flag 0
+sbit at 0xD0+6 AC; // Auxiliary carry flag
+sbit at 0xD0+7 CY; // Carry flag
+sfr at 0xD8 EICON; // External Interrupt Control
+sbit at 0xD8+3 INT6; // External interrupt 6
+sbit at 0xD8+4 RESI; // Wakeup interrupt flag
+sbit at 0xD8+5 ERESI; // Enable Resume interrupt
+sbit at 0xD8+7 SMOD1; // Serial Port 1 baud rate doubler enable
+sfr at 0xE0 ACC; // Accumulator
+sbit at 0xE0+0 ACC0; // Accumulator bit 0
+sbit at 0xE0+1 ACC1; // Accumulator bit 1
+sbit at 0xE0+2 ACC2; // Accumulator bit 2
+sbit at 0xE0+3 ACC3; // Accumulator bit 3
+sbit at 0xE0+4 ACC4; // Accumulator bit 4
+sbit at 0xE0+5 ACC5; // Accumulator bit 5
+sbit at 0xE0+6 ACC6; // Accumulator bit 6
+sbit at 0xE0+7 ACC7; // Accumulator bit 7
+sfr at 0xE8 EIE; // External Interrupt Enable(s)
+sbit at 0xE8+0 EUSB; // Enable USB interrupt (USBINT)
+sbit at 0xE8+1 EI2C; // Enable I2C bus interrupt (I2CINT)
+sbit at 0xE8+2 EIEX4; // Enable external interrupt 4
+sbit at 0xE8+3 EIEX5; // Enable external interrupt 5
+sbit at 0xE8+4 EIEX6; // Enable external interrupt 6
+sfr at 0xF0 BREG; // B Register
+sbit at 0xF0+0 BREG0; // B Register bit 0
+sbit at 0xF0+1 BREG1; // B Register bit 1
+sbit at 0xF0+2 BREG2; // B Register bit 2
+sbit at 0xF0+3 BREG3; // B Register bit 3
+sbit at 0xF0+4 BREG4; // B Register bit 4
+sbit at 0xF0+5 BREG5; // B Register bit 5
+sbit at 0xF0+6 BREG6; // B Register bit 6
+sbit at 0xF0+7 BREG7; // B Register bit 7
+sfr at 0xF8 EIP; // External Interrupt Priority Control
+sbit at 0xF8+0 PUSB; // USBINT priority control
+sbit at 0xF8+1 PI2C; // I2CINT priority control
+sbit at 0xF8+2 EIPX4; // External interrupt 4 priority control
+sbit at 0xF8+3 EIPX5; // External interrupt 5 priority control
+sbit at 0xF8+4 EIPX6; // External interrupt 6 priority control
+
+#endif /* EZREGS_H */
Index: usb_fpga_1_2/trunk/include/Version
===================================================================
--- usb_fpga_1_2/trunk/include/Version (nonexistent)
+++ usb_fpga_1_2/trunk/include/Version (revision 2)
@@ -0,0 +1,3 @@
+ZTEX Firmware Kit for EZ-USB Microcontrollers
+
+Implements ZTEX descriptor version 1, Interface 1
Index: usb_fpga_1_2/trunk/include/ztex-eeprom.h
===================================================================
--- usb_fpga_1_2/trunk/include/ztex-eeprom.h (nonexistent)
+++ usb_fpga_1_2/trunk/include/ztex-eeprom.h (revision 2)
@@ -0,0 +1,253 @@
+/*!
+ ZTEX Firmware Kit for EZ-USB Microcontrollers
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+/*
+ EEPROM support an some I2C helper routines
+*/
+
+#ifndef[ZTEX_EEPROM_H]
+#define[ZTEX_EEPROM_H]
+
+#define[@CAPABILITY_EEPROM;]
+#define[EEPROM_ADDR][0xA2]
+
+/* *********************************************************************
+ ***** global variables **********************************************
+ ********************************************************************* */
+xdata WORD eeprom_addr;
+xdata WORD eeprom_length;
+xdata WORD eeprom_write_bytes;
+xdata BYTE eeprom_write_checksum;
+
+/* *********************************************************************
+ ***** i2c_waitWrite *************************************************
+ ********************************************************************* */
+/* Do the necessary steps after writing I2DAT register. Returns 1 on error. */
+BYTE i2c_waitWrite()
+{
+ unsigned char i2csbuf,toc;
+ for ( toc=0; toc<255 && !(I2CS & bmBIT0); toc++ );
+ i2csbuf = I2CS;
+ if ( (i2csbuf & bmBIT2) || (!(i2csbuf & bmBIT1)) ) {
+ I2CS |= bmBIT6;
+ return 1;
+ }
+ return 0;
+}
+
+/* *********************************************************************
+ ***** i2c_waitRead **************************************************
+ ********************************************************************* */
+/* Do the necessary steps after reading I2DAT register. Returns 1 on error. */
+BYTE i2c_waitRead(void)
+{
+ unsigned char i2csbuf, toc;
+ for ( toc=0; toc<255 && !(I2CS & bmBIT0); toc++ );
+ i2csbuf = I2CS;
+ if (i2csbuf & bmBIT2) {
+ I2CS |= bmBIT6;
+ return 1;
+ }
+ return 0;
+}
+
+/* *********************************************************************
+ ***** i2c_waitStart *************************************************
+ ********************************************************************* */
+/* Do the necessary steps after start bit. Returns 1 on error. */
+BYTE i2c_waitStart()
+{
+ BYTE toc;
+ for ( toc=0; toc<255; toc++ ) {
+ if ( ! (I2CS & bmBIT2) )
+ return 0;
+ }
+ return 1;
+}
+
+/* *********************************************************************
+ ***** i2c_waitStop **************************************************
+ ********************************************************************* */
+/* Do the necessary steps after stop bit. Returns 1 on error. */
+BYTE i2c_waitStop()
+{
+ BYTE toc;
+ for ( toc=0; toc<255; toc++ ) {
+ if ( ! (I2CS & bmBIT6) )
+ return 0;
+ }
+ return 1;
+}
+
+/* *********************************************************************
+ ***** eeprom_select *************************************************
+ ********************************************************************* */
+/* Select the EEPROM device, i.e. send the control Byte.
+ specifies the time to wait in 0.1ms steps if the EEPROM is busy (during a write cycle).
+ if =0 no sop bit is sent. Returns 1 on error or if EEPROM is busy. */
+BYTE eeprom_select ( BYTE to, BYTE stop ) {
+ BYTE toc = 0;
+eeprom_select_start:
+ I2CS |= bmBIT7; // start bit
+ i2c_waitStart();
+ I2DAT = EEPROM_ADDR; // select device for writing
+ if ( ! i2c_waitWrite() ) {
+ if ( stop ) {
+ I2CS |= bmBIT6;
+ i2c_waitStop();
+ }
+ return 0;
+ }
+ else if (toc bytes from EEPROM address and write them to buf.
+ Returns the number of bytes read. This number is 0 during a write cycle. */
+BYTE eeprom_read ( __xdata BYTE *buf, WORD addr, BYTE length ) {
+ BYTE bytes = 0,i;
+
+ if ( eeprom_select(100,0) )
+ goto eeprom_read_end;
+
+ I2DAT = HI(addr); // write address
+ if ( i2c_waitWrite() ) goto eeprom_read_end;
+ I2DAT = LO(addr); // write address
+ if ( i2c_waitWrite() ) goto eeprom_read_end;
+ I2CS |= bmBIT6;
+ i2c_waitStop();
+
+ I2CS |= bmBIT7; // start bit
+ i2c_waitStart();
+ I2DAT = EEPROM_ADDR | 1; // select device for reading
+ if ( i2c_waitWrite() ) goto eeprom_read_end;
+
+ *buf = I2DAT; // dummy read
+ if ( i2c_waitRead()) goto eeprom_read_end;
+ for (; bytes bytes from buf to and write them EEPROM address .
+ must be smaller or equal than 64. Returns the number of bytes
+ read. This number is 0 during a write cycle. */
+BYTE eeprom_write ( __xdata BYTE *buf, WORD addr, BYTE length ) {
+ BYTE bytes = 0;
+
+ if ( eeprom_select(100,0) )
+ goto eeprom_write_end;
+
+ I2DAT = HI(addr); // write address
+ if ( i2c_waitWrite() ) goto eeprom_write_end;
+ I2DAT = LO(addr); // write address
+ if ( i2c_waitWrite() ) goto eeprom_write_end;
+
+ for (; bytes 64 ) ? 64 : eeprom_length;
+ i = eeprom_read(EP0BUF, eeprom_addr, b);
+ eeprom_addr += b;
+ eeprom_length -= b;
+ return i;
+}
+
+ADD_EP0_VENDOR_REQUEST((0x38,, // read from EEPROM
+ eeprom_addr = (SETUPDAT[3] << 8) | SETUPDAT[2]; // Address
+ eeprom_length = (SETUPDAT[7] << 8) | SETUPDAT[6]; // size
+ EP0BCH = 0;
+ EP0BCL = eeprom_read_ep0();
+,,
+ EP0BCH = 0;
+ EP0BCL = eeprom_read_ep0();
+));;
+
+
+/* *********************************************************************
+ ***** EP0 vendor command 0x39 ***************************************
+ ********************************************************************* */
+void eeprom_write_ep0 ( BYTE length ) {
+ eeprom_write(EP0BUF, eeprom_addr, length);
+ eeprom_addr += length;
+}
+
+ADD_EP0_VENDOR_COMMAND((0x39,, // write to EEPROM
+ eeprom_write_checksum = 0;
+ eeprom_write_bytes = 0;
+ eeprom_addr = ( SETUPDAT[3] << 8) | SETUPDAT[2]; // Address
+ EP0BCL = 1;
+,,
+ eeprom_write_ep0(EP0BCL);
+ ));;
+
+/* *********************************************************************
+ ***** EP0 vendor request 0x3A ***************************************
+ ********************************************************************* */
+ADD_EP0_VENDOR_REQUEST((0x3A,, // EEPROM state
+ EP0BUF[0] = LSB(eeprom_write_bytes);
+ EP0BUF[1] = MSB(eeprom_write_bytes);
+ EP0BUF[2] = eeprom_write_checksum;
+ EP0BUF[3] = eeprom_select(0,1); // 1 means busy or error
+ EP0BCH = 0;
+ EP0BCL = 4;
+,,));;
+
+
+#endif /*ZTEX_EEPROM_H*/
Index: usb_fpga_1_2/trunk/include/ztex-isr.h
===================================================================
--- usb_fpga_1_2/trunk/include/ztex-isr.h (nonexistent)
+++ usb_fpga_1_2/trunk/include/ztex-isr.h (revision 2)
@@ -0,0 +1,432 @@
+/*!
+ ZTEX Firmware Kit for EZ-USB Microcontrollers
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+/*
+ Interrupt routines
+*/
+
+#ifndef[ZTEX_ISR_H]
+#define[ZTEX_ISR_H]
+
+xdata BYTE prevSetupRequest = 0xff;
+
+xdata WORD ISOFRAME_COUNTER[4] = {0, 0, 0, 0}; // counters for iso frames automatically reset by sync frame request
+
+/* *********************************************************************
+ ***** toggleData ****************************************************
+ ********************************************************************* */
+static void resetToggleData () {
+#define[RESET_TOGGLE_DATA_EP(][);][
+#ifeq[EP$0_DIR][OUT]
+ TOGCTL = $0; // EP$0 out
+ TOGCTL = $0 | bmBIT5;
+#endif
+#ifeq[EP$0_DIR][IN]
+ TOGCTL = bmBIT4 | $0; // EP$0 in
+ TOGCTL = bmBIT4 | $0 | bmBIT5;
+#endif]
+
+ TOGCTL = 0; // EP0 out
+ TOGCTL = 0 | bmBIT5;
+ TOGCTL = 0x10; // EP0 in
+ TOGCTL = 0x10 | bmBIT5;
+#ifeq[EP1OUT_DIR][OUT]
+ TOGCTL = 1; // EP1 out
+ TOGCTL = 1 | bmBIT5;
+#endif
+#ifeq[EP1IN_DIR][IN]
+ TOGCTL = 0x11; // EP1 in
+ TOGCTL = 0x11 | bmBIT5;
+#endif
+ RESET_TOGGLE_DATA_EP(2);
+ RESET_TOGGLE_DATA_EP(4);
+ RESET_TOGGLE_DATA_EP(6);
+ RESET_TOGGLE_DATA_EP(8);
+}
+
+/* *********************************************************************
+ ***** getStringDescriptor *******************************************
+ ********************************************************************* */
+#define[SEND_STRING_DESCRIPTOR(][,$1);][sendStringDescriptor(LSB($1), MSB($1), sizeof($1) );]
+
+static void sendStringDescriptor (BYTE loAddr, BYTE hiAddr, BYTE size)
+{
+ BYTE i;
+ if ( size > 31)
+ size = 31;
+ AUTOPTRL1 = loAddr;
+ AUTOPTRH1 = hiAddr;
+ AUTOPTRL2 = (BYTE)(((unsigned short)(&EP0BUF))+1);
+ AUTOPTRH2 = (BYTE)((((unsigned short)(&EP0BUF))+1) >> 8);
+ XAUTODAT2 = 3;
+ AUTOPTRSETUP = 7;
+ for (i=0; i> 1)-1) & 3 ] & bmBIT0;
+ break;
+ }
+ EP0BUF[1] = 0;
+ EP0BCH = 0;
+ EP0BCL = 2;
+ break;
+ }
+ break;
+ case 0x01: // disable feature, e.g. remote wake, stall bit
+ if ( SETUPDAT[0] == 2 && SETUPDAT[2] == 0 ) {
+ switch ( SETUPDAT[4] ) {
+ case 0x00 :
+ case 0x80 :
+ EP0CS &= ~bmBIT0;
+ break;
+ case 0x01 :
+ EP1OUTCS &= ~bmBIT0;
+ break;
+ case 0x81 :
+ EP1INCS &= ~bmBIT0;
+ break;
+ default:
+ EPXCS[ ((SETUPDAT[4] >> 1)-1) & 3 ] &= ~bmBIT0;
+ break;
+ }
+ }
+ break;
+ case 0x03: // enable feature, e.g. remote wake, test mode, stall bit
+ if ( SETUPDAT[0] == 2 && SETUPDAT[2] == 0 ) {
+ switch ( SETUPDAT[4] ) {
+ case 0x00 :
+ case 0x80 :
+ EP0CS |= bmBIT0;
+ break;
+ case 0x01 :
+ EP1OUTCS |= bmBIT0;
+ break;
+ case 0x81 :
+ EP1INCS |= bmBIT0;
+ break;
+ default:
+ EPXCS[ ((SETUPDAT[4] >> 1)-1) & 3 ] |= ~bmBIT0;
+ break;
+ }
+ a = ( (SETUPDAT[4] & 0x80) >> 3 ) | (SETUPDAT[4] & 0x0f);
+ TOGCTL = a;
+ TOGCTL = a | bmBIT5;
+ }
+ break;
+ case 0x06: // get descriptor
+ switch(SETUPDAT[3]) {
+ case 0x01: // device
+ SUDPTRH = MSB(&DeviceDescriptor);
+ SUDPTRL = LSB(&DeviceDescriptor);
+ break;
+ case 0x02: // configuration
+ if (USBCS & bmBIT7) {
+ SUDPTRH = MSB(&HighSpeedConfigDescriptor);
+ SUDPTRL = LSB(&HighSpeedConfigDescriptor);
+ }
+ else {
+ SUDPTRH = MSB(&FullSpeedConfigDescriptor);
+ SUDPTRL = LSB(&FullSpeedConfigDescriptor);
+ }
+ break;
+ case 0x03: // strings
+ switch (SETUPDAT[2]) {
+ case 1:
+ SEND_STRING_DESCRIPTOR(1,manufacturerString);
+ break;
+ case 2:
+ SEND_STRING_DESCRIPTOR(2,productString);
+ break;
+ case 3:
+ SEND_STRING_DESCRIPTOR(3,SN_STRING);
+ break;
+ case 4:
+ SEND_STRING_DESCRIPTOR(4,configurationString);
+ break;
+ default:
+ SUDPTRH = MSB(&EmptyStringDescriptor);
+ SUDPTRL = LSB(&EmptyStringDescriptor);
+ break;
+ }
+ break;
+ case 0x06: // device qualifier
+ SUDPTRH = MSB(&DeviceQualifierDescriptor);
+ SUDPTRL = LSB(&DeviceQualifierDescriptor);
+ break;
+ case 0x07: // other speed configuration
+ if (USBCS & bmBIT7) {
+ SUDPTRH = MSB(&FullSpeedConfigDescriptor);
+ SUDPTRL = LSB(&FullSpeedConfigDescriptor);
+ }
+ else {
+ SUDPTRH = MSB(&HighSpeedConfigDescriptor);
+ SUDPTRL = LSB(&HighSpeedConfigDescriptor);
+ }
+ break;
+ default:
+ EP0CS |= 0x01; // set stall, unknown descriptor
+ }
+ break;
+ case 0x07: // set descriptor
+ break;
+ case 0x08: // get configuration
+ EP0BUF[0] = 0; // only one configuration
+ EP0BCH = 0;
+ EP0BCL = 1;
+ break;
+ case 0x09: // set configuration
+ resetToggleData();
+ break; // do nothing since we have only one configuration
+ case 0x0a: // get alternate setting for an interface
+ EP0BUF[0] = 0; // only one alternate setting
+ EP0BCH = 0;
+ EP0BCL = 1;
+ break;
+ case 0x0b: // set alternate setting for an interface
+ resetToggleData();
+ break; // do nothing since we have only on alternate setting
+ case 0x0c: // sync frame
+ if ( SETUPDAT[0] == 0x82 ) {
+ ISOFRAME_COUNTER[ ((SETUPDAT[4] >> 1)-1) & 3 ] = 0;
+ EP0BUF[0] = USBFRAMEL; // use current frame as sync frame, i hope that works
+ EP0BUF[1] = USBFRAMEH;
+ EP0BCH = 0;
+ EP0BCL = 2;
+ }
+ break; // do nothing since we have only on alternate setting
+
+ }
+
+ // vendor request and commands
+ switch ( bmRequestType ) {
+ case 0xc0: // vendor request
+ switch ( bRequest ) {
+ case 0x22: // get ZTEX descriptor
+ SUDPTRCTL = 0;
+ EP0BCH = 0;
+ EP0BCL = ZTEX_DESCRIPTOR_LEN;
+ SUDPTRH = MSB(ZTEX_DESCRIPTOR_OFFS);
+ SUDPTRL = LSB(ZTEX_DESCRIPTOR_OFFS);
+ break;
+ EP0_VENDOR_REQUESTS_SU;
+ default:
+ EP0CS |= 0x01; // set stall, unknown request
+ }
+ break;
+ case 0x40: // vendor command
+ switch ( bRequest ) {
+ EP0_VENDOR_COMMANDS_SU;
+ default:
+ EP0CS |= 0x01; // set stall, unknown request
+ }
+ break;
+ }
+
+ EP0CS |= 0x80;
+ EXIF &= ~bmBIT4;
+ USBIRQ = bmBIT0;
+}
+
+/* *********************************************************************
+ ***** SOF_ISR *******************************************************
+ ********************************************************************* */
+void SOF_ISR() interrupt
+{
+ EXIF &= ~bmBIT4;
+ USBIRQ = bmBIT1;
+}
+
+/* *********************************************************************
+ ***** SUTOK_ISR *****************************************************
+ ********************************************************************* */
+void SUTOK_ISR() interrupt
+{
+ EXIF &= ~bmBIT4;
+ USBIRQ = bmBIT2;
+}
+
+/* *********************************************************************
+ ***** SUSP_ISR ******************************************************
+ ********************************************************************* */
+void SUSP_ISR() interrupt
+{
+ EXIF &= ~bmBIT4;
+ USBIRQ = bmBIT3;
+}
+
+/* *********************************************************************
+ ***** URES_ISR ******************************************************
+ ********************************************************************* */
+void URES_ISR() interrupt
+{
+ EXIF &= ~bmBIT4;
+ USBIRQ = bmBIT4;
+}
+
+/* *********************************************************************
+ ***** HSGRANT_ISR ***************************************************
+ ********************************************************************* */
+void HSGRANT_ISR() interrupt
+{
+ EXIF &= ~bmBIT4;
+ USBIRQ = bmBIT5;
+}
+
+/* *********************************************************************
+ ***** AP0ACK_ISR ****************************************************
+ ********************************************************************* */
+void EP0ACK_ISR() interrupt
+{
+ EXIF &= ~bmBIT4;
+ USBIRQ = bmBIT6;
+}
+
+/* *********************************************************************
+ ***** EP0IN_ISR *****************************************************
+ ********************************************************************* */
+static void EP0IN_ISR () interrupt
+{
+ switch ( prevSetupRequest ) {
+ EP0_VENDOR_REQUESTS_DAT;
+ default:
+ EP0BCH = 0;
+ EP0BCL = 0;
+ }
+ EP0CS |= 0x80;
+ EXIF &= ~bmBIT4;
+ EPIRQ = bmBIT0;
+}
+
+/* *********************************************************************
+ ***** EP0OUT_ISR ****************************************************
+ ********************************************************************* */
+static void EP0OUT_ISR () interrupt
+{
+ switch ( prevSetupRequest ) {
+ EP0_VENDOR_COMMANDS_DAT;
+ }
+
+ EP0BCL = 1;
+
+ EXIF &= ~bmBIT4;
+ EPIRQ = bmBIT1;
+}
+
+
+/* *********************************************************************
+ ***** EP1IN_ISR *****************************************************
+ ********************************************************************* */
+void EP1IN_ISR() interrupt
+{
+ EXIF &= ~bmBIT4;
+ EPIRQ = bmBIT2;
+
+}
+
+/* *********************************************************************
+ ***** EP1OUT_ISR ****************************************************
+ ********************************************************************* */
+void EP1OUT_ISR() interrupt
+{
+ EXIF &= ~bmBIT4;
+ EPIRQ = bmBIT3;
+}
+
+/* *********************************************************************
+ ***** EP2_ISR *******************************************************
+ ********************************************************************* */
+void EP2_ISR() interrupt
+{
+ EXIF &= ~bmBIT4;
+ EPIRQ = bmBIT4;
+}
+
+/* *********************************************************************
+ ***** EP4_ISR *******************************************************
+ ********************************************************************* */
+void EP4_ISR() interrupt
+{
+ EXIF &= ~bmBIT4;
+ EPIRQ = bmBIT5;
+}
+
+/* *********************************************************************
+ ***** EP6_ISR *******************************************************
+ ********************************************************************* */
+void EP6_ISR() interrupt
+{
+ EXIF &= ~bmBIT4;
+ EPIRQ = bmBIT6;
+}
+
+/* *********************************************************************
+ ***** EP8_ISR *******************************************************
+ ********************************************************************* */
+void EP8_ISR() interrupt
+{
+ EXIF &= ~bmBIT4;
+ EPIRQ = bmBIT7;
+}
+
+#endif /* ZTEX_ISR_H */
Index: usb_fpga_1_2/trunk/include/ztex-fpga.h
===================================================================
--- usb_fpga_1_2/trunk/include/ztex-fpga.h (nonexistent)
+++ usb_fpga_1_2/trunk/include/ztex-fpga.h (revision 2)
@@ -0,0 +1,175 @@
+/*!
+ ZTEX Firmware Kit for EZ-USB Microcontrollers
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+/*
+ FPGA configuration support
+*/
+
+#ifndef[ZTEX_FPGA_H]
+#define[ZTEX_FPGA_H]
+
+#define[@CAPABILITY_FPGA;]
+
+xdata BYTE fpga_checksum = 0; // checksum
+xdata DWORD fpga_bytes = 0; // transfered bytes
+xdata BYTE fpga_init_b = 0; // init_b state (should be 222 after configuration)
+
+/* *********************************************************************
+ ***** resetFPGA *****************************************************
+ ********************************************************************* */
+static void resetFPGA () { // reset FPGA
+ unsigned short k;
+ IFCONFIG = bmBIT7;
+ SYNCDELAY;
+ PORTACFG = 0;
+ PORTCCFG = 0;
+ PORTECFG = 0;
+
+ OEA = bmBIT1;
+ IOA1 = 0;
+ wait(10);
+
+ OEB = 0xff; // setup IO's
+ OEC = bmBIT2 | bmBIT3;
+ IOC = bmBIT3;
+
+ OED = bmBIT0;
+ IOD0 = 0;
+
+ IOA1 = 1; // ready for configuration
+ IOD0 = 1;
+ k=0;
+ while (!IOC0 && k<65535)
+ k++;
+
+ fpga_init_b = IOC0 ? 200 : 100;
+ fpga_bytes = 0;
+ fpga_checksum = 0;
+
+ IOC = 0;
+}
+
+/* *********************************************************************
+ ***** initFPGAConfiguration *****************************************
+ ********************************************************************* */
+static void initFPGAConfiguration () {
+ {
+ PRE_FPGA_RESET
+ }
+ resetFPGA(); // reset FPGA
+}
+
+/* *********************************************************************
+ ***** finishFPGAConfiguration ***************************************
+ ********************************************************************* */
+static void finishFPGAConfiguration () {
+ fpga_init_b += IOC0 ? 20 : 10;
+ IOD0 = 0; IOB = 0; IOD0 = 1;
+ IOD0 = 0; IOD0 = 1;
+ IOD0 = 0; IOD0 = 1;
+ IOD0 = 0; IOD0 = 1;
+ IOD0 = 0; IOD0 = 1;
+ IOD0 = 0; IOD0 = 1;
+ IOD0 = 0; IOD0 = 1;
+ IOD0 = 0; IOD0 = 1;
+ IOD0 = 0; IOD0 = 1;
+ IOD0 = 0; IOD0 = 1;
+ IOD0 = 0; IOD0 = 1;
+ OEB = 0;
+// OEC = 0;
+ OED = 0;
+ OEA = 0;
+ fpga_init_b += IOC0 ? 2 : 1;
+ if ( IOA1 ) {
+ POST_FPGA_CONFIG
+ }
+
+ IOA1 = 1;
+ OEA |= bmBIT1;
+}
+
+
+/* *********************************************************************
+ ***** EP0 vendor request 0x30 ***************************************
+ ********************************************************************* */
+ADD_EP0_VENDOR_REQUEST((0x30,, // get FPGA state
+ MEM_COPY1(fpga_checksum,EP0BUF+1,6);
+ OEA &= ~bmBIT1;
+ if ( IOA1 ) {
+ EP0BUF[0] = 0; // FPGA configured
+ IOA1 = 1;
+ OEA |= bmBIT1;
+ }
+ else {
+ EP0BUF[0] = 1; // FPGA unconfigured
+ resetFPGA(); // prepare FPGA for configuration
+ }
+
+ EP0BCH = 0;
+ EP0BCL = 7;
+,,));;
+
+
+/* *********************************************************************
+ ***** EP0 vendor command 0x31 ***************************************
+ ********************************************************************* */
+ADD_EP0_VENDOR_COMMAND((0x31,,initFPGAConfiguration();,,));; // reset FPGA
+
+
+/* *********************************************************************
+ ***** EP0 vendor command 0x32 ***************************************
+ ********************************************************************* */
+ADD_EP0_VENDOR_COMMAND((0x32,, // send FPGA configuration data
+ EP0BCL=1;
+,,
+ fpga_bytes += EP0BCL;
+ _asm
+ mov _AUTOPTRL1,#(_EP0BUF)
+ mov _AUTOPTRH1,#(_EP0BUF >> 8)
+ mov _AUTOPTRSETUP,#0x07
+ mov dptr,#_EP0BCL
+ movx a,@dptr
+ jz 010000$
+ mov r2,a
+ mov dptr,#_fpga_checksum
+ movx a,@dptr
+ mov r1,a
+ mov dptr,#_XAUTODAT1
+010001$:
+ clr _IOD0
+ movx a,@dptr
+ mov _IOB,a
+ add a,r1
+ mov r1,a
+ setb _IOD0
+ djnz r2, 010001$
+
+ mov dptr,#_fpga_checksum
+ mov a,r1
+ movx @dptr,a
+
+010000$:
+ _endasm;
+
+ if ( EP0BCL<64 ) {
+ finishFPGAConfiguration();
+ }
+));;
+
+
+#endif /*ZTEX_FPGA_H*/
Index: usb_fpga_1_2/trunk/include/ztex-HSFPGAConf.h
===================================================================
--- usb_fpga_1_2/trunk/include/ztex-HSFPGAConf.h (nonexistent)
+++ usb_fpga_1_2/trunk/include/ztex-HSFPGAConf.h (revision 2)
@@ -0,0 +1,117 @@
+/*!
+ ZTEX Firmware Kit for EZ-USB Microcontrollers
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+#ifndef[ZTEX_HS_FPGA_CONF1_H]
+#define[ZTEX_HS_FPGA_CONF1_H]
+
+ADD_EP0_VENDOR_COMMAND((0x33,,initHSFPGAConfiguration();,,));;
+ADD_EP0_VENDOR_COMMAND((0x34,,finishHSFPGAConfiguration();,,));;
+
+#ifndef[HS_FPGA_CONF_EP]
+#error[Macro `HS_FPGA_CONF_EP' is not defined]
+#endif
+
+#ifeq[HS_FPGA_CONF_EP][2]
+#elifeq[HS_FPGA_CONF_EP][4]
+#elifeq[HS_FPGA_CONF_EP][6]
+#elifneq[HS_FPGA_CONF_EP][8]
+#error[Macro `HS_FPGA_CONF_EP' is not defined correctly. Valid values are: `2', `4', `6', `8'.]
+#endif
+
+
+static void initHSFPGAConfiguration();
+static void finishHSFPGAConfiguration();
+
+#elifndef[ZTEX_HS_FPGA_CONF2_H] /*ZTEX_HS_FPGA_CONF1_H*/
+#define[ZTEX_HS_FPGA_CONF2_H]
+
+static void finishHSFPGAConfiguration() {
+ GPIFABORT = 0xFF;
+ SYNCDELAY;
+ IFCONFIG = bmBIT7 | bmBIT6;
+ SYNCDELAY;
+ finishFPGAConfiguration();
+}
+
+// FIFO write wave form
+const char xdata GPIF_WAVE_DATA_HSFPGA[32] =
+{
+/* LenBr */ 0x88, 0x01, 0xB8, 0x01, 0x01, 0x01, 0x01, 0x07,
+/* Opcode*/ 0x03, 0x06, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
+/* Output*/ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+/* LFun */ 0xF7, 0x00, 0x2D, 0x00, 0x00, 0x00, 0x00, 0x3F,
+};
+
+
+static void initHSFPGAConfiguration() {
+ initFPGAConfiguration();
+
+ EPHS_FPGA_CONF_EPCS &= ~bmBIT0; // clear stall bit
+
+ GPIFABORT = 0xFF; // abort pendig
+
+ IFCONFIG = bmBIT7 + bmBIT6 + bmBIT5 + 2; // Internal source, 48MHz, GPIF
+
+ GPIFREADYCFG = bmBIT7 | bmBIT6 | bmBIT5;
+ GPIFCTLCFG = 0;
+ GPIFIDLECS = 0;
+ GPIFIDLECTL = 0;
+ GPIFWFSELECT = 0x4E;
+ GPIFREADYSTAT = 0;
+
+ MEM_COPY1(GPIF_WAVE_DATA_HSFPGA,GPIF_WAVE3_DATA,32);
+
+ FLOWSTATE = 0;
+ FLOWLOGIC = 0;
+ FLOWEQ0CTL = 0;
+ FLOWEQ1CTL = 0;
+ FLOWHOLDOFF = 0;
+ FLOWSTB = 0;
+ FLOWSTBEDGE = 0;
+ FLOWSTBHPERIOD = 0;
+
+ REVCTL = 0x0; // reset fifo
+ SYNCDELAY;
+ FIFORESET = 0x80;
+ SYNCDELAY;
+ FIFORESET = HS_FPGA_CONF_EP;
+ SYNCDELAY;
+ FIFORESET = 0x0;
+ SYNCDELAY;
+
+ EPHS_FPGA_CONF_EPFIFOCFG = bmBIT0; // config fifo
+ SYNCDELAY;
+ EPHS_FPGA_CONF_EPFIFOCFG = bmBIT4 | bmBIT0;
+ SYNCDELAY;
+ EPHS_FPGA_CONF_EPGPIFFLGSEL = 1;
+ SYNCDELAY;
+
+ GPIFTCB3 = 0; // abort after at least 14*65536 transactions
+ SYNCDELAY;
+ GPIFTCB2 = 14;
+ SYNCDELAY;
+ GPIFTCB1 = 0;
+ SYNCDELAY;
+ GPIFTCB0 = 0;
+ SYNCDELAY;
+
+ EPHS_FPGA_CONF_EPGPIFTRIG = 0xff; // arm fifos
+ SYNCDELAY;
+}
+
+#endif /*ZTEX_HS_FPGA_CONF2_H*/
Index: usb_fpga_1_2/trunk/include/ztex-flash1.h
===================================================================
--- usb_fpga_1_2/trunk/include/ztex-flash1.h (nonexistent)
+++ usb_fpga_1_2/trunk/include/ztex-flash1.h (revision 2)
@@ -0,0 +1,120 @@
+/*!
+ ZTEX Firmware Kit for EZ-USB Microcontrollers
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+/*
+ supports AT45D* Flash on Port E
+*/
+
+#ifndef[ZTEX_FLASH_H]
+#define[ZTEX_FLASH_H]
+
+#define[FLASH_SI_BIT][6]
+#define[FLASH_SO_BIT][4]
+#define[FLASH_CLK_BIT][5]
+#ifeq[PRODUCT_IS][UFM-1_1]
+#define[FLASH_CS_BIT][3]
+//#warning[FLASH_CS_BIT=3]
+#else
+#define[FLASH_CS_BIT][7]
+//#warning[FLASH_CS_BIT=7]
+#endif
+
+xdata BYTE flash_buffer = 1; // current buffer 1
+xdata BYTE flash_bufferModified = 0; // 1 indicates that the current flash page needs to be reprogrammeded
+xdata WORD flash_page = 0xffff; // current flash page
+xdata WORD flash_nextPage = 0xffff; // next flash page (usually flashPage+1)
+xdata WORD flash_maxPage = 0; // next flash page (usually flashPage+1)
+xdata WORD flash_pageSize = 528; // page size (512 or 528)
+xdata BYTE flash_register[4]; // used to store register content
+
+/* *********************************************************************
+ ***** flash_setPage *************************************************
+ ********************************************************************* */
+/* set the current page, i.e. executes the following steps
+ 1. wait if busy
+ 2. read the desired page from the falsh array into the new buffer
+ 3. write the old buffer to the flash array (if modified)
+*/
+static void flash_setPage(WORD page)
+{
+ flash_nextPage = page + 1;
+}
+
+/* *********************************************************************
+ ***** flash_write ***************************************************
+ ********************************************************************* */
+/* writes bytes at address to the current buffer starting at .
+ If = 1 the next page (defined by is set automatically
+*/
+static void flash_write(WORD addr, WORD bytes, WORD offs, BYTE setNextPage)
+{
+ addr = 0;
+ bytes = 0;
+ offs = 0;
+ setNextPage = 0;
+}
+
+/* *********************************************************************
+ ***** flash_write ***************************************************
+ ********************************************************************* */
+static void flash_readRegister(BYTE cmd)
+{
+ BYTE oe,b,i,j;
+
+ b = OEE & ( ~( (1 << FLASH_SO_BIT) | (1 << FLASH_SI_BIT) | (1 << FLASH_CLK_BIT) | (1 << FLASH_CS_BIT) ) );
+ oe = IOE & b;
+ IOE = oe | (1 << FLASH_CS_BIT); // CS = 1
+ OEE = b | (1 << FLASH_SI_BIT) | (1 << FLASH_CLK_BIT) | (1 << FLASH_CS_BIT);
+ IOE = oe; // CS = 0
+
+ // CLK=0
+ for ( i=0; i<8; i++ ) {
+ IOE = b = oe | ((cmd & 128) >> (7-FLASH_SI_BIT)); // CLK = 0, SI=x
+ IOE = b | (1 << FLASH_CLK_BIT); // CLK = 1, SI=x
+ cmd <<= 1;
+ }
+
+ for ( j=0; j<4; j++ ) {
+ // CLK = 1
+ b = 0;
+ for ( i=0; i<8; i++ ) {
+ IOE = oe; // CLK = 0, SO=x
+ b = (b << 1) | ((IOE >> FLASH_SO_BIT) & 1);
+ IOE = oe | (1 << FLASH_CLK_BIT); // CLK = 1
+ }
+ flash_register[j]=b;
+ }
+
+ IOE = oe | (1 << FLASH_CS_BIT); // CS = 1
+}
+
+
+/* *********************************************************************
+ ***** EP0 vendor request 0x40 ***************************************
+ ********************************************************************* */
+ADD_EP0_VENDOR_REQUEST((0x40,,
+ flash_readRegister(SETUPDAT[2]);
+ EP0BUF[0] = flash_register[0];
+ EP0BUF[1] = flash_register[1];
+ EP0BUF[2] = flash_register[2];
+ EP0BUF[3] = flash_register[3];
+ EP0BCH = 0;
+ EP0BCL = 4;
+,,));;
+
+#endif /*ZTEX_DESCRIPTORS_H*/
Index: usb_fpga_1_2/trunk/include/ztex-utils.h
===================================================================
--- usb_fpga_1_2/trunk/include/ztex-utils.h (nonexistent)
+++ usb_fpga_1_2/trunk/include/ztex-utils.h (revision 2)
@@ -0,0 +1,111 @@
+/*!
+ ZTEX Firmware Kit for EZ-USB Microcontrollers
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+/*
+ Various utility routines
+*/
+
+#ifndef[ZTEX_UTILS_H]
+#define[ZTEX_UTILS_H]
+
+#define[bmBIT0][1]
+#define[bmBIT1][2]
+#define[bmBIT2][4]
+#define[bmBIT3][8]
+#define[bmBIT4][16]
+#define[bmBIT5][32]
+#define[bmBIT6][64]
+#define[bmBIT7][128]
+
+#define[NOP;][_asm
+ nop
+ _endasm;
+]
+
+#define[MSB(][)][((BYTE)(((unsigned short)($0)) >> 8))]
+#define[LSB(][)][((BYTE)($0))]
+#define[HI(][)][((BYTE)(((unsigned short)($0)) >> 8))]
+#define[LO(][)][((BYTE)($0))]
+
+typedef unsigned char BYTE;
+typedef unsigned short WORD;
+typedef unsigned long DWORD;
+
+/* *********************************************************************
+ ***** include the basic functions ***********************************
+ ********************************************************************* */
+#include[ezregs.h]
+#include[ezintavecs.h]
+
+/* *********************************************************************
+ ***** wait **********************************************************
+ ********************************************************************* */
+void wait(WORD short ms) { // wait in ms
+ WORD i,j;
+ for (j=0; j> 8)
+ mov _AUTOPTRL2,#(_$1)
+ mov _AUTOPTRH2,#((_$1) >> 8)
+ mov r2,#($2);
+ lcall _MEM_COPY1_int
+ _endasm;
+}]
+
+
+#endif // ZTEX_UTILS_H
Index: usb_fpga_1_2/trunk/Makefile.mk
===================================================================
--- usb_fpga_1_2/trunk/Makefile.mk (nonexistent)
+++ usb_fpga_1_2/trunk/Makefile.mk (revision 2)
@@ -0,0 +1,61 @@
+# This Makefile defines the standard rules for building the project.
+#
+# The following variables are used:
+#
+# ZTEXPREFIX
+# Defines location if this firmware / driver kit.
+# Must be defined!
+# Example: ZTEXPREFIX=../../..
+#
+# JARTARGET
+# The name of the jar archive
+# Example: JARTARGET=UCEcho.jar
+#
+# CLASSTARGETS
+# Java Classes that have to be build
+# Example: CLASSTARGETS=UCEcho.class
+#
+# CLASSEXTRADEPS
+# Extra dependencies for Java Classes
+# Example: CLASSEXTRADEPS:=$(shell echo $(ZTEXPREFIX)/java/ztex/*.java)
+#
+# IHXTARGETS
+# ihx files (firmware ROM files) that have to be build
+# Example: IHXTARGETS=ucecho.ihx
+#
+# IHXEXTRADEPS
+# Extra Dependencies for ihx files
+# Example: IHXEXTRADEPS:=$(shell echo $(ZTEXPREFIX)/include/*.h)
+#
+# EXTRAJARFILES
+# Extra files that should be included into th jar achieve
+# Example: EXTRAJARFILES=ucecho.ihx fpga/ucecho.bin
+
+.PHONY: all ihx jar clean distclean
+
+JAVAC=javac
+SDCC=$(ZTEXPREFIX)/bin/bmpsdcc.sh
+CLASSPATH:=.:$(ZTEXPREFIX)/libusbJava:$(ZTEXPREFIX)/java:$(CLASSPATH)
+INCLUDES=-I $(ZTEXPREFIX)/include/
+
+all : ihx jar
+ihx : $(IHXTARGETS)
+jar : $(JARTARGET)
+
+%.ihx: %.c $(IHXEXTRADEPS)
+ $(SDCC) $< "$(INCLUDES)"
+
+%.class: %.java $(CLASSEXTRADEPS)
+ $(JAVAC) -cp "$(CLASSPATH)" $<
+
+$(JARTARGET) : $(CLASSTARGETS) $(EXTRAJARFILES)
+ jar cf $(JARTARGET) *.class $(EXTRAJARFILES) -C $(ZTEXPREFIX)/libusbJava . $(shell cd $(ZTEXPREFIX)/java; ls ztex/*.class | while read a; do echo "-C $(ZTEXPREFIX)/java $$a"; done)
+
+clean:
+ rm -f *~ *.bak *.old
+ rm -f *.class
+ rm -f *.rel *.rst *.lnk *.lst *.map *.asm *.sym *.mem *.tmp.c
+
+distclean: clean
+ rm -f $(JARTARGET)
+ rm -f *.ihx
Index: usb_fpga_1_2/trunk/makecopyright
===================================================================
--- usb_fpga_1_2/trunk/makecopyright (nonexistent)
+++ usb_fpga_1_2/trunk/makecopyright (revision 2)
@@ -0,0 +1,80 @@
+#!/bin/sh
+#
+# makecopyright - put a copyright info into source files
+# Copyright (C) 2008-2009 ZTEX e.K., http://www.ztex.de
+#
+
+# writes the copyright info to stdout
+# $1 short description
+# $2 begin of comment
+# $3 end of comment
+msg () {
+echo "$2
+ $1
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+$3"
+}
+
+readonly=no
+
+# copyright info for single file
+# $1 file
+# $2 short description
+# $3 begin of comment
+# $4 end of comment
+singlefile () {
+# if [ ! -f "$1" -o -f "$1.tmp" ]; then
+ if [ ! -f "$1" ]; then
+ return
+ fi
+ echo "$1"
+ if [ "$readonly" = "no" ]; then
+ mv "$1" "$1.tmp"
+ (
+ msg "$2" "$3" "$4"
+ echo "@@@define[$3][$4
+][]" | bmp -mm "@@@" - "$1.tmp"
+ ) > "$1"
+ rm -f "$1.tmp"
+ fi
+ echo "$1" >> files.tmp
+}
+
+
+# copyright info for single directory
+# $1 dir
+# $2 description
+singledir () {
+ for i in $1/*.pas $1/*.inc; do
+ singlefile "$i" "$2" "{*!" "!*}"
+ done
+ for i in $1/*.c $1/*.h $1/*.java; do
+ singlefile "$i" "$2" "/*!" "!*/"
+ done
+}
+
+rm -f files.tmp
+
+singledir bmp/src "bmp -- babel macro processor"
+singledir examples/usb-fpga-1.2/ucecho "ucecho -- example for ZTEX USB FPGA Module 1.2"
+singledir include "ZTEX Firmware Kit for EZ-USB Microcontrollers"
+#singledir java "Java utilities for the ZTEX Firmware Kit / Driver API"
+singledir java "Firmware / Bitstream loader for the ZTEX Firmware Kit"
+singledir java/ztex "Java Driver API for the ZTEX Firmware Kit"
+
+files=`cat files.tmp`
+wc $files
+rm -f files.tmp
usb_fpga_1_2/trunk/makecopyright
Property changes :
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: usb_fpga_1_2/trunk/libusbJava-src/Make.bat
===================================================================
--- usb_fpga_1_2/trunk/libusbJava-src/Make.bat (nonexistent)
+++ usb_fpga_1_2/trunk/libusbJava-src/Make.bat (revision 2)
@@ -0,0 +1,3 @@
+mingw32-gcc -shared -Wall -D_JNI_IMPLEMENTATION_ -Wl,--kill-at -IC:\Programme\Java\jdk1.6.0_13\include -IC:\Programme\Java\jdk1.6.0_13\Include\win32 -I..\libusb-win32 LibusbJava.c ..\libusb-win32\libusb.a -o libusbJava.dll
+
+pause
Index: usb_fpga_1_2/trunk/libusbJava-src/LibusbJava.c
===================================================================
--- usb_fpga_1_2/trunk/libusbJava-src/LibusbJava.c (nonexistent)
+++ usb_fpga_1_2/trunk/libusbJava-src/LibusbJava.c (revision 2)
@@ -0,0 +1,850 @@
+/*
+ * Java libusb wrapper
+ * Copyright (c) 2005-2006 Andreas Schläpfer
+ *
+ * http://libusbjava.sourceforge.net
+ * This library is covered by the LGPL, read LGPL.txt for details.
+ */
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include "LibusbJava.h"
+
+// Windows specific stuff
+#ifdef WIN32
+#include
+#endif
+
+//#define DEBUGON
+
+// global bus (updated when usb_get_busses() is called)
+struct usb_bus *busses;
+
+// global flag for loading all class, method and field ID references
+int java_references_loaded = 0;
+
+// if > 0 an LibusbJava specific error string is set
+char *libusbJavaError = NULL;
+
+// macros to set and clear LibusbJava specific errors
+#define setLibusbJavaError(error) libusbJavaError = error
+#define clearLibusbJavaError() libusbJavaError = NULL
+
+// class references
+jclass usb_busClazz, usb_devClazz, usb_devDescClazz, usb_confDescClazz, \
+ usb_intClazz, usb_intDescClazz, usb_epDescClazz;
+
+// method ID references
+jmethodID usb_busMid, usb_devMid, usb_devDescMid, usb_confDescMid, \
+ usb_intMid, usb_intDescMid, usb_epDescMid;
+
+// field ID references
+// usb_bus
+jfieldID usb_busFID_next, usb_busFID_prev, usb_busFID_dirname, \
+ usb_busFID_devices, usb_busFID_location, usb_busFID_root_dev;
+// usb_device
+jfieldID usb_devFID_next, usb_devFID_prev, usb_devFID_filename, \
+ usb_devFID_bus, usb_devFID_descriptor, usb_devFID_config, \
+ usb_devFID_devnum, usb_devFID_num_children, usb_devFID_children, \
+ usb_devFID_devStructAddr;
+// usb_deviceDescriptor
+jfieldID usb_devDescFID_bLength, usb_devDescFID_bDescriptorType, \
+ usb_devDescFID_bcdUSB, usb_devDescFID_bDeviceClass, \
+ usb_devDescFID_bDeviceSubClass, usb_devDescFID_bDeviceProtocol, \
+ usb_devDescFID_bMaxPacketSize0, usb_devDescFID_idVendor, \
+ usb_devDescFID_idProduct, usb_devDescFID_bcdDevice, \
+ usb_devDescFID_iManufacturer, usb_devDescFID_iProduct, \
+ usb_devDescFID_iSerialNumber, usb_devDescFID_bNumConfigurations;
+// usb_configurationDescriptor
+jfieldID usb_confDescFID_bLength, usb_confDescFID_bDescriptorType, usb_confDescFID_wTotalLength, \
+ usb_confDescFID_bNumInterfaces, usb_confDescFID_bConfigurationValue, \
+ usb_confDescFID_iConfiguration, usb_confDescFID_bmAttributes, usb_confDescFID_MaxPower, \
+ usb_confDescFID_interface_, usb_confDescFID_extra, usb_confDescFID_extralen;
+// usb_interface
+jfieldID usb_intFID_altsetting, usb_intFID_num_altsetting;
+// usb_intDesc
+jfieldID usb_intDescFID_bLength, usb_intDescFID_bDescriptorType, \
+ usb_intDescFID_bInterfaceNumber, usb_intDescFID_bAlternateSetting, \
+ usb_intDescFID_bNumEndpoints, usb_intDescFID_bInterfaceClass, \
+ usb_intDescFID_bInterfaceSubClass, usb_intDescFID_bInterfaceProtocol, \
+ usb_intDescFID_iInterface, usb_intDescFID_endpoint, usb_intDescFID_extra, \
+ usb_intDescFID_extralen;
+// usb_endpointDescriptor
+jfieldID usb_epDescFID_bLength, usb_epDescFID_bDescriptorType, \
+ usb_epDescFID_bEndpointAddress, usb_epDescFID_bmAttributes, \
+ usb_epDescFID_wMaxPacketSize, usb_epDescFID_bInterval, \
+ usb_epDescFID_bRefresh, usb_epDescFID_bSynchAddress, usb_epDescFID_extra, \
+ usb_epDescFID_extralen;
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_set_debug
+ * Signature: (B)V
+ */
+JNIEXPORT void JNICALL Java_ch_ntb_usb_LibusbJava_usb_1set_1debug
+ (JNIEnv *env, jclass obj, jint level)
+ {
+ clearLibusbJavaError();
+ usb_set_debug(level);
+ }
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_init
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL Java_ch_ntb_usb_LibusbJava_usb_1init
+ (JNIEnv *env, jclass obj)
+ {
+ clearLibusbJavaError();
+ usb_init();
+ }
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_find_busses
+ * Signature: ()I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1find_1busses
+ (JNIEnv *env, jclass obj)
+ {
+ clearLibusbJavaError();
+ return usb_find_busses();
+ }
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_find_devices
+ * Signature: ()I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1find_1devices
+ (JNIEnv *env, jclass obj)
+ {
+ clearLibusbJavaError();
+ return usb_find_devices();
+ }
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_get_busses
+ * Signature: ()Lch/ntb/usb/Usb_Bus;
+ */
+JNIEXPORT jobject JNICALL Java_ch_ntb_usb_LibusbJava_usb_1get_1busses
+ (JNIEnv *env, jclass obj)
+ {
+
+ clearLibusbJavaError();
+
+ // only load class, method and field ID references once
+ if (!java_references_loaded) {
+ // find classes and field ids
+ // usb_bus
+ usb_busClazz = (*env)->FindClass(env, "ch/ntb/usb/Usb_Bus");
+ if (usb_busClazz == NULL) { return NULL; /* exception thrown */ }
+ usb_busMid = (*env)->GetMethodID(env, usb_busClazz, "","()V");
+ if (usb_busMid == NULL) { return NULL; }
+
+ usb_busFID_next = (*env)->GetFieldID(env, usb_busClazz, "next", "Lch/ntb/usb/Usb_Bus;");
+ usb_busFID_prev = (*env)->GetFieldID(env, usb_busClazz, "prev", "Lch/ntb/usb/Usb_Bus;");
+ usb_busFID_dirname = (*env)->GetFieldID(env, usb_busClazz, "dirname", "Ljava/lang/String;");
+ usb_busFID_devices = (*env)->GetFieldID(env, usb_busClazz, "devices", "Lch/ntb/usb/Usb_Device;");
+ usb_busFID_location = (*env)->GetFieldID(env, usb_busClazz, "location", "J");
+ usb_busFID_root_dev = (*env)->GetFieldID(env, usb_busClazz, "root_dev", "Lch/ntb/usb/Usb_Device;");
+
+ // usb_device
+ usb_devClazz = (*env)->FindClass(env, "ch/ntb/usb/Usb_Device");
+ if (usb_devClazz == NULL) { return NULL; /* exception thrown */ }
+ usb_devMid = (*env)->GetMethodID(env, usb_devClazz, "","()V");
+ if (usb_devMid == NULL) { return NULL; }
+
+ usb_devFID_next = (*env)->GetFieldID(env, usb_devClazz, "next", "Lch/ntb/usb/Usb_Device;");
+ usb_devFID_prev = (*env)->GetFieldID(env, usb_devClazz, "prev", "Lch/ntb/usb/Usb_Device;");
+ usb_devFID_filename = (*env)->GetFieldID(env, usb_devClazz, "filename", "Ljava/lang/String;");
+ usb_devFID_bus = (*env)->GetFieldID(env, usb_devClazz, "bus", "Lch/ntb/usb/Usb_Bus;");
+ usb_devFID_descriptor = (*env)->GetFieldID(env, usb_devClazz, "descriptor", "Lch/ntb/usb/Usb_Device_Descriptor;");
+ usb_devFID_config = (*env)->GetFieldID(env, usb_devClazz, "config", "[Lch/ntb/usb/Usb_Config_Descriptor;");
+ usb_devFID_devnum = (*env)->GetFieldID(env, usb_devClazz, "devnum", "B");
+ usb_devFID_num_children = (*env)->GetFieldID(env, usb_devClazz, "num_children", "B");
+ usb_devFID_children = (*env)->GetFieldID(env, usb_devClazz, "children", "Lch/ntb/usb/Usb_Device;");
+ usb_devFID_devStructAddr = (*env)->GetFieldID(env, usb_devClazz, "devStructAddr", "J");
+
+
+ // usb_device_descriptor
+ usb_devDescClazz = (*env)->FindClass(env, "ch/ntb/usb/Usb_Device_Descriptor");
+ if (usb_devDescClazz == NULL) { return NULL; /* exception thrown */ }
+ usb_devDescMid = (*env)->GetMethodID(env, usb_devDescClazz, "","()V");
+ if (usb_devDescMid == NULL) { return NULL; }
+
+ usb_devDescFID_bLength = (*env)->GetFieldID(env, usb_devDescClazz, "bLength", "B");
+ usb_devDescFID_bDescriptorType = (*env)->GetFieldID(env, usb_devDescClazz, "bDescriptorType", "B");
+ usb_devDescFID_bcdUSB = (*env)->GetFieldID(env, usb_devDescClazz, "bcdUSB", "S");
+ usb_devDescFID_bDeviceClass = (*env)->GetFieldID(env, usb_devDescClazz, "bDeviceClass", "B");
+ usb_devDescFID_bDeviceSubClass = (*env)->GetFieldID(env, usb_devDescClazz, "bDeviceSubClass", "B");
+ usb_devDescFID_bDeviceProtocol = (*env)->GetFieldID(env, usb_devDescClazz, "bDeviceProtocol", "B");
+ usb_devDescFID_bMaxPacketSize0 = (*env)->GetFieldID(env, usb_devDescClazz, "bMaxPacketSize0", "B");
+ usb_devDescFID_idVendor = (*env)->GetFieldID(env, usb_devDescClazz, "idVendor", "S");
+ usb_devDescFID_idProduct = (*env)->GetFieldID(env, usb_devDescClazz, "idProduct", "S");
+ usb_devDescFID_bcdDevice = (*env)->GetFieldID(env, usb_devDescClazz, "bcdDevice", "S");
+ usb_devDescFID_iManufacturer = (*env)->GetFieldID(env, usb_devDescClazz, "iManufacturer", "B");
+ usb_devDescFID_iProduct = (*env)->GetFieldID(env, usb_devDescClazz, "iProduct", "B");
+ usb_devDescFID_iSerialNumber = (*env)->GetFieldID(env, usb_devDescClazz, "iSerialNumber", "B");
+ usb_devDescFID_bNumConfigurations = (*env)->GetFieldID(env, usb_devDescClazz, "bNumConfigurations", "B");
+
+ // usb_configuration_descriptor
+ usb_confDescClazz = (*env)->FindClass(env, "ch/ntb/usb/Usb_Config_Descriptor");
+ if (usb_confDescClazz == NULL) { return NULL; /* exception thrown */ }
+ usb_confDescMid = (*env)->GetMethodID(env, usb_confDescClazz, "","()V");
+ if (usb_confDescMid == NULL) { return NULL; }
+
+ usb_confDescFID_bLength = (*env)->GetFieldID(env, usb_confDescClazz, "bLength", "B");
+ usb_confDescFID_bDescriptorType = (*env)->GetFieldID(env, usb_confDescClazz, "bDescriptorType", "B");
+ usb_confDescFID_wTotalLength = (*env)->GetFieldID(env, usb_confDescClazz, "wTotalLength", "S");
+ usb_confDescFID_bNumInterfaces = (*env)->GetFieldID(env, usb_confDescClazz, "bNumInterfaces", "B");
+ usb_confDescFID_bConfigurationValue = (*env)->GetFieldID(env, usb_confDescClazz, "bConfigurationValue", "B");
+ usb_confDescFID_iConfiguration = (*env)->GetFieldID(env, usb_confDescClazz, "iConfiguration", "B");
+ usb_confDescFID_bmAttributes = (*env)->GetFieldID(env, usb_confDescClazz, "bmAttributes", "B");
+ usb_confDescFID_MaxPower = (*env)->GetFieldID(env, usb_confDescClazz, "MaxPower", "B");
+ usb_confDescFID_interface_ = (*env)->GetFieldID(env, usb_confDescClazz, "interface_", "[Lch/ntb/usb/Usb_Interface;");
+ usb_confDescFID_extra = (*env)->GetFieldID(env, usb_confDescClazz, "extra", "[B");
+ usb_confDescFID_extralen = (*env)->GetFieldID(env, usb_confDescClazz, "extralen", "I");
+
+ // usb_interface
+ usb_intClazz = (*env)->FindClass(env, "ch/ntb/usb/Usb_Interface");
+ if (usb_intClazz == NULL) { return NULL; /* exception thrown */ }
+ usb_intMid = (*env)->GetMethodID(env, usb_intClazz, "","()V");
+ if (usb_intMid == NULL) { return NULL; }
+
+ usb_intFID_altsetting = (*env)->GetFieldID(env, usb_intClazz, "altsetting", "[Lch/ntb/usb/Usb_Interface_Descriptor;");
+ usb_intFID_num_altsetting = (*env)->GetFieldID(env, usb_intClazz, "num_altsetting", "I");
+
+ // usb_interface_descriptor
+ usb_intDescClazz = (*env)->FindClass(env, "ch/ntb/usb/Usb_Interface_Descriptor");
+ if (usb_intDescClazz == NULL) { return NULL; /* exception thrown */ }
+ usb_intDescMid = (*env)->GetMethodID(env, usb_intDescClazz, "","()V");
+ if (usb_intDescMid == NULL) { return NULL; }
+
+ usb_intDescFID_bLength = (*env)->GetFieldID(env, usb_intDescClazz, "bLength", "B");
+ usb_intDescFID_bDescriptorType = (*env)->GetFieldID(env, usb_intDescClazz, "bDescriptorType", "B");
+ usb_intDescFID_bInterfaceNumber = (*env)->GetFieldID(env, usb_intDescClazz, "bInterfaceNumber", "B");
+ usb_intDescFID_bAlternateSetting = (*env)->GetFieldID(env, usb_intDescClazz, "bAlternateSetting", "B");
+ usb_intDescFID_bNumEndpoints = (*env)->GetFieldID(env, usb_intDescClazz, "bNumEndpoints", "B");
+ usb_intDescFID_bInterfaceClass = (*env)->GetFieldID(env, usb_intDescClazz, "bInterfaceClass", "B");
+ usb_intDescFID_bInterfaceSubClass = (*env)->GetFieldID(env, usb_intDescClazz, "bInterfaceSubClass", "B");
+ usb_intDescFID_bInterfaceProtocol = (*env)->GetFieldID(env, usb_intDescClazz, "bInterfaceProtocol", "B");
+ usb_intDescFID_iInterface = (*env)->GetFieldID(env, usb_intDescClazz, "iInterface", "B");
+ usb_intDescFID_endpoint = (*env)->GetFieldID(env, usb_intDescClazz, "endpoint", "[Lch/ntb/usb/Usb_Endpoint_Descriptor;");
+ usb_intDescFID_extra = (*env)->GetFieldID(env, usb_intDescClazz, "extra", "[B");
+ usb_intDescFID_extralen = (*env)->GetFieldID(env, usb_intDescClazz, "extralen", "I");
+
+ // usb_endpoint_descriptor
+ usb_epDescClazz = (*env)->FindClass(env, "ch/ntb/usb/Usb_Endpoint_Descriptor");
+ if (usb_epDescClazz == NULL) { return NULL; /* exception thrown */ }
+ usb_epDescMid = (*env)->GetMethodID(env, usb_epDescClazz, "","()V");
+ if (usb_epDescMid == NULL) { return NULL; }
+
+ usb_epDescFID_bLength = (*env)->GetFieldID(env, usb_epDescClazz, "bLength", "B");
+ usb_epDescFID_bDescriptorType = (*env)->GetFieldID(env, usb_epDescClazz, "bDescriptorType", "B");
+ usb_epDescFID_bEndpointAddress = (*env)->GetFieldID(env, usb_epDescClazz, "bEndpointAddress", "B");
+ usb_epDescFID_bmAttributes = (*env)->GetFieldID(env, usb_epDescClazz, "bmAttributes", "B");
+ usb_epDescFID_wMaxPacketSize = (*env)->GetFieldID(env, usb_epDescClazz, "wMaxPacketSize", "S");
+ usb_epDescFID_bInterval = (*env)->GetFieldID(env, usb_epDescClazz, "bInterval", "B");
+ usb_epDescFID_bRefresh = (*env)->GetFieldID(env, usb_epDescClazz, "bRefresh", "B");
+ usb_epDescFID_bSynchAddress = (*env)->GetFieldID(env, usb_epDescClazz, "bSynchAddress", "B");
+ usb_epDescFID_extra = (*env)->GetFieldID(env, usb_epDescClazz, "extra", "[B");
+ usb_epDescFID_extralen = (*env)->GetFieldID(env, usb_epDescClazz, "extralen", "I");
+#ifdef DEBUGON
+ printf("usb_get_busses: Field initialization done (1)\n");
+#endif
+ }
+
+ //************************************************************************//
+
+ struct usb_device *dev;
+ struct usb_bus *bus;
+
+ busses = usb_get_busses();
+ bus = busses;
+ if (!bus){
+ return NULL;
+ }
+
+ // objects
+ jobject main_usb_busObj, usb_busObj, usb_busObj_next, usb_busObj_prev, \
+ main_usb_devObj, usb_devObj, usb_devObj_next, usb_devObj_prev, \
+ usb_devDescObj, usb_confDescObj, usb_intObj, usb_intDescObj, \
+ usb_epDescObj;
+
+ jobjectArray usb_confDescObjArray, usb_intObjArray, usb_intDescObjArray, usb_epDescObjArray;
+
+ usb_busObj = NULL;
+ usb_busObj_prev = NULL;
+ main_usb_busObj = NULL;
+
+#ifdef DEBUGON
+ printf("usb_get_busses: usb_get_busses done (2)\n");
+#endif
+
+ while (bus){
+#ifdef DEBUGON
+ printf("\tusb_get_busses: bus %x (3)\n", bus);
+#endif
+
+ // create a new object for every bus
+ if (!usb_busObj) {
+ usb_busObj = (*env)->NewObject(env, usb_busClazz, usb_busMid);
+ if (!usb_busObj) {
+ setLibusbJavaError("shared library error: Error NewObject (usb_busObj)");
+ return NULL;
+ }
+ main_usb_busObj = usb_busObj;
+ }
+
+ // fill the fields of the object
+ usb_busObj_next = NULL;
+ if (bus->next){
+ usb_busObj_next = (*env)->NewObject(env, usb_busClazz, usb_busMid);
+ if (!usb_busObj_next) {
+ setLibusbJavaError("shared library error: Error NewObject (usb_busObj_next)");
+ return NULL;
+ }
+ }
+ (*env)->SetObjectField(env, usb_busObj, usb_busFID_next, usb_busObj_next);
+ (*env)->SetObjectField(env, usb_busObj, usb_busFID_prev, usb_busObj_prev);
+ (*env)->SetObjectField(env, usb_busObj, usb_busFID_dirname, (*env)->NewStringUTF(env, bus->dirname));
+ (*env)->SetLongField(env, usb_busObj, usb_busFID_location, bus->location);
+
+ dev = bus->devices;
+ usb_devObj = NULL;
+ usb_devObj_prev = NULL;
+ main_usb_devObj = NULL;
+
+ while (dev){
+#ifdef DEBUGON
+ printf("\tusb_get_busses: dev %x (4)\n", dev);
+#endif
+ // create a new object for every device
+ if (!usb_devObj){
+ usb_devObj = (*env)->NewObject(env, usb_devClazz, usb_devMid);
+ if (!usb_devObj) {
+ setLibusbJavaError("shared library error: Error NewObject (usb_devObj)");
+ return NULL;
+ }
+ main_usb_devObj = usb_devObj;
+ }
+ // fill the fields of the object
+ usb_devObj_next = NULL;
+ if (dev->next){
+ usb_devObj_next = (*env)->NewObject(env, usb_devClazz, usb_devMid);
+ if (!usb_devObj_next) {
+ setLibusbJavaError("shared library error: Error NewObject (usb_devObj_next)");
+ return NULL;
+ }
+ }
+ (*env)->SetObjectField(env, usb_devObj, usb_devFID_next, usb_devObj_next);
+ (*env)->SetObjectField(env, usb_devObj, usb_devFID_prev, usb_devObj_prev);
+ (*env)->SetObjectField(env, usb_devObj, usb_devFID_bus, usb_busObj);
+ (*env)->SetObjectField(env, usb_devObj, usb_devFID_filename, (*env)->NewStringUTF(env, dev->filename));
+ (*env)->SetByteField(env, usb_devObj, usb_devFID_devnum, dev->devnum);
+ (*env)->SetByteField(env, usb_devObj, usb_devFID_num_children, dev->num_children);
+ (*env)->SetLongField(env, usb_devObj, usb_devFID_devStructAddr, (jlong) (int) dev);
+
+ // device descriptor
+ usb_devDescObj = (*env)->NewObject(env, usb_devDescClazz, usb_devDescMid);
+ if (!usb_devDescObj) {
+ setLibusbJavaError("shared library error: Error NewObject (usb_devDescObj)");
+ return NULL;
+ }
+ (*env)->SetByteField(env, usb_devDescObj, usb_devDescFID_bLength, dev->descriptor.bLength);
+ (*env)->SetByteField(env, usb_devDescObj, usb_devDescFID_bDescriptorType, dev->descriptor.bDescriptorType);
+ (*env)->SetShortField(env, usb_devDescObj, usb_devDescFID_bcdUSB, dev->descriptor.bcdUSB);
+ (*env)->SetByteField(env, usb_devDescObj, usb_devDescFID_bDeviceClass, dev->descriptor.bDeviceClass);
+ (*env)->SetByteField(env, usb_devDescObj, usb_devDescFID_bDeviceSubClass, dev->descriptor.bDeviceSubClass);
+ (*env)->SetByteField(env, usb_devDescObj, usb_devDescFID_bDeviceProtocol, dev->descriptor.bDeviceProtocol);
+ (*env)->SetByteField(env, usb_devDescObj, usb_devDescFID_bMaxPacketSize0, dev->descriptor.bMaxPacketSize0);
+ (*env)->SetShortField(env, usb_devDescObj, usb_devDescFID_idVendor, dev->descriptor.idVendor);
+ (*env)->SetShortField(env, usb_devDescObj, usb_devDescFID_idProduct, dev->descriptor.idProduct);
+ (*env)->SetShortField(env, usb_devDescObj, usb_devDescFID_bcdDevice, dev->descriptor.bcdDevice);
+ (*env)->SetByteField(env, usb_devDescObj, usb_devDescFID_iManufacturer, dev->descriptor.iManufacturer);
+ (*env)->SetByteField(env, usb_devDescObj, usb_devDescFID_iProduct, dev->descriptor.iProduct);
+ (*env)->SetByteField(env, usb_devDescObj, usb_devDescFID_iSerialNumber, dev->descriptor.iSerialNumber);
+ (*env)->SetByteField(env, usb_devDescObj, usb_devDescFID_bNumConfigurations, dev->descriptor.bNumConfigurations);
+
+ (*env)->SetObjectField(env, usb_devObj, usb_devFID_descriptor, usb_devDescObj);
+ // configuration descriptor
+ // Loop through all of the configurations
+ usb_confDescObjArray = (jobjectArray) (*env)->NewObjectArray(env, dev->descriptor.bNumConfigurations, usb_confDescClazz, NULL);
+ if (!usb_confDescObjArray) {
+ setLibusbJavaError("shared library error: Error NewObject 6");
+ return NULL;
+ }
+ for (int c = 0; c < dev->descriptor.bNumConfigurations; c++){
+#ifdef DEBUGON
+ printf("\t\tusb_get_busses: configuration %x (5)\n", c);
+#endif
+ if (dev->config == NULL) {
+ // this shouldn't happen, but it did occasionally (maybe this is (or probably was) a libusb bug)
+ setLibusbJavaError("shared library error: dev->config == NULL");
+ return main_usb_busObj;
+ }
+
+ usb_confDescObj = (*env)->NewObject(env, usb_confDescClazz, usb_confDescMid);
+ if (!usb_confDescObj) {
+ setLibusbJavaError("shared library error: Error NewObject (usb_confDescObj)");
+ return NULL;
+ }
+ (*env)->SetObjectArrayElement(env, usb_confDescObjArray, c, usb_confDescObj);
+ (*env)->SetByteField(env, usb_confDescObj, usb_confDescFID_bLength, dev->config[c].bLength);
+ (*env)->SetByteField(env, usb_confDescObj, usb_confDescFID_bDescriptorType, dev->config[c].bDescriptorType);
+ (*env)->SetShortField(env, usb_confDescObj, usb_confDescFID_wTotalLength, dev->config[c].wTotalLength);
+ (*env)->SetByteField(env, usb_confDescObj, usb_confDescFID_bNumInterfaces, dev->config[c].bNumInterfaces);
+ (*env)->SetByteField(env, usb_confDescObj, usb_confDescFID_bConfigurationValue, dev->config[c].bConfigurationValue);
+ (*env)->SetByteField(env, usb_confDescObj, usb_confDescFID_iConfiguration, dev->config[c].iConfiguration);
+ (*env)->SetByteField(env, usb_confDescObj, usb_confDescFID_bmAttributes, dev->config[c].bmAttributes);
+ (*env)->SetByteField(env, usb_confDescObj, usb_confDescFID_MaxPower, dev->config[c].MaxPower);
+ (*env)->SetIntField(env, usb_confDescObj, usb_confDescFID_extralen, dev->config[c].extralen);
+ if (dev->config[c].extra){
+ jbyteArray jbExtraDesc = (*env)->NewByteArray(env, dev->config[c].extralen);
+ (*env)->SetByteArrayRegion(env, jbExtraDesc, 0, dev->config[c].extralen, (jbyte *) dev->config[c].extra);
+ (*env)->SetObjectField(env, usb_confDescObj, usb_confDescFID_extra, jbExtraDesc);
+ } else {
+ (*env)->SetObjectField(env, usb_confDescObj, usb_confDescFID_extra, NULL);
+ }
+ // interface
+ usb_intObjArray = (jobjectArray) (*env)->NewObjectArray(env, dev->config[c].bNumInterfaces, usb_intClazz, NULL);
+ if (!usb_intObjArray) {
+ setLibusbJavaError("shared library error: Error NewObject (usb_intObjArray)");
+ return NULL;
+ }
+ for (int i = 0; i < dev->config[c].bNumInterfaces; i++){
+#ifdef DEBUGON
+ printf("\t\t\tusb_get_busses: interface %x (6)\n", i);
+#endif
+ if (dev->config[c].interface == NULL) {
+ // this shouldn't happen
+ printf("dev->config[c].interface == NULL");
+ return main_usb_busObj;
+ }
+
+ usb_intObj = (*env)->NewObject(env, usb_intClazz, usb_intMid);
+ if (!usb_intObj) {
+ setLibusbJavaError("shared library error: Error NewObject (usb_intObj)");
+ return NULL;
+ }
+ (*env)->SetObjectArrayElement(env, usb_intObjArray, i, usb_intObj);
+ (*env)->SetIntField(env, usb_intObj, usb_intFID_num_altsetting, dev->config[c].interface[i].num_altsetting);
+ // interface descriptor
+ usb_intDescObjArray = (jobjectArray) (*env)->NewObjectArray(env, dev->config[c].interface[i].num_altsetting, usb_intDescClazz, NULL);
+ if (!usb_intDescObjArray) {
+ setLibusbJavaError("shared library error: Error NewObject (usb_intDescObjArray)");
+ return NULL;
+ }
+ for (int a = 0; a < dev->config[c].interface[i].num_altsetting; a++){
+#ifdef DEBUGON
+ printf("\t\t\t\tusb_get_busses: interface descriptor %x (7)\n", a);
+#endif
+ if (dev->config[c].interface[i].altsetting == NULL) {
+ // this shouldn't happen
+ printf("LibusbJava: usb_get_busses: dev->config[c].interface[i].altsetting == NULL\n");
+ return main_usb_busObj;
+ }
+
+ usb_intDescObj = (*env)->NewObject(env, usb_intDescClazz, usb_intDescMid);
+ if (!usb_intDescObj) {
+ setLibusbJavaError("shared library error: Error NewObject (usb_intDescObj)");
+ return NULL;
+ }
+ (*env)->SetObjectArrayElement(env, usb_intDescObjArray, a, usb_intDescObj);
+ (*env)->SetByteField(env, usb_intDescObj, usb_intDescFID_bLength, dev->config[c].interface[i].altsetting[a].bLength);
+ (*env)->SetByteField(env, usb_intDescObj, usb_intDescFID_bDescriptorType, dev->config[c].interface[i].altsetting[a].bDescriptorType);
+ (*env)->SetByteField(env, usb_intDescObj, usb_intDescFID_bInterfaceNumber, dev->config[c].interface[i].altsetting[a].bInterfaceNumber);
+ (*env)->SetByteField(env, usb_intDescObj, usb_intDescFID_bAlternateSetting, dev->config[c].interface[i].altsetting[a].bAlternateSetting);
+ (*env)->SetByteField(env, usb_intDescObj, usb_intDescFID_bNumEndpoints, dev->config[c].interface[i].altsetting[a].bNumEndpoints);
+ (*env)->SetByteField(env, usb_intDescObj, usb_intDescFID_bInterfaceClass, dev->config[c].interface[i].altsetting[a].bInterfaceClass);
+ (*env)->SetByteField(env, usb_intDescObj, usb_intDescFID_bInterfaceSubClass, dev->config[c].interface[i].altsetting[a].bInterfaceSubClass);
+ (*env)->SetByteField(env, usb_intDescObj, usb_intDescFID_bInterfaceProtocol, dev->config[c].interface[i].altsetting[a].bInterfaceProtocol);
+ (*env)->SetByteField(env, usb_intDescObj, usb_intDescFID_iInterface, dev->config[c].interface[i].altsetting[a].iInterface);
+ (*env)->SetIntField(env, usb_intDescObj, usb_intDescFID_extralen, dev->config[c].interface[i].altsetting[a].extralen);
+ if (dev->config[c].interface[i].altsetting[a].extra){
+ jbyteArray jbExtraDesc = (*env)->NewByteArray(env, dev->config[c].interface[i].altsetting[a].extralen);
+ (*env)->SetByteArrayRegion(env, jbExtraDesc, 0, dev->config[c].interface[i].altsetting[a].extralen, (jbyte *) dev->config[c].interface[i].altsetting[a].extra);
+ (*env)->SetObjectField(env, usb_intDescObj, usb_intDescFID_extra, jbExtraDesc);
+ } else {
+ (*env)->SetObjectField(env, usb_intDescObj, usb_intDescFID_extra, NULL);
+ }
+ // endpoint descriptor
+ usb_epDescObjArray = (jobjectArray) (*env)->NewObjectArray(env, dev->config[c].interface[i].altsetting[a].bNumEndpoints, usb_epDescClazz, NULL);
+ if (!usb_epDescObjArray) {
+ setLibusbJavaError("shared library error: Error NewObject (usb_epDescObjArray)");
+ return NULL;
+ }
+ for (int e = 0; e < dev->config[c].interface[i].altsetting[a].bNumEndpoints; e++){
+#ifdef DEBUGON
+ printf("\t\t\t\t\tusb_get_busses: endpoint descriptor %x (8)\n", e);
+#endif
+ if (dev->config[c].interface[i].altsetting[a].endpoint == NULL) {
+ printf("LibusbJava: usb_get_busses: dev->config[c].interface[i].altsetting[a].endpoint == NULL\n");
+ return main_usb_busObj;
+ }
+
+ usb_epDescObj = (*env)->NewObject(env, usb_epDescClazz, usb_epDescMid);
+ if (!usb_epDescObj) {
+ setLibusbJavaError("shared library error: Error NewObject (usb_epDescObj)");
+ return NULL;
+ }
+ (*env)->SetObjectArrayElement(env, usb_epDescObjArray, e, usb_epDescObj);
+ (*env)->SetByteField(env, usb_epDescObj, usb_epDescFID_bLength, dev->config[c].interface[i].altsetting[a].endpoint[e].bLength);
+ (*env)->SetByteField(env, usb_epDescObj, usb_epDescFID_bDescriptorType, dev->config[c].interface[i].altsetting[a].endpoint[e].bDescriptorType);
+ (*env)->SetByteField(env, usb_epDescObj, usb_epDescFID_bEndpointAddress, dev->config[c].interface[i].altsetting[a].endpoint[e].bEndpointAddress);
+ (*env)->SetByteField(env, usb_epDescObj, usb_epDescFID_bmAttributes, dev->config[c].interface[i].altsetting[a].endpoint[e].bmAttributes);
+ (*env)->SetShortField(env, usb_epDescObj, usb_epDescFID_wMaxPacketSize, dev->config[c].interface[i].altsetting[a].endpoint[e].wMaxPacketSize);
+ (*env)->SetByteField(env, usb_epDescObj, usb_epDescFID_bInterval, dev->config[c].interface[i].altsetting[a].endpoint[e].bInterval);
+ (*env)->SetByteField(env, usb_epDescObj, usb_epDescFID_bRefresh, dev->config[c].interface[i].altsetting[a].endpoint[e].bRefresh);
+ (*env)->SetByteField(env, usb_epDescObj, usb_epDescFID_bSynchAddress, dev->config[c].interface[i].altsetting[a].endpoint[e].bSynchAddress);
+ (*env)->SetIntField(env, usb_epDescObj, usb_epDescFID_extralen, dev->config[c].interface[i].altsetting[a].endpoint[e].extralen);
+ if (dev->config[c].interface[i].altsetting[a].endpoint[e].extra){
+ jbyteArray jbExtraDesc = (*env)->NewByteArray(env, dev->config[c].interface[i].altsetting[a].endpoint[e].extralen);
+ (*env)->SetByteArrayRegion(env, jbExtraDesc, 0, dev->config[c].interface[i].altsetting[a].endpoint[e].extralen, (jbyte *) dev->config[c].interface[i].altsetting[a].endpoint[e].extra);
+ (*env)->SetObjectField(env, usb_epDescObj, usb_epDescFID_extra, jbExtraDesc);
+ } else {
+ (*env)->SetObjectField(env, usb_epDescObj, usb_epDescFID_extra, NULL);
+ }
+ }
+ (*env)->SetObjectField(env, usb_intDescObj, usb_intDescFID_endpoint, usb_epDescObjArray);
+ }
+ (*env)->SetObjectField(env, usb_intObj, usb_intFID_altsetting, usb_intDescObjArray);
+ }
+ (*env)->SetObjectField(env, usb_confDescObj, usb_confDescFID_interface_, usb_intObjArray);
+ }
+
+
+ (*env)->SetObjectField(env, usb_devObj, usb_devFID_config, usb_confDescObjArray);
+
+ usb_devObj_prev = usb_devObj;
+ usb_devObj = usb_devObj_next;
+ dev = dev->next;
+ }
+ (*env)->SetObjectField(env, usb_busObj, usb_busFID_devices, main_usb_devObj);
+ (*env)->SetObjectField(env, usb_busObj, usb_busFID_root_dev, main_usb_devObj);
+
+ usb_busObj_prev = usb_busObj;
+ usb_busObj = usb_busObj_next;
+ bus = bus->next;
+ }
+
+#ifdef DEBUGON
+ printf("usb_get_busses: done\n");
+#endif
+ return main_usb_busObj;
+ }
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_open
+ * Signature: (Lch/ntb/usb/Usb_Device;)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1open
+ (JNIEnv *env, jclass obj, jobject dev)
+ {
+ clearLibusbJavaError();
+ if (busses == NULL) {
+ setLibusbJavaError("shared library error: busses is null");
+ return 0;
+ }
+
+ jlong usb_device_cmp_addr = (*env)->GetLongField(env, dev, usb_devFID_devStructAddr);
+ struct usb_bus *tmpBus;
+
+ for (tmpBus = busses; tmpBus; tmpBus = tmpBus->next) {
+ struct usb_device *device;
+ for (device = tmpBus->devices; device; device = device->next) {
+ if ((jlong) (int) device == usb_device_cmp_addr){
+ return (jint) usb_open(device);
+ }
+ }
+ }
+ setLibusbJavaError("shared library error: no device with dev.devnum found on busses");
+ return 0;
+ }
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_close
+ * Signature: (I)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1close
+ (JNIEnv *env, jclass obj, jint dev_handle)
+ {
+ clearLibusbJavaError();
+ return (jint) usb_close((usb_dev_handle *) dev_handle);
+ }
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_set_configuration
+ * Signature: (II)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1set_1configuration
+ (JNIEnv *env, jclass obj, jint dev_handle, jint configuration)
+ {
+ clearLibusbJavaError();
+ return usb_set_configuration((usb_dev_handle *) dev_handle, configuration);
+ }
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_set_altinterface
+ * Signature: (II)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1set_1altinterface
+ (JNIEnv *env, jclass obj, jint dev_handle, jint alternate)
+ {
+ clearLibusbJavaError();
+ return usb_set_altinterface((usb_dev_handle *) dev_handle, alternate);
+ }
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_clear_halt
+ * Signature: (II)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1clear_1halt
+ (JNIEnv *env, jclass obj, jint dev_handle, jint ep)
+ {
+ clearLibusbJavaError();
+ return usb_clear_halt((usb_dev_handle *) dev_handle, (unsigned) ep);
+ }
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_reset
+ * Signature: (I)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1reset
+ (JNIEnv *env, jclass obj, jint dev_handle)
+ {
+ clearLibusbJavaError();
+ return usb_reset((usb_dev_handle *) dev_handle);
+ }
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_claim_interface
+ * Signature: (II)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1claim_1interface
+ (JNIEnv *env, jclass obj, jint dev_handle, jint interface)
+ {
+ clearLibusbJavaError();
+ return usb_claim_interface((usb_dev_handle *) dev_handle, interface);
+ }
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_release_interface
+ * Signature: (II)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1release_1interface
+ (JNIEnv *env, jclass obj, jint dev_handle, jint interface)
+ {
+ clearLibusbJavaError();
+ return usb_release_interface((usb_dev_handle *) dev_handle, interface);
+ }
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_control_msg
+ * Signature: (IIIII[BII)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1control_1msg
+ (JNIEnv *env, jclass obj, jint dev_handle, jint requesttype, jint request, jint value, jint index, jbyteArray jbytes, jint size, jint timeout)
+ {
+ clearLibusbJavaError();
+ jbyte *bytes = (*env)->GetByteArrayElements(env, jbytes, NULL);
+ int num_bytes = usb_control_msg((usb_dev_handle *) dev_handle, requesttype, request, value, index, (char *) bytes, size, timeout);
+ (*env)->SetByteArrayRegion(env, jbytes, 0, size, bytes);
+ (*env)->ReleaseByteArrayElements(env, jbytes, bytes, 0);
+ return num_bytes;
+ }
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_get_string
+ * Signature: (III)Ljava/lang/String;
+ */
+JNIEXPORT jstring JNICALL Java_ch_ntb_usb_LibusbJava_usb_1get_1string
+ (JNIEnv *env, jclass obj, jint dev_handle, jint index, jint langid)
+ {
+ clearLibusbJavaError();
+ char string[256];
+ int retVal = usb_get_string((usb_dev_handle *) dev_handle, index, langid, string, 256);
+ if (retVal > 0)
+ return (*env)->NewStringUTF(env, string);
+ return 0;
+ }
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_get_string_simple
+ * Signature: (II)Ljava/lang/String;
+ */
+JNIEXPORT jstring JNICALL Java_ch_ntb_usb_LibusbJava_usb_1get_1string_1simple
+ (JNIEnv *env, jclass obj, jint dev_handle, jint index)
+ {
+ clearLibusbJavaError();
+ char string[256];
+ int retVal = usb_get_string_simple((usb_dev_handle *) dev_handle, index, string, 256);
+ if (retVal > 0)
+ return (*env)->NewStringUTF(env, string);
+ return 0;
+ }
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_get_descriptor
+ * Signature: (IBBI)Ljava/lang/String;
+ */
+JNIEXPORT jstring JNICALL Java_ch_ntb_usb_LibusbJava_usb_1get_1descriptor
+ (JNIEnv *env, jclass obj, jint dev_handle, jbyte type, jbyte index, jint size)
+ {
+ clearLibusbJavaError();
+ char *string = (char *) malloc(size * sizeof(char));
+ int retVal = usb_get_descriptor((usb_dev_handle *) dev_handle, (unsigned) type,
+ (unsigned) index, string, size);
+ if (retVal > 0)
+ return (*env)->NewStringUTF(env, string);
+ return 0;
+ }
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_get_descriptor_by_endpoint
+ * Signature: (IIBBI)Ljava/lang/String;
+ */
+JNIEXPORT jstring JNICALL Java_ch_ntb_usb_LibusbJava_usb_1get_1descriptor_1by_1endpoint
+ (JNIEnv *env, jclass obj, jint dev_handle, jint ep, jbyte type, jbyte index, jint size)
+ {
+ clearLibusbJavaError();
+ char *string = (char *) malloc(size * sizeof(char));
+ int retVal = usb_get_descriptor_by_endpoint((usb_dev_handle *) dev_handle, ep, (unsigned) type,
+ (unsigned) index, string, size);
+ if (retVal > 0)
+ return (*env)->NewStringUTF(env, string);
+ return 0;
+ }
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_bulk_write
+ * Signature: (II[BII)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1bulk_1write
+ (JNIEnv *env, jclass obj, jint dev_handle, jint ep, jbyteArray jbytes, jint size, jint timeout)
+ {
+ clearLibusbJavaError();
+ jbyte *bytes = (*env)->GetByteArrayElements(env, jbytes, NULL);
+ int num_bytes = usb_bulk_write((usb_dev_handle *) dev_handle, ep, (char *) bytes, size, timeout);
+ (*env)->ReleaseByteArrayElements(env, jbytes, bytes, 0);
+ return num_bytes;
+ }
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_bulk_read
+ * Signature: (II[BII)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1bulk_1read
+ (JNIEnv *env, jclass obj, jint dev_handle, jint ep, jbyteArray jbytes, jint size, jint timeout)
+ {
+ clearLibusbJavaError();
+ char *bytes = (char *) malloc(size * sizeof(char));
+ int num_bytes = usb_bulk_read((usb_dev_handle *) dev_handle, ep, bytes, size, timeout);
+ if (!bytes) { return num_bytes; }
+ (*env)->SetByteArrayRegion(env, jbytes, 0, size, (jbyte *) bytes);
+ free(bytes);
+ return num_bytes;
+ }
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_interrupt_write
+ * Signature: (II[BII)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1interrupt_1write
+ (JNIEnv *env, jclass obj, jint dev_handle, jint ep, jbyteArray jbytes, jint size, jint timeout)
+ {
+ clearLibusbJavaError();
+ jbyte *bytes = (*env)->GetByteArrayElements(env, jbytes, NULL);
+ int num_bytes = usb_interrupt_write( (usb_dev_handle *) dev_handle, ep, (char *) bytes, size, timeout);
+ (*env)->ReleaseByteArrayElements(env, jbytes, bytes, 0);
+ return num_bytes;
+ }
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_interrupt_read
+ * Signature: (II[BII)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1interrupt_1read
+ (JNIEnv *env, jclass obj, jint dev_handle, jint ep, jbyteArray jbytes, jint size, jint timeout)
+ {
+ clearLibusbJavaError();
+ char *bytes = (char *) malloc(size * sizeof(char));
+ int num_bytes = usb_interrupt_read((usb_dev_handle *) dev_handle, ep, bytes, size, timeout);
+ if (!bytes) { return num_bytes; }
+ (*env)->SetByteArrayRegion(env, jbytes, 0, size, (jbyte *) bytes);
+ free(bytes);
+ return num_bytes;
+ }
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_strerror
+ * Signature: ()Ljava/lang/String;
+ */
+JNIEXPORT jstring JNICALL Java_ch_ntb_usb_LibusbJava_usb_1strerror
+ (JNIEnv *env, jclass obj){
+
+ char *str;
+ // check for LibusbJava specific errors first
+ if (libusbJavaError != NULL) {
+ str = libusbJavaError;
+ clearLibusbJavaError();
+ } else {
+ str = usb_strerror();
+ }
+
+ return (*env)->NewStringUTF(env, str);
+}
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_error_no
+ * Signature: (I)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1error_1no
+ (JNIEnv *env, jclass obj, jint java_error_no){
+
+ switch (java_error_no) {
+ case 0:
+ return 0;
+ case 1:
+ return EBADF;
+ case 2:
+ return ENXIO;
+ case 3:
+ return EBUSY;
+ case 4:
+ return EINVAL;
+ case 5:
+ return ETIMEDOUT;
+ case 6:
+ return EIO;
+ case 7:
+ return ENOMEM;
+ default:
+ return 100000;
+ }
+}
Index: usb_fpga_1_2/trunk/libusbJava-src/LibusbJava.h
===================================================================
--- usb_fpga_1_2/trunk/libusbJava-src/LibusbJava.h (nonexistent)
+++ usb_fpga_1_2/trunk/libusbJava-src/LibusbJava.h (revision 2)
@@ -0,0 +1,199 @@
+/* DO NOT EDIT THIS FILE - it is machine generated */
+#include
+/* Header for class ch_ntb_usb_LibusbJava */
+
+#ifndef _Included_ch_ntb_usb_LibusbJava
+#define _Included_ch_ntb_usb_LibusbJava
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_set_debug
+ * Signature: (I)V
+ */
+JNIEXPORT void JNICALL Java_ch_ntb_usb_LibusbJava_usb_1set_1debug
+ (JNIEnv *, jclass, jint);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_init
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL Java_ch_ntb_usb_LibusbJava_usb_1init
+ (JNIEnv *, jclass);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_find_busses
+ * Signature: ()I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1find_1busses
+ (JNIEnv *, jclass);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_find_devices
+ * Signature: ()I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1find_1devices
+ (JNIEnv *, jclass);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_get_busses
+ * Signature: ()Lch/ntb/usb/Usb_Bus;
+ */
+JNIEXPORT jobject JNICALL Java_ch_ntb_usb_LibusbJava_usb_1get_1busses
+ (JNIEnv *, jclass);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_open
+ * Signature: (Lch/ntb/usb/Usb_Device;)J
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1open
+ (JNIEnv *, jclass, jobject);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_close
+ * Signature: (J)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1close
+ (JNIEnv *, jclass, jint);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_set_configuration
+ * Signature: (JI)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1set_1configuration
+ (JNIEnv *, jclass, jint, jint);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_set_altinterface
+ * Signature: (JI)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1set_1altinterface
+ (JNIEnv *, jclass, jint, jint);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_clear_halt
+ * Signature: (JI)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1clear_1halt
+ (JNIEnv *, jclass, jint, jint);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_reset
+ * Signature: (J)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1reset
+ (JNIEnv *, jclass, jint);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_claim_interface
+ * Signature: (JI)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1claim_1interface
+ (JNIEnv *, jclass, jint, jint);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_release_interface
+ * Signature: (JI)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1release_1interface
+ (JNIEnv *, jclass, jint, jint);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_control_msg
+ * Signature: (JIIII[BII)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1control_1msg
+ (JNIEnv *, jclass, jint, jint, jint, jint, jint, jbyteArray, jint, jint);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_get_string
+ * Signature: (JII)Ljava/lang/String;
+ */
+JNIEXPORT jstring JNICALL Java_ch_ntb_usb_LibusbJava_usb_1get_1string
+ (JNIEnv *, jclass, jint, jint, jint);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_get_string_simple
+ * Signature: (JI)Ljava/lang/String;
+ */
+JNIEXPORT jstring JNICALL Java_ch_ntb_usb_LibusbJava_usb_1get_1string_1simple
+ (JNIEnv *, jclass, jint, jint);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_get_descriptor
+ * Signature: (JBBI)Ljava/lang/String;
+ */
+JNIEXPORT jstring JNICALL Java_ch_ntb_usb_LibusbJava_usb_1get_1descriptor
+ (JNIEnv *, jclass, jint, jbyte, jbyte, jint);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_get_descriptor_by_endpoint
+ * Signature: (JIBBI)Ljava/lang/String;
+ */
+JNIEXPORT jstring JNICALL Java_ch_ntb_usb_LibusbJava_usb_1get_1descriptor_1by_1endpoint
+ (JNIEnv *, jclass, jint, jint, jbyte, jbyte, jint);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_bulk_write
+ * Signature: (JI[BII)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1bulk_1write
+ (JNIEnv *, jclass, jint, jint, jbyteArray, jint, jint);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_bulk_read
+ * Signature: (JI[BII)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1bulk_1read
+ (JNIEnv *, jclass, jint, jint, jbyteArray, jint, jint);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_interrupt_write
+ * Signature: (JI[BII)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1interrupt_1write
+ (JNIEnv *, jclass, jint, jint, jbyteArray, jint, jint);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_interrupt_read
+ * Signature: (JI[BII)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1interrupt_1read
+ (JNIEnv *, jclass, jint, jint, jbyteArray, jint, jint);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_strerror
+ * Signature: ()Ljava/lang/String;
+ */
+JNIEXPORT jstring JNICALL Java_ch_ntb_usb_LibusbJava_usb_1strerror
+ (JNIEnv *, jclass);
+
+/*
+ * Class: ch_ntb_usb_LibusbJava
+ * Method: usb_error_no
+ * Signature: (I)I
+ */
+JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1error_1no
+ (JNIEnv *, jclass, jint);
+
+#endif
Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/logger/LogUtil.java
===================================================================
--- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/logger/LogUtil.java (nonexistent)
+++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/logger/LogUtil.java (revision 2)
@@ -0,0 +1,135 @@
+/*
+ * Java libusb wrapper
+ * Copyright (c) 2005-2006 Andreas Schläpfer
+ *
+ * http://libusbjava.sourceforge.net
+ * This library is covered by the LGPL, read LGPL.txt for details.
+ */
+package ch.ntb.usb.logger;
+
+import java.io.InputStream;
+import java.util.Properties;
+import java.util.logging.ConsoleHandler;
+import java.util.logging.Handler;
+import java.util.logging.Level;
+import java.util.logging.LogManager;
+import java.util.logging.Logger;
+
+public class LogUtil {
+
+ // debug this class
+ private static final boolean debugLogUtil = false;
+
+ private static final String PLUGIN_ID = "ch.ntb.usb";
+ private static final String PROPERTIES_FILE = ".configure";
+ private static final String LOGGER_WARNING = "Warning in class "
+ + LogUtil.class.getName()
+ + ": could not load the logger properties file " + PROPERTIES_FILE;
+
+ private static boolean debugEnabled;
+
+ static {
+ createLoggersFromProperties();
+ }
+
+ private static void debugMsg(String method, String message) {
+ if (debugLogUtil) {
+ System.out.println(method + ": " + message);
+ }
+ }
+
+ public static void setLevel(Logger logger, Level loglevel) {
+ Handler[] h = logger.getHandlers();
+ for (int i = 0; i < h.length; i++) {
+ System.out.println("setLevel " + loglevel.toString());
+ h[i].setLevel(loglevel);
+ }
+ logger.setLevel(loglevel);
+ }
+
+ public static Logger getLogger(String name) {
+ debugMsg("getLogger", name);
+ LogManager manager = LogManager.getLogManager();
+ // check if logger is already registered
+ Logger logger = manager.getLogger(name);
+ if (logger == null) {
+ logger = Logger.getLogger(name);
+ setLevel(logger, Level.OFF);
+ manager.addLogger(logger);
+ debugMsg("getLogger", "creating new logger");
+ }
+ if (logger.getLevel() == null) {
+ debugMsg("getLogger", "level == null -> setLevel to OFF ");
+ setLevel(logger, Level.OFF);
+ }
+ debugMsg("getLogger", "logLevel " + logger.getLevel().getName());
+ return logger;
+ }
+
+ private static void initLevel(Logger logger, Level loglevel) {
+ Handler[] h = logger.getHandlers();
+ for (int i = 0; i < h.length; i++) {
+ logger.removeHandler(h[i]);
+ }
+ Handler console = new ConsoleHandler();
+ console.setLevel(loglevel);
+ logger.addHandler(console);
+ logger.setLevel(loglevel);
+ logger.setUseParentHandlers(false);
+ }
+
+ private static void createLoggersFromProperties() {
+ try {
+ debugMsg(LogUtil.class.getName(), "createLoggersFromProperties");
+ InputStream is = LogUtil.class.getClassLoader()
+ .getResourceAsStream(PROPERTIES_FILE);
+ if (is == null) {
+ System.err.println(LOGGER_WARNING);
+ } else {
+ Properties prop = new Properties();
+ prop.load(is);
+ debugMsg("createLoggersFromProperties",
+ "properties file loaded: " + PROPERTIES_FILE);
+ debugMsg("createLoggersFromProperties", "file content:\n"
+ + prop.toString());
+ // get global debug enable flag
+ debugEnabled = Boolean.parseBoolean(prop.getProperty(PLUGIN_ID
+ + "/debug"));
+ debugMsg("createLoggersFromProperties", "debuging enabled: "
+ + debugEnabled);
+ // get and configure loggers
+ boolean moreLoggers = true;
+ int loggerCount = 0;
+ while (moreLoggers) {
+ String loggerProp = prop.getProperty(PLUGIN_ID
+ + "/debug/logger" + loggerCount);
+ loggerCount++;
+ if (loggerProp != null) {
+ // parse string and get logger name and log level
+ int slashIndex = loggerProp.indexOf('/');
+ String loggerName = loggerProp.substring(0, slashIndex)
+ .trim();
+ String logLevel = loggerProp.substring(slashIndex + 1,
+ loggerProp.length());
+ // register logger
+ Level level;
+ if (debugEnabled) {
+ level = Level.parse(logLevel);
+ } else {
+ level = Level.OFF;
+ }
+ Logger logger = getLogger(loggerName);
+ initLevel(logger, level);
+ debugMsg("createLoggersFromProperties",
+ "create logger " + loggerName + " with level "
+ + level.toString());
+ } else {
+ moreLoggers = false;
+ }
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+}
Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/logger/package.html
===================================================================
--- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/logger/package.html (nonexistent)
+++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/logger/package.html (revision 2)
@@ -0,0 +1,16 @@
+
+
+
+
+
+Logging related classes.
+
+
+ *
+ * http://libusbjava.sourceforge.net
+ * This library is covered by the LGPL, read LGPL.txt for details.
+ */
+package ch.ntb.usb;
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import ch.ntb.usb.logger.LogUtil;
+
+/**
+ * This class represents an USB device.
+ * To get an instance of an USB device use
+ * The descriptors can be read with {@link #getDeviceDescriptor()} and + * {@link #getConfigDescriptors()}. + * + * @throws USBException + */ + public void updateDescriptors() throws USBException { + dev = initDevice(idVendor, idProduct, filename); + } + + /** + * Returns the device descriptor associated with this device.
+ * The descriptor is updated by calling {@link #updateDescriptors()} or + * {@link #open(int, int, int)}. + * + * @return the device descriptor associated with this device or + *
+ * The descriptors are updated by calling {@link #updateDescriptors()} or + * {@link #open(int, int, int)}. + * + * @return the configuration descriptors associated with this device or + *
+ * First the bus is enumerated. If the device is found its descriptors are + * read and the
+ * + * @throws USBException + */ + public void close() throws USBException { + if (usbDevHandle == 0) { + throw new USBException("invalid device handle"); + } + release_interface(usbDevHandle, dev_interface); + if (LibusbJava.usb_close(usbDevHandle) < 0) { + usbDevHandle = 0; + throw new USBException("LibusbJava.usb_close: " + + LibusbJava.usb_strerror()); + } + usbDevHandle = 0; + maxPacketSize = -1; + logger.info("device closed"); + } + + /** + * Sends an USB reset to the device. The device handle will no longer be + * valid. To use the device again, {@link #open(int, int, int)} must be + * called. + * + * @throws USBException + */ + public void reset() throws USBException { + if (usbDevHandle == 0) { + throw new USBException("invalid device handle"); + } + release_interface(usbDevHandle, dev_interface); + if (LibusbJava.usb_reset(usbDevHandle) < 0) { + usbDevHandle = 0; + throw new USBException("LibusbJava.usb_reset: " + + LibusbJava.usb_strerror()); + } + usbDevHandle = 0; + logger.info("device reset"); + } + + /** + * Write data to the device using a bulk transfer.
+ * + * @param out_ep_address + * endpoint address to write to + * @param data + * data to write to this endpoint + * @param size + * size of the data + * @param timeout + * amount of time in ms the device will try to send the data + * until a timeout exception is thrown + * @param reopenOnTimeout + * if set to true, the device will try to open the connection and + * send the data again before a timeout exception is thrown + * @return the actual number of bytes written + * @throws USBException + */ + public int writeBulk(int out_ep_address, byte[] data, int size, + int timeout, boolean reopenOnTimeout) throws USBException { + if (usbDevHandle == 0) { + throw new USBException("invalid device handle"); + } + if (data == null) { + throw new USBException("data must not be null"); + } + if (size <= 0 || size > data.length) { + throw new ArrayIndexOutOfBoundsException("invalid size: " + size); + } + int lenWritten = LibusbJava.usb_bulk_write(usbDevHandle, + out_ep_address, data, size, timeout); + if (lenWritten < 0) { + if (lenWritten == LibusbJava.ERROR_TIMEDOUT) { + // try to reopen the device and send the data again + if (reopenOnTimeout) { + logger.info("try to reopen"); + reset(); + open(dev_configuration, dev_interface, dev_altinterface); + return writeBulk(out_ep_address, data, size, timeout, false); + } + throw new USBTimeoutException("LibusbJava.usb_bulk_write: " + + LibusbJava.usb_strerror()); + } + throw new USBException("LibusbJava.usb_bulk_write: " + + LibusbJava.usb_strerror()); + } + + logger.info("length written: " + lenWritten); + if (logger.isLoggable(Level.FINEST)) { + StringBuffer sb = new StringBuffer("bulkwrite, ep 0x" + + Integer.toHexString(out_ep_address) + ": " + lenWritten + + " Bytes sent: "); + for (int i = 0; i < lenWritten; i++) { + sb.append("0x" + String.format("%1$02X", data[i]) + " "); + } + logger.info(sb.toString()); + } + return lenWritten; + } + + /** + * Read data from the device using a bulk transfer.
+ * + * @param in_ep_address + * endpoint address to read from + * @param data + * data buffer for the data to be read + * @param size + * the maximum requested data size + * @param timeout + * amount of time in ms the device will try to receive data until + * a timeout exception is thrown + * @param reopenOnTimeout + * if set to true, the device will try to open the connection and + * receive the data again before a timeout exception is thrown + * @return the actual number of bytes read + * @throws USBException + */ + public int readBulk(int in_ep_address, byte[] data, int size, int timeout, + boolean reopenOnTimeout) throws USBException { + if (usbDevHandle == 0) { + throw new USBException("invalid device handle"); + } + if (data == null) { + throw new USBException("data must not be null"); + } + if (size <= 0 || size > data.length) { + throw new ArrayIndexOutOfBoundsException("invalid size: " + size); + } + int lenRead = LibusbJava.usb_bulk_read(usbDevHandle, in_ep_address, + data, size, timeout); + if (lenRead < 0) { + if (lenRead == LibusbJava.ERROR_TIMEDOUT) { + // try to reopen the device and send the data again + if (reopenOnTimeout) { + logger.info("try to reopen"); + reset(); + open(dev_configuration, dev_interface, dev_altinterface); + return readBulk(in_ep_address, data, size, timeout, false); + } + throw new USBTimeoutException("LibusbJava.usb_bulk_read: " + + LibusbJava.usb_strerror()); + } + throw new USBException("LibusbJava.usb_bulk_read: " + + LibusbJava.usb_strerror()); + } + + logger.info("length read: " + lenRead); + if (logger.isLoggable(Level.FINEST)) { + StringBuffer sb = new StringBuffer("bulkread, ep 0x" + + Integer.toHexString(in_ep_address) + ": " + lenRead + + " Bytes received: "); + for (int i = 0; i < lenRead; i++) { + sb.append("0x" + String.format("%1$02X", data[i]) + " "); + } + logger.info(sb.toString()); + } + return lenRead; + } + + /** + * Write data to the device using a interrupt transfer.
+ * + * @param out_ep_address + * endpoint address to write to + * @param data + * data to write to this endpoint + * @param size + * size of the data + * @param timeout + * amount of time in ms the device will try to send the data + * until a timeout exception is thrown + * @param reopenOnTimeout + * if set to true, the device will try to open the connection and + * send the data again before a timeout exception is thrown + * @return the actual number of bytes written + * @throws USBException + */ + public int writeInterrupt(int out_ep_address, byte[] data, int size, + int timeout, boolean reopenOnTimeout) throws USBException { + if (usbDevHandle == 0) { + throw new USBException("invalid device handle"); + } + if (data == null) { + throw new USBException("data must not be null"); + } + if (size <= 0 || size > data.length) { + throw new ArrayIndexOutOfBoundsException("invalid size: " + size); + } + int lenWritten = LibusbJava.usb_interrupt_write(usbDevHandle, + out_ep_address, data, size, timeout); + if (lenWritten < 0) { + if (lenWritten == LibusbJava.ERROR_TIMEDOUT) { + // try to reopen the device and send the data again + if (reopenOnTimeout) { + logger.info("try to reopen"); + reset(); + open(dev_configuration, dev_interface, dev_altinterface); + return writeInterrupt(out_ep_address, data, size, timeout, + false); + } + throw new USBTimeoutException( + "LibusbJava.usb_interrupt_write: " + + LibusbJava.usb_strerror()); + } + throw new USBException("LibusbJava.usb_interrupt_write: " + + LibusbJava.usb_strerror()); + } + + logger.info("length written: " + lenWritten); + if (logger.isLoggable(Level.FINEST)) { + StringBuffer sb = new StringBuffer("interruptwrite, ep 0x" + + Integer.toHexString(out_ep_address) + ": " + lenWritten + + " Bytes sent: "); + for (int i = 0; i < lenWritten; i++) { + sb.append("0x" + String.format("%1$02X", data[i]) + " "); + } + logger.info(sb.toString()); + } + return lenWritten; + } + + /** + * Read data from the device using a interrupt transfer.
+ * + * @param in_ep_address + * endpoint address to read from + * @param data + * data buffer for the data to be read + * @param size + * the maximum requested data size + * @param timeout + * amount of time in ms the device will try to receive data until + * a timeout exception is thrown + * @param reopenOnTimeout + * if set to true, the device will try to open the connection and + * receive the data again before a timeout exception is thrown + * @return the actual number of bytes read + * @throws USBException + */ + public int readInterrupt(int in_ep_address, byte[] data, int size, + int timeout, boolean reopenOnTimeout) throws USBException { + if (usbDevHandle == 0) { + throw new USBException("invalid device handle"); + } + if (data == null) { + throw new USBException("data must not be null"); + } + if (size <= 0 || size > data.length) { + throw new ArrayIndexOutOfBoundsException("invalid size: " + size); + } + int lenRead = LibusbJava.usb_interrupt_read(usbDevHandle, + in_ep_address, data, size, timeout); + if (lenRead < 0) { + if (lenRead == LibusbJava.ERROR_TIMEDOUT) { + // try to reopen the device and send the data again + if (reopenOnTimeout) { + logger.info("try to reopen"); + reset(); + open(dev_configuration, dev_interface, dev_altinterface); + return readInterrupt(in_ep_address, data, size, timeout, + false); + } + throw new USBTimeoutException("LibusbJava.usb_interrupt_read: " + + LibusbJava.usb_strerror()); + } + throw new USBException("LibusbJava.usb_interrupt_read: " + + LibusbJava.usb_strerror()); + } + + logger.info("length read: " + lenRead); + if (logger.isLoggable(Level.FINEST)) { + StringBuffer sb = new StringBuffer("interrupt, ep 0x" + + Integer.toHexString(in_ep_address) + ": " + lenRead + + " Bytes received: "); + for (int i = 0; i < lenRead; i++) { + sb.append("0x" + String.format("%1$02X", data[i]) + " "); + } + logger.info(sb.toString()); + } + return lenRead; + } + + /** + * Performs a control request to the default control pipe on a device.
+ * The parameters mirror the types of the same name in the USB + * specification. + * + * @param requestType + * USB device request type (USB specification 9.3, + * bmRequestType). Use constants from {@link ch.ntb.usb.USB} + * (REQ_TYPE_xxx). + * @param request + * specific request (USB specification 9.4, bRequest). Use + * constants from {@link ch.ntb.usb.USB} (REQ_xxx). + * @param value + * field that varies according to request (USB specification 9.4, + * wValue) + * @param index + * field that varies according to request (USB specification 9.4, + * wIndex) + * @param data + * the send/receive buffer + * @param size + * the buffer size. 0 is a valid value, but there must still be a + * dummy data buffer provided. + * @param timeout + * amount of time in ms the device will try to send/receive data + * until a timeout exception is thrown + * @param reopenOnTimeout + * if set to true, the device will try to open the connection and + * send/receive the data again before a timeout exception is + * thrown + * @return the number of bytes written/read + * @throws USBException + */ + public int controlMsg(int requestType, int request, int value, int index, + byte[] data, int size, int timeout, boolean reopenOnTimeout) + throws USBException { + if (usbDevHandle == 0) { + throw new USBException("invalid device handle"); + } + if (data == null) { + throw new USBException("data must not be null"); + } + if (size < 0 || size > data.length) { + throw new ArrayIndexOutOfBoundsException("invalid size: " + size); + } + int len = LibusbJava.usb_control_msg(usbDevHandle, requestType, + request, value, index, data, size, timeout); + if (len < 0) { + if (len == LibusbJava.ERROR_TIMEDOUT) { + // try to reopen the device and send the data again + if (reopenOnTimeout) { + logger.info("try to reopen"); + reset(); + open(dev_configuration, dev_interface, dev_altinterface); + return controlMsg(requestType, request, value, index, data, + size, timeout, false); + } + throw new USBTimeoutException("LibusbJava.controlMsg: " + + LibusbJava.usb_strerror()); + } + throw new USBException("LibusbJava.controlMsg: " + + LibusbJava.usb_strerror()); + } + + logger.info("length read/written: " + len); + if (logger.isLoggable(Level.FINEST)) { + StringBuffer sb = new StringBuffer("controlMsg: " + len + + " Bytes received(written: "); + for (int i = 0; i < len; i++) { + sb.append("0x" + String.format("%1$02X", data[i]) + " "); + } + logger.info(sb.toString()); + } + return len; + } + + /** + * Claim an interface to send and receive USB data.
+ * + * @param usb_dev_handle + * the handle of the device (MUST BE VALID) + * @param configuration + * the configuration to use + * @param interface_ + * the interface to claim + * @param altinterface + * the alternate interface to use. If no alternate interface must + * be set -1 can be used. + * @throws USBException + * throws an USBException if the action fails + */ + private void claim_interface(int usb_dev_handle, int configuration, + int interface_, int altinterface) throws USBException { + if (LibusbJava.usb_set_configuration(usb_dev_handle, configuration) < 0) { + usbDevHandle = 0; + throw new USBException("LibusbJava.usb_set_configuration: " + + LibusbJava.usb_strerror()); + } + if (LibusbJava.usb_claim_interface(usb_dev_handle, interface_) < 0) { + usbDevHandle = 0; + throw new USBException("LibusbJava.usb_claim_interface: " + + LibusbJava.usb_strerror()); + } + if (altinterface >= 0) { + if (LibusbJava.usb_set_altinterface(usb_dev_handle, altinterface) < 0) { + try { + release_interface(usb_dev_handle, interface_); + } catch (USBException e) { + // ignore + } + usbDevHandle = 0; + throw new USBException("LibusbJava.usb_set_altinterface: " + + LibusbJava.usb_strerror()); + } + } + logger.info("interface claimed"); + } + + /** + * Release a previously claimed interface.
+ * + * @param dev_handle + * the handle of the device (MUST BE VALID) + * @param interface_ + * the interface to claim + * @throws USBException + * throws an USBException if the action fails + */ + private void release_interface(int dev_handle, int interface_) + throws USBException { + if (LibusbJava.usb_release_interface(dev_handle, interface_) < 0) { + usbDevHandle = 0; + throw new USBException("LibusbJava.usb_release_interface: " + + LibusbJava.usb_strerror()); + } + logger.info("interface released"); + } + + /** + * Returns the product ID of the device.
+ * + * @return the product ID of the device. + */ + public int getIdProduct() { + return idProduct; + } + + /** + * Returns the vendor ID of the device.
+ * + * @return the vendor ID of the device. + */ + public int getIdVendor() { + return idVendor; + } + + /** + * Returns the alternative interface.
+ * This value is only valid after opening the device. + * + * @return the alternative interface. This value is only valid after opening + * the device. + */ + public int getAltinterface() { + return dev_altinterface; + } + + /** + * Returns the current configuration used.
+ * This value is only valid after opening the device. + * + * @return the current configuration used. This value is only valid after + * opening the device. + */ + public int getConfiguration() { + return dev_configuration; + } + + /** + * Returns the current interface.
+ * This value is only valid after opening the device. + * + * @return the current interface. This value is only valid after opening the + * device. + */ + public int getInterface() { + return dev_interface; + } + + /** + * Returns the maximum packet size in bytes which is allowed to be + * transmitted at once.
+ * The value is determined by reading the endpoint descriptor(s) when + * opening the device. It is invalid before the device is opened! Note that + * if some endpoints use different packet sizes the maximum packet size is + * return. This value may be used to determine if a device is opened in + * fullspeed or highspeed mode. + * + * @return the maximum packet size + */ + public int getMaxPacketSize() { + return maxPacketSize; + } + + /** + * Check if the device is open.
+ * This checks only for a valid device handle. It doesn't check if the + * device is still attached or working. + * + * @return true if the device is open + */ + public boolean isOpen() { + return usbDevHandle != 0; + } + + /** + * If enabled, the device is reset when first opened.
+ * This will only happen once. When the application is started, the device + * state is unknown. If the device is not reset, read or write may result in + * a {@link USBTimeoutException}.
+ *
+ * This feature is disabled by default. + * + * @param enable + * true if the device should be reset when first opened + * @param timeout + * the timeout between the reset and the reopening + */ + public void setResetOnFirstOpen(boolean enable, int timeout) { + resetOnFirstOpen = enable; + resetTimeout = timeout; + } + + /** + * Returns the optional filename which is set when there are multiple + * devices with the same vendor and product id. See + * {@link USB#getDevice(short, short, String)}. Use + * {@link Usb_Device#getFilename()} to read the filename of a device. + * + * @return the filename if set or null + */ + protected String getFilename() { + return filename; + } + + /** + * Returns the Usb_Device instance associated with this device. This value + * is only valid after opening the device. + * + * @return the Usb_Device instance associated with this device. + */ + public Usb_Device getDevice() { + return dev; + } +} Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Utils.java =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Utils.java (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Utils.java (revision 2) @@ -0,0 +1,60 @@ +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer
+ *
+ * http://libusbjava.sourceforge.net
+ * This library is covered by the LGPL, read LGPL.txt for details.
+ */
+package ch.ntb.usb;
+
+import java.io.PrintStream;
+
+public class Utils {
+
+ public static void logBus(Usb_Bus bus) {
+ logBus(bus, System.out);
+ }
+
+ public static void logBus(Usb_Bus bus, PrintStream out) {
+ Usb_Bus usb_Bus = bus;
+ while (usb_Bus != null) {
+ out.println(usb_Bus.toString());
+ Usb_Device dev = usb_Bus.getDevices();
+ while (dev != null) {
+ out.println("\t" + dev.toString());
+ // Usb_Device_Descriptor
+ Usb_Device_Descriptor defDesc = dev.getDescriptor();
+ out.println("\t\t" + defDesc.toString());
+ // Usb_Config_Descriptor
+ Usb_Config_Descriptor[] confDesc = dev.getConfig();
+ for (int i = 0; i < confDesc.length; i++) {
+ out.println("\t\t" + confDesc[i].toString());
+ Usb_Interface[] int_ = confDesc[i].getInterface();
+ if (int_ != null) {
+ for (int j = 0; j < int_.length; j++) {
+ out.println("\t\t\t" + int_[j].toString());
+ Usb_Interface_Descriptor[] intDesc = int_[j]
+ .getAltsetting();
+ if (intDesc != null) {
+ for (int k = 0; k < intDesc.length; k++) {
+ out.println("\t\t\t\t"
+ + intDesc[k].toString());
+ Usb_Endpoint_Descriptor[] epDesc = intDesc[k]
+ .getEndpoint();
+ if (epDesc != null) {
+ for (int e = 0; e < epDesc.length; e++) {
+ out.println("\t\t\t\t\t"
+ + epDesc[e].toString());
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ dev = dev.getNext();
+ }
+ usb_Bus = usb_Bus.getNext();
+ }
+ }
+}
Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Bus.java
===================================================================
--- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Bus.java (nonexistent)
+++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Bus.java (revision 2)
@@ -0,0 +1,86 @@
+/*
+ * Java libusb wrapper
+ * Copyright (c) 2005-2006 Andreas Schläpfer
+ *
+ * http://libusbjava.sourceforge.net
+ * This library is covered by the LGPL, read LGPL.txt for details.
+ */
+package ch.ntb.usb;
+
+/**
+ * Represents an USB bus.
+ * This is the root class for the representation of the libusb USB structure. + * Zero or more devices may be connected to an USB bus. + * + */ +public class Usb_Bus { + + private Usb_Bus next, prev; + + private String dirname; + + private Usb_Device devices; + + private long location; + + private Usb_Device root_dev; + + /** + * Get the first device ojects of the devices linked list.
+ * + * @return the first device ojects of the devices linked list or null + */ + public Usb_Device getDevices() { + return devices; + } + + /** + * Returns the systems String representation of the bus.
+ * + * @return the systems String representation of the bus + */ + public String getDirname() { + return dirname; + } + + /** + * Returns the next bus object.
+ * + * @return Returns the next bus object or null + */ + public Usb_Bus getNext() { + return next; + } + + /** + * Returns the previous bus object.
+ * + * @return Returns the previous bus object or null + */ + public Usb_Bus getPrev() { + return prev; + } + + /** + * Get the root device of this bus.
+ * + * @return the root device oject or null + */ + public Usb_Device getRootDev() { + return root_dev; + } + + /** + * Returns the location in the USB bus linked list.
+ * + * @return the location in the USB bus linked list + */ + public long getLocation() { + return location; + } + + @Override + public String toString() { + return "Usb_Bus " + dirname; + } +} \ No newline at end of file Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Device_Descriptor.java =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Device_Descriptor.java (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Device_Descriptor.java (revision 2) @@ -0,0 +1,190 @@ +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer
+ *
+ * http://libusbjava.sourceforge.net
+ * This library is covered by the LGPL, read LGPL.txt for details.
+ */
+package ch.ntb.usb;
+
+/**
+ * Represents the descriptor of a USB device.
+ * A USB device can only have one device descriptor. It specifies some basic, + * yet important information about the device.
+ *
+ * The length of the device descriptor is + * {@link ch.ntb.usb.Usb_Descriptor#USB_DT_DEVICE_SIZE} and the type is + * {@link ch.ntb.usb.Usb_Descriptor#USB_DT_DEVICE}. + * + */ +public class Usb_Device_Descriptor extends Usb_Descriptor { + /** + * Device and/or interface class codes. + */ + public static final int USB_CLASS_PER_INTERFACE = 0, USB_CLASS_AUDIO = 1, + USB_CLASS_COMM = 2, USB_CLASS_HID = 3, USB_CLASS_PRINTER = 7, + USB_CLASS_MASS_STORAGE = 8, USB_CLASS_HUB = 9, USB_CLASS_DATA = 10, + USB_CLASS_VENDOR_SPEC = 0xff; + + private short bcdUSB; + + private byte bDeviceClass; + + private byte bDeviceSubClass; + + private byte bDeviceProtocol; + + private byte bMaxPacketSize0; + + private short idVendor; + + private short idProduct; + + private short bcdDevice; + + private byte iManufacturer; + + private byte iProduct; + + private byte iSerialNumber; + + private byte bNumConfigurations; + + /** + * Returns the device release number.
+ * Assigned by the manufacturer of the device. + * + * @return the device release number + */ + public short getBcdDevice() { + return bcdDevice; + } + + /** + * Returns the USB specification number to which the device complies to.
+ * This field reports the highest version of USB the device supports. The + * value is in binary coded decimal with a format of 0xJJMN where JJ is the + * major version number, M is the minor version number and N is the sub + * minor version number.
+ * Examples: USB 2.0 is reported as 0x0200, USB 1.1 as 0x0110 and USB 1.0 as + * 0x100 + * + * @return the USB specification number to which the device complies to + */ + public short getBcdUSB() { + return bcdUSB; + } + + /** + * Returns the class code (Assigned by www.usb.org)
+ * If equal to zero, each interface specifies it's own class code. If equal + * to 0xFF, the class code is vendor specified. Otherwise the field is a + * valid class code. + * + * @return the class code + */ + public byte getBDeviceClass() { + return bDeviceClass; + } + + /** + * Returns the protocol code (Assigned by www.usb.org)
+ * + * @return the protocol code + */ + public byte getBDeviceProtocol() { + return bDeviceProtocol; + } + + /** + * Returns the subclass code (Assigned by www.usb.org)
+ * + * @return the subclass code + */ + public byte getBDeviceSubClass() { + return bDeviceSubClass; + } + + /** + * Returns the maximum packet size for endpoint zero.
+ * Valid sizes are 8, 16, 32, 64. + * + * @return the maximum packet size for endpoint zero + */ + public byte getBMaxPacketSize0() { + return bMaxPacketSize0; + } + + /** + * Returns the number of possible configurations supported at its current + * speed.
+ * + * @return the number of possible configurations supported at its current + * speed + */ + public byte getBNumConfigurations() { + return bNumConfigurations; + } + + /** + * Returns the product ID (Assigned by www.usb.org)
+ * + * @return the product ID + */ + public short getIdProduct() { + return idProduct; + } + + /** + * Returns the Vendor ID (Assigned by www.usb.org)
+ * + * @return the Vendor ID + */ + public short getIdVendor() { + return idVendor; + } + + /** + * Returns the index of the manufacturer string descriptor.
+ * If this value is 0, no string descriptor is used. + * + * @return the index of the manufacturer string descriptor + */ + public byte getIManufacturer() { + return iManufacturer; + } + + /** + * Returns the index of the product string descriptor.
+ * If this value is 0, no string descriptor is used. + * + * @return the index of the product string descriptor + */ + public byte getIProduct() { + return iProduct; + } + + /** + * Returns the index of serial number string descriptor.
+ * If this value is 0, no string descriptor is used. + * + * @return the index of serial number string descriptor + */ + public byte getISerialNumber() { + return iSerialNumber; + } + + @Override + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("Usb_Device_Descriptor idVendor: 0x" + + Integer.toHexString(idVendor & 0xFFFF) + ", idProduct: 0x" + + Integer.toHexString(idProduct & 0xFFFF)); + return sb.toString(); + } +} \ No newline at end of file Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Interface_Descriptor.java =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Interface_Descriptor.java (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Interface_Descriptor.java (revision 2) @@ -0,0 +1,145 @@ +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer
+ *
+ * http://libusbjava.sourceforge.net
+ * This library is covered by the LGPL, read LGPL.txt for details.
+ */
+package ch.ntb.usb;
+
+/**
+ * Represents the descriptor of a USB interface.
+ * The interface descriptor could be seen as a header or grouping of the + * endpoints into a functional group performing a single feature of the device.
+ *
+ * The length of the interface descriptor is + * {@link ch.ntb.usb.Usb_Descriptor#USB_DT_INTERFACE_SIZE} and the type is + * {@link ch.ntb.usb.Usb_Descriptor#USB_DT_INTERFACE}. + * + */ +public class Usb_Interface_Descriptor extends Usb_Descriptor { + + /** + * Maximum number of interfaces + */ + public static final int USB_MAXINTERFACES = 32; + + private byte bInterfaceNumber; + + private byte bAlternateSetting; + + private byte bNumEndpoints; + + private byte bInterfaceClass; + + private byte bInterfaceSubClass; + + private byte bInterfaceProtocol; + + private byte iInterface; + + private Usb_Endpoint_Descriptor[] endpoint; + + private byte[] extra; /* Extra descriptors */ + + private int extralen; + + @Override + public String toString() { + return "Usb_Interface_Descriptor bNumEndpoints: 0x" + + Integer.toHexString(bNumEndpoints); + } + + /** + * Returns the value used to select the alternate setting ({@link LibusbJava#usb_set_altinterface(int, int)}).
+ * + * @return the alternate setting + */ + public byte getBAlternateSetting() { + return bAlternateSetting; + } + + /** + * Returns the class code (Assigned by www.usb.org).
+ * + * @return the class code + */ + public byte getBInterfaceClass() { + return bInterfaceClass; + } + + /** + * Returns the number (identifier) of this interface.
+ * + * @return the number (identifier) of this interface + */ + public byte getBInterfaceNumber() { + return bInterfaceNumber; + } + + /** + * Returns the protocol code (Assigned by www.usb.org).
+ * + * @return the protocol code + */ + public byte getBInterfaceProtocol() { + return bInterfaceProtocol; + } + + /** + * Returns the subclass code (Assigned by www.usb.org).
+ * + * @return the subclass code + */ + public byte getBInterfaceSubClass() { + return bInterfaceSubClass; + } + + /** + * Returns the number of endpoints used for this interface.
+ * + * @return the number of endpoints used for this interface + */ + public byte getBNumEndpoints() { + return bNumEndpoints; + } + + /** + * Returns an array of endpoint descriptors.
+ * + * @return an array of endpoint descriptors + */ + public Usb_Endpoint_Descriptor[] getEndpoint() { + return endpoint; + } + + /** + * Returns the data of extra descriptor(s) if available.
+ * + * @return null or a byte array with the extra descriptor data + */ + public byte[] getExtra() { + return extra; + } + + /** + * Returns the number of bytes of the extra descriptor.
+ * + * @return the number of bytes of the extra descriptor + */ + public int getExtralen() { + return extralen; + } + + /** + * Returns the index of the String descriptor describing this interface.
+ * + * @return the index of the String descriptor + */ + public byte getIInterface() { + return iInterface; + } +} Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/USBException.java =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/USBException.java (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/USBException.java (revision 2) @@ -0,0 +1,23 @@ +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer
+ *
+ * http://libusbjava.sourceforge.net
+ * This library is covered by the LGPL, read LGPL.txt for details.
+ */
+package ch.ntb.usb;
+
+import java.io.IOException;
+
+public class USBException extends IOException {
+
+ public USBException(String string) {
+ super(string);
+ }
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1690857437804284710L;
+
+}
Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Device.java
===================================================================
--- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Device.java (nonexistent)
+++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Device.java (revision 2)
@@ -0,0 +1,126 @@
+/*
+ * Java libusb wrapper
+ * Copyright (c) 2005-2006 Andreas Schläpfer
+ *
+ * http://libusbjava.sourceforge.net
+ * This library is covered by the LGPL, read LGPL.txt for details.
+ */
+package ch.ntb.usb;
+
+/**
+ * Represents an USB device.
+ * An USB device has one device descriptor and it may have multiple + * configuration descriptors. + * + */ +public class Usb_Device { + + private Usb_Device next, prev; + + private String filename; + + private Usb_Bus bus; + + private Usb_Device_Descriptor descriptor; + + private Usb_Config_Descriptor[] config; + + private byte devnum; + + private byte num_children; + + private Usb_Device children; + + /** + * The address of the device structure to be passed to usb_open. This value + * is used only internally so we don't use getter or setter methods. + */ + @SuppressWarnings("unused") + private long devStructAddr; + + /** + * Returns the reference to the bus to which this device is connected.
+ * + * @return the reference to the bus to which this device is connected + */ + public Usb_Bus getBus() { + return bus; + } + + /** + * Returns a reference to the first child.
+ * + * @return a reference to the first child + */ + public Usb_Device getChildren() { + return children; + } + + /** + * Returns the USB config descriptors.
+ * + * @return the USB config descriptors + */ + public Usb_Config_Descriptor[] getConfig() { + return config; + } + + /** + * Returns the USB device descriptor.
+ * + * @return the USB device descriptor + */ + public Usb_Device_Descriptor getDescriptor() { + return descriptor; + } + + /** + * Returns the number assigned to this device.
+ * + * @return the number assigned to this device + */ + public byte getDevnum() { + return devnum; + } + + /** + * Returns the systems String representation.
+ * + * @return the systems String representation + */ + public String getFilename() { + return filename; + } + + /** + * Returns the pointer to the next device.
+ * + * @return the pointer to the next device or null + */ + public Usb_Device getNext() { + return next; + } + + /** + * Returns the number of children of this device.
+ * + * @return the number of children of this device + */ + public byte getNumChildren() { + return num_children; + } + + /** + * Returns the pointer to the previous device.
+ * + * @return the pointer to the previous device or null + */ + public Usb_Device getPrev() { + return prev; + } + + @Override + public String toString() { + return "Usb_Device " + filename; + } +} \ No newline at end of file Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Interface.java =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Interface.java (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Interface.java (revision 2) @@ -0,0 +1,50 @@ +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer
+ *
+ * http://libusbjava.sourceforge.net
+ * This library is covered by the LGPL, read LGPL.txt for details.
+ */
+package ch.ntb.usb;
+
+/**
+ * Represents an USB interface.
+ * An interface is a group of alternate settings of a configuration.
+ * + */ +public class Usb_Interface { + + /** + * Maximal number of alternate settings + */ + public static final int USB_MAXALTSETTING = 128; /* Hard limit */ + + private Usb_Interface_Descriptor[] altsetting; + + private int num_altsetting; + + @Override + public String toString() { + return "Usb_Interface num_altsetting: 0x" + + Integer.toHexString(num_altsetting); + } + + /** + * Retuns an array of interface descriptors.
+ * + * @return an array of interface descriptors + */ + public Usb_Interface_Descriptor[] getAltsetting() { + return altsetting; + } + + /** + * Returns the number of alternate settings.
+ * + * @return the number of alternate settings + */ + public int getNumAltsetting() { + return num_altsetting; + } + +} Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Config_Descriptor.java =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Config_Descriptor.java (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Config_Descriptor.java (revision 2) @@ -0,0 +1,139 @@ +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer
+ *
+ * http://libusbjava.sourceforge.net
+ * This library is covered by the LGPL, read LGPL.txt for details.
+ */
+package ch.ntb.usb;
+
+/**
+ * Represents the descriptor of a USB configuration.
+ * A USB device can have several different configuration.
+ *
+ * The length of the configuration descriptor is + * {@link ch.ntb.usb.Usb_Descriptor#USB_DT_CONFIG_SIZE} and the type is + * {@link ch.ntb.usb.Usb_Descriptor#USB_DT_CONFIG}. + * + */ +public class Usb_Config_Descriptor extends Usb_Descriptor { + + /** + * Maximum number of configurations per device + */ + public static final int USB_MAXCONFIG = 8; + + private short wTotalLength; + + private byte bNumInterfaces; + + private byte bConfigurationValue; + + private byte iConfiguration; + + private byte bmAttributes; + + private byte MaxPower; + + private Usb_Interface[] interface_; + + private byte[] extra; /* Extra descriptors */ + + private int extralen; + + /** + * Returns the value to use as an argument to select this configuration ({@link LibusbJava#usb_set_configuration(int, int)}). + * + * @return the value to use as an argument to select this configuration + */ + public byte getBConfigurationValue() { + return bConfigurationValue; + } + + /** + * Returns the power parameters for this configuration.
+ *
+ * Bit 7: Reserved, set to 1 (USB 1.0 Bus Powered)
+ * Bit 6: Self Powered
+ * Bit 5: Remote Wakeup
+ * Bit 4..0: Reserved, set to 0 + * + * @return the power parameters for this configuration + */ + public byte getBmAttributes() { + return bmAttributes; + } + + /** + * Returns the number of interfaces.
+ * + * @return the number of interfaces + */ + public byte getBNumInterfaces() { + return bNumInterfaces; + } + + /** + * Returns the data of extra descriptor(s) if available.
+ * + * @return null or a byte array with the extra descriptor data + */ + public byte[] getExtra() { + return extra; + } + + /** + * Returns the number of bytes of the extra descriptor.
+ * + * @return the number of bytes of the extra descriptor + */ + public int getExtralen() { + return extralen; + } + + /** + * Returns the index of the String descriptor describing this configuration.
+ * + * @return the index of the String descriptor + */ + public byte getIConfiguration() { + return iConfiguration; + } + + /** + * Returns the USB interface descriptors.
+ * + * @return the USB interface descriptors + */ + public Usb_Interface[] getInterface() { + return interface_; + } + + /** + * Returns the maximum power consumption in 2mA units.
+ * + * @return the maximum power consumption in 2mA units + */ + public byte getMaxPower() { + return MaxPower; + } + + /** + * Returns the total length in bytes of all descriptors.
+ * When the configuration descriptor is read, it returns the entire + * configuration hierarchy which includes all related interface and endpoint + * descriptors. The
+LibusbJava.java +is the JNI class to the +LibusbJava.dll +. Every class starting with +Usb_ +represents a descriptor of the bus structure which is retrieved by +calling +LibusbJava.usb_get_busses() +. + +
+ *
+ * http://libusbjava.sourceforge.net
+ * This library is covered by the LGPL, read LGPL.txt for details.
+ */
+package ch.ntb.usb;
+
+public class USBTimeoutException extends USBException {
+
+ public USBTimeoutException(String string) {
+ super(string);
+ }
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = -1065328371159778249L;
+
+}
Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/LibusbJava.java
===================================================================
--- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/LibusbJava.java (nonexistent)
+++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/LibusbJava.java (revision 2)
@@ -0,0 +1,378 @@
+/*
+ * Java libusb wrapper
+ * Copyright (c) 2005-2006 Andreas Schläpfer
+ *
+ * http://libusbjava.sourceforge.net
+ * This library is covered by the LGPL, read LGPL.txt for details.
+ */
+package ch.ntb.usb;
+
+/**
+ * This class represents the Java Native Interface to the shared library which
+ * is (with some exceptions) a one-to-one representation of the libusb API.
+ *
+ *
+ * Libusb-win32 is a port of + * the USB library libusb to the + * Windows operating systems. The library allows user space applications to + * access any USB device on Windows in a generic way without writing any line of + * kernel driver code.
+ *
+ * The API description of this class has been copied from the libusb documentation + * and adapted where neccessary.
+ * + */ +public class LibusbJava { + + /** + * System error codes.
+ * This list is not complete! For more error codes see the file 'errorno.h' + * on your system. + */ + public static int ERROR_SUCCESS, ERROR_BAD_FILE_DESCRIPTOR, + ERROR_NO_SUCH_DEVICE_OR_ADDRESS, ERROR_BUSY, + ERROR_INVALID_PARAMETER, ERROR_TIMEDOUT, ERROR_IO_ERROR, + ERROR_NOT_ENOUGH_MEMORY;; + + /** + * Sets the debugging level of libusb.
+ * + * The range is from 0 to 255, where 0 disables debug output and 255 enables + * all output. On application start, debugging is disabled (0). + * + * @param level + * 0 to 255 + */ + public static native void usb_set_debug(int level); + + // Core + /** + * Just like the name implies,
+ * The tree represents the bus structure with devices, configurations, + * interfaces and endpoints. Note that this is only a copy. To refresh the + * information,
+ * The name of the objects contained in the tree is starting with + *
+ *
+ * Causes re-enumeration: After calling
+ *
+ * Must be called!:
+ *
+ * See {@link #usb_get_descriptor_by_endpoint(int, int, byte, byte, int)} + * for a function that allows the control endpoint to be specified. + * + * @param dev_handle + * The handle to the device. + * @param type + * @param index + * @param size + * number of charactes which will be retrieved (the length of the + * resulting String) + * @return the descriptor String or null + */ + public static native String usb_get_descriptor(int dev_handle, byte type, + byte index, int size); + + /** + * Retrieves a descriptor from the device identified by the type and index + * of the descriptor from the control pipe identified by ep. + * + * @param dev_handle + * The handle to the device. + * @param ep + * @param type + * @param index + * @param size + * number of charactes which will be retrieved (the length of the + * resulting String) + * @return the descriptor String or null + */ + public static native String usb_get_descriptor_by_endpoint(int dev_handle, + int ep, byte type, byte index, int size); + + // Bulk Transfers + /** + * Performs a bulk write request to the endpoint specified by ep. + * + * @param dev_handle + * The handle to the device. + * @param ep + * @param bytes + * @param size + * @param timeout + * @return the number of bytes written on success or < 0 on error. + */ + public static native int usb_bulk_write(int dev_handle, int ep, + byte[] bytes, int size, int timeout); + + /** + * Performs a bulk read request to the endpoint specified by ep. + * + * @param dev_handle + * The handle to the device. + * @param ep + * @param bytes + * @param size + * @param timeout + * @return the number of bytes read on success or < 0 on error. + */ + public static native int usb_bulk_read(int dev_handle, int ep, + byte[] bytes, int size, int timeout); + + // Interrupt Transfers + /** + * Performs an interrupt write request to the endpoint specified by ep. + * + * @param dev_handle + * The handle to the device. + * @param ep + * @param bytes + * @param size + * @param timeout + * @return the number of bytes written on success or < 0 on error. + */ + public static native int usb_interrupt_write(int dev_handle, int ep, + byte[] bytes, int size, int timeout); + + /** + * Performs a interrupt read request to the endpoint specified by ep. + * + * @param dev_handle + * The handle to the device. + * @param ep + * @param bytes + * @param size + * @param timeout + * @return the number of bytes read on success or < 0 on error. + */ + public static native int usb_interrupt_read(int dev_handle, int ep, + byte[] bytes, int size, int timeout); + + /** + * Returns the error string after an error occured. + * + * @return the last error sring. + */ + public static native String usb_strerror(); + + /** **************************************************************** */ + + /** + * Maps the Java error code to the system error code.
+ *
+ * Note that not all error codes are be mapped by this method. For more + * error codes see the file 'errno.h' on your system.
+ *
+ * 1: EBADF: Bad file descriptor.
+ * 2: ENXIO: No such device or address.
+ * 3: EBUSY: Device or resource busy.
+ * 4: EINVAL: Invalid argument.
+ * 5: ETIMEDOUT: Connection timed out.
+ * 6: EIO: I/O error.
+ * 7: ENOMEM: Not enough memory.
+ * + * + * @return the system error code or 100000 if no mapping has been found. + */ + private static native int usb_error_no(int value); + + static { + String os = System.getProperty("os.name"); + if (os.contains("Windows")) { + LibLoader.load( "libusbJava" ); + } else { + LibLoader.load( "usbJava" ); + } + // define the error codes + ERROR_SUCCESS = 0; + ERROR_BAD_FILE_DESCRIPTOR = -usb_error_no(1); + ERROR_NO_SUCH_DEVICE_OR_ADDRESS = -usb_error_no(2); + ERROR_BUSY = -usb_error_no(3); + ERROR_INVALID_PARAMETER = -usb_error_no(4); + ERROR_TIMEDOUT = -usb_error_no(5); + ERROR_IO_ERROR = -usb_error_no(6); + ERROR_NOT_ENOUGH_MEMORY = -usb_error_no(7); + } +} \ No newline at end of file Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Descriptor.java =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Descriptor.java (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Descriptor.java (revision 2) @@ -0,0 +1,59 @@ +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer
+ *
+ * http://libusbjava.sourceforge.net
+ * This library is covered by the LGPL, read LGPL.txt for details.
+ */
+package ch.ntb.usb;
+
+/**
+ * Common USB descriptor values.
+ * + */ +public class Usb_Descriptor { + + /** + * Descriptor types ({@link #bDescriptorType}). + */ + public static final int USB_DT_DEVICE = 0x01, USB_DT_CONFIG = 0x02, + USB_DT_STRING = 0x03, USB_DT_INTERFACE = 0x04, + USB_DT_ENDPOINT = 0x05; + + /** + * Descriptor types ({@link #bDescriptorType}). + */ + public static final int USB_DT_HID = 0x21, USB_DT_REPORT = 0x22, + USB_DT_PHYSICAL = 0x23, USB_DT_HUB = 0x29; + + /** + * Descriptor sizes per descriptor type ({@link #bLength}). + */ + public static final int USB_DT_DEVICE_SIZE = 18, USB_DT_CONFIG_SIZE = 9, + USB_DT_INTERFACE_SIZE = 9, USB_DT_ENDPOINT_SIZE = 7, + USB_DT_ENDPOINT_AUDIO_SIZE = 9 /* Audio extension */, + USB_DT_HUB_NONVAR_SIZE = 7; + + private byte bLength; + + private byte bDescriptorType; + + /** + * Get the type of this descriptor.
+ * + * @return the type of this descriptor + */ + public byte getBDescriptorType() { + return bDescriptorType; + } + + /** + * Get the size of this descriptor in bytes.
+ * + * @return the size of this descriptor in bytes + */ + public byte getBLength() { + return bLength; + } + +} Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Endpoint_Descriptor.java =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Endpoint_Descriptor.java (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Endpoint_Descriptor.java (revision 2) @@ -0,0 +1,156 @@ +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer
+ *
+ * http://libusbjava.sourceforge.net
+ * This library is covered by the LGPL, read LGPL.txt for details.
+ */
+package ch.ntb.usb;
+
+/**
+ * Represents the descriptor of an USB endpoint.
+ * Endpoint descriptors are used to describe endpoints other than endpoint zero. + * Endpoint zero is always assumed to be a control endpoint and is configured + * before any descriptors are even requested. The host will use the information + * returned from these descriptors to determine the bandwidth requirements of + * the bus.
+ *
+ * The length of the configuration descriptor is + * {@link ch.ntb.usb.Usb_Descriptor#USB_DT_ENDPOINT_SIZE} and the type is + * {@link ch.ntb.usb.Usb_Descriptor#USB_DT_ENDPOINT}. + * + */ +public class Usb_Endpoint_Descriptor extends Usb_Descriptor { + + /** + * Maximum number of endpoints + */ + public static final int USB_MAXENDPOINTS = 32; + + /** + * Endpoint address mask (in bEndpointAddress). + */ + public static final int USB_ENDPOINT_ADDRESS_MASK = 0x0f, + USB_ENDPOINT_DIR_MASK = 0x80; + + /** + * Endpoint type mask (in bmAttributes). + */ + public static final int USB_ENDPOINT_TYPE_MASK = 0x03; + + /** + * Possible endpoint types (in bmAttributes). + */ + public static final int USB_ENDPOINT_TYPE_CONTROL = 0, + USB_ENDPOINT_TYPE_ISOCHRONOUS = 1, USB_ENDPOINT_TYPE_BULK = 2, + USB_ENDPOINT_TYPE_INTERRUPT = 3; + + private byte bEndpointAddress; + + private byte bmAttributes; + + private short wMaxPacketSize; + + private byte bInterval; + + private byte bRefresh; + + private byte bSynchAddress; + + private byte[] extra; /* Extra descriptors */ + + private int extralen; + + /** + * Returns the endpoint address.
+ *
+ * Bits 3..0: Endpoint number
+ * Bits 6..4: Reserved. Set to zero
+ * Bit 7: Direction. 0 = Out, 1 = In (ignored for control endpoints)
+ * + * @return the endpoint address + */ + public byte getBEndpointAddress() { + return bEndpointAddress; + } + + /** + * Returns the intervall for polling endpoint data transfers.
+ * Value in frame counts. Ignored for Bulk & Control eEndpoints. Isochronous + * endpoints must equal 1 and field may range from 1 to 255 for interrupt + * endpoints. + * + * @return the intervall for polling endpoint data transfers + */ + public byte getBInterval() { + return bInterval; + } + + /** + * Returns the attributes of this endpoint.
+ * + * Bits 1..0: Transfer Type (see USB_ENDPOINT_TYPE_XXX).
+ * Bits 7..2: Reserved.
+ * + *
+ * + * @return null or a byte array with the extra descriptor data + */ + public byte[] getExtra() { + return extra; + } + + /** + * Returns the number of bytes of the extra descriptor.
+ * + * @return the number of bytes of the extra descriptor + */ + public int getExtralen() { + return extralen; + } + + /** + * Returns the maximum packet size of this endpoint is capable of sending or + * receiving.
+ * + * @return the maximum packet size + */ + public short getWMaxPacketSize() { + return wMaxPacketSize; + } + + @Override + public String toString() { + return "Usb_Endpoint_Descriptor bEndpointAddress: 0x" + + Integer.toHexString(bEndpointAddress & 0xFF); + } +} Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/USB.java =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/USB.java (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/USB.java (revision 2) @@ -0,0 +1,271 @@ +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer
+ *
+ * http://libusbjava.sourceforge.net
+ * This library is covered by the LGPL, read LGPL.txt for details.
+ */
+package ch.ntb.usb;
+
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.logging.Logger;
+
+import ch.ntb.usb.logger.LogUtil;
+
+/**
+ * This class manages all USB devices and defines some USB specific constants.
+ * + */ +public class USB { + + // Standard requests (USB spec 9.4) + /** + * This request returns status for the specified recipient (USB spec 9.4.5). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_GET_STATUS = 0x00; + /** + * This request is used to clear or disable a specific feature (USB spec + * 9.4.1). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_CLEAR_FEATURE = 0x01; + // 0x02 is reserved + /** + * This request is used to set or enable a specific feature (USB spec + * 9.4.9). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_SET_FEATURE = 0x03; + // 0x04 is reserved + /** + * This request sets the device address for all future device accesses (USB + * spec 9.4.6). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_SET_ADDRESS = 0x05; + /** + * This request returns the specified descriptor if the descriptor exists + * (USB spec 9.4.3). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_GET_DESCRIPTOR = 0x06; + /** + * This request is optional and may be used to update existing descriptors + * or new descriptors may be added (USB spec 9.4.8). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_SET_DESCRIPTOR = 0x07; + /** + * This request returns the current device configuration value (USB spec + * 9.4.2). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_GET_CONFIGURATION = 0x08; + /** + * This request sets the device configuration (USB spec 9.4.7). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_SET_CONFIGURATION = 0x09; + /** + * This request returns the selected alternate setting for the specified + * interface (USB spec 9.4.4). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_GET_INTERFACE = 0x0A; + /** + * This request allows the host to select an alternate setting for the + * specified interface (USB spec 9.4.10). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_SET_INTERFACE = 0x0B; + /** + * This request is used to set and then report an endpoint’s synchronization + * frame (USB spec 9.4.11). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_SYNCH_FRAME = 0x0C; + + // data transfer direction (USB spec 9.3) + /** + * Identifies the direction of data transfer in the second phase of the + * control transfer.
+ * The state of the Direction bit is ignored if the wLength field is zero, + * signifying there is no Data stage.
+ * Specifies bit 7 of bmRequestType. + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_TYPE_DIR_HOST_TO_DEVICE = (0x00 << 7), + REQ_TYPE_DIR_DEVICE_TO_HOST = (0x01 << 7); + + // request types (USB spec 9.3) + /** + * Specifies the type of the request.
+ * Specifies bits 6..5 of bmRequestType. + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_TYPE_TYPE_STANDARD = (0x00 << 5), + REQ_TYPE_TYPE_CLASS = (0x01 << 5), + REQ_TYPE_TYPE_VENDOR = (0x02 << 5), + REQ_TYPE_TYPE_RESERVED = (0x03 << 5); + + // request recipient (USB spec 9.3) + /** + * Specifies the intended recipient of the request.
+ * Requests may be directed to the device, an interface on the device, or a + * specific endpoint on a device. When an interface or endpoint is + * specified, the wIndex field identifies the interface or endpoint.
+ * Specifies bits 4..0 of bmRequestType. + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_TYPE_RECIP_DEVICE = 0x00, + REQ_TYPE_RECIP_INTERFACE = 0x01, REQ_TYPE_RECIP_ENDPOINT = 0x02, + REQ_TYPE_RECIP_OTHER = 0x03; + + /** + * The maximum packet size of a bulk transfer when operating in highspeed + * (480 MB/s) mode. + */ + public static int HIGHSPEED_MAX_BULK_PACKET_SIZE = 512; + + /** + * The maximum packet size of a bulk transfer when operating in fullspeed + * (12 MB/s) mode. + */ + public static int FULLSPEED_MAX_BULK_PACKET_SIZE = 64; + + private static final Logger logger = LogUtil.getLogger("ch.ntb.usb"); + + private static LinkedList devices = new LinkedList();
+
+ private static boolean initUSBDone = false;
+
+ /**
+ * Create a new device an register it in a device queue. If the device is
+ * already registered, a reference to it will be returned.
+ * + * @param idVendor + * the vendor id of the USB device + * @param idProduct + * the product id of the USB device + * @param filename + * an optional filename which can be used to distinguish multiple + * devices with the same vendor and product id. + * @return a newly created device or an already registered device + */ + public static Device getDevice(short idVendor, short idProduct, + String filename) { + + // check if this device is already registered + Device dev = getRegisteredDevice(idVendor, idProduct, filename); + if (dev != null) { + logger.info("return already registered device"); + return dev; + } + dev = new Device(idVendor, idProduct, filename); + logger.info("create new device"); + devices.add(dev); + return dev; + } + + /** + * See {@link #getDevice(short, short, String)}. The parameter + *
+ * + * @param idVendor + * the vendor id of the USB device + * @param idProduct + * the product id of the USB device + * @param filename + * an optional filename which can be used to distinguish multiple + * devices with the same vendor and product id. + * @return the device or null + */ + private static Device getRegisteredDevice(short idVendor, short idProduct, + String filename) { + for (Iterator iter = devices.iterator(); iter.hasNext();) {
+ Device dev = iter.next();
+ if (filename != null && dev.getFilename() != null
+ && filename.compareTo(dev.getFilename()) == 0
+ && dev.getIdVendor() == idVendor
+ && dev.getIdProduct() == idProduct) {
+ return dev;
+ } else if (dev.getIdVendor() == idVendor
+ && dev.getIdProduct() == idProduct) {
+ return dev;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns the root {@link Usb_Bus} element.
+ *
+ * @return the root {@link Usb_Bus} element
+ * @throws USBException
+ */
+ public static Usb_Bus getBus() throws USBException {
+ if (!initUSBDone) {
+ init();
+ }
+ LibusbJava.usb_find_busses();
+ LibusbJava.usb_find_devices();
+
+ Usb_Bus bus = LibusbJava.usb_get_busses();
+ if (bus == null) {
+ throw new USBException("LibusbJava.usb_get_busses(): "
+ + LibusbJava.usb_strerror());
+ }
+ return bus;
+ }
+
+ /**
+ * Explicitly calls {@link LibusbJava#usb_init()}. Note that you don't need
+ * to call this procedure as it is called implicitly when creating a new
+ * device with {@link USB#getDevice(short, short, String)}.
+ */
+ public static void init() {
+ LibusbJava.usb_init();
+ initUSBDone = true;
+ }
+}
Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/LibLoader.java
===================================================================
--- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/LibLoader.java (nonexistent)
+++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/LibLoader.java (revision 2)
@@ -0,0 +1,85 @@
+/*
+ * library loader with the ability to load libraries as system resource (e.g. form the current .jar file)
+ * Copyright (c) 2007-2009, ZTEX e.K.
+ * http://www.ztex.de
+ *
+ * This library is covered by the LGPL, read LGPL.txt for details.
+ */
+
+package ch.ntb.usb;
+
+import java.io.*;
+
+/**
+ * This class allows to load libraries in the normal way or as a system resource.
+ * See below for a further description.
+ * + * @author Stefan Ziegenbalg + * + */ +public class LibLoader { + +/** + * Loads a library. This is done in three steps.
+ * 1. The library is tried to be load from the path list specified by the java.library.path proterty.
+ * 2. The library is tried to be load from the currrent directory.
+ * 3. The library is searched as a system ressource (e.g. in the current .jar file), + * copied to te temporary directory and loaded from there. Afterwards the temporary library is deleted. + * The copying is necessary because libraries cant be loeaded directly from .jar files.
+ * + * @param libName Library name (e.g. usbJava) + * + * @throws UnsatisfiedLinkError + * + */ + public static void load( String libName ) { + +// Step 1: Normal way + try { + System.loadLibrary( libName ); + } + catch ( Throwable e1 ) { + +// Step 2: From the current directory + String basename = System.mapLibraryName( libName ); + try { + System.load( System.getProperty("user.dir") + System.getProperty("file.separator") + basename ); + } + catch ( Throwable e2 ) { + +// Step 2: As system ressource + String libFileName = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + basename; + try { + InputStream inputStream = ClassLoader.getSystemResourceAsStream( basename ); + if ( inputStream == null ) { + throw new Exception(); + } + File libFile = new File( libFileName ); + + FileOutputStream outputStream = new FileOutputStream( libFile ); + + byte[] buf = new byte[65536]; + int bytesRead = -1; + while ( (bytesRead = inputStream.read(buf)) > 0 ) { + outputStream.write(buf, 0, bytesRead); + } + outputStream.close(); + inputStream.close(); + + System.load( libFileName ); + + try { + libFile.delete(); + } + catch (Exception e3) { +// System.err.println( "Warning: Cannot delete temporary library file `" + libFileName + "'" ); + } + } + catch (Exception e3) { + throw new UnsatisfiedLinkError ("Library `"+basename+"' cannot be loaded as system resource, from current directory or from java.library.path (java.library.path=" + System.getProperty("java.library.path")+")" ); + } + } + } + } + +} Index: usb_fpga_1_2/trunk/libusbJava-src/Makefile =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/Makefile (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/Makefile (revision 2) @@ -0,0 +1,61 @@ +# Makefile for libusbJava, a Java libusb wrapper +# Copyright (C) 2009 ZTEX e.K. +# http://www.ztex.de +# +# This Makefile ia a part of the reorganized version of the libusbJava source tree +# with proper makefiles. (SVN version of Apr. 6, 2009). +# +# Please visit http://libusbjava.sourceforge.net for more information about the +# original project. + +######################### +# Configuration section # +######################### + +# $(JAVAPREFIX)/include should contain jni.h +JAVAPREFIX=/usr/local/java + +############################### +# this should not be modified # +############################### +GCC=gcc +JAVAC=javac +RM=rm -f +INSTALL=install +INSTALLDIR=$(INSTALL) -d +INSTALLEXE=$(INSTALL) -m 0755 +INSTALLFILE=$(INSTALL) -m 0644 +LIBSRCS=LibusbJava.c +LIBEXTRADEPS=LibusbJava.h +JAVASRCS=$(shell echo ch/ntb/usb/*.java) $(shell echo ch/ntb/usb/logger/*.java) + +LIBTARGET=libusbJava.so +LIBLIBS=-lusb +LIBINCS=-I $(JAVAPREFIX)/include -I $(JAVAPREFIX)/include/linux + +.PHONY: all libs classes install2 clean distclean + +all: libs classes + +classes: classes.made + +libs: $(LIBTARGET) + +$(LIBTARGET): $(LIBSRCS) $(LIBEXTRADEPS) + $(GCC) -shared -std=c99 -Wall -Wl,-static,-soname,$(LIBTARGET) $(LIBINCS) -static $(LIBSRCS) -o $(LIBTARGET) $(LIBLIBS) + +classes.made: $(JAVASRCS) + $(JAVAC) $(JAVASRCS) + echo > classes.made + +install2: all + $(INSTALLDIR) ../libusbJava/ch/ntb/usb/logger + $(INSTALLFILE) $(LIBTARGET) ../libusbJava + $(INSTALLFILE) ch/ntb/usb/*.class ../libusbJava/ch/ntb/usb + $(INSTALLFILE) ch/ntb/usb/logger/*.class ../libusbJava/ch/ntb/usb/logger + +clean: + $(RM) *.o + +distclean: + $(RM) $(LIBTARGET) ch/ntb/usb/*.class ch/ntb/usb/logger/*.class classes.made Index: usb_fpga_1_2/trunk/libusbJava-src/Readme =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/Readme (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/Readme (revision 2) @@ -0,0 +1,6 @@ +This is a reorganized version of libusbJava source tree with proper makefiles. +(SVN version of Apr. 6, 2009). + +Please visit http://libusbjava.sourceforge.net for more information about the +original project. + Index: usb_fpga_1_2/trunk/bin/bmpsdcc.sh =================================================================== --- usb_fpga_1_2/trunk/bin/bmpsdcc.sh (nonexistent) +++ usb_fpga_1_2/trunk/bin/bmpsdcc.sh (revision 2) @@ -0,0 +1,67 @@ +if [ "$1" = "" ]; then + echo "Usage: $0 "
+ exit 1
+fi
+
+exe=""
+if [ "$WINDIR" != "" ]; then
+ exe=".exe"
+fi
+
+BINDIR=`dirname $0`
+BMP=bmp
+if [ -x "$BINDIR/bmp$exe" ]; then
+ BMP="$BINDIR/bmp$exe"
+fi
+
+if [ -f "$BINDIR/peeph.def" ]; then
+ PEEPH="--peep-file $BINDIR/peeph.def"
+fi
+
+
+inp="$1"
+if [ ! -f "$inp" -a -f "$inp.c" ]; then
+ inp="$1.c"
+fi
+base=${inp%*.c}
+
+if [ ! -f "$inp" ]; then
+ echo "File not found: $inp"
+ exit 2
+fi
+
+bytePad=""
+while true; do
+ if [ "$LINEINFO" = "no" ]; then
+ li='//line %2 "%1"'
+ else
+ li='#line %2 "%1"'
+ fi
+ $BMP -c -l "$li" $2 $bytePad $inp -o $base.tmp.c
+ ec="$?"
+ if [ "$ec" != 0 ]; then
+ exit $ec
+ fi
+
+ sdcc -mmcs51 --code-loc 0x0200 --code-size 0x2e00 --xram-loc 0x3200 --xram-size 0x1000 --iram-size 256 $PEEPH $3 $base.tmp.c -o $base.ihx
+ ec="$?"
+ if [ "$ec" != 0 ]; then
+ exit $ec
+ fi
+
+ addr=`grep ".*:.* _DeviceDescriptor" $base.map | (
+ read a b
+ echo 0x${a#*:}
+ )`
+ echo "Addr=$addr"
+ if [ $((addr & 1)) = "0" ]; then
+ exit 0
+ else
+ if [ "$bytePad" != "" ]; then
+ echo "USB Descriptors not word aligned, -DPAD_BYTE has no effect"
+ exit 3
+ else
+ bytePad="-D PAD_BYTE"
+ fi
+ fi
+done
Related Resources
+ +For more information about this project visit +http://libusbjava.sourceforge.net +. + + + Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Device.java =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Device.java (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Device.java (revision 2) @@ -0,0 +1,763 @@ +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer+ * To get an instance of an USB device use
USB.getDevice(...)
.
+ *
+ */
+public class Device {
+
+ private static final Logger logger = LogUtil.getLogger("ch.ntb.usb");
+
+ private int maxPacketSize;
+
+ /**
+ * Mandatory identification values for the device.
+ */
+ private int idVendor, idProduct;
+
+ /**
+ * Optional identification value for the device (e.g. if there are multiple
+ * devices with the same vendor and product id).
+ */
+ private String filename;
+
+ private int dev_configuration, dev_interface, dev_altinterface;
+
+ private int usbDevHandle;
+
+ private boolean resetOnFirstOpen, resetDone;
+
+ private int resetTimeout = 2000;
+
+ private Usb_Device dev;
+
+ protected Device(short idVendor, short idProduct) {
+ resetOnFirstOpen = false;
+ resetDone = false;
+ maxPacketSize = -1;
+ this.idVendor = idVendor;
+ this.idProduct = idProduct;
+ this.filename = null;
+ }
+
+ protected Device(short idVendor, short idProduct, String filename) {
+ resetOnFirstOpen = false;
+ resetDone = false;
+ maxPacketSize = -1;
+ this.idVendor = idVendor;
+ this.idProduct = idProduct;
+ this.filename = filename;
+ }
+
+ private void updateMaxPacketSize(Usb_Device device) throws USBException {
+ maxPacketSize = -1;
+ Usb_Config_Descriptor[] confDesc = device.getConfig();
+ for (int i = 0; i < confDesc.length; i++) {
+ Usb_Interface[] int_ = confDesc[i].getInterface();
+ for (int j = 0; j < int_.length; j++) {
+ Usb_Interface_Descriptor[] intDesc = int_[j].getAltsetting();
+ for (int k = 0; k < intDesc.length; k++) {
+ Usb_Endpoint_Descriptor[] epDesc = intDesc[k].getEndpoint();
+ for (int l = 0; l < epDesc.length; l++) {
+ maxPacketSize = Math.max(epDesc[l].getWMaxPacketSize(),
+ maxPacketSize);
+ }
+ }
+ }
+ }
+ if (maxPacketSize <= 0) {
+ throw new USBException(
+ "No USB endpoints found. Check the device configuration");
+ }
+ }
+
+ /**
+ * Initializes the device. The parameters idVendor
and
+ * idProduct
are mandatory. The parameter
+ * filename
is optional.
+ */
+ private Usb_Device initDevice(int idVendorParam, int idProductParam,
+ String filename) throws USBException {
+ Usb_Bus bus = USB.getBus();
+
+ Usb_Device device = null;
+ // search for device
+ while (bus != null) {
+ device = bus.getDevices();
+ while (device != null) {
+ Usb_Device_Descriptor devDesc = device.getDescriptor();
+ if (filename != null
+ && filename.compareTo(device.getFilename()) == 0
+ && devDesc.getIdVendor() == idVendorParam
+ && devDesc.getIdProduct() == idProductParam) {
+ // idVendor, idProduct and filename
+ logger.info("Device found: " + device.getFilename());
+ updateMaxPacketSize(device);
+ return device;
+ } else if (devDesc.getIdVendor() == idVendorParam
+ && devDesc.getIdProduct() == idProductParam) {
+ // only idVendor and idProduct
+ logger.info("Device found: " + device.getFilename());
+ updateMaxPacketSize(device);
+ return device;
+ }
+ device = device.getNext();
+ }
+ bus = bus.getNext();
+ }
+ return null;
+ }
+
+ /**
+ * Updates the device and descriptor information from the bus.+ * The descriptors can be read with {@link #getDeviceDescriptor()} and + * {@link #getConfigDescriptors()}. + * + * @throws USBException + */ + public void updateDescriptors() throws USBException { + dev = initDevice(idVendor, idProduct, filename); + } + + /** + * Returns the device descriptor associated with this device.
+ * The descriptor is updated by calling {@link #updateDescriptors()} or + * {@link #open(int, int, int)}. + * + * @return the device descriptor associated with this device or + *
null
+ */
+ public Usb_Device_Descriptor getDeviceDescriptor() {
+ if (dev == null) {
+ return null;
+ }
+ return dev.getDescriptor();
+ }
+
+ /**
+ * Returns the configuration descriptors associated with this device.+ * The descriptors are updated by calling {@link #updateDescriptors()} or + * {@link #open(int, int, int)}. + * + * @return the configuration descriptors associated with this device or + *
null
+ */
+ public Usb_Config_Descriptor[] getConfigDescriptors() {
+ if (dev == null) {
+ return null;
+ }
+ return dev.getConfig();
+ }
+
+ /**
+ * Opens the device and claims the specified configuration, interface and
+ * altinterface.+ * First the bus is enumerated. If the device is found its descriptors are + * read and the
maxPacketSize
value is updated. If no
+ * endpoints are found in the descriptors an exception is thrown.
+ *
+ * @param configuration
+ * the configuration, see
+ * {@link Usb_Config_Descriptor#getBConfigurationValue()}
+ * @param interface_
+ * the interface, see
+ * {@link Usb_Interface_Descriptor#getBInterfaceNumber()}
+ * @param altinterface
+ * the alternate interface, see
+ * {@link Usb_Interface_Descriptor#getBAlternateSetting()}. If
+ * no alternate interface must be set -1 can be used.
+ * @throws USBException
+ */
+ public void open(int configuration, int interface_, int altinterface)
+ throws USBException {
+ this.dev_configuration = configuration;
+ this.dev_interface = interface_;
+ this.dev_altinterface = altinterface;
+
+ if (usbDevHandle != 0) {
+ throw new USBException("device opened, close or reset first");
+ }
+
+ dev = initDevice(idVendor, idProduct, filename);
+
+ if (dev != null) {
+ int res = LibusbJava.usb_open(dev);
+ if (res == 0) {
+ throw new USBException("LibusbJava.usb_open: "
+ + LibusbJava.usb_strerror());
+ }
+ usbDevHandle = res;
+ }
+
+ if (dev == null || usbDevHandle == 0) {
+ throw new USBException("USB device with idVendor 0x"
+ + Integer.toHexString(idVendor & 0xFFFF)
+ + " and idProduct 0x"
+ + Integer.toHexString(idProduct & 0xFFFF) + " not found");
+ }
+ claim_interface(usbDevHandle, configuration, interface_, altinterface);
+ if (resetOnFirstOpen & !resetDone) {
+ logger.info("reset on first open");
+ resetDone = true;
+ reset();
+ try {
+ Thread.sleep(resetTimeout);
+ } catch (InterruptedException e) {
+ //
+ }
+ open(configuration, interface_, altinterface);
+ }
+ }
+
+ /**
+ * Release the claimed interface and close the opened device.+ * + * @throws USBException + */ + public void close() throws USBException { + if (usbDevHandle == 0) { + throw new USBException("invalid device handle"); + } + release_interface(usbDevHandle, dev_interface); + if (LibusbJava.usb_close(usbDevHandle) < 0) { + usbDevHandle = 0; + throw new USBException("LibusbJava.usb_close: " + + LibusbJava.usb_strerror()); + } + usbDevHandle = 0; + maxPacketSize = -1; + logger.info("device closed"); + } + + /** + * Sends an USB reset to the device. The device handle will no longer be + * valid. To use the device again, {@link #open(int, int, int)} must be + * called. + * + * @throws USBException + */ + public void reset() throws USBException { + if (usbDevHandle == 0) { + throw new USBException("invalid device handle"); + } + release_interface(usbDevHandle, dev_interface); + if (LibusbJava.usb_reset(usbDevHandle) < 0) { + usbDevHandle = 0; + throw new USBException("LibusbJava.usb_reset: " + + LibusbJava.usb_strerror()); + } + usbDevHandle = 0; + logger.info("device reset"); + } + + /** + * Write data to the device using a bulk transfer.
+ * + * @param out_ep_address + * endpoint address to write to + * @param data + * data to write to this endpoint + * @param size + * size of the data + * @param timeout + * amount of time in ms the device will try to send the data + * until a timeout exception is thrown + * @param reopenOnTimeout + * if set to true, the device will try to open the connection and + * send the data again before a timeout exception is thrown + * @return the actual number of bytes written + * @throws USBException + */ + public int writeBulk(int out_ep_address, byte[] data, int size, + int timeout, boolean reopenOnTimeout) throws USBException { + if (usbDevHandle == 0) { + throw new USBException("invalid device handle"); + } + if (data == null) { + throw new USBException("data must not be null"); + } + if (size <= 0 || size > data.length) { + throw new ArrayIndexOutOfBoundsException("invalid size: " + size); + } + int lenWritten = LibusbJava.usb_bulk_write(usbDevHandle, + out_ep_address, data, size, timeout); + if (lenWritten < 0) { + if (lenWritten == LibusbJava.ERROR_TIMEDOUT) { + // try to reopen the device and send the data again + if (reopenOnTimeout) { + logger.info("try to reopen"); + reset(); + open(dev_configuration, dev_interface, dev_altinterface); + return writeBulk(out_ep_address, data, size, timeout, false); + } + throw new USBTimeoutException("LibusbJava.usb_bulk_write: " + + LibusbJava.usb_strerror()); + } + throw new USBException("LibusbJava.usb_bulk_write: " + + LibusbJava.usb_strerror()); + } + + logger.info("length written: " + lenWritten); + if (logger.isLoggable(Level.FINEST)) { + StringBuffer sb = new StringBuffer("bulkwrite, ep 0x" + + Integer.toHexString(out_ep_address) + ": " + lenWritten + + " Bytes sent: "); + for (int i = 0; i < lenWritten; i++) { + sb.append("0x" + String.format("%1$02X", data[i]) + " "); + } + logger.info(sb.toString()); + } + return lenWritten; + } + + /** + * Read data from the device using a bulk transfer.
+ * + * @param in_ep_address + * endpoint address to read from + * @param data + * data buffer for the data to be read + * @param size + * the maximum requested data size + * @param timeout + * amount of time in ms the device will try to receive data until + * a timeout exception is thrown + * @param reopenOnTimeout + * if set to true, the device will try to open the connection and + * receive the data again before a timeout exception is thrown + * @return the actual number of bytes read + * @throws USBException + */ + public int readBulk(int in_ep_address, byte[] data, int size, int timeout, + boolean reopenOnTimeout) throws USBException { + if (usbDevHandle == 0) { + throw new USBException("invalid device handle"); + } + if (data == null) { + throw new USBException("data must not be null"); + } + if (size <= 0 || size > data.length) { + throw new ArrayIndexOutOfBoundsException("invalid size: " + size); + } + int lenRead = LibusbJava.usb_bulk_read(usbDevHandle, in_ep_address, + data, size, timeout); + if (lenRead < 0) { + if (lenRead == LibusbJava.ERROR_TIMEDOUT) { + // try to reopen the device and send the data again + if (reopenOnTimeout) { + logger.info("try to reopen"); + reset(); + open(dev_configuration, dev_interface, dev_altinterface); + return readBulk(in_ep_address, data, size, timeout, false); + } + throw new USBTimeoutException("LibusbJava.usb_bulk_read: " + + LibusbJava.usb_strerror()); + } + throw new USBException("LibusbJava.usb_bulk_read: " + + LibusbJava.usb_strerror()); + } + + logger.info("length read: " + lenRead); + if (logger.isLoggable(Level.FINEST)) { + StringBuffer sb = new StringBuffer("bulkread, ep 0x" + + Integer.toHexString(in_ep_address) + ": " + lenRead + + " Bytes received: "); + for (int i = 0; i < lenRead; i++) { + sb.append("0x" + String.format("%1$02X", data[i]) + " "); + } + logger.info(sb.toString()); + } + return lenRead; + } + + /** + * Write data to the device using a interrupt transfer.
+ * + * @param out_ep_address + * endpoint address to write to + * @param data + * data to write to this endpoint + * @param size + * size of the data + * @param timeout + * amount of time in ms the device will try to send the data + * until a timeout exception is thrown + * @param reopenOnTimeout + * if set to true, the device will try to open the connection and + * send the data again before a timeout exception is thrown + * @return the actual number of bytes written + * @throws USBException + */ + public int writeInterrupt(int out_ep_address, byte[] data, int size, + int timeout, boolean reopenOnTimeout) throws USBException { + if (usbDevHandle == 0) { + throw new USBException("invalid device handle"); + } + if (data == null) { + throw new USBException("data must not be null"); + } + if (size <= 0 || size > data.length) { + throw new ArrayIndexOutOfBoundsException("invalid size: " + size); + } + int lenWritten = LibusbJava.usb_interrupt_write(usbDevHandle, + out_ep_address, data, size, timeout); + if (lenWritten < 0) { + if (lenWritten == LibusbJava.ERROR_TIMEDOUT) { + // try to reopen the device and send the data again + if (reopenOnTimeout) { + logger.info("try to reopen"); + reset(); + open(dev_configuration, dev_interface, dev_altinterface); + return writeInterrupt(out_ep_address, data, size, timeout, + false); + } + throw new USBTimeoutException( + "LibusbJava.usb_interrupt_write: " + + LibusbJava.usb_strerror()); + } + throw new USBException("LibusbJava.usb_interrupt_write: " + + LibusbJava.usb_strerror()); + } + + logger.info("length written: " + lenWritten); + if (logger.isLoggable(Level.FINEST)) { + StringBuffer sb = new StringBuffer("interruptwrite, ep 0x" + + Integer.toHexString(out_ep_address) + ": " + lenWritten + + " Bytes sent: "); + for (int i = 0; i < lenWritten; i++) { + sb.append("0x" + String.format("%1$02X", data[i]) + " "); + } + logger.info(sb.toString()); + } + return lenWritten; + } + + /** + * Read data from the device using a interrupt transfer.
+ * + * @param in_ep_address + * endpoint address to read from + * @param data + * data buffer for the data to be read + * @param size + * the maximum requested data size + * @param timeout + * amount of time in ms the device will try to receive data until + * a timeout exception is thrown + * @param reopenOnTimeout + * if set to true, the device will try to open the connection and + * receive the data again before a timeout exception is thrown + * @return the actual number of bytes read + * @throws USBException + */ + public int readInterrupt(int in_ep_address, byte[] data, int size, + int timeout, boolean reopenOnTimeout) throws USBException { + if (usbDevHandle == 0) { + throw new USBException("invalid device handle"); + } + if (data == null) { + throw new USBException("data must not be null"); + } + if (size <= 0 || size > data.length) { + throw new ArrayIndexOutOfBoundsException("invalid size: " + size); + } + int lenRead = LibusbJava.usb_interrupt_read(usbDevHandle, + in_ep_address, data, size, timeout); + if (lenRead < 0) { + if (lenRead == LibusbJava.ERROR_TIMEDOUT) { + // try to reopen the device and send the data again + if (reopenOnTimeout) { + logger.info("try to reopen"); + reset(); + open(dev_configuration, dev_interface, dev_altinterface); + return readInterrupt(in_ep_address, data, size, timeout, + false); + } + throw new USBTimeoutException("LibusbJava.usb_interrupt_read: " + + LibusbJava.usb_strerror()); + } + throw new USBException("LibusbJava.usb_interrupt_read: " + + LibusbJava.usb_strerror()); + } + + logger.info("length read: " + lenRead); + if (logger.isLoggable(Level.FINEST)) { + StringBuffer sb = new StringBuffer("interrupt, ep 0x" + + Integer.toHexString(in_ep_address) + ": " + lenRead + + " Bytes received: "); + for (int i = 0; i < lenRead; i++) { + sb.append("0x" + String.format("%1$02X", data[i]) + " "); + } + logger.info(sb.toString()); + } + return lenRead; + } + + /** + * Performs a control request to the default control pipe on a device.
+ * The parameters mirror the types of the same name in the USB + * specification. + * + * @param requestType + * USB device request type (USB specification 9.3, + * bmRequestType). Use constants from {@link ch.ntb.usb.USB} + * (REQ_TYPE_xxx). + * @param request + * specific request (USB specification 9.4, bRequest). Use + * constants from {@link ch.ntb.usb.USB} (REQ_xxx). + * @param value + * field that varies according to request (USB specification 9.4, + * wValue) + * @param index + * field that varies according to request (USB specification 9.4, + * wIndex) + * @param data + * the send/receive buffer + * @param size + * the buffer size. 0 is a valid value, but there must still be a + * dummy data buffer provided. + * @param timeout + * amount of time in ms the device will try to send/receive data + * until a timeout exception is thrown + * @param reopenOnTimeout + * if set to true, the device will try to open the connection and + * send/receive the data again before a timeout exception is + * thrown + * @return the number of bytes written/read + * @throws USBException + */ + public int controlMsg(int requestType, int request, int value, int index, + byte[] data, int size, int timeout, boolean reopenOnTimeout) + throws USBException { + if (usbDevHandle == 0) { + throw new USBException("invalid device handle"); + } + if (data == null) { + throw new USBException("data must not be null"); + } + if (size < 0 || size > data.length) { + throw new ArrayIndexOutOfBoundsException("invalid size: " + size); + } + int len = LibusbJava.usb_control_msg(usbDevHandle, requestType, + request, value, index, data, size, timeout); + if (len < 0) { + if (len == LibusbJava.ERROR_TIMEDOUT) { + // try to reopen the device and send the data again + if (reopenOnTimeout) { + logger.info("try to reopen"); + reset(); + open(dev_configuration, dev_interface, dev_altinterface); + return controlMsg(requestType, request, value, index, data, + size, timeout, false); + } + throw new USBTimeoutException("LibusbJava.controlMsg: " + + LibusbJava.usb_strerror()); + } + throw new USBException("LibusbJava.controlMsg: " + + LibusbJava.usb_strerror()); + } + + logger.info("length read/written: " + len); + if (logger.isLoggable(Level.FINEST)) { + StringBuffer sb = new StringBuffer("controlMsg: " + len + + " Bytes received(written: "); + for (int i = 0; i < len; i++) { + sb.append("0x" + String.format("%1$02X", data[i]) + " "); + } + logger.info(sb.toString()); + } + return len; + } + + /** + * Claim an interface to send and receive USB data.
+ * + * @param usb_dev_handle + * the handle of the device (MUST BE VALID) + * @param configuration + * the configuration to use + * @param interface_ + * the interface to claim + * @param altinterface + * the alternate interface to use. If no alternate interface must + * be set -1 can be used. + * @throws USBException + * throws an USBException if the action fails + */ + private void claim_interface(int usb_dev_handle, int configuration, + int interface_, int altinterface) throws USBException { + if (LibusbJava.usb_set_configuration(usb_dev_handle, configuration) < 0) { + usbDevHandle = 0; + throw new USBException("LibusbJava.usb_set_configuration: " + + LibusbJava.usb_strerror()); + } + if (LibusbJava.usb_claim_interface(usb_dev_handle, interface_) < 0) { + usbDevHandle = 0; + throw new USBException("LibusbJava.usb_claim_interface: " + + LibusbJava.usb_strerror()); + } + if (altinterface >= 0) { + if (LibusbJava.usb_set_altinterface(usb_dev_handle, altinterface) < 0) { + try { + release_interface(usb_dev_handle, interface_); + } catch (USBException e) { + // ignore + } + usbDevHandle = 0; + throw new USBException("LibusbJava.usb_set_altinterface: " + + LibusbJava.usb_strerror()); + } + } + logger.info("interface claimed"); + } + + /** + * Release a previously claimed interface.
+ * + * @param dev_handle + * the handle of the device (MUST BE VALID) + * @param interface_ + * the interface to claim + * @throws USBException + * throws an USBException if the action fails + */ + private void release_interface(int dev_handle, int interface_) + throws USBException { + if (LibusbJava.usb_release_interface(dev_handle, interface_) < 0) { + usbDevHandle = 0; + throw new USBException("LibusbJava.usb_release_interface: " + + LibusbJava.usb_strerror()); + } + logger.info("interface released"); + } + + /** + * Returns the product ID of the device.
+ * + * @return the product ID of the device. + */ + public int getIdProduct() { + return idProduct; + } + + /** + * Returns the vendor ID of the device.
+ * + * @return the vendor ID of the device. + */ + public int getIdVendor() { + return idVendor; + } + + /** + * Returns the alternative interface.
+ * This value is only valid after opening the device. + * + * @return the alternative interface. This value is only valid after opening + * the device. + */ + public int getAltinterface() { + return dev_altinterface; + } + + /** + * Returns the current configuration used.
+ * This value is only valid after opening the device. + * + * @return the current configuration used. This value is only valid after + * opening the device. + */ + public int getConfiguration() { + return dev_configuration; + } + + /** + * Returns the current interface.
+ * This value is only valid after opening the device. + * + * @return the current interface. This value is only valid after opening the + * device. + */ + public int getInterface() { + return dev_interface; + } + + /** + * Returns the maximum packet size in bytes which is allowed to be + * transmitted at once.
+ * The value is determined by reading the endpoint descriptor(s) when + * opening the device. It is invalid before the device is opened! Note that + * if some endpoints use different packet sizes the maximum packet size is + * return. This value may be used to determine if a device is opened in + * fullspeed or highspeed mode. + * + * @return the maximum packet size + */ + public int getMaxPacketSize() { + return maxPacketSize; + } + + /** + * Check if the device is open.
+ * This checks only for a valid device handle. It doesn't check if the + * device is still attached or working. + * + * @return true if the device is open + */ + public boolean isOpen() { + return usbDevHandle != 0; + } + + /** + * If enabled, the device is reset when first opened.
+ * This will only happen once. When the application is started, the device + * state is unknown. If the device is not reset, read or write may result in + * a {@link USBTimeoutException}.
+ *
+ * This feature is disabled by default. + * + * @param enable + * true if the device should be reset when first opened + * @param timeout + * the timeout between the reset and the reopening + */ + public void setResetOnFirstOpen(boolean enable, int timeout) { + resetOnFirstOpen = enable; + resetTimeout = timeout; + } + + /** + * Returns the optional filename which is set when there are multiple + * devices with the same vendor and product id. See + * {@link USB#getDevice(short, short, String)}. Use + * {@link Usb_Device#getFilename()} to read the filename of a device. + * + * @return the filename if set or null + */ + protected String getFilename() { + return filename; + } + + /** + * Returns the Usb_Device instance associated with this device. This value + * is only valid after opening the device. + * + * @return the Usb_Device instance associated with this device. + */ + public Usb_Device getDevice() { + return dev; + } +} Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Utils.java =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Utils.java (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Utils.java (revision 2) @@ -0,0 +1,60 @@ +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer
+ * This is the root class for the representation of the libusb USB structure. + * Zero or more devices may be connected to an USB bus. + * + */ +public class Usb_Bus { + + private Usb_Bus next, prev; + + private String dirname; + + private Usb_Device devices; + + private long location; + + private Usb_Device root_dev; + + /** + * Get the first device ojects of the devices linked list.
+ * + * @return the first device ojects of the devices linked list or null + */ + public Usb_Device getDevices() { + return devices; + } + + /** + * Returns the systems String representation of the bus.
+ * + * @return the systems String representation of the bus + */ + public String getDirname() { + return dirname; + } + + /** + * Returns the next bus object.
+ * + * @return Returns the next bus object or null + */ + public Usb_Bus getNext() { + return next; + } + + /** + * Returns the previous bus object.
+ * + * @return Returns the previous bus object or null + */ + public Usb_Bus getPrev() { + return prev; + } + + /** + * Get the root device of this bus.
+ * + * @return the root device oject or null + */ + public Usb_Device getRootDev() { + return root_dev; + } + + /** + * Returns the location in the USB bus linked list.
+ * + * @return the location in the USB bus linked list + */ + public long getLocation() { + return location; + } + + @Override + public String toString() { + return "Usb_Bus " + dirname; + } +} \ No newline at end of file Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Device_Descriptor.java =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Device_Descriptor.java (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Device_Descriptor.java (revision 2) @@ -0,0 +1,190 @@ +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer
+ * A USB device can only have one device descriptor. It specifies some basic, + * yet important information about the device.
+ *
+ * The length of the device descriptor is + * {@link ch.ntb.usb.Usb_Descriptor#USB_DT_DEVICE_SIZE} and the type is + * {@link ch.ntb.usb.Usb_Descriptor#USB_DT_DEVICE}. + * + */ +public class Usb_Device_Descriptor extends Usb_Descriptor { + /** + * Device and/or interface class codes. + */ + public static final int USB_CLASS_PER_INTERFACE = 0, USB_CLASS_AUDIO = 1, + USB_CLASS_COMM = 2, USB_CLASS_HID = 3, USB_CLASS_PRINTER = 7, + USB_CLASS_MASS_STORAGE = 8, USB_CLASS_HUB = 9, USB_CLASS_DATA = 10, + USB_CLASS_VENDOR_SPEC = 0xff; + + private short bcdUSB; + + private byte bDeviceClass; + + private byte bDeviceSubClass; + + private byte bDeviceProtocol; + + private byte bMaxPacketSize0; + + private short idVendor; + + private short idProduct; + + private short bcdDevice; + + private byte iManufacturer; + + private byte iProduct; + + private byte iSerialNumber; + + private byte bNumConfigurations; + + /** + * Returns the device release number.
+ * Assigned by the manufacturer of the device. + * + * @return the device release number + */ + public short getBcdDevice() { + return bcdDevice; + } + + /** + * Returns the USB specification number to which the device complies to.
+ * This field reports the highest version of USB the device supports. The + * value is in binary coded decimal with a format of 0xJJMN where JJ is the + * major version number, M is the minor version number and N is the sub + * minor version number.
+ * Examples: USB 2.0 is reported as 0x0200, USB 1.1 as 0x0110 and USB 1.0 as + * 0x100 + * + * @return the USB specification number to which the device complies to + */ + public short getBcdUSB() { + return bcdUSB; + } + + /** + * Returns the class code (Assigned by www.usb.org)
+ * If equal to zero, each interface specifies it's own class code. If equal + * to 0xFF, the class code is vendor specified. Otherwise the field is a + * valid class code. + * + * @return the class code + */ + public byte getBDeviceClass() { + return bDeviceClass; + } + + /** + * Returns the protocol code (Assigned by www.usb.org)
+ * + * @return the protocol code + */ + public byte getBDeviceProtocol() { + return bDeviceProtocol; + } + + /** + * Returns the subclass code (Assigned by www.usb.org)
+ * + * @return the subclass code + */ + public byte getBDeviceSubClass() { + return bDeviceSubClass; + } + + /** + * Returns the maximum packet size for endpoint zero.
+ * Valid sizes are 8, 16, 32, 64. + * + * @return the maximum packet size for endpoint zero + */ + public byte getBMaxPacketSize0() { + return bMaxPacketSize0; + } + + /** + * Returns the number of possible configurations supported at its current + * speed.
+ * + * @return the number of possible configurations supported at its current + * speed + */ + public byte getBNumConfigurations() { + return bNumConfigurations; + } + + /** + * Returns the product ID (Assigned by www.usb.org)
+ * + * @return the product ID + */ + public short getIdProduct() { + return idProduct; + } + + /** + * Returns the Vendor ID (Assigned by www.usb.org)
+ * + * @return the Vendor ID + */ + public short getIdVendor() { + return idVendor; + } + + /** + * Returns the index of the manufacturer string descriptor.
+ * If this value is 0, no string descriptor is used. + * + * @return the index of the manufacturer string descriptor + */ + public byte getIManufacturer() { + return iManufacturer; + } + + /** + * Returns the index of the product string descriptor.
+ * If this value is 0, no string descriptor is used. + * + * @return the index of the product string descriptor + */ + public byte getIProduct() { + return iProduct; + } + + /** + * Returns the index of serial number string descriptor.
+ * If this value is 0, no string descriptor is used. + * + * @return the index of serial number string descriptor + */ + public byte getISerialNumber() { + return iSerialNumber; + } + + @Override + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("Usb_Device_Descriptor idVendor: 0x" + + Integer.toHexString(idVendor & 0xFFFF) + ", idProduct: 0x" + + Integer.toHexString(idProduct & 0xFFFF)); + return sb.toString(); + } +} \ No newline at end of file Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Interface_Descriptor.java =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Interface_Descriptor.java (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Interface_Descriptor.java (revision 2) @@ -0,0 +1,145 @@ +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer
+ * The interface descriptor could be seen as a header or grouping of the + * endpoints into a functional group performing a single feature of the device.
+ *
+ * The length of the interface descriptor is + * {@link ch.ntb.usb.Usb_Descriptor#USB_DT_INTERFACE_SIZE} and the type is + * {@link ch.ntb.usb.Usb_Descriptor#USB_DT_INTERFACE}. + * + */ +public class Usb_Interface_Descriptor extends Usb_Descriptor { + + /** + * Maximum number of interfaces + */ + public static final int USB_MAXINTERFACES = 32; + + private byte bInterfaceNumber; + + private byte bAlternateSetting; + + private byte bNumEndpoints; + + private byte bInterfaceClass; + + private byte bInterfaceSubClass; + + private byte bInterfaceProtocol; + + private byte iInterface; + + private Usb_Endpoint_Descriptor[] endpoint; + + private byte[] extra; /* Extra descriptors */ + + private int extralen; + + @Override + public String toString() { + return "Usb_Interface_Descriptor bNumEndpoints: 0x" + + Integer.toHexString(bNumEndpoints); + } + + /** + * Returns the value used to select the alternate setting ({@link LibusbJava#usb_set_altinterface(int, int)}).
+ * + * @return the alternate setting + */ + public byte getBAlternateSetting() { + return bAlternateSetting; + } + + /** + * Returns the class code (Assigned by www.usb.org).
+ * + * @return the class code + */ + public byte getBInterfaceClass() { + return bInterfaceClass; + } + + /** + * Returns the number (identifier) of this interface.
+ * + * @return the number (identifier) of this interface + */ + public byte getBInterfaceNumber() { + return bInterfaceNumber; + } + + /** + * Returns the protocol code (Assigned by www.usb.org).
+ * + * @return the protocol code + */ + public byte getBInterfaceProtocol() { + return bInterfaceProtocol; + } + + /** + * Returns the subclass code (Assigned by www.usb.org).
+ * + * @return the subclass code + */ + public byte getBInterfaceSubClass() { + return bInterfaceSubClass; + } + + /** + * Returns the number of endpoints used for this interface.
+ * + * @return the number of endpoints used for this interface + */ + public byte getBNumEndpoints() { + return bNumEndpoints; + } + + /** + * Returns an array of endpoint descriptors.
+ * + * @return an array of endpoint descriptors + */ + public Usb_Endpoint_Descriptor[] getEndpoint() { + return endpoint; + } + + /** + * Returns the data of extra descriptor(s) if available.
+ * + * @return null or a byte array with the extra descriptor data + */ + public byte[] getExtra() { + return extra; + } + + /** + * Returns the number of bytes of the extra descriptor.
+ * + * @return the number of bytes of the extra descriptor + */ + public int getExtralen() { + return extralen; + } + + /** + * Returns the index of the String descriptor describing this interface.
+ * + * @return the index of the String descriptor + */ + public byte getIInterface() { + return iInterface; + } +} Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/USBException.java =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/USBException.java (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/USBException.java (revision 2) @@ -0,0 +1,23 @@ +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer
+ * An USB device has one device descriptor and it may have multiple + * configuration descriptors. + * + */ +public class Usb_Device { + + private Usb_Device next, prev; + + private String filename; + + private Usb_Bus bus; + + private Usb_Device_Descriptor descriptor; + + private Usb_Config_Descriptor[] config; + + private byte devnum; + + private byte num_children; + + private Usb_Device children; + + /** + * The address of the device structure to be passed to usb_open. This value + * is used only internally so we don't use getter or setter methods. + */ + @SuppressWarnings("unused") + private long devStructAddr; + + /** + * Returns the reference to the bus to which this device is connected.
+ * + * @return the reference to the bus to which this device is connected + */ + public Usb_Bus getBus() { + return bus; + } + + /** + * Returns a reference to the first child.
+ * + * @return a reference to the first child + */ + public Usb_Device getChildren() { + return children; + } + + /** + * Returns the USB config descriptors.
+ * + * @return the USB config descriptors + */ + public Usb_Config_Descriptor[] getConfig() { + return config; + } + + /** + * Returns the USB device descriptor.
+ * + * @return the USB device descriptor + */ + public Usb_Device_Descriptor getDescriptor() { + return descriptor; + } + + /** + * Returns the number assigned to this device.
+ * + * @return the number assigned to this device + */ + public byte getDevnum() { + return devnum; + } + + /** + * Returns the systems String representation.
+ * + * @return the systems String representation + */ + public String getFilename() { + return filename; + } + + /** + * Returns the pointer to the next device.
+ * + * @return the pointer to the next device or null + */ + public Usb_Device getNext() { + return next; + } + + /** + * Returns the number of children of this device.
+ * + * @return the number of children of this device + */ + public byte getNumChildren() { + return num_children; + } + + /** + * Returns the pointer to the previous device.
+ * + * @return the pointer to the previous device or null + */ + public Usb_Device getPrev() { + return prev; + } + + @Override + public String toString() { + return "Usb_Device " + filename; + } +} \ No newline at end of file Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Interface.java =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Interface.java (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Interface.java (revision 2) @@ -0,0 +1,50 @@ +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer
+ * An interface is a group of alternate settings of a configuration.
+ * + */ +public class Usb_Interface { + + /** + * Maximal number of alternate settings + */ + public static final int USB_MAXALTSETTING = 128; /* Hard limit */ + + private Usb_Interface_Descriptor[] altsetting; + + private int num_altsetting; + + @Override + public String toString() { + return "Usb_Interface num_altsetting: 0x" + + Integer.toHexString(num_altsetting); + } + + /** + * Retuns an array of interface descriptors.
+ * + * @return an array of interface descriptors + */ + public Usb_Interface_Descriptor[] getAltsetting() { + return altsetting; + } + + /** + * Returns the number of alternate settings.
+ * + * @return the number of alternate settings + */ + public int getNumAltsetting() { + return num_altsetting; + } + +} Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Config_Descriptor.java =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Config_Descriptor.java (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Config_Descriptor.java (revision 2) @@ -0,0 +1,139 @@ +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer
+ * A USB device can have several different configuration.
+ *
+ * The length of the configuration descriptor is + * {@link ch.ntb.usb.Usb_Descriptor#USB_DT_CONFIG_SIZE} and the type is + * {@link ch.ntb.usb.Usb_Descriptor#USB_DT_CONFIG}. + * + */ +public class Usb_Config_Descriptor extends Usb_Descriptor { + + /** + * Maximum number of configurations per device + */ + public static final int USB_MAXCONFIG = 8; + + private short wTotalLength; + + private byte bNumInterfaces; + + private byte bConfigurationValue; + + private byte iConfiguration; + + private byte bmAttributes; + + private byte MaxPower; + + private Usb_Interface[] interface_; + + private byte[] extra; /* Extra descriptors */ + + private int extralen; + + /** + * Returns the value to use as an argument to select this configuration ({@link LibusbJava#usb_set_configuration(int, int)}). + * + * @return the value to use as an argument to select this configuration + */ + public byte getBConfigurationValue() { + return bConfigurationValue; + } + + /** + * Returns the power parameters for this configuration.
+ *
+ * Bit 7: Reserved, set to 1 (USB 1.0 Bus Powered)
+ * Bit 6: Self Powered
+ * Bit 5: Remote Wakeup
+ * Bit 4..0: Reserved, set to 0 + * + * @return the power parameters for this configuration + */ + public byte getBmAttributes() { + return bmAttributes; + } + + /** + * Returns the number of interfaces.
+ * + * @return the number of interfaces + */ + public byte getBNumInterfaces() { + return bNumInterfaces; + } + + /** + * Returns the data of extra descriptor(s) if available.
+ * + * @return null or a byte array with the extra descriptor data + */ + public byte[] getExtra() { + return extra; + } + + /** + * Returns the number of bytes of the extra descriptor.
+ * + * @return the number of bytes of the extra descriptor + */ + public int getExtralen() { + return extralen; + } + + /** + * Returns the index of the String descriptor describing this configuration.
+ * + * @return the index of the String descriptor + */ + public byte getIConfiguration() { + return iConfiguration; + } + + /** + * Returns the USB interface descriptors.
+ * + * @return the USB interface descriptors + */ + public Usb_Interface[] getInterface() { + return interface_; + } + + /** + * Returns the maximum power consumption in 2mA units.
+ * + * @return the maximum power consumption in 2mA units + */ + public byte getMaxPower() { + return MaxPower; + } + + /** + * Returns the total length in bytes of all descriptors.
+ * When the configuration descriptor is read, it returns the entire + * configuration hierarchy which includes all related interface and endpoint + * descriptors. The
wTotalLength
field reflects the number of
+ * bytes in the hierarchy.
+ *
+ * @return the total length in bytes of all descriptors
+ */
+ public short getWTotalLength() {
+ return wTotalLength;
+ }
+
+ @Override
+ public String toString() {
+ return "Usb_Config_Descriptor bNumInterfaces: 0x"
+ + Integer.toHexString(bNumInterfaces);
+ }
+}
\ No newline at end of file
Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/package.html
===================================================================
--- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/package.html (nonexistent)
+++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/package.html (revision 2)
@@ -0,0 +1,26 @@
+
+
+
+
+
+Includes the main classes for the Java libusb wrapper.
++LibusbJava.java +is the JNI class to the +LibusbJava.dll +. Every class starting with +Usb_ +represents a descriptor of the bus structure which is retrieved by +calling +LibusbJava.usb_get_busses() +. + +
Related Resources
+ +For more information about this project visit +http://libusbjava.sourceforge.net +. + + + Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/USBTimeoutException.java =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/USBTimeoutException.java (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/USBTimeoutException.java (revision 2) @@ -0,0 +1,21 @@ +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer+ *
+ *
Project Description
+ * Java libusb is a Java wrapper for the libusb and libusb-win32 USB library. + * + * libusb aim is to create a + * library for use by user level applications to access USB devices regardless + * of OS.+ * Libusb-win32 is a port of + * the USB library libusb to the + * Windows operating systems. The library allows user space applications to + * access any USB device on Windows in a generic way without writing any line of + * kernel driver code.
+ *
+ * The API description of this class has been copied from the libusb documentation + * and adapted where neccessary.
+ * + */ +public class LibusbJava { + + /** + * System error codes.
+ * This list is not complete! For more error codes see the file 'errorno.h' + * on your system. + */ + public static int ERROR_SUCCESS, ERROR_BAD_FILE_DESCRIPTOR, + ERROR_NO_SUCH_DEVICE_OR_ADDRESS, ERROR_BUSY, + ERROR_INVALID_PARAMETER, ERROR_TIMEDOUT, ERROR_IO_ERROR, + ERROR_NOT_ENOUGH_MEMORY;; + + /** + * Sets the debugging level of libusb.
+ * + * The range is from 0 to 255, where 0 disables debug output and 255 enables + * all output. On application start, debugging is disabled (0). + * + * @param level + * 0 to 255 + */ + public static native void usb_set_debug(int level); + + // Core + /** + * Just like the name implies,
usb_init
sets up some internal
+ * structures. usb_init
must be called before any other
+ * libusb functions.
+ */
+ public static native void usb_init();
+
+ /**
+ * usb_find_busses
will find all of the busses on the system.
+ *
+ * @return the number of changes since previous call to this function (total
+ * of new busses and busses removed).
+ */
+ public static native int usb_find_busses();
+
+ /**
+ * usb_find_devices
will find all of the devices on each bus.
+ * This should be called after usb_find_busses
.
+ *
+ * @return the number of changes since the previous call to this function
+ * (total of new device and devices removed).
+ */
+ public static native int usb_find_devices();
+
+ /**
+ * usb_get_busses
returns a tree of descriptor objects.+ * The tree represents the bus structure with devices, configurations, + * interfaces and endpoints. Note that this is only a copy. To refresh the + * information,
usb_get_busses()
must be called again.+ * The name of the objects contained in the tree is starting with + *
Usb_
.
+ *
+ * @return the structure of all busses and devices. Note:
The
+ * java objects are copies of the C structs.
+ */
+ public static native Usb_Bus usb_get_busses();
+
+ // Device Operations
+ /**
+ * usb_open
is to be used to open up a device for use.
+ * usb_open
must be called before attempting to perform any
+ * operations to the device.
+ *
+ * @param dev
+ * The device to open.
+ * @return a handle used in future communication with the device. 0 if an
+ * error has occurred.
+ */
+ public static native int usb_open(Usb_Device dev);
+
+ /**
+ * usb_close
closes a device opened with
+ * usb_open
.
+ *
+ * @param dev_handle
+ * The handle to the device.
+ * @return 0 on success or < 0 on error.
+ */
+ public static native int usb_close(int dev_handle);
+
+ /**
+ * Sets the active configuration of a device
+ *
+ * @param dev_handle
+ * The handle to the device.
+ * @param configuration
+ * The value as specified in the descriptor field
+ * bConfigurationValue.
+ * @return 0 on success or < 0 on error.
+ */
+ public static native int usb_set_configuration(int dev_handle,
+ int configuration);
+
+ /**
+ * Sets the active alternate setting of the current interface
+ *
+ * @param dev_handle
+ * The handle to the device.
+ * @param alternate
+ * The value as specified in the descriptor field
+ * bAlternateSetting.
+ * @return 0 on success or < 0 on error.
+ */
+ public static native int usb_set_altinterface(int dev_handle, int alternate);
+
+ /**
+ * Clears any halt status on an endpoint.
+ *
+ * @param dev_handle
+ * The handle to the device.
+ * @param ep
+ * The value specified in the descriptor field bEndpointAddress.
+ * @return 0 on success or < 0 on error.
+ */
+ public static native int usb_clear_halt(int dev_handle, int ep);
+
+ /**
+ * Resets a device by sending a RESET down the port it is connected to.+ *
+ * Causes re-enumeration: After calling
usb_reset
,
+ * the device will need to re-enumerate and thusly, requires you to find the
+ * new device and open a new handle. The handle used to call
+ * usb_reset
will no longer work.
+ *
+ * @param dev_handle
+ * The handle to the device.
+ * @return 0 on success or < 0 on error.
+ */
+ public static native int usb_reset(int dev_handle);
+
+ /**
+ * Claim an interface of a device.+ *
+ * Must be called!:
usb_claim_interface
must be
+ * called before you perform any operations related to this interface (like
+ * usb_set_altinterface, usb_bulk_write
, etc).
+ *
+ * @param dev_handle
+ * The handle to the device.
+ * @param interface_
+ * The value as specified in the descriptor field
+ * bInterfaceNumber.
+ * @return 0 on success or < 0 on error.
+ */
+ public static native int usb_claim_interface(int dev_handle, int interface_);
+
+ /**
+ * Releases a previously claimed interface
+ *
+ * @param dev_handle
+ * The handle to the device.
+ * @param interface_
+ * The value as specified in the descriptor field
+ * bInterfaceNumber.
+ * @return 0 on success or < 0 on error.
+ */
+ public static native int usb_release_interface(int dev_handle,
+ int interface_);
+
+ // Control Transfers
+ /**
+ * Performs a control request to the default control pipe on a device. The
+ * parameters mirror the types of the same name in the USB specification.
+ *
+ * @param dev_handle
+ * The handle to the device.
+ * @param requesttype
+ * @param request
+ * @param value
+ * @param index
+ * @param bytes
+ * @param size
+ * @param timeout
+ * @return the number of bytes written/read or < 0 on error.
+ */
+ public static native int usb_control_msg(int dev_handle, int requesttype,
+ int request, int value, int index, byte[] bytes, int size,
+ int timeout);
+
+ /**
+ * Retrieves the string descriptor specified by index and langid from a
+ * device.
+ *
+ * @param dev_handle
+ * The handle to the device.
+ * @param index
+ * @param langid
+ * @return the descriptor String or null
+ */
+ public static native String usb_get_string(int dev_handle, int index,
+ int langid);
+
+ /**
+ * usb_get_string_simple
is a wrapper around
+ * usb_get_string
that retrieves the string description
+ * specified by index in the first language for the descriptor.
+ *
+ * @param dev_handle
+ * The handle to the device.
+ * @param index
+ * @return the descriptor String or null
+ */
+ public static native String usb_get_string_simple(int dev_handle, int index);
+
+ /**
+ * Retrieves a descriptor from the device identified by the type and index
+ * of the descriptor from the default control pipe.+ *
+ * See {@link #usb_get_descriptor_by_endpoint(int, int, byte, byte, int)} + * for a function that allows the control endpoint to be specified. + * + * @param dev_handle + * The handle to the device. + * @param type + * @param index + * @param size + * number of charactes which will be retrieved (the length of the + * resulting String) + * @return the descriptor String or null + */ + public static native String usb_get_descriptor(int dev_handle, byte type, + byte index, int size); + + /** + * Retrieves a descriptor from the device identified by the type and index + * of the descriptor from the control pipe identified by ep. + * + * @param dev_handle + * The handle to the device. + * @param ep + * @param type + * @param index + * @param size + * number of charactes which will be retrieved (the length of the + * resulting String) + * @return the descriptor String or null + */ + public static native String usb_get_descriptor_by_endpoint(int dev_handle, + int ep, byte type, byte index, int size); + + // Bulk Transfers + /** + * Performs a bulk write request to the endpoint specified by ep. + * + * @param dev_handle + * The handle to the device. + * @param ep + * @param bytes + * @param size + * @param timeout + * @return the number of bytes written on success or < 0 on error. + */ + public static native int usb_bulk_write(int dev_handle, int ep, + byte[] bytes, int size, int timeout); + + /** + * Performs a bulk read request to the endpoint specified by ep. + * + * @param dev_handle + * The handle to the device. + * @param ep + * @param bytes + * @param size + * @param timeout + * @return the number of bytes read on success or < 0 on error. + */ + public static native int usb_bulk_read(int dev_handle, int ep, + byte[] bytes, int size, int timeout); + + // Interrupt Transfers + /** + * Performs an interrupt write request to the endpoint specified by ep. + * + * @param dev_handle + * The handle to the device. + * @param ep + * @param bytes + * @param size + * @param timeout + * @return the number of bytes written on success or < 0 on error. + */ + public static native int usb_interrupt_write(int dev_handle, int ep, + byte[] bytes, int size, int timeout); + + /** + * Performs a interrupt read request to the endpoint specified by ep. + * + * @param dev_handle + * The handle to the device. + * @param ep + * @param bytes + * @param size + * @param timeout + * @return the number of bytes read on success or < 0 on error. + */ + public static native int usb_interrupt_read(int dev_handle, int ep, + byte[] bytes, int size, int timeout); + + /** + * Returns the error string after an error occured. + * + * @return the last error sring. + */ + public static native String usb_strerror(); + + /** **************************************************************** */ + + /** + * Maps the Java error code to the system error code.
+ *
+ * Note that not all error codes are be mapped by this method. For more + * error codes see the file 'errno.h' on your system.
+ *
+ * 1: EBADF: Bad file descriptor.
+ * 2: ENXIO: No such device or address.
+ * 3: EBUSY: Device or resource busy.
+ * 4: EINVAL: Invalid argument.
+ * 5: ETIMEDOUT: Connection timed out.
+ * 6: EIO: I/O error.
+ * 7: ENOMEM: Not enough memory.
+ * + * + * @return the system error code or 100000 if no mapping has been found. + */ + private static native int usb_error_no(int value); + + static { + String os = System.getProperty("os.name"); + if (os.contains("Windows")) { + LibLoader.load( "libusbJava" ); + } else { + LibLoader.load( "usbJava" ); + } + // define the error codes + ERROR_SUCCESS = 0; + ERROR_BAD_FILE_DESCRIPTOR = -usb_error_no(1); + ERROR_NO_SUCH_DEVICE_OR_ADDRESS = -usb_error_no(2); + ERROR_BUSY = -usb_error_no(3); + ERROR_INVALID_PARAMETER = -usb_error_no(4); + ERROR_TIMEDOUT = -usb_error_no(5); + ERROR_IO_ERROR = -usb_error_no(6); + ERROR_NOT_ENOUGH_MEMORY = -usb_error_no(7); + } +} \ No newline at end of file Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Descriptor.java =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Descriptor.java (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Descriptor.java (revision 2) @@ -0,0 +1,59 @@ +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer
+ * + */ +public class Usb_Descriptor { + + /** + * Descriptor types ({@link #bDescriptorType}). + */ + public static final int USB_DT_DEVICE = 0x01, USB_DT_CONFIG = 0x02, + USB_DT_STRING = 0x03, USB_DT_INTERFACE = 0x04, + USB_DT_ENDPOINT = 0x05; + + /** + * Descriptor types ({@link #bDescriptorType}). + */ + public static final int USB_DT_HID = 0x21, USB_DT_REPORT = 0x22, + USB_DT_PHYSICAL = 0x23, USB_DT_HUB = 0x29; + + /** + * Descriptor sizes per descriptor type ({@link #bLength}). + */ + public static final int USB_DT_DEVICE_SIZE = 18, USB_DT_CONFIG_SIZE = 9, + USB_DT_INTERFACE_SIZE = 9, USB_DT_ENDPOINT_SIZE = 7, + USB_DT_ENDPOINT_AUDIO_SIZE = 9 /* Audio extension */, + USB_DT_HUB_NONVAR_SIZE = 7; + + private byte bLength; + + private byte bDescriptorType; + + /** + * Get the type of this descriptor.
+ * + * @return the type of this descriptor + */ + public byte getBDescriptorType() { + return bDescriptorType; + } + + /** + * Get the size of this descriptor in bytes.
+ * + * @return the size of this descriptor in bytes + */ + public byte getBLength() { + return bLength; + } + +} Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Endpoint_Descriptor.java =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Endpoint_Descriptor.java (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/Usb_Endpoint_Descriptor.java (revision 2) @@ -0,0 +1,156 @@ +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer
+ * Endpoint descriptors are used to describe endpoints other than endpoint zero. + * Endpoint zero is always assumed to be a control endpoint and is configured + * before any descriptors are even requested. The host will use the information + * returned from these descriptors to determine the bandwidth requirements of + * the bus.
+ *
+ * The length of the configuration descriptor is + * {@link ch.ntb.usb.Usb_Descriptor#USB_DT_ENDPOINT_SIZE} and the type is + * {@link ch.ntb.usb.Usb_Descriptor#USB_DT_ENDPOINT}. + * + */ +public class Usb_Endpoint_Descriptor extends Usb_Descriptor { + + /** + * Maximum number of endpoints + */ + public static final int USB_MAXENDPOINTS = 32; + + /** + * Endpoint address mask (in bEndpointAddress). + */ + public static final int USB_ENDPOINT_ADDRESS_MASK = 0x0f, + USB_ENDPOINT_DIR_MASK = 0x80; + + /** + * Endpoint type mask (in bmAttributes). + */ + public static final int USB_ENDPOINT_TYPE_MASK = 0x03; + + /** + * Possible endpoint types (in bmAttributes). + */ + public static final int USB_ENDPOINT_TYPE_CONTROL = 0, + USB_ENDPOINT_TYPE_ISOCHRONOUS = 1, USB_ENDPOINT_TYPE_BULK = 2, + USB_ENDPOINT_TYPE_INTERRUPT = 3; + + private byte bEndpointAddress; + + private byte bmAttributes; + + private short wMaxPacketSize; + + private byte bInterval; + + private byte bRefresh; + + private byte bSynchAddress; + + private byte[] extra; /* Extra descriptors */ + + private int extralen; + + /** + * Returns the endpoint address.
+ *
+ * Bits 3..0: Endpoint number
+ * Bits 6..4: Reserved. Set to zero
+ * Bit 7: Direction. 0 = Out, 1 = In (ignored for control endpoints)
+ * + * @return the endpoint address + */ + public byte getBEndpointAddress() { + return bEndpointAddress; + } + + /** + * Returns the intervall for polling endpoint data transfers.
+ * Value in frame counts. Ignored for Bulk & Control eEndpoints. Isochronous + * endpoints must equal 1 and field may range from 1 to 255 for interrupt + * endpoints. + * + * @return the intervall for polling endpoint data transfers + */ + public byte getBInterval() { + return bInterval; + } + + /** + * Returns the attributes of this endpoint.
+ * + * Bits 1..0: Transfer Type (see USB_ENDPOINT_TYPE_XXX).
+ * Bits 7..2: Reserved.
+ * + *
+ * If isochronous endpoint: + * Bits 3..2: Synchronisation type + * 00 = No synchronisation + * 01 = Asynchronous + * 10 = Adaptive + * 11 = Synchronous + * Bits 5..4: Usage Type + * 00 = Data endpoint + * 01 = Feedback endpoint + * 10 = Explicit feedback data endpoint + * 11 = Reserved + *+ * + * @return the attributes of this endpoint + */ + public byte getBmAttributes() { + return bmAttributes; + } + + public byte getBRefresh() { + return bRefresh; + } + + public byte getBSynchAddress() { + return bSynchAddress; + } + + /** + * Returns the data of extra descriptor(s) if available.
+ * + * @return null or a byte array with the extra descriptor data + */ + public byte[] getExtra() { + return extra; + } + + /** + * Returns the number of bytes of the extra descriptor.
+ * + * @return the number of bytes of the extra descriptor + */ + public int getExtralen() { + return extralen; + } + + /** + * Returns the maximum packet size of this endpoint is capable of sending or + * receiving.
+ * + * @return the maximum packet size + */ + public short getWMaxPacketSize() { + return wMaxPacketSize; + } + + @Override + public String toString() { + return "Usb_Endpoint_Descriptor bEndpointAddress: 0x" + + Integer.toHexString(bEndpointAddress & 0xFF); + } +} Index: usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/USB.java =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/USB.java (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/ch/ntb/usb/USB.java (revision 2) @@ -0,0 +1,271 @@ +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer
+ * + */ +public class USB { + + // Standard requests (USB spec 9.4) + /** + * This request returns status for the specified recipient (USB spec 9.4.5). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_GET_STATUS = 0x00; + /** + * This request is used to clear or disable a specific feature (USB spec + * 9.4.1). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_CLEAR_FEATURE = 0x01; + // 0x02 is reserved + /** + * This request is used to set or enable a specific feature (USB spec + * 9.4.9). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_SET_FEATURE = 0x03; + // 0x04 is reserved + /** + * This request sets the device address for all future device accesses (USB + * spec 9.4.6). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_SET_ADDRESS = 0x05; + /** + * This request returns the specified descriptor if the descriptor exists + * (USB spec 9.4.3). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_GET_DESCRIPTOR = 0x06; + /** + * This request is optional and may be used to update existing descriptors + * or new descriptors may be added (USB spec 9.4.8). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_SET_DESCRIPTOR = 0x07; + /** + * This request returns the current device configuration value (USB spec + * 9.4.2). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_GET_CONFIGURATION = 0x08; + /** + * This request sets the device configuration (USB spec 9.4.7). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_SET_CONFIGURATION = 0x09; + /** + * This request returns the selected alternate setting for the specified + * interface (USB spec 9.4.4). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_GET_INTERFACE = 0x0A; + /** + * This request allows the host to select an alternate setting for the + * specified interface (USB spec 9.4.10). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_SET_INTERFACE = 0x0B; + /** + * This request is used to set and then report an endpoint’s synchronization + * frame (USB spec 9.4.11). + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_SYNCH_FRAME = 0x0C; + + // data transfer direction (USB spec 9.3) + /** + * Identifies the direction of data transfer in the second phase of the + * control transfer.
+ * The state of the Direction bit is ignored if the wLength field is zero, + * signifying there is no Data stage.
+ * Specifies bit 7 of bmRequestType. + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_TYPE_DIR_HOST_TO_DEVICE = (0x00 << 7), + REQ_TYPE_DIR_DEVICE_TO_HOST = (0x01 << 7); + + // request types (USB spec 9.3) + /** + * Specifies the type of the request.
+ * Specifies bits 6..5 of bmRequestType. + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_TYPE_TYPE_STANDARD = (0x00 << 5), + REQ_TYPE_TYPE_CLASS = (0x01 << 5), + REQ_TYPE_TYPE_VENDOR = (0x02 << 5), + REQ_TYPE_TYPE_RESERVED = (0x03 << 5); + + // request recipient (USB spec 9.3) + /** + * Specifies the intended recipient of the request.
+ * Requests may be directed to the device, an interface on the device, or a + * specific endpoint on a device. When an interface or endpoint is + * specified, the wIndex field identifies the interface or endpoint.
+ * Specifies bits 4..0 of bmRequestType. + * + * @see ch.ntb.usb.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_TYPE_RECIP_DEVICE = 0x00, + REQ_TYPE_RECIP_INTERFACE = 0x01, REQ_TYPE_RECIP_ENDPOINT = 0x02, + REQ_TYPE_RECIP_OTHER = 0x03; + + /** + * The maximum packet size of a bulk transfer when operating in highspeed + * (480 MB/s) mode. + */ + public static int HIGHSPEED_MAX_BULK_PACKET_SIZE = 512; + + /** + * The maximum packet size of a bulk transfer when operating in fullspeed + * (12 MB/s) mode. + */ + public static int FULLSPEED_MAX_BULK_PACKET_SIZE = 64; + + private static final Logger logger = LogUtil.getLogger("ch.ntb.usb"); + + private static LinkedList
+ * + * @param idVendor + * the vendor id of the USB device + * @param idProduct + * the product id of the USB device + * @param filename + * an optional filename which can be used to distinguish multiple + * devices with the same vendor and product id. + * @return a newly created device or an already registered device + */ + public static Device getDevice(short idVendor, short idProduct, + String filename) { + + // check if this device is already registered + Device dev = getRegisteredDevice(idVendor, idProduct, filename); + if (dev != null) { + logger.info("return already registered device"); + return dev; + } + dev = new Device(idVendor, idProduct, filename); + logger.info("create new device"); + devices.add(dev); + return dev; + } + + /** + * See {@link #getDevice(short, short, String)}. The parameter + *
filename
is set to null.
+ *
+ * @param idVendor
+ * @param idProduct
+ * @return a newly created device or an already registered device
+ */
+ public static Device getDevice(short idVendor, short idProduct) {
+ return getDevice(idVendor, idProduct, null);
+ }
+
+ /**
+ * Get an already registered device or null if the device does not exist.+ * + * @param idVendor + * the vendor id of the USB device + * @param idProduct + * the product id of the USB device + * @param filename + * an optional filename which can be used to distinguish multiple + * devices with the same vendor and product id. + * @return the device or null + */ + private static Device getRegisteredDevice(short idVendor, short idProduct, + String filename) { + for (Iterator
+ * + * @author Stefan Ziegenbalg + * + */ +public class LibLoader { + +/** + * Loads a library. This is done in three steps.
+ * 1. The library is tried to be load from the path list specified by the java.library.path proterty.
+ * 2. The library is tried to be load from the currrent directory.
+ * 3. The library is searched as a system ressource (e.g. in the current .jar file), + * copied to te temporary directory and loaded from there. Afterwards the temporary library is deleted. + * The copying is necessary because libraries cant be loeaded directly from .jar files.
+ * + * @param libName Library name (e.g. usbJava) + * + * @throws UnsatisfiedLinkError + * + */ + public static void load( String libName ) { + +// Step 1: Normal way + try { + System.loadLibrary( libName ); + } + catch ( Throwable e1 ) { + +// Step 2: From the current directory + String basename = System.mapLibraryName( libName ); + try { + System.load( System.getProperty("user.dir") + System.getProperty("file.separator") + basename ); + } + catch ( Throwable e2 ) { + +// Step 2: As system ressource + String libFileName = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + basename; + try { + InputStream inputStream = ClassLoader.getSystemResourceAsStream( basename ); + if ( inputStream == null ) { + throw new Exception(); + } + File libFile = new File( libFileName ); + + FileOutputStream outputStream = new FileOutputStream( libFile ); + + byte[] buf = new byte[65536]; + int bytesRead = -1; + while ( (bytesRead = inputStream.read(buf)) > 0 ) { + outputStream.write(buf, 0, bytesRead); + } + outputStream.close(); + inputStream.close(); + + System.load( libFileName ); + + try { + libFile.delete(); + } + catch (Exception e3) { +// System.err.println( "Warning: Cannot delete temporary library file `" + libFileName + "'" ); + } + } + catch (Exception e3) { + throw new UnsatisfiedLinkError ("Library `"+basename+"' cannot be loaded as system resource, from current directory or from java.library.path (java.library.path=" + System.getProperty("java.library.path")+")" ); + } + } + } + } + +} Index: usb_fpga_1_2/trunk/libusbJava-src/Makefile =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/Makefile (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/Makefile (revision 2) @@ -0,0 +1,61 @@ +# Makefile for libusbJava, a Java libusb wrapper +# Copyright (C) 2009 ZTEX e.K. +# http://www.ztex.de +# +# This Makefile ia a part of the reorganized version of the libusbJava source tree +# with proper makefiles. (SVN version of Apr. 6, 2009). +# +# Please visit http://libusbjava.sourceforge.net for more information about the +# original project. + +######################### +# Configuration section # +######################### + +# $(JAVAPREFIX)/include should contain jni.h +JAVAPREFIX=/usr/local/java + +############################### +# this should not be modified # +############################### +GCC=gcc +JAVAC=javac +RM=rm -f +INSTALL=install +INSTALLDIR=$(INSTALL) -d +INSTALLEXE=$(INSTALL) -m 0755 +INSTALLFILE=$(INSTALL) -m 0644 +LIBSRCS=LibusbJava.c +LIBEXTRADEPS=LibusbJava.h +JAVASRCS=$(shell echo ch/ntb/usb/*.java) $(shell echo ch/ntb/usb/logger/*.java) + +LIBTARGET=libusbJava.so +LIBLIBS=-lusb +LIBINCS=-I $(JAVAPREFIX)/include -I $(JAVAPREFIX)/include/linux + +.PHONY: all libs classes install2 clean distclean + +all: libs classes + +classes: classes.made + +libs: $(LIBTARGET) + +$(LIBTARGET): $(LIBSRCS) $(LIBEXTRADEPS) + $(GCC) -shared -std=c99 -Wall -Wl,-static,-soname,$(LIBTARGET) $(LIBINCS) -static $(LIBSRCS) -o $(LIBTARGET) $(LIBLIBS) + +classes.made: $(JAVASRCS) + $(JAVAC) $(JAVASRCS) + echo > classes.made + +install2: all + $(INSTALLDIR) ../libusbJava/ch/ntb/usb/logger + $(INSTALLFILE) $(LIBTARGET) ../libusbJava + $(INSTALLFILE) ch/ntb/usb/*.class ../libusbJava/ch/ntb/usb + $(INSTALLFILE) ch/ntb/usb/logger/*.class ../libusbJava/ch/ntb/usb/logger + +clean: + $(RM) *.o + +distclean: + $(RM) $(LIBTARGET) ch/ntb/usb/*.class ch/ntb/usb/logger/*.class classes.made Index: usb_fpga_1_2/trunk/libusbJava-src/Readme =================================================================== --- usb_fpga_1_2/trunk/libusbJava-src/Readme (nonexistent) +++ usb_fpga_1_2/trunk/libusbJava-src/Readme (revision 2) @@ -0,0 +1,6 @@ +This is a reorganized version of libusbJava source tree with proper makefiles. +(SVN version of Apr. 6, 2009). + +Please visit http://libusbjava.sourceforge.net for more information about the +original project. + Index: usb_fpga_1_2/trunk/bin/bmpsdcc.sh =================================================================== --- usb_fpga_1_2/trunk/bin/bmpsdcc.sh (nonexistent) +++ usb_fpga_1_2/trunk/bin/bmpsdcc.sh (revision 2) @@ -0,0 +1,67 @@ +if [ "$1" = "" ]; then + echo "Usage: $0
usb_fpga_1_2/trunk/bin/bmpsdcc.sh
Property changes :
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: usb_fpga_1_2/trunk/bin/peeph.def
===================================================================
--- usb_fpga_1_2/trunk/bin/peeph.def (nonexistent)
+++ usb_fpga_1_2/trunk/bin/peeph.def (revision 2)
@@ -0,0 +1,76 @@
+replace {
+ mov dptr,%1
+ movx a,@dptr
+ mov %2,a
+ mov dptr,%1
+} by {
+ ; peep hole 1001, saves 3 bytes
+ mov dptr,%1
+ movx a,@dptr
+ mov %2,a
+}
+
+
+replace {
+ mov dptr,%1
+ movx a,@dptr
+ mov %3,a
+ mov dptr,%2
+ movx a,@dptr
+ mov %4,a
+ mov a%5,%4
+ mov %4,#0x00
+ mov %6,#0x00
+ mov dptr,%7
+ mov a,%4
+ orl a,%3
+ movx @dptr,a
+ mov a,%5
+ orl a,%6
+ inc dptr
+ movx @dptr,a
+} by {
+ ; peep hole 1001, saves 10 bytes
+ mov dptr,%2
+ movx a,@dptr
+ mov %4,a
+ mov dptr,%1
+ movx a,@dptr
+ mov dptr,%7
+ movx @dptr,a
+ mov a,%4
+ inc dptr
+ movx @dptr,a
+}
+
+replace {
+ mov dptr,%1
+ movx a,@dptr
+ mov %3,a
+ mov a%4,%3
+ mov %3,#0x00
+ mov dptr,%2
+ movx a,@dptr
+ mov %5,a
+ mov %6,#0x00
+ mov dptr,%7
+ mov a,%5
+ orl a,%3
+ movx @dptr,a
+ mov a,%6
+ orl a,%4
+ inc dptr
+ movx @dptr,a
+} by {
+ ; peep hole 1002, saves 10 bytes
+ mov dptr,%1
+ movx a,@dptr
+ mov %4,a
+ mov dptr,%2
+ movx a,@dptr
+ mov dptr,%7
+ movx @dptr,a
+ mov a,%4
+ inc dptr
+ movx @dptr,a
+}
Index: usb_fpga_1_2/trunk/COPYING
===================================================================
--- usb_fpga_1_2/trunk/COPYING (nonexistent)
+++ usb_fpga_1_2/trunk/COPYING (revision 2)
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+ .
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
Index: usb_fpga_1_2/trunk/Readme
===================================================================
--- usb_fpga_1_2/trunk/Readme (nonexistent)
+++ usb_fpga_1_2/trunk/Readme (revision 2)
@@ -0,0 +1,15 @@
+ZTEX Firmware Kit and Driver API for EZ-USB Microcontrollers
+------------------------------------------------------------
+
+This package is especially developed for the ZTEX Modules with EZ-USB
+Microcontrollers but also works with other EZ-USB based hardware.
+
+
+For documentation and more information please visit
+
+http://wiki.ztex.de
+
+and
+
+http://www.ztex.de .
+
Index: usb_fpga_1_2/trunk/Makefile
===================================================================
--- usb_fpga_1_2/trunk/Makefile (nonexistent)
+++ usb_fpga_1_2/trunk/Makefile (revision 2)
@@ -0,0 +1,17 @@
+DIRS=bmp examples java libusbJava-src
+
+.PHONY: default all clean distclean
+
+default:
+ @echo "This makefile is intended to clean up the project or to build the utilties and examples"
+ @echo "Usage: make all | clean | distclean"
+
+all:
+ make -C java all
+ make -C examples all
+
+clean:
+ for i in $(DIRS); do make -C $$i clean; done
+
+distclean: clean
+ for i in $(DIRS); do make -C $$i distclean; done
Index: usb_fpga_1_2/trunk/bmp/configure
===================================================================
--- usb_fpga_1_2/trunk/bmp/configure (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/configure (revision 2)
@@ -0,0 +1,245 @@
+#!/bin/sh
+# Makefile.config -- script for automatic configuration of Makefile variables
+# Copyright (C) 2002-2003 Stefan Ziegenbalg
+
+configfile=Makefile.conf
+
+# nice output routines
+# \033 is just ascii ESC
+# \033[G move to column
+# \033[1m switch bold on
+# \033[31m switch red on
+# \033[32m switch green on
+# \033[33m switch yellow on
+# \033[m switch color/bold off
+echo_red () {
+ echo -e "\033[31m\033[1m$1\033[m" >&2
+}
+
+echo_green () {
+ echo -e "\033[32m$1\033[m" >&2
+}
+
+echo_yellow () {
+ echo -e "\033[33m\033[1m$1\033[m" >&2
+}
+
+# read config file
+readconfig () {
+ result="-"
+ read var par
+ while [ "$result" = "-" -a "$var" != "" ]; do
+ [ "$var" = "$1" ] && result=$par
+ read var par
+ done
+ echo $result
+}
+
+# remove temporay files
+rmtmp () {
+ rm -f $tmpfile $tmpfile.*
+}
+
+# checks coompilinmg + running
+# $1 compiler command + flags
+# $2 test file (without .pas)
+checkcr () {
+ echo "$1 $2" >> $tmpfile.log
+ $1 $2 >> $tmpfile.log 2>> $tmpfile.log
+ if [ "$?" = "0" ]; then
+ echo "./$2" >> $tmpfile.log
+ ./$2
+ else
+ return 1
+ fi
+}
+
+# checks command
+findexec () {
+ result=""
+ for i; do
+ if [ "$result" = "" ]; then
+ if [ "${i#*/}" = "$i" ]; then
+ which $i >> $tmpfile.log 2>> $tmpfile.log
+ [ "$?" = "0" ] && result=$i
+ else
+ [ -x $i -a ! -d $i ] && result=$i
+ fi
+ fi
+ done
+ echo $result
+}
+
+
+failure () {
+ echo -n $failreturn
+ exit 1
+}
+
+#####################
+##### main part #####
+#####################
+failreturn=""
+case "$1" in
+ "pc2") cmd=pc; failreturn="ppc386" ;;
+ "install2") cmd=install; failreturn="install" ;;
+ "findexec2") cmd=findexec; failreturn=${2%% *} ;;
+ *) cmd=$1 ;;
+esac
+
+case "$cmd" in
+ "findexec") varname=$cmd_$2 ;;
+ "have_unit") varname=have_$3 ;;
+ "unit_flags") varname=$3"_flags" ;;
+ *) varname=$cmd ;;
+esac
+tmpfile="conf_$varname"
+
+result="-"
+[ -f $configfile -a "$varname" != "" ] && result=`readconfig $varname < $configfile`
+
+if [ "$result" != "-" ]; then
+ echo $result
+ exit 0
+fi
+
+result=""
+rm -f $tmpfile.log
+case "$cmd" in
+ "pc")
+ echo -n "Checking for freepascal compiler (FLAGS=\"$2\"): " >&2
+ echo -e "begin\nend." > $tmpfile.pas
+ for i in ppc386 fpc pc $3; do
+ if [ "$result" = "" ]; then
+ if [ "${i#*/}" = "$i" ]; then
+ which $i >> $tmpfile.log 2>> $tmpfile.log
+ [ "$?" = "0" ] && checkcr "$i $2" $tmpfile && result=$i
+ else
+ [ -x $i -a ! -d $i ] && checkcr "$i $2" $tmpfile && result=$i
+ fi
+ fi
+ done
+ if [ "$result" != "" ]; then
+ echo_green "$result"
+ rmtmp
+ else
+ echo_red "not found"
+ failure
+ fi
+ ;;
+ "install")
+ echo -n "Checking for install command: " >&2
+ result=`findexec install ginstall $2`
+ if [ "$result" != "" ]; then
+ echo_green "$result"
+ rmtmp
+ else
+ echo_red "not found"
+ failure
+ fi
+ ;;
+ "have_unit" | "unit_flags" )
+ echo -n "Checking for $3 unit: " >&2
+ echo -e "uses $3;\nbegin\nend." > $tmpfile.pas
+ for i in $4 " "; do
+ if [ "$result" = "" ]; then
+ if [ "$i" = " " ]; then
+ checkcr "$2" $tmpfile && result=$i
+ else
+ [ -f $i/$3.ppu ] && checkcr "$2 -Fu$i" $tmpfile && result=$i
+ fi
+ fi
+ done
+ if [ "$result" != "" ]; then
+ if [ "$result" = " " ]; then
+ echo_green "available"
+ else
+ echo_green "$result"
+ result="-Fu$result"
+ fi
+ if [ "$1" = "have_unit" ]; then
+ echo "$3""_flags $result" >> $configfile
+ result=1
+ else
+ echo "have_$3 1" >> $configfile
+ fi
+ rmtmp
+ else
+ echo_yellow "not available"
+ echo "$3""_flags " >> $configfile
+ if [ "$1" = "have_unit" ]; then
+ result=0
+ else
+ echo "have_$3 0" >> $configfile
+ failure
+ fi
+ fi
+ ;;
+ "optalign")
+ echo -n "Checking for -Oa flag: " >&2
+ echo -e "begin\nend." > $tmpfile.pas
+ checkcr "$2 -Oa" $tmpfile
+ if [ "$?" = "0" ]; then
+ echo_green "works"
+ result=1
+ rmtmp
+ else
+ echo_yellow "failed"
+ result=0
+ fi
+ ;;
+ "findexec")
+ echo -n "Checking for $2: " >&2
+ result=`findexec $3`
+ if [ "$result" != "" ]; then
+ echo_green "$result"
+ rmtmp
+ else
+ echo_red "not found"
+ failure
+ fi
+ ;;
+ *)
+ echo "$0 -- script for automatic configuration of Makefile variables"
+ echo
+ echo
+ echo " !! Run make to build the project or run ./update to update the Makefile (e.g. after changing sources)!!"
+ echo
+ echo
+ echo "Usage: $0 [options]"
+ echo ""
+ echo "variables:"
+ echo " pc [compiler flags [additional compilers]]"
+ echo " checks for freepascal compiler, returns \"\" on failure"
+ echo ""
+ echo " pc2 [compiler flags [additional compilers]]"
+ echo " as above, but ppc386 is returned on failure"
+ echo ""
+ echo " install [additonal commands]"
+ echo " checks for install command, returns \"\" on failure"
+ echo ""
+ echo " install2 [additonal commands]"
+ echo " as above, but install is returned on failure"
+ echo ""
+ echo " have_unit []"
+ echo " checks whether is available; returns 0 on failure, 1 on success; unit list must be coma separated"
+ echo ""
+ echo " unit_flags []"
+ echo " as above, but returns \"-ul\" if unit found in []"
+ echo ""
+ echo " optalign "
+ echo " checks whether -Oa flag works"
+ echo ""
+ echo " findexec
- "
+ echo " checks for existing executable in
- "
+ echo ""
+ echo " findexec2
- "
+ echo " as above, but first variant is returned on failure"
+ echo ""
+ exit 1
+ ;;
+esac
+
+[ "$result" != "" -a "$varname" != "" ] && echo "$varname $result" >> $configfile
+echo $result
+
usb_fpga_1_2/trunk/bmp/configure
Property changes :
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: usb_fpga_1_2/trunk/bmp/tests/000
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/000 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/000 (revision 2)
@@ -0,0 +1,11 @@
+P2
+#creator: SImg (http://www.simage.org)
+7 7
+255
+ 16 32 48 64 48 32 16
+ 32 64 96 128 96 64 32
+ 48 96 143 191 143 96 48
+ 64 128 191 255 191 128 64
+ 48 96 143 191 143 96 48
+ 32 64 96 128 96 64 32
+ 16 32 48 64 48 32 16
Index: usb_fpga_1_2/trunk/bmp/tests/010
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/010 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/010 (revision 2)
@@ -0,0 +1,4 @@
+//define[test(][,#1);][1, ##0=#0, ##1=#1]
+#define[test(][,$1);][2, $$0=$0, $$1=$1]
+#define{test(}{,$1);}{3, $$0=$0, $$1=$1}
+test(123,abc);
Index: usb_fpga_1_2/trunk/bmp/tests/001
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/001 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/001 (revision 2)
@@ -0,0 +1,47 @@
+//
+
+////
+//define
+//define[Test1]
+//define[Test2][zweiter Test]//define[Testa2][2a]
+//define[Test3][(#1,#2)][d##1r#1i#2t#bte#3r Test#]
+//define[Testa3][#1#2][d#0rit#1ter T#2estb]
+//define[Testb3][][[]]
+//define[Test4][;][viert#0er Te#1st]
+//define[/*][*/][]
+
+const bufmax = 65535;
+ rbufmax = 65535;
+ maxfiles = 256;
+ maxmacros = 4095;
+ matchlength = 3;
+
+const bc_pm : string = '//';
+ bc_ob : char = '[';
+ bc_cb : char = ']';
+ bc_pa : char = '#';
+ bc_sm : string = '';
+ bc_em : string = ';';
+ bc_lf : string = #10;
+
+const bmp_exit : longint = 0;
+
+const debugoutput : boolean = true;
+
+{*********************************************************************}
+var main : tmainbmp;
+begin
+1-->Test1<--1
+main.init;
+2-->Test2<--2
+main.run;
+2a-->Testa2<--2a
+main.done;
+3-->Test3(abc,cde)<--3
+halt(bmp_exit);
+3a-->Testa3[123][]<--3a
+end.
+3b-->Testb3<--3b
+4-->Test4123;<--4
+5-->/*123 */<--5
+
Index: usb_fpga_1_2/trunk/bmp/tests/011
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/011 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/011 (revision 2)
@@ -0,0 +1,6 @@
+//define[simgfp][single]
+//define[asm_single][dword]
+//define[single_asm][dword]
+
+asm_simgfp
+simgfp_asm
Index: usb_fpga_1_2/trunk/bmp/tests/002
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/002 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/002 (revision 2)
@@ -0,0 +1,35 @@
+
+//define[@01]
+//define[@02]
+
+
+a
+//ifndef[@01]
+b
+//ifdef[@02]
+//define[@03]
+1
+//else
+2
+//endif
+b
+//else
+c
+//ifdef[@02]
+//define[@04]
+3
+//else
+4
+//endif
+c
+//endif
+d
+
+//ifdef[@03]
+@03
+//endif
+
+//ifdef[@04]
+@04
+
+//endif
Index: usb_fpga_1_2/trunk/bmp/tests/004.1
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/004.1 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/004.1 (revision 2)
@@ -0,0 +1,2 @@
+//define[@03]
+ist
\ No newline at end of file
Index: usb_fpga_1_2/trunk/bmp/tests/012
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/012 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/012 (revision 2)
@@ -0,0 +1,4 @@
+//define[@a@][1]
+//define[@ab@][@a@2]
+//define[@abc@][@ab@3]
+@abc@
Index: usb_fpga_1_2/trunk/bmp/tests/003
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/003 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/003 (revision 2)
@@ -0,0 +1,19 @@
+
+//define[@01]
+//define[@02]
+//define[@01]
+
+//uadefine[@01]
+
+//ifdef[@01]
+@01
+//endif
+
+//ifdef[@02]
+@02
+//endif
+
+//define[@10][geht]
+//ifdef[@10]
+@10
+//endif
\ No newline at end of file
Index: usb_fpga_1_2/trunk/bmp/tests/004.2
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/004.2 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/004.2 (revision 2)
@@ -0,0 +1 @@
+ein
\ No newline at end of file
Index: usb_fpga_1_2/trunk/bmp/tests/013
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/013 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/013 (revision 2)
@@ -0,0 +1,16 @@
+//define[test1][1: test1]
+test1
+//define[test1][2: test1]
+test1
+//define[test1][3: test1]
+test1
+
+//define[testa][a1: testb]
+//define[testb][b1: testa]
+testa
+testb
+
+//define[testa][a2: testb]
+//define[testb][b2: testa]
+testa
+testb
Index: usb_fpga_1_2/trunk/bmp/tests/004
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/004 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/004 (revision 2)
@@ -0,0 +1,13 @@
+-->
+
+//nolf//define[@01][//define[@02][est]
+@02]
+dies
+//nolf//include[004.1]
+//nolf//include[004.2]
+//nolf//ifdef[@03]
+T
+//nolf//else
+t
+//endif
+@01
Index: usb_fpga_1_2/trunk/bmp/tests/014
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/014 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/014 (revision 2)
@@ -0,0 +1,25 @@
+//define[a1a][abc]
+//define[a1b][abc]
+//define[a2a][123]
+//define[a2b][234]
+--
+//ifeq[a1b][a1b]
+1
+//else
+//ifeq[a2a][a2b]
+-1,2
+//else
+-1,-2
+//endif
+//endif
+--
+//ifneq[a1a][a1b]
+-1
+//else
+//ifneq[a2a][a2b]
+1,-2
+//else
+1,2
+//endif
+//endif
+--
Index: usb_fpga_1_2/trunk/bmp/tests/005
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/005 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/005 (revision 2)
@@ -0,0 +1,6 @@
+schreiben
+//disableout
+keine Ausgabe
+//enableout
+again
+
Index: usb_fpga_1_2/trunk/bmp/tests/006
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/006 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/006 (revision 2)
@@ -0,0 +1,10 @@
+//define[case][Groß-/Kleinschreibung]
+//define[Case][egal]
+default: case
+//ignorecase
+ausschalten: case
+//exactcase
+anschalten: case
+//ignorecase
+ausschalten: case
+
Index: usb_fpga_1_2/trunk/bmp/tests/016.1
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/016.1 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/016.1 (revision 2)
@@ -0,0 +1 @@
+warning(Warnung 2);
\ No newline at end of file
Index: usb_fpga_1_2/trunk/bmp/tests/015
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/015 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/015 (revision 2)
@@ -0,0 +1,56 @@
+//define[a1a][abc]
+a1a
+//noexpand[!]a1a!
+--
+//ifeq[a1a][abc]
+1
+//else
+-1
+//endif
+--
+//ifeq[//noexpand!a1a!][abc]
+1
+//else
+-1
+//endif
+--
+//ifneq[//noexpand!a1a!][abc]
+-1
+//else
+1
+//endif
+--
+
+--
+//ifeq[a1a][a1a]
+2
+//else
+-2
+//endif
+--
+//ifeq[a1a][//noexpand!a1a!]
+2
+//else
+-2
+//endif
+--
+//ifneq[a1a][//noexpand!a1a!]
+-2
+//else
+2
+//endif
+--
+
+--
+//ifeq[//noexpand!a1a!][//noexpand!a1a!]
+3
+//else
+-3
+//endif
+--
+//ifneq[//noexpand!a1a!][//noexpand!a1a!]
+-3
+//else
+3
+//endif
+--
Index: usb_fpga_1_2/trunk/bmp/tests/016
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/016 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/016 (revision 2)
@@ -0,0 +1,15 @@
+1
+//define[error(][);][Fehler:
+//error[#0]
+//nolf]
+2
+//define[warning(][);][Warnung:
+//warning[#0]
+//nolf]
+3
+warning(Warnung 1);
+4
+//include[016.1]
+5
+//include[016.2]
+6
Index: usb_fpga_1_2/trunk/bmp/tests/016.2
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/016.2 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/016.2 (revision 2)
@@ -0,0 +1 @@
+error(Fehler 1);
\ No newline at end of file
Index: usb_fpga_1_2/trunk/bmp/tests/007
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/007 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/007 (revision 2)
@@ -0,0 +1,11 @@
+//define[rangen;][//ifdef[i386]
+intel
+//else
+alpa
+//endif]
+
+rangen;
+//define[i386]
+rangen;
+//udefine[i386]
+rangen;
Index: usb_fpga_1_2/trunk/bmp/tests/017
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/017 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/017 (revision 2)
@@ -0,0 +1,15 @@
+#define[EP2_INTERFACE][1]
+#define[EP4_INTERFACE][0]
+EP2_INTERFACE
+EP4_INTERFACE
+EP6_INTERFACE
+EP8_INTERFACE
+#ifeq[EP2_INTERFACE][0]
+1
+#elifeq[EP4_INTERFACE][0]
+2
+#elifeq[EP6_INTERFACE][0]
+3
+#elifneq[EP8_INTERFACE][0]
+4
+#endif
Index: usb_fpga_1_2/trunk/bmp/tests/008
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/008 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/008 (revision 2)
@@ -0,0 +1,2 @@
+Hallo
+//nolf//noexpand[!]//else! Welt
Index: usb_fpga_1_2/trunk/bmp/tests/009
===================================================================
--- usb_fpga_1_2/trunk/bmp/tests/009 (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/tests/009 (revision 2)
@@ -0,0 +1,8 @@
+//define[abc][def]
+//define[abc][123]
+
+abc
+//udefine[abc]
+abc
+//udefine[abc]
+abc
Index: usb_fpga_1_2/trunk/bmp/Make.bat
===================================================================
--- usb_fpga_1_2/trunk/bmp/Make.bat (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/Make.bat (revision 2)
@@ -0,0 +1,5 @@
+set PATH=%PATH%;c:\FPC\2.2.2\bin\i386-win32
+
+ppc386 -Scgm -O3 -FE. -Xs src\bmp.pas
+
+pause
\ No newline at end of file
Index: usb_fpga_1_2/trunk/bmp/src/bmpsys.pas
===================================================================
--- usb_fpga_1_2/trunk/bmp/src/bmpsys.pas (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/src/bmpsys.pas (revision 2)
@@ -0,0 +1,75 @@
+{*!
+ bmp -- babel macro processor
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*}
+
+{$mode objfpc}
+unit bmpsys;
+
+interface
+
+const bmp_exit_error = 1;
+ bmp_exit_faterror = 2;
+ bmp_exit_paramerror = 3;
+ bmp_exit_usererror = 100; { //error[...] }
+
+const bmp_exit : longint = 0;
+
+procedure bmp_warning(const s:ansistring);
+procedure bmp_error(const s:ansistring);
+procedure bmp_faterror(const s:ansistring);
+function min(i,j:longint):longint;
+function max(i,j:longint):longint;
+function int2str(i:longint):shortstring;
+
+implementation
+
+procedure bmp_warning(const s:ansistring);
+begin
+writeln(stderr,'Warning: ',s);
+end;
+
+procedure bmp_error(const s:ansistring);
+begin
+writeln(stderr,'Error: ',s);
+bmp_exit:=1;
+end;
+
+procedure bmp_faterror(const s:ansistring);
+begin
+writeln(stderr,'Fatal error: ',s);
+halt(2);
+end;
+
+function min(i,j:longint):longint;
+begin
+if ij then max:=i
+ else max:=j;
+end;
+
+function int2str(i:longint):shortstring;
+begin
+str(i,int2str);
+end;
+
+
+end.
Index: usb_fpga_1_2/trunk/bmp/src/bmp.pas
===================================================================
--- usb_fpga_1_2/trunk/bmp/src/bmp.pas (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/src/bmp.pas (revision 2)
@@ -0,0 +1,1763 @@
+{*!
+ bmp -- babel macro processor
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*}
+
+{ todo:
+Ausgabe als Eingabe (mehrfache Bearbeitung)
+}
+
+{ codes
+ bc_pm : string
+ bc_ob : char
+ bc_cb : char
+ bc_pa : char
+
+meta macros:
+ define
+ define(sym) define symb
+ define(m1)(r1) define macro m1 with replacement r1
+ define(m2)(p2)(r2) define macro m2 with parmaters p2 and replacement r1
+
+ udefine
+ uadefine
+
+ include
+
+ ifdef/ifndef
+ elifdef/elfndef
+ ifeq/ifneq macros are expanded in the compared strings, but no meta macros, except of \\noexapnd which disbales the expansion
+ elifeq/elifneq
+ else
+ endif
+
+ nolf
+
+ error
+ warning
+
+ disablaeout
+ enableout
+
+ ignorecase
+ exactcase
+
+ noexpand
+}
+
+{$mode objfpc}
+
+{$define USE_SHORTSTRINGS} // shortstrings are two times faster
+{ $define ENABLE_DEBUGOUT}
+
+uses dos,strings,textbuf,bmpsys,sysutils;
+
+{ ******************************************************************** }
+{ ****** constants *************************************************** }
+{ ******************************************************************** }
+{$ifdef USE_SHORTSTRINGS}
+type bmpstring = shortstring;
+{$else}
+type bmpstring = ansistring;
+{$endif}
+
+const rbufmax = 65535; { must be 2^n-1 ! }
+ maxmacros = 16383; { max amount of macros }
+ maxifs = 4095; { max input files }
+ maxbs = 255; { brace stack }
+ maxoutfiles = 256; { max input files }
+ maxparams = 35; { max amount of macro parameters }
+
+ bc_pm : bmpstring = '//'; { default for pascal mode }
+ bc_ob : char = '['; { default }
+ bc_cb : char = ']'; { default }
+ bc_pa : char = '#'; { default for pascal mode }
+ bc_lf = #10;
+ bp_icase : boolean = false; { ignore case }
+
+{$ifdef WINDOWS}
+ dirsep = '\'; { directory seperator }
+{$else}
+ dirsep = '/'; { directory seperator }
+{$endif}
+
+ enable_hints : boolean = true; { enable hints }
+ printdefs : boolean = false; { print definitions }
+{$ifdef ENABLE_DEBUGOUT}
+ debugoutput : boolean = false; { debug mode }
+{$endif}
+ paramids : array[0..maxparams] of char = ('0','1','2','3','4','5','6','7','8','9', { parameters (in that order!) }
+ 'a','b','c','d','e','f','g','h','i','j',
+ 'k','l','m','n','o','p','q','r','s','t',
+ 'u','v','w','x','y','z');
+
+{ ****** modes ******************************************************* }
+const bm_plain = 0;
+ bm_neplain = 1; { no expand plain }
+
+ bm_comm = 10; { comment }
+
+ bm_em = 100; { (macro) expanding mode }
+ bm_em_p0 = 101; { zero paramter (#0) }
+ bm_em_pz = bm_em_p0+maxparams; { last paramter }
+
+ bm_pm = 1000; { programming mode }
+
+ bm_def = 1100; { define mode }
+ bm_def_sob2 = 1101; { searching 2nd opening bracket }
+ bm_def_sob3 = 1102; { searching 3rd opening bracket }
+ bm_def_scb1 = 1103; { searching 1st closing bracket }
+ bm_def_scb2 = 1104; { searching 2nd closing bracket }
+ bm_def_scb3 = 1105; { searching 3rd closing bracket }
+ bm_def_scbu = 1120; { searching udefine closing bracket }
+ bm_def_scba = 1130; { searching uadefine closing bracket }
+
+ bm_if = 1200; { if mode }
+ bm_if_scb = 1201; { searching closing bracket }
+ bm_ifn_scb = 1202; { searching closing bracket }
+ bm_if_not = 1203; { marks the ignored part, searching for else }
+
+ bm_ifeq_sob = 1210;
+ bm_ifneq_sob = 1211;
+ bm_ifeq_scb1 = 1212;
+ bm_ifeq_scb2 = 1213;
+ bm_ifneq_scb1 = 1214;
+ bm_ifneq_scb2 = 1215;
+ bm_ifeq_scb1_ne = 1216;
+ bm_ifeq_scb2_ne = 1217;
+ bm_ifneq_scb1_ne = 1218;
+ bm_ifneq_scb2_ne = 1219;
+ bm_ifb = 1220;
+
+ bm_inc = 1300; { include mode }
+ bm_inc_scb = 1301; { searching closing bracket }
+
+ bm_noexpand = 1400; { noexpand mode }
+ bm_noexpand_scb = 1401; { searching closing bracket }
+
+ bm_err = 1500; { error }
+ bm_err_scb = 1501; { searching closing bracket }
+
+ bm_warn = 1510; { warning }
+ bm_warn_scb = 1511; { searching closing bracket }
+
+
+ bm_outfile_a = 10000; { outfile number }
+ bm_outfile_z = bm_outfile_a+maxoutfiles;
+
+ bm_invalid = -1; { invalid character }
+
+
+{ ******************************************************************** }
+{ ****** helper functions ******************************************** }
+{ ******************************************************************** }
+function upcase(ch:char):char; { no Umlaute }
+begin
+if (ch>='a') and (ch<='z')
+ then result:=chr(ord(ch)-32)
+ else result:=ch;
+end;
+
+function upstr(const s:bmpstring):bmpstring;
+var i : longint;
+begin
+setlength(upstr, length(s));
+for i:=1 to length(s) do
+ begin
+ if (s[i]>='a') and (s[i]<='z')
+ then upstr[i]:=chr(ord(s[i])-32)
+ else upstr[i]:=s[i];
+ end;
+end;
+
+procedure upstr2(var s:shortstring);
+var i : longint;
+begin
+for i:=1 to length(s) do
+ if (s[i]>='a') and (s[i]<='z') then byte(s[i])-=32;
+end;
+
+
+{ ******************************************************************** }
+{ ****** rbufstr ***************************************************** }
+{ ******************************************************************** }
+type RBufStr = record { string within ring, }
+ rbuf : pchar; { buffer }
+ pt : longint; { where the ring starts }
+ length : longint; { length of the string }
+ end;
+
+function rbuf(const rb:rbufstr):bmpstring;
+var i,j,k : longint;
+begin
+k:=rb.length;
+{$ifdef USE_SHORTSTRINGS}
+if k>255 then k:=255;
+{$endif}
+j:=rb.pt;
+setlength(result,k);
+for i:=1 to k do
+ begin
+ result[i]:=rb.rbuf[j and rbufmax];
+ j+=1;
+ end;
+end;
+
+function cmp_rbuf(const rb:rbufstr; const s:bmpstring):boolean;
+var i,j : longint;
+begin
+result:=false;
+if rb.length<>length(s) then exit;
+j:=rb.pt;
+for i:=1 to rb.length do
+ begin
+ if rb.rbuf[j and rbufmax]<>s[i] then exit;
+ j+=1;
+ end;
+result:=true;
+end;
+
+function cmpcase_rbuf(const rb:rbufstr; const s:bmpstring):boolean;
+var i,j : longint;
+begin
+result:=false;
+if rb.length<>length(s) then exit;
+j:=rb.pt;
+for i:=1 to rb.length do
+ begin
+ if lowercase(rb.rbuf[j and rbufmax])<>lowercase(s[i]) then exit;
+ j+=1;
+ end;
+result:=true;
+end;
+
+
+{ ******************************************************************** }
+{ ****** TBabelMacro ************************************************* }
+{ ******************************************************************** }
+type PBabelMacro=^TBabelMacro;
+ TBabelMacro=record
+ name : bmpstring; { macro name }
+ mmatch_s : array[0..1] of dword; { quick match string (normal, upercase) }
+ mmatch_m : dword; { quick match mask }
+ pn : longint; { number of parameters }
+ rsize : longint; { replacement size }
+ r : ^char; { replacement }
+ li : ^dword; { lnie info }
+ quick : boolean; { quick comparison }
+ enabled : boolean; { set to false to avoid recursions }
+ paramsep : array[0..maxparams] of ansistring; { parameter seperators }
+ end;
+
+{ ****** freemacro *************************************************** }
+procedure freemacro(var mac:PBabelMacro);
+var i : longint;
+begin
+if (mac^.r<>nil) and (mac^.rsize>0) then freemem(mac^.r, mac^.rsize);
+if (mac^.li<>nil) and (mac^.rsize>0) then freemem(mac^.li, mac^.rsize*4);
+{$ifndef USE_SHORTSTRINGS}
+mac^.name:='';
+{$endif}
+for i:=1 to maxparams do
+ mac^.paramsep[i]:='';
+freemem(mac,sizeof(TBabelMacro));
+mac:=nil;
+end;
+
+{ ******************************************************************** }
+{ ****** CMacroBuf *************************************************** }
+{ ******************************************************************** }
+const macrobuf_size = 1024;
+type CMacroBuf = class(CTextBuf)
+ constructor create(var tb:CTextBuf; m:PBabelMacro; clone:boolean);
+ constructor insert(var mb:CMacroBuf);
+ destructor destroy; override;
+ private
+ mac : PBabelMacro;
+ end;
+
+{ ****** create ****************************************************** }
+constructor CMacroBuf.create(var tb:CTextBuf; m:PBabelMacro; clone:boolean);
+begin
+if clone
+ then inherited create(tb, m^.r, m^.li, m^.rsize)
+ else inherited create(tb, macrobuf_size);
+m^.enabled:=false;
+mac:=m;
+end;
+
+constructor CMacroBuf.insert(var mb:CMacroBuf);
+var tmp : CMacroBuf;
+begin
+tmp:=mb;
+inherited create(mb, macrobuf_size);
+last:=tmp.last;
+tmp.last:=self;
+mac:=tmp.mac;
+tmp.mac:=nil;
+end;
+
+{ ****** destroy ***************************************************** }
+destructor CMacroBuf.destroy;
+begin
+if mac<>nil then mac^.enabled:=true;
+end;
+
+
+{ ******************************************************************** }
+{ ****** CMainBmp **************************************************** }
+{ ******************************************************************** }
+type CMainBmp=class
+ buf : CTextBuf;
+ macros : array[0..maxmacros] of PBabelMacro;
+
+ constructor create;
+ destructor destroy; override;
+ procedure run(const mf:ansistring; var fo:text);
+ procedure initsymb(const s:bmpstring);
+
+ private
+
+ rbuf : array[0..rbufmax] of char;
+ bufm : array[0..rbufmax] of smallint;
+ li : array[0..rbufmax] of dword;
+ rbp,lastmacro : longint; { buffer pointer }
+ lineInfo : dword;
+
+ procedure error_int(const t:ansistring);
+ procedure error(const s:ansistring);
+ procedure faterror(const s:ansistring);
+ procedure warning(const s:ansistring);
+ procedure hint(const s:ansistring);
+
+ function copylaststr(l,mode:longint):rbufstr; { last l continuous chars with mode m }
+ function copylaststr(l:longint):rbufstr; { last l chars }
+ function copylaststr_br(l,mode:longint):bmpstring; { last l chars with mode m, breaks allowed }
+
+ function matchstr(const s:bmpstring;mode:longint):boolean;
+ function matchstr(const s:bmpstring):boolean;
+ function matchstr(ic:boolean;const s:bmpstring;mode:longint):boolean;
+ function matchstr(ic:boolean;const s:bmpstring):boolean;
+ function matchstr_br(const s:bmpstring;mode:longint):boolean;
+ function matchstr_br(ic:boolean;const s:bmpstring;mode:longint):boolean;
+
+ function lastmodestr(mode:longint):bmpstring;
+ function lastmodestr1(mode:longint):bmpstring;
+ procedure lastmodestr(mode:longint;var size:longint; var ptc:pchar; var ptli:pdword);
+ procedure lastmodestr1(mode:longint;var size:longint; var ptc:pchar; var ptli:pdword);
+ procedure lastmodestr(mode:longint;var fst,l:longint);
+
+ procedure setmode(num,om,nm:longint); { om: old mode; nm: new mode}
+
+ procedure printmacros(const m : array of pbabelmacro; mm:longint);
+ procedure printmacros;
+{$ifdef ENABLE_DEBUGOUT }
+ procedure debugwrite;
+{$endif}
+ end;
+
+type TS4 = packed record
+ case integer of
+ 0 : ( s : string[4]; );
+ 1 : ( len : byte;
+ i : dword; );
+ end;
+
+
+{ ****** create ****************************************************** }
+constructor CMainBmp.create;
+var i : longint;
+begin
+for i:=0 to maxmacros do
+ macros[i]:=nil;
+lastmacro:=-1;
+{$ifdef UNIX}
+initsymb('UNIX');
+{$endif}
+{$ifdef WINDOWS}
+initsymb('WINDOWS');
+{$endif}
+{$ifdef dos}
+initsymb('dos');
+{$endif}
+{$ifdef linux}
+initsymb('linux');
+{$endif}
+{$ifdef unix}
+initsymb('unix');
+{$endif}
+{$ifdef go32v1}
+initsymb('go32v1');
+{$endif}
+{$ifdef go32v2}
+initsymb('go32v2');
+{$endif}
+{$ifdef os2}
+initsymb('os2');
+{$endif}
+{$ifdef win32}
+initsymb('win32');
+{$endif}
+{$ifdef macos}
+initsymb('macos');
+{$endif}
+{$ifdef amiga}
+initsymb('amiga');
+{$endif}
+{$ifdef atari}
+initsymb('atari');
+{$endif}
+end;
+
+{ ****** destroy **************************************************** }
+destructor CMainBmp.destroy;
+var i : longint;
+begin
+for i:=0 to lastmacro do
+ if macros[i]<>nil then freemacro(macros[i]);
+end;
+
+{ ****** run ******************************************************** }
+procedure CMainBmp.run(const mf:ansistring; var fo:text);
+var i,mode,j,k,l,bl,ifc : longint;
+ outfile,bm_expand : longint;
+ prevli,ampos : dword;
+ sx,endnoexpand : bmpstring;
+ s4 : array[0..3] of char;
+ i4 : dword absolute s4;
+ tmpbuf : CTextBuf;
+ tmpmbuf : CMacroBuf;
+ amacro : PBabelMacro;
+ writebuf : shortstring;
+
+ pm_s,pm_m : dword;
+ pm_q : boolean;
+ t4 : TS4;
+
+ ifs : array[0..maxifs] of byte;
+ ifli : array[0..maxifs] of dword;
+ bli : array[0..maxbs] of dword;
+
+label endparse;
+
+begin
+amacro:=nil;
+t4.s:=copy(' '+bc_pm, length(bc_pm)+1,4);
+pm_s:=t4.i;
+pm_m:=$ffffffff shl ((4-min(length(bc_pm),4))*8);
+pm_q:=length(bc_pm)<=4;
+
+writebuf:='';
+CFileBuf.create(buf,mf,'');
+
+bl:=0;
+fillchar(bufm, sizeof(bufm), 0);
+fillchar(rbuf, sizeof(rbuf), #32);
+fillchar(li, sizeof(li), 0);
+bufm[0]:=bm_outfile_a;
+bufm[rbufmax]:=bm_outfile_a+1;
+
+rbp:=0;
+mode:=bm_plain;
+ifc:=-1;
+outfile:=1;
+bm_expand:=bm_plain;
+
+prevli:=dword(-1);
+ampos:=0;
+while (buf<>nil) and (bmp_exit<>bmp_exit_usererror) do
+ begin
+ if buf.d>buf.lastbuf
+ then begin
+ buf.endbuf;
+ if buf.killme then
+ begin
+ tmpbuf:=buf.last;
+ buf.destroy;
+ buf:=tmpbuf;
+ end;
+ end
+ else if buf.buf[buf.d]=#13 then buf.d+=1
+ else begin
+{$ifdef ENABLE_DEBUGOUT}
+ if debugoutput then debugwrite;
+{$endif}
+ i:=bufm[rbp];
+ if (i<10) and (i>=0) and (outfile>0) then
+ begin
+ j:=ord(writebuf[0])+1; { avoid the range checking }
+ writebuf[0]:=char(j);
+ writebuf[j]:=rbuf[rbp];
+ if rbuf[rbp]=#10 then
+ begin
+ if (li[rbp]<>prevli+4096) and (lineInfoPattern<>'') then lineInfoStr(fo,li[rbp]);
+ prevli:=li[rbp];
+ byte(writebuf[0])-=1;
+ writeln(fo,writebuf);
+ writebuf:='';
+ end;
+ if (j>=255) then
+ begin
+ write(fo,writebuf);
+ writebuf:='';
+ end;
+ end
+ else if (i>=bm_outfile_a) and (i<=bm_outfile_z) then outfile:=i-bm_outfile_a;
+
+ rbuf[rbp]:=buf.buf[buf.d];
+ lineInfo:=buf.li[buf.d];
+ li[rbp]:=lineInfo;
+ bufm[rbp]:=mode;
+ buf.d+=1;
+
+{brackets}
+ if rbuf[rbp]=bc_ob then
+ begin
+ if (bl>=0) and (blbm_plain then
+ begin
+ if (mode=bm_pm) and matchstr(bc_pm+'ifdef'+bc_ob,bm_pm) then
+ begin
+ setmode(length(bc_pm+'ifdef'+bc_ob),bm_pm,bm_if);
+ mode:=bm_if_scb;
+ bli[0]:=lineInfo;
+ bl:=1;
+ end;
+ if (mode=bm_pm) and matchstr(bc_pm+'ifndef'+bc_ob,bm_pm) then
+ begin
+ setmode(length(bc_pm+'ifndef'+bc_ob),bm_pm,bm_if);
+ mode:=bm_ifn_scb;
+ bli[0]:=lineInfo;
+ bl:=1;
+ end;
+ if (mode=bm_pm) and matchstr(bc_pm+'ifeq'+bc_ob,bm_pm) then
+ begin
+ setmode(length(bc_pm+'ifeq'+bc_ob),bm_pm,bm_if);
+ mode:=bm_ifeq_scb1;
+ bm_expand:=bm_ifeq_scb1;
+ bli[0]:=lineInfo;
+ bl:=1;
+ end;
+ if (mode=bm_pm) and matchstr(bc_pm+'ifneq'+bc_ob,bm_pm) then
+ begin
+ setmode(length(bc_pm+'ifeq'+bc_ob),bm_pm,bm_if);
+ mode:=bm_ifneq_scb1;
+ bm_expand:=bm_ifneq_scb1;
+ bli[0]:=lineInfo;
+ bl:=1;
+ end;
+
+ if (mode=bm_if_not) and matchstr(bc_pm+'ifdef'+bc_ob,bm_if_not) then
+ begin
+ setmode(length(bc_pm+'ifdef'+bc_ob),bm_if_not,bm_if);
+ ifc+=1;
+ if ifc>maxifs then faterror('if memory exceeded');
+ ifli[ifc]:=lineInfo;
+ ifs[ifc]:=2;
+ end;
+ if (mode=bm_if_not) and matchstr(bc_pm+'ifndef'+bc_ob,bm_if_not) then
+ begin
+ setmode(length(bc_pm+'ifndef'+bc_ob),bm_if_not,bm_if);
+ ifc+=1;
+ if ifc>maxifs then faterror('if memory exceeded');
+ ifli[ifc]:=lineInfo;
+ ifs[ifc]:=2;
+ end;
+ if (mode=bm_if_not) and matchstr(bc_pm+'ifeq'+bc_ob,bm_if_not) then
+ begin
+ setmode(length(bc_pm+'ifeq'+bc_ob),bm_if_not,bm_if);
+ ifc+=1;
+ if ifc>maxifs then faterror('if memory exceeded');
+ ifli[ifc]:=lineInfo;
+ ifs[ifc]:=2;
+ end;
+ if (mode=bm_if_not) and matchstr(bc_pm+'ifneq'+bc_ob,bm_if_not) then
+ begin
+ setmode(length(bc_pm+'ifneq'+bc_ob),bm_if_not,bm_if);
+ ifc+=1;
+ if ifc>maxifs then faterror('if memory exceeded');
+ ifli[ifc]:=lineInfo;
+ ifs[ifc]:=2;
+ end;
+
+ if ((mode=bm_ifeq_scb1) or (mode=bm_ifeq_scb1_ne) or (mode=bm_ifneq_scb1) or (mode=bm_ifneq_scb1_ne)) and (bl=0) then
+ begin
+ bufm[rbp]:=bm_ifb;
+ if (mode=bm_ifeq_scb1) or (mode=bm_ifeq_scb1_ne)
+ then mode:=bm_ifeq_sob
+ else mode:=bm_ifneq_sob;
+ ampos:=lineInfo;
+ bm_expand:=bm_plain;
+ end;
+
+ if ((mode=bm_ifeq_sob) or (mode=bm_ifneq_sob)) and (rbuf[rbp]=bc_ob) then
+ begin
+ bli[0]:=lineInfo;
+ bl:=1;
+ if mode=bm_ifeq_sob
+ then mode:=bm_ifeq_scb2
+ else mode:=bm_ifneq_scb2;
+ bm_expand:=mode;
+ end;
+
+ if ((mode=bm_if_scb) or (mode=bm_ifn_scb)) and (bl=0) then
+ begin
+ sx:=lastmodestr1(mode);
+ if length(sx)<1
+ then begin
+ warning('empty symbol name');
+ mode:=bm_pm;
+ end
+ else begin
+ ifc+=1;
+ if ifc>maxifs then faterror('if memory exceeded');
+ ifli[ifc]:=lineInfo;
+ if mode=bm_if_scb
+ then ifs[ifc]:=0
+ else ifs[ifc]:=1;
+ i:=lastmacro;
+ while i>=0 do
+ begin
+ if (macros[i]^.name=sx) then
+ begin
+ if mode=bm_if_scb
+ then ifs[ifc]:=1
+ else ifs[ifc]:=0;
+ i:=0;
+ end;
+ i-=1;
+ end;
+ if ifs[ifc]=0
+ then mode:=bm_if_not
+ else mode:=bm_pm;
+ end;
+ end;
+ if ((mode=bm_ifeq_scb2) or (mode=bm_ifeq_scb2_ne) or (mode=bm_ifneq_scb2) or (mode=bm_ifneq_scb2_ne)) and (bl=0) then
+ begin
+ i:=0;
+ j:=0;
+ repeat
+ repeat
+ i+=1;
+ k:=bufm[(rbp-i) and rbufmax];
+// writeln(stderr,' i=',i,' k=',k);
+ until (i>=rbufmax) or (k=bm_if) or (k=bm_ifeq_scb2) or (k=bm_ifeq_scb2_ne) or (k=bm_ifneq_scb2) or (k=bm_ifneq_scb2_ne);
+ repeat
+ j+=1;
+ l:=bufm[(rbp-j) and rbufmax];
+// writeln(stderr,' j=',j,' l=',l);
+ until (j>=rbufmax) or (l=bm_if) or (l=bm_ifeq_scb1) or (l=bm_ifeq_scb1_ne) or (l=bm_ifneq_scb1) or (l=bm_ifneq_scb1_ne);
+// writeln(stderr,rbp,',',i,',',j,'-->',rbuf[(rbp-i) and rbufmax],'<-->',rbuf[(rbp-j) and rbufmax],'<--');
+ until (j>=rbufmax) or (l=bm_if) or (k=bm_if) or (rbuf[(rbp-i) and rbufmax]<>rbuf[(rbp-j) and rbufmax]);
+// writeln(stderr);
+ ifc+=1;
+ if ifc>maxifs then faterror('if memory exceeded');
+ ifli[ifc]:=lineInfo;
+
+ if (i=j) = ((mode=bm_ifeq_scb2) or (mode=bm_ifeq_scb2_ne))
+ then ifs[ifc]:=1
+ else ifs[ifc]:=0;
+
+ if ifs[ifc]=0
+ then mode:=bm_if_not
+ else mode:=bm_pm;
+ bm_expand:=bm_plain;
+ end;
+
+ if (mode=bm_pm) and matchstr(bc_pm+'else',bm_pm) then
+ begin
+ if ifc<0 then error('else without ifdef');
+ if ifs[ifc]<>1 then error('internal error 5');
+ ifs[ifc]:=0;
+ mode:=bm_if_not;
+ end;
+ if (mode=bm_pm) and ( matchstr(bc_pm+'elifdef'+bc_ob,bm_pm)
+ or matchstr(bc_pm+'elifndef'+bc_ob,bm_pm)
+ or matchstr(bc_pm+'elifeq'+bc_ob,bm_pm)
+ or matchstr(bc_pm+'elifneq'+bc_ob,bm_pm) ) then
+ begin
+ if ifc<0 then error('else without ifdef');
+ if ifs[ifc]<>1 then error('internal error 5');
+ ifs[ifc]:=2;
+ mode:=bm_if_not;
+ end;
+
+ if (mode=bm_if_not) and matchstr(bc_pm+'else',bm_if_not) then
+ begin
+ setmode(length(bc_pm+'else'+bc_ob),bm_if_not,bm_if);
+ if ifc<0
+ then error('else without ifdef')
+ else if ifs[ifc]=0
+ then begin
+ ifs[ifc]:=1;
+ mode:=bm_pm;
+ end
+ else begin
+ if ifs[ifc]<>2 then error('internal error 6')
+ end;
+ end;
+ if (mode=bm_if_not) and matchstr(bc_pm+'elifdef'+bc_ob,bm_if_not) then
+ begin
+ setmode(length(bc_pm+'elifdef'+bc_ob),bm_if_not,bm_if);
+ if ifc<0
+ then error('elifdef without ifdef')
+ else if ifs[ifc]=0
+ then begin
+ ifc-=1;
+ mode:=bm_if_scb;
+ bli[0]:=lineInfo;
+ bl:=1;
+ end
+ else begin
+ if ifs[ifc]<>2 then error('internal error 6a')
+ end;
+ end;
+ if (mode=bm_if_not) and matchstr(bc_pm+'elifndef'+bc_ob,bm_if_not) then
+ begin
+ setmode(length(bc_pm+'elifndef'+bc_ob),bm_if_not,bm_if);
+ if ifc<0
+ then error('elifndef without ifdef')
+ else if ifs[ifc]=0
+ then begin
+ ifc-=1;
+ mode:=bm_ifn_scb;
+ bli[0]:=lineInfo;
+ bl:=1;
+ end
+ else begin
+ if ifs[ifc]<>2 then error('internal error 6b')
+ end;
+ end;
+ if (mode=bm_if_not) and matchstr(bc_pm+'elifeq'+bc_ob,bm_if_not) then
+ begin
+ setmode(length(bc_pm+'elifeq'+bc_ob),bm_if_not,bm_if);
+ if ifc<0
+ then error('elifeq without ifdef')
+ else if ifs[ifc]=0
+ then begin
+ ifc-=1;
+ mode:=bm_ifeq_scb1;
+ bm_expand:=bm_ifeq_scb1;
+ bli[0]:=lineInfo;
+ bl:=1;
+ end
+ else begin
+ if ifs[ifc]<>2 then error('internal error 6c')
+ end;
+ end;
+ if (mode=bm_if_not) and matchstr(bc_pm+'elifneq'+bc_ob,bm_if_not) then
+ begin
+ setmode(length(bc_pm+'elifneq'+bc_ob),bm_if_not,bm_if);
+ if ifc<0
+ then error('elifneq without ifdef')
+ else if ifs[ifc]=0
+ then begin
+ ifc-=1;
+ mode:=bm_ifneq_scb1;
+ bm_expand:=bm_ifneq_scb1;
+ bli[0]:=lineInfo;
+ bl:=1;
+ end
+ else begin
+ if ifs[ifc]<>2 then error('internal error 6d')
+ end;
+ end;
+
+ if ((mode=bm_if_not) or (mode=bm_pm)) and (matchstr(bc_pm+'endif',bm_if_not) or matchstr(bc_pm+'endif',bm_pm)) then
+ begin
+ if ifc<0
+ then error('endif without if')
+ else ifc-=1;
+ if (ifc=-1) or (ifs[ifc]=1)
+ then mode:=bm_pm
+ else mode:=bm_if_not;
+ end;
+ if mode=bm_if_not then goto endparse;
+{define mode}
+ if mode=bm_def_sob2 then
+ begin
+ if rbuf[rbp]=bc_ob
+ then begin
+ mode:=bm_def_scb2;
+ bli[0]:=lineInfo;
+ bl:=1;
+ end
+ else begin
+ mode:=bm_pm;
+ setmode(1,-1,bm_pm);
+ end;
+ end;
+ if mode=bm_def_sob3 then
+ begin
+ if rbuf[rbp]=bc_ob
+ then begin
+ mode:=bm_def_scb3;
+ bli[0]:=lineInfo;
+ bl:=1;
+ end
+ else begin
+ lastmodestr1(bm_def_scb2, macros[lastmacro]^.rsize, macros[lastmacro]^.r, macros[lastmacro]^.li);
+ mode:=bm_pm;
+ setmode(1,-1,bm_pm);
+ end;
+ end;
+ if (mode=bm_def_scb1) and (bl=0) then
+ begin
+ mode:=bm_def_sob2;
+ sx:=lastmodestr1(bm_def_scb1);
+ if length(sx)<1
+ then begin
+ warning('empty macro name');
+ mode:=bm_pm;
+ end
+ else initsymb(sx);
+ end;
+ if (mode=bm_def_scb2) and (bl=0) then
+ begin
+ mode:=bm_def_sob3;
+ end;
+ if (mode=bm_def_scb3) and (bl=0) then
+ begin
+ mode:=bm_pm;
+ lastmodestr(bm_def_scb2,i,j);
+ j-=1;
+ k:=1;
+ while k<=j do
+ begin
+ if rbuf[i]=bc_pa
+ then begin
+ if macros[lastmacro]^.pn>=maxparams then error('only '+int2str(maxparams)+' paramters allowed');
+ if k=j then error(paramids[macros[lastmacro]^.pn+1]+' expected after `'+bc_pa+''', found '+bc_cb)
+ else begin
+ inc(k);
+ i:=(i+1) and rbufmax;
+ if rbuf[i]=paramids[macros[lastmacro]^.pn+1]
+ then inc(macros[lastmacro]^.pn)
+ else error(paramids[macros[lastmacro]^.pn+1]+' expected after `'+bc_pa+''', found '+rbuf[i]);
+ end;
+ end
+ else macros[lastmacro]^.paramsep[macros[lastmacro]^.pn]+=rbuf[i];
+ i:=(i+1) and rbufmax;
+ k+=1;
+ end;
+ if (macros[lastmacro]^.pn>0) then
+ begin
+ if macros[lastmacro]^.paramsep[0]='' then macros[lastmacro]^.paramsep[0]:=bc_ob;
+ if macros[lastmacro]^.paramsep[macros[lastmacro]^.pn]='' then macros[lastmacro]^.paramsep[macros[lastmacro]^.pn]:=bc_cb;
+ end;
+ for i:=1 to macros[lastmacro]^.pn-1 do
+ if macros[lastmacro]^.paramsep[i]='' then macros[lastmacro]^.paramsep[i]:=bc_cb+bc_ob;
+ lastmodestr1(bm_def_scb3, macros[lastmacro]^.rsize, macros[lastmacro]^.r, macros[lastmacro]^.li);
+ end;
+ if (mode=bm_def_scbu) and (bl=0) then
+ begin
+ sx:=lastmodestr1(bm_def_scbu);
+ j:=0;
+ if length(sx)<1
+ then warning('empty symbol name')
+ else begin
+ i:=lastmacro;
+ while i>=0 do
+ begin
+ if macros[i]^.name=sx then
+ begin
+ freemacro(macros[i]);
+ for j:=i to lastmacro-1 do
+ macros[j]:=macros[j+1];
+ macros[lastmacro]:=nil;
+ dec(lastmacro);
+ j:=-10;
+ i:=0;
+ end;
+ i-=1;
+ end;
+ if j<>-10 then warning('`'+sx+''' not defined');
+ end;
+ mode:=bm_pm;
+ end;
+ if (mode=bm_def_scba) and (bl=0) then
+ begin
+ sx:=lastmodestr1(bm_def_scba);
+ j:=0;
+ if length(sx)<1
+ then warning('empty symbol name')
+ else begin
+ i:=0;k:=0;
+ while i<=lastmacro do
+ if macros[i]^.name=sx
+ then begin
+ freemacro(macros[i]);
+ for j:=i to lastmacro-1 do
+ macros[j]:=macros[j+1];
+ macros[lastmacro]:=nil;
+ dec(lastmacro);
+ k:=-10;
+ end
+ else inc(i);
+ if k<>-10 then warning('`'+sx+''' not defined');
+ end;
+ mode:=bm_pm;
+ end;
+{include mode}
+ if (mode=bm_inc_scb) and (bl=0) then
+ begin
+ sx:=lastmodestr1(bm_inc_scb);
+ if length(sx)<1
+ then warning('empty include file name')
+ else CFileBuf.create(buf,sx, lineInfoStr(lineInfo)+': ');
+ mode:=bm_plain;
+ end;
+{noexpand mode}
+ if ((mode=bm_pm) or (mode=bm_ifeq_scb1) or (mode=bm_ifeq_scb2) or (mode=bm_ifneq_scb1) or (mode=bm_ifneq_scb2)) and matchstr(bc_pm+'noexpand'+bc_ob,bm_pm) then
+ begin
+ setmode(length(bc_pm+'noexpand'+bc_ob),bm_pm,bm_noexpand);
+ mode:=bm_noexpand_scb;
+ bli[0]:=lineInfo;
+ bl:=1;
+ end;
+ if (mode=bm_noexpand_scb) and (bl=0) then
+ begin
+ endnoexpand:=lastmodestr1(bm_noexpand_scb);
+ case bm_expand of
+ bm_ifeq_scb1 : mode:=bm_ifeq_scb1_ne;
+ bm_ifeq_scb2 : mode:=bm_ifeq_scb2_ne;
+ bm_ifneq_scb1 : mode:=bm_ifneq_scb1_ne;
+ bm_ifneq_scb2 : mode:=bm_ifneq_scb2_ne;
+ else mode:=bm_neplain;
+ end;
+ ampos:=lineInfo;
+ end;
+ if ((mode=bm_neplain) or (mode=bm_ifeq_scb1_ne) or (mode=bm_ifeq_scb2_ne) or (mode=bm_ifneq_scb1_ne) or (mode=bm_ifneq_scb2_ne)) and (endnoexpand<>'') and matchstr(endnoexpand,bm_neplain) then
+ begin
+ setmode(length(endnoexpand),bm_neplain,bm_noexpand);
+ case bm_expand of
+ bm_ifeq_scb1_ne : mode:=bm_ifeq_scb1;
+ bm_ifeq_scb2_ne : mode:=bm_ifeq_scb2;
+ bm_ifneq_scb1_ne : mode:=bm_ifneq_scb1;
+ bm_ifneq_scb2_ne : mode:=bm_ifneq_scb2;
+ else mode:=bm_plain;
+ end;
+ end;
+{error mode}
+ if (mode=bm_err_scb) and (bl=0) then
+ begin
+ error(lastmodestr1(bm_err_scb));
+ mode:=bm_plain;
+ bmp_exit:=bmp_exit_usererror;
+ end;
+{warning mode}
+ if (mode=bm_warn_scb) and (bl=0) then
+ begin
+ warning(lastmodestr1(bm_warn_scb));
+ mode:=bm_plain;
+ end;
+{programming mode}
+ if mode=bm_pm then
+ begin
+ if matchstr(bc_pm+bc_pm,bm_pm) then
+ begin
+ setmode(length(bc_pm),bm_pm,bm_plain);
+ mode:=bm_plain;
+ end;
+ if matchstr(bc_lf,bm_pm) then mode:=bm_plain;
+ if matchstr(bc_pm+'define'+bc_ob,bm_pm) then
+ begin
+ setmode(length(bc_pm+'define'+bc_ob),bm_pm,bm_def);
+ mode:=bm_def_scb1;
+ bli[0]:=lineInfo;
+ bl:=1;
+ end;
+ if matchstr(bc_pm+'udefine'+bc_ob,bm_pm) then
+ begin
+ setmode(length(bc_pm+'udefine'+bc_ob),bm_pm,bm_def);
+ mode:=bm_def_scbu;
+ bli[0]:=lineInfo;
+ bl:=1;
+ end;
+ if matchstr(bc_pm+'uadefine'+bc_ob,bm_pm) then
+ begin
+ setmode(length(bc_pm+'uadefine'+bc_ob),bm_pm,bm_def);
+ mode:=bm_def_scba;
+ bli[0]:=lineInfo;
+ bl:=1;
+ end;
+ if matchstr(bc_pm+'nolf',bm_pm) then
+ begin
+ i:=rbp; j:=0; k:=0;
+ while (j<=rbufmax+1-length(bc_lf)) and (k=0) do
+ begin
+ rbp:=(rbp-1) and rbufmax;
+ if matchstr(bc_lf,bm_plain) then
+ begin
+ setmode(length(bc_lf),-1,bm_comm);
+ k:=1;
+ end;
+ j+=1;
+ end;
+ rbp:=i;
+ end;
+ if matchstr(bc_pm+'include'+bc_ob,bm_pm) then
+ begin
+ setmode(length(bc_pm+'include'+bc_ob),bm_pm,bm_inc);
+ mode:=bm_inc_scb;
+ bli[0]:=lineInfo;
+ bl:=1;
+ end;
+ if matchstr(bc_pm+'error'+bc_ob,bm_pm) then
+ begin
+ setmode(length(bc_pm+'error'+bc_ob),bm_pm,bm_err);
+ mode:=bm_err_scb;
+ bli[0]:=lineInfo;
+ bl:=1;
+ end;
+ if matchstr(bc_pm+'warning'+bc_ob,bm_pm) then
+ begin
+ setmode(length(bc_pm+'warning'+bc_ob),bm_pm,bm_warn);
+ mode:=bm_warn_scb;
+ bli[0]:=lineInfo;
+ bl:=1;
+ end;
+ if matchstr(bc_pm+'disableout',bm_pm) then bufm[rbp]:=bm_outfile_a;
+ if matchstr(bc_pm+'enableout',bm_pm) then bufm[rbp]:=bm_outfile_a+1;
+ if matchstr(bc_pm+'ignorecase',bm_pm) then bp_icase:=true;
+ if matchstr(bc_pm+'exactcase',bm_pm) then bp_icase:=false;
+ end;
+
+{expanding mode}
+ if ((mode>=bm_em_p0) and (mode<=bm_em_pz)) and (matchstr(bp_icase, amacro^.paramsep[mode-bm_em_p0], mode)) then
+ begin
+ setmode(length(amacro^.paramsep[mode-bm_em_p0])-1,mode,bm_em);
+ if (mode=bm_em_pz) or (mode-bm_em_p0=amacro^.pn)
+ then begin
+ mode:=bm_expand;
+ if amacro^.rsize<0 then error('internal error 2');
+ if amacro^.rsize>0 then
+ begin
+ tmpmbuf:=CMacroBuf.create(buf, amacro, false);
+ i:=0;
+ while i=macrobuf_size-1 then CMacroBuf.insert(tmpmbuf);
+ if (amacro^.r[i]=bc_pa) and (i+1=macrobuf_size-1 then CMacroBuf.insert(tmpmbuf);
+ inc(tmpmbuf.lastbuf);
+ tmpmbuf.buf[tmpmbuf.lastbuf]:=bc_pa;
+ tmpmbuf.li[tmpmbuf.lastbuf]:=amacro^.li[i];
+ inc(i);
+ end;
+ end
+ else begin
+ l:=-1;
+ repeat
+ inc(l);
+ until (l>amacro^.pn) or (paramids[l]=amacro^.r[i]);
+ if l<=amacro^.pn
+ then begin
+ lastmodestr(bm_em_p0+l,j,k);
+ dec(k);
+ while (k>0) do
+ begin
+ if tmpmbuf.lastbuf>=macrobuf_size-1 then CMacroBuf.insert(tmpmbuf);
+ inc(tmpmbuf.lastbuf);
+ tmpmbuf.buf[tmpmbuf.lastbuf]:=rbuf[j];
+ tmpmbuf.li[tmpmbuf.lastbuf]:=li[j];
+ j:=(j+1) and rbufmax;
+ dec(k);
+ end;
+ inc(i);
+ end
+ else begin
+ inc(tmpmbuf.lastbuf);
+ tmpmbuf.buf[tmpmbuf.lastbuf]:=bc_pa;
+ tmpmbuf.li[tmpmbuf.lastbuf]:=amacro^.li[i];
+ end;
+ end;
+ end
+ else begin
+ inc(tmpmbuf.lastbuf);
+ tmpmbuf.buf[tmpmbuf.lastbuf]:=amacro^.r[i];
+ tmpmbuf.li[tmpmbuf.lastbuf]:=amacro^.li[i];
+ inc(i);
+ end;
+ end;
+ end;
+ end
+ else inc(mode);
+ end;
+ end;
+{plain mode}
+ if mode=bm_expand then
+ begin
+ i:=3; j:=0; k:=rbp; { equal to copylaststr_br(4,bm_expand); }
+ i4:=0;
+ while (i>=0) and (j<=rbufmax) do
+ begin
+ if bufm[k]=bm_expand then
+ begin
+ s4[i]:=rbuf[k];
+ i-=1;
+ end;
+ k:=(k-1) and rbufmax;
+ j+=1;
+ end;
+
+ if (mode=bm_plain) and ((i4 xor pm_s) and pm_m=0) and (pm_q or matchstr(bc_pm,bm_plain)) and (matchstr(bc_lf+bc_pm) or (buf.d=length(bc_pm)))
+ then begin
+ mode:=bm_pm;
+ setmode(length(bc_pm),bm_plain,mode);
+ end
+ else begin
+ if bp_icase
+ then begin
+ if (s4[0]>='a') and (s4[0]<='z') then byte(s4[0])-=32;
+ if (s4[1]>='a') and (s4[1]<='z') then byte(s4[1])-=32;
+ if (s4[2]>='a') and (s4[2]<='z') then byte(s4[2])-=32;
+ if (s4[3]>='a') and (s4[3]<='z') then byte(s4[3])-=32;
+ j:=1;
+ end
+ else j:=0;
+
+ i:=lastmacro;
+ while i>=0 do
+ begin
+ amacro:=macros[i];
+ if (amacro^.rsize>=0) and (amacro^.enabled) and ((i4 xor amacro^.mmatch_s[j]) and amacro^.mmatch_m=0) and (amacro^.quick or matchstr_br(bp_icase,amacro^.name,bm_expand)) then
+ begin
+ setmode(length(amacro^.name),bm_expand,bm_em);
+ ampos:=lineInfo;
+ if amacro^.paramsep[0]=''
+ then begin
+ if amacro^.rsize>0 then CMacroBuf.create(buf, amacro, true);
+ end
+ else mode:=bm_em_p0;
+ i:=0;
+ end;
+ i-=1;
+ end;
+ end;
+ end;
+endparse:
+ rbp:=(rbp+1) and rbufmax;
+ end;
+ end;
+
+if bmp_exit=0 then case mode of
+ bm_plain, bm_pm, bm_def_sob2, bm_def_sob3, bm_if_not
+ : if ifc>=0 then
+ begin
+ if ifc>0 then sx:='if''s without endif''s at '+lineInfoStr(ifli[0])
+ else sx:='if without endif at '+lineInfoStr(ifli[0]);
+ for i:=1 to ifc do
+ sx+=', '+lineInfoStr(ifli[i]);
+ error(sx);
+ end;
+ bm_neplain, bm_ifeq_scb1_ne, bm_ifeq_scb2_ne, bm_ifneq_scb1_ne, bm_ifneq_scb2_ne
+ : error('Unexpected end of file, `'+endnoexpand+''' expected for '+bc_pm+'noexpand at '+lineInfoStr(ampos));
+ bm_em_p0..bm_em_pz
+ : error('Unexpected end of file, `'+amacro^.paramsep[mode-bm_em_p0]+''' expected for '+amacro^.name+' at '+lineInfoStr(ampos));
+ bm_def_scb1, bm_def_scb2, bm_def_scb3, bm_def_scbu, bm_def_scba,
+ bm_if_scb, bm_ifn_scb, bm_ifeq_scb1, bm_ifeq_scb2, bm_ifneq_scb1, bm_ifneq_scb2,
+ bm_inc_scb, bm_err, bm_err_scb, bm_warn
+ : begin
+ if bl>1 then begin
+ if bl>2 then sx:=', there are unclosed `'+bc_ob+'''s at '+lineInfoStr(bli[1])
+ else sx:=', there is a unclosed `'+bc_ob+''' at '+lineInfoStr(bli[1]);
+ for i:=2 to bl-1 do
+ sx+=', '+lineInfoStr(bli[i]);
+ end
+ else sx:=' (maybe there are unclosed `'+bc_ob+'''s)';
+ error('Unexpected end of file, `'+bc_cb+''' expected for `'+bc_ob+''' at '+lineInfoStr(bli[0])+sx);
+ end;
+ bm_ifeq_sob
+ : error('Unexpected end of file, `'+bc_ob+''' expected for '+bc_pm+'ifeq at '+lineInfoStr(ampos));
+ bm_ifneq_sob
+ : error('Unexpected end of file, `'+bc_ob+''' expected for '+bc_pm+'ifneq at '+lineInfoStr(ampos));
+ else error('Unexpected end of file ('+int2str(mode)+')');
+ end;
+
+for k:=0 to rbufmax do
+ begin
+{$ifdef ENABLE_DEBUGOUT }
+ if debugoutput then debugwrite;
+{$endif}
+ i:=bufm[rbp];
+ if (i<10) and (i>=0) and (outfile>0) then
+ begin
+ j:=ord(writebuf[0])+1; { avoid the range checking }
+ writebuf[0]:=char(j);
+ writebuf[j]:=rbuf[rbp];
+ if rbuf[rbp]=#10 then
+ begin
+ if (li[rbp]<>prevli+4096) and (lineInfoPattern<>'') then lineInfoStr(fo,li[rbp]);
+ prevli:=li[rbp];
+ byte(writebuf[0])-=1;
+ writeln(fo,writebuf);
+ writebuf:='';
+ end;
+ if j>=255 then
+ begin
+ write(fo,writebuf);
+ writebuf:='';
+ end;
+ end
+ else if (i>=bm_outfile_a) and (i<=bm_outfile_z) then outfile:=i-bm_outfile_a;
+ rbp:=(rbp+1) and rbufmax;
+ end;
+write(fo,writebuf);
+if printdefs then printmacros;
+end;
+
+{ ******** initsymb ************************************************** }
+procedure CMainBmp.initsymb(const s:bmpstring);
+var s4 : TS4;
+begin
+lastmacro+=1;
+if lastmacro>maxmacros then faterror('Macro memory exceeded');
+
+getmem(macros[lastmacro],sizeof(TBabelMacro));
+fillchar( macros[lastmacro]^, sizeof(TBabelMacro), 0 );
+
+s4.s:=copy(' '+s,length(s)+1,4);
+macros[lastmacro]^.mmatch_s[0]:=s4.i;
+upstr2(s4.s);
+macros[lastmacro]^.mmatch_s[1]:=s4.i;
+macros[lastmacro]^.mmatch_m:=$ffffffff shl ((4-min(length(s),4))*8);
+macros[lastmacro]^.quick:=length(s)<=4;
+macros[lastmacro]^.enabled:=true;
+
+macros[lastmacro]^.rsize:=-1;
+macros[lastmacro]^.pn:=0;
+macros[lastmacro]^.name:=s;
+end;
+
+{ ****** error_int ************************************************** }
+procedure CMainBmp.error_int(const t:ansistring);
+var i,j,k : longint;
+ tmp : CTextBuf;
+ s : shortstring;
+begin
+tmp:=buf;
+i:=0;
+while tmp<>nil do
+ begin
+ tmp:=CTextBuf(tmp.last);
+ i+=1;
+ end;
+s:='';
+for j:=1 to i do
+ begin
+ tmp:=buf;
+ for k:=1 to i-j do
+ tmp:=tmp.last;
+ k:=tmp.d;
+ if k>0 then k-=1;
+ writeln(stderr, s, lineInfoStr(tmp.li[k]), ':');
+ s+=' ';
+ end;
+writeln(stderr,s,t);
+end;
+
+{ ****** hint ******************************************************* }
+procedure CMainBmp.hint(const s:ansistring);
+begin
+if enable_hints then writeln(stderr,'Hint: '+lineInfoStr(lineInfo)+': '+s);
+end;
+
+{ ****** warning **************************************************** }
+procedure CMainBmp.warning(const s:ansistring);
+begin
+error_int('Warning: '+s);
+end;
+
+{ ****** error ****************************************************** }
+procedure CMainBmp.error(const s:ansistring);
+begin
+error_int('Error: '+s);
+bmp_exit:=bmp_exit_error;
+end;
+
+{ ****** faterror *************************************************** }
+procedure CMainBmp.faterror(const s:ansistring);
+begin
+error_int('Fatal error: '+s);
+halt(bmp_exit_faterror);
+end;
+
+{ ****** copylaststr ************************************************ }
+function CMainBmp.copylaststr(l,mode:longint):rbufstr;
+var i,k : longint;
+begin
+l:=l and rbufmax;
+i:=0; k:=rbp;
+while (i255 then l:=255;
+{$endif}
+i:=0; j:=0; k:=rbp;
+setlength(result,l);
+while (imode) and (j<=rbufmax) do
+ begin
+ i:=(i-1) and rbufmax;
+ j+=1;
+ end;
+while (bufm[i]=mode) and (j<=rbufmax) do
+ begin
+ i:=(i-1) and rbufmax;
+ j+=1;
+ k+=1;
+ end;
+i:=(i+1) and rbufmax;
+fst:=i;
+l:=k;
+end;
+
+procedure CMainBmp.lastmodestr(mode:longint; var size:longint; var ptc:pchar; var ptli:pdword);
+var i,j,k : longint;
+begin
+lastmodestr(mode,i,j);
+if j>0 then begin
+ size:=j;
+ getmem(ptc,j);
+ getmem(ptli,j*4);
+ for k:=0 to j-1 do
+ begin
+ ptc[k]:=rbuf[i];
+ ptli[k]:=li[i];
+ i:=(i+1) and rbufmax;
+ end;
+ end
+ else begin
+ size:=0;
+ ptc:=nil;
+ ptli:=nil;
+ end;
+end;
+
+function CMainBmp.lastmodestr(mode:longint):bmpstring;
+var i,j,k : longint;
+begin
+lastmodestr(mode,i,j);
+{$ifdef USE_SHORTSTRINGS}
+if j>255 then j:=255;
+{$endif}
+setlength(lastmodestr,j);
+for k:=1 to j do
+ begin
+ lastmodestr[k]:=rbuf[i];
+ i:=(i+1) and rbufmax;
+ end;
+end;
+
+procedure CMainBmp.lastmodestr1(mode:longint; var size:longint; var ptc:pchar; var ptli:pdword);
+var i,j,k : longint;
+begin
+lastmodestr(mode,i,j);
+j-=1;
+if j>0 then begin
+ size:=j;
+ getmem(ptc,j);
+ getmem(ptli,j*4);
+ for k:=0 to j-1 do
+ begin
+ ptc[k]:=rbuf[i];
+ ptli[k]:=li[i];
+ i:=(i+1) and rbufmax;
+ end;
+ end
+ else begin
+ size:=0;
+ ptc:=nil;
+ ptli:=nil;
+ end;
+end;
+
+function CMainBmp.lastmodestr1(mode:longint):bmpstring;
+var i,j,k : longint;
+begin
+lastmodestr(mode,i,j);
+j-=1;
+{$ifdef USE_SHORTSTRINGS}
+if j>255 then j:=255;
+{$endif}
+setlength(lastmodestr1,j);
+for k:=1 to j do
+ begin
+ lastmodestr1[k]:=rbuf[i];
+ i:=(i+1) and rbufmax;
+ end;
+end;
+
+
+{ ****** setmode ***************************************************** }
+procedure CMainBmp.setmode(num,om,nm:longint);
+var i,j,k : longint;
+begin
+k:=rbp;
+i:=0; j:=0;
+while (i'' then write(stderr,m[j]^.paramsep[0]);
+ for i:=1 to m[j]^.pn do
+ write(stderr,bc_pa,i,m[j]^.paramsep[i]);
+ if (m[j]^.pn>0) or (m[j]^.paramsep[0]<>'') then writeln(stderr);
+ for i:=0 to m[j]^.rsize-1 do
+ write(stderr,m[j]^.r[i]);
+ if m[j]^.rsize>0 then writeln(stderr);
+ if m[j]^.rsize=0 then writeln(stderr,'');
+ writeln(stderr);
+ writeln(stderr);
+ end;
+end;
+
+procedure CMainBmp.printmacros;
+begin
+printmacros(macros, lastmacro);
+end;
+
+{$ifdef ENABLE_DEBUGOUT }
+{ ******** debugwrite ************************************************ }
+procedure CMainBmp.debugwrite;
+var i : longint;
+ lf : boolean;
+begin
+if rbuf[rbp]=#10
+ then begin
+ writeln;
+ lf:=true;
+ end
+ else lf:=false;
+if (bufm[rbp]<>bm_invalid) and (rbuf[rbp]<>#13) and (rbuf[rbp]<>#10) then write(rbuf[rbp]);
+i:=(rbp+1) and rbufmax;
+if bufm[rbp]<>bufm[i]
+ then begin
+ if not lf then writeln;
+ write(bufm[i]);
+ case bufm[i] of
+ 0..9 : write(' ');
+ 10..99 : write(' ');
+ 200..999 : write(' ');
+ 1000..9999 : write(' ');
+ else write(' ');
+ end;
+ end
+ else if lf then write(' ');
+end;
+{$endif}
+
+{ ********************************************************************* }
+{ ****** main ********************************************************* }
+{ ********************************************************************* }
+
+{ ****** paramerr ***************************************************** }
+procedure paramerr(msg:ansistring);
+begin
+writeln(stderr,'Usage: '+paramstr(0)+' [] [ [ ...]]');
+writeln(stderr,'Options: ');
+writeln(stderr,' -o Output file');
+writeln(stderr,' -p Pascal mode (default), equal to -mm "//" -mo "[" -mc "]" -mp "#"');
+writeln(stderr,' -c C mode, equal to -mm "#" -mo "[" -mc "]" -mp "$" -l "\"#line %2 "%1\""');
+writeln(stderr,' -i Ignore case');
+writeln(stderr,' -l Line info (default for C mode: "#line %2 \"%1\"")');
+writeln(stderr,' -I Include path');
+writeln(stderr,' -D Define symbol ');
+writeln(stderr,' -mm Meta macro start string');
+writeln(stderr,' -mo Open bracket');
+writeln(stderr,' -mc Close bracket');
+writeln(stderr,' -mp Parameter sign');
+//writeln(stderr,' -nh Disable hints');
+{$ifdef ENABLE_DEBUGOUT}
+writeln(stderr,' -do Enable debug output');
+{$endif}
+writeln(stderr,' -dd Print definitions');
+writeln(stderr,' -h Help');
+if msg<>''
+ then begin
+ writeln(stderr,msg);
+ halt(bmp_exit_paramerror);
+ end
+ else halt(0);
+end;
+
+{ ****** main ********************************************************* }
+const maxInfilec = 1024;
+
+var main : CMainBmp;
+ infile : array[0..maxInfilec-1] of ansistring;
+ i,j,infilec : longint;
+ s,t : ansistring;
+ fo : text;
+
+ fofn : ansistring;
+ bc_pm_d,bc_ob_d : boolean;
+ bc_cb_d,bc_pa_d : boolean;
+ pasmode,lidef : boolean;
+
+begin
+spath[0]:='';
+spathc:=1;
+
+main:=CMainBmp.create;
+
+fofn:='';
+bc_pm_d:=false;
+bc_ob_d:=false;
+bc_cb_d:=false;
+bc_pa_d:=false;
+pasmode:=true;
+lidef:=false;
+
+infilec:=0;
+i:=1;
+while i<=paramcount do
+ begin
+ s:=paramstr(i);
+ if (length(s)>1) and (s[1]='-')
+ then begin
+ if s='-o' then
+ begin
+ if i>=paramcount then paramerr('File name expected after -o');
+ i+=1;
+ fofn:=paramstr(i);
+ end
+ else if s='-p' then pasmode:=true
+ else if s='-c' then pasmode:=false
+ else if s='-i' then bp_icase:=true
+ else if s='-l' then
+ begin
+ if i>=paramcount then paramerr('String expected after -l');
+ i+=1;
+ lineInfoPattern:=paramstr(i);
+{$ifdef WINDOWS}
+ for j:=1 to length(lineInfoPattern) do
+ if lineInfoPattern[j]='\' then lineInfoPattern[j]:='"';
+{$endif}
+ lidef:=true;
+ end
+ else if s='-I' then
+ begin
+ if i>=paramcount then paramerr('Path expected after -I');
+ i+=1;
+ t:=paramstr(i);
+{$ifdef WINDOWS}
+ for j:=1 to length(t) do
+ if t[j]='/' then t[j]:='\';
+{$endif}
+ if t<>'' then
+ begin
+ if t[length(t)]<>dirsep then t+=dirsep;
+ if spathc>=maxspathc
+ then bmp_error('Maximum amount of search paths reached')
+ else begin
+ spath[spathc]:=t;
+ spathc+=1;
+ end;
+ end;
+ end
+ else if s='-D' then
+ begin
+ if i>=paramcount then paramerr('Symbol expected after -D');
+ i+=1;
+ main.initsymb(paramstr(i));
+ end
+ else if s='-mm' then
+ begin
+ if i>=paramcount then paramerr('String expected after -mm');
+ i+=1;
+ bc_pm_d:=true;
+ bc_pm:=paramstr(i);
+ end
+ else if s='-mo' then
+ begin
+ if (i>=paramcount) or (length(paramstr(i+1))<>1) then paramerr('Character expected after -mo');
+ i+=1;
+ bc_ob_d:=true;
+ bc_ob:=paramstr(i)[1];
+ end
+ else if s='-mc' then
+ begin
+ if (i>=paramcount) or (length(paramstr(i+1))<>1) then paramerr('Character expected after -mc');
+ i+=1;
+ bc_cb_d:=true;
+ bc_cb:=paramstr(i)[1];
+ end
+ else if s='-mp' then
+ begin
+ if (i>=paramcount) or (length(paramstr(i+1))<>1) then paramerr('Character expected after -mp');
+ i+=1;
+ bc_pa_d:=true;
+ bc_pa:=paramstr(i)[1];
+ end
+ else if s='-eh' then enable_hints:=false
+{$ifdef ENABLE_DEBUGOUT}
+ else if s='-do' then debugoutput:=true
+{$endif}
+ else if s='-dd' then printdefs:=true
+ else if s='-h' then paramerr('')
+ else paramerr('Invalid option: '+s);
+ end
+ else begin
+ if infilec>=maxinfilec
+ then bmp_error('Maximum amount of input files reached')
+ else begin
+{$ifdef WINDOWS}
+ for j:=1 to length(s) do
+ if s[j]='/' then s[j]:='\';
+{$endif}
+ if s='-'
+ then infile[infilec]:=''
+ else infile[infilec]:=s;
+ infilec+=1;
+ end;
+ end;
+ i+=1;
+ end;
+
+if pasmode
+ then begin
+ if not bc_pm_d then bc_pm:='//';
+ if not bc_ob_d then bc_ob:='[';
+ if not bc_cb_d then bc_cb:=']';
+ if not bc_pa_d then bc_pa:='#';
+ end
+ else begin
+ if not bc_pm_d then bc_pm:='#';
+ if not bc_ob_d then bc_ob:='[';
+ if not bc_cb_d then bc_cb:=']';
+ if not bc_pa_d then bc_pa:='$';
+ if not lidef then lineInfoPattern:='#line %2 "%1"';
+ end;
+
+if infilec=0 then
+ begin
+ infile[0]:='';
+ infilec:=1;
+ end;
+
+if fofn<>''
+ then begin
+ try
+ assign(fo,fofn);
+ rewrite(fo);
+ for i:=0 to infilec-1 do
+ main.run(infile[i],fo);
+ close(fo);
+ except
+ bmp_faterror('Error writing to file '+fofn);
+ end;
+ end
+ else for i:=0 to infilec-1 do
+ main.run(infile[i],output);
+
+main.destroy;
+halt(bmp_exit);
+end.
Index: usb_fpga_1_2/trunk/bmp/src/textbuf.pas
===================================================================
--- usb_fpga_1_2/trunk/bmp/src/textbuf.pas (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/src/textbuf.pas (revision 2)
@@ -0,0 +1,310 @@
+{*!
+ bmp -- babel macro processor
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*}
+
+{$mode objfpc}
+unit textbuf;
+
+interface
+
+const maxspathc = 1024;
+ lineInfoPattern : shortstring = '';
+
+type pdword = ^dword;
+
+ CTextBuf = class;
+ CTextBuf = class
+ buf : pchar; { character buffer }
+ li : pdword; { line info lineNum shl 12 + file }
+ lastbuf,d : longint;
+ allocsize : longint; { allocated size }
+ last : CTextBuf;
+ killme : boolean;
+ constructor create(var tb:CTextBuf);
+ constructor create(var tb:CTextBuf; asize:longint);
+ constructor create(var tb:CTextBuf; cb:pchar; lib:pdword; bufsize:longint);
+ destructor destroy; override;
+ procedure endbuf; virtual;
+ end;
+
+ CFileBuf = class(CTextBuf)
+ constructor create(var tb:CTextBuf; const fn,ep:ansistring);
+ procedure endbuf; override;
+ private
+ fileNum : longint;
+ line : longint;
+ fname : ansistring;
+ errStr : ansistring; { error trefix }
+ stat : longint;
+ f : file;
+ end;
+
+var spath : array[0..maxspathc-1] of ansistring;
+ spathc : longint;
+
+function getFileNum(const fn:ansistring):longint;
+function lineInfoStr(li:dword):ansistring;
+procedure lineInfoStr(var fo:text; li:dword);
+
+implementation
+
+uses dos,bmpsys;
+const textbuf_size = 2048;
+
+{ ********************************************************************* }
+{ ****** CTextBuf ***************************************************** }
+{ ********************************************************************* }
+{ ****** create ******************************************************* }
+constructor CTextBuf.create(var tb:CTextBuf);
+begin
+lastbuf:=-1;
+d:=0;
+killme:=false;
+last:=tb;
+tb:=self;
+end;
+
+constructor CTextBuf.create(var tb:CTextBuf; asize:longint);
+begin
+create(tb);
+getmem(buf,asize);
+getmem(li,asize*4);
+allocsize:=asize;
+end;
+
+constructor CTextBuf.create(var tb:CTextBuf; cb:pchar; lib:pdword; bufsize:longint);
+begin
+create(tb);
+buf:=cb;
+li:=lib;
+lastbuf:=bufsize-1;
+allocsize:=0;
+end;
+
+{ ****** destroy ****************************************************** }
+destructor CTextBuf.destroy;
+begin
+if allocsize>0 then
+ begin
+ freemem(buf,allocsize);
+ freemem(li,allocsize*4);
+ end;
+end;
+
+{ ****** endbuf ******************************************************* }
+procedure CTextBuf.endbuf;
+begin
+killme:=true;
+end;
+
+{ ********************************************************************* }
+{ ****** CFileBuf ***************************************************** }
+{ ********************************************************************* }
+{ ****** create ******************************************************* }
+constructor CFileBuf.create(var tb:CTextBuf; const fn,ep:ansistring);
+begin
+inherited create(tb,textbuf_size);
+stat:=0;
+pointer(fname):=nil;
+fname:=fn;
+pointer(errStr):=nil;
+errStr:=ep;
+fileNum:=-1;
+line:=0;
+end;
+
+{ ****** endbuf ******************************************************* }
+procedure CFileBuf.endbuf;
+var i,j : longint;
+ e : dword;
+ sr : searchrec;
+ dir : dirstr;
+ name : namestr;
+ ext : extstr;
+ b : boolean;
+begin
+lastbuf:=-1;
+d:=0;
+killme:=true;
+
+if stat=0 then
+ begin
+ stat:=1;
+ if fname<>'' then
+ begin
+ j:=-1;
+// write(fname+': ');
+ for i:=0 to spathc-1 do
+ begin
+// write(spath[i]+' ');
+ findfirst(spath[i]+fname,$27,sr);
+ if doserror=0 then
+ begin
+ if j<>-1
+ then bmp_warning(errstr+'`'+spath[i]+fname+''' found, using `'+spath[j]+fname+'''')
+ else j:=i;
+ end;
+ end;
+// writeln(': '+spath[j]+fname);
+
+ if j=-1 then
+ begin
+ bmp_error(errstr+'Can not find file: `'+fname+'''');
+ stat:=2;
+ exit;
+ end;
+
+ fsplit(spath[j]+fname,dir,name,ext);
+ b:=true;
+ for i:=0 to spathc-1 do
+ if dir=spath[i] then b:=false;
+ if b then
+ begin
+ if spathc>=maxspathc
+ then bmp_error(errstr+'Maximum amount of search paths reached')
+ else begin
+ spath[spathc]:=dir;
+ spathc+=1;
+ end;
+ end;
+
+ fileNum:=getFileNum(spath[j]+fname);
+ line:=0;
+ try
+ filemode:=0;
+ assign(f,spath[j]+fname);
+ reset(f,1);
+ except
+ bmp_error(errstr+'Can not open file: '+spath[j]+fname);
+ fname:='';
+ stat:=2;
+ end;
+ end;
+ end;
+
+if stat=1 then
+ begin
+ if fname=''
+ then begin
+ lastbuf:=-1;
+ while (not(eof(input))) and (lastbuf'' then
+ begin
+ try
+ close(f);
+ except
+ end;
+ end;
+ end;
+ end;
+
+if lastbuf>=0 then killme:=false;
+end;
+
+
+{ ********************************************************************* }
+{ ****** FileCache **************************************************** }
+{ ********************************************************************* }
+const fileCount : longint = 0;
+var fileCache : array[0..4095] of ansistring;
+
+{ ****** getFileNum *************************************************** }
+function getFileNum(const fn:ansistring):longint;
+var i : longint;
+begin
+i:=0;
+while (ifileCache[i]) do
+ i+=1;
+if fn<>fileCache[i] then
+ begin
+ i:=fileCount and 4095;
+ fileCache[i]:=fn;
+ fileCount+=1;
+ end;
+result:=i;
+end;
+
+{ ****** lineInfoStr ************************************************* }
+function lineInfoStr(li:dword):ansistring;
+begin
+result:=fileCache[li and 4095]+'('+int2str((li shr 12)+1)+')';
+end;
+
+procedure lineInfoStr(var fo:text; li:dword);
+var s : ansistring;
+ i,j : longint;
+begin
+pointer(s):=nil;
+i:=1;
+while i<=length(lineInfoPattern) do
+ begin
+ if (lineInfoPattern[i]='%') and (i
+ Copyright (C) 19yy
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) 19yy name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ , 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Library General
+Public License instead of this License.
Index: usb_fpga_1_2/trunk/bmp/Makefile
===================================================================
--- usb_fpga_1_2/trunk/bmp/Makefile (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/Makefile (revision 2)
@@ -0,0 +1,116 @@
+# Copyright (C) 1999-2009 Stefan Ziegenbalg
+#
+# main targets:
+# all build bmp
+# install install applications
+# install2 install applications to ../bin
+# uninstall uninstall applications
+# resetconf reset configuration
+# clean clean everything but exe's
+# distclean clean everything
+
+#########################
+# configuration section #
+#########################
+#OS operating system (UNIX for unix like OS)
+#default: detected automatically
+#e.g. OS=UNIX
+
+#PCEXTRAFLAGS additional flags
+#e.g. PCEXTRAFLAGS=-Xs
+PCEXTRAFLAGS=-gl
+
+#PREFIX base directory for installing
+#default: /usr/local for OS=UNIX and c:\usr else
+#e.g. PREFIX=/usr
+
+#BINDIR where to install bin's
+#default: $(PREFIX)/bin
+#e.g. BINDIR=/usr/bin
+
+################################
+# DO NOT CHANAGE THE FOLLOWING #
+################################
+ifndef OS
+ifeq ($(WINDIR),)
+OS=UNIX
+else
+OS=WINDOS
+endif
+endif
+
+SOURCES=src/bmp.pas src/bmpsys.pas src/textbuf.pas
+
+UNITS=-Fusrc
+
+PCFLAGS:=-Scgm -O3rGp3 -FE. -Xs $(PCEXTRAFLAGS)
+INSTALLDIR=$(INSTALL) -d
+INSTALLEXE=$(INSTALL) -m 0755
+RM=rm -f
+ECHO=echo
+
+ifeq ($(OS),UNIX)
+
+CONFIGURESCRIPT=./configure
+PC:=$(shell $(CONFIGURESCRIPT) pc "$(PCFLAGS)")
+ifndef PC
+ $(error Fatal: No correct compiler found or wrong flags)
+endif
+INSTALL=$(shell $(CONFIGURESCRIPT) install2)
+
+ifndef PREFIX
+ PREFIX=/usr/local
+endif
+
+TARGETS=bmp
+DEFS=-DUNIX
+
+else
+
+PC=ppc386
+INSTALL=install
+
+ifndef PREFIX
+ PREFIX=c:\usr
+endif
+
+TARGETS=bmp.exe
+DEFS=-DWINDOWS
+
+endif
+
+ifndef BINDIR
+ BINDIR=$(PREFIX)/bin
+endif
+
+.PHONY: all install uninstall resetconf clean distclean
+
+all: bmp.made
+
+bmp.made: $(TARGETS)
+ $(ECHO) > bmp.made
+
+bmp bmp.exe: $(SOURCES)
+ $(PC) $(PCFLAGS) $(UNITS) src/bmp.pas
+
+install: $(TARGETS)
+ $(INSTALLDIR) $(BINDIR)
+ $(INSTALLEXE) $(TARGETS) $(BINDIR)
+
+install2: $(TARGETS)
+ $(INSTALLEXE) $(TARGETS) ../bin
+
+uninstall:
+ - $(RM) $(addprefix $(BINDIR)/,$(TARGETS))
+
+resetconf:
+ - $(RM) Makefile.conf
+ - $(RM) conf_*
+
+clean:
+ - $(RM) *.bak *.o *.ppu *.s */*.bak *.log *.a *~ */*~ *.out
+ - $(RM) ppas.sh link.res
+
+
+distclean: clean resetconf
+ - $(RM) bmp bmp.exe bmp.made bmp.pas
Index: usb_fpga_1_2/trunk/bmp/Readme
===================================================================
--- usb_fpga_1_2/trunk/bmp/Readme (nonexistent)
+++ usb_fpga_1_2/trunk/bmp/Readme (revision 2)
@@ -0,0 +1,35 @@
+What is bmp
+-----------
+
+BMP is a universal macro processor.
+
+
+Compiling
+---------
+
+For compilation the freepascal compiler (http://www.freepascal.org) is
+required.
+
+To build and install everything just run make, make install, ...
+
+Hered are the main make targets:
+ all build bmp
+ install install applications
+ uninstall uninstall applications
+ resetconf reset configuration
+ clean clean everything but exe's
+ distclean clean everything
+
+
+Examples/ Tests
+---------------
+
+The directory `tests' contains some examples and tests. They can be build with
+`make test*'. (see Makefile)
+
+
+Author:
+-------
+
+Stefan Ziegenbalg
+email: stefan.ziegenbalg@simg.de
Index: usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/ucecho.sh
===================================================================
--- usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/ucecho.sh (nonexistent)
+++ usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/ucecho.sh (revision 2)
@@ -0,0 +1,4 @@
+#make -C ../../../java distclean all || exit
+#make || exit
+#rm ucecho.ihx
+java -cp UCEcho.jar UCEcho $@
usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/ucecho.sh
Property changes :
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/UCEcho.java
===================================================================
--- usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/UCEcho.java (nonexistent)
+++ usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/UCEcho.java (revision 2)
@@ -0,0 +1,182 @@
+/*!
+ ucecho -- example for ZTEX USB FPGA Module 1.2
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+import java.io.*;
+import java.util.*;
+
+import ch.ntb.usb.*;
+
+import ztex.*;
+
+// *****************************************************************************
+// ******* ParameterException **************************************************
+// *****************************************************************************
+// Exception the prints a help message
+class ParameterException extends Exception {
+ public final static String helpMsg = new String (
+ "Parameters:\n"+
+ " -d Device Number (default: 0)\n" +
+ " -f Force uploads\n" +
+ " -p Print bus info\n" +
+ " -w Enable certain workarounds which may be required for vmware + windows\n"+
+ " -h This help" );
+
+ public ParameterException (String msg) {
+ super( msg + "\n" + helpMsg );
+ }
+}
+
+// *****************************************************************************
+// ******* Test0 ***************************************************************
+// *****************************************************************************
+class UCEcho extends Ztex1v1 {
+
+// ******* UCEcho **************************************************************
+// constructor
+ public UCEcho ( ZtexDevice1 pDev ) throws UsbException, ZtexDescriptorException {
+ super ( pDev );
+ }
+
+// ******* claimInterface ******************************************************
+// claims interface 0
+ public void claimInterface ( ) throws UsbException{
+ if ( LibusbJava.usb_set_configuration(handle(), 1) < 0 )
+ throw new UsbException("Setting configuration to 1 failed: " + LibusbJava.usb_strerror());
+ if ( LibusbJava.usb_claim_interface(handle(), 0) < 0 )
+ throw new UsbException("Claiming interface 0 failed: " + LibusbJava.usb_strerror());
+ }
+
+// ******* releaseInterface ****************************************************
+// releases interface 0
+ public void releaseInterface ( ) {
+ LibusbJava.usb_release_interface(handle(), 0);
+ }
+
+// ******* echo ****************************************************************
+// writes a string to Endpoint 4, reads it back from Endpoint 2 and writes the output to System.out
+ public void echo ( String input ) throws UsbException {
+ byte buf[] = input.getBytes();
+ int i = LibusbJava.usb_bulk_write(handle, 0x04, buf, buf.length, 1000);
+ if ( i<0 )
+ throw new UsbException("Error sending data: " + LibusbJava.usb_strerror());
+ System.out.println("Send "+i+" bytes: `"+input+"'" );
+
+ try {
+ Thread.sleep( 10 );
+ }
+ catch ( InterruptedException e ) {
+ }
+
+ buf = new byte[1024];
+ i = LibusbJava.usb_bulk_read(handle, 0x82, buf, 1024, 1000);
+ if ( i<0 )
+ throw new UsbException("Error receiving data: " + LibusbJava.usb_strerror());
+ System.out.println("Read "+i+" bytes: `"+new String(buf,0,i)+"'" );
+ }
+
+// ******* main ****************************************************************
+ public static void main (String args[]) {
+
+ int devNum = 0;
+ boolean force = false;
+ boolean workarounds = false;
+
+ try {
+// init USB stuff
+ LibusbJava.usb_init();
+
+// scan the USB bus
+ ZtexScanBus1 bus = new ZtexScanBus1( ZtexDevice1.cypressVendorId, ZtexDevice1.cypressProductId, true, false, 1);
+ if ( bus.numberOfDevices() <= 0) {
+ System.err.println("No devices found");
+ System.exit(0);
+ }
+
+// scan the command line arguments
+ for (int i=0; i=args.length) throw new Exception();
+ devNum = Integer.parseInt( args[i] );
+ }
+ catch (Exception e) {
+ throw new ParameterException("Device number expected after -d");
+ }
+ }
+ else if ( args[i].equals("-f") ) {
+ force = true;
+ }
+ else if ( args[i].equals("-p") ) {
+ bus.printBus(System.out);
+ System.exit(0);
+ }
+ else if ( args[i].equals("-p") ) {
+ bus.printBus(System.out);
+ System.exit(0);
+ }
+ else if ( args[i].equals("-w") ) {
+ workarounds = true;
+ }
+ else if ( args[i].equals("-h") ) {
+ System.err.println(ParameterException.helpMsg);
+ System.exit(0);
+ }
+ else throw new ParameterException("Invalid Parameter: "+args[i]);
+ }
+
+
+// create the main class
+ UCEcho ztex = new UCEcho ( bus.device(devNum) );
+ ztex.certainWorkarounds = workarounds;
+
+// upload the firmware if necessary
+ if ( force || ! ztex.valid() || ! ztex.dev().productString().equals("ucecho for USB FPGA MODULE 1.2") ) {
+ System.out.println("Firmware upload time: " + ztex.uploadFirmware( "ucecho.ihx", force ) + " ms");
+ }
+
+// upload the bitstream if necessary
+ if ( force || ! ztex.getFpgaConfiguration() ) {
+ System.out.println("FPGA configuration time: " + ztex.configureFpga( "fpga/ucecho.bin" , force ) + " ms");
+ }
+
+
+// claim interface 0
+ ztex.claimInterface();
+
+// read string from stdin and write it to USB device
+ String str = "";
+ BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) );
+ while ( ! str.equals("quit") ) {
+ System.out.print("Enter a string or `quit' to exit the program: ");
+ str = reader.readLine();
+ if ( ! str.equals("") )
+ ztex.echo(str);
+ System.out.println("");
+ }
+
+// release interface 0
+ ztex.releaseInterface();
+
+ }
+ catch (Exception e) {
+ System.out.println("Error: "+e.getLocalizedMessage() );
+ }
+ }
+
+}
Index: usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/ucecho.c
===================================================================
--- usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/ucecho.c (nonexistent)
+++ usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/ucecho.c (revision 2)
@@ -0,0 +1,77 @@
+/*!
+ ucecho -- example for ZTEX USB FPGA Module 1.2
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+#include[ztex-conf.h] // Loads the configuration macros, see ztex-conf.h for the available macros
+#include[ztex-utils.h] // include basic functions
+
+// Cypress vendor ID and product ID may only (!) be used for experimental purposes
+SET_VPID(0x4b4,0x8613);
+
+// define endpoints 2 and 4, both belong to interface 0 (in/out are from the point of view of the host)
+EP_CONFIG(2,0,BULK,IN,512,2);
+EP_CONFIG(4,0,BULK,OUT,512,2);
+
+// identify as ZTEX USB FPGA Module 1.2 (Important for FPGA configuration)
+IDENTITY_UFM_1_2(1.0.0.0,0);
+
+// give them a nice name
+#define[PRODUCT_STRING]["ucecho for USB FPGA MODULE 1.2"]
+
+// this is called automatically after FPGA configuration
+#define[POST_FPGA_CONFIG][POST_FPGA_CONFIG
+ OEC = 255;
+]
+
+// include the main part of the firmware kit, define the descriptors, ...
+#include[ztex.h]
+
+
+void main(void)
+{
+ WORD i,size;
+
+// init everything
+ init_USB();
+
+ EP2CS &= ~bmBIT0; // stall = 0
+ SYNCDELAY;
+ EP4CS &= ~bmBIT0; // stall = 0
+
+ SYNCDELAY; // first two packages are waste
+ EP4BCL = 0x80; // skip package, (re)arm EP4
+ SYNCDELAY;
+ EP4BCL = 0x80; // skip package, (re)arm EP4
+
+ while (1) {
+ if ( !(EP4CS & bmBIT2) ) { // EP4 is not empty
+ size = (EP4BCH << 8) | EP4BCL;
+ if ( size>0 && size<=512 && !(EP2CS & bmBIT3)) { // EP2 is not full
+ for ( i=0; i> 8;
+ SYNCDELAY;
+ EP2BCL = size & 255; // arm EP2
+ }
+ SYNCDELAY;
+ EP4BCL = 0x80; // skip package, (re)arm EP4
+ }
+ }
+}
+
Index: usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/ucecho.bat
===================================================================
--- usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/ucecho.bat (nonexistent)
+++ usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/ucecho.bat (revision 2)
@@ -0,0 +1,2 @@
+java -cp UCEcho.jar UCEcho
+pause
Index: usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/distclean.sh
===================================================================
--- usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/distclean.sh (nonexistent)
+++ usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/distclean.sh (revision 2)
@@ -0,0 +1,6 @@
+#!/bin/bash
+
+# This files wil be removed additionally
+binfiles="*.bin *.bit"
+
+. clean.sh
usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/distclean.sh
Property changes :
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/promgen.sh
===================================================================
--- usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/promgen.sh (nonexistent)
+++ usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/promgen.sh (revision 2)
@@ -0,0 +1,14 @@
+#!/bin/bash
+
+# On my computer I use a sript named xilinx to preload the environment
+# variables. The command "xilinx ise" starts the ISE for example.
+# Therefore we check for the xilinx script first.
+if `which xilinx > /dev/null`; then
+ xilinx="xilinx"
+else
+ xilinx=""
+fi
+
+for i in *.bit; do
+ $xilinx promgen -w -p bin -u 0 $i
+done
usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/promgen.sh
Property changes :
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/ucecho.ucf
===================================================================
--- usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/ucecho.ucf (nonexistent)
+++ usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/ucecho.ucf (revision 2)
@@ -0,0 +1,20 @@
+NET "CLK" TNM_NET = "CLK";
+TIMESPEC "TS_CLK" = PERIOD "CLK" 20 ns HIGH 50 %;
+#PACE: Start of PACE I/O Pin Assignments
+NET "CLK" LOC = "P52" | IOSTANDARD = LVCMOS33 ;
+NET "pb<0>" LOC = "P65" | IOSTANDARD = LVCMOS33 | DRIVE = 12 ;
+NET "pb<1>" LOC = "P63" | IOSTANDARD = LVCMOS33 | DRIVE = 12 ;
+NET "pb<2>" LOC = "P60" | IOSTANDARD = LVCMOS33 | DRIVE = 12 ;
+NET "pb<3>" LOC = "P59" | IOSTANDARD = LVCMOS33 | DRIVE = 12 ;
+NET "pb<4>" LOC = "P51" | IOSTANDARD = LVCMOS33 | DRIVE = 12 ;
+NET "pb<5>" LOC = "P50" | IOSTANDARD = LVCMOS33 | DRIVE = 12 ;
+NET "pb<6>" LOC = "P47" | IOSTANDARD = LVCMOS33 | DRIVE = 12 ;
+NET "pb<7>" LOC = "P46" | IOSTANDARD = LVCMOS33 | DRIVE = 12 ;
+NET "pc<0>" LOC = "P58" | IOSTANDARD = LVCMOS33 ;
+NET "pc<1>" LOC = "P44" | IOSTANDARD = LVCMOS33 ;
+NET "pc<2>" LOC = "P41" | IOSTANDARD = LVCMOS33 ;
+NET "pc<3>" LOC = "P40" | IOSTANDARD = LVCMOS33 ;
+NET "pc<4>" LOC = "P36" | IOSTANDARD = LVCMOS33 ;
+NET "pc<5>" LOC = "P35" | IOSTANDARD = LVCMOS33 ;
+NET "pc<6>" LOC = "P33" | IOSTANDARD = LVCMOS33 ;
+NET "pc<7>" LOC = "P32" | IOSTANDARD = LVCMOS33 ;
Index: usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/ucecho.ise
===================================================================
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Index: usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/ucecho.ise
===================================================================
--- usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/ucecho.ise (nonexistent)
+++ usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/ucecho.ise (revision 2)
usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/ucecho.ise
Property changes :
Added: svn:mime-type
## -0,0 +1 ##
+application/octet-stream
\ No newline at end of property
Index: usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/ucecho.vhd
===================================================================
--- usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/ucecho.vhd (nonexistent)
+++ usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/ucecho.vhd (revision 2)
@@ -0,0 +1,30 @@
+library ieee;
+use IEEE.std_logic_1164.all;
+use IEEE.numeric_std.all;
+
+entity ucecho is
+ port(
+ pc : in unsigned(7 downto 0);
+ pb : out unsigned(7 downto 0);
+ CLK : in std_logic
+ );
+end ucecho;
+
+
+--signal declaration
+architecture RTL of ucecho is
+
+begin
+ dpUCECHO: process(CLK)
+ begin
+ if CLK' event and CLK = '1' then
+ if ( pc >= 97 ) and ( pc <= 122)
+ then
+ pb <= pc - 32;
+ else
+ pb <= pc;
+ end if;
+ end if;
+ end process dpUCECHO;
+
+end RTL;
Index: usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/clean.sh
===================================================================
--- usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/clean.sh (nonexistent)
+++ usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/clean.sh (revision 2)
@@ -0,0 +1,70 @@
+#!/bin/bash
+
+# This files / directories from this directory will not be removed
+# Filenames with spaces or other spuid characters will be ignored
+sourcefiles="*.vhd *.ucf *.sh *.ise *.bit *.bin"
+
+
+# This sould not be edited.
+list_files() {
+ if [ "$2" != "" ]; then
+ echo "$1"
+ for i in $2; do
+ echo " $i"
+ done
+ fi
+}
+
+rmfiles=""
+rmdirs=""
+keepfiles=""
+keepdirs=""
+allfiles=`ls -A`
+for f in $allfiles; do
+ keep=false
+ for i in $sourcefiles; do
+ if [ "$i" == "$f" ]; then
+ keep=true
+ fi
+ done
+ for i in $binfiles; do # binfiles is set by distclean.sh
+ if [ "$i" == "$f" ]; then
+ keep=false
+ fi
+ done
+ if [ -d "$f" ]; then
+ if $keep; then
+ keepdirs+=" $f"
+ else
+ rmdirs+=" $f"
+ fi
+ fi
+ if [ -f "$f" ]; then
+ if $keep; then
+ keepfiles+=" $f"
+ else
+ rmfiles+=" $f"
+ fi
+ fi
+done
+
+
+list_files "This directories will NOT be removed:" "$keepdirs"
+list_files "This files will NOT be removed:" "$keepfiles"
+list_files "This directories will be removed:" "$rmdirs"
+list_files "This files will be removed:" "$rmfiles"
+
+if [ "$rmfiles" == "" -a "$rmdirs" == "" ]; then
+ exit 0
+fi
+
+echo -n 'Confirm this by entering "yes": '
+read c
+if [ "$c" == "yes" ]; then
+ [ "$rmfiles" != "" ] && rm $rmfiles
+ [ "$rmdirs" != "" ] && rm -r $rmdirs
+ exit 0
+fi
+exit 1
+
+
usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/fpga/clean.sh
Property changes :
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/Readme
===================================================================
--- usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/Readme (nonexistent)
+++ usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/Readme (revision 2)
@@ -0,0 +1,21 @@
+ucecho
+------
+
+This example is intended for ZTEX USB-FPGA-Modules.
+
+The firmware (defined in ucecho.c) declares Endpoint 2 and Endpoint 4
+(both 512 bytes, double buffered, bulk transfer, belong to interface 0).
+All data that is written to Endpoint 4 is converted to uppercase by
+the FPGA and can be read back from Endpoint 2.
+
+This example does the same as the example in directory ../../all/ucecho
+except that the uppercase - lowercase conversion made by the FPGA.
+
+The driver (defined in UCEcho.java) uploads the the Firmware (ucecho.ihx)
+to the EZ-USB Microcontroller and the Bitstream (fpga/ucecho.bin) to the
+FPGA if necessary, sends user string to the device and reads them back.
+
+Uploading the Firmware to EEPROM is also supported by the firmware (e.g.
+using the FWLoader utility).
+
+This example may serve a good starting point for own projects.
Index: usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/Makefile
===================================================================
--- usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/Makefile (nonexistent)
+++ usb_fpga_1_2/trunk/examples/usb-fpga-1.2/ucecho/Makefile (revision 2)
@@ -0,0 +1,21 @@
+#########################
+# configuration section #
+#########################
+
+ZTEXPREFIX=../../..
+
+JARTARGET=UCEcho.jar
+CLASSTARGETS=UCEcho.class
+CLASSEXTRADEPS=
+#CLASSEXTRADEPS:=$(shell echo $(ZTEXPREFIX)/java/ztex/*.java)
+
+IHXTARGETS=ucecho.ihx
+IHXEXTRADEPS=
+#IHXEXTRADEPS:=$(shell echo $(ZTEXPREFIX)/include/*.h)
+EXTRAJARFILES=ucecho.ihx fpga/ucecho.bin
+
+################################
+# DO NOT CHANAGE THE FOLLOWING #
+################################
+
+include $(ZTEXPREFIX)/Makefile.mk
Index: usb_fpga_1_2/trunk/examples/usb-fpga-1.2/Makefile
===================================================================
--- usb_fpga_1_2/trunk/examples/usb-fpga-1.2/Makefile (nonexistent)
+++ usb_fpga_1_2/trunk/examples/usb-fpga-1.2/Makefile (revision 2)
@@ -0,0 +1,16 @@
+DIRS=ucecho
+
+.PHONY: default all clean distclean
+
+default:
+ @echo "This makefile is intended to clean up the project or to build all examples in this subdirectory"
+ @echo "Usage: make all | clean | distclean"
+
+all:
+ for i in $(DIRS); do make -C $$i all; done
+
+clean:
+ for i in $(DIRS); do make -C $$i clean; done
+
+distclean: clean
+ for i in $(DIRS); do make -C $$i distclean; done
Index: usb_fpga_1_2/trunk/examples/all/ucecho/ucecho.sh
===================================================================
--- usb_fpga_1_2/trunk/examples/all/ucecho/ucecho.sh (nonexistent)
+++ usb_fpga_1_2/trunk/examples/all/ucecho/ucecho.sh (revision 2)
@@ -0,0 +1,4 @@
+#make -C ../../../java distclean all || exit
+#make || exit
+#rm ucecho.ihx
+java -cp UCEcho.jar UCEcho $@
usb_fpga_1_2/trunk/examples/all/ucecho/ucecho.sh
Property changes :
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: usb_fpga_1_2/trunk/examples/all/ucecho/UCEcho.java
===================================================================
--- usb_fpga_1_2/trunk/examples/all/ucecho/UCEcho.java (nonexistent)
+++ usb_fpga_1_2/trunk/examples/all/ucecho/UCEcho.java (revision 2)
@@ -0,0 +1,176 @@
+/*!
+ ucecho -- example for ZTEX USB FPGA Module 1.2
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+import java.io.*;
+import java.util.*;
+
+import ch.ntb.usb.*;
+
+import ztex.*;
+
+// *****************************************************************************
+// ******* ParameterException **************************************************
+// *****************************************************************************
+// Exception the prints a help message
+class ParameterException extends Exception {
+ public final static String helpMsg = new String (
+ "Parameters:\n"+
+ " -d Device Number (default: 0)\n" +
+ " -f Force uploads\n" +
+ " -p Print bus info\n" +
+ " -w Enable certain workarounds which may be required for vmware + windows\n"+
+ " -h This help" );
+
+ public ParameterException (String msg) {
+ super( msg + "\n" + helpMsg );
+ }
+}
+
+// *****************************************************************************
+// ******* Test0 ***************************************************************
+// *****************************************************************************
+class UCEcho extends Ztex1v1 {
+
+// ******* UCEcho **************************************************************
+// constructor
+ public UCEcho ( ZtexDevice1 pDev ) throws UsbException, ZtexDescriptorException {
+ super ( pDev );
+ }
+
+// ******* claimInterface ******************************************************
+// claims interface 0
+ public void claimInterface ( ) throws UsbException{
+ if ( LibusbJava.usb_set_configuration(handle(), 1) < 0 )
+ throw new UsbException("Setting configuration to 1 failed: " + LibusbJava.usb_strerror());
+ if ( LibusbJava.usb_claim_interface(handle(), 0) < 0 )
+ throw new UsbException("Claiming interface 0 failed: " + LibusbJava.usb_strerror());
+ }
+
+// ******* releaseInterface ****************************************************
+// releases interface 0
+ public void releaseInterface ( ) {
+ LibusbJava.usb_release_interface(handle(), 0);
+ }
+
+// ******* echo ****************************************************************
+// writes a string to Endpoint 4, reads it back from Endpoint 2 and writes the output to System.out
+ public void echo ( String input ) throws UsbException {
+ byte buf[] = input.getBytes();
+ int i = LibusbJava.usb_bulk_write(handle, 0x04, buf, buf.length, 1000);
+ if ( i<0 )
+ throw new UsbException("Error sending data: " + LibusbJava.usb_strerror());
+ System.out.println("Send "+i+" bytes: `"+input+"'" );
+
+ try {
+ Thread.sleep( 10 );
+ }
+ catch ( InterruptedException e ) {
+ }
+
+ buf = new byte[1024];
+ i = LibusbJava.usb_bulk_read(handle, 0x82, buf, 1024, 1000);
+ if ( i<0 )
+ throw new UsbException("Error receiving data: " + LibusbJava.usb_strerror());
+ System.out.println("Read "+i+" bytes: `"+new String(buf,0,i)+"'" );
+ }
+
+// ******* main ****************************************************************
+ public static void main (String args[]) {
+
+ int devNum = 0;
+ boolean force = false;
+ boolean workarounds = false;
+
+ try {
+// init USB stuff
+ LibusbJava.usb_init();
+
+// scan the USB bus
+ ZtexScanBus1 bus = new ZtexScanBus1( ZtexDevice1.cypressVendorId, ZtexDevice1.cypressProductId, true, false, 1);
+ if ( bus.numberOfDevices() <= 0) {
+ System.err.println("No devices found");
+ System.exit(0);
+ }
+
+// scan the command line arguments
+ for (int i=0; i=args.length) throw new Exception();
+ devNum = Integer.parseInt( args[i] );
+ }
+ catch (Exception e) {
+ throw new ParameterException("Device number expected after -d");
+ }
+ }
+ else if ( args[i].equals("-f") ) {
+ force = true;
+ }
+ else if ( args[i].equals("-p") ) {
+ bus.printBus(System.out);
+ System.exit(0);
+ }
+ else if ( args[i].equals("-p") ) {
+ bus.printBus(System.out);
+ System.exit(0);
+ }
+ else if ( args[i].equals("-w") ) {
+ workarounds = true;
+ }
+ else if ( args[i].equals("-h") ) {
+ System.err.println(ParameterException.helpMsg);
+ System.exit(0);
+ }
+ else throw new ParameterException("Invalid Parameter: "+args[i]);
+ }
+
+
+// create the main class
+ UCEcho ztex = new UCEcho ( bus.device(devNum) );
+ ztex.certainWorkarounds = workarounds;
+
+// upload the firmware if necessary
+ if ( force || ! ztex.valid() || ! ztex.dev().productString().equals("ucecho for EZ-USB devices") ) {
+ System.out.println("Firmware upload time: " + ztex.uploadFirmware( "ucecho.ihx", force ) + " ms");
+ }
+
+// claim interface 0
+ ztex.claimInterface();
+
+// read string from stdin and write it to USB device
+ String str = "";
+ BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) );
+ while ( ! str.equals("quit") ) {
+ System.out.print("Enter a string or `quit' to exit the program: ");
+ str = reader.readLine();
+ if ( ! str.equals("") )
+ ztex.echo(str);
+ System.out.println("");
+ }
+
+// release interface 0
+ ztex.releaseInterface();
+
+ }
+ catch (Exception e) {
+ System.out.println("Error: "+e.getLocalizedMessage() );
+ }
+ }
+
+}
Index: usb_fpga_1_2/trunk/examples/all/ucecho/ucecho.c
===================================================================
--- usb_fpga_1_2/trunk/examples/all/ucecho/ucecho.c (nonexistent)
+++ usb_fpga_1_2/trunk/examples/all/ucecho/ucecho.c (revision 2)
@@ -0,0 +1,71 @@
+/*!
+ ucecho -- example for ZTEX USB FPGA Module 1.2
+ Copyright (C) 2008-2009 ZTEX e.K.
+ http://www.ztex.de
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 3 as
+ published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, see http://www.gnu.org/licenses/.
+!*/
+
+#include[ztex-conf.h] // Loads the configuration macros, see ztex-conf.h for the available macros
+#include[ztex-utils.h] // include basic functions
+
+// Cypress vendor ID and product ID may only (!) be used for experimental purposes
+SET_VPID(0x4b4,0x8613);
+
+// define endpoints 2 and 4, both belong to interface 0 (in/out are from the point of view of the host)
+EP_CONFIG(2,0,BULK,IN,512,2);
+EP_CONFIG(4,0,BULK,OUT,512,2);
+
+// give them a nice name
+#define[PRODUCT_STRING]["ucecho for EZ-USB devices"]
+
+// include the main part of the firmware kit, define the descriptors, ...
+#include[ztex.h]
+
+void main(void)
+{
+ WORD i,size;
+ BYTE b;
+
+// init everything
+ init_USB();
+
+ EP2CS &= ~bmBIT0; // stall = 0
+ SYNCDELAY;
+ EP4CS &= ~bmBIT0; // stall = 0
+
+ SYNCDELAY; // first two packages are waste
+ EP4BCL = 0x80; // skip package, (re)arm EP4
+ SYNCDELAY;
+ EP4BCL = 0x80; // skip package, (re)arm EP4
+
+ while (1) {
+ if ( !(EP4CS & bmBIT2) ) { // EP4 is not empty
+ size = (EP4BCH << 8) | EP4BCL;
+ if ( size>0 && size<=512 && !(EP2CS & bmBIT3)) { // EP2 is not full
+ for ( i=0; i='a' && b<='z' ) // ... is converted to uppercase ...
+ b-=32;
+ EP2FIFOBUF[i] = b; // ... and written back to EP2 buffer
+ }
+ EP2BCH = size >> 8;
+ SYNCDELAY;
+ EP2BCL = size & 255; // arm EP2
+ }
+ SYNCDELAY;
+ EP4BCL = 0x80; // skip package, (re)arm EP4
+ }
+ }
+}
+
Index: usb_fpga_1_2/trunk/examples/all/ucecho/ucecho.bat
===================================================================
--- usb_fpga_1_2/trunk/examples/all/ucecho/ucecho.bat (nonexistent)
+++ usb_fpga_1_2/trunk/examples/all/ucecho/ucecho.bat (revision 2)
@@ -0,0 +1,2 @@
+java -cp UCEcho.jar UCEcho
+pause
Index: usb_fpga_1_2/trunk/examples/all/ucecho/Readme
===================================================================
--- usb_fpga_1_2/trunk/examples/all/ucecho/Readme (nonexistent)
+++ usb_fpga_1_2/trunk/examples/all/ucecho/Readme (revision 2)
@@ -0,0 +1,18 @@
+ucecho
+------
+
+This example is intended for all EZ-USB Products.
+
+The firmware (defined in ucecho.c) declares Endpoint 2 and Endpoint 4
+(both 512 bytes, double buffered, bulk transfer, belong to interface 0).
+All data that is written to Endpoint 4 is converted to uppercase and can
+be read back from Endpoint 2.
+
+The driver (defined in UCEcho.java) uploads the the Firmware (ucecho.ihx)
+to the EZ-USB Microcontroller if necessary, sends user string to the
+device and reads them back.
+
+Uploading the Firmware to EEPROM is also supported by the firmware (e.g.
+using the FWLoader utility).
+
+This example may serve a good starting point for own projects.
Index: usb_fpga_1_2/trunk/examples/all/ucecho/Makefile
===================================================================
--- usb_fpga_1_2/trunk/examples/all/ucecho/Makefile (nonexistent)
+++ usb_fpga_1_2/trunk/examples/all/ucecho/Makefile (revision 2)
@@ -0,0 +1,21 @@
+#########################
+# configuration section #
+#########################
+
+ZTEXPREFIX=../../..
+
+JARTARGET=UCEcho.jar
+CLASSTARGETS=UCEcho.class
+CLASSEXTRADEPS=
+#CLASSEXTRADEPS:=$(shell echo $(ZTEXPREFIX)/java/ztex/*.java)
+
+IHXTARGETS=ucecho.ihx
+IHXEXTRADEPS=
+#IHXEXTRADEPS:=$(shell echo $(ZTEXPREFIX)/include/*.h)
+EXTRAJARFILES=ucecho.ihx
+
+################################
+# DO NOT CHANAGE THE FOLLOWING #
+################################
+
+include $(ZTEXPREFIX)/Makefile.mk
Index: usb_fpga_1_2/trunk/examples/all/Makefile
===================================================================
--- usb_fpga_1_2/trunk/examples/all/Makefile (nonexistent)
+++ usb_fpga_1_2/trunk/examples/all/Makefile (revision 2)
@@ -0,0 +1,16 @@
+DIRS=ucecho
+
+.PHONY: default all clean distclean
+
+default:
+ @echo "This makefile is intended to clean up the project or to build all examples in this subdirectory"
+ @echo "Usage: make all | clean | distclean"
+
+all:
+ for i in $(DIRS); do make -C $$i all; done
+
+clean:
+ for i in $(DIRS); do make -C $$i clean; done
+
+distclean: clean
+ for i in $(DIRS); do make -C $$i distclean; done
Index: usb_fpga_1_2/trunk/examples/Makefile
===================================================================
--- usb_fpga_1_2/trunk/examples/Makefile (nonexistent)
+++ usb_fpga_1_2/trunk/examples/Makefile (revision 2)
@@ -0,0 +1,16 @@
+DIRS=all usb-fpga-1.2
+
+.PHONY: default all clean distclean
+
+default:
+ @echo "This makefile is intended to clean up the project or to build all examples"
+ @echo "Usage: make all | clean | distclean"
+
+all:
+ for i in $(DIRS); do make -C $$i all; done
+
+clean:
+ for i in $(DIRS); do make -C $$i clean; done
+
+distclean: clean
+ for i in $(DIRS); do make -C $$i distclean; done