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.
96 lines
2.9 KiB
96 lines
2.9 KiB
import 'package:get/get.dart';
|
|
|
|
import '/core/utils/logger.dart';
|
|
import '/data/models/user_Info.dart';
|
|
import '/data/services/ble_manager.dart';
|
|
import '/data/services/network/api.dart';
|
|
import '/routes/app_routes.dart';
|
|
|
|
/// 用户已绑定设备管理页:拉取用户绑定列表、解绑。
|
|
class MyDevicesController extends GetxController {
|
|
static const String _tag = 'MyDevicesController';
|
|
|
|
late final BleManager _bleManager;
|
|
|
|
/// 按设备类型分组的已绑定设备
|
|
final RxMap<int, List<UserDevice>> devicesByType =
|
|
<int, List<UserDevice>>{}.obs;
|
|
|
|
final RxBool isLoading = false.obs;
|
|
|
|
@override
|
|
void onInit() {
|
|
super.onInit();
|
|
_bleManager = Get.find<BleManager>();
|
|
_refreshFromUser();
|
|
Future.microtask(loadDevices);
|
|
}
|
|
|
|
/// 从服务端拉取最新的设备列表,并刷新 [User.instance.devices]。
|
|
Future<void> loadDevices() async {
|
|
if (!User.isLoggedIn()) return;
|
|
isLoading.value = true;
|
|
try {
|
|
final response = await Api.getdevices();
|
|
if (response != null) {
|
|
final list = response['devices'] as List<dynamic>?;
|
|
if (list != null) {
|
|
User.instance.devices = list
|
|
.map((e) => UserDevice.fromJson(e as Map<String, dynamic>))
|
|
.toList();
|
|
} else {
|
|
User.instance.devices = [];
|
|
}
|
|
Logger.i(_tag, '设备列表刷新完成: ${User.instance.devices.length} 条');
|
|
}
|
|
} catch (e) {
|
|
Logger.e(_tag, '获取设备列表失败: $e');
|
|
} finally {
|
|
_refreshFromUser();
|
|
isLoading.value = false;
|
|
}
|
|
}
|
|
|
|
/// 解绑设备:调接口成功后从本地列表移除;如果是当前连接的设备,断开并跳到扫描页。
|
|
Future<void> unbindDevice(UserDevice device) async {
|
|
try {
|
|
final response = await Api.unbinddevice({'id': device.id});
|
|
Logger.i(_tag, '解绑接口返回: $response');
|
|
if (response == null) return;
|
|
|
|
User.instance.removeUserDevice(device.id);
|
|
_refreshFromUser();
|
|
|
|
if (device.devicemac.isNotEmpty &&
|
|
_bleManager.currentDeviceAddress == device.devicemac) {
|
|
Logger.i(_tag, '解绑的设备就是当前连接,断开并回到扫描页');
|
|
await _bleManager.disconnect();
|
|
await Future.delayed(const Duration(milliseconds: 300));
|
|
Get.offAllNamed(Routes.devices);
|
|
}
|
|
} catch (e) {
|
|
Logger.e(_tag, '解绑异常: $e');
|
|
}
|
|
}
|
|
|
|
void _refreshFromUser() {
|
|
final grouped = <int, List<UserDevice>>{};
|
|
if (User.isLoggedIn()) {
|
|
for (final d in User.instance.devices) {
|
|
grouped.putIfAbsent(d.devicetype, () => <UserDevice>[]).add(d);
|
|
}
|
|
}
|
|
devicesByType.value = grouped;
|
|
devicesByType.refresh();
|
|
}
|
|
|
|
bool isConnected(UserDevice device) {
|
|
if (device.devicemac.isEmpty) return false;
|
|
return _bleManager.isConnected &&
|
|
_bleManager.currentDeviceAddress == device.devicemac;
|
|
}
|
|
|
|
void goToScan() {
|
|
Get.toNamed(Routes.devices);
|
|
}
|
|
}
|
|
|