Android App drops Bluetooth 2 SPP data stream after 30 seconds

771 Views Asked by At

Problem. Data stream over Bluetooth 2 SPP connection in my Android app hangs after about thirty seconds

Context. I’m trying to connect an android tablet running Android 4.3 (first generation nexus 7) as a client to a Bluetooth 2 RN-41 module that is being controlled by an Atmega 1284P microcontroller. The microcontroller is just pushing data over the USART line to the Bluetooth module, and I’m having success connecting to the module and streaming some of that data in my android application. However, I’ve noticed that after about thirty seconds the data stream stops (even though the connection seems to persist). This is driving me crazy and I’m not quite sure what is wrong. I’m a beginner Android developer. Thanks everyone for your help!

Android Code. I took out the else's and some of the catches to shorten the amount of code and attempted to break down the code in logical, commented sections. I'm new to this, so I apologize if my code is silly!

private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private InputStream inStream = null;
private BluetoothDevice pairedScale = null;
private UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); // found this at https://stackoverflow.com/questions/4632524/how-to-find-the-uuid-of-serial-port-bluetooth-device
private String MAC_ADDR;
private boolean isBTConnected = false;
...


public void connectToBT() {

/* * *
 * Find Bluetooth device from list of paired devices
 * * */

        if (mBluetoothAdapter.isEnabled()) {
            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
            MAC_ADDR = macSpinner.getItemAtPosition(macSpinner.getSelectedItemPosition()).toString();
            for (BluetoothDevice device : pairedDevices) {
                Log.v("HP", "Iterating through paired BT devices for a match");
                if (MAC_ADDR.equals(device.toString())) {
                    pairedScale = device;
                    Toast.makeText(MainActivity.this, device.toString(), Toast.LENGTH_LONG).show();
                    Log.v("HP", "Found a BT device match: " + device.toString());
                    changeDisplayText("\nUsing paired device: " + device.toString(), true);
                    break;
                }
            }
        }


/* * *
 * Spawn new thread and attempt to connect
 * * */

        // If socket created successfully, spawn new thread
        if (btSocket != null) {
            new Thread(new Runnable() {
                public void run() {
                    isConnecting = true;
                    // try to connect
                    try {
                        btSocket.connect();
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.e("HP", "Couldn't connect socket");
                    }

/* * *
 * Create IO Streams
 * * */

                    // create IO stream
                    if (btSocket.isConnected()) {
                        Log.v("HP", "Congratulations! Socket connected");
                        isBTConnected = true;
                        try {
                            inStream = btSocket.getInputStream();
                            outStream = btSocket.getOutputStream();
                        } catch (IOException e) {
                            e.printStackTrace();
                            Log.e("HP", "Couldn't create io stream");
                        }
                    } else {
                        Log.e("HP", "Couldn't connect socket");
                    }

                    // we have our io streams, now get data
                    if (isBTConnected && inStream != null) {
                        Log.v("HP", "Attempting to get data from inStream");
                        runOnUiThread(new Runnable() {
                            public void run() {
                                changeDisplayText("\nConnection successful!" +
                                        "\nStreaming Data...", true);
                            }
                        });
                        Log.v("HP", "Starting data stream...");
                        // read from the input stream
                        byte[] scaleData = new byte[512];
                        byte[] allScaleData;
                        String hpFileName = "streamedData_" + epoch.toString() + ".dat";
                        FileOutputStream fOutStream = null;

/* * *
 * Create file to store data
 * * */

                        // external storage
                        File myDir = new File(Environment.getExternalStorageDirectory().toString() + "/streamedData");
                        myDir.mkdirs();
                        File file = new File(myDir, hpFileName);
                        Log.v("HP", "Attempted to make file");
                        try {
                            fOutStream = new FileOutputStream(file);
                            Log.v("HP", "Made file");
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                            Log.e("HP", "Error: Couldn't make file");
                        }


/* * *
 * Stream data here
 * * */

                        Integer bytesRead;
                        while (true) {
                            try {
                                bytesRead = inStream.read(scaleData);
                                Log.d("HP", "Read " + bytesRead.toString() + " bytes");
                                fOutStream.write(Arrays.copyOfRange(scaleData, 0, bytesRead.intValue()));
                            } catch (IOException e) {
                                Log.d("HP", "Done reading bytes");
                                try {
                                    btSocket.close();
                                } catch (IOException e1) {
                                    e1.printStackTrace();
                                }
                                break;
                            }
                        }

                        try {
                            fOutStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    clearBTConnection();
                    isConnecting = false;
                }
            }).start();
        }
    }
}

Research. I've read a few articles with no luck. For example: Android Bluetooth SPP connection to seems to go dead after a couple of seconds

0

There are 0 best solutions below