0

Im writing a BLE app for android as the title says, but when I select a device from my list of discovered devices (my embedded device), the app connects but no data shows up... unless I select it a second time. I know its connecting the first time because the device has an LED indicator but no data comes through until I select it again. Does anyone have any idea why that would be?

public class BluetoothDiscovery extends AppCompatActivity {

private String DEVICE = "Bluetooth Device";
private String COMMS = "Bluetooth Communication";
private int REQUEST_ENABLE_BT = 5;

private BluetoothAdapter mBluetoothAdapter;
private BluetoothLeScannerCompat scanner;
private ScanSettings settings;
private UUID baseUUID = UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e"); // service UUID
private UUID txUUID = UUID.fromString("6e400002-b5a3-f393-e0a9-e50e24dcca9e"); // TX UUID characteristic
private UUID rxUUID = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e"); // RX UUID characteristic
private ScanFilter scanFilter;
private BluetoothDevice device, mdevice;
private BluetoothGatt mGatt;
private boolean mScanning = false;
private ArrayList<deviceShowFormat> foundDevices = new ArrayList<>();
formattingAdapter BTadapter;

Button scanButton;
TextView fancyWords;
ListView deviceList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bluetooth_discovery);

    BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = manager.getAdapter();

    //mBluetoothAdapter.getBluetoothLeScanner();
    //mBluetoothAdapter.getDefaultAdapter();//.getBluetoothLeScanner();

    scanButton = findViewById(R.id.scanButt);
    scanButton.setText(getString(R.string.notScanning));

    fancyWords = findViewById(R.id.discoverText);
    fancyWords.setText(getString(R.string.nonScanTitle));

    deviceList = findViewById(R.id.deviceList);
    BTadapter = new formattingAdapter(BluetoothDiscovery.this, foundDevices);
    deviceList.setAdapter(BTadapter);


    scanner = BluetoothLeScannerCompat.getScanner();

    settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).setReportDelay(1000).build();

    scanFilter = new ScanFilter.Builder().setServiceUuid(new ParcelUuid(baseUUID)).build();

    //scanner.startScan(Arrays.asList(scanFilter), settings, mScanCallback);

    deviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @SuppressLint("LongLogTag")
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            scanner.stopScan(mScanCallback);
            scanButton.setText(getString(R.string.notScanning));

            deviceShowFormat mBTDevice = foundDevices.get(i);

            BluetoothDevice Device = mBTDevice.get_device();
            String deviceName = mBTDevice.get_device_name();
            String deviceAddress = mBTDevice.get_device_address();

            Log.i(DEVICE, "Selected device: " + Device.toString());
            Log.i(DEVICE, "Selected device name: " + deviceName);
            Log.i(DEVICE, "Selected device address: " + deviceAddress);


            mBluetoothAdapter.getRemoteDevice(deviceAddress);
            mGatt = Device.connectGatt(BluetoothDiscovery.this, false, mGattCallback);

        }
    });
}

private final no.nordicsemi.android.support.v18.scanner.ScanCallback mScanCallback = new no.nordicsemi.android.support.v18.scanner.ScanCallback() {
    @Override
    public void onScanResult(int callbackType, ScanResult result) {
        super.onScanResult(callbackType, result);

        Log.i("onScanResult", "device detected");

        device = result.getDevice();
        String deviceName = device.getName();
        String deviceAddress = device.getAddress();

        Log.i(DEVICE, "Scanned device: " + device.toString());
        Log.i(DEVICE, "Scanned device name: " + deviceName);
        Log.i(DEVICE, "Scanned device address: " + deviceAddress);


        foundDevices.add(new deviceShowFormat(device, deviceName, deviceAddress));
        BTadapter.notifyDataSetChanged();

    }
};

