This commit is contained in:
2026-04-17 10:42:16 +08:00
parent 17c52c978c
commit d26dde07d7
64 changed files with 4737 additions and 17 deletions

View File

@@ -0,0 +1,16 @@
package com.fastbee.service;
import org.springframework.stereotype.Service;
import java.util.LinkedList;
import java.util.Queue;
@Service
public class DevicePathService {
}

View File

@@ -0,0 +1,275 @@
package com.fastbee.service;
import com.alibaba.fastjson2.JSON;
import com.fastbee.common.NettyCacheKey;
import com.fastbee.dto.DeviceErrorPushDTO;
import com.fastbee.dto.DeviceErrorPushDetail;
import com.fastbee.dto.NettyDevice;
import com.fastbee.enums.RespondCode;
import com.fastbee.iot.domain.*;
import com.fastbee.iot.enums.DeviceTaskPlanRepeatType;
import com.fastbee.iot.enums.DeviceTaskStaus;
import com.fastbee.iot.mapper.DevicePlanMapper;
import com.fastbee.iot.mapper.DevicePlanTaskMapper;
import com.fastbee.iot.mapper.WorkRecordMapper;
import com.fastbee.iot.model.WorkRecord;
import com.fastbee.manager.DeviceSessionManager;
import com.fastbee.memory.GlobalMemory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
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;
@Slf4j
@Service
public class DevicePlanTaskMonitorService {
@Autowired
private GlobalMemory globalMemory;
@Autowired
private DevicePlanTaskMapper devicePlanTaskMapper;
@Autowired
private DevicePlanMapper devicePlanMapper;
@Autowired
private DeviceSessionManager deviceSessionManager;
@Autowired
private WorkRecordMapper workRecordMapper;
/**
* 计划迟的任务生成机器执行任务
*/
public void generatePlanTask() throws InterruptedException {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(() -> {
try {
Map<String, List<DevicePlan>> planMap = GlobalMemory.devicePlanMap;
if (!CollectionUtils.isEmpty(planMap.values())) {
Iterator<String> iterator = planMap.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
List<DevicePlan> list = planMap.get(key);
if (!CollectionUtils.isEmpty(list)) {
list.forEach(this::createPlanTask);
}
}
}
} catch (Exception e) {
log.error("执行任务生成线程错误", e);
}
}, 0, 1000, TimeUnit.MILLISECONDS);
}
private void createPlanTask(DevicePlan devicePlan) {
if (devicePlan.isDayTriggerFlag()) return; //当天应该创建的全部创建完
DeviceTaskPlanRule rules = devicePlan.getDeviceTaskPlanRules();
if (rules != null) {
DeviceTaskPlanRepeatType type = rules.getType();
switch (type) {
case DAY:
dayPlan(devicePlan);
break;
case WEEK:
weekPlan(devicePlan);
break;
case MONTH:
monthPlan(devicePlan);
break;
// case ONCE:
// oncePlan(devicePlan);
// break;
}
}
}
public void dayPlan(DevicePlan devicePlan) {
DeviceTaskPlanRule rules = devicePlan.getDeviceTaskPlanRules();
LocalTime nowTime = LocalTime.now();
LocalTime dayTime = LocalTime.parse(rules.getDayTime());
if (nowTime.isAfter(dayTime)) {
DevicePlanTask devicePlanTask = new DevicePlanTask();
devicePlanTask.setPlanId(devicePlan.getId());
devicePlanTask.setDeviceId(devicePlan.getDeviceId());
devicePlanTask.setTaskStaus(DeviceTaskStaus.NEW);
devicePlanTask.setRouteId(devicePlan.getRouteId());
devicePlanTask.setCreateTime(LocalDateTime.now());
devicePlanTask.setTaskType("");//待拓展任务类型
devicePlanTaskMapper.insert(devicePlanTask);
globalMemory.addDevicePlanPrepare(devicePlanTask);
//啥时候重置?每日0点?
devicePlan.setDayTriggerFlag(true);
devicePlan.setUpdateTime(LocalDateTime.now());
devicePlan.setTaskStaus(DeviceTaskStaus.EXECUTING);
//todo 怎么判断任务全部排完了?排完了就删除
LocalDate today = LocalDate.now(); // 获取当前日期(系统时区)
LocalDate endTime = rules.getEndTime();
if (endTime != null && endTime.isEqual(today)) {
devicePlan.setFinishTime(LocalDateTime.now());
devicePlan.setTaskStaus(DeviceTaskStaus.FINISH);
GlobalMemory.removeDevicePlan(devicePlan);
}
devicePlanMapper.updateById(devicePlan);
}
}
public void weekPlan(DevicePlan devicePlan) {
DeviceTaskPlanRule rules = devicePlan.getDeviceTaskPlanRules();
LocalTime nowTime = LocalTime.now();
List<DayOfWeek> days = devicePlan.getDeviceTaskPlanRules().getDays();
// 1. 获取当前日期
LocalDate today = LocalDate.now();
DayOfWeek dayOfWeek = today.getDayOfWeek();
LocalTime dayTime = LocalTime.parse(rules.getDayTime());
if (!CollectionUtils.isEmpty(days) && days.contains(dayOfWeek) && nowTime.isAfter(dayTime)) {
DevicePlanTask devicePlanTask = new DevicePlanTask();
devicePlanTask.setPlanId(devicePlan.getId());
devicePlanTask.setDeviceId(devicePlan.getDeviceId());
devicePlanTask.setTaskStaus(DeviceTaskStaus.NEW);
devicePlanTask.setRouteId(devicePlan.getRouteId());
devicePlanTask.setCreateTime(LocalDateTime.now());
devicePlanTask.setTaskType("");//待拓展任务类型
devicePlanTaskMapper.insert(devicePlanTask);
globalMemory.addDevicePlanPrepare(devicePlanTask);
//啥时候重置?每日0点?
devicePlan.setDayTriggerFlag(true);
devicePlan.setUpdateTime(LocalDateTime.now());
devicePlan.setTaskStaus(DeviceTaskStaus.EXECUTING);
//todo 怎么判断任务全部排完了?排完了就删除
LocalDate endTime = rules.getEndTime();
if (endTime != null && endTime.isEqual(today)) {
devicePlan.setFinishTime(LocalDateTime.now());
devicePlan.setTaskStaus(DeviceTaskStaus.FINISH);
GlobalMemory.removeDevicePlan(devicePlan);
}
devicePlanMapper.updateById(devicePlan);
}
}
public void monthPlan(DevicePlan devicePlan) {
DeviceTaskPlanRule rules = devicePlan.getDeviceTaskPlanRules();
List<Integer> dayOfMonthList = rules.getDayOfMonth();
LocalDate today = LocalDate.now();
LocalTime nowTime = LocalTime.now();
int dayOfMonth = today.getDayOfMonth();
LocalTime dayTime = LocalTime.parse(rules.getDayTime());
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());
devicePlanTask.setCreateTime(LocalDateTime.now());
devicePlanTask.setTaskType("");//待拓展任务类型
devicePlanTaskMapper.insert(devicePlanTask);
globalMemory.addDevicePlanPrepare(devicePlanTask);
//啥时候重置?每日0点?
devicePlan.setDayTriggerFlag(true);
devicePlan.setUpdateTime(LocalDateTime.now());
devicePlan.setTaskStaus(DeviceTaskStaus.EXECUTING);
//todo 怎么判断任务全部排完了?排完了就删除
LocalDate endTime = rules.getEndTime();
if (endTime != null && endTime.isEqual(today)) {
devicePlan.setFinishTime(LocalDateTime.now());
devicePlan.setTaskStaus(DeviceTaskStaus.FINISH);
GlobalMemory.removeDevicePlan(devicePlan);
}
devicePlanMapper.updateById(devicePlan);
}
}
public void oncePlan(DevicePlan devicePlan) {
// DeviceTaskPlanRule rules = devicePlan.getDeviceTaskPlanRules();
}
public void doLoop() throws InterruptedException {
//prepare 进执行execute的逻辑
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(() -> {
try {
Map<String, List<DevicePlanTask>> planMap = GlobalMemory.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<DevicePlanTask> 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)) {
GlobalMemory.addDevicePlanExecute(devicePlanTask);
device.setCurrentTaskId(devicePlanTask.getId());
GlobalMemory.removeDevicePlanPrepare(devicePlanTask);
}
}
}
}
});
}
} catch (Exception e) {
log.error("执行任务prepare线程错误", e);
}
}, 0, 1000, TimeUnit.MILLISECONDS);
}
public void doExecute() {
//prepare 进执行execute的逻辑
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(() -> {
try {
Map<String, DevicePlanTask> planMap = GlobalMemory.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
}
}
}
});
}
} catch (Exception e) {
log.error("执行任务execute线程错误", e);
}
}, 0, 1000, TimeUnit.MILLISECONDS);
}
}

