- mcdp renamed to java

git-svn-id: https://svn.code.sf.net/p/libusbjava/code/trunk@144 94ad28fe-ef68-46b1-9651-e7ae4fcf1c4c
This commit is contained in:
schlaepfer
2006-05-05 08:43:29 +00:00
parent 1468369ac7
commit 86ac913d63
23 changed files with 0 additions and 0 deletions

7
java/.classpath Normal file
View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="SWT_CONTAINER/PLATFORM"/>
<classpathentry kind="output" path="bin"/>
</classpath>

19
java/.project Normal file
View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>ch.ntb.usb</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.jem.beaninfo.BeanInfoNature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,12 @@
#Wed Oct 26 15:55:07 CEST 2005
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.5
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.5

View File

@@ -0,0 +1,3 @@
#Thu Oct 06 09:12:32 CEST 2005
eclipse.preferences.version=1
internal.default.compliance=default

View File

@@ -0,0 +1,423 @@
package ch.ntb.usb;
import java.util.logging.Level;
import ch.ntb.usb.logger.LogUtil;
import ch.ntb.usb.logger.UsbLogger;
/**
* This class represents an USB device.<br>
* To get an instance of an USB device use <code>USB.getDevice(...)</code>.
*
* @author schlaepfer
*
*/
public class Device {
private static UsbLogger logger = LogUtil.ch_ntb_usb;
private static final int TIMEOUT_ERROR_CODE = -116;
private int maxPacketSize;
private int idVendor, idProduct, configuration, interface_, altinterface;
private int usb_dev_handle;
private boolean resetOnFirstOpen, resetDone;
protected Device(short idVendor, short idProduct) {
resetOnFirstOpen = false;
resetDone = false;
maxPacketSize = -1;
this.idVendor = idVendor;
this.idProduct = idProduct;
}
/**
* Opens the device and claims the specified configuration, interface and
* altinterface.<br>
* First the bus is enumerated. If the device is found its descriptors are
* read and the <code>maxPacketSize</code> value is updated. If no
* endpoints are found in the descriptors an exception is thrown.
*
* @param configuration
* the desired configuration
* @param interface_
* the desired interface
* @param altinterface
* the desired alternative interface
* @throws USBException
*/
public void open(int configuration, int interface_, int altinterface)
throws USBException {
this.configuration = configuration;
this.interface_ = interface_;
this.altinterface = altinterface;
Usb_Bus bus;
if (usb_dev_handle > 0) {
throw new USBException("device opened, close or reset first");
}
// open bus
LibusbWin.usb_init();
LibusbWin.usb_find_busses();
LibusbWin.usb_find_devices();
bus = LibusbWin.usb_get_busses();
if (bus == null) {
throw new USBException("LibusbWin.usb_get_busses(): "
+ LibusbWin.usb_strerror());
}
maxPacketSize = -1;
// search for device
while (bus != null) {
Usb_Device dev = bus.devices;
while (dev != null) {
// Usb_Device_Descriptor
Usb_Device_Descriptor defDesc = dev.descriptor;
if ((defDesc.idVendor == idVendor)
&& (defDesc.idProduct == idProduct)) {
logger.info("Open device: " + dev.filename);
int res = LibusbWin.usb_open(dev);
if (res <= 0) {
throw new USBException("LibusbWin.usb_open: "
+ LibusbWin.usb_strerror());
} else {
usb_dev_handle = res;
// get endpoint wMaxPacketSize
Usb_Config_Descriptor[] confDesc = dev.config;
for (int i = 0; i < confDesc.length; i++) {
Usb_Interface[] int_ = confDesc[i].interface_;
for (int j = 0; j < int_.length; j++) {
Usb_Interface_Descriptor[] intDesc = int_[j].altsetting;
for (int k = 0; k < intDesc.length; k++) {
Usb_Endpoint_Descriptor[] epDesc = intDesc[k].endpoint;
for (int l = 0; l < epDesc.length; l++) {
maxPacketSize = Math.max(
epDesc[l].wMaxPacketSize,
maxPacketSize);
}
}
}
}
if (maxPacketSize <= 0) {
throw new USBException(
"No USB endpoints found. Check the device configuration");
}
}
}
dev = dev.next;
}
bus = bus.next;
}
if (usb_dev_handle <= 0) {
throw new USBException("USB device with idVendor 0x"
+ Integer.toHexString(idVendor & 0xFFFF)
+ " and idProduct 0x"
+ Integer.toHexString(idProduct & 0xFFFF) + " not found");
}
claim_interface(usb_dev_handle, configuration, interface_, altinterface);
if (resetOnFirstOpen & !resetDone) {
logger.info("reset on first open");
resetDone = true;
reset();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
open(configuration, interface_, altinterface);
}
}
/**
* Release the claimed interface and close the opened device.<br>
*
* @throws USBException
*/
public void close() throws USBException {
if (usb_dev_handle <= 0) {
throw new USBException("invalid device handle");
}
release_interface(usb_dev_handle, interface_);
if (LibusbWin.usb_close(usb_dev_handle) < 0) {
usb_dev_handle = 0;
throw new USBException("LibusbWin.usb_close: "
+ LibusbWin.usb_strerror());
}
usb_dev_handle = 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 (usb_dev_handle <= 0) {
throw new USBException("invalid device handle");
}
if (LibusbWin.usb_reset(usb_dev_handle) < 0) {
throw new USBException("LibusbWin.usb_reset: "
+ LibusbWin.usb_strerror());
}
usb_dev_handle = 0;
logger.info("device reset");
}
/**
* Write data to the device using a bulk transfer.<br>
*
* @param out_ep_address
* endpoint address to write to
* @param data
* data to write to this endpoint
* @param length
* length 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 bulkwrite(int out_ep_address, byte[] data, int length,
int timeout, boolean reopenOnTimeout) throws USBException {
if (usb_dev_handle <= 0) {
throw new USBException("invalid device handle");
}
if (data == null) {
throw new USBException("data must not be null");
}
if (length <= 0) {
throw new USBException("size must be > 0");
}
int lenWritten = LibusbWin.usb_bulk_write(usb_dev_handle,
out_ep_address, data, length, timeout);
if (lenWritten < 0) {
if (lenWritten == TIMEOUT_ERROR_CODE) {
// try to reopen the device and send the data again
if (reopenOnTimeout) {
logger.info("try to reopen");
reset();
open(configuration, interface_, altinterface);
return bulkwrite(out_ep_address, data, length, timeout,
false);
}
throw new USBTimeoutException("LibusbWin.usb_bulk_write: "
+ LibusbWin.usb_strerror());
}
throw new USBException("LibusbWin.usb_bulk_write: "
+ LibusbWin.usb_strerror());
}
if (logger.getLevel().intValue() <= Level.INFO.intValue()) {
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.<br>
*
* @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 bulkread(int in_ep_address, byte[] data, int size, int timeout,
boolean reopenOnTimeout) throws USBException {
if (usb_dev_handle <= 0) {
throw new USBException("invalid device handle");
}
if (data == null) {
throw new USBException("data must not be null");
}
if (size <= 0) {
throw new USBException("size must be > 0");
}
int lenRead = LibusbWin.usb_bulk_read(usb_dev_handle, in_ep_address,
data, size, timeout);
if (lenRead < 0) {
if (lenRead == TIMEOUT_ERROR_CODE) {
if (lenRead == TIMEOUT_ERROR_CODE) {
// try to reopen the device and send the data again
if (reopenOnTimeout) {
logger.info("try to reopen");
reset();
open(configuration, interface_, altinterface);
return bulkwrite(in_ep_address, data, size, timeout,
false);
}
throw new USBTimeoutException("LibusbWin.usb_bulk_write: "
+ LibusbWin.usb_strerror());
}
throw new USBTimeoutException("LibusbWin.usb_bulk_read: "
+ LibusbWin.usb_strerror());
}
throw new USBException("LibusbWin.usb_bulk_read: "
+ LibusbWin.usb_strerror());
}
if (logger.getLevel().intValue() <= Level.INFO.intValue()) {
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;
}
/**
* Claim an interface to send and receive USB data.<br>
*
* @param usb_dev_handle
* the handle of the device <b>(MUST BE VALID)</b>
* @param configuration
* the configuration to use
* @param interface_
* the interface to claim
* @param altinterface
* the alternative interface to use
* @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 (LibusbWin.usb_set_configuration(usb_dev_handle, configuration) < 0) {
throw new USBException("LibusbWin.usb_set_configuration: "
+ LibusbWin.usb_strerror());
}
if (LibusbWin.usb_claim_interface(usb_dev_handle, interface_) < 0) {
throw new USBException("LibusbWin.usb_claim_interface: "
+ LibusbWin.usb_strerror());
}
if (LibusbWin.usb_set_altinterface(usb_dev_handle, altinterface) < 0) {
throw new USBException("LibusbWin.usb_set_altinterface: "
+ LibusbWin.usb_strerror());
}
logger.info("interface claimed");
}
/**
* Release a previously claimed interface.<br>
*
* @param dev_handle
* the handle of the device <b>(MUST BE VALID)</b>
* @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 (LibusbWin.usb_release_interface(dev_handle, interface_) < 0) {
throw new USBException("LibusbWin.usb_release_interface: "
+ LibusbWin.usb_strerror());
}
logger.info("interface released");
}
/**
* @return the product ID of the device.
*/
public int getIdProduct() {
return idProduct;
}
/**
* @return the vendor ID of the device.
*/
public int getIdVendor() {
return idVendor;
}
/**
* @return the alternative interface. This value is only valid after opening
* the device.
*/
public int getAltinterface() {
return altinterface;
}
/**
* @return the current configuration used. This value is only valid after
* opening the device.
*/
public int getConfiguration() {
return configuration;
}
/**
* @return the current interface. This value is only valid after opening the
* device.
*/
public int getInterface() {
return interface_;
}
/**
* @return the current device handle. This value is only valid after opening
* the device.
*/
public int getUsb_dev_handle() {
return usb_dev_handle;
}
/**
* Returns the maximum packet size in bytes which is allowed to be
* transmitted at once.<br>
* 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;
}
/**
* If enabled, the device is reset when first opened. <br>
* 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}.
*
* @param enable
* true if the device should be reset when first opened
*/
public void setResetOnFirstOpen(boolean enable) {
resetOnFirstOpen = enable;
}
}

