1 Star 0 Fork 0

ChenJun / FastBle

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

效果图

Thanks to the logo designed by anharismail

FastBle

Android Bluetooth Low Energy

  • Filtering, scanning, linking, reading, writing, notification subscription and cancellation in a simple way.
  • Supports acquiring signal strength and setting the maximum transmission unit.
  • Support custom scan rules
  • Support multi device connections
  • Support reconnection
  • Support configuration timeout for conncet or operation

Preview

Preview_1 Preview_2 Preview_3 Preview_4

APK

If you want to quickly preview all the functions, you can download APK as a test tool directly.

FastBLE.apk

Maven

<dependency>
   <groupId>com.clj.fastble</groupId>
   <artifactId>FastBleLib</artifactId>
   <version>2.3.4</version>
   <type>pom</type>
</dependency>

Gradle

compile 'com.clj.fastble:FastBleLib:2.3.4'

Jar

FastBLE-2.3.4.jar

Wiki

中文文档

Android BLE开发详解和FastBle源码解析

Usage

  • Init

      BleManager.getInstance().init(getApplication());
  • Determine whether the current Android system supports BLE

      boolean isSupportBle()
  • Open or close Bluetooth

      void enableBluetooth()
      void disableBluetooth()
  • Initialization configuration

      BleManager.getInstance()
              .enableLog(true)
              .setReConnectCount(1, 5000)
              .setSplitWriteNum(20)
              .setConnectOverTime(10000)
              .setOperateTimeout(5000);
  • Configuration scan rules

    void initScanRule(BleScanRuleConfig scanRuleConfig)

      BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
              .setServiceUuids(serviceUuids)
              .setDeviceName(true, names)
              .setDeviceMac(mac)
              .setAutoConnect(isAutoConnect)
              .setScanTimeOut(10000)
              .build();
      BleManager.getInstance().initScanRule(scanRuleConfig);

    Tips:

    • Before scanning the device, scan rules can be configured to filter out the equipment matching the program.
    • What is not configured is the default parameter
  • Scan

    void scan(BleScanCallback callback)

      BleManager.getInstance().scan(new BleScanCallback() {
          @Override
          public void onScanStarted(boolean success) {
    
          }
    
          @Override
          public void onScanning(BleDevice bleDevice) {
    
          }
    
          @Override
          public void onScanFinished(List<BleDevice> scanResultList) {
    
          }
      });

    Tips:

    • The scanning and filtering process is carried out in the worker thread, so it will not affect the UI operation of the main thread. Eventually, every callback result will return to the main thread.。
  • Connect with device

    BluetoothGatt connect(BleDevice bleDevice, BleGattCallback bleGattCallback)

      BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
          @Override
          public void onStartConnect() {
    
          }
    
          @Override
          public void onConnectFail(BleDevice bleDevice, BleException exception) {
    
          }
    
          @Override
          public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
    
          }
    
          @Override
          public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
    
          }
      });

    Tips:

    • On some types of phones, connectGatt must be effective on the main thread. It is very recommended that the connection process be placed in the main thread.
    • After connection failure, reconnect: the framework contains reconnection mechanism after connection failure, which can configure reconnection times and intervals. Of course, you can also call the connect method in onConnectFail callback automatically.
    • The connection is disconnected and reconnected: you can call the connect method again in the onDisConnected callback method.
    • In order to ensure the success rate of reconnection, it is recommended to reconnect after a period of interval.
    • When some models fail, they will be unable to scan devices for a short time. They can be connected directly through device objects or devices MAC without scanning.
  • Connect with Mac

    BluetoothGatt connect(String mac, BleGattCallback bleGattCallback)

      BleManager.getInstance().connect(mac, new BleGattCallback() {
          @Override
          public void onStartConnect() {
    
          }
    
          @Override
          public void onConnectFail(BleDevice bleDevice, BleException exception) {
    
          }
    
          @Override
          public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
    
          }
    
          @Override
          public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
    
          }
      });

    Tips:

    • This method can attempt to connect directly to the BLE device around the Mac without scanning.
    • In many usage scenarios, I suggest that APP save the Mac of the user's customary device, then use this method to connect, which will greatly improve the connection efficiency.
  • Scan and connect

    After scanning the first equipment that meets the scanning rules, it will stop scanning and connect to the device.

    void scanAndConnect(BleScanAndConnectCallback callback)

      BleManager.getInstance().scanAndConnect(new BleScanAndConnectCallback() {
          @Override
          public void onScanStarted(boolean success) {
    
          }
    
          @Override
          public void onScanFinished(BleDevice scanResult) {
    
          }
    
          @Override
          public void onStartConnect() {
    
          }
    
          @Override
          public void onConnectFail(BleDevice bleDevice,BleException exception) {
    
          }
    
          @Override
          public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
    
          }
    
          @Override
          public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
    
          }
      }); 
  • Cancel scan

    void cancelScan()

      BleManager.getInstance().cancelScan();

    Tips:

    • If this method is called, if it is still in the scan state, it will end immediately, and callback the onScanFinished method.
  • Notify

    void notify(BleDevice bleDevice, String uuid_service, String uuid_notify, BleNotifyCallback callback) void notify(BleDevice bleDevice, String uuid_service, String uuid_notify, boolean useCharacteristicDescriptor, BleNotifyCallback callback)

      BleManager.getInstance().notify(
              bleDevice,
              uuid_service,
              uuid_characteristic_notify,
              new BleNotifyCallback() {
                  @Override
                  public void onNotifySuccess() {
    
                  }
    
                  @Override
                  public void onNotifyFailure(BleException exception) {
    
                  }
    
                  @Override
                  public void onCharacteristicChanged(byte[] data) {
    
                  }
              });
  • Stop Notify

    boolean stopNotify(BleDevice bleDevice, String uuid_service, String uuid_notify) boolean stopNotify(BleDevice bleDevice, String uuid_service, String uuid_notify, boolean useCharacteristicDescriptor)

      BleManager.getInstance().stopNotify(uuid_service, uuid_characteristic_notify);
  • Indicate

    void indicate(BleDevice bleDevice, String uuid_service, String uuid_indicate, BleIndicateCallback callback) void indicate(BleDevice bleDevice, String uuid_service, String uuid_indicate, boolean useCharacteristicDescriptor, BleIndicateCallback callback)

      BleManager.getInstance().indicate(
              bleDevice,
              uuid_service,
              uuid_characteristic_indicate,
              new BleIndicateCallback() {
                  @Override
                  public void onIndicateSuccess() {
    
                  }
    
                  @Override
                  public void onIndicateFailure(BleException exception) {
    
                  }
    
                  @Override
                  public void onCharacteristicChanged(byte[] data) {
    
                  }
              });
  • Stop Indicate

    boolean stopIndicate(BleDevice bleDevice, String uuid_service, String uuid_indicate) boolean stopIndicate(BleDevice bleDevice, String uuid_service, String uuid_indicate, boolean useCharacteristicDescriptor)

      BleManager.getInstance().stopIndicate(uuid_service, uuid_characteristic_indicate);
  • Write

    void write(BleDevice bleDevice, String uuid_service, String uuid_write, byte[] data, BleWriteCallback callback) void write(BleDevice bleDevice, String uuid_service, String uuid_write, byte[] data, boolean split, BleWriteCallback callback) void write(BleDevice bleDevice, String uuid_service, String uuid_write, byte[] data, boolean split, boolean sendNextWhenLastSuccess, long intervalBetweenTwoPackage, BleWriteCallback callback)

      BleManager.getInstance().write(
              bleDevice,
              uuid_service,
              uuid_characteristic_write,
              data,
              new BleWriteCallback() {
                  @Override
                  public void onWriteSuccess(int current, int total, byte[] justWrite) {
    
                  }
    
                  @Override
                  public void onWriteFailure(BleException exception) {
    
                  }
              });

    Tips:

    • Without expanding MTU and expanding MTU's ineffectiveness, subcontracting is required when long data with more than 20 bytes are to be sent. The parameter boolean split indicates whether to use packet delivery; the write method without the boolean split parameter is subcontracted to the data by more than 20 bytes by default.
    • On the onWriteSuccess callback method: current represents the number of packets that are currently sent, and total represents the total packet data this time, and justWrite represents the successful packet that has just been sent.
  • Read

    void read(BleDevice bleDevice, String uuid_service, String uuid_read, BleReadCallback callback)

      BleManager.getInstance().read(
              bleDevice,
              uuid_service,
              uuid_characteristic_read,
              new BleReadCallback() {
                  @Override
                  public void onReadSuccess(byte[] data) {
    
                  }
    
                  @Override
                  public void onReadFailure(BleException exception) {
    
                  }
              });
  • Get Rssi

    void readRssi(BleDevice bleDevice, BleRssiCallback callback)

      BleManager.getInstance().readRssi(
              bleDevice,
              new BleRssiCallback() {
    
                  @Override
                  public void onRssiFailure(BleException exception) {
    
                  }
    
                  @Override
                  public void onRssiSuccess(int rssi) {
    
                  }
              });

    Tips:

    • Obtaining the signal strength of the device must be carried out after the device is connected.
    • Some devices may not be able to read Rssi, do not callback onRssiSuccess (), and callback onRssiFailure () because of timeout.
  • set Mtu

    void setMtu(BleDevice bleDevice, int mtu, BleMtuChangedCallback callback)

      BleManager.getInstance().setMtu(bleDevice, mtu, new BleMtuChangedCallback() {
          @Override
          public void onSetMTUFailure(BleException exception) {
    
          }
    
          @Override
          public void onMtuChanged(int mtu) {
    
          }
      });

    Tips:

    • Setting up MTU requires operation after the device is connected.
    • There is no such restriction in the Android Version (API-17 to API-20). Therefore, only the equipment above API21 will expand the demand for MTU.
    • The parameter MTU of the method is set to 23, and the maximum setting is 512.
    • Not every device supports the expansion of MTU, which requires both sides of the communication, that is to say, the need for the device hardware also supports the expansion of the MTU method. After calling this method, you can see through onMtuChanged (int MTU) how much the maximum transmission unit of the device is expanded to after the final setup. If the device does not support, no matter how many settings, the final MTU will be 23.
  • requestConnectionPriority

    boolean requestConnectionPriority(BleDevice bleDevice,int connectionPriority)

    Tips:

    • Request a specific connection priority. Must be one of{@link BluetoothGatt#CONNECTION_PRIORITY_BALANCED}, {@link BluetoothGatt#CONNECTION_PRIORITY_HIGH} or {@link BluetoothGatt#CONNECTION_PRIORITY_LOW_POWER}.
  • Converte BleDevice object

    BleDevice convertBleDevice(BluetoothDevice bluetoothDevice)

    BleDevice convertBleDevice(ScanResult scanResult)

    Tips:

    • The completed BleDevice object is still unconnected, if necessary, advanced connection.
  • Get all connected devices

    List<BleDevice> getAllConnectedDevice()

      BleManager.getInstance().getAllConnectedDevice();
  • Get a BluetoothGatt of a connected device

    BluetoothGatt getBluetoothGatt(BleDevice bleDevice)

  • Get all Service of a connected device

    List<BluetoothGattService> getBluetoothGattServices(BleDevice bleDevice)

  • Get all the Characteristic of a Service

    List<BluetoothGattCharacteristic> getBluetoothGattCharacteristics(BluetoothGattService service)

  • Determine whether a device has been connected

    boolean isConnected(BleDevice bleDevice)

      BleManager.getInstance().isConnected(bleDevice);

    boolean isConnected(String mac)

      BleManager.getInstance().isConnected(mac);
  • Determine the current connection state of a device

    int getConnectState(BleDevice bleDevice)

      BleManager.getInstance().getConnectState(bleDevice);
  • Disconnect a device

    void disconnect(BleDevice bleDevice)

      BleManager.getInstance().disconnect(bleDevice);
  • Disconnect all devices

    void disconnectAllDevice()

      BleManager.getInstance().disconnectAllDevice();
  • Out of use, clean up resources

    void destroy()

      BleManager.getInstance().destroy();
  • HexUtil

    Data operation tool class

    String formatHexString(byte[] data, boolean addSpace)

    byte[] hexStringToBytes(String hexString)

    char[] encodeHex(byte[] data, boolean toLowerCase)

  • BleDevice

    BLE device object is the smallest unit object of scanning, connection and operation in this framework.

    String getName() Bluetooth broadcast name

    String getMac() Bluetooth MAC

    byte[] getScanRecord() Broadcast data

    int getRssi() Initial signal intensity

Contact

If you have problems and ideas to communicate with me, you can contact me in the following ways.

QQ: 1033526540

Email: jasonchenlijian@gmail.com

License

   Copyright 2016 chenlijian

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

	   http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2016 chenlijian(陈利健) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

暂无描述 展开 收起
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/clx2016/FastBle.git
git@gitee.com:clx2016/FastBle.git
clx2016
FastBle
FastBle
master

搜索帮助