This commit is contained in:
2026-11-10 16:40:15 +08:00
parent 99c7a3ab87
commit c3a2aee8fb
36 changed files with 932 additions and 262 deletions

View File

@@ -15,7 +15,9 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.maibu.core.business.DevicePlan;
import com.maibu.core.business.RegionConsecutiveTaskRecord;
import com.maibu.core.business.dto.ConsecutiveTaskDTO;
import com.maibu.core.business.dto.ConsecutiveTaskQueryDTO;
import com.maibu.core.business.dto.DeviceTaskCommandDTO;
import com.maibu.core.controller.BaseController;
import com.maibu.core.domain.AjaxResult;
@@ -106,7 +108,7 @@ public class DeviceTaskController extends BaseController {
}
@PostMapping("/createDeviceTask")
public AjaxResult createDeviceTask(@RequestBody DeviceTaskCommandDTO dto) {
public AjaxResult createDeviceTask(@RequestBody DeviceTaskCommandDTO dto) throws Exception {
String deviceId = dto.getDeviceId();
Long siteId = dto.getSiteId();
Long orgId = dto.getOrgId();
@@ -135,7 +137,7 @@ public class DeviceTaskController extends BaseController {
}
@PostMapping("/createRegionDefaultTask")
public AjaxResult createRegionDeviceTask(@RequestBody DeviceTaskCommandDTO dto) {
public AjaxResult createRegionDeviceTask(@RequestBody DeviceTaskCommandDTO dto) throws Exception {
String deviceId = dto.getDeviceId();
Long siteId = dto.getSiteId();
Long orgId = dto.getOrgId();
@@ -177,7 +179,7 @@ public class DeviceTaskController extends BaseController {
}
@PostMapping("/pauseTask")
public AjaxResult pauseTask(@RequestBody DeviceTaskCommandDTO dto) {
public AjaxResult pauseTask(@RequestBody DeviceTaskCommandDTO dto) throws MqttException {
String deviceId = dto.getDeviceId();
if (StringUtils.isEmpty(deviceId) && dto.getTaskId() == null) {
return AjaxResult.error("deviceId或taskId为空!");
@@ -186,7 +188,7 @@ public class DeviceTaskController extends BaseController {
}
@PostMapping("/recoveryTask")
public AjaxResult recoveryTask(@RequestBody DeviceTaskCommandDTO dto) throws InterruptedException {
public AjaxResult recoveryTask(@RequestBody DeviceTaskCommandDTO dto) throws InterruptedException, MqttException {
String deviceId = dto.getDeviceId();
if (StringUtils.isEmpty(deviceId) && dto.getTaskId() == null) {
return AjaxResult.error("deviceId或taskId为空!");
@@ -195,7 +197,7 @@ public class DeviceTaskController extends BaseController {
}
@PostMapping("/backToRestPoint")
public AjaxResult backToRestPoint(@RequestBody DeviceTaskCommandDTO dto) {
public AjaxResult backToRestPoint(@RequestBody DeviceTaskCommandDTO dto) throws Exception {
String deviceId = dto.getDeviceId();
Long siteId = dto.getSiteId();
Long orgId = dto.getOrgId();
@@ -223,8 +225,8 @@ public class DeviceTaskController extends BaseController {
return AjaxResult.success(deviceTaskService.backToRestPoint(dto, getLoginUser().getUsername()));
}
@PostMapping("/createConsecutiveTasks")
public AjaxResult createConsecutiveTasks(@RequestBody ConsecutiveTaskDTO dto) {
@PostMapping("/createConsecutiveTask")
public AjaxResult createConsecutiveTasks(@RequestBody ConsecutiveTaskDTO dto) throws Exception {
String deviceId = dto.getDeviceId();
Long siteId = dto.getSiteId();
Long orgId = dto.getOrgId();
@@ -278,4 +280,11 @@ public class DeviceTaskController extends BaseController {
return AjaxResult.success();
}
@PostMapping("/getConsecutiveTask")
public TableDataInfo getConsecutiveTask(@RequestBody ConsecutiveTaskQueryDTO dto) {
startPage();
List<RegionConsecutiveTaskRecord> list = deviceTaskService.getRegionConsecutiveTaskRecords(dto);
return getDataTable(list);
}
}

View File

@@ -14,7 +14,7 @@ public class MowerCommamdHandler implements MowerCommandInter {
private DeviceTaskService dService;
@Override
public Long createDeviceTask(DeviceTaskCommandDTO dto) {
public Long createDeviceTask(DeviceTaskCommandDTO dto) throws Exception {
return dService.createDeviceTask(dto, "system");
}

View File

@@ -36,6 +36,7 @@ import com.maibu.core.business.WorkRecord;
import com.maibu.core.domain.entity.SysParam;
import com.maibu.core.domain.entity.SysSite;
import com.maibu.core.domain.map.SiteMapInfo;
import com.maibu.core.domain.rule.IotAutoRule;
import com.maibu.core.enums.DeviceTaskStaus;
import com.maibu.core.enums.RouteType;
import com.maibu.influxdb.util.InfluxDBUtil;
@@ -45,6 +46,7 @@ import com.maibu.mapper.DevicePlanTaskMapper;
import com.maibu.mapper.DeviceProductMapper;
import com.maibu.mapper.DeviceRunParamMapper;
import com.maibu.mapper.ErrorIdentificationStandardMapper;
import com.maibu.mapper.IotAutoRuleMapper;
import com.maibu.mapper.IotDeviceCommonMapper;
import com.maibu.mapper.OrderModelMapper;
import com.maibu.mapper.SiteMapInfoMapper;
@@ -138,6 +140,9 @@ public class InitThread implements ApplicationRunner {
@Autowired
private WorkRecordMapper workRecordMapper;
@Autowired
private IotAutoRuleMapper iotAutoRuleMapper;
@Value("${influxdb.url}")
private String influxDBUrl;
@@ -250,6 +255,19 @@ public class InitThread implements ApplicationRunner {
});
}
// 任务触发规则
List<IotAutoRule> iotAutoRuleList = iotAutoRuleMapper.selectList();
if (!CollectionUtils.isEmpty(iotAutoRuleList)) {
iotAutoRuleList.forEach(x -> {
Long orgId = x.getOrgId();
Long siteId = x.getSiteId();
SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId);
if (siteMemory != null) {
siteMemory.saveIotAutoRule(x.getRuleType(), x);
}
});
}
// 场站的 地图配置信息
List<SiteMapInfo> siteMapInfoList = siteMapInfoMapper.selectList();
if (!CollectionUtils.isEmpty(siteMapInfoList)) {
@@ -452,7 +470,7 @@ public class InitThread implements ApplicationRunner {
workRecord -> workRecord.getRouteType().toString()));
if (!CollectionUtils.isEmpty(records)) {
records.forEach(x -> {
if (!map.containsKey(x.getRouteType())) {
if (!map.containsKey(x.getRouteType().toString())) {
x.setUserId(1L);
saveList.add(x);
}

View File

@@ -117,7 +117,7 @@ public class CommandForwardHandler extends SimpleChannelInboundHandler<String> {
data.setCutter(pEntity.getMowerSpeedFlag());
data.setIgnition(pEntity.getIgnitionFlag());
data.setEmergency_stop(pEntity.getEmergencyStopFlag());
data.setValid_for_ms(500);
data.setValid_for_ms(200); //间隔 可调整
deviceRemoteControlDTO.setData(data);
deviceRemoteControlDTO
.setCommand_id(Constant.remote_control_cmd_prefix + System.currentTimeMillis());

View File

@@ -1,9 +1,26 @@
package com.maibu.service;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.maibu.core.business.DevicePlan;
import com.maibu.core.business.DevicePlanTask;
import com.maibu.core.business.DeviceTaskPlanRule;
import com.maibu.core.business.WorkRecord;
import com.maibu.core.business.device.NettyDevice;
import com.maibu.core.enums.DeviceTaskPlanRepeatType;
import com.maibu.core.enums.DeviceTaskStaus;
@@ -13,21 +30,8 @@ import com.maibu.mapper.WorkRecordMapper;
import com.maibu.memory.DeviceSessionManager;
import com.maibu.memory.GlobalMemory;
import com.maibu.memory.SiteMemory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.PreDestroy;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
@@ -47,6 +51,7 @@ public class DevicePlanTaskMonitorService {
@Autowired
private ScheduledExecutorService executor;
/**
* 计划迟的任务生成机器执行任务
*/
@@ -71,7 +76,8 @@ public class DevicePlanTaskMonitorService {
}
private void createPlanTask(DevicePlan devicePlan) {
if (devicePlan.isDayTriggerFlag()) return; //当天应该创建的全部创建完
if (devicePlan.isDayTriggerFlag())
return; // 当天应该创建的全部创建完
DeviceTaskPlanRule rules = devicePlan.getDeviceTaskPlanRules();
if (rules != null) {
DeviceTaskPlanRepeatType type = rules.getType();
@@ -85,9 +91,9 @@ public class DevicePlanTaskMonitorService {
case MONTH:
monthPlan(devicePlan);
break;
// case ONCE:
// oncePlan(devicePlan);
// break;
// case ONCE:
// oncePlan(devicePlan);
// break;
}
}
}
@@ -102,18 +108,25 @@ public class DevicePlanTaskMonitorService {
devicePlanTask.setDeviceId(devicePlan.getDeviceId());
devicePlanTask.setTaskStaus(DeviceTaskStaus.NEW);
devicePlanTask.setRouteId(devicePlan.getRouteId());
// 设置当前的路径规划信息
WorkRecord workRecord = workRecordMapper.selectById(devicePlan.getRouteId());
if (workRecord != null) {
devicePlanTask.setRouteType(workRecord.getRouteType());
devicePlanTask.setWorkName(workRecord.getWorkName());
}
devicePlanTask.setCreateTime(LocalDateTime.now());
devicePlanTask.setTaskType("");//待拓展任务类型
devicePlanTask.setTaskType("");// 待拓展任务类型
devicePlanTask.setOrgId(devicePlan.getOrgId());
devicePlanTask.setSiteId(devicePlan.getSiteId());
devicePlanTaskMapper.insert(devicePlanTask);
SiteMemory siteMemory = GlobalMemory.getSiteMemory(devicePlan.getOrgId(), devicePlan.getSiteId());
siteMemory.addDevicePlanPrepare(devicePlanTask);
//啥时候重置?每日0点?
// 啥时候重置?每日0点?
devicePlan.setDayTriggerFlag(true);
devicePlan.setUpdateTime(LocalDateTime.now());
devicePlan.setTaskStaus(DeviceTaskStaus.EXECUTING);
//todo 怎么判断任务全部排完了?排完了就删除
// todo 怎么判断任务全部排完了?排完了就删除
LocalDate today = LocalDate.now(); // 获取当前日期(系统时区)
LocalDate endTime = rules.getEndTime();
if (endTime != null && endTime.isEqual(today)) {
@@ -139,18 +152,24 @@ public class DevicePlanTaskMonitorService {
devicePlanTask.setDeviceId(devicePlan.getDeviceId());
devicePlanTask.setTaskStaus(DeviceTaskStaus.NEW);
devicePlanTask.setRouteId(devicePlan.getRouteId());
// 设置当前的路径规划信息
WorkRecord workRecord = workRecordMapper.selectById(devicePlan.getRouteId());
if (workRecord != null) {
devicePlanTask.setRouteType(workRecord.getRouteType());
devicePlanTask.setWorkName(workRecord.getWorkName());
}
devicePlanTask.setCreateTime(LocalDateTime.now());
devicePlanTask.setOrgId(devicePlan.getOrgId());
devicePlanTask.setSiteId(devicePlan.getSiteId());
devicePlanTask.setTaskType("");//待拓展任务类型
devicePlanTask.setTaskType("");// 待拓展任务类型
devicePlanTaskMapper.insert(devicePlanTask);
SiteMemory siteMemory = GlobalMemory.getSiteMemory(devicePlan.getOrgId(), devicePlan.getSiteId());
siteMemory.addDevicePlanPrepare(devicePlanTask);
//啥时候重置?每日0点?
// 啥时候重置?每日0点?
devicePlan.setDayTriggerFlag(true);
devicePlan.setUpdateTime(LocalDateTime.now());
devicePlan.setTaskStaus(DeviceTaskStaus.EXECUTING);
//todo 怎么判断任务全部排完了?排完了就删除
// todo 怎么判断任务全部排完了?排完了就删除
LocalDate endTime = rules.getEndTime();
if (endTime != null && endTime.isEqual(today)) {
devicePlan.setFinishTime(LocalDateTime.now());
@@ -168,24 +187,31 @@ public class DevicePlanTaskMonitorService {
LocalTime nowTime = LocalTime.now();
int dayOfMonth = today.getDayOfMonth();
LocalTime dayTime = LocalTime.parse(rules.getDayTime());
if (!CollectionUtils.isEmpty(dayOfMonthList) && dayOfMonthList.contains(dayOfMonth) && nowTime.isAfter(dayTime)) {
if (!CollectionUtils.isEmpty(dayOfMonthList) && dayOfMonthList.contains(dayOfMonth)
&& nowTime.isAfter(dayTime)) {
DevicePlanTask devicePlanTask = new DevicePlanTask();
devicePlanTask.setPlanId(devicePlan.getId());
devicePlanTask.setDeviceId(devicePlan.getDeviceId());
devicePlanTask.setTaskStaus(DeviceTaskStaus.NEW);
devicePlanTask.setRouteId(devicePlan.getRouteId());
// 设置当前的路径规划信息
WorkRecord workRecord = workRecordMapper.selectById(devicePlan.getRouteId());
if (workRecord != null) {
devicePlanTask.setRouteType(workRecord.getRouteType());
devicePlanTask.setWorkName(workRecord.getWorkName());
}
devicePlanTask.setCreateTime(LocalDateTime.now());
devicePlanTask.setTaskType("");//待拓展任务类型
devicePlanTask.setTaskType("");// 待拓展任务类型
devicePlanTask.setOrgId(devicePlan.getOrgId());
devicePlanTask.setSiteId(devicePlan.getSiteId());
devicePlanTaskMapper.insert(devicePlanTask);
SiteMemory siteMemory = GlobalMemory.getSiteMemory(devicePlan.getOrgId(), devicePlan.getSiteId());
siteMemory.addDevicePlanPrepare(devicePlanTask);
//啥时候重置?每日0点?
// 啥时候重置?每日0点?
devicePlan.setDayTriggerFlag(true);
devicePlan.setUpdateTime(LocalDateTime.now());
devicePlan.setTaskStaus(DeviceTaskStaus.EXECUTING);
//todo 怎么判断任务全部排完了?排完了就删除
// todo 怎么判断任务全部排完了?排完了就删除
LocalDate endTime = rules.getEndTime();
if (endTime != null && endTime.isEqual(today)) {
devicePlan.setFinishTime(LocalDateTime.now());
@@ -197,13 +223,12 @@ public class DevicePlanTaskMonitorService {
}
public void oncePlan(DevicePlan devicePlan) {
// DeviceTaskPlanRule rules = devicePlan.getDeviceTaskPlanRules();
// DeviceTaskPlanRule rules = devicePlan.getDeviceTaskPlanRules();
}
public void doLoop() throws InterruptedException {
//prepare 进执行execute的逻辑
// prepare 进执行execute的逻辑
executor.scheduleWithFixedDelay(() -> {
try {
List<SiteMemory> list = GlobalMemory.getAllSiteMemory();
@@ -213,17 +238,16 @@ public class DevicePlanTaskMonitorService {
if (!CollectionUtils.isEmpty(planMap.keySet())) {
planMap.keySet().forEach(key -> {
NettyDevice device = deviceSessionManager.getDevice(key);
//判断是否能进execute
if (device != null && device.getTask() == null && device.getOnlineStatus() != null && device.getOnlineStatus() == 1) {
// 判断是否能进execute
if (device != null && device.getTask() == null && device.getOnlineStatus() != null
&& device.getOnlineStatus() == 1) {
List<DevicePlanTask> tasks = planMap.get(key);
if (!CollectionUtils.isEmpty(tasks)) {
tasks.removeIf(Objects::isNull);
tasks.sort(
tasks.sort(
Comparator.comparing(
DevicePlanTask::getStartTime,
Comparator.nullsLast(Comparator.naturalOrder())
)
);
Comparator.nullsLast(Comparator.naturalOrder())));
if (!CollectionUtils.isEmpty(tasks)) {
DevicePlanTask devicePlanTask = tasks.get(0);
String deviceId = devicePlanTask.getDeviceId();
@@ -248,7 +272,7 @@ public class DevicePlanTaskMonitorService {
}
public void doExecute() {
//prepare 进执行execute的逻辑
// prepare 进执行execute的逻辑
executor.scheduleWithFixedDelay(() -> {
try {
List<SiteMemory> list = GlobalMemory.getAllSiteMemory();

View File

@@ -6,7 +6,10 @@ import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
@@ -27,6 +30,7 @@ import com.maibu.core.business.RegionConsecutiveTaskRecord;
import com.maibu.core.business.WorkRecord;
import com.maibu.core.business.device.NettyDevice;
import com.maibu.core.business.dto.ConsecutiveTaskDTO;
import com.maibu.core.business.dto.ConsecutiveTaskQueryDTO;
import com.maibu.core.business.dto.DeviceTaskCommandDTO;
import com.maibu.core.domain.entity.SysRegion;
import com.maibu.core.domain.entity.SysSite;
@@ -35,6 +39,7 @@ import com.maibu.core.domain.map.SiteMapInfo;
import com.maibu.core.domain.model.LoginUser;
import com.maibu.core.enums.DeviceTaskStaus;
import com.maibu.core.enums.RouteType;
import com.maibu.core.host.VehicleMessage;
import com.maibu.dto.DevicePlanStatisticsDTO;
import com.maibu.dto.DevicePlanTaskStatisticsDTO;
import com.maibu.dto.DeviceTaskQueryDTO;
@@ -50,6 +55,7 @@ import com.maibu.mapper.WorkRecordMapper;
import com.maibu.memory.DeviceSessionManager;
import com.maibu.memory.GlobalMemory;
import com.maibu.memory.SiteMemory;
import com.maibu.service.impl.HostComputerService;
import com.maibu.utils.MessageUtils;
import lombok.extern.slf4j.Slf4j;
@@ -82,6 +88,9 @@ public class DeviceTaskService {
@Autowired
private RegionConsecutiveTaskRecordMapper regionConsecutiveTaskRecordMapper;
@Autowired
private HostComputerService hostComputerService;
private static final ObjectMapper objectMapper = new ObjectMapper();
public int insertOrUpdate(DevicePlan devicePlan, LoginUser loginUser) {
@@ -422,6 +431,47 @@ public class DeviceTaskService {
&& !x.getCreateTime().isAfter(dto.getEndTime()))
.collect(Collectors.toList());
}
// 批量查询路线名称
Set<Long> routeIds = list.stream()
.map(DevicePlanTask::getRouteId)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
if (!routeIds.isEmpty()) {
List<WorkRecord> workRecords = workRecordMapper.selectList(
new LambdaQueryWrapper<WorkRecord>()
.select(WorkRecord::getId, WorkRecord::getWorkName)
.in(WorkRecord::getId, routeIds));
Map<Long, String> workNameMap = workRecords.stream()
.collect(Collectors.toMap(
WorkRecord::getId,
WorkRecord::getWorkName,
(a, b) -> a));
list.forEach(task -> task.setWorkName(workNameMap.get(task.getRouteId())));
}
// 查别名
Set<String> deviceIds = list.stream()
.map(DevicePlanTask::getDeviceId)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
if (!deviceIds.isEmpty()) {
List<Device> devices = deviceMapper.selectList(
new LambdaQueryWrapper<Device>()
.select(Device::getSerialNumber, Device::getDeviceAlias)
.in(Device::getSerialNumber, deviceIds));
Map<String, String> deviceAliasMap = devices.stream()
.collect(Collectors.toMap(
Device::getSerialNumber,
Device::getDeviceAlias,
(a, b) -> a));
list.forEach(task -> task.setDeviceAlias(deviceAliasMap.get(task.getDeviceId())));
}
return transferDeviceTaskData(list);
}
@@ -476,7 +526,10 @@ public class DeviceTaskService {
return list;
}
public Long createDeviceTask(DeviceTaskCommandDTO dto, String username) {
public Long createDeviceTask(DeviceTaskCommandDTO dto, String username) throws Exception {
SiteMemory siteMemory = GlobalMemory.getSiteMemory(dto.getOrgId(), dto.getSiteId());
sendAutoTaskMode(siteMemory, dto.getDeviceId()); // 检验权限
DevicePlanTask task = new DevicePlanTask();
task.setOrgId(dto.getOrgId());
task.setSiteId(dto.getSiteId());
@@ -490,6 +543,7 @@ public class DeviceTaskService {
WorkRecord workRecord = workRecordMapper.selectById(dto.getRouteId());
if (workRecord != null) {
task.setRouteType(workRecord.getRouteType());
task.setWorkName(workRecord.getWorkName());
}
devicePlanTaskMapper.saveOrUpdate(task);
@@ -499,12 +553,12 @@ public class DeviceTaskService {
dto.setOrgId(site.getOrgId());
}
}
SiteMemory siteMemory = GlobalMemory.getSiteMemory(task.getOrgId(), task.getSiteId());
siteMemory.addDevicePlanPrepare(task);
return task.getId();
}
public Long createRegionDeviceTask(DeviceTaskCommandDTO dto, String username) {
public Long createRegionDeviceTask(DeviceTaskCommandDTO dto, String username) throws Exception {
LambdaQueryWrapper<SysRegion> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(SysRegion::getId, dto.getRegionId());
SysRegion region = sysRegionMapper.selectOne(queryWrapper);
@@ -517,6 +571,8 @@ public class DeviceTaskService {
routeId = region.getDefaultRoute();
}
SiteMemory siteMemory = GlobalMemory.getSiteMemory(dto.getOrgId(), dto.getSiteId());
sendAutoTaskMode(siteMemory, dto.getDeviceId()); // 检验权限
if (dto.getOrgId() == null) {
SysSite site = sysSiteMapper.selectById(dto.getSiteId());
if (site != null) {
@@ -536,11 +592,11 @@ public class DeviceTaskService {
WorkRecord workRecord = workRecordMapper.selectById(region.getDefaultRoute());
if (workRecord != null) {
task.setRouteType(workRecord.getRouteType());
task.setWorkName(workRecord.getWorkName());
}
devicePlanTaskMapper.saveOrUpdate(task);
SiteMemory siteMemory = GlobalMemory.getSiteMemory(task.getOrgId(), task.getSiteId());
siteMemory.addDevicePlanPrepare(task);
return task.getId();
}
@@ -558,6 +614,7 @@ public class DeviceTaskService {
NettyDevice device = deviceSessionManager.getDevice(deviceId);
if (device != null && device.getTask() != null) {
if (dto.isForceCancel()) {
device.cancelingTask();
return device.canceledTask() != null;
} else {
return device.cancelingTask();
@@ -579,7 +636,7 @@ public class DeviceTaskService {
}
// todo 完善
public boolean pauseTask(DeviceTaskCommandDTO dto, String username) {
public boolean pauseTask(DeviceTaskCommandDTO dto, String username) throws MqttException {
if (!StringUtils.isEmpty(dto.getDeviceId())) {
NettyDevice device = deviceSessionManager.getDevice(dto.getDeviceId());
if (device != null) {
@@ -599,7 +656,7 @@ public class DeviceTaskService {
}
// todo 完善
public boolean recoveryTask(DeviceTaskCommandDTO dto, String username) throws InterruptedException {
public boolean recoveryTask(DeviceTaskCommandDTO dto, String username) throws InterruptedException, MqttException {
if (!StringUtils.isEmpty(dto.getDeviceId())) {
NettyDevice device = deviceSessionManager.getDevice(dto.getDeviceId());
if (device != null) {
@@ -618,7 +675,9 @@ public class DeviceTaskService {
return false;
}
public Long backToRestPoint(DeviceTaskCommandDTO dto, String username) {
public Long backToRestPoint(DeviceTaskCommandDTO dto, String username) throws Exception {
// 先判断 mode 是不是 0 是0 切换成2 成功 失败返回 不是 0 判断是不是2 ,是2 执行 不是2 切换 等结果
if (dto.getOrgId() == null) {
SysSite site = sysSiteMapper.selectById(dto.getSiteId());
@@ -628,12 +687,13 @@ public class DeviceTaskService {
}
SiteMemory siteMemory = GlobalMemory.getSiteMemory(dto.getOrgId(), dto.getSiteId());
SiteMapInfo siteMapInfo;
if (siteMemory == null) {
throw new ServiceException(MessageUtils.message("任务下发出错!"));
}
siteMapInfo = siteMemory.getSysSite().getSiteMapInfo();
sendAutoTaskMode(siteMemory, dto.getDeviceId()); // 检验权限
SiteMapInfo siteMapInfo = siteMemory.getSysSite().getSiteMapInfo();
if (siteMapInfo == null || CollectionUtils.isEmpty(siteMapInfo.getRestPoints())) {
throw new ServiceException(MessageUtils.message("当前机器未配置返回点!"));
@@ -659,6 +719,7 @@ public class DeviceTaskService {
task.setRouteId(workRecord.getId());
task.setRouteType(workRecord.getRouteType());
task.setWorkName(workRecord.getWorkName());
task.setBackTaskPoint(switchRestPoint);
task.setOrgId(dto.getOrgId());
@@ -674,7 +735,7 @@ public class DeviceTaskService {
return task.getId();
}
public void createConsecutiveTasks(ConsecutiveTaskDTO dto, String username) {
public void createConsecutiveTasks(ConsecutiveTaskDTO dto, String username) throws Exception {
if (dto.getOrgId() == null) {
SysSite site = sysSiteMapper.selectById(dto.getSiteId());
@@ -686,6 +747,7 @@ public class DeviceTaskService {
if (siteMemory == null) {
throw new ServiceException(MessageUtils.message("任务下发出错!"));
}
sendAutoTaskMode(siteMemory, dto.getDeviceId()); // 检验权限
siteMemory.saveRegionConsecutiveTask(dto.getDeviceId(), dto, username);
}
@@ -720,4 +782,38 @@ public class DeviceTaskService {
}
}
public List<RegionConsecutiveTaskRecord> getRegionConsecutiveTaskRecords(ConsecutiveTaskQueryDTO dto) {
LambdaQueryWrapper<RegionConsecutiveTaskRecord> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(RegionConsecutiveTaskRecord::getSiteId, dto.getSiteId());
if (!StringUtils.isEmpty(dto.getDeviceId())) {
queryWrapper.eq(RegionConsecutiveTaskRecord::getDeviceId, dto.getDeviceId());
}
if (dto.getTaskStatus() != null) {
queryWrapper.eq(RegionConsecutiveTaskRecord::getTaskStatus, dto.getTaskStatus());
}
if (dto.getStartTime() != null) {
queryWrapper.ge(RegionConsecutiveTaskRecord::getCreateTime, dto.getStartTime());
}
if (dto.getEndTime() != null) {
queryWrapper.le(RegionConsecutiveTaskRecord::getCreateTime, dto.getEndTime());
}
queryWrapper.orderByDesc(RegionConsecutiveTaskRecord::getCreateTime);
return regionConsecutiveTaskRecordMapper.selectList(queryWrapper);
}
public void sendAutoTaskMode(SiteMemory siteMemory, String deviceId) throws Exception {
VehicleMessage vehicleMessage = siteMemory.getVehicleMessage(deviceId);
if (vehicleMessage == null || vehicleMessage.getControl_mode() == null) {
throw new ServiceException(MessageUtils.message("当前机器未连接!"));
}
Integer controlMode = vehicleMessage.getControl_mode();
boolean isSend = controlMode != 2;
if (isSend) {
boolean result = hostComputerService.modeChage(deviceId, 2);
if (!result) {
throw new ServiceException(MessageUtils.message("当前设备切换模式失败!"));
}
}
}
}

View File

@@ -2,7 +2,6 @@ package com.maibu.service;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
@@ -14,16 +13,7 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import com.maibu.core.business.dto.DeviceMapPushDTO;
import com.maibu.core.business.dto.DeviceTaskCommandDTO;
import com.maibu.core.business.dto.WebMapMessageDTO;
import com.maibu.core.business.dto.WebOlineStatusMessageDTO;
import com.maibu.core.enums.*;
import com.maibu.utils.json.JsonUtils;
import com.maibu.utils.spring.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.s;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
@@ -44,17 +34,27 @@ import com.maibu.core.business.ErrorIdentificationStandard;
import com.maibu.core.business.RegionConsecutiveTaskRecord;
import com.maibu.core.business.alarm_center.AlarmMessage;
import com.maibu.core.business.device.NettyDevice;
import com.maibu.core.business.dto.DeviceMapPushDTO;
import com.maibu.core.business.dto.DeviceTaskCommandDTO;
import com.maibu.core.business.dto.WebMapMessageDTO;
import com.maibu.core.business.dto.WebOlineStatusMessageDTO;
import com.maibu.core.business.inter.WebsocketMesDispather;
import com.maibu.core.domain.AjaxResult;
import com.maibu.core.domain.rule.ActionConfig;
import com.maibu.core.domain.rule.IotAutoRule;
import com.maibu.core.domain.rule.TriggerConditions;
import com.maibu.core.enums.ActionType;
import com.maibu.core.enums.CompareEnum;
import com.maibu.core.enums.ConnectorStatus;
import com.maibu.core.enums.DeviceStatus;
import com.maibu.core.enums.ErrorSource;
import com.maibu.core.enums.MesType;
import com.maibu.core.enums.RespondCode;
import com.maibu.core.enums.RuleType;
import com.maibu.core.host.HeartBeatDTO;
import com.maibu.core.host.LocationMessage;
import com.maibu.core.host.VehicleMessage;
import com.maibu.core.redis.RedisCache;
import com.maibu.dto.DeviceErrorPushDTO;
import com.maibu.dto.DeviceTaskStatusMessageDTO;
import com.maibu.mapper.DeviceRunStatisticsMapper;
import com.maibu.mapper.ErrorIdentificationStandardMapper;
import com.maibu.mapper.HostLocationMapper;
@@ -64,6 +64,7 @@ import com.maibu.memory.GlobalMemory;
import com.maibu.memory.SiteMemory;
import com.maibu.mqtt.MqttTopic;
import com.maibu.utils.CompareUtils;
import com.maibu.utils.json.JsonUtils;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
@@ -162,7 +163,7 @@ public class DeviceThreadService {
});
}
} catch (Exception e) {
log.error("执行监测错误线程错误:{}", e.getMessage());
log.error("执行监测错误线程错误", e);
}
}, 0, 5, TimeUnit.SECONDS);
}
@@ -237,7 +238,7 @@ public class DeviceThreadService {
});
}
} catch (Exception e) {
log.error("推送错误信息失败 device:{}error:{}", deviceId, e.getMessage());
log.error("推送错误信息失败 device:{}error", deviceId);
}
}
@@ -287,8 +288,7 @@ public class DeviceThreadService {
Object value = field.get(history);
return (String) value;
} catch (NoSuchFieldException | IllegalAccessException e) {
System.out.println("获取字段失败: " + e.getMessage());
log.error("获取属性值失败:{}", e.getMessage());
log.error("获取属性值失败", e);
}
return null;
}
@@ -318,63 +318,44 @@ public class DeviceThreadService {
// 超时了判断离线
if (nettyDevice != null && nettyDevice.getOnlineStatus() != null
&& nettyDevice.getOnlineStatus() == 1) {
nettyDevice.status(DeviceStatus.offline.getType());
// todo 推送设备离线
String key = NettyCacheKey.latestPositonKey + deviceId;
// 保存一下最新一次的数据到 数据库
LocationMessage locationMessage = redisCache.getCacheObject(key);
if (locationMessage != null) {
LambdaQueryWrapper<LocationMessage> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(LocationMessage::getDeviceId, deviceId);
LocationMessage existing = hostLocationMapper.selectOne(queryWrapper);
if (existing != null) {
locationMessage.setId(existing.getId());
} else {
locationMessage.setCreateTime(LocalDateTime.now());
}
locationMessage.setUpdateTime(LocalDateTime.now());
hostLocationMapper.saveOrUpdate(locationMessage);
}
Device device = deviceService.selectDeviceBySerialNumber(deviceId);
if (device != null) {
device.setOnlineStatus(DeviceStatus.offline.getType());
device.setUpdateTime(LocalDateTime.now());
deviceService.updateDeviceBySelf(device);
}
Long orgId = nettyDevice.getDevice().getOrgId();
Long siteId = nettyDevice.getDevice().getSiteId();
SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId);
if (siteMemory != null) {
DeviceRunStatistics deviceRunStatistics = siteMemory.getRunStatistics(deviceId);
if (deviceRunStatistics != null) {
LambdaQueryWrapper<DeviceRunStatistics> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(DeviceRunStatistics::getDeviceId, deviceId);
DeviceRunStatistics existing = deviceRunStatisticsMapper
.selectOne(queryWrapper);
if (existing != null) {
deviceRunStatistics.setId(existing.getId());
deviceRunStatistics.setDistance(
existing.getDistance() + deviceRunStatistics.getDistance());
deviceRunStatistics.setWorkArea(
existing.getWorkArea() + deviceRunStatistics.getWorkArea());
long time = System.currentTimeMillis() - nettyDevice.getLatestLoginTime();
deviceRunStatistics.setTime(existing.getTime() + time / (1000 * 60)); // 累加时长,单位为分钟
} else {
long time = System.currentTimeMillis() - nettyDevice.getLatestLoginTime();
deviceRunStatistics.setTime(time / (1000 * 60)); // 累加时长,单位为分钟
}
deviceRunStatisticsMapper.saveOrUpdate(deviceRunStatistics);
try {
// 标记离线
nettyDevice.status(DeviceStatus.offline.getType());
updatelatestLocation(deviceId);
Device device = deviceService.selectDeviceBySerialNumber(deviceId);
if (device != null) {
device.setOnlineStatus(DeviceStatus.offline.getType());
device.setUpdateTime(LocalDateTime.now());
deviceService.updateDeviceBySelf(device);
}
SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId);
if (siteMemory != null) {
updateTotalArea(nettyDevice, siteMemory, deviceId);
}
// TODO 统计总里程、总作业面积
statusChangePush(deviceId, siteId, 0);
sessionManager.removeDevice(deviceId);
} catch (Exception e) {
log.error("设备离线处理异常,deviceId={}", deviceId, e);
} finally {
// 必须执行:清理实时缓存
try {
SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId);
if (siteMemory != null) {
siteMemory.removeMapPushDTO(deviceId);
siteMemory.removeVehicleMessage(deviceId);
}
} catch (Exception e) {
log.error("设备离线缓存清理失败,deviceId={}", deviceId, e);
}
// todo 删除实时消息推送里面的数据
siteMemory.removeMapPushDTO(deviceId);
siteMemory.removeVehicleMessage(deviceId);
}
statusChangePush(deviceId, siteId, 0);
sessionManager.removeDevice(deviceId);
// TODO 统计总里程、总作业面积
}
} else {
Device device = deviceService.selectDeviceBySerialNumber(deviceId);
@@ -428,6 +409,50 @@ public class DeviceThreadService {
}, 0, 500, TimeUnit.MILLISECONDS);
}
public void updatelatestLocation(String deviceId) {
// todo 推送设备离线
String key = NettyCacheKey.latestPositonKey + deviceId;
// 保存一下最新一次的数据到 数据库
LocationMessage locationMessage = redisCache.getCacheObject(key);
if (locationMessage != null) {
LambdaQueryWrapper<LocationMessage> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(LocationMessage::getDeviceId, deviceId);
LocationMessage existing = hostLocationMapper.selectOne(queryWrapper);
if (existing != null) {
locationMessage.setId(existing.getId());
} else {
locationMessage.setCreateTime(LocalDateTime.now());
}
locationMessage.setUpdateTime(LocalDateTime.now());
hostLocationMapper.saveOrUpdate(locationMessage);
}
}
public void updateTotalArea(NettyDevice nettyDevice, SiteMemory siteMemory, String deviceId) {
DeviceRunStatistics deviceRunStatistics = siteMemory.getRunStatistics(deviceId);
if (deviceRunStatistics != null) {
LambdaQueryWrapper<DeviceRunStatistics> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(DeviceRunStatistics::getDeviceId, deviceId);
DeviceRunStatistics existing = deviceRunStatisticsMapper
.selectOne(queryWrapper);
if (existing != null) {
deviceRunStatistics.setId(existing.getId());
deviceRunStatistics.setDistance(
existing.getDistance() + deviceRunStatistics.getDistance());
deviceRunStatistics.setWorkArea(
existing.getWorkArea() + deviceRunStatistics.getWorkArea());
long time = System.currentTimeMillis()
- nettyDevice.getLatestLoginTime();
deviceRunStatistics.setTime(existing.getTime() + time / (1000 * 60)); // 累加时长,单位为分钟
} else {
long time = System.currentTimeMillis()
- nettyDevice.getLatestLoginTime();
deviceRunStatistics.setTime(time / (1000 * 60)); // 累加时长,单位为分钟
}
deviceRunStatisticsMapper.saveOrUpdate(deviceRunStatistics);
}
}
public void statusChangePush(String deviceId, Long siteId, Integer status) {
// todo 推送设备离线
WebOlineStatusMessageDTO dto = new WebOlineStatusMessageDTO();
@@ -474,7 +499,7 @@ public class DeviceThreadService {
});
}
} catch (Exception e) {
log.error("执行监测心跳线程错误:{}", e.getMessage());
log.error("执行监测心跳线程错误", e);
}
}, 0, 100, TimeUnit.MILLISECONDS);
}
@@ -488,17 +513,24 @@ public class DeviceThreadService {
List<SiteMemory> list = GlobalMemory.getAllSiteMemory();
if (!CollectionUtils.isEmpty(list)) {
list.forEach(x -> {
List<IotAutoRule> rules = x.getAllIotAutoRule();
if (!CollectionUtils.isEmpty(rules)) {
rules.forEach(rule -> {
// 根据不同的 类型区分处理方式
handleAutoRule(rule, x);
if (!CollectionUtils.isEmpty(x.iotAutoRuleMap)) {
x.iotAutoRuleMap.keySet().forEach(y -> {
List<IotAutoRule> rules = x.iotAutoRuleMap.get(y);
if (!CollectionUtils.isEmpty(rules)) {
rules.forEach(rule -> {
// 根据不同的 类型区分处理方式
if (rule != null && rule.getEnabled()) {
handleAutoRule(rule, x);
}
});
}
});
}
});
}
} catch (Exception e) {
log.error("执行规则出发线程错误:{}", e.getMessage());
log.error("执行规则出发线程错误", e);
}
}, 0, 500, TimeUnit.MILLISECONDS);
}
@@ -529,7 +561,12 @@ public class DeviceThreadService {
dto.setOrgId(siteMemory.getSysSite().getOrgId());
dto.setSiteId(siteMemory.getSysSite().getId());
deviceTaskService.backToRestPoint(dto, "system");
try {
deviceTaskService.backToRestPoint(dto, "system");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (ActionType.AUTO_TASK.equals(actionType)) {
if (siteMemory.hasTask(deviceId)) {
@@ -541,7 +578,12 @@ public class DeviceThreadService {
dto.setOrgId(siteMemory.getSysSite().getOrgId());
dto.setSiteId(siteMemory.getSysSite().getId());
dto.setRouteId(routeId);
deviceTaskService.createDeviceTask(dto, "system");
try {
deviceTaskService.createDeviceTask(dto, "system");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (ActionType.ALARM.equals(actionType)) {
@@ -568,10 +610,9 @@ public class DeviceThreadService {
Field field = vehicleClass.getDeclaredField(fieldName);
field.setAccessible(true);
Object value = field.get(history);
return (String) value;
return String.valueOf(value);
} catch (NoSuchFieldException | IllegalAccessException e) {
System.out.println("获取字段失败: " + e.getMessage());
log.error("获取属性值失败:{}", e.getMessage());
log.error("获取属性值失败:", e);
}
return null;
}
@@ -602,7 +643,13 @@ public class DeviceThreadService {
dto.setOrgId(siteMemory.getSysSite().getOrgId());
dto.setSiteId(siteMemory.getSysSite().getId());
dto.setRouteId(routeId);
Long taskId = deviceTaskService.createDeviceTask(dto, "system");
Long taskId = null;
try {
taskId = deviceTaskService.createDeviceTask(dto, "system");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (taskId != null) {
record.getTaskIds().add(taskId);
record.setCurrentIndex(currentIndex + 1);
@@ -616,7 +663,7 @@ public class DeviceThreadService {
});
}
} catch (Exception e) {
log.error("区域连续任务处理线程错误:{}", e.getMessage());
log.error("区域连续任务处理线程错误", e);
}
}, 0, 500, TimeUnit.MILLISECONDS);
}