蓝牙无法接收正确的数据

时间:2017-03-11 15:33:48

标签: android bluetooth

即时发送数据" 52 40 00 00 CF E6 2A 1 2A 0 0 0 0 5 2A 0 0 0 0 2A 0 0 0 0 0 3B 00" 来自HC-05。但问题是,当我收到数据时,我会得到不同的数据。 设备连接正常,但是当我向移动设备发送数据时,我得到了错误的数据。帮助我。

这是我的代码我做错了什么?

    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btnSubmit, nextPage;
TextView txtArduino, txtString, txtStringLength, txtOutput, lblmeterId;
EditText txtMeterId, txtCommandNo;
Spinner txtCommandType;
Handler bluetoothIn;


StringBuilder packetFormat;
String packetRequest;

long packetFormatArray[] = new long[28];
long receivedDataArray[] = new long[28];

final int handlerState = 0;  //used to identify handler message
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder recDataString = new StringBuilder();

private ConnectedThread mConnectedThread;

private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

// String for MAC address
private static String address;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    btnSubmit = (Button) findViewById(R.id.btnSubmit);

    nextPage = (Button) findViewById(R.id.nextPage);
    txtString = (TextView) findViewById(R.id.txtString);
    txtStringLength = (TextView) findViewById(R.id.testView1);
    lblmeterId = (TextView) findViewById(R.id.lblmeterId);

    txtOutput = (TextView) findViewById(R.id.txtOutput);
    txtMeterId = (EditText) findViewById(R.id.txtMeterId);
    txtCommandNo = (EditText) findViewById(R.id.txtCommandNo);
    txtCommandType = (Spinner) findViewById(R.id.txtCommandType);


    bluetoothIn = new Handler() {
        public void handleMessage(android.os.Message msg) {

            if (msg.what == handlerState) {       

                byte[] readBuf = (byte[]) msg.obj;

                receivedDataArray = BytesTrans.bytes2HexString(readBuf, msg.arg1);

                StringBuilder RpacketFormat = new StringBuilder();
                for (long value : receivedDataArray) {
                    RpacketFormat.append(value + " ");
                }

                String dataReceived = RpacketFormat.toString();
                int dataLength = dataReceived.length();
                txtString.setText("Received from Bluetooth: " + dataReceived);

                if (receivedDataArray[0] == 82  && receivedDataArray[1] == 64) {

                    //find meterId from string
                    StringBuilder rMid = new StringBuilder();
                    String rMeterId = "";
                    for (int i = 2; i <= 5; i++) {
                        String hex = Integer.toHexString((int) (receivedDataArray[i] & 0xFF));
                        rMid.append(hex);
                        rMeterId = String.valueOf(rMid);
                    }
                    rMeterId = String.valueOf(Integer.parseInt(rMeterId, 16));
                    lblmeterId.setText("Received from Bluetooth: " + rMeterId);

                    //find command no from string
                    StringBuilder cId = new StringBuilder();
                    String cmdId = "";
                    cId.append(receivedDataArray[7]);
                    cmdId = String.valueOf(cId);
                    //cmdId= String.valueOf(Integer.parseInt(cmdId,16));

                    //find kilo liters from String
                    StringBuilder kId = new StringBuilder();
                    String kiloLiters = "";
                    for (int i = 9; i <= 12; i++) {
                        kId.append(receivedDataArray[i]);
                        kiloLiters = String.valueOf(kId);
                        //kiloLiters = kiloLiters.replace("0","");
                    }
                    kiloLiters = String.valueOf(Integer.parseInt(kiloLiters, 16));

                    //find kilo liters from String
                    StringBuilder lId = new StringBuilder();
                    String liters = "";
                    for (int i = 13; i <= 14; i++) {
                        lId.append(receivedDataArray[i]);
                        liters = String.valueOf(lId);
                        //liters = liters.replace("0","");
                    }
                    liters = String.valueOf(Integer.parseInt(liters, 16));

                    //find I data liters from String
                    StringBuilder iId = new StringBuilder();
                    String idata = "";
                    for (int i = 16; i <= 17; i++) {
                        iId.append(receivedDataArray[i]);
                        idata = String.valueOf(iId);
                        //idata = idata.replace("0","");
                    }
                    idata = String.valueOf(Integer.parseInt(idata, 16));

                    //find F data liters from String
                    StringBuilder fId = new StringBuilder();
                    String fdata = "";
                    for (int i = 18; i <= 19; i++) {
                        fId.append(receivedDataArray[i]);
                        fdata = String.valueOf(fId);
                        //fdata = fdata.replace("0","");
                    }
                    fdata = String.valueOf(Integer.parseInt(fdata, 16));

                    //find flag1 from string
                    StringBuilder f1Id = new StringBuilder();
                    String flag1 = "";
                    f1Id.append(receivedDataArray[21]);
                    flag1 = String.valueOf(f1Id);
                    cmdId = String.valueOf(Integer.parseInt(flag1, 16));

                    //find flag2 from string
                    StringBuilder f2Id = new StringBuilder();
                    String flag2 = "";
                    f2Id.append(receivedDataArray[22]);
                    flag2 = String.valueOf(f2Id);
                    flag2 = String.valueOf(Integer.parseInt(flag2, 16));

                    //find flag3 from string
                    StringBuilder f3Id = new StringBuilder();
                    String flag3 = "";
                    f3Id.append(receivedDataArray[23]);
                    flag3 = String.valueOf(f3Id);
                    flag3 = String.valueOf(Integer.parseInt(flag3, 16));

                    //find flag4 from string
                    StringBuilder f4Id = new StringBuilder();
                    String flag4 = "";
                    f4Id.append(receivedDataArray[24]);
                    flag4 = String.valueOf(f4Id);
                    flag4 = String.valueOf(Integer.parseInt(flag4, 16));

                    //find flag5 from string
                    StringBuilder f5Id = new StringBuilder();
                    String flag5 = "";
                    f5Id.append(receivedDataArray[25]);
                    flag5 = String.valueOf(f5Id);
                    flag5 = String.valueOf(Integer.parseInt(flag5, 16));

                    recDataString.delete(0, recDataString.length()); //clear all string data

                    Intent receivedData = new Intent(MainActivity.this, DisplayDate.class);

                    receivedData.putExtra("meterId", rMeterId);
                    receivedData.putExtra("cmdId", cmdId);
                    receivedData.putExtra("kiloLiters", kiloLiters);
                    receivedData.putExtra("liters", liters);
                    receivedData.putExtra("idata", idata);
                    receivedData.putExtra("fdata", fdata);
                    receivedData.putExtra("flag1", flag1);
                    receivedData.putExtra("flag2", flag2);
                    receivedData.putExtra("flag3", flag3);
                    receivedData.putExtra("flag4", flag4);
                    receivedData.putExtra("flag5", flag5);
                    receivedData.putExtra("dataReceived", dataReceived);
                    startActivity(receivedData);
                } else {
                    Toast.makeText(getBaseContext(), "Please Try Again. not getting proper data. ", Toast.LENGTH_LONG).show();

                    packetFormat = new StringBuilder();
                    for (long value : receivedDataArray) {
                        packetFormat.append(value + " ");
                    }
                    packetRequest = packetFormat.toString();
                    lblmeterId.setText("Received Data: " + packetRequest);
                }
            }
        }
    };

    btAdapter = BluetoothAdapter.getDefaultAdapter();       // get Bluetooth adapter
    checkBTState();
}


