Commit b2651c89 authored by 18600395998's avatar 18600395998

蓝牙连接调试---1

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