Compare commits

...

4 Commits

  1. 147
      zc-business/src/main/java/com/zc/business/controller/DcDeviceController.java
  2. 113
      zc-business/src/main/java/com/zc/business/controller/RadarController.java

147
zc-business/src/main/java/com/zc/business/controller/DcDeviceController.java

@ -11,6 +11,7 @@ import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.spring.SpringUtils;
@ -22,6 +23,7 @@ import com.zc.business.enums.UniversalEnum;
import com.zc.business.interfaces.OperationLog;
import com.zc.business.request.DeviceGetPropertiesOperateRequest;
import com.zc.business.service.IDcDeviceService;
import com.zc.business.service.IDcWarningService;
import com.zc.common.core.httpclient.OkHttp;
import com.zc.common.core.httpclient.exception.HttpException;
import com.zc.common.core.httpclient.request.RequestParams;
@ -63,7 +65,8 @@ import java.util.stream.Collectors;
@RestController
@RequestMapping("/business/device")
public class DcDeviceController extends BaseController {
@Resource
private RedisCache redisCache;
@Resource
private IDcDeviceService dcDeviceService;
@Resource
@ -406,8 +409,130 @@ private VideoController videoController;
}
@ApiOperation("太阳能状况统计")
@GetMapping("/properties/history/oneDay/{propertyId}")
public AjaxResult queryDevicePropertiesDay(
@PathVariable @Parameter(description = "属性ID") String propertyId) throws HttpException, IOException, ParseException {
public AjaxResult queryDevicePropertiesDay(@PathVariable @Parameter(description = "属性ID") String propertyId) throws HttpException, IOException, ParseException {
// HashMap<String, Object> props = new HashMap<>();
// // 设置查询条件的键为“timestamp$BTW”,表示时间戳在一定范围内
// props.put("terms[0].column", "timestamp$BTW");
// ArrayList<String> dateList = new ArrayList<>();
// // 添加当前日期的开始和结束时间到列表,用于设定时间范围
// dateList.add(DateUtil.beginOfDay(new Date()).toString());
// dateList.add(DateUtil.endOfDay(new Date()).toString());
// // 将日期列表以逗号分隔并设置为查询条件的值
// props.put("terms[0].value", String.join(",", dateList));
// props.put("paging", false);
// props.put("sorts[0].order", "asc");
// props.put("sorts[0].name", "timestamp");
// Map<String, Object> parameter = new HashMap<>();
// String[] endStakeMark = {"208", "979"};
// String[] startStakeMark = {"054", "378"};
// parameter.put("deviceType", "15");
// parameter.put("endStakeMark", endStakeMark);
// parameter.put("startStakeMark", startStakeMark);
// // parameter.put("deviceState","1");
// // 创建一个映射来存储按小时汇总的数据
// Map<String, Double> allDevicesHourlyAggregates = new TreeMap<>();
//
// List<DcDevice> dcDevices = dcDeviceService.devicePileNumberQueryDevice(parameter);
// for (DcDevice dcDevice : dcDevices) {
// AjaxResult ajaxResult = queryDeviceProperties(dcDevice.getIotDeviceId(), propertyId, props);
// if (!ajaxResult.get("code").equals(UniversalEnum.TWO_HUNDRED.getNumber())) {
// return ajaxResult;
// }
// // 定义时间格式
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//
// Object data = JSON.parseObject(ajaxResult.get("data").toString()).get("data");
// JSONArray dataArray = JSON.parseArray(data.toString());
// // 创建一个映射来存储单个设备按小时汇总的数据
// Map<String, Map<String, Object>> deviceHourlyLatestData = new TreeMap<>();
//
// DecimalFormat decimalFormat = new DecimalFormat("#.##");
// decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
//
// // 处理每个数据点
// for (Object o : dataArray) {
// JSONObject jsonObject = JSON.parseObject(o.toString());
// String formatValueStr = jsonObject.getString("formatValue");
// String timestampStr = jsonObject.getString("timestamp");
//
// // 将 Unix 时间戳转换为 Date 对象
// long timestamp = Long.parseLong(timestampStr);
// Date date = new Date(timestamp);
//
// // 将 Date 对象格式化为字符串
// String formattedTimestamp = sdf.format(date);
// Calendar calendar = Calendar.getInstance();
// calendar.setTime(date);
//
// // 提取小时部分
// int hour = calendar.get(Calendar.HOUR_OF_DAY);
// String key = String.format("%d-%02d-%02d %02d:00:00",
// calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1,
// calendar.get(Calendar.DAY_OF_MONTH), hour);
//
// // 转换为 double 类型,去除单位
// String valueWithoutUnit = formatValueStr.replaceAll("[^\\d.]", "");
// double parsedValue = Double.parseDouble(valueWithoutUnit);
// // 保留两位小数
// double formatValue = Double.parseDouble(decimalFormat.format(parsedValue));
//
// // 检查当前小时是否有数据,如果没有则直接添加
// if (!deviceHourlyLatestData.containsKey(key)) {
// Map<String, Object> dataPoint = new HashMap<>();
// dataPoint.put("value", formatValue);
// dataPoint.put("timestamp", timestamp);
// deviceHourlyLatestData.put(key, dataPoint);
// } else {
// // 如果已经有数据,比较时间戳,保留最新的数据
// long existingTimestamp = (long) deviceHourlyLatestData.get(key).get("timestamp");
// if (timestamp > existingTimestamp) {
// Map<String, Object> dataPoint = new HashMap<>();
// dataPoint.put("value", formatValue);
// dataPoint.put("timestamp", timestamp);
// deviceHourlyLatestData.put(key, dataPoint);
// }
// }
// }
//
// // 将设备的数据合并到所有设备的汇总数据中
// for (String key : deviceHourlyLatestData.keySet()) {
// double latestValue = (double) deviceHourlyLatestData.get(key).get("value");
// allDevicesHourlyAggregates.merge(key, latestValue, (oldVal, newVal) -> {
// double sum = oldVal + newVal;
// return Double.parseDouble(decimalFormat.format(sum));
// });
// }
// }
Map<String, Double> allDevicesHourlyAggregates= redisCache.getCacheObject(propertyId);
return AjaxResult.success(allDevicesHourlyAggregates);
}
public void solarEnergyConditionStatisticsOne() {
RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
Map<String, Double> stringDoubleMap = solarEnergyConditionStatistics("dailyAccumulatedCharge");
if (stringDoubleMap != null) {
redisCache.setCacheObject("dailyAccumulatedCharge", stringDoubleMap);
}
}
public void solarEnergyConditionStatisticsTwo(){
RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
Map<String, Double> stringDoubleMap = solarEnergyConditionStatistics("cumulativeElectricityConsumptionOnTheDay");
if (stringDoubleMap!=null) {
redisCache.setCacheObject("cumulativeElectricityConsumptionOnTheDay", stringDoubleMap);
}
}
public void solarEnergyConditionStatisticsThree(){
RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
Map<String, Double> stringDoubleMap = solarEnergyConditionStatistics("generatingPower");
if (stringDoubleMap!=null){
redisCache.setCacheObject("generatingPower", stringDoubleMap);
}
}
public Map<String, Double> solarEnergyConditionStatistics (String propertyId) {
IDcDeviceService dcDeviceService = SpringUtils.getBean(IDcDeviceService.class);
HashMap<String, Object> props = new HashMap<>();
// 设置查询条件的键为“timestamp$BTW”,表示时间戳在一定范围内
props.put("terms[0].column", "timestamp$BTW");
@ -432,9 +557,17 @@ private VideoController videoController;
List<DcDevice> dcDevices = dcDeviceService.devicePileNumberQueryDevice(parameter);
for (DcDevice dcDevice : dcDevices) {
AjaxResult ajaxResult = queryDeviceProperties(dcDevice.getIotDeviceId(), propertyId, props);
AjaxResult ajaxResult = null;
try {
ajaxResult = queryDeviceProperties(dcDevice.getIotDeviceId(), propertyId, props);
} catch (HttpException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (!ajaxResult.get("code").equals(UniversalEnum.TWO_HUNDRED.getNumber())) {
return ajaxResult;
return null;
}
// 定义时间格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@ -501,10 +634,8 @@ private VideoController videoController;
});
}
}
return AjaxResult.success(allDevicesHourlyAggregates);
return allDevicesHourlyAggregates;
}
@ApiOperation("太阳能重点数据")
@GetMapping("/properties/latestOne")
public AjaxResult getDeviceLatest() throws HttpException, IOException {

113
zc-business/src/main/java/com/zc/business/controller/RadarController.java

@ -22,6 +22,9 @@ import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
*
@ -42,57 +45,80 @@ public class RadarController {
LocalDateTime fifteenMinutesAgo = now.minus(Duration.ofMinutes(5));
String FifteenMinutesAgo = fifteenMinutesAgo.format(formatter);
// 获取当前时间前20分钟的时间点
LocalDateTime twentyMinutesAgo = now.minus(Duration.ofMinutes(20));
// 获取当前时间前25分钟的时间点
LocalDateTime twentyMinutesAgo = now.minus(Duration.ofMinutes(25));
String TwentyMinutesAgo = twentyMinutesAgo.format(formatter);
DcWarning dcWarning = new DcWarning();
dcWarning.setStartDate(TwentyMinutesAgo);
dcWarning.setEndDate(FifteenMinutesAgo);
List<DcWarning> radarList = dcWarningService.radarList(dcWarning);
radarList.forEach(radar -> {
if (radar.getId() != null) {
try {
//获取雷达事件视频
String baseUrl = dcWarningService.getRadarIncidentVideo(radar.getId());
// String baseUrl = "http://10.0.11.252:9021/profile/mp4/G35 长清大学城站 内广场_20241108_090235_60.mp4";
String ftpServer= configService.selectConfigByKey("FTP-IP");//密钥
// int port = 21;
int port= Integer.parseInt(configService.selectConfigByKey("FTP-PORT"));
//ftpuser
//String user = "1911390090@qq.com";
String username= configService.selectConfigByKey("FTP-USER");//密钥
//Dxc123!@#
String password= configService.selectConfigByKey("FPT-PASSWORD");//密钥
/* String ftpServer = "10.168.71.135";
int port = 21;
String username = "1911390090@qq.com";
String password = "989878wxl";*/
String[] split = StringUtils.split(baseUrl, "_");
// 拼接文件名
String fileName = radar.getStakeMark() + "_" + split[1] + "_" + split[2] + "_" + split[3];
DateTimeFormatter dirFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
DateTimeFormatter hourFormatter = DateTimeFormatter.ofPattern("HH");
String datePart = now.format(dirFormatter);
String hourPart = now.format(hourFormatter);
//文件路径
// String remoteFilePath = "/path/to/remote/directory";
String remoteFilePath = "/radar/" + datePart + "/" + hourPart;
String download = directDownloadToFtp(baseUrl, ftpServer, port, username, password, remoteFilePath, fileName);
DcWarning dcWarning1 = new DcWarning();
dcWarning1.setId(radar.getId());
dcWarning1.setRadarUrl(download);
int i = dcWarningService.updateDcWarning(dcWarning1);
} catch (Exception e) {
throw new RuntimeException(e);
}
// 创建一个固定大小的线程池
ExecutorService executor = Executors.newFixedThreadPool(5); // 线程池大小
try {
radarList.forEach(radar -> {
if (radar != null && radar.getId() != null) {
executor.submit(() -> processRadarEvent(radar, now));
}
});
// 关闭线程池,并等待所有任务完成
executor.shutdown();
executor.awaitTermination(1, TimeUnit.HOURS); // 设置超时时间
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // 恢复中断状态
log.error("线程池关闭过程中发生中断", e);
} finally {
if (!executor.isTerminated()) {
executor.shutdownNow(); // 强制关闭未完成的任务
}
});
}
}
private void processRadarEvent(DcWarning radar, LocalDateTime now) {
try {
// 获取雷达事件视频
String baseUrl = dcWarningService.getRadarIncidentVideo(radar.getId());
System.out.println("雷达视频地址:" + baseUrl);
if (baseUrl == null || baseUrl.isEmpty()) {
log.warn("雷达事件ID {} 没有对应的视频URL", radar.getId());
return;
}
String ftpServer= configService.selectConfigByKey("FTP-IP");//密钥
int port= Integer.parseInt(configService.selectConfigByKey("FTP-PORT"));
String username= configService.selectConfigByKey("FTP-USER");//密钥
String password= configService.selectConfigByKey("FPT-PASSWORD");//密钥
// String ftpServer = "192.168.3.1";
// int port = 21;
// String username = "1911390090@qq.com";
// String password = "989878wxl";
String[] split = StringUtils.split(baseUrl, "/");
// 拼接文件名
String fileName = split[split.length - 1];
DateTimeFormatter dirFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
DateTimeFormatter hourFormatter = DateTimeFormatter.ofPattern("HH");
String datePart = now.format(dirFormatter);
String hourPart = now.format(hourFormatter);
// 文件路径
String remoteFilePath = "/radar/" + datePart + "/" + hourPart;
String download = directDownloadToFtp(baseUrl, ftpServer, port, username, password, remoteFilePath, fileName);
DcWarning dcWarning1 = new DcWarning();
dcWarning1.setId(radar.getId());
dcWarning1.setRadarUrl(download);
int i = dcWarningService.updateDcWarning(dcWarning1);
if (i <= 0) {
log.error("更新数据库失败,ID: {}", radar.getId());
}
} catch (Exception e) {
log.error("处理雷达事件ID {} 时发生异常", radar.getId(), e);
}
}
public static String directDownloadToFtp(String baseUrl, String ftpServer, int port, String user, String pass, String remotePath, String fileName) throws IOException, URISyntaxException, InterruptedException {
FTPClient ftpClient = new FTPClient();
HttpURLConnection httpConn = null;
@ -104,8 +130,7 @@ public class RadarController {
System.out.println("encodedUrl: " + encodedUrl);
URI uri = new URI(encodedUrl);
URL url = uri.toURL();
// 睡眠3秒钟
Thread.sleep(3000); //
httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
@ -115,7 +140,7 @@ public class RadarController {
ftpClient.connect(ftpServer, port);
boolean loginResult = ftpClient.login(user, pass);
if (!loginResult) {
throw new IOException("FTP登录失败");
log.info("FTP登录失败");
}
log.info("成功登录到FTP服务器");
// 设置为二进制传输模式和被动模式
@ -145,7 +170,7 @@ public class RadarController {
log.info("最终工作目录: " + ftpClient.printWorkingDirectory());
}
// 上传文件到FTP服务器
boolean done = ftpClient.storeFile(fileName, inputStream);
boolean done = ftpClient.storeFile(new String(fileName.getBytes("GBK"),"ISO-8859-1"), inputStream);
if (done) {
log.info("文件上传成功");
return URL+ftpClient.printWorkingDirectory()+"/" + fileName;

Loading…
Cancel
Save