View File

@@ -0,0 +1,310 @@
package ch.ntb.usb;
/**
* This class represents the Java Native Interface to the LibUsbWin.dll.<br>
* <br>
* <h1>Project Description</h1>
* Java LibUsb-Win32 is a Java wrapper for the LibUsb-Win32 USB library. <a
* href="http://libusb-win32.sourceforge.net/">LibUsb-Win32</a> is a port of
* the USB library <a href="http://libusb.sourceforge.net/">libusb</a> 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.
*
* @author schlaepfer
*
*/
public class LibusbWin {
// Core
/**
* Just like the name implies, <code>usb_init</code> sets up some internal
* structures. <code>usb_init</code> must be called before any other
* libusb functions.
*/
public static native void usb_init();
/**
* <code>usb_find_busses</code> 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();
/**
* <code>usb_find_devices</code> will find all of the devices on each bus.
* This should be called after <code>usb_find_busses</code>.
*
* @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();
/**
* <code>usb_get_busses</code> simply returns the value of the global
* variable usb_busses. This was implemented for those languages that
* support C calling convention and can use shared libraries, but don't
* support C global variables (like Delphi).
*
* @return the structure of all busses and devices. <b>Note:</b> The java
* objects are copies of the C structs.
*/
public static native Usb_Bus usb_get_busses();
// Device Operations
/**
* <code>usb_open</code> is to be used to open up a device for use.
* <code>usb_open</code> 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.
*/
public static native int usb_open(Usb_Device dev);
/**
* <code>usb_close</code> closes a device opened with
* <code>usb_open</code>.
*
* @param dev_handle
* The handle to the device.
* @return
*/
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.<br>
* <br>
* <b>Causes re-enumeration:</b> After calling <code>usb_reset</code>,
* 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
* <code>usb_reset</code> 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.<br>
* <br>
* <b>Must be called!:</b> <code>usb_claim_interface</code> must be
* called before you perform any operations related to this interface (like
* <code>usb_set_altinterface, usb_bulk_write</code>, 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
* @param buf
* @param buflen
* @return the number of bytes returned in buf or < 0 on error.
*/
public static native int usb_get_string(int dev_handle, int index,
int langid, String buf, int buflen);
/**
* <code>usb_get_string_simple</code> is a wrapper around
* <code>usb_get_string</code> 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
* @param buf
* @param buflen
* @return the number of bytes returned in buf or < 0 on error.
*/
public static native int usb_get_string_simple(int dev_handle, int index,
String buf, int buflen);
/**
* Retrieves a descriptor from the device identified by the type and index
* of the descriptor from the default control pipe.<br>
* <br>
* See <code>usb_get_descriptor_by_endpoint</code> for a function that
* allows the control endpoint to be specified.
*
* @param dev_handle
* The handle to the device.
* @param type
* @param index
* @param buf
* @param size
* @return the number of bytes read for the descriptor or < 0 on error.
*/
public static native int usb_get_descriptor(int dev_handle, byte type,
byte index, String buf, 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 buf
* @param size
* @return the number of bytes read for the descriptor or < 0 on error.
*/
public static native int usb_get_descriptor_by_endpoint(int dev_handle,
int ep, byte type, byte index, String buf, 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();
/** **************************************************************** */
static {
System.load(System.getenv("SystemRoot") + "/system32/LibusbWin.dll");
}
}

View File

@@ -0,0 +1,76 @@
package ch.ntb.usb;
import java.util.Iterator;
import java.util.LinkedList;
import ch.ntb.usb.logger.LogUtil;
import ch.ntb.usb.logger.UsbLogger;
/**
* This class manages all USB devices and defines some USB specific constants.
*
* @author schlaepfer
*
*/
public class USB {
/**
* The maximum packet size of a bulk transfer when operation in highspeed
* (480 MB/s) mode.
*/
public static int HIGHSPEED_MAX_BULK_PACKET_SIZE = 512;
/**
* The maximum packet size of a bulk transfer when operation in fullspeed
* (12 MB/s) mode.
*/
public static int FULLSPEED_MAX_BULK_PACKET_SIZE = 64;
private static UsbLogger logger = LogUtil.ch_ntb_usb;
private static LinkedList<Device> devices = new LinkedList<Device>();
/**
* Create a new device an register it in a device queue or get an already
* created device.<br>
*
* @param idVendor
* the vendor id of the USB device
* @param idProduct
* the product id of the USB device
* @return a newly created device or an already registered device
*/
public static Device getDevice(short idVendor, short idProduct) {
// check if this device is already registered
Device dev = getRegisteredDevice(idVendor, idProduct);
if (dev != null) {
logger.info("return already registered device");
return dev;
}
dev = new Device(idVendor, idProduct);
logger.info("create new device");
devices.add(dev);
return dev;
}
/**
* Get an already registered device or null if the device does not exist.<br>
*
* @param idVendor
* the vendor id of the USB device
* @param idProduct
* the product id of the USB device
* @return the device or null
*/
private static Device getRegisteredDevice(short idVendor, short idProduct) {
for (Iterator<Device> iter = devices.iterator(); iter.hasNext();) {
Device dev = iter.next();
if ((dev.getIdVendor() == idVendor)
&& (dev.getIdProduct() == idProduct)) {
return dev;
}
}
return null;
}
}

View File

@@ -0,0 +1,18 @@
package ch.ntb.usb;
public class USBException extends Exception{
public class USBTimeoutException {
}
public USBException(String string) {
super(string);
}
/**
*
*/
private static final long serialVersionUID = 1690857437804284710L;
}

View File

@@ -0,0 +1,14 @@
package ch.ntb.usb;
public class USBTimeoutException extends USBException {
public USBTimeoutException(String string) {
super(string);
}
/**
*
*/
private static final long serialVersionUID = -1065328371159778249L;
}

View File

@@ -0,0 +1,23 @@
package ch.ntb.usb;
public class Usb_Bus {
public Usb_Bus next, prev;
public String dirname;
public Usb_Device devices;
public long location;
public Usb_Device root_dev;
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("** Usb_Bus **\n");
sb.append("\tdirname: " + dirname + "\n");
sb.append("\tlocation: " + location + "\n");
return sb.toString();
}
}

View File

@@ -0,0 +1,44 @@
package ch.ntb.usb;
public class Usb_Config_Descriptor {
public static final int USB_MAXCONFIG = 8;
public byte bLength;
public byte bDescriptorType;
public short wTotalLength;
public byte bNumInterfaces;
public byte bConfigurationValue;
public byte iConfiguration;
public byte bmAttributes;
public byte MaxPower;
public Usb_Interface[] interface_;
// TODO: Extra descriptors are not interpreted because of their unknown
// structure
public Usb_Config_Descriptor extra; /* Extra descriptors */
public int extralen;
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("** Usb_Config_Descriptor **\n");
sb.append("\tblenght: " + bLength + "\n");
sb.append("\tbDescriptorType: " + bDescriptorType + "\n");
sb.append("\tbNumInterfaces: " + bNumInterfaces + "\n");
sb.append("\tbConfigurationValue: " + bConfigurationValue + "\n");
sb.append("\tiConfiguration: " + iConfiguration + "\n");
sb.append("\tbmAttributes: 0x"
+ Integer.toHexString(bmAttributes & 0xFF) + "\n");
sb.append("\tMaxPower [mA]: " + MaxPower + "\n");
return sb.toString();
}
}

View File

@@ -0,0 +1,29 @@
package ch.ntb.usb;
public class Usb_Device {
public Usb_Device next, prev;
public String filename;
public Usb_Bus bus;
public Usb_Device_Descriptor descriptor;
public Usb_Config_Descriptor[] config;
public byte devnum;
public byte num_children;
public Usb_Device children;
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("** Usb_Device **\n");
sb.append("\tfilename: " + filename + "\n");
sb.append("\tdevnum: " + devnum + "\n");
sb.append("\tnum_children: " + num_children + "\n");
return sb.toString();
}
}

