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

read failed, socket might closed or timeout, read ret: -1 #18

Open
ctrleffive opened this issue Mar 6, 2019 · 27 comments
Open

read failed, socket might closed or timeout, read ret: -1 #18

ctrleffive opened this issue Mar 6, 2019 · 27 comments
Labels
Type: Bug Something isn't working Type: Maintenance Lack of maintenance. Should be quick fix.

Comments

@ctrleffive
Copy link

Error occurred while connecting to a paired device.

W/BluetoothAdapter(28901): getBluetoothService() called with no BluetoothManagerCallback
E/FlutterBluePlugin(28901): read failed, socket might closed or timeout, read ret: -1
E/FlutterBluePlugin(28901): java.io.IOException: read failed, socket might closed or timeout, read ret: -1
E/FlutterBluePlugin(28901): 	at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:741)
E/FlutterBluePlugin(28901): 	at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:753)
E/FlutterBluePlugin(28901): 	at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:375)
E/FlutterBluePlugin(28901): 	at io.github.edufolly.flutterbluetoothserial.FlutterBluetoothSerialPlugin.lambda$connect$0(FlutterBluetoothSerialPlugin.java:235)
E/FlutterBluePlugin(28901): 	at io.github.edufolly.flutterbluetoothserial.-$$Lambda$FlutterBluetoothSerialPlugin$52C5RUgoP_r70sgAnP8ZXC1Ysz0.run(lambda)
E/FlutterBluePlugin(28901): 	at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
E/FlutterBluePlugin(28901): 	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
E/FlutterBluePlugin(28901): 	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
E/FlutterBluePlugin(28901): 	at java.lang.Thread.run(Thread.java:760)

Flutter Doctor

[✓] Flutter (Channel stable, v1.2.1, on Linux, locale en_GB.UTF-8)
    • Flutter version 1.2.1 at /home/chandu/Flutter
    • Framework revision 8661d8aecd (3 weeks ago), 2019-02-14 19:19:53 -0800
    • Engine revision 3757390fa4
    • Dart version 2.1.2 (build 2.1.2-dev.0.0 0a7dcf17eb)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /home/chandu/Android/Sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.3
    • ANDROID_SDK_ROOT = /home/chandu/Android/Sdk
    • Java binary at: /opt/android-studio/jre/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)
    • All Android licenses accepted.

[✓] Android Studio (version 3.3)
    • Android Studio at /opt/android-studio
    • Flutter plugin version 33.3.1
    • Dart plugin version 182.5215
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)

[✓] VS Code (version 1.31.1)
    • VS Code at /usr/share/code
    • Flutter extension version 2.24.0

[✓] Connected device (1 available)
    • Redmi Note 4 • 192.168.0.100:5555 • android-arm64 • Android 7.0 (API 24)

• No issues found!
@niteforce
Copy link

niteforce commented Apr 7, 2019

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

@rafaelterada
Copy link
Contributor

I created a new pull correcting this error

@edufolly
Copy link
Owner

edufolly commented Apr 9, 2019

I merged @rafaelterada. As soon as possible I'll release a new version. Thanks a lot.

@AlexanderHow
Copy link

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

@edufolly
Copy link
Owner

edufolly commented Jun 5, 2019

Hi @AlexanderHow,

if your adapter is BLE compatible, try to use flutter_blue.

Best.

@AlexanderHow
Copy link

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

@ianhzhang
Copy link

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.

@ianhzhang
Copy link

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.

@matteobertino
Copy link

matteobertino commented Jun 25, 2019

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.

@AgainPsychoX
Copy link
Collaborator

AgainPsychoX commented Jun 27, 2019

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.

@anilslabs
Copy link

anilslabs commented Dec 23, 2019

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.

@AgainPsychoX
Copy link
Collaborator

AgainPsychoX commented Dec 24, 2019

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.

@jovanovski
Copy link

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.

@AakashAgiwal
Copy link

AakashAgiwal commented Mar 4, 2020

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.

@AgainPsychoX
Copy link
Collaborator

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.

@AakashAgiwal
Copy link

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?

@AgainPsychoX
Copy link
Collaborator

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.

@uzairleo
Copy link

uzairleo commented Sep 7, 2020

@edufolly i am still facing this issue can u please help me i m facing the same issue

@MohammadSharafi
Copy link

MohammadSharafi commented Jan 3, 2022

@edufolly I have this issue while I am trying to connect to ESP32 Bluetooth :(

@vaibhiarora03
Copy link

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.

@ctrleffive
Copy link
Author

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.

@vaibhiarora03
Copy link

@ctrleffive okay. thanks.

@vaibhiarora03
Copy link

hi @edufolly and @AgainPsychoX , is this issue resolved?

@david-macharia
Copy link

` 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`

@vaibhiarora03
Copy link

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());
        }
    }

@rupeshdashtech
Copy link

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

@Senthilrajagunasekar
Copy link

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 {
FlutterBluetoothSerial bluetooth = FlutterBluetoothSerial.instance;
late BluetoothConnection connection;
bool isConnected = false;

@OverRide
void initState() {
super.initState();
_requestPermissions();
_startDiscovery();
}

Future _requestPermissions() async {
Map<Permission, PermissionStatus> status = await [
Permission.bluetooth,
Permission.bluetoothConnect,
Permission.bluetoothScan,
Permission.location,
].request();
print("Bluetooth status: ${status[Permission.bluetooth]}");
print("Bluetooth Connect status: ${status[Permission.bluetoothConnect]}");
print("Bluetooth Connect status: ${status[Permission.bluetoothScan]}");
print("Location status: ${status[Permission.location]}");
}

Future _startDiscovery() async {
try {
await bluetooth.startDiscovery();
} catch (e) {
print(e);
}
}

Future _connectToDevice(BluetoothDevice device) async {
try {
connection = await BluetoothConnection.toAddress(device.address);
setState(() {
isConnected = true;
});
_configureBluetoothConnection();
_startReadingData();
} catch (e) {
print(e);
}
}

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: [
Text(
'Bluetooth Status: ${isConnected ? "Connected" : "Disconnected"}',
style: TextStyle(fontSize: 18),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
_startDiscovery();
},
child: Text('Discover Devices'),
),
SizedBox(height: 20),
FutureBuilder<List>(
future: bluetooth.getBondedDevices(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else if (snapshot.hasData) {
List? devices = snapshot.data;
return Column(
children: (devices ?? []).map((device) => ListTile(
title: Text(device.name ?? 'Unknown'),
subtitle: Text(device.address),
onTap: () {
_connectToDevice(device);
},
)).toList(),

              );
            } 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Type: Bug Something isn't working Type: Maintenance Lack of maintenance. Should be quick fix.
Projects
None yet
Development

No branches or pull requests