View File

@@ -0,0 +1,347 @@
package com.fastbee.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fastbee.common.core.domain.model.LoginUser;
import com.fastbee.dto.DevicePlanStatisticsDTO;
import com.fastbee.dto.DevicePlanTaskStatisticsDTO;
import com.fastbee.dto.DeviceTaskQueryDTO;
import com.fastbee.dto.DeviceWorkStatisticsDTO;
import com.fastbee.iot.domain.Device;
import com.fastbee.iot.domain.DevicePlan;
import com.fastbee.iot.domain.DevicePlanTask;
import com.fastbee.iot.domain.DeviceTaskPlanRule;
import com.fastbee.iot.enums.DeviceTaskStaus;
import com.fastbee.iot.mapper.DeviceMapper;
import com.fastbee.iot.mapper.DevicePlanMapper;
import com.fastbee.iot.mapper.DevicePlanTaskMapper;
import com.fastbee.iot.mapper.WorkRecordMapper;
import com.fastbee.iot.model.WorkRecord;
import com.fastbee.memory.GlobalMemory;
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 org.springframework.web.bind.annotation.RequestParam;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
@Service
@Slf4j
public class DeviceTaskService {
@Autowired
private DevicePlanMapper devicePlanMapper;
@Autowired
private DevicePlanTaskMapper devicePlanTaskMapper;
@Autowired
private DeviceMapper deviceMapper;
@Autowired
private WorkRecordMapper workRecordMapper;
public int insertOrUpdate(DevicePlan devicePlan, LoginUser loginUser) {
Long id = devicePlan.getId();
if (id != null) {
devicePlan.setUpdateBy(loginUser.getUsername());
devicePlan.setUpdateTime(LocalDateTime.now());
transferDays(devicePlan);
int i = devicePlanMapper.updateById(devicePlan);
GlobalMemory.addDevicePlan(devicePlan);
return i;
} else {
devicePlan.setTaskStaus(DeviceTaskStaus.NEW);
devicePlan.setCreateTime(LocalDateTime.now());
devicePlan.setCreateBy(loginUser.getUsername());
transferDays(devicePlan);
int i = devicePlanMapper.insert(devicePlan);
GlobalMemory.addDevicePlan(devicePlan);
return i;
}
}
public void transferDays(DevicePlan devicePlan) {
DeviceTaskPlanRule deviceTaskPlanRules = devicePlan.getDeviceTaskPlanRules();
if (deviceTaskPlanRules != null && !CollectionUtils.isEmpty(deviceTaskPlanRules.getDays())) {
List<String> days = new ArrayList<>();
deviceTaskPlanRules.getDays().forEach(x -> {
String day = null;
switch (x) {
case MONDAY:
day = "周一";
break;
case TUESDAY:
day = "周二";
break;
case WEDNESDAY:
day = "周三";
break;
case THURSDAY:
day = "周四";
break;
case FRIDAY:
day = "周五";
break;
case SATURDAY:
day = "周六";
break;
case SUNDAY:
day = "周日";
break;
}
days.add(day);
});
devicePlan.getDeviceTaskPlanRules().setDaysTranslate(days);
}
}
public List<DevicePlan> getDeviceTaskByUser(Long userId) {
if (userId != null) {
LambdaQueryWrapper<DevicePlan> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(DevicePlan::getUserId, userId);
return transferDevicePlanData(devicePlanMapper.selectList(queryWrapper));
} else {
return new ArrayList<>();
}
}
public List<DevicePlan> getDeviceTask(DeviceTaskQueryDTO dto) {
if (dto != null) {
LambdaQueryWrapper<DevicePlan> queryWrapper = new LambdaQueryWrapper<>();
if (dto.getUserId() != null) {
queryWrapper.eq(DevicePlan::getUserId, dto.getUserId());
}
if (dto.getDeviceId() != null) {
queryWrapper.eq(DevicePlan::getDeviceId, dto.getDeviceId());
}
if (dto.getTaskStaus() != null) {
queryWrapper.eq(DevicePlan::getTaskStaus, dto.getTaskStaus());
}
if (dto.getPlanName() != null) {
queryWrapper.like(DevicePlan::getPlanName, dto.getPlanName());
}
queryWrapper.eq(DevicePlan::getDelFlag, 0);
List<DevicePlan> list = devicePlanMapper.selectList(queryWrapper);
if (!CollectionUtils.isEmpty(list)) {
list.forEach(x -> {
Device device = deviceMapper.selectDeviceBySerialNumber(x.getDeviceId());
if (device != null) {
x.setDeviceAlias(device.getDeviceAlias());
}
});
}
return transferDevicePlanData(list);
} else {
return new ArrayList<>();
}
}
public int delete(Long id) {
DevicePlan planTask = devicePlanMapper.selectById(id);
if (planTask != null) {
planTask.setDelFlag(1);
GlobalMemory.removeDevicePlan(planTask);
return devicePlanMapper.updateById(planTask);
}
return 0;
}
public void start(Long id, LoginUser loginUser) {
if (id != null) {
DevicePlan planTask = devicePlanMapper.selectById(id);
if (planTask != null) {
planTask.setTaskStaus(DeviceTaskStaus.EXECUTING);
planTask.setUpdateTime(LocalDateTime.now());
planTask.setUpdateBy(loginUser.getUsername());
devicePlanMapper.updateById(planTask);
}
}
}
public List<DevicePlanStatisticsDTO> getDevicePlanStatistics(Long userId) {
List<DevicePlanStatisticsDTO> list = new ArrayList<>();
LocalDate today = LocalDate.now();
LocalDateTime monthStart = LocalDateTime.of(
today.getYear(), // 当前年
today.getMonth(), // 当前月
1, // 当月第一天
0, 0, 0, 0 // 时:分:秒:纳秒(00:00:00.000)
);
LocalDate lastDayOfMonth = today.withDayOfMonth(today.lengthOfMonth()); // 获取当月最后一天
LocalDateTime monthEnd = LocalDateTime.of(
lastDayOfMonth.getYear(),
lastDayOfMonth.getMonth(),
lastDayOfMonth.getDayOfMonth(),
23, 59, 59, 999_999_999 // 时:分:秒:纳秒(23:59:59.999)
);
LambdaQueryWrapper<DevicePlan> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.ge(DevicePlan::getCreateTime, monthStart)
.le(DevicePlan::getCreateTime, monthEnd)
.eq(DevicePlan::getUserId,userId);
List<DevicePlan> devicePlans = transferDevicePlanData(devicePlanMapper.selectList(queryWrapper));
if (!CollectionUtils.isEmpty(devicePlans)) {
List<LocalDate> dates = getMonthDays();
for (LocalDate date : dates) {
List<DevicePlan> plans = devicePlans.stream().filter(x -> x.getCreateTime().toLocalDate().equals(date)).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(plans)) {
DevicePlanStatisticsDTO dto = new DevicePlanStatisticsDTO();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M.d");
dto.setName(formatter.format(date));
long count = plans.stream().filter(x -> DeviceTaskStaus.FINISH.equals(x.getTaskStaus())).count();
dto.setCompleted((int) count);
dto.setPlanned(plans.size());
list.add(dto);
}
}
}
return list;
}
public List<LocalDate> getMonthDays() {
LocalDate today = LocalDate.now();
int totalDays = today.lengthOfMonth();
LocalDate firstDayOfMonth = LocalDate.of(today.getYear(), today.getMonth(), 1);
List<LocalDate> allDaysOfCurrentMonth = new ArrayList<>();
for (int i = 0; i < totalDays; i++) {
// 每次累加1天,获取当月每一天
LocalDate currentDay = firstDayOfMonth.plusDays(i);
allDaysOfCurrentMonth.add(currentDay);
}
return allDaysOfCurrentMonth;
}
public List<DevicePlanTaskStatisticsDTO> getDevicePlanTaskStatistics(Long userId) {
List<DevicePlanTaskStatisticsDTO> list = new ArrayList<>();
// 1. 获取当前日期
LocalDate today = LocalDate.now();
// 2. 构造当前月份的起始时间:当月第一天 00:00:00
LocalDateTime monthStart = LocalDateTime.of(
today.getYear(), // 当前年
today.getMonth(), // 当前月
1, // 当月第一天
0, 0, 0, 0 // 时:分:秒:纳秒(00:00:00.000)
);
// 3. 构造当前月份的结束时间:当月最后一天 23:59:59.999
LocalDate lastDayOfMonth = today.withDayOfMonth(today.lengthOfMonth()); // 获取当月最后一天
LocalDateTime monthEnd = LocalDateTime.of(
lastDayOfMonth.getYear(),
lastDayOfMonth.getMonth(),
lastDayOfMonth.getDayOfMonth(),
23, 59, 59, 999_999_999 // 时:分:秒:纳秒(23:59:59.999)
);
// 4. 构建 LambdaQueryWrapper 进行范围查询
LambdaQueryWrapper<DevicePlan> query = new LambdaQueryWrapper<>();
query.eq(DevicePlan::getUserId,userId);
List<DevicePlan> devicePlans = transferDevicePlanData(devicePlanMapper.selectList(query));
if(CollectionUtils.isEmpty(devicePlans)) return new ArrayList<>();
List<Long> planIds = devicePlans.stream().map(DevicePlan::getId).collect(Collectors.toList());
if(CollectionUtils.isEmpty(planIds)) return new ArrayList<>();
LambdaQueryWrapper<DevicePlanTask> queryWrapper = new LambdaQueryWrapper<>();
// 核心:筛选 createTime 大于等于起始时间,且小于等于结束时间
queryWrapper.ge(DevicePlanTask::getCreateTime, monthStart)
.le(DevicePlanTask::getCreateTime, monthEnd)
.in(DevicePlanTask::getPlanId,planIds);
List<DevicePlanTask> devicePlanTasks = transferDeviceTaskData(devicePlanTaskMapper.selectList(queryWrapper));
if (!CollectionUtils.isEmpty(devicePlanTasks)) {
List<LocalDate> dates = getMonthDays();
for (LocalDate date : dates) {
List<DevicePlanTask> planTasks = devicePlanTasks.stream().filter(x -> x.getCreateTime().toLocalDate().equals(date)).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(planTasks)) {
DevicePlanTaskStatisticsDTO dto = new DevicePlanTaskStatisticsDTO();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M.d");
dto.setDate(formatter.format(date));
long finishCount = planTasks.stream().filter(x -> DeviceTaskStaus.FINISH.equals(x.getTaskStaus())).count();
dto.setSuccess((int) finishCount);
long failedCount = planTasks.stream().filter(x -> DeviceTaskStaus.FAILED.equals(x.getTaskStaus())).count();
dto.setFailed((int) failedCount);
long pauseCount = planTasks.stream().filter(x -> DeviceTaskStaus.PAUSE.equals(x.getTaskStaus())).count();
dto.setPaused((int) pauseCount);
list.add(dto);
}
}
}
return list;
}
public WorkRecord concurrentDevicePlanTask(String deviceId) {
LambdaQueryWrapper<DevicePlanTask> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(DevicePlanTask::getDeviceId, deviceId)
.eq(DevicePlanTask::getTaskStaus, DeviceTaskStaus.EXECUTING);
List<DevicePlanTask> devicePlanTasks = devicePlanTaskMapper.selectList(queryWrapper);
Long routId = CollectionUtils.isEmpty(devicePlanTasks) ? null : devicePlanTasks.get(0).getRouteId();
return routId == null ? null : workRecordMapper.selectWorkRecordById(routId);
}
public List<DeviceWorkStatisticsDTO> workStatistics(Long userId) {
//todo update
List<DeviceWorkStatisticsDTO> result = new ArrayList<>();
Random random = new Random();
int times = random.nextInt(100);
int s = random.nextInt(1000);
DeviceWorkStatisticsDTO dto = new DeviceWorkStatisticsDTO();
dto.setLabel("割草次数");
dto.setValue(times);
DeviceWorkStatisticsDTO dto2 = new DeviceWorkStatisticsDTO();
dto2.setLabel("割草时长(s)");
dto2.setValue(s);
DeviceWorkStatisticsDTO dto3 = new DeviceWorkStatisticsDTO();
dto3.setLabel("割草面积(m2)");
dto3.setValue(s * 5);
result.add(dto);
result.add(dto2);
result.add(dto3);
return result;
}
public List<DevicePlanTask> deviceTaskPool(DeviceTaskQueryDTO dto) {
List<DevicePlanTask> list = new ArrayList<>();
GlobalMemory.devicePlanTaskPrepareMap.values().forEach(list::addAll);
list.addAll(GlobalMemory.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());
}
}
return transferDeviceTaskData(list);
}
public List<DevicePlan> transferDevicePlanData(List<DevicePlan> list) {
if (CollectionUtils.isEmpty(list)) return list;
list.forEach(x -> {
DeviceTaskStaus taskStaus = x.getTaskStaus();
x.setTaskStausTranslate(taskStaus.getDescription());
});
return list;
}
public List<DevicePlanTask> transferDeviceTaskData(List<DevicePlanTask> list) {
if (CollectionUtils.isEmpty(list)) return list;
list.forEach(x -> {
DeviceTaskStaus taskStaus = x.getTaskStaus();
x.setTaskStausTranslate(taskStaus.getDescription());
});
return list;
}
}

