4

Estoy tratando de que en una aplicación Android pueda recibir los datos de dos dispositivos bluetooth diferentes, uno a la ves obviamente. Por separado esto trabaja bien, es decir, si primero establezco conexión con uno de ellos, este envía cadenas hacia la app y posteriormente esta hace procesamiento de los datos, en el caso de este dispositivo la recepción de los datos en la app se hace de esta manera:

public void run() {
    Log.i(TAG, "BEGIN mConnectedThread");
    int bytes;
    mDataParse = new DataParse(mHandler);

    try {
        Thread.sleep(100);
    } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    String prev = null;
    while (mState == STATE_CONNECTED) {

        try {
            /********************************************** PRIMER DISPOSITIVO **********************************************************/
            /************************** Parte para capturar datos del arduino y poder hacer las substrings ******************************/
            /****************************************************************************************************************************/

            String readMessage = new String();
            int c,d;
            int tmpSize=0;
            boolean parsedOK=false;
            while((c = mmInStream.read()) != -1) {//Notese que no debe llevar tamaño de buffer
                char tmpChar = (char) c;
                if(tmpChar=='\n'){
                    mHandler.obtainMessage(CONST.MSG_LEER,readMessage).sendToTarget();//cadenas completas obtenidas para poder procesarlas
                    readMessage="";
                    tmpSize=0;
                }else{
                    readMessage = readMessage+tmpChar;
                    tmpSize++;
                }
            }
            /****************************************************************************************************************************/
            /****************************************************************************************************************************/
            /****************************************************************************************************************************/

        } catch (IOException e) {
            Log.e(TAG, "disconnected", e);
            connectionLost();
            // Start the service over to restart listening mode
            BluetoothChatService.this.start();
            break;
        }

        try {
            Thread.sleep(40);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

Cuando establezco conexión con un segundo dispositivo este envía datos hacia la app y posteriormente estos datos son pasados a otra clase para realizar el procesamiento de estos, en el caso de este segundo dispositivo la recepción de los datos en la app se hace de la siguiente manera:

public void run() {
    Log.i(TAG, "BEGIN mConnectedThread");
    //byte[] buffer = new byte[1024];
    int bytes;
    mDataParse = new DataParse(mHandler);

    try {
        Thread.sleep(100);
    } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    String prev = null;
    while (mState == STATE_CONNECTED) {

        try {
            /********************************************** sEGUNDO DISPOSITIVO DISPOSITIVO *********************************************/
            /************************** Parte para capturar datos del SEGUNDO DISPOSITIVO y hacer el procesamiento correspondiente ******/
            /****************************************************************************************************************************/
                    byte[] buffer = new byte[256];
                    bytes = mmInStream.read(buffer);//necesita el tamaño en bytes de buffer//sin tamaño de buffer no puede procesar
                    mDataParse.Add(buffer, bytes); //Metodo de la clase donde se procesan los datosentrantes del bluetooth
            /****************************************************************************************************************************/
            /****************************************************************************************************************************/
            /****************************************************************************************************************************/
        } catch (IOException e) {
            Log.e(TAG, "disconnected", e);
            connectionLost();
            // Start the service over to restart listening mode
            BluetoothChatService.this.start();
            break;
        }

        try {
            Thread.sleep(40);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

Como pueden notar, la única diferencia es que para el segundo dispositivo es obligatorio el uso de un tamaño de buffer de lectura:

byte[] buffer = new byte[256];
bytes = mmInStream.read(buffer);//necesita el tamaño en bytes de buffer//sin tamaño de buffer no puede procesar
mDataParse.Add(buffer, bytes);

Mientras que en el primero no se debe llevar tamaño de buffer pues de fijar un tamaño de buffer el procesamiento no se hace correctamente, al contrario del segundo dispositivo en el cual si no se le pone un tamaño no se puede procesar los datos en la clase a la cual se envían.

while((c = mmInStream.read()) != -1) 

¿Cómo puedo hacer para que ambos dispositivos puedan conectar en la misma app tomando en cuenta que uno necesita un tamaño de buffer y otro no?

Esta es la clase donde se hace el procesamiento del segundo dispositivo, en el cual es necesario el tamaño del buffer

public class DataParse implements Runnable {
    int cuentaValoresECG=0;
    int cuentaValoresOXI=0;
    private final String         TAG                 = getClass().getName();
    private final static int     BUFFER_SIZE         = 1024;
    private final int[]   PACKAGE_HEAD        = new int[]{0x55,0xaa};
    private final int     PKG_ECG_WAVE        = 0x01;
    private final int     PKG_ECG_PARAM       = 0x02;
    private final int     PKG_NIBP            = 0x03;
    private final int     PKG_SPO2            = 0x04;
    private final int     PKG_TEMP            = 0x05;
    private final int     PKG_SW_VER          = 0xfc;

    private final int     PKG_HW_VER          = 0xfd;
    private final int     PKG_SPO2_WAVE       = 0xfe;

    private int skipCounter = 0;
    private Handler mHandler;


    private byte[] recvData = new byte[BUFFER_SIZE];
    private int    emptyIndex = 0;
    private int    parseIndex = 0;

    public DataParse(Handler handler)
    {
        // TODO Auto-generated constructor stub
        this.mHandler = handler;
    }

    public void Add(byte[] buf, int bufSize)
    {
        boolean pkgStart = false;
        int pkgIndex = 0;
        int pkgLength = 0;
        byte[] pkgData = null;


        if(bufSize+emptyIndex <= BUFFER_SIZE)
        {
            System.arraycopy(buf, 0, recvData, emptyIndex, bufSize);
            emptyIndex = (emptyIndex+bufSize) % BUFFER_SIZE;
        }
        else if( (bufSize+emptyIndex > BUFFER_SIZE) && (bufSize+emptyIndex < 2*BUFFER_SIZE))
        {
            System.arraycopy(buf, 0, recvData, emptyIndex, BUFFER_SIZE-emptyIndex);
            int temp = emptyIndex;
            emptyIndex = 0;
            System.arraycopy(buf, BUFFER_SIZE-temp, recvData, emptyIndex, bufSize-(BUFFER_SIZE-temp));
            emptyIndex = bufSize-(BUFFER_SIZE-temp);
        }
        else {
            Log.i(TAG, "Receive too much data.");
            return;
        }

        if(bufSize < 5) return;

        int i = parseIndex;
        while (i != emptyIndex) {

            if ((recvData[i]&0xff) == PACKAGE_HEAD[0]) {
                int j = (i + 1)%BUFFER_SIZE;
                if (j != emptyIndex && (recvData[j]&0xff) == PACKAGE_HEAD[1]) {
                    int k = (j+1)%BUFFER_SIZE;
                    if(k != emptyIndex)
                    {
                        pkgLength = recvData[k]&0xff;
                        pkgData = new byte[pkgLength+2];
                        pkgStart = true;
                        pkgIndex = 0;
                        parseIndex = i;
                    }
                }
            }
            if (pkgStart && pkgLength > 0) {
                pkgData[pkgIndex] = recvData[i];
                pkgIndex++;

                if ((pkgLength != 0) && (pkgIndex == pkgLength + 2)) {
                    if(CheckSum(pkgData)){
                        ParsePackage(pkgData);
                    }
                    pkgStart = false;
                    parseIndex = (i + 1) % BUFFER_SIZE;
                }
            }
            i = (i + 1) % BUFFER_SIZE;
        }


    }

    @Override
    public void run() {
    }


    private void ParsePackage(final byte[] pkgData) {
        // TODO Auto-generated method stub
        int pkgType = pkgData[3]&0xff;
        switch (pkgType) {

            case PKG_ECG_WAVE:

                skipCounter++;

                if(skipCounter == 1)
                {
                    cuentaValoresECG++;


                    MainActivity.mECGWaveDraw.add(pkgData[4]&0xff);//Aqui es donde se mandan los datos para hacer la Grafica
                    float f = pkgData[4]&0xff;
                    Globals.lstSendContadorECGDataParse.add(cuentaValoresECG);
                    Globals.lstSendECGValor.add(pkgData[4]&0xff);
                    UIActions.calcularPromedio(Globals.lstSendContadorECGDataParse,Globals.lstSendECGValor );
                    Globals.lstSendContadorECGDataParse.remove(0);
                    Globals.lstSendECGValor.remove(0);

                    skipCounter = 0;
                }

                break;

            case PKG_SPO2_WAVE:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        MainActivity.mSpO2WaveDraw.add(pkgData[4]&0xff);
                    }
                }).start();

                cuentaValoresOXI++;

                Globals.lstSendSPOGraphValueData.add(pkgData[4]&0xff);
                System.out.println("Valor grafico SPO["+cuentaValoresOXI+"] = "+Integer.toString(pkgData[4]&0xff));

                break;
            case PKG_ECG_PARAM:
                mHandler.obtainMessage(CONST.MESSAGE_ECG_PARAMS, 0xff&pkgData[6], 0xff&pkgData[5]).sendToTarget();
                break;
            case PKG_NIBP:
                mHandler.obtainMessage(CONST.MESSAGE_NIBP_PARAMS, 0xff&pkgData[6], 0xff&pkgData[8]).sendToTarget();

                break;
            case PKG_SPO2:
                mHandler.obtainMessage(CONST.MESSAGE_SPO2_PARAM, 0xff&pkgData[5], 0xff&pkgData[6]).sendToTarget();

                break;
            case PKG_TEMP:
                mHandler.obtainMessage(CONST.MESSAGE_TEMP_PARAMS, 0xff&pkgData[5], 0xff&pkgData[6]).sendToTarget();
                break;
            case PKG_SW_VER:
                break;
            case PKG_HW_VER:
                break;
            default:
                break;
        }

    }

    private boolean CheckSum(byte[] packageData) {
        // TODO Auto-generated method stub
        int sum = 0;
        for(int i = 2; i < packageData.length-1; i++)
        {
            sum+=(packageData[i]&0xff);
        }

        if(((~sum)&0xff) == (packageData[packageData.length-1]&0xff))
        {
            return true;
        }

        return false;
    }
}

Este es el case dentro de la clase principal donde hago el procesamiento de las cadenas que recibo del primer dispositivo:

case CONST.MSG_LEER:
        //String readMessage = (String) msg.obj;
        String readMessage =  msg.obj.toString();
        //System.out.println("Mensaje recibido: "+readMessage);
        int charInicioCadena = readMessage.indexOf("#");
        int charInicioTiempo = readMessage.indexOf("{");
        int charInicioValor = readMessage.indexOf("(");
        int charInicioValor2 = readMessage.indexOf(")");
        int charFinCadena = readMessage.indexOf("~");


        if (charFinCadena > 0) {
        try {
        nombreDispositivo = readMessage.substring(charInicioCadena + 1, charInicioTiempo);

        switch (nombreDispositivo) {

        case "ecg":
        cuenta++;
        segundo = readMessage.substring(charInicioTiempo + 1, charInicioValor);
        valorECG = readMessage.substring(charInicioValor + 1, charFinCadena);

        Globals.lstSendTiempo.add(Integer.parseInt(segundo));
        Globals.lstSendECGValor.add(Integer.parseInt(valorECG));
        UIActions.calcularPromedio(Globals.lstSendTiempo, Globals.lstSendECGValor);
        Globals.lstSendTiempo.remove(0);
        Globals.lstSendECGValor.remove(0);
        break;


        case "oxi":
        String tiempoMS = readMessage.substring(charInicioTiempo+1,charInicioValor);
        String valor1 = readMessage.substring(charInicioValor+1,charInicioValor2);
        String valor2 = readMessage.substring(charInicioValor2+1,charFinCadena);
        int v1 = Integer.parseInt(valor1);
        int v2 = Integer.parseInt(valor2);
        int t = Integer.parseInt(tiempoMS);
        cuentaDatosOxy++;
        Globals.lstSendOxy.add(v1);
        Globals.lstSendOxy2.add(v2);
        Globals.lstSendCounterOxy.add(t);
        Globals.lstSendContadorDatosOxy.add(cuentaDatosOxy);
        new Handler().postDelayed(new Runnable() {
@Override
public void run() {
        ServiceManager2.onSendData();
        }
        },255);
        System.out.println("******************************************************");
        break;

        case "tem":
        cuentaDatosTemp++;
        String tiempoTemp = readMessage.substring(charInicioTiempo+1,charInicioValor);
        String stringTemperatura = readMessage.substring(charInicioValor+1,charFinCadena);
        float temperature = (Integer.parseInt(stringTemperatura))/100;
        Globals.lstSendTemp.add(temperature);
        int timeTemp = Integer.parseInt(stringTemperatura);
        Globals.lstSendTimerTempARDData.add(timeTemp);
        Globals.lstSendContadorDatosTemp.add(cuentaDatosTemp);
        new Handler().postDelayed(new Runnable() {
@Override
public void run() {
        ServiceManager2.onSendData();
        }
        },273);
        System.out.println("******************************************************");
        break;

default:
        System.out.print("No esta entrando a ningun caso");
        String r = recDataString.substring(charInicioCadena,charFinCadena);
        Log.d("ERROR",r);
        break;
        }
        }catch(NullPointerException|StringIndexOutOfBoundsException|NumberFormatException ex){}
        }

        break;

Parte del mmInStream

    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        private DataParse mDataParse;

    public ConnectedThread(BluetoothSocket socket, String socketType) {
        Log.d(TAG, "create ConnectedThread: " + socketType);
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the BluetoothSocket input and output streams
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
            Log.e(TAG, "temp sockets not created", e);
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }
....
2
  • si para uno depende de que haya un tamaño de buffer y para el otro no, entonces lea siempre el tamaño de buffer fijo para ambos casos y ya se entiende para el caso en que no lo necesita aparte segun los datos reales que hayan llegado, igual falta codigo para ver porque realmente necesita que sea de esa manera ya que si esta utilizando bluetooth serial, uno podria leer por tamaño de buffer o por byte dependiendo de la cantidad de datos entrantes
    – Lcop
    el 19 ene. 2017 a las 18:43
  • 1
    Gracias por responder, he agregado las clases donde se hace el procesamiento para los datos de cada dispositivo, espero te sean útiles para poderme ayudar.
    – Xavi
    el 19 ene. 2017 a las 19:00

1 respuesta 1

1
+50

Entiendo que lo que debe hacer la app es:

  1. Conectar primer dispositivo
  2. Leer datos
  3. Procesar datos
  4. Desconectar dispositivo
  5. Conectar segundo dispositivo
  6. Leer datos
  7. Procesar datos
  8. Desconectar dispositivo

como haces esto, como creas el mmInStream?

un saludo

@Xavi En efecto eso es lo que quiero hacer, ya que de momento para poder leer de uno u otro dispositivo(holter o arduino) tengo que poner primero esta parte del codigo (en el caso de querer leer del holter).

/************************** Parte para capturar datos del SEGUNDO DISPOSITIVO y hacer el procesamiento correspondiente ******/
/****************************************************************************************************************************/
                        byte[] buffer = new byte[256];
                        bytes = mmInStream.read(buffer);//necesita el tamaño en bytes de buffer//sin tamaño de buffer no puede procesar
                        mDataParse.Add(buffer, bytes); //Metodo de la clase donde se procesan los datosentrantes del bluetooth
/****************************************************************************************************************************/

Y sustituirla por esta en el caso de querer leer del arduino:

/************************** Parte para capturar datos del arduino y poder hacer las substrings ******************************/
/****************************************************************************************************************************/

                String readMessage = new String();
                int c,d;
                int tmpSize=0;
                boolean parsedOK=false;
                while((c = mmInStream.read()) != -1) {//Notese que no debe llevar tamaño de buffer
                    char tmpChar = (char) c;
                    if(tmpChar=='\n'){
                        mHandler.obtainMessage(CONST.MSG_LEER,readMessage).sendToTarget();//cadenas completas obtenidas para poder procesarlas
                        readMessage="";
                        tmpSize=0;
                    }else{
                        readMessage = readMessage+tmpChar;
                        tmpSize++;
                    }
                }

Switch case en run:

    public void run() {
        Log.i(TAG, "BEGIN mConnectedThread");
        int bytes;
        mDataParse = new DataParse(mHandler);

        try {
            Thread.sleep(100);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        String prev = null;
        while (mState == STATE_CONNECTED) {

            try {
              switch(dispositivo){
                  case 1:
                      /************************** Parte para capturar datos del arduino y poder hacer las substrings ******************************/
                      String readMessage = new String();
                      int c,d;
                      int tmpSize=0;
                      boolean parsedOK=false;
                      while((c = mmInStream.read()) != -1) {//Notese que no debe llevar tamaño de buffer
                           char tmpChar = (char) c;
                           if(tmpChar=='\n'){
                              mHandler.obtainMessage(CONST.MSG_LEER,readMessage).sendToTarget();//cadenas completas obtenidas para poder procesarlas
                              readMessage="";
                              tmpSize=0;
                           }else{
                              readMessage = readMessage+tmpChar;
                              tmpSize++;
                           }
                      }
                  break;
                  case 2:
                      /************************** Parte para capturar datos del SEGUNDO DISPOSITIVO y hacer el procesamiento correspondiente ******/
                      byte[] buffer = new byte[256];
                      bytes = mmInStream.read(buffer);//necesita el tamaño en bytes de buffer//sin tamaño de buffer no puede procesar
                      mDataParse.Add(buffer, bytes); //Metodo de la clase donde se procesan los datosentrantes del bluetooth
                  break;
                }
            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                connectionLost();
                // Start the service over to restart listening mode
                BluetoothChatService.this.start();
                break;
            }

            try {
                Thread.sleep(40);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
6
  • 1
    Buen dia @Ivan G Domenech he agregado la parte del codigo donde se crea el mmInStream
    – Xavi
    el 28 ene. 2017 a las 14:05
  • Y porque no haces un switch como en la clase que procesa la cadena: switch (nombreDispositivo) { ..., en todo caso sabes que puedes conectar a varios dispositivos bluetooth al mismo tiempo, hasta 7 creo, revisa este enlace si te sirve arissa34.github.io/Android-Multi-Bluetooth-Library el 28 ene. 2017 a las 14:38
  • Tienes idea de como crear el switch case?
    – Xavi
    el 31 ene. 2017 a las 18:26
  • Seria algo así: switch (nombreDispositivo) { case "ecg": /*parte para capturar dispositivo 1*/; case "oxi": /*parte para capturar dispositivo 2*/; } , dentro del -> while (mState == STATE_CONNECTED) { try { , en el metodo run, no? el 31 ene. 2017 a las 19:06
  • 1
    Deberías poder identificar los dispositivos por nombre -> BluetoothDevice.getName() , mas información developer.android.com/reference/android/bluetooth/… el 1 feb. 2017 a las 15:24

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.