From 5c9edbf13aad3a20eefbba6301c4cd30518f8aa2 Mon Sep 17 00:00:00 2001 From: aicareles <823581722@qq.com> Date: Tue, 28 Apr 2020 16:44:53 +0800 Subject: [PATCH] =?UTF-8?q?1.=E6=9B=B4=E6=96=B0README=E6=96=87=E4=BB=B6,?= =?UTF-8?q?=E6=9B=B4=E6=96=B0=E6=8E=A5=E5=85=A5=E6=96=87=E6=A1=A3=202.?= =?UTF-8?q?=E6=9B=B4=E6=96=B0=E7=89=88=E6=9C=AC=E8=87=B3v3.1.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/caches/build_file_checksums.ser | Bin 644 -> 644 bytes README-en.md | 316 +++++++++ README.md | 650 ++++++------------ core/build.gradle | 6 +- .../cn/com/heaton/blelibrary/ble/Ble.java | 24 +- ...iftCallback.java => BleNotiyCallback.java} | 2 +- .../ble/callback/BleWriteCallback.java | 2 +- .../blelibrary/ble/model/BleDevice.java | 4 +- .../blelibrary/ble/proxy/RequestImpl.java | 10 +- .../blelibrary/ble/proxy/RequestListener.java | 11 +- .../ble/request/ConnectRequest.java | 4 +- .../blelibrary/ble/request/NotifyRequest.java | 11 +- .../blelibrary/ble/request/WriteRequest.java | 2 +- java-sample/build.gradle | 4 +- .../admin/mybledemo/MyApplication.java | 2 + .../com/example/admin/mybledemo/Test.java | 2 +- .../admin/mybledemo/adapter/ChildAdapter.java | 8 +- .../admin/mybledemo/ui/BleActivity.java | 11 + .../mybledemo/ui/DeviceInfoActivity.java | 9 +- .../com/i502tech/appkotlin/AppProtocol.kt | 2 +- .../com/i502tech/appkotlin/MainActivity.kt | 4 +- 21 files changed, 601 insertions(+), 483 deletions(-) create mode 100644 README-en.md rename core/src/main/java/cn/com/heaton/blelibrary/ble/callback/{BleNotiftCallback.java => BleNotiyCallback.java} (91%) diff --git a/.idea/caches/build_file_checksums.ser b/.idea/caches/build_file_checksums.ser index c5a7aec94cffdec504a9a4018a5df5d345f74e9a..e49ca853fbb0de001e0aadad04a25920ec73f94a 100644 GIT binary patch delta 72 zcmV-O0Jr~y1%w5Vm;}G{ZZwgce-QNm5!LtjQ!W7}Hd2Uh>=lzM0ZJLy^X&ndBzk-E et=}_OS8U*P02*s=bZlvEk?<9hYykx^8 e1(pkdLTp2H02*s=bZlvEk?<9hYyk scanCallback = new BleScanCallback() { + @Override + public void onLeScan(final BleDevice device, int rssi, byte[] scanRecord) { + //Scanned devices + } + + @Override + public void onStart() { + super.onStart(); + } + + @Override + public void onStop() { + super.onStop(); + } + + @Override + public void onScanFailed(int errorCode) { + super.onScanFailed(errorCode); + Log.e(TAG, "onScanFailed: "+errorCode); + } + }; +``` +#### 2.connect/disconnect +``` +//Connect a device +ble.connect(device, connectCallback); + +//Connect multiple devices +ble.connects(devices, connectCallback); + +//Cancel the connecting device +ble.cancelConnecting(device); + +//Cancel the connecting devices +ble.cancelConnectings(devices); + +//disconnect a device +ble.disconnect(device); + +//disconnect all devices +ble.disconnectAll(); +``` +#### connect/disconnect callback +``` +private BleConnCallback connectCallback = new BleConnCallback() { + @Override + public void onConnectionChanged(BleDevice device) { + + } + + @Override + public void onConnectTimeOut(BleDevice device) { + super.onConnectTimeOut(device); + Log.e(TAG, "onConnectTimeOut: " + device.getBleAddress()); + } + + @Override + public void onConnectCancel(BleDevice device) { + super.onConnectCancel(device); + Log.e(TAG, "onConnectCancel: " + device.getBleName()); + } + + @Override + public void onServicesDiscovered(BleDevice device, BluetoothGatt gatt) { + super.onServicesDiscovered(device, gatt); + } + + @Override + public void onReady(BleDevice device) { + super.onReady(device); + //connect successful to enable notification + ble.enableNotify(...); + } + + @Override + public void onConnectException(BleDevice device, int errorCode) { + super.onConnectException(device, errorCode); + + } + }; +``` +#### 3.enable/disable notification +``` +ble.enableNotify(device, true, new BleNotifyCallback() { + @Override + public void onChanged(BleDevice device, BluetoothGattCharacteristic characteristic) { + UUID uuid = characteristic.getUuid(); + BleLog.e(TAG, "onChanged==uuid:" + uuid.toString()); + BleLog.e(TAG, "onChanged==data:" + ByteUtils.toHexString(characteristic.getValue())); + } + + @Override + public void onNotifySuccess(BleDevice device) { + super.onNotifySuccess(device); + BleLog.e(TAG, "onNotifySuccess: "+device.getBleName()); + } + }); +``` +#### 4.read data +``` +ble.read(device, new BleReadCallback() { + @Override + public void onReadSuccess(BleRssiDevice dedvice, BluetoothGattCharacteristic characteristic) { + super.onReadSuccess(dedvice, characteristic); + } + + @Override + public void onReadFailed(BleRssiDevice device, int failedCode) { + super.onReadFailed(device, failedCode); + } + }) +``` +#### 5.write data +``` +//write a package payload +ble.write(device, data, new BleWriteCallback() { + @Override + public void onWriteSuccess(BleRssiDevice device, BluetoothGattCharacteristic characteristic) { + + } + + @Override + public void onWriteFailed(BleRssiDevice device, int failedCode) { + super.onWriteFailed(device, failedCode); + } +}); + +//write large file/payload +byte[]data = toByteArray(getAssets().open("WhiteChristmas.bin")); +ble.writeEntity(mBle.getConnectedDevices().get(0), data, 20, 50, new BleWriteEntityCallback() { + @Override + public void onWriteSuccess() { + + } + + @Override + public void onWriteFailed() { + + } + + override void onWriteProgress(double progress) { + + } + + override void onWriteCancel() { + + } +}); + +//write data to the queue (The default interval is 50ms) +ble.writeQueue(RequestTask.newWriteTask(address, data)); +//write data to the queue with delay +ble.writeQueueDelay(delay, RequestTask.newWriteTask(address, data)); + +//Custom write data by service and characteristic uuid +ble.writeByUuid(device, data, serviceUuid, charUuid, new BleWriteCallback() { + @Override + public void onWriteSuccess(BleRssiDevice device, BluetoothGattCharacteristic characteristic) { + + } + + @Override + public void onWiteFailed(BleRssiDevice device, int failedCode) { + super.onWiteFailed(device, failedCode); + } +}); +``` +#### 6. remove callback (scan、connect) +``` +ble.cancelCallback(connectCallback); +or +ble.cancelCallback(scanCallback); +``` +#### 8. release +``` + ble.released(); +``` + +## History version introduction: +[History version](https://github.com/aicareles/Android-BLE/wiki/BLE%E5%BA%93%E5%8E%86%E5%8F%B2%E7%89%88%E6%9C%AC%E4%BB%8B%E7%BB%8D) + +## BLE Common problems and solutions +Please see this [Wiki BLE Page][Wiki] for more infos. + +[Wiki]:https://github.com/aicareles/Android-BLE/wiki#连接常见问题 + +## Java-Sample Screenshot: + +![2](https://github.com/aicareles/Android-BLE/blob/master/screenshots/2.jpeg) +![3](https://github.com/aicareles/Android-BLE/blob/master/screenshots/3.jpeg) +![4](https://github.com/aicareles/Android-BLE/blob/master/screenshots/4.jpeg) + +## *License* +``` +Copyright 2016 jerry + +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. +``` + +## Contribute: +![](https://upload-images.jianshu.io/upload_images/3884117-5d22ae84180a93ed.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/320) +![](https://upload-images.jianshu.io/upload_images/3884117-1f6c1c0fb5885252.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/320) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/README.md b/README.md index 9dabb39..7649a58 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -#### 对蓝牙感兴趣可以加群讨论学习(QQ:494309361) +#### 对蓝牙感兴趣可以加群讨论学习(QQ:494309361 已满) ### 有个人项目或者定制化需求的可加QQ:823581722 进行联系 ### Email:jerryee0911@qq.com @@ -6,496 +6,282 @@ ![二维码.png]( https://android-resource.oss-cn-qingdao.aliyuncs.com/GitClub/image/mJW4.png?Expires=1577947521&OSSAccessKeyId=TMP.hhbo7QSce5gPRayo3tJUYViA69964YTNBHGVNQd8PJ6L8PVwXatiaKGcL52pcneAzwAwv8jASidyskmj3g5HypuBK8AFrBRBN7Hi8krKU8pbGWNa4fxDaHsERWtJWC.tmp&Signature=ni2nOP8Ordl5srIw9LnvBJ1I5lY%3D) -#### 一、先来看张BleLib库的api之间的关系图: -![BleLib库结构图.png](http://upload-images.jianshu.io/upload_images/3884117-2c5a0b95cda75158.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/840) -### 1、BleDevice -``` -该类的主要是来描述并记录蓝牙的属性和状态,如记录蓝牙名称、蓝牙MAC地址、蓝牙别名(即修改之后的名称)、蓝牙连接状态等,该类处在被保护状态,禁止外部随意生成该对象, -如果有特别需求可以通过BleFactory.create(...)进行创建该对象(并不建议) -``` -### 2、BleStatus -``` -该类是蓝牙状态类,定义了蓝牙扫描、连接、通知使能、发送、接收等状态的常量值(连接异常等状态码可参考该类) -``` -### 3、BluetoothLeService -``` -该类是最重要的一个类,主要是蓝牙操作中用到的各个方法的实现类,是整个蓝牙的核心功能实现,BleManager是对外提供所有蓝牙操作接口的 -管理类,当BluetoothLeService处理之后要把结果返回到BleManager中,然后再由BleManager对外提供接口。 +# Android-BLE +[![License](https://img.shields.io/badge/license-Apache%202-green.svg)](https://www.apache.org/licenses/LICENSE-2.0) +[![Download](https://api.bintray.com/packages/superliu/maven/BleLib/images/download.svg)](https://bintray.com/superliu/maven/BleLib/_latestVersion) + +Android-BLE蓝牙框架,提供了扫描、连接、使能/除能通知、发送/读取数据、接收数据,读取rssi,设置mtu等蓝牙相关的所有操作接口,内部优化了连接队列,以及快速写入队列, +并支持多服务通讯,可扩展配置蓝牙相关操作。 + +## Android-BLE API +* **Ble** - 最重要的类,对外提供所有的蓝牙操作接口. +* **BleDevice** - 封装了蓝牙对象类,包含蓝牙连接状态以及基本蓝牙信息. +* **BleLog** - 内部日志类,开发环境下打开可查看蓝牙相关操作信息. +* **BleStates** - 蓝牙操作异常状态码信息类.(扫描、连接、读写等异常状态码). +* **ByteUtils** - 各种字节数据转换的工具类. + +## 接入文档 +### 1. 在 **build.gradle** 中添加下面依赖. +``` groovy +implementation 'cn.com.superLei:blelibrary:latestVersion' +``` +### 2. 在Application中初始化. +``` +private void initBle() { + Ble ble = Ble.options()//开启配置 + .setLogBleEnable(true)//设置是否输出打印蓝牙日志(非正式打包请设置为true,以便于调试) + .setThrowBleException(true)//设置是否抛出蓝牙异常 (默认true) + .setAutoConnect(false)//设置是否自动连接 (默认false) + .setIgnoreRepeat(false)//设置是否过滤扫描到的设备(已扫描到的不会再次扫描) + .setConnectTimeout(10 * 1000)//设置连接超时时长(默认10*1000 ms) + .setMaxConnectNum(7)//最大连接数量 + .setScanPeriod(12 * 1000)//设置扫描时长(默认10*1000 ms) + .setScanFilter(scanFilter)//设置扫描过滤 + .setUuidService(UUID.fromString(UuidUtils.uuid16To128("fd00")))//设置主服务的uuid(必填) + .setUuidWriteCha(UUID.fromString(UuidUtils.uuid16To128("fd01")))//设置可写特征的uuid (必填,否则写入失败) + .setUuidReadCha(UUID.fromString(UuidUtils.uuid16To128("fd02")))//设置可读特征的uuid (选填) + .setUuidNotifyCha(UUID.fromString(UuidUtils.uuid16To128("fd03")))//设置可通知特征的uuid (选填,库中默认已匹配可通知特征的uuid) + .setFactory(new BleFactory() {//实现自定义BleDevice时必须设置 + @Override + public MyDevice create(String address, String name) { + return new MyDevice(address, name);//自定义BleDevice的子类 + } + }) + .setBleWrapperCallback(new MyBleWrapperCallback())//设置全部蓝牙相关操作回调(例: OTA升级可以再这里实现,与项目其他功能逻辑完全解耦) + .create(mApplication, new Ble.InitCallback() { + @Override + public void success() { + BleLog.e("MainApplication", "初始化成功"); + } + + @Override + public void failed(int failedCode) { + BleLog.e("MainApplication", "初始化失败:" + failedCode); + } + }); + } ``` -### 4、Ble +### 3. 开始使用. +#### 1.扫描 ``` -该类提供了几乎所有你需要用到的方法,包括蓝牙扫描、连接、断开、蓝牙当前连接状态等等,管理了蓝牙操作的所有接口和方法。 +ble.startScan(scanCallback); ``` - -### 二、历史版本介绍: -[![Version](https://img.shields.io/badge/BleLib-v3.0.5-blue.svg)](https://bintray.com/superliu/maven/BleLib/3.0.5) +#### 扫描回调 (注: 记得打开蓝牙并检查是否授予蓝牙权限) ``` -1.添加自定义BleDevice接口(实现BleDeviceFactory接口) -public class BleRssiDevice extends BleDevice{ - //添加自定义属性值 - private int deviceType; - private int rssi; - ... -} -必须在初始化时设置: -Ble.options().setFactory(new BleFactory() {//实现自定义BleDevice时必须设置 - @Override - public BleRssiDevice create(String address, String name) { - return new BleRssiDevice(address, name);//自定义BleDevice的子类 - } -}) +BleScanCallback scanCallback = new BleScanCallback() { + @Override + public void onLeScan(final BleDevice device, int rssi, byte[] scanRecord) { + //Scanned devices + } -2.添加实现所有回调接口的Callback(可用于OTA升级等,完全解耦项目) -public class MyBleWrapperCallback extends BleWrapperCallback { - ... -} + @Override + public void onStart() { + super.onStart(); + } -Ble.options().setBleWrapperCallback(new MyBleWrapperCallback()) -``` -[![Version](https://img.shields.io/badge/BleLib-v3.0.0-blue.svg)](https://bintray.com/superliu/maven/BleLib/3.0.0) -``` -1.添加写入队列(异步,可自定义队列每个任务延迟时间) - @CheckConnect //检查是否连接 - private void writeQueue() { - String address = ble.getConnetedDevices().get(0).getBleAddress(); - for (int i = 0; i < 30; i++) { - //ble.writeQueueDelay(50, RequestTask.newWriteTask(address, "hello android".getBytes())); - ble.writeQueue(RequestTask.newWriteTask(address, "hello android".getBytes())); + @Override + public void onStop() { + super.onStop(); } - } -2.同时连接多个 - ble.connects(adapter.getDevices(), connectCallback); -3.取消连接多个设备(取消正在连接/已加入队列中还未连接的设备) - ble.cancelConnecttings(adapter.getDevices()); -4.更新部分: - BleConnectCallback connectCallback = new BleConnectCallback() { + @Override - public void onReady(BleDevice device) { - super.onReady(device); - /*连接成功后,在次回调中设置通知,否则收不到设备的数据*/ - ble.startNotify(device, bleNotiftCallback); + public void onScanFailed(int errorCode) { + super.onScanFailed(errorCode); + Log.e(TAG, "onScanFailed: "+errorCode); } }; ``` -[![Version](https://img.shields.io/badge/BleLib-v2.6.1-blue.svg)](https://bintray.com/superliu/maven/BleLib/2.6.1) +#### 2.连接/断开 ``` -添加自动分包发送接口(无需添加延迟,自动根据系统底层返回结果处理) - EntityData entityData = new EntityData.Builder() - .setLastPackComplete(true)//最后一包是否自动补零,默认false - .setAutoWriteMode(autoWriteMode)//是否设置自动模式发送,默认false - .setAddress(device.getBleAddress()) - .setData(data)//大数据文件的字节数组 - .setPackLength(20)//每包发送字节数 - .setDelay(50L)//自动模式下无需设置delay - .build(); - mBle.writeEntity(entityData, new BleWriteEntityCallback() { - @Override - public void onWriteSuccess() { - ... - } - - @Override - public void onWriteFailed() { - ... - } - }); +//连接设备 +ble.connect(device, connectCallback); -``` -[![Version](https://img.shields.io/badge/BleLib-v2.6.0-blue.svg)](https://bintray.com/superliu/maven/BleLib/2.6.0) -``` -优化频繁收到通知数据,偶尔丢包的问题 -``` -[![Version](https://img.shields.io/badge/BleLib-v2.5.4-blue.svg)](https://bintray.com/superliu/maven/BleLib/2.5.4) -``` -1、添加过滤扫描设备接口 - mBle = Ble.options() - .setLogBleExceptions(true) - .setThrowBleException(true) - .setAutoConnect(true) - .setFilterScan(true)//设置是否过滤扫描到的设备 - .setConnectFailedRetryCount(3) - .setConnectTimeout(10 * 1000) - .setScanPeriod(12 * 1000) - .setUuidService(UUID.fromString("0000fee9-0000-1000-8000-00805f9b34fb")) - .setUuidWriteCha(UUID.fromString("d44bc439-abfd-45a2-b575-925416129600")) - .create(getApplicationContext()); - 2、优化自动重连接口 - 3、添加Android5.0发送广播的接口 - byte[] payload = new byte[16]; - payload[0] = 0x01; - mBle.startAdvertising(payload); - 4、收到广播包并解析后的数据 - BleScanCallback scanCallback = new BleScanCallback() { - @Override - public void onLeScan(final BleDevice device, int rssi, byte[] scanRecord) { - Log.e(TAG, "onLeScan: "+device.getBleAddress()); - synchronized (mBle.getLocker()) { - mLeDeviceListAdapter.addDevice(device); - mLeDeviceListAdapter.notifyDataSetChanged(); - } - } +//连接多个设备 +ble.connects(devices, connectCallback); - //收到广播包并解析后的数据 - @Override - public void onParsedData(BleDevice device, ScanRecord scanRecord) { - super.onParsedData(device, scanRecord); - byte[] data = scanRecord.getManufacturerSpecificData(65535);//参数为厂商id - if (data != null){ - Log.e(TAG, "onParsedData: "+ ByteUtils.BinaryToHexString(data)); - } - } - }; +//取消正在连接的设备 +ble.cancelConnecting(device); +//取消正在连接的多个设备 +ble.cancelConnectings(devices); -``` +//断开设备 +ble.disconnect(device); -[![Version](https://img.shields.io/badge/BleLib-v2.5.3-blue.svg)](https://bintray.com/superliu/maven/BleLib/2.5.3) -``` -1、添加发送大数据量的进度回调 - private void sendEntityData() throws IOException { - byte[] data = ByteUtils.toByteArray(getAssets().open("WhiteChristmas.bin")); - Log.e(TAG, "sendEntityData: "+data.length); - mBle.writeEntity(mBle.getConnetedDevices().get(0), data, 20, 50, new BleWriteEntityCallback() { - @Override - public void onWriteSuccess() { - L.e("writeEntity", "onWriteSuccess"); - } - - @Override - public void onWriteFailed() { - L.e("writeEntity", "onWriteFailed"); - } - - @Override - public void onWriteProgress(double progress) { - Log.e("writeEntity", "当前发送进度: "+progress); - } - - @Override - public void onWriteCancel() { - Log.e(TAG, "onWriteCancel: "); - } - }); - } -2、修复持续接收通知回调过快导致数据重复的问题 -3、修复多设备连接,同时断开所有设备,回调次数不完整的问题 -``` -[![Version](https://img.shields.io/badge/BleLib-v2.5.2%20beta-blue.svg)](https://bintray.com/superliu/maven/BleLib/2.5.2-beta) +//断开所有设备 +ble.disconnectAll(); ``` -1、添加自动连接的接口(使用新的初始化写法) - mBle = Ble.options() - .setLogBleEnable(true) - .setThrowBleException(true) - .setAutoConnect(true)//自动重连 - .setConnectFailedRetryCount(3) - .setConnectTimeout(10 * 1000) - .setScanPeriod(12 * 1000) - .setUuidService(UUID.fromString("0000fee9-0000-1000-8000-00805f9b34fb")) - .setUuidWriteCha(UUID.fromString("d44bc439-abfd-45a2-b575-925416129600")) - .create(getApplicationContext()); -2、优化断开连接后,自动移除通知监听的问题 +#### 连接/断开回调 ``` -[![Version](https://img.shields.io/badge/BleLib-v2.5.0-blue.svg)](https://bintray.com/superliu/maven/BleLib/2.5.0) -``` -1、添加了发送大数据包(如:文件等)的接口 - try { - //获取整个文件的总字节 - byte[]data = toByteArray(getAssets().open("WhiteChristmas.bin")); - //发送大数据量的包 - mBle.writeEntity(mBle.getConnetedDevices().get(0), data, 20, 50, new BleWriteEntityCallback() { - @Override - public void onWriteSuccess() { - L.e("writeEntity", "onWriteSuccess"); - } +private BleConnCallback connectCallback = new BleConnCallback() { + @Override + public void onConnectionChanged(BleDevice device) { - @Override - public void onWriteFailed() { - L.e("writeEntity", "onWriteFailed"); - } - }); - } catch (IOException e) { - e.printStackTrace(); - } -2、修复了正在扫描时,关闭蓝牙导致停止扫描onStop()不回调的问题 -``` -[![Version](https://img.shields.io/badge/BleLib-v2.3.0-blue.svg)](https://bintray.com/superliu/maven/BleLib/2.3.0) -``` -1、添加通过mac地址连接的接口: - String address = device.getBleAddress();//或者 String address = "3E:9A:4A:71:F6:4D"; - mBle.connect(address, new BleConnCallback() { - @Override - public void onConnectionChanged(BleDevice device) { - - } - }); -2、添加BLE4.2的设置MTU的接口: - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ - //此处第二个参数 不是特定的 比如你也可以设置500 但是如果设备不支持500个字节则会返回最大支持数 - mBle.setMTU(mBle.getConnetedDevices().get(0).getBleAddress(), 250, new BleMtuCallback() { - @Override - public void onMtuChanged(BleDevice device, int mtu, int status) { - super.onMtuChanged(device, mtu, status); - ToastUtil.showToast("最大支持MTU:"+mtu); - } - }); - }else { - ToastUtil.showToast("设备不支持MTU"); - } + } -``` -[![Version](https://img.shields.io/badge/BleLib-v2.2.0-blue.svg)](https://bintray.com/superliu/maven/BleLib/2.2.0) -``` -修复连接多个设备在onChanged()回调中判断设备对象 - /*设置通知的回调*/ - private BleNotiftCallback bleNotiftCallback = new BleNotiftCallback() { @Override - public void onChanged(BleDevice device, BluetoothGattCharacteristic characteristic) { - UUID uuid = characteristic.getUuid(); - Log.e(TAG, "onChanged==uuid:" + uuid.toString()); - Log.e(TAG, "onChanged==address:"+ device.getBleAddress()); - Log.e(TAG, "onChanged==data:" + Arrays.toString(characteristic.getValue())); + public void onConnectTimeOut(BleDevice device) { + super.onConnectTimeOut(device); + Log.e(TAG, "onConnectTimeOut: " + device.getBleAddress()); } - }; -``` -[![Version](https://img.shields.io/badge/BleLib-v2.1.5-blue.svg)](https://bintray.com/superliu/maven/BleLib/2.1.5) -``` -更新低版本手机(初始化问题)报错问题 -``` -[![Version](https://img.shields.io/badge/BleLib-v2.1.2-blue.svg)](https://bintray.com/superliu/maven/BleLib/2.1.2) -``` -1、修复上个版本依赖地址变化,导致依赖时出现问题。 -2、添加清理蓝牙缓存接口 -``` -[![Version](https://img.shields.io/badge/BleLib-v2.1.1-blue.svg)](https://bintray.com/superliu/maven/BleLib/2.1.1) -``` -适配更新5.0以上版本手机扫描的API -``` -[![Version](https://img.shields.io/badge/BleLib-v2.1.0-blue.svg)](https://bintray.com/superliu/maven/BleLib/2.1.0) -``` -该版本添加跳转到测试界面(先连接设备),在测试界面操作该蓝牙对象的扫描、连接、断开、通知等回调的接口(任意界面都可以随心所欲的操作或者拿到mcu返回的数据) -1、在其他界面你也想拿到蓝牙设备传过来的数据,你可以这样做:(重要) - //测试通知 - public void testNotify(BleDevice device) { - if(device != null){ - mNotifyStatus.setText("设置通知监听成功!!!"); - mBle.startNotify(device, new BleNotiftCallback() { - @Override - public void onChanged(BluetoothGattCharacteristic characteristic) { - Log.e(TAG, "onChanged: " + Arrays.toString(characteristic.getValue())); - mNotifyValue.setText("收到MCU通知值:\n"+Arrays.toString(characteristic.getValue())); - } - }); + @Override + public void onConnectCancel(BleDevice device) { + super.onConnectCancel(device); + Log.e(TAG, "onConnectCancel: " + device.getBleName()); } - } -2、在其他界面也想连接或者断开上个界面的设备对象,你可以这么做: - mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { - //测试连接或断开 - final BleDevice device = mLeDeviceListAdapter.getDevice(position); - if (device == null) return; - if (mBle.isScanning()) { - mBle.stopScan(); - } - if (device.isConnected()) { - //2.1.0版本新增接口(mBle.disconnect(device)接口仍可正常使用) - mBle.disconnect(device, connectCallback); - } else if (!device.isConnectting()) { - mBle.connect(device, connectCallback); - } - } - }); -3、扫描、发送数据、读取数据等接口都可如上正常使用(与之前版本一样) -``` -[![Version](https://img.shields.io/badge/BleLib-v2.0.5-blue.svg)](https://bintray.com/superliu/maven/BleLib/2.0.5) -``` -该版本添加根据蓝牙地址获取蓝牙对象的接口 -``` -[![Version](https://img.shields.io/badge/BleLib-v2.0.4-blue.svg)](https://bintray.com/superliu/maven/BleLib/2.0.4) -``` -该版本修复读、写、通知特征uuid相同的情况下,出现无法设置通知的BUG -``` -[![Version](https://img.shields.io/badge/BleLib-v2.0.3-blue.svg)](https://bintray.com/superliu/maven/BleLib/2.0.3) -``` -该版本优化内部api结构,但并不影响外部接口调用 -``` -[![Version](https://img.shields.io/badge/BleLib-v2.0.2-blue.svg)](https://bintray.com/superliu/maven/BleLib/2.0.2) -``` -该版本增加主动读取数据以及读取远程RSSI值的接口 -``` -[![Version](https://img.shields.io/badge/BleLib-v2.0.0-blue.svg)](https://bintray.com/superliu/maven/BleLib/2.0.0) -``` -该版本重构V 1.x版本,作为全新升级版本,重大类、接口进行重命名,使各个接口完成单一功能,并使之得到单一功能的回调。 -注:至此V 2.0.0版本以后不再维护1.x版本 -``` -[![Version](https://img.shields.io/badge/BleLib-v1.0.4-blue.svg)](https://bintray.com/superliu/maven/BleLib/1.0.4) -``` -增加了自动连接的接口 -``` -[![Version](https://img.shields.io/badge/BleLib-v1.0.0-blue.svg)](https://bintray.com/superliu/maven/BleLib/1.0.0) -``` -初始版本,可完成基本的BLE蓝牙一系列操作(扫描、连接、断开、设置通知、发送数据等等) -``` - -### 三、使用步骤: - -#### 首先buidl.gradle中添加依赖: -[![License](https://img.shields.io/badge/license-Apache%202-green.svg)](https://www.apache.org/licenses/LICENSE-2.0) -[![Download](https://api.bintray.com/packages/superliu/maven/BleLib/images/download.svg)](https://bintray.com/superliu/maven/BleLib/_latestVersion) -```groovy -compile 'cn.com.superLei:blelibrary:latestVersion' -``` -#### 1.初始化蓝牙(判断设备是否支持BLE,蓝牙是否打开以及6.0动态授权蓝牙权限等)
+ @Override + public void onServicesDiscovered(BleDevice device, BluetoothGatt gatt) { + super.onServicesDiscovered(device, gatt); + } -``` - private void initBle() { - //方式1 - mBle = Ble.options()//开启配置 - .setLogBleEnable(true)//设置是否输出打印蓝牙日志 - .setThrowBleException(true)//设置是否抛出蓝牙异常 - .setLogTAG("AndroidBLE")//设置全局蓝牙操作日志TAG - .setAutoConnect(true)//设置是否自动连接 - .setFilterScan(false)//设置是否过滤扫描到的设备 - .setConnectFailedRetryCount(3) - .setConnectTimeout(10 * 1000)//设置连接超时时长(默认10*1000 ms) - .setScanPeriod(12 * 1000)//设置扫描时长(默认10*1000 ms) - .setUuidService(UUID.fromString("0000fee9-0000-1000-8000-00805f9b34fb"))//主服务的uuid - .setUuidWriteCha(UUID.fromString("d44bc439-abfd-45a2-b575-925416129600"))//可写特征的uuid - .create(getApplicationContext()); - - 或者 - //方式2 使用默认配置 - mBle = Ble.create(getApplicationContext()); - //方式3(同方式1) - Ble.Options options = Ble.options() - .setLogBleEnable(true) - .setAutoConnect(true)...; - mBle = Ble.create(getApplicationContext(), options); - - 注意:若进行数据交互,必须进行配置uuid的各个值 - } -``` + @Override + public void onReady(BleDevice device) { + super.onReady(device); + //connect successful to enable notification + ble.enableNotify(...); + } -#### 2.开始扫描 -``` -mBle.startScan(scanCallback); -``` -### 扫描的回调 -``` -BleScanCallback scanCallback = new BleScanCallback() { @Override - public void onLeScan(final BleDevice device, int rssi, byte[] scanRecord) { - Toast.makeText(BleActivity.this, "ssss", Toast.LENGTH_SHORT).show(); - synchronized (mBle.getLocker()) { - runOnUiThread(new Runnable() { - @Override - public void run() { - mLeDeviceListAdapter.addDevice(device); - mLeDeviceListAdapter.notifyDataSetChanged(); - } - }); - } + public void onConnectException(BleDevice device, int errorCode) { + super.onConnectException(device, errorCode); + } }; ``` -#### 3.开始连接 -``` -mBle.connect(device, connectCallback); +#### 3.使能/除能通知 ``` -#### 连接的回调 -``` - private BleConnCallback connectCallback = new BleConnCallback() { +ble.enableNotify(device, true, new BleNotifyCallback() { @Override - public void onConnectionChanged(BleDevice device) { - if (device.isConnected()) { - setNotify(device); - } - Log.e(TAG, "onConnectionChanged: " + device.isConnected()); - mLeDeviceListAdapter.notifyDataSetChanged(); - setConnectedNum(); + public void onChanged(BleDevice device, BluetoothGattCharacteristic characteristic) { + UUID uuid = characteristic.getUuid(); + BleLog.e(TAG, "onChanged==uuid:" + uuid.toString()); + BleLog.e(TAG, "onChanged==data:" + ByteUtils.toHexString(characteristic.getValue())); } @Override - public void onConnectException(BleDevice device, int errorCode) { - super.onConnectException(device, errorCode); - Toast.makeText(BleActivity.this, "连接异常,异常状态码:" + errorCode, Toast.LENGTH_SHORT).show(); + public void onNotifySuccess(BleDevice device) { + super.onNotifySuccess(device); + BleLog.e(TAG, "onNotifySuccess: "+device.getBleName()); } - }; + }); ``` -#### 4.设置通知及回调 +#### 4.读取数据 ``` -private void setNotify(BleDevice device) { - /*连接成功后,设置通知*/ - mBle.startNotify(device, new BleNotiftCallback() { +ble.read(device, new BleReadCallback() { @Override - public void onChanged(BleDevice device, BluetoothGattCharacteristic characteristic) { - Log.e(TAG, "onChanged: " + Arrays.toString(characteristic.getValue())); + public void onReadSuccess(BleRssiDevice dedvice, BluetoothGattCharacteristic characteristic) { + super.onReadSuccess(dedvice, characteristic); } @Override - public void onReady(BleDevice device) { - Log.e(TAG, "onReady: "); + public void onReadFailed(BleRssiDevice device, int failedCode) { + super.onReadFailed(device, failedCode); } + }) +``` +#### 5.写入数据 +``` +//写入一包数据 +ble.write(device, data, new BleWriteCallback() { + @Override + public void onWriteSuccess(BleRssiDevice device, BluetoothGattCharacteristic characteristic) { - @Override - public void onServicesDiscovered(BluetoothGatt gatt) { - Log.e(TAG, "onServicesDiscovered is success "); - } + } - @Override - public void onNotifySuccess(BluetoothGatt gatt) { - Log.e(TAG, "onNotifySuccess is success "); - } - }); + @Override + public void onWriteFailed(BleRssiDevice device, int failedCode) { + super.onWriteFailed(device, failedCode); } +}); + +//写入大数据(文件、图片等) +byte[]data = toByteArray(getAssets().open("WhiteChristmas.bin")); +ble.writeEntity(mBle.getConnectedDevices().get(0), data, 20, 50, new BleWriteEntityCallback() { + @Override + public void onWriteSuccess() { + + } + + @Override + public void onWriteFailed() { + + } + + override void onWriteProgress(double progress) { + + } + + override void onWriteCancel() { + + } +}); + +//写入数据到队列中 (默认发送间隔50ms) +ble.writeQueue(RequestTask.newWriteTask(address, data)); +//写入数据到队列中 (自定义间隔时间) +ble.writeQueueDelay(delay, RequestTask.newWriteTask(address, data)); + +//通过特定服务和特征值uuid写入数据 +ble.writeByUuid(device, data, serviceUuid, charUuid, new BleWriteCallback() { + @Override + public void onWriteSuccess(BleRssiDevice device, BluetoothGattCharacteristic characteristic) { + + } + + @Override + public void onWiteFailed(BleRssiDevice device, int failedCode) { + super.onWiteFailed(device, failedCode); + } +}); ``` -#### 5.读取远程Rssi -``` -mBle.readRssi(mBle.getConnetedDevices().get(0), new BleReadRssiCallback() { - @Override - public void onReadRssiSuccess(int rssi) { - super.onReadRssiSuccess(rssi); - Log.e(TAG, "onReadRssiSuccess: " + rssi); - Toast.makeText(BleActivity.this, "onReadRssiSuccess:"+ rssi, Toast.LENGTH_SHORT).show(); - } - }); +#### 6. 移除监听(scan、connect) ``` -#### 5.写入数据 +ble.cancelCallback(connectCallback); +或 +ble.cancelCallback(scanCallback); ``` -boolean result = mBle.write(device, changeLevelInner(), new BleWriteCallback() { - @Override - public void onWriteSuccess(BluetoothGattCharacteristic characteristic) { - Toast.makeText(BleActivity.this, "发送数据成功", Toast.LENGTH_SHORT).show(); - } - }); - if (!result) { - Log.e(TAG, "changeLevelInner: " + "发送数据失败!"); - } +#### 8. 释放资源 ``` -#### 6.OTA升级 + ble.released(); ``` -//找到你需要升级文件的路径(一般情况都是保存再服务器上,一旦有更新会自动提示,然后APP下载并保存到本地,生成对应的file对象) -File file = new File(...); -//读写SD卡权限,此处略(6.0及以上需添加) -OtaManager mOtaManager = new OtaManager(BleActivity.this); -boolean result = mOtaManager.startOtaUpdate(file, (BleDevice) mBle.getConnetedDevices().get(0), mBle); -Log.e("OTA升级结果:", result + ""); + +## 历史版本介绍: +[历史版本](https://github.com/aicareles/Android-BLE/wiki/BLE%E5%BA%93%E5%8E%86%E5%8F%B2%E7%89%88%E6%9C%AC%E4%BB%8B%E7%BB%8D) + +## BLE蓝牙常见问题及解决方案 +请通过该 [Wiki BLE Page][Wiki] 了解更多信息. + +[Wiki]:https://github.com/aicareles/Android-BLE/wiki#连接常见问题 + +## Java-Sample Screenshot: + +![2](https://github.com/aicareles/Android-BLE/blob/master/screenshots/2.jpeg) +![3](https://github.com/aicareles/Android-BLE/blob/master/screenshots/3.jpeg) +![4](https://github.com/aicareles/Android-BLE/blob/master/screenshots/4.jpeg) + +## *License* ``` -### 四、工具类截图: +Copyright 2016 jerry -![](https://www.pgyer.com/image/view/app_screenshots/d72c86ea0d47a770d353219afe63f5b3-528) -![](https://www.pgyer.com/image/view/app_screenshots/02d4a22f7e19aea2dccc0791c5fcd85b-528) -![](https://www.pgyer.com/image/view/app_screenshots/ff9aae940594298cb5c77e8f2a0e7658-528) +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. +``` + +## Contribute: ![](https://upload-images.jianshu.io/upload_images/3884117-5d22ae84180a93ed.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/320) ![](https://upload-images.jianshu.io/upload_images/3884117-1f6c1c0fb5885252.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/320) -``` -注:打赏后可留言/联系本人,提供您的需求以及建议,本人会进行定期的更新优化库的体验,多谢支持! -``` diff --git a/core/build.gradle b/core/build.gradle index 603c191..d52c41c 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -8,8 +8,8 @@ android { defaultConfig { minSdkVersion 18 targetSdkVersion 28 - versionCode 56 - versionName "3.0.5" + versionCode 57 + versionName "3.1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } @@ -42,7 +42,7 @@ tasks.withType(Javadoc) { // options.addStringOption('links','http://docs.oracle.com/javase/7/docs/api') } -version = "3.0.5" //这个是版本号,必须填写 +version = "3.1.0" //这个是版本号,必须填写 def siteUrl = 'https://github.com/aicareles/Android-BLE' // 项目的主页 这个是说明,可随便填 def gitUrl = 'https://github.com/aicareles/Android-BLE' // Git仓库的url 这个是说明,可随便填 //implementation 'com.arshowbaby:mylibrary:1.0.0'中的com.arshowbaby diff --git a/core/src/main/java/cn/com/heaton/blelibrary/ble/Ble.java b/core/src/main/java/cn/com/heaton/blelibrary/ble/Ble.java index 7e37975..c1d93b8 100644 --- a/core/src/main/java/cn/com/heaton/blelibrary/ble/Ble.java +++ b/core/src/main/java/cn/com/heaton/blelibrary/ble/Ble.java @@ -16,7 +16,7 @@ import cn.com.heaton.blelibrary.ble.callback.BleConnectCallback; import cn.com.heaton.blelibrary.ble.callback.BleMtuCallback; -import cn.com.heaton.blelibrary.ble.callback.BleNotiftCallback; +import cn.com.heaton.blelibrary.ble.callback.BleNotiyCallback; import cn.com.heaton.blelibrary.ble.callback.BleReadCallback; import cn.com.heaton.blelibrary.ble.callback.BleReadDescCallback; import cn.com.heaton.blelibrary.ble.callback.BleReadRssiCallback; @@ -247,18 +247,18 @@ public void disconnectAll(){ * 连接成功后,开始设置通知 * @param device 蓝牙设备对象 * @param callback 通知回调 - * @deprecated Use {@link Ble#enableNotify(T, boolean, BleNotiftCallback)} instead. + * @deprecated Use {@link Ble#enableNotify(T, boolean, BleNotiyCallback)} instead. */ - public void startNotify(T device, BleNotiftCallback callback){ + public void startNotify(T device, BleNotiyCallback callback){ request.notify(device, callback); } /** * 移除通知 * @param device 蓝牙设备对象 - * @deprecated Use {@link Ble#enableNotify(T, boolean, BleNotiftCallback)} instead. + * @deprecated Use {@link Ble#enableNotify(T, boolean, BleNotiyCallback)} instead. */ - public void cancelNotify(T device, BleNotiftCallback callback){ + public void cancelNotify(T device, BleNotiyCallback callback){ request.cancelNotify(device, callback); } @@ -268,7 +268,7 @@ public void cancelNotify(T device, BleNotiftCallback callback){ * @param enable 打开/关闭 * @param callback 通知回调 */ - public void enableNotify(T device, boolean enable, BleNotiftCallback callback){ + public void enableNotify(T device, boolean enable, BleNotiyCallback callback){ request.enableNotify(device, enable, callback); } @@ -280,7 +280,7 @@ public void enableNotify(T device, boolean enable, BleNotiftCallback callback * @param characteristicUUID 通知特征uuid * @param callback 通知回调 */ - public void enableNotifyByUuid(T device, boolean enable, UUID serviceUUID, UUID characteristicUUID, BleNotiftCallback callback){ + public void enableNotifyByUuid(T device, boolean enable, UUID serviceUUID, UUID characteristicUUID, BleNotiyCallback callback){ request.enableNotifyByUuid(device, enable, serviceUUID, characteristicUUID, callback); } @@ -788,7 +788,7 @@ public Options setFactory(BleFactory factory) { UUID uuid_service = UUID.fromString("0000fee9-0000-1000-8000-00805f9b34fb"); UUID uuid_write_cha = UUID.fromString("d44bc439-abfd-45a2-b575-925416129600"); UUID uuid_read_cha = UUID.fromString("d44bc439-abfd-45a2-b575-925416129600"); - UUID uuid_notify = UUID.fromString("d44bc439-abfd-45a2-b575-925416129601"); + UUID uuid_notify_cha = UUID.fromString("d44bc439-abfd-45a2-b575-925416129601"); UUID uuid_notify_desc = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); UUID uuid_ota_service = UUID.fromString("0000fee8-0000-1000-8000-00805f9b34fb"); @@ -831,12 +831,12 @@ public Options setUuidReadCha(UUID uuid_read_cha) { return this; } - public UUID getUuidNotify() { - return uuid_notify; + public UUID getUuidNotifyCha() { + return uuid_notify_cha; } - public Options setUuidNotify(UUID uuid_notify) { - this.uuid_notify = uuid_notify; + public Options setUuidNotifyCha(UUID uuid_notify_cha) { + this.uuid_notify_cha = uuid_notify_cha; return this; } diff --git a/core/src/main/java/cn/com/heaton/blelibrary/ble/callback/BleNotiftCallback.java b/core/src/main/java/cn/com/heaton/blelibrary/ble/callback/BleNotiyCallback.java similarity index 91% rename from core/src/main/java/cn/com/heaton/blelibrary/ble/callback/BleNotiftCallback.java rename to core/src/main/java/cn/com/heaton/blelibrary/ble/callback/BleNotiyCallback.java index 54816c3..b1b552e 100644 --- a/core/src/main/java/cn/com/heaton/blelibrary/ble/callback/BleNotiftCallback.java +++ b/core/src/main/java/cn/com/heaton/blelibrary/ble/callback/BleNotiyCallback.java @@ -7,7 +7,7 @@ * Created by LiuLei on 2017/10/23. */ -public abstract class BleNotiftCallback { +public abstract class BleNotiyCallback { /** * MCU data sent to the app when the data callback call is setNotify * @param device ble device object diff --git a/core/src/main/java/cn/com/heaton/blelibrary/ble/callback/BleWriteCallback.java b/core/src/main/java/cn/com/heaton/blelibrary/ble/callback/BleWriteCallback.java index 1a73813..229290c 100644 --- a/core/src/main/java/cn/com/heaton/blelibrary/ble/callback/BleWriteCallback.java +++ b/core/src/main/java/cn/com/heaton/blelibrary/ble/callback/BleWriteCallback.java @@ -9,5 +9,5 @@ public abstract class BleWriteCallback { public abstract void onWriteSuccess(T device, BluetoothGattCharacteristic characteristic); - public void onWiteFailed(T device, int failedCode){} + public void onWriteFailed(T device, int failedCode){} } diff --git a/core/src/main/java/cn/com/heaton/blelibrary/ble/model/BleDevice.java b/core/src/main/java/cn/com/heaton/blelibrary/ble/model/BleDevice.java index 75fa64c..4a2f633 100644 --- a/core/src/main/java/cn/com/heaton/blelibrary/ble/model/BleDevice.java +++ b/core/src/main/java/cn/com/heaton/blelibrary/ble/model/BleDevice.java @@ -11,9 +11,9 @@ */ public class BleDevice implements Parcelable { - public static final int CONNECTED = 1; - public static final int CONNECTING = 2; public static final int DISCONNECT = 0; + public static final int CONNECTING = 1; + public static final int CONNECTED = 2; public final static String TAG = BleDevice.class.getSimpleName(); private static final long serialVersionUID = -2576082824642358033L; diff --git a/core/src/main/java/cn/com/heaton/blelibrary/ble/proxy/RequestImpl.java b/core/src/main/java/cn/com/heaton/blelibrary/ble/proxy/RequestImpl.java index 873ee5b..c44be56 100644 --- a/core/src/main/java/cn/com/heaton/blelibrary/ble/proxy/RequestImpl.java +++ b/core/src/main/java/cn/com/heaton/blelibrary/ble/proxy/RequestImpl.java @@ -5,7 +5,7 @@ import cn.com.heaton.blelibrary.ble.model.BleDevice; import cn.com.heaton.blelibrary.ble.callback.BleConnectCallback; import cn.com.heaton.blelibrary.ble.callback.BleMtuCallback; -import cn.com.heaton.blelibrary.ble.callback.BleNotiftCallback; +import cn.com.heaton.blelibrary.ble.callback.BleNotiyCallback; import cn.com.heaton.blelibrary.ble.callback.BleReadCallback; import cn.com.heaton.blelibrary.ble.callback.BleReadRssiCallback; import cn.com.heaton.blelibrary.ble.callback.BleScanCallback; @@ -50,25 +50,25 @@ public boolean connect(String address, BleConnectCallback callback) { } @Override - public void notify(T device, BleNotiftCallback callback) { + public void notify(T device, BleNotiyCallback callback) { NotifyRequest request = Rproxy.getRequest(NotifyRequest.class); request.notify(device, true, callback); } @Override - public void cancelNotify(T device, BleNotiftCallback callback) { + public void cancelNotify(T device, BleNotiyCallback callback) { NotifyRequest request = Rproxy.getRequest(NotifyRequest.class); request.notify(device, false, callback); } @Override - public void enableNotify(T device, boolean enable, BleNotiftCallback callback) { + public void enableNotify(T device, boolean enable, BleNotiyCallback callback) { NotifyRequest request = Rproxy.getRequest(NotifyRequest.class); request.notify(device, enable, callback); } @Override - public void enableNotifyByUuid(T device, boolean enable, UUID serviceUUID, UUID characteristicUUID, BleNotiftCallback callback) { + public void enableNotifyByUuid(T device, boolean enable, UUID serviceUUID, UUID characteristicUUID, BleNotiyCallback callback) { NotifyRequest request = Rproxy.getRequest(NotifyRequest.class); request.notifyByUuid(device, enable, serviceUUID, characteristicUUID, callback); } diff --git a/core/src/main/java/cn/com/heaton/blelibrary/ble/proxy/RequestListener.java b/core/src/main/java/cn/com/heaton/blelibrary/ble/proxy/RequestListener.java index 0e68eb3..a67b71f 100644 --- a/core/src/main/java/cn/com/heaton/blelibrary/ble/proxy/RequestListener.java +++ b/core/src/main/java/cn/com/heaton/blelibrary/ble/proxy/RequestListener.java @@ -1,10 +1,9 @@ package cn.com.heaton.blelibrary.ble.proxy; -import java.util.List; import java.util.UUID; import cn.com.heaton.blelibrary.ble.callback.BleConnectCallback; import cn.com.heaton.blelibrary.ble.callback.BleMtuCallback; -import cn.com.heaton.blelibrary.ble.callback.BleNotiftCallback; +import cn.com.heaton.blelibrary.ble.callback.BleNotiyCallback; import cn.com.heaton.blelibrary.ble.callback.BleReadCallback; import cn.com.heaton.blelibrary.ble.callback.BleReadRssiCallback; import cn.com.heaton.blelibrary.ble.callback.BleScanCallback; @@ -27,13 +26,13 @@ public interface RequestListener { boolean connect(String address, BleConnectCallback callback); - void notify(T device, BleNotiftCallback callback); + void notify(T device, BleNotiyCallback callback); - void cancelNotify(T device, BleNotiftCallback callback); + void cancelNotify(T device, BleNotiyCallback callback); - void enableNotify(T device, boolean enable, BleNotiftCallback callback); + void enableNotify(T device, boolean enable, BleNotiyCallback callback); - void enableNotifyByUuid(T device, boolean enable, UUID serviceUUID, UUID characteristicUUID, BleNotiftCallback callback); + void enableNotifyByUuid(T device, boolean enable, UUID serviceUUID, UUID characteristicUUID, BleNotiyCallback callback); void disconnect(T device); diff --git a/core/src/main/java/cn/com/heaton/blelibrary/ble/request/ConnectRequest.java b/core/src/main/java/cn/com/heaton/blelibrary/ble/request/ConnectRequest.java index 5123b1d..5bedded 100644 --- a/core/src/main/java/cn/com/heaton/blelibrary/ble/request/ConnectRequest.java +++ b/core/src/main/java/cn/com/heaton/blelibrary/ble/request/ConnectRequest.java @@ -134,8 +134,8 @@ public void cancelConnectings(List devices){ */ public void disconnect(String address){ //Traverse the connected device collection to disconnect automatically cancel the automatic connection - ArrayList connetedDevices = getConnectedDevices(); - for (T bleDevice : connetedDevices) { + ArrayList connectedDevices = getConnectedDevices(); + for (T bleDevice : connectedDevices) { if (bleDevice.getBleAddress().equals(address)) { bleDevice.setAutoConnect(false); } diff --git a/core/src/main/java/cn/com/heaton/blelibrary/ble/request/NotifyRequest.java b/core/src/main/java/cn/com/heaton/blelibrary/ble/request/NotifyRequest.java index db39b66..78b3af5 100644 --- a/core/src/main/java/cn/com/heaton/blelibrary/ble/request/NotifyRequest.java +++ b/core/src/main/java/cn/com/heaton/blelibrary/ble/request/NotifyRequest.java @@ -1,6 +1,5 @@ package cn.com.heaton.blelibrary.ble.request; -import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGattCharacteristic; import java.util.UUID; @@ -10,7 +9,7 @@ import cn.com.heaton.blelibrary.ble.callback.wrapper.BleWrapperCallback; import cn.com.heaton.blelibrary.ble.model.BleDevice; import cn.com.heaton.blelibrary.ble.annotation.Implement; -import cn.com.heaton.blelibrary.ble.callback.BleNotiftCallback; +import cn.com.heaton.blelibrary.ble.callback.BleNotiyCallback; import cn.com.heaton.blelibrary.ble.callback.wrapper.NotifyWrapperCallback; /** @@ -20,27 +19,27 @@ public class NotifyRequest implements NotifyWrapperCallback { private static final String TAG = "NotifyRequest"; - private BleNotiftCallback notiftCallback; + private BleNotiyCallback notiftCallback; private BleWrapperCallback bleWrapperCallback; protected NotifyRequest() { bleWrapperCallback = Ble.options().bleWrapperCallback; } - public void notify(T device, boolean enable, BleNotiftCallback callback) { + public void notify(T device, boolean enable, BleNotiyCallback callback) { notiftCallback = callback; BleRequestImpl bleRequest = BleRequestImpl.getBleRequest(); bleRequest.setCharacteristicNotification(device.getBleAddress(), enable); } - public void notifyByUuid(T device, boolean enable, UUID serviceUUID, UUID characteristicUUID, BleNotiftCallback callback) { + public void notifyByUuid(T device, boolean enable, UUID serviceUUID, UUID characteristicUUID, BleNotiyCallback callback) { notiftCallback = callback; BleRequestImpl bleRequest = BleRequestImpl.getBleRequest(); bleRequest.setCharacteristicNotificationByUuid(device.getBleAddress(),enable, serviceUUID, characteristicUUID); } @Deprecated - public void cancelNotify(T device, BleNotiftCallback callback) { + public void cancelNotify(T device, BleNotiyCallback callback) { notiftCallback = callback; BleRequestImpl bleRequest = BleRequestImpl.getBleRequest(); bleRequest.setCharacteristicNotification(device.getBleAddress(), false); diff --git a/core/src/main/java/cn/com/heaton/blelibrary/ble/request/WriteRequest.java b/core/src/main/java/cn/com/heaton/blelibrary/ble/request/WriteRequest.java index a816c2e..82285a7 100644 --- a/core/src/main/java/cn/com/heaton/blelibrary/ble/request/WriteRequest.java +++ b/core/src/main/java/cn/com/heaton/blelibrary/ble/request/WriteRequest.java @@ -177,7 +177,7 @@ public void onWriteSuccess(T device, BluetoothGattCharacteristic characteristic) @Override public void onWriteFailed(T device, int failedCode) { if(bleWriteCallback != null){ - bleWriteCallback.onWiteFailed(device, failedCode); + bleWriteCallback.onWriteFailed(device, failedCode); } if (bleWrapperCallback != null){ diff --git a/java-sample/build.gradle b/java-sample/build.gradle index 17fb57e..9013f05 100644 --- a/java-sample/build.gradle +++ b/java-sample/build.gradle @@ -7,8 +7,8 @@ android { applicationId "com.example.admin.mybledemo" minSdkVersion 19 targetSdkVersion 28 - versionCode 15 - versionName "3.0.5" + versionCode 16 + versionName "3.1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" vectorDrawables.useSupportLibrary = true } diff --git a/java-sample/src/main/java/com/example/admin/mybledemo/MyApplication.java b/java-sample/src/main/java/com/example/admin/mybledemo/MyApplication.java index c244c75..85ac5c0 100644 --- a/java-sample/src/main/java/com/example/admin/mybledemo/MyApplication.java +++ b/java-sample/src/main/java/com/example/admin/mybledemo/MyApplication.java @@ -84,6 +84,8 @@ private void initBle() { .setScanFilter(scanFilter) .setUuidService(UUID.fromString(UuidUtils.uuid16To128("fd00")))//设置主服务的uuid .setUuidWriteCha(UUID.fromString(UuidUtils.uuid16To128("fd01")))//设置可写特征的uuid +// .setUuidReadCha(UUID.fromString(UuidUtils.uuid16To128("fd02")))//设置可读特征的uuid (选填) + .setUuidNotifyCha(UUID.fromString(UuidUtils.uuid16To128("fd03")))//设置可通知特征的uuid (选填,库中默认已匹配可通知特征的uuid) .setFactory(new BleFactory() {//实现自定义BleDevice时必须设置 @Override public BleRssiDevice create(String address, String name) { diff --git a/java-sample/src/main/java/com/example/admin/mybledemo/Test.java b/java-sample/src/main/java/com/example/admin/mybledemo/Test.java index 14fbaae..d7ac8b5 100644 --- a/java-sample/src/main/java/com/example/admin/mybledemo/Test.java +++ b/java-sample/src/main/java/com/example/admin/mybledemo/Test.java @@ -75,7 +75,7 @@ public void onWriteSuccess(BleDevice device, BluetoothGattCharacteristic charact } @Override - public void onWiteFailed(BleDevice device, int failedCode) { + public void onWriteFailed(BleDevice device, int failedCode) { Log.e(TAG, "onWiteFailed: " + failedCode); } }); diff --git a/java-sample/src/main/java/com/example/admin/mybledemo/adapter/ChildAdapter.java b/java-sample/src/main/java/com/example/admin/mybledemo/adapter/ChildAdapter.java index 335e19d..fa3ff32 100644 --- a/java-sample/src/main/java/com/example/admin/mybledemo/adapter/ChildAdapter.java +++ b/java-sample/src/main/java/com/example/admin/mybledemo/adapter/ChildAdapter.java @@ -26,7 +26,7 @@ import java.util.UUID; import cn.com.heaton.blelibrary.ble.Ble; -import cn.com.heaton.blelibrary.ble.callback.BleNotiftCallback; +import cn.com.heaton.blelibrary.ble.callback.BleNotiyCallback; import cn.com.heaton.blelibrary.ble.callback.BleReadCallback; import cn.com.heaton.blelibrary.ble.callback.BleReadDescCallback; import cn.com.heaton.blelibrary.ble.callback.BleWriteCallback; @@ -111,7 +111,7 @@ public void onClick(View v) { enable, serviceUuid, characteristicUuid, - new BleNotiftCallback() { + new BleNotiyCallback() { @Override public void onChanged(BleDevice device, BluetoothGattCharacteristic characteristic) { ThreadUtils.ui(new Runnable() { @@ -323,8 +323,8 @@ public void onWriteSuccess(BleDevice device, BluetoothGattCharacteristic charact } @Override - public void onWiteFailed(BleDevice device, int failedCode) { - super.onWiteFailed(device, failedCode); + public void onWriteFailed(BleDevice device, int failedCode) { + super.onWriteFailed(device, failedCode); toast("写入特征失败:"+failedCode); } }); diff --git a/java-sample/src/main/java/com/example/admin/mybledemo/ui/BleActivity.java b/java-sample/src/main/java/com/example/admin/mybledemo/ui/BleActivity.java index f6fad6b..78e3c34 100644 --- a/java-sample/src/main/java/com/example/admin/mybledemo/ui/BleActivity.java +++ b/java-sample/src/main/java/com/example/admin/mybledemo/ui/BleActivity.java @@ -5,6 +5,7 @@ import android.animation.ValueAnimator; import android.app.Activity; import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothGattCharacteristic; import android.content.Intent; import android.os.Build; import android.os.Bundle; @@ -38,9 +39,13 @@ import cn.com.heaton.blelibrary.ble.Ble; import cn.com.heaton.blelibrary.ble.BleLog; +import cn.com.heaton.blelibrary.ble.callback.BleConnectCallback; +import cn.com.heaton.blelibrary.ble.callback.BleReadCallback; import cn.com.heaton.blelibrary.ble.callback.BleScanCallback; import cn.com.heaton.blelibrary.ble.callback.BleStatusCallback; +import cn.com.heaton.blelibrary.ble.callback.BleWriteCallback; import cn.com.heaton.blelibrary.ble.model.ScanRecord; +import cn.com.heaton.blelibrary.ble.queue.RequestTask; import cn.com.heaton.blelibrary.ble.utils.BleUtils; import cn.com.superLei.aoparms.annotation.Permission; import cn.com.superLei.aoparms.annotation.PermissionDenied; @@ -75,6 +80,9 @@ protected void onCreate(@Nullable Bundle savedInstanceState) { initLinsenter(); initBleStatus(); requestPermission(); + + + } @Permission(value = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, @@ -215,6 +223,9 @@ private void rescan() { adapter.notifyDataSetChanged(); ble.startScan(scanCallback); } + + + } private BleScanCallback scanCallback = new BleScanCallback() { diff --git a/java-sample/src/main/java/com/example/admin/mybledemo/ui/DeviceInfoActivity.java b/java-sample/src/main/java/com/example/admin/mybledemo/ui/DeviceInfoActivity.java index b1f8dc1..92fbc88 100644 --- a/java-sample/src/main/java/com/example/admin/mybledemo/ui/DeviceInfoActivity.java +++ b/java-sample/src/main/java/com/example/admin/mybledemo/ui/DeviceInfoActivity.java @@ -1,6 +1,7 @@ package com.example.admin.mybledemo.ui; import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattService; import android.os.Bundle; import android.support.annotation.Nullable; @@ -17,10 +18,14 @@ import com.example.admin.mybledemo.adapter.DeviceInfoAdapter; import java.util.ArrayList; import java.util.List; +import java.util.UUID; import cn.com.heaton.blelibrary.ble.Ble; +import cn.com.heaton.blelibrary.ble.BleLog; import cn.com.heaton.blelibrary.ble.callback.BleConnectCallback; +import cn.com.heaton.blelibrary.ble.callback.BleNotiyCallback; import cn.com.heaton.blelibrary.ble.model.BleDevice; +import cn.com.heaton.blelibrary.ble.utils.ByteUtils; public class DeviceInfoActivity extends AppCompatActivity { @@ -114,7 +119,7 @@ public void run() { public void onReady(BleDevice device) { super.onReady(device); //连接成功后,设置通知 - /*ble.enableNotify(device, true, new BleNotiftCallback() { + ble.enableNotify(device, true, new BleNotiyCallback() { @Override public void onChanged(BleDevice device, BluetoothGattCharacteristic characteristic) { UUID uuid = characteristic.getUuid(); @@ -133,7 +138,7 @@ public void onNotifySuccess(BleDevice device) { super.onNotifySuccess(device); BleLog.e(TAG, "onNotifySuccess: "+device.getBleName()); } - });*/ + }); } }; diff --git a/kotlin-sample/src/main/java/com/i502tech/appkotlin/AppProtocol.kt b/kotlin-sample/src/main/java/com/i502tech/appkotlin/AppProtocol.kt index 39fadf8..11d1bb9 100644 --- a/kotlin-sample/src/main/java/com/i502tech/appkotlin/AppProtocol.kt +++ b/kotlin-sample/src/main/java/com/i502tech/appkotlin/AppProtocol.kt @@ -20,7 +20,7 @@ object AppProtocol { BleLog.w(TAG, "onWriteSuccess: ") } - override fun onWiteFailed(device: BleDevice?, failedCode: Int) { + override fun onWriteFailed(device: BleDevice?, failedCode: Int) { BleLog.e(TAG, "onWiteFailed:$failedCode") } diff --git a/kotlin-sample/src/main/java/com/i502tech/appkotlin/MainActivity.kt b/kotlin-sample/src/main/java/com/i502tech/appkotlin/MainActivity.kt index 6946213..b374205 100644 --- a/kotlin-sample/src/main/java/com/i502tech/appkotlin/MainActivity.kt +++ b/kotlin-sample/src/main/java/com/i502tech/appkotlin/MainActivity.kt @@ -209,8 +209,8 @@ class MainActivity : AppCompatActivity() { } } - private fun bleNotifyCallback(): BleNotiftCallback { - return object : BleNotiftCallback(){ + private fun bleNotifyCallback(): BleNotiyCallback { + return object : BleNotiyCallback(){ override fun onChanged(device: BleDevice?, characteristic: BluetoothGattCharacteristic?) { BleLog.i("收到硬件数据>>>>>onChanged:",ByteUtils.toHexString(characteristic?.value)) }