How i can get bluetooth rssi in realtime 10 times in second for 10 seconds

Here is my code: MainActivity:

public class MainActivity extends AppCompatActivity {

    private final static int REQUEST_ENABLE_BT=1;
    private BluetoothAdapter bluetooth;
    private BluetoothLeScanner bluetoothLeScanner;
    private LinearLayout devicesList;
    private HashSet<BluetoothDevice> devices = new HashSet();
    private Pattern p = Pattern.compile("Beacon_\\d*");
    private boolean discovering = false;

    private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(BluetoothDevice.ACTION_FOUND.equals(intent.getAction())){
                // Получаем объект BluetoothDevice из интента
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Matcher m = p.matcher(device.getName());
                if(!devices.contains(device) && m.matches()) {
                    TextView textView = new TextView(getApplicationContext());
                    textView.setText(device.getName());
                    devicesList.addView(textView);
                    devices.add(device);
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(intent.getAction())) {
                Toast.makeText(getApplicationContext(), "Сканирование завершено", Toast.LENGTH_LONG).show();
                discovering = false;
                startDiscoveringButton.setText("Начать новое сканирование");
            }
        }
    };

    private final ScanCallback scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            System.out.println(result.getRssi());
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
        }
    };

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

        devicesList = findViewById(R.id.devicesList);
        startDiscoveringButton = findViewById(R.id.startDiscoveringButton);
        checkAndSaveSignalsButton = findViewById(R.id.checkAndSaveSignalsButton);

        bluetooth = BluetoothAdapter.getDefaultAdapter();
        if(bluetooth != null) {
            if (!bluetooth.isEnabled()) {
                // Bluetooth выключен. Предложим пользователю включить его.
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            } else {
                startScanning();
            }
        } else {
            Toast.makeText(this, "Bluetooth не поддерживается", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_ENABLE_BT) {
            startScanning();
        }
    }

    private void startScanning() {
        Toast.makeText(this, "Начинаю сканирование", Toast.LENGTH_SHORT).show();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(broadcastReceiver, filter);
        bluetooth.startDiscovery();
        discovering = true;
        startDiscoveringButton.setText("Идёт сканирование ...");
        bluetoothLeScanner = bluetooth.getBluetoothLeScanner();
        bluetoothLeScanner.startScan(scanCallback);
    }

    private void clear() {
        devices.clear();
        devicesList.removeAllViews();
    }
}

SignalsStorage:

 public void checkSignals(final HashSet<BluetoothDevice> devices) {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                measurings.add(new HashMap<String, Double>());
                for(int i = 0; i < 10; ++i) {

                }
            }
        }, 0, 1000);
    }

I have some bluetooth beacons. I can get their names, adress etc, also i can get rssi of ech but only one time. I need to receive every second 10 measurings rssi every device which i've found before for 10 seconds. But Broadcast reciever works only once for each device and LeScanner doesn't work at all. How i can do it?

Upvotes: 1

Views: 403

Answers (1)

Adarsh ML
Adarsh ML

Reputation: 128

I had the same problem a while back, and this is what I did.

 private final BroadcastReceiver brBluetoothScanningLooper=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action=intent.getAction();
            if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
                if(deviceFound==false) {
                    bluetoothAdapter.cancelDiscovery();
                    bluetoothAdapter.startDiscovery();
                }
            }
        }

    };


    private final BroadcastReceiver brNearbyBluetoothDevices=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action=intent.getAction();
            if(BluetoothDevice.ACTION_FOUND.equals(action)){
                BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                String deviceName=device.getName();
                String deviceHardwareAddress=device.getAddress();
                int rssi=intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);

                if(bondedList.contains(deviceHardwareAddress)){

                    if(!trackerList.contains(deviceHardwareAddress)){
                        if(trackerList.isEmpty()){
                            MAC=deviceHardwareAddress;
                        }
                        trackerList.add(deviceHardwareAddress);
                        rssiList.add(String.valueOf(rssi));
                        displayList.add(deviceName+"  "+rssi);
                        arrayAdapter.notifyDataSetChanged();
                        lv.setAdapter(arrayAdapter);
                    }
                    if(trackerList.contains(deviceHardwareAddress)){
                        rssiList.set(trackerList.indexOf(deviceHardwareAddress), String.valueOf(rssi));
                        displayList.set(trackerList.indexOf(deviceHardwareAddress),deviceName+"   "+(rssiList.get(trackerList.indexOf(deviceHardwareAddress))));
                        arrayAdapter.notifyDataSetChanged();
                       lv.setAdapter(arrayAdapter);
                    }
                }
}
};

I was doing things somewhat different. I wanted a scan RSSI of a device whose MAC id I already knew. One braodcast receiver keeps looping through the discovery process, the other does the actual discovery

Upvotes: 1

Related Questions