如何将App Android与2 BLE设备连接

时间:2018-10-09 14:14:35

标签: android bluetooth-lowenergy

我想构建一个从两个BLE设备下载数据的Android应用程序。

所以我正在用Button建立一个简单的活动。当我单击它时,用户可以通过AlertDialog设置秒数。 之后,该应用程序应在第一个BLE设备上连接并发送命令,然后在第二个BLE设备上连接并发送命令。

现在的问题是,当我尝试单击按钮时,我可以在第一台设备上连接并发送命令,但是我无法在第二台设备上连接并发送命令。我认为问题是因为该应用无法关闭与第一台设备的连接。

这是代码:

“ doStartScanner”方法,当用户单击命令时使用

 public void doStartScannerI(View view) {
            checkBluetoothActive();
            //RECUPERO LE IMPOSTAZIONI SETTATE DALL'UTENTE
            if (settingApp == null || (settingApp.getAddressBleSX()==null && settingApp.getAddressBleDX()==null)) {
                AlertDialog alertDialog = new AlertDialog.Builder(this).create();
                alertDialog.setTitle(getString(R.string.device_not_associated_title));
                alertDialog.setMessage(getString(R.string.device_not_associated_description));
                alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.SI),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                Intent i = new Intent(getApplicationContext(), SettingActivity.class);
                                startActivity(i);
                            }
                        });
                alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.NO),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                alertDialog.show();
            }else if(mGatt == null || currDevice == null) {
                //DEVO EFFETTUARE NUOVAMENTE LA SCANSIONE CON IL DISPOSITIVO
                initBle();
                scanLeDevice(true);
            }else{
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.setTitle(getString(R.string.tempo_acquisizione_title));
                final EditText input = new EditText(this);
                input.setInputType(InputType.TYPE_CLASS_NUMBER);
                input.setRawInputType(Configuration.KEYBOARD_12KEY);
                alert.setView(input);
                alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String value = input.getText().toString();
                        if(value == null || value.isEmpty()){
                            /*Toast.makeText(getApplicationContext(), getString(R.string.minuti_acquisizione_non_validi),
                                    Toast.LENGTH_LONG).show();*/
                            return;
                        }
                        try{
                            CALZA_TO_CONNECT = 0;
                            //readTemperatura();
                            TIME = Integer.parseInt(value);
                            //qui devo avviare il processo di scansione ble
                            boolean writeCharSx = writeCharacteristic(TIME);
                            Thread.sleep(1500);
                            //ADESSO MODIFICO IL CODICE PER FAR SI CHE L'APP SI COLLEGHI SUL PIEDE DX
                            //ED INOLTRI, LO STESSO COMANDO.
                            //TODO
                            //SCOLLEGO LO SMARTPHONE DALLA CALZA PIEDE SINISTRO
                            doStopScan(null);
                            Thread.sleep(1500);
                            //COLLEGO LO SMARTPHONE ALLA CALZA PIEDE DESTRO
                            //per questo motivo imposto calzaToConnect = 1
                            CALZA_TO_CONNECT = 1;
                            //avvio la nuova acquisizione
                            initBle();
                            scanLeDevice(true);
                            //boolean writeCharDx = writeCharacteristic(time);

                        }catch(Exception e){
                            Toast.makeText(getApplicationContext(), getString(R.string.minuti_acquisizione_non_validi),
                                    Toast.LENGTH_LONG).show();
                        }

                    }
                });
                alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                });
                alert.show();
            }
        }

public void initBle(){
        mHandler = new Handler();
        final BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        //VERIFICO SE IL BLUETOOTH DEL DISPOSITIVO E' ABILITATO
        //OPPURE NO. SE NON è ABILITATO DEVO CHIEDERE ALL'UTENTE DI ATTIVARLO
        // Ensures Bluetooth is available on the device and it is enabled. If not,
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
        mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
    }

