flutter蓝牙插件
程序员文章站
2022-03-03 22:01:37
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档文章目录前言一、flutter_ble_plugin是什么?二、使用步骤1.引入库2.读入数据总结前言第一次开源,一个flutter蓝牙开发的小插件。背景:本人是做Android开发的,公司需要花了一个礼拜学习flutter,然后就开始开发了,先做了Android版本,后面又去学习了c,oc,然后再做iOS层,做完之后发现可以出一个蓝牙插件,所以有了这篇文章,这是我的第二篇文章,之前那篇关于Android逆向的被禁了!所以写文章我还是...
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
第一次开源,一个flutter蓝牙开发的小插件。背景:本人是做Android开发的,公司需要花了一个礼拜学习flutter,然后就开始开发了,先做了Android版本,后面又去学习了c,oc,然后再做iOS层,做完之后发现可以出一个蓝牙插件,所以有了这篇文章,这是我的第二篇文章,之前那篇关于Android逆向的被禁了!所以写文章我还是个新手,写的不好的地方请大家指出。
项目地址:[https://github.com/laoeg/flutter_ble_plugin]
一、flutter_ble_plugin是什么?
示例:flutter_ble_plugin是基于Android,ISO的蓝牙插件,提供扫描,连接,发送指令等一系列功能的插件。
二、使用步骤
1.引入库
代码如下(示例):
项目地址
下载项目源码到本地,
dependencies:
flutter_ble:
path: "项目本地路径"
2.读入数据
代码如下(示例):
//初始化
FlutterBle flutterBle = new FlutterBle();
// 设置需要连接的服务,读写特征值,描述(android必须,ios可以不传)
Flutter.initTarget("targetServiceUUID","targetWriteCharacriticUUID","targetReadCharariticUUID","DiscriptorUUID");
// 添加底层发送给flutter层的事件监听
flutterBle.setDeviceListener(this);
底层和上层通信的标识。
static const FOUND_DEVICES = 1;//搜索到蓝牙设备
static const START_SACN = 2;//开始扫描
static const STOP_SACN = 3;//开始扫描
static const STATE_CONNECTED=4;//蓝牙状态改变,连接上了蓝牙
static const STATE_DISCONNECTED=5;//蓝牙状态改变,蓝牙连接断开
static const GATT_SERVICES_DISCOVERED=6;//发现可用的蓝牙服务
static const DOES_NOT_SUPPORT_UART=7;//服务或特征值不可用
static const DATA_AVAILABLE=8;//收到蓝牙设备发送的数据
static const BLUETOOTHOFF=9;//蓝牙关闭通知
static const BLUETOOTHON=10;//蓝牙开启通知
static const STATE_RECONNECTED=11;//蓝牙状态改变,重连上了之前的蓝牙,不需要发现服务
flutter层事件,底层发送事件,flutter实现接口,然后的接口flutter就会响应。
abstract class DeviceListener {
void onScanStart() {}
void onFoundDevice(List<DeviceBle> devices) {}
void onScanStop() {}
void onConnectionStateChange(int status) {
print("flutter插件监听到蓝牙状态发送改变:" + (status == 4 ? "蓝牙连接上了" : "蓝牙断开了"));
}
void onReceivedDataListener(List<dynamic> byteData) {
print("插件接收到数据:" + byteData.toString());
}
void onServicesDiscovered() {}
void onServicesNotSupport() {}
void onBluetoothOff() {}
void onBluetoothOn() {}
void onReConnected() {}
}
Android端处理flutter端发送过来的事件。
// flutter调用原生Android处理方法
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
switch (call.method) {
case "getPlatformVersion":
result.success("Android " + android.os.Build.VERSION.RELEASE);
break;
case "isSupport":
result.success(isSupport());
break;
case "isEnabled":
result.success(isEnabled());
break;
case "startScanBluetooth":
result.success(startScanBluetooth());
break;
case "stopScanBluetooth":
stopScanBluetooth();
break;
case "connect":
connect(call.argument("address").toString());
break;
case "enabled":
enabled();
break;
case "disconnect":
disconnect();
break;
case "status":
result.success(status());
break;
case "isConnect":
result.success(isConnect());
break;
case "auth":
auth(call.argument("authCode").toString().getBytes());
break;
case "broadcastData":
broadcastData(call.argument("command").toString().getBytes());
break;
case "isCommanding":
result.success(mService.sendingStoredData);
break;
default:
result.notImplemented();
break;
}
}
}
IOS端处理flutter端发送过来的事件。
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
NSLog(@"handleMethodCall=======%@",call.method);
if ([@"getPlatformVersion" isEqualToString:call.method]) {
result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
}else if([@"initTargetUUID" isEqualToString:call.method]){
NSMutableDictionary* dic = call.arguments;
NSString* targetServiceUUID = [dic objectForKey:@"targetServiceUUID"];
NSString* targetWriteCharacriticUUID = [dic objectForKey:@"targetWriteCharacriticUUID"];
NSString* targetReadCharacriticUUID = [dic objectForKey:@"targetReadCharacriticUUID"];
_targetServiceUUID = targetServiceUUID;
_targetWriteCharacteristicUUID = targetWriteCharacriticUUID;
_targetreadCharacteristicUUID = targetReadCharacriticUUID;
}else if([@"isSupport" isEqualToString:call.method]){
return result([NSNumber numberWithBool:_isSupport?YES:NO]);
} else if([@"isEnabled" isEqualToString:call.method]){
return result([NSNumber numberWithBool:_isEnable?YES:NO]);
}else if([@"startScanBluetooth" isEqualToString:call.method]){
if(!_targetServiceUUID||!_targetWriteCharacteristicUUID||!_targetreadCharacteristicUUID){
NSLog(@"没有初始化目标服务UUID或目标写特征值或目标读特征值");
return;
}
//停止之前的连接
[_centralManager stopScan];
[_centralManager scanForPeripheralsWithServices:nil options:nil];
// 清空存储蓝牙设备的数组
peripheralDataArray = [[NSMutableArray alloc]init];
_eventSink([self sendEvent:START_SACN data:@"start scan ble"]);
//baby.scanForPeripherals().begin().stop(10);
return result([NSNumber numberWithBool:YES]);
}else if([@"stopScanBluetooth" isEqualToString:call.method]){
[_centralManager stopScan ];
if(![_centralManager isScanning]){
_eventSink([self sendEvent:STOP_SACN data:@"stop scan ble"]);
}
}else if([@"connect" isEqualToString:call.method]){
NSMutableDictionary* dic = call.arguments;
NSString* address = [dic objectForKey:@"address"];
NSLog(@"address:%@",address);
NSArray *peripherals = [peripheralDataArray valueForKey:@"peripheral"];
if(peripherals.count<=0){
NSLog(@"数组中没有数据");
if(!_targetServiceUUID||!_targetWriteCharacteristicUUID||!_targetreadCharacteristicUUID){
NSLog(@"没有初始化目标服务UUID或目标写特征值或目标读特征值");
return;
}
tempAddress = address;
//扫描查找uuid和tempAddress(重连地址)一样的蓝牙设备,找到后直接连接。不设置超时时间
[_centralManager stopScan];
[_centralManager scanForPeripheralsWithServices:nil options:nil];
return;
}else{
tempAddress = nil;
}
for (CBPeripheral* peripheral in peripherals) {
NSLog(@"ios 遍历数组,peripheral.name=%@",peripheral.name);
NSLog(@"ios 遍历数组,peripheral.identifier=%@",peripheral.identifier.UUIDString);
if([peripheral.identifier.UUIDString isEqualToString: address]){
NSLog(@"ios 在数组中找到了对应的peripheral=================");
[_centralManager stopScan];
[_centralManager connectPeripheral:peripheral options:nil];
_peripheral = peripheral;
_state = 1;
break;
}
}
}else if([@"disconnect" isEqualToString:call.method]){
if(_centralManager && _peripheral){
if(_isConnected){
[_centralManager cancelPeripheralConnection:_peripheral];
}
}else{
[_centralManager stopScan];
}
}else if([@"status" isEqualToString:call.method]){
return result([NSNumber numberWithBool:_state]);
}else if([@"isConnect" isEqualToString:call.method]){
return result([NSNumber numberWithBool:_isConnected?YES:NO]);
}else if([@"auth" isEqualToString:call.method]){
// 发送数据给蓝牙外设
NSMutableDictionary* dic = call.arguments;
NSString* authCode = [dic objectForKey:@"authCode"];
NSLog(@"authCode:%@",authCode);
//发送数据给蓝牙设备
[_peripheral writeValue:[authCode dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:_writeCharacteristic type:CBCharacteristicWriteWithoutResponse];
}else if([@"broadcastData" isEqualToString:call.method]){
NSMutableDictionary* dic = call.arguments;
NSString* command = [dic objectForKey:@"command"];
NSLog(@"command:%@",command);
[_peripheral writeValue:[command dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:_writeCharacteristic type:CBCharacteristicWriteWithoutResponse];
}else if([@"isCommanding" isEqualToString:call.method]){
//是否正在发送指令,不支持iso,支持安卓
return result([NSNumber numberWithBool:NO]);
}else {
result(FlutterMethodNotImplemented);
}
}
总结
写文章好难啊!!!有什么问题直接联系我把。QQ:2912842867。
本文地址:https://blog.csdn.net/weixin_39931106/article/details/108166273
上一篇: Android项目配置签名
推荐阅读
-
flash浏览器插件下载(自带flash的手机浏览器)
-
solidworks已经安装的motion插件却不能使用该怎么办?
-
ps cc怎么安装coolorus色轮插件?coolorus cc2017安装破解图文教程
-
Eclipse软件中怎么安装SVN插件?
-
小米蓝牙耳机发布 售价79元 6月18日10:00 开卖
-
jQuery插件实现非常实用的tab栏切换功能【案例】
-
详解基于canvas的视频遮罩插件
-
jQuery插件之validation插件
-
jQuery插件FusionCharts绘制的2D帕累托图效果示例【附demo源码】
-
PHP+ajaxfileupload+jcrop插件完美实现头像上传剪裁