Android Mobile Phone Developed by Android BLE Communicates with BLE Terminal

Keywords: Android Mobile

               

This article comes from http://blog.csdn.net/hellogv/ The citation must indicate the source!

Recently, wearing equipment has developed rapidly, bringing the related technology to a boom, one of which is BLE.( Bluetooth Low Energy ) BLE is the core Profile of Bluetooth 4.0. Its main function is fast search, fast connection, ultra-low power to maintain connection and data transmission. Its weakness is low data transmission rate. Because of its low power consumption, BLE is widely used in wearable devices. Android 4.3 only started supporting BLE API, so please run the code in Bluetooth 4.0 and Android 4.3 and above. In addition, the BLE terminal used in this paper is a Bluetooth 4.0 serial port Bluetooth module.

PS: My i9100 can even communicate with BLE Bluetooth module after swiping 4.4 system.


BLE is divided into three parts: Service, Characteristic and Descriptor, all of which are uniquely marked by UUID. A Bluetooth 4.0 terminal can contain multiple services, a service can contain multiple Characteristic, a Characteristic can contain one Value and multiple Descriptors, and a Descriptor can contain one Value. Generally speaking, Characteristic is the key to exchange data between mobile phone and BLE terminal. Characteristic has many fields related to permission, such as PERMISSION and PROPERTY, and the most commonly used one is PROPERTY. The BLE Bluetooth module used in this paper has no standard Characteristic PERMISSION. Characteristic's PROPERTY can set read and write attributes through bitwise operator combinations, such as READ|WRITE, READ|WRITE_NO_RESPONSE|NOTIFY, so it is decomposed into the combinations used after reading PROPERTY (the decomposition method is included in this code).


The code of this article is changed from Bluetooth LeGatt of Android 4.3 Sample. Redundant code is removed, BLE device information is obtained through Log, and there are some necessary reading and writing Bluetooth methods, which should be simplified to everyone. The code in this article is available http://download.csdn.net/detail/hellogv/7228819 Download. Next, we post the results of this article. First, after connecting BLE devices, we enumerate all the services, Characteristic and Descriptor of the devices, and the mobile phone will write a "send data - >" string to Characteristic uuid=0000ffe1-0000-1000-8000-00805f9b34fb. The BLE terminal receives data from the serial port to PC serial port assistant (see the screenshot of PC serial port assistant):

04-21 18:28:25.465: E/DeviceScanActivity(12254): -->service type:PRIMARY
04-21 18:28:25.465: E/DeviceScanActivity(12254): -->includedServices size:0
04-21 18:28:25.465: E/DeviceScanActivity(12254): -->service uuid:00001800-0000-1000-8000-00805f9b34fb
04-21 18:28:25.465: E/DeviceScanActivity(12254): ---->char uuid:00002a00-0000-1000-8000-00805f9b34fb
04-21 18:28:25.465: E/DeviceScanActivity(12254): ---->char permission:UNKNOW
04-21 18:28:25.465: E/DeviceScanActivity(12254): ---->char property:READ
04-21 18:28:25.465: E/DeviceScanActivity(12254): ---->char uuid:00002a01-0000-1000-8000-00805f9b34fb
04-21 18:28:25.470: E/DeviceScanActivity(12254): ---->char permission:UNKNOW
04-21 18:28:25.470: E/DeviceScanActivity(12254): ---->char property:READ
04-21 18:28:25.470: E/DeviceScanActivity(12254): ---->char uuid:00002a02-0000-1000-8000-00805f9b34fb
04-21 18:28:25.470: E/DeviceScanActivity(12254): ---->char permission:UNKNOW
04-21 18:28:25.470: E/DeviceScanActivity(12254): ---->char property:READ|WRITE|
04-21 18:28:25.470: E/DeviceScanActivity(12254): ---->char uuid:00002a03-0000-1000-8000-00805f9b34fb
04-21 18:28:25.470: E/DeviceScanActivity(12254): ---->char permission:UNKNOW
04-21 18:28:25.475: E/DeviceScanActivity(12254): ---->char property:READ|WRITE|
04-21 18:28:25.475: E/DeviceScanActivity(12254): ---->char uuid:00002a04-0000-1000-8000-00805f9b34fb
04-21 18:28:25.475: E/DeviceScanActivity(12254): ---->char permission:UNKNOW
04-21 18:28:25.475: E/DeviceScanActivity(12254): ---->char property:READ
04-21 18:28:25.475: E/DeviceScanActivity(12254): -->service type:PRIMARY
04-21 18:28:25.475: E/DeviceScanActivity(12254): -->includedServices size:0
04-21 18:28:25.475: E/DeviceScanActivity(12254): -->service uuid:00001801-0000-1000-8000-00805f9b34fb
04-21 18:28:25.480: E/DeviceScanActivity(12254): ---->char uuid:00002a05-0000-1000-8000-00805f9b34fb
04-21 18:28:25.480: E/DeviceScanActivity(12254): ---->char permission:UNKNOW
04-21 18:28:25.480: E/DeviceScanActivity(12254): ---->char property:INDICATE
04-21 18:28:25.480: E/DeviceScanActivity(12254): -------->desc uuid:00002902-0000-1000-8000-00805f9b34fb
04-21 18:28:25.480: E/DeviceScanActivity(12254): -------->desc permission:UNKNOW
04-21 18:28:25.480: E/DeviceScanActivity(12254): -->service type:PRIMARY
04-21 18:28:25.480: E/DeviceScanActivity(12254): -->includedServices size:0
04-21 18:28:25.480: E/DeviceScanActivity(12254): -->service uuid:0000ffe0-0000-1000-8000-00805f9b34fb
04-21 18:28:25.480: E/DeviceScanActivity(12254): ---->char uuid:0000ffe1-0000-1000-8000-00805f9b34fb
04-21 18:28:25.480: E/DeviceScanActivity(12254): ---->char permission:UNKNOW
04-21 18:28:25.480: E/DeviceScanActivity(12254): ---->char property:READ|WRITE_NO_RESPONSE|NOTIFY|
04-21 18:28:25.490: E/DeviceScanActivity(12254): -------->desc uuid:00002902-0000-1000-8000-00805f9b34fb
04-21 18:28:25.490: E/DeviceScanActivity(12254): -------->desc permission:UNKNOW
04-21 18:28:25.490: E/DeviceScanActivity(12254): -------->desc uuid:00002901-0000-1000-8000-00805f9b34fb
04-21 18:28:25.490: E/DeviceScanActivity(12254): -------->desc permission:UNKNOW
04-21 18:28:26.025: E/DeviceScanActivity(12254): onCharRead BLE DEVICE read 0000ffe1-0000-1000-8000-00805f9b34fb -> 00

