作业首页和机器状态的数据
This commit is contained in:
@@ -3,6 +3,7 @@ import 'package:dio/dio.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import '../../../../core/consts/http_api_consts.dart';
|
||||
import '../../../../core/logging/i_logger_service.dart';
|
||||
import '../../domain/entities/device_schedule_plan_entity.dart';
|
||||
import '../models/device_task_model.dart';
|
||||
|
||||
abstract class DeviceTaskDatasource {
|
||||
@@ -35,6 +36,10 @@ abstract class DeviceTaskDatasource {
|
||||
required int orgId,
|
||||
required int siteId,
|
||||
});
|
||||
|
||||
/// 创建设备定时任务(定时作业计划)POST /iot/deviceTask/save
|
||||
/// 周期规则报文组装封在实现内,调用方只交业务实体
|
||||
Future<bool> saveDeviceSchedulePlan({required DeviceSchedulePlanEntity plan});
|
||||
}
|
||||
|
||||
class DeviceTaskDatasourceImpl implements DeviceTaskDatasource {
|
||||
@@ -53,8 +58,8 @@ class DeviceTaskDatasourceImpl implements DeviceTaskDatasource {
|
||||
}) async {
|
||||
try {
|
||||
final url = '${HttpApiConsts.baseUrl}/iot/deviceTask/deviceTaskPool';
|
||||
_logger.logWithLevel('[getDeviceTaskPool] 请求: POST $url');
|
||||
_logger.logWithLevel('[getDeviceTaskPool] 参数: userId=$userId, siteId=$siteId, orgId=$orgId');
|
||||
_logger.logWithLevel('[getDeviceTaskPool] 请求: POST $url', shouldLog: true);
|
||||
_logger.logWithLevel('[getDeviceTaskPool] 参数: userId=$userId, siteId=$siteId, orgId=$orgId, pageNum=$pageNum, pageSize=$pageSize', shouldLog: true);
|
||||
final response = await dio.post(
|
||||
url,
|
||||
data: {
|
||||
@@ -70,6 +75,7 @@ class DeviceTaskDatasourceImpl implements DeviceTaskDatasource {
|
||||
final data = response.data as Map<String, dynamic>;
|
||||
if (data['code'] == 200) {
|
||||
final rows = data['rows'] as List? ?? [];
|
||||
_logger.logWithLevel('[getDeviceTaskPool] 返回任务 ${rows.length} 条', shouldLog: true);
|
||||
return rows
|
||||
.map((item) => DeviceTaskModel.fromJson(item as Map<String, dynamic>))
|
||||
.toList();
|
||||
@@ -199,4 +205,84 @@ class DeviceTaskDatasourceImpl implements DeviceTaskDatasource {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> saveDeviceSchedulePlan({
|
||||
required DeviceSchedulePlanEntity plan,
|
||||
}) async {
|
||||
final url = '${HttpApiConsts.baseUrl}/iot/deviceTask/save';
|
||||
final body = _schedulePlanBody(plan);
|
||||
_logger.logWithLevel('[saveDeviceSchedulePlan] 请求: POST $url', shouldLog: true);
|
||||
_logger.logWithLevel('[saveDeviceSchedulePlan] 参数: ${jsonEncode(body)}', shouldLog: true);
|
||||
try {
|
||||
final response = await dio.post(url, data: body);
|
||||
_logger.logWithLevel('[saveDeviceSchedulePlan] 响应: statusCode=${response.statusCode}, body=${jsonEncode(response.data)}', shouldLog: true);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = response.data as Map<String, dynamic>;
|
||||
if (data['code'] == 200) {
|
||||
// 保存接口返回数量(如 data: 1),同时兼容布尔值及无 data 的成功响应。
|
||||
final saved = switch (data['data']) {
|
||||
bool value => value,
|
||||
num value => value > 0,
|
||||
_ => true,
|
||||
};
|
||||
_logger.logWithLevel(
|
||||
'[saveDeviceSchedulePlan] 结果: ${saved ? '成功' : '未保存'}',
|
||||
shouldLog: true,
|
||||
);
|
||||
return saved;
|
||||
} else {
|
||||
_logger.logWithLevel('[saveDeviceSchedulePlan] 业务失败: code=${data['code']}, msg=${data['msg']}', shouldLog: true);
|
||||
throw Exception(data['msg'] ?? '创建定时计划失败');
|
||||
}
|
||||
} else {
|
||||
throw Exception('HTTP ${response.statusCode}');
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.logWithLevel('[saveDeviceSchedulePlan] 异常: $e', shouldLog: true);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// 业务实体 → 后端报文:字段名 / DAY・WEEK・MONTH 枚举字面量 /
|
||||
/// days・dates 条件结构 / 时间格式,全部封在数据层,不外泄到 domain。
|
||||
static Map<String, dynamic> _schedulePlanBody(DeviceSchedulePlanEntity p) {
|
||||
// 下标 = weekday.value - 1(周一~周日)
|
||||
const List<String> weekdayWire = <String>[
|
||||
'MONDAY',
|
||||
'TUESDAY',
|
||||
'WEDNESDAY',
|
||||
'THURSDAY',
|
||||
'FRIDAY',
|
||||
'SATURDAY',
|
||||
'SUNDAY',
|
||||
];
|
||||
String pad(int value) => value.toString().padLeft(2, '0');
|
||||
String dateText(DateTime d) =>
|
||||
'${d.year}-${pad(d.month)}-${pad(d.day)}';
|
||||
|
||||
return <String, dynamic>{
|
||||
'deviceId': p.deviceId,
|
||||
'orgId': p.orgId,
|
||||
'planName': p.planName.trim(),
|
||||
'routeId': p.routeId,
|
||||
'siteId': p.siteId,
|
||||
'deviceTaskPlanRules': <String, dynamic>{
|
||||
'type': switch (p.type) {
|
||||
WorkScheduleType.day => 'DAY',
|
||||
WorkScheduleType.week => 'WEEK',
|
||||
WorkScheduleType.month => 'MONTH',
|
||||
},
|
||||
if (p.type == WorkScheduleType.week)
|
||||
'days': <String>[
|
||||
for (final Weekday w in p.days) weekdayWire[w.value - 1],
|
||||
],
|
||||
if (p.type == WorkScheduleType.month) 'dates': p.dates,
|
||||
'dayTime': '${pad(p.dayHour)}:${pad(p.dayMinute)}:00',
|
||||
},
|
||||
'startTime': '${dateText(p.startDate)} 00:00:00',
|
||||
'finishTime': '${dateText(p.endDate)} 23:59:59',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,8 +16,11 @@ class DeviceTaskModel extends DeviceTaskEntity {
|
||||
return DeviceTaskModel(
|
||||
id: json['id'] as int,
|
||||
deviceId: json['deviceId'] as String? ?? '',
|
||||
taskStatus: json['taskStaus'] as String? ?? '',
|
||||
taskStatusTranslate: json['taskStausTranslate'] as String? ?? '',
|
||||
taskStatus: (json['taskStaus'] ?? json['taskStatus']) as String? ?? '',
|
||||
taskStatusTranslate:
|
||||
(json['taskStausTranslate'] ?? json['taskStatusTranslate'])
|
||||
as String? ??
|
||||
'',
|
||||
routeId: json['routeId'] as int?,
|
||||
siteId: json['siteId'] as int?,
|
||||
orgId: json['orgId'] as int?,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import '../../../../core/error/failure.dart';
|
||||
import '../../domain/entities/device_schedule_plan_entity.dart';
|
||||
import '../../domain/entities/device_task_entity.dart';
|
||||
import '../../domain/repositories/device_task_repository.dart';
|
||||
import '../datasources/device_task_datasource.dart';
|
||||
@@ -92,4 +93,16 @@ class DeviceTaskRepositoryImpl implements DeviceTaskRepository {
|
||||
return Left(Failure(e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Either<Failure, bool>> saveDeviceSchedulePlan({
|
||||
required DeviceSchedulePlanEntity plan,
|
||||
}) async {
|
||||
try {
|
||||
final result = await datasource.saveDeviceSchedulePlan(plan: plan);
|
||||
return Right(result);
|
||||
} catch (e) {
|
||||
return Left(Failure(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
/// 定时作业计划(设备定时任务)业务实体。
|
||||
///
|
||||
/// 只表达业务概念(设备/路线/周期规则/生效区间),不含任何后端字段名与
|
||||
/// 报文格式;entity → JSON 的组装封在 data 层(DeviceTaskDatasource)。
|
||||
/// 对应接口:POST /iot/deviceTask/save(按天/周/月循环策略)。
|
||||
library;
|
||||
|
||||
/// 循环策略:每天 / 每周指定星期 / 每月指定几号
|
||||
enum WorkScheduleType { day, week, month }
|
||||
|
||||
/// 星期几(domain 自定义,不绑定 intl;value 与 DateTime.weekday 同口径 1-7)
|
||||
enum Weekday { monday, tuesday, wednesday, thursday, friday, saturday, sunday }
|
||||
|
||||
extension WeekdayX on Weekday {
|
||||
/// 1-7,周一=1,与 [DateTime.weekday] 对齐
|
||||
int get value => index + 1;
|
||||
}
|
||||
|
||||
/// 星期选择项(周一~周日),提交时由数据层映射为后端枚举字面量
|
||||
const List<Weekday> kWorkScheduleWeekdays = <Weekday>[
|
||||
Weekday.monday,
|
||||
Weekday.tuesday,
|
||||
Weekday.wednesday,
|
||||
Weekday.thursday,
|
||||
Weekday.friday,
|
||||
Weekday.saturday,
|
||||
Weekday.sunday,
|
||||
];
|
||||
|
||||
/// 一条待创建的定时作业计划。
|
||||
///
|
||||
/// 时间拆成「日期 + 时分」:
|
||||
/// - [startDate] / [endDate]:方案生效区间(仅日期部分有效,
|
||||
/// 提交时格式化为开始日 00:00:00 ~ 结束日 23:59:59)
|
||||
/// - [dayHour] / [dayMinute]:每日执行时刻
|
||||
class DeviceSchedulePlanEntity {
|
||||
const DeviceSchedulePlanEntity({
|
||||
required this.deviceId,
|
||||
required this.orgId,
|
||||
required this.planName,
|
||||
required this.routeId,
|
||||
required this.siteId,
|
||||
required this.type,
|
||||
this.days = const <Weekday>[],
|
||||
this.dates = const <int>[],
|
||||
this.dayHour = 8,
|
||||
this.dayMinute = 0,
|
||||
required this.startDate,
|
||||
required this.endDate,
|
||||
});
|
||||
|
||||
/// 设备 SN(如 MC700-xxx,与任务下发接口同一口径)
|
||||
final String deviceId;
|
||||
|
||||
/// 所属组织 ID(与场站同源,取自 SiteCubit 选中场站的 orgId)
|
||||
final int orgId;
|
||||
|
||||
/// 定时任务方案名称
|
||||
final String planName;
|
||||
|
||||
/// 作业路线 ID(路线库一条作业记录的主键,A 环境 = workRecord.id)
|
||||
final int routeId;
|
||||
|
||||
/// 站点 ID(当前选中场站)
|
||||
final int siteId;
|
||||
|
||||
final WorkScheduleType type;
|
||||
|
||||
/// type=week:选中星期集合(不能为空)
|
||||
final List<Weekday> days;
|
||||
|
||||
/// type=month:每月执行日期集合,取值 1-31(不能为空;小月缺该日则当月跳过)
|
||||
final List<int> dates;
|
||||
|
||||
/// 每日执行时刻
|
||||
final int dayHour;
|
||||
final int dayMinute;
|
||||
|
||||
/// 生效区间(仅日期部分有效)
|
||||
final DateTime startDate;
|
||||
final DateTime endDate;
|
||||
|
||||
/// 提交前的完整校验,返回 null = 通过。
|
||||
///
|
||||
/// 与后端入参校验规则逐条对齐,本地能拦的先拦(省一次失败往返):
|
||||
/// 1. 必填项(设备/名称/路线/场站/组织);
|
||||
/// 2. days / dates 数组非空(按周期类型);
|
||||
/// 3. 结束时间必须晚于开始时间;
|
||||
/// 4. 业务强校验:生效区间内必须存在至少一个满足周期规则、
|
||||
/// 且执行时刻落在区间内的可执行日期;否则后端拒绝保存。
|
||||
String? getValidationError() {
|
||||
if (deviceId.isEmpty) return '请选择执行设备';
|
||||
if (planName.trim().isEmpty) return '请填写方案名称';
|
||||
if (routeId <= 0) return '请选择作业路线';
|
||||
if (siteId <= 0 || orgId <= 0) return '请先在首页选择场站';
|
||||
if (type == WorkScheduleType.week && days.isEmpty) {
|
||||
return '按周执行需至少选择一个星期';
|
||||
}
|
||||
if (type == WorkScheduleType.month && dates.isEmpty) {
|
||||
return '按月执行需至少选择一个日期';
|
||||
}
|
||||
if (dates.any((d) => d < 1 || d > 31)) {
|
||||
return '每月执行日期取值范围为 1-31';
|
||||
}
|
||||
if (dayHour < 0 || dayHour > 23 || dayMinute < 0 || dayMinute > 59) {
|
||||
return '执行时刻不合法';
|
||||
}
|
||||
if (_dayOf(endDate).isBefore(_dayOf(startDate))) {
|
||||
return '结束日期必须晚于开始日期';
|
||||
}
|
||||
if (!hasExecutableTime) {
|
||||
return '生效区间内没有满足周期规则的可执行日期,任务不会触发';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// 业务强校验:逐天扫描 [startDate, endDate],
|
||||
/// 存在「命中周期规则 且 执行时刻落在 [开始日 00:00, 结束日 24:00) 内」的一天即可执行。
|
||||
/// 示例:有效期 11-19 ~ 11-20、week · days=[monday],区间内没有周一 → false。
|
||||
bool get hasExecutableTime {
|
||||
DateTime day = _dayOf(startDate);
|
||||
final DateTime last = _dayOf(endDate);
|
||||
while (!day.isAfter(last)) {
|
||||
if (_matches(day)) {
|
||||
// startTime 固定当天 00:00:00、finishTime 当天 23:59:59,
|
||||
// 任意时刻的执行点在区间内等价于「日期落在 [start, end] 闭区间」
|
||||
return true;
|
||||
}
|
||||
day = day.add(const Duration(days: 1));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool _matches(DateTime day) => switch (type) {
|
||||
WorkScheduleType.day => true,
|
||||
WorkScheduleType.week => days.contains(
|
||||
kWorkScheduleWeekdays[day.weekday - 1],
|
||||
),
|
||||
WorkScheduleType.month => dates.contains(day.day),
|
||||
};
|
||||
|
||||
static DateTime _dayOf(DateTime d) => DateTime(d.year, d.month, d.day);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import '../../../../core/error/failure.dart';
|
||||
import '../entities/device_schedule_plan_entity.dart';
|
||||
import '../entities/device_task_entity.dart';
|
||||
|
||||
abstract class DeviceTaskRepository {
|
||||
@@ -36,4 +37,9 @@ abstract class DeviceTaskRepository {
|
||||
required int orgId,
|
||||
required int siteId,
|
||||
});
|
||||
|
||||
/// 创建设备定时任务(定时作业计划,按天/周/月循环)
|
||||
Future<Either<Failure, bool>> saveDeviceSchedulePlan({
|
||||
required DeviceSchedulePlanEntity plan,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -57,6 +57,9 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
|
||||
// 🔥 当前 MQTT 机器状态监听的设备 SN(用于换设备时清空旧缓存)
|
||||
String? _currentListeningSn;
|
||||
|
||||
/// 当前实时快照的设备身份,供入口模式确认使用(只读)。
|
||||
String? get listeningDeviceSn => _currentListeningSn;
|
||||
|
||||
// 🔥 MQTT机器状态收帧计数(用于链路日志)
|
||||
int _mqttVehicleFrameCount = 0;
|
||||
int _mqttLocationFrameCount = 0;
|
||||
@@ -322,8 +325,12 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
|
||||
rightTargetSpeed: host.rightTargetRpm,
|
||||
leftMeasureSpeed: host.leftMeasuredRpm,
|
||||
rightMeasureSpeed: host.rightMeasuredRpm,
|
||||
controlMode:
|
||||
host.controlMode.isNotEmpty ? host.controlMode : base.controlMode,
|
||||
// 严格按后端本帧给的值写:没带 control_mode 就置空(显示「未知」)。
|
||||
// 以前写的是 host.controlMode.isNotEmpty ? ... : base.controlMode,
|
||||
// 导致“后端已经不发控制模式了”界面仍永远停在第一次收到的值上。
|
||||
// 代价:若 host 帧偶发漏带该字段,此栏会在真值与「未知」间跳动;
|
||||
// 现场若出现闪烁,说明 host 帧字段不稳定,应从后端侧解决而非在此兜底。
|
||||
controlMode: host.controlMode,
|
||||
workingArea: host.totalWorkArea.toString(),
|
||||
// 🔥 供全功能模式(pv_control)展示:累计作业里程 + host 已推数据标记
|
||||
totalWorkDistance: host.totalWorkDistance,
|
||||
@@ -486,7 +493,11 @@ class DeviceStatusBloc extends Bloc<DeviceStatusEvent, DeviceStatusState> {
|
||||
if (_cachedStatus != null && !isClosed) {
|
||||
final gps = _cachedGps ??
|
||||
GPSEntity(_cachedStatus!.latitude, _cachedStatus!.longitude);
|
||||
debugPrint('📤 [节流发射] 电压=${_cachedStatus!.voltage}V 电量=${_cachedStatus!.battery}% 经纬度=(${gps.latitude}, ${gps.longitude}) yaw=${_cachedStatus!.yaw} 控制模式=${_cachedStatus!.controlMode} | ${DateTime.now().toString().substring(11, 19)}');
|
||||
// 控制模式为空串 = 后端从未给过,日志里显式标出来,免得和 0 混看
|
||||
final controlModeLog = _cachedStatus!.controlMode.isEmpty
|
||||
? '--(未收到)'
|
||||
: _cachedStatus!.controlMode;
|
||||
debugPrint('📤 [节流发射] 电压=${_cachedStatus!.voltage}V 电量=${_cachedStatus!.battery}% 经纬度=(${gps.latitude}, ${gps.longitude}) yaw=${_cachedStatus!.yaw} 控制模式=$controlModeLog | ${DateTime.now().toString().substring(11, 19)}');
|
||||
emit(DeviceStatusUpdated(_cachedStatus!, gps));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user