Bluetooth SPP - gelegentlich chaos

  • Antworten:2
Jan Klement
  • Forum-Beiträge: 2

24.06.2016, 00:08:06 via Website

Hallo,

Ich habe erfolgreich ein HC-06 Modul+Arduino mit meinem Tablet verbunden. Aber manchmal sind ein par ASCII Zeichen an der falschen Stelle in dem empfangenem StringBuider sb. In einer Bluetooth Terminal app sehe ich keine Fehler. Daher denke ich das es an meinem Android Code liegt.

Hat jemand so etwas vergleichbares gehabt oder sieht vieleicht schon wo der Fehler liegt?

Vielen Dank für Antworten!

in der Handler in der oncreate Funktion:

    h = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case RECIEVE_MESSAGE:                                                   // if receive massage
                    byte[] readBuf = (byte[]) msg.obj;
                    String strIncom = new String(readBuf, 0, msg.arg1);                 // create string from bytes array
                    //Log.d(TAG,strIncom);
                    sb.append(strIncom);                                                // append string
                    int endOfLineIndex = sb.indexOf("\r\n");                            // determine the end-of-line

                    if (endOfLineIndex > 0) {                                            // if end-of-line,
                        String sbprint = sb.substring(0, endOfLineIndex);               // extract string
                        Log.d(TAG, "Data from Arduino: " + sbprint);
                        sb.delete(0, endOfLineIndex+2);                                      // and clear
                        textViewInfo.setText("Data from Arduino: " + sbprint);            // update TextView

                        /*char[] A= (sbprint.toCharArray());
                        int sum = 0;
                        int i;
                        for( i=0; i< 5;i++) {
                            sum += (int) A[i];
                        }*/

                        appendData(sbprint);
                        updateDisplay();
                        btnMode.setEnabled(true);
                        btnSend.setEnabled(true);
                    }
                    else if( sb.indexOf("\n")==1){
                        sb.delete(0,1);
                    }
                    break;
            }
        };
    };

Hier die Asyntask Classe

    private class ConnectBT extends AsyncTask<Void, Void, Void>  // UI thread
{
    private boolean ConnectSuccess = true; //if it's here, it's almost connected

    @Override
    protected void onPreExecute()
    {
        progress = ProgressDialog.show(MainActivity.this, "Connecting...", "Please wait!!!");  //show a progress dialog
    }

    @Override
    protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
    {
        try
        {
            if (btSocket == null || !isBtConnected)
            {
                myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
                BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
                btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
                BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
                btSocket.connect();//start connection
                mConnectedThread = new ConnectedThread(btSocket);
                mConnectedThread.start();
            }
        }
        catch (IOException e)
        {
            ConnectSuccess = false;//if the try failed, you can check the exception here
        }
        return null;
    }
    @Override
    protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
    {
        super.onPostExecute(result);

        if (!ConnectSuccess)
        {
            msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
            //finish();
        }
        else
        {
            msg("Connected.");
            isBtConnected = true;
        }
        progress.dismiss();
    }
}

private class ConnectedThread extends Thread {
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer = new byte[2048];  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);        // Get number of bytes and message in "buffer"
                h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();     // Send to message queue Handler
            } catch (IOException e) {
                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(String message) {
        Log.d(TAG, "...Data to send: " + message + "...");
        byte[] msgBuffer = message.getBytes();
        try {
            mmOutStream.write(msgBuffer);
        } catch (IOException e) {
            Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
        }
    }
}

Antworten
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

24.06.2016, 09:45:41 via App

Ich würde mal schauen dass du das ganze debuggen kannst. Dann schaust du dir das Byte Array an und findest raus woran es liegt.

LG Pascal //It's not a bug, it's a feature. :) ;)

Antworten
Vor Nachname
  • Forum-Beiträge: 2

26.06.2016, 23:04:30 via Website

Jan Klement

    public void run() {
        byte[] buffer = new byte[2048];  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);        // Get number of bytes and message in "buffer"
                h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();     // Send to message queue Handler
            } catch (IOException e) {
                break;
            }
        }
    }

Das Problem hatte ich auch vor Kurzem. Schuld daran ist der Buffer buffer, der zeitgleich gefüllt und abgearbeitet wird!
Ich habe eine Copy des Buffers definiert:
byte[] copyofbuffer = new byte[256];

und dann vor dem sendToTarget()

buffer in copyofbuffer geklont und den copyofbuffer an den queue Handler geschickt. Das müsste bei dir dann so aussehen

public void run() {
byte[] buffer = new byte[2048]; // buffer store for the stream
int bytes; // bytes returned from read()

      // Keep listening to the InputStream until an exception occurs
         while (true) {
             try {
                 // Read from the InputStream
                 bytes = mmInStream.read(buffer);        // Get number of bytes and message in "buffer"
                 copyofbuffer = buffer.clone();
                 h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, copyofbuffer).sendToTarget();     // Send to message queue Handler
             } catch (IOException e) {
                 break;
             }
         }
     }

Viel Erfolg!

Antworten