蓝牙和上位机和非上位机的功能的适配
This commit is contained in:
@@ -16,6 +16,9 @@ class BleManager {
|
||||
BluetoothCharacteristic? _writeCharacteristic;
|
||||
BluetoothCharacteristic? _readCharacteristic;
|
||||
|
||||
/// 🔥 已连接设备的名称(连接时从扫描结果或设备属性保存,断开时清空)
|
||||
String? _connectedDeviceName;
|
||||
|
||||
/// 有状态的协议解析器(支持 BLE 分片)
|
||||
final ProtocolParser _parser = ProtocolParser();
|
||||
|
||||
@@ -52,11 +55,19 @@ class BleManager {
|
||||
bool get isConnected => _connectedDevice != null;
|
||||
BluetoothDevice? get connectedDevice => _connectedDevice;
|
||||
BluetoothDevice? get connectingDevice => _connectingDevice;
|
||||
|
||||
/// 🔥 获取已连接设备的名称(连接时缓存,断开后为 null)
|
||||
String? get connectedDeviceName => _connectedDeviceName;
|
||||
Stream<List<ScanResult>> get scanResults => _scanController.stream;
|
||||
Stream<BlePacket> get packetStream => _packetController.stream;
|
||||
Stream<BluetoothAdapterState> get adapterState =>
|
||||
FlutterBluePlus.adapterState;
|
||||
|
||||
/// 🔥 获取当前蓝牙扫描结果列表(供外部查询使用)
|
||||
List<ScanResult> getScanResults() {
|
||||
return _scanResults.values.toList();
|
||||
}
|
||||
|
||||
/// 连接状态变化流:连接成功时发出 device,断开时发出 null
|
||||
Stream<BluetoothDevice?> get connectionStream => _connectionController.stream;
|
||||
|
||||
@@ -241,6 +252,18 @@ class BleManager {
|
||||
|
||||
/// 连接设备,返回 null 表示成功,返回错误信息字符串表示失败
|
||||
Future<String?> connect(BluetoothDevice device) async {
|
||||
// 🔥 连接前先保存设备名(从扫描结果或设备属性中获取)
|
||||
final scanResult = _scanResults[device.remoteId];
|
||||
final advName = scanResult?.device.advName ?? '';
|
||||
final platformName = device.platformName;
|
||||
_connectedDeviceName = platformName.isNotEmpty
|
||||
? platformName
|
||||
: (advName.isNotEmpty ? advName : device.remoteId.toString());
|
||||
developer.log(
|
||||
'[BLE] 🔥 保存已连接设备名: $_connectedDeviceName',
|
||||
name: 'BleManager',
|
||||
);
|
||||
|
||||
// 标记正在连接,通知所有监听者
|
||||
_connectingDevice = device;
|
||||
_connectingController.add(device);
|
||||
@@ -328,6 +351,7 @@ class BleManager {
|
||||
void _onDeviceDisconnected() {
|
||||
_connectedDevice = null;
|
||||
_connectingDevice = null;
|
||||
_connectedDeviceName = null; // 🔥 清空已连接设备名
|
||||
_writeCharacteristic = null;
|
||||
_readCharacteristic = null;
|
||||
_negotiatedMtu = 23;
|
||||
|
||||
Reference in New Issue
Block a user