View File

@@ -0,0 +1,91 @@
package ch.ntb.usb;
public class Usb_Device_Descriptor {
/*
* Device and/or Interface Class codes
*/
public static final int USB_CLASS_PER_INTERFACE = 0;
public static final int USB_CLASS_AUDIO = 1;
public static final int USB_CLASS_COMM = 2;
public static final int USB_CLASS_HID = 3;
public static final int USB_CLASS_PRINTER = 7;
public static final int USB_CLASS_MASS_STORAGE = 8;
public static final int USB_CLASS_HUB = 9;
public static final int USB_CLASS_DATA = 10;
public static final int USB_CLASS_VENDOR_SPEC = 0xff;
/*
* Descriptor types
*/
public static final int USB_DT_DEVICE = 0x01;
public static final int USB_DT_CONFIG = 0x02;
public static final int USB_DT_STRING = 0x03;
public static final int USB_DT_INTERFACE = 0x04;
public static final int USB_DT_ENDPOINT = 0x05;
public static final int USB_DT_HID = 0x21;
public static final int USB_DT_REPORT = 0x22;
public static final int USB_DT_PHYSICAL = 0x23;
public static final int USB_DT_HUB = 0x29;
/*
* Descriptor sizes per descriptor type
*/
public static final int USB_DT_DEVICE_SIZE = 18;
public static final int USB_DT_CONFIG_SIZE = 9;
public static final int USB_DT_INTERFACE_SIZE = 9;
public static final int USB_DT_ENDPOINT_SIZE = 7;
public static final int USB_DT_ENDPOINT_AUDIO_SIZE = 9; /* Audio extension */
public static final int USB_DT_HUB_NONVAR_SIZE = 7;
public byte bLength;
public byte bDescriptorType;
public short bcdUSB;
public byte bDeviceClass;
public byte bDeviceSubClass;
public byte bDeviceProtocol;
public byte bMaxPacketSize0;
public short idVendor;
public short idProduct;
public short bcdDevice;
public byte iManufacturer;
public byte iProduct;
public byte iSerialNumber;
public byte bNumConfigurations;
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("** Usb_Device_Descriptor **\n");
sb.append("\tblenght: " + bLength + "\n");
sb.append("\tbDescriptorType: " + bDescriptorType + "\n");
sb.append("\tbcdUSB: 0x" + Integer.toHexString(bcdUSB) + "\n");
sb.append("\tbDeviceClass: " + bDeviceClass + "\n");
sb.append("\tbDeviceSubClass: " + bDeviceSubClass + "\n");
sb.append("\tbDeviceProtocol: " + bDeviceProtocol + "\n");
sb.append("\tbMaxPacketSize0: " + bMaxPacketSize0 + "\n");
sb.append("\tidVendor: 0x" + Integer.toHexString(idVendor & 0xFFFF)
+ "\n");
sb.append("\tidProduct: 0x" + Integer.toHexString(idProduct & 0xFFFF)
+ "\n");
sb.append("\tbcdDevice: " + bcdDevice + "\n");
sb.append("\tiManufacturer: " + iManufacturer + "\n");
sb.append("\tiProduct: " + iProduct + "\n");
sb.append("\tiSerialNumber: " + iSerialNumber + "\n");
sb.append("\tbNumConfigurations: " + bNumConfigurations + "\n");
return sb.toString();
}
};

