重整多余的UI组件和未定功能的逻辑链路的修正
This commit is contained in:
@@ -2,6 +2,12 @@ import '../env/env_config.dart';
|
||||
|
||||
class HttpApiConsts {
|
||||
static String get baseUrl => EnvConfig.baseUrl;
|
||||
static String get siteDevicePlans => '$baseUrl/iot/deviceTask/getSiteDevicePlan';
|
||||
static String get deleteDevicePlan => '$baseUrl/iot/deviceTask/delete';
|
||||
static String get siteDeviceTaskHistory =>
|
||||
'$baseUrl/iot/deviceTask/getSiteDeviceTaskHistory';
|
||||
static String get createConsecutiveTask =>
|
||||
'$baseUrl/iot/deviceTask/createConsecutiveTask';
|
||||
static String get saveRegion => '$baseUrl/system/region/save';
|
||||
static String get regionsBySite => '$baseUrl/system/region/selectBySiteId';
|
||||
static String get deleteRegions => '$baseUrl/system/region/delete';
|
||||
|
||||
@@ -1,3 +1,20 @@
|
||||
import '../../features/autonomous_work/domain/usecases/load_site_return_plan_usecase.dart';
|
||||
import '../../features/v2/work/presentation/cubit/return_plan_library_cubit.dart';
|
||||
import '../../features/site_task_plans/data/datasources/site_task_plan_remote_datasource.dart';
|
||||
import '../../features/site_task_plans/data/repositories/site_task_plan_repository_impl.dart';
|
||||
import '../../features/site_task_plans/domain/repositories/site_task_plan_repository.dart';
|
||||
import '../../features/site_task_plans/domain/usecases/site_task_plan_usecases.dart';
|
||||
import '../../features/site_task_plans/presentation/cubit/site_task_plans_cubit.dart';
|
||||
import '../../features/work_history/data/datasources/work_history_remote_datasource.dart';
|
||||
import '../../features/work_history/data/repositories/work_history_repository_impl.dart';
|
||||
import '../../features/work_history/domain/repositories/work_history_repository.dart';
|
||||
import '../../features/work_history/domain/usecases/load_site_work_history_usecase.dart';
|
||||
import '../../features/work_history/presentation/cubit/work_history_cubit.dart';
|
||||
import '../../features/consecutive_tasks/data/datasources/consecutive_task_remote_datasource.dart';
|
||||
import '../../features/consecutive_tasks/data/repositories/consecutive_task_repository_impl.dart';
|
||||
import '../../features/consecutive_tasks/domain/repositories/consecutive_task_repository.dart';
|
||||
import '../../features/consecutive_tasks/domain/usecases/create_consecutive_task_usecase.dart';
|
||||
import '../../features/consecutive_tasks/presentation/cubit/area_task_create_cubit.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'adapters/device_control_mode_realtime_adapter.dart';
|
||||
import '../../features/device_control_mode/data/datasources/control_mode_remote_datasource.dart';
|
||||
@@ -508,7 +525,7 @@ Future<void> init() async {
|
||||
);
|
||||
|
||||
// 🔥 语言管理 Cubit (单例)
|
||||
sl.registerLazySingleton(() => LocaleCubit());
|
||||
sl.registerLazySingleton(() => LocaleCubit(sl<SharedPreferences>()));
|
||||
|
||||
// 🔥 主题管理 Cubit (单例,管理亮/暗/跟随系统)
|
||||
sl.registerLazySingleton(() => ThemeCubit());
|
||||
@@ -640,6 +657,24 @@ Future<void> init() async {
|
||||
);
|
||||
sl.registerLazySingleton(() => GetDeviceTaskPoolUseCase(sl()));
|
||||
sl.registerFactory(() => WorkHomeTaskCubit(sl<GetDeviceTaskPoolUseCase>()));
|
||||
sl.registerLazySingleton(
|
||||
() => SiteTaskPlanRemoteDatasource(sl<Dio>(), sl<ILoggerService>()),
|
||||
);
|
||||
sl.registerLazySingleton<SiteTaskPlanRepository>(
|
||||
() => SiteTaskPlanRepositoryImpl(sl<SiteTaskPlanRemoteDatasource>()),
|
||||
);
|
||||
sl.registerLazySingleton(
|
||||
() => LoadSiteTaskPlansUseCase(sl<SiteTaskPlanRepository>()),
|
||||
);
|
||||
sl.registerLazySingleton(
|
||||
() => DeleteSiteTaskPlanUseCase(sl<SiteTaskPlanRepository>()),
|
||||
);
|
||||
sl.registerFactory(
|
||||
() => SiteTaskPlansCubit(
|
||||
sl<LoadSiteTaskPlansUseCase>(),
|
||||
sl<DeleteSiteTaskPlanUseCase>(),
|
||||
),
|
||||
);
|
||||
sl.registerLazySingleton(() => CancelTaskUseCase(sl()));
|
||||
sl.registerLazySingleton(() => PauseTaskUseCase(sl()));
|
||||
sl.registerLazySingleton(() => RecoveryTaskUseCase(sl()));
|
||||
@@ -688,7 +723,39 @@ Future<void> init() async {
|
||||
() => LoadRegionRoutesUseCase(sl<RegionRepository>()),
|
||||
);
|
||||
sl.registerLazySingleton(() => LoadRegionsUseCase(sl<RegionRepository>()));
|
||||
sl.registerLazySingleton(
|
||||
() => LoadSiteReturnPlanUseCase(sl<AutonomousWorkGateway>()),
|
||||
);
|
||||
sl.registerFactory(
|
||||
() => ReturnPlanLibraryCubit(sl<LoadSiteReturnPlanUseCase>()),
|
||||
);
|
||||
sl.registerLazySingleton(() => DeleteRegionsUseCase(sl<RegionRepository>()));
|
||||
sl.registerLazySingleton(
|
||||
() => WorkHistoryRemoteDatasource(sl<Dio>(), sl<ILoggerService>()),
|
||||
);
|
||||
sl.registerLazySingleton<WorkHistoryRepository>(
|
||||
() => WorkHistoryRepositoryImpl(sl<WorkHistoryRemoteDatasource>()),
|
||||
);
|
||||
sl.registerLazySingleton(
|
||||
() => LoadSiteWorkHistoryUseCase(sl<WorkHistoryRepository>()),
|
||||
);
|
||||
sl.registerFactory(() => WorkHistoryCubit(sl<LoadSiteWorkHistoryUseCase>()));
|
||||
sl.registerLazySingleton(
|
||||
() => ConsecutiveTaskRemoteDatasource(sl<Dio>(), sl<ILoggerService>()),
|
||||
);
|
||||
sl.registerLazySingleton<ConsecutiveTaskRepository>(
|
||||
() => ConsecutiveTaskRepositoryImpl(sl<ConsecutiveTaskRemoteDatasource>()),
|
||||
);
|
||||
sl.registerLazySingleton(
|
||||
() => CreateConsecutiveTaskUseCase(sl<ConsecutiveTaskRepository>()),
|
||||
);
|
||||
sl.registerFactory(
|
||||
() => AreaTaskCreateCubit(
|
||||
sl<LoadRegionsUseCase>(),
|
||||
sl<LoadRegionRoutesUseCase>(),
|
||||
sl<CreateConsecutiveTaskUseCase>(),
|
||||
),
|
||||
);
|
||||
sl.registerFactory(
|
||||
() => RegionListCubit(sl<LoadRegionsUseCase>(), sl<DeleteRegionsUseCase>()),
|
||||
);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class UserEntity extends Equatable {
|
||||
static const adminRoleKey = 'admin';
|
||||
|
||||
final String userId;
|
||||
final String username;
|
||||
final String nickname;
|
||||
@@ -25,6 +27,8 @@ class UserEntity extends Equatable {
|
||||
this.siteId,
|
||||
});
|
||||
|
||||
bool get isAdmin => roleKey == adminRoleKey;
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
userId,
|
||||
|
||||
2
lib/core/env/env_config.dart
vendored
2
lib/core/env/env_config.dart
vendored
@@ -12,7 +12,7 @@ class EnvConfig {
|
||||
return 'https://1a72051f8ac6c21cde96ded18a318217@o4510984107261952.ingest.de.sentry.io/4510984468824144';
|
||||
}
|
||||
|
||||
static bool get isProduction => environment == 'prod';
|
||||
static const bool isProduction = environment == 'prod';
|
||||
|
||||
// ─── 服务器 IP(测试/生产共用同一台机器) ───
|
||||
static const String serverHost = '1.95.137.212';
|
||||
|
||||
@@ -9,6 +9,12 @@ import '../../logging/i_logger_service.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
class SentryLoggerImpl implements ILoggerService {
|
||||
// 正式包默认关闭上报,重新启用时传入 --dart-define=ENABLE_SENTRY=true。
|
||||
static const bool _sentryEnabled = bool.fromEnvironment(
|
||||
'ENABLE_SENTRY',
|
||||
defaultValue: !kReleaseMode && !EnvConfig.isProduction,
|
||||
);
|
||||
|
||||
File? _localLogFile;
|
||||
//调试模式开关
|
||||
bool _isDebugModeEnabled = false;
|
||||
@@ -16,20 +22,17 @@ class SentryLoggerImpl implements ILoggerService {
|
||||
@override
|
||||
Future<void> init() async {
|
||||
_isDebugModeEnabled = false;
|
||||
await SentryFlutter.init((options) {
|
||||
options.dsn = EnvConfig.sentryDsn;
|
||||
options.environment = EnvConfig.environment;
|
||||
// 生产环境只采样 20% 的性能数据,测试环境全开
|
||||
options.tracesSampleRate = EnvConfig.isProduction ? 0.2 : 1.0;
|
||||
if (_sentryEnabled) {
|
||||
await SentryFlutter.init((options) {
|
||||
options.dsn = EnvConfig.sentryDsn;
|
||||
options.environment = EnvConfig.environment;
|
||||
// 生产环境只采样 20% 的性能数据,测试环境全开
|
||||
options.tracesSampleRate = EnvConfig.isProduction ? 0.2 : 1.0;
|
||||
options.debug = _isDebugModeEnabled;
|
||||
});
|
||||
|
||||
// 动态设置 Sentry 接收的日志级别
|
||||
// 如果开启调试模式,接收 DEBUG;否则生产环境只接收 INFO 以上
|
||||
|
||||
options.debug = _isDebugModeEnabled; // 开启 SDK 内部调试
|
||||
|
||||
});
|
||||
|
||||
await _collectDeviceInfo();
|
||||
await _collectDeviceInfo();
|
||||
}
|
||||
await _prepareLocalFile();
|
||||
}
|
||||
|
||||
@@ -67,7 +70,9 @@ class SentryLoggerImpl implements ILoggerService {
|
||||
|
||||
@override
|
||||
void captureException(dynamic exception, {dynamic stackTrace}) {
|
||||
Sentry.captureException(exception, stackTrace: stackTrace);
|
||||
if (_sentryEnabled) {
|
||||
Sentry.captureException(exception, stackTrace: stackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -80,13 +85,13 @@ class SentryLoggerImpl implements ILoggerService {
|
||||
final level = isWarning ? 'WARNING' : 'INFO';
|
||||
final logEntry = "[$timestamp] [$level] $message ${data ?? ''}\n";
|
||||
|
||||
// 1.发送日志到 Sentry
|
||||
Sentry.captureMessage(
|
||||
message,
|
||||
level: isWarning ? SentryLevel.warning : SentryLevel.info,
|
||||
);
|
||||
if (_sentryEnabled) {
|
||||
Sentry.captureMessage(
|
||||
message,
|
||||
level: isWarning ? SentryLevel.warning : SentryLevel.info,
|
||||
);
|
||||
}
|
||||
|
||||
// 2.写入本地文件
|
||||
_writeToLocalFile(logEntry);
|
||||
|
||||
if (kDebugMode) {
|
||||
@@ -127,10 +132,10 @@ class SentryLoggerImpl implements ILoggerService {
|
||||
_isDebugModeEnabled;
|
||||
|
||||
if (shouldProcess) {
|
||||
// 写入本地文件
|
||||
_writeToLocalFile(logEntry);
|
||||
}
|
||||
|
||||
// 上报 Sentry
|
||||
if (_sentryEnabled && shouldProcess) {
|
||||
SentryLevel sentryLevel;
|
||||
switch (level) {
|
||||
case 'DEBUG': sentryLevel = SentryLevel.debug; break;
|
||||
@@ -164,11 +169,15 @@ class SentryLoggerImpl implements ILoggerService {
|
||||
|
||||
@override
|
||||
void addBreadcrumb(String message, {String? category}) {
|
||||
Sentry.addBreadcrumb(Breadcrumb(message: message, category: category));
|
||||
if (_sentryEnabled) {
|
||||
Sentry.addBreadcrumb(Breadcrumb(message: message, category: category));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void setUser(String userId) {
|
||||
Sentry.configureScope((scope) => scope.setUser(SentryUser(id: userId)));
|
||||
if (_sentryEnabled) {
|
||||
Sentry.configureScope((scope) => scope.setUser(SentryUser(id: userId)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,21 +3,32 @@ import 'package:flutter/services.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class AppLocalizations {
|
||||
static const chinese = Locale('zh', 'CN');
|
||||
static const english = Locale('en', 'US');
|
||||
static const supportedLocales = [chinese, english];
|
||||
|
||||
static Locale localeForLanguage(String? languageCode) =>
|
||||
languageCode == 'zh' ? chinese : english;
|
||||
|
||||
static final _placeholderPattern = RegExp(r'\{(\w+)\}');
|
||||
|
||||
final Locale locale;
|
||||
Map<String, dynamic> _localizedStrings = {};
|
||||
|
||||
|
||||
AppLocalizations(this.locale);
|
||||
|
||||
|
||||
static AppLocalizations of(BuildContext context) {
|
||||
return Localizations.of<AppLocalizations>(context, AppLocalizations)!;
|
||||
}
|
||||
|
||||
static const LocalizationsDelegate<AppLocalizations> delegate = _AppLocalizationsDelegate();
|
||||
|
||||
|
||||
static const LocalizationsDelegate<AppLocalizations> delegate =
|
||||
_AppLocalizationsDelegate();
|
||||
|
||||
Future<bool> load() async {
|
||||
try {
|
||||
String jsonString = await rootBundle.loadString(
|
||||
'assets/languages/${locale.languageCode}-${locale.countryCode}.json',
|
||||
final assetLocale = localeForLanguage(locale.languageCode);
|
||||
final jsonString = await rootBundle.loadString(
|
||||
'assets/languages/${assetLocale.toLanguageTag()}.json',
|
||||
);
|
||||
Map<String, dynamic> jsonMap = json.decode(jsonString);
|
||||
_localizedStrings = jsonMap;
|
||||
@@ -27,11 +38,11 @@ class AppLocalizations {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
String translate(String key) {
|
||||
|
||||
String translate(String key, [Map<String, Object?> values = const {}]) {
|
||||
final keys = key.split('.');
|
||||
dynamic value = _localizedStrings;
|
||||
|
||||
|
||||
for (final k in keys) {
|
||||
if (value is Map<String, dynamic>) {
|
||||
value = value[k];
|
||||
@@ -39,26 +50,34 @@ class AppLocalizations {
|
||||
return key;
|
||||
}
|
||||
}
|
||||
|
||||
return value?.toString() ?? key;
|
||||
|
||||
final text = value?.toString() ?? key;
|
||||
if (values.isEmpty) return text;
|
||||
return text.replaceAllMapped(
|
||||
_placeholderPattern,
|
||||
(match) => values[match[1]]?.toString() ?? match[0]!,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {
|
||||
class _AppLocalizationsDelegate
|
||||
extends LocalizationsDelegate<AppLocalizations> {
|
||||
const _AppLocalizationsDelegate();
|
||||
|
||||
|
||||
@override
|
||||
bool isSupported(Locale locale) {
|
||||
return ['zh', 'en'].contains(locale.languageCode);
|
||||
return AppLocalizations.supportedLocales.any(
|
||||
(supported) => supported.languageCode == locale.languageCode,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@override
|
||||
Future<AppLocalizations> load(Locale locale) async {
|
||||
final localizations = AppLocalizations(locale);
|
||||
await localizations.load();
|
||||
return localizations;
|
||||
}
|
||||
|
||||
|
||||
@override
|
||||
bool shouldReload(_AppLocalizationsDelegate old) => false;
|
||||
}
|
||||
|
||||
@@ -2,44 +2,57 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'app_localizations.dart';
|
||||
|
||||
class LocaleCubit extends Cubit<Locale> {
|
||||
static const String _localeKey = 'app_locale';
|
||||
static const String _chosenKey = 'app_locale_chosen';
|
||||
static const _languageKey = 'app_locale_lang';
|
||||
static const _countryKey = 'app_locale_country';
|
||||
static const _chosenKey = 'app_locale_chosen';
|
||||
|
||||
/// 用户是否已明确选择过语言(决定登录页是否弹强制语言选择框)
|
||||
bool hasChosenLanguage = false;
|
||||
LocaleCubit(this._preferences)
|
||||
: _hasChosenLanguage = _preferences.get(_chosenKey) == true,
|
||||
super(_savedLocale(_preferences));
|
||||
|
||||
LocaleCubit() : super(const Locale('en', 'US')) {
|
||||
_loadSavedLocale();
|
||||
final SharedPreferences _preferences;
|
||||
bool _hasChosenLanguage;
|
||||
Future<void> _pendingSave = Future<void>.value();
|
||||
|
||||
/// 用户是否已明确选择过语言。
|
||||
bool get hasChosenLanguage => _hasChosenLanguage;
|
||||
|
||||
static Locale _savedLocale(SharedPreferences preferences) {
|
||||
if (preferences.get(_chosenKey) != true) return AppLocalizations.english;
|
||||
return AppLocalizations.localeForLanguage(
|
||||
preferences.get(_languageKey)?.toString(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _loadSavedLocale() async {
|
||||
Future<void> setLocale(Locale locale) {
|
||||
if (isClosed) return Future<void>.value();
|
||||
final selected = AppLocalizations.localeForLanguage(locale.languageCode);
|
||||
_hasChosenLanguage = true;
|
||||
emit(selected);
|
||||
|
||||
// 快速切换时按点选顺序写入,最后一次选择用于下次启动。
|
||||
return _pendingSave = _pendingSave.then((_) => _persist(selected));
|
||||
}
|
||||
|
||||
Future<void> _persist(Locale locale) async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
hasChosenLanguage = prefs.getBool(_chosenKey) ?? false;
|
||||
if (hasChosenLanguage) {
|
||||
final languageCode = prefs.getString('${_localeKey}_lang') ?? 'en';
|
||||
final countryCode = prefs.getString('${_localeKey}_country') ?? 'US';
|
||||
emit(Locale(languageCode, countryCode));
|
||||
} else {
|
||||
// 未选择过:默认英文(登录页仍会弹出强制选择框)
|
||||
emit(const Locale('en', 'US'));
|
||||
final languageSaved = await _preferences.setString(
|
||||
_languageKey,
|
||||
locale.languageCode,
|
||||
);
|
||||
final countrySaved = await _preferences.setString(
|
||||
_countryKey,
|
||||
locale.countryCode!,
|
||||
);
|
||||
final chosenSaved = await _preferences.setBool(_chosenKey, true);
|
||||
if (!languageSaved || !countrySaved || !chosenSaved) {
|
||||
debugPrint('[LocaleCubit] 语言偏好未写入存储');
|
||||
}
|
||||
} catch (e) {
|
||||
emit(const Locale('en', 'US'));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setLocale(Locale locale) async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString('${_localeKey}_lang', locale.languageCode);
|
||||
await prefs.setString('${_localeKey}_country', locale.countryCode ?? '');
|
||||
await prefs.setBool(_chosenKey, true);
|
||||
hasChosenLanguage = true;
|
||||
emit(locale);
|
||||
} catch (e) {
|
||||
debugPrint('❌ [LocaleCubit] 保存语言设置失败: $e');
|
||||
} catch (error) {
|
||||
debugPrint('[LocaleCubit] 保存语言设置失败: $error');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,11 @@ abstract class MowerRealtimeDataSource {
|
||||
/// 🔥 主机实时状态(device/{sn}/host/realTime/message,新增话题,纯附加)
|
||||
Stream<HostRealtimeMessageEntity> get hostRealtimeStream;
|
||||
|
||||
/// 按设备观察概览所需的电量和控制模式,订阅随监听者释放。
|
||||
Stream<({double? battery, String controlMode})> watchOverviewStatus(
|
||||
String deviceSn,
|
||||
);
|
||||
|
||||
/// 按设备 SN 启动订阅:自动退订旧设备主题、同 SN 去重
|
||||
Future<void> startListening({required String deviceSn});
|
||||
|
||||
@@ -76,6 +81,70 @@ class MowerRealtimeDataSourceImpl implements MowerRealtimeDataSource {
|
||||
String _routeTopic(String sn) => 'device/$sn/$_routeSuffix';
|
||||
String _hostRealtimeTopic(String sn) => 'device/$sn/$_hostRealtimeSuffix';
|
||||
|
||||
@override
|
||||
Stream<({double? battery, String controlMode})> watchOverviewStatus(
|
||||
String deviceSn,
|
||||
) {
|
||||
final sn = deviceSn.trim();
|
||||
final messages = mqttClient.messageStream;
|
||||
if (sn.isEmpty || messages == null) return const Stream.empty();
|
||||
|
||||
final topic = _hostRealtimeTopic(sn);
|
||||
StreamSubscription<MqttMessage>? messageSubscription;
|
||||
Future<void>? topicSubscription;
|
||||
double? lastBattery;
|
||||
late final StreamController<({double? battery, String controlMode})>
|
||||
controller;
|
||||
|
||||
controller = StreamController(
|
||||
onListen: () {
|
||||
// 先监听报文再订阅 Topic,接住订阅时立即到达的消息。
|
||||
messageSubscription = messages.where((msg) => msg.topic == topic).listen(
|
||||
(message) {
|
||||
try {
|
||||
final json = jsonDecode(message.payload);
|
||||
if (json is! Map) return;
|
||||
final payload = json['data'];
|
||||
final data = payload is Map ? payload : json;
|
||||
final battery = HostRealtimeMessageEntity.parseBatteryPercentage(
|
||||
data['battery_percentage'],
|
||||
);
|
||||
lastBattery = battery ?? lastBattery;
|
||||
controller.add(
|
||||
(
|
||||
battery: lastBattery,
|
||||
controlMode: data['control_mode']?.toString().trim() ?? '',
|
||||
),
|
||||
);
|
||||
} on FormatException {
|
||||
// 忽略格式异常的单帧,等待下一次上报。
|
||||
}
|
||||
},
|
||||
onError: controller.addError,
|
||||
onDone: controller.close,
|
||||
);
|
||||
topicSubscription = mqttClient.subscribe(topic).catchError(
|
||||
(Object error, StackTrace stackTrace) {
|
||||
if (!controller.isClosed) controller.addError(error, stackTrace);
|
||||
},
|
||||
);
|
||||
},
|
||||
onCancel: () async {
|
||||
await messageSubscription?.cancel();
|
||||
final subscription = topicSubscription;
|
||||
if (subscription == null) return;
|
||||
await subscription;
|
||||
try {
|
||||
// 客户端按引用计数释放,详情页仍在使用时会保留其订阅。
|
||||
await mqttClient.unsubscribe(topic);
|
||||
} catch (error) {
|
||||
debugPrint('[设备概览] 释放订阅失败 $topic: $error');
|
||||
}
|
||||
},
|
||||
);
|
||||
return controller.stream.distinct();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> startListening({required String deviceSn}) async {
|
||||
if (deviceSn.isEmpty) {
|
||||
|
||||
@@ -28,6 +28,11 @@ class MowerRealtimeRepositoryImpl implements MowerRealtimeRepository {
|
||||
Stream<HostRealtimeMessageEntity> get hostRealtimeStream =>
|
||||
dataSource.hostRealtimeStream;
|
||||
|
||||
@override
|
||||
Stream<({double? battery, String controlMode})> watchOverviewStatus(
|
||||
String deviceSn,
|
||||
) => dataSource.watchOverviewStatus(deviceSn);
|
||||
|
||||
@override
|
||||
Future<Either<Failure, void>> startListening({
|
||||
required String deviceSn,
|
||||
|
||||
@@ -66,7 +66,7 @@ class HostRealtimeMessageEntity extends Equatable {
|
||||
/// [data] 为报文 `data` 子对象(由 DataSource 提取,与 MowerLocationEntity 一致)
|
||||
factory HostRealtimeMessageEntity.fromJson(Map<String, dynamic> data) {
|
||||
return HostRealtimeMessageEntity(
|
||||
batteryPercentage: _toDouble(data['battery_percentage']),
|
||||
batteryPercentage: parseBatteryPercentage(data['battery_percentage']) ?? 0,
|
||||
batteryVoltage: _toDouble(data['battery_voltage']),
|
||||
leftMotorCurrent: _toDouble(data['left_motor_current']),
|
||||
rightMotorCurrent: _toDouble(data['right_motor_current']),
|
||||
@@ -95,6 +95,20 @@ class HostRealtimeMessageEntity extends Equatable {
|
||||
);
|
||||
}
|
||||
|
||||
/// 供主机状态和设备概览使用,区分无效值与真实的 0%。
|
||||
static double? parseBatteryPercentage(Object? value) {
|
||||
final percentage = value is num
|
||||
? value.toDouble()
|
||||
: double.tryParse(value?.toString() ?? '');
|
||||
if (percentage == null ||
|
||||
!percentage.isFinite ||
|
||||
percentage < 0 ||
|
||||
percentage > 100) {
|
||||
return null;
|
||||
}
|
||||
return percentage;
|
||||
}
|
||||
|
||||
static double _toDouble(dynamic value) {
|
||||
if (value == null) return 0;
|
||||
if (value is num) return value.toDouble();
|
||||
|
||||
@@ -13,6 +13,10 @@ abstract class MowerRealtimeRepository {
|
||||
Stream<RouteStatusEntity> get routeStatusStream;
|
||||
Stream<HostRealtimeMessageEntity> get hostRealtimeStream;
|
||||
|
||||
Stream<({double? battery, String controlMode})> watchOverviewStatus(
|
||||
String deviceSn,
|
||||
);
|
||||
|
||||
Future<Either<Failure, void>> startListening({
|
||||
required String deviceSn,
|
||||
});
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:logger/logger.dart';
|
||||
import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart';
|
||||
import 'package:maibu_satabot_v2/core/app/app_user_state.dart';
|
||||
import 'package:maibu_satabot_v2/core/domain/entities/user_entity.dart';
|
||||
import 'package:open_file/open_file.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
@@ -11,19 +15,52 @@ import 'update_state.dart';
|
||||
/// 更新 Cubit
|
||||
class UpdateCubit extends Cubit<UpdateState> {
|
||||
final VersionCheckService _versionService;
|
||||
final Logger _logger;
|
||||
final AppUserCubit _users;
|
||||
final Logger _logger = Logger();
|
||||
late final StreamSubscription<AppUserState> _adminChanges;
|
||||
UserEntity? _updateOwner;
|
||||
|
||||
UpdateCubit(this._versionService)
|
||||
: _logger = Logger(),
|
||||
super(UpdateInitial());
|
||||
UpdateCubit(this._versionService, this._users) : super(const UpdateInitial()) {
|
||||
_adminChanges = _users.stream.listen((_) {
|
||||
final owner = _updateOwner;
|
||||
if (owner != null && !_canContinue(owner)) {
|
||||
_updateOwner = null;
|
||||
emit(const UpdateInitial());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
UserEntity? get _adminUser {
|
||||
final user = _users.state.user;
|
||||
return user?.isAdmin == true ? user : null;
|
||||
}
|
||||
|
||||
UserEntity? _beginUpdate() {
|
||||
if (isClosed) return null;
|
||||
final admin = _adminUser;
|
||||
if (admin != null) _updateOwner = admin;
|
||||
return admin;
|
||||
}
|
||||
|
||||
bool _canContinue(UserEntity admin) =>
|
||||
!isClosed && identical(_updateOwner, admin) && identical(_adminUser, admin);
|
||||
|
||||
@override
|
||||
Future<void> close() async {
|
||||
await _adminChanges.cancel();
|
||||
await super.close();
|
||||
}
|
||||
|
||||
/// 检查版本更新
|
||||
Future<void> checkUpdate() async {
|
||||
emit(UpdateChecking());
|
||||
final admin = _beginUpdate();
|
||||
if (admin == null) return;
|
||||
emit(const UpdateChecking());
|
||||
|
||||
try {
|
||||
// 从 pubspec.yaml 读取版本信息
|
||||
final String versionString = await rootBundle.loadString('pubspec.yaml');
|
||||
if (!_canContinue(admin)) return;
|
||||
final versionMatch = RegExp(r'version:\s*(\d+\.\d+\.\d+)\+(\d+)').firstMatch(versionString);
|
||||
|
||||
final currentVersion = versionMatch?.group(1) ?? '1.0.0';
|
||||
@@ -37,6 +74,7 @@ class UpdateCubit extends Cubit<UpdateState> {
|
||||
currentVersionCode: currentVersionCode,
|
||||
);
|
||||
|
||||
if (!_canContinue(admin)) return;
|
||||
if (versionInfo == null) {
|
||||
_logger.i('✅ 已是最新版本');
|
||||
emit(UpdateUpToDate());
|
||||
@@ -49,6 +87,7 @@ class UpdateCubit extends Cubit<UpdateState> {
|
||||
|
||||
emit(UpdateAvailable(versionInfo));
|
||||
} catch (e) {
|
||||
if (!_canContinue(admin)) return;
|
||||
_logger.e('❌ 检查更新失败: $e');
|
||||
emit(UpdateFailure('检查更新失败: $e'));
|
||||
}
|
||||
@@ -56,6 +95,8 @@ class UpdateCubit extends Cubit<UpdateState> {
|
||||
|
||||
/// 应用差量补丁
|
||||
Future<void> applyPatch(String patchUrl, String version, int targetVersionCode, {String? md5}) async {
|
||||
final admin = _beginUpdate();
|
||||
if (admin == null) return;
|
||||
emit(const UpdateDownloading(0.0, isPatch: true));
|
||||
|
||||
try {
|
||||
@@ -67,11 +108,13 @@ class UpdateCubit extends Cubit<UpdateState> {
|
||||
targetVersionCode: targetVersionCode,
|
||||
md5: md5,
|
||||
onProgress: (progress) {
|
||||
// 🔥 实时更新下载进度
|
||||
emit(UpdateDownloading(progress, isPatch: true));
|
||||
if (_canContinue(admin)) {
|
||||
emit(UpdateDownloading(progress, isPatch: true));
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
if (!_canContinue(admin)) return;
|
||||
if (success) {
|
||||
emit(const UpdateInstalling(isPatch: true));
|
||||
emit(UpdateSuccess());
|
||||
@@ -79,6 +122,7 @@ class UpdateCubit extends Cubit<UpdateState> {
|
||||
emit(const UpdateFailure('补丁应用失败'));
|
||||
}
|
||||
} catch (e) {
|
||||
if (!_canContinue(admin)) return;
|
||||
_logger.e('❌ 应用补丁异常: $e');
|
||||
emit(UpdateFailure('应用补丁失败: $e'));
|
||||
}
|
||||
@@ -86,15 +130,20 @@ class UpdateCubit extends Cubit<UpdateState> {
|
||||
|
||||
/// 自动下载并安装 APK(App 内下载)
|
||||
Future<void> downloadAndInstallApk(String apkUrl) async {
|
||||
final admin = _beginUpdate();
|
||||
if (admin == null) return;
|
||||
emit(const UpdateDownloading(0.0, isPatch: false));
|
||||
|
||||
try {
|
||||
_logger.i('⬇️ 开始下载完整 APK');
|
||||
|
||||
final apkPath = await _versionService.downloadApk(apkUrl, (progress) {
|
||||
emit(UpdateDownloading(progress, isPatch: false));
|
||||
if (_canContinue(admin)) {
|
||||
emit(UpdateDownloading(progress, isPatch: false));
|
||||
}
|
||||
});
|
||||
|
||||
if (!_canContinue(admin)) return;
|
||||
if (apkPath != null) {
|
||||
_logger.i('✅ APK 下载完成: $apkPath');
|
||||
// 🔥 关键:先清理版本号记录,并等待用户看到提示
|
||||
@@ -105,6 +154,7 @@ class UpdateCubit extends Cubit<UpdateState> {
|
||||
|
||||
// 🔥 短暂延迟,让用户看到清理完成的提示
|
||||
await Future.delayed(const Duration(milliseconds: 800));
|
||||
if (!_canContinue(admin)) return;
|
||||
|
||||
// 🔥 直接调起系统安装页面,不再等待用户点击
|
||||
_logger.i('📦 自动调起系统安装页面');
|
||||
@@ -113,6 +163,7 @@ class UpdateCubit extends Cubit<UpdateState> {
|
||||
emit(const UpdateFailure('APK 下载失败'));
|
||||
}
|
||||
} catch (e) {
|
||||
if (!_canContinue(admin)) return;
|
||||
_logger.e('❌ 下载安装 APK 异常: $e');
|
||||
emit(UpdateFailure('下载安装 APK 失败: $e'));
|
||||
}
|
||||
@@ -120,6 +171,8 @@ class UpdateCubit extends Cubit<UpdateState> {
|
||||
|
||||
/// 触发系统安装页面
|
||||
Future<void> triggerInstall(String apkPath) async {
|
||||
final admin = _beginUpdate();
|
||||
if (admin == null) return;
|
||||
emit(const UpdateInstalling(isPatch: false));
|
||||
|
||||
try {
|
||||
@@ -129,6 +182,7 @@ class UpdateCubit extends Cubit<UpdateState> {
|
||||
// 🔥 验证文件是否存在
|
||||
final file = File(apkPath);
|
||||
if (!await file.exists()) {
|
||||
if (!_canContinue(admin)) return;
|
||||
_logger.e('❌ APK 文件不存在: $apkPath');
|
||||
emit(UpdateFailure('APK 文件不存在,请重新下载'));
|
||||
return;
|
||||
@@ -139,6 +193,7 @@ class UpdateCubit extends Cubit<UpdateState> {
|
||||
|
||||
// 🔥 关键修复:将APK复制到外部存储,避免某些Android版本的安装限制
|
||||
final externalDir = await getExternalStorageDirectory();
|
||||
if (!_canContinue(admin)) return;
|
||||
String finalApkPath = apkPath;
|
||||
|
||||
if (externalDir != null) {
|
||||
@@ -157,7 +212,9 @@ class UpdateCubit extends Cubit<UpdateState> {
|
||||
// 打开 APK 文件,触发系统安装界面
|
||||
_logger.i('🚀 调用 OpenFile.open...');
|
||||
_logger.i('🚀 最终APK路径: $finalApkPath');
|
||||
if (!_canContinue(admin)) return;
|
||||
final result = await OpenFile.open(finalApkPath);
|
||||
if (!_canContinue(admin)) return;
|
||||
_logger.i('📦 安装结果: ${result.message} (type: ${result.type})');
|
||||
|
||||
// 如果用户取消安装,显示提示信息并保留文件路径
|
||||
@@ -180,6 +237,7 @@ class UpdateCubit extends Cubit<UpdateState> {
|
||||
emit(UpdateSuccess());
|
||||
}
|
||||
} catch (e) {
|
||||
if (!_canContinue(admin)) return;
|
||||
_logger.e('❌ 调起安装页面异常: $e');
|
||||
emit(UpdateFailure('调起安装页面失败: $e'));
|
||||
}
|
||||
@@ -187,24 +245,29 @@ class UpdateCubit extends Cubit<UpdateState> {
|
||||
|
||||
/// 整包更新:浏览器下载 + 引导弹窗
|
||||
Future<void> fullApkUpdateWithBrowser(String apkUrl) async {
|
||||
final admin = _beginUpdate();
|
||||
if (admin == null) return;
|
||||
try {
|
||||
_logger.i('🌐 整包更新:打开浏览器下载');
|
||||
|
||||
final uri = Uri.parse(apkUrl);
|
||||
if (await canLaunchUrl(uri)) {
|
||||
final canLaunch = await canLaunchUrl(uri);
|
||||
if (!_canContinue(admin)) return;
|
||||
if (canLaunch) {
|
||||
await launchUrl(uri, mode: LaunchMode.externalApplication);
|
||||
_logger.i('✅ 已打开浏览器下载');
|
||||
|
||||
// 🔥 整包更新后,立即清除补丁版本记录(避免死循环)
|
||||
await _versionService.clearPatchVersionInfo();
|
||||
_logger.i('🗑️ 已清除补丁版本记录');
|
||||
|
||||
emit(UpdateSuccess());
|
||||
|
||||
if (_canContinue(admin)) emit(const UpdateSuccess());
|
||||
} else {
|
||||
_logger.e('❌ 无法打开浏览器');
|
||||
emit(const UpdateFailure('无法打开浏览器'));
|
||||
}
|
||||
} catch (e) {
|
||||
if (!_canContinue(admin)) return;
|
||||
_logger.e('❌ 打开浏览器异常: $e');
|
||||
emit(UpdateFailure('打开浏览器失败: $e'));
|
||||
}
|
||||
@@ -212,6 +275,7 @@ class UpdateCubit extends Cubit<UpdateState> {
|
||||
|
||||
/// 取消更新
|
||||
void cancelUpdate() {
|
||||
_updateOwner = null;
|
||||
_logger.i('❌ 用户取消更新');
|
||||
emit(UpdateInitial());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user