"Turn" BLE learning record

Source: Internet
Author: User

Original URL: http://m.blog.csdn.net/blog/chiooo/43985401

BLE Learning Record

Anroid BLE Development, based on Bluetoothlegatt analysis

    1. Mbluetoothadapter = Mbluetoothmanager.getadapter (); Get the adapter for the Bluetooth host on your phone mbluetoothadapter

      public Boolean Initialize () {
      For API level and above, get a reference to bluetoothadapter through
      Bluetoothmanager.
      if (Mbluetoothmanager = = null) {
      Mbluetoothmanager = (Bluetoothmanager) mcontext.getsystemservice (Context.bluetooth_service);
      if (Mbluetoothmanager = = null) {
      LOG.E (TAG, "Unable to initialize Bluetoothmanager.");
      return false;
      }
      }

      mBluetoothAdapter = mBluetoothManager.getAdapter();if (mBluetoothAdapter == null) {    Log.e(TAG, "Unable to obtain a BluetoothAdapter.");    return false;}return true;

      }

2. Get Mbluetoothgatt, Register callback

 * Connects to the GATT server hosted on the Bluetooth LE device. * * @param address the device address of the destination device. * * @return return TRUE if the connection is initiated successfully. The connection result * is reported asynchronously through the * {@code bluetoothgattcallback#onconnection    StateChange (android.bluetooth.BluetoothGatt, int, int)} * Callback.public Boolean connect (final String address) { if (Mbluetoothadapter = = NULL | | address = NULL) {LOG.W (TAG, "bluetoothadapter not initialized or unspecified        Address. ");    return false;  }//previously connected device.    Try to reconnect. if (mbluetoothdeviceaddress! = null && address.equals (mbluetoothdeviceaddress) && Mbluetoothgat        T! = null) {LOG.D (TAG, "Trying to use a existing mbluetoothgatt for connection.");        if (Mbluetoothgatt.connect ()) {return true;        } else {return false; }} FINAL Bluetoothdevice device = mbluetoothadapter.getremotedevice (address);  Get Bluetoothdevice if (device = = null) {LOG.W (TAG, "Device not found.        Unable to connect. ");    return false;    }//We want to directly connect to the device, so We is setting the AutoConnect//parameter to FALSE. Mbluetoothgatt = Device.connectgatt (Mcontext, False, mgattcallback);//bluetoothdevice got Mbluetoothgatt in it.    Bluetoothgattcallback, from the name, is the callback.    LOG.D (TAG, "Trying to create a new connection.");    mbluetoothdeviceaddress = address; return true;}

3. Read-write bluetoothgattcharacteristic, enable notification

Mbluetoothgatt.readcharacteristic (characteristic);  Read mbluetoothgatt.writecharacteristic (characteristic); Write * Enables or disables notification on a give characteristic. * * @param characteristic characteristic to act on.  * @param enabled IF True, enable notification.                                          False otherwise.public void setcharacteristicnotification (bluetoothgattcharacteristic characteristic, Boolean enabled) {if (Mbluetoothadapter = = NULL | | mbluetoothgatt = = NULL) {LOG.W (TAG, "B        Luetoothadapter not initialized ");    Return } mbluetoothgatt.setcharacteristicnotification (characteristic, enabled);}                Write down data://Set data content Gattcharacteristic.setvalue ("Send data->");    Write data to the Bluetooth module mble.writecharacteristic (gattcharacteristic); Read data: if (Gattcharacteristic.getuuid (). toString (). Equals (Uuid_key_data)) {//test read current Charac                Teristic data, will trigger Mondataavailable.oncharacteristicread ()Mhandler.postdelayed (New Runnable () {@Override public void run () {                    Mble.readcharacteristic (gattcharacteristic);                }}, 500); Accept the notification that characteristic was written, the data after receiving the Bluetooth module will trigger Mondataavailable.oncharacteristicwrite () mble.setcharacteristicnotific ation (gattcharacteristic, true);

4. Access to supported services

 * Retrieves a list of supported GATT services on the connected device. This should be * invoked only after {@code BluetoothGatt#discoverServices()} completes successfully. * * @return A {@code List} of supported services.public List<BluetoothGattService> getSupportedGattServices() {    if (mBluetoothGatt == null) return null;    return mBluetoothGatt.getServices();}

5. Relationship

Bluetoothgatt represents a connection that contains one or more bluetoothgattservice, and each bluetoothgattservice contains multiple bluetoothgattcharacteristic, a Bluetoothgattcharacteristic may contain 0 or more bluetoothgattdescriptor

6.BLE device-side log
Conditions:
Host side: Blegattle reference Program,
Device side: Nodic official ble UART program

Serial Port log:

 Main start Traceuart_init. \main.c:leds_init:137> Enter_now. \main.c:timers_init:149> Enter_now. \main.c:ble_stack_init:457> Enter_now. \main.c:gap_params_init:166> enter_nowstart.....\main.c:advertising_start:331> Enter_now. \main.c:ble_evt_dispatch:442> enter_nowp_ble_evt->header.evt_id:16//Connect Eventp_ble_evt->header.evt_ Id:16 p_ble_evt->header.evt_id:16. \main.c:ble_evt_dispatch:442> enter_nowp_ble_evt->header.evt_id:20 p_ble_evt->header.evt_id:20//BLE_GAP _evt_sec_info_requestp_ble_evt->header.evt_id:20. \main.c:ble_evt_dispatch:442> enter_nowp_ble_evt->header.evt_id:19 p_ble_evt->header.evt_id:19//BLE_GAP _evt_sec_params_requestp_ble_evt->header.evt_id:19. \main.c:ble_evt_dispatch:442> enter_nowp_ble_evt->header.evt_id:80//write eventp_ble_evt->header.evt_id : p_ble_evt->header.evt_id:80. \main.c:ble_evt_dispatch:442> enter_nowp_ble_evt->header.evt_id:80//write eventp_ble_evt->header.evt_id : 80.. \main.c:nus_data_handler:224> enter_nowsend data->//Received Datap_ble_evt->header.evt_ ID:80//write event: \main.c:ble_evt_dispatch:442> enter_nowp_ble_evt->header.evt_id:24//ble_gap_evt_auth_statusp_ble_evt-> Header.evt_id:24 p_ble_evt->header.evt_id:24. \main.c:ble_evt_dispatch:442> enter_nowp_ble_evt->header.evt_id:23//Ble_gap_evt_auth_key_requestp_ble_ Evt->header.evt_id:23 p_ble_evt->header.evt_id:23. \main.c:ble_evt_dispatch:442> enter_nowp_ble_evt->header.evt_id:18. \main.c:on_conn_params_evt:279> enter_nowp_ble_evt->header.evt_id:18//Ble_gap_evt_conn_param_updatep_ble_ Evt->header.evt_id:18

7.BLE Connection Parameters

#define MIN_CONN_INTERVALMSEC_TO_UNITS(500, UNIT_1_25_MS) /**< Minimum acceptable connection interval (0.5 seconds). */6~3200, 就是说7.5MS~ 4S, 1.25MS单位。连接时间间隔。#define MAX_CONN_INTERVALMSEC_TO_UNITS(1000, UNIT_1_25_MS)/**< Maximum acceptable connection interval (1 second). */ #define SLAVE_LATENCY0 跳过连接事件/**< Slave latency. */#define CONN_SUP_TIMEOUT MSEC_TO_UNITS(4000, UNIT_10_MS)  /**< Connection supervisory timeout (4 seconds). */  管理超时,如果超过此时间没有连接成功事件,则认为是连接丢失。

Experimental validation:

#define MIN_CONN_INTERVAL/**< Minimum acceptable connection Interval (ms), Connection interval uses 1.25 ms units. */#define MAX_CONN_INTERVAL/**< Maximum acceptable connecti On interval (ms), Connection interval uses 1.25 ms units. */#define SLAVE_LATENCY 0/**< SLAVE LATENCY. */#define CONN_SUP_TIMEOUT/**< Connection supervisory Time Out (4 seconds), supervision Timeout uses MS units. */#define First_conn_params_update_delay app_timer_ticks (20000, App_timer_prescaler)/**< time from initiating Event (Connect or start of notification) to first time Sd_ble_gap_conn_param_update is called (5 seconds). */#define Next_conn_params_update_delay app_timer_ticks (30000, App_timer_prescaler)/**< time between each call to SD _ble_gaP_conn_param_update after the first call (seconds).   */#define MAX_CONN_PARAMS_UPDATE_COUNT 3

Test record:

When the APP just connected, the connection between this parameter is determined by the mobile phone, after First_conn_params_update_delay App_timer_ticks, the phone will send new parameters, I tested, mobile phone is max_conn_ INTERVAL to decide, slave_latency no matter how much I changed, issued by 0.

Discussion on the web

    1. For iOS devices, Apple sets a set of rules that do not allow the configuration from the device to exceed these ranges. Other main devices are not yet heard of any specific scope set. Android devices are not yet clearly defined by Google. So in other words, as long as the main equipment requirements, from the device can be within the scope of the main equipment to request the main device to change the connection interval.
    2. You only set the parameters through Gap_setparamvalue (), and finally you need to request the modification by sending it to the main device. So it's not right here. Refer to the Gaprole_setparameter (gaprole_param_update_enable,.) function.
    3. You can catch the bag by packet sniffer, and you can see the connection interval clearly on the timestamp. Or you can add your own code, from the program to get, or in notify way to the main device, from the main device, in short, the method is many ha.
      Also attached apple to connection interval requirements, in fact there are other connection parameter requirements, such as slave latency, supervision timeout, if not meet these, iOS device will refuse.

      The connection parameter request may be rejected if it does not comply with all of the These rules:
      Interval Max * (Slave Latency + 1) ≤2 seconds
      Interval min≥20 ms
      Interval Min + ms≤interval Max
      Slave latency≤4
      Connsupervisiontimeout≤6 seconds
      Interval Max * (Slave Latency + 1) * 3 < Connsupervisiontimeout

8. How to disconnect from the device actively

You can directly call Gaprole_terminateconnection () to actively disconnect the connection.
After that function call, the connection is successfully disconnected and you receive the Gap_link_terminated_event event.
After this event, you restart the broadcast, you can

"Turn" BLE learning record

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.