View File

@@ -0,0 +1,54 @@
package ch.ntb.usb;
public class Usb_Endpoint_Descriptor {
public static final int USB_MAXENDPOINTS = 32;
/* in bEndpointAddress */
public static final int USB_ENDPOINT_ADDRESS_MASK = 0x0f;
public static final int USB_ENDPOINT_DIR_MASK = 0x80;
/* in bmAttributes */
public static final int USB_ENDPOINT_TYPE_MASK = 0x03;
public static final int USB_ENDPOINT_TYPE_CONTROL = 0;
public static final int USB_ENDPOINT_TYPE_ISOCHRONOUS = 1;
public static final int USB_ENDPOINT_TYPE_BULK = 2;
public static final int USB_ENDPOINT_TYPE_INTERRUPT = 3;
public byte bLength;
public byte bDescriptorType;
public byte bEndpointAddress;
public byte bmAttributes;
public short wMaxPacketSize;
public byte bInterval;
public byte bRefresh;
public byte bSynchAddress;
// TODO: Extra descriptors are not interpreted because of their unknown
// structure
public Usb_Endpoint_Descriptor extra; /* Extra descriptors */
public int extralen;
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("**Usb_Endpoint_Descriptor**\n");
sb.append("\tblenght: " + bLength + "\n");
sb.append("\tbDescriptorType: " + bDescriptorType + "\n");
sb.append("\tbEndpointAddress: 0x"
+ Integer.toHexString(bEndpointAddress & 0xFF) + "\n");
sb.append("\tbmAttributes: 0x"
+ Integer.toHexString(bmAttributes & 0xFF) + "\n");
sb.append("\twMaxPacketSize: " + wMaxPacketSize + "\n");
sb.append("\tbInterval: " + bInterval + "\n");
sb.append("\tbRefresh: " + bRefresh + "\n");
sb.append("\tbSynchAddress: " + bSynchAddress + "\n");
return sb.toString();
}
}

View File

@@ -0,0 +1,17 @@
package ch.ntb.usb;
public class Usb_Interface {
public static final int USB_MAXALTSETTING = 128; /* Hard limit */
public Usb_Interface_Descriptor[] altsetting;
public int num_altsetting;
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("** Usb_Interface **\n");
sb.append("\tnum_altsetting: " + num_altsetting + "\n");
return sb.toString();
}
}

View File

@@ -0,0 +1,49 @@
package ch.ntb.usb;
public class Usb_Interface_Descriptor {
public static final int USB_MAXINTERFACES = 32;
public byte bLength;
public byte bDescriptorType;
public byte bInterfaceNumber;
public byte bAlternateSetting;
public byte bNumEndpoints;
public byte bInterfaceClass;
public byte bInterfaceSubClass;
public byte bInterfaceProtocol;
public byte iInterface;
public Usb_Endpoint_Descriptor[] endpoint;
// TODO: Extra descriptors are not interpreted because of their unknown
// structure
public Usb_Interface_Descriptor extra; /* Extra descriptors */
public int extralen;
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("** Usb_Interface_Descriptor **\n");
sb.append("\tblenght: " + bLength + "\n");
sb.append("\tbDescriptorType: " + bDescriptorType + "\n");
sb.append("\tbInterfaceNumber: " + bInterfaceNumber + "\n");
sb.append("\tbAlternateSetting: " + bAlternateSetting + "\n");
sb.append("\tbNumEndpoints: " + bNumEndpoints + "\n");
sb.append("\tbInterfaceClass: 0x"
+ Integer.toHexString(bInterfaceClass & 0xFF) + "\n");
sb.append("\tbInterfaceSubClass: 0x"
+ Integer.toHexString(bInterfaceSubClass & 0xFF) + "\n");
sb.append("\tbInterfaceProtocol: 0x"
+ Integer.toHexString(bInterfaceProtocol & 0xFF) + "\n");
sb.append("\tiInterface: " + iInterface + "\n");
return sb.toString();
}
}

View File

