第二次提交
This commit is contained in:
10
lib/features/ai/presentation/pages/ai_page.dart
Normal file
10
lib/features/ai/presentation/pages/ai_page.dart
Normal file
@@ -0,0 +1,10 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class AiPage extends StatelessWidget {
|
||||
const AiPage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(body: Center(child: Text('Welcome AI page')));
|
||||
}
|
||||
}
|
||||
31
lib/features/ai/presentation/routes/ai_routes.dart
Normal file
31
lib/features/ai/presentation/routes/ai_routes.dart
Normal file
@@ -0,0 +1,31 @@
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:maibu_satabot_v2/features/ai/presentation/pages/ai_page.dart';
|
||||
|
||||
import '../../../../core/router/route_paths.dart';
|
||||
|
||||
class AiRoutes {
|
||||
/// 1. 全屏功能页面(不带导航栏)
|
||||
/// 在 createRouter 的根 routes 中使用 ...HomeRoutes.routes 引入
|
||||
static List<RouteBase> get routes => [
|
||||
// GoRoute(
|
||||
// path: RoutePaths.remoteControl,
|
||||
// builder: (context, state) => const RemoteControlPage(), // 需导入对应 Page
|
||||
// ),
|
||||
// GoRoute(
|
||||
// path: RoutePaths.routePlan,
|
||||
// builder: (context, state) => const RoutePlanPage(),
|
||||
// ),
|
||||
// GoRoute(
|
||||
// path: RoutePaths.runningStatus,
|
||||
// builder: (context, state) => const RunningStatusPage(),
|
||||
// ),
|
||||
];
|
||||
|
||||
/// 2. 首页 Tab 分支(带导航栏)
|
||||
/// 仅保留真正的首页入口
|
||||
static StatefulShellBranch get branch => StatefulShellBranch(
|
||||
routes: [
|
||||
GoRoute(path: RoutePaths.ai, builder: (context, state) => const AiPage()),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:maibu_satabot_v2/core/consts/http_api_consts.dart';
|
||||
|
||||
import '../../models/user_model.dart';
|
||||
import '../auth_http_datasource.dart';
|
||||
@@ -11,7 +12,7 @@ class AuthHttpDataSourceImpl implements AuthHttpDataSource {
|
||||
@override
|
||||
Future<UserModel> login(String username, String password, sourceType) async {
|
||||
final response = await dio.post(
|
||||
'/login',
|
||||
HttpApiConsts.loginUrl,
|
||||
data: {
|
||||
'username': username,
|
||||
'password': password,
|
||||
@@ -19,11 +20,21 @@ class AuthHttpDataSourceImpl implements AuthHttpDataSource {
|
||||
},
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
print('runtimeType = ${response.data.runtimeType}');
|
||||
return UserModel.fromJson(response.data);
|
||||
} else {
|
||||
throw Exception(response.data['message'] ?? 'Login failed');
|
||||
if (response.statusCode != 200) {
|
||||
throw Exception('网络请求失败: ${response.statusCode}');
|
||||
}
|
||||
|
||||
final responseData = response.data;
|
||||
|
||||
if (responseData['code'] != 200) {
|
||||
throw Exception(responseData['msg'] ?? '业务异常');
|
||||
}
|
||||
|
||||
final loginUsername = responseData['username'];
|
||||
if (loginUsername == null || loginUsername == '') {
|
||||
throw Exception('服务器返回的数据结构不完整(缺少用户信息)');
|
||||
}
|
||||
var userModel = UserModel.fromJson(responseData);
|
||||
return userModel;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import 'package:maibu_satabot_v2/core/data/base_model.dart';
|
||||
|
||||
import '../../../../core/domain/entities/user_entity.dart';
|
||||
|
||||
class UserModel extends UserEntity {
|
||||
class UserModel extends UserEntity implements BaseModel {
|
||||
UserModel({
|
||||
required super.userId,
|
||||
required super.username,
|
||||
|
||||
@@ -1,37 +1,40 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import 'package:maibu_satabot_v2/core/storage/user_storage.dart';
|
||||
|
||||
import '../../../../core/domain/entities/user_entity.dart';
|
||||
import '../../domain/errors/auth_failure.dart';
|
||||
import '../../domain/repositories/auth_repository.dart';
|
||||
import '../datasources/auth_http_datasource.dart';
|
||||
|
||||
class AuthRepositoryImpl implements AuthRepository {
|
||||
final AuthHttpDataSource remote;
|
||||
final AuthHttpDataSource httpRemote;
|
||||
final UserStorage localTokenStorage;
|
||||
|
||||
AuthRepositoryImpl({required this.remote, required this.localTokenStorage});
|
||||
AuthRepositoryImpl({
|
||||
required this.httpRemote,
|
||||
required this.localTokenStorage,
|
||||
});
|
||||
|
||||
@override
|
||||
// 注意 1:返回类型应该是 Domain 层的 UserEntity,而不是 UserModel
|
||||
Future<UserEntity> login(
|
||||
Future<Either<AuthFailure, UserEntity>> login(
|
||||
String username,
|
||||
String password,
|
||||
int sourceType,
|
||||
) async {
|
||||
try {
|
||||
// 1. 从数据源获取 Data Model
|
||||
final userModel = await remote.login(username, password, sourceType);
|
||||
final userModel = await httpRemote.login(username, password, sourceType);
|
||||
|
||||
// 2. 职责核心:将 Model 转换为 Entity (解耦业务与 JSON 结构)
|
||||
if (userModel != null) {
|
||||
await localTokenStorage.saveUser(userModel);
|
||||
}
|
||||
await localTokenStorage.saveUser(userModel);
|
||||
|
||||
// 2. 只返回纯粹的用户信息实体
|
||||
return userModel.toEntity();
|
||||
return Right(userModel.toEntity());
|
||||
} on DioException catch (e) {
|
||||
final String serverMessage = e.response?.data['msg'] ?? "网络连接异常";
|
||||
return Left(AuthFailure(serverMessage));
|
||||
} catch (e) {
|
||||
// 3. 职责核心:异常翻译
|
||||
// 不直接抛出 Dio 异常,而是抛出业务层定义的自定义异常或返回 Failure
|
||||
throw Exception(e.toString());
|
||||
final cleanMessage = e.toString().replaceFirst('Exception: ', '');
|
||||
return Left(AuthFailure(cleanMessage));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
14
lib/features/auth/domain/errors/auth_failure.dart
Normal file
14
lib/features/auth/domain/errors/auth_failure.dart
Normal file
@@ -0,0 +1,14 @@
|
||||
import 'package:maibu_satabot_v2/core/error/failure.dart';
|
||||
|
||||
class AuthFailure extends Failure implements Exception {
|
||||
final int? code;
|
||||
AuthFailure(super.message, {this.code});
|
||||
}
|
||||
|
||||
class InvalidCredentialsFailure extends AuthFailure {
|
||||
InvalidCredentialsFailure(String message) : super(message);
|
||||
}
|
||||
|
||||
class ServerFailure extends AuthFailure {
|
||||
ServerFailure(String message, int code) : super(message, code: code);
|
||||
}
|
||||
@@ -1,5 +1,12 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
|
||||
import '../../../../core/domain/entities/user_entity.dart';
|
||||
import '../errors/auth_failure.dart';
|
||||
|
||||
abstract class AuthRepository {
|
||||
Future<UserEntity> login(String username, String password, int sourceType);
|
||||
Future<Either<AuthFailure, UserEntity>> login(
|
||||
String username,
|
||||
String password,
|
||||
int sourceType,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
|
||||
import '../../../../core/domain/entities/user_entity.dart';
|
||||
import '../../../../core/domain/usecases/base_usecase.dart';
|
||||
import '../errors/auth_failure.dart';
|
||||
import '../repositories/auth_repository.dart';
|
||||
|
||||
class LoginUseCase implements BaseUseCase<UserEntity, LoginParams> {
|
||||
@@ -8,8 +11,8 @@ class LoginUseCase implements BaseUseCase<UserEntity, LoginParams> {
|
||||
LoginUseCase(this.repository);
|
||||
|
||||
@override
|
||||
Future<UserEntity> call(LoginParams params) {
|
||||
return repository.login(
|
||||
Future<Either<AuthFailure, UserEntity>> call(LoginParams params) async {
|
||||
return await repository.login(
|
||||
params.username,
|
||||
params.password,
|
||||
params.sourceType,
|
||||
|
||||
@@ -5,7 +5,7 @@ import 'package:maibu_satabot_v2/core/consts/tcp_consts.dart';
|
||||
import 'package:maibu_satabot_v2/core/domain/entities/user_entity.dart';
|
||||
import 'package:maibu_satabot_v2/core/network/net_message_dispatcher.dart';
|
||||
|
||||
import '../../../../core/app/app_cubit.dart';
|
||||
import '../../../../core/app/app_user_cubit.dart';
|
||||
import '../../../../core/network/tcp/tcp_client.dart';
|
||||
import '../../../../core/storage/user_storage.dart';
|
||||
import 'auth_state.dart';
|
||||
@@ -17,7 +17,7 @@ import 'auth_state.dart';
|
||||
class AuthCubit extends Cubit<AuthState> {
|
||||
final UserStorage storage;
|
||||
final TcpClient tcp;
|
||||
final AppCubit appCubit;
|
||||
final AppUserCubit appCubit;
|
||||
final NetMessageDispatcher dispatcher;
|
||||
StreamSubscription? _kickOutSub; // 新增:用于管理监听生命周期
|
||||
|
||||
|
||||
@@ -11,11 +11,13 @@ class LoginBloc extends Bloc<LoginEvent, LoginState> {
|
||||
on<LoginSubmitted>((event, emit) async {
|
||||
emit(LoginLoading());
|
||||
try {
|
||||
final user = await loginUseCase(
|
||||
final result = await loginUseCase(
|
||||
LoginParams(event.username, event.password, event.sourceType),
|
||||
);
|
||||
print('✅ Got user: $user');
|
||||
emit(LoginSuccess(user));
|
||||
result.fold(
|
||||
(failure) => emit(LoginFailure(failure.message)),
|
||||
(user) => emit(LoginSuccess(user)),
|
||||
);
|
||||
} catch (e) {
|
||||
emit(LoginFailure(e.toString()));
|
||||
}
|
||||
|
||||
@@ -17,11 +17,13 @@ class LoginCubit extends Cubit<LoginState> {
|
||||
Future<void> login(String username, String password, sourceType) async {
|
||||
emit(LoginLoading());
|
||||
try {
|
||||
final resultUser = await loginUseCase.call(
|
||||
final result = await loginUseCase.call(
|
||||
LoginParams(username, password, sourceType),
|
||||
);
|
||||
authCubit.loginSuccess(resultUser);
|
||||
emit(LoginSuccess(resultUser));
|
||||
result.fold((failure) => emit(LoginFailure(failure.message)), (user) {
|
||||
emit(LoginSuccess(user));
|
||||
authCubit.loginSuccess(user);
|
||||
});
|
||||
} catch (e) {
|
||||
emit(LoginFailure(e.toString()));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class ChangePasswordPage extends StatelessWidget {
|
||||
const ChangePasswordPage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('ChangePwd')),
|
||||
body: Center(child: Text('Welcome ChangePwd page')),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,42 +7,259 @@ import '../../../../core/router/route_paths.dart';
|
||||
import '../bloc/login_cubit.dart';
|
||||
import '../bloc/login_state.dart';
|
||||
|
||||
class LoginPage extends StatelessWidget {
|
||||
class LoginPage extends StatefulWidget {
|
||||
const LoginPage({super.key});
|
||||
|
||||
@override
|
||||
State<LoginPage> createState() => _LoginPageState();
|
||||
}
|
||||
|
||||
class _LoginPageState extends State<LoginPage> {
|
||||
final _userCtrl = TextEditingController();
|
||||
final _pwdCtrl = TextEditingController();
|
||||
bool _isAgreed = false; // 协议勾选状态
|
||||
bool _obscurePwd = true; // 密码可见性
|
||||
|
||||
LoginPage({super.key});
|
||||
@override
|
||||
void dispose() {
|
||||
_userCtrl.dispose();
|
||||
_pwdCtrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Login')),
|
||||
backgroundColor: Colors.white,
|
||||
// 保持 AppBar 简洁或直接去掉
|
||||
appBar: AppBar(backgroundColor: Colors.white, elevation: 0),
|
||||
body: BlocListener<LoginCubit, LoginState>(
|
||||
listener: (context, state) {
|
||||
if (state is LoginSuccess) {
|
||||
// Navigator.pushReplacement(
|
||||
// context,
|
||||
// MaterialPageRoute(builder: (_) => HomePage(user: state.user)),
|
||||
// );
|
||||
context.go(RoutePaths.home);
|
||||
} else if (state is LoginFailure) {
|
||||
// 可以在这里弹出简洁的黑白提示框
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text('登录失败,${state.message}')));
|
||||
}
|
||||
},
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 30.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const SizedBox(height: 40),
|
||||
const Text(
|
||||
"账号登录",
|
||||
style: TextStyle(
|
||||
fontSize: 28,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.black,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
const Text(
|
||||
"请填写以下信息以验证身份",
|
||||
style: TextStyle(fontSize: 15, color: Colors.grey),
|
||||
),
|
||||
const SizedBox(height: 40),
|
||||
|
||||
// 账号输入框
|
||||
_buildInputLabel("账号"),
|
||||
TextField(
|
||||
controller: _userCtrl,
|
||||
cursorColor: Colors.black,
|
||||
decoration: _inputDecoration(hint: "请输入用户名"),
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// 密码输入框
|
||||
_buildInputLabel("密码"),
|
||||
TextField(
|
||||
controller: _pwdCtrl,
|
||||
obscureText: _obscurePwd,
|
||||
cursorColor: Colors.black,
|
||||
decoration: _inputDecoration(
|
||||
hint: "请输入密码",
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(
|
||||
_obscurePwd
|
||||
? Icons.visibility_off_outlined
|
||||
: Icons.visibility_outlined,
|
||||
color: Colors.grey,
|
||||
size: 20,
|
||||
),
|
||||
onPressed: () => setState(() => _obscurePwd = !_obscurePwd),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// 协议勾选区域
|
||||
_buildProtocolSection(),
|
||||
|
||||
const SizedBox(height: 40),
|
||||
|
||||
// 登录按钮 (使用你的 CCPrimaryButton 并增加状态控制)
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: BlocBuilder<LoginCubit, LoginState>(
|
||||
builder: (context, state) {
|
||||
bool isLoading = state is LoginLoading; // 假设你有 Loading 状态
|
||||
|
||||
return CCPrimaryButton(
|
||||
onPressed: () {
|
||||
if (!_isAgreed) {
|
||||
// 如果没有勾选协议,弹出提示
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('请先阅读并同意用户协议')),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (state is! LoginLoading) {
|
||||
_handleLogin();
|
||||
}
|
||||
},
|
||||
text: state is LoginLoading ? '登录中...' : '登 录',
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 执行登录逻辑
|
||||
void _handleLogin() {
|
||||
context.read<LoginCubit>().login(_userCtrl.text, _pwdCtrl.text, 2);
|
||||
}
|
||||
|
||||
// 辅助组件:输入框标签
|
||||
Widget _buildInputLabel(String label) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8.0),
|
||||
child: Text(
|
||||
label,
|
||||
style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 辅助组件:输入框装饰
|
||||
InputDecoration _inputDecoration({required String hint, Widget? suffixIcon}) {
|
||||
return InputDecoration(
|
||||
hintText: hint,
|
||||
hintStyle: TextStyle(color: Colors.grey.shade400, fontSize: 14),
|
||||
filled: true,
|
||||
fillColor: Colors.grey.shade50,
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: BorderSide(color: Colors.grey.shade200),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: const BorderSide(color: Colors.black, width: 1),
|
||||
),
|
||||
suffixIcon: suffixIcon,
|
||||
);
|
||||
}
|
||||
|
||||
// 辅助组件:协议勾选
|
||||
Widget _buildProtocolSection() {
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
SizedBox(
|
||||
height: 24,
|
||||
width: 24,
|
||||
child: Checkbox(
|
||||
value: _isAgreed,
|
||||
activeColor: Colors.black,
|
||||
onChanged: (val) => setState(() => _isAgreed = val!),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Wrap(
|
||||
children: [
|
||||
const Text(
|
||||
"我已阅读并同意 ",
|
||||
style: TextStyle(fontSize: 13, color: Colors.grey),
|
||||
),
|
||||
_protocolText("《用户协议》", () => _showProtocolDetail("用户协议")),
|
||||
const Text(
|
||||
" 和 ",
|
||||
style: TextStyle(fontSize: 13, color: Colors.grey),
|
||||
),
|
||||
_protocolText("《隐私政策》", () => _showProtocolDetail("隐私政策")),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _protocolText(String text, VoidCallback onTap) {
|
||||
return GestureDetector(
|
||||
onTap: onTap,
|
||||
child: Text(
|
||||
text,
|
||||
style: const TextStyle(
|
||||
fontSize: 13,
|
||||
color: Colors.black,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _showProtocolDetail(String title) {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
backgroundColor: Colors.white,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
|
||||
),
|
||||
builder: (context) => Container(
|
||||
padding: const EdgeInsets.all(24),
|
||||
height: MediaQuery.of(context).size.height * 0.7,
|
||||
child: Column(
|
||||
children: [
|
||||
TextField(controller: _userCtrl),
|
||||
TextField(controller: _pwdCtrl, obscureText: true),
|
||||
CCPrimaryButton(
|
||||
onPressed: () {
|
||||
// context.read<LoginBloc>().add(
|
||||
// LoginSubmitted(_userCtrl.text, _pwdCtrl.text),
|
||||
// );
|
||||
context.read<LoginCubit>().login(
|
||||
_userCtrl.text,
|
||||
_pwdCtrl.text,
|
||||
2,
|
||||
);
|
||||
},
|
||||
text: 'Login',
|
||||
Text(
|
||||
title,
|
||||
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
|
||||
),
|
||||
const Divider(height: 32),
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
child: Text(
|
||||
"此处放置您的${title}详细内容...\n" * 20,
|
||||
style: const TextStyle(color: Colors.black87, height: 1.5),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: BlocBuilder<LoginCubit, LoginState>(
|
||||
builder: (context, state) {
|
||||
return CCPrimaryButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
text: "我已了解",
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class RegisterPage extends StatelessWidget {
|
||||
const RegisterPage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Register')),
|
||||
body: Center(child: Text('Welcome Register page')),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
19
lib/features/auth/presentation/routes/auth_routes.dart
Normal file
19
lib/features/auth/presentation/routes/auth_routes.dart
Normal file
@@ -0,0 +1,19 @@
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:maibu_satabot_v2/core/router/route_paths.dart';
|
||||
import 'package:maibu_satabot_v2/features/auth/presentation/pages/login_page.dart';
|
||||
|
||||
import '../pages/register_page.dart';
|
||||
|
||||
class AuthRoutes {
|
||||
// 返回一个 List<RouteBase>
|
||||
static List<RouteBase> routes = [
|
||||
GoRoute(
|
||||
path: RoutePaths.login,
|
||||
builder: (context, state) => const LoginPage(),
|
||||
),
|
||||
GoRoute(
|
||||
path: RoutePaths.register,
|
||||
builder: (context, state) => const RegisterPage(),
|
||||
),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart';
|
||||
|
||||
abstract class DeviceHttpDatasource {
|
||||
Future<List<DeviceEntity>> getUserDevices(String username);
|
||||
Future<int> bindDevice(String deviceId, String deviceAlias);
|
||||
Future<int> unbindDevice(String deviceId);
|
||||
Future<int> switchDevice(String platform, String deviceId);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:maibu_satabot_v2/core/consts/http_api_consts.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/data/datasources/device_http_datasource.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart';
|
||||
|
||||
class DeviceHttpDatasourceImpl implements DeviceHttpDatasource {
|
||||
final Dio dio;
|
||||
|
||||
DeviceHttpDatasourceImpl(this.dio);
|
||||
|
||||
@override
|
||||
Future<int> bindDevice(String deviceId, String deviceAlias) async {
|
||||
var response = await dio.post(
|
||||
HttpApiConsts.bindDevice,
|
||||
data: {'deviceId': deviceId, 'deviceAlias': deviceAlias},
|
||||
);
|
||||
if (response.statusCode != 200) {
|
||||
throw Exception('网络请求失败:${response.statusCode}');
|
||||
}
|
||||
|
||||
final responseData = response.data;
|
||||
|
||||
if (responseData['code'] != 200 || responseData['data'] != true) {
|
||||
throw Exception(responseData['msg'] ?? '业务异常');
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<DeviceEntity>> getUserDevices(String username) async {
|
||||
var response = await dio.get(
|
||||
HttpApiConsts.getUserDevicesList,
|
||||
queryParameters: {'tenantName': username},
|
||||
);
|
||||
if (response.statusCode != 200) {
|
||||
throw Exception('网络请求失败:${response.statusCode}');
|
||||
}
|
||||
|
||||
final responseData = response.data;
|
||||
|
||||
if (responseData['code'] != 200) {
|
||||
throw Exception(responseData['msg'] ?? '业务异常');
|
||||
}
|
||||
|
||||
if (responseData['total'] == 0) {
|
||||
return [];
|
||||
} else {
|
||||
List<DeviceEntity> devices = [];
|
||||
for (var item in responseData['rows']) {
|
||||
devices.add(DeviceEntity.fromJson(item));
|
||||
}
|
||||
return devices;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<int> switchDevice(String platform, String deviceId) async {
|
||||
var response = await dio.post(
|
||||
HttpApiConsts.switchDevice,
|
||||
data: {'platform': platform, 'deviceId': deviceId},
|
||||
);
|
||||
if (response.statusCode != 200) {
|
||||
throw Exception('网络请求失败:${response.statusCode}');
|
||||
}
|
||||
|
||||
final responseData = response.data;
|
||||
|
||||
if (responseData['code'] != 200 || responseData['data'] != true) {
|
||||
throw Exception(responseData['msg'] ?? '业务异常');
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<int> unbindDevice(String deviceId) {
|
||||
// TODO: implement unbindDevice
|
||||
throw UnimplementedError();
|
||||
}
|
||||
}
|
||||
77
lib/features/devices/data/models/device_model.dart
Normal file
77
lib/features/devices/data/models/device_model.dart
Normal file
@@ -0,0 +1,77 @@
|
||||
import 'package:maibu_satabot_v2/core/data/base_model.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart';
|
||||
|
||||
class DeviceModel extends DeviceEntity implements BaseModel {
|
||||
DeviceModel({
|
||||
required super.deviceName,
|
||||
required super.productId,
|
||||
required super.productName,
|
||||
required super.tenantId,
|
||||
required super.tenantName,
|
||||
required super.status,
|
||||
required super.activeTime,
|
||||
required super.deviceAlias,
|
||||
required super.isBind,
|
||||
required super.onlineStatus,
|
||||
});
|
||||
|
||||
factory DeviceModel.fromJson(Map<String, dynamic> json) {
|
||||
return DeviceModel(
|
||||
deviceName: json['deviceName'],
|
||||
productId: json['productId'],
|
||||
productName: json['productName'],
|
||||
tenantId: json['tenantId'],
|
||||
tenantName: json['tenantName'],
|
||||
status: json['status'],
|
||||
activeTime: json['activeTime'],
|
||||
deviceAlias: json['deviceAlias'],
|
||||
isBind: json['isBind'],
|
||||
onlineStatus: json['onlineStatus'],
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'deviceName': deviceName,
|
||||
'productId': productId,
|
||||
'productName': productName,
|
||||
'tenantId': tenantId,
|
||||
'tenantName': tenantName,
|
||||
'status': status,
|
||||
'activeTime': activeTime,
|
||||
'deviceAlias': deviceAlias,
|
||||
'isBind': isBind,
|
||||
'onlineStatus': onlineStatus,
|
||||
};
|
||||
}
|
||||
|
||||
toEntity() {
|
||||
return DeviceEntity(
|
||||
deviceName: deviceName,
|
||||
productId: productId,
|
||||
productName: productName,
|
||||
tenantId: tenantId,
|
||||
tenantName: tenantName,
|
||||
status: status,
|
||||
activeTime: activeTime,
|
||||
deviceAlias: deviceAlias,
|
||||
isBind: isBind,
|
||||
onlineStatus: onlineStatus,
|
||||
);
|
||||
}
|
||||
|
||||
factory DeviceModel.fromEntity(DeviceEntity entity) {
|
||||
return DeviceModel(
|
||||
deviceName: entity.deviceName,
|
||||
productId: entity.productId,
|
||||
productName: entity.productName,
|
||||
tenantId: entity.tenantId,
|
||||
tenantName: entity.tenantName,
|
||||
status: entity.status,
|
||||
activeTime: entity.activeTime,
|
||||
deviceAlias: entity.deviceAlias,
|
||||
isBind: entity.isBind,
|
||||
onlineStatus: entity.onlineStatus,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:fpdart/src/either.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/data/datasources/device_http_datasource.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/errors/device_failure.dart';
|
||||
|
||||
import '../../domain/repositories/device_repository.dart';
|
||||
|
||||
class DeviceRepositoryImpl implements DeviceRepository {
|
||||
DeviceHttpDatasource _deviceHttpDatasource;
|
||||
|
||||
DeviceRepositoryImpl(this._deviceHttpDatasource);
|
||||
|
||||
@override
|
||||
Future<Either<DeviceFailure, int>> bindDevice(
|
||||
String deviceId,
|
||||
String deviceAlias,
|
||||
) async {
|
||||
try {
|
||||
var result = await _deviceHttpDatasource.bindDevice(
|
||||
deviceId,
|
||||
deviceAlias,
|
||||
);
|
||||
return Right(result);
|
||||
} on DioException catch (e) {
|
||||
final String serverMessage = e.response?.data['msg'] ?? "网络连接异常";
|
||||
return Left(DeviceFailure(serverMessage));
|
||||
} catch (e) {
|
||||
final cleanMessage = e.toString().replaceFirst('Exception: ', '');
|
||||
return Left(DeviceFailure(cleanMessage));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Either<DeviceFailure, List<DeviceEntity>>> getUserDevice(
|
||||
String username,
|
||||
) async {
|
||||
try {
|
||||
var result = await _deviceHttpDatasource.getUserDevices(username);
|
||||
return Right(result);
|
||||
} on DioException catch (e) {
|
||||
final String serverMessage = e.response?.data['msg'] ?? "网络连接异常";
|
||||
return Left(DeviceFailure(serverMessage));
|
||||
} catch (e) {
|
||||
final cleanMessage = e.toString().replaceFirst('Exception: ', '');
|
||||
return Left(DeviceFailure(cleanMessage));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Either<DeviceFailure, int>> unBindDevice(String deviceId) {
|
||||
// TODO: implement unBindDevice
|
||||
throw UnimplementedError();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Either<DeviceFailure, int>> switchDevice(
|
||||
String platform,
|
||||
String deviceId,
|
||||
) async {
|
||||
try {
|
||||
var result = await _deviceHttpDatasource.switchDevice(platform, deviceId);
|
||||
return Right(result);
|
||||
} on DioException catch (e) {
|
||||
final String serverMessage = e.response?.data['msg'] ?? "网络连接异常";
|
||||
return Left(DeviceFailure(serverMessage));
|
||||
} catch (e) {
|
||||
final cleanMessage = e.toString().replaceFirst('Exception: ', '');
|
||||
return Left(DeviceFailure(cleanMessage));
|
||||
}
|
||||
}
|
||||
}
|
||||
65
lib/features/devices/domain/entities/device_entity.dart
Normal file
65
lib/features/devices/domain/entities/device_entity.dart
Normal file
@@ -0,0 +1,65 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class DeviceEntity extends Equatable {
|
||||
final String deviceName;
|
||||
final int productId;
|
||||
final String productName;
|
||||
final int tenantId;
|
||||
final String tenantName;
|
||||
final int status;
|
||||
final String? activeTime;
|
||||
final String? deviceAlias;
|
||||
final int isBind; // 是否被绑定过
|
||||
final int onlineStatus; // 在线状态
|
||||
|
||||
DeviceEntity({
|
||||
required this.deviceName,
|
||||
required this.productId,
|
||||
required this.productName,
|
||||
required this.tenantId,
|
||||
required this.tenantName,
|
||||
this.status = 0,
|
||||
this.activeTime,
|
||||
this.deviceAlias,
|
||||
this.isBind = 0,
|
||||
this.onlineStatus = 0,
|
||||
});
|
||||
|
||||
// 方便从后端 JSON 转换
|
||||
factory DeviceEntity.fromJson(Map<String, dynamic> json) {
|
||||
return DeviceEntity(
|
||||
deviceName: json['deviceName'],
|
||||
productId: json['productId'] ?? -1,
|
||||
productName: json['productName'] ?? "割草机产品MC700",
|
||||
tenantId: json['tenantId'],
|
||||
tenantName: json['tenantName'],
|
||||
status: json['status'] ?? 0,
|
||||
activeTime: json['activeTime'],
|
||||
deviceAlias: json['deviceAlias'],
|
||||
isBind: json['isBind'] ?? 0,
|
||||
onlineStatus: json['onlineStatus'] ?? 0,
|
||||
);
|
||||
}
|
||||
|
||||
// 获取显示的名称(优先别名,没有则用设备名)
|
||||
String get displayName => (deviceAlias != null && deviceAlias!.isNotEmpty)
|
||||
? deviceAlias!
|
||||
: (deviceName ?? "未知设备");
|
||||
|
||||
// 辅助方法:判断是否在线
|
||||
bool get isOnline => onlineStatus == 1;
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
deviceName,
|
||||
productId,
|
||||
productName,
|
||||
tenantId,
|
||||
tenantName,
|
||||
status,
|
||||
activeTime,
|
||||
deviceAlias,
|
||||
isBind,
|
||||
onlineStatus,
|
||||
];
|
||||
}
|
||||
18
lib/features/devices/domain/errors/device_failure.dart
Normal file
18
lib/features/devices/domain/errors/device_failure.dart
Normal file
@@ -0,0 +1,18 @@
|
||||
import '../../../../core/error/failure.dart';
|
||||
|
||||
class DeviceFailure extends Failure implements Exception {
|
||||
final int? code;
|
||||
DeviceFailure(super.message, {this.code});
|
||||
}
|
||||
|
||||
class DeviceNotConnectedFailure extends DeviceFailure {
|
||||
DeviceNotConnectedFailure(super.message);
|
||||
}
|
||||
|
||||
class DeviceOfflineFailure extends DeviceFailure {
|
||||
DeviceOfflineFailure(super.message);
|
||||
}
|
||||
|
||||
class DeviceNotBoundFailure extends DeviceFailure {
|
||||
DeviceNotBoundFailure(super.message);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/errors/device_failure.dart';
|
||||
|
||||
abstract class DeviceRepository {
|
||||
Future<Either<DeviceFailure, List<DeviceEntity>>> getUserDevice(
|
||||
String userName,
|
||||
);
|
||||
Future<Either<DeviceFailure, int>> bindDevice(
|
||||
String deviceId,
|
||||
String deviceAlias,
|
||||
);
|
||||
Future<Either<DeviceFailure, int>> unBindDevice(String deviceId);
|
||||
Future<Either<DeviceFailure, int>> switchDevice(
|
||||
String platform,
|
||||
String deviceId,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import 'package:maibu_satabot_v2/core/domain/usecases/base_usecase.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/errors/device_failure.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/repositories/device_repository.dart';
|
||||
|
||||
class BindDeviceUseCase implements BaseUseCase<int, BindDeviceParams> {
|
||||
final DeviceRepository deviceRepository;
|
||||
|
||||
BindDeviceUseCase(this.deviceRepository);
|
||||
|
||||
@override
|
||||
Future<Either<DeviceFailure, int>> call(BindDeviceParams params) async {
|
||||
return await deviceRepository.bindDevice(
|
||||
params.deviceId,
|
||||
params.deviceAlias,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class BindDeviceParams {
|
||||
final String deviceId;
|
||||
final String deviceAlias;
|
||||
|
||||
BindDeviceParams(this.deviceId, this.deviceAlias);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import 'package:maibu_satabot_v2/core/domain/usecases/base_usecase.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/errors/device_failure.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/repositories/device_repository.dart';
|
||||
|
||||
class GetUserDeviceUseCase
|
||||
implements BaseUseCase<List<DeviceEntity>, GetUserDeviceParams> {
|
||||
final DeviceRepository repository;
|
||||
|
||||
GetUserDeviceUseCase(this.repository);
|
||||
|
||||
@override
|
||||
Future<Either<DeviceFailure, List<DeviceEntity>>> call(
|
||||
GetUserDeviceParams params,
|
||||
) async {
|
||||
return await repository.getUserDevice(params.tenantName);
|
||||
}
|
||||
}
|
||||
|
||||
class GetUserDeviceParams {
|
||||
final String tenantName;
|
||||
|
||||
GetUserDeviceParams(this.tenantName);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import 'package:maibu_satabot_v2/core/domain/usecases/base_usecase.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/errors/device_failure.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/repositories/device_repository.dart';
|
||||
|
||||
class SwitchDeviceUseCase implements BaseUseCase<int, SwitchDeviceParams> {
|
||||
final DeviceRepository deviceRepository;
|
||||
|
||||
SwitchDeviceUseCase(this.deviceRepository);
|
||||
|
||||
@override
|
||||
Future<Either<DeviceFailure, int>> call(SwitchDeviceParams params) async {
|
||||
return await deviceRepository.switchDevice(
|
||||
params.platform,
|
||||
params.deviceId,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class SwitchDeviceParams {
|
||||
final String platform;
|
||||
final String deviceId;
|
||||
|
||||
SwitchDeviceParams(this.platform, this.deviceId);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import 'package:maibu_satabot_v2/core/domain/usecases/base_usecase.dart';
|
||||
import 'package:maibu_satabot_v2/core/error/failure.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/repositories/device_repository.dart';
|
||||
|
||||
class UnbindDeviceUseCase implements BaseUseCase<int, UnbindDeviceParams> {
|
||||
final DeviceRepository repository;
|
||||
|
||||
UnbindDeviceUseCase(this.repository);
|
||||
|
||||
@override
|
||||
Future<Either<Failure, int>> call(UnbindDeviceParams params) async {
|
||||
return await repository.unBindDevice(params.deviceId);
|
||||
}
|
||||
}
|
||||
|
||||
class UnbindDeviceParams {
|
||||
final String deviceId;
|
||||
|
||||
UnbindDeviceParams(this.deviceId);
|
||||
}
|
||||
78
lib/features/devices/presentation/bloc/devices_cubit.dart
Normal file
78
lib/features/devices/presentation/bloc/devices_cubit.dart
Normal file
@@ -0,0 +1,78 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/repositories/device_repository.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/usecases/get_user_device_usecase.dart';
|
||||
|
||||
import 'devices_state.dart';
|
||||
|
||||
class DevicesCubit extends Cubit<DevicesState> {
|
||||
final GetUserDeviceUseCase _getUserDeviceUseCase;
|
||||
|
||||
final DeviceRepository repository;
|
||||
|
||||
DevicesCubit(this.repository, this._getUserDeviceUseCase)
|
||||
: super(const DevicesState());
|
||||
|
||||
// 获取所有设备列表
|
||||
Future<void> fetchAllDevices(String username) async {
|
||||
emit(state.copyWith(isLoading: true));
|
||||
try {
|
||||
// 模拟网络请求获取列表
|
||||
var resultEither = await _getUserDeviceUseCase.call(
|
||||
GetUserDeviceParams(username),
|
||||
);
|
||||
|
||||
resultEither.fold(
|
||||
(failure) => emit(
|
||||
state.copyWith(
|
||||
isLoading: false,
|
||||
errorMessage: failure.message, // 假设你的 Failure 类有 message 字段
|
||||
),
|
||||
),
|
||||
(deviceList) {
|
||||
emit(
|
||||
state.copyWith(
|
||||
devices: deviceList,
|
||||
selectedDevice: deviceList.isNotEmpty ? deviceList.first : null,
|
||||
isLoading: false,
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
emit(state.copyWith(isLoading: false, errorMessage: e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
// 切换当前选中的设备
|
||||
void selectDevice(DeviceEntity device) {
|
||||
emit(state.copyWith(selectedDevice: device));
|
||||
}
|
||||
|
||||
// 更新单个设备的状态(例如从 Tcp 收到实时电量更新)
|
||||
void updateDeviceStatus(DeviceEntity updatedDevice) {
|
||||
final newList = state.devices.map((d) {
|
||||
return d.deviceName == updatedDevice.deviceName ? updatedDevice : d;
|
||||
}).toList();
|
||||
|
||||
// 如果更新的是当前选中的设备,也要同步更新 selectedDevice
|
||||
final newSelected =
|
||||
state.selectedDevice?.deviceName == updatedDevice.deviceName
|
||||
? updatedDevice
|
||||
: state.selectedDevice;
|
||||
|
||||
emit(state.copyWith(devices: newList, selectedDevice: newSelected));
|
||||
}
|
||||
|
||||
Future<void> switchDevice(DeviceEntity device) async {
|
||||
// 保持现有列表,只改 loading
|
||||
emit(state.copyWith(isLoading: true));
|
||||
|
||||
final result = await repository.switchDevice("app", device.deviceName);
|
||||
|
||||
result.fold((l) {
|
||||
emit(state.copyWith(isLoading: false, errorMessage: l.message));
|
||||
selectDevice(device);
|
||||
}, (r) => emit(state.copyWith(isLoading: false, selectedDevice: device)));
|
||||
}
|
||||
}
|
||||
34
lib/features/devices/presentation/bloc/devices_state.dart
Normal file
34
lib/features/devices/presentation/bloc/devices_state.dart
Normal file
@@ -0,0 +1,34 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart';
|
||||
|
||||
class DevicesState extends Equatable {
|
||||
final List<DeviceEntity> devices; // 名下所有设备列表
|
||||
final DeviceEntity? selectedDevice; // 当前主界面选中的/操作的设备
|
||||
final bool isLoading; // 是否正在加载
|
||||
final String? errorMessage; // 错误信息
|
||||
|
||||
const DevicesState({
|
||||
this.devices = const [],
|
||||
this.selectedDevice,
|
||||
this.isLoading = false,
|
||||
this.errorMessage,
|
||||
});
|
||||
|
||||
// 使用 copyWith 方便局部更新状态
|
||||
DevicesState copyWith({
|
||||
List<DeviceEntity>? devices,
|
||||
DeviceEntity? selectedDevice,
|
||||
bool? isLoading,
|
||||
String? errorMessage,
|
||||
}) {
|
||||
return DevicesState(
|
||||
devices: devices ?? this.devices,
|
||||
selectedDevice: selectedDevice ?? this.selectedDevice,
|
||||
isLoading: isLoading ?? this.isLoading,
|
||||
errorMessage: errorMessage, // 错误信息通常每次更新都要重新赋值或清空
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [devices, selectedDevice, isLoading, errorMessage];
|
||||
}
|
||||
@@ -1,18 +1,44 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/presentation/bloc/devices_cubit.dart';
|
||||
|
||||
import '../../../../core/app/app_cubit.dart';
|
||||
import '../../../../core/di/injection.dart';
|
||||
import '../widgets/ImmersionHeader.dart';
|
||||
import '../widgets/quick_actions_grid.dart';
|
||||
import '../widgets/work_params_card.dart';
|
||||
|
||||
class HomePage extends StatelessWidget {
|
||||
// final User user;
|
||||
// const HomePage({super.key, required this.user});
|
||||
const HomePage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final user = sl<AppCubit>().state.user;
|
||||
// 同时监听用户和设备状态
|
||||
final userState = context.watch<AppUserCubit>().state;
|
||||
final deviceState = context.watch<DevicesCubit>().state;
|
||||
final currentDevice = deviceState.selectedDevice;
|
||||
|
||||
if (currentDevice == null)
|
||||
return const Scaffold(body: Center(child: Text("加载中...")));
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Home')),
|
||||
body: Center(child: Text('Welcome ${user?.username}')),
|
||||
backgroundColor: const Color(0xFFF7F7F7),
|
||||
body: CustomScrollView(
|
||||
physics: const BouncingScrollPhysics(),
|
||||
slivers: [
|
||||
// 1. 沉浸式顶部展示区
|
||||
SliverToBoxAdapter(child: ImmersionHeader(device: currentDevice)),
|
||||
|
||||
// 2. 功能网格(保持原有逻辑,但背景建议改为纯白)
|
||||
const SliverToBoxAdapter(child: QuickActionsGrid()),
|
||||
|
||||
// 3. 作业参数卡片
|
||||
SliverToBoxAdapter(child: WorkParamsCard()),
|
||||
|
||||
// 4. 地图区域
|
||||
// SliverToBoxAdapter(child: _buildMapSection()),
|
||||
const SliverToBoxAdapter(child: SizedBox(height: 120)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
28
lib/features/home/presentation/pages/route_plan_page.dart
Normal file
28
lib/features/home/presentation/pages/route_plan_page.dart
Normal file
@@ -0,0 +1,28 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../../../../core/app/app_user_cubit.dart';
|
||||
import '../../../devices/presentation/bloc/devices_cubit.dart';
|
||||
|
||||
class RoutePlanPage extends StatelessWidget {
|
||||
const RoutePlanPage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// 同时监听用户和设备状态
|
||||
final userState = context.read<AppUserCubit>().state;
|
||||
final deviceState = context.read<DevicesCubit>().state;
|
||||
final currentDevice = deviceState.selectedDevice;
|
||||
|
||||
if (currentDevice == null)
|
||||
return const Scaffold(body: Center(child: Text("加载中...")));
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: const Color(0xFFF7F7F7),
|
||||
body: CustomScrollView(
|
||||
physics: const BouncingScrollPhysics(),
|
||||
slivers: [],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../../../../core/app/app_user_cubit.dart';
|
||||
import '../../../devices/presentation/bloc/devices_cubit.dart';
|
||||
|
||||
class RunningStatusPage extends StatelessWidget {
|
||||
const RunningStatusPage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// 同时监听用户和设备状态
|
||||
final userState = context.read<AppUserCubit>().state;
|
||||
final deviceState = context.read<DevicesCubit>().state;
|
||||
final currentDevice = deviceState.selectedDevice;
|
||||
|
||||
if (currentDevice == null)
|
||||
return const Scaffold(body: Center(child: Text("加载中...")));
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: const Color(0xFFF7F7F7),
|
||||
body: CustomScrollView(
|
||||
physics: const BouncingScrollPhysics(),
|
||||
slivers: [],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
44
lib/features/home/presentation/routes/home_routes.dart
Normal file
44
lib/features/home/presentation/routes/home_routes.dart
Normal file
@@ -0,0 +1,44 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:maibu_satabot_v2/features/home/presentation/pages/home_page.dart';
|
||||
|
||||
import '../../../../core/di/injection.dart';
|
||||
import '../../../../core/router/route_paths.dart';
|
||||
import '../../../remote_control/presentation/bloc/remote_control_cubit.dart';
|
||||
import '../../../remote_control/presentation/pages/remote_control_page.dart';
|
||||
import '../pages/route_plan_page.dart';
|
||||
import '../pages/running_status_page.dart';
|
||||
|
||||
class HomeRoutes {
|
||||
/// 1. 全屏功能页面(不带导航栏)
|
||||
/// 在 createRouter 的根 routes 中使用 ...HomeRoutes.routes 引入
|
||||
static List<RouteBase> get routes => [
|
||||
GoRoute(
|
||||
path: RoutePaths.remoteControl,
|
||||
builder: (context, state) => BlocProvider(
|
||||
// 每次进入该路由,都会创建一个全新的 Cubit 并开启循环
|
||||
create: (context) => sl<RemoteControlCubit>()..startControlLoop(),
|
||||
child: const RemoteControlPage(),
|
||||
),
|
||||
),
|
||||
GoRoute(
|
||||
path: RoutePaths.routePlan,
|
||||
builder: (context, state) => const RoutePlanPage(),
|
||||
),
|
||||
GoRoute(
|
||||
path: RoutePaths.runningStatus,
|
||||
builder: (context, state) => const RunningStatusPage(),
|
||||
),
|
||||
];
|
||||
|
||||
/// 2. 首页 Tab 分支(带导航栏)
|
||||
/// 仅保留真正的首页入口
|
||||
static StatefulShellBranch get branch => StatefulShellBranch(
|
||||
routes: [
|
||||
GoRoute(
|
||||
path: RoutePaths.home,
|
||||
builder: (context, state) => const HomePage(),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
410
lib/features/home/presentation/widgets/ImmersionHeader.dart
Normal file
410
lib/features/home/presentation/widgets/ImmersionHeader.dart
Normal file
@@ -0,0 +1,410 @@
|
||||
import 'package:cc_ui_kit/cc_ui_kit.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:google_fonts/google_fonts.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart';
|
||||
|
||||
import '../../../../core/app/app_user_cubit.dart';
|
||||
import '../../../devices/presentation/bloc/devices_cubit.dart';
|
||||
import '../../../devices/presentation/bloc/devices_state.dart';
|
||||
// 导入你的主题文件以获取 offWhite
|
||||
// import 'package:maibu_satabot_v2/core/theme/app_theme.dart';
|
||||
|
||||
class ImmersionHeader extends StatelessWidget {
|
||||
final DeviceEntity device;
|
||||
const ImmersionHeader({super.key, required this.device});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
height: 380,
|
||||
// 1. 修改这里:去掉 color: Colors.white,改用透明或背景色
|
||||
decoration: const BoxDecoration(
|
||||
color: Colors.transparent, // 设为透明,直接透出 Scaffold 的 offWhite
|
||||
),
|
||||
child: Stack(
|
||||
children: [
|
||||
// 背景文字占位 (SataBot)
|
||||
Positioned(
|
||||
top: 140,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: Text(
|
||||
'SataBot',
|
||||
textAlign: TextAlign.center,
|
||||
style: GoogleFonts.roboto(
|
||||
fontSize: 100,
|
||||
fontWeight: FontWeight.w900,
|
||||
// 2. 既然背景变深了,背景字可以稍微再淡一点点
|
||||
color: Colors.black.withOpacity(0.08),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// 机器大图
|
||||
Transform.translate(
|
||||
offset: const Offset(20, 90), // 正数向右移动(例如 20 像素),负数向左
|
||||
child: Center(
|
||||
child: Image.asset(
|
||||
'assets/images/car.png',
|
||||
width: 380,
|
||||
fit: BoxFit.contain,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// 顶部状态信息
|
||||
SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 10),
|
||||
child: Row(
|
||||
// 1. 依然保持顶部对齐
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
// --- 左侧:标题 + 进度条 + 状态标签 (封装成一个 Column) ---
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min, // 尽可能收缩高度
|
||||
children: [
|
||||
// 设备名称和电量
|
||||
Text(
|
||||
device.displayName,
|
||||
style: GoogleFonts.roboto(
|
||||
fontSize: 22,
|
||||
fontWeight: FontWeight.w900,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
'${device.onlineStatus == 1 ? "100" : "--"} %',
|
||||
style: GoogleFonts.roboto(
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.w900,
|
||||
),
|
||||
),
|
||||
const Icon(
|
||||
Icons.chevron_right,
|
||||
size: 20,
|
||||
color: Colors.grey,
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
const SizedBox(height: 8),
|
||||
|
||||
// 2. 进度条现在紧跟在电量下面,不会被右侧挤走
|
||||
_buildProgressBar(),
|
||||
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// 3. 状态标签也紧跟其后
|
||||
_buildStatusTag(device.isOnline),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
// --- 右侧:图标栏 ---
|
||||
Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
_buildCircleIcon(Icons.sync, () {
|
||||
// 1. 触发 Cubit 请求最新设备列表
|
||||
// 假设你的 username 存储在 AuthCubit 或类似的全局状态中
|
||||
final username =
|
||||
context.read<AppUserCubit>().state.user?.username ??
|
||||
"";
|
||||
context.read<DevicesCubit>().fetchAllDevices(username);
|
||||
|
||||
// 2. 弹出窗口(窗口内部会根据状态显示转圈或列表)
|
||||
_showDeviceSwitcher(context);
|
||||
}),
|
||||
const SizedBox(height: 20), // 这里你改大的间距,只会让两个图标拉开
|
||||
_buildCircleIcon(Icons.bluetooth, null, isAccent: true),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildStatusTag(bool isOnline) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
// 在 offWhite 背景下,标签用纯白色会显得更精致
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
boxShadow: [
|
||||
BoxShadow(color: Colors.black.withOpacity(0.02), blurRadius: 4),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
CircleAvatar(
|
||||
radius: 3,
|
||||
backgroundColor: isOnline ? Colors.green : Colors.grey,
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
isOnline ? "在线" : "离线",
|
||||
style: const TextStyle(fontSize: 12, color: Colors.black54),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 辅助方法:进度条
|
||||
Widget _buildProgressBar() {
|
||||
return Container(
|
||||
width: 120,
|
||||
height: 6,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.blueAccent,
|
||||
borderRadius: BorderRadius.circular(5),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildCircleIcon(
|
||||
IconData icon,
|
||||
VoidCallback? voidCallback, { // 将回调函数放在这里
|
||||
bool isAccent = false,
|
||||
}) {
|
||||
return GestureDetector(
|
||||
onTap: voidCallback, // 绑定点击事件
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: isAccent ? Colors.blue.withOpacity(0.1) : Colors.white,
|
||||
boxShadow: [
|
||||
if (!isAccent)
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.02),
|
||||
blurRadius: 4,
|
||||
offset: const Offset(0, 2), // 稍微增加偏移感
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Icon(
|
||||
icon,
|
||||
size: 30,
|
||||
color: isAccent ? Colors.blue : Colors.black54,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 设备切换窗口
|
||||
void _showDeviceSwitcher(BuildContext context) {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
useRootNavigator: true, // 💡 解决被三段导航栏遮挡的问题
|
||||
backgroundColor: Colors.transparent,
|
||||
builder: (modalContext) {
|
||||
return Container(
|
||||
height: MediaQuery.of(context).size.height * 0.75,
|
||||
decoration: const BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
// 优化的控制条
|
||||
Container(
|
||||
margin: const EdgeInsets.symmetric(vertical: 12),
|
||||
width: 36,
|
||||
height: 5,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.grey[300],
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
),
|
||||
const Text(
|
||||
"切换设备",
|
||||
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Container(
|
||||
height: 0.5,
|
||||
margin: const EdgeInsets.symmetric(horizontal: 20),
|
||||
color: Colors.grey.withOpacity(0.1),
|
||||
),
|
||||
|
||||
// 💡 动态内容区
|
||||
Expanded(
|
||||
child: BlocBuilder<DevicesCubit, DevicesState>(
|
||||
builder: (context, state) {
|
||||
// 1. 如果正在加载(查询或切换中),显示转圈
|
||||
if (state.isLoading) {
|
||||
return Center(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const CircularProgressIndicator(color: Colors.blue),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
"处理中...",
|
||||
style: TextStyle(color: Colors.grey[600]),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 2. 列表展示
|
||||
if (state.devices.isEmpty) {
|
||||
return const Center(child: Text("暂无可用设备"));
|
||||
}
|
||||
|
||||
return ListView.builder(
|
||||
// 💡 底部留出安全距离,防止最后一条滚不上来
|
||||
padding: EdgeInsets.only(
|
||||
bottom: MediaQuery.of(context).padding.bottom + 20,
|
||||
top: 10,
|
||||
),
|
||||
itemCount: state.devices.length,
|
||||
itemBuilder: (context, index) {
|
||||
// 传入当前选中的 ID 方便做 UI 区分
|
||||
final isSelected =
|
||||
state.selectedDevice?.deviceName ==
|
||||
state.devices[index].deviceName;
|
||||
return _buildDeviceItem(
|
||||
state.devices[index],
|
||||
context,
|
||||
isSelected,
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildDeviceItem(
|
||||
DeviceEntity device,
|
||||
BuildContext context,
|
||||
bool isSelected,
|
||||
) {
|
||||
return GestureDetector(
|
||||
onTap: () {
|
||||
print("跳转到详情页: ${device.deviceAlias}");
|
||||
// TODO: Navigator.push(...)
|
||||
},
|
||||
child: Container(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
// 💡 如果是当前选中设备,边框颜色略深
|
||||
border: Border.all(
|
||||
color: isSelected
|
||||
? Colors.blue.withOpacity(0.5)
|
||||
: Colors.grey.withOpacity(0.3),
|
||||
width: isSelected ? 1.5 : 1,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
boxShadow: [
|
||||
if (isSelected)
|
||||
BoxShadow(color: Colors.blue.withOpacity(0.05), blurRadius: 4),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
// 设备图片
|
||||
Transform.translate(
|
||||
offset: const Offset(10, 0),
|
||||
child: Image.asset(
|
||||
'assets/images/car.png',
|
||||
width: 100,
|
||||
height: 80,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
// 设备信息
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.circle,
|
||||
color: device.isOnline ? Colors.green : Colors.grey,
|
||||
size: 12,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
device.deviceAlias ?? '未知设备',
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
],
|
||||
),
|
||||
const Text(
|
||||
"点击查看详情",
|
||||
style: TextStyle(color: Colors.grey, fontSize: 12),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// 按钮组
|
||||
Column(
|
||||
children: [
|
||||
CCPrimaryImageButton(
|
||||
onPressed: isSelected
|
||||
? null
|
||||
: () async {
|
||||
// 💡 执行切换逻辑
|
||||
await context.read<DevicesCubit>().switchDevice(
|
||||
device,
|
||||
);
|
||||
// 切换成功后,UI 会自动更新(因为 BlocBuilder 在监听),我们可以关闭弹窗
|
||||
if (context.mounted) {
|
||||
Navigator.pop(context);
|
||||
}
|
||||
},
|
||||
text: isSelected ? "使用中" : "切换",
|
||||
width: 80,
|
||||
height: 30,
|
||||
fontSize: 14,
|
||||
// 如果是当前设备,按钮颜色变灰
|
||||
backgroundColor: isSelected ? Colors.grey : Colors.black,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
CCPrimaryButton(
|
||||
onPressed: () {
|
||||
print("通过按钮进入详情");
|
||||
},
|
||||
text: "详情",
|
||||
width: 80,
|
||||
height: 30,
|
||||
fontSize: 14,
|
||||
backgroundColor: Colors.white,
|
||||
textColor: Colors.black,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class DeviceStatusCard extends StatelessWidget {
|
||||
const DeviceStatusCard({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
padding: const EdgeInsets.all(20),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(28),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
// 设备图片/占位
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(16), // 保持和原代码一致的圆角
|
||||
child: Transform.translate(
|
||||
offset: const Offset(10, 0), // 向左偏移10像素,Y轴不变
|
||||
child: Image.asset(
|
||||
'assets/images/car.png',
|
||||
width: 120,
|
||||
height: 80,
|
||||
fit: BoxFit.cover, // 确保图片填满80x80的区域
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
// 信息区
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
const Text(
|
||||
'未知设备',
|
||||
style: TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
Icon(Icons.swap_horiz, color: Colors.grey[400]),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
_buildTag('离线', Colors.grey[400]!),
|
||||
const Spacer(),
|
||||
const Icon(Icons.battery_3_bar_rounded, size: 18),
|
||||
const Text(
|
||||
' 0%',
|
||||
style: TextStyle(fontWeight: FontWeight.w500),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildTag(String text, Color color) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.2),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: Text(
|
||||
text,
|
||||
style: TextStyle(
|
||||
color: color,
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:maibu_satabot_v2/core/router/route_paths.dart';
|
||||
|
||||
class QuickActionsGrid extends StatelessWidget {
|
||||
const QuickActionsGrid({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
_buildActionItem(
|
||||
icon: Icons.videogame_asset_outlined,
|
||||
label: '远程遥控',
|
||||
iconColor: Colors.blue,
|
||||
onTap: () => context.push(RoutePaths.remoteControl),
|
||||
),
|
||||
_buildActionItem(
|
||||
icon: Icons.near_me_outlined,
|
||||
label: '路径规划',
|
||||
iconColor: Colors.purple,
|
||||
onTap: () => context.push(RoutePaths.routePlan),
|
||||
),
|
||||
_buildActionItem(
|
||||
icon: Icons.insights_rounded,
|
||||
label: '机器状态',
|
||||
iconColor: Colors.orange,
|
||||
onTap: () => context.push(RoutePaths.runningStatus),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 💡 改造后的构建函数,支持命名参数和点击事件
|
||||
Widget _buildActionItem({
|
||||
required IconData icon,
|
||||
required String label,
|
||||
required Color iconColor,
|
||||
required VoidCallback onTap,
|
||||
}) {
|
||||
return Expanded(
|
||||
child: Container(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 4),
|
||||
// 💡 使用 Material 和 InkWell 组合来实现点击效果
|
||||
child: Material(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
child: InkWell(
|
||||
onTap: onTap,
|
||||
borderRadius: BorderRadius.circular(20), // 确保水波纹不超出圆角
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
child: Column(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: iconColor.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
child: Icon(icon, color: iconColor),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
label,
|
||||
style: const TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
147
lib/features/home/presentation/widgets/work_params_card.dart
Normal file
147
lib/features/home/presentation/widgets/work_params_card.dart
Normal file
@@ -0,0 +1,147 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class WorkParamsCard extends StatelessWidget {
|
||||
const WorkParamsCard({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
padding: const EdgeInsets.all(20),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
// 极淡的阴影
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.02),
|
||||
blurRadius: 10,
|
||||
offset: const Offset(0, 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// 标题行
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
// 左侧蓝色装饰条
|
||||
Container(
|
||||
width: 4,
|
||||
height: 16,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.blueAccent,
|
||||
borderRadius: BorderRadius.circular(2),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
const Text(
|
||||
'作业参数',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.black,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
// 刷新状态
|
||||
Row(
|
||||
children: [
|
||||
Icon(Icons.refresh, size: 14, color: Colors.grey[400]),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
'刚刚更新',
|
||||
style: TextStyle(fontSize: 12, color: Colors.grey[400]),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// 数据展示行
|
||||
IntrinsicHeight(
|
||||
// 关键:使分割线高度自动充满
|
||||
child: Row(
|
||||
children: [
|
||||
_buildParamItem('作业面积', '0', '亩'),
|
||||
_buildDivider(),
|
||||
_buildParamItem('作业里程', '0', 'km'),
|
||||
_buildDivider(),
|
||||
_buildParamItem('作业时长', '0', 'h'),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 构建单个参数项
|
||||
Widget _buildParamItem(String label, String value, String unit) {
|
||||
return Expanded(
|
||||
child: Column(
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
label == '作业面积'
|
||||
? Icons.aspect_ratio
|
||||
: label == '作业里程'
|
||||
? Icons.local_shipping_outlined
|
||||
: Icons.access_time,
|
||||
size: 14,
|
||||
color: Colors.black38,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
label,
|
||||
style: const TextStyle(fontSize: 12, color: Colors.black38),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
RichText(
|
||||
text: TextSpan(
|
||||
children: [
|
||||
TextSpan(
|
||||
text: value,
|
||||
style: const TextStyle(
|
||||
fontSize: 28,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: Colors.black,
|
||||
fontFamily: 'Inter', // 建议使用数字显示更漂亮的字体
|
||||
),
|
||||
),
|
||||
TextSpan(
|
||||
text: ' $unit',
|
||||
style: const TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.normal,
|
||||
color: Colors.black54,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 垂直分割线
|
||||
Widget _buildDivider() {
|
||||
return VerticalDivider(
|
||||
color: Colors.black.withOpacity(0.05),
|
||||
thickness: 1,
|
||||
indent: 10,
|
||||
endIndent: 10,
|
||||
);
|
||||
}
|
||||
}
|
||||
84
lib/features/main_container/presentation/main_wrapper.dart
Normal file
84
lib/features/main_container/presentation/main_wrapper.dart
Normal file
@@ -0,0 +1,84 @@
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:google_nav_bar/google_nav_bar.dart';
|
||||
|
||||
class MainWrapper extends StatelessWidget {
|
||||
final StatefulNavigationShell navigationShell;
|
||||
|
||||
const MainWrapper({super.key, required this.navigationShell});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
extendBody: true, // 必须开启,让内容流过导航栏下方
|
||||
body: navigationShell,
|
||||
bottomNavigationBar: Container(
|
||||
margin: const EdgeInsets.fromLTRB(20, 0, 20, 32), // 稍微调高底部间距
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(32),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.12), // 强化阴影,增加悬浮感
|
||||
blurRadius: 30,
|
||||
offset: const Offset(0, 10),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(32),
|
||||
child: BackdropFilter(
|
||||
filter: ImageFilter.blur(sigmaX: 16, sigmaY: 16), // 增加模糊半径
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
// 降低白色透明度到 0.4,减少“灰蒙蒙”的白雾感,让背景颜色更亮地透出来
|
||||
color: Colors.white.withOpacity(0.4),
|
||||
borderRadius: BorderRadius.circular(32),
|
||||
border: Border.all(
|
||||
// 使用极细的深色半透明边框勾勒轮廓
|
||||
color: Colors.black.withOpacity(0.08),
|
||||
width: 0.5,
|
||||
),
|
||||
),
|
||||
child: SafeArea(
|
||||
top: false,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 10,
|
||||
vertical: 8,
|
||||
),
|
||||
child: GNav(
|
||||
rippleColor: Colors.transparent,
|
||||
hoverColor: Colors.transparent,
|
||||
gap: 10,
|
||||
// 【关键修改】选中状态:纯黑背景 + 纯白图标/文字
|
||||
activeColor: Colors.white,
|
||||
tabBackgroundColor: Colors.black,
|
||||
// 未选中状态:深黑色
|
||||
color: Colors.black87,
|
||||
iconSize: 24,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 18,
|
||||
vertical: 10,
|
||||
),
|
||||
duration: const Duration(milliseconds: 300),
|
||||
selectedIndex: navigationShell.currentIndex,
|
||||
onTabChange: (index) {
|
||||
navigationShell.goBranch(index);
|
||||
},
|
||||
tabs: const [
|
||||
GButton(icon: Icons.grid_view_rounded, text: '状态'),
|
||||
GButton(icon: Icons.auto_awesome_rounded, text: 'AI'),
|
||||
GButton(icon: Icons.person_rounded, text: '我的'),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
10
lib/features/my/presentation/pages/my_page.dart
Normal file
10
lib/features/my/presentation/pages/my_page.dart
Normal file
@@ -0,0 +1,10 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class MyPage extends StatelessWidget {
|
||||
const MyPage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(body: Center(child: Text('Welcome My page')));
|
||||
}
|
||||
}
|
||||
31
lib/features/my/presentation/routes/my_routes.dart
Normal file
31
lib/features/my/presentation/routes/my_routes.dart
Normal file
@@ -0,0 +1,31 @@
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:maibu_satabot_v2/features/my/presentation/pages/my_page.dart';
|
||||
|
||||
import '../../../../core/router/route_paths.dart';
|
||||
|
||||
class MyRoutes {
|
||||
/// 1. 全屏功能页面(不带导航栏)
|
||||
/// 在 createRouter 的根 routes 中使用 ...HomeRoutes.routes 引入
|
||||
static List<RouteBase> get routes => [
|
||||
// GoRoute(
|
||||
// path: RoutePaths.remoteControl,
|
||||
// builder: (context, state) => const RemoteControlPage(), // 需导入对应 Page
|
||||
// ),
|
||||
// GoRoute(
|
||||
// path: RoutePaths.routePlan,
|
||||
// builder: (context, state) => const RoutePlanPage(),
|
||||
// ),
|
||||
// GoRoute(
|
||||
// path: RoutePaths.runningStatus,
|
||||
// builder: (context, state) => const RunningStatusPage(),
|
||||
// ),
|
||||
];
|
||||
|
||||
/// 2. 首页 Tab 分支(带导航栏)
|
||||
/// 仅保留真正的首页入口
|
||||
static StatefulShellBranch get branch => StatefulShellBranch(
|
||||
routes: [
|
||||
GoRoute(path: RoutePaths.my, builder: (context, state) => const MyPage()),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class RegisterPage extends StatelessWidget {
|
||||
// final User user;
|
||||
|
||||
const RegisterPage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Home')),
|
||||
body: Center(child: Text('Welcome Register')),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
class RemoteHttpDatasource {
|
||||
final Dio _dio;
|
||||
|
||||
RemoteHttpDatasource(this._dio);
|
||||
|
||||
/// 示例:获取控制授权 (对应之前逻辑中的权限申请)
|
||||
Future<Map<String, dynamic>> requestControlAuth(String robotId) async {
|
||||
try {
|
||||
final response = await _dio.post(
|
||||
'/robot/auth/request',
|
||||
data: {'robotId': robotId},
|
||||
);
|
||||
return response.data;
|
||||
} catch (e) {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import '../../../../core/protocol/machine_protocol_codec.dart';
|
||||
|
||||
class LawnMoverProtocolModel {
|
||||
final int left;
|
||||
final int right;
|
||||
final int lift;
|
||||
final int mower;
|
||||
final int ignition;
|
||||
final int emergency;
|
||||
|
||||
LawnMoverProtocolModel({
|
||||
required this.left,
|
||||
required this.right,
|
||||
this.lift = 0,
|
||||
this.mower = 0,
|
||||
this.ignition = 0,
|
||||
this.emergency = 0,
|
||||
});
|
||||
|
||||
Uint8List toBytes() => MachineProtocolCodec.encodeRemoteControlPayload(
|
||||
left: left,
|
||||
right: right,
|
||||
lift: lift,
|
||||
mower: mower,
|
||||
ignition: ignition,
|
||||
emergency: emergency,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import 'dart:async';
|
||||
|
||||
import '../../../../core/network/protocol_decoder.dart';
|
||||
import '../../../../core/network/tcp/tcp_client.dart';
|
||||
import '../../../../core/protocol/machine_protocol_codec.dart';
|
||||
import '../../../../core/protocol/machine_protocol_constants.dart';
|
||||
import '../../domain/entities/machine_control_status_entity.dart';
|
||||
import '../../domain/repositories/remote_control_repository.dart';
|
||||
import '../../domain/usecase/diff_steer_usecase.dart';
|
||||
|
||||
class RemoteControlRepositoryImpl implements RemoteControlRepository {
|
||||
final TcpClient _tcpClient;
|
||||
final DiffSteerUseCase _diffSteer;
|
||||
|
||||
RemoteControlRepositoryImpl(this._tcpClient, this._diffSteer);
|
||||
|
||||
@override
|
||||
void changeWebViewDirection(String direction) {
|
||||
// TODO: implement changeWebViewDirection
|
||||
}
|
||||
|
||||
@override
|
||||
void sendControlMachineCmd(MachineControlStatusEntity status) {
|
||||
// 1. 调用算法:将摇杆坐标 (x, y) 转换为左右轮电机转速
|
||||
final speeds = _diffSteer.calculate(status.originX, status.originY);
|
||||
|
||||
// 2. 调用 Codec:仅生成协议要求的 8 字节 Payload 负载数据
|
||||
final payload = MachineProtocolCodec.encodeRemoteControlPayload(
|
||||
left: speeds['left']!,
|
||||
right: speeds['right']!,
|
||||
lift: status.chassisLift,
|
||||
mower: status.mowerSpeed,
|
||||
ignition: status.ignitionStatus,
|
||||
emergency: status.isEmergency ? 1 : 0,
|
||||
);
|
||||
|
||||
// 3. 调用 TcpClient:发送指令。
|
||||
// TcpClient.sendRaw 会自动帮你加上 [0xAB, 0xAA] 头和 [0xAA, 0xAB] 尾
|
||||
_tcpClient.sendRaw(
|
||||
MachineProtocolConstants.cmdRemoteControl, // 这里通常是 0x00
|
||||
payload,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<RawPacket> get responseStream => _tcpClient.packetStream;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
class MachineControlStatusEntity {
|
||||
final int originX;
|
||||
final int originY;
|
||||
final int chassisLift; // 0:停, 1:上, 2:下
|
||||
final int mowerSpeed; // 0:停, 1:+, 2:-
|
||||
final int ignitionStatus; // 0:停, 1:火, 2:熄
|
||||
final bool isEmergency;
|
||||
|
||||
MachineControlStatusEntity({
|
||||
this.originX = 0,
|
||||
this.originY = 0,
|
||||
this.chassisLift = 0,
|
||||
this.mowerSpeed = 0,
|
||||
this.ignitionStatus = 0,
|
||||
this.isEmergency = false,
|
||||
});
|
||||
|
||||
MachineControlStatusEntity copyWith({
|
||||
int? x,
|
||||
int? y,
|
||||
int? lift,
|
||||
int? mower,
|
||||
int? ignition,
|
||||
bool? emergency,
|
||||
}) {
|
||||
return MachineControlStatusEntity(
|
||||
originX: x ?? originX,
|
||||
originY: y ?? originY,
|
||||
chassisLift: lift ?? chassisLift,
|
||||
mowerSpeed: mower ?? mowerSpeed,
|
||||
ignitionStatus: ignition ?? ignitionStatus,
|
||||
isEmergency: emergency ?? isEmergency,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import '../../../../core/network/protocol_decoder.dart';
|
||||
import '../../domain/entities/machine_control_status_entity.dart';
|
||||
|
||||
abstract class RemoteControlRepository {
|
||||
/// 高频发送遥控指令 (被 Cubit 的 100ms 定时器调用)
|
||||
/// 负责将 Entity 转换为底层的 0x00 指令并发出
|
||||
void sendControlMachineCmd(MachineControlStatusEntity status);
|
||||
|
||||
/// 暴露解析后的回包流 (如 0x12 权限申请)
|
||||
/// UI 或 Cubit 监听此流来处理机器人主动推送的消息
|
||||
Stream<RawPacket> get responseStream;
|
||||
|
||||
/// WebView 视角控制 (逻辑层面的切换,不涉及 TCP)
|
||||
void changeWebViewDirection(String direction);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
class DiffSteerUseCase {
|
||||
static const int polarityHigh = 0;
|
||||
static const int polarityLow = 1;
|
||||
|
||||
double _turnSpeedScale = 1500 / 100;
|
||||
double _forwardSpeedScale = 3000 / 100;
|
||||
int _speedAmplLimit = 3000;
|
||||
|
||||
int _leftWheelDir = polarityHigh;
|
||||
int _rightWheelDir = polarityHigh;
|
||||
int _xDir = polarityHigh;
|
||||
int _yDir = polarityHigh;
|
||||
|
||||
Map<String, int> calculate(int x, int y) {
|
||||
int turnSpeed = _signOperator((x * _turnSpeedScale).toInt(), _xDir);
|
||||
int forwardSpeed = _signOperator((y * _forwardSpeedScale).toInt(), _yDir);
|
||||
|
||||
// 倒车补偿
|
||||
int adjustedTurn = (forwardSpeed >= 0 ? turnSpeed : -turnSpeed);
|
||||
|
||||
int left = _signOperator(forwardSpeed + adjustedTurn, _leftWheelDir);
|
||||
int right = _signOperator(forwardSpeed - adjustedTurn, _rightWheelDir);
|
||||
|
||||
return {
|
||||
'left': left.clamp(-_speedAmplLimit, _speedAmplLimit),
|
||||
'right': right.clamp(-_speedAmplLimit, _speedAmplLimit),
|
||||
};
|
||||
}
|
||||
|
||||
int _signOperator(int num, int polarity) =>
|
||||
polarity != polarityHigh ? -num : num;
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:maibu_satabot_v2/features/remote_control/presentation/bloc/remote_control_state.dart';
|
||||
|
||||
import '../../domain/entities/machine_control_status_entity.dart';
|
||||
import '../../domain/repositories/remote_control_repository.dart';
|
||||
|
||||
class RemoteControlCubit extends Cubit<RemoteControlState> {
|
||||
final RemoteControlRepository _repository;
|
||||
Timer? _timer;
|
||||
|
||||
RemoteControlCubit(this._repository)
|
||||
: super(RemoteControlState(controlEntity: MachineControlStatusEntity())) {
|
||||
_initPacketListener();
|
||||
}
|
||||
|
||||
// 1. 初始化回包监听 (如 0x12 权限)
|
||||
void _initPacketListener() {
|
||||
_repository.responseStream.listen((packet) {
|
||||
if (packet.command == 0x12) {
|
||||
// 根据负载判断是否有权限,更新状态
|
||||
emit(state.copyWith(hasPermission: true));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 2. 开启 100ms 控制循环 (在进入遥控页面或点击“开始”时调用)
|
||||
void startControlLoop() {
|
||||
_timer?.cancel();
|
||||
_timer = Timer.periodic(const Duration(milliseconds: 100), (timer) {
|
||||
// 核心调用:直接把 state 里的实体丢给 repository
|
||||
_repository.sendControlMachineCmd(state.controlEntity);
|
||||
});
|
||||
emit(state.copyWith(status: RemoteControlStatus.controlling));
|
||||
}
|
||||
|
||||
// 3. 更新摇杆数据
|
||||
void updateJoystick(double x, double y) {
|
||||
final updatedEntity = state.controlEntity.copyWith(
|
||||
x: x.toInt(),
|
||||
y: y.toInt(),
|
||||
);
|
||||
emit(state.copyWith(controlEntity: updatedEntity));
|
||||
}
|
||||
|
||||
// 4. 更新功能开关 (比如割刀速度、灯光、点火等)
|
||||
void updateFunction({int? mower, int? lift, int? ignition, bool? emergency}) {
|
||||
final updatedEntity = state.controlEntity.copyWith(
|
||||
mower: mower,
|
||||
lift: lift,
|
||||
ignition: ignition,
|
||||
emergency: emergency,
|
||||
);
|
||||
emit(state.copyWith(controlEntity: updatedEntity));
|
||||
}
|
||||
|
||||
void updateOriginY(int y) {}
|
||||
|
||||
// 5. 停止控制循环
|
||||
void stopControlLoop() {
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
emit(state.copyWith(status: RemoteControlStatus.initial));
|
||||
}
|
||||
|
||||
void toggleLock() {}
|
||||
|
||||
void togglePermissionDialog(bool show) {
|
||||
emit(state.copyWith(showPermissionRequestDialog: show));
|
||||
}
|
||||
|
||||
void requestControlPermission() {
|
||||
// 1. 关闭弹窗
|
||||
emit(state.copyWith(showPermissionRequestDialog: false));
|
||||
|
||||
// 2. 这里执行你发送 0x12 指令的逻辑
|
||||
// _sendProtocolData(0x12, ...);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
_timer?.cancel(); // 退出页面时务必销毁定时器
|
||||
return super.close();
|
||||
}
|
||||
|
||||
void updateChassisLift(int i) {}
|
||||
|
||||
void updateEmergency(bool bool) {}
|
||||
|
||||
void respondPermission(bool bool) {}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
import '../../domain/entities/machine_control_status_entity.dart';
|
||||
|
||||
enum RemoteControlStatus { initial, controlling, error }
|
||||
|
||||
class RemoteControlState extends Equatable {
|
||||
final RemoteControlStatus status;
|
||||
final MachineControlStatusEntity controlEntity; // 之前的业务实体
|
||||
final String? errorMessage;
|
||||
final bool hasPermission; // 是否获得了 0x12 权限
|
||||
final bool isEmergency;
|
||||
final bool isLocked;
|
||||
final int ping;
|
||||
final int battery;
|
||||
final String permissionPlatform;
|
||||
final String currentPlatform;
|
||||
final bool showPermissionRequestDialog;
|
||||
|
||||
const RemoteControlState({
|
||||
this.status = RemoteControlStatus.initial,
|
||||
required this.controlEntity,
|
||||
this.errorMessage,
|
||||
this.hasPermission = false,
|
||||
this.isEmergency = false,
|
||||
this.isLocked = false,
|
||||
this.ping = 0,
|
||||
this.battery = 0,
|
||||
this.permissionPlatform = '',
|
||||
this.currentPlatform = '',
|
||||
this.showPermissionRequestDialog = false,
|
||||
});
|
||||
|
||||
// 方便 UI 更新部分属性
|
||||
RemoteControlState copyWith({
|
||||
RemoteControlStatus? status,
|
||||
MachineControlStatusEntity? controlEntity,
|
||||
String? errorMessage,
|
||||
bool? hasPermission,
|
||||
bool? isEmergency,
|
||||
bool? isLocked,
|
||||
int? ping,
|
||||
int? battery,
|
||||
String? permissionPlatform,
|
||||
String? currentPlatform,
|
||||
bool? showPermissionRequestDialog,
|
||||
}) {
|
||||
return RemoteControlState(
|
||||
status: status ?? this.status,
|
||||
controlEntity: controlEntity ?? this.controlEntity,
|
||||
errorMessage: errorMessage ?? this.errorMessage,
|
||||
hasPermission: hasPermission ?? this.hasPermission,
|
||||
isEmergency: isEmergency ?? this.isEmergency,
|
||||
isLocked: isLocked ?? this.isLocked,
|
||||
ping: ping ?? this.ping,
|
||||
battery: battery ?? this.battery,
|
||||
permissionPlatform: permissionPlatform ?? this.permissionPlatform,
|
||||
currentPlatform: currentPlatform ?? this.currentPlatform,
|
||||
showPermissionRequestDialog:
|
||||
showPermissionRequestDialog ?? this.showPermissionRequestDialog,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
status,
|
||||
controlEntity,
|
||||
errorMessage,
|
||||
hasPermission,
|
||||
isEmergency,
|
||||
isLocked,
|
||||
ping,
|
||||
battery,
|
||||
permissionPlatform,
|
||||
currentPlatform,
|
||||
showPermissionRequestDialog,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:maibu_satabot_v2/core/consts/tcp_consts.dart';
|
||||
|
||||
import '../../../../core/app/app_user_cubit.dart';
|
||||
import '../../../devices/presentation/bloc/devices_cubit.dart';
|
||||
import '../bloc/remote_control_cubit.dart';
|
||||
import '../bloc/remote_control_state.dart';
|
||||
import '../widgets/center_control_area.dart';
|
||||
import '../widgets/emergency_overlay.dart';
|
||||
import '../widgets/left_joystick_area.dart';
|
||||
import '../widgets/my_video_player.dart';
|
||||
import '../widgets/right_joystick_area.dart';
|
||||
import '../widgets/top_status_bar.dart'; // 假设路径
|
||||
|
||||
class RemoteControlPage extends StatefulWidget {
|
||||
const RemoteControlPage({super.key});
|
||||
|
||||
@override
|
||||
State<RemoteControlPage> createState() => _RemoteControlPageState();
|
||||
}
|
||||
|
||||
class _RemoteControlPageState extends State<RemoteControlPage> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// 强制横屏与沉浸式
|
||||
SystemChrome.setPreferredOrientations([
|
||||
DeviceOrientation.landscapeLeft,
|
||||
DeviceOrientation.landscapeRight,
|
||||
]);
|
||||
SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
// 恢复竖屏
|
||||
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
|
||||
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// 1. 监听全局状态 (实现方案二:掉线实时刷新)
|
||||
final userState = context.watch<AppUserCubit>().state;
|
||||
final deviceState = context.watch<DevicesCubit>().state;
|
||||
final currentDevice = deviceState.selectedDevice;
|
||||
|
||||
// 2. 监听局部遥控状态 (对应 Android Compose 的 collectAsState)
|
||||
final remoteState = context.watch<RemoteControlCubit>().state;
|
||||
|
||||
// 如果设备突然掉线,显示遮罩 (对应 Android 的 finishEvent 逻辑)
|
||||
if (currentDevice == null /*|| !currentDevice.isOnline*/ ) {
|
||||
return _buildOfflineScaffold();
|
||||
}
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.black,
|
||||
body: Stack(
|
||||
children: [
|
||||
// 底层:视频流 (传入 device 和 user)
|
||||
Positioned.fill(
|
||||
child: MyVideoPlayer(
|
||||
deviceIp: TCPConsts.TCP_IP,
|
||||
device: currentDevice,
|
||||
user: userState.user!, // 假设 AppUserCubit 存有 user 实体
|
||||
),
|
||||
),
|
||||
|
||||
// 中层:急停呼吸灯光晕 (对应 Android 的 EmergencyBreathingOverlay)
|
||||
if (remoteState.isEmergency)
|
||||
const Positioned.fill(child: EmergencyOverlay()),
|
||||
|
||||
// 顶层:UI 控制层
|
||||
SafeArea(
|
||||
child: Column(
|
||||
children: [
|
||||
// 顶部胶囊状态条
|
||||
const TopStatusBar(),
|
||||
|
||||
// 左右摇杆及中间控制区
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 20,
|
||||
vertical: 10,
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
// 左摇杆:前后控制
|
||||
LeftJoystickArea(isLocked: remoteState.isLocked),
|
||||
|
||||
// 中间区:底盘升降/急停按钮
|
||||
const CenterControlArea(),
|
||||
|
||||
// 右摇杆:左右控制
|
||||
RightJoystickArea(isLocked: remoteState.isLocked),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
// 权限请求弹窗 (对应 Android 的 PermissionRequestDialog)
|
||||
if (remoteState.showPermissionRequestDialog)
|
||||
_buildPermissionDialog(context, remoteState),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildOfflineScaffold() {
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.black,
|
||||
body: Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(Icons.signal_wifi_off, color: Colors.white, size: 60),
|
||||
const SizedBox(height: 20),
|
||||
const Text(
|
||||
"设备已断开连接",
|
||||
style: TextStyle(color: Colors.white, fontSize: 18),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
ElevatedButton(
|
||||
onPressed: () => context.pop(),
|
||||
child: const Text("返回"),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPermissionDialog(
|
||||
BuildContext context,
|
||||
RemoteControlState state,
|
||||
) {
|
||||
return Container(
|
||||
color: Colors.black54,
|
||||
child: AlertDialog(
|
||||
title: const Text("权限变更"),
|
||||
content: Text("${state.permissionPlatform}端正请求控制权,同意释放吗?"),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () =>
|
||||
context.read<RemoteControlCubit>().respondPermission(false),
|
||||
child: const Text("拒绝"),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () =>
|
||||
context.read<RemoteControlCubit>().respondPermission(true),
|
||||
child: const Text("同意"),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../bloc/remote_control_cubit.dart';
|
||||
import 'emergency_stop_button.dart';
|
||||
import 'middle_expandslider.dart';
|
||||
|
||||
class CenterControlArea extends StatelessWidget {
|
||||
const CenterControlArea({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final remoteState = context.watch<RemoteControlCubit>().state;
|
||||
|
||||
// 如果处于急停激活状态,根据 Compose 逻辑,中间只显示急停状态
|
||||
if (remoteState.isEmergency) {
|
||||
return const Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
EmergencyStopButton(), // 刚才写的带 3 秒解除逻辑的按钮
|
||||
SizedBox(height: 16),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
// 左推杆:底盘升降 (对应 Compose 的第一个 MiddleExpandSlider)
|
||||
_buildVerticalSlider(
|
||||
label: "底盘",
|
||||
onTop: () =>
|
||||
context.read<RemoteControlCubit>().updateChassisLift(1),
|
||||
onMiddle: () =>
|
||||
context.read<RemoteControlCubit>().updateChassisLift(0),
|
||||
onBottom: () =>
|
||||
context.read<RemoteControlCubit>().updateChassisLift(2),
|
||||
iconTop: Icons.expand_less,
|
||||
iconMiddle: Icons.layers,
|
||||
iconBottom: Icons.expand_more,
|
||||
),
|
||||
|
||||
const SizedBox(width: 24),
|
||||
|
||||
// 中间:急停按钮
|
||||
const EmergencyStopButton(),
|
||||
|
||||
const SizedBox(width: 24),
|
||||
|
||||
// 右推杆:备用/其他 (对应 Compose 的第二个 MiddleExpandSlider)
|
||||
_buildVerticalSlider(
|
||||
label: "云台",
|
||||
onTop: () {}, // 预留接口
|
||||
onMiddle: () {},
|
||||
onBottom: () {},
|
||||
iconTop: Icons.keyboard_arrow_up,
|
||||
iconMiddle: Icons.videocam,
|
||||
iconBottom: Icons.keyboard_arrow_down,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 快捷构建推杆的方法
|
||||
Widget _buildVerticalSlider({
|
||||
required String label,
|
||||
required VoidCallback onTop,
|
||||
required VoidCallback onMiddle,
|
||||
required VoidCallback onBottom,
|
||||
required IconData iconTop,
|
||||
required IconData iconMiddle,
|
||||
required IconData iconBottom,
|
||||
}) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
MiddleExpandSlider(
|
||||
onTop: onTop,
|
||||
onMiddle: onMiddle,
|
||||
onBottom: onBottom,
|
||||
iconTop: iconTop,
|
||||
iconMiddle: iconMiddle,
|
||||
iconBottom: iconBottom,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(label, style: const TextStyle(color: Colors.grey, fontSize: 12)),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class EmergencyOverlay extends StatefulWidget {
|
||||
const EmergencyOverlay({super.key});
|
||||
|
||||
@override
|
||||
State<EmergencyOverlay> createState() => _EmergencyOverlayState();
|
||||
}
|
||||
|
||||
class _EmergencyOverlayState extends State<EmergencyOverlay>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late AnimationController _controller;
|
||||
late Animation<double> _opacityAnimation;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// 设置动画循环时间,例如 600ms 闪烁一次
|
||||
_controller = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 600),
|
||||
)..repeat(reverse: true); // 反转运行实现呼吸效果
|
||||
|
||||
_opacityAnimation = Tween<double>(
|
||||
begin: 0.0,
|
||||
end: 0.5,
|
||||
).animate(CurvedAnimation(parent: _controller, curve: Curves.easeInOut));
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AnimatedBuilder(
|
||||
animation: _opacityAnimation,
|
||||
builder: (context, child) {
|
||||
return IgnorePointer(
|
||||
// 极其重要:确保光晕不遮挡下方的点击事件
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
// 使用径向渐变,让四周红,中间透明
|
||||
border: Border.all(
|
||||
color: Colors.red.withOpacity(_opacityAnimation.value),
|
||||
width: 20, // 边框宽度决定了红边的厚度
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.red.withOpacity(_opacityAnimation.value),
|
||||
blurRadius: 40,
|
||||
spreadRadius: 10,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../bloc/remote_control_cubit.dart';
|
||||
|
||||
class EmergencyStopButton extends StatefulWidget {
|
||||
const EmergencyStopButton({super.key});
|
||||
|
||||
@override
|
||||
State<EmergencyStopButton> createState() => _EmergencyStopButtonState();
|
||||
}
|
||||
|
||||
class _EmergencyStopButtonState extends State<EmergencyStopButton>
|
||||
with TickerProviderStateMixin {
|
||||
late AnimationController _progressController;
|
||||
bool _isPressing = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// 对应 Compose 中的 durationMs = 3000L
|
||||
_progressController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(seconds: 3),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_progressController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// 监听 Cubit 中的急停状态
|
||||
final isEmergencyActive = context
|
||||
.watch<RemoteControlCubit>()
|
||||
.state
|
||||
.isEmergency;
|
||||
|
||||
return GestureDetector(
|
||||
// 1. 处理点击:仅在未急停时触发
|
||||
onTap: () {
|
||||
if (!isEmergencyActive) {
|
||||
context.read<RemoteControlCubit>().updateEmergency(true);
|
||||
HapticFeedback.heavyImpact(); // 震动反馈
|
||||
}
|
||||
},
|
||||
// 2. 处理长按开始:仅在已急停时触发解除逻辑
|
||||
onLongPressStart: (_) {
|
||||
if (isEmergencyActive) {
|
||||
setState(() => _isPressing = true);
|
||||
_progressController.forward(from: 0).then((_) {
|
||||
if (_isPressing) {
|
||||
// 进度走完且仍在按压
|
||||
context.read<RemoteControlCubit>().updateEmergency(false);
|
||||
HapticFeedback.vibrate();
|
||||
setState(() => _isPressing = false);
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
// 3. 处理松手:重置进度
|
||||
onLongPressEnd: (_) {
|
||||
_isPressing = false;
|
||||
_progressController.stop();
|
||||
_progressController.value = 0;
|
||||
setState(() {});
|
||||
},
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
// 对应 Compose 的 Canvas 绘制进度环
|
||||
if (_isPressing)
|
||||
SizedBox(
|
||||
width: 130,
|
||||
height: 130,
|
||||
child: CircularProgressIndicator(
|
||||
value: _progressController.value,
|
||||
strokeWidth: 10,
|
||||
color: Colors.red.withOpacity(0.8),
|
||||
backgroundColor: Colors.red.withOpacity(0.2),
|
||||
),
|
||||
),
|
||||
|
||||
// 按钮本体 (对应 Android 的 120.dp Box)
|
||||
Container(
|
||||
width: 120,
|
||||
height: 120,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
// 根据状态切换颜色,对应 Color(0x80C53030)
|
||||
color: isEmergencyActive
|
||||
? Colors.red.withOpacity(0.5)
|
||||
: const Color(0x80C53030),
|
||||
boxShadow: isEmergencyActive
|
||||
? [
|
||||
BoxShadow(
|
||||
color: Colors.red.withOpacity(0.5),
|
||||
blurRadius: 20,
|
||||
),
|
||||
]
|
||||
: [],
|
||||
),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.report_problem_outlined, // 对应 remote_alert 图标
|
||||
color: Colors.white,
|
||||
size: 45,
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
isEmergencyActive ? "急停中" : "急停",
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w900,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import 'package:cc_ui_kit/cc_ui_kit.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../bloc/remote_control_cubit.dart';
|
||||
|
||||
class LeftJoystickArea extends StatelessWidget {
|
||||
final bool isLocked;
|
||||
|
||||
const LeftJoystickArea({super.key, required this.isLocked});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min, // 紧凑布局
|
||||
children: [
|
||||
// 使用 IgnorePointer 处理锁定逻辑,对应 Android 的 isLocked 判断
|
||||
IgnorePointer(
|
||||
ignoring: isLocked,
|
||||
child: AnimatedOpacity(
|
||||
duration: const Duration(milliseconds: 300),
|
||||
opacity: isLocked ? 0.3 : 1.0, // 锁定后变透明
|
||||
child: CCJoystick(
|
||||
radius: 100, // 对应 size(200.dp)
|
||||
axisHint: AxisHint.forwardBackward,
|
||||
onValueChanged: (value) {
|
||||
// 对应 viewModel.updateOriginY(y)
|
||||
context.read<RemoteControlCubit>().updateOriginY(value.y);
|
||||
},
|
||||
onPress: () {
|
||||
// 对应 VibrateOnce(current, 100)
|
||||
HapticFeedback.mediumImpact();
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
const Text(
|
||||
"前后控制",
|
||||
style: TextStyle(
|
||||
color: Colors.grey,
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
class MiddleExpandSlider extends StatefulWidget {
|
||||
final VoidCallback onTop; // 对应 Compose 的 onTop (例如:升)
|
||||
final VoidCallback onMiddle; // 对应 Compose 的 onMiddle (例如:停止/复位)
|
||||
final VoidCallback onBottom; // 对应 Compose 的 onBottom (例如:降)
|
||||
final IconData iconTop;
|
||||
final IconData iconMiddle;
|
||||
final IconData iconBottom;
|
||||
|
||||
const MiddleExpandSlider({
|
||||
super.key,
|
||||
required this.onTop,
|
||||
required this.onMiddle,
|
||||
required this.onBottom,
|
||||
required this.iconTop,
|
||||
required this.iconMiddle,
|
||||
required this.iconBottom,
|
||||
});
|
||||
|
||||
@override
|
||||
State<MiddleExpandSlider> createState() => _MiddleExpandSliderState();
|
||||
}
|
||||
|
||||
class _MiddleExpandSliderState extends State<MiddleExpandSlider> {
|
||||
// 0: Top, 1: Middle, 2: Bottom
|
||||
int _currentIndex = 1;
|
||||
|
||||
// 处理滑动更新逻辑
|
||||
void _handleDragUpdate(DragUpdateDetails details, double maxHeight) {
|
||||
// 将 120 的高度分为三等份
|
||||
double localY = details.localPosition.dy;
|
||||
int newIndex;
|
||||
|
||||
if (localY < maxHeight / 3) {
|
||||
newIndex = 0;
|
||||
} else if (localY > (maxHeight / 3) * 2) {
|
||||
newIndex = 2;
|
||||
} else {
|
||||
newIndex = 1;
|
||||
}
|
||||
|
||||
if (newIndex != _currentIndex) {
|
||||
setState(() => _currentIndex = newIndex);
|
||||
// 触发对应的指令回调
|
||||
if (_currentIndex == 0) widget.onTop();
|
||||
if (_currentIndex == 1) widget.onMiddle();
|
||||
if (_currentIndex == 2) widget.onBottom();
|
||||
|
||||
// 触感反馈:对应 Android 的 VibrateOnce(current, 20)
|
||||
HapticFeedback.lightImpact();
|
||||
}
|
||||
}
|
||||
|
||||
// 对应 Compose 的松手回弹逻辑
|
||||
void _handleDragEnd() {
|
||||
if (_currentIndex != 1) {
|
||||
setState(() => _currentIndex = 1);
|
||||
widget.onMiddle(); // 回到中间,停止动作
|
||||
HapticFeedback.selectionClick();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
const double sliderHeight = 120.0;
|
||||
const double sliderWidth = 45.0;
|
||||
|
||||
return GestureDetector(
|
||||
onVerticalDragUpdate: (details) =>
|
||||
_handleDragUpdate(details, sliderHeight),
|
||||
onVerticalDragEnd: (_) => _handleDragEnd(),
|
||||
child: Container(
|
||||
width: sliderWidth,
|
||||
height: sliderHeight,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.grey.withOpacity(
|
||||
0.2,
|
||||
), // 对应 Color.Gray.copy(alpha = 0.4f)
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: Colors.white.withOpacity(0.2), width: 0.5),
|
||||
),
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
// 1. 背景图标层:提示用户上下功能
|
||||
Column(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||
children: [
|
||||
Icon(widget.iconTop, color: Colors.white12, size: 20),
|
||||
Icon(widget.iconMiddle, color: Colors.white12, size: 20),
|
||||
Icon(widget.iconBottom, color: Colors.white12, size: 20),
|
||||
],
|
||||
),
|
||||
|
||||
// 2. 活动滑块:对应 Compose 中的蓝色选中状态
|
||||
AnimatedPositioned(
|
||||
duration: const Duration(milliseconds: 150),
|
||||
curve: Curves.easeOutBack, // 增加一点点弹簧感
|
||||
top: _currentIndex == 0 ? 5 : (_currentIndex == 1 ? 40 : 75),
|
||||
child: Container(
|
||||
width: 38,
|
||||
height: 40,
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xCC0078D4), // 对应 Compose 里的蓝色
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: const Color(0xCC0078D4).withOpacity(0.4),
|
||||
blurRadius: 8,
|
||||
spreadRadius: 1,
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Icon(
|
||||
_currentIndex == 0
|
||||
? widget.iconTop
|
||||
: (_currentIndex == 1
|
||||
? widget.iconMiddle
|
||||
: widget.iconBottom),
|
||||
color: Colors.white,
|
||||
size: 22,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
|
||||
import 'package:maibu_satabot_v2/core/domain/entities/user_entity.dart';
|
||||
import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart';
|
||||
|
||||
class MyVideoPlayer extends StatefulWidget {
|
||||
final String deviceIp;
|
||||
final DeviceEntity device;
|
||||
final UserEntity user;
|
||||
const MyVideoPlayer({
|
||||
Key? key,
|
||||
required this.deviceIp,
|
||||
required this.device,
|
||||
required this.user,
|
||||
}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<MyVideoPlayer> createState() => _MyVideoPlayerState();
|
||||
}
|
||||
|
||||
class _MyVideoPlayerState extends State<MyVideoPlayer> {
|
||||
// 1. 定义本地服务器
|
||||
InAppLocalhostServer? _localServer;
|
||||
InAppWebViewController? _webViewController;
|
||||
bool _isServerRunning = false;
|
||||
var actualPort;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_startServer();
|
||||
}
|
||||
|
||||
// 2. 启动服务器 (适用于 Windows, Android, iOS)
|
||||
Future<void> _startServer() async {
|
||||
// 1. 手动找一个系统分配的空闲端口
|
||||
int availablePort = 0;
|
||||
try {
|
||||
// 绑定到端口 0,系统会随机分配一个
|
||||
var socket = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
|
||||
availablePort = socket.port;
|
||||
await socket.close(); // 立即释放,给 LocalhostServer 用
|
||||
} catch (e) {
|
||||
availablePort = 8080; // 万一失败,给个保底
|
||||
}
|
||||
|
||||
// 2. 使用找到的明确端口启动
|
||||
_localServer = InAppLocalhostServer(port: availablePort);
|
||||
await _localServer!.start();
|
||||
|
||||
// 确认端口(有些版本需要通过这种方式确认)
|
||||
actualPort = availablePort;
|
||||
|
||||
debugPrint("服务器启动在端口: $actualPort");
|
||||
|
||||
setState(() {
|
||||
_isServerRunning = true;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_localServer?.close(); // 页面销毁时关闭服务器
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (!_isServerRunning) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
return InAppWebView(
|
||||
// 3. 通过 localhost 地址访问,而不是 file://
|
||||
initialUrlRequest: URLRequest(
|
||||
url: WebUri("http://localhost:$actualPort/assets/www/playwebrtc.html"),
|
||||
),
|
||||
initialSettings: InAppWebViewSettings(
|
||||
javaScriptEnabled: true,
|
||||
mediaPlaybackRequiresUserGesture: false,
|
||||
allowsInlineMediaPlayback: true,
|
||||
// Windows/Android 开启硬件加速优化图传
|
||||
preferredContentMode: UserPreferredContentMode.DESKTOP,
|
||||
),
|
||||
onWebViewCreated: (controller) => _webViewController = controller,
|
||||
onPermissionRequest: (controller, request) async {
|
||||
return PermissionResponse(
|
||||
resources: request.resources,
|
||||
action: PermissionResponseAction.GRANT,
|
||||
);
|
||||
},
|
||||
onLoadStop: (controller, url) {
|
||||
_initWebRTC(
|
||||
widget.deviceIp,
|
||||
widget.device.deviceName,
|
||||
widget.user.token,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
void _initWebRTC(String deviceIp, String deviceId, String token) {
|
||||
final streamUrl =
|
||||
"webrtc://$deviceIp/live/livestream/$deviceId?token=$token";
|
||||
_webViewController?.evaluateJavascript(
|
||||
source: "setStreamUrl('$streamUrl')",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import 'package:cc_ui_kit/cc_ui_kit.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../bloc/remote_control_cubit.dart';
|
||||
|
||||
class RightJoystickArea extends StatelessWidget {
|
||||
final bool isLocked;
|
||||
|
||||
const RightJoystickArea({super.key, required this.isLocked});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min, // 垂直方向紧凑布局
|
||||
children: [
|
||||
// 1. 交互锁定逻辑:对应 Compose 的 isLocked 判断
|
||||
IgnorePointer(
|
||||
ignoring: isLocked,
|
||||
child: AnimatedOpacity(
|
||||
duration: const Duration(milliseconds: 300),
|
||||
opacity: isLocked ? 0.3 : 1.0, // 锁定后变透明/灰色
|
||||
child: CCJoystick(
|
||||
radius: 100, // 对应 size(200.dp)
|
||||
axisHint: AxisHint.leftRight, // 关键:指定为左右控制
|
||||
onValueChanged: (value) {
|
||||
// 对应 viewModel.updateOriginX(x)
|
||||
context.read<RemoteControlCubit>().updateOriginY(value.x);
|
||||
},
|
||||
onPress: () {
|
||||
// 对应 VibrateOnce(current, 100)
|
||||
HapticFeedback.mediumImpact();
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
// 2. 底部文字:对应 Text("左右控制", color = Color.Gray)
|
||||
const Text(
|
||||
"左右控制",
|
||||
style: TextStyle(
|
||||
color: Colors.grey,
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class StatusChip extends StatefulWidget {
|
||||
final String text;
|
||||
final Color color;
|
||||
final IconData icon;
|
||||
final bool breathing; // 是否开启呼吸灯特效
|
||||
final VoidCallback? onTap;
|
||||
|
||||
const StatusChip({
|
||||
super.key,
|
||||
required this.text,
|
||||
required this.color,
|
||||
required this.icon,
|
||||
this.breathing = false,
|
||||
this.onTap,
|
||||
});
|
||||
|
||||
@override
|
||||
State<StatusChip> createState() => _StatusChipState();
|
||||
}
|
||||
|
||||
class _StatusChipState extends State<StatusChip>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late AnimationController _controller;
|
||||
late Animation<double> _opacityAnimation;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 1000),
|
||||
);
|
||||
if (widget.breathing) _controller.repeat(reverse: true);
|
||||
|
||||
_opacityAnimation = Tween<double>(
|
||||
begin: 0.4,
|
||||
end: 1.0,
|
||||
).animate(CurvedAnimation(parent: _controller, curve: Curves.linear));
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AnimatedBuilder(
|
||||
animation: _opacityAnimation,
|
||||
builder: (context, child) {
|
||||
final currentAlpha = widget.breathing ? _opacityAnimation.value : 0.6;
|
||||
return GestureDetector(
|
||||
onTap: widget.onTap,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: widget.color.withOpacity(currentAlpha),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(
|
||||
color: widget.color.withOpacity(0.35),
|
||||
width: 0.5,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(widget.icon, color: Colors.white, size: 14),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
widget.text,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:maibu_satabot_v2/features/remote_control/presentation/widgets/status_chip.dart';
|
||||
|
||||
import '../../../devices/presentation/bloc/devices_cubit.dart';
|
||||
import '../bloc/remote_control_cubit.dart';
|
||||
|
||||
class TopStatusBar extends StatelessWidget {
|
||||
const TopStatusBar({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// 监听全局设备状态
|
||||
final deviceState = context.watch<DevicesCubit>().state;
|
||||
final device = deviceState.selectedDevice;
|
||||
|
||||
// 监听局部遥控状态
|
||||
final remoteState = context.watch<RemoteControlCubit>().state;
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(12.0),
|
||||
child: Row(
|
||||
children: [
|
||||
// 1. 返回按钮 (对应 SimpleSmallFunctionButton)
|
||||
_buildIconButton(Icons.arrow_back_ios_new, () => context.pop()),
|
||||
const SizedBox(width: 16),
|
||||
|
||||
// 2. 控制状态 (对应 StatusChipLeft)
|
||||
StatusChip(
|
||||
text: remoteState.hasPermission ? "正在控制" : "未在控制",
|
||||
color: remoteState.hasPermission
|
||||
? const Color(0xFF1DB954)
|
||||
: Colors.red,
|
||||
icon: Icons.eighteen_mp,
|
||||
breathing: !remoteState.hasPermission,
|
||||
onTap: () {
|
||||
if (!remoteState.hasPermission) {
|
||||
// 弹出请求权限对话框逻辑
|
||||
context.read<RemoteControlCubit>().togglePermissionDialog(true);
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
|
||||
// 3. 锁定状态 (对应 SmallFunctionButton)
|
||||
_buildIconButton(
|
||||
remoteState.isLocked ? Icons.lock : Icons.lock_open,
|
||||
() => context.read<RemoteControlCubit>().toggleLock(),
|
||||
isSelected: remoteState.isLocked,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
|
||||
// 4. 刷新按钮
|
||||
_buildIconButton(Icons.refresh, () {
|
||||
// 刷新 WebView 逻辑
|
||||
}),
|
||||
|
||||
const Spacer(),
|
||||
|
||||
// 5. 信号延迟 (对应 pingStatusChip)
|
||||
_buildPingChip(remoteState.ping),
|
||||
const SizedBox(width: 8),
|
||||
|
||||
// 6. 电量 (对应 StatusChipRight)
|
||||
_buildBatteryChip(remoteState?.battery ?? 0),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 对应 Android 里的 SimpleSmallFunctionButton 样式
|
||||
Widget _buildIconButton(
|
||||
IconData icon,
|
||||
VoidCallback onTap, {
|
||||
bool isSelected = false,
|
||||
}) {
|
||||
return InkWell(
|
||||
onTap: onTap,
|
||||
child: Container(
|
||||
width: 32,
|
||||
height: 32,
|
||||
decoration: BoxDecoration(
|
||||
color: isSelected
|
||||
? const Color(0xCC0078D4)
|
||||
: Colors.grey.withOpacity(0.4),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(color: Colors.white.withOpacity(0.3), width: 0.5),
|
||||
),
|
||||
child: Icon(icon, color: Colors.white, size: 18),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPingChip(int ping) {
|
||||
Color color = ping < 100
|
||||
? Colors.green
|
||||
: (ping < 200 ? Colors.orange : Colors.red);
|
||||
return StatusChip(
|
||||
text: "$ping ms",
|
||||
color: color,
|
||||
icon: Icons.network_check,
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildBatteryChip(int level) {
|
||||
IconData icon = level > 80
|
||||
? Icons.battery_full
|
||||
: (level > 20 ? Icons.battery_3_bar : Icons.battery_alert);
|
||||
Color color = level > 80
|
||||
? Colors.green
|
||||
: (level > 30 ? Colors.orange : Colors.red);
|
||||
return StatusChip(text: "$level%", color: color, icon: icon);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user