Browse Source

20240723提交在线监测完整代码

develop
gaoguangchao 4 months ago
parent
commit
3592ca8a6a
  1. 327
      zc-business/src/main/java/com/zc/business/controller/DcDeviceOnlineController.java
  2. 10
      zc-business/src/main/java/com/zc/business/domain/DcDevice.java
  3. 58
      zc-business/src/main/java/com/zc/business/domain/OnlineLog.java
  4. 228
      zc-business/src/main/java/com/zc/business/domain/OnlineSum.java
  5. 57
      zc-business/src/main/java/com/zc/business/enums/NetworkQuality.java
  6. 40
      zc-business/src/main/java/com/zc/business/enums/UniversalEnum.java
  7. 1
      zc-business/src/main/java/com/zc/business/mapper/DcDeviceMapper.java
  8. 9
      zc-business/src/main/java/com/zc/business/mapper/OnlineLogMapper.java
  9. 26
      zc-business/src/main/java/com/zc/business/mapper/OnlineSumMapper.java
  10. 3
      zc-business/src/main/java/com/zc/business/service/IOnlineLogService.java
  11. 27
      zc-business/src/main/java/com/zc/business/service/IOnlineSumService.java
  12. 4
      zc-business/src/main/java/com/zc/business/service/impl/DcDeviceServiceImpl.java
  13. 11
      zc-business/src/main/java/com/zc/business/service/impl/OnlineLogServiceImpl.java
  14. 55
      zc-business/src/main/java/com/zc/business/service/impl/OnlineSumServiceImpl.java
  15. 86
      zc-business/src/main/java/com/zc/business/task/DeviceOnlineTask.java
  16. 18
      zc-business/src/main/java/com/zc/business/utils/MathUtil.java
  17. 108
      zc-business/src/main/resources/mapper/OnlineSumMapper.xml
  18. 8
      zc-business/src/main/resources/mapper/business/DcDeviceMapper.xml
  19. 27
      zc-business/src/main/resources/mapper/business/OnlineLogMapper.xml

327
zc-business/src/main/java/com/zc/business/controller/DcDeviceOnlineController.java

