-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUSB_Interface.java
More file actions
63 lines (53 loc) · 1.92 KB
/
Copy pathUSB_Interface.java
File metadata and controls
63 lines (53 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import com.hoho.usb.*;
import java.util.List;
public class USB_Interface {
private UsbServices services;
private UsbDevice device;
private UsbConfiguration configuration;
private UsbInterface iface;
private UsbEndpoint endpoint;
public USB_Interface() {
// Initialize the usb4java library
this.services = UsbHostManager.getUsb Services();
}
public void findDevice(String vendorId, String productId) {
// Search for devices with matching Vendor and Product IDs
List<UsbDevice> devices = service. getRootUsbHub().getAttachedUsbDevices();
for (UsbDevice dev : devices) {
if (dev.getVendor Id().equals(vendorId) && dev.getProductId().equals(productId)) {
this.device = dev;
break;
}
}
}
public void open() throws UsbException {
// Open the connection to the device
device.open();
// Claim the default configuration and interface
configuration = device.getActiveUsb Configuration();
configuration.claim();
iface = configuration.getUsb Interface(0);
iface.claim();
// Get the first available endpoint
endpoint = iface.getUsb Endpoint(0);
}
public void close() throws UsbException {
// Release resources
endpoint.releaseInterrupt();
iface.release();
configuration.release();
device.close();
}
public byte[] read() throws UsbException {
// Read data from the endpoint
int timeout = 500;
ByteBuffer buffer = ByteBuffer.allocateDirect(endpoint.getMaxPacketSize());
endpoint.controlTransfer(buffer, timeout);
return new byte[buffer.position()];
}
public void write(byte[] data) throws UsbException {
// Write data to the endpoint
ByteBuffer buffer = ByteBuffer.wrap(data);
endpoint.controlTransfer(buffer, 0);
}
}