@@ -0,0 +1,44 @@
package ch.ntb.usb;
public class Utils {
public static void logUsb(Usb_Bus bus) {
while (bus != null) {
System.out.println(bus.toString());
Usb_Device dev = bus.devices;
while (dev != null) {
System.out.println("\t" + dev.toString());
// Usb_Device_Descriptor
Usb_Device_Descriptor defDesc = dev.descriptor;
System.out.println("\t" + defDesc.toString());
// Usb_Config_Descriptor
Usb_Config_Descriptor[] confDesc = dev.config;
for (int i = 0; i < confDesc.length; i++) {
System.out.println("\t" + confDesc[i].toString());
Usb_Interface[] int_ = confDesc[i].interface_;
if (int_ != null) {
for (int j = 0; j < int_.length; j++) {
System.out.println("\t" + int_[j].toString());
Usb_Interface_Descriptor[] intDesc = int_[j].altsetting;
if (intDesc != null) {
for (int k = 0; k < intDesc.length; k++) {
System.out.println("\t"
+ intDesc[k].toString());
Usb_Endpoint_Descriptor[] epDesc = intDesc[k].endpoint;
if (epDesc != null) {
for (int e = 0; e < epDesc.length; e++) {
System.out.println("\t"
+ epDesc[e].toString());
}
}
}
}
}
}
}
dev = dev.next;
}
bus = bus.next;
}
}
}

View File

@@ -0,0 +1,13 @@
package ch.ntb.usb.logger;
import java.util.logging.Level;
public class LogLevel extends Level {
public static final Level DEBUG = new LogLevel("DEBUG", 750);
protected LogLevel(String name, int value) {
super(name, value);
}
}

View File