View File

@@ -0,0 +1,166 @@
package com.fastbee.service;
import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson2.JSON;
import com.fastbee.common.CommandConstant;
import com.fastbee.common.NettyCacheKey;
import com.fastbee.common.core.redis.RedisCache;
import com.fastbee.dto.DeviceErrorPushDTO;
import com.fastbee.dto.DeviceErrorPushDetail;
import com.fastbee.dto.NettyDevice;
import com.fastbee.iot.domain.DeviceRunningStatusHistory;
import com.fastbee.entity.ErrorIdentificationStandard;
import com.fastbee.enums.CompareEnum;
import com.fastbee.enums.RespondCode;
import com.fastbee.iot.domain.DeviceStatusRecordDTO;
import com.fastbee.manager.DeviceSessionManager;
import com.fastbee.mapper.ErrorIdentificationStandardMapper;
import com.fastbee.memory.GlobalMemory;
import com.fastbee.netty.handler.DeviceConnectHandler;
import com.fastbee.utils.CommandUtils;
import com.fastbee.utils.CompareUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
public class DeviceThreadService {
@Autowired
private ResourceLoader resourceLoader;
@Autowired
private GlobalMemory globalMemory;
@Autowired
private RedisCache redisCache;
@Autowired
private DeviceSessionManager sessionManager;
@Autowired
private ErrorIdentificationStandardMapper standardMapper;
public void deviceErrorMonitor() throws InterruptedException, IOException {
initStandard();
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(() -> {
try {
String key = NettyCacheKey.deviceRunningStatusKey;
Collection<String> keys = redisCache.getListKeyByPrefix(key);
if (!CollectionUtils.isEmpty(keys)) {
keys.forEach(k -> {
DeviceStatusRecordDTO recordDTO = redisCache.getCacheObject(k);
if (recordDTO != null && !CollectionUtils.isEmpty(recordDTO.getHistories())) {
recordDTO.getHistories().sort(Comparator.comparing(DeviceRunningStatusHistory::getCreateTime).reversed());
DeviceRunningStatusHistory history = recordDTO.getHistories().get(0);
List<DeviceErrorPushDetail> compared = compareErrorStandard(history, globalMemory.standard);
String[] parts = k.split(":");
String deviceId = parts[1];
DeviceErrorPushDTO pushDTO = new DeviceErrorPushDTO();
pushDTO.setDeviceId(deviceId);
pushDTO.setTime(System.currentTimeMillis());
pushDTO.setDetails(compared);
pushDTO.setEvent(RespondCode.device_error_push);
//todo push 推送到前端
pushErrorMessage(deviceId, JSON.toJSONString(pushDTO));
}
});
}
} catch (Exception e) {
log.error("执行监测错误线程错误:{}", e.getMessage());
}
}, 0, 2, TimeUnit.MINUTES);
}
public void initStandard() throws IOException {
if (globalMemory.standard == null) {
List<ErrorIdentificationStandard> standards = standardMapper.selectList();
if (CollectionUtils.isEmpty(standards)) {
// 读取resource目录下的device-config.json文件
Resource resource = resourceLoader.getResource("classpath:errorStandard.json");
// 使用fastjson2转换为DeviceConfig对象
String jsonContent = IoUtil.readUtf8(resource.getInputStream());
globalMemory.standard = JSON.parseArray(jsonContent, ErrorIdentificationStandard.class);
} else {
globalMemory.standard = standards;
}
}
}
public void pushErrorMessage(String deviceId, String dto) {
NettyDevice device = sessionManager.getDevice(deviceId);
if (device != null) {
ByteBuf buf = Unpooled.buffer();
CommandUtils.buildCommand(buf, dto, CommandConstant.interaction);
if (device.getChannel() != null && device.getChannel().isActive()) {
device.getChannel().writeAndFlush(buf);
}
}
}
public List<DeviceErrorPushDetail> compareErrorStandard(DeviceRunningStatusHistory history, List<ErrorIdentificationStandard> standards) {
if (history == null || CollectionUtils.isEmpty(standards)) return null;
List<DeviceErrorPushDetail> list = new ArrayList<>();
standards.forEach(standard -> {
String fieldName = standard.getField();
String compareValues = standard.getCompareValues();
CompareEnum compareType = standard.getCompareType();
String targetValue = knownClassFieldFinding(fieldName, history);
if (!StringUtils.isEmpty(compareValues) && !StringUtils.isEmpty(targetValue)) {
boolean result = CompareUtils.compare(compareType, compareValues, targetValue);
if (!result) {
DeviceErrorPushDetail detail = new DeviceErrorPushDetail();
detail.setErrorName(standard.getErrorName());
detail.setDescription(standard.getErrorDescription());
detail.setValue(targetValue);
detail.setRange(compareValues);
list.add(detail);
}
}
});
return list;
}
private static String knownClassFieldFinding(String fieldName, DeviceRunningStatusHistory history) {
try {
// 1. 获取类的Class对象
Class<?> historyClass = DeviceRunningStatusHistory.class;
Field field = historyClass.getDeclaredField(fieldName);
field.setAccessible(true);
Object value = field.get(history);
return (String) value;
} catch (NoSuchFieldException | IllegalAccessException e) {
System.out.println("获取字段失败: " + e.getMessage());
log.error("获取属性值失败:{}", e.getMessage());
}
return null;
}
}

