0

Problem Description:

The android app communicates with the peer microcontroller through Bluetooth, The data of the single chip microcomputer comes from the serial port, and then sends it to the android app through Bluetooth SPP,

ps: this single chip microcomputer contain a bluetooth module.

The current problem is: The peer data received by the Bluetooth app is all garbled characters:

The serial port program settings are as follows: Baud rate: 115200 Data bits: 8 Stop bits: 1 Parity: None Flow control: None

HEX send data like below: FE 01 02 enter image description here

The expectation is: The android app can receive the following string: 0xFE 0x12 0x02

enter image description here But currently the app receives garbled characters, After reading the byte stream of inputStream.read is -1,0,0..., Personally, I feel very weird. I don’t know why the byte stream sent by the board is like this.

try:

  1. Try to process the received byte stream with different encodings, such as UTF8/ASCII/UNICODE, but it is useless;

  2. Try to send in non-HEX, that is, string: FE 01 02, and found the same problem;

  3. Do you feel that the android Bluetooth SPP/RFCOM needs to set the same serial port settings as the peer? But the current problem is that the set interface cannot be found: BluetoothSocket.setBaudRate?/setUartConfig? -- there is no such interface actually

  4. At present, I feel that there may be two problems: i. The data from the peer MCU is not sent through Bluetooth at all, that is, the sensor data of the underlying LoRa-01 MCU is transmitted to its classic Bluetooth module SPP through Uart. There may be a problem, but there is no code for this piece.

I'm not sure if this is the problem. ii. The data from the peer MCU is sent via bluetooth, but its data encoding is completely incompatible with android? What android receives via bluetooth is a byte stream.

Please take a look at the above questions, and wait online anxiously! Thanks you!

in MyActivity.mHandler:

private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
    switch (msg.what) {
        case Constants.MESSAGE_READ:
            byte[] readBuf = (byte[]) msg.obj;
            // construct a string from the valid bytes in the buffer
            String readMessage = new String(readBuf, 0, msg.arg1);
            mConversationArrayAdapter.add(mConnectedDeviceName + ":  " + readMessage);

            break;
        case Constants.MESSAGE_DEVICE_NAME:
            // save the connected device's name
            mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
            Toast.makeText(getApplicationContext(), "Connected to "
                    + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
            break;

in BtClientService.ConnectThread

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

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

    mmInStream = tmpIn;
    mmOutStream = tmpOut;
    mState = STATE_CONNECTED;
}

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

    // Keep listening to the InputStream while connected
    while (mState == STATE_CONNECTED) {
        try {
            // Read from the InputStream
            bytes = mmInStream.read(buffer);

            // Send the obtained bytes to the UI Activity
            mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer)
                    .sendToTarget();
        } catch (IOException e) {
            Log.e(TAG, "disconnected ~ " + e.toString());
            connectionLost();
            break;
        }
    }
}

And I just use different encoding from bytes to string like: utf8/ASCII/UNICODE, but it doesn't work.

//default encoding
String readMessage = new String(readBuf, 0, msg.arg1);
// convert to string Encode with UTF-8 format
String readMessage = new String(byteArray, StandardCharsets.UTF_8);

// convert to string Encode with ASCII format
String readMessage = new String(byteArray, StandardCharsets.US_ASCII);

// convert to string Encode with Unicode format
String readMessage = new String(byteArray, StandardCharsets.UTF_16);
PETRER
  • 1
  • 1
  • Are you using a custom app or an existing Bluetooth terminal? – Michael Kotzjan Jul 12 '23 at 09:28
  • custom android app with bluetooth spp protocol, and I'm sure data transfer between two android phone is ok, only this mcu bluetooth controller's data can't be showed in right way on my app. – PETRER Jul 13 '23 at 02:50
  • Could you try an existing bluetooth terminal, just to make sure whether the app or the MCU is at fault – Michael Kotzjan Jul 13 '23 at 08:52
  • I use bt terminal in bellow google play link, data from bluetooth mcu can be showed in right way like "0xFE 0x32 0xAE", and I don't have source code abouth this 3rd part app. https://play.google.com/store/apps/details?id=com.shenyaocn.android.BlueSPP – PETRER Jul 14 '23 at 04:45
  • So we can definetly say that it is your app that is at fault. Maybe it is just a form of convertion problem? Hard to say without seeing your code. Could you [edit] your question to show at least the part of your app where you received and printed `FE 01 02`? – Michael Kotzjan Jul 14 '23 at 05:34
  • 1
    I have paste subcode of my program, and the detailed code logic description, you can see from blew link :https://stackoverflow.com/questions/76602539/how-to-implement-if-no-bluetooth-data-is-received-within-10s-then-vibrate-the-p?noredirect=1#comment135062349_76602539 – PETRER Jul 14 '23 at 05:53
  • Just to clarify further: What do you expect to receive when sending `0xFE 0x01 0x02`? Just the same? – Michael Kotzjan Jul 14 '23 at 08:08
  • Yes, in fact I need to receive the right hex string like: 0xFE 0x01 0x02, and then I will combine this data unit into hex number : 12, 0XFE just is a data unit flag. – PETRER Jul 14 '23 at 09:31

1 Answers1

0

You are trying to convert a byte array directly to a string. That will not give you the expected result. When you look at the received bytes directly you will most likely see that the send values have been received correctly, maybe just in a different format which entirely depends on how you represent it.

If you want to receive a HEX string from a byte array you would need to use something like this answer suggested:

final protected static char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
public static String byteArrayToHexString(byte[] bytes) {
    char[] hexChars = new char[bytes.length*2];
    int v;

    for(int j=0; j < bytes.length; j++) {
        v = bytes[j] & 0xFF;
        hexChars[j*2] = hexArray[v>>>4];
        hexChars[j*2 + 1] = hexArray[v & 0x0F];
    }

    return new String(hexChars);
}

See this example for a test implementation

Michael Kotzjan
  • 2,093
  • 2
  • 14
  • 23
  • Thanks for your help, only convert byte code to hex is not a problem for me, I used your code for test again, but still not work, I think this may be caused by the communication between uart and the bluetooth mcu controller, but I don't have code of them, so ... – PETRER Jul 16 '23 at 09:50
  • Sorry this did not help you, I might have misunderstood your problem. Hopefully someone else has a solution for you! – Michael Kotzjan Jul 17 '23 at 07:48