Skip to content

Commit

Permalink
Fixed Usb4JavaUsbDeviceCommunication and cleaned up all the code
Browse files Browse the repository at this point in the history
- Usb4JavaUsbDeviceCommunication: fixed data returned handling, which fixed everything (was expecting data.array() to work), cleaned up the code (most of logs are now debug), better logging, better open and close handling
- removed some unneeded classes
- removed TAG lines of old logging from all classes
  • Loading branch information
andy.rozman committed Apr 13, 2024
1 parent e93ffd2 commit 22482e3
Show file tree
Hide file tree
Showing 15 changed files with 56 additions and 485 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -37,20 +37,27 @@ public class Usb4JavaUsbDeviceCommunication implements UsbCommunication {
private static final int TRANSFER_TIMEOUT = 5000; // 21000
DeviceHandle deviceHandle;
UsbMassStorageDeviceConfig deviceConfig;
boolean deviceIsOpenAndClaimed = false;

public Usb4JavaUsbDeviceCommunication(UsbMassStorageDeviceConfig usbMassStorageDeviceConfig) {
this.deviceConfig = usbMassStorageDeviceConfig;
}

public void openDevice() throws LibAumsException {
log.info("openDevice {}", deviceConfig.getReadableDeviceId());

if (deviceHandle != null) {
log.error("Device {} is already opened, exiting.", deviceConfig.getReadableDeviceId());
return;
}

log.info("openDevice: opening {}", deviceConfig.getReadableDeviceId());
Context context = UsbMassStorageLibrary.initLibrary();

// Open device
DeviceHandle handle = LibUsb.openDeviceWithVidPid(context, deviceConfig.getVendorId(),
deviceConfig.getProductId());
if (handle == null) {
log.error("Device {} not found, or could not be opened.", deviceConfig.getReadableDeviceId());
log.error("openDevice: Device {} not found, or could not be opened.", deviceConfig.getReadableDeviceId());
System.exit(1);
}

Expand All @@ -66,31 +73,30 @@ public void openDevice() throws LibAumsException {
if (result2 != LibUsb.SUCCESS &&
result2 != LibUsb.ERROR_NOT_SUPPORTED &&
result2 != LibUsb.ERROR_NOT_FOUND) {
throw new LibUsbException("Device busy and unable to detach kernel driver",
throw LibAumsException.createWithLibUsbException("Device busy and unable to detach kernel driver",
result2);
}
log.debug("Device {} was busy. We dettached kernel driver which was successful.", deviceConfig.getReadableDeviceId());
log.debug("openDevice: Device {} was busy. We detached kernel driver which was successful.", deviceConfig.getReadableDeviceId());
} else {
throw new LibUsbException("Unable to claim interface", result);
throw LibAumsException.createWithLibUsbException("Unable to claim interface", result);
}

log.debug("Trying to claim interafce again.");
log.debug("openDevice: Trying to claim interface again.");
int result3 = LibUsb.claimInterface(handle, deviceConfig.getInterfaceNumber());
if (result3 != LibUsb.SUCCESS) {
throw new LibUsbException("Unable to claim interface even after detaching kernel.", result3);
throw LibAumsException.createWithLibUsbException("Unable to claim interface even after detaching kernel.", result3);
}

}

log.info("Device {} opened and interaface {} claimed.", deviceConfig.getReadableDeviceId(), deviceConfig.getInterfaceNumber());
log.info("openDevice: Device {} opened and interface {} claimed.", deviceConfig.getReadableDeviceId(), deviceConfig.getInterfaceNumber());
this.deviceIsOpenAndClaimed = true;
}


@Override
public int bulkOutTransfer(byte[] data, int length) throws LibAumsException {
// TODO implement Usb4JavaUsbDeviceCommunication

log.info("BulkOutTransfer (data={},length={})", data, length);
log.debug("bulkOutTransfer (data={},length={})", data, length);

ByteBuffer buffer = BufferUtils.allocateByteBuffer(data.length);
buffer.put(data);
Expand All @@ -99,27 +105,22 @@ public int bulkOutTransfer(byte[] data, int length) throws LibAumsException {
buffer,
transferred, TRANSFER_TIMEOUT);
if (result != LibUsb.SUCCESS) {
throw new LibUsbException("Unable to send data: " + result, result);
throw LibAumsException.createWithLibUsbException("Unable to send data: " + result, result);
}

int transferredCount = transferred.get();

log.info(transferredCount + " bytes sent to device");

// return deviceConnection.bulkTransfer(outEndpoint, buffer, length, TRANSFER_TIMEOUT);
log.debug("bulkOutTransfer: {} bytes sent to device", transferredCount);

return transferredCount;
}

@Override
public int bulkOutTransfer(byte[] data, int offset, int length) throws LibAumsException{
// TODO implement Usb4JavaUsbDeviceCommunication

if (offset==0) {
return bulkOutTransfer(data, length);
}

log.info("BulkOutTransfer (data={},length={},offset={})", data, length, offset);
log.debug("bulkOutTransfer(offset): (data={},length={},offset={})", data, length, offset);

int remaining = length-offset;
byte[] newData = new byte[length-offset];
Expand All @@ -136,28 +137,15 @@ public int bulkOutTransfer(byte[] data, int offset, int length) throws LibAumsE
}

int transferredCount = transferred.get();
log.info(transferredCount + " bytes sent to device");
log.debug("bulkOutTransfer(offset): {} bytes sent to device", transferredCount);

return transferredCount;

// if (offset == 0)
// return deviceConnection.bulkTransfer(outEndpoint, buffer, length, TRANSFER_TIMEOUT);
//
// byte[] tmpBuffer = new byte[length];
// System.arraycopy(buffer, offset, tmpBuffer, 0, length);
// return deviceConnection.bulkTransfer(outEndpoint, tmpBuffer, length,
// TRANSFER_TIMEOUT);


}

