Программно уменьшите диапазон Bluetooth устройства android в студии android - PullRequest
0 голосов
/ 04 марта 2020

Я работаю в мобильном приложении android, и мой телефон успешно подключается к микроконтроллеру ESP32. Диапазон Bluetooth в ESP32 высок, и я хочу отключить Bluetooth моего телефона, если расстояние / расстояние между телефоном и оборудованием превышает 10 метров. Я не могу изменить код ESP32 для уменьшения диапазона мощности, поэтому есть ли способ уменьшить диапазон bluetooth или автоматически отключить телефон, если он превышает указанный диапазон c? Пожалуйста, найдите мой android код студии ниже, который у меня есть:

public class ConnectedDevice extends AppCompatActivity {    
    
    private BluetoothAdapter myBluetooth = null;
    private BluetoothSocket btSocket = null;
    private boolean isBtConnected = false;
    private BluetoothDisconnect bluetoothDisconnect;
    static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");        

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_connected_device);                
        new ConnectBT().execute();

        btnDis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DisconnectOnBtnClick();
            }
        });

        bluetoothDisconnect = new BluetoothDisconnect();
        IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        registerReceiver(bluetoothDisconnect, intentFilter);

        mButtonStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCountDownTimer.cancel();
                mTimerRunning = false;
                mButtonStop.setVisibility(View.INVISIBLE);
                Intent intent = new Intent(ConnectedDevice.this, PairedDevices.class);
                startActivity(intent);
            }
        });
    }

    protected  void onDestroy() {
        super.onDestroy();
        unregisterReceiver(bluetoothDisconnect);
}

    
    private void DisconnectOnBtnClick() {

        if (mReadThread != null) {
            mReadThread.stop();
            do {

            } while (mReadThread.isRunning());
            mReadThread = null;
        }
        try {
            btSocket.close();
        }
        catch(IOException e)
        {
            Toast.makeText(getApplicationContext(), "Could not disconnect", Toast.LENGTH_SHORT).show();
        }
        finish();
    }

    private void sendSMS() {
        try {
            message = brand + " " + model + " " + licensePlate;
            SmsManager sms = SmsManager.getDefault();
            sms.sendTextMessage("5089715596",null,message,null,null);
            Toast.makeText(this,"Message Sent",Toast.LENGTH_SHORT).show();
        }
        catch (Exception e) {
            Toast.makeText(this, "Could not send message",Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    
    private class BluetoothDisconnect extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            sendSMS();
            startTimer();

            try {
                btSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void startTimer() {
        mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mTimeLeftInMillis = millisUntilFinished;
                updateCountDownText();
                mButtonStop.setVisibility(View.VISIBLE);
            }

            @Override
            public void onFinish() {
                mTimerRunning = false;
                mButtonStop.setVisibility(View.INVISIBLE);
                Toast.makeText(ConnectedDevice.this, "Calling", Toast.LENGTH_SHORT).show();
                callNumber();
            }
        }.start();

        mTimerRunning = true;
        mButtonStop.setText("Stop");
    }

    @SuppressLint("MissingPermission")
    private void callNumber()
    {
        Intent phoneIntent = new Intent(Intent.ACTION_CALL);
        phoneIntent.setData(Uri.parse("tel:5088631994"));
        startActivity(phoneIntent);
    }

    private void updateCountDownText() {
        int minutes = (int) (mTimeLeftInMillis / 1000) / 60;
        int seconds = (int) (mTimeLeftInMillis / 1000) % 60;
        String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
        mTextViewCountDown.setText(timeLeftFormatted);
    }

    
    private class ConnectBT extends AsyncTask<Void, Void, Void> {
        private boolean ConnectSuccess = true;

        @Override
        protected  void onPreExecute () {
            progress = ProgressDialog.show(ConnectedDevice.this, "Connecting...", "Please Wait!!!");
        }

        @Override
        protected Void doInBackground (Void... devices) {
            try {
                if ( btSocket==null || !isBtConnected ) {
                    myBluetooth = BluetoothAdapter.getDefaultAdapter();
                    remoteDevice = myBluetooth.getRemoteDevice(address);
                    btSocket = remoteDevice.createInsecureRfcommSocketToServiceRecord(myUUID);
                    BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
                    btSocket.connect();
                }
            }
            catch (IOException e) {
                ConnectSuccess = false;
            }
            return null;
        }

        @Override
        protected void onPostExecute (Void result) {
            super.onPostExecute(result);

            if (!ConnectSuccess) {
                Toast.makeText(getApplicationContext(), "Connection Failed. Make sure your device is in range", Toast.LENGTH_SHORT).show();
                finish();
            }
            else {
                isBtConnected = true;
                mReadThread = new ReadInput();
                getCurrentData();
            }
            progress.dismiss();
        }
    }    
}

Ответы [ 2 ]

0 голосов
/ 04 марта 2020
         short rssi = intent.getExtras().getShort(BluetoothDevice.EXTRA_RSSI);
         int iRssi = abs(rssi);
         // 将蓝牙信号强度换算为距离
         double power = (iRssi - 59) / 25.0;
         String mm = new Formatter().format("%.2f", pow(10, power)).toString();
 private final BroadcastReceiver receiver = 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 aa = tvDevices.getText().toString() + "";
                if (aa.contains(device.getAddress())) {
                    return;
                } else {
                    if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                        short rssi = intent.getExtras().getShort(
                                BluetoothDevice.EXTRA_RSSI);
                        int iRssi = abs(rssi);
                        double power = (iRssi - 59) / 25.0;
                        String mm = new Formatter().format("%.2f", pow(10, power)).toString();
                       // tvDevices.append(device.getName() + ":" + device.getAddress() + " :" + mm + "m" + "\n");
                    }else {

                    }
                }
                // search finished
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
                    .equals(action)) {
                //TODO
            }
        }
    };
0 голосов
/ 04 марта 2020

Рассчитано с использованием значений интенсивности и мощности rssi

public double getDistance(int measuredPower, double rssi) {
            if (rssi >= 0) {
                return -1.0;
            }
            if (measuredPower == 0) {
                return -1.0;
            }
            double ratio = rssi * 1.0 / measuredPower;
            if (ratio < 1.0) {
                return Math.pow(ratio, 10);
            } else {
                double distance= (0.42093) * Math.pow(ratio, 6.9476) + 0.54992;
                return distance;
            }
       }

как получить значения мощности?

в вызове ScanResult getTxPower (если ваш api> 26)

Примечание: надежность rssi не 100%, на нее могут влиять факторы окружающей среды

...