Android开发蓝牙+NDK+JNI物联网集合

实战BLE蓝牙之数据收发

2017-07-24  本文已影响0人  枫雪狼情

BLE蓝牙用途越来越广泛,在开发安卓过程中或多或少接触到蓝牙,网上关于低功耗蓝牙的资料也非常多,今天我就来总结一下低功耗蓝牙的开发技巧,让大家少走弯路,不妥之处请大家斧正!

注意开启定位权限

BLE蓝牙收发demo
串口收发助手

BLE2540硬件和USB接口
demo界面
PC端串口助手 在我的电脑的属性>设备管理器中查看端口号这里是CMD3

DeviceScanActivity

这个类主要是扫描蓝牙然后或获取蓝牙的地址:

// 初始化蓝牙适配器。
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();

通过蓝牙适配器就可以扫描蓝牙了
mBluetoothAdapter.stopLeScan(mLeScanCallback);

//设备扫描回调。类似于普通蓝牙的广播接收扫描结果
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mLeDeviceListAdapter.addDevice(device,rssi,scanRecord);
mLeDeviceListAdapter.notifyDataSetChanged(); //刷新界面
}
});
}
};

可以看到上面回调当中有三个参数其中device为蓝牙设备,这里面包含蓝牙名称和蓝牙地址,rssi可以通过算出模糊的算出蓝牙直接的距离;

BleSppActivity

在这个类中包括启动服务和接收服务发送过来的广播,以及蓝牙的连接和对服务的什么周期管理;

启动服务
startService(new Intent(this, BluetoothLeService.class));

注册广播
registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter()); //注册广播

连接蓝牙
final boolean result = mBluetoothLeService.connect(mDeviceAddress); //连接蓝牙

可以看到连接蓝牙只需要蓝牙的地址就可以,通过调用服务中封装好的连接蓝牙方法就可以连接
蓝牙建立好连接,然后通过UUID的读写通道建立读写的关系就可以在广播处接受分发送数据到服务类中将数据发送或接收;

BluetoothLeService核心类

连接蓝牙
// 第二个参数: 如果为false,则直接立即连接。
// 如果为true,则等待远程设备可用时(在范围内,。。)连接。并不是断开后重新连接。
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
这里mGattCallback是蓝牙的BluetoothGattCallback的回调,这个回调中有几个重要方法,弄懂这几个方法那就弄懂了蓝牙。

在onServicesDiscovered中调用displayGattServices(getSupportedGattServices());会看到蓝牙设备的所有UUID通道

 private void displayGattServices(List<BluetoothGattService> gattServices) {
        if (gattServices == null)
            return;
        for (BluetoothGattService gattService : gattServices) {
            // -----Service的字段信息----//
            int type = gattService.getType();
            Log.d("print", "-->服务的 type:" + Utils.getServiceType(type));
            Log.d("print", "-->包括服务规模 size:" + gattService.getIncludedServices().size());
            Log.d("print","-->服务的 uuid:" + gattService.getUuid());
            // -----Characteristics的字段信息----//
            List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
            for (final BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                Log.d("print", "---->char uuid:" + gattCharacteristic.getUuid());
                int permission = gattCharacteristic.getPermissions();
                Log.d("print", "---->char permission:" + Utils.getCharPermission(permission));
                int property = gattCharacteristic.getProperties();
                Log.d("print","---->char property:" + Utils.getCharPropertie(property));
                byte[] data = gattCharacteristic.getValue();
                if (data != null && data.length > 0) {
                    Log.d("print", "---->char value:" + new String(data));
                }
                // -----Descriptors的字段信息----//
                List<BluetoothGattDescriptor> gattDescriptors = gattCharacteristic.getDescriptors();
                for (BluetoothGattDescriptor gattDescriptor : gattDescriptors) {
                    Log.d("print", "-------->desc uuid:" + gattDescriptor.getUuid());
                    int descPermission = gattDescriptor.getPermissions();
                    Log.d("print", "-------->desc permission:" + Utils.getDescPermission(descPermission));
                    byte[] desData = gattDescriptor.getValue();
                    if (desData != null && desData.length > 0) {
                        Log.d("print", "-------->desc value:" + new String(desData));
                    }
                }
            }
        }

    }```

![360截图20170704183235745.jpg](https://img.haomeiwen.com/i3983667/bc28dc818913e073.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

![![360截图20170704183301031.jpg](https://img.haomeiwen.com/i3983667/14dcebfd09400f9e.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
](https://img.haomeiwen.com/i3983667/590f83869bf1570d.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


### 看上面的每一个UUID都有不同的权限,READ,WRUTE,还有一个通知的权限;
### 如果说其中的UUID只有读的权限那么它只能读取了;


# BleSppGattAttributes

    public static String BLE_SPP_Service = "0000fff0-0000-1000-8000-00805f9b34fb";
    public static String BLE_SPP_Notify_Characteristic = "0000fff4-0000-1000-8000-00805f9b34fb";
    public static String  BLE_SPP_Write_Characteristic = "0000fff1-0000-1000-8000-00805f9b34fb";
    public static String  BLE_SPP_AT_Characteristic = "0000fee2-0000-1000-8000-00805f9b34fb";


这个类主要就是填写能够读写的UUID了,每个BLEapp的写法不同但原理都是一样的;通过UUID获取读写的通道,建立起数据收发,在收发的时候每一次只能发送20个字节,当发送100个字节时其实是发送五个次的,感兴趣的可以看看BLE数据包的结构;


在BleSppActivity接收数据的也是20个字节一次的接收,这里是把它放进字符串缓存中,接收和发送数据的格式多种多样有ASCII码 ,十六进制,字符串,甚至还有JSon,只要能读取到数据其他的就没什么问题了;

工作中用到的蓝牙远不止这些,上面的代码也是最基础的,运用到项目中是远远不够的,但上面的代码还是比较健全的,因为是谷歌官方的demo,实际项目中就会有很多奇特的功能了,比如说蓝牙自动连接,保存后台一直存活,直接在后台收发数据等等。。。
上一篇 下一篇

猜你喜欢

热点阅读