@Override
public int bulkInTransfer(byte[] data, int length) throws LibAumsException {

log.info("BulkInTransfer (data={},length={})", data, length);

// TODO bulkInTransfer, Libusb does things different than android
// some problem
log.debug("bulkInTransfer: dataLength={},requestLength={}", data.length, length);

ByteBuffer buffer = BufferUtils.allocateByteBuffer(length).order(
ByteOrder.LITTLE_ENDIAN);
Expand All @@ -170,32 +158,27 @@ public int bulkInTransfer(byte[] data, int length) throws LibAumsException {
}

int transferredCount = transferred.get();
log.info(transferredCount + " bytes read from device");
log.debug("bulkInTransfer: {} bytes read from device", transferredCount);

if (buffer.hasArray()) {
log.debug("Buffer: " + buffer);
log.trace("bulkInTransfer: Buffer.hasArray: {}", buffer);
System.arraycopy(buffer.array(), 0, data, 0, length);
} else {
log.debug("No data: " + buffer);
buffer.get(data);
}

return transferredCount;

// return LibUsb.bulkTransfer(
// deviceHandle, deviceConfig.getInEndpointAddress(), buffer, length, TRANSFER_TIMEOUT);

log.debug("bulkInTransfer: Data Returned: {}", data);

//return LibUsb.SUCCESS;
return transferredCount;
}

@Override
public int bulkInTransfer(byte[] data, int offset, int length) throws LibAumsException{
// TODO implement Usb4JavaUsbDeviceCommunication not Sure if this will work ok

if (offset==0) {
return bulkInTransfer(data, length);
}

log.info("BulkInTransfer (data={},length={},offset={})", data, length, offset);
log.debug("bulkInTransfer(offset): dataLength={},requestLength={},offset={}", data.length, length, offset);

ByteBuffer buffer = BufferUtils.allocateByteBuffer(length).order(
ByteOrder.LITTLE_ENDIAN);
Expand All @@ -208,87 +191,40 @@ public int bulkInTransfer(byte[] data, int offset, int length) throws LibAumsEx
}

int transferredCount = transferred.get();
log.info(transferredCount + " bytes read from device");
log.debug("bulkInTransfer(offset): {} bytes read from device", transferredCount);

if (buffer.hasArray()) {
log.debug("Buffer: " + buffer);
log.trace("bulkInTransfer(offset): Buffer.hasArray: {}", buffer);
System.arraycopy(buffer.array(), 0, data, offset, length);
} else {
log.debug("No data: " + buffer);
buffer.get(data, offset, length);
}

log.debug("bulkInTransfer(offset): Data Returned: {}", data);

return transferredCount;

// if (offset == 0)
// return deviceConnection.bulkTransfer(inEndpoint, buffer, length, TRANSFER_TIMEOUT);
//
// byte[] tmpBuffer = new byte[length];
// int result = deviceConnection.bulkTransfer(inEndpoint, tmpBuffer, length,
// TRANSFER_TIMEOUT);
// System.arraycopy(tmpBuffer, 0, buffer, offset, length);
// return result;
}


/**
* Writes some data to the device.
*
* @param handle
* The device handle.
* @param data
* The data to send to the device.
*/
public static void write(DeviceHandle handle, byte[] data) throws LibAumsException
{
// ByteBuffer buffer = BufferUtils.allocateByteBuffer(data.length);
// buffer.put(data);
// IntBuffer transferred = BufferUtils.allocateIntBuffer();
// int result = LibUsb.bulkTransfer(handle, OUT_ENDPOINT, buffer,
// transferred, TIMEOUT);
// if (result != LibUsb.SUCCESS)
// {
// throw new LibUsbException("Unable to send data", result);
// }
// System.out.println(transferred.get() + " bytes sent to device");
}

