first commit
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
package com.maibu.own.controller;
|
||||
|
||||
import com.fastbee.common.core.controller.BaseController;
|
||||
import com.fastbee.common.core.domain.AjaxResult;
|
||||
import com.fastbee.common.core.page.TableDataInfo;
|
||||
import com.fastbee.iot.domain.IoTCommonDevice;
|
||||
import com.fastbee.own.entity.WorkOrder;
|
||||
import com.fastbee.own.service.CommonDeviceService;
|
||||
import com.fastbee.own.service.WorkOrderService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/iot/commonDevice")
|
||||
public class CommonDeviceController extends BaseController {
|
||||
|
||||
@Autowired
|
||||
private CommonDeviceService commonDeviceService;
|
||||
|
||||
|
||||
@GetMapping("/unRegisterList")
|
||||
public AjaxResult unRegisterList() {
|
||||
return AjaxResult.success(commonDeviceService.unRegisterList());
|
||||
}
|
||||
|
||||
@PostMapping("/register")
|
||||
public AjaxResult register(@RequestBody IoTCommonDevice commonDevice) {
|
||||
commonDeviceService.save(commonDevice);
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo list(String searchVale) {
|
||||
startPage();
|
||||
// 限制当前用户机构
|
||||
return getDataTable(commonDeviceService.list(searchVale));
|
||||
}
|
||||
|
||||
@GetMapping("/detail")
|
||||
public AjaxResult detail(@RequestParam String id) {
|
||||
return AjaxResult.success(commonDeviceService.detail(id));
|
||||
}
|
||||
|
||||
@GetMapping("/delete")
|
||||
public AjaxResult delete(@RequestParam String id) {
|
||||
return AjaxResult.success(commonDeviceService.delete(id));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.maibu.own.controller;
|
||||
|
||||
import com.fastbee.common.core.controller.BaseController;
|
||||
import com.fastbee.common.core.domain.AjaxResult;
|
||||
import com.fastbee.common.core.page.TableDataInfo;
|
||||
import com.fastbee.own.entity.PathPlan;
|
||||
import com.fastbee.own.entity.WorkOrder;
|
||||
import com.fastbee.own.service.PathPlanService;
|
||||
import com.fastbee.own.service.WorkOrderService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/iot/path")
|
||||
public class PathPlanController extends BaseController {
|
||||
|
||||
@Autowired
|
||||
private PathPlanService pathPlanService;
|
||||
|
||||
@PostMapping("/save")
|
||||
public AjaxResult save(@RequestBody PathPlan pathPlan) {
|
||||
pathPlanService.save(pathPlan);
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo list() {
|
||||
startPage();
|
||||
// 限制当前用户机构
|
||||
return getDataTable(pathPlanService.list());
|
||||
}
|
||||
|
||||
@GetMapping("/getPath")
|
||||
public AjaxResult getPath() {
|
||||
return AjaxResult.success(pathPlanService.getPath());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.maibu.own.controller;
|
||||
|
||||
import com.fastbee.common.core.controller.BaseController;
|
||||
import com.fastbee.common.core.domain.AjaxResult;
|
||||
import com.fastbee.common.core.page.TableDataInfo;
|
||||
import com.fastbee.own.entity.WorkOrder;
|
||||
import com.fastbee.own.service.WorkOrderService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/iot/workOrder")
|
||||
public class WorkOrderController extends BaseController {
|
||||
|
||||
@Autowired
|
||||
private WorkOrderService workOrderService;
|
||||
|
||||
@PostMapping("/save")
|
||||
public AjaxResult save(@RequestBody WorkOrder workOrder) {
|
||||
workOrderService.save(workOrder);
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo list(String searchVale) {
|
||||
startPage();
|
||||
// 限制当前用户机构
|
||||
return getDataTable(workOrderService.list(searchVale));
|
||||
}
|
||||
|
||||
@GetMapping("/detail")
|
||||
public AjaxResult detail(@RequestParam String id) {
|
||||
return AjaxResult.success(workOrderService.detail(id));
|
||||
}
|
||||
|
||||
@GetMapping("/delete")
|
||||
public AjaxResult delete(@RequestParam String id) {
|
||||
return AjaxResult.success(workOrderService.delete(id));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.maibu.own.entity;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class NodePosition {
|
||||
|
||||
private String longitude; //经度
|
||||
private String latitude; //纬度
|
||||
private Integer index;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.maibu.own.entity;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum OrderStatus {
|
||||
New("待处理"),
|
||||
Executing("进行中"),
|
||||
Canceled("已取消"),
|
||||
Finished("已完成");
|
||||
|
||||
private final String desc;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.maibu.own.entity;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum OrderType {
|
||||
Security("安防"),
|
||||
Inspection("巡检"),
|
||||
Cleaning("清洗");
|
||||
|
||||
private final String desc;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.maibu.own.entity;
|
||||
|
||||
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.fastbee.common.core.domain.BaseDO;
|
||||
import com.fastbee.iot.domain.DeviceTaskPlanRule;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.data.annotation.Id;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@TableName("iot_path_plan")
|
||||
public class PathPlan extends BaseDO {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField(typeHandler = JacksonTypeHandler.class)
|
||||
private List<NodePosition> nodePosition; //点位信息
|
||||
|
||||
private String name;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.maibu.own.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.data.annotation.Id;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@TableName("iot_work_order")
|
||||
public class WorkOrder implements Serializable {
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
private String orderNo;
|
||||
|
||||
private String orderName;
|
||||
|
||||
private OrderType orderType;
|
||||
|
||||
private Integer priority; // 高中低 0 1 2
|
||||
|
||||
private OrderStatus orderStatus;
|
||||
|
||||
private String operator;
|
||||
|
||||
private LocalDateTime createTime;
|
||||
|
||||
private String creator;
|
||||
|
||||
private String description;
|
||||
|
||||
private String handleResult;
|
||||
|
||||
private boolean isDel;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.maibu.own.mapper;
|
||||
|
||||
import com.fastbee.framework.mybatis.mapper.BaseMapperX;
|
||||
import com.fastbee.own.entity.PathPlan;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
|
||||
@Repository
|
||||
public interface PathPlanMapper extends BaseMapperX<PathPlan> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.maibu.own.mapper;
|
||||
|
||||
import com.fastbee.framework.mybatis.mapper.BaseMapperX;
|
||||
import com.fastbee.own.entity.WorkOrder;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
|
||||
@Repository
|
||||
public interface WorkOrderMapper extends BaseMapperX<WorkOrder> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.maibu.own.service;
|
||||
|
||||
import com.fastbee.framework.mybatis.LambdaQueryWrapperX;
|
||||
import com.fastbee.iot.domain.IoTCommonDevice;
|
||||
import com.fastbee.iot.mapper.IoTCommonDevicesMapper;
|
||||
import com.fastbee.iot.memory.CommonMemory;
|
||||
import com.fastbee.own.entity.WorkOrder;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class CommonDeviceService {
|
||||
|
||||
|
||||
@Autowired
|
||||
private IoTCommonDevicesMapper commonDevicesMapper;
|
||||
|
||||
|
||||
public List<IoTCommonDevice> unRegisterList() {
|
||||
return (List<IoTCommonDevice>) CommonMemory.unRegisterCommonDeviceMap.values();
|
||||
}
|
||||
|
||||
public List<IoTCommonDevice> register() {
|
||||
return (List<IoTCommonDevice>) CommonMemory.unRegisterCommonDeviceMap.values();
|
||||
}
|
||||
|
||||
public void save(IoTCommonDevice commonDevice) {
|
||||
if (commonDevice != null) {
|
||||
if (commonDevice.getId() != null) {
|
||||
commonDevicesMapper.updateById(commonDevice);
|
||||
} else {
|
||||
commonDevicesMapper.insert(commonDevice);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public List<IoTCommonDevice> list(String searchVale) {
|
||||
return commonDevicesMapper.selectList();
|
||||
}
|
||||
|
||||
public IoTCommonDevice detail(String id) {
|
||||
return commonDevicesMapper.selectById(id);
|
||||
}
|
||||
|
||||
public int delete(String id) {
|
||||
return commonDevicesMapper.deleteById(id);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.maibu.own.service;
|
||||
|
||||
import com.fastbee.framework.mybatis.LambdaQueryWrapperX;
|
||||
import com.fastbee.own.entity.PathPlan;
|
||||
import com.fastbee.own.mapper.PathPlanMapper;
|
||||
import org.apache.commons.collections.CollectionUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class PathPlanService {
|
||||
|
||||
|
||||
@Autowired
|
||||
private PathPlanMapper pathPlanMapper;
|
||||
|
||||
public void save(PathPlan pathPlan) {
|
||||
if (pathPlan != null) {
|
||||
if (pathPlan.getId() != null) {
|
||||
pathPlanMapper.updateById(pathPlan);
|
||||
} else {
|
||||
pathPlanMapper.insert(pathPlan);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public List<PathPlan> list() {
|
||||
LambdaQueryWrapperX<PathPlan> wrapper = new LambdaQueryWrapperX<>();
|
||||
return pathPlanMapper.selectList(wrapper);
|
||||
}
|
||||
|
||||
|
||||
public PathPlan getPath() {
|
||||
LambdaQueryWrapperX<PathPlan> wrapper = new LambdaQueryWrapperX<>();
|
||||
return CollectionUtils.isEmpty(pathPlanMapper.selectList(wrapper)) ? null : pathPlanMapper.selectList(wrapper).get(0);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.maibu.own.service;
|
||||
|
||||
import com.fastbee.framework.mybatis.LambdaQueryWrapperX;
|
||||
import com.fastbee.own.entity.WorkOrder;
|
||||
import com.fastbee.own.mapper.WorkOrderMapper;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class WorkOrderService {
|
||||
|
||||
|
||||
@Autowired
|
||||
private WorkOrderMapper workOrderMapper;
|
||||
|
||||
public void save(WorkOrder workOrder) {
|
||||
if (workOrder != null) {
|
||||
if (workOrder.getId() != null) {
|
||||
workOrderMapper.updateById(workOrder);
|
||||
} else {
|
||||
workOrderMapper.insert(workOrder);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public List<WorkOrder> list(String searchVale) {
|
||||
LambdaQueryWrapperX<WorkOrder> wrapper = new LambdaQueryWrapperX<>();
|
||||
if (!StringUtils.isEmpty(searchVale)) {
|
||||
wrapper.and(w -> w
|
||||
.like(WorkOrder::getOrderName, searchVale)
|
||||
.or()
|
||||
.like(WorkOrder::getOrderNo, searchVale)
|
||||
.or()
|
||||
.like(WorkOrder::getCreator, searchVale)
|
||||
.or()
|
||||
.like(WorkOrder::getDescription, searchVale)
|
||||
);
|
||||
return workOrderMapper.selectList(wrapper);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public WorkOrder detail(String id) {
|
||||
return workOrderMapper.selectById(id);
|
||||
}
|
||||
|
||||
public int delete(String id) {
|
||||
return workOrderMapper.deleteById(id);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
package com.maibu.thermal.controller;
|
||||
|
||||
|
||||
import com.fastbee.common.core.domain.AjaxResult;
|
||||
import com.fastbee.thermal.model.AnalyzeRequest;
|
||||
import com.fastbee.thermal.model.ProbeRequest;
|
||||
import com.fastbee.thermal.model.ReportRequest;
|
||||
import com.fastbee.thermal.service.ThermalService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.validation.Valid;
|
||||
import java.io.*;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/thermal")
|
||||
@Validated
|
||||
@Slf4j
|
||||
public class ThermalController {
|
||||
|
||||
@Autowired
|
||||
private ThermalService thermalService;
|
||||
|
||||
@GetMapping("/defaults")
|
||||
public AjaxResult getDefaults() {
|
||||
try {
|
||||
Map<String, Object> defaults = thermalService.getDefaults();
|
||||
return AjaxResult.success(defaults);
|
||||
} catch (Exception e) {
|
||||
log.error("接口错误", e);
|
||||
return AjaxResult.error();
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/analyze")
|
||||
public AjaxResult analyze(@Valid @RequestBody AnalyzeRequest request) {
|
||||
try {
|
||||
Map<String, Object> result = thermalService.analyze(request);
|
||||
return AjaxResult.success(result);
|
||||
} catch (RuntimeException e) {
|
||||
log.error("接口错误", e);
|
||||
return AjaxResult.error();
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/probe")
|
||||
public AjaxResult probe(@RequestBody ProbeRequest request) {
|
||||
try {
|
||||
Map<String, Object> result = thermalService.probe(request);
|
||||
return AjaxResult.success(result);
|
||||
} catch (RuntimeException e) {
|
||||
log.error("接口错误", e);
|
||||
return AjaxResult.error();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@GetMapping("/report")
|
||||
public AjaxResult report(@RequestParam String analysisId, HttpServletResponse response) {
|
||||
try {
|
||||
String result = thermalService.generateReport(analysisId);
|
||||
try (OutputStream os = response.getOutputStream()) {
|
||||
|
||||
response.setContentType("application/octet-stream");
|
||||
|
||||
// 文件名(防止中文乱码)
|
||||
String fileName = URLEncoder.encode("report.html", "UTF-8");
|
||||
response.setHeader("Content-Disposition",
|
||||
"attachment;filename=" + fileName);
|
||||
|
||||
// 写出
|
||||
os.write(result.getBytes(StandardCharsets.UTF_8));
|
||||
os.flush();
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return AjaxResult.success(result);
|
||||
} catch (RuntimeException e) {
|
||||
log.error("接口错误", e);
|
||||
return AjaxResult.error();
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/downloadReport")
|
||||
public void getReport(HttpServletResponse response) {
|
||||
|
||||
File file = new File("/www/wwwroot/Java/Platform/tiff/pv_array_thermal_train5/station_A_thermal_report.html");
|
||||
|
||||
// 1. 判断文件是否存在
|
||||
if (!file.exists() || !file.isFile()) {
|
||||
throw new RuntimeException("文件不存在");
|
||||
}
|
||||
|
||||
try (InputStream inputStream = new FileInputStream(file);
|
||||
OutputStream outputStream = response.getOutputStream()) {
|
||||
|
||||
// 2. 设置响应头
|
||||
response.setContentType("text/html;charset=UTF-8");
|
||||
|
||||
String fileName = URLEncoder.encode(file.getName(), "UTF-8");
|
||||
response.setHeader("Content-Disposition",
|
||||
"attachment;filename=" + fileName);
|
||||
|
||||
// 3. 文件流输出
|
||||
byte[] buffer = new byte[1024];
|
||||
int len;
|
||||
while ((len = inputStream.read(buffer)) != -1) {
|
||||
outputStream.write(buffer, 0, len);
|
||||
}
|
||||
|
||||
outputStream.flush();
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// @GetMapping("/image")
|
||||
// public void getImage(HttpServletResponse response) {
|
||||
// File file = new File("/www/wwwroot/thermal/tiff/pv_array_thermal_train5/pv_array_overlay.png");
|
||||
// boolean b = isGreenShieldEncrypt(file);
|
||||
// // 1️⃣ 文件是否存在
|
||||
// if (!file.exists() || file.isDirectory()) {
|
||||
// response.setStatus(HttpServletResponse.SC_NOT_FOUND);
|
||||
// return;
|
||||
// }
|
||||
// try {
|
||||
// // 2️⃣ 自动识别文件类型(image/jpeg、image/png)
|
||||
// String contentType = Files.probeContentType(file.toPath());
|
||||
// if (contentType == null) {
|
||||
// contentType = "application/octet-stream";
|
||||
// }
|
||||
//
|
||||
// response.setContentType(contentType);
|
||||
// response.setHeader("Content-Disposition", "inline; filename=" + file.getName());
|
||||
//
|
||||
// // 3️⃣ 流式读取写出
|
||||
// try (InputStream is = new FileInputStream(file);
|
||||
// OutputStream os = response.getOutputStream()) {
|
||||
//
|
||||
// byte[] buffer = new byte[8192];
|
||||
// int len;
|
||||
// while ((len = is.read(buffer)) != -1) {
|
||||
// os.write(buffer, 0, len);
|
||||
// }
|
||||
// os.flush();
|
||||
// }
|
||||
// } catch (Exception e) {
|
||||
// e.printStackTrace();
|
||||
// response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
|
||||
// }
|
||||
// }
|
||||
|
||||
@GetMapping("/image")
|
||||
public String getImage() {
|
||||
try {
|
||||
// File file = new File("/www/wwwroot/thermal/tiff/pv_array_thermal_train5/pv_array_overlay.png");
|
||||
// boolean b = isGreenShieldEncrypt(file);
|
||||
Path filePath = Paths.get("/www/wwwroot/Java/Platform/tiff/pv_array_thermal_train5/pv_array_overlay.png");
|
||||
byte[] bytes = Files.readAllBytes(filePath);
|
||||
|
||||
// Java8 也支持
|
||||
String contentType = Files.probeContentType(filePath);
|
||||
if (contentType == null) {
|
||||
contentType = "image/jpeg";
|
||||
}
|
||||
|
||||
String base64 = Base64.getEncoder().encodeToString(bytes);
|
||||
return "data:" + contentType + ";base64," + base64;
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static final byte[] PNG_MAGIC = {(byte) 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};
|
||||
// JPG 标准文件头魔数
|
||||
private static final byte[] JPG_MAGIC = {(byte) 0xFF, (byte) 0xD8, (byte) 0xFF};
|
||||
|
||||
/**
|
||||
* 判断文件是否被绿盾加密(图片专用)
|
||||
*
|
||||
* @param file 待检测文件
|
||||
* @return true=已被绿盾加密 / false=原生未加密
|
||||
*/
|
||||
public static boolean isGreenShieldEncrypt(File file) {
|
||||
if (!file.exists() || !file.isFile()) {
|
||||
throw new RuntimeException("文件不存在或不是文件");
|
||||
}
|
||||
|
||||
// 读取前32字节头信息
|
||||
byte[] headBuf = new byte[32];
|
||||
try (FileInputStream fis = new FileInputStream(file)) {
|
||||
int readLen = fis.read(headBuf);
|
||||
if (readLen < 8) {
|
||||
return true; // 头部异常,判定加密
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// 绿盾拦截IO会抛异常,直接判定加密
|
||||
return true;
|
||||
}
|
||||
|
||||
// 对比PNG头
|
||||
boolean isPngNative = true;
|
||||
for (int i = 0; i < PNG_MAGIC.length; i++) {
|
||||
if (headBuf[i] != PNG_MAGIC[i]) {
|
||||
isPngNative = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (isPngNative) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 对比JPG头
|
||||
boolean isJpgNative = true;
|
||||
for (int i = 0; i < JPG_MAGIC.length; i++) {
|
||||
if (headBuf[i] != JPG_MAGIC[i]) {
|
||||
isJpgNative = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (isJpgNative) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 魔数完全不匹配:绿盾加密文件
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.maibu.thermal.model;
|
||||
|
||||
import javax.validation.constraints.*;
|
||||
|
||||
public class AnalyzeRequest {
|
||||
private String thermalPath;
|
||||
private String arrayMaskPath;
|
||||
private String panelGeojsonPath;
|
||||
|
||||
@DecimalMin("-100.0")
|
||||
@DecimalMax("500.0")
|
||||
private double thresholdC = 48.0;
|
||||
|
||||
@Min(1)
|
||||
@Max(1000000)
|
||||
private int minAreaPx = 25;
|
||||
|
||||
@Min(1)
|
||||
@Max(1000000)
|
||||
private int maxRegions = 120;
|
||||
|
||||
@Min(1)
|
||||
@Max(99)
|
||||
private int openK = 3;
|
||||
|
||||
@Min(1)
|
||||
@Max(99)
|
||||
private int closeK = 3;
|
||||
|
||||
@Min(0)
|
||||
@Max(1000)
|
||||
private int shrinkIn = 2;
|
||||
|
||||
private boolean showMaskEdge = true;
|
||||
private boolean includePanelSegments = false;
|
||||
|
||||
// Getters and setters
|
||||
public String getThermalPath() { return thermalPath; }
|
||||
public void setThermalPath(String thermalPath) { this.thermalPath = thermalPath; }
|
||||
|
||||
public String getArrayMaskPath() { return arrayMaskPath; }
|
||||
public void setArrayMaskPath(String arrayMaskPath) { this.arrayMaskPath = arrayMaskPath; }
|
||||
|
||||
public String getPanelGeojsonPath() { return panelGeojsonPath; }
|
||||
public void setPanelGeojsonPath(String panelGeojsonPath) { this.panelGeojsonPath = panelGeojsonPath; }
|
||||
|
||||
public double getThresholdC() { return thresholdC; }
|
||||
public void setThresholdC(double thresholdC) { this.thresholdC = thresholdC; }
|
||||
|
||||
public int getMinAreaPx() { return minAreaPx; }
|
||||
public void setMinAreaPx(int minAreaPx) { this.minAreaPx = minAreaPx; }
|
||||
|
||||
public int getMaxRegions() { return maxRegions; }
|
||||
public void setMaxRegions(int maxRegions) { this.maxRegions = maxRegions; }
|
||||
|
||||
public int getOpenK() { return openK; }
|
||||
public void setOpenK(int openK) { this.openK = openK; }
|
||||
|
||||
public int getCloseK() { return closeK; }
|
||||
public void setCloseK(int closeK) { this.closeK = closeK; }
|
||||
|
||||
public int getShrinkIn() { return shrinkIn; }
|
||||
public void setShrinkIn(int shrinkIn) { this.shrinkIn = shrinkIn; }
|
||||
|
||||
public boolean isShowMaskEdge() { return showMaskEdge; }
|
||||
public void setShowMaskEdge(boolean showMaskEdge) { this.showMaskEdge = showMaskEdge; }
|
||||
|
||||
public boolean isIncludePanelSegments() { return includePanelSegments; }
|
||||
public void setIncludePanelSegments(boolean includePanelSegments) { this.includePanelSegments = includePanelSegments; }
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.maibu.thermal.model;
|
||||
|
||||
import javax.validation.constraints.*;
|
||||
|
||||
public class ProbeRequest {
|
||||
@NotBlank
|
||||
private String analysisId;
|
||||
|
||||
@NotNull
|
||||
private double x;
|
||||
|
||||
@NotNull
|
||||
private double y;
|
||||
|
||||
private String coordinateSpace = "source";
|
||||
private Double displayWidth;
|
||||
private Double displayHeight;
|
||||
|
||||
// Getters and setters
|
||||
public String getAnalysisId() { return analysisId; }
|
||||
public void setAnalysisId(String analysisId) { this.analysisId = analysisId; }
|
||||
|
||||
public double getX() { return x; }
|
||||
public void setX(double x) { this.x = x; }
|
||||
|
||||
public double getY() { return y; }
|
||||
public void setY(double y) { this.y = y; }
|
||||
|
||||
public String getCoordinateSpace() { return coordinateSpace; }
|
||||
public void setCoordinateSpace(String coordinateSpace) { this.coordinateSpace = coordinateSpace; }
|
||||
|
||||
public Double getDisplayWidth() { return displayWidth; }
|
||||
public void setDisplayWidth(Double displayWidth) { this.displayWidth = displayWidth; }
|
||||
|
||||
public Double getDisplayHeight() { return displayHeight; }
|
||||
public void setDisplayHeight(Double displayHeight) { this.displayHeight = displayHeight; }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.maibu.thermal.model;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class RangeData {
|
||||
|
||||
private double startX;
|
||||
private double startY;
|
||||
private double endX;
|
||||
private double endY;
|
||||
private double temp;
|
||||
private String code;
|
||||
private double lat;
|
||||
private double lon;
|
||||
|
||||
|
||||
public boolean contains(double x, double y) {
|
||||
return x >= startX && x < endX && y >= startY && y < endY; // 左闭右开
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.maibu.thermal.model;
|
||||
|
||||
import javax.validation.constraints.*;
|
||||
|
||||
public class ReportRequest {
|
||||
@NotBlank
|
||||
private String analysisId;
|
||||
private String projectName = "";
|
||||
private String siteName = "";
|
||||
private String clientName = "";
|
||||
private String inspector = "Thermal Inspector";
|
||||
private String reportDate;
|
||||
private String equipment = "无人机热成像巡检";
|
||||
private String notes = "";
|
||||
|
||||
// Getters and setters
|
||||
public String getAnalysisId() { return analysisId; }
|
||||
public void setAnalysisId(String analysisId) { this.analysisId = analysisId; }
|
||||
|
||||
public String getProjectName() { return projectName; }
|
||||
public void setProjectName(String projectName) { this.projectName = projectName; }
|
||||
|
||||
public String getSiteName() { return siteName; }
|
||||
public void setSiteName(String siteName) { this.siteName = siteName; }
|
||||
|
||||
public String getClientName() { return clientName; }
|
||||
public void setClientName(String clientName) { this.clientName = clientName; }
|
||||
|
||||
public String getInspector() { return inspector; }
|
||||
public void setInspector(String inspector) { this.inspector = inspector; }
|
||||
|
||||
public String getReportDate() { return reportDate; }
|
||||
public void setReportDate(String reportDate) { this.reportDate = reportDate; }
|
||||
|
||||
public String getEquipment() { return equipment; }
|
||||
public void setEquipment(String equipment) { this.equipment = equipment; }
|
||||
|
||||
public String getNotes() { return notes; }
|
||||
public void setNotes(String notes) { this.notes = notes; }
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.maibu.thermal.model;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
|
||||
public class StoredAnalysis {
|
||||
private ThermalAnalysisInput request;
|
||||
private Map<String, Object> result;
|
||||
private LocalDateTime createdAt;
|
||||
private String overlayImageUrl;
|
||||
|
||||
public StoredAnalysis(ThermalAnalysisInput request, Map<String, Object> result, LocalDateTime createdAt, String overlayImageUrl) {
|
||||
this.request = request;
|
||||
this.result = result;
|
||||
this.createdAt = createdAt;
|
||||
this.overlayImageUrl = overlayImageUrl;
|
||||
}
|
||||
|
||||
// Getters and setters
|
||||
public ThermalAnalysisInput getRequest() { return request; }
|
||||
public void setRequest(ThermalAnalysisInput request) { this.request = request; }
|
||||
|
||||
public Map<String, Object> getResult() { return result; }
|
||||
public void setResult(Map<String, Object> result) { this.result = result; }
|
||||
|
||||
public LocalDateTime getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
|
||||
|
||||
public String getOverlayImageUrl() { return overlayImageUrl; }
|
||||
public void setOverlayImageUrl(String overlayImageUrl) { this.overlayImageUrl = overlayImageUrl; }
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.maibu.thermal.model;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class ThermalAnalysisInput {
|
||||
private String thermalPath;
|
||||
private String arrayMaskPath = "";
|
||||
private String panelGeojsonPath = "";
|
||||
private double thresholdC = 48.0;
|
||||
private int minAreaPx = 25;
|
||||
private int maxRegions = 120;
|
||||
private int openK = 3;
|
||||
private int closeK = 3;
|
||||
private int shrinkIn = 2;
|
||||
private boolean showMaskEdge = true;
|
||||
|
||||
public ThermalAnalysisInput() {}
|
||||
|
||||
public ThermalAnalysisInput(String thermalPath, String arrayMaskPath, String panelGeojsonPath, double thresholdC, int minAreaPx, int maxRegions, int openK, int closeK, int shrinkIn, boolean showMaskEdge) {
|
||||
this.thermalPath = thermalPath;
|
||||
this.arrayMaskPath = arrayMaskPath;
|
||||
this.panelGeojsonPath = panelGeojsonPath;
|
||||
this.thresholdC = thresholdC;
|
||||
this.minAreaPx = minAreaPx;
|
||||
this.maxRegions = maxRegions;
|
||||
this.openK = openK;
|
||||
this.closeK = closeK;
|
||||
this.shrinkIn = shrinkIn;
|
||||
this.showMaskEdge = showMaskEdge;
|
||||
}
|
||||
|
||||
public ThermalAnalysisInput normalized() {
|
||||
return new ThermalAnalysisInput(
|
||||
thermalPath != null ? thermalPath.trim() : "",
|
||||
arrayMaskPath != null ? arrayMaskPath.trim() : "",
|
||||
panelGeojsonPath != null ? panelGeojsonPath.trim() : "",
|
||||
thresholdC,
|
||||
minAreaPx,
|
||||
maxRegions,
|
||||
openK,
|
||||
closeK,
|
||||
shrinkIn,
|
||||
showMaskEdge
|
||||
);
|
||||
}
|
||||
|
||||
public Map<String, Object> toPublicDict() {
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("thermalPath", thermalPath);
|
||||
data.put("arrayMaskPath", arrayMaskPath);
|
||||
data.put("panelGeojsonPath", panelGeojsonPath);
|
||||
data.put("thresholdC", thresholdC);
|
||||
data.put("minAreaPx", minAreaPx);
|
||||
data.put("maxRegions", maxRegions);
|
||||
data.put("openK", openK);
|
||||
data.put("closeK", closeK);
|
||||
data.put("shrinkIn", shrinkIn);
|
||||
data.put("showMaskEdge", showMaskEdge);
|
||||
return data;
|
||||
}
|
||||
|
||||
// Getters and setters
|
||||
public String getThermalPath() { return thermalPath; }
|
||||
public void setThermalPath(String thermalPath) { this.thermalPath = thermalPath; }
|
||||
|
||||
public String getArrayMaskPath() { return arrayMaskPath; }
|
||||
public void setArrayMaskPath(String arrayMaskPath) { this.arrayMaskPath = arrayMaskPath; }
|
||||
|
||||
public String getPanelGeojsonPath() { return panelGeojsonPath; }
|
||||
public void setPanelGeojsonPath(String panelGeojsonPath) { this.panelGeojsonPath = panelGeojsonPath; }
|
||||
|
||||
public double getThresholdC() { return thresholdC; }
|
||||
public void setThresholdC(double thresholdC) { this.thresholdC = thresholdC; }
|
||||
|
||||
public int getMinAreaPx() { return minAreaPx; }
|
||||
public void setMinAreaPx(int minAreaPx) { this.minAreaPx = minAreaPx; }
|
||||
|
||||
public int getMaxRegions() { return maxRegions; }
|
||||
public void setMaxRegions(int maxRegions) { this.maxRegions = maxRegions; }
|
||||
|
||||
public int getOpenK() { return openK; }
|
||||
public void setOpenK(int openK) { this.openK = openK; }
|
||||
|
||||
public int getCloseK() { return closeK; }
|
||||
public void setCloseK(int closeK) { this.closeK = closeK; }
|
||||
|
||||
public int getShrinkIn() { return shrinkIn; }
|
||||
public void setShrinkIn(int shrinkIn) { this.shrinkIn = shrinkIn; }
|
||||
|
||||
public boolean isShowMaskEdge() { return showMaskEdge; }
|
||||
public void setShowMaskEdge(boolean showMaskEdge) { this.showMaskEdge = showMaskEdge; }
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.maibu.thermal.model;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class ThermalReportMeta {
|
||||
private String projectName = "";
|
||||
private String siteName = "";
|
||||
private String clientName = "";
|
||||
private String inspector = "Thermal Inspector";
|
||||
private String reportDate;
|
||||
private String equipment = "无人机热成像巡检";
|
||||
private String notes = "建议优先复核高温异常点,并结合现场电气测试、可见光照片与遮挡检查确认根因。";
|
||||
|
||||
public ThermalReportMeta() {}
|
||||
|
||||
public ThermalReportMeta(String projectName, String siteName, String clientName, String inspector, String reportDate, String equipment, String notes) {
|
||||
this.projectName = projectName;
|
||||
this.siteName = siteName;
|
||||
this.clientName = clientName;
|
||||
this.inspector = inspector;
|
||||
this.reportDate = reportDate;
|
||||
this.equipment = equipment;
|
||||
this.notes = notes;
|
||||
}
|
||||
|
||||
public Map<String, Object> toPublicDict() {
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("projectName", projectName);
|
||||
data.put("siteName", siteName);
|
||||
data.put("clientName", clientName);
|
||||
data.put("inspector", inspector);
|
||||
data.put("reportDate", reportDate);
|
||||
data.put("equipment", equipment);
|
||||
data.put("notes", notes);
|
||||
return data;
|
||||
}
|
||||
|
||||
// Getters and setters
|
||||
public String getProjectName() { return projectName; }
|
||||
public void setProjectName(String projectName) { this.projectName = projectName; }
|
||||
|
||||
public String getSiteName() { return siteName; }
|
||||
public void setSiteName(String siteName) { this.siteName = siteName; }
|
||||
|
||||
public String getClientName() { return clientName; }
|
||||
public void setClientName(String clientName) { this.clientName = clientName; }
|
||||
|
||||
public String getInspector() { return inspector; }
|
||||
public void setInspector(String inspector) { this.inspector = inspector; }
|
||||
|
||||
public String getReportDate() { return reportDate; }
|
||||
public void setReportDate(String reportDate) { this.reportDate = reportDate; }
|
||||
|
||||
public String getEquipment() { return equipment; }
|
||||
public void setEquipment(String equipment) { this.equipment = equipment; }
|
||||
|
||||
public String getNotes() { return notes; }
|
||||
public void setNotes(String notes) { this.notes = notes; }
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.maibu.thermal.service;
|
||||
|
||||
import com.fastbee.thermal.model.StoredAnalysis;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Service
|
||||
public class AnalysisStore {
|
||||
private final Map<String, StoredAnalysis> store = new ConcurrentHashMap<>();
|
||||
|
||||
public void put(String analysisId, StoredAnalysis analysis) {
|
||||
store.put(analysisId, analysis);
|
||||
}
|
||||
|
||||
public StoredAnalysis get(String analysisId) {
|
||||
return store.get(analysisId);
|
||||
}
|
||||
|
||||
public boolean exists(String analysisId) {
|
||||
return store.containsKey(analysisId);
|
||||
}
|
||||
|
||||
public void remove(String analysisId) {
|
||||
store.remove(analysisId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,895 @@
|
||||
package com.maibu.thermal.service;
|
||||
|
||||
import com.fastbee.thermal.model.*;
|
||||
import com.fastbee.thermal.util.FileUtil;
|
||||
import com.fastbee.thermal.util.HtmlTemplateUtil;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class ThermalService {
|
||||
@Autowired
|
||||
private AnalysisStore analysisStore;
|
||||
|
||||
private final Path baseDir;
|
||||
private final Path frontendDir;
|
||||
private final Path runtimeDir;
|
||||
private final Path artifactDir;
|
||||
private final Path analysisDir;
|
||||
private final Path reportDir;
|
||||
|
||||
private final String defaultThermalTif;
|
||||
private final String defaultArrayFilledMask;
|
||||
private final String defaultPanelPixelGeojson;
|
||||
|
||||
public ThermalService() {
|
||||
// Get base directory
|
||||
this.baseDir = Paths.get(System.getProperty("user.dir")).getParent();
|
||||
this.frontendDir = baseDir.resolve("frontend");
|
||||
this.runtimeDir = baseDir.resolve("runtime");
|
||||
this.artifactDir = runtimeDir.resolve("artifacts");
|
||||
this.analysisDir = artifactDir.resolve("analyses");
|
||||
this.reportDir = artifactDir.resolve("reports");
|
||||
|
||||
// Default file paths
|
||||
this.defaultThermalTif = baseDir.resolve("tiff").resolve("thermal_002_transparent_reflectance_grayscale_cleaned_full.tif").toString();
|
||||
this.defaultArrayFilledMask = baseDir.resolve("tiff").resolve("pv_array_thermal_train5").resolve("pv_array_filled_mask.png").toString();
|
||||
this.defaultPanelPixelGeojson = baseDir.resolve("tiff").resolve("pv_array_thermal_train5").resolve("pv_panels_pixel.geojson").toString();
|
||||
|
||||
// Create directories if they don't exist
|
||||
createDirectories();
|
||||
}
|
||||
|
||||
private void createDirectories() {
|
||||
try {
|
||||
if (!analysisDir.toFile().exists()) {
|
||||
analysisDir.toFile().mkdirs();
|
||||
}
|
||||
if (!reportDir.toFile().exists()) {
|
||||
reportDir.toFile().mkdirs();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Object> getDefaults() {
|
||||
Map<String, Object> defaults = new HashMap<>();
|
||||
|
||||
// Get default analysis input
|
||||
ThermalAnalysisInput analysisInput = getDefaultAnalysisInput();
|
||||
|
||||
// Get site name from thermal path
|
||||
String siteName = "";
|
||||
if (analysisInput.getThermalPath() != null && !analysisInput.getThermalPath().isEmpty()) {
|
||||
File thermalFile = new File(analysisInput.getThermalPath());
|
||||
String fileName = thermalFile.getName();
|
||||
int dotIndex = fileName.lastIndexOf('.');
|
||||
if (dotIndex > 0) {
|
||||
siteName = fileName.substring(0, dotIndex);
|
||||
}
|
||||
}
|
||||
|
||||
// Get default report meta
|
||||
ThermalReportMeta reportMeta = getDefaultReportMeta(siteName);
|
||||
|
||||
defaults.put("analysis", analysisInput.toPublicDict());
|
||||
defaults.put("report", reportMeta.toPublicDict());
|
||||
|
||||
return defaults;
|
||||
}
|
||||
|
||||
public Map<String, Object> analyze(AnalyzeRequest request) {
|
||||
// Build thermal analysis input
|
||||
ThermalAnalysisInput analysisInput = buildRequest(request);
|
||||
|
||||
// Validate input files
|
||||
validateFile(analysisInput.getThermalPath(), "热成像TIFF");
|
||||
if (!analysisInput.getArrayMaskPath().isEmpty()) {
|
||||
validateFile(analysisInput.getArrayMaskPath(), "阵列掩膜PNG");
|
||||
}
|
||||
if (!analysisInput.getPanelGeojsonPath().isEmpty()) {
|
||||
validateFile(analysisInput.getPanelGeojsonPath(), "板框GeoJSON");
|
||||
}
|
||||
|
||||
// Run detection analysis
|
||||
Map<String, Object> result;
|
||||
try {
|
||||
result = runDetectionAnalysis(analysisInput);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e.getMessage());
|
||||
}
|
||||
|
||||
// Generate analysis ID and timestamp
|
||||
String analysisId = UUID.randomUUID().toString().replace("-", "");
|
||||
LocalDateTime createdAt = LocalDateTime.now();
|
||||
|
||||
// Generate overlay image
|
||||
String fileName = analysisId + ".png";
|
||||
Path overlayPath = analysisDir.resolve(fileName);
|
||||
|
||||
// Encode and write overlay image
|
||||
byte[] overlayImageBytes = encodeRgbPngBytes(result.get("view"));
|
||||
try {
|
||||
FileUtil.writeBinary(overlayPath, overlayImageBytes);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Failed to save overlay image: " + e.getMessage());
|
||||
}
|
||||
|
||||
// Generate overlay image URL
|
||||
String overlayUrl = "/thermal-web-artifacts/analyses/" + fileName;
|
||||
|
||||
// Store analysis
|
||||
StoredAnalysis storedAnalysis = new StoredAnalysis(analysisInput, result, createdAt, overlayUrl);
|
||||
analysisStore.put(analysisId, storedAnalysis);
|
||||
|
||||
// Serialize analysis result
|
||||
return serializeAnalysisResult(analysisId, analysisInput, result, overlayUrl, createdAt, request.isIncludePanelSegments());
|
||||
}
|
||||
|
||||
public Map<String, Object> probe(ProbeRequest request) {
|
||||
// Get stored analysis
|
||||
StoredAnalysis stored = analysisStore.get(request.getAnalysisId());
|
||||
if (stored == null) {
|
||||
throw new RuntimeException("分析结果不存在或已失效,请重新分析。");
|
||||
}
|
||||
|
||||
// Resolve source coordinates
|
||||
double[] srcCoords = resolveProbeSourceXY(stored, request);
|
||||
double srcX = srcCoords[0];
|
||||
double srcY = srcCoords[1];
|
||||
|
||||
// Get probe data
|
||||
Map<String, Object> probeData = probeSourceLocation(stored.getRequest(), stored.getResult(), request.getX(), request.getY());
|
||||
|
||||
// Build response
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("analysis_id", request.getAnalysisId());
|
||||
response.put("coordinate_space", request.getCoordinateSpace());
|
||||
response.put("source_x", (int) Math.round(srcX));
|
||||
response.put("source_y", (int) Math.round(srcY));
|
||||
response.put("probe", probeData);
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
public String generateReport(String analysisId) {
|
||||
// Get stored analysis
|
||||
StoredAnalysis stored = analysisStore.get(analysisId);
|
||||
if (stored == null) {
|
||||
throw new RuntimeException("分析结果不存在或已失效,请重新分析。");
|
||||
}
|
||||
return buildThermalReportPayload(stored.getResult());
|
||||
}
|
||||
|
||||
private ThermalAnalysisInput getDefaultAnalysisInput() {
|
||||
return new ThermalAnalysisInput(
|
||||
defaultThermalTif,
|
||||
defaultArrayFilledMask,
|
||||
defaultPanelPixelGeojson,
|
||||
48.0,
|
||||
25,
|
||||
120,
|
||||
3,
|
||||
3,
|
||||
2,
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
private ThermalReportMeta getDefaultReportMeta(String siteName) {
|
||||
return new ThermalReportMeta(
|
||||
siteName,
|
||||
siteName,
|
||||
"",
|
||||
"Thermal Inspector",
|
||||
LocalDateTime.now().toLocalDate().toString(),
|
||||
"无人机热成像巡检",
|
||||
"建议优先复核高温异常点,并结合现场电气测试、可见光照片与遮挡检查确认根因。"
|
||||
);
|
||||
}
|
||||
|
||||
private ThermalAnalysisInput buildRequest(AnalyzeRequest request) {
|
||||
return new ThermalAnalysisInput(
|
||||
request.getThermalPath(),
|
||||
request.getArrayMaskPath(),
|
||||
request.getPanelGeojsonPath(),
|
||||
request.getThresholdC(),
|
||||
request.getMinAreaPx(),
|
||||
request.getMaxRegions(),
|
||||
request.getOpenK(),
|
||||
request.getCloseK(),
|
||||
request.getShrinkIn(),
|
||||
request.isShowMaskEdge()
|
||||
).normalized();
|
||||
}
|
||||
|
||||
private void validateFile(String filePath, String fileType) {
|
||||
// if (filePath == null || filePath.isEmpty()) {
|
||||
// throw new RuntimeException(fileType + "路径不能为空");
|
||||
// }
|
||||
// File file = new File(filePath);
|
||||
// if (!file.exists()) {
|
||||
// throw new RuntimeException("未找到" + fileType + ": " + filePath);
|
||||
// }
|
||||
// if (!file.isFile()) {
|
||||
// throw new RuntimeException(fileType + "路径不是文件: " + filePath);
|
||||
// }
|
||||
}
|
||||
|
||||
public static List<RangeData> dataList = new ArrayList<>();
|
||||
|
||||
@PostConstruct
|
||||
public void intData() {
|
||||
for (int x = 1; x < 8; x++) {
|
||||
int sx = (x - 1) * 90;
|
||||
int ex = x * 90;
|
||||
double lat = 39.9042 + 0.0001 * (x - 1);
|
||||
for (int y = 1; y < 5; y++) {
|
||||
int sy = (y - 1) * 90;
|
||||
int ey = y * 90;
|
||||
double lon = 116.4074 + 0.0001 * (y - 1);
|
||||
RangeData data = new RangeData();
|
||||
data.setStartX(sx);
|
||||
data.setEndX(ex);
|
||||
data.setStartY(sy);
|
||||
data.setEndY(ey);
|
||||
double min = 45.2;
|
||||
double max = 65.8;
|
||||
double random = min + (max - min) * Math.random();
|
||||
random = Math.round(random * 100.0) / 100.0;
|
||||
data.setTemp(random);
|
||||
data.setCode(y + "-" + x);
|
||||
data.setLat(lat);
|
||||
data.setLon(lon);
|
||||
dataList.add(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Object> runDetectionAnalysis(ThermalAnalysisInput input) {
|
||||
// Mock implementation - in a real scenario, this would call the actual thermal analysis library
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
// Mock summary
|
||||
Map<String, Object> summary = new HashMap<>();
|
||||
summary.put("width", 1920);
|
||||
summary.put("height", 1080);
|
||||
summary.put("valid_px", 2073600);
|
||||
|
||||
List<RangeData> list = dataList.stream().sorted(Comparator.comparing(RangeData::getTemp).reversed()).collect(Collectors.toList());
|
||||
|
||||
summary.put("p95_temp", 50.05);
|
||||
summary.put("max_temp", list.get(0).getTemp());
|
||||
|
||||
|
||||
summary.put("array_hotspots", 15);
|
||||
summary.put("panel_hotspots", 10);
|
||||
summary.put("filtered_hotspots", 5);
|
||||
summary.put("array_mask_px", 1800000);
|
||||
summary.put("panel_polygon_count", 100);
|
||||
summary.put("panel_mask_px", 1500000);
|
||||
summary.put("array_src", "pv_array_filled_mask.png");
|
||||
summary.put("panel_src", "pv_panels_pixel.geojson");
|
||||
summary.put("threshold", input.getThresholdC());
|
||||
summary.put("thermal_name", new File(input.getThermalPath()).getName());
|
||||
|
||||
|
||||
List<Map<String, Object>> finalDf = mockFinalDf();
|
||||
|
||||
// Build panel display table
|
||||
List<Map<String, Object>> panelDisplayDf = buildPanelDisplayTable(finalDf);
|
||||
|
||||
// Build temp bucket table
|
||||
List<Map<String, Object>> tempBucketDf = buildTempBucketTable(panelDisplayDf, input.getThresholdC());
|
||||
|
||||
// Mock panel_segments
|
||||
List<Map<String, Object>> panelSegments = mockPanelSegments();
|
||||
|
||||
result.put("summary", summary);
|
||||
result.put("view", new ArrayList<>(Collections.nCopies(10, 0))); // Mock view
|
||||
result.put("view_scale", 1.0);
|
||||
result.put("final_df", finalDf);
|
||||
result.put("panel_overview", panelDisplayDf);
|
||||
result.put("temp_buckets", tempBucketDf);
|
||||
result.put("panel_segments", panelSegments);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<Map<String, Object>> mockPanelSegments() {
|
||||
List<Map<String, Object>> panelSegments = new ArrayList<>();
|
||||
|
||||
// Create mock panel segments
|
||||
for (int i = 1; i <= 5; i++) {
|
||||
Map<String, Object> segment = new HashMap<>();
|
||||
segment.put("panel_id", "1-" + i);
|
||||
segment.put("parent_id", "1");
|
||||
|
||||
// Create a simple polygon for each panel
|
||||
List<List<Double>> poly = new ArrayList<>();
|
||||
int xStart = 100 + (i - 1) * 100;
|
||||
int yStart = 100;
|
||||
poly.add(new ArrayList<>(Arrays.asList((double) xStart, (double) yStart)));
|
||||
poly.add(new ArrayList<>(Arrays.asList((double) xStart + 90, (double) yStart)));
|
||||
poly.add(new ArrayList<>(Arrays.asList((double) xStart + 90, (double) yStart + 90)));
|
||||
poly.add(new ArrayList<>(Arrays.asList((double) xStart, (double) yStart + 90)));
|
||||
segment.put("poly", poly);
|
||||
|
||||
panelSegments.add(segment);
|
||||
}
|
||||
|
||||
return panelSegments;
|
||||
}
|
||||
|
||||
private byte[] encodeRgbPngBytes(Object view) {
|
||||
// Mock implementation - in a real scenario, this would encode the actual image
|
||||
// Return a simple 1x1 PNG image
|
||||
return new byte[]{(byte) 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0, 14, 114, (byte) 205, (byte) 199, 0, 0, 0, 11, 73, 68, 65, 84, 8, (byte) 215, 99, 120, (byte) 173, (byte) 168, (byte) 213, 10, 0, 0, 0, 5, 0, 1, (byte) 134, 11, (byte) 252, 10, 0, 0, 0, 0, 73, 69, 78, 68, (byte) 174, 66, 96, (byte) 130};
|
||||
}
|
||||
|
||||
private Map<String, Object> serializeAnalysisResult(String analysisId, ThermalAnalysisInput request, Map<String, Object> result, String overlayImageUrl, LocalDateTime createdAt, boolean includePanelSegments) {
|
||||
Map<String, Object> serialized = new HashMap<>();
|
||||
serialized.put("analysis_id", analysisId);
|
||||
serialized.put("request", request.toPublicDict());
|
||||
serialized.put("result", result);
|
||||
serialized.put("overlay_image_url", overlayImageUrl);
|
||||
serialized.put("created_at", createdAt.toString());
|
||||
return serialized;
|
||||
}
|
||||
|
||||
private double[] resolveProbeSourceXY(StoredAnalysis stored, ProbeRequest request) {
|
||||
if ("source".equals(request.getCoordinateSpace())) {
|
||||
return new double[]{request.getX(), request.getY()};
|
||||
}
|
||||
|
||||
if (request.getDisplayWidth() == null || request.getDisplayHeight() == null) {
|
||||
throw new RuntimeException("coordinate_space=display 时必须传 display_width 和 display_height。");
|
||||
}
|
||||
|
||||
// Get view dimensions from result
|
||||
Map<String, Object> result = stored.getResult();
|
||||
Map<String, Object> summary = (Map<String, Object>) result.get("summary");
|
||||
int renderedWidth = (int) summary.get("width");
|
||||
int renderedHeight = (int) summary.get("height");
|
||||
double scale = (double) result.get("view_scale");
|
||||
|
||||
double viewX = request.getX() * renderedWidth / Math.max(request.getDisplayWidth(), 1.0);
|
||||
double viewY = request.getY() * renderedHeight / Math.max(request.getDisplayHeight(), 1.0);
|
||||
|
||||
// Convert to source coordinates
|
||||
return new double[]{viewX / Math.max(scale, 1e-6), viewY / Math.max(scale, 1e-6)};
|
||||
}
|
||||
|
||||
|
||||
private Map<String, Object> probeSourceLocation(ThermalAnalysisInput request, Map<String, Object> result, double x, double y) {
|
||||
// Mock implementation - in a real scenario, this would use the actual thermal data
|
||||
Map<String, Object> probeData = new HashMap<>();
|
||||
|
||||
// Get summary and view scale
|
||||
Map<String, Object> summary = (Map<String, Object>) result.get("summary");
|
||||
double scale = (double) result.get("view_scale");
|
||||
|
||||
// Calculate source coordinates with clipping
|
||||
int srcW = (int) summary.get("width");
|
||||
int srcH = (int) summary.get("height");
|
||||
int xSrc = (int) Math.round(x);
|
||||
xSrc = Math.max(0, Math.min(xSrc, srcW - 1));
|
||||
int ySrc = (int) Math.round(y);
|
||||
ySrc = Math.max(0, Math.min(ySrc, srcH - 1));
|
||||
|
||||
// Mock temperature
|
||||
double tempC = 52.3; // In a real scenario, this would come from the thermal data
|
||||
|
||||
// Find panel segment at point
|
||||
Map<String, Object> panelSeg = findPanelSegmentAtPoint(result.get("panel_segments"), xSrc, ySrc);
|
||||
String panelId = panelSeg != null && panelSeg.containsKey("panel_id") ? cleanIdText(panelSeg.get("panel_id").toString()) : "";
|
||||
String blockId = panelSeg != null && panelSeg.containsKey("parent_id") ? cleanIdText(panelSeg.get("parent_id").toString()) : "";
|
||||
|
||||
// Mock GPS data
|
||||
double lat = 39.9042;
|
||||
double lon = 116.4074;
|
||||
|
||||
// Build probe data
|
||||
probeData.put("x", xSrc);
|
||||
probeData.put("y", ySrc);
|
||||
probeData.put("plot_x", (int) Math.round(xSrc * scale));
|
||||
probeData.put("plot_y", (int) Math.round(ySrc * scale));
|
||||
|
||||
RangeData rangeData = dataList.stream().filter(item -> item.contains(x, y)).findFirst().orElse(null);
|
||||
if (rangeData != null) {
|
||||
probeData.put("temp_c", rangeData.getTemp());
|
||||
probeData.put("panel_id", rangeData.getCode());
|
||||
probeData.put("block_id", rangeData.getCode());
|
||||
probeData.put("lat", rangeData.getLat());
|
||||
probeData.put("lon", rangeData.getLon());
|
||||
} else {
|
||||
probeData.put("temp_c", "");
|
||||
probeData.put("panel_id", panelId.isEmpty() ? "未命中板框" : panelId);
|
||||
probeData.put("block_id", blockId.isEmpty() ? "-" : blockId);
|
||||
probeData.put("lat", roundToDecimalPlaces(lat, 6));
|
||||
probeData.put("lon", roundToDecimalPlaces(lon, 6));
|
||||
}
|
||||
probeData.put("gps_text", formatGps(lat, lon));
|
||||
|
||||
return probeData;
|
||||
}
|
||||
|
||||
private Map<String, Object> findPanelSegmentAtPoint(Object panelSegments, int x, int y) {
|
||||
if (panelSegments instanceof List) {
|
||||
List<?> segments = (List<?>) panelSegments;
|
||||
System.out.println("Panel segments size: " + segments.size());
|
||||
|
||||
for (Object segment : segments) {
|
||||
// Check if segment is a map with required properties
|
||||
if (segment instanceof Map) {
|
||||
Map<?, ?> segMap = (Map<?, ?>) segment;
|
||||
// Check if the segment contains a polygon
|
||||
if (segMap.containsKey("poly")) {
|
||||
Object polyObj = segMap.get("poly");
|
||||
// Check if poly is a list of coordinates
|
||||
if (polyObj instanceof List) {
|
||||
List<?> poly = (List<?>) polyObj;
|
||||
// Check if the point is inside the polygon
|
||||
boolean isInside = isPointInPolygon(x, y, poly);
|
||||
if (isInside) {
|
||||
System.out.println("Point (" + x + ", " + y + ") is inside panel segment");
|
||||
// Convert to Map<String, Object> and return
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
if (segMap.containsKey("panel_id")) {
|
||||
result.put("panel_id", segMap.get("panel_id").toString());
|
||||
}
|
||||
if (segMap.containsKey("parent_id")) {
|
||||
result.put("parent_id", segMap.get("parent_id").toString());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
System.out.println("Panel segments is not a list: " + (panelSegments != null ? panelSegments.getClass() : "null"));
|
||||
}
|
||||
System.out.println("No panel segment found for point (" + x + ", " + y + ")");
|
||||
return null;
|
||||
}
|
||||
|
||||
private boolean isPointInPolygon(int x, int y, List<?> polygon) {
|
||||
boolean inside = false;
|
||||
int n = polygon.size();
|
||||
|
||||
// Iterate through each edge of the polygon
|
||||
for (int i = 0, j = n - 1; i < n; j = i++) {
|
||||
// Get current and next point
|
||||
Object pointI = polygon.get(i);
|
||||
Object pointJ = polygon.get(j);
|
||||
|
||||
// Check if points are valid coordinate pairs
|
||||
if (!(pointI instanceof List) || !(pointJ instanceof List)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
List<?> coordI = (List<?>) pointI;
|
||||
List<?> coordJ = (List<?>) pointJ;
|
||||
|
||||
if (coordI.size() < 2 || coordJ.size() < 2) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
// Get coordinates
|
||||
double xi = Double.parseDouble(coordI.get(0).toString());
|
||||
double yi = Double.parseDouble(coordI.get(1).toString());
|
||||
double xj = Double.parseDouble(coordJ.get(0).toString());
|
||||
double yj = Double.parseDouble(coordJ.get(1).toString());
|
||||
|
||||
// Check if the point's y-coordinate is within the edge's y-range
|
||||
boolean intersect = ((yi > y) != (yj > y)) &&
|
||||
(x < (xj - xi) * (y - yi) / (yj - yi) + xi);
|
||||
|
||||
if (intersect) {
|
||||
inside = !inside;
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
// Ignore invalid coordinates
|
||||
}
|
||||
}
|
||||
|
||||
return inside;
|
||||
}
|
||||
|
||||
private double roundToDecimalPlaces(double value, int places) {
|
||||
double scale = Math.pow(10, places);
|
||||
return Math.round(value * scale) / scale;
|
||||
}
|
||||
|
||||
private String buildThermalReportPayload(Map<String, Object> result) {
|
||||
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||
|
||||
result.put("reportDate", sdf.format(new Date()));
|
||||
List<Map<String, Object>> s = (List<Map<String, Object>>) result.get("temp_buckets");
|
||||
result.put("t1", s.get(0).get("数量"));
|
||||
result.put("t2", s.get(1).get("数量"));
|
||||
result.put("t3", s.get(2).get("数量"));
|
||||
|
||||
Map<String, Object> summary = (Map<String, Object>) result.get("summary");
|
||||
result.put("p95_temp", summary.get("p95_temp"));
|
||||
result.put("max_temp", summary.get("max_temp"));
|
||||
|
||||
// 获取面板概览数据
|
||||
List<Map<String, Object>> panelOverview = (List<Map<String, Object>>) result.get("panel_overview");
|
||||
|
||||
// 生成异常明细表格HTML
|
||||
String anomalyDetailRows = buildAnomalyDetailTableRows(panelOverview, 48);
|
||||
result.put("anomalyDetailRows", anomalyDetailRows);
|
||||
|
||||
String html = HtmlTemplateUtil.renderFromFile("templates/reportTemplate.html", result);
|
||||
|
||||
|
||||
return html;
|
||||
}
|
||||
|
||||
private String buildAnomalyDetailTableRows(List<Map<String, Object>> panelOverview, double thresholdC) {
|
||||
if (panelOverview == null || panelOverview.isEmpty()) {
|
||||
return "<tr><td colspan=\"8\" style=\"text-align: center; padding: 20px; color: #999;\">暂无异常数据</td></tr>";
|
||||
}
|
||||
|
||||
StringBuilder htmlBuilder = new StringBuilder();
|
||||
int totalItems = panelOverview.size();
|
||||
|
||||
for (int i = 0; i < panelOverview.size(); i++) {
|
||||
Map<String, Object> row = panelOverview.get(i);
|
||||
|
||||
// 获取各字段数据
|
||||
String code = getSafeString(row, "编号");
|
||||
Double temp = getSafeDouble(row, "温度(℃)");
|
||||
String area = getSafeString(row, "逆变器");
|
||||
String gps = getSafeString(row, "GPS位置");
|
||||
Integer blockId = getSafeInteger(row, "块号");
|
||||
|
||||
// 固定优先级分配:前3个高,中间3个中,后面低
|
||||
String priorityText;
|
||||
String priorityClass;
|
||||
if (i < 3) {
|
||||
priorityText = "高优先级";
|
||||
priorityClass = "priority-high";
|
||||
} else if (i < 6) {
|
||||
priorityText = "中优先级";
|
||||
priorityClass = "priority-medium";
|
||||
} else {
|
||||
priorityText = "低优先级";
|
||||
priorityClass = "priority-low";
|
||||
}
|
||||
|
||||
// 计算超阈值,带加号
|
||||
String overThreshold = temp != null ? String.format("+%.2f℃", temp - thresholdC) : "-";
|
||||
|
||||
// 温度格式化为两位小数
|
||||
String tempStr = temp != null ? String.format("%.2f℃", temp) : "-";
|
||||
|
||||
// 生成像素坐标,格式为 "x=xxx, y=xxx"
|
||||
String pixelCoords = getSafeString(row, "阵列号");
|
||||
|
||||
// 构建表格行
|
||||
htmlBuilder.append("<tr>");
|
||||
htmlBuilder.append("<td>").append(code).append("</td>");
|
||||
htmlBuilder.append("<td><span class=\"priority-pill ").append(priorityClass).append("\">")
|
||||
.append(priorityText).append("</span></td>");
|
||||
htmlBuilder.append("<td>").append(tempStr).append("</td>");
|
||||
htmlBuilder.append("<td>").append(overThreshold).append("</td>");
|
||||
htmlBuilder.append("<td>").append(area != null ? area : "-").append("</td>");
|
||||
htmlBuilder.append("<td>").append(pixelCoords).append("</td>");
|
||||
htmlBuilder.append("<td>").append(blockId != null ? blockId : "-").append("</td>");
|
||||
htmlBuilder.append("<td>").append(gps).append("</td>");
|
||||
htmlBuilder.append("</tr>");
|
||||
}
|
||||
|
||||
return htmlBuilder.toString();
|
||||
}
|
||||
|
||||
private String generatePixelCoords(String code) {
|
||||
// 根据编号生成模拟像素坐标,格式为 "x=xxx, y=xxx"
|
||||
if (code == null || code.isEmpty()) {
|
||||
return "-";
|
||||
}
|
||||
|
||||
try {
|
||||
// 解析编号格式如 "1-2"
|
||||
String[] parts = code.split("-");
|
||||
if (parts.length == 2) {
|
||||
int block = Integer.parseInt(parts[0]);
|
||||
int panel = Integer.parseInt(parts[1]);
|
||||
int x = (block - 1) * 1000 + panel * 100;
|
||||
int y = (panel - 1) * 500 + 100;
|
||||
return String.format("x=%d, y=%d", x, y);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// 忽略解析错误
|
||||
}
|
||||
|
||||
return "-";
|
||||
}
|
||||
|
||||
private String getSafeString(Map<String, Object> map, String key) {
|
||||
Object value = map.get(key);
|
||||
return value != null ? value.toString() : "";
|
||||
}
|
||||
|
||||
private Double getSafeDouble(Map<String, Object> map, String key) {
|
||||
Object value = map.get(key);
|
||||
if (value instanceof Number) {
|
||||
return ((Number) value).doubleValue();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private Integer getSafeInteger(Map<String, Object> map, String key) {
|
||||
Object value = map.get(key);
|
||||
if (value instanceof Number) {
|
||||
return ((Number) value).intValue();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
private List<Map<String, Object>> mockFinalDf() {
|
||||
List<Map<String, Object>> finalDf = new ArrayList<>();
|
||||
|
||||
List<RangeData> list = dataList.stream().sorted(Comparator.comparing(RangeData::getTemp).reversed()).collect(Collectors.toList());
|
||||
|
||||
// Mock some hotspots
|
||||
for (int i = 1; i <= 10; i++) {
|
||||
Map<String, Object> hotspot = new HashMap<>();
|
||||
RangeData rangeData = list.get(i - 1);
|
||||
hotspot.put("panel_id", rangeData.getCode());
|
||||
hotspot.put("最高温(℃)", rangeData.getTemp());
|
||||
hotspot.put("面积(px)", 100 + i * 10);
|
||||
hotspot.put("纬度", rangeData.getLat());
|
||||
hotspot.put("经度", rangeData.getLon());
|
||||
finalDf.add(hotspot);
|
||||
}
|
||||
|
||||
return finalDf;
|
||||
}
|
||||
|
||||
private List<Map<String, Object>> buildPanelDisplayTable(List<Map<String, Object>> hotspots) {
|
||||
List<Map<String, Object>> result = new ArrayList<>();
|
||||
|
||||
if (hotspots == null || hotspots.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// Process hotspots
|
||||
Map<String, Map<String, Object>> namedHotspots = new HashMap<>();
|
||||
List<Map<String, Object>> unnamedHotspots = new ArrayList<>();
|
||||
|
||||
for (Map<String, Object> hotspot : hotspots) {
|
||||
Map<String, Object> processed = new HashMap<>(hotspot);
|
||||
|
||||
// Set 编号
|
||||
if (hotspot.containsKey("panel_id")) {
|
||||
processed.put("编号", cleanIdText(hotspot.get("panel_id").toString()));
|
||||
} else if (hotspot.containsKey("sub_id")) {
|
||||
processed.put("编号", cleanIdText(hotspot.get("sub_id").toString()));
|
||||
} else if (hotspot.containsKey("热斑ID")) {
|
||||
try {
|
||||
int hotId = Integer.parseInt(hotspot.get("热斑ID").toString());
|
||||
processed.put("编号", "热斑#" + hotId);
|
||||
} catch (Exception e) {
|
||||
processed.put("编号", "");
|
||||
}
|
||||
} else {
|
||||
processed.put("编号", "");
|
||||
}
|
||||
|
||||
if (processed.get("编号") != null) {
|
||||
String s = String.valueOf(processed.get("编号").toString());
|
||||
String[] sl = s.split("-");
|
||||
if (sl.length > 1) {
|
||||
processed.put("逆变器", sl[0]);
|
||||
processed.put("阵列号", sl[1]);
|
||||
}
|
||||
}
|
||||
|
||||
// Set 温度(℃)
|
||||
if (hotspot.containsKey("最高温(℃)")) {
|
||||
try {
|
||||
processed.put("温度(℃)", Double.parseDouble(hotspot.get("最高温(℃)").toString()));
|
||||
} catch (Exception e) {
|
||||
processed.put("温度(℃)", null);
|
||||
}
|
||||
} else {
|
||||
processed.put("温度(℃)", null);
|
||||
}
|
||||
|
||||
// Set 面积(px)
|
||||
if (hotspot.containsKey("面积(px)")) {
|
||||
try {
|
||||
processed.put("面积(px)", Integer.parseInt(hotspot.get("面积(px)").toString()));
|
||||
} catch (Exception e) {
|
||||
processed.put("面积(px)", null);
|
||||
}
|
||||
} else {
|
||||
processed.put("面积(px)", null);
|
||||
}
|
||||
|
||||
// Set 纬度和经度
|
||||
double lat = 0.0, lon = 0.0;
|
||||
if (hotspot.containsKey("纬度")) {
|
||||
try {
|
||||
lat = Double.parseDouble(hotspot.get("纬度").toString());
|
||||
processed.put("纬度", lat);
|
||||
} catch (Exception e) {
|
||||
processed.put("纬度", null);
|
||||
}
|
||||
} else {
|
||||
processed.put("纬度", null);
|
||||
}
|
||||
|
||||
if (hotspot.containsKey("经度")) {
|
||||
try {
|
||||
lon = Double.parseDouble(hotspot.get("经度").toString());
|
||||
processed.put("经度", lon);
|
||||
} catch (Exception e) {
|
||||
processed.put("经度", null);
|
||||
}
|
||||
} else {
|
||||
processed.put("经度", null);
|
||||
}
|
||||
|
||||
// Set GPS位置
|
||||
processed.put("GPS位置", formatGps(lat, lon));
|
||||
|
||||
// Set 异常点数
|
||||
processed.put("异常点数", 1);
|
||||
|
||||
// Set 块号
|
||||
String id = processed.get("编号").toString();
|
||||
if (!id.isEmpty()) {
|
||||
try {
|
||||
String blockId = id.split("-")[0];
|
||||
processed.put("块号", Integer.parseInt(blockId));
|
||||
} catch (Exception e) {
|
||||
processed.put("块号", null);
|
||||
}
|
||||
} else {
|
||||
processed.put("块号", null);
|
||||
}
|
||||
|
||||
// Separate named and unnamed hotspots
|
||||
if (!id.isEmpty()) {
|
||||
if (!namedHotspots.containsKey(id)) {
|
||||
namedHotspots.put(id, processed);
|
||||
}
|
||||
} else {
|
||||
unnamedHotspots.add(processed);
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate anomaly count for named hotspots
|
||||
Map<String, Integer> anomalyCount = new HashMap<>();
|
||||
for (Map<String, Object> hotspot : hotspots) {
|
||||
String id = "";
|
||||
if (hotspot.containsKey("panel_id")) {
|
||||
id = cleanIdText(hotspot.get("panel_id").toString());
|
||||
} else if (hotspot.containsKey("sub_id")) {
|
||||
id = cleanIdText(hotspot.get("sub_id").toString());
|
||||
}
|
||||
|
||||
if (!id.isEmpty()) {
|
||||
anomalyCount.put(id, anomalyCount.getOrDefault(id, 0) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Update anomaly count
|
||||
for (Map.Entry<String, Map<String, Object>> entry : namedHotspots.entrySet()) {
|
||||
entry.getValue().put("异常点数", anomalyCount.getOrDefault(entry.getKey(), 1));
|
||||
}
|
||||
|
||||
// Combine named and unnamed hotspots
|
||||
List<Map<String, Object>> combined = new ArrayList<>(namedHotspots.values());
|
||||
combined.addAll(unnamedHotspots);
|
||||
|
||||
// Sort by temperature and area
|
||||
combined.sort(new Comparator<Map<String, Object>>() {
|
||||
@Override
|
||||
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
|
||||
// Compare temperature
|
||||
Double temp1 = (Double) o1.get("温度(℃)");
|
||||
Double temp2 = (Double) o2.get("温度(℃)");
|
||||
if (temp1 == null && temp2 == null) return 0;
|
||||
if (temp1 == null) return 1;
|
||||
if (temp2 == null) return -1;
|
||||
int tempCompare = temp2.compareTo(temp1); // Descending
|
||||
if (tempCompare != 0) return tempCompare;
|
||||
|
||||
// Compare area
|
||||
Integer area1 = (Integer) o1.get("面积(px)");
|
||||
Integer area2 = (Integer) o2.get("面积(px)");
|
||||
if (area1 == null && area2 == null) return 0;
|
||||
if (area1 == null) return 1;
|
||||
if (area2 == null) return -1;
|
||||
return area2.compareTo(area1); // Descending
|
||||
}
|
||||
});
|
||||
|
||||
return combined;
|
||||
}
|
||||
|
||||
private List<Map<String, Object>> buildTempBucketTable(List<Map<String, Object>> panelDf, double thresholdC) {
|
||||
List<Map<String, Object>> result = new ArrayList<>();
|
||||
|
||||
if (panelDf == null || panelDf.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// Collect temperatures
|
||||
List<Double> temps = new ArrayList<>();
|
||||
for (Map<String, Object> row : panelDf) {
|
||||
if (row.containsKey("温度(℃)") && row.get("温度(℃)") != null) {
|
||||
try {
|
||||
temps.add((Double) row.get("温度(℃)"));
|
||||
} catch (Exception e) {
|
||||
// Ignore invalid temperatures
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (temps.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// Define bins
|
||||
double[] bins = {thresholdC, thresholdC + 5.0, thresholdC + 10.0, Double.POSITIVE_INFINITY};
|
||||
String[] labels = {
|
||||
String.format("%.1f~%.1f℃", thresholdC, thresholdC + 5.0),
|
||||
String.format("%.1f~%.1f℃", thresholdC + 5.0, thresholdC + 10.0),
|
||||
String.format(">=%.1f℃", thresholdC + 10.0)
|
||||
};
|
||||
|
||||
// Count temperatures in each bin
|
||||
int[] counts = new int[3];
|
||||
for (double temp : temps) {
|
||||
if (temp < bins[1]) {
|
||||
counts[0]++;
|
||||
} else if (temp < bins[2]) {
|
||||
counts[1]++;
|
||||
} else {
|
||||
counts[2]++;
|
||||
}
|
||||
}
|
||||
|
||||
// Build result
|
||||
for (int i = 0; i < 3; i++) {
|
||||
Map<String, Object> bucket = new HashMap<>();
|
||||
bucket.put("温度区间", labels[i]);
|
||||
bucket.put("数量", counts[i]);
|
||||
result.add(bucket);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private String cleanIdText(String text) {
|
||||
if (text == null) return "";
|
||||
return text.trim().replaceAll("\\s+", " ");
|
||||
}
|
||||
|
||||
private String formatGps(double lat, double lon) {
|
||||
if (lat == 0.0 && lon == 0.0) return "";
|
||||
return String.format("%.6f, %.6f", lat, lon);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.maibu.thermal.util;
|
||||
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
|
||||
public class FileUtil {
|
||||
|
||||
public static void writeBinary(Path path, byte[] data) throws IOException {
|
||||
try (FileOutputStream fos = new FileOutputStream(path.toFile())) {
|
||||
fos.write(data);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.maibu.thermal.util;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class HtmlTemplateUtil {
|
||||
|
||||
// 匹配 ${xxx}
|
||||
private static final Pattern PATTERN = Pattern.compile("\\$\\{(\\w+)}");
|
||||
|
||||
/**
|
||||
* 渲染模板(读取文件 + 替换变量)
|
||||
* @param templatePath resources目录下路径,例如:templates/test.html
|
||||
* @param data 替换数据
|
||||
*/
|
||||
public static String renderFromFile(String templatePath, Map<String, Object> data) {
|
||||
String template = loadTemplate(templatePath);
|
||||
return render(template, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 替换占位符
|
||||
*/
|
||||
public static String render(String template, Map<String, Object> data) {
|
||||
if (template == null || template.isEmpty()) {
|
||||
return template;
|
||||
}
|
||||
|
||||
Matcher matcher = PATTERN.matcher(template);
|
||||
StringBuffer sb = new StringBuffer();
|
||||
|
||||
while (matcher.find()) {
|
||||
String key = matcher.group(1);
|
||||
Object value = data.get(key);
|
||||
|
||||
String replacement = (value == null) ? "" : value.toString();
|
||||
|
||||
// 防止 $ 和 \ 导致异常
|
||||
replacement = Matcher.quoteReplacement(replacement);
|
||||
|
||||
matcher.appendReplacement(sb, replacement);
|
||||
}
|
||||
|
||||
matcher.appendTail(sb);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取 resources 下的 html 文件
|
||||
*/
|
||||
private static String loadTemplate(String path) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
try (InputStream is = HtmlTemplateUtil.class
|
||||
.getClassLoader()
|
||||
.getResourceAsStream(path);
|
||||
BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(is, StandardCharsets.UTF_8))) {
|
||||
|
||||
if (is == null) {
|
||||
throw new RuntimeException("模板文件不存在: " + path);
|
||||
}
|
||||
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
sb.append(line).append("\n");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("读取模板失败", e);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.maibu.uav.controller;
|
||||
|
||||
import com.fastbee.common.core.controller.BaseController;
|
||||
import com.fastbee.common.core.domain.AjaxResult;
|
||||
import com.fastbee.uav.dto.*;
|
||||
import com.fastbee.uav.service.UAVService;
|
||||
import io.minio.errors.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/iot/UAV")
|
||||
public class UAVController extends BaseController {
|
||||
|
||||
@Autowired
|
||||
private UAVService uavService;
|
||||
|
||||
|
||||
@GetMapping("/getProjectDeviceList")
|
||||
public AjaxResult getProjectDeviceList() {
|
||||
UavDeviceStateResponseDTO result = uavService.getProjectDeviceList();
|
||||
return AjaxResult.success(result);
|
||||
}
|
||||
|
||||
@GetMapping("/getDeviceHMS")
|
||||
public String getDeviceHMS(@RequestParam String deviceSn) {
|
||||
return uavService.getDeviceHMS(deviceSn);
|
||||
}
|
||||
|
||||
@GetMapping("/getDeviceState")
|
||||
public String getDeviceState(@RequestParam String deviceSn) {
|
||||
return uavService.getDeviceState(deviceSn);
|
||||
}
|
||||
|
||||
@GetMapping("/getWayline")
|
||||
public String getWayline() {
|
||||
return uavService.getWayline();
|
||||
}
|
||||
|
||||
@GetMapping("/getWaylineDetail")
|
||||
public String getWaylineDetail(@RequestParam String waylineId) {
|
||||
return uavService.getWaylineDetail(waylineId);
|
||||
}
|
||||
|
||||
@PostMapping("/createFlightTask")
|
||||
public String createFlightTask(@RequestBody FlightTaskCreateDTO dto) {
|
||||
return uavService.createFlightTask(dto);
|
||||
}
|
||||
|
||||
@PostMapping("/flightTaskCommand")
|
||||
public String flightTaskCommand(@RequestBody FlightTaskCommandDTO dto) {
|
||||
return uavService.flightTaskCommand(dto);
|
||||
}
|
||||
|
||||
/**
|
||||
* 在线直播
|
||||
*
|
||||
* @param dto
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/liveStream")
|
||||
public AjaxResult liveStream(@RequestBody CameraLiveParamDTO dto) {
|
||||
return AjaxResult.success(uavService.liveStream(dto));
|
||||
}
|
||||
|
||||
@GetMapping("/getFlightTask")
|
||||
public String getFlightTask(@RequestParam String sn) {
|
||||
return uavService.flightTaskList(sn);
|
||||
}
|
||||
|
||||
@GetMapping("/getFlightTaskDetail")
|
||||
public String flightTaskDetail(@RequestParam String taskId) {
|
||||
return uavService.flightTaskDetail(taskId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取飞行轨迹
|
||||
*
|
||||
* @param taskId
|
||||
* @return
|
||||
*/
|
||||
@GetMapping("/getFlightTaskTrack")
|
||||
public String getFlightTaskTrack(@RequestParam String taskId) {
|
||||
return uavService.getFlightTaskTrack(taskId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传航线文件并通知完成
|
||||
*
|
||||
* @param file
|
||||
* @param name
|
||||
* @return
|
||||
* @throws ServerException
|
||||
* @throws InsufficientDataException
|
||||
* @throws ErrorResponseException
|
||||
* @throws IOException
|
||||
* @throws NoSuchAlgorithmException
|
||||
* @throws InvalidKeyException
|
||||
* @throws InvalidResponseException
|
||||
* @throws XmlParserException
|
||||
* @throws InternalException
|
||||
*/
|
||||
@PostMapping("/uploadWayline")
|
||||
public Object uploadWayline(MultipartFile file, @RequestParam String name) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
|
||||
return uavService.uploadWayline(file, name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新飞行任务状态
|
||||
*
|
||||
* @param taskId status suspended 任务挂起/ restored任务恢复
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/updateFlightTaskStatus")
|
||||
public String updateFlightTaskStatus(@RequestParam String taskId, @RequestParam String status) {
|
||||
return uavService.updateFlightTaskStatus(taskId, status);
|
||||
}
|
||||
|
||||
@PostMapping("/liveHeartbeat")
|
||||
public AjaxResult liveHeartbeat(@RequestParam String sn, @RequestParam String cameraIndex) {
|
||||
uavService.liveHeartbeat(sn, cameraIndex);
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
@PostMapping("/changeCamera")
|
||||
public String changeCamera(@RequestParam String sn, @RequestParam String cameraIndex, @RequestParam String cameraPosition) {
|
||||
return uavService.changeCamera(sn, cameraIndex, cameraPosition);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.maibu.uav.dto;
|
||||
|
||||
import com.fastbee.uav.entity.CameraInfo;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class CameraLiveParamDTO {
|
||||
private String getway_sn;
|
||||
private String drone_sn;
|
||||
private List<CameraInfo> getway_camera_list;
|
||||
private List<CameraInfo> drone_camera_list;
|
||||
private Long video_expire;
|
||||
private String quality_type; //adaptive 自动 smooth流畅 ultra_high_definition超清
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.maibu.uav.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class CameraLiveResultDTO {
|
||||
private String sn;
|
||||
private String camera_index;
|
||||
private String url;
|
||||
private Long expire_ts;
|
||||
private String url_type;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.maibu.uav.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class CameraLiveStreamDTO {
|
||||
private String sn;
|
||||
private String camera_index;
|
||||
private Long video_expire;
|
||||
private String quality_type; //adaptive 自动 smooth流畅 ultra_high_definition超清
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.maibu.uav.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class CameraLiveStreamResultDTO {
|
||||
private String url;
|
||||
private Long expire_ts;
|
||||
private String url_type;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.maibu.uav.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class FlightTaskCommandDTO {
|
||||
private UAVCommand command;
|
||||
private String deviceSn;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.maibu.uav.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class FlightTaskCreateDTO {
|
||||
private String name;
|
||||
private String sn;
|
||||
private String wayline_uuid;
|
||||
private String time_zone;
|
||||
private Integer rth_altitude;
|
||||
private String rth_mode;
|
||||
private String wayline_precision_type;
|
||||
private String resumable_status;
|
||||
private String task_type;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.maibu.uav.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class SK2ResultDTO {
|
||||
private int code;
|
||||
private String message;
|
||||
private Object data;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.maibu.uav.dto;
|
||||
|
||||
public enum UAVCommand {
|
||||
return_home, //返航
|
||||
return_specific_home,//蛙跳任务指定目标机场返航
|
||||
return_home_cancel, //取消返航
|
||||
flighttask_pause, //飞行任务暂停
|
||||
flighttask_recovery //飞行任务恢复
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.maibu.uav.dto;
|
||||
|
||||
import com.fastbee.uav.entity.DeviceModel;
|
||||
import com.fastbee.uav.entity.UavDeviceState;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class UavDeviceStateDTO {
|
||||
private String device_sn;
|
||||
private DeviceModel device_model;
|
||||
private UavDeviceState device_state;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.maibu.uav.dto;
|
||||
|
||||
import com.fastbee.uav.entity.DeviceModel;
|
||||
import com.fastbee.uav.entity.UavDeviceState;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class UavDeviceStateResponseDTO {
|
||||
private Integer total;
|
||||
private Integer online;
|
||||
private Integer offline;
|
||||
private List<UavDeviceStateResponseDetailDTO> detail;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.maibu.uav.dto;
|
||||
|
||||
import com.fastbee.uav.entity.CameraInfo;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class UavDeviceStateResponseDetailDTO {
|
||||
private String device_sn;
|
||||
private String gateway_sn;
|
||||
private String callsign;
|
||||
private String drone_callsign;
|
||||
private Integer onlineStatus; //1在线2离线
|
||||
private Integer drone_onlineStatus; //1在线2离线
|
||||
private Double latitude;
|
||||
private Double longitude;
|
||||
private Integer capacity_percent;
|
||||
private Double wind_speed;
|
||||
private Double height;
|
||||
private Float environment_temperature;
|
||||
private Object network_state;
|
||||
private Object position_state;
|
||||
private Double home_distance;
|
||||
private Object live_capacity;
|
||||
private String rainfall;
|
||||
|
||||
private List<CameraInfo> gateway_camera_list;
|
||||
private List<CameraInfo> drone_camera_list;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.maibu.uav.dto;
|
||||
|
||||
import com.fastbee.uav.entity.UavDevice;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class UavProjectDeviceDTO {
|
||||
|
||||
private UavDevice gateway;
|
||||
private UavDevice drone;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.maibu.uav.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class UavStsTokenCredentials {
|
||||
private String access_key_id;
|
||||
private String access_key_secret;
|
||||
private Integer expire;
|
||||
private String security_token;
|
||||
private Integer platform;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.maibu.uav.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class UavStsTokenDTO {
|
||||
private String endpoint;
|
||||
private String provider;
|
||||
private String region;
|
||||
private String bucket;
|
||||
private String object_key_prefix;
|
||||
private UavStsTokenCredentials credentials;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.maibu.uav.entity;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class CameraInfo {
|
||||
private String camera_index;
|
||||
private List<String> available_camera_positions;
|
||||
private String camera_position;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.maibu.uav.entity;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class DeviceModel {
|
||||
private String key;
|
||||
private String domain;
|
||||
private String type;
|
||||
private String sub_type;
|
||||
private String name;
|
||||
@JsonProperty("class")
|
||||
private String className;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.maibu.uav.entity;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class UavBattery {
|
||||
private Object batteries;
|
||||
private Integer capacity_percent;
|
||||
private Integer landing_power;
|
||||
private Integer remain_flight_time;
|
||||
private Integer return_home_power;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.maibu.uav.entity;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class UavDevice {
|
||||
private String sn;
|
||||
private String callsign;
|
||||
private DeviceModel device_model;
|
||||
private Boolean device_online_status;
|
||||
private Integer mode_code;
|
||||
private List<CameraInfo> camera_list;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.maibu.uav.entity;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class UavDeviceState {
|
||||
private Long activation_time;
|
||||
private Double attitude_head;
|
||||
private Double attitude_pitch;
|
||||
private Double attitude_roll;
|
||||
private UavBattery battery;
|
||||
|
||||
private String best_link_gateway;
|
||||
private Object camera_watermark_settings;
|
||||
private Object cameras;
|
||||
private Double commander_flight_height;
|
||||
private String commander_flight_mode;
|
||||
private String commander_mode_lost_action;
|
||||
private String no_consistency_upgrade_required;
|
||||
private String control_source;
|
||||
private String current_rth_mode;
|
||||
private Object dongle_infos;
|
||||
private Double elevation;
|
||||
private String firmware_upgrade_status;
|
||||
private String firmware_version;
|
||||
private String flysafe_database_version;
|
||||
private String gear;
|
||||
private Double height;
|
||||
private Double height_limit;
|
||||
private Double home_distance;
|
||||
private Double home_latitude;
|
||||
private Double home_longitude;
|
||||
private Double horizontal_speed;
|
||||
private String not_reaching_the_geo_zone;
|
||||
private String is_near_height_limit;
|
||||
private Double latitude; //经纬度
|
||||
private Double longitude;
|
||||
private Double low_battery_warning_threshold;
|
||||
private Object maintain_status;
|
||||
private String mode_code;
|
||||
private String mode_code_reason;
|
||||
private String night_lights_state;
|
||||
private Object obstacle_avoidance;
|
||||
private Boolean offline_map_enable;
|
||||
private Object position_state;
|
||||
private Integer rth_mode;
|
||||
private Double serious_low_battery_warning_threshold;
|
||||
private Object storage;
|
||||
private Double total_flight_distance;
|
||||
private Double total_flight_sorties;
|
||||
private Double total_flight_time;
|
||||
private String track_id;
|
||||
private Double vertical_speed;
|
||||
private String wind_direction;
|
||||
private Double wind_speed;
|
||||
private Object wireless_link_topo;
|
||||
@JsonProperty("80-0-0")
|
||||
private Object key80;
|
||||
private Float environment_temperature;
|
||||
private Object network_state;
|
||||
private Object live_capacity;
|
||||
private String rainfall;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.maibu.uav.entity;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class UavProject {
|
||||
private String name;
|
||||
private String introduction;
|
||||
private String uuid;
|
||||
private String org_uuid;
|
||||
private Map<String,Double> project_work_center_point;
|
||||
private Long created_at;
|
||||
private Long updated_at;
|
||||
}
|
||||
@@ -0,0 +1,407 @@
|
||||
package com.maibu.uav.service;
|
||||
|
||||
import com.fastbee.common.utils.StringUtils;
|
||||
import com.fastbee.common.utils.json.JsonUtils;
|
||||
import com.fastbee.iot.domain.DevicePlanTask;
|
||||
import com.fastbee.uav.dto.*;
|
||||
import com.fastbee.uav.entity.UavDevice;
|
||||
import com.fastbee.uav.entity.UavDeviceState;
|
||||
import com.fastbee.uav.utils.UavHttpUtils;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.minio.MinioClient;
|
||||
import io.minio.PutObjectArgs;
|
||||
import io.minio.credentials.StaticProvider;
|
||||
import io.minio.errors.*;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class UAVService {
|
||||
|
||||
|
||||
@Value("${UAV.baseUrl:https://es-flight-api-cn.djigate.com}")
|
||||
private String baseUrl;
|
||||
|
||||
@Autowired
|
||||
private UavHttpUtils httpService;
|
||||
|
||||
|
||||
public static final Map<String, Long> latestActiveTime = new ConcurrentHashMap<>();
|
||||
|
||||
public static final Map<String, CameraLiveResultDTO> liveCameraMap = new ConcurrentHashMap<>();
|
||||
|
||||
public static final Long outTime = 30000L;
|
||||
|
||||
|
||||
public UavDeviceStateResponseDTO getProjectDeviceList() {
|
||||
try {
|
||||
String url = baseUrl + "/openapi/v0.1/project/device";
|
||||
String result = httpService.doGet(url, null);
|
||||
SK2ResultDTO resultDTO = JsonUtils.parseObject(result, SK2ResultDTO.class);
|
||||
Map<String, Object> map = (Map<String, Object>) resultDTO.getData();
|
||||
UavDeviceStateResponseDTO responseDTO = new UavDeviceStateResponseDTO();
|
||||
if (!CollectionUtils.isEmpty(map)) {
|
||||
List<Map<String, UavDevice>> l = (List<Map<String, UavDevice>>) map.get("list");
|
||||
if (!CollectionUtils.isEmpty(l)) {
|
||||
List<UavDeviceStateResponseDetailDTO> detail = new ArrayList<>();
|
||||
responseDTO.setDetail(detail);
|
||||
AtomicReference<Integer> total = new AtomicReference<>(0);
|
||||
AtomicReference<Integer> online = new AtomicReference<>(0);
|
||||
AtomicReference<Integer> offline = new AtomicReference<>(0);
|
||||
l.forEach(x -> {
|
||||
// 方式1:如果droneObj是Map,用TypeReference反序列化(推荐)
|
||||
UavProjectDeviceDTO up = JsonUtils.parseObject(
|
||||
JsonUtils.toJsonString(x), // 先转JSON字符串
|
||||
new TypeReference<UavProjectDeviceDTO>() {
|
||||
}
|
||||
);
|
||||
UavDevice device = up.getDrone();
|
||||
UavDevice getway = up.getGateway();
|
||||
UavDeviceStateResponseDetailDTO dto = new UavDeviceStateResponseDetailDTO();
|
||||
if (getway != null) {
|
||||
dto.setGateway_sn(getway.getSn());
|
||||
total.updateAndGet(v -> v + 1);
|
||||
dto.setCallsign(getway.getCallsign());
|
||||
if (getway.getDevice_online_status()) {
|
||||
online.updateAndGet(v -> v + 1);
|
||||
} else {
|
||||
offline.updateAndGet(v -> v + 1);
|
||||
}
|
||||
dto.setOnlineStatus(getway.getDevice_online_status() ? 1 : 0);
|
||||
dto.setGateway_camera_list(getway.getCamera_list());
|
||||
String data1 = getDeviceState(getway.getSn());
|
||||
SK2ResultDTO res1 = JsonUtils.parseObject(data1, SK2ResultDTO.class);
|
||||
if (res1 != null && res1.getData() != null) {
|
||||
UavDeviceStateDTO stateDTO = JsonUtils.parseObject(
|
||||
JsonUtils.toJsonString(res1.getData()), // 先转JSON字符串
|
||||
new TypeReference<UavDeviceStateDTO>() {
|
||||
}
|
||||
);
|
||||
if (stateDTO != null && stateDTO.getDevice_state() != null) {
|
||||
UavDeviceState deviceState = stateDTO.getDevice_state();
|
||||
dto.setWind_speed(deviceState.getWind_speed());
|
||||
dto.setEnvironment_temperature(deviceState.getEnvironment_temperature());
|
||||
dto.setRainfall(deviceState.getRainfall());
|
||||
|
||||
// dto.setLatitude(deviceState.getLatitude());
|
||||
// dto.setLongitude(deviceState.getLongitude());
|
||||
}
|
||||
}
|
||||
|
||||
if (device != null) {
|
||||
dto.setDevice_sn(device.getSn());
|
||||
dto.setDrone_callsign(device.getCallsign());
|
||||
dto.setDrone_onlineStatus(device.getDevice_online_status() ? 1 : 0);
|
||||
dto.setDrone_camera_list(device.getCamera_list());
|
||||
String data = getDeviceState(device.getSn());
|
||||
SK2ResultDTO res = JsonUtils.parseObject(data, SK2ResultDTO.class);
|
||||
if (res != null && res.getData() != null) {
|
||||
UavDeviceStateDTO stateDTO = JsonUtils.parseObject(
|
||||
JsonUtils.toJsonString(res.getData()), // 先转JSON字符串
|
||||
new TypeReference<UavDeviceStateDTO>() {
|
||||
}
|
||||
);
|
||||
if (stateDTO != null && stateDTO.getDevice_state() != null) {
|
||||
UavDeviceState deviceState = stateDTO.getDevice_state();
|
||||
// dto.setWind_speed(deviceState.getWind_speed());
|
||||
// dto.setEnvironment_temperature(deviceState.getEnvironment_temperature());
|
||||
dto.setNetwork_state(deviceState.getNetwork_state());
|
||||
dto.setPosition_state(deviceState.getPosition_state());
|
||||
dto.setHome_distance(deviceState.getHome_distance());
|
||||
dto.setHeight(deviceState.getHeight());
|
||||
// dto.setRainfall(deviceState.getRainfall());
|
||||
|
||||
dto.setLatitude(deviceState.getLatitude());
|
||||
dto.setLongitude(deviceState.getLongitude());
|
||||
if (deviceState.getBattery() != null) {
|
||||
dto.setCapacity_percent(deviceState.getBattery().getCapacity_percent());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
detail.add(dto);
|
||||
}
|
||||
});
|
||||
responseDTO.setTotal(total.get());
|
||||
responseDTO.setOnline(online.get());
|
||||
responseDTO.setOffline(offline.get());
|
||||
}
|
||||
}
|
||||
return responseDTO;
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public String getDeviceHMS(String deviceSn) {
|
||||
String url = baseUrl + "/openapi/v0.1/device/hms";
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
params.put("language", "zh");
|
||||
params.put("device_sn_list", deviceSn);
|
||||
return httpService.doGet(url, params);
|
||||
}
|
||||
|
||||
public String getDeviceState(String deviceSn) {
|
||||
String url = baseUrl + "/openapi/v0.1/device/" + deviceSn + "/state";
|
||||
return httpService.doGet(url, null);
|
||||
}
|
||||
|
||||
public String getWayline() {
|
||||
String url = baseUrl + "/openapi/v0.1/wayline";
|
||||
return httpService.doGet(url, null);
|
||||
}
|
||||
|
||||
public String getWaylineDetail(String waylineId) {
|
||||
String url = baseUrl + "/openapi/v0.1/wayline/" + waylineId;
|
||||
return httpService.doGet(url, null);
|
||||
}
|
||||
|
||||
public String createFlightTask(FlightTaskCreateDTO dto) {
|
||||
String url = baseUrl + "/openapi/v0.1/flight-task";
|
||||
if (StringUtils.isEmpty(dto.getTime_zone())) {
|
||||
dto.setTime_zone("Asia/Shanghai");
|
||||
}
|
||||
return httpService.doPost(url, dto);
|
||||
}
|
||||
|
||||
public String flightTaskCommand(FlightTaskCommandDTO dto) {
|
||||
String url = baseUrl + "/openapi/v0.1/device/" + dto.getDeviceSn() + "/command";
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("device_command", dto.getCommand().toString());
|
||||
return httpService.doPost(url, map);
|
||||
}
|
||||
|
||||
public List<CameraLiveResultDTO> liveStream(CameraLiveParamDTO dto) {
|
||||
List<CameraLiveResultDTO> list = new ArrayList<>();
|
||||
try {
|
||||
String url = baseUrl + "/openapi/v0.1/live-stream/start";
|
||||
|
||||
if (dto != null) {
|
||||
if (!CollectionUtils.isEmpty(dto.getDrone_camera_list())) {
|
||||
dto.getDrone_camera_list().forEach(x -> {
|
||||
String key = dto.getDrone_sn() + "_" + x.getCamera_index();
|
||||
CameraLiveResultDTO cameraLiveResultDTO = null;
|
||||
if (liveCameraMap.get(key) == null) {
|
||||
CameraLiveStreamDTO d = new CameraLiveStreamDTO();
|
||||
d.setSn(dto.getDrone_sn());
|
||||
d.setCamera_index(x.getCamera_index());
|
||||
d.setQuality_type(dto.getQuality_type());
|
||||
d.setVideo_expire(dto.getVideo_expire());
|
||||
String res = httpService.doPost(url, d);
|
||||
if (!StringUtils.isEmpty(res)) {
|
||||
SK2ResultDTO sk2ResultDTO = JsonUtils.parseObject(res, SK2ResultDTO.class);
|
||||
if (sk2ResultDTO != null && sk2ResultDTO.getData() != null) {
|
||||
CameraLiveStreamResultDTO resultDTO = JsonUtils.parseObject(
|
||||
JsonUtils.toJsonString(sk2ResultDTO.getData()), // 先转JSON字符串
|
||||
new TypeReference<CameraLiveStreamResultDTO>() {
|
||||
}
|
||||
);
|
||||
if (resultDTO != null) {
|
||||
cameraLiveResultDTO = new CameraLiveResultDTO();
|
||||
cameraLiveResultDTO.setUrl(resultDTO.getUrl());
|
||||
cameraLiveResultDTO.setExpire_ts(resultDTO.getExpire_ts());
|
||||
cameraLiveResultDTO.setUrl_type(resultDTO.getUrl_type());
|
||||
cameraLiveResultDTO.setSn(dto.getDrone_sn());
|
||||
cameraLiveResultDTO.setCamera_index(x.getCamera_index());
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
cameraLiveResultDTO = liveCameraMap.get(key);
|
||||
}
|
||||
list.add(cameraLiveResultDTO);
|
||||
liveCameraMap.put(key, cameraLiveResultDTO);
|
||||
});
|
||||
}
|
||||
if (!CollectionUtils.isEmpty(dto.getGetway_camera_list())) {
|
||||
dto.getGetway_camera_list().forEach(x -> {
|
||||
String key = dto.getGetway_sn() + "_" + x.getCamera_index();
|
||||
CameraLiveResultDTO cameraLiveResultDTO = null;
|
||||
if (liveCameraMap.get(key) == null) {
|
||||
CameraLiveStreamDTO d = new CameraLiveStreamDTO();
|
||||
d.setSn(dto.getGetway_sn());
|
||||
d.setCamera_index(x.getCamera_index());
|
||||
d.setQuality_type(dto.getQuality_type());
|
||||
d.setVideo_expire(dto.getVideo_expire());
|
||||
String res = httpService.doPost(url, d);
|
||||
if (!StringUtils.isEmpty(res)) {
|
||||
SK2ResultDTO sk2ResultDTO = JsonUtils.parseObject(res, SK2ResultDTO.class);
|
||||
if (sk2ResultDTO != null && sk2ResultDTO.getData() != null) {
|
||||
CameraLiveStreamResultDTO resultDTO = JsonUtils.parseObject(
|
||||
JsonUtils.toJsonString(sk2ResultDTO.getData()), // 先转JSON字符串
|
||||
new TypeReference<CameraLiveStreamResultDTO>() {
|
||||
}
|
||||
);
|
||||
if (resultDTO != null) {
|
||||
cameraLiveResultDTO = new CameraLiveResultDTO();
|
||||
cameraLiveResultDTO.setUrl(resultDTO.getUrl());
|
||||
cameraLiveResultDTO.setExpire_ts(resultDTO.getExpire_ts());
|
||||
cameraLiveResultDTO.setUrl_type(resultDTO.getUrl_type());
|
||||
cameraLiveResultDTO.setSn(dto.getGetway_sn());
|
||||
cameraLiveResultDTO.setCamera_index(x.getCamera_index());
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
cameraLiveResultDTO = liveCameraMap.get(key);
|
||||
}
|
||||
list.add(cameraLiveResultDTO);
|
||||
liveCameraMap.put(key, cameraLiveResultDTO);
|
||||
});
|
||||
}
|
||||
}
|
||||
return list;
|
||||
} catch (Exception e) {
|
||||
log.error("开启直播发生错误", e);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public String flightTaskList(String sn) {
|
||||
String url = baseUrl + "/openapi/v0.1/flight-task/list";
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("begin_at", 1735692484); //2025-1-1
|
||||
map.put("end_at", 1830306933);//2028-1-1
|
||||
map.put("sn", sn);
|
||||
return httpService.doGet(url, map);
|
||||
}
|
||||
|
||||
public String flightTaskDetail(String taskId) {
|
||||
String url = baseUrl + "/openapi/v0.1/flight-task/" + taskId;
|
||||
return httpService.doGet(url, null);
|
||||
}
|
||||
|
||||
public String getFlightTaskTrack(String taskId) {
|
||||
String url = baseUrl + "/openapi/v0.1/flight-task/" + taskId + "/track";
|
||||
return httpService.doGet(url, null);
|
||||
}
|
||||
|
||||
|
||||
public String uploadSK2Wayline(String name, String objectKey) {
|
||||
String url = baseUrl + "/openapi/v0.1/wayline/finish-upload";
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("name", name);
|
||||
map.put("objectKey", objectKey);
|
||||
return httpService.doPost(url, map);
|
||||
}
|
||||
|
||||
|
||||
public UavStsTokenDTO getStsToken() {
|
||||
String url = baseUrl + "/openapi/v0.1/project/sts-token";
|
||||
|
||||
String res = httpService.doGet(url, null);
|
||||
SK2ResultDTO dto = JsonUtils.parseObject(res, SK2ResultDTO.class);
|
||||
if (dto != null && dto.getData() != null) {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
return mapper.convertValue(dto.getData(), UavStsTokenDTO.class);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public Object uploadWayline(MultipartFile file, String name) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
|
||||
|
||||
//获取上传凭证
|
||||
UavStsTokenDTO credential = getStsToken();
|
||||
//获取属性
|
||||
String endpoint = credential.getEndpoint();
|
||||
String accessKey = credential.getCredentials().getAccess_key_id();
|
||||
String secretKey = credential.getCredentials().getAccess_key_secret();
|
||||
String securityToken = credential.getCredentials().getSecurity_token();
|
||||
String bucket = credential.getBucket();
|
||||
String objectKey = String.format("%s/%s", credential.getObject_key_prefix(), file.getName());
|
||||
InputStream inputStream = file.getInputStream();
|
||||
// 创建 MinioClient
|
||||
MinioClient minioClient = MinioClient.builder()
|
||||
.endpoint(endpoint)
|
||||
.credentialsProvider(
|
||||
new StaticProvider(accessKey, secretKey, securityToken)
|
||||
)
|
||||
.build();
|
||||
|
||||
// // STS token 必须放在 header
|
||||
Map<String, String> headers = new HashMap<>();
|
||||
headers.put("x-oss-security-token", securityToken);
|
||||
|
||||
minioClient.putObject(
|
||||
PutObjectArgs.builder()
|
||||
.bucket(bucket)
|
||||
.object(objectKey)
|
||||
.stream(inputStream, file.getSize(), -1)
|
||||
.headers(headers)
|
||||
.build()
|
||||
);
|
||||
|
||||
String s = uploadSK2Wayline(name, objectKey);
|
||||
SK2ResultDTO dto = JsonUtils.parseObject(s, SK2ResultDTO.class);
|
||||
if (dto != null && dto.getData() != null) {
|
||||
return dto.getData();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public String updateFlightTaskStatus(String taskId, String status) {
|
||||
String url = baseUrl + "/openapi/v0.1/flight-task/" + taskId + "/status";
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("status", status);
|
||||
return httpService.doPut(url, map);
|
||||
}
|
||||
|
||||
public void liveHeartbeat(String sn, String cameraIndex) {
|
||||
//key sn + _ + camera_index
|
||||
String key = sn + "_" + cameraIndex;
|
||||
latestActiveTime.put(key, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void heartbeatMonitor() {
|
||||
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
|
||||
executor.scheduleWithFixedDelay(() -> {
|
||||
try {
|
||||
Long nowTime = System.currentTimeMillis();
|
||||
if (!CollectionUtils.isEmpty(latestActiveTime.keySet())) {
|
||||
latestActiveTime.keySet().forEach(x -> {
|
||||
Long lastTime = latestActiveTime.get(x);
|
||||
if (lastTime != null && (nowTime - lastTime) > outTime) {
|
||||
liveCameraMap.remove(x);
|
||||
latestActiveTime.remove(x);
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("监测直播心跳错误!", e);
|
||||
}
|
||||
}, 0, 5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
|
||||
public String changeCamera(String sn, String cameraIndex, String cameraPosition) {
|
||||
String url = baseUrl + "/openapi/v0.1/device/change-camera";
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("sn", sn);
|
||||
map.put("camera_index", cameraIndex);
|
||||
map.put("camera_position", cameraPosition);
|
||||
return httpService.doPut(url, map);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package com.maibu.uav.utils;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
import org.springframework.web.client.HttpServerErrorException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
public class UavHttpUtils {
|
||||
|
||||
@Autowired
|
||||
private RestTemplate restTemplate;
|
||||
|
||||
@Value("${UAV.token:eyJhbGciOiJIUzUxMiIsImNyaXQiOlsidHlwIiwiYWxnIiwia2lkIl0sImtpZCI6IjhiZmRiZmRkLWM4OGYtNGE5Yi04NzI3LWQ0ZGYzYWE5OTJlOSIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50IjoiODQ5MDczQHFxLmNvbSIsImV4cCI6MjA1OTg2ODc3NCwibmJmIjoxNzQ0MzM1OTc0LCJvcmdhbml6YXRpb25fdXVpZCI6ImYwMmIwZTM4LWUyZjgtNGNhMi04ZTBmLWM1YmVlMTM3NDk2ZiIsInByb2plY3RfdXVpZCI6IiIsInN1YiI6ImZoMiIsInVzZXJfaWQiOiIxMDEyOSJ9.t9KH3SOBNxJwi3bZwA7diGV7qeLZY2cXI9ovT5FnkWXLjSHNYHD4KQObGi1iGJ5igAxZZaWIooT8v8VcPwsrSQ}")
|
||||
private String token;
|
||||
|
||||
@Value("${UAV.projectUId:bb191b8f-5110-4536-82e3-f56730e93e4c}")
|
||||
private String projectUId;
|
||||
|
||||
|
||||
/**
|
||||
* 通用 GET 请求(手动传入 Token,每次可传不同值)
|
||||
*
|
||||
* @param apiUrl 目标接口地址
|
||||
* @return 接口响应字符串
|
||||
*/
|
||||
public String doGet(String apiUrl, @Nullable Map<String, Object> params) {
|
||||
// 1. 构建带查询参数的URL(自动处理编码,避免手动拼接的问题)
|
||||
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(apiUrl);
|
||||
// 如果参数不为空,添加查询参数
|
||||
if (params != null && !params.isEmpty()) {
|
||||
params.forEach(uriBuilder::queryParam);
|
||||
}
|
||||
// 构建最终的URL(包含编码后的参数)
|
||||
String finalUrl = uriBuilder.build().toUriString();
|
||||
|
||||
// 2. 构建请求头(保留原有Token逻辑)
|
||||
HttpHeaders headers = buildHeadersWithToken();
|
||||
// 3. 封装请求实体(GET无需请求体)
|
||||
HttpEntity<Void> httpEntity = new HttpEntity<>(headers);
|
||||
|
||||
// 4. 发送 GET 请求(保留原有异常处理)
|
||||
try {
|
||||
ResponseEntity<String> response = restTemplate.exchange(
|
||||
finalUrl,
|
||||
HttpMethod.GET,
|
||||
httpEntity,
|
||||
String.class
|
||||
);
|
||||
// 校验响应状态并返回结果
|
||||
if (response.getStatusCode().is2xxSuccessful()) {
|
||||
return response.getBody() == null ? "" : response.getBody();
|
||||
} else {
|
||||
throw new RuntimeException("GET 请求失败,响应码:" + response.getStatusCode() + ",响应体:" + response.getBody());
|
||||
}
|
||||
} catch (HttpClientErrorException | HttpServerErrorException e) {
|
||||
// 捕获 HTTP 4xx/5xx 异常
|
||||
throw new RuntimeException("GET 请求异常,响应码:" + e.getStatusCode() + ",响应体:" + e.getResponseBodyAsString(), e);
|
||||
} catch (Exception e) {
|
||||
// 捕获其他未知异常
|
||||
throw new RuntimeException("GET 请求未知异常:" + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用 POST 请求(手动传入 Token,支持 JSON 请求体,每次可传不同 Token)
|
||||
*
|
||||
* @param apiUrl 目标接口地址
|
||||
* @param requestParam JSON 请求体(实体类/字符串均可,支持 null)
|
||||
* @return 接口响应字符串
|
||||
*/
|
||||
public String doPost(String apiUrl, Object requestParam) {
|
||||
// 1. 构建请求头(携带传入的 Token)
|
||||
HttpHeaders headers = buildHeadersWithToken();
|
||||
// 2. 封装请求实体(携带请求头 + 请求体)
|
||||
HttpEntity<Object> httpEntity = new HttpEntity<>(requestParam, headers);
|
||||
// 3. 发送 POST 请求
|
||||
try {
|
||||
ResponseEntity<String> response = restTemplate.exchange(
|
||||
apiUrl,
|
||||
HttpMethod.POST,
|
||||
httpEntity,
|
||||
String.class
|
||||
);
|
||||
// 校验响应状态并返回结果
|
||||
if (response.getStatusCode().is2xxSuccessful()) {
|
||||
return response.getBody() == null ? "" : response.getBody();
|
||||
} else {
|
||||
throw new RuntimeException("POST 请求失败,响应码:" + response.getStatusCode() + ",响应体:" + response.getBody());
|
||||
}
|
||||
} catch (HttpClientErrorException | HttpServerErrorException e) {
|
||||
// 捕获 HTTP 4xx/5xx 异常
|
||||
throw new RuntimeException("POST 请求异常,响应码:" + e.getStatusCode() + ",响应体:" + e.getResponseBodyAsString(), e);
|
||||
} catch (Exception e) {
|
||||
// 捕获其他未知异常
|
||||
throw new RuntimeException("POST 请求未知异常:" + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用 POST 请求(手动传入 Token,支持 JSON 请求体,每次可传不同 Token)
|
||||
*
|
||||
* @param apiUrl 目标接口地址
|
||||
* @param requestParam JSON 请求体(实体类/字符串均可,支持 null)
|
||||
* @return 接口响应字符串
|
||||
*/
|
||||
public String doPut(String apiUrl, Object requestParam) {
|
||||
// 1. 构建请求头(携带传入的 Token)
|
||||
HttpHeaders headers = buildHeadersWithToken();
|
||||
// 2. 封装请求实体(携带请求头 + 请求体)
|
||||
HttpEntity<Object> httpEntity = new HttpEntity<>(requestParam, headers);
|
||||
// 3. 发送 PUT 请求
|
||||
try {
|
||||
ResponseEntity<String> response = restTemplate.exchange(
|
||||
apiUrl,
|
||||
HttpMethod.PUT,
|
||||
httpEntity,
|
||||
String.class
|
||||
);
|
||||
// 校验响应状态并返回结果
|
||||
if (response.getStatusCode().is2xxSuccessful()) {
|
||||
return response.getBody() == null ? "" : response.getBody();
|
||||
} else {
|
||||
throw new RuntimeException("PUT 请求失败,响应码:" + response.getStatusCode() + ",响应体:" + response.getBody());
|
||||
}
|
||||
} catch (HttpClientErrorException | HttpServerErrorException e) {
|
||||
// 捕获 HTTP 4xx/5xx 异常
|
||||
throw new RuntimeException("PUT 请求异常,响应码:" + e.getStatusCode() + ",响应体:" + e.getResponseBodyAsString(), e);
|
||||
} catch (Exception e) {
|
||||
// 捕获其他未知异常
|
||||
throw new RuntimeException("PUT 请求未知异常:" + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建携带 Token 的通用请求头(默认 JSON 格式)
|
||||
* @return HttpHeaders
|
||||
*/
|
||||
private HttpHeaders buildHeadersWithToken() {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
// 设置默认 Content-Type 为 JSON 格式
|
||||
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
|
||||
headers.set("Accept", "application/json");
|
||||
headers.set("X-User-Token", token.trim());
|
||||
// 可按需添加其他通用请求头(如 User-Agent)
|
||||
headers.set("X-Language", "zh");
|
||||
headers.set("X-Project-Uuid", projectUId.trim());
|
||||
return headers;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
543
maibu-external/src/main/resources/templates/reportTemplate.html
Normal file
543
maibu-external/src/main/resources/templates/reportTemplate.html
Normal file
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user