Я использовал mik3y:usb-serial-for-android. но он не поддерживает указанную скорость передачи данных
фрагмент моего кода. хотя это читается. кажется, использует 230400 бод. которые не совместимы. используя мое сетевое приложение в Windows. работает. тот же кабель, то же устройство
Код: Выделить всё
public synchronized boolean openConnection(UsbDevice device, DeviceConfig config) {
if (device == null || config == null) {
Log.e(TAG, "Device or configuration is null");
return false;
}
if (isConnected() && device.equals(connectedDevice)) {
Log.i(TAG, "Already connected to this device.");
return true;
}
closeConnection();
try {
usbInterface = device.getInterface(0);
connection = usbManager.openDevice(device);
if (connection == null) {
Log.e(TAG, "Failed to open USB device connection.");
return false;
}
if (!connection.claimInterface(usbInterface, true)) {
Log.e(TAG, "Failed to claim USB interface.");
closeConnection();
return false;
}
for (int i = 0; i < usbInterface.getEndpointCount(); i++) {
UsbEndpoint endpoint = usbInterface.getEndpoint(i);
if (endpoint.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (endpoint.getDirection() == UsbConstants.USB_DIR_IN) {
inEndpoint = endpoint;
} else {
outEndpoint = endpoint;
}
}
}
if (inEndpoint == null || outEndpoint == null) {
Log.e(TAG, "Required endpoints not found.");
closeConnection();
return false;
}
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialPort != null) {
if (serialPort.open()) {
serialPort.setBaudRate(config.getBaudRate());
serialPort.setDataBits(config.getDataBit());
serialPort.setStopBits(config.getStopBit().equals("One") ? UsbSerialInterface.STOP_BITS_1 : UsbSerialInterface.STOP_BITS_2);
serialPort.setParity(config.getParity().equals("None") ? UsbSerialInterface.PARITY_NONE : UsbSerialInterface.PARITY_ODD);
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
serialPort.read(new UsbSerialInterface.UsbReadCallback() {
@Override
public void onReceivedData(byte[] bytes) {
String data = new String(bytes);
// Process the received data as needed
}
});
} else {
Log.e(TAG, "Failed to open serial port.");
closeConnection();
return false;
}
} else {
Log.e(TAG, "Serial device not supported.");
closeConnection();
return false;
}
connectedDevice = device;
return true;
} catch (Exception e) {
Log.e(TAG, "Exception during USB connection: " + e.getMessage(), e);
closeConnection();
return false;
}
}
Код: Выделить всё
if (connection != null && inEndpoint != null && config != null) {
int readCommand = Integer.parseInt(config.getReadCommand());
int stopCommand = Integer.parseInt(config.getStopCommand());
byte[] buffer = new byte[inEndpoint.getMaxPacketSize()];
while (attempts
Подробнее здесь: [url]https://stackoverflow.com/questions/79142824/serial-port-via-usb-comunication[/url]