/**
* Reads some data from the device.
*
* @param handle
* The device handle.
* @param size
* The number of bytes to read from the device.
* @return The read data.
*/
public static ByteBuffer read(DeviceHandle handle, int size) throws LibAumsException
{
// ByteBuffer buffer = BufferUtils.allocateByteBuffer(size).order(
// ByteOrder.LITTLE_ENDIAN);
// IntBuffer transferred = BufferUtils.allocateIntBuffer();
// int result = LibUsb.bulkTransfer(handle, IN_ENDPOINT, buffer,
// transferred, TIMEOUT);
// if (result != LibUsb.SUCCESS)
// {
// throw new LibUsbException("Unable to read data", result);
// }
// System.out.println(transferred.get() + " bytes read from device");
// return buffer;
return null;

}



public void closeDevice() throws LibAumsException {
// Release interface
int result = LibUsb.releaseInterface(deviceHandle, deviceConfig.getInterfaceNumber());
if (result != LibUsb.SUCCESS) {
throw LibAumsException.createWithLibUsbException("Unable to release interface", result);
if (deviceHandle == null) {
log.warn("closeDevice: device {} is already closed. Exiting.", deviceConfig.getReadableDeviceId());
return;
}
log.info("closeDevice: closing device {}", deviceConfig.getReadableDeviceId());

if (deviceIsOpenAndClaimed) {
// Release interface
int result = LibUsb.releaseInterface(deviceHandle, deviceConfig.getInterfaceNumber());
if (result != LibUsb.SUCCESS) {
throw LibAumsException.createWithLibUsbException("Unable to release interface", result);
}
this.deviceIsOpenAndClaimed = false;
}

// Close the device
LibUsb.close(deviceHandle);
log.info("closeDevice: device {} closed and interface released", deviceConfig.getReadableDeviceId());
deviceHandle = null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

import java.util.List;
Expand All @@ -40,7 +41,11 @@ public class ExampleCreateScsiBlockDevice {
public ExampleCreateScsiBlockDevice() {
String PATTERN = "%d{HH:mm:ss,SSS} %5p [%c{1}:%L] - %m%n";
UsbMassStorageLibrary.LOAD_PARTITIONS = false;
createConsoleAppender(Level.ALL, PATTERN);
//createConsoleAppender(Level.ALL, PATTERN);
Logger.getRootLogger().removeAllAppenders();
Logger.getRootLogger().addAppender(createConsoleAppender(Level.ALL, PATTERN));
Logger.getLogger("com").setLevel(Level.DEBUG);
Logger.getLogger("github").setLevel(Level.DEBUG);
}

public static ConsoleAppender createConsoleAppender(Level threshold, String pattern) {
Expand Down Expand Up @@ -144,9 +149,9 @@ public void dispose() {
public static void main(String[] args) {

ExampleCreateScsiBlockDevice flexi = new ExampleCreateScsiBlockDevice();
//flexi.connectToVerio();
flexi.connectToVerio();
//flexi.findDevice();
flexi.readMicroSDreader();
//flexi.readMicroSDreader();

flexi.dispose();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,6 @@
@Slf4j
public class ScsiBlockDevice implements BlockDeviceDriver {

private static final String TAG = ScsiBlockDevice.class.getSimpleName();

private UsbCommunication usbCommunication;
private ByteBuffer outBuffer;
private byte[] cswBuffer;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,6 @@ public class CommandStatusWrapper {
*/
public static final int SIZE = 13;

private static final String TAG = CommandStatusWrapper.class.getSimpleName();

private static final int D_CSW_SIGNATURE = 0x53425355;

private int dCswSignature;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
*/
public class ScsiRead10 extends CommandBlockWrapper {

// private static final String TAG = ScsiRead10.class.getSimpleName();
private static final byte LENGTH = 0x10;
private static final byte OPCODE = 0x28;//sbc_read10

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
*/
public class ScsiWrite10 extends CommandBlockWrapper {

// private static final String TAG = ScsiWrite10.class.getSimpleName();
private static final byte LENGTH = 0x10;
private static final byte OPCODE = 0x2a;//0x2a

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,6 @@
@Slf4j
public class ClusterChain {

private static final String TAG = ClusterChain.class.getSimpleName();

private BlockDeviceDriver blockDevice;
private FAT fat;
private Long[] chain;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,6 @@
@Slf4j
public class FAT {

private static final String TAG = FAT.class.getSimpleName();

/**
* End of file / chain marker. This is used to determine when following a
* cluster chain should be stopped. (Last allocated cluster has been found.)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,6 @@
private static int STRUCT_SIGNATURE = 0x61417272;
private static int TRAIL_SIGNATURE = 0xAA550000;

private static final String TAG = FsInfoStructure.class.getSimpleName();

private int offset;
private BlockDeviceDriver blockDevice;
private ByteBuffer buffer;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,6 @@
@Slf4j
public class Partition implements BlockDeviceDriver {

private static final String TAG = Partition.class.getSimpleName();

// private PartitionTableEntry partitionTableEntry;
private BlockDeviceDriver blockDevice;
/**
Expand Down
Loading

0 comments on commit 22482e3

Please sign in to comment.