View File

@@ -0,0 +1,44 @@
package com.fastbee.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fastbee.iot.domain.DeviceRunningStatusHistory;
import com.fastbee.entity.ErrorIdentificationStandard;
import com.fastbee.iot.mapper.DeviceStatusHistoryMapper;
import com.fastbee.mapper.ErrorIdentificationStandardMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@Slf4j
public class NettyDeviceService {
@Autowired
private DeviceStatusHistoryMapper deviceStatusHistoryMapper;
@Autowired
private ErrorIdentificationStandardMapper errorIdentificationStandardMapper;
public List<DeviceRunningStatusHistory> statusHistory(DeviceRunningStatusHistory history) {
LambdaQueryWrapper<DeviceRunningStatusHistory> queryWrapper = new LambdaQueryWrapper<>();
if (!StringUtils.isEmpty(history.getDeviceId())) {
queryWrapper.eq(DeviceRunningStatusHistory::getDeviceId, history.getDeviceId());
}
return deviceStatusHistoryMapper.selectList(queryWrapper);
}
public List<ErrorIdentificationStandard> allErrorIdentificationStandard() {
return errorIdentificationStandardMapper.selectList(null);
}
public int updateErrorIdentification(ErrorIdentificationStandard standard) {
return errorIdentificationStandardMapper.updateById(standard);
}
}

