Flutter中蓝牙开发:flutter_blue_plus的应用理解
蓝牙的原理(基于flutter_blue_plus的理解)
设备
手机设备能够识别到两种蓝牙设备:
1.系统设备(手机系统连接或配对过的设备,类型为 BluetoothDevice
)
2.扫描设备(现时现地扫描到的设备,类型为ScanResult
)
扫描设备是会不断地向外发送广播数据来供手机发现,因此我们看ScanResult
:
dart
class ScanResult {
final BluetoothDevice device; //扫描到的蓝牙设备对象
final AdvertisementData advertisementData; //设备的广播数据包
final int rssi;
final DateTime timeStamp;
ScanResult({
required this.device,
required this.advertisementData,
required this.rssi,
required this.timeStamp,
});
}
其中就包含系统设备的类型BluetoothDevice
属性,而且还包括广播的AdvertisementData
属性;我们来简单看一下AdvertisementData
包含什么东西:
dart
class AdvertisementData {
final String advName;
final int? txPowerLevel;
final int? appearance; // not supported on iOS / macOS
final bool connectable;
final Map<int, List<int>> manufacturerData; // key: manufacturerId
final Map<Guid, List<int>> serviceData; // key: service guid
final List<Guid> serviceUuids;
AdvertisementData({
required this.advName,
required this.txPowerLevel,
required this.appearance,
required this.connectable,
required this.manufacturerData,
required this.serviceData,
required this.serviceUuids,
});
}
在广播数据类中简单包含蓝牙设备的信息,我们可以获取设备的电量以及设备支持的服务UUID
列表来帮助我们后期有过滤设备需求。
BluetoothDevice
类的属性和方法详见flutter_blue_plus
插件,代码太多了不好贴,简单来说我们后续的连接蓝牙设备以及蓝牙通信都是调用他其中的方法。因此不管是扫描到的设备或者是系统有记录的设备都能够点击进行连接,有点像手机蓝牙中的可用设备。所以系统设备能够帮助我们快速连接设备。
服务
在对蓝牙设备进行通信之前,作为新手通过看文章以及官方示例代码大致了解到了一些。我的理解:蓝牙设备(Device)通过发广播的形式,告诉手机其的存在。手机接收到广播后获取到设备的基本信息,然后建立连接。蓝牙设备本身对外提供了很多服务(Services),每个服务下又有很多特征值(Characteristics)(特征值有读、写、订阅的功能,其中订阅就是不断接收通知)这里举个水平仪的例子,水平仪的x,y不断变化就是通过通知把这个变化的值传给手机的;然后特征值下还有描述符(Descriptors),描述符同样也有读、写的功能,对描述符进行写可以操作特征值的是否订阅的功能,同时描述符还用来描述特征值。知道他们大致的关系就行,接下来BluetoothDevice
为我们提供了所有相关方法。
另外做了一个测试,在对水平仪的某个特征值进行写入十六进制(Hex)字符串后,能够切换水平仪的显示状态,更理解了蓝牙通信的作用。