优化+摄像头+扫码绑定

This commit is contained in:
2026-08-10 10:00:52 +08:00
parent db70665ced
commit 9dc445eeb5
41 changed files with 2618 additions and 438 deletions

View File

@@ -1,3 +1,4 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart';
import 'package:maibu_satabot_v2/core/domain/entities/user_entity.dart';
@@ -24,15 +25,51 @@ class BindDeviceCubit extends Cubit<BindDeviceState> {
) : super(const BindDeviceState());
UserEntity? get _currentUser => _appUserCubit.state.user;
String get _roleKey => _currentUser?.roleKey ?? 'user';
String get roleKey => state.roleKey;
bool get isOrgEnabled => roleKey == 'admin';
bool get isSiteEnabled => roleKey == 'admin' || roleKey == 'manager';
bool get isUserEnabled =>
roleKey == 'admin' || roleKey == 'manager' || roleKey == 'siteManager';
// ── 去重辅助 ──
List<OrgEntity> _uniqueOrgs(List<OrgEntity> list) {
final seen = <int>{};
return list.where((e) => seen.add(e.id)).toList();
}
List<SiteEntity> _uniqueSites(List<SiteEntity> list) {
final seen = <int>{};
return list.where((e) => seen.add(e.id)).toList();
}
List<UserSimpleEntity> _uniqueUsers(List<UserSimpleEntity> list) {
final seen = <int>{};
return list.where((e) => seen.add(e.id)).toList();
}
/// 确保 selectedId 存在于列表中,否则置 null
int? _validSelected(int? id, List<dynamic> list) {
if (id == null) return null;
final ids = list.map((e) => e.id as int).toSet();
return ids.contains(id) ? id : null;
}
Future<void> init() async {
final user = _currentUser;
if (user == null) return;
if (user == null) {
debugPrint(
'>>> [BindDevice] ERROR: _currentUser is null! AppUserCubit.state.user is null. Cannot proceed.',
);
return;
}
emit(state.copyWith(isLoading: true));
debugPrint(
'>>> [BindDevice] roleKey=${user.roleKey}, orgId=${user.orgId}, siteId=${user.siteId}, userId=${user.userId}, username=${user.username}',
);
switch (_roleKey) {
emit(state.copyWith(isLoading: true, roleKey: user.roleKey ?? 'user'));
switch (roleKey) {
case 'admin':
await _loadAllOrgs();
break;
@@ -57,7 +94,15 @@ class BindDeviceCubit extends Cubit<BindDeviceState> {
result.fold(
(failure) =>
emit(state.copyWith(errorMessage: failure.message, isLoading: false)),
(orgs) => emit(state.copyWith(orgList: orgs)),
(orgs) {
final unique = _uniqueOrgs(orgs);
emit(
state.copyWith(
orgList: unique,
selectedOrgId: _validSelected(state.selectedOrgId, unique),
),
);
},
);
}
@@ -67,8 +112,9 @@ class BindDeviceCubit extends Cubit<BindDeviceState> {
(failure) =>
emit(state.copyWith(errorMessage: failure.message, isLoading: false)),
(orgs) async {
emit(state.copyWith(orgList: orgs, selectedOrgId: user.orgId));
await _loadSitesByOrg(user.orgId);
final unique = _ensureOrgInList(_uniqueOrgs(orgs), user.orgId);
emit(state.copyWith(orgList: unique, selectedOrgId: user.orgId));
await _loadSitesByOrgForManager(user.orgId, user.siteId);
},
);
}
@@ -79,7 +125,8 @@ class BindDeviceCubit extends Cubit<BindDeviceState> {
(failure) =>
emit(state.copyWith(errorMessage: failure.message, isLoading: false)),
(orgs) async {
emit(state.copyWith(orgList: orgs, selectedOrgId: user.orgId));
final unique = _ensureOrgInList(_uniqueOrgs(orgs), user.orgId);
emit(state.copyWith(orgList: unique, selectedOrgId: user.orgId));
await _loadSitesAndUsers(user);
},
);
@@ -91,18 +138,65 @@ class BindDeviceCubit extends Cubit<BindDeviceState> {
(failure) =>
emit(state.copyWith(errorMessage: failure.message, isLoading: false)),
(orgs) async {
emit(state.copyWith(orgList: orgs, selectedOrgId: user.orgId));
final unique = _ensureOrgInList(_uniqueOrgs(orgs), user.orgId);
emit(state.copyWith(orgList: unique, selectedOrgId: user.orgId));
await _loadSitesAndUsers(user);
},
);
}
List<OrgEntity> _ensureOrgInList(List<OrgEntity> orgs, int orgId) {
if (orgs.any((e) => e.id == orgId)) return orgs;
return [...orgs, OrgEntity(id: orgId, name: '组织 #$orgId')];
}
List<SiteEntity> _ensureSiteInList(List<SiteEntity> sites, int? siteId) {
if (siteId == null) return sites;
if (sites.any((e) => e.id == siteId)) return sites;
return [...sites, SiteEntity(id: siteId, name: '场站 #$siteId')];
}
List<UserSimpleEntity> _ensureUserInList(
List<UserSimpleEntity> users,
UserEntity user,
) {
final uid = int.tryParse(user.userId) ?? 0;
if (users.any((e) => e.id == uid)) return users;
return [...users, UserSimpleEntity(id: uid, name: user.nickname)];
}
Future<void> _loadSitesByOrg(int orgId) async {
final result = await _getSitesByOrgUseCase(orgId);
result.fold(
(failure) =>
emit(state.copyWith(errorMessage: failure.message, isLoading: false)),
(sites) => emit(state.copyWith(siteList: sites)),
(sites) {
final unique = _uniqueSites(sites);
emit(
state.copyWith(
siteList: unique,
selectedSiteId: _validSelected(state.selectedSiteId, unique),
),
);
},
);
}
Future<void> _loadSitesByOrgForManager(int orgId, int? siteId) async {
final result = await _getSitesByOrgUseCase(orgId);
result.fold(
(failure) =>
emit(state.copyWith(errorMessage: failure.message, isLoading: false)),
(sites) {
final unique = _ensureSiteInList(_uniqueSites(sites), siteId);
emit(
state.copyWith(
siteList: unique,
selectedSiteId:
siteId ?? _validSelected(state.selectedSiteId, unique),
),
);
},
);
}
@@ -112,7 +206,8 @@ class BindDeviceCubit extends Cubit<BindDeviceState> {
(failure) =>
emit(state.copyWith(errorMessage: failure.message, isLoading: false)),
(sites) async {
emit(state.copyWith(siteList: sites, selectedSiteId: user.siteId));
final unique = _ensureSiteInList(_uniqueSites(sites), user.siteId);
emit(state.copyWith(siteList: unique, selectedSiteId: user.siteId));
if (user.siteId != null) {
await _loadUsers(user);
} else {
@@ -139,23 +234,21 @@ class BindDeviceCubit extends Cubit<BindDeviceState> {
name: user.nickname,
);
result.fold(
(failure) =>
emit(state.copyWith(errorMessage: failure.message, isLoading: false)),
(users) {
final allUsers = <UserSimpleEntity>[];
final seenIds = <int>{};
for (final u in users) {
if (u.id != currentUser.id && !seenIds.contains(u.id)) {
allUsers.add(u);
seenIds.add(u.id);
}
}
if (!seenIds.contains(currentUser.id)) {
allUsers.add(currentUser);
}
(failure) {
final list = _ensureUserInList([], user);
emit(
state.copyWith(
userList: allUsers,
userList: list,
selectedUserId: currentUser.id,
isLoading: false,
),
);
},
(users) {
final unique = _ensureUserInList(_uniqueUsers(users), user);
emit(
state.copyWith(
userList: unique,
selectedUserId: currentUser.id,
isLoading: false,
),
@@ -179,7 +272,10 @@ class BindDeviceCubit extends Cubit<BindDeviceState> {
final result = await _getSitesByOrgUseCase(orgId);
result.fold(
(failure) => emit(state.copyWith(errorMessage: failure.message)),
(sites) => emit(state.copyWith(siteList: sites)),
(sites) {
final unique = _uniqueSites(sites);
emit(state.copyWith(siteList: unique));
},
);
}
@@ -196,7 +292,10 @@ class BindDeviceCubit extends Cubit<BindDeviceState> {
final result = await _getUsersBySiteUseCase(siteId);
result.fold(
(failure) => emit(state.copyWith(errorMessage: failure.message)),
(users) => emit(state.copyWith(userList: users)),
(users) {
final unique = _uniqueUsers(users);
emit(state.copyWith(userList: unique));
},
);
}
@@ -205,32 +304,39 @@ class BindDeviceCubit extends Cubit<BindDeviceState> {
}
Future<bool> submitBind(String deviceId) async {
if (state.selectedOrgId == null ||
state.selectedSiteId == null ||
state.selectedUserId == null) {
emit(state.copyWith(errorMessage: '请选择完整的绑定信息'));
if (state.selectedOrgId == null) {
emit(state.copyWith(errorMessage: '请选择所属组织'));
return false;
}
if (roleKey == 'user' && state.selectedUserId == null) {
emit(state.copyWith(errorMessage: '请选择负责人'));
return false;
}
emit(state.copyWith(isSubmitting: true, errorMessage: null));
final existResult = await _isDeviceAtSiteUseCase(
deviceId: deviceId,
siteId: state.selectedSiteId!,
);
if (state.selectedSiteId != null) {
final existResult = await _isDeviceAtSiteUseCase(
deviceId: deviceId,
siteId: state.selectedSiteId!,
);
final isAtSite = existResult.fold((failure) => false, (exists) => exists);
final isAtSite = existResult.fold((failure) => false, (exists) => exists);
if (isAtSite) {
emit(state.copyWith(isSubmitting: false, errorMessage: '该设备已在当前场站,无需绑定'));
return false;
if (isAtSite) {
emit(
state.copyWith(isSubmitting: false, errorMessage: '该设备已在当前场站,无需绑定'),
);
return false;
}
}
final result = await _bindDeviceUseCase(
deviceIds: [deviceId],
orgId: state.selectedOrgId!,
siteId: state.selectedSiteId!,
userId: state.selectedUserId!,
siteId: state.selectedSiteId,
userId: state.selectedUserId,
);
return result.fold(
@@ -246,11 +352,4 @@ class BindDeviceCubit extends Cubit<BindDeviceState> {
},
);
}
bool get isOrgEnabled => _roleKey == 'admin';
bool get isSiteEnabled => _roleKey == 'admin' || _roleKey == 'manager';
bool get isUserEnabled =>
_roleKey == 'admin' || _roleKey == 'manager' || _roleKey == 'siteManager';
String get roleKey => _roleKey;
}

View File

@@ -8,6 +8,7 @@ class BindDeviceState extends Equatable {
final int? selectedOrgId;
final int? selectedSiteId;
final int? selectedUserId;
final String roleKey;
final bool isLoading;
final bool isSubmitting;
final String? errorMessage;
@@ -20,6 +21,7 @@ class BindDeviceState extends Equatable {
this.selectedOrgId,
this.selectedSiteId,
this.selectedUserId,
this.roleKey = 'user',
this.isLoading = false,
this.isSubmitting = false,
this.errorMessage,
@@ -33,6 +35,7 @@ class BindDeviceState extends Equatable {
int? selectedOrgId,
int? selectedSiteId,
int? selectedUserId,
String? roleKey,
bool? isLoading,
bool? isSubmitting,
String? errorMessage,
@@ -45,6 +48,7 @@ class BindDeviceState extends Equatable {
selectedOrgId: selectedOrgId ?? this.selectedOrgId,
selectedSiteId: selectedSiteId ?? this.selectedSiteId,
selectedUserId: selectedUserId ?? this.selectedUserId,
roleKey: roleKey ?? this.roleKey,
isLoading: isLoading ?? this.isLoading,
isSubmitting: isSubmitting ?? this.isSubmitting,
errorMessage: errorMessage,
@@ -60,9 +64,10 @@ class BindDeviceState extends Equatable {
selectedOrgId,
selectedSiteId,
selectedUserId,
roleKey,
isLoading,
isSubmitting,
errorMessage,
isSuccess,
];
}
}

View File

@@ -92,6 +92,8 @@ class _BindDevicePageState extends State<BindDevicePage> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildRoleTag(state.roleKey),
const SizedBox(height: 16),
_buildRequiredField(
label: '已选装备 ID',
child: Container(
@@ -126,10 +128,15 @@ class _BindDevicePageState extends State<BindDevicePage> {
child: _buildSiteDropdown(state),
),
const SizedBox(height: 16),
_buildField(
label: '负责人',
child: _buildUserDropdown(state),
),
_cubit.roleKey == 'user'
? _buildRequiredField(
label: '负责人',
child: _buildUserDropdown(state),
)
: _buildField(
label: '负责人',
child: _buildUserDropdown(state),
),
const SizedBox(height: 32),
Row(
children: [
@@ -206,6 +213,12 @@ class _BindDevicePageState extends State<BindDevicePage> {
);
}
int? _validValue(List<dynamic> list, int? selectedId) {
if (selectedId == null) return null;
final count = list.where((e) => e.id == selectedId).length;
return count == 1 ? selectedId : null;
}
Widget _buildOrgDropdown(BindDeviceState state) {
final enabled = _cubit.isOrgEnabled;
final selectedName = state.selectedOrgId != null
@@ -214,23 +227,22 @@ class _BindDevicePageState extends State<BindDevicePage> {
.fold<String?>(null, (_, org) => org.name)
: null;
if (!enabled && selectedName != null) {
return _buildReadonlyField(selectedName);
if (!enabled) {
return _buildReadonlyField(selectedName ?? '未分配组织');
}
final validValue = _validValue(state.orgList, state.selectedOrgId);
return Container(
decoration: BoxDecoration(
color: enabled ? Colors.white : const Color(0xFFF7F8FA),
color: Colors.white,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: const Color(0xFFE5E6EB)),
),
child: DropdownButtonFormField<int>(
value: state.selectedOrgId,
decoration: _dropdownDecoration(enabled),
icon: Icon(
Icons.expand_more,
color: enabled ? const Color(0xFF86909C) : const Color(0xFFC9CDD4),
),
value: validValue,
decoration: _dropdownDecoration(enabled, '请选择'),
icon: const Icon(Icons.expand_more, color: Color(0xFF86909C)),
items: state.orgList.map((org) {
return DropdownMenuItem<int>(
value: org.id,
@@ -241,11 +253,9 @@ class _BindDevicePageState extends State<BindDevicePage> {
),
);
}).toList(),
onChanged: enabled
? (v) {
if (v != null) _cubit.onOrgChanged(v);
}
: null,
onChanged: (v) {
if (v != null) _cubit.onOrgChanged(v);
},
),
);
}
@@ -258,23 +268,23 @@ class _BindDevicePageState extends State<BindDevicePage> {
.fold<String?>(null, (_, site) => site.name)
: null;
if (!enabled && selectedName != null) {
return _buildReadonlyField(selectedName);
if (!enabled) {
return _buildReadonlyField(selectedName ?? '未分配场站');
}
final hintText = state.selectedOrgId == null ? '请先选择组织' : '请选择';
final validValue = _validValue(state.siteList, state.selectedSiteId);
return Container(
decoration: BoxDecoration(
color: enabled ? Colors.white : const Color(0xFFF7F8FA),
color: Colors.white,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: const Color(0xFFE5E6EB)),
),
child: DropdownButtonFormField<int>(
value: state.selectedSiteId,
decoration: _dropdownDecoration(enabled),
icon: Icon(
Icons.expand_more,
color: enabled ? const Color(0xFF86909C) : const Color(0xFFC9CDD4),
),
value: validValue,
decoration: _dropdownDecoration(enabled, hintText),
icon: const Icon(Icons.expand_more, color: Color(0xFF86909C)),
items: state.siteList.map((site) {
return DropdownMenuItem<int>(
value: site.id,
@@ -285,11 +295,9 @@ class _BindDevicePageState extends State<BindDevicePage> {
),
);
}).toList(),
onChanged: enabled
? (v) {
if (v != null) _cubit.onSiteChanged(v);
}
: null,
onChanged: (v) {
if (v != null) _cubit.onSiteChanged(v);
},
),
);
}
@@ -302,23 +310,23 @@ class _BindDevicePageState extends State<BindDevicePage> {
.fold<String?>(null, (_, user) => user.name)
: null;
if (!enabled && selectedName != null) {
return _buildReadonlyField(selectedName);
if (!enabled) {
return _buildReadonlyField(selectedName ?? '未分配负责人');
}
final hintText = state.selectedSiteId == null ? '请先选择场站' : '请选择';
final validValue = _validValue(state.userList, state.selectedUserId);
return Container(
decoration: BoxDecoration(
color: enabled ? Colors.white : const Color(0xFFF7F8FA),
color: Colors.white,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: const Color(0xFFE5E6EB)),
),
child: DropdownButtonFormField<int>(
value: state.selectedUserId,
decoration: _dropdownDecoration(enabled),
icon: Icon(
Icons.expand_more,
color: enabled ? const Color(0xFF86909C) : const Color(0xFFC9CDD4),
),
value: validValue,
decoration: _dropdownDecoration(enabled, hintText),
icon: const Icon(Icons.expand_more, color: Color(0xFF86909C)),
items: state.userList.map((user) {
return DropdownMenuItem<int>(
value: user.id,
@@ -329,11 +337,37 @@ class _BindDevicePageState extends State<BindDevicePage> {
),
);
}).toList(),
onChanged: enabled
? (v) {
_cubit.onUserChanged(v);
}
: null,
onChanged: (v) {
if (v != null) _cubit.onUserChanged(v);
},
),
);
}
Widget _buildRoleTag(String roleKey) {
final roleLabel =
const {
'admin': '管理员',
'manager': '组织管理员',
'siteManager': '场站管理员',
'user': '普通用户',
}[roleKey] ??
'普通用户';
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: BoxDecoration(
color: const Color(0xFFE8F3FF),
borderRadius: BorderRadius.circular(4),
border: Border.all(color: const Color(0xFF165DFF), width: 0.5),
),
child: Text(
'当前角色:$roleLabel($roleKey)',
style: const TextStyle(
fontSize: 12,
color: Color(0xFF165DFF),
fontWeight: FontWeight.w500,
),
),
);
}
@@ -361,14 +395,14 @@ class _BindDevicePageState extends State<BindDevicePage> {
);
}
InputDecoration _dropdownDecoration(bool enabled) {
InputDecoration _dropdownDecoration(bool enabled, String hintText) {
return InputDecoration(
isDense: true,
contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
border: InputBorder.none,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
hintText: enabled ? '请选择' : '请选择',
hintText: hintText,
hintStyle: const TextStyle(color: Color(0xFF86909C), fontSize: 14),
);
}

View File

@@ -618,8 +618,8 @@ class _DeviceStatusViewState extends State<DeviceStatusView> {
productName: robot.type,
tenantId: 0,
tenantName: '',
status: robot.status == '在线' ? 1 : 0,
onlineStatus: robot.status == '在线' ? 1 : 0,
status: robot.isOnline ? 1 : 0,
onlineStatus: robot.isOnline ? 1 : 0,
);
final remoteCubit = GetIt.I<RemoteControlCubit>();
@@ -784,6 +784,13 @@ class _DeviceStatusViewState extends State<DeviceStatusView> {
BuildContext context,
DeviceListState.DeviceStatusLoaded state,
) {
// 从实际设备列表计算统计数据(不再使用硬编码的假数据)
final devices = state.devices;
final totalCount = devices.length;
final onlineCount = devices.where((d) => d.status == '在线').length;
final exceptionCount = devices.where((d) => d.status == '异常').length;
final offlineCount = totalCount - onlineCount - exceptionCount;
return Container(
margin: const EdgeInsets.symmetric(horizontal: 16.0),
padding: const EdgeInsets.all(16.0),
@@ -801,7 +808,7 @@ class _DeviceStatusViewState extends State<DeviceStatusView> {
child: Row(
children: [
_buildStatItem(
value: state.deviceStatus.total.toString(),
value: totalCount.toString(),
label: AppLocalizations.of(
context,
).translate('device_list_v2.total_devices'),
@@ -810,7 +817,7 @@ class _DeviceStatusViewState extends State<DeviceStatusView> {
),
Container(width: 1, height: 40, color: const Color(0xFFE5E6EB)),
_buildStatItem(
value: state.deviceStatus.online.toString(),
value: onlineCount.toString(),
label: AppLocalizations.of(
context,
).translate('device_list_v2.online'),
@@ -819,7 +826,7 @@ class _DeviceStatusViewState extends State<DeviceStatusView> {
),
Container(width: 1, height: 40, color: const Color(0xFFE5E6EB)),
_buildStatItem(
value: state.deviceStatus.exception.toString(),
value: exceptionCount.toString(),
label: AppLocalizations.of(
context,
).translate('device_list_v2.alarm'),
@@ -828,7 +835,7 @@ class _DeviceStatusViewState extends State<DeviceStatusView> {
),
Container(width: 1, height: 40, color: const Color(0xFFE5E6EB)),
_buildStatItem(
value: state.deviceStatus.offline.toString(),
value: offlineCount.toString(),
label: AppLocalizations.of(
context,
).translate('device_list_v2.offline'),

View File

@@ -109,11 +109,11 @@ class _RobotListViewState extends State<RobotListView> {
final weedingRobots = allRobots.where((r) => r.type == 'weeding').toList();
final onlineInspection = inspectionRobots
.where((r) => r.status == '在线')
.where((r) => r.isOnline)
.length;
final onlineCleaning = cleaningRobots.where((r) => r.status == '在线').length;
final onlineCleaning = cleaningRobots.where((r) => r.isOnline).length;
// 暂且所有设备都视为除草机器人,在线数使用总数
final onlineWeeding = allRobots.where((r) => r.status == '在线').length;
final onlineWeeding = allRobots.where((r) => r.isOnline).length;
return Container(
margin: const EdgeInsets.fromLTRB(16, 16, 16, 12),
padding: const EdgeInsets.symmetric(vertical: 16),
@@ -385,14 +385,12 @@ class _RobotListViewState extends State<RobotListView> {
Widget _buildQuickActions(RobotListLoaded state) {
// 计算统计数据
final onlineCount = state.robots.where((r) => r.status == '在线').length;
final onlineCount = state.robots.where((r) => r.isOnline).length;
final workingCount = state.robots
.where((r) => r.task != '待机中' && r.task != '充电中')
.length;
final standbyCount = state.robots.where((r) => r.task == '待机中').length;
final faultCount = state.robots
.where((r) => r.status == '异常' || r.status == '离线')
.length;
final faultCount = state.robots.where((r) => !r.isOnline).length;
return Container(
margin: const EdgeInsets.fromLTRB(16, 0, 16, 12),
padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 16),
@@ -429,7 +427,7 @@ class _RobotListViewState extends State<RobotListView> {
Container(width: 1, height: 40, color: const Color(0xFFE5E6EB)),
_buildStatusItem(
value: '$faultCount',
label: '故障数',
label: '离线数',
valueColor: const Color(0xFFF53F3F),
),
],
@@ -474,6 +472,8 @@ class _RobotListViewState extends State<RobotListView> {
id: '',
type: '',
status: '',
isOnline: false,
statusCode: 0,
battery: 0,
task: '无任务',
),
@@ -641,8 +641,8 @@ class _RobotListViewState extends State<RobotListView> {
productName: robot.type,
tenantId: 0,
tenantName: '',
status: robot.status == '在线' ? 1 : 0,
onlineStatus: robot.status == '在线' ? 1 : 0,
status: robot.isOnline ? 1 : 0,
onlineStatus: robot.isOnline ? 1 : 0,
);
debugPrint('🎯 [RobotListPage] 准备调用 setTargetDevice...');

View File

@@ -110,20 +110,20 @@ class _DroneOsdCardState extends State<DroneOsdCard> {
void _initFields() {
_osdFields.addAll([
{
'icon': Icons.battery_full_rounded,
'label': '电量',
'key': 'battery',
'value': '未知',
'color': const Color(0xFF00B42A),
},
{
'icon': Icons.height_rounded,
'label': '飞行高度',
'label': '高度',
'key': 'height',
'value': '未知',
'color': const Color(0xFF165DFF),
},
{
'icon': Icons.speed_rounded,
'label': '飞行速度',
'key': 'speed',
'value': '未知',
'color': const Color(0xFF722ED1),
},
{
'icon': Icons.trending_flat_rounded,
'label': '水平速度',
@@ -138,34 +138,6 @@ class _DroneOsdCardState extends State<DroneOsdCard> {
'value': '未知',
'color': const Color(0xFF00B42A),
},
{
'icon': Icons.route_rounded,
'label': '飞行距离',
'key': 'distance',
'value': '未知',
'color': const Color(0xFF00B42A),
},
{
'icon': Icons.battery_full_rounded,
'label': '电量',
'key': 'battery',
'value': '未知',
'color': const Color(0xFF00B42A),
},
{
'icon': Icons.bolt_rounded,
'label': '电池电压',
'key': 'voltage',
'value': '未知',
'color': const Color(0xFF00B42A),
},
{
'icon': Icons.thermostat_rounded,
'label': '电池温度',
'key': 'batteryTemp',
'value': '未知',
'color': const Color(0xFF165DFF),
},
{
'icon': Icons.navigation_rounded,
'label': '航向角',
@@ -173,48 +145,20 @@ class _DroneOsdCardState extends State<DroneOsdCard> {
'value': '未知',
'color': const Color(0xFF165DFF),
},
{
'icon': Icons.rotate_90_degrees_cw_rounded,
'label': '俯仰角',
'key': 'pitch',
'value': '未知',
'color': const Color(0xFF722ED1),
},
{
'icon': Icons.rotate_right_rounded,
'label': '横滚角',
'key': 'roll',
'value': '未知',
'color': const Color(0xFF722ED1),
},
{
'icon': Icons.satellite_rounded,
'label': 'GPS卫星',
'label': 'GPS',
'key': 'gps',
'value': '未知',
'color': const Color(0xFF00B42A),
},
{
'icon': Icons.satellite_alt_rounded,
'label': 'RTK卫星',
'label': 'RTK',
'key': 'rtk',
'value': '未知',
'color': const Color(0xFF00B42A),
},
{
'icon': Icons.home_rounded,
'label': '无人机状态',
'key': 'droneState',
'value': '未知',
'color': const Color(0xFF165DFF),
},
{
'icon': Icons.flight_rounded,
'label': '飞行模式',
'key': 'flightMode',
'value': '未知',
'color': const Color(0xFF165DFF),
},
]);
}
@@ -263,78 +207,45 @@ class _DroneOsdCardState extends State<DroneOsdCard> {
(droneData['height'] as num?)?.toDouble() ??
(droneData['altitude'] as num?)?.toDouble();
double? groundSpeed = (droneData['ground_speed'] as num?)?.toDouble();
double? flightDistance = (droneData['flight_distance'] as num?)?.toDouble();
int? flightTime = droneData['flight_time'] as int?;
double? horizontalSpeed = (droneData['horizontal_speed'] as num?)
?.toDouble();
double? verticalSpeed = (droneData['vertical_speed'] as num?)?.toDouble();
final batteryMap = droneData['battery'] as Map?;
int? batteryPercent =
droneData['battery_percent'] as int? ??
batteryMap?['capacity_percent'] as int?;
double? batteryVoltage = (droneData['battery_voltage'] as num?)?.toDouble();
if (batteryVoltage == null && batteryMap != null) {
final batteries = batteryMap['batteries'] as List?;
if (batteries != null && batteries.isNotEmpty) {
final firstBattery = batteries[0] as Map?;
batteryVoltage = (firstBattery?['voltage'] as num?)?.toDouble();
}
}
if (batteryVoltage != null && batteryVoltage > 1000) {
batteryVoltage = batteryVoltage / 1000;
}
double? batteryTemp = (droneData['battery_temperature'] as num?)
?.toDouble();
if (batteryTemp == null && batteryMap != null) {
final batteries = batteryMap['batteries'] as List?;
if (batteries != null && batteries.isNotEmpty) {
final firstBattery = batteries[0] as Map?;
batteryTemp = (firstBattery?['temperature'] as num?)?.toDouble();
}
}
double? heading =
(droneData['heading'] as num?)?.toDouble() ??
(droneData['attitude_head'] as num?)?.toDouble();
double? pitch =
(droneData['pitch'] as num?)?.toDouble() ??
(droneData['attitude_pitch'] as num?)?.toDouble();
double? roll =
(droneData['roll'] as num?)?.toDouble() ??
(droneData['attitude_roll'] as num?)?.toDouble();
int? gpsSatellites = droneData['gps_satellites'] as int?;
int? rtkSatellites = droneData['rtk_satellites'] as int?;
double? horizontalSpeed = (droneData['horizontal_speed'] as num?)
?.toDouble();
double? verticalSpeed = (droneData['vertical_speed'] as num?)?.toDouble();
String? droneState = droneData['drone_state'] as String?;
if (droneState == null) {
final inHangar = droneData['in_hangar'] as int?;
if (inHangar != null) {
droneState = inHangar == 1 ? '在库' : '外出';
}
// GPS/RTK:DJI Cloud API 中 GPS 卫星数和 RTK 定位状态均位于 position_state 对象内
// - position_state.gps_number:GPS 卫星数
// - position_state.is_fixed:RTK 定位状态(0=未定位, 1=浮点解, 2=固定解)
final positionState = droneData['position_state'];
int? gpsSatellites;
int? rtkFixed;
if (positionState is Map) {
gpsSatellites = positionState['gps_number'] as int?;
rtkFixed = positionState['is_fixed'] as int?;
}
if (droneState == null) {
final droneInDock = droneData['drone_in_dock'] as int?;
if (droneInDock != null) {
droneState = droneInDock == 1 ? '在库' : '外出';
}
// 兼容直接放在顶层的旧字段名
gpsSatellites = gpsSatellites ?? droneData['gps_satellites'] as int?;
final int? rtkSatellites = droneData['rtk_satellites'] as int?;
if (batteryPercent != null) {
parsedValues['battery'] = '$batteryPercent%';
parsedColors['battery'] = batteryPercent > 50
? const Color(0xFF00B42A)
: batteryPercent > 20
? const Color(0xFFFF7D00)
: const Color(0xFFF53F3F);
}
String? flightMode = droneData['flight_mode'] as String?;
if (height != null) {
parsedValues['height'] = '${height.toStringAsFixed(1)}m';
parsedColors['height'] = const Color(0xFF165DFF);
}
if (groundSpeed != null) {
parsedValues['speed'] = '${groundSpeed.toStringAsFixed(1)}m/s';
parsedColors['speed'] = const Color(0xFF722ED1);
}
if (horizontalSpeed != null) {
parsedValues['horizontalSpeed'] =
'${horizontalSpeed.toStringAsFixed(1)}m/s';
@@ -345,58 +256,40 @@ class _DroneOsdCardState extends State<DroneOsdCard> {
? const Color(0xFFF53F3F)
: const Color(0xFF00B42A);
}
if (flightDistance != null) {
parsedValues['distance'] = '${flightDistance.toStringAsFixed(0)}m';
}
if (batteryPercent != null) {
parsedValues['battery'] = '$batteryPercent%';
parsedColors['battery'] = batteryPercent > 50
? const Color(0xFF00B42A)
: batteryPercent > 20
? const Color(0xFFFF7D00)
: const Color(0xFFF53F3F);
}
if (batteryVoltage != null) {
parsedValues['voltage'] = '${batteryVoltage.toStringAsFixed(1)}V';
}
if (batteryTemp != null) {
parsedValues['batteryTemp'] = '${batteryTemp.toStringAsFixed(0)}°C';
parsedColors['batteryTemp'] = batteryTemp > 50
? const Color(0xFFF53F3F)
: batteryTemp > 40
? const Color(0xFFFF7D00)
: const Color(0xFF165DFF);
}
if (heading != null) {
parsedValues['heading'] = '${heading.toStringAsFixed(0)}°';
}
if (pitch != null) {
parsedValues['pitch'] = '${pitch.toStringAsFixed(1)}°';
}
if (roll != null) {
parsedValues['roll'] = '${roll.toStringAsFixed(1)}°';
}
if (gpsSatellites != null) {
parsedValues['gps'] = '$gpsSatellites颗';
parsedColors['gps'] = gpsSatellites >= 6
? const Color(0xFF00B42A)
: const Color(0xFFFF7D00);
}
if (rtkSatellites != null) {
// RTK:优先展示定位状态(is_fixed),其次回退到卫星数
if (rtkFixed != null) {
String rtkStatus;
Color rtkColor;
switch (rtkFixed) {
case 2:
rtkStatus = '固定解';
rtkColor = const Color(0xFF00B42A);
break;
case 1:
rtkStatus = '浮点解';
rtkColor = const Color(0xFFFF7D00);
break;
default:
rtkStatus = '未定位';
rtkColor = const Color(0xFF86909C);
}
parsedValues['rtk'] = rtkStatus;
parsedColors['rtk'] = rtkColor;
} else if (rtkSatellites != null) {
parsedValues['rtk'] = '$rtkSatellites颗';
parsedColors['rtk'] = rtkSatellites >= 4
? const Color(0xFF00B42A)
: const Color(0xFFFF7D00);
}
if (droneState != null) {
parsedValues['droneState'] = droneState;
parsedColors['droneState'] = droneState == '在库'
? const Color(0xFF00B42A)
: const Color(0xFF165DFF);
}
if (flightMode != null) {
parsedValues['flightMode'] = flightMode;
}
if (!mounted) return;
setState(() {

View File

@@ -5,10 +5,9 @@ import 'package:maibu_satabot_v2/core/app/app_user_state.dart'; // 🔥 导入 A
import 'package:maibu_satabot_v2/core/consts/tcp_consts.dart';
import 'package:maibu_satabot_v2/features/remote_control/presentation/widgets/webrtc/webrtc_local_player.dart';
import '../../../device_run_param/presentation/pages/robot_param_settings_page.dart';
import '../../../device_run_param/presentation/pages/robot_param_settings_page.dart';
/// 机器人顶部信息卡片
class RobotHeaderCard extends StatefulWidget {
class RobotHeaderCard extends StatefulWidget {
final Map<String, dynamic> robot;
const RobotHeaderCard({super.key, required this.robot});
@@ -17,15 +16,31 @@ class RobotHeaderCard extends StatefulWidget {
State<RobotHeaderCard> createState() => _RobotHeaderCardState();
}
/// 视频展示状态
/// - idle:未播放,显示播放按钮
/// - loading:正在加载视频
/// - playing:视频播放中
/// - noStream:暂无视频(加载失败后也回到此态,并显示播放按钮供重试)
enum _VideoState { idle, loading, playing, noStream }
class _RobotHeaderCardState extends State<RobotHeaderCard> {
int _currentViewIndex = 0; // 0=前, 1=后, 2=左, 3=右, 4=上
_VideoState _videoState = _VideoState.idle;
// 视角配置
final List<Map<String, dynamic>> _viewConfigs = [
{'name': '前视', 'alignment': Alignment.topLeft, 'icon': Icons.arrow_upward},
{'name': '后视', 'alignment': Alignment.topRight, 'icon': Icons.arrow_downward},
{
'name': '后视',
'alignment': Alignment.topRight,
'icon': Icons.arrow_downward,
},
{'name': '左视', 'alignment': Alignment.bottomLeft, 'icon': Icons.arrow_back},
{'name': '右视', 'alignment': Alignment.bottomRight, 'icon': Icons.arrow_forward},
{
'name': '右视',
'alignment': Alignment.bottomRight,
'icon': Icons.arrow_forward,
},
{'name': '俯视', 'alignment': Alignment.center, 'icon': Icons.view_agenda},
];
@@ -35,6 +50,42 @@ class _RobotHeaderCardState extends State<RobotHeaderCard> {
debugPrint('🎬 [RobotHeaderCard] 初始化 - robot: ${widget.robot}');
}
/// 🔥 构造视频流 URL(仅在用户点击播放时使用)
String _buildStreamUrl(String? token) {
final deviceId = widget.robot['name'] as String?;
if (deviceId == null || deviceId.isEmpty || token == null) {
return '';
}
return "webrtc://${TCPConsts.TCP_IP}/live/livestream/$deviceId?token=$token";
}
/// 🔥 点击播放按钮
void _onPlayTapped(String? token) {
final url = _buildStreamUrl(token);
if (url.isEmpty) {
// 无法构造 URL(设备 ID 或 token 缺失)→ 直接显示暂无视频
setState(() => _videoState = _VideoState.noStream);
return;
}
setState(() => _videoState = _VideoState.loading);
}
/// 🔥 接收 WebRTCLocalPlayer 的加载状态回调
void _onWebRTCStateChanged(WebRTCLoadState state) {
switch (state) {
case WebRTCLoadState.loading:
setState(() => _videoState = _VideoState.loading);
break;
case WebRTCLoadState.playing:
setState(() => _videoState = _VideoState.playing);
break;
case WebRTCLoadState.error:
// 打不开 → 显示暂无视频 → 视觉上仍展示播放按钮(可重试)
setState(() => _videoState = _VideoState.noStream);
break;
}
}
@override
Widget build(BuildContext context) {
return Container(
@@ -128,9 +179,8 @@ class _RobotHeaderCardState extends State<RobotHeaderCard> {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => RobotParamSettingsPage(
robot: widget.robot,
),
builder: (_) =>
RobotParamSettingsPage(robot: widget.robot),
),
);
},
@@ -143,67 +193,53 @@ class _RobotHeaderCardState extends State<RobotHeaderCard> {
],
),
const SizedBox(height: 12),
// 🔥 视频展示区域(替换原来的静态图片)
// 🔥 视频展示区域:默认显示播放按钮,点击后才加载视频
AspectRatio(
aspectRatio: 16 / 9,
child: Container(
color: Colors.black, // 🔥 强制整个视频区域为黑色背景
child: BlocBuilder<AppUserCubit, AppUserState>(
builder: (context, userState) {
final deviceId = widget.robot['name'] as String?; // 🔥 使用 name 字段(长序列号)
String videoStreamUrl = '';
debugPrint('🎬 [RobotHeaderCard] BlocBuilder 重建');
debugPrint(' - deviceId (name): $deviceId');
debugPrint(' - user != null: ${userState.user != null}');
debugPrint(' - token != null: ${userState.user?.token != null}');
debugPrint(' - TCP_IP: ${TCPConsts.TCP_IP}');
if (deviceId != null &&
deviceId.isNotEmpty &&
userState.user != null &&
userState.user!.token != null) {
videoStreamUrl = "webrtc://${TCPConsts.TCP_IP}/live/livestream/$deviceId?token=${userState.user!.token}";
debugPrint('✅ [RobotHeaderCard] 视频URL构建成功: $videoStreamUrl');
} else {
debugPrint('❌ [RobotHeaderCard] 视频URL构建失败');
if (deviceId == null || deviceId.isEmpty) {
debugPrint(' - 原因: deviceId 为空');
}
if (userState.user == null) {
debugPrint(' - 原因: user 为 null');
}
if (userState.user?.token == null) {
debugPrint(' - 原因: token 为 null');
}
final token = userState.user?.token;
// loading / playing 态:渲染 WebRTCLocalPlayer
// - loading:WebRTCLocalPlayer 内部自带“视频加载中...”加载屏,并建立连接
// - playing:收到视频流后正常播放
// 两种态都保持 WebRTCLocalPlayer 挂载,避免重建断流
if (_videoState == _VideoState.loading ||
_videoState == _VideoState.playing) {
final url = _buildStreamUrl(token);
return WebRTCLocalPlayer(
key: ValueKey('play_$url'),
streamUrl: url,
showLeftPip: false,
showRightPip: false,
mainViewAlignment:
_viewConfigs[_currentViewIndex]['alignment']
as Alignment,
onLoadingStateChanged: _onWebRTCStateChanged,
onTap: () {
// 🔥 播放中单击 → 停止拉流,回到播放按钮态
// 移除 WebRTCLocalPlayer 后其 dispose 会自动断连
setState(() => _videoState = _VideoState.idle);
},
);
}
return videoStreamUrl.isNotEmpty
? WebRTCLocalPlayer(
key: ValueKey(videoStreamUrl),
streamUrl: videoStreamUrl,
showLeftPip: false,
showRightPip: false,
mainViewAlignment: _viewConfigs[_currentViewIndex]['alignment'] as Alignment,
)
: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.videocam_off, size: 48, color: Colors.white54),
const SizedBox(height: 12),
Text(
'暂无视频',
style: TextStyle(color: Colors.white70, fontSize: 14, fontWeight: FontWeight.w500),
),
],
),
);
// idle / noStream 态:显示播放按钮
// - idle:进入页面默认态
// - noStream:视频流打不开,显示“暂无视频”提示 + 播放按钮供重试
final bool showNoStreamHint =
_videoState == _VideoState.noStream;
return _buildPlayOverlay(
showNoStreamHint: showNoStreamHint,
onTap: () => _onPlayTapped(token),
);
},
),
),
),
// 🔥 视角切换按钮
Padding(
padding: const EdgeInsets.fromLTRB(0, 12, 0, 0),
@@ -213,7 +249,7 @@ class _RobotHeaderCardState extends State<RobotHeaderCard> {
final index = entry.key;
final config = entry.value;
final isSelected = _currentViewIndex == index;
return Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 2),
@@ -222,13 +258,22 @@ class _RobotHeaderCardState extends State<RobotHeaderCard> {
setState(() {
_currentViewIndex = index;
});
debugPrint('🎬 [RobotHeaderCard] 切换视角: ${config['name']}');
debugPrint(
'🎬 [RobotHeaderCard] 切换视角: ${config['name']}',
);
},
style: ElevatedButton.styleFrom(
backgroundColor: isSelected ? const Color(0xFF165DFF) : Colors.grey[200],
foregroundColor: isSelected ? Colors.white : Colors.grey[700],
backgroundColor: isSelected
? const Color(0xFF165DFF)
: Colors.grey[200],
foregroundColor: isSelected
? Colors.white
: Colors.grey[700],
elevation: 0,
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 4),
padding: const EdgeInsets.symmetric(
vertical: 8,
horizontal: 4,
),
minimumSize: const Size(0, 36),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
@@ -257,6 +302,77 @@ class _RobotHeaderCardState extends State<RobotHeaderCard> {
),
);
}
/// 🔥 播放按钮遮罩层
/// - [showNoStreamHint]:true 时在按钮上方额外显示“暂无视频”提示(视频流打不开的回退态)
/// - [onTap]:点击播放按钮的回调
Widget _buildPlayOverlay({
required bool showNoStreamHint,
required VoidCallback onTap,
}) {
return GestureDetector(
onTap: onTap,
behavior: HitTestBehavior.opaque,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
// 暂无视频提示(仅在 noStream 态显示)
if (showNoStreamHint) ...[
const Icon(Icons.videocam_off, size: 36, color: Colors.white38),
const SizedBox(height: 8),
const Text(
'暂无视频',
style: TextStyle(
color: Colors.white54,
fontSize: 13,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 12),
],
// 播放按钮(圆角矩形,与卡片矩形风格呼应)
Container(
width: 56,
height: 56,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(18),
color: const Color(0xFF165DFF).withOpacity(0.9),
boxShadow: [
// 主题色柔和光晕,与整体蓝色调呼应
BoxShadow(
color: const Color(0xFF165DFF).withOpacity(0.35),
blurRadius: 16,
offset: const Offset(0, 4),
),
// 细微黑色投影,与卡片阴影同色系更和谐
BoxShadow(
color: Colors.black.withOpacity(0.15),
blurRadius: 6,
offset: const Offset(0, 2),
),
],
),
child: const Icon(
Icons.play_arrow_rounded,
color: Colors.white,
size: 30,
),
),
const SizedBox(height: 10),
// “播放”文字
const Text(
'播放',
style: TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
],
),
),
);
}
}

View File

@@ -196,17 +196,9 @@ class RobotItemCard extends StatelessWidget {
bgColor = const Color(0xFFF0F9FF);
textColor = const Color(0xFF00B42A);
break;
case '离线':
default:
bgColor = const Color(0xFFF5F0FF);
textColor = const Color(0xFFF53F3F);
break;
case '异常':
bgColor = const Color(0xFFFFF7E6);
textColor = const Color(0xFFFF7D00);
break;
default:
bgColor = const Color(0xFFF5F5F5);
textColor = const Color(0xFF86909C);
}
return Container(