You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

122 lines
3.1 KiB

import 'dart:async';
import 'package:flutter/services.dart';
/// 经典蓝牙插件
class ClassicBluetooth {
static const MethodChannel _methodChannel =
MethodChannel('com.yunqiinnovation.classic_bluetooth/methods');
static const EventChannel _eventChannel =
EventChannel('com.yunqiinnovation.classic_bluetooth/events');
static Stream<BluetoothEvent>? _eventStream;
/// 获取已连接的蓝牙设备
static Future<List<BluetoothDevice>> getConnectedDevices() async {
final List<dynamic> devices =
await _methodChannel.invokeMethod('getConnectedDevices');
return devices.map((device) => BluetoothDevice.fromJson(device)).toList();
}
/// 检查蓝牙是否已启用
static Future<bool> isBluetoothEnabled() async {
return await _methodChannel.invokeMethod('isBluetoothEnabled');
}
/// 监听蓝牙事件(状态变化、设备连接/断开)
static Stream<BluetoothEvent> get events {
_eventStream ??= _eventChannel
.receiveBroadcastStream()
.map((dynamic event) => BluetoothEvent.fromJson(event))
.handleError((error) {
print('[ClassicBluetooth] 事件流错误: $error');
});
return _eventStream!;
}
}
/// 蓝牙设备模型
class BluetoothDevice {
final String name;
final String address;
final bool isActive;
BluetoothDevice({
required this.name,
required this.address,
this.isActive = false,
});
factory BluetoothDevice.fromJson(Map<dynamic, dynamic> json) {
return BluetoothDevice(
name: json['name'] as String,
address: json['address'] as String,
isActive: json['isActive'] == 'true',
);
}
Map<String, dynamic> toJson() {
return {
'name': name,
'address': address,
'isActive': isActive,
};
}
@override
String toString() =>
'BluetoothDevice(name: $name, address: $address, isActive: $isActive)';
}
/// 简化的蓝牙事件类
class BluetoothEvent {
/// 事件类型:stateChanged, deviceConnected, deviceDisconnected
final String type;
/// 蓝牙状态: on, off, turningOn, turningOff, unknown
final String? state;
/// 相关的蓝牙设备
final BluetoothDevice? device;
/// 事件发生时间
final DateTime timestamp;
BluetoothEvent({
required this.type,
this.state,
this.device,
required this.timestamp,
});
factory BluetoothEvent.fromJson(Map<dynamic, dynamic> json) {
final String type = json['type'] as String;
final timestamp =
DateTime.fromMillisecondsSinceEpoch(json['timestamp'] as int);
// 处理设备相关事件
BluetoothDevice? device;
if (json.containsKey('device')) {
device = BluetoothDevice.fromJson(json['device']);
}
return BluetoothEvent(
type: type,
state: json['state'] as String?,
device: device,
timestamp: timestamp,
);
}
@override
String toString() {
if (type == 'stateChanged') {
return 'BluetoothEvent(type: $type, state: $state)';
} else if (type == 'deviceConnected' || type == 'deviceDisconnected') {
return 'BluetoothEvent(type: $type, device: $device)';
} else {
return 'BluetoothEvent(type: $type)';
}
}
}