private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        super.onConnectionStateChange(gatt, status, newState);

        Log.i("onConnectionStateChange", "State Changed from: " + status + " to " + newState);

        if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED){ // 2
            //Toast.makeText(BluetoothDiscovery.this, "Attempting service discovery", Toast.LENGTH_SHORT).show();
            //Log.i("onConnectionStateChange", "Attempting service discovery: " + mGatt.discoverServices());
            gatt.discoverServices();

        } else if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_DISCONNECTED){ // 0
            Toast.makeText(BluetoothDiscovery.this, "Connection has been terminated?", Toast.LENGTH_SHORT).show();

        } else if (status != BluetoothGatt.GATT_SUCCESS){
            Log.i("GATT", "Unsuccessful");
            gatt.disconnect();
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status){
        super.onServicesDiscovered(gatt, status);

        Log.i("onServicesDiscovered", "Hey, we found a service");

        List<BluetoothGattService> services = gatt.getServices();
        Log.i("SERVICE", "Services: " + services.toString());


        BluetoothGattCharacteristic characteristic = services.get(4).getCharacteristics().get(0);
        //BluetoothGattCharacteristic characteristic = gatt.getService(baseUUID).getCharacteristic(rxUUID);


        gatt.setCharacteristicNotification(characteristic, true);



        List<BluetoothGattDescriptor> describeMe = characteristic.getDescriptors();
        Log.i("DESCRIPTORS", "Descriptors: " + describeMe.toString());
        Log.i("DESCRIPTORS", "Descriptors: " + describeMe.get(1).getUuid().toString());


        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(describeMe.get(0).getUuid());//UUID.fromString("00002902-0000-1000-8000-00805F9B34FB"));//describeMe.get(1).getUuid()
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        gatt.writeDescriptor(descriptor);

        Log.i("ByeSERVICESDISCOVERED", "that");
    }


    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        Log.i("onCharacteristicChanged", "Entered");

        byte[] dataInput = characteristic.getValue();
        Log.i("MESSAGE", dataInput.toString());

        try {
            String data = new String(dataInput, "UTF-8");

            // create list to contain data

            Log.i("MESSAGE2", data);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


        Log.i("onCharacteristicChanged", "Bye");
    }

};

public void toggleScan(View view){
    mScanning = !mScanning;

    if(mScanning){
        scanner.startScan(mScanCallback); //Arrays.asList(scanFilter) null, settings,
        scanButton.setText(getString(R.string.scanInProgress));
        fancyWords.setText(getString(R.string.ScanTitle));

    } else {
        scanner.stopScan(mScanCallback);
        scanButton.setText(getString(R.string.notScanning));
        //foundDevices.clear();
    }
}



}

edit: Logs on first clickenter image description here

Logs on second click enter image description here

Red marks my debugging logs

Marcos Vasconcelos
  • 18,136
  • 30
  • 106
  • 167
  • What does your log end up looking like? – ArtHare Aug 07 '18 at 20:42
  • I editted the post with logs @ArtHare – thunderbootyclap Aug 10 '18 at 15:06
  • You have two calls to "discoverServices()" (one on the Log.i line and one on the next line) and hence your onServicesDiscovered() callback will be called twice. You should first remove one of the calls and edit your question and debug logs accordingly. – Emil Aug 10 '18 at 18:25
  • I commented out the log.i containing discoverServices, and updated the log cat. – thunderbootyclap Aug 14 '18 at 14:57
  • I know it's been a while -- have you found out anything? I have a VERY similar issue, with a little twist: Only on the first connect after the module (Microchip RN4020) powers up do I get this. Basically, I'm "solving" this by timing out on data being received and doing a disconnect/connect. I have this behavior always on Android, always when using a USB BLE module (SiLabs BLED112), and often on iOS. – bobwki Nov 27 '18 at 18:07
  • @bobwki I did "solve" this problem but i dont particularly know what did it. I just started working after tweaking the characteristic and descriptor stuff but i dont have a definitive answer. – thunderbootyclap Dec 07 '18 at 18:09

0 Answers0