Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

java.lang.InterruptedException on close invocation #104

Open
camillobucciarelli opened this issue Mar 7, 2024 · 5 comments
Open

java.lang.InterruptedException on close invocation #104

camillobucciarelli opened this issue Mar 7, 2024 · 5 comments

Comments

@camillobucciarelli
Copy link

When I try to close connection with port.close(); I get the following error in console:

D/UsbDeviceConnectionJNI(28094): close
W/System.err(28094): java.lang.InterruptedException
W/System.err(28094): 	at java.lang.Object.wait(Native Method)
W/System.err(28094): 	at java.lang.Object.wait(Object.java:386)
W/System.err(28094): 	at java.lang.Object.wait(Object.java:524)
W/System.err(28094): 	at com.felhr.usbserial.SerialBuffer$SynchronizedBuffer.get(SerialBuffer.java:117)
W/System.err(28094): 	at com.felhr.usbserial.SerialBuffer.getWriteBuffer(SerialBuffer.java:72)
W/System.err(28094): 	at com.felhr.usbserial.UsbSerialDevice$WriteThread.doRun(UsbSerialDevice.java:402)
W/System.err(28094): 	at com.felhr.usbserial.AbstractWorkerThread.run(AbstractWorkerThread.java:21)

there is something that I'm doing wrong?

Thank you

@rockerer
Copy link

rockerer commented Apr 2, 2024

Hi,
can you provde a small code example, how you use the lib? Some information about the used hardware is helpful, too.
Thanks

@cwangfr
Copy link

cwangfr commented Jun 25, 2024

i have same problem
android-arm • Android 9 (API 28)
CH34xSerialDevice
Flutter 3.16.9
Dart version 3.2.6

my code is like this

final port = usbDevice.create();
if (await port.open()) {
      debugPrint("connection success");
      port.setPortParameters(
          9600, UsbPort.DATABITS_8, UsbPort.STOPBITS_1, UsbPort.PARITY_NONE);
      debugPrint("port parameter: ${port.toString()}");
  final anser = <int>[];
  Timer? timeoutTimer;
  bool success = false;
  final completer = Completer<void>();
  late final StreamSubscription<Uint8List> sub;
  sub = port.inputStream!.listen((event) {
    anser.addAll(event);
    debugPrint("event: $event, anser: $anser");
    if (response.isEmpty ||
        (response.isNotEmpty && anser.containsAll(response))) {
      debugPrint("success");
      sub.cancel();
      success = true;
      if (timeoutTimer != null) timeoutTimer.cancel();
      completer.complete();
    }
  });
  await port.write(dataSend);

  timeoutTimer = Timer(Duration(milliseconds: timeOut), () {
    if (!success) {
      debugPrint('Timeout: Did not find the required data within 3 seconds');
      sub.cancel(); //cancel Stream
      completer.complete(); // finish Completer
    }
  });
  await completer.future;
// all task finished.
port.close(); // exception is here
}

@rockerer
Copy link

Does your android device work with the CH34xSerialDevice when using the example app? What does the error look like?

@zyq9613
Copy link

zyq9613 commented Feb 17, 2025

Is it resolved? I also encountered this mistake.

@zyq9613
Copy link

zyq9613 commented Feb 17, 2025

`Future _readResponseWithTimeout(UsbPort port) async {
print('1@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@');
final completer = Completer();
port.inputStream?.listen((Uint8List data) {
if (data.isEmpty) {
if (!completer.isCompleted) {
completer.complete("");
}
}
print('received: $data');
String hexString =
data.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join();

  if (!completer.isCompleted) {
    completer.complete(hexString.toUpperCase());
  }
});
// 设置超时
Future.delayed(const Duration(milliseconds: timeoutMs), () async {
  if (!completer.isCompleted) {
    completer.complete("");
  }
});
return completer.future;

}

Uint8List hexStringToUint8List(String hexString) {
// 去除空格并将字符串转换为大写
hexString = hexString.replaceAll(' ', '').toUpperCase();
// 创建一个空的列表来存储转换后的字节
List byteList = [];
// 遍历每两个字符,将其转换为十六进制字节
for (int i = 0; i < hexString.length; i += 2) {
String hexByte = hexString.substring(i, i + 2); // 取出每两位字符
byteList.add(int.parse(hexByte, radix: 16)); // 将两位字符转换为十六进制字节
}
print(Uint8List.fromList(byteList));
// 返回对应的 Uint8List
return Uint8List.fromList(byteList);
}

void initialize({String? portName}) async {
if (_serialPort != null) return;
UsbPort? port;
try {
List devices = await UsbSerial.listDevices();
if (devices.isEmpty) {
print("没有可用的USB设备");
return;
}
Uint8List byteArray = hexStringToUint8List(hexString);
for (UsbDevice device in devices) {
// 创建端口
port = await device.create();
bool? openResult = await port?.open();
if (openResult == null || !openResult) {
print("打开串口失败: ${device.toString()}");
continue;
}
print('当前的串口: ${port.toString()}');
await port!.setDTR(true);
await port.setRTS(true);
port.setPortParameters(115200, UsbPort.DATABITS_8, UsbPort.STOPBITS_1,
UsbPort.PARITY_NONE);
port.setFlowControl(UsbPort.FLOW_CONTROL_OFF);
// 发送消息
await port.write(byteArray);
// 获取返回信息
String data = await _readResponseWithTimeout(port);
print("Received data: $data");
// 当前关闭的时候会报错,等官方修复,不影响其他操作
await port.close();
if (data.contains('FE')) {
_serialPort = port;
return;
}
}
} catch (e) {
print("初始化失败: $e");
} finally {}
}`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants