对接连续任务列表接口和连续任务下发,便捷操作中暂停任务的对接,底部导航tab项的设置根据用户角色显示和设置

This commit is contained in:
2026-11-11 16:51:21 +08:00
parent 47f518f94c
commit 985bcf4b55
54 changed files with 5017 additions and 0 deletions

View File

@@ -0,0 +1,201 @@
import 'package:flutter/material.dart';
import 'package:maibu_satabot_v2/components/capsule_toast.dart';
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
import 'package:shared_preferences/shared_preferences.dart';
class DeviceQuickActions extends StatefulWidget {
const DeviceQuickActions({
super.key,
required this.actions,
required this.preferences,
});
final Map<String, ({IconData icon, VoidCallback onTap})> actions;
final SharedPreferences preferences;
@override
State<DeviceQuickActions> createState() => _DeviceQuickActionsState();
}
class _DeviceQuickActionsState extends State<DeviceQuickActions> {
static const _preferenceKey = 'device_detail_quick_action_order';
static const _navy = Color(0xFF1A2B4A);
static const _blue = Color(0xFF1C96F6);
static const _columns = 3;
late final List<String> _order;
bool _editing = false;
bool _saving = false;
@override
void initState() {
super.initState();
final saved = widget.preferences.getStringList(_preferenceKey) ?? [];
_order = {
...saved.where(widget.actions.containsKey),
...widget.actions.keys,
}.toList();
}
void _move(String source, String target) {
if (!_editing || _saving) return;
final from = _order.indexOf(source);
final to = _order.indexOf(target);
setState(() => _order.insert(to, _order.removeAt(from)));
}
Future<void> _save() async {
if (_saving) return;
setState(() => _saving = true);
var saved = false;
try {
saved = await widget.preferences.setStringList(
_preferenceKey,
List.of(_order),
);
} catch (error) {
debugPrint('常用功能排序保存失败: $error');
}
if (!mounted) return;
setState(() {
_saving = false;
_editing = !saved;
});
if (!saved) {
CapsuleToast.show(
AppLocalizations.of(
context,
).translate('device_detail_v2.fn_save_failed'),
showCheck: false,
);
}
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
spacing: 8,
children: [
Row(
children: [
Expanded(
child: Text(
l10n.translate('device_detail_v2.fn_title'),
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w800,
color: _navy,
),
),
),
GestureDetector(
onTap: _saving
? null
: _editing
? _save
: () => setState(() => _editing = true),
child: Row(
mainAxisSize: MainAxisSize.min,
spacing: 4,
children: [
Icon(
_editing ? Icons.check_rounded : Icons.edit_outlined,
size: 13,
color: _blue,
),
Text(
l10n.translate(
_editing
? 'device_detail_v2.fn_save_order'
: 'device_detail_v2.fn_edit_order',
),
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: _blue,
),
),
],
),
),
],
),
if (_editing)
Text(
l10n.translate('device_detail_v2.fn_drag_order'),
style: const TextStyle(fontSize: 12, color: Color(0xFF86909C)),
),
for (var start = 0; start < _order.length; start += _columns)
Row(
spacing: 10,
children: [
for (final id in _order.skip(start).take(_columns))
Expanded(
child: _editing
? _buildDraggable(id)
: GestureDetector(
onTap: widget.actions[id]!.onTap,
child: _buildTile(id),
),
),
for (var slot = _order.length; slot < start + _columns; slot++)
const Spacer(),
],
),
],
);
}
Widget _buildDraggable(String id) => DragTarget<String>(
onWillAcceptWithDetails: (details) =>
!_saving && details.data != id && _order.contains(details.data),
onAcceptWithDetails: (details) => _move(details.data, id),
builder: (context, candidates, _) => LayoutBuilder(
builder: (context, constraints) {
final tile = _buildTile(id, highlighted: candidates.isNotEmpty);
return LongPressDraggable<String>(
data: id,
maxSimultaneousDrags: _saving ? 0 : 1,
feedback: Material(
color: Colors.transparent,
child: SizedBox(width: constraints.maxWidth, child: tile),
),
childWhenDragging: Opacity(opacity: 0.35, child: tile),
child: tile,
);
},
),
);
Widget _buildTile(String id, {bool highlighted = false}) {
final l10n = AppLocalizations.of(context);
return Container(
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 4),
decoration: BoxDecoration(
color: highlighted ? const Color(0xFFE5F3FF) : const Color(0xFFF6FAFE),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: highlighted ? _blue : const Color(0xFFD9E8F8),
),
),
child: Column(
children: [
Icon(widget.actions[id]!.icon, size: 22, color: _blue),
const SizedBox(height: 6),
Text(
l10n.translate('device_detail_v2.$id'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: _navy,
),
),
],
),
);
}
}

View File

@@ -0,0 +1,407 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
import '../../../../autonomous_work/domain/entities/work_session_models.dart';
import '../../../../autonomous_work/domain/repositories/autonomous_work_gateway.dart';
/// 与自主作业共用任务池和指令链路,设备编号使用 deviceName(SN)。
class DeviceTaskControlTile extends StatefulWidget {
const DeviceTaskControlTile({
super.key,
required this.deviceId,
required this.gateway,
});
final String deviceId;
final AutonomousWorkGateway gateway;
@override
State<DeviceTaskControlTile> createState() => _DeviceTaskControlTileState();
}
class _DeviceTaskControlTileState extends State<DeviceTaskControlTile>
with WidgetsBindingObserver {
static const _blue = Color(0xFF1C96F6);
static const _navy = Color(0xFF1A2B4A);
static const _yellow = Color(0xFFFFF3CD);
final _tasks = <String, WorkTaskSnapshot>{};
final _updates = <String, (int, WorkTaskSnapshot)>{};
StreamSubscription<WorkTaskSnapshot?>? _subscription;
int _revision = 0;
int _clearedAt = 0;
int _queryVersion = 0;
int _generation = 0;
bool _busy = false;
bool _dialogOpen = false;
String? _selectedId;
AppLocalizations get _l10n => AppLocalizations.of(context);
String _text(String key) => _l10n.translate('device_task_control.$key');
bool _controllable(WorkTaskSnapshot task) =>
task.deviceId == widget.deviceId &&
task.rawStatus.toUpperCase() != 'CANCELING' &&
(task.state == WorkRunState.running || task.state == WorkRunState.paused);
List<WorkTaskSnapshot> get _candidates =>
_tasks.values.where(_controllable).toList();
bool get _paused {
final selected = _tasks[_selectedId];
if (selected != null && _controllable(selected)) {
return selected.state == WorkRunState.paused;
}
return _candidates.isNotEmpty &&
_candidates.every((task) => task.state == WorkRunState.paused);
}
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_listen();
}
void _listen() {
final gateway = widget.gateway;
final generation = _generation;
final stream = gateway is WorkTaskQueueSource
? (gateway as WorkTaskQueueSource).watchTaskChanges(
deviceId: widget.deviceId,
)
: gateway.watchTask(deviceId: widget.deviceId);
_subscription = stream.listen((task) {
if (!mounted ||
generation != _generation ||
(task != null && task.deviceId != widget.deviceId)) {
return;
}
setState(() {
_revision++;
if (task == null) {
_clearedAt = _revision;
_tasks.clear();
_updates.clear();
} else {
_updates[task.taskId] = (_revision, task);
_apply(task);
}
});
}, onError: (Object _) {});
unawaited(_refresh());
}
@override
void didUpdateWidget(DeviceTaskControlTile oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.deviceId == widget.deviceId &&
identical(oldWidget.gateway, widget.gateway)) {
return;
}
unawaited(_subscription?.cancel());
_generation++;
_queryVersion++;
_revision++;
_tasks.clear();
_updates.clear();
_busy = false;
_selectedId = null;
_listen();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed && !_busy) unawaited(_refresh());
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
unawaited(_subscription?.cancel());
super.dispose();
}
void _apply(WorkTaskSnapshot task) {
if (task.state == WorkRunState.finished ||
task.state == WorkRunState.idle) {
_tasks.remove(task.taskId);
} else {
_tasks[task.taskId] = task;
}
}
bool _sameTarget(String deviceId, AutonomousWorkGateway gateway) =>
mounted &&
widget.deviceId == deviceId &&
identical(widget.gateway, gateway);
Future<bool> _refresh() async {
final deviceId = widget.deviceId;
final gateway = widget.gateway;
final startedAt = _revision;
final queryVersion = ++_queryVersion;
try {
final result = await gateway.loadTasks(deviceId: deviceId);
if (!_sameTarget(deviceId, gateway) || queryVersion != _queryVersion) {
return false;
}
if (!result.isOk) return false;
setState(() {
_tasks.clear();
if (_clearedAt <= startedAt) {
for (final task in result.data ?? <WorkTaskSnapshot>[]) {
if (task.deviceId == deviceId) _apply(task);
}
}
// 请求期间的设备回执优先,避免重新显示已结束或已恢复的任务。
for (final (revision, task) in _updates.values) {
if (revision > startedAt) _apply(task);
}
});
return true;
} catch (_) {
return false;
}
}
Future<T?> _dialog<T>(WidgetBuilder builder) async {
if (!mounted) return null;
setState(() => _dialogOpen = true);
try {
return await showDialog<T>(context: context, builder: builder);
} finally {
if (mounted) setState(() => _dialogOpen = false);
}
}
Future<void> _notice(String key) => _dialog<void>(
(context) => AlertDialog(
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
title: Text(_text('title')),
content: Text(_text(key)),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text(_l10n.translate('common.ok')),
),
],
),
);
String _taskName(WorkTaskSnapshot task) =>
task.routeName?.trim().isNotEmpty == true
? task.routeName!
: _l10n.translate('device_task_control.task_number', {'id': task.taskId});
Future<WorkTaskSnapshot?> _choose(
List<WorkTaskSnapshot> tasks,
) => _dialog<WorkTaskSnapshot>(
(context) => SimpleDialog(
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
title: Text(_text('choose_task')),
children: [
for (final task in tasks)
SimpleDialogOption(
onPressed: () => Navigator.pop(context, task),
child: ListTile(
contentPadding: EdgeInsets.zero,
leading: Icon(
task.state == WorkRunState.paused
? Icons.play_circle_outline
: Icons.pause_circle_outline,
color: _blue,
),
title: Text(_taskName(task)),
subtitle: Text(
'${_l10n.translate('device_task_control.task_number', {'id': task.taskId})} · ${_text(task.state == WorkRunState.paused ? 'paused' : 'running')}',
),
),
),
],
),
);
Future<void> _onTap() async {
if (_busy) return;
final deviceId = widget.deviceId;
final gateway = widget.gateway;
final generation = _generation;
bool current() =>
_sameTarget(deviceId, gateway) && generation == _generation;
setState(() => _busy = true);
try {
if (!await _refresh()) {
if (current()) await _notice('load_failed');
return;
}
if (!current()) return;
final candidates = _candidates;
if (candidates.isEmpty) {
await _notice(_tasks.isEmpty ? 'no_task' : 'not_running');
return;
}
final selected = _tasks[_selectedId];
final task =
selected != null &&
_controllable(selected) &&
selected.state == WorkRunState.paused
? selected
: candidates.length == 1
? candidates.single
: await _choose(candidates);
if (task == null || !current()) return;
final resume = task.state == WorkRunState.paused;
if (!(resume
? gateway.capabilities.resume
: gateway.capabilities.pause)) {
await _notice('unavailable');
return;
}
final confirmed = await _dialog<bool>(
(context) => AlertDialog(
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18),
),
title: Text(_text(resume ? 'resume' : 'pause')),
content: Text(
'${_taskName(task)}\n\n${_l10n.translate(resume ? 'autonomous_work.resume_description' : 'autonomous_work.pause_description', {'route': _taskName(task)})}',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: Text(_l10n.translate('common.cancel')),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
child: Text(
_l10n.translate(
resume
? 'autonomous_work.resume_confirm'
: 'autonomous_work.pause_confirm',
),
),
),
],
),
);
if (confirmed != true || !current()) return;
// 弹窗停留期间可能换任务或任务结束,发送前再次核对同一任务。
if (!await _refresh()) {
if (current()) await _notice('load_failed');
return;
}
if (!current()) return;
final latest = _tasks[task.taskId];
if (latest == null ||
!_controllable(latest) ||
latest.state != task.state) {
await _notice(_tasks.isEmpty ? 'no_task' : 'task_changed');
return;
}
final sentAt = _revision;
final result = resume
? await gateway.resumeWork(deviceId: deviceId, task: latest)
: await gateway.pauseWork(deviceId: deviceId, task: latest);
if (!current()) return;
if (!result.isOk || result.data == null) {
await _notice(resume ? 'resume_failed' : 'pause_failed');
return;
}
final event = _updates[task.taskId];
final updated = event != null && event.$1 > sentAt
? event.$2
: result.data!;
if (updated.deviceId == deviceId && _clearedAt <= sentAt) {
setState(() {
_apply(updated);
_selectedId = _controllable(updated) ? updated.taskId : null;
});
}
} catch (_) {
if (current()) await _notice('operation_failed');
} finally {
if (current()) setState(() => _busy = false);
}
}
@override
Widget build(BuildContext context) {
final paused = _paused;
final color = paused ? const Color(0xFF9A6700) : _blue;
return Semantics(
button: true,
enabled: !_busy,
child: GestureDetector(
onTap: _busy ? null : _onTap,
behavior: HitTestBehavior.opaque,
child: Container(
key: const ValueKey('device-task-control-background'),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 10),
decoration: BoxDecoration(
color: paused ? _yellow : Colors.white,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: paused ? const Color(0xFFF1CE70) : const Color(0xFFE5EDF7),
),
),
child: Row(
children: [
if (_busy && !_dialogOpen)
SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
color: color,
),
)
else
Icon(
paused
? Icons.play_circle_outline
: Icons.pause_circle_outline,
size: 20,
color: color,
),
const SizedBox(width: 7),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_text(paused ? 'resume' : 'pause'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 11.5,
fontWeight: FontWeight.w700,
color: _navy,
),
),
const SizedBox(height: 2),
Text(
_busy && !_dialogOpen
? _l10n.translate('common.loading')
: _text(paused ? 'resume_hint' : 'pause_hint'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 9,
color: paused ? color : const Color(0xFF86909C),
),
),
],
),
),
],
),
),
),
);
}
}

View File

@@ -0,0 +1,235 @@
import 'dart:math' as math;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'autonomous/work_ui.dart';
/// 地图保持正北朝上,手柄沿地图的东西和南北方向调整矩形。
class ObstacleResizeLayer extends StatelessWidget {
const ObstacleResizeLayer({
super.key,
required this.corners,
required this.dimensions,
required this.onChanged,
});
final List<LatLng> corners;
final String dimensions;
final ValueChanged<List<LatLng>> onChanged;
static const _handles = [
Alignment.topLeft,
Alignment.topCenter,
Alignment.topRight,
Alignment.centerLeft,
Alignment.centerRight,
Alignment.bottomLeft,
Alignment.bottomCenter,
Alignment.bottomRight,
];
static const double _targetSize = 28;
@override
Widget build(BuildContext context) {
final camera = MapCamera.of(context);
final bounds = LatLngBounds.fromPoints(corners);
final northWest = camera.latLngToScreenPoint(
LatLng(bounds.north, bounds.west),
);
final southEast = camera.latLngToScreenPoint(
LatLng(bounds.south, bounds.east),
);
final rect = Rect.fromPoints(
Offset(northWest.x, northWest.y),
Offset(southEast.x, southEast.y),
);
// 小矩形在低缩放级别仍要能分别抓住边和角。仅将手柄向外错开。
final xGap = math.max(0.0, _targetSize - rect.width / 2);
final yGap = math.max(0.0, _targetSize - rect.height / 2);
return Stack(
fit: StackFit.expand,
children: [
Positioned.fromRect(
rect: rect,
child: IgnorePointer(
child: DecoratedBox(
decoration: BoxDecoration(
border: Border.all(color: kWtBlue, width: 2),
),
),
),
),
Positioned(
top: rect.top - yGap - 36,
left: rect.center.dx,
child: FractionalTranslation(
translation: const Offset(-0.5, 0),
child: IgnorePointer(
child: WorkChip(
text: dimensions,
background: Colors.white,
foreground: kWtNavy,
),
),
),
),
for (final alignment in _handles)
Positioned(
key: ValueKey(alignment),
left:
alignment.withinRect(rect).dx +
alignment.x * xGap -
_targetSize / 2,
top:
alignment.withinRect(rect).dy +
alignment.y * yGap -
_targetSize / 2,
width: _targetSize,
height: _targetSize,
child: _ResizeHandle(
alignment: alignment,
bounds: bounds,
camera: camera,
onChanged: onChanged,
),
),
],
);
}
}
class _ResizeHandle extends StatefulWidget {
const _ResizeHandle({
required this.alignment,
required this.bounds,
required this.camera,
required this.onChanged,
});
final Alignment alignment;
final LatLngBounds bounds;
final MapCamera camera;
final ValueChanged<List<LatLng>> onChanged;
@override
State<_ResizeHandle> createState() => _ResizeHandleState();
}
class _ResizeHandleState extends State<_ResizeHandle> {
({
LatLngBounds bounds,
MapCamera camera,
math.Point<double> anchor,
Offset start,
})?
_drag;
void _start(DragStartDetails details) {
final bounds = widget.bounds;
final alignment = widget.alignment;
final anchor = LatLng(
alignment.y < 0
? bounds.north
: alignment.y > 0
? bounds.south
: bounds.center.latitude,
alignment.x < 0
? bounds.west
: alignment.x > 0
? bounds.east
: bounds.center.longitude,
);
final camera = widget.camera;
_drag = (
bounds: bounds,
camera: camera,
anchor: camera.project(anchor),
start: details.globalPosition,
);
}
void _update(DragUpdateDetails details) {
final drag = _drag;
if (drag == null) return;
final delta = details.globalPosition - drag.start;
final target = drag.camera.unproject(
drag.anchor + math.Point<double>(delta.dx, delta.dy),
);
final bounds = drag.bounds;
final alignment = widget.alignment;
// 保留相对边的位置,至少留下 0.1 米,避免拖过另一边时反转。
const minLat = 0.1 / 111320.0;
final cosLat = math.cos(bounds.center.latitude * math.pi / 180);
final minLng = minLat / math.max(cosLat, 0.000001);
final west = alignment.x < 0
? math.max(-180.0, math.min(target.longitude, bounds.east - minLng))
: bounds.west;
final east = alignment.x > 0
? math.min(180.0, math.max(target.longitude, bounds.west + minLng))
: bounds.east;
final north = alignment.y < 0
? math.min(90.0, math.max(target.latitude, bounds.south + minLat))
: bounds.north;
final south = alignment.y > 0
? math.max(-90.0, math.min(target.latitude, bounds.north - minLat))
: bounds.south;
if (west >= east || south >= north) return;
widget.onChanged([
LatLng(south, west),
LatLng(south, east),
LatLng(north, east),
LatLng(north, west),
]);
}
@override
Widget build(BuildContext context) {
final alignment = widget.alignment;
final horizontalEdge = alignment.x == 0;
final verticalEdge = alignment.y == 0;
return RawGestureDetector(
behavior: HitTestBehavior.opaque,
gestures: {
_ResizePanRecognizer:
GestureRecognizerFactoryWithHandlers<_ResizePanRecognizer>(
_ResizePanRecognizer.new,
(recognizer) {
recognizer
..dragStartBehavior = DragStartBehavior.down
..onStart = _start
..onUpdate = _update
..onEnd = (_) {
_drag = null;
}
..onCancel = () {
_drag = null;
};
},
),
},
child: Center(
child: Container(
width: horizontalEdge ? 18 : 11,
height: verticalEdge ? 18 : 11,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(4),
border: Border.all(color: kWtBlue, width: 2),
),
),
),
);
}
}
/// 地图的横竖拖动阈值低于普通 Pan。按住手柄时优先交给矩形编辑。
class _ResizePanRecognizer extends PanGestureRecognizer {
@override
void addAllowedPointer(PointerDownEvent event) {
super.addAllowedPointer(event);
resolve(GestureDisposition.accepted);
}
}

View File

@@ -0,0 +1,82 @@
import 'package:flutter/material.dart';
import 'package:maibu_satabot_v2/components/control_mode_text.dart';
import 'package:maibu_satabot_v2/core/di/injection.dart';
import 'package:maibu_satabot_v2/core/localization/app_localizations.dart';
import 'package:maibu_satabot_v2/core/network/mqtt/domain/repositories/mower_realtime_repository.dart';
/// 电量和控制模式共用同一条主机实时订阅。
class OverviewDeviceTelemetry extends StatefulWidget {
const OverviewDeviceTelemetry({
super.key,
this.deviceSn,
required this.batteryFallback,
});
final String? deviceSn;
final String batteryFallback;
@override
State<OverviewDeviceTelemetry> createState() =>
_OverviewDeviceTelemetryState();
}
class _OverviewDeviceTelemetryState extends State<OverviewDeviceTelemetry> {
late Stream<({double? battery, String controlMode})>? _stream =
_watchStatus();
Stream<({double? battery, String controlMode})>? _watchStatus() {
final sn = widget.deviceSn;
return sn == null
? null
: sl<MowerRealtimeRepository>().watchOverviewStatus(sn);
}
@override
void didUpdateWidget(covariant OverviewDeviceTelemetry oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.deviceSn != widget.deviceSn) {
_stream = _watchStatus();
}
}
@override
Widget build(BuildContext context) {
return StreamBuilder<({double? battery, String controlMode})>(
key: ValueKey(widget.deviceSn),
stream: _stream,
builder: (context, snapshot) {
final battery = snapshot.data?.battery;
final mode = snapshot.data?.controlMode ?? '';
return Row(
children: [
Expanded(
flex: 2,
child: Text(
battery == null ? widget.batteryFallback : '$battery%',
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: Color(0xFF1A2B4A),
),
),
),
Expanded(
flex: 4,
child: Text(
mode.isEmpty
? '--'
: controlModeDisplayText(
AppLocalizations.of(context),
mode,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 11, color: Color(0xFF86909C)),
),
),
],
);
},
);
}
}