LdTaskController.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. package com.ruoyi.web.controller.robot;
  2. import java.util.HashMap;
  3. import java.util.List;
  4. import java.util.Map;
  5. import java.util.stream.Collectors;
  6. import javax.servlet.http.HttpServletResponse;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.http.ResponseEntity;
  9. import org.springframework.scheduling.support.CronTrigger;
  10. import org.springframework.scheduling.support.SimpleTriggerContext;
  11. import org.springframework.web.bind.annotation.*;
  12. import org.springframework.web.multipart.MultipartFile;
  13. import com.alibaba.fastjson2.JSON;
  14. import com.alibaba.fastjson2.JSONArray;
  15. import com.alibaba.fastjson2.JSONObject;
  16. import com.ruoyi.common.annotation.Log;
  17. import com.ruoyi.common.core.controller.BaseController;
  18. import com.ruoyi.common.core.domain.AjaxResult;
  19. import com.ruoyi.common.core.page.TableDataInfo;
  20. import com.ruoyi.common.enums.BusinessType;
  21. import com.ruoyi.common.utils.poi.ExcelUtil;
  22. import com.ruoyi.robot.domain.LdTask;
  23. import com.ruoyi.robot.domain.LdTaskExecutionLog;
  24. import com.ruoyi.robot.service.ILdTaskExecutionLogService;
  25. import com.ruoyi.robot.service.ILdTaskService;
  26. import io.swagger.annotations.Api;
  27. import io.swagger.annotations.ApiOperation;
  28. import io.swagger.annotations.ApiParam;
  29. /**
  30. * LD导航系统任务管理接口
  31. * 提供任务的增删改查及定时任务执行功能
  32. *
  33. * 接口前缀: /v1
  34. */
  35. @Api(tags = "LD导航系统任务管理接口")
  36. @RestController
  37. @RequestMapping("/v1")
  38. public class LdTaskController extends BaseController {
  39. @Autowired
  40. private ILdTaskService ldTaskService;
  41. @Autowired
  42. private ILdTaskExecutionLogService ldTaskExecutionLogService;
  43. /**
  44. * 1.1 获取任务列表
  45. * GET /v1/path/list?map=地图名
  46. */
  47. @ApiOperation("获取任务列表")
  48. @GetMapping("/path/list")
  49. public ResponseEntity<Map<String, Object>> getTaskList(
  50. @ApiParam("地图名称") @RequestParam(value = "map", required = false) String mapName) {
  51. try {
  52. Map<String, Object> response = new HashMap<>();
  53. List<LdTask> taskList;
  54. if (mapName != null && !mapName.isEmpty()) {
  55. taskList = ldTaskService.selectLdTaskListByMapName(mapName);
  56. } else {
  57. taskList = ldTaskService.selectLdTaskList(new LdTask());
  58. }
  59. List<Map<String, Object>> paths = taskList.stream().map(task -> {
  60. Map<String, Object> path = new HashMap<>();
  61. path.put("taskId", task.getId());
  62. path.put("taskName", task.getTaskName());
  63. path.put("status", task.getStatus());
  64. path.put("cron", task.getCronExpression());
  65. path.put("executeTime", task.getExecuteTime());
  66. path.put("executeWeekdays", task.getExecuteWeekdays());
  67. path.put("repeatCount", task.getRepeatCount());
  68. // 解析目标点坐标
  69. if (task.getWaypointCoords() != null && !task.getWaypointCoords().isEmpty()) {
  70. try {
  71. path.put("coord", JSON.parse(task.getWaypointCoords()));
  72. } catch (Exception e) {
  73. path.put("coord", new java.util.ArrayList<>());
  74. }
  75. } else {
  76. path.put("coord", new java.util.ArrayList<>());
  77. }
  78. // 解析目标点类型
  79. if (task.getWaypointTypes() != null && !task.getWaypointTypes().isEmpty()) {
  80. try {
  81. path.put("plan", JSON.parse(task.getWaypointTypes()));
  82. } catch (Exception e) {
  83. path.put("plan", new java.util.ArrayList<>());
  84. }
  85. } else {
  86. path.put("plan", new java.util.ArrayList<>());
  87. }
  88. // 解析目标点动作
  89. if (task.getWaypointActions() != null && !task.getWaypointActions().isEmpty()) {
  90. try {
  91. path.put("action", JSON.parse(task.getWaypointActions()));
  92. } catch (Exception e) {
  93. path.put("action", new java.util.ArrayList<>());
  94. }
  95. } else {
  96. path.put("action", new java.util.ArrayList<>());
  97. }
  98. path.put("map", task.getMapName());
  99. path.put("lastExecuteTime", task.getLastExecuteTime());
  100. path.put("totalExecuteCount", task.getTotalExecuteCount());
  101. return path;
  102. }).collect(Collectors.toList());
  103. response.put("status", true);
  104. response.put("paths", paths);
  105. response.put("total", paths.size());
  106. return ResponseEntity.ok(response);
  107. } catch (Exception e) {
  108. logger.error("获取任务列表异常", e);
  109. return buildErrorResponse(4, "内部错误: " + e.getMessage());
  110. }
  111. }
  112. /**
  113. * 1.2 获取任务详情
  114. * GET /v1/path?map=地图名&path=任务名
  115. */
  116. @ApiOperation("获取任务详情")
  117. @GetMapping("/path")
  118. public ResponseEntity<Map<String, Object>> getTask(
  119. @ApiParam("地图名称") @RequestParam("map") String mapName,
  120. @ApiParam("任务名称") @RequestParam("path") String taskName) {
  121. try {
  122. LdTask task = ldTaskService.selectLdTaskByMapAndName(mapName, taskName);
  123. if (task == null) {
  124. return buildErrorResponse(2, "任务不存在");
  125. }
  126. Map<String, Object> response = new HashMap<>();
  127. response.put("status", true);
  128. response.put("taskId", task.getId());
  129. response.put("taskName", task.getTaskName());
  130. response.put("taskDesc", task.getTaskDesc());
  131. response.put("status", task.getStatus());
  132. response.put("cron", task.getCronExpression());
  133. response.put("executeTime", task.getExecuteTime());
  134. response.put("executeWeekdays", task.getExecuteWeekdays());
  135. response.put("repeatCount", task.getRepeatCount());
  136. response.put("coord_type", task.getCoordType());
  137. response.put("map", task.getMapName());
  138. // 解析目标点坐标
  139. if (task.getWaypointCoords() != null && !task.getWaypointCoords().isEmpty()) {
  140. response.put("coord", JSON.parse(task.getWaypointCoords()));
  141. } else {
  142. response.put("coord", new java.util.ArrayList<>());
  143. }
  144. // 解析目标点类型
  145. if (task.getWaypointTypes() != null && !task.getWaypointTypes().isEmpty()) {
  146. response.put("plan", JSON.parse(task.getWaypointTypes()));
  147. } else {
  148. response.put("plan", new java.util.ArrayList<>());
  149. }
  150. // 解析目标点动作
  151. if (task.getWaypointActions() != null && !task.getWaypointActions().isEmpty()) {
  152. response.put("action", JSON.parse(task.getWaypointActions()));
  153. } else {
  154. response.put("action", new java.util.ArrayList<>());
  155. }
  156. // 解析目标点ID
  157. if (task.getWaypointIds() != null && !task.getWaypointIds().isEmpty()) {
  158. response.put("waypointIds", JSON.parse(task.getWaypointIds()));
  159. } else {
  160. response.put("waypointIds", new java.util.ArrayList<>());
  161. }
  162. response.put("lastExecuteTime", task.getLastExecuteTime());
  163. response.put("lastExecuteStatus", task.getLastExecuteStatus());
  164. response.put("nextExecuteTime", task.getNextExecuteTime());
  165. response.put("totalExecuteCount", task.getTotalExecuteCount());
  166. return ResponseEntity.ok(response);
  167. } catch (Exception e) {
  168. logger.error("获取任务详情异常", e);
  169. return buildErrorResponse(4, "内部错误: " + e.getMessage());
  170. }
  171. }
  172. /**
  173. * 1.3 创建任务
  174. * POST /v1/path
  175. */
  176. @ApiOperation("创建任务")
  177. @PostMapping("/path")
  178. public ResponseEntity<Map<String, Object>> createTask(@RequestBody JSONObject taskData) {
  179. try {
  180. String mapName = taskData.getString("map");
  181. String pathName = taskData.getString("path");
  182. if (mapName == null || mapName.isEmpty() || pathName == null || pathName.isEmpty()) {
  183. return buildErrorResponse(1, "请求参数不合法:缺少map或path参数");
  184. }
  185. // 检查任务是否已存在
  186. LdTask existingTask = ldTaskService.selectLdTaskByMapAndName(mapName, pathName);
  187. if (existingTask != null) {
  188. return buildErrorResponse(2, "任务已存在");
  189. }
  190. // 构建任务对象
  191. LdTask task = new LdTask();
  192. task.setMapName(mapName);
  193. task.setTaskName(pathName);
  194. task.setTaskDesc(taskData.getString("desc"));
  195. task.setCronExpression(taskData.getString("cron"));
  196. task.setExecuteTime(taskData.getString("executeTime"));
  197. task.setExecuteWeekdays(taskData.getString("executeWeekdays"));
  198. task.setRepeatCount(taskData.getInteger("repeate") != null ? taskData.getInteger("repeate") : 1);
  199. task.setCoordType(taskData.getString("coord_type") != null ? taskData.getString("coord_type") : "local");
  200. task.setStatus("idle");
  201. task.setTotalExecuteCount(0);
  202. // 保存目标点坐标
  203. Object coordObj = taskData.get("coord");
  204. if (coordObj != null) {
  205. task.setWaypointCoords(JSON.toJSONString(coordObj));
  206. }
  207. // 保存目标点类型
  208. Object planObj = taskData.get("plan");
  209. if (planObj != null) {
  210. task.setWaypointTypes(JSON.toJSONString(planObj));
  211. }
  212. // 保存目标点动作
  213. Object actionObj = taskData.get("action");
  214. if (actionObj != null) {
  215. task.setWaypointActions(JSON.toJSONString(actionObj));
  216. }
  217. // 保存目标点ID
  218. Object waypointIdsObj = taskData.get("waypointIds");
  219. if (waypointIdsObj != null) {
  220. task.setWaypointIds(JSON.toJSONString(waypointIdsObj));
  221. }
  222. // 计算下次执行时间
  223. if (task.getCronExpression() != null && !task.getCronExpression().isEmpty()) {
  224. task.setNextExecuteTime(calculateNextExecuteTime(task.getCronExpression()));
  225. }
  226. int result = ldTaskService.insertLdTask(task);
  227. Map<String, Object> response = new HashMap<>();
  228. if (result > 0) {
  229. response.put("status", true);
  230. response.put("taskId", task.getId());
  231. response.put("msg", "任务创建成功");
  232. } else {
  233. response.put("status", false);
  234. response.put("msg", "任务创建失败");
  235. }
  236. return ResponseEntity.ok(response);
  237. } catch (Exception e) {
  238. logger.error("创建任务异常", e);
  239. return buildErrorResponse(4, "内部错误: " + e.getMessage());
  240. }
  241. }
  242. /**
  243. * 1.4 更新任务
  244. * PUT /v1/path
  245. */
  246. @ApiOperation("更新任务")
  247. @PutMapping("/path")
  248. public ResponseEntity<Map<String, Object>> updateTask(@RequestBody JSONObject taskData) {
  249. try {
  250. Long taskId = taskData.getLong("taskId");
  251. String mapName = taskData.getString("map");
  252. String pathName = taskData.getString("path");
  253. if (taskId == null && (mapName == null || mapName.isEmpty() || pathName == null || pathName.isEmpty())) {
  254. return buildErrorResponse(1, "请求参数不合法:缺少taskId或map/path参数");
  255. }
  256. LdTask task;
  257. if (taskId != null) {
  258. task = ldTaskService.selectLdTaskById(taskId);
  259. } else {
  260. task = ldTaskService.selectLdTaskByMapAndName(mapName, pathName);
  261. }
  262. if (task == null) {
  263. return buildErrorResponse(2, "任务不存在");
  264. }
  265. // 更新字段
  266. if (taskData.containsKey("taskName")) {
  267. String newTaskName = taskData.getString("taskName");
  268. if (!newTaskName.equals(task.getTaskName())) {
  269. // 检查新名称是否已存在
  270. LdTask existingTask = ldTaskService.selectLdTaskByMapAndName(task.getMapName(), newTaskName);
  271. if (existingTask != null) {
  272. return buildErrorResponse(2, "任务名称已存在");
  273. }
  274. task.setTaskName(newTaskName);
  275. }
  276. }
  277. task.setTaskDesc(taskData.getString("desc"));
  278. task.setCronExpression(taskData.getString("cron"));
  279. task.setExecuteTime(taskData.getString("executeTime"));
  280. task.setExecuteWeekdays(taskData.getString("executeWeekdays"));
  281. if (taskData.containsKey("repeate")) {
  282. task.setRepeatCount(taskData.getInteger("repeate"));
  283. }
  284. // 更新目标点数据
  285. Object coordObj = taskData.get("coord");
  286. if (coordObj != null) {
  287. task.setWaypointCoords(JSON.toJSONString(coordObj));
  288. }
  289. Object planObj = taskData.get("plan");
  290. if (planObj != null) {
  291. task.setWaypointTypes(JSON.toJSONString(planObj));
  292. }
  293. Object actionObj = taskData.get("action");
  294. if (actionObj != null) {
  295. task.setWaypointActions(JSON.toJSONString(actionObj));
  296. }
  297. Object waypointIdsObj = taskData.get("waypointIds");
  298. if (waypointIdsObj != null) {
  299. task.setWaypointIds(JSON.toJSONString(waypointIdsObj));
  300. }
  301. // 重新计算下次执行时间
  302. if (task.getCronExpression() != null && !task.getCronExpression().isEmpty()) {
  303. task.setNextExecuteTime(calculateNextExecuteTime(task.getCronExpression()));
  304. }
  305. int result = ldTaskService.updateLdTask(task);
  306. Map<String, Object> response = new HashMap<>();
  307. response.put("status", result > 0);
  308. response.put("msg", result > 0 ? "任务更新成功" : "任务更新失败");
  309. return ResponseEntity.ok(response);
  310. } catch (Exception e) {
  311. logger.error("更新任务异常", e);
  312. return buildErrorResponse(4, "内部错误: " + e.getMessage());
  313. }
  314. }
  315. /**
  316. * 1.5 删除任务
  317. * DELETE /v1/path
  318. */
  319. @ApiOperation("删除任务")
  320. @DeleteMapping("/path")
  321. public ResponseEntity<Map<String, Object>> deleteTask(@RequestBody JSONObject params) {
  322. try {
  323. String mapName = params.getString("map");
  324. String taskName = params.getString("path");
  325. Long taskId = params.getLong("taskId");
  326. if (taskId == null && (mapName == null || taskName == null)) {
  327. return buildErrorResponse(1, "请求参数不合法:缺少taskId或map/path参数");
  328. }
  329. LdTask task;
  330. if (taskId != null) {
  331. task = ldTaskService.selectLdTaskById(taskId);
  332. } else {
  333. task = ldTaskService.selectLdTaskByMapAndName(mapName, taskName);
  334. }
  335. if (task == null) {
  336. return buildErrorResponse(2, "任务不存在");
  337. }
  338. int result = ldTaskService.deleteLdTaskById(task.getId());
  339. Map<String, Object> response = new HashMap<>();
  340. response.put("status", result > 0);
  341. response.put("msg", result > 0 ? "任务删除成功" : "任务删除失败");
  342. return ResponseEntity.ok(response);
  343. } catch (Exception e) {
  344. logger.error("删除任务异常", e);
  345. return buildErrorResponse(4, "内部错误: " + e.getMessage());
  346. }
  347. }
  348. /**
  349. * 1.6 更新任务状态
  350. * PUT /v1/path/status
  351. */
  352. @ApiOperation("更新任务状态")
  353. @PutMapping("/path/status")
  354. public ResponseEntity<Map<String, Object>> updateTaskStatus(
  355. @ApiParam("任务ID") @RequestParam("taskId") Long taskId,
  356. @ApiParam("新状态") @RequestParam("status") String status) {
  357. try {
  358. LdTask task = ldTaskService.selectLdTaskById(taskId);
  359. if (task == null) {
  360. return buildErrorResponse(2, "任务不存在");
  361. }
  362. int result = ldTaskService.updateTaskStatus(taskId, status);
  363. Map<String, Object> response = new HashMap<>();
  364. response.put("status", result > 0);
  365. response.put("msg", result > 0 ? "状态更新成功" : "状态更新失败");
  366. return ResponseEntity.ok(response);
  367. } catch (Exception e) {
  368. logger.error("更新任务状态异常", e);
  369. return buildErrorResponse(4, "内部错误: " + e.getMessage());
  370. }
  371. }
  372. /**
  373. * 1.7 获取任务执行记录
  374. * GET /v1/path/logs
  375. */
  376. @ApiOperation("获取任务执行记录")
  377. @GetMapping("/path/logs")
  378. public ResponseEntity<Map<String, Object>> getTaskLogs(
  379. @ApiParam("任务ID") @RequestParam(value = "taskId", required = false) Long taskId,
  380. @ApiParam("设备ID") @RequestParam(value = "deviceId", required = false) String deviceId,
  381. @ApiParam("地图名称") @RequestParam(value = "map", required = false) String mapName) {
  382. try {
  383. LdTaskExecutionLog logQuery = new LdTaskExecutionLog();
  384. if (taskId != null) {
  385. logQuery.setTaskId(taskId);
  386. }
  387. if (deviceId != null) {
  388. logQuery.setDeviceId(deviceId);
  389. }
  390. if (mapName != null) {
  391. logQuery.setMapName(mapName);
  392. }
  393. List<LdTaskExecutionLog> logs = ldTaskExecutionLogService.selectLdTaskExecutionLogList(logQuery);
  394. List<Map<String, Object>> logList = logs.stream().map(log -> {
  395. Map<String, Object> logMap = new HashMap<>();
  396. logMap.put("id", log.getId());
  397. logMap.put("taskId", log.getTaskId());
  398. logMap.put("taskName", log.getTaskName());
  399. logMap.put("mapName", log.getMapName());
  400. logMap.put("executeTime", log.getExecuteTime());
  401. logMap.put("endTime", log.getEndTime());
  402. logMap.put("status", log.getStatus());
  403. logMap.put("startWaypoint", log.getStartWaypoint());
  404. logMap.put("endWaypoint", log.getEndWaypoint());
  405. logMap.put("completedWaypoints", log.getCompletedWaypoints());
  406. logMap.put("totalWaypoints", log.getTotalWaypoints());
  407. logMap.put("errorCode", log.getErrorCode());
  408. logMap.put("errorMessage", log.getErrorMessage());
  409. logMap.put("deviceId", log.getDeviceId());
  410. return logMap;
  411. }).collect(Collectors.toList());
  412. Map<String, Object> response = new HashMap<>();
  413. response.put("status", true);
  414. response.put("logs", logList);
  415. response.put("total", logList.size());
  416. return ResponseEntity.ok(response);
  417. } catch (Exception e) {
  418. logger.error("获取任务执行记录异常", e);
  419. return buildErrorResponse(4, "内部错误: " + e.getMessage());
  420. }
  421. }
  422. /**
  423. * 1.8 获取设备今日执行记录
  424. * GET /v1/path/logs/today
  425. */
  426. @ApiOperation("获取设备今日执行记录")
  427. @GetMapping("/path/logs/today")
  428. public ResponseEntity<Map<String, Object>> getTodayExecutionLogs(
  429. @ApiParam("设备ID") @RequestParam("deviceId") String deviceId) {
  430. try {
  431. List<LdTaskExecutionLog> logs = ldTaskExecutionLogService.selectTodayExecutionLogsByDeviceId(deviceId);
  432. Map<String, Object> response = new HashMap<>();
  433. response.put("status", true);
  434. response.put("logs", logs);
  435. response.put("total", logs.size());
  436. return ResponseEntity.ok(response);
  437. } catch (Exception e) {
  438. logger.error("获取今日执行记录异常", e);
  439. return buildErrorResponse(4, "内部错误: " + e.getMessage());
  440. }
  441. }
  442. /**
  443. * 辅助方法:根据Cron表达式计算下次执行时间
  444. */
  445. private java.util.Date calculateNextExecuteTime(String cronExpression) {
  446. try {
  447. CronTrigger cronTrigger = new CronTrigger(cronExpression);
  448. SimpleTriggerContext triggerContext = new SimpleTriggerContext();
  449. return cronTrigger.nextExecutionTime(triggerContext);
  450. } catch (Exception e) {
  451. logger.warn("解析Cron表达式失败: {}", cronExpression, e);
  452. return null;
  453. }
  454. }
  455. /**
  456. * 构建错误响应
  457. */
  458. private ResponseEntity<Map<String, Object>> buildErrorResponse(int code, String msg) {
  459. Map<String, Object> response = new HashMap<>();
  460. response.put("status", false);
  461. response.put("code", code);
  462. response.put("msg", msg);
  463. return ResponseEntity.ok(response);
  464. }
  465. }