import 'dart:async'; import 'package:flutter/services.dart'; /// 经典蓝牙设备信息 class BluetoothDevice { /// 设备名称 final String name; /// 设备地址 final String address; /// 设备类型 final String type; /// 构造函数 BluetoothDevice({ required this.name, required this.address, required this.type, }); /// 从Map创建设备信息 factory BluetoothDevice.fromMap(Map map) { return BluetoothDevice( name: map['name'] as String? ?? '未知设备', address: map['address'] as String? ?? '', type: map['type'] as String? ?? '未知类型', ); } /// 转换为Map Map toMap() { return { 'name': name, 'address': address, 'type': type, }; } @override String toString() => '$name ($address) [$type]'; } /// 蓝牙事件 class BluetoothEvent { /// 事件类型 final String type; /// 时间戳 final int timestamp; /// 事件数据 final Map data; /// 构造函数 BluetoothEvent({ required this.type, required this.timestamp, required this.data, }); /// 从Map创建事件 factory BluetoothEvent.fromMap(Map map) { return BluetoothEvent( type: map['type'] as String, timestamp: map['timestamp'] as int, data: Map.from(map) ..remove('type') ..remove('timestamp'), ); } /// 获取关联的设备(如果有) BluetoothDevice? get device { if (data.containsKey('device')) { return BluetoothDevice.fromMap(Map.from(data['device'] as Map)); } return null; } /// 获取蓝牙状态(如果是状态变化事件) String? get bluetoothState { if (type == 'bluetoothStateChanged') { return data['state'] as String?; } return null; } } /// 经典蓝牙插件类 class ClassicBluetooth { static const MethodChannel _methodChannel = MethodChannel('com.yunqiinnovation.classic_bluetooth/methods'); static const EventChannel _eventChannel = EventChannel('com.yunqiinnovation.classic_bluetooth/events'); static Stream? _eventStream; /// 获取蓝牙事件流 static Stream get events { _eventStream ??= _eventChannel.receiveBroadcastStream() .map((dynamic event) => BluetoothEvent.fromMap(Map.from(event as Map))); return _eventStream!; } /// 获取当前连接的蓝牙设备 static Future> getConnectedDevices() async { final List devices = await _methodChannel.invokeMethod('getConnectedDevices'); return devices .map((device) => BluetoothDevice.fromMap(Map.from(device as Map))) .toList(); } /// 检查蓝牙是否启用 static Future isBluetoothEnabled() async { return await _methodChannel.invokeMethod('isBluetoothEnabled'); } }