Commit b2651c89 authored by 18600395998's avatar 18600395998

蓝牙连接调试---1

parent eb31d95b
...@@ -58,6 +58,12 @@ android { ...@@ -58,6 +58,12 @@ android {
storePassword '111111' storePassword '111111'
} }
} }
sourceSets {
main {
jniLibs.srcDirs = ['libs']
}
}
} }
flutter { flutter {
...@@ -65,5 +71,5 @@ flutter { ...@@ -65,5 +71,5 @@ flutter {
} }
dependencies { dependencies {
implementation files('libs\\uhf.jar') implementation files('libs/uhf.jar')
} }
No preview for this file type
No preview for this file type
No preview for this file type
...@@ -7,57 +7,16 @@ import android.os.Bundle; ...@@ -7,57 +7,16 @@ import android.os.Bundle;
import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodCall;
import io.flutter.embedding.engine.FlutterEngine; import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity { public class MainActivity extends FlutterActivity {
// 通道名称
protected String channel = "通道名称";
// 获取推送,发给flutter
protected String payLoad = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 获取自定义透传参数值
Intent intent = getIntent();
if (intent != null) {
payLoad = intent.getStringExtra("payload");
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// 获取自定义透传参数值
if (intent != null) {
payLoad = intent.getStringExtra("payload");
}
}
@Override @Override
public void configureFlutterEngine(FlutterEngine flutterEngine) { public void configureFlutterEngine(FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine); super.configureFlutterEngine(flutterEngine);
payLoad = getIntent().getStringExtra("payload"); flutterEngine.getPlugins().add(new RfidPlugin());
GeneratedPluginRegistrant.registerWith(flutterEngine);
try {
// 通过MethodChannel调用通知flutter开启参数
new MethodChannel(
flutterEngine.getDartExecutor().getBinaryMessenger(),
channel
).setMethodCallHandler(new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
if (call.method.equals("getIntentData")) {
result.success(payLoad);
}
}
});
} catch (Exception err) {}
} }
} }
......
package com.phlx.anchor_collect_flutter; package com.phlx.anchor_collect_flutter;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import com.uhf.linkage.Linkage; import com.uhf.linkage.Linkage;
import com.uhf.structures.InventoryData; import com.uhf.structures.InventoryData;
import com.uhf.structures.OnBluetoothListener; import com.uhf.structures.OnBluetoothListener;
import com.uhf.structures.OnInventoryListener; import com.uhf.structures.OnInventoryListener;
import com.uhf.structures.Rfid_Value; import com.uhf.structures.Rfid_Value;
import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.EventChannel; import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodCall;
...@@ -19,12 +28,15 @@ import io.flutter.plugin.common.MethodChannel; ...@@ -19,12 +28,15 @@ import io.flutter.plugin.common.MethodChannel;
/** /**
* rfid插件 * rfid插件
*/ */
public class RfidPlugin implements FlutterPlugin, MethodChannel.MethodCallHandler public class RfidPlugin implements FlutterPlugin, MethodChannel.MethodCallHandler, OnBluetoothListener, OnInventoryListener {
, OnBluetoothListener, OnInventoryListener {
private MethodChannel _methodChannel; private MethodChannel _methodChannel;
private Linkage link; private Linkage link;
private Handler handler;
private ConnectManger connectManger;
// 事件派发对象 // 事件派发对象
private EventChannel.EventSink _eventSink; private EventChannel.EventSink _eventSink;
...@@ -40,15 +52,23 @@ public class RfidPlugin implements FlutterPlugin, MethodChannel.MethodCallHandle ...@@ -40,15 +52,23 @@ public class RfidPlugin implements FlutterPlugin, MethodChannel.MethodCallHandle
} }
}; };
RfidPlugin() {
connectManger = ConnectManger.from(getLinkage());
getLinkage().setOnBluetoothListener(this);
}
@Override @Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) { public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
_methodChannel = new MethodChannel(binding.getBinaryMessenger(), "flutter_rfid_plugin"); _methodChannel = new MethodChannel(binding.getBinaryMessenger(), "flutter_rfid_plugin");
_methodChannel.setMethodCallHandler(this); _methodChannel.setMethodCallHandler(this);
EventChannel channel = new EventChannel(binding.getBinaryMessenger(), "flutter_rfid_plugin/event"); EventChannel channel = new EventChannel(binding.getBinaryMessenger(), "flutter_rfid_plugin/event");
channel.setStreamHandler(_streamHandler); channel.setStreamHandler(_streamHandler);
// 创建 Handler,关联到主线程的 Looper
handler = new Handler(Looper.getMainLooper());
} }
@Override @Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
_methodChannel.setMethodCallHandler(null); _methodChannel.setMethodCallHandler(null);
...@@ -57,36 +77,26 @@ public class RfidPlugin implements FlutterPlugin, MethodChannel.MethodCallHandle ...@@ -57,36 +77,26 @@ public class RfidPlugin implements FlutterPlugin, MethodChannel.MethodCallHandle
@Override @Override
public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) { public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
switch (call.method) { if (call.method.equals("init_rfid")) {
case "init_rfid": initModule();
initModule(); } else if (call.method.equals("get_version")) {
break; String rm70xxVersion = connectManger.getRm70xxVersion();
case "get_version": result.success(rm70xxVersion);
Rfid_Value version_value = new Rfid_Value();
byte[] versionData = getLinkage().getVersion(version_value); } else if (call.method.equals("start_inventory")) {
String version = ""; /**
if (version_value.value == 0) { * 下发盘点指令
version = new String(versionData); *
} else { * @param mode 盘点模式:0-单次盘点,1-高速盘点,2-低功耗盘点 默认高速盘点
version = "" + version_value.value; * @param status 掩码状态 0-禁用,1-启用
} */
result.success(version); getLinkage().startInventory(1, 0);
break; } else if (call.method.equals("stop_inventory")) {
case "start_inventory": getLinkage().stopInventory();
/** } else if (call.method.equals("push_data")) {
* 下发盘点指令 byte[] pushData = call.argument("value");
* Log.e("push", pushData.length + "----->" + Arrays.toString(pushData));
* @param mode 盘点模式:0-单次盘点,1-高速盘点,2-低功耗盘点 默认高速盘点 getLinkage().pushRemoteRFIDData(call.argument("value"));
* @param status 掩码状态 0-禁用,1-启用
*/
getLinkage().startInventory(1, 0);
break;
case "stop_inventory":
getLinkage().stopInventory();
break;
case "push_data":
getLinkage().pushRemoteRFIDData(call.argument("value"));
break;
} }
} }
...@@ -102,16 +112,20 @@ public class RfidPlugin implements FlutterPlugin, MethodChannel.MethodCallHandle ...@@ -102,16 +112,20 @@ public class RfidPlugin implements FlutterPlugin, MethodChannel.MethodCallHandle
link = new Linkage(); link = new Linkage();
link.initRFID(); link.initRFID();
} }
return link; return link;
} }
@Override @Override
public void getBluetoothData(byte[] bytes) { public void getBluetoothData(byte[] bytes) {
Map result = new HashMap();
result.put("key", "BluetoothData"); // 在主线程上执行 UI 操作
result.put("value", bytes); handler.post(() -> {
_eventSink.success(result); Map<String, Object> result = new HashMap<>();
result.put("key", "BluetoothData");
//Log.e("Data:Send", bytes.length + "<--" + Arrays.toString(bytes));
result.put("value", bytes);
_eventSink.success(result);
});
} }
@Override @Override
......
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
#include "Generated.xcconfig" #include "Generated.xcconfig"
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
#include "Generated.xcconfig" #include "Generated.xcconfig"
...@@ -7,6 +7,8 @@ class Config { ...@@ -7,6 +7,8 @@ class Config {
static String baseUrl = ""; static String baseUrl = "";
static String version = "";
static bool isOnLine = false; static bool isOnLine = false;
// 定义一个全局的相机列表 // 定义一个全局的相机列表
......
...@@ -9,6 +9,7 @@ import 'package:flutter_blue_plus/flutter_blue_plus.dart'; ...@@ -9,6 +9,7 @@ import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart'; import 'package:permission_handler/permission_handler.dart';
import '../congifs.dart';
import '../rfid/rfid_plugin.dart'; import '../rfid/rfid_plugin.dart';
typedef void DiscoveredCallback(args); typedef void DiscoveredCallback(args);
...@@ -33,7 +34,8 @@ class BleService extends GetxService { ...@@ -33,7 +34,8 @@ class BleService extends GetxService {
late StreamSubscription<List<ScanResult>> _scanResultsSubscription; late StreamSubscription<List<ScanResult>> _scanResultsSubscription;
late StreamSubscription<bool> _isScanningSubscription; late StreamSubscription<bool> _isScanningSubscription;
late StreamSubscription<BluetoothConnectionState> _connectionStateSubscription; late StreamSubscription<BluetoothConnectionState>
_connectionStateSubscription;
late StreamSubscription<List<int>> _lastValueSubscription; late StreamSubscription<List<int>> _lastValueSubscription;
late StreamSubscription<List<int>> _valueReceivedSubscription; late StreamSubscription<List<int>> _valueReceivedSubscription;
...@@ -44,8 +46,7 @@ class BleService extends GetxService { ...@@ -44,8 +46,7 @@ class BleService extends GetxService {
}); });
_scanResultsSubscription = FlutterBluePlus.scanResults.listen((results) { _scanResultsSubscription = FlutterBluePlus.scanResults.listen((results) {
// List<ScanResult> tempList = List.from(results); // for (var element in results) {
// for (var element in tempList) {
// if (!EmptyUtils.isStrNotEmpty(element.device.platformName)) { // if (!EmptyUtils.isStrNotEmpty(element.device.platformName)) {
// tempList.remove(element); // tempList.remove(element);
// } // }
...@@ -83,7 +84,9 @@ class BleService extends GetxService { ...@@ -83,7 +84,9 @@ class BleService extends GetxService {
// so instead we only ask for 1/8 of them // so instead we only ask for 1/8 of them
int divisor = Platform.isAndroid ? 8 : 1; int divisor = Platform.isAndroid ? 8 : 1;
await FlutterBluePlus.startScan( await FlutterBluePlus.startScan(
timeout: const Duration(seconds: 15), continuousUpdates: true, continuousDivisor: divisor); timeout: const Duration(seconds: 15),
continuousUpdates: true,
continuousDivisor: divisor);
} catch (e) { } catch (e) {
DialogUtils.showToast('扫描错误'); DialogUtils.showToast('扫描错误');
} }
...@@ -101,6 +104,8 @@ class BleService extends GetxService { ...@@ -101,6 +104,8 @@ class BleService extends GetxService {
isScanning.value = false; isScanning.value = false;
} }
bool isFirst = false;
// 连接设备 // 连接设备
Future<void> connectToDevice(int index, ConnectCallback callback) async { Future<void> connectToDevice(int index, ConnectCallback callback) async {
connectCallback = callback; connectCallback = callback;
...@@ -111,49 +116,42 @@ class BleService extends GetxService { ...@@ -111,49 +116,42 @@ class BleService extends GetxService {
isScanning.value = false; // 设置 isScanning 为 false isScanning.value = false; // 设置 isScanning 为 false
DialogUtils.showLoadingDialog('正在连接到 ${selectedDevice.advName}'); DialogUtils.showLoadingDialog('正在连接到 ${selectedDevice.advName}');
_connectionStateSubscription = selectedDevice.connectionState.listen((BluetoothConnectionState state) async { _connectionStateSubscription = selectedDevice.connectionState
.listen((BluetoothConnectionState state) async {
if (state == BluetoothConnectionState.disconnected) { if (state == BluetoothConnectionState.disconnected) {
isConnect = false; isConnect = false;
if (kDebugMode) {
print("${selectedDevice.disconnectReason!.code} ${selectedDevice.disconnectReason!.description}");
}
} else if (state == BluetoothConnectionState.connected) { } else if (state == BluetoothConnectionState.connected) {
if (Platform.isAndroid) { if (Platform.isAndroid) {
await selectedDevice.requestMtu(512); await selectedDevice.requestMtu(512);
} }
List<BluetoothService> services = await selectedDevice.discoverServices(); List<BluetoothService> services =
await selectedDevice.discoverServices();
services.forEach((service) { services.forEach((service) {
//打印所有服务的 uuid
if (kDebugMode) {
print('service uuid: ${service.uuid}');
}
if (!service.serviceUuid.toString().contains('000180')) { if (!service.serviceUuid.toString().contains('000180')) {
selectService = service; selectService = service;
//打印 service uuid
if (kDebugMode) {
print('service 000180 uuid: ${service.uuid}');
}
var characteristics = service.characteristics; var characteristics = service.characteristics;
for (BluetoothCharacteristic c in characteristics) { for (BluetoothCharacteristic c in characteristics) {
if (c.properties.write) { if (c.properties.write) {
//打印写的特征值 uuid
if (kDebugMode) {
print('write characteristic uuid: ${c.uuid}');
}
_writeCharacteristic = c; _writeCharacteristic = c;
} }
if (c.properties.notify) { if (c.properties.notify) {
//打印通知的特征值 uuid
if (kDebugMode) {
print('notify characteristic uuid: ${c.uuid}');
}
_notifyCharacteristic = c; _notifyCharacteristic = c;
c.setNotifyValue(true); c.setNotifyValue(true);
// _lastValueSubscription = c.lastValueStream.listen((value) { _valueReceivedSubscription =
// print(value); c.onValueReceived.listen((value) async {
// }); if (value.isNotEmpty) {
_valueReceivedSubscription = c.onValueReceived.listen((value) { if (!isFirst) {
isFirst = true;
RfidPlugin.getVersion().then((value) {
Config.version=value;
print('Version: $value');
});
}
}
if (value.isEmpty) return;
RfidPlugin.pushRemoteRFIDData(value); RfidPlugin.pushRemoteRFIDData(value);
}); });
} }
...@@ -181,11 +179,7 @@ class BleService extends GetxService { ...@@ -181,11 +179,7 @@ class BleService extends GetxService {
// 写入数据 // 写入数据
Future<void> writeData(List<int> data) async { Future<void> writeData(List<int> data) async {
// if (selectedDevice == null) { await _writeCharacteristic.write(data);
// throw Exception('No device connected');
// }
await _writeCharacteristic.write(data, allowLongWrite: true);
} }
// 检查权限 // 检查权限
......
...@@ -47,6 +47,8 @@ Future<void> initServices() async { ...@@ -47,6 +47,8 @@ Future<void> initServices() async {
RfidPlugin(); RfidPlugin();
RfidPlugin.initRfid();
print('All services started...'); print('All services started...');
} }
......
import 'dart:core';
import 'package:anchor_collect_flutter/controllers/ble_service.dart'; import 'package:anchor_collect_flutter/controllers/ble_service.dart';
import 'package:anchor_collect_flutter/routes/routes.dart'; import 'package:anchor_collect_flutter/routes/routes.dart';
import 'package:anchor_collect_flutter/utils/dialog_utils.dart'; import 'package:anchor_collect_flutter/utils/dialog_utils.dart';
...@@ -5,6 +7,7 @@ import 'package:flutter/cupertino.dart'; ...@@ -5,6 +7,7 @@ import 'package:flutter/cupertino.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart'; import 'package:permission_handler/permission_handler.dart';
import '../../rfid/rfid_plugin.dart';
import 'setting_state.dart'; import 'setting_state.dart';
class SettingLogic extends GetxController { class SettingLogic extends GetxController {
...@@ -30,9 +33,10 @@ class SettingLogic extends GetxController { ...@@ -30,9 +33,10 @@ class SettingLogic extends GetxController {
if (BleService.to.isConnect) { if (BleService.to.isConnect) {
BleService.to.stopScan(); BleService.to.stopScan();
} }
BleService.to.connectToDevice(index, (args) { BleService.to.connectToDevice(index, (args) async {
BleService.to.isConnect = true; BleService.to.isConnect = true;
DialogUtils.showToast('蓝牙设备连接成功');
//DialogUtils.showToast('蓝牙设备连接成功:$versionStr');
// DialogUtils.dismissDialog(); // DialogUtils.dismissDialog();
Get.back(); Get.back();
}); });
......
...@@ -3,15 +3,18 @@ import 'dart:async'; ...@@ -3,15 +3,18 @@ import 'dart:async';
import 'package:anchor_collect_flutter/utils/empty_utils.dart'; import 'package:anchor_collect_flutter/utils/empty_utils.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:isar/isar.dart';
import '../controllers/ble_service.dart'; import '../controllers/ble_service.dart';
typedef void EventCallback(args, args2); typedef void EventCallback(args, args2);
class RfidPlugin { class RfidPlugin {
static const MethodChannel _methodChannel = MethodChannel('flutter_rfid_plugin'); static const MethodChannel _methodChannel =
MethodChannel('flutter_rfid_plugin');
static const EventChannel _eventChannel = EventChannel('flutter_rfid_plugin/event'); static const EventChannel _eventChannel =
EventChannel('flutter_rfid_plugin/event');
static EventCallback? _callback; static EventCallback? _callback;
...@@ -20,11 +23,16 @@ class RfidPlugin { ...@@ -20,11 +23,16 @@ class RfidPlugin {
static String rfidTagTemp = ''; static String rfidTagTemp = '';
RfidPlugin() { RfidPlugin() {
_streamSubscription = _eventChannel.receiveBroadcastStream().listen((event) async { _streamSubscription =
_eventChannel.receiveBroadcastStream().listen((event) async {
final Map<dynamic, dynamic> map = event; final Map<dynamic, dynamic> map = event;
switch (map['key']) { switch (map['key']) {
case 'BluetoothData': case 'BluetoothData':
await BleService.to.writeData(map['BluetoothData']); if (map['value'] != null) {
List<int> bluetoothData = map['value'];
print('Received Byte List: $bluetoothData');
await BleService.to.writeData(bluetoothData);
}
break; break;
case 'InventoryData': case 'InventoryData':
checkInventory(map['value'].toString()); checkInventory(map['value'].toString());
...@@ -55,7 +63,7 @@ class RfidPlugin { ...@@ -55,7 +63,7 @@ class RfidPlugin {
static Future<void> pushRemoteRFIDData(List<int> readData) async { static Future<void> pushRemoteRFIDData(List<int> readData) async {
// List<int> readData = await BleService.to.readData(); // List<int> readData = await BleService.to.readData();
Map params = { Map params = {
"value":readData, "value": Uint8List.fromList(readData),
}; };
await _methodChannel.invokeMethod('push_data', params); await _methodChannel.invokeMethod('push_data', params);
} }
...@@ -81,5 +89,4 @@ class RfidPlugin { ...@@ -81,5 +89,4 @@ class RfidPlugin {
_callback!(rfids[0] ?? "", rfids[1] ?? ""); _callback!(rfids[0] ?? "", rfids[1] ?? "");
} }
} }
} }
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
#include "ephemeral/Flutter-Generated.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig"
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
#include "ephemeral/Flutter-Generated.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig"
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment