Open ctrleffive opened 5 years ago
Same issue. Trying to connect to HM-10 bluetooth arduino module on Android 7.1, Mi Note 3 I will test it on other phones too soon
I created a new pull correcting this error
I merged @rafaelterada. As soon as possible I'll release a new version. Thanks a lot.
Hi, I got the same issue. Is there any way to know when the version including this fix will be available or if there is a way to by pass this issue in order to connect my app to an arduino (using a groveBLE v1.0) ? (I can already connect an android bluetooth terminal app to the arduino device but I would want to do it through a flutter app) With regards, thanks
Thanks for your answer. Unfortunately, I already tried this solution and as my flutter app use the 0.13.11 version of protobuf (for gRpc), I'm also waiting for the fix of their issue#257.
Thanks for your help, I wish you good luck in future
I dig into the Java code, I found whenever socket.connect(); It has exception: read failed, socket might closed or timeout, read ret: -1. What is the exact cause for this? Is my echo server problem or bluetooth USB hardware problem? Thanks.
I dig into the Java code, I found whenever socket.connect(); It has exception: read failed, socket might closed or timeout, read ret: -1. What is the exact cause for this? Is my echo server problem or bluetooth USB hardware problem? Thanks.
I found in the code MY_UUID is hard coded to a specific uuid string.
Why do I still have this error? I'm using 0.1.0 which should include @rafaelterada's fix.
Update: Issue is solved for me indeed. It was my fault, I was trying to connect to a device without serial service enabled.
There are few issues that could make the error happen:
A) Remove device is not responding.
The device might have other address than specified, be in non-connectable state or just hanged up.
B) Service Discovery Protocol is not available,
Standalone modules like HC-05 should have configured it for default. For Raspberry Pi (and other Linux devices I guess) there is example how to setup it.
C) End device is using other Bluetooth protocol,
This library is for now using only RFCOMM. Other thing is also UUID expectation on the other side. There will be option to provide own UUID instead of hard-coded one in future. For now UUID is
00001101-0000-1000-8000-00805F9B34FB
.
D) Secure connection is unavailable.
You should also pair the device you are connecting to - at least for now, since there is no other method to connect than RFCOMM via secure socket.
E) Remote device is busy.
The device might be connected by another device, another app or another session (multiple instances of same app). There is no way to detect it for now, and it could also result in that way.
F) You misunderstood Bluetooth Serial for Bluetooth Low Energy.
These are quite different protocols, even while using same underlying band and link protocols (including almost the same pairing and discovery). This library is created for classic Serial connectivity - see flutter_blue for BLE instead.
The issue will stay open for now (until other protocols or/and custom UUID will be implemented?) Feel free to ask for further help here, if you occurred the issue.
I am getting the same error. I am using the latest version of the plugin and I am trying to run the example app provided in Plugin repo.
I am using the latest version of the plugin and I am trying to run the example app provided in Plugin repo.
Is it chat example with Raspberry or the one with sensors and Arduino? Please provide more details about your testing environment if possible.
I have the same error. Trying to connect to a HC05.
It fails to connect if I manually try to call BluetoothConnection.toAddress
, but does work if I turn off and turn on the Bluetooth while listening for a state change.
Hi PsychoXIVI ,
When I am connecting to a paired android mobile device (running Android 9) , using the code
var connection = await BluetoothConnection.toAddress('<PairedDeviceAddress>')
,
I am facing the exception socket might closed or timeout, read ret: -1.
I am not understanding how to resolve the issue. Could you please help or suggest anything.
When I am connecting to a paired android mobile device (running Android 9)
Is the device you are trying to connect listening? Does it run also SDP? Does UUID match?
From my very important comment above:
B) Service Discovery Protocol is not available,
Android standalone modules like HC-05 should have configured it for default. For Raspberry Pi there is example how to setup it.
C) End device is using other Bluetooth protocol,
This library is for now using only RFCOMM. Other thing is also UUID expectation on the other side. There will be option to provide own UUID instead of hard-coded one in future. For now UUID is
00001101-0000-1000-8000-00805F9B34FB
.
PsychoXIVI,
Thanks for the prompt reply. So does that mean I can connect to only android standalone modules like HC-05 or Raspberry pi using this package?
Has anyone being successful in trying to connect 2 android mobile phones using this package?
Sorry, Bluetooth connection require both slave (server) and master (client). This library allow only act as client - at least for now. It is planned feature. Issue #17 is used to track this issue.
@edufolly i am still facing this issue can u please help me i m facing the same issue
@edufolly I have this issue while I am trying to connect to ESP32 Bluetooth :(
Hi @ctrleffive,
Was this issue resolved? Are you able to use the module without occurrence of this error? I'm looking forward to hearing from you.
Thanks.
Hey @vaibhiarora03, Actually, it's been a while since I left that project. Right now I'm unable to test it. You can maybe close this issue.
@ctrleffive okay. thanks.
hi @edufolly and @AgainPsychoX , is this issue resolved?
` if (isConnected()) { throw new IOException("already connected"); }
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
if (device == null) {
throw new IOException("device not found");
}
Method method = null;
try {
method = device.getClass().getMethod("createRfcommSocket", new Class[]{ int.class});
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
// method = device.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
BluetoothSocket socket = null;
try {
socket = (BluetoothSocket) method.invoke(device, 1);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}`### i did some reflection and did the trick , i cloned the project and modified the java file `BluetoothConnection.class`
Hi @david-macharia . Thanks for replying.
Were you able to completely resolve it by this integration of yours?
What was the occurrence rate of this issue with you?
Was this less frequent or was it a complete failure that your connection was not able to be created even once?
I also tried something which decreased the connection failure rate. I integrated re-connection by closing the socket, input and output streams. Sometimes due to connection failure, the socket and input-output streams are left open and when we try to re-connect the connection doesn't get established. But that too didn't help me completely resolve the issue.
public void connect() throws IOException {
if (isConnected()) {
throw new IOException("already connected");
}
// BluetoothSocket fallbackSocket = null;
boolean isConnectionEstablished = false;
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(mRemoteAddress);
if (device == null) {
throw new IOException("device not found");
}
mBluetoothSocket = device.createRfcommSocketToServiceRecord(DEFAULT_UUID); // @TODO . introduce ConnectionMethod
if (mBluetoothSocket == null) {
throw new IOException("socket connection not established");
}
// Cancel discovery, even though we didn't start it
bluetoothAdapter.cancelDiscovery();
if (mFirstConnection == 0)
mFirstConnection = 1;
try {
mBluetoothSocket.connect();
isConnectionEstablished = true;
} catch (IOException ioException) {
Log.e(TAG, "IO exception: " + ioException.getMessage());
try {
Class<?> clazz = mBluetoothSocket.getRemoteDevice().getClass();
Class<?>[] paramTypes = new Class<?>[] {Integer.TYPE};
Method m = clazz.getMethod("createRfcommSocket", paramTypes);
Object[] params = new Object[] {Integer.valueOf(1)};
mBluetoothSocket = (BluetoothSocket) m.invoke(mBluetoothSocket.getRemoteDevice(), params);
if (mBluetoothSocket != null) {
mBluetoothSocket.connect();
isConnectionEstablished = true;
}else{
Log.d(TAG, "fallback_socket received null....: " + mBluetoothSocket);
}
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | IOException e) {
Log.e(TAG, "exception_in_code....: " + e);
e.printStackTrace();
}
}
if (isConnectionEstablished) {
connectionThread = new ConnectionThread(mBluetoothSocket);
connectionThread.start();
} else {
if (mFirstConnection == 1) {
mFirstConnection = 2;
try {
reconnectSocket();
} catch (IOException e) {
throw new IOException(e + " 3333F");
}
} else {
mFirstConnection = 0;
throw new IOException("socket connection not established 2222");
}
}
}
In the function reconnectSocket()
, I close the socket, input and output streams and then try to connect again.
public void reconnectSocket() throws IOException {
Log.d(TAG, "Reconnection Bluetooth socket...");
if (mBluetoothSocket == null)
throw new IOException("Bluetooth Socket is NULL!");
StringBuilder errorBuilder = new StringBuilder();
try {
mBluetoothSocket.getInputStream().close();
} catch (IOException | NullPointerException e) {
e.printStackTrace();
Log.e(TAG, "Error closing input stream: " + e.getMessage());
errorBuilder.append("Error closing input stream: ").append(e.getMessage()).append(" | ");
}
try {
mBluetoothSocket.getOutputStream().close();
} catch (IOException | NullPointerException e) {
e.printStackTrace();
Log.e(TAG, "Error closing output stream: " + e.getMessage());
errorBuilder.append("Error closing output stream: ").append(e.getMessage()).append(" | ");
}
try {
mBluetoothSocket.close();
Thread.sleep(2000);
} catch (IOException | InterruptedException | NullPointerException e) {
e.printStackTrace();
Log.e(TAG, "Error closing bluetooth socket: " + e.getMessage());
errorBuilder.append("Error closing bluetooth socket: ").append(e.getMessage()).append(" | ");
}
try {
connect();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "Error starting service: " + e.getMessage());
errorBuilder.append("Error starting service: ").append(e.getMessage());
throw new IOException(errorBuilder.toString());
}
}
Hi all Actually I'm also facing the same issue from last week and I tried to go into deep of this problem then I found that it's waiting for the response from server side that isn't come first interact and it returning -1.
Is any one have any solution for this ??
Thanks regards Rupesh Singh
can anyone please explain about the error and how to correct the error ??? import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart'; import 'package:permission_handler/permission_handler.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Bluetooth App', home: BluetoothApp(), ); } }
class BluetoothApp extends StatefulWidget { @override _BluetoothAppState createState() => _BluetoothAppState(); }
class _BluetoothAppState extends State
@override void initState() { super.initState(); _requestPermissions(); _startDiscovery(); }
Future
Future
Future
void _configureBluetoothConnection() { // Implement your configuration steps here }
void _startReadingData() { Timer.periodic(Duration(seconds: 2), (Timer timer) async { if (connection.isConnected) { // Implement your data reading and handling here // Example: connection.output.add(utf8.encode('Hello, OBD!')); } else { timer.cancel(); } }); }
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Bluetooth App'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children:
);
} else {
return Text('No devices found.');
}
},
),
],
),
),
);
}
@override void dispose() { bluetooth.cancelDiscovery(); connection.dispose(); super.dispose(); } } this my code i got the error D/FlutterBluePlugin( 6091): Connecting to C8:9F:0C:93:BA:3E (id: 2) I/BluetoothAdapter( 6091): cancelDiscovery I/BluetoothSocket( 6091): connect() for device XX:XX:XX:XX:BA:3E called by pid: 6091 I/flutter ( 6091): PlatformException(connect_error, read failed, socket might closed or timeout, read ret: -1, java.io.IOException: read failed, socket might closed or timeout, read ret: -1 I/flutter ( 6091): at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:1054) I/flutter ( 6091): at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:1068) I/flutter ( 6091): at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:583) I/flutter ( 6091): at io.github.edufolly.flutterbluetoothserial.BluetoothConnection.connect(BluetoothConnection.java:57) I/flutter ( 6091): at io.github.edufolly.flutterbluetoothserial.BluetoothConnection.connect(BluetoothConnection.java:64) I/flutter ( 6091): at io.github.edufolly.flutterbluetoothserial.FlutterBluetoothSerialPlugin$FlutterBluetoothSerialMethodCallHandler.lambda$onMethodCall$4$io-github-edufolly-flutterbluetoothserial-FlutterBluetoothSerialPlugin$FlutterBluetoothSerialMethodCallHandler(FlutterBluetoothSerialPlugin.java:1007) I/flutter ( 6091): at io.github.edufolly.flutterbluetoothserial.FlutterBluetoothSerialPlugin$FlutterBluetoothSerialMethodCallHandler$$ExternalSyntheticLambda7
Error occurred while connecting to a paired device.
Flutter Doctor