private void scanLeDevice(final boolean enable) {
        if (enable) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (Build.VERSION.SDK_INT < 21) {
                        mBluetoothAdapter.stopLeScan(mLeScanCallback);
                    } else {
                        mLEScanner.stopScan(mScanCallback);

                    }
                }
            }, SCAN_PERIOD);
            if (Build.VERSION.SDK_INT < 21) {
                mBluetoothAdapter.startLeScan(mLeScanCallback);
            } else {
                mLEScanner.startScan(filters, settings, mScanCallback);
            }
        } else {
            if (Build.VERSION.SDK_INT < 21) {
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
            } else {
                mLEScanner.stopScan(mScanCallback);
                mLEScanner.flushPendingScanResults(mScanCallback);
                mBluetoothAdapter.getBluetoothLeScanner().stopScan(mScanCallback);
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
            }
        }
    }





    private ScanCallback mScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            Log.i("callbackType", String.valueOf(callbackType));
            Log.i("result", result.toString());
            BluetoothDevice btDevice = result.getDevice();
            if(settingApp!= null){
                if(CALZA_TO_CONNECT == 0 && btDevice.getAddress().equals(settingApp.getAddressBleSX())){
                    //CALZA SINISTRA
                    connectToDevice(btDevice,READ_OR_WRITE);
                }else if(CALZA_TO_CONNECT == 1 && btDevice.getAddress().equals(settingApp.getAddressBleDX())){
                    //CALZA DESTRA
                    connectToDevice(btDevice,READ_OR_WRITE);
                    //SE SONO IN SCRITTURA, SCRIVO DIRETTAMENTE SULLA CALZA DESTRA
                    if(READ_OR_WRITE == 0) {
                        writeCharacteristic(TIME);
                        //INTERROMPO QUALSIASI CONNESSIONE
                        doStopScan(null);
                        //QUI DEVO AVVIARE UNA PROCEDURA PER AVVIARE LA SCANSIONE DAL DISPOSITIVO
                    }
                }
            }
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            for (ScanResult sr : results) {
                Log.i("ScanResult - Results", sr.toString());
            }
        }

        @Override
        public void onScanFailed(int errorCode) {
            Log.e("Scan Failed", "Error Code: " + errorCode);
        }
    };

    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, int rssi,
                                     byte[] scanRecord) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.i("onLeScan", device.toString());
                            connectToDevice(device,READ_OR_WRITE);
                        }
                    });
                }
            };

    /**
     *
     * @param device
     * @param readOrWrite 0 = WRITE ON CHARACTERISTIC 1= READ FROM CHARACTERISTIC
     */
    public void connectToDevice(BluetoothDevice device, int readOrWrite) {
        if (mGatt == null) {
            currDevice = device;
            fbBle.setBackgroundTintList(getResources().getColorStateList(R.color.primary));
            //ibDownload.setImageResource(R.drawable.download_ok);
            //mGatt = device.connectGatt(this, false, gattCallback);
            currDevice = device;
            mGatt = currDevice.connectGatt(getBaseContext(), false,
                    readOrWrite == 0 ? gattCallbackWrite : gattCallbackReadValue);
        }
        scanLeDevice(false);// will stop after first device detection
    }

    /**
     * questa call back serve solo per collegarsi al dispositivo
     * ed avviare l acquisizione dei dati
     */
    private final BluetoothGattCallback gattCallbackWrite = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            Log.i("onConnectionStateChange", "Status: " + status);
            switch (newState) {
                case BluetoothProfile.STATE_CONNECTED:
                    Log.i("gattCallback", "STATE_CONNECTED");
                    gatt.discoverServices();
                    break;
                case BluetoothProfile.STATE_DISCONNECTED:
                    Log.e("gattCallback", "STATE_DISCONNECTED");
                    break;
                default:
                    Log.e("gattCallback", "STATE_OTHER");
            }

        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt,
                                      BluetoothGattDescriptor descriptor, int status) {
            //if (DESCRIPTOR_CONFIG_UUID.equals(descriptor.getUuid())) {
            BluetoothGattCharacteristic characteristic = gatt
                    .getService(Constants.SERVICE_UUID)
                    .getCharacteristic(Constants.CHARACTERISTIC_FORZA_UUID);
            gatt.readCharacteristic(characteristic);
            //}
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                // Log.i("INFO", "Characteristic written successfully");
            } else {
                // Log.e("ERROR","Characteristic write unsuccessful, status: " + status);

            }
        }
    };

0 个答案:

没有答案