@Override
public void onClick(View view) {
}

private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {

    return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
    //creates secure outgoing connecetion with BT device using UUID
}

@Override
public void onResume() {
    super.onResume();

    //Get MAC address from DeviceListActivity via intent
    Intent intent = getIntent();

    //Get the MAC address from the DeviceListActivty via EXTRA
    address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);

    //create device and set the MAC address
    if (address != null) {
        BluetoothDevice device = btAdapter.getRemoteDevice(address);

        try {
            btSocket = createBluetoothSocket(device);
        } catch (IOException e) {
            Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
        }
        // Establish the Bluetooth socket connection.
        try {
            btSocket.connect();
        } catch (IOException e) {
            try {
                btSocket.close();
            } catch (IOException e2) {
                //insert code to deal with this
            }
        }
    }
    mConnectedThread = new ConnectedThread(btSocket);
    mConnectedThread.start();

    //I send a character when resuming.beginning transmission to check device is connected
    //If it is not an exception will be thrown in the write method and finish() will be called
    // mConnectedThread.write("Hi Im Connected.");
}

@Override
public void onPause() {
    super.onPause();
    try {
        //Don't leave Bluetooth sockets open when leaving activity
        btSocket.close();
    } catch (IOException e2) {
        //insert code to deal with this
    }
}

//Checks that the Android device Bluetooth is available and prompts to be turned on if off
private void checkBTState() {

    if (btAdapter == null) {
        Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show();
    } else {
        if (btAdapter.isEnabled()) {
        } else {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        }
    }
}

//create new class for connect thread
private class ConnectedThread extends Thread {
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    //creation of the connect thread
    public ConnectedThread(BluetoothSocket socket) {
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        try {
            //Create I/O streams for connection
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }


    public void run() {


        byte[] buffer = new byte[29];
        int bytes;
        // Keep listening to the InputStream while connected
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer, 0, buffer.length);
                // Send the obtained bytes to the UI Activity
                bluetoothIn.obtainMessage(handlerState, bytes, -1, buffer).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    public void write(long[] packetFormatArray) {
        //converts entered String into bytes
        try {
            for (int i = 0; i < packetFormatArray.length; i++) {
                int msgBuffer = (int) packetFormatArray[i];
                mmOutStream.write(msgBuffer);
            }
        } catch (IOException e) {
            Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
            finish();

        }
    }
}

}

这里是

 public class BytesTrans {
public static long[] bytes2HexString(byte[] b, int count) {
    long  receivedData[] =  new long[29];
    String ret = "";
    for (int i = 0; i < count; i++) {
        String hex = Integer.toHexString(b[i] & 0xFF);
        if (hex.length() ==1) {
            hex = '0' + hex;
        }
        String capsHex= hex.toUpperCase();

        receivedData[i] = Long.parseLong(capsHex,16);

        ret += hex.toUpperCase() + " ";
    }
    return receivedData;
}

}

1 个答案:

答案 0 :(得分:0)

这是代码

      public void run() {
        byte[] buffer = new byte[28];  // buffer store for the stream
        int bytes=0
 while (true) {
            try {
                // Read from the InputStream
                // Get number of bytes and message in "buffer"
                for (int i = 0; i < buffer.length; i++) {
                    bytes = mmInStream.read();
                    receivedDataArray[i] = bytes;
                }
                long abc[] = receivedDataArray;
                bluetoothIn.obtainMessage(handlerState, bytes, -1, receivedDataArray).sendToTarget();
            }
            catch (IOException e) {
                e.printStackTrace();
                break;
            }
        }