@@ -0,0 +1,41 @@
package ch.ntb.usb.logger;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
public class LogUtil {
public static UsbLogger ch_ntb_usb;
static {
// set all loglevels here
ch_ntb_usb = getLogger("ch.ntb.usb", LogLevel.OFF);
}
public static void setLevel(UsbLogger logger, Level loglevel) {
Handler[] h = logger.getHandlers();
for (int i = 0; i < h.length; i++) {
h[i].setLevel(loglevel);
}
logger.setLevel(loglevel);
}
private static void initLevel(UsbLogger 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 UsbLogger getLogger(String name, Level loglevel) {
UsbLogger logger = UsbLogger.getLogger(name);
initLevel(logger, loglevel);
return logger;
}
}

View File

@@ -0,0 +1,27 @@
package ch.ntb.usb.logger;
import java.util.logging.LogManager;
import java.util.logging.Logger;
public class UsbLogger extends Logger {
protected UsbLogger(String name, String resourceBundleName) {
super(name, resourceBundleName);
}
public void debug(String msg) {
log(LogLevel.DEBUG, msg);
}
public static synchronized UsbLogger getLogger(String name) {
LogManager manager = LogManager.getLogManager();
UsbLogger result = (UsbLogger) manager.getLogger(name);
if (result == null) {
result = new UsbLogger(name, null);
manager.addLogger(result);
result = (UsbLogger) manager.getLogger(name);
}
result.setLevel(null);
return result;
}
}

View File

@@ -0,0 +1,395 @@
package ch.ntb.usb.test;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class TestGUI {
private static final int HEX_WIDTH = 5;
private Shell rootShell = null; // @jve:decl-index=0:visual-constraint="10,10"
private Group vendorIDGroup = null;
private Text vendorID = null;
private Group productIDGroup = null;
private Text productID = null;
private Group configGroup = null;
private Text configuration = null;
private Group interfaceGroup = null;
private Text interface_ = null;
private Group altIntGroup = null;
private Text altInt = null;
private Group deviceGroup = null;
private Group endpointGroup = null;
private Group deviceGroup2 = null;
private Group outEPGroup = null;
private Text outEP = null;
private Group inEPGroup = null;
private Text inEP = null;
private Group timeoutGroup = null;
private Text timeout = null;
private Group dataGroup = null;
private Composite dataButtonComp = null;
private Button sendButton = null;
private Button recButton = null;
private Composite devComp = null;
private Composite devButtonComp = null;
private Button devOpenButton = null;
private Button devCloseButton = null;
private Group dataFieldGoup = null;
private Text dataField = null;
private Button resetButton = null;
/**
* This method initializes sShell
*/
private int parseInt(String s){
if (s == "") return 0;
if (s.indexOf('x') > 0) {
// is hex number
if (s.length() <= 2){ // exception for "0x"
return 0;
}
return Integer.parseInt(s.substring(s.indexOf('x') + 1, s.length()), 16);
} else {
// is decimal number
return Integer.parseInt(s);
}
}
private byte[] parseByteArray(String s){
StringBuffer sb = new StringBuffer();
int stringIndex = 0, spaceIndex = 0;
String ss;
while (stringIndex + 3 < s.length()){
ss = s.substring(spaceIndex, spaceIndex + 4);
spaceIndex = s.indexOf(' ', stringIndex) + 1;
sb.append((char) parseInt(ss));
stringIndex += HEX_WIDTH;
}
return sb.toString().getBytes();
}
private void createSShell() {
RowLayout rowLayout = new RowLayout();
rowLayout.type = org.eclipse.swt.SWT.VERTICAL;
rowLayout.justify = true;
rowLayout.fill = true;
rootShell = new Shell();
rootShell.setText("Usb TestApplication");
rootShell.setLayout(rowLayout);
createDeviceGroup();
createDataGroup();
rootShell.setSize(new org.eclipse.swt.graphics.Point(466,315));
}
/**
* This method initializes vendorIDGroup
*
*/
private void createVendorIDGroup() {
vendorIDGroup = new Group(deviceGroup2, SWT.NONE);
vendorIDGroup.setText("VendorID");
vendorID = new Text(vendorIDGroup, SWT.BORDER | SWT.RIGHT);
vendorID.setBounds(new org.eclipse.swt.graphics.Rectangle(7,23,76,19));
vendorID.setText("0x8235");
TestImplementation.IdVendor = (short) parseInt(vendorID.getText());
vendorID.addModifyListener(new org.eclipse.swt.events.ModifyListener() {
public void modifyText(org.eclipse.swt.events.ModifyEvent e) {
TestImplementation.IdVendor = (short) parseInt(vendorID.getText());
}
});
}
/**
* This method initializes productIDGroup
*
*/
private void createProductIDGroup() {
productIDGroup = new Group(deviceGroup2, SWT.NONE);
productIDGroup.setText("ProductID");
productID = new Text(productIDGroup, SWT.BORDER | SWT.RIGHT);
productID.setBounds(new org.eclipse.swt.graphics.Rectangle(4,24,76,19));
productID.setText("0x0100");
TestImplementation.IdProduct = (short) parseInt(productID.getText());
productID.addModifyListener(new org.eclipse.swt.events.ModifyListener() {
public void modifyText(org.eclipse.swt.events.ModifyEvent e) {
TestImplementation.IdProduct = (short) parseInt(productID.getText());
}
});
}
/**
* This method initializes group
*
*/
private void createGroup() {
configGroup = new Group(deviceGroup2, SWT.NONE);
configGroup.setText("Configuration");
configuration = new Text(configGroup, SWT.BORDER | SWT.RIGHT);
configuration.setBounds(new org.eclipse.swt.graphics.Rectangle(4,24,75,19));
configuration.setText("1");
configuration.addModifyListener(new org.eclipse.swt.events.ModifyListener() {
public void modifyText(org.eclipse.swt.events.ModifyEvent e) {
TestImplementation.CONFIGURATION = parseInt(configuration.getText());
}
});
}
/**
* This method initializes group
*
*/
private void createGroup2() {
interfaceGroup = new Group(deviceGroup2, SWT.NONE);
interfaceGroup.setText("Interface");
interface_ = new Text(interfaceGroup, SWT.BORDER | SWT.RIGHT);
interface_.setBounds(new org.eclipse.swt.graphics.Rectangle(4,24,57,19));
interface_.setText("0");
interface_.addModifyListener(new org.eclipse.swt.events.ModifyListener() {
public void modifyText(org.eclipse.swt.events.ModifyEvent e) {
TestImplementation.INTERFACE = parseInt(interface_.getText());
}
});
}
/**
* This method initializes group
*
*/
private void createGroup3() {
altIntGroup = new Group(deviceGroup2, SWT.NONE);
altIntGroup.setText("Alternative Int");
altInt = new Text(altIntGroup, SWT.BORDER | SWT.RIGHT);
altInt.setBounds(new Rectangle(4, 24, 76, 19));
altInt.setText("0");
altInt.addModifyListener(new org.eclipse.swt.events.ModifyListener() {
public void modifyText(org.eclipse.swt.events.ModifyEvent e) {
TestImplementation.ALTINTERFACE = parseInt(altInt.getText());
}
});
}
/**
* This method initializes deviceGroup
*
*/
private void createDeviceGroup() {
RowLayout rowLayout1 = new RowLayout();
rowLayout1.type = org.eclipse.swt.SWT.VERTICAL;
rowLayout1.fill = true;
deviceGroup = new Group(rootShell, SWT.NONE);
deviceGroup.setText("Device Settings");
createDeviceGroup2();
deviceGroup.setLayout(rowLayout1);
createDevComp();
}
/**
* This method initializes endpointGroup
*
*/
private void createEndpointGroup() {
endpointGroup = new Group(devComp, SWT.NONE);
endpointGroup.setLayout(new RowLayout());
createGroup4();
createGroup5();
createGroup6();
}
/**
* This method initializes deviceGroup2
*
*/
private void createDeviceGroup2() {
deviceGroup2 = new Group(deviceGroup, SWT.NONE);
deviceGroup2.setLayout(new RowLayout());
createVendorIDGroup();
createProductIDGroup();
createGroup();
createGroup2();
createGroup3();
}
/**
* This method initializes group
*
*/
private void createGroup4() {
outEPGroup = new Group(endpointGroup, SWT.NONE);
outEPGroup.setText("OUT EP");
outEP = new Text(outEPGroup, SWT.BORDER | SWT.RIGHT);
outEP.setBounds(new org.eclipse.swt.graphics.Rectangle(4,24,46,19));
outEP.setText("0x02");
outEP.addModifyListener(new org.eclipse.swt.events.ModifyListener() {
public void modifyText(org.eclipse.swt.events.ModifyEvent e) {
TestImplementation.OUT_ENDPOINT = parseInt(outEP.getText());
}
});
}
/**
* This method initializes group
*
*/
private void createGroup5() {
inEPGroup = new Group(endpointGroup, SWT.NONE);
inEPGroup.setText("IN EP");
inEP = new Text(inEPGroup, SWT.BORDER | SWT.RIGHT);
inEP.setBounds(new org.eclipse.swt.graphics.Rectangle(4,24,46,19));
inEP.setText("0x86");
inEP.addModifyListener(new org.eclipse.swt.events.ModifyListener() {
public void modifyText(org.eclipse.swt.events.ModifyEvent e) {
TestImplementation.IN_ENDPOINT = parseInt(inEP.getText());
}
});
}
/**
* This method initializes group
*
*/
private void createGroup6() {
timeoutGroup = new Group(endpointGroup, SWT.NONE);
timeoutGroup.setText("Timeout");
timeout = new Text(timeoutGroup, SWT.BORDER | SWT.RIGHT);
timeout.setBounds(new Rectangle(4, 24, 46, 19));
timeout.setText("2000");
timeout.addModifyListener(new org.eclipse.swt.events.ModifyListener() {
public void modifyText(org.eclipse.swt.events.ModifyEvent e) {
TestImplementation.TIMEOUT = parseInt(timeout.getText());
}
});
}
/**
* This method initializes dataGroup
*
*/
private void createDataGroup() {
RowLayout rowLayout5 = new RowLayout();
rowLayout5.type = org.eclipse.swt.SWT.HORIZONTAL;
rowLayout5.spacing = 10;
dataGroup = new Group(rootShell, SWT.NONE);
dataGroup.setText("Send and Receive Data");
dataGroup.setLayout(rowLayout5);
createDataFieldGoup();
createButtonComp();
}
/**
* This method initializes buttonComp
*
*/
private void createButtonComp() {
RowLayout rowLayout3 = new RowLayout();
rowLayout3.type = org.eclipse.swt.SWT.VERTICAL;
rowLayout3.justify = true;
rowLayout3.fill = true;
dataButtonComp = new Composite(dataGroup, SWT.NONE);
sendButton = new Button(dataButtonComp, SWT.NONE);
sendButton.setText("Send");
sendButton.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
byte[] b = parseByteArray(dataField.getText());
TestImplementation.write(b, b.length);
}
});
recButton = new Button(dataButtonComp, SWT.NONE);
dataButtonComp.setLayout(rowLayout3);
recButton.setText("Receive");
recButton.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
TestImplementation.read();
}
});
}
/**
* This method initializes devComp
*
*/
private void createDevComp() {
RowLayout rowLayout4 = new RowLayout();
rowLayout4.fill = true;
rowLayout4.spacing = 50;
devComp = new Composite(deviceGroup, SWT.NONE);
createEndpointGroup();
devComp.setLayout(rowLayout4);
createDevButtonComp();
}
/**
* This method initializes devButtonComp
*
*/
private void createDevButtonComp() {
RowLayout rowLayout2 = new RowLayout();
rowLayout2.marginHeight = 25;
rowLayout2.spacing = 5;
devButtonComp = new Composite(devComp, SWT.NONE);
devButtonComp.setLayout(rowLayout2);
devOpenButton = new Button(devButtonComp, SWT.NONE);
devOpenButton.setText("Open Device");
devOpenButton
.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
TestImplementation.openUsbDevice();
}
});
devCloseButton = new Button(devButtonComp, SWT.NONE);
devCloseButton.setText("Close Device");
resetButton = new Button(devButtonComp, SWT.NONE);
resetButton.setText("Reset");
resetButton.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
TestImplementation.resetUsbDevice();
}
});
devCloseButton
.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
TestImplementation.closeUsbDevice();
}
});
}
/**
* This method initializes dataFieldGoup
*
*/
private void createDataFieldGoup() {
RowData rowData = new org.eclipse.swt.layout.RowData();
rowData.width = 340;
RowLayout rowLayout6 = new RowLayout();
rowLayout6.fill = true;
rowLayout6.marginHeight = 5;
rowLayout6.justify = true;
dataFieldGoup = new Group(dataGroup, SWT.NONE);
dataFieldGoup.setText("Data to send [hex]");
dataFieldGoup.setLayout(rowLayout6);
dataField = new Text(dataFieldGoup, SWT.BORDER);
// 33 5B 02 01 00 05 01 03 07 0F 7F 1F
dataField.setText("0x5B 0x02 0x01 0x00 0x05 0x01 0x03 0x07 0x0F 0x7F 0x1F");
dataField.setLayoutData(rowData);
}
public static void main(String[] args) {
TestGUI app = new TestGUI();
app.createSShell();
app.rootShell.open();
Display display = app.rootShell.getDisplay();
while (!app.rootShell.isDisposed()) {
if(!display.readAndDispatch()) {
display.sleep();
}
}
}
}