View File

@@ -0,0 +1,386 @@
package com.fastbee.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.core.domain.entity.UserClient;
import com.fastbee.common.core.domain.model.LoginUser;
import com.fastbee.common.exception.ServiceException;
import com.fastbee.common.utils.MessageUtils;
import com.fastbee.dto.*;
import com.fastbee.enums.ConnectorStatus;
import com.fastbee.iot.domain.Device;
import com.fastbee.iot.mapper.DeviceMapper;
import com.fastbee.iot.service.IDeviceService;
import com.fastbee.manager.DeviceSessionManager;
import com.fastbee.system.mapper.SysUserClientMapper;
import com.fastbee.system.service.ISysUserClientService;
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 java.util.Date;
import java.util.List;
import java.util.Set;
@Service
@Slf4j
public class TransferDeviceService {
@Autowired
private IDeviceService iDeviceService;
@Autowired
private ISysUserClientService sysUserClientService;
@Autowired
private DeviceSessionManager sessionManager;
@Autowired
private SysUserClientMapper userClientMapper;
@Autowired
private DeviceMapper deviceMapper;
public AjaxResult bind(DeviceBindDTO bindDTO, LoginUser user) {
try {
String deviceId = bindDTO.getDeviceId();
String deviceAlias = bindDTO.getDeviceAlias();
//判断当前设备是否存
Device device = iDeviceService.selectDeviceBySerialNumber(deviceId);
if (device == null) {
return AjaxResult.error("设备不存在");
} else {
Long tenantId = device.getTenantId();
if (tenantId != -1) {
if (!tenantId.equals(user.getUserId())) {
return AjaxResult.error("设备有其他用户绑定");
}
}
device.setTenantId(user.getUserId());
device.setTenantName(user.getUsername());
device.setUpdateTime(new Date());
device.setDeviceAlias(deviceAlias);
device.setActiveTime(new Date());
iDeviceService.updateDeviceBySelf(device);
// deviceMapper.updateById(device);
return AjaxResult.success(true);
}
} catch (Exception e) {
log.error("设备绑定失败: {}", e.getMessage(), e);
return AjaxResult.error("设备绑定失败:" + e.getMessage());
}
}
public AjaxResult unbind(DeviceBindDTO bindDTO, LoginUser user) {
try {
String deviceId = bindDTO.getDeviceId();
//判断当前设备是否存
Device device = iDeviceService.selectDeviceBySerialNumber(deviceId);
if (device == null) {
return AjaxResult.error("设备不存在");
} else {
Long tenantId = device.getTenantId();
if (tenantId == -1) {
return AjaxResult.error("设备未绑定");
}
if (!tenantId.equals(user.getUserId())) {
return AjaxResult.error("无解绑权限");
}
device.setTenantId(-1L);
device.setTenantName("");
device.setUpdateTime(new Date());
device.setDeviceAlias("");
// deviceMapper.updateById(device);
iDeviceService.updateDeviceBySelf(device);
//判断是否正在控制 如果正在控制,删除控制状态
LambdaQueryWrapper<UserClient> lambdaWrapper = new LambdaQueryWrapper<>();
lambdaWrapper.eq(UserClient::getDeviceName, deviceId);
List<UserClient> users = userClientMapper.selectList(lambdaWrapper);
log.info("users:{}", users);
if (!CollectionUtils.isEmpty(users)) {
users.forEach(userClient -> {
log.info("userClient:{}", userClient);
if (userClient != null) {
String masterId = userClient.getClientName();
NettyDevice deviceMaster = sessionManager.getDevice(masterId);
if (deviceMaster != null) {
String oldSlave = userClient.getDeviceName();
//删除主的连接关系
deviceMaster.getConnectedConnectors().removeIf(x -> x.getConnectorId().equals(oldSlave));
//删除从的连接关系
NettyDevice oldSlaveDevice = sessionManager.getDevice(oldSlave);
if (oldSlaveDevice != null && !CollectionUtils.isEmpty(oldSlaveDevice.getConnectedConnectors())) {
Set<Connector> connectedDevices = oldSlaveDevice.getConnectedConnectors();
connectedDevices.removeIf(x -> x.getConnectorId().equals(masterId));
}
}
sysUserClientService.updateAliveStatus(masterId, "", 0);
log.info("updateById:{}", userClient.getClientName());
}
});
}
return AjaxResult.success(true);
}
} catch (Exception e) {
log.error("设备解绑失败: {}", e.getMessage(), e);
return AjaxResult.error("设备解绑失败:" + e.getMessage());
}
}
public AjaxResult updateDeviceAlias(DeviceBindDTO bindDTO, LoginUser user) {
try {
String deviceId = bindDTO.getDeviceId();
//判断当前设备是否存
Device device = iDeviceService.selectDeviceBySerialNumber(deviceId);
if (device == null) {
return AjaxResult.error("设备不存在");
} else {
Long tenantId = device.getTenantId();
if (tenantId == -1) {
return AjaxResult.error("设备未绑定");
}
if (!tenantId.equals(user.getUserId())) {
return AjaxResult.error("无操作权限");
}
device.setDeviceAlias(bindDTO.getDeviceAlias());
device.setUpdateTime(new Date());
device.setCreateBy(user.getUsername());
iDeviceService.updateDeviceBySelf(device);
return AjaxResult.success(true);
}
} catch (Exception e) {
log.error("设备更新失败: {}", e.getMessage(), e);
return AjaxResult.error("设备更新失败:" + e.getMessage());
}
}
public synchronized boolean switchDevice(DeviceBindDTO bindDTO, LoginUser user) {
try {
String slaveId = bindDTO.getDeviceId();
String platform = bindDTO.getPlatform();
String userName = user.getUsername();
String masterId = userName + ":" + platform;
//todo 判断是否有权限 正在控制才能切
//todo 离线没有控制权的怎么切
log.info("switchDevice:{}", masterId);
NettyDevice deviceMaster = sessionManager.getDevice(masterId);
log.info("deviceMaster:{}", deviceMaster);
if (deviceMaster != null) {
log.info("ConnectorStatus:{}", deviceMaster.getConnectorStatus());
if (ConnectorStatus.RECEIVER.equals(deviceMaster.getConnectorStatus())) {
//当前账号没有控制则可以切换为控制?
NettyDevice activeDevice = sessionManager.getUserControl(userName);
deviceMaster.getConnectedConnectors().clear();
if (activeDevice == null) {
log.info("bindConnector ACTIVE :{}", masterId);
sessionManager.bindConnector(masterId, slaveId);
deviceMaster.setConnectorStatus(ConnectorStatus.ACTIVE);
deviceMaster.setCurrentSlaveId(slaveId);
sysUserClientService.updateAliveStatus(masterId, slaveId, 1);
} else {
log.info("bindConnector RECEIVER :{}", masterId);
sessionManager.bindConnector(masterId, slaveId);
deviceMaster.setConnectorStatus(ConnectorStatus.RECEIVER);
deviceMaster.setCurrentSlaveId(slaveId);
sysUserClientService.updateAliveStatus(masterId, slaveId, 2);
}
} else {
//从关联其他设备切换到 当前禁言 假如有控制且不是当前更新为2
List<NettyDevice> controls = sessionManager.getSlaveControl(slaveId);
if (CollectionUtils.isEmpty(controls)) {
deviceMaster.getConnectedConnectors().clear();
log.info("bindConnector 1:{}", masterId);
sessionManager.bindConnector(masterId, slaveId);
deviceMaster.setConnectorStatus(ConnectorStatus.ACTIVE);
deviceMaster.setCurrentSlaveId(slaveId);
sysUserClientService.updateAliveStatus(masterId, slaveId, 1);
} else {
NettyDevice controlDevice = controls.get(0);
if (!masterId.equals(controlDevice.getConnectorId())) {
//当前的设备有控制 的主机
deviceMaster.getConnectedConnectors().clear();
log.info("bindConnector RECEIVER 2:{}", masterId);
sessionManager.bindConnector(masterId, slaveId);
deviceMaster.setConnectorStatus(ConnectorStatus.RECEIVER);
deviceMaster.setCurrentSlaveId(slaveId);
sysUserClientService.updateAliveStatus(masterId, slaveId, 2);
}
//当前 切当前不做操作
}
}
return true;
}
} catch (Exception e) {
log.error("切换设备失败: {}", e.getMessage(), e);
}
return false;
}
// public DeviceControlDTO remoteControl(DeviceBindDTO bindDTO, LoginUser user) {
// try {
// String slaveId = bindDTO.getDeviceId();
// String platform = bindDTO.getPlatform();
// String userName = user.getUsername();
// String masterId = userName + ":" + platform;
// DeviceControlDTO dto = new DeviceControlDTO();
// NettyDevice deviceMaster = sessionManager.getDevice(masterId);
// log.info("remoteControl deviceMaster:{}", masterId);
// if (deviceMaster != null) {
// if (ConnectorStatus.ACTIVE.equals(deviceMaster.getConnectorStatus())) {
// if (!StringUtils.isEmpty(deviceMaster.getCurrentSlaveId())) {
// if (deviceMaster.getCurrentSlaveId().equalsIgnoreCase(slaveId)) {
// dto.setRemoteControl(true);
// dto.setOwner(platform);
// } else {
// dto.setRemoteControl(false);
// dto.setReason("occupied");
// List<NettyDevice> list = sessionManager.getSlaveControl(slaveId);
// if (!CollectionUtils.isEmpty(list)) {
// dto.setOwner(list.get(0).getConnectorId());
// }
// }
// } else {
// dto.setRemoteControl(false);
// dto.setReason("no control");
// List<NettyDevice> list = sessionManager.getSlaveControl(slaveId);
// if (!CollectionUtils.isEmpty(list)) {
// dto.setOwner(list.get(0).getConnectorId());
// }
// }
// } else {
// dto.setRemoteControl(false);
// dto.setReason("not active");
// List<NettyDevice> list = sessionManager.getSlaveControl(slaveId);
// if (!CollectionUtils.isEmpty(list)) {
// dto.setOwner(list.get(0).getConnectorId());
// }
// }
// } else {
// dto.setRemoteControl(false);
// dto.setReason("not exist");
// List<NettyDevice> list = sessionManager.getSlaveControl(slaveId);
// if (!CollectionUtils.isEmpty(list)) {
// dto.setOwner(list.get(0).getConnectorId());
// }
// }
// return dto;
// } catch (Exception e) {
// log.error(e.getMessage());
// }
// return null;
// }
public DeviceControlDTO remoteControl(DeviceBindDTO bindDTO, LoginUser user) {
try {
// String slaveId = bindDTO.getDeviceId();
String platform = bindDTO.getPlatform();
String userName = user.getUsername();
String masterId = userName + ":" + platform;
DeviceControlDTO dto = new DeviceControlDTO();
NettyDevice deviceMaster = sessionManager.getDevice(masterId);
log.info("remoteControl deviceMaster:{}", masterId);
if (deviceMaster != null) {
if (ConnectorStatus.ACTIVE.equals(deviceMaster.getConnectorStatus())) {
dto.setRemoteControl(true);
dto.setOwner(platform);
} else {
dto.setRemoteControl(false);
dto.setReason("occupied");
NettyDevice activeDevice = sessionManager.getUserControl(userName);
if (activeDevice != null) {
String[] l = activeDevice.getConnectorId().split(":");
dto.setOwner(l[1]);
}
}
} else {
dto.setRemoteControl(false);
dto.setReason("not exist");
NettyDevice activeDevice = sessionManager.getUserControl(userName);
if (activeDevice != null) {
String[] l = activeDevice.getConnectorId().split(":");
dto.setOwner(l[1]);
}
}
return dto;
} catch (Exception e) {
log.error("获取设备权限失败", e);
}
return null;
}
public DeviceSwitchControlDTO switchControl(DeviceBindDTO bindDTO, LoginUser user) {
try {
String slaveId = bindDTO.getDeviceId();
String platform = bindDTO.getPlatform();
String userName = user.getUsername();
String masterId = userName + ":" + platform;
DeviceSwitchControlDTO dto = new DeviceSwitchControlDTO();
//收到明确的切换设备请求了 从哪边切换到另一边
//判断当前是否有控制的设备
NettyDevice masterDevice = sessionManager.getDevice(masterId);
if (masterDevice == null || !masterDevice.getChannel().isActive()) {
//主机已离线
dto.setSwitchControl(false);
dto.setReason("主机已离线");
return dto;
}
NettyDevice slaveDevice = sessionManager.getDevice(slaveId);
if (slaveDevice == null || !masterDevice.getChannel().isActive()) {
//从机已离线
//主机已离线
dto.setSwitchControl(false);
dto.setReason("从机已离线");
return dto;
}
List<NettyDevice> controlList = sessionManager.getSlaveControl(slaveId);
if (!CollectionUtils.isEmpty(controlList)) {
//如果当前设备有控制
controlList.forEach(c -> {
if (!c.getConnectorId().equals(masterId)) {
c.setCurrentSlaveId(null);
c.removeConnectedDevice(slaveDevice);
c.setConnectorStatus(ConnectorStatus.RECEIVER);
sysUserClientService.updateAliveStatus(c.getConnectorId(), slaveId, 2);
}
});
}
masterDevice.setCurrentSlaveId(slaveId);
masterDevice.setConnectorStatus(ConnectorStatus.ACTIVE);
sysUserClientService.updateAliveStatus(masterDevice.getConnectorId(), slaveId, 1);
dto.setSwitchControl(true);
dto.setHolder(platform);
return dto;
} catch (Exception e) {
log.error(e.getMessage());
return new DeviceSwitchControlDTO(false);
}
}
public void releaseControl(DeviceBindDTO bindDTO, LoginUser user) {
try {
String platform = bindDTO.getPlatform();
String userName = user.getUsername();
String masterId = userName + ":" + platform;
NettyDevice deviceMaster = sessionManager.getDevice(masterId);
if (deviceMaster != null) {
sysUserClientService.updateAliveStatus(masterId, "", 0);
deviceMaster.setCurrentSlaveId(null);
deviceMaster.getConnectedConnectors().clear();
}
} catch (Exception e) {
log.error(e.getMessage());
}
}
}