第二次提交

This commit is contained in:
cc
2026-01-18 20:21:14 +08:00
parent 4346601481
commit 289e706337
129 changed files with 4615 additions and 135 deletions

View File

@@ -1,17 +1,16 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import '../domain/entities/user_entity.dart';
import 'app_state.dart';
import 'app_user_state.dart';
class AppCubit extends Cubit<AppState> {
AppCubit() : super(const AppState());
class AppUserCubit extends Cubit<AppUserState> {
AppUserCubit() : super(const AppUserState());
// 传入实体对象,而不是零散的 id
void setAuth(UserEntity user) {
emit(state.copyWith(user));
}
void clearAuth() {
emit(const AppState());
emit(const AppUserState());
}
}

View File

@@ -2,16 +2,16 @@ import 'package:equatable/equatable.dart';
import '../domain/entities/user_entity.dart';
class AppState extends Equatable {
class AppUserState extends Equatable {
final UserEntity? user; // 直接存实体,包含 userId, username,token 等所有信息
const AppState({this.user});
const AppUserState({this.user});
// 辅助属性:判断是否登录
bool get isLoggedIn => user != null;
AppState copyWith(UserEntity? user) {
return AppState(user: user ?? this.user);
AppUserState copyWith(UserEntity? user) {
return AppUserState(user: user ?? this.user);
}
// 必须重写 props,UI 才会只在数据真正变化时刷新

View File

@@ -0,0 +1,17 @@
class HttpApiConsts {
static const String baseUrl = "http://1.95.137.212:8081";
/// 账号相关
// 登录
static const String loginUrl = "$baseUrl/login";
///设备相关
// 获取设备列表
static const String getUserDevicesList = "$baseUrl/iot/device/list";
// 绑定设备
static const String bindDevice = "$baseUrl/forward/device/bind";
// 解绑设备
static const String unbindDevice = "$baseUrl/forward/device/unbind";
// 切换设备
static const String switchDevice = "$baseUrl/forward/device/switchDevice";
}

View File

@@ -0,0 +1,8 @@
import '../../features/devices/domain/entities/device_entity.dart';
abstract class BaseModel {
BaseModel.fromJson(Map<String, dynamic> json);
Map<String, dynamic> toJson();
toEntity();
BaseModel.fromEntity(DeviceEntity entity);
}

View File

@@ -1,6 +1,13 @@
import 'package:dio/dio.dart';
import 'package:get_it/get_it.dart';
import 'package:go_router/go_router.dart';
import 'package:maibu_satabot_v2/features/devices/data/datasources/impl/device_http_datasource_impl.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 'package:maibu_satabot_v2/features/devices/presentation/bloc/devices_cubit.dart';
import 'package:maibu_satabot_v2/features/remote_control/data/repositories/remote_control_repository_impl.dart';
import 'package:maibu_satabot_v2/features/remote_control/domain/repositories/remote_control_repository.dart';
import 'package:maibu_satabot_v2/features/remote_control/domain/usecase/diff_steer_usecase.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../features/auth/data/datasources/auth_http_datasource.dart';
@@ -11,7 +18,10 @@ import '../../features/auth/domain/usecases/login_usecase.dart';
import '../../features/auth/presentation/bloc/auth_cubit.dart';
import '../../features/auth/presentation/bloc/login_bloc.dart';
import '../../features/auth/presentation/bloc/login_cubit.dart';
import '../app/app_cubit.dart';
import '../../features/devices/data/datasources/device_http_datasource.dart';
import '../../features/devices/data/repositories/device_repository_impl.dart';
import '../../features/remote_control/presentation/bloc/remote_control_cubit.dart';
import '../app/app_user_cubit.dart';
import '../network/dio_client.dart';
import '../network/net_message_dispatcher.dart';
import '../network/tcp/tcp_client.dart';
@@ -48,20 +58,31 @@ Future<void> init() async {
sl.registerLazySingleton<AuthHttpDataSource>(
() => AuthHttpDataSourceImpl(sl()),
);
sl.registerLazySingleton<DeviceHttpDatasource>(
() => DeviceHttpDatasourceImpl(sl()),
);
/// 3. 仓库 (Repository)
sl.registerLazySingleton<AuthRepository>(
() => AuthRepositoryImpl(
remote: sl(), // 自动寻找已注册的 LoginRemoteDataSource
httpRemote: sl(), // 自动寻找已注册的 LoginRemoteDataSource
localTokenStorage: sl(), // 自动寻找已注册的 TokenStorage
),
);
sl.registerLazySingleton<DeviceRepository>(() => DeviceRepositoryImpl(sl()));
sl.registerLazySingleton<RemoteControlRepository>(
() => RemoteControlRepositoryImpl(sl(), sl()),
);
/// 4. 用例 (UseCase)
sl.registerLazySingleton(() => LoginUseCase(sl()));
sl.registerLazySingleton(() => GetUserDeviceUseCase(sl()));
sl.registerLazySingleton(() => DiffSteerUseCase());
/// 5. 状态管理 (Cubit/Bloc)
sl.registerLazySingleton(() => AppCubit()); // AuthCubit 依赖它,必须先注册
sl.registerLazySingleton(() => AppUserCubit()); // AuthCubit 依赖它,必须先注册
sl.registerLazySingleton(() => DevicesCubit(sl(), sl()));
sl.registerFactory(() => RemoteControlCubit(sl()));
/// 6. 认证 (Auth)
// --- 关键修改点 1: AuthCubit 必须在 GoRouter 之前注册,并传入参数 ---
@@ -69,7 +90,7 @@ Future<void> init() async {
() => AuthCubit(
sl<UserStorage>(),
sl<TcpClient>(),
sl<AppCubit>(),
sl<AppUserCubit>(),
sl<NetMessageDispatcher>(),
),
);

View File

@@ -1,5 +1,11 @@
import 'package:fpdart/fpdart.dart';
import '../../error/failure.dart';
abstract class BaseUseCase<Type, Params> {
Future<Type> call(Params params);
Future<Either<Failure, Type>> call(Params params);
}
class NoParams {}
class NoParams {
const NoParams();
}

View File

@@ -1,16 +1,39 @@
import 'package:dio/dio.dart';
import 'package:maibu_satabot_v2/core/consts/http_api_consts.dart';
import '../app/app_user_cubit.dart';
import '../di/injection.dart';
class DioClient {
static Dio create() {
final dio = Dio(
BaseOptions(
baseUrl: 'http://1.95.137.212:8081',
baseUrl: HttpApiConsts.baseUrl,
connectTimeout: const Duration(seconds: 5),
receiveTimeout: const Duration(seconds: 5),
headers: {'Content-Type': 'application/json'},
),
);
dio.interceptors.add(LogInterceptor(requestBody: true, responseBody: true));
dio.interceptors.add(
InterceptorsWrapper(
onRequest: (options, handler) {
// 1. 从 GetIt 中获取全局的 AppUserCubit
final userCubit = sl<AppUserCubit>();
// 2. 从 Cubit 的状态中提取 Token
final token = userCubit.state.user?.token;
// 3. 如果 Token 存在,则添加到请求头
if (token != null && token.isNotEmpty) {
options.headers['Authorization'] = 'Bearer $token';
}
// 继续发送请求
return handler.next(options);
},
),
);
return dio;
}
}

View File

@@ -1,7 +1,9 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:maibu_satabot_v2/core/network/protocol_decoder.dart';
class TcpClient {
@@ -42,13 +44,23 @@ class TcpClient {
void sendRaw(int cmd, List<int> payload) {
if (_socket == null) return;
// 组装:头 AB AA + 指令 + 数据 + 尾 AA AB
final data = [0xAB, 0xAA, cmd, ...payload, 0xAA, 0xAB];
_socket!.add(data);
final builder = BytesBuilder()
..addByte(0xAB)
..addByte(0xAA)
..addByte(cmd)
..add(payload)
..add([0x00, 0x00]) // CRC
..addByte(0xAA)
..addByte(0xAB);
_socket!.add(builder.takeBytes());
}
void disconnect() {
_socket?.destroy();
_socket = null;
_controller.close();
debugPrint("TCP Disconnected");
}
}

View File

@@ -0,0 +1,28 @@
import 'dart:typed_data';
/// 极简化的 Codec:只负责中间那段变化的“负载数据”
class MachineProtocolCodec {
/// 仅封装 0x00 指令的数据部分 (Byte 3 到 Byte 10,共 8 字节)
static Uint8List encodeRemoteControlPayload({
required int left,
required int right,
int lift = 0,
int mower = 0,
int ignition = 0,
int emergency = 0,
}) {
final bd = ByteData(8); // 只分配 8 字节
int pos = 0;
bd.setInt16(pos, left, Endian.little);
pos += 2;
bd.setInt16(pos, right, Endian.little);
pos += 2;
bd.setUint8(pos++, lift);
bd.setUint8(pos++, mower);
bd.setUint8(pos++, ignition);
bd.setUint8(pos++, emergency);
return bd.buffer.asUint8List();
}
}

View File

@@ -0,0 +1,18 @@
class MachineProtocolConstants {
// 固定字节
static const int header1 = 0xAB;
static const int header2 = 0xAA;
static const int endFlag1 = 0xAA;
static const int endFlag2 = 0xAB;
// 指令类型 (根据你的 CSV 文件)
static const int cmdRemoteControl = 0x00; // 远程遥控
static const int cmdPathPlanning = 0x01; // 路径规划
static const int cmdStatusInfo = 0x02; // 状态信息
static const int cmdGetId = 0x03; // 连接请求/查询ID
static const int cmdGetAuth = 0x04; // 获取授权
static const int cmdReadConfig = 0x05; // 读配置
static const int cmdWriteConfig = 0x06; // 写配置
static const int cmdObstacleAvoid = 0x07; // 避障
static const int cmdHeartbeat = 0xFF; // 心跳包
}

View File

@@ -1,11 +1,13 @@
import 'package:go_router/go_router.dart';
import 'package:maibu_satabot_v2/core/router/route_paths.dart';
import 'package:maibu_satabot_v2/features/ai/presentation/routes/ai_routes.dart';
import 'package:maibu_satabot_v2/features/auth/presentation/routes/auth_routes.dart';
import 'package:maibu_satabot_v2/features/home/presentation/routes/home_routes.dart';
import 'package:maibu_satabot_v2/features/my/presentation/routes/my_routes.dart';
import '../../features/auth/presentation/bloc/auth_cubit.dart';
import '../../features/auth/presentation/bloc/auth_state.dart';
import '../../features/auth/presentation/pages/login_page.dart';
import '../../features/home/presentation/pages/home_page.dart';
import '../../features/register/presentation/pages/register_page.dart';
import '../../features/main_container/presentation/main_wrapper.dart';
import 'go_router_refresh_stream.dart';
GoRouter createRouter(AuthCubit authCubit) {
@@ -25,9 +27,27 @@ GoRouter createRouter(AuthCubit authCubit) {
return null;
},
routes: [
GoRoute(path: RoutePaths.login, builder: (_, __) => LoginPage()),
GoRoute(path: RoutePaths.register, builder: (_, __) => RegisterPage()),
GoRoute(path: RoutePaths.home, builder: (context, state) => HomePage()),
// 1. 外部路由(无底部导航栏)
...AuthRoutes.routes,
...HomeRoutes.routes,
...AiRoutes.routes,
...MyRoutes.routes,
// 2. 内部路由(带底部导航栏的容器)
StatefulShellRoute.indexedStack(
builder: (context, state, navigationShell) {
// 返回我们定义的 MainWrapper
return MainWrapper(navigationShell: navigationShell);
},
branches: [
// 拿一级页面
HomeRoutes.branch,
AiRoutes.branch,
MyRoutes.branch,
],
),
],
);
}

View File

@@ -1,5 +1,16 @@
class RoutePaths {
static const login = '/auth';
static const register = '/register';
/// 账号相关页面
static const login = '/auth/login';
static const register = '/auth/register';
/// 一级页面
static const home = '/home';
static const ai = '/ai';
static const my = '/my';
/// 二级页面
// Home下子页面
static const remoteControl = '/home/remote_control';
static const routePlan = '/home/route_plan';
static const runningStatus = '/home/running_status';
}

View File

@@ -0,0 +1,85 @@
import 'package:flutter/material.dart';
class AppTheme {
// 基础色值定义
static const Color _pureWhite = Color(0xFFFFFFFF);
static const Color _offWhite = Color(0xFFfafafc); // 稍微带点灰的白,用于背景增加层次感
static const Color _pureBlack = Color(0xFF000000);
static const Color _darkGrey = Color(0xFF1C1C1E); // iOS 风格的深灰黑色
static ThemeData get lightTheme {
return ThemeData(
useMaterial3: true,
brightness: Brightness.light,
// 1. 整体背景色
scaffoldBackgroundColor: _offWhite,
// 2. 核心颜色方案
colorScheme: const ColorScheme.light(
primary: _pureBlack, // 主色设为黑色
onPrimary: _pureWhite, // 黑色背景上的文字设为白色
surface: _pureWhite, // 卡片、弹窗等表面颜色
onSurface: _pureBlack, // 表面上的文字色
background: _offWhite,
),
// 3. 全局按钮主题
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
backgroundColor: _pureBlack,
foregroundColor: _pureWhite,
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 24),
),
),
// 4. 填充按钮主题 (常用语 Material 3)
filledButtonTheme: FilledButtonThemeData(
style: FilledButton.styleFrom(
backgroundColor: _pureBlack,
foregroundColor: _pureWhite,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
// 5. AppBar 主题 (纯白背景,黑色文字)
appBarTheme: const AppBarTheme(
backgroundColor: _pureWhite,
surfaceTintColor: Colors.transparent,
elevation: 0,
centerTitle: true,
iconTheme: IconThemeData(color: _pureBlack),
titleTextStyle: TextStyle(
color: _pureBlack,
fontSize: 18,
fontWeight: FontWeight.w700,
letterSpacing: -0.5,
),
),
// 6. 输入框主题 (黑白简约)
inputDecorationTheme: InputDecorationTheme(
filled: true,
fillColor: _pureWhite,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: const BorderSide(color: Colors.black12),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: const BorderSide(color: Colors.black12),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: const BorderSide(color: _pureBlack, width: 1.5),
),
),
);
}
}

View File