View File

@@ -0,0 +1,101 @@
package ch.ntb.usb.test;
import java.util.logging.Level;
import java.util.logging.Logger;
import ch.ntb.usb.Device;
import ch.ntb.usb.USB;
import ch.ntb.usb.USBException;
import ch.ntb.usb.Usb_Bus;
public class TestImplementation {
private static Logger logger = Logger.getLogger("ch.ntb.usb.test");
static Usb_Bus bus;
static int usb_dev_handle = 0;
static short IdVendor = 0x04B4;
static short IdProduct = (short) 0x1004;
static int TIMEOUT = 1000;
static int CONFIGURATION = 1;
static int INTERFACE = 0;
static int ALTINTERFACE = 0;
static int OUT_ENDPOINT = 0x02;
static int IN_ENDPOINT = 0x86;
private static Device dev = null;
static {
logger.setLevel(Level.ALL);
}
static void openUsbDevice() {
dev = USB.getDevice(IdVendor, IdProduct);
try {
dev.open(CONFIGURATION, INTERFACE, ALTINTERFACE);
logger.info("device opened, interface claimed");
} catch (USBException e) {
e.printStackTrace();
}
}
static void closeUsbDevice() {
try {
dev.close();
logger.info("device closed");
} catch (USBException e) {
e.printStackTrace();
}
}
static void resetUsbDevice() {
try {
dev.reset();
logger.info("device reset");
} catch (USBException e) {
e.printStackTrace();
}
}
static void write(byte[] data, int length) {
int lenWritten = 0;
try {
lenWritten = dev.bulkwrite(OUT_ENDPOINT, data, length, TIMEOUT,
false);
StringBuffer sb = new StringBuffer("write_bulkdata: " + lenWritten
+ " Bytes sent: ");
for (int i = 0; i < lenWritten; i++) {
sb.append("0x" + String.format("%1$02X", data[i]) + " ");
}
logger.info(sb.toString());
} catch (USBException e) {
e.printStackTrace();
}
}
static void read() {
byte[] data = new byte[dev.getMaxPacketSize()];
int lenRead = 0;
try {
lenRead = dev.bulkread(IN_ENDPOINT, data, dev.getMaxPacketSize(),
TIMEOUT, false);
StringBuffer sb = new StringBuffer("read_bulkdata: " + lenRead
+ " Bytes received: Data: ");
for (int i = 0; i < lenRead; i++) {
sb.append("0x" + String.format("%1$02X", data[i]) + " ");
}
logger.info(sb.toString());
} catch (USBException e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,303 @@
package ch.ntb.usb.test;
import java.io.IOException;
import ch.ntb.usb.*;
public class TestUsb_old {
static Usb_Bus bus;
static final short EZ_USB_DevKit_idVendor = 0x04B4;
static final short EZ_USB_DevKit_idProduct = (short) 0x1004; // 0x8613;
static final int TIMEOUT = 3000;
static final int CONFIGURATION = 1;
static final int INTERFACE = 0;
static final int ALTINTERFACE = 0; // 1;
static final int OUT_ENDPOINT = 0x02; // 0x04;
static final int IN_ENDPOINT = 0x86; // 0x88;
static final int MAX_BYTEARRAY_SIZE = 512;
static final int PACKET_HEADER_1 = 0x33; // first byte of header
static final int PACKET_HEADER_2 = 0x5B; // second byte of header
static final int PACKET_END = 0x1F; // last byte of packet
static final int PACKET_DATA_OFFSET = 6; // offset to the first byte of
// data
static final int PACKET_MIN_LENGTH = 7; // minimal Length of a packet (no
// payload)
// Main Types
static final int MTYPE_ERROR = 0x01; // Errors before dispatching data
static final int MTYPE_BDI = 0x02;
static final int MTYPE_UART_1 = 0x03;
// Sub Types
// ERRORS
static final int STYPE_ERROR_HEADER = 0x01; // Header of packet wrong
static final int STYPE_ERROR_PACKET_END = 0x02; // Packet end wrong
// BDI
static final int STYPE_BDI_35IN = 0x01; // 35 Bit Packet to BDI
static final int STYPE_BDI_35OUT = 0x02; // 35 Bit Packet from BDI
static final int STYPE_BDI_10IN = 0x03; // 10 Bit Packet to BDI
static final int STYPE_BDI_10OUT = 0x04; // 10 Bit Packet from BDI
static final int STYPE_BDI_FD_DATA = 0x05; // Fast Download Data
static final int STYPE_BDI_ERROR_FD_LENGTH = 0x06; // Error if length in FD
// packet too small
// UART 1
static final int STYPE_UART_1_IN = 0x11; // Data to UART 1
static final int STYPE_UART_1_OUT = 0x22; // Data from UART 1
private static void do_read(Usb_Bus bus, int dev_handle) {
byte[] data = new byte[MAX_BYTEARRAY_SIZE];
int res = read_bulkdata(dev_handle, CONFIGURATION, INTERFACE,
ALTINTERFACE, IN_ENDPOINT, data, MAX_BYTEARRAY_SIZE, TIMEOUT);
if (res <= 0) {
System.err.println("Error on read_bulkdata "
+ LibusbWin.usb_strerror());
return;
}
System.out.println("read_bulkdata length: " + res);
System.out.print("Data: ");
for (int i = 0; i < res; i++) {
System.out.print("0x" + String.format("%1$02X", data[i]) + " ");
}
System.out.println();
// System.out.println("Data: " + logBytesAsChars(data));
}
private static String logBytesAsChars(byte[] data) {
StringBuffer sb = new StringBuffer(MAX_BYTEARRAY_SIZE);
int i = 0;
while ((data[i] != 0) && (i < MAX_BYTEARRAY_SIZE)) {
sb.append((char) data[i]);
i++;
}
return sb.toString();
}
private static void findFirstDevice() {
// find a valid device
Usb_Device dev;
while (bus != null) {
dev = bus.devices;
while (dev != null) {
System.out.println("dev.devnum " + dev.devnum);
int dev_handle = LibusbWin.usb_open(dev);
System.out.println("dev_handle " + dev_handle);
if (dev_handle > 0) {
if (LibusbWin.usb_close(dev_handle) < 0) {
System.err
.println("error on usb.usb_close(dev_handle)");
}
return;
}
dev = dev.next;
}
bus = bus.next;
}
}
private static void openDevice(Usb_Bus bus) {
int handle = openUsb_Device(bus, EZ_USB_DevKit_idVendor,
EZ_USB_DevKit_idProduct);
if (handle > 0) {
System.out.println("Usb_device_handle: " + handle);
System.out.println("closed: " + LibusbWin.usb_close(handle));
}
}
private static int write_bulkdata(int dev_handle, int configuration,
int interface_, int altinterface, int endpoint, byte[] data,
int length, int timeout) {
int res = LibusbWin.usb_set_configuration(dev_handle, configuration);
if (res < 0) {
System.err.println("Error on usb_set_configuration: "
+ LibusbWin.usb_strerror());
return res;
}
res = LibusbWin.usb_claim_interface(dev_handle, interface_);
if (res < 0) {
System.err.println("Error on usb_claim_interface: "
+ LibusbWin.usb_strerror());
return res;
}
LibusbWin.usb_set_altinterface(dev_handle, altinterface);
res = LibusbWin.usb_bulk_write(dev_handle, endpoint, data, length,
timeout);
LibusbWin.usb_release_interface(dev_handle, interface_);
if (res <= 0) {
System.err.println("Error on usb_bulk_write: "
+ LibusbWin.usb_strerror());
}
return res;
}
private static int read_bulkdata(int dev_handle, int configuration,
int interface_, int altinterface, int endpoint, byte[] data,
int size, int timeout) {
int res = LibusbWin.usb_set_configuration(dev_handle, configuration);
if (res < 0) {
System.err.println("Error on usb_set_configuration: "
+ LibusbWin.usb_strerror());
return res;
}
res = LibusbWin.usb_claim_interface(dev_handle, interface_);
if (res < 0) {
System.err.println("Error on read_bulkdata: "
+ LibusbWin.usb_strerror());
return res;
}
LibusbWin.usb_set_altinterface(dev_handle, altinterface);
res = LibusbWin
.usb_bulk_read(dev_handle, endpoint, data, size, timeout);
LibusbWin.usb_release_interface(dev_handle, interface_);
if (res <= 0) {
System.err.println("Error on usb_bulk_read: "
+ LibusbWin.usb_strerror());
return res;
}
return res;
}
private static void do_write(Usb_Bus bus, int dev_handle) {
// byte[] data = new String("Data to send...").getBytes();
byte[] data = new byte[512];
data[0] = PACKET_HEADER_1; // header
data[1] = (byte) PACKET_HEADER_2; // header
data[2] = MTYPE_BDI; // header
data[3] = STYPE_BDI_35IN; // header
data[4] = 0x00; // length of payload
data[5] = 0x05;
data[6] = 0x01; // payload
data[7] = 0x03;
data[8] = 0x07;
data[9] = 0x0F;
data[10] = 0x7F;
data[11] = (byte) PACKET_END; // packet end
int length = 12;
int res = write_bulkdata(dev_handle, CONFIGURATION, INTERFACE,
ALTINTERFACE, OUT_ENDPOINT, data, length, TIMEOUT);
if (res <= 0) {
System.err.println("Error on write_bulkdata");
return;
}
System.out.print(res + " Bytes sent: ");
for (int i = 0; i < res; i++) {
System.out.print("0x" + String.format("%1$02X", data[i]) + " ");
}
System.out.println();
System.out.println("write_bulkdata done");
}
private static String logBytes(byte[] data) {
StringBuffer sb = new StringBuffer(MAX_BYTEARRAY_SIZE);
for (int i = 0; i < data.length; i++) {
sb.append(data[i]);
sb.append(" ");
}
return sb.toString();
}
private static void do_write_read(Usb_Bus bus) {
int dev_handle = openUsb_Device(bus, EZ_USB_DevKit_idVendor,
EZ_USB_DevKit_idProduct);
if (dev_handle <= 0) {
System.err.println("Error on openUsb_Device: " + dev_handle);
return;
}
boolean run = true;
char c = 'a';
while (run) {
try {
c = (char) System.in.read();
} catch (IOException e) {
e.printStackTrace();
run = false;
}
switch (c) {
case 'w':
do_write(bus, dev_handle);
break;
case 'r':
do_read(bus, dev_handle);
break;
case 'x':
run = false;
break;
default:
break;
}
}
LibusbWin.usb_close(dev_handle);
}
public static int openUsb_Device(Usb_Bus bus, short idVendor,
short idProduct) {
int handle = -1;
while (bus != null) {
Usb_Device dev = bus.devices;
while (dev != null) {
// Usb_Device_Descriptor
Usb_Device_Descriptor defDesc = dev.descriptor;
if ((defDesc.idVendor == idVendor)
&& (defDesc.idProduct == idProduct)) {
System.out.println("Open device: " + dev.filename);
return LibusbWin.usb_open(dev);
}
dev = dev.next;
}
bus = bus.next;
}
return handle;
}
public static void main(String[] args) {
LibusbWin.usb_init();
LibusbWin.usb_find_busses();
LibusbWin.usb_find_devices();
bus = LibusbWin.usb_get_busses();
if (bus == null) {
System.err.println("Error on usb.usb_get_busses(): "
+ LibusbWin.usb_strerror());
return;
}
// Utils.logUsb(bus);
// openDevice(bus);
do_write_read(bus);
System.out.println("LibusbWin done");
}
}