diff --git a/maibu-common/src/main/java/com/maibu/core/business/Device.java b/maibu-common/src/main/java/com/maibu/core/business/Device.java index 188bf84..8e5e495 100644 --- a/maibu-common/src/main/java/com/maibu/core/business/Device.java +++ b/maibu-common/src/main/java/com/maibu/core/business/Device.java @@ -14,6 +14,7 @@ import org.springframework.data.annotation.Transient; import java.math.BigDecimal; import java.util.Date; import java.util.List; +import java.util.Map; /** * 设备对象 iot_device @@ -106,7 +107,7 @@ public class Device extends BaseDO { private Integer onlineStatus; @TableField(exist = false) - private Integer feStatus; //前端大屏显示 1任务中/2空闲/3离线 + private Integer feStatus; //前端大屏显示 1任务中/2空闲 /** * wifi信号强度(信号极好4格[-55— 0],信号好3格[-70— -55],信号一般2格[-85— -70],信号差1格[-100— -85]) @@ -223,4 +224,7 @@ public class Device extends BaseDO { return lastRunningStatus != null ? lastRunningStatus : new DeviceRunningStatusHistory(); } + @TableField(exist = false) + private Map statusStatistics; + } diff --git a/maibu-common/src/main/java/com/maibu/core/business/DevicePlan.java b/maibu-common/src/main/java/com/maibu/core/business/DevicePlan.java index 21321a6..056ea55 100644 --- a/maibu-common/src/main/java/com/maibu/core/business/DevicePlan.java +++ b/maibu-common/src/main/java/com/maibu/core/business/DevicePlan.java @@ -5,14 +5,19 @@ import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.maibu.core.domain.OrgBaseDO; import com.maibu.core.enums.DeviceTaskStaus; import lombok.Data; +import lombok.EqualsAndHashCode; +import java.time.LocalDate; import java.time.LocalDateTime; +@EqualsAndHashCode(callSuper = true) @Data @TableName(value = "iot_device_plan", autoResultMap = true) -public class DevicePlan { +public class DevicePlan extends OrgBaseDO { @TableId(type = IdType.AUTO) private Long id; @@ -31,25 +36,15 @@ public class DevicePlan { private Long routeId; // 线路id - private Long userId; // 用户id - @TableField(typeHandler = JacksonTypeHandler.class) private DeviceTaskPlanRule deviceTaskPlanRules; //计划 - private LocalDateTime createTime; - - private String createBy; - - private LocalDateTime updateTime; - - private String updateBy; - + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime finishTime; + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime startTime; //开始时间 时分秒 - private int delFlag = 0; //删除状态 1删除 - @TableField(exist = false) private boolean dayTriggerFlag = false; //当天的任务是否已经生成 } diff --git a/maibu-common/src/main/java/com/maibu/core/business/DevicePlanTask.java b/maibu-common/src/main/java/com/maibu/core/business/DevicePlanTask.java index 514028c..287948c 100644 --- a/maibu-common/src/main/java/com/maibu/core/business/DevicePlanTask.java +++ b/maibu-common/src/main/java/com/maibu/core/business/DevicePlanTask.java @@ -4,14 +4,18 @@ import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; +import com.maibu.core.domain.BaseDO; +import com.maibu.core.domain.OrgBaseDO; import com.maibu.core.enums.DeviceTaskStaus; import lombok.Data; +import lombok.EqualsAndHashCode; import java.time.LocalDateTime; +@EqualsAndHashCode(callSuper = true) @Data @TableName("iot_device_task") -public class DevicePlanTask { +public class DevicePlanTask extends OrgBaseDO { @TableId(type = IdType.AUTO) private Long id; @@ -31,8 +35,6 @@ public class DevicePlanTask { private LocalDateTime startTime; //开始时间 时分秒 - private LocalDateTime createTime; //创建时间 - private String taskType; //任务类型分类 } diff --git a/maibu-common/src/main/java/com/maibu/core/business/PlanPath.java b/maibu-common/src/main/java/com/maibu/core/business/PlanPath.java new file mode 100644 index 0000000..9ba3260 --- /dev/null +++ b/maibu-common/src/main/java/com/maibu/core/business/PlanPath.java @@ -0,0 +1,17 @@ +package com.maibu.core.business; + +import com.maibu.core.business.path.LatAndLngEntity; +import lombok.Data; + +import java.util.List; + +@Data +public class PlanPath { + + private String name; + private List path; + private List outer; + private String img; + private String planModel; + +} diff --git a/maibu-common/src/main/java/com/maibu/core/business/WorkRecord.java b/maibu-common/src/main/java/com/maibu/core/business/WorkRecord.java index cb28f59..46dbfa5 100644 --- a/maibu-common/src/main/java/com/maibu/core/business/WorkRecord.java +++ b/maibu-common/src/main/java/com/maibu/core/business/WorkRecord.java @@ -1,15 +1,30 @@ package com.maibu.core.business; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler; +import com.maibu.core.domain.OrgBaseDO; import lombok.Data; +import lombok.EqualsAndHashCode; import java.io.Serializable; @Data -public class WorkRecord implements Serializable { +@EqualsAndHashCode(callSuper = true) +@TableName(value = "iot_work_record", autoResultMap = true) +public class WorkRecord extends OrgBaseDO { private static final long serialVersionUID = 1L; + @TableId(type = IdType.AUTO) private Long id; private String workName; private Long userId; - private String jsonData; + +// private String jsonData; + + @TableField(typeHandler = JacksonTypeHandler.class) + private PlanPath jsonData; //计划 + private String imgUrl; } diff --git a/maibu-common/src/main/java/com/maibu/core/business/device/NettyDevice.java b/maibu-common/src/main/java/com/maibu/core/business/device/NettyDevice.java index 1c70bc5..b8384b5 100644 --- a/maibu-common/src/main/java/com/maibu/core/business/device/NettyDevice.java +++ b/maibu-common/src/main/java/com/maibu/core/business/device/NettyDevice.java @@ -1,12 +1,26 @@ package com.maibu.core.business.device; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.maibu.core.business.DevicePlanTask; import com.maibu.core.business.DeviceRunStatistics; +import com.maibu.core.business.PlanPath; +import com.maibu.core.business.WorkRecord; +import com.maibu.core.business.path.RoutePlanSendEntity; import com.maibu.core.enums.ConnectorType; +import com.maibu.core.enums.DeviceTaskStaus; +import com.maibu.mapper.DevicePlanTaskMapper; +import com.maibu.mapper.WorkRecordMapper; +import com.maibu.memory.GlobalMemory; +import com.maibu.memory.SiteMemory; +import com.maibu.utils.spring.SpringUtils; +import io.netty.buffer.Unpooled; import lombok.Data; import lombok.EqualsAndHashCode; import com.maibu.core.business.path.LatAndLngEntity; +import org.springframework.util.CollectionUtils; +import java.time.LocalDateTime; import java.util.LinkedList; import java.util.Queue; @@ -20,14 +34,24 @@ public class NettyDevice extends Connector { private Long currentTaskId; //当前执行的任务; + private DevicePlanTask task; //当前执行的任务; + private Integer onlineStatus; //在线状态 0 离线 1在线 + private LatAndLngEntity currentPoint; //执行任务的当前点 + private Queue locationQueue = new LinkedList<>(); private DeviceRunStatistics latestStatus; private Long latestLoginTime; + private boolean executingTask = false; + + private DevicePlanTaskMapper devicePlanTaskMapper = SpringUtils.getBean(DevicePlanTaskMapper.class); + + private WorkRecordMapper workRecordMapper = SpringUtils.getBean(WorkRecordMapper.class); + public NettyDevice(String connectorId) { super(connectorId); this.deviceType = ConnectorType.MASTER; // 默认上位机角色 @@ -38,5 +62,105 @@ public class NettyDevice extends Connector { this.deviceType = deviceType; } + public void sendNextPoint() { + if (task.getTaskStaus().equals(DeviceTaskStaus.PAUSE)) return; + if (!locationQueue.isEmpty()) { + LatAndLngEntity entity = locationQueue.poll(); + if (entity != null) { + RoutePlanSendEntity routePlanSendEntity = new RoutePlanSendEntity(); + routePlanSendEntity.setCommandType((byte) 0x01); + routePlanSendEntity.setPointCounts((short) 1); + routePlanSendEntity.setTargetLatitude(entity.getLat()); + routePlanSendEntity.setTargetLongitude(entity.getLng()); + routePlanSendEntity.setSpeed((short) 1000); + byte[] bytes = routePlanSendEntity.toBytes(); + System.out.println("====Lat:" + entity.getLat() + " ====Lng:" + entity.getLng()); + + currentPoint = entity; + if (this.getChannel() != null && this.getChannel().isActive()) { + this.getChannel().writeAndFlush(Unpooled.wrappedBuffer(bytes)); + } + } + } + } + + public synchronized void finishTask() { + if (executingTask) { + task.setTaskStaus(DeviceTaskStaus.FINISH); + task.setFinishTime(LocalDateTime.now()); + devicePlanTaskMapper.saveOrUpdate(task); + SiteMemory siteMemory = GlobalMemory.getSiteMemory(task.getOrgId(), task.getSiteId()); + siteMemory.removeDevicePlanExecute(task.getDeviceId()); + task = null; + currentTaskId = null; + executingTask = false; + } + } + + public synchronized boolean cancelTask() { + if (executingTask) { + task.setTaskStaus(DeviceTaskStaus.CANCELED); + task.setUpdateTime(LocalDateTime.now()); + devicePlanTaskMapper.saveOrUpdate(task); + SiteMemory siteMemory = GlobalMemory.getSiteMemory(task.getOrgId(), task.getSiteId()); + siteMemory.removeDevicePlanExecute(task.getDeviceId()); + task = null; + currentTaskId = null; + locationQueue.clear(); + executingTask = false; + return true; + } else { + return false; + } + } + + //todo 优化 + public synchronized boolean pauseTask() { + if (executingTask) { + task.setTaskStaus(DeviceTaskStaus.PAUSE); + executingTask = false; + return true; + } else { + return false; + } + + } + + //todo 优化 + public synchronized boolean recoveryTask() { + if (!executingTask) { + task.setTaskStaus(DeviceTaskStaus.EXECUTING); + executingTask = true; + sendNextPoint(); + return true; + }else { + return false; + } + } + + + public void startTask() { + try { + if (executingTask) return; + if (task != null) { + Long routeId = task.getRouteId(); + WorkRecord workRecord = workRecordMapper.selectById(routeId); + if (workRecord != null) { + PlanPath planPath = workRecord.getJsonData(); + if (planPath != null && !CollectionUtils.isEmpty(planPath.getPath())) { + planPath.getPath().forEach(x -> { + locationQueue.offer(x); + }); + } + } + task.setStartTime(LocalDateTime.now()); + } + executingTask = true; + sendNextPoint(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } diff --git a/maibu-common/src/main/java/com/maibu/core/domain/BaseDO.java b/maibu-common/src/main/java/com/maibu/core/domain/BaseDO.java index 7d1ea20..7af55c9 100644 --- a/maibu-common/src/main/java/com/maibu/core/domain/BaseDO.java +++ b/maibu-common/src/main/java/com/maibu/core/domain/BaseDO.java @@ -42,7 +42,7 @@ public class BaseDO implements Serializable { /** 逻辑删除 */ @ApiModelProperty("逻辑删除") @TableLogic - private Boolean delFlag; + private Boolean delFlag = false; /** 请求参数 */ @TableField(exist = false) diff --git a/maibu-common/src/main/java/com/maibu/core/domain/OrgBaseDO.java b/maibu-common/src/main/java/com/maibu/core/domain/OrgBaseDO.java new file mode 100644 index 0000000..2cf523b --- /dev/null +++ b/maibu-common/src/main/java/com/maibu/core/domain/OrgBaseDO.java @@ -0,0 +1,24 @@ +package com.maibu.core.domain; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * 拓展多租户的 BaseDO 基类 + * + * @author fastbee + */ +@Data +@EqualsAndHashCode(callSuper = true) +public abstract class OrgBaseDO extends BaseDO { + + /** + * 多租户编号 + */ + private Long orgId; + + private Long siteId; + + private Long userId; + +} diff --git a/maibu-common/src/main/java/com/maibu/core/enums/DeviceTaskStaus.java b/maibu-common/src/main/java/com/maibu/core/enums/DeviceTaskStaus.java index d613642..d1caccb 100644 --- a/maibu-common/src/main/java/com/maibu/core/enums/DeviceTaskStaus.java +++ b/maibu-common/src/main/java/com/maibu/core/enums/DeviceTaskStaus.java @@ -10,6 +10,7 @@ public enum DeviceTaskStaus { NEW("NEW","新建"), EXECUTING("EXECUTING","执行中"), PAUSE("PAUSE","暂停中"), + CANCELED("CANCELED","已取消"), FINISH("FINISH","执行成功"), FAILED("FAILED","执行失败"); diff --git a/maibu-service/maibu-iot-service/src/main/java/com/maibu/mapper/DevicePlanMapper.java b/maibu-common/src/main/java/com/maibu/mapper/DevicePlanMapper.java similarity index 100% rename from maibu-service/maibu-iot-service/src/main/java/com/maibu/mapper/DevicePlanMapper.java rename to maibu-common/src/main/java/com/maibu/mapper/DevicePlanMapper.java diff --git a/maibu-service/maibu-iot-service/src/main/java/com/maibu/mapper/DevicePlanTaskMapper.java b/maibu-common/src/main/java/com/maibu/mapper/DevicePlanTaskMapper.java similarity index 100% rename from maibu-service/maibu-iot-service/src/main/java/com/maibu/mapper/DevicePlanTaskMapper.java rename to maibu-common/src/main/java/com/maibu/mapper/DevicePlanTaskMapper.java diff --git a/maibu-common/src/main/java/com/maibu/mapper/WorkRecordMapper.java b/maibu-common/src/main/java/com/maibu/mapper/WorkRecordMapper.java new file mode 100644 index 0000000..721f887 --- /dev/null +++ b/maibu-common/src/main/java/com/maibu/mapper/WorkRecordMapper.java @@ -0,0 +1,10 @@ +package com.maibu.mapper; + + +import com.maibu.core.business.WorkRecord; +import com.maibu.mybatis.mapper.BaseMapperX; + + +public interface WorkRecordMapper extends BaseMapperX { + +} diff --git a/maibu-common/src/main/java/com/maibu/memory/GlobalMemory.java b/maibu-common/src/main/java/com/maibu/memory/GlobalMemory.java index b7284ce..4425b67 100644 --- a/maibu-common/src/main/java/com/maibu/memory/GlobalMemory.java +++ b/maibu-common/src/main/java/com/maibu/memory/GlobalMemory.java @@ -9,6 +9,7 @@ import lombok.Data; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -35,7 +36,7 @@ public class GlobalMemory { public static ConcurrentHashMap productMap = new ConcurrentHashMap<>(); - public SiteMemory getSiteMemory(Long orgId, Long siteId) { + public static SiteMemory getSiteMemory(Long orgId, Long siteId) { if (orgId != null && siteId != null) { Map siteMemories = orgAttrs.get(orgId); if (!CollectionUtils.isEmpty(siteMemories)) { @@ -45,13 +46,23 @@ public class GlobalMemory { return null; } + public static List getAllSiteMemory() { + List list = new ArrayList<>(); + orgAttrs.values().forEach(x -> { + list.addAll(x.values()); + }); + return list; + } + /** * 新增场站内存 * @param orgId * @param siteId * @param siteMemory */ - public void addSiteMemory(Long orgId, Long siteId, SiteMemory siteMemory) { + //todo 初始化 + public static void addSiteMemory(Long orgId, Long siteId, SiteMemory siteMemory) { + if (orgId != null && siteId != null) { Map siteMemories = orgAttrs.get(orgId); if (CollectionUtils.isEmpty(siteMemories)) { @@ -67,7 +78,7 @@ public class GlobalMemory { * @param orgId * @param siteId */ - public void removeSiteMemory(Long orgId, Long siteId) { + public static void removeSiteMemory(Long orgId, Long siteId) { if (orgId != null && siteId != null) { Map siteMemories = orgAttrs.get(orgId); if (!CollectionUtils.isEmpty(siteMemories)) { diff --git a/maibu-common/src/main/java/com/maibu/memory/SiteMemory.java b/maibu-common/src/main/java/com/maibu/memory/SiteMemory.java index ca39cac..b6f2c74 100644 --- a/maibu-common/src/main/java/com/maibu/memory/SiteMemory.java +++ b/maibu-common/src/main/java/com/maibu/memory/SiteMemory.java @@ -38,7 +38,6 @@ public class SiteMemory { //key deviceId execute public static ConcurrentHashMap devicePlanTaskExecuteMap = new ConcurrentHashMap<>(); - public static void saveDevice(Device device) { deviceMap.put(device.getSerialNumber(), device); } @@ -49,7 +48,7 @@ public class SiteMemory { } } - public static void addDevicePlan(DevicePlan devicePlan) { + public void addDevicePlan(DevicePlan devicePlan) { if (devicePlan != null && !StringUtils.isEmpty(devicePlan.getDeviceId())) { String deviceId = devicePlan.getDeviceId(); List list = devicePlanMap.get(deviceId); @@ -66,7 +65,7 @@ public class SiteMemory { } - public static void removeDevicePlan(DevicePlan devicePlan) { + public void removeDevicePlan(DevicePlan devicePlan) { if (devicePlan != null && !StringUtils.isEmpty(devicePlan.getDeviceId())) { String deviceId = devicePlan.getDeviceId(); List list = devicePlanMap.get(deviceId); @@ -76,7 +75,7 @@ public class SiteMemory { } } - public static void addDevicePlanPrepare(DevicePlanTask devicePlanTask) { + public void addDevicePlanPrepare(DevicePlanTask devicePlanTask) { if (devicePlanTask != null && !StringUtils.isEmpty(devicePlanTask.getDeviceId())) { String deviceId = devicePlanTask.getDeviceId(); List list = devicePlanTaskPrepareMap.get(deviceId); @@ -88,7 +87,7 @@ public class SiteMemory { } } - public static void removeDevicePlanPrepare(DevicePlanTask devicePlanTask) { + public void removeDevicePlanPrepare(DevicePlanTask devicePlanTask) { if (devicePlanTask != null && !StringUtils.isEmpty(devicePlanTask.getDeviceId())) { String deviceId = devicePlanTask.getDeviceId(); List list = devicePlanTaskPrepareMap.get(deviceId); @@ -99,18 +98,33 @@ public class SiteMemory { } - public static void addDevicePlanExecute(DevicePlanTask devicePlanTask) { + public void addDevicePlanExecute(DevicePlanTask devicePlanTask) { if (devicePlanTask != null && !StringUtils.isEmpty(devicePlanTask.getDeviceId())) { String deviceId = devicePlanTask.getDeviceId(); devicePlanTaskExecuteMap.put(deviceId, devicePlanTask); } } - public static void removeDevicePlanExecute(String deviceId) { + public void removeDevicePlanExecute(String deviceId) { if (!StringUtils.isEmpty(deviceId)) { devicePlanTaskExecuteMap.remove(deviceId); } } + public boolean hasTask(String deviceId) { + DevicePlanTask task = devicePlanTaskExecuteMap.get(deviceId); + List list = devicePlanTaskPrepareMap.get(deviceId); + return task != null || !CollectionUtils.isEmpty(list); + } + + public DevicePlanTask getDeviceExecuteTask(String deviceId) { + if (!StringUtils.isEmpty(deviceId)) { + return devicePlanTaskExecuteMap.get(deviceId); + } + return null; + } + + + } diff --git a/maibu-external/src/main/java/com/maibu/uav/dto/UavDeviceStateResponseDetailDTO.java b/maibu-external/src/main/java/com/maibu/uav/dto/UavDeviceStateResponseDetailDTO.java index b1cfdf6..c76e15c 100644 --- a/maibu-external/src/main/java/com/maibu/uav/dto/UavDeviceStateResponseDetailDTO.java +++ b/maibu-external/src/main/java/com/maibu/uav/dto/UavDeviceStateResponseDetailDTO.java @@ -4,6 +4,7 @@ import com.maibu.uav.entity.CameraInfo; import lombok.Data; import java.util.List; +import java.util.Map; @Data public class UavDeviceStateResponseDetailDTO { @@ -31,4 +32,8 @@ public class UavDeviceStateResponseDetailDTO { private Long orgId; private Long siteId; private Long userId; + + private Integer mode_code; + + private Map modeStatistics; } diff --git a/maibu-external/src/main/java/com/maibu/uav/service/UAVService.java b/maibu-external/src/main/java/com/maibu/uav/service/UAVService.java index a718ce0..00ef0fd 100644 --- a/maibu-external/src/main/java/com/maibu/uav/service/UAVService.java +++ b/maibu-external/src/main/java/com/maibu/uav/service/UAVService.java @@ -126,6 +126,7 @@ public class UAVService { return new ArrayList<>(); } + //todo 更新统计数据加内存不重复查 public List transferData(List list) { if (!CollectionUtils.isEmpty(list)) { Map deviceMap = list.stream() @@ -167,6 +168,7 @@ public class UAVService { Map map = (Map) resultDTO.getData(); UavDeviceStateResponseDTO responseDTO = new UavDeviceStateResponseDTO(); if (!CollectionUtils.isEmpty(map)) { + Map statistics = new HashMap<>(); List> l = (List>) map.get("list"); if (!CollectionUtils.isEmpty(l)) { List detail = new ArrayList<>(); @@ -182,6 +184,13 @@ public class UAVService { UavDevice getway = up.getGateway(); UavDeviceStateResponseDetailDTO dto = new UavDeviceStateResponseDetailDTO(); if (getway != null) { + Integer c = statistics.get(getway.getMode_code()); + if (c == null) { + c = 0; + } + c += 1; + statistics.put(getway.getMode_code(), c); + dto.setMode_code(getway.getMode_code()); dto.setGateway_sn(getway.getSn()); dto.setCallsign(getway.getCallsign()); dto.setOnlineStatus(getway.getDevice_online_status() ? 1 : 0); @@ -195,6 +204,9 @@ public class UAVService { detail.add(dto); } }); + detail.forEach(y -> { + y.setModeStatistics(statistics); + }); } } return responseDTO; @@ -363,8 +375,8 @@ public class UAVService { public UavDeviceStateResponseDetailDTO getUAVState(String deviceSn, String droneSn) { List list = getCurrentState(); UavDeviceStateResponseDetailDTO dto = null; - if(!CollectionUtils.isEmpty(list)){ - dto = list.stream().filter(x->x.getGateway_sn().equals(deviceSn)).findFirst().orElse(null); + if (!CollectionUtils.isEmpty(list)) { + dto = list.stream().filter(x -> x.getGateway_sn().equals(deviceSn)).findFirst().orElse(null); if (!StringUtils.isEmpty(deviceSn)) { String url = baseUrl + "/openapi/v0.1/device/" + deviceSn + "/state"; String deviceData = httpService.doGet(url, null); diff --git a/maibu-netty-server/src/main/java/com/maibu/controller/DeviceTaskController.java b/maibu-netty-server/src/main/java/com/maibu/controller/DeviceTaskController.java index 1773a85..c4493c4 100644 --- a/maibu-netty-server/src/main/java/com/maibu/controller/DeviceTaskController.java +++ b/maibu-netty-server/src/main/java/com/maibu/controller/DeviceTaskController.java @@ -4,12 +4,21 @@ import com.maibu.core.business.DevicePlan; import com.maibu.core.controller.BaseController; import com.maibu.core.domain.AjaxResult; import com.maibu.core.domain.model.LoginUser; +import com.maibu.core.enums.DeviceTaskStaus; +import com.maibu.core.page.TableDataInfo; +import com.maibu.dto.DeviceTaskCommandDTO; import com.maibu.dto.DeviceTaskQueryDTO; +import com.maibu.memory.GlobalMemory; +import com.maibu.memory.SiteMemory; import com.maibu.service.DeviceTaskService; import com.maibu.utils.SecurityUtils; +import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.bind.annotation.*; +import java.time.LocalDate; + @RestController @RequestMapping("/iot/deviceTask") public class DeviceTaskController extends BaseController { @@ -28,6 +37,15 @@ public class DeviceTaskController extends BaseController { return AjaxResult.success(deviceTaskService.getDeviceTaskByUser(userId)); } + @GetMapping("/getSiteDevicePlan") + public AjaxResult getSiteDevicePlan(@RequestParam Long siteId, + @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime, + @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime, + @RequestParam(required = false) String deviceId, + @RequestParam(required = false) DeviceTaskStaus taskStaus) { + return AjaxResult.success(deviceTaskService.getSiteDevicePlan(siteId, startTime, endTime, deviceId, taskStaus)); + } + @PostMapping("/getDevicePlan") public AjaxResult getDevicePlan(@RequestBody DeviceTaskQueryDTO dto) { return AjaxResult.success(deviceTaskService.getDeviceTask(dto)); @@ -68,8 +86,63 @@ public class DeviceTaskController extends BaseController { } @PostMapping("/deviceTaskPool") - public AjaxResult deviceTaskPool(@RequestBody DeviceTaskQueryDTO dto) { - return AjaxResult.success(deviceTaskService.deviceTaskPool(dto)); + public TableDataInfo deviceTaskPool(@RequestBody DeviceTaskQueryDTO dto) { + startPage(); + return getDataTable(deviceTaskService.deviceTaskPool(dto)); + } + + @PostMapping("/getSiteDeviceTaskHistory") + public TableDataInfo getSiteDeviceTaskHistory(@RequestBody DeviceTaskQueryDTO dto) { + startPage(); + return getDataTable(deviceTaskService.getSiteDeviceTaskHistory(dto)); + } + + @PostMapping("/createDeviceTask") + public AjaxResult createDeviceTask(@RequestBody DeviceTaskCommandDTO dto) { + String deviceId = dto.getDeviceId(); + Long siteId = dto.getSiteId(); + Long orgId = dto.getOrgId(); + if (StringUtils.isEmpty(deviceId)) { + return AjaxResult.error("deviceId为空!"); + } + if (siteId == null) { + return AjaxResult.error("siteId为空!"); + } + if (orgId == null) { + return AjaxResult.error("orgId为空!"); + } + SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); + if (siteMemory.hasTask(deviceId)) { + return AjaxResult.error("当前设备存在任务!"); + } + return AjaxResult.success(deviceTaskService.createDeviceTask(dto, getLoginUser().getUsername())); + } + + @PostMapping("/cancelTask") + public AjaxResult cancelTask(@RequestBody DeviceTaskCommandDTO dto) { + String deviceId = dto.getDeviceId(); + if (StringUtils.isEmpty(deviceId) && dto.getTaskId() == null) { + return AjaxResult.error("deviceId或taskId为空!"); + } + return AjaxResult.success(deviceTaskService.cancelTask(dto, getUsername())); + } + + @PostMapping("/pauseTask") + public AjaxResult pauseTask(@RequestBody DeviceTaskCommandDTO dto) { + String deviceId = dto.getDeviceId(); + if (StringUtils.isEmpty(deviceId) && dto.getTaskId() == null) { + return AjaxResult.error("deviceId或taskId为空!"); + } + return AjaxResult.success(deviceTaskService.pauseTask(dto, getUsername())); + } + + @PostMapping("/recoveryTask") + public AjaxResult recoveryTask(@RequestBody DeviceTaskCommandDTO dto) { + String deviceId = dto.getDeviceId(); + if (StringUtils.isEmpty(deviceId) && dto.getTaskId() == null) { + return AjaxResult.error("deviceId或taskId为空!"); + } + return AjaxResult.success(deviceTaskService.recoveryTask(dto, getUsername())); } diff --git a/maibu-netty-server/src/main/java/com/maibu/dto/DeviceTaskCommandDTO.java b/maibu-netty-server/src/main/java/com/maibu/dto/DeviceTaskCommandDTO.java new file mode 100644 index 0000000..df5b4d9 --- /dev/null +++ b/maibu-netty-server/src/main/java/com/maibu/dto/DeviceTaskCommandDTO.java @@ -0,0 +1,23 @@ +package com.maibu.dto; + +import lombok.Data; + +import java.time.LocalDateTime; + + +@Data +public class DeviceTaskCommandDTO { + + private String deviceId; + + private Long routeId; // 线路id + + private LocalDateTime startTime; //开始时间 时分秒 + + private Long orgId; + + private Long siteId; + + private Long taskId; + +} diff --git a/maibu-netty-server/src/main/java/com/maibu/dto/DeviceTaskQueryDTO.java b/maibu-netty-server/src/main/java/com/maibu/dto/DeviceTaskQueryDTO.java index 2300b93..38ca463 100644 --- a/maibu-netty-server/src/main/java/com/maibu/dto/DeviceTaskQueryDTO.java +++ b/maibu-netty-server/src/main/java/com/maibu/dto/DeviceTaskQueryDTO.java @@ -9,11 +9,13 @@ import java.time.LocalDateTime; public class DeviceTaskQueryDTO { private Long userId; - private LocalDateTime startTime; - private LocalDateTime endTime; +// private LocalDateTime startTime; +// private LocalDateTime endTime; private DeviceTaskStaus taskStaus; private String planName; private Long planId; private String deviceId; + private Long siteId; + private Long orgId; } diff --git a/maibu-netty-server/src/main/java/com/maibu/init/InitThread.java b/maibu-netty-server/src/main/java/com/maibu/init/InitThread.java index b83b8d5..c3d71dc 100644 --- a/maibu-netty-server/src/main/java/com/maibu/init/InitThread.java +++ b/maibu-netty-server/src/main/java/com/maibu/init/InitThread.java @@ -2,9 +2,14 @@ package com.maibu.init; import com.maibu.constant.FastBeeConstant; import com.maibu.core.business.DevicePlan; +import com.maibu.core.business.DevicePlanTask; +import com.maibu.core.domain.entity.SysSite; import com.maibu.core.enums.DeviceTaskStaus; import com.maibu.mapper.DevicePlanMapper; +import com.maibu.mapper.DevicePlanTaskMapper; +import com.maibu.mapper.SysSiteMapper; import com.maibu.mapper.SysUserClientMapper; +import com.maibu.memory.GlobalMemory; import com.maibu.memory.SiteMemory; import com.maibu.mybatis.LambdaQueryWrapperX; import com.maibu.service.DevicePlanTaskMonitorService; @@ -46,7 +51,10 @@ public class InitThread implements ApplicationRunner { private DevicePlanMapper devicePlanMapper; @Autowired - private SysUserClientMapper sysUserClientMapper; + private DevicePlanTaskMapper devicePlanTaskMapper; + + @Autowired + private SysSiteMapper sysSiteMapper; @Override public void run(ApplicationArguments args) { @@ -82,17 +90,60 @@ public class InitThread implements ApplicationRunner { /** * 恢复内存 */ - public void recoverMemory(){ + public void recoverMemory() { //todo 启动时清除当前登录记录 // System.out.println("开始清除登录信息"); // sysUserClientMapper.clearDeviceName(); + List siteList = sysSiteMapper.selectList(); + if (!CollectionUtils.isEmpty(siteList)) { + siteList.forEach(x -> { + Long orgId = x.getOrgId(); + Long siteId = x.getId(); + SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); + if (siteMemory == null) { + siteMemory = new SiteMemory(); + GlobalMemory.addSiteMemory(orgId, siteId, siteMemory); + } + }); + } // 未执行完的重复计划 LambdaQueryWrapperX query = new LambdaQueryWrapperX<>(); - List list = Arrays.asList(DeviceTaskStaus.NEW.getCode(),DeviceTaskStaus.EXECUTING.getCode(), DeviceTaskStaus.PAUSE.getCode()); + List list = Arrays.asList(DeviceTaskStaus.NEW.getCode(), DeviceTaskStaus.EXECUTING.getCode(), DeviceTaskStaus.PAUSE.getCode()); query.in(DevicePlan::getTaskStaus, list); List devicePlanList = devicePlanMapper.selectList(query); - if(!CollectionUtils.isEmpty(devicePlanList)){ - devicePlanList.forEach(SiteMemory::addDevicePlan); + if (!CollectionUtils.isEmpty(devicePlanList)) { + devicePlanList.forEach(x -> { + Long orgId = x.getOrgId(); + Long siteId = x.getSiteId(); + SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); + siteMemory.addDevicePlan(x); + }); } + + // 未执行完的重复计划 + LambdaQueryWrapperX taskQuery = new LambdaQueryWrapperX<>(); + taskQuery.eq(DevicePlanTask::getTaskStaus, DeviceTaskStaus.NEW.getCode()); + List newStatusList = devicePlanTaskMapper.selectList(taskQuery); + if (!CollectionUtils.isEmpty(newStatusList)) { + newStatusList.forEach(x -> { + Long orgId = x.getOrgId(); + Long siteId = x.getSiteId(); + SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); + siteMemory.addDevicePlanPrepare(x); + }); + } + + LambdaQueryWrapperX executeTaskQuery = new LambdaQueryWrapperX<>(); + executeTaskQuery.eq(DevicePlanTask::getTaskStaus, DeviceTaskStaus.EXECUTING.getCode()); + List executeStatusList = devicePlanTaskMapper.selectList(executeTaskQuery); + if (!CollectionUtils.isEmpty(executeStatusList)) { + executeStatusList.forEach(x -> { + Long orgId = x.getOrgId(); + Long siteId = x.getSiteId(); + SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); + siteMemory.addDevicePlanExecute(x); + }); + } + } } diff --git a/maibu-netty-server/src/main/java/com/maibu/netty/handler/DeviceConnectHandler.java b/maibu-netty-server/src/main/java/com/maibu/netty/handler/DeviceConnectHandler.java index 2076035..ecec09d 100644 --- a/maibu-netty-server/src/main/java/com/maibu/netty/handler/DeviceConnectHandler.java +++ b/maibu-netty-server/src/main/java/com/maibu/netty/handler/DeviceConnectHandler.java @@ -4,6 +4,7 @@ import com.maibu.common.CommandConstant; import com.maibu.common.Constant; import com.maibu.core.business.Device; import com.maibu.core.business.device.NettyDevice; +import com.maibu.core.business.path.LatAndLngEntity; import com.maibu.core.domain.entity.SysUser; import com.maibu.core.domain.entity.UserClient; import com.maibu.core.enums.*; @@ -36,6 +37,7 @@ import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.List; +import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; @Component @@ -301,15 +303,22 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler { } } } + } else if (cmdType == CommandConstant.path) { + //路径下发完成 + if(bytes.length < 11){ + //01 表示完成 + if (bytes[5] == (byte) 0x01) { + Channel channel = ctx.channel(); + String deviceId = channel.attr(Constant.ATT_DEVICE_ID).get(); + NettyDevice device = sessionManager.getDevice(deviceId); + if(CollectionUtils.isEmpty(device.getLocationQueue())) { + device.finishTask(); + }else{ + device.sendNextPoint(); + } + } + } } -// else if (cmdType == CommandConstant.path) { -// Channel channel = ctx.channel(); -// String deviceId = channel.attr(ATT_DEVICE_ID).get(); -// NettyDevice device = sessionManager.getDevice(deviceId); -// if(CollectionUtils.isEmpty(device.getLocationQueue())) return; -// Queue locationQueue = device.getLocationQueue(); -// -// } ctx.fireChannelRead(msg); // 如有其他 handler 需要处理 } catch (Exception e) { logger.error("deviceConnect channelRead:{}", e.getMessage()); diff --git a/maibu-netty-server/src/main/java/com/maibu/service/DevicePlanTaskMonitorService.java b/maibu-netty-server/src/main/java/com/maibu/service/DevicePlanTaskMonitorService.java index 24c2c52..0a5ccc6 100644 --- a/maibu-netty-server/src/main/java/com/maibu/service/DevicePlanTaskMonitorService.java +++ b/maibu-netty-server/src/main/java/com/maibu/service/DevicePlanTaskMonitorService.java @@ -5,13 +5,14 @@ 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; -import com.maibu.core.business.device.NettyDevice; import com.maibu.manager.DeviceSessionManager; import com.maibu.mapper.DevicePlanMapper; import com.maibu.mapper.DevicePlanTaskMapper; import com.maibu.mapper.WorkRecordMapper; +import com.maibu.memory.GlobalMemory; import com.maibu.memory.SiteMemory; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; @@ -32,10 +33,6 @@ import java.util.concurrent.TimeUnit; @Service public class DevicePlanTaskMonitorService { - - @Autowired - private SiteMemory siteMemory; - @Autowired private DevicePlanTaskMapper devicePlanTaskMapper; @@ -108,7 +105,10 @@ public class DevicePlanTaskMonitorService { devicePlanTask.setRouteId(devicePlan.getRouteId()); devicePlanTask.setCreateTime(LocalDateTime.now()); 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点? devicePlan.setDayTriggerFlag(true); @@ -120,7 +120,7 @@ public class DevicePlanTaskMonitorService { if (endTime != null && endTime.isEqual(today)) { devicePlan.setFinishTime(LocalDateTime.now()); devicePlan.setTaskStaus(DeviceTaskStaus.FINISH); - SiteMemory.removeDevicePlan(devicePlan); + siteMemory.removeDevicePlan(devicePlan); } devicePlanMapper.updateById(devicePlan); } @@ -141,8 +141,11 @@ public class DevicePlanTaskMonitorService { devicePlanTask.setTaskStaus(DeviceTaskStaus.NEW); devicePlanTask.setRouteId(devicePlan.getRouteId()); devicePlanTask.setCreateTime(LocalDateTime.now()); + devicePlanTask.setOrgId(devicePlan.getOrgId()); + devicePlanTask.setSiteId(devicePlan.getSiteId()); devicePlanTask.setTaskType("");//待拓展任务类型 devicePlanTaskMapper.insert(devicePlanTask); + SiteMemory siteMemory = GlobalMemory.getSiteMemory(devicePlan.getOrgId(), devicePlan.getSiteId()); siteMemory.addDevicePlanPrepare(devicePlanTask); //啥时候重置?每日0点? devicePlan.setDayTriggerFlag(true); @@ -153,7 +156,7 @@ public class DevicePlanTaskMonitorService { if (endTime != null && endTime.isEqual(today)) { devicePlan.setFinishTime(LocalDateTime.now()); devicePlan.setTaskStaus(DeviceTaskStaus.FINISH); - SiteMemory.removeDevicePlan(devicePlan); + siteMemory.removeDevicePlan(devicePlan); } devicePlanMapper.updateById(devicePlan); } @@ -174,7 +177,10 @@ public class DevicePlanTaskMonitorService { devicePlanTask.setRouteId(devicePlan.getRouteId()); devicePlanTask.setCreateTime(LocalDateTime.now()); 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点? devicePlan.setDayTriggerFlag(true); @@ -185,7 +191,7 @@ public class DevicePlanTaskMonitorService { if (endTime != null && endTime.isEqual(today)) { devicePlan.setFinishTime(LocalDateTime.now()); devicePlan.setTaskStaus(DeviceTaskStaus.FINISH); - SiteMemory.removeDevicePlan(devicePlan); + siteMemory.removeDevicePlan(devicePlan); } devicePlanMapper.updateById(devicePlan); } @@ -202,31 +208,37 @@ public class DevicePlanTaskMonitorService { ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); executor.scheduleWithFixedDelay(() -> { try { - Map> planMap = SiteMemory.devicePlanTaskPrepareMap; - if (!CollectionUtils.isEmpty(planMap.keySet())) { - planMap.keySet().forEach(key -> { - NettyDevice device = deviceSessionManager.getDevice(key); - //判断是否能进execute - if (device != null && device.getCurrentTaskId() == null && device.getOnlineStatus() != null && device.getOnlineStatus() == 1) { - List list = planMap.get(key); - if (!CollectionUtils.isEmpty(list)) { - list.removeIf(Objects::isNull); - list.sort( - Comparator.comparing( - DevicePlanTask::getStartTime, - Comparator.nullsLast(Comparator.naturalOrder()) - ) - ); - if (!CollectionUtils.isEmpty(list)) { - DevicePlanTask devicePlanTask = list.get(0); - String deviceId = devicePlanTask.getDeviceId(); - if (!StringUtils.isEmpty(deviceId) && deviceId.equals(key)) { - SiteMemory.addDevicePlanExecute(devicePlanTask); - device.setCurrentTaskId(devicePlanTask.getId()); - SiteMemory.removeDevicePlanPrepare(devicePlanTask); + List list = GlobalMemory.getAllSiteMemory(); + if (!CollectionUtils.isEmpty(list)) { + list.forEach(siteMemory -> { + Map> planMap = siteMemory.devicePlanTaskPrepareMap; + if (!CollectionUtils.isEmpty(planMap.keySet())) { + planMap.keySet().forEach(key -> { + NettyDevice device = deviceSessionManager.getDevice(key); + //判断是否能进execute + if (device != null && device.getCurrentTaskId() == null && device.getOnlineStatus() != null && device.getOnlineStatus() == 1) { + List tasks = planMap.get(key); + if (!CollectionUtils.isEmpty(tasks)) { + tasks.removeIf(Objects::isNull); + tasks.sort( + Comparator.comparing( + DevicePlanTask::getStartTime, + Comparator.nullsLast(Comparator.naturalOrder()) + ) + ); + if (!CollectionUtils.isEmpty(tasks)) { + DevicePlanTask devicePlanTask = tasks.get(0); + String deviceId = devicePlanTask.getDeviceId(); + if (!StringUtils.isEmpty(deviceId) && deviceId.equals(key)) { + siteMemory.addDevicePlanExecute(devicePlanTask); + device.setCurrentTaskId(devicePlanTask.getId()); + device.setTask(devicePlanTask); + siteMemory.removeDevicePlanPrepare(devicePlanTask); + } + } } } - } + }); } }); } @@ -241,26 +253,18 @@ public class DevicePlanTaskMonitorService { ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); executor.scheduleWithFixedDelay(() -> { try { - Map planMap = SiteMemory.devicePlanTaskExecuteMap; - if (!CollectionUtils.isEmpty(planMap.keySet())) { - planMap.keySet().forEach(key -> { - NettyDevice device = deviceSessionManager.getDevice(key); - if (device != null && device.getCurrentTaskId() == null && device.getOnlineStatus() != null && device.getOnlineStatus() == 1) { - DevicePlanTask devicePlanTask = planMap.get(key); - if (devicePlanTask != null && DeviceTaskStaus.NEW.equals(devicePlanTask.getTaskStaus())) { - devicePlanTask.setTaskStaus(DeviceTaskStaus.EXECUTING); - //todo 任务结束的逻辑,执行完路线规划更新 任务完成 - Long routId = devicePlanTask.getRouteId(); - WorkRecord workRecord = workRecordMapper.selectWorkRecordById(routId); - if (workRecord != null) { - //todo 执行转化 并更新到nettyDevice - //todo 更新到device - - } + List list = GlobalMemory.getAllSiteMemory(); + list.forEach(siteMemory -> { + Map planMap = siteMemory.devicePlanTaskExecuteMap; + if (!CollectionUtils.isEmpty(planMap.keySet())) { + planMap.keySet().forEach(key -> { + NettyDevice device = deviceSessionManager.getDevice(key); + if (device != null && !device.isExecutingTask() && device.getTask() != null) { + device.startTask(); } - } - }); - } + }); + } + }); } catch (Exception e) { log.error("执行任务execute线程错误", e); } diff --git a/maibu-netty-server/src/main/java/com/maibu/service/DeviceTaskService.java b/maibu-netty-server/src/main/java/com/maibu/service/DeviceTaskService.java index 78989c4..952d87d 100644 --- a/maibu-netty-server/src/main/java/com/maibu/service/DeviceTaskService.java +++ b/maibu-netty-server/src/main/java/com/maibu/service/DeviceTaskService.java @@ -2,16 +2,14 @@ package com.maibu.service; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.maibu.core.business.*; +import com.maibu.core.business.device.NettyDevice; +import com.maibu.core.domain.entity.SysSite; import com.maibu.core.domain.model.LoginUser; import com.maibu.core.enums.DeviceTaskStaus; -import com.maibu.dto.DevicePlanStatisticsDTO; -import com.maibu.dto.DevicePlanTaskStatisticsDTO; -import com.maibu.dto.DeviceTaskQueryDTO; -import com.maibu.dto.DeviceWorkStatisticsDTO; -import com.maibu.mapper.DeviceMapper; -import com.maibu.mapper.DevicePlanMapper; -import com.maibu.mapper.DevicePlanTaskMapper; -import com.maibu.mapper.WorkRecordMapper; +import com.maibu.dto.*; +import com.maibu.manager.DeviceSessionManager; +import com.maibu.mapper.*; +import com.maibu.memory.GlobalMemory; import com.maibu.memory.SiteMemory; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; @@ -24,6 +22,7 @@ import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.Random; import java.util.stream.Collectors; @@ -44,14 +43,22 @@ public class DeviceTaskService { private WorkRecordMapper workRecordMapper; + @Autowired + private DeviceSessionManager deviceSessionManager; + + @Autowired + private SysSiteMapper sysSiteMapper; + + public int insertOrUpdate(DevicePlan devicePlan, LoginUser loginUser) { Long id = devicePlan.getId(); + SiteMemory siteMemory = GlobalMemory.getSiteMemory(devicePlan.getOrgId(), devicePlan.getSiteId()); if (id != null) { devicePlan.setUpdateBy(loginUser.getUsername()); devicePlan.setUpdateTime(LocalDateTime.now()); transferDays(devicePlan); int i = devicePlanMapper.updateById(devicePlan); - SiteMemory.addDevicePlan(devicePlan); + siteMemory.addDevicePlan(devicePlan); return i; } else { devicePlan.setTaskStaus(DeviceTaskStaus.NEW); @@ -59,7 +66,7 @@ public class DeviceTaskService { devicePlan.setCreateBy(loginUser.getUsername()); transferDays(devicePlan); int i = devicePlanMapper.insert(devicePlan); - SiteMemory.addDevicePlan(devicePlan); + siteMemory.addDevicePlan(devicePlan); return i; } } @@ -109,19 +116,44 @@ public class DeviceTaskService { } } + public List getSiteDevicePlan(Long siteId, LocalDate startTime, LocalDate endTime, String deviceId, DeviceTaskStaus taskStaus) { + if (siteId != null) { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + queryWrapper.eq(DevicePlan::getSiteId, siteId); + if (taskStaus != null) { + queryWrapper.eq(DevicePlan::getTaskStaus, taskStaus); + } + if (!StringUtils.isEmpty(deviceId)) { + queryWrapper.eq(DevicePlan::getDeviceId, deviceId); + } + if (startTime != null && endTime != null) { + queryWrapper.between(DevicePlan::getCreateTime, startTime, endTime); + } + return transferDevicePlanData(devicePlanMapper.selectList(queryWrapper)); + } else { + return new ArrayList<>(); + } + } + public List getDeviceTask(DeviceTaskQueryDTO dto) { if (dto != null) { LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); if (dto.getUserId() != null) { queryWrapper.eq(DevicePlan::getUserId, dto.getUserId()); } - if (dto.getDeviceId() != null) { + if (!StringUtils.isEmpty(dto.getDeviceId())) { queryWrapper.eq(DevicePlan::getDeviceId, dto.getDeviceId()); } if (dto.getTaskStaus() != null) { queryWrapper.eq(DevicePlan::getTaskStaus, dto.getTaskStaus()); } - if (dto.getPlanName() != null) { + if (dto.getOrgId() != null) { + queryWrapper.eq(DevicePlan::getOrgId, dto.getOrgId()); + } + if (dto.getSiteId() != null) { + queryWrapper.eq(DevicePlan::getSiteId, dto.getSiteId()); + } + if (!StringUtils.isEmpty(dto.getPlanName())) { queryWrapper.like(DevicePlan::getPlanName, dto.getPlanName()); } queryWrapper.eq(DevicePlan::getDelFlag, 0); @@ -143,9 +175,9 @@ public class DeviceTaskService { public int delete(Long id) { DevicePlan planTask = devicePlanMapper.selectById(id); if (planTask != null) { - planTask.setDelFlag(1); - SiteMemory.removeDevicePlan(planTask); - return devicePlanMapper.updateById(planTask); + SiteMemory siteMemory = GlobalMemory.getSiteMemory(planTask.getOrgId(), planTask.getSiteId()); + siteMemory.removeDevicePlan(planTask); + return devicePlanMapper.deleteById(id); } return 0; } @@ -181,7 +213,7 @@ public class DeviceTaskService { LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.ge(DevicePlan::getCreateTime, monthStart) .le(DevicePlan::getCreateTime, monthEnd) - .eq(DevicePlan::getUserId,userId); + .eq(DevicePlan::getUserId, userId); List devicePlans = transferDevicePlanData(devicePlanMapper.selectList(queryWrapper)); if (!CollectionUtils.isEmpty(devicePlans)) { List dates = getMonthDays(); @@ -235,17 +267,17 @@ public class DeviceTaskService { ); // 4. 构建 LambdaQueryWrapper 进行范围查询 LambdaQueryWrapper query = new LambdaQueryWrapper<>(); - query.eq(DevicePlan::getUserId,userId); + query.eq(DevicePlan::getUserId, userId); List devicePlans = transferDevicePlanData(devicePlanMapper.selectList(query)); - if(CollectionUtils.isEmpty(devicePlans)) return new ArrayList<>(); + if (CollectionUtils.isEmpty(devicePlans)) return new ArrayList<>(); List planIds = devicePlans.stream().map(DevicePlan::getId).collect(Collectors.toList()); - if(CollectionUtils.isEmpty(planIds)) return new ArrayList<>(); + if (CollectionUtils.isEmpty(planIds)) return new ArrayList<>(); LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); // 核心:筛选 createTime 大于等于起始时间,且小于等于结束时间 queryWrapper.ge(DevicePlanTask::getCreateTime, monthStart) .le(DevicePlanTask::getCreateTime, monthEnd) - .in(DevicePlanTask::getPlanId,planIds); + .in(DevicePlanTask::getPlanId, planIds); List devicePlanTasks = transferDeviceTaskData(devicePlanTaskMapper.selectList(queryWrapper)); if (!CollectionUtils.isEmpty(devicePlanTasks)) { List dates = getMonthDays(); @@ -275,7 +307,7 @@ public class DeviceTaskService { .eq(DevicePlanTask::getTaskStaus, DeviceTaskStaus.EXECUTING); List devicePlanTasks = devicePlanTaskMapper.selectList(queryWrapper); Long routId = CollectionUtils.isEmpty(devicePlanTasks) ? null : devicePlanTasks.get(0).getRouteId(); - return routId == null ? null : workRecordMapper.selectWorkRecordById(routId); + return routId == null ? null : workRecordMapper.selectById(routId); } @@ -304,22 +336,56 @@ public class DeviceTaskService { public List deviceTaskPool(DeviceTaskQueryDTO dto) { List list = new ArrayList<>(); - SiteMemory.devicePlanTaskPrepareMap.values().forEach(list::addAll); - list.addAll(SiteMemory.devicePlanTaskExecuteMap.values()); - if (dto != null) { - if (dto.getTaskStaus() != null) { - list = list.stream().filter(x -> x.getTaskStaus().equals(dto.getTaskStaus())).collect(Collectors.toList()); - } - if (!StringUtils.isEmpty(dto.getDeviceId())) { - list = list.stream().filter(x -> x.getDeviceId().equals(dto.getDeviceId())).collect(Collectors.toList()); - } - if (dto.getPlanId() != null) { - list = list.stream().filter(x -> x.getPlanId().equals(dto.getPlanId())).collect(Collectors.toList()); + if (dto.getOrgId() == null) { + SysSite site = sysSiteMapper.selectById(dto.getSiteId()); + if (site != null) { + dto.setOrgId(site.getOrgId()); } } + SiteMemory siteMemory = GlobalMemory.getSiteMemory(dto.getOrgId(), dto.getSiteId()); + siteMemory.devicePlanTaskPrepareMap.values().forEach(list::addAll); + list.addAll(SiteMemory.devicePlanTaskExecuteMap.values()); + if (dto.getTaskStaus() != null) { + list = list.stream().filter(x -> x.getTaskStaus().equals(dto.getTaskStaus())).collect(Collectors.toList()); + } + if (!StringUtils.isEmpty(dto.getDeviceId())) { + list = list.stream().filter(x -> x.getDeviceId().equals(dto.getDeviceId())).collect(Collectors.toList()); + } + if (dto.getPlanId() != null) { + list = list.stream().filter(x -> x.getPlanId().equals(dto.getPlanId())).collect(Collectors.toList()); + } + if (dto.getSiteId() != null) { + list = list.stream().filter(x -> x.getSiteId().equals(dto.getSiteId())).collect(Collectors.toList()); + } + if (dto.getOrgId() != null) { + list = list.stream().filter(x -> x.getOrgId().equals(dto.getOrgId())).collect(Collectors.toList()); + } + if (!StringUtils.isEmpty(dto.getDeviceId())) { + list = list.stream().filter(x -> x.getDeviceId().equals(dto.getDeviceId())).collect(Collectors.toList()); + } return transferDeviceTaskData(list); } + public List getSiteDeviceTaskHistory(DeviceTaskQueryDTO dto) { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + if (dto.getSiteId() != null) { + queryWrapper.eq(DevicePlanTask::getSiteId, dto.getSiteId()); + } + if (dto.getOrgId() != null) { + queryWrapper.eq(DevicePlanTask::getOrgId, dto.getOrgId()); + } + if (dto.getTaskStaus() != null) { + queryWrapper.eq(DevicePlanTask::getTaskStaus, dto.getTaskStaus()); + } + if (dto.getPlanId() != null) { + queryWrapper.eq(DevicePlanTask::getPlanId, dto.getPlanId()); + } + if (!StringUtils.isEmpty(dto.getDeviceId())) { + queryWrapper.eq(DevicePlanTask::getDeviceId, dto.getDeviceId()); + } + return transferDeviceTaskData(devicePlanTaskMapper.selectList(queryWrapper)); + } + public List transferDevicePlanData(List list) { if (CollectionUtils.isEmpty(list)) return list; @@ -339,4 +405,95 @@ public class DeviceTaskService { return list; } + public boolean createDeviceTask(DeviceTaskCommandDTO dto, String username) { + DevicePlanTask task = new DevicePlanTask(); + task.setOrgId(dto.getOrgId()); + task.setSiteId(dto.getSiteId()); + task.setTaskStaus(DeviceTaskStaus.NEW); + task.setDeviceId(dto.getDeviceId()); + task.setCreateBy(username); + task.setCreateTime(LocalDateTime.now()); + task.setRouteId(dto.getRouteId()); + task.setStartTime(dto.getStartTime()); + boolean result = devicePlanTaskMapper.saveOrUpdate(task); + if (dto.getOrgId() == null) { + SysSite site = sysSiteMapper.selectById(dto.getSiteId()); + if (site != null) { + dto.setOrgId(site.getOrgId()); + } + } + SiteMemory siteMemory = GlobalMemory.getSiteMemory(task.getOrgId(), task.getSiteId()); + siteMemory.addDevicePlanPrepare(task); + return result; + } + + public boolean cancelTask(DeviceTaskCommandDTO dto, String username) { + if (!StringUtils.isEmpty(dto.getDeviceId())) { + NettyDevice device = deviceSessionManager.getDevice(dto.getDeviceId()); + if (device != null) { + return device.cancelTask(); + } + } else { + Long taskId = dto.getTaskId(); + Long siteId = dto.getSiteId(); + Long orgId = dto.getOrgId(); + DevicePlanTask devicePlanTask = devicePlanTaskMapper.selectById(taskId); + if (devicePlanTask != null) { + devicePlanTask.setUpdateTime(LocalDateTime.now()); + devicePlanTask.setTaskStaus(DeviceTaskStaus.CANCELED); + devicePlanTask.setUpdateBy(username); + devicePlanTaskMapper.saveOrUpdate(devicePlanTask); + SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); + siteMemory.removeDevicePlanPrepare(devicePlanTask); + siteMemory.removeDevicePlanExecute(devicePlanTask.getDeviceId()); + } + } + return false; + } + + //todo 完善 + public boolean pauseTask(DeviceTaskCommandDTO dto, String username) { + if (!StringUtils.isEmpty(dto.getDeviceId())) { + NettyDevice device = deviceSessionManager.getDevice(dto.getDeviceId()); + if (device != null) { + return device.pauseTask(); + } + } else { + Long taskId = dto.getTaskId(); + DevicePlanTask devicePlanTask = devicePlanTaskMapper.selectById(taskId); + if (devicePlanTask != null) { + devicePlanTask.setUpdateTime(LocalDateTime.now()); + devicePlanTask.setTaskStaus(DeviceTaskStaus.PAUSE); + devicePlanTask.setUpdateBy(username); + devicePlanTaskMapper.saveOrUpdate(devicePlanTask); + } + } + return false; + } + + + //todo 完善 + public boolean recoveryTask(DeviceTaskCommandDTO dto, String username) { + if (!StringUtils.isEmpty(dto.getDeviceId())) { + NettyDevice device = deviceSessionManager.getDevice(dto.getDeviceId()); + if (device != null) { + return device.recoveryTask(); + } + } else { + Long taskId = dto.getTaskId(); + Long siteId = dto.getSiteId(); + Long orgId = dto.getOrgId(); + DevicePlanTask devicePlanTask = devicePlanTaskMapper.selectById(taskId); + SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); + DevicePlanTask executeTask = siteMemory.getDeviceExecuteTask(devicePlanTask.getDeviceId()); + if (Objects.equals(devicePlanTask.getId(), executeTask.getId())) { + devicePlanTask.setUpdateTime(LocalDateTime.now()); + devicePlanTask.setTaskStaus(DeviceTaskStaus.EXECUTING); + devicePlanTask.setUpdateBy(username); + devicePlanTaskMapper.saveOrUpdate(devicePlanTask); + } + } + return false; + } + } diff --git a/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/DeviceController.java b/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/DeviceController.java index 931b012..046420c 100644 --- a/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/DeviceController.java +++ b/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/DeviceController.java @@ -122,9 +122,9 @@ public class DeviceController extends BaseController { return AjaxResult.success(deviceRunStatisticsMapper.selectList(queryWrapperX)); } - @GetMapping("/getDeviceIntradayData") - public AjaxResult getDeviceIntradayData(@RequestParam("deviceId") String deviceId) { - List resultList = getIntradayData(); + @GetMapping("/getDeviceTotalData") + public AjaxResult getDeviceTotalData(@RequestParam("deviceId") String deviceId) { + List resultList = getIntradayData(false); DeviceRunStatistics statistics = null; if (!CollectionUtils.isEmpty(resultList)) { statistics = resultList.stream().filter(x -> deviceId.equals(x.getDeviceId())).findFirst().orElse(null); @@ -132,15 +132,31 @@ public class DeviceController extends BaseController { return AjaxResult.success(statistics); } - public List getIntradayData() { - LambdaQueryWrapperX wrapper = new LambdaQueryWrapperX<>(); - LocalDateTime start = LocalDate.now().atStartOfDay(); // 今天 00:00:00 - LocalDateTime end = LocalDate.now().plusDays(1).atStartOfDay(); // 明天 00:00:00 + @GetMapping("/getDeviceIntradayData") + public AjaxResult getDeviceIntradayData(@RequestParam("deviceId") String deviceId) { + List resultList = getIntradayData(true); + DeviceRunStatistics statistics = null; + if (!CollectionUtils.isEmpty(resultList)) { + statistics = resultList.stream().filter(x -> deviceId.equals(x.getDeviceId())).findFirst().orElse(null); + } + return AjaxResult.success(statistics); + } - wrapper.ge(DeviceRunStatistics::getStartTime, start) - .lt(DeviceRunStatistics::getStartTime, end); + public List getIntradayData(Boolean day) { - List list = deviceRunStatisticsMapper.selectList(wrapper); + List list; + if (day) { + LambdaQueryWrapperX wrapper = new LambdaQueryWrapperX<>(); + LocalDateTime start = LocalDate.now().atStartOfDay(); // 今天 00:00:00 + LocalDateTime end = LocalDate.now().plusDays(1).atStartOfDay(); // 明天 00:00:00 + + wrapper.ge(DeviceRunStatistics::getStartTime, start) + .lt(DeviceRunStatistics::getStartTime, end); + + list = deviceRunStatisticsMapper.selectList(wrapper); + } else { + list = deviceRunStatisticsMapper.selectList(); + } List resultList = new ArrayList<>(); if (!CollectionUtils.isEmpty(list)) { @@ -184,7 +200,7 @@ public class DeviceController extends BaseController { @GetMapping("/generateOperationReport") public void generateOperationReport(HttpServletResponse response) throws UnsupportedEncodingException { - List resultList = getIntradayData(); + List resultList = getIntradayData(true); // ✅ 4. 响应头(下载) response.setContentType( "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); diff --git a/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/WorkRecordController.java b/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/WorkRecordController.java new file mode 100644 index 0000000..c6f842e --- /dev/null +++ b/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/WorkRecordController.java @@ -0,0 +1,92 @@ +package com.maibu.controller; + + +import com.maibu.core.business.WorkRecord; +import com.maibu.core.domain.R; +import com.maibu.service.impl.WorkRecordService; +import com.maibu.utils.MinioUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.io.InputStream; +import java.util.List; + + +@RestController +@RequestMapping("/iot/workRecord") +public class WorkRecordController { + + @Autowired + private MinioUtil minioUtil; + + @Autowired + private WorkRecordService workRecordService; + + + @PostMapping("/add") + public R addWorkRecord( + @RequestPart("file") MultipartFile file, // 接收上传的图片 + @RequestPart("workRecord") WorkRecord workRecord // 接收表单里的 JSON 对象 + ) { + int i = -1; + + WorkRecord workRecord1 = workRecordService.selectWorkRecordByWorkName(workRecord.getWorkName()); + if (workRecord1 != null) { + return R.fail("该任务已存在"); + } + + try (InputStream inputStream = file.getInputStream()) { + + String fileName = "routePlanImage/rt" + workRecord.getWorkName() + System.currentTimeMillis() + ".png"; + + // 上传到 MinIO + minioUtil.uploadFile(fileName, inputStream, "image/png"); + + // 获取访问 URL + String url = minioUtil.getPublicUrl(fileName); + System.out.println("✅ 图片上传成功,访问地址: " + url); + + // 这里可以把 URL 存到 workRecord 里 + workRecord.setImgUrl(url); + + i = workRecordService.addWorkRecord(workRecord); + } catch (Exception e) { + return R.fail("新增失败: " + e.getMessage()); + } + + return i <= 0 ? R.fail("新增失败") : R.ok("新增成功"); + } + + + @GetMapping("/selectByUserId") + public R selectWorkRecordByUserId(String userId) { + List workRecords = workRecordService.selectWorkRecordByUserId(userId); + return R.ok(workRecords); + } + + @GetMapping("/selectByWorkName") + public R selectWorkRecordByWorkName(String workName) { + WorkRecord workRecord = workRecordService.selectWorkRecordByWorkName(workName); + return R.ok(workRecord); + } + + @GetMapping("/deleteByWorkName") + public R deleteWorkRecordByWorkName(String workName) { + int i = workRecordService.deleteWorkRecordByWorkName(workName); + return i <= 0 ? R.fail("删除失败") : R.ok("删除成功"); + } + + @PostMapping("/update") + public R updateWorkRecord(@RequestBody WorkRecord workRecord) { + boolean b = workRecordService.updateWorkRecord(workRecord); + return !b ? R.fail("更新失败") : R.ok("更新成功"); + } + + @GetMapping("/selectBySiteId") + public R selectBySiteId(@RequestParam Long siteId) { + List workRecords = workRecordService.selectBySiteId(siteId); + return R.ok(workRecords); + } + +} diff --git a/maibu-service/maibu-iot-service/src/main/java/com/maibu/mapper/WorkRecordMapper.java b/maibu-service/maibu-iot-service/src/main/java/com/maibu/mapper/WorkRecordMapper.java deleted file mode 100644 index 9f9c1d3..0000000 --- a/maibu-service/maibu-iot-service/src/main/java/com/maibu/mapper/WorkRecordMapper.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.maibu.mapper; - - - -import com.maibu.core.business.WorkRecord; - -import java.util.List; - -public interface WorkRecordMapper { - public int insertWorkRecord(WorkRecord workRecord); - - public WorkRecord selectWorkRecordByWorkName(String workName); - - public WorkRecord selectWorkRecordById(Long id); - - public List selectWorkRecordByUserId(String workName); - - public int deleteWorkRecordByWorkName(String workName); - - public int updateWorkRecord(WorkRecord workRecord); - -} diff --git a/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/IWorkRecordService.java b/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/IWorkRecordService.java deleted file mode 100644 index 9b1c499..0000000 --- a/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/IWorkRecordService.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.maibu.service; - - - -import com.maibu.core.business.WorkRecord; - -import java.util.List; - -public interface IWorkRecordService { - - public int addWorkRecord(WorkRecord workRecord) throws Exception; - - public WorkRecord selectWorkRecordByWorkName(String workName); - - public List selectWorkRecordByUserId(String workName); - - public int deleteWorkRecordByWorkName(String workName); - - public int updateWorkRecord(WorkRecord workRecord); -} diff --git a/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/DeviceServiceImpl.java b/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/DeviceServiceImpl.java index e960a51..6692574 100644 --- a/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/DeviceServiceImpl.java +++ b/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/DeviceServiceImpl.java @@ -1,20 +1,20 @@ package com.maibu.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.maibu.core.business.Device; -import com.maibu.core.business.DevicePlan; -import com.maibu.core.business.DeviceRunningStatusHistory; -import com.maibu.core.business.DeviceStatusRecordDTO; +import com.maibu.core.business.*; import com.maibu.core.business.dto.DeviceBindDTO; -import com.maibu.core.business.uav.IotUAVDevice; import com.maibu.core.domain.AjaxResult; import com.maibu.core.domain.entity.SysRole; +import com.maibu.core.domain.entity.SysSite; import com.maibu.core.domain.model.LoginUser; import com.maibu.core.enums.DeviceTaskStaus; import com.maibu.core.redis.RedisCache; import com.maibu.mapper.DeviceMapper; import com.maibu.mapper.DevicePlanMapper; import com.maibu.mapper.DeviceStatusHistoryMapper; +import com.maibu.mapper.SysSiteMapper; +import com.maibu.memory.GlobalMemory; +import com.maibu.memory.SiteMemory; import com.maibu.service.IDeviceService; import com.maibu.service.ISysRoleService; import com.maibu.utils.SecurityUtils; @@ -29,6 +29,7 @@ import org.springframework.util.CollectionUtils; import javax.annotation.Resource; import java.time.LocalDateTime; import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; @@ -55,7 +56,8 @@ public class DeviceServiceImpl implements IDeviceService { @Autowired private ISysRoleService roleService; - + @Autowired + private SysSiteMapper sysSiteMapper; /** @@ -227,17 +229,17 @@ public class DeviceServiceImpl implements IDeviceService { @Override - public boolean bind(DeviceBindDTO bindDTO,String username) { + public boolean bind(DeviceBindDTO bindDTO, String username) { try { List deviceIds = bindDTO.getDeviceIds(); LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); - queryWrapper.in(Device::getSerialNumber,deviceIds); - List list =deviceMapper.selectList(queryWrapper); + queryWrapper.in(Device::getSerialNumber, deviceIds); + List list = deviceMapper.selectList(queryWrapper); if (CollectionUtils.isEmpty(list)) { return false; } else { list.forEach(device -> { - if(bindDTO.getUserId()!=null){ + if (bindDTO.getUserId() != null) { device.setTenantId(bindDTO.getUserId()); } device.setOrgId(bindDTO.getOrgId()); @@ -254,11 +256,11 @@ public class DeviceServiceImpl implements IDeviceService { } @Override - public boolean unbind(DeviceBindDTO dto,String username) { + public boolean unbind(DeviceBindDTO dto, String username) { List deviceIds = dto.getDeviceIds(); if (!CollectionUtils.isEmpty(deviceIds)) { LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); - queryWrapper.in(Device::getSerialNumber,deviceIds); + queryWrapper.in(Device::getSerialNumber, deviceIds); List list = deviceMapper.selectList(queryWrapper); if (!CollectionUtils.isEmpty(list)) { list.forEach(x -> { @@ -279,7 +281,7 @@ public class DeviceServiceImpl implements IDeviceService { } @Override - public List getSiteList(LoginUser loginUser,Device device) { + public List getSiteList(LoginUser loginUser, Device device) { SysRole sysRole = roleService.selectRoleById(loginUser.getRoleId()); List deviceList = new ArrayList<>(); if (sysRole != null) { @@ -293,11 +295,66 @@ public class DeviceServiceImpl implements IDeviceService { deviceList = deviceMapper.selectDeviceList(device); } } + Map statusStatistics = new HashMap<>(); + if (device.getOrgId() == null) { + SysSite site = sysSiteMapper.selectById(device.getSiteId()); + if (site != null) { + device.setOrgId(site.getOrgId()); + } + } + SiteMemory siteMemory = GlobalMemory.getSiteMemory(device.getOrgId(), device.getSiteId()); + if (siteMemory != null) { + Integer work = 0; + Integer free = 0; + if (!CollectionUtils.isEmpty(deviceList)) { + List ids = deviceList.stream().map(Device::getDeviceName).collect(Collectors.toList()); + List allStatusList = deviceStatusHistoryMapper.selectLatestByDeviceIds(ids); + for (Device x : deviceList) { + if (siteMemory.hasTask(x.getSerialNumber())) { + work += 1; + x.setFeStatus(1); + } else { + free += 1; + x.setFeStatus(2); + } + String key = "running_status:" + x.getDeviceName(); + DeviceStatusRecordDTO recordDTO = redisCache.getCacheObject(key); + DeviceRunningStatusHistory lastRunningStatus = null; + if (recordDTO != null && !CollectionUtils.isEmpty(recordDTO.getHistories())) { + List list = recordDTO.getHistories().stream().filter(y -> !"0".equals(y.getQual())).collect(Collectors.toList()); + if (!CollectionUtils.isEmpty(list)) { + lastRunningStatus = list.get(list.size() - 1); + } + } + if (lastRunningStatus == null) { + if (!CollectionUtils.isEmpty(allStatusList)) { + Map> statusMap = + allStatusList.stream() + .collect(Collectors.groupingBy(DeviceRunningStatusHistory::getDeviceId)); + List list = statusMap.get(x.getDeviceName()); + if (!CollectionUtils.isEmpty(list)) { + List l = list.stream().filter(y -> !"0".equals(y.getQual())).collect(Collectors.toList()); + if (!CollectionUtils.isEmpty(l)) { + lastRunningStatus = l.get(l.size() - 1); + } + } + } + } + x.setLastRunningStatus(lastRunningStatus); + } + statusStatistics.put(0, work); + statusStatistics.put(1, free); + deviceList.forEach(y -> { + y.setStatusStatistics(statusStatistics); + }); + } + } + deviceList.sort(Comparator.comparing(Device::getFeStatus)); return deviceList; } @Override - public List getDeviceList(LoginUser loginUser,Device device) { + public List getDeviceList(LoginUser loginUser, Device device) { SysRole sysRole = roleService.selectRoleById(loginUser.getRoleId()); List deviceList = new ArrayList<>(); if (sysRole != null) { @@ -315,14 +372,11 @@ public class DeviceServiceImpl implements IDeviceService { // } else { // deviceList = deviceMapper.selectDeviceList(device); // } - deviceList = deviceMapper.selectDeviceList(device); + deviceList = deviceMapper.selectDeviceList(device); } } return deviceList; } - - - } diff --git a/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/WorkRecordService.java b/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/WorkRecordService.java new file mode 100644 index 0000000..1d59655 --- /dev/null +++ b/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/WorkRecordService.java @@ -0,0 +1,54 @@ +package com.maibu.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.maibu.core.business.WorkRecord; +import com.maibu.mapper.WorkRecordMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class WorkRecordService { + + @Autowired + private WorkRecordMapper workRecordMapper; + + + public int addWorkRecord(WorkRecord workRecord) throws Exception { + int i = workRecordMapper.insert(workRecord); +// int i = workRecordMapper.insertWorkRecord(workRecord); + return i; + } + + public WorkRecord selectWorkRecordByWorkName(String workName) { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + queryWrapper.eq(WorkRecord::getWorkName, workName); + return workRecordMapper.selectOne(queryWrapper); + } + + public List selectWorkRecordByUserId(String userId) { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + queryWrapper.eq(WorkRecord::getUserId, userId); + return workRecordMapper.selectList(queryWrapper); + } + + + public int deleteWorkRecordByWorkName(String workName) { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + queryWrapper.eq(WorkRecord::getWorkName, workName); + return workRecordMapper.delete(queryWrapper); + } + + + public boolean updateWorkRecord(WorkRecord workRecord) { + return workRecordMapper.saveOrUpdate(workRecord); + } + + + public List selectBySiteId(Long siteId) { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + queryWrapper.eq(WorkRecord::getSiteId, siteId); + return workRecordMapper.selectList(queryWrapper); + } +} diff --git a/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/WorkRecordServiceImpl.java b/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/WorkRecordServiceImpl.java deleted file mode 100644 index 6c927f4..0000000 --- a/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/WorkRecordServiceImpl.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.maibu.service.impl; - -import com.maibu.core.business.WorkRecord; -import com.maibu.mapper.WorkRecordMapper; -import com.maibu.service.IWorkRecordService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.util.List; - -@Service -public class WorkRecordServiceImpl implements IWorkRecordService { - - @Autowired - private WorkRecordMapper workRecordMapper; - - - - @Override - public int addWorkRecord(WorkRecord workRecord) throws Exception { - int i = workRecordMapper.insertWorkRecord(workRecord); - return i; - } - - @Override - public WorkRecord selectWorkRecordByWorkName(String workName) { - WorkRecord workRecord = workRecordMapper.selectWorkRecordByWorkName(workName); - return workRecord; - } - - @Override - public List selectWorkRecordByUserId(String workName) { - List workRecordList = workRecordMapper.selectWorkRecordByUserId(workName); - return workRecordList; - } - - @Override - public int deleteWorkRecordByWorkName(String workName) { - int i = workRecordMapper.deleteWorkRecordByWorkName(workName); - return i; - } - - @Override - public int updateWorkRecord(WorkRecord workRecord) { - int i = workRecordMapper.updateWorkRecord(workRecord); - return i; - } -} diff --git a/maibu-service/maibu-iot-service/src/main/resources/mapper/iot/WorkRecordMapper.xml b/maibu-service/maibu-iot-service/src/main/resources/mapper/iot/WorkRecordMapper.xml deleted file mode 100644 index 76de8c5..0000000 --- a/maibu-service/maibu-iot-service/src/main/resources/mapper/iot/WorkRecordMapper.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - insert into iot_work_record(work_name, user_id, json_data, img_url) - values (#{workName}, #{userId}, #{jsonData}, #{imgUrl}) - - - - - - - - - - delete - from iot_work_record - where work_name = #{workName} - - - - update iot_work_record - set work_name=#{workName}, - user_id= #{userId}, - json_data=#{jsonData}, - img_url= #{imgUrl} - where id = #{id} - - - - \ No newline at end of file