Here the scarlet letter is typed as Log by the onCharacteristicRead() callback of Bluetooth GattCallback




The following logs are sent by serial port tools on PC through BLE module, and logs are typed out by onCharacteristicChanged () of Bluetooth GattCallback.
04-21 18:30:18.260: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone
04-21 18:30:18.745: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone
04-21 18:30:19.085: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone
04-21 18:30:19.350: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone
04-21 18:30:19.605: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone
04-21 18:30:19.835: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone
04-21 18:30:20.055: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone
04-21 18:30:20.320: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone
04-21 18:30:20.510: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone
04-21 18:30:20.735: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone
04-21 18:30:21.000: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone

Next, post the core code of this article:

public class DeviceScanActivity extends ListActivity private final static String TAG = DeviceScanActivity.class.getSimpleName(); private final static String UUID_KEY_DATA = "0000ffe1-0000-1000-8000-00805f9b34fb";    private LeDeviceListAdapter mLeDeviceListAdapter;    /**Search BLE Terminal*/    private BluetoothAdapter mBluetoothAdapter;    /**Read-write BLE terminal*/    private BluetoothLeClass mBLE;    private boolean mScanning;    private Handler mHandler;    // Stops scanning after 10 seconds.    private static final long SCAN_PERIOD = 10000;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        getActionBar().setTitle(R.string.title_devices);        mHandler = new Handler();        // Use this check to determine whether BLE is supported on the device.  Then you can        // selectively disable BLE-related features.        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {            Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();            finish();        }        // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to        // BluetoothAdapter through BluetoothManager.        final BluetoothManager bluetoothManager =                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);        mBluetoothAdapter = bluetoothManager.getAdapter();                // Checks if Bluetooth is supported on the device.        if (mBluetoothAdapter == null) {            Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();            finish();            return;        }        //Turn on Bluetooth        mBluetoothAdapter.enable();                mBLE = new BluetoothLeClass(this);        if (!mBLE.initialize()) {            Log.e(TAG, "Unable to initialize Bluetooth");            finish();        }        //Callback when Service of BLE terminal is found        mBLE.setOnServiceDiscoverListener(mOnServiceDiscover);        //Events Receiving BLE Terminal Data Interaction        mBLE.setOnDataAvailableListener(mOnDataAvailable);    }    @Override    protected void onResume() {        super.onResume();        // Initializes list view adapter.        mLeDeviceListAdapter = new LeDeviceListAdapter(this);        setListAdapter(mLeDeviceListAdapter);        scanLeDevice(true);    }    @Override    protected void onPause() {        super.onPause();        scanLeDevice(false);        mLeDeviceListAdapter.clear();        mBLE.disconnect();    }    @Override    protected void onStop() {        super.onStop();        mBLE.close();    }        @Override    protected void onListItemClick(ListView l, View v, int position, long id) {        final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);        if (device == null) return;        if (mScanning) {            mBluetoothAdapter.stopLeScan(mLeScanCallback);            mScanning = false;        }                mBLE.connect(device.getAddress());    }    private void scanLeDevice(final boolean enable) {        if (enable) {            // Stops scanning after a pre-defined scan period.            mHandler.postDelayed(new Runnable() {                @Override                public void run() {                    mScanning = false;                    mBluetoothAdapter.stopLeScan(mLeScanCallback);                    invalidateOptionsMenu();                }            }, SCAN_PERIOD);            mScanning = true;            mBluetoothAdapter.startLeScan(mLeScanCallback);        } else {            mScanning = false;            mBluetoothAdapter.stopLeScan(mLeScanCallback);        }        invalidateOptionsMenu();    }    /**     * Events Searched for BLE Terminal Services */    private BluetoothLeClass.OnServiceDiscoverListener mOnServiceDiscover = new OnServiceDiscoverListener(){  @Override  public void onServiceDiscover(BluetoothGatt gatt) {   displayGattServices(mBLE.getSupportedGattServices());  }         };        /**     * Events Receiving BLE Terminal Data Interaction */    private BluetoothLeClass.OnDataAvailableListener mOnDataAvailable = new OnDataAvailableListener(){     /**      * BLE Events in which terminal data is read */  @Override  public void onCharacteristicRead(BluetoothGatt gatt,    BluetoothGattCharacteristic characteristic, int status) {   if (status == BluetoothGatt.GATT_SUCCESS)     Log.e(TAG,"onCharRead "+gatt.getDevice().getName()      +" read "      +characteristic.getUuid().toString()      +" -> "      +Utils.bytesToHexString(characteristic.getValue()));  }       /**      * Write data callback received from BLE terminal */  @Override  public void onCharacteristicWrite(BluetoothGatt gatt,    BluetoothGattCharacteristic characteristic) {   Log.e(TAG,"onCharWrite "+gatt.getDevice().getName()     +" write "     +characteristic.getUuid().toString()     +" -> "     +new String(characteristic.getValue()));  }    };    // Device scan callback.    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() {                    mLeDeviceListAdapter.addDevice(device);                    mLeDeviceListAdapter.notifyDataSetChanged();                }            });        }    };    private void displayGattServices(List<BluetoothGattService> gattServices) {        if (gattServices == null) return;        for (BluetoothGattService gattService : gattServices) {         //Service field information-//         int type = gattService.getType();            Log.e(TAG,"-->service type:"+Utils.getServiceType(type));            Log.e(TAG,"-->includedServices size:"+gattService.getIncludedServices().size());            Log.e(TAG,"-->service uuid:"+gattService.getUuid());                        //Characteristics field information-//            List<BluetoothGattCharacteristic> gattCharacteristics =gattService.getCharacteristics();            for (final BluetoothGattCharacteristic  gattCharacteristic: gattCharacteristics) {                Log.e(TAG,"---->char uuid:"+gattCharacteristic.getUuid());                                int permission = gattCharacteristic.getPermissions();                Log.e(TAG,"---->char permission:"+Utils.getCharPermission(permission));                                int property = gattCharacteristic.getProperties();                Log.e(TAG,"---->char property:"+Utils.getCharPropertie(property));                byte[] data = gattCharacteristic.getValue();          if (data != null && data.length > 0) {           Log.e(TAG,"---->char value:"+new String(data));          }          //UUID_KEY_DATA is a Characteristic that can communicate with Bluetooth module in serial port.          if(gattCharacteristic.getUuid().toString().equals(UUID_KEY_DATA)){                      //The test reads the current Characteristic data and triggers mOnDataAvailable.onCharacteristicRead()           mHandler.postDelayed(new Runnable() {                        @Override                        public void run() {                         mBLE.readCharacteristic(gattCharacteristic);                        }                    }, 500);                      //Accept the notification that CharacteristicWrite is written and trigger mOnDataAvailable.onCharacteristicWrite()           mBLE.setCharacteristicNotification(gattCharacteristic, true);           //Setting up data content           gattCharacteristic.setValue("send data->");           //Write data to Bluetooth module           mBLE.writeCharacteristic(gattCharacteristic);          }                    //Field information for Descriptors-//    List<BluetoothGattDescriptor> gattDescriptors = gattCharacteristic.getDescriptors();    for (BluetoothGattDescriptor gattDescriptor : gattDescriptors) {     Log.e(TAG, "-------->desc uuid:" + gattDescriptor.getUuid());     int descPermission = gattDescriptor.getPermissions();     Log.e(TAG,"-------->desc permission:"+ Utils.getDescPermission(descPermission));          byte[] desData = gattDescriptor.getValue();     if (desData != null && desData.length > 0) {      Log.e(TAG, "-------->desc value:"+ new String(desData));     }           }            }        }//    }}

           

Posted by lar5 on Wed, 24 Apr 2019 13:09:35 -0700