@ -0,0 +1,327 @@
package com.zc.business.controller;
import com.alibaba.excel.util.DateUtils;
import com.github.pagehelper.util.StringUtil;
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.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.zc.business.constant.RedisKeyConstants;
import com.zc.business.domain.*;
import com.zc.business.enums.UniversalEnum;
import com.zc.business.service.IDcRoadSectionService;
import com.zc.business.service.IOnlineLogService;
import com.zc.business.service.IOnlineSumService;
import com.zc.business.service.impl.DcDeviceServiceImpl;
import com.zc.business.utils.MathUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
@Api(tags = "设备在线监测")
@RestController
@RequestMapping("/system/status1")
public class DcDeviceOnlineController extends BaseController {
@Autowired
private DcDeviceServiceImpl dcDeviceService;
@Resource
private RedisCache redisCache;
@Resource
private IDcRoadSectionService dcRoadSectionService;
@Resource
private IOnlineSumService onlineSumService;
@Resource
private IOnlineLogService onlineLogService;
private static final String ORDERRULE = "orderRule";//排序策略key
@ApiOperation("设备状态列表按时间和类型")
@GetMapping("/tablist")
public TableDataInfo getTabList(@RequestParam("type") String[] deviceTypes,
@RequestParam(required = false) String orderByField,
@RequestParam(required = false) String orderDirection,
@RequestParam(required = false) String searchValue) {
if(ObjectUtils.isEmpty(deviceTypes)) {
return getDataTable(new ArrayList<>());
}
startPage();
List<OnlineSum> sums = onlineSumService.queryByDeviceTypesOfToday(deviceTypes, orderByField, orderDirection, searchValue);
Map<String,OnlineSum> onlineSumMap = redisCache.getCacheMap(RedisKeyConstants.DEVICE_ONLINE);
String date = LocalDate.now().toString();
for (OnlineSum sum : sums) {
String deviceId = sum.getDeviceId().toString();
String hKey = date+":"+deviceId;
OnlineSum online = onlineSumMap.get(hKey);
if(ObjectUtils.isEmpty(online)) {
continue;
}
sum.setLastOnlineTime(onlineSumMap.get(hKey).getLastOnlineTime());
sum.setDeviceStatus(onlineSumMap.get(hKey).getDeviceStatus());
}
return getDataTable(sums);
}
//按时间划分设备柱状图
@ApiOperation("设备状态柱状图按时间和类型")
@GetMapping("/list")
public AjaxResult getStatusList(
@RequestParam("startTime") String startTime,
@RequestParam("time") String endTime,
@RequestParam("type") String[] types,
@RequestParam(value = "direction",required = false) String direction) {
Map<String, Map<String, Double>> maps = new HashMap<>();
LocalDateTime start = LocalDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
LocalDateTime end = LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
List<OnlineSum> onlineSums = onlineSumService.queryByDeviceTypeAndDate(types, start.toLocalDate(), end.toLocalDate(),direction);
Map<String,List<OnlineSum>> stringListMap = onlineSums.stream().collect(Collectors.groupingBy(OnlineSum::getDeviceType));
for (String type : types) {
Map<String, Double> map = new HashMap<>();
List<OnlineSum> listOfType = stringListMap.getOrDefault(type, new ArrayList<>());
Map<LocalDate,List<OnlineSum>> localDateListMap = listOfType.stream().collect(Collectors.groupingBy(OnlineSum::getStatisticalDate));
for (LocalDate date = start.toLocalDate(); date.isBefore(end.toLocalDate().plusDays(1)); date=date.plusDays(1)) {
List<OnlineSum> dayList = localDateListMap.getOrDefault(date, new ArrayList<>());
map.put(date.toString(), MathUtil.doubleTwoDecimal(dayList.stream().mapToDouble(OnlineSum::getOnlineRate).average().orElse(0.0)));
}
maps.put(type, new TreeMap<>(map));
}
return AjaxResult.success(maps);
}
/**
* 查询设备在线率
* @param deviceId
* @return
*/
@ApiOperation("根据设备Id查询折线图数据")
@GetMapping("/deviceStatusList/{deviceId}")
public AjaxResult getDeviceStatusList(@PathVariable Long deviceId) {
LocalDate startDate = LocalDate.now().minusDays(30);
LocalDate endDate = LocalDate.now();
List<OnlineSum> onlineSums = onlineSumService.queryByDateRangeOfDevice(deviceId, startDate, endDate);
if(onlineSums.isEmpty()) {
return AjaxResult.success(UniversalEnum.NO_DATA_AVAILABLE.getValue());
}
Map<String, Object> map = new HashMap<>();
for (OnlineSum onlineSum : onlineSums) {
map.put(onlineSum.getStatisticalDate().toString(), onlineSum.getOnlineRate());
}
return AjaxResult.success(new TreeMap<>(map));
}
/**
* 缓存类型卡片排序规则
* @param rule 排序规则
* @return AjaxResult
*/
@ApiOperation("缓存类型卡片排序规则")
@GetMapping("/rule")
public AjaxResult setRule(String rule) {
redisCache.setCacheObject(ORDERRULE, rule);
return AjaxResult.success();
}
/**
* 设备分类当日在线率
*/
@ApiOperation("设备分类当日在线率")
@GetMapping("/type")
public AjaxResult getTypeList() {
String LOST_RATE = "lostRate";//丢包率
String SUCESS_RATE = "sucessRate";//在线率
String FAIL_RATE = "failRate";//离线率
String SUM_USE_STATE = "sumUseState";//在用数
String SUM = "sum";//总数
String RULE = "rule";
String All_TYPE = "全部设备";
String SORT_RULE = "排序规则";
Map<String, Object> returnMap = new HashMap<>();
List<OnlineSum> onlineSums = onlineSumService.queryByDateOfDeviceType(LocalDate.now());
List<DcDevice> dcDeviceList = dcDeviceService.list();
List<DcDevice> useDeviceList = dcDeviceList.stream().filter(device ->device.getUseState()!=null && device.getUseState()==1).collect(Collectors.toList());
//分类总数
Map<String, Long> totalCounts = dcDeviceList.stream()
.collect(Collectors.groupingBy(DcDevice::getRealType, Collectors.counting()));
//分类在用数
Map<String,Long> useCounts = useDeviceList.stream()
.collect(Collectors.groupingBy(DcDevice::getRealType, Collectors.counting()));
Map<String,List<OnlineSum>> typeSumGroup = onlineSums.stream().collect(Collectors.groupingBy(OnlineSum::getDeviceType));
DeviceType.toMap().forEach((k,v) -> {
Map<String,Object> itemMap = new HashMap<>();
itemMap.put(SUM,totalCounts.getOrDefault(k,0L));//总数
itemMap.put(SUM_USE_STATE,useCounts.getOrDefault(k,0L));//在用数
List<OnlineSum> onlineSumsOfType = typeSumGroup.getOrDefault(k,new ArrayList<>());
itemMap.put(LOST_RATE, MathUtil.doubleTwoDecimal(onlineSumsOfType.stream().mapToDouble(OnlineSum::getLossRate).average().orElse(0.0)));
itemMap.put(SUCESS_RATE,MathUtil.doubleTwoDecimal(onlineSumsOfType.stream().mapToDouble(OnlineSum::getOnlineRate).average().orElse(0.0)));
itemMap.put(FAIL_RATE,MathUtil.doubleTwoDecimal(onlineSumsOfType.stream().mapToDouble(OnlineSum::getOfflineRate).average().orElse(0.0)));
returnMap.put(v,itemMap);
});
Map<String, Object> allMap = new HashMap<>();
allMap.put(SUM,dcDeviceList.size());//总数
allMap.put(SUM_USE_STATE,useDeviceList.size());//在用数
allMap.put(LOST_RATE,MathUtil.doubleTwoDecimal(onlineSums.stream().mapToDouble(OnlineSum::getLossRate).average().orElse(0.0)));
allMap.put(SUCESS_RATE,MathUtil.doubleTwoDecimal(onlineSums.stream().mapToDouble(OnlineSum::getOnlineRate).average().orElse(0.0)));
allMap.put(FAIL_RATE,MathUtil.doubleTwoDecimal(onlineSums.stream().mapToDouble(OnlineSum::getOfflineRate).average().orElse(0.0)));
returnMap.put(All_TYPE,allMap);
Map<String, Object> sortMap = new TreeMap<>();
String orderRule = redisCache.getCacheObject(ORDERRULE);
if (StringUtil.isNotEmpty(orderRule)) {
sortMap.put(RULE, orderRule);
} else {
sortMap.put(RULE, DeviceType.defaultSortRule());
}
returnMap.put(SORT_RULE, sortMap);
return AjaxResult.success(returnMap);
}
//按路段统计设备在线率
@ApiOperation("设备状态列表按路段")
@GetMapping("/section")
public AjaxResult getSectionList() {
String LOST_RATE = "lostRate";//丢包率
String SUCESS_RATE = "sucessRate";//在线率
String FAIL_RATE = "failRate";//离线率
String SUM_USE_STATE = "sumUseState";//在用数
String SUM = "sum";//总数
Map<String, Object> returnMap = new HashMap<>();
List<Map<String, Object>> deviceOfRoad = dcDeviceService.selectDeviceOfRoad();
List<DcRoadSection> dcRoadSections = dcRoadSectionService.selectDcRoadSectionList(new DcRoadSection());
List<OnlineSum> onlineSums = onlineSumService.queryByDateOfRoad(LocalDate.now());
Map<String,Long> totalRoadCounts = deviceOfRoad.stream()
.collect(Collectors.groupingBy(m -> m.get("roadId").toString(),Collectors.counting()));
Map<String,Long> useRoadCounts = deviceOfRoad.stream().filter(dr -> dr.get("useStata")!=null && dr.get("useStata").toString().equals("1"))
.collect(Collectors.groupingBy(m -> m.get("roadId").toString(),Collectors.counting()));
Map<Long,List<OnlineSum>> onLineSumMap = onlineSums.stream().filter(onlineSum -> onlineSum.getRoadId() != null).collect(Collectors.groupingBy(OnlineSum::getRoadId));
for(DcRoadSection dcRoadSection : dcRoadSections) {
Map<String,Object> itemMap = new HashMap<>();
itemMap.put(SUM,totalRoadCounts.getOrDefault(dcRoadSection.getId().toString(),0L));//总数
itemMap.put(SUM_USE_STATE,useRoadCounts.getOrDefault(dcRoadSection.getId().toString(),0L));//在用数
List<OnlineSum> onlineSumsByRoad = onLineSumMap.getOrDefault(dcRoadSection.getId(),new ArrayList<>());
itemMap.put(LOST_RATE, MathUtil.doubleTwoDecimal(onlineSumsByRoad.stream().mapToDouble(OnlineSum::getLossRate).average().orElse(0.0)));
itemMap.put(SUCESS_RATE,MathUtil.doubleTwoDecimal(onlineSumsByRoad.stream().mapToDouble(OnlineSum::getOnlineRate).average().orElse(0.0)));
itemMap.put(FAIL_RATE,MathUtil.doubleTwoDecimal(onlineSumsByRoad.stream().mapToDouble(OnlineSum::getOfflineRate).average().orElse(0.0)));
returnMap.put(dcRoadSection.getSectionName(),itemMap);
}
return AjaxResult.success(returnMap);
}
@ApiOperation("查询设备网络日志")
@GetMapping("/networkLogTable")
public TableDataInfo networkLogTable(
@RequestParam("deviceId") Long deviceId,
@RequestParam("queryDate")String queryDate) {
LocalDateTime start = LocalDateTime.parse(queryDate + " 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
LocalDateTime end = LocalDateTime.now();
startPage();
List<OnlineLog> onlineLogs = onlineLogService.queryByDateAndDevice(start,end,deviceId);
return getDataTable(onlineLogs);
}
@ApiOperation("查询设备网络日志")
@GetMapping("/networkLogEcharts")
public AjaxResult networkLogEcharts(
@RequestParam("deviceId") Long deviceId,
@RequestParam("queryDate")String queryDate) {
String LOST_RATE = "lostRate";//丢包率
String RTT_AVG = "rttAvg";//平均往返时延
String MONITOR_TIME = "time";//监控时间
LocalDateTime start = LocalDateTime.parse(queryDate + " 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
LocalDateTime end = LocalDateTime.now();
List<OnlineLog> onlineLogs = onlineLogService.queryByDateAndDevice(start,end,deviceId);
Map<String,Object> returnMap = new HashMap<>();
List<String> xAxis = new ArrayList<>();
List<Double> lossRate = new ArrayList<>();
List<Double> rttAvg = new ArrayList<>();
onlineLogs.stream().sorted(Comparator.comparing(OnlineLog::getMonitorTime)).forEach(onlineLog -> {
xAxis.add(onlineLog.getMonitorTime().format(DateTimeFormatter.ofPattern("HH:mm")));
lossRate.add(onlineLog.getLossRate());
rttAvg.add(onlineLog.getRttAvg());
});
returnMap.put(LOST_RATE,lossRate);
returnMap.put(RTT_AVG,rttAvg);
returnMap.put(MONITOR_TIME,xAxis);
return AjaxResult.success(returnMap);
}
enum DeviceType {
GUN_CAMERA("1-1","高清网络枪型固定摄像机"),
SPHERICAL_CAMERA("1-2", "高清网络球形摄像机"),
SPHERICAL_CAMERA_BRIDGE("1-3", "桥下高清网络球形摄像机"),
PANORAMIC_CAMERA_360("1-4", "360°全景摄像机"),
PANORAMIC_CAMERA_180("1-5", "180°全景摄像机"),
GANTRY_VMS("2-1", "门架式可变信息标志"),
STATION_FRONT_VMS("2-2", "站前可变信息标志"),
AWNING_VMS("2-3", "雨棚可变信息标志"),
//站前悬臂式可变信息标志2-4
MET_DET("3", "气象检测器"),
//出口诱导灯4
VOICE_BROADCAST("5", "路段语音广播系统"),
GUARDRAIL_COLLISION("6", "护栏碰撞预警系统"),
MMW_RADAR("7", "毫米波雷达"),
CA_EARLY("8", "合流区预警系统"),
//智慧锥桶9
LASER_FATIGUE_AWAKENING("10", "激光疲劳唤醒"),
TRAFFIC_SURVEY_STATION("11", "一类交通量调查站"),
DRIVING_GUIDANCE("12", "智能行车诱导系统"),
DEVICE_BOX("13", "智能设备箱"),
//光纤在线监测14
SOLAR_PANEL("15", "太阳能板"),
REMOTE_COMPUTER("16", "远端机");
private final String value;
private final String description;
public String getValue() {
return value;
}
public String getDescription() {
return description;
}
DeviceType(String value, String description) {
this.value = value;
this.description = description;
}
/**
* map转换{value,description}
* @return 转换后的map
*/
static Map<String,String> toMap(){
Map<String, String> map = new HashMap<>();
for (DeviceType deviceType : DeviceType.values()) {
map.put(deviceType.getValue(), deviceType.getDescription());
}
return map;
}
/**
* 默认排序规则
* @return 排序规则
*/
static String defaultSortRule(){
StringBuilder stringBuilder = new StringBuilder();
String ALL_TYPE = "全部设备";
stringBuilder.append(ALL_TYPE);
for (DeviceType deviceType : DeviceType.values()) {
stringBuilder.append(",").append(deviceType.getDescription());
}
return stringBuilder.toString();
}
}
}

10
zc-business/src/main/java/com/zc/business/domain/DcDevice.java

@ -8,6 +8,7 @@ import com.zc.business.utils.StakeMarkUtils;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.util.ObjectUtils;
import java.util.Date;
@ -114,7 +115,16 @@ public class DcDevice {
@TableField(exist = false)
private String manufacturer;
public Integer stakeMarkToInt() {
return StakeMarkUtils.stakeMarkToInt(stakeMark);
}
public String getRealType(){
if(ObjectUtils.isEmpty(this.childType)){
return this.deviceType;
}else{
return this.childType;
}
}
}

58
zc-business/src/main/java/com/zc/business/domain/OnlineLog.java

@ -3,7 +3,9 @@ package com.zc.business.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.utils.DateUtils;
import com.zc.business.enums.NetworkQuality;
import com.zc.business.enums.UniversalEnum;
import com.zc.business.utils.MathUtil;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
@ -18,12 +20,14 @@ public class OnlineLog implements Serializable {
private String deviceIp;
private String deviceName;
private String stakeMark;
private String direction;//方向
private String deviceType;//设备类型
private String deviceStatus;
private String networkQuality;//网络质量
private int sendCount;//发送数
private int receiveCount;//返回数
private int lossCount;//丢包数
private String lossRate;//丢包率
private double lossRate;//丢包率
private double rttAvg;//平均往返时延
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ -109,11 +113,11 @@ public class OnlineLog implements Serializable {
this.lossCount = lossCount;
}
public String getLossRate() {
public double getLossRate() {
return lossRate;
}
public void setLossRate(String lossRate) {
public void setLossRate(double lossRate) {
this.lossRate = lossRate;
}
@ -133,6 +137,24 @@ public class OnlineLog implements Serializable {
this.monitorTime = monitorTime;
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
public String getDeviceType() {
return deviceType;
}
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
@Override
public String toString() {
return "OnlineLog{" +
@ -141,6 +163,8 @@ public class OnlineLog implements Serializable {
", deviceIp='" + deviceIp + '\'' +
", deviceName='" + deviceName + '\'' +
", stakeMark='" + stakeMark + '\'' +
", direction='" + direction + '\'' +
", deviceType='" + deviceType + '\'' +
", deviceStatus='" + deviceStatus + '\'' +
", networkQuality='" + networkQuality + '\'' +
", sendCount=" + sendCount +
@ -174,8 +198,11 @@ public class OnlineLog implements Serializable {
onlineLog.setDeviceId(device.getId());
onlineLog.setDeviceIp(device.getDeviceIp());
onlineLog.setDeviceName(device.getDeviceName());
onlineLog.setDirection(device.getDirection());
onlineLog.setDeviceType(device.getDeviceType());
onlineLog.setStakeMark(device.getStakeMark());
String lossRate = String.format("%.2f%%", (double) onlineLog.getLossCount() / onlineLog.getSendCount() * 100);
onlineLog.setLossCount(onlineLog.getSendCount() - onlineLog.getReceiveCount());
double lossRate = onlineLog.getSendCount()==0?0:(double) onlineLog.getLossCount() / onlineLog.getSendCount() * 100;
onlineLog.setLossRate(lossRate);
double rttAvg = onlineLog.getRttAvg();
if(rttAvg > 0 && rttAvg <= 30){
@ -185,7 +212,7 @@ public class OnlineLog implements Serializable {
}else {
onlineLog.setNetworkQuality(NetworkQuality.BAD.getValue());
}
onlineLog.setLossCount(onlineLog.getSendCount() - onlineLog.getReceiveCount());
onlineLog.setNetworkQuality(NetworkQuality.ofNetworkQuality(onlineLog.getLossRate(),onlineLog.getRttAvg()));
onlineLog.setMonitorTime(LocalDateTime.now());
return onlineLog;
}
@ -194,12 +221,14 @@ public class OnlineLog implements Serializable {
onlineLog.setDeviceIp(device.getDeviceIp());
onlineLog.setDeviceName(device.getDeviceName());
onlineLog.setStakeMark(device.getStakeMark());
onlineLog.setDirection(device.getDirection());
onlineLog.setDeviceType(device.getDeviceType());
onlineLog.setNetworkQuality(NetworkQuality.BAD.getValue());
onlineLog.setMonitorTime(LocalDateTime.now());
onlineLog.setSendCount(4);
onlineLog.setReceiveCount(0);
onlineLog.setLossCount(4);
onlineLog.setLossRate("100.00%");
onlineLog.setLossRate(MathUtil.doubleTwoDecimal(100));
onlineLog.setRttAvg(0);
onlineLog.setDeviceStatus(UniversalEnum.ZERO.getValue());
return onlineLog;
@ -209,28 +238,17 @@ public class OnlineLog implements Serializable {
onlineLog.setDeviceIp(device.getDeviceIp());
onlineLog.setDeviceName(device.getDeviceName());
onlineLog.setStakeMark(device.getStakeMark());
onlineLog.setDirection(device.getDirection());
onlineLog.setDeviceType(device.getDeviceType());
onlineLog.setNetworkQuality(NetworkQuality.GOOD.getValue());
onlineLog.setMonitorTime(LocalDateTime.now());
onlineLog.setSendCount(4);
onlineLog.setReceiveCount(4);
onlineLog.setLossCount(0);
onlineLog.setLossRate("0.00%");
onlineLog.setLossRate(MathUtil.doubleTwoDecimal(0));
onlineLog.setRttAvg(30);
onlineLog.setDeviceStatus(UniversalEnum.ONE.getValue());
return onlineLog;
}
}
enum NetworkQuality{
GOOD("优"),
NORMAL("良"),
BAD("差");
private final String value;
String getValue() {
return value;
}
NetworkQuality(String value) {
this.value = value;
}
}
}

228
zc-business/src/main/java/com/zc/business/domain/OnlineSum.java

@ -1,35 +1,66 @@
package com.zc.business.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.zc.business.enums.NetworkQuality;
import org.springframework.format.annotation.DateTimeFormat;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class OnlineSum implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private long id;
private long deviceId;
private String deviceName;
private String deviceIp;
private String stakeMark;
private String deviceStatus;
private int sendCount;//发送数
private int receiveCount;//返回数
private int lossCount;//丢包数
private String lossRate;//丢包率
private Long id;//id
private Long deviceId;//设备ID
private int totalCount;//当天总次数
private double onlineRate;//在线率
private double offlineRate;//离线率
private double lossRate;//丢包率
private double rttAvg;//平均往返时延
private String networkQuality;//网络质量
@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd")
private Date statisticalDate;//统计日期
private LocalDate statisticalDate;//统计日期
private int sendCount;//发送数据包总数
private int receiveCount;//返回数
private int lossCount;//丢包数
private int totalOnlineCount;//当天总在线次数
private int totalOfflineCount;//当天总离线次数
private Long roadId;
private String deviceName;//设备名称
private String deviceIp;//设备IP
private String stakeMark;//设备桩号
private String direction;//方向
private String deviceType;//设备类型
private String deviceStatus;//当前设备状态?
private String useState;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime lastOnlineTime;//最后在线时间
public String getUseState() {
return useState;
}
public void setUseState(String useState) {
this.useState = useState;
}
public Long getRoadId() {
return roadId;
}
public long getId() {
public void setRoadId(Long roadId) {
this.roadId = roadId;
}
public Long getId() {
return id;
}
public void setId(long id) {
public void setId(Long id) {
this.id = id;
}
@ -73,6 +104,88 @@ public class OnlineSum implements java.io.Serializable {
this.deviceStatus = deviceStatus;
}
public double getRttAvg() {
return rttAvg;
}
public void setRttAvg(double rttAvg) {
this.rttAvg = rttAvg;
}
public String getNetworkQuality() {
return networkQuality;
}
public void setNetworkQuality(String networkQuality) {
this.networkQuality = networkQuality;
}
public LocalDate getStatisticalDate() {
return statisticalDate;
}
public void setStatisticalDate(LocalDate statisticalDate) {
this.statisticalDate = statisticalDate;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public LocalDateTime getLastOnlineTime() {
return lastOnlineTime;
}
public void setLastOnlineTime(LocalDateTime lastOnlineTime) {
this.lastOnlineTime = lastOnlineTime;
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
public String getDeviceType() {
return deviceType;
}
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
public double getOnlineRate() {
return onlineRate;
}
public void setOnlineRate(double onlineRate) {
this.onlineRate = onlineRate;
}
public double getOfflineRate() {
return offlineRate;
}
public void setOfflineRate(double offlineRate) {
this.offlineRate = offlineRate;
}
public double getLossRate() {
return lossRate;
}
public void setLossRate(double lossRate) {
this.lossRate = lossRate;
}
public int getSendCount() {
return sendCount;
}
@ -97,90 +210,103 @@ public class OnlineSum implements java.io.Serializable {
this.lossCount = lossCount;
}
public String getLossRate() {
return lossRate;
}
public void setLossRate(String lossRate) {
this.lossRate = lossRate;
}
public double getRttAvg() {
return rttAvg;
}
public void setRttAvg(double rttAvg) {
this.rttAvg = rttAvg;
public int getTotalOnlineCount() {
return totalOnlineCount;
}
public String getNetworkQuality() {
return networkQuality;
public void setTotalOnlineCount(int totalOnlineCount) {
this.totalOnlineCount = totalOnlineCount;
}
public void setNetworkQuality(String networkQuality) {
this.networkQuality = networkQuality;
public int getTotalOfflineCount() {
return totalOfflineCount;
}
public Date getStatisticalDate() {
return statisticalDate;
}
public void setStatisticalDate(Date statisticalDate) {
this.statisticalDate = statisticalDate;
public void setTotalOfflineCount(int totalOfflineCount) {
this.totalOfflineCount = totalOfflineCount;
}
@Override
public String toString() {
return "OnlineSum{" +
"id=" + id +
", deviceId='" + deviceId + '\'' +
", deviceId=" + deviceId +
", deviceName='" + deviceName + '\'' +
", deviceIp='" + deviceIp + '\'' +
", stakeMark='" + stakeMark + '\'' +
", direction='" + direction + '\'' +
", deviceType='" + deviceType + '\'' +
", deviceStatus='" + deviceStatus + '\'' +
", totalCount=" + totalCount +
", totalOnlineCount=" + totalOnlineCount +
", totalOfflineCount=" + totalOfflineCount +
", onlineRate='" + onlineRate + '\'' +
", offlineRate='" + offlineRate + '\'' +
", sendCount=" + sendCount +
", receiveCount=" + receiveCount +
", lossCount=" + lossCount +
", lossRate='" + lossRate + '\'' +
", rttAvg=" + rttAvg +
", networkQuality='" + networkQuality + '\'' +
", lastOnlineTime=" + lastOnlineTime +
", statisticalDate=" + statisticalDate +
'}';
}
/**
* 复制日志数据
* @param onlineLog 日志数据
* @return @see OnlineSum
*/
public OnlineSum copyFromLog(OnlineLog onlineLog) {
this.deviceId = onlineLog.getDeviceId();
this.deviceName = onlineLog.getDeviceName();
this.deviceIp = onlineLog.getDeviceIp();
this.stakeMark = onlineLog.getStakeMark();
this.direction = onlineLog.getDirection();
this.deviceType = onlineLog.getDeviceType();
this.deviceStatus = onlineLog.getDeviceStatus();
this.totalCount = 1;
this.totalOnlineCount = onlineLog.getDeviceStatus().equals(DcDevice.ONLINE)?1:0;
this.totalOfflineCount = onlineLog.getDeviceStatus().equals(DcDevice.OFFLINE)?1:0;
this.onlineRate = (double) this.totalOnlineCount/this.totalCount*100;
this.offlineRate = (double) this.totalOfflineCount/this.totalCount*100;
this.sendCount = onlineLog.getSendCount();
this.receiveCount = onlineLog.getReceiveCount();
this.lossCount = onlineLog.getLossCount();
this.lossRate = onlineLog.getLossRate();
this.rttAvg = onlineLog.getRttAvg();
this.networkQuality = onlineLog.getNetworkQuality();
this.statisticalDate = new Date();
if(this.deviceStatus.equals(DcDevice.ONLINE))
this.lastOnlineTime = onlineLog.getMonitorTime();
this.statisticalDate = onlineLog.getMonitorTime().toLocalDate();
return this;
}
/**
* 统计汇总
* @param onlineLog 日志数据
* @return @see OnlineSum
*/
public OnlineSum incrementSummary(OnlineLog onlineLog) {
double rtt = this.rttAvg*this.sendCount+onlineLog.getRttAvg()*onlineLog.getSendCount();
//总rtt时间
double rtt = this.rttAvg*this.receiveCount+onlineLog.getRttAvg()*onlineLog.getReceiveCount();
//更新设备在线状态
this.deviceStatus = onlineLog.getDeviceStatus();
this.totalCount += 1;
this.totalOnlineCount += onlineLog.getDeviceStatus().equals(DcDevice.ONLINE)?1:0;
this.totalOfflineCount += onlineLog.getDeviceStatus().equals(DcDevice.OFFLINE)?1:0;
this.onlineRate = (this.totalCount==0?0:(double)this.totalOnlineCount/this.totalCount)*100;
this.offlineRate = (this.totalCount==0?0:(double)this.totalOfflineCount/this.totalCount)*100;
this.sendCount += onlineLog.getSendCount();
this.receiveCount += onlineLog.getReceiveCount();
this.lossCount += onlineLog.getLossCount();
this.lossRate = String.format("%.2f%%", (this.sendCount==0?0:(double)this.lossCount/this.sendCount)*100);
BigDecimal bd = new BigDecimal(Double.toString(this.sendCount==0?0:rtt/this.sendCount));
this.lossRate = (this.sendCount==0?0:(double)this.lossCount/this.sendCount)*100;
BigDecimal bd = new BigDecimal(Double.toString(this.receiveCount==0?0:rtt/this.receiveCount));
bd = bd.setScale(2, RoundingMode.HALF_UP);
this.rttAvg =bd.doubleValue();
if(this.rttAvg > 0 && this.rttAvg <= 30){
this.networkQuality = OnlineLog.NetworkQuality.GOOD.getValue();
}else if(this.rttAvg >30 && this.rttAvg <= 100){
this.networkQuality = OnlineLog.NetworkQuality.NORMAL.getValue();
}else {
this.networkQuality = OnlineLog.NetworkQuality.BAD.getValue();
}
this.networkQuality = NetworkQuality.ofNetworkQuality(this.offlineRate,this.rttAvg);
this.lastOnlineTime = onlineLog.getMonitorTime();
return this;
}
}

57
zc-business/src/main/java/com/zc/business/enums/NetworkQuality.java

@ -0,0 +1,57 @@
package com.zc.business.enums;
public enum NetworkQuality {
GOOD("优"),
FAIR("良"),
NORMAL("一般"),
BAD("差");
private final String value;
public String getValue() {
return value;
}
NetworkQuality(String value) {
this.value = value;
}
public static String ofNetworkQuality(double offlineRate,double rttAvg) {
double score = calculateScore(offlineRate,rttAvg);
if (score <= 10 && score >= 9) {
return GOOD.getValue();
}else if (score < 9 && score >= 7) {
return FAIR.getValue();
}else if(score >=6 && score < 7){
return NORMAL.getValue();
}else {
return BAD.getValue();
}
}
/**
* 计算网络质量分(权重丢包率0.5平均往返时延0.5)
* @param offlineRate 丢包率
* @param rttAvg 平均往返时延
* @return 分数
*/
private static double calculateScore(double offlineRate,double rttAvg){
double offScore ,rttScore;
if (offlineRate <= 2) {
offScore = 10;
}else if (offlineRate <= 10 && offlineRate > 2){
offScore = 5;
}else if (offlineRate <= 15 && offlineRate > 10){
offScore = 4;
}else {
offScore = 1;
}
if (rttAvg <= 30 && rttAvg > 0) {
rttScore = 10;
}else if (rttAvg <= 50 && rttAvg > 30){
rttScore = 5;
}else if (rttAvg <= 100 && rttAvg > 50){
rttScore = 4;
}else {
rttScore = 1;
}
return offScore*0.5+rttScore*0.5;
}
}

40
zc-business/src/main/java/com/zc/business/enums/UniversalEnum.java

@ -361,64 +361,64 @@ public enum UniversalEnum {
//全部设备
ALL_EQUIPMENT(0, "全部设备"),
//高清网络枪型固定摄像机
//高清网络枪型固定摄像机1-1
HD_NETWORK_GUN_TYPE_FIXED_CAMERA(0, "高清网络枪型固定摄像机"),
//高清网络球形摄像机
//高清网络球形摄像机1-2
HD_NETWORK_SPHERICAL_CAMERA(0, "高清网络球形摄像机"),
//桥下高清网络球形摄像机
//桥下高清网络球形摄像机1-3
UNDER_THE_BRIDGE_HD_NETWORK_SPHERICAL_CAMERA(0, "桥下高清网络球形摄像机"),
//360°全景摄像机
//360°全景摄像机1-4
THREE_HUNDRED_SIXTY_PANORAMIC_CAMERA(0, "360°全景摄像机"),
//180°全景摄像机
//180°全景摄像机1-5
ONE_HUNDRED_EIGHTY_PANORAMIC_CAMERA(0, "180°全景摄像机"),
//门架式可变信息标志
//门架式可变信息标志2-1
GANTRY_TYPE_VARIABLE_MESSAGE_SIGN(0, "门架式可变信息标志"),
//雨棚可变信息标志
//雨棚可变信息标志2-3
AWNING_VARIABLE_INFORMATION_SIGN(0, "雨棚可变信息标志"),
//站前可变信息标志
//站前可变信息标志2-2
VARIABLE_MESSAGE_SIGN_IN_FRONT_OF_STATION(0, "站前可变信息标志"),
//站前悬臂式可变信息标志
//站前悬臂式可变信息标志2-4
CANTILEVER_VARIABLE_INFORMATION_SIGN_IN_FRONT_OF_STATION(0, "站前悬臂式可变信息标志"),
//气象检测器
//气象检测器3
METEOROLOGICAL_DETECTOR(0, "气象检测器"),
//路段语音广播系统
//路段语音广播系统5
SECTION_VOICE_BROADCAST_SYSTEM(0, "路段语音广播系统"),
//护栏碰撞预警系统
//护栏碰撞预警系统6
GUARDRAIL_COLLISION_WARNING_SYSTEM(0, "护栏碰撞预警系统"),
//毫米波雷达
//毫米波雷达7
MILLIMETER_WAVE_RADAR(0, "毫米波雷达"),
//合流区预警系统
//合流区预警系统8
CONFLUENCE_AREA_EARLY_WARNING_SYSTEM(0, "合流区预警系统"),
//激光疲劳唤醒
//激光疲劳唤醒10
LASER_FATIGUE_AWAKENING(0, "激光疲劳唤醒"),
//一类交通量调查站
//一类交通量调查站11
CLASS_I_TRAFFIC_SURVEY_STATION(0, "一类交通量调查站"),
//智能行车诱导系统
//智能行车诱导系统12
INTELLIGENT_DRIVING_GUIDANCE_SYSTEM(0, "智能行车诱导系统"),
//智能设备箱
//智能设备箱13 光纤在线监测14
SMART_DEVICE_BOX(0, "智能设备箱"),
//太阳能板
//太阳能板15
SOLAR_PANEL(0, "太阳能板"),
//远端机
//远端机16
REMOTE_COMPUTER(0, "远端机"),
//设备名称

1
zc-business/src/main/java/com/zc/business/mapper/DcDeviceMapper.java

@ -34,4 +34,5 @@ public interface DcDeviceMapper extends BaseMapper<DcDevice> {
public List<HashMap<String,Object>> selectDeviceParameterProperties(DcDevice dcDevice);
int selectDeviceNumber();
public List<Map<String,Object>> selectDeviceOfRoad();
}

9
zc-business/src/main/java/com/zc/business/mapper/OnlineLogMapper.java

@ -1,9 +1,18 @@
package com.zc.business.mapper;
import com.zc.business.domain.OnlineLog;
import org.apache.ibatis.annotations.Param;
import java.time.LocalDateTime;
import java.util.List;
public interface OnlineLogMapper {
int addBatch(List<OnlineLog> onlineLogs);
List<OnlineLog> queryByDate(
@Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime);
List<OnlineLog> queryByDateAndDevice(
@Param("startTime")LocalDateTime startTime,
@Param("endTime")LocalDateTime endTime,
@Param("deviceId")Long deviceId);
}

26
zc-business/src/main/java/com/zc/business/mapper/OnlineSumMapper.java

@ -0,0 +1,26 @@
package com.zc.business.mapper;
import com.zc.business.domain.OnlineSum;
import org.apache.ibatis.annotations.Param;
import java.time.LocalDate;
import java.util.List;
public interface OnlineSumMapper {
int duplicateKeyUpdate(OnlineSum onlineSum);
List<OnlineSum> queryByDateRangeOfDevice(@Param("deviceId") Long deviceId,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
List<OnlineSum> queryByDeviceTypeAndDate(
@Param("types") String[] types,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate,
@Param("direction") String direction
);
List<OnlineSum> queryByDateOfDeviceType(@Param("queryDate") LocalDate queryDate);
List<OnlineSum> queryByDateOfRoad(@Param("queryDate") LocalDate queryDate);
List<OnlineSum> queryByDeviceTypesOfToday(
@Param("types") String[] deviceTypes,
@Param("orderByField") String orderByField,
@Param("orderDirection") String orderDirection,
@Param("searchValue") String searchValue);
}

3
zc-business/src/main/java/com/zc/business/service/IOnlineLogService.java

@ -2,6 +2,7 @@ package com.zc.business.service;
import com.zc.business.domain.OnlineLog;
import java.time.LocalDateTime;
import java.util.List;
/**
@ -9,4 +10,6 @@ import java.util.List;
*/
public interface IOnlineLogService {
int addBatch(List<OnlineLog> list);
List<OnlineLog> queryByDate(LocalDateTime startTime, LocalDateTime endTime);
List<OnlineLog> queryByDateAndDevice(LocalDateTime startTime, LocalDateTime endTime, Long deviceId);
}

27
zc-business/src/main/java/com/zc/business/service/IOnlineSumService.java

@ -0,0 +1,27 @@
package com.zc.business.service;
import com.zc.business.domain.OnlineSum;
import java.time.LocalDate;
import java.util.List;
public interface IOnlineSumService {
int duplicateKeyUpdate(OnlineSum onlineSum);
List<OnlineSum> queryByDateRangeOfDevice(Long deviceId, LocalDate startDate, LocalDate endDate);
List<OnlineSum> queryByDeviceTypeAndDate(
String[] deviceType,
LocalDate startDate,
LocalDate endDate,
String direction
);
List<OnlineSum> queryByDateOfDeviceType(LocalDate queryDate);
List<OnlineSum> queryByDateOfRoad(LocalDate queryDate);
List<OnlineSum> queryByDeviceTypesOfToday(
String[] deviceTypes,
String orderByField,
String orderDirection,
String searchValue);
}

4
zc-business/src/main/java/com/zc/business/service/impl/DcDeviceServiceImpl.java

@ -574,5 +574,9 @@ public class DcDeviceServiceImpl extends ServiceImpl<DcDeviceMapper, DcDevice> i
.get(); // 请求方法
return JSON.parseObject(response.body().string(), AjaxResult.class);
}
public List<Map<String,Object>> selectDeviceOfRoad(){
return dcDeviceMapper.selectDeviceOfRoad();
}
}

11
zc-business/src/main/java/com/zc/business/service/impl/OnlineLogServiceImpl.java

@ -6,6 +6,7 @@ import com.zc.business.service.IOnlineLogService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class OnlineLogServiceImpl implements IOnlineLogService {
@ -16,4 +17,14 @@ public class OnlineLogServiceImpl implements IOnlineLogService {
public int addBatch(List<OnlineLog> list) {
return onlineLogMapper.addBatch(list);
}
@Override
public List<OnlineLog> queryByDate(LocalDateTime startTime, LocalDateTime endTime) {
return onlineLogMapper.queryByDate(startTime, endTime);
}
@Override
public List<OnlineLog> queryByDateAndDevice(LocalDateTime startTime, LocalDateTime endTime, Long deviceId) {
return onlineLogMapper.queryByDateAndDevice(startTime, endTime, deviceId);
}
}

55
zc-business/src/main/java/com/zc/business/service/impl/OnlineSumServiceImpl.java

@ -0,0 +1,55 @@
package com.zc.business.service.impl;
import com.zc.business.domain.OnlineSum;
import com.zc.business.mapper.OnlineSumMapper;
import com.zc.business.service.IOnlineSumService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
@Service
public class OnlineSumServiceImpl implements IOnlineSumService {
@Resource
OnlineSumMapper onlineSumMapper;
@Override
public int duplicateKeyUpdate(OnlineSum onlineSum) {
return onlineSumMapper.duplicateKeyUpdate(onlineSum);
}
@Override
public List<OnlineSum> queryByDateRangeOfDevice(
Long deviceId,
LocalDate startDate,
LocalDate endDate) {
return onlineSumMapper.queryByDateRangeOfDevice(deviceId, startDate, endDate);
}
@Override
public List<OnlineSum> queryByDeviceTypeAndDate(
String[] deviceType,
LocalDate startDate,
LocalDate endDate,
String direction) {
return onlineSumMapper.queryByDeviceTypeAndDate(deviceType, startDate, endDate, direction);
}
@Override
public List<OnlineSum> queryByDateOfDeviceType(LocalDate queryDate) {
return onlineSumMapper.queryByDateOfDeviceType(queryDate);
}
@Override
public List<OnlineSum> queryByDateOfRoad(LocalDate queryDate) {
return onlineSumMapper.queryByDateOfRoad(queryDate);
}
@Override
public List<OnlineSum> queryByDeviceTypesOfToday(String[] deviceTypes, String orderByField, String orderDirection, String searchValue) {
return onlineSumMapper.queryByDeviceTypesOfToday(
deviceTypes,
orderByField,
orderDirection,
searchValue);
}
}

86
zc-business/src/main/java/com/zc/business/task/DeviceOnlineTask.java

@ -14,12 +14,14 @@ import com.zc.business.domain.OnlineSum;
import com.zc.business.enums.UniversalEnum;
import com.zc.business.service.IDcDeviceService;
import com.zc.business.service.IOnlineLogService;
import com.zc.business.service.IOnlineSumService;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
@ -29,6 +31,8 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.springframework.util.ObjectUtils;
@ -43,6 +47,7 @@ public class DeviceOnlineTask {
Logger logger = LoggerFactory.getLogger(DeviceOnlineTask.class);
IDcDeviceService dcDeviceService = SpringUtils.getBean(IDcDeviceService.class);
IOnlineLogService onlineLogService = SpringUtils.getBean(IOnlineLogService.class);
IOnlineSumService onlineSumService = SpringUtils.getBean(IOnlineSumService.class);
RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
ExecutorService executorService;
final static int BATCH_SIZE = 100;
@ -144,12 +149,14 @@ public class DeviceOnlineTask {
rttAvg = Double.parseDouble(stats[3].split("/")[1]);
}
}
// Wait for the process to finish
process.waitFor();
return logBuilder.setDeviceStatus(UniversalEnum.ONE.getValue())
.setSendCount(transmitted)
.setReceiveCount(received)
.setRttAvg(rttAvg)
.build(device);
} catch (IOException e) {
} catch (IOException | InterruptedException e) {
e.printStackTrace();
return logBuilder.buildBad(device);
}
@ -157,7 +164,7 @@ public class DeviceOnlineTask {
public OnlineLog sendPingPacketOfWindows(DcDevice device) {
OnlineLog.LogBuilder logBuilder = new OnlineLog.LogBuilder();
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "ping", "-n", "4", device.getDeviceIp());
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "ping", "-n", "10", device.getDeviceIp());
try {
// 启动进程
Process process = processBuilder.start();
@ -229,7 +236,7 @@ public class DeviceOnlineTask {
*/
private void incrementSummary(OnlineLog onlineLog) {
// 获取当天日期
String date = DateUtils.format(new Date(), "yyyy-MM-dd");
String date = LocalDate.now().toString();
long deviceId = onlineLog.getDeviceId();
OnlineSum onlineSum = redisCache.getCacheMapValue(RedisKeyConstants.DEVICE_ONLINE , date+":"+deviceId);
if (ObjectUtils.isEmpty(onlineSum)){
@ -242,6 +249,7 @@ public class DeviceOnlineTask {
onlineSum.incrementSummary(onlineLog);
redisCache.setCacheMapValue(RedisKeyConstants.DEVICE_ONLINE, date+":"+deviceId, onlineSum);
}
onlineSumService.duplicateKeyUpdate(onlineSum);
}
/**
@ -284,8 +292,8 @@ public class DeviceOnlineTask {
AIX_SYSTEM("aix"),
UNIX_SYSTEM("unix"),
UNKNOWN_SYSTEM("unknown");
String value;
String getValue() {
private final String value;
public String getValue() {
return value;
}
SystemType(String value) {
@ -293,24 +301,23 @@ public class DeviceOnlineTask {
}
static SystemType checkSystem(){
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains(SystemType.WIN_SYSTEM.getValue())) {
return SystemType.WIN_SYSTEM;
} else if (osName.contains(SystemType.LINUX_SYSTEM.getValue())) {
return SystemType.LINUX_SYSTEM;
} else if (osName.contains(SystemType.AIX_SYSTEM.getValue())) {
return SystemType.AIX_SYSTEM;
} else if (osName.contains(SystemType.UNIX_SYSTEM.getValue())) {
return SystemType.UNIX_SYSTEM;
if (osName.contains(WIN_SYSTEM.getValue())) {
return WIN_SYSTEM;
} else if (osName.contains(LINUX_SYSTEM.getValue())) {
return LINUX_SYSTEM;
} else if (osName.startsWith(AIX_SYSTEM.getValue())) {
return AIX_SYSTEM;
} else if (osName.contains(UNIX_SYSTEM.getValue()) && !osName.contains(LINUX_SYSTEM.getValue())) {
return UNIX_SYSTEM;
}
return SystemType.UNKNOWN_SYSTEM;
return UNKNOWN_SYSTEM;
}
}
enum PingCommand{
LINUX_PING("ping -c 4 "),
LINUX_PING("ping -c 10 "),
WINDOWS_PING("ping ");
private final String value;
String getValue() {
public String getValue() {
return value;
}
PingCommand(String value) {
@ -318,32 +325,27 @@ public class DeviceOnlineTask {
}
}
public static void main(String[] args) {
// 假设你要ping的主机地址
String host = "10.0.111.11";
// 构建ping命令,注意:Windows和Unix/Linux的ping命令略有不同
// Windows: ping -n 4 www.google.com
// Unix/Linux: ping -c 4 www.google.com
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "ping", "-n", "4", host);
try {
// 启动进程
Process process = processBuilder.start();
// 读取命令的标准输出
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
public void sumLogByDayCount(Integer days){
if(Objects.isNull(days)){
days = 2;
}
LocalDateTime start = LocalDateTime.now().minusDays(days);
LocalDateTime end = LocalDateTime.now();
List<OnlineLog> onlineLogs = onlineLogService.queryByDate(start, end);
Map<LocalDate,List<OnlineLog>> localDateListMap = onlineLogs.stream().collect(Collectors.groupingBy(onlineLog -> onlineLog.getMonitorTime().toLocalDate()));
localDateListMap.forEach((key,value)->{
value.stream().collect(Collectors.groupingBy(OnlineLog::getDeviceId)).forEach((k,v)->{
OnlineSum onlineSum = new OnlineSum();
for (int i = 0; i < v.size(); i++) {
if(i == 0){
onlineSum = onlineSum.copyFromLog(v.get(i));
}else {
onlineSum.incrementSummary(v.get(i));
}
// 等待进程结束
int exitCode = process.waitFor();
System.out.println("\nExited with error code : " + exitCode);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
onlineSumService.duplicateKeyUpdate(onlineSum);
});
});
}
}

18
zc-business/src/main/java/com/zc/business/utils/MathUtil.java

@ -0,0 +1,18 @@
package com.zc.business.utils;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class MathUtil {
/**
* 保留两位小数
* @param d 数字
* @return 保留两位小数后的数字
*/
public static double doubleTwoDecimal(double d){
BigDecimal originalNumber = new BigDecimal(d);
BigDecimal roundedNumber = originalNumber.setScale(2, RoundingMode.HALF_UP);
return roundedNumber.doubleValue();
}
}

108
zc-business/src/main/resources/mapper/OnlineSumMapper.xml

@ -0,0 +1,108 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zc.business.mapper.OnlineSumMapper">
<resultMap type="com.zc.business.domain.OnlineSum" id="OnlineSum">
<result property="id" column="id"/>
<result property="deviceId" column="device_id"/>
<result property="totalCount" column="total_count"/>
<result property="onlineRate" column="online_rate"/>
<result property="offlineRate" column="offline_rate"/>
<result property="lossRate" column="loss_rate"/>
<result property="rttAvg" column="rtt_avg"/>
<result property="networkQuality" column="network_quality"/>
<result property="statisticalDate" column="statistical_date"/>
<result property="deviceType" column="device_type"/>
<result property="roadId" column="section_id"/>
<result property="deviceIp" column="device_ip"/>
<result property="deviceName" column="device_name"/>
<result property="stakeMark" column="stake_mark"/>
<result property="direction" column="direction"/>
<result property="useState" column="use_state"/>
</resultMap>
<insert id="duplicateKeyUpdate">
insert into dc_online_sum
(device_id,total_count,online_rate,offline_rate,loss_rate,rtt_avg,network_quality,statistical_date)
values
(#{deviceId},#{totalCount},#{onlineRate},#{offlineRate},#{lossRate},#{rttAvg},#{networkQuality},#{statisticalDate})
on duplicate key update
total_count= values(total_count),
online_rate = values(online_rate),
offline_rate = values(offline_rate),
loss_rate = values(loss_rate),
rtt_avg = values(rtt_avg),
network_quality = values(network_quality)
</insert>
<select id="queryByDateRangeOfDevice" resultMap="OnlineSum">
select id,device_id,total_count,online_rate,offline_rate,loss_rate,rtt_avg,network_quality,statistical_date
from dc_online_sum
where
device_id = #{deviceId} and (statistical_date between #{startDate} and #{endDate})
</select>
<select id="queryByDeviceTypeAndDate" resultMap="OnlineSum">
select s.id,s.device_id,total_count,online_rate,offline_rate,loss_rate,rtt_avg,network_quality,statistical_date,COALESCE(d.child_type,d.device_type) as device_type
from dc_online_sum s join dc_device d on s.device_id = d.id
where d.use_state = 1
AND (s.statistical_date BETWEEN #{startDate} AND #{endDate})
AND (d.device_type in
<foreach item="typeItem" collection="types" open="(" separator="," close=")">
#{typeItem}
</foreach>
or d.child_type in
<foreach item="typeItem" collection="types" open="(" separator="," close=")">
#{typeItem}
</foreach>
)
<if test="direction != null and direction != ''">
AND d.direction = #{direction}
</if>
</select>
<select id="queryByDateOfDeviceType" resultMap="OnlineSum">
select s.id,s.device_id,total_count,
online_rate,offline_rate,loss_rate,
rtt_avg,network_quality,statistical_date,COALESCE (d.child_type, d.device_type) as device_type
from dc_online_sum s join dc_device d on s.device_id = d.id
where d.use_state = 1 and s.statistical_date = #{queryDate}
</select>
<select id="queryByDateOfRoad" resultMap="OnlineSum">
select s.id,s.device_id,total_count,online_rate,
offline_rate,loss_rate,rtt_avg,network_quality,statistical_date,
m.section_id
from dc_online_sum s join dc_device d on s.device_id = d.id
LEFT JOIN dc_stake_mark m on m.stake_mark=d.stake_mark and m.direction = d.direction
where d.use_state = 1 and s.statistical_date = #{queryDate}
</select>
<select id="queryByDeviceTypesOfToday" resultMap="OnlineSum">
select d.device_ip,d.device_name,d.stake_mark,COALESCE (d.child_type, d.device_type) as device_type,
d.direction,d.use_state,
s.id,s.device_id,total_count,online_rate,
offline_rate,loss_rate,rtt_avg,network_quality,statistical_date
from dc_device d
join dc_online_sum s on s.device_id = d.id
where
s.statistical_date = CURDATE()
<if test="types.length != 0">
and (d.device_type in
<foreach item="typeItem" collection="types" open="(" separator="," close=")">
#{typeItem}
</foreach>
or d.child_type in
<foreach item="typeItem" collection="types" open="(" separator="," close=")">
#{typeItem}
</foreach>
)
</if>
<if test="searchValue != null and searchValue != ''">
and (d.device_ip like concat('%',#{searchValue},'%')
or d.stake_mark like concat('%',#{searchValue},'%'))
</if>
<if test="orderByField != null and orderDirection != null">
order by ${orderByField} ${orderDirection}
</if>
</select>
</mapper>

8
zc-business/src/main/resources/mapper/business/DcDeviceMapper.xml

@ -111,7 +111,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</select>
<select id="numberOfDevicesByType" parameterType="dcDevice" resultMap="DcDevice">
SELECT COALESCE(child_type, device_type) AS device_type, COUNT(*) AS sumAll
SELECT use_state, COALESCE(child_type, device_type) AS device_type, COUNT(*) AS sumAll
FROM dc_device
<where>
<if test="useState!=null">
@ -177,4 +177,10 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
(SELECT COUNT(id) FROM dc_facility) AS total_count;
</select>
<select id="selectDeviceOfRoad" resultType="java.util.HashMap">
select d.id deviceId, r.id roadId,use_state useStata FROM dc_device d
JOIN dc_stake_mark s ON s.stake_mark = d.stake_mark AND s.direction = d.direction
JOIN dc_road_section r ON r.id = s.section_id
</select>
</mapper>

27
zc-business/src/main/resources/mapper/business/OnlineLogMapper.xml

@ -4,10 +4,20 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zc.business.mapper.OnlineLogMapper">
<resultMap type="OnlineLog" id="OnlineLog">
<resultMap type="com.zc.business.domain.OnlineLog" id="OnlineLog">
<result property="id" column="id"/>
<result property="deviceId" column="device_id"/>
<result property="deviceName" column="device_name"/>
<result property="deviceIp" column="device_ip"/>
<result property="stakeMark" column="stake_mark"/>
<result property="deviceStatus" column="device_status"/>
<result property="sendCount" column="send_count"/>
<result property="receiveCount" column="receive_count"/>
<result property="lossCount" column="loss_count"/>
<result property="lossRate" column="loss_rate"/>
<result property="networkQuality" column="network_quality"/>
<result property="rttAvg" column="rtt_avg"/>
<result property="monitorTime" column="monitor_time"/>
</resultMap>
<insert id="addBatch">
@ -35,4 +45,15 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</foreach>
</insert>
<select id="queryByDate" resultMap="OnlineLog">
select id,device_id,device_name,device_ip,stake_mark,device_status,send_count,
receive_count,loss_count,loss_rate,network_quality,rtt_avg,monitor_time
from dc_online_log where monitor_time between #{startTime} and #{endTime}
</select>
<select id="queryByDateAndDevice" resultMap="OnlineLog">
select id,device_id,device_name,device_ip,stake_mark,device_status,send_count,
receive_count,loss_count,loss_rate,network_quality,rtt_avg,monitor_time
from dc_online_log where device_id = #{deviceId} and monitor_time between #{startTime} and #{endTime}
</select>
</mapper>

Loading…
Cancel
Save