package com.zc.business.controller; import cn.hutool.core.date.DateUtil; import cn.hutool.core.io.unit.DataUnit; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.*; 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.DateUtils; import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.common.utils.spring.SpringUtils; import com.ruoyi.system.service.ISysConfigService; import com.zc.business.constant.DeviceTypeConstants; import com.zc.business.domain.DcDevice; import com.zc.business.domain.DcDoor; import com.zc.business.domain.DcEvent; import com.zc.business.domain.DcEventProcess; import com.zc.business.domain.DcSmokeRecord; import com.zc.business.domain.DcSnmpAlarm; 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; import com.zc.common.core.websocket.WebSocketService; import com.zc.common.core.websocket.constant.WebSocketEvent; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.v3.oas.annotations.Parameter; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import org.aspectj.weaver.patterns.HasMemberTypePattern; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.converter.xml.AbstractJaxb2HttpMessageConverter; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.io.IOException; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.stream.Collectors; /** * 设备Controller * * @author zhaoxianglong */ @Component() @Api(tags = {"设备"}) @RestController @RequestMapping("/business/device") public class DcDeviceController extends BaseController { @Resource private RedisCache redisCache; @Resource private IDcDeviceService dcDeviceService; @Resource private VideoController videoController; private static final int THREAD_POOL_SIZE = 100; // 线程池大小 private ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE); private static final String DOORSTATUS = "doorStatus";//redis策略缓存的key private static final String SOMKEVALUE = "smokeValue";//redis策略缓存的key private static final String ALARMVALUE = "alarmValue";//redis策略缓存的key /* @Value("${iot.address}") private String iotAddress; */ private static String iotAddress; @Value("${iot.address}") public void setIotAddress(String url) { iotAddress = url; } @Resource private BroadcastController broadcastController; @Resource private ISysConfigService configService; //*********************************设备增删改查****************************************** //根据设备id查询设备信息 @PostMapping("/getDeviceById") public AjaxResult getDeviceById(@RequestBody DcDevice dcDevice) { if (dcDevice==null||dcDevice.getIotDeviceId()==null){ return AjaxResult.error("参数异常"); } return AjaxResult.success(dcDeviceService.getDcDeviceById(dcDevice.getIotDeviceId())); } /** * 分页查询设备列表 * * @param dcDevice 请求参数 * @return 分页查询结果 */ @ApiOperation("分页查询设备列表") // @PreAuthorize("@ss.hasPermi('iot:device:list')") @GetMapping("list") public TableDataInfo listDevice(DcDevice dcDevice) { return getDataTable(dcDeviceService.pageDevice(dcDevice)); } /** * 统计异常设备 * * @return 查询结果 */ @ApiOperation("统计异常设备") // @PreAuthorize("@ss.hasPermi('iot:device:list')") @GetMapping("abnormalDevice") public AjaxResult statisticalAnomalyDevice() { return AjaxResult.success(dcDeviceService.statisticalAnomalyDevice()); } /** * 无分页查询设备列表 * * @param dcDevice 请求参数 * @return 查询结果 */ @ApiOperation("无分页查询设备列表") // @PreAuthorize("@ss.hasPermi('iot:device:query')") @GetMapping("query") public AjaxResult queryDevice(DcDevice dcDevice) { return AjaxResult.success(dcDeviceService.listDevice(dcDevice)); } /** * 根据事件数据查询可用设备 */ @ApiOperation("根据事件数据查询可用设备") @PostMapping("/deviceList/{deviceType}") public AjaxResult deviceListByEvent(@RequestBody DcEvent dcEvent,@PathVariable String deviceType) { return AjaxResult.success(dcDeviceService.deviceListByEvent(dcEvent, deviceType)); } /** * 无分页根据设备桩号查询设备列表 * * @param parameter 请求参数 * @return 查询结果 */ @ApiOperation("无分页根据设备桩号查询设备列表") //@PreAuthorize("@ss.hasPermi('iot:device:query')") @PostMapping("pileNumberQuery") public AjaxResult devicePileNumberQueryDevice(@RequestBody Map parameter) throws HttpException, IOException, InterruptedException { List dcDevices = dcDeviceService.devicePileNumberQueryDevice(parameter); // String deviceType = String.valueOf(parameter.get("deviceType")); // if (deviceType.equals("15")){ // AjaxResult ajaxResult = ConfluenceAreaEarlyWarningDeviceBatteryLowWarning(); // Object data = ajaxResult.get("data"); // if (data instanceof List) { // List> dataList = (List>) data; // for (Map entry : dataList) { // String functionId = (String) entry.get("functionId"); // String device = (String) entry.get("device"); // System.out.println("device:"+device); // System.out.println("functionId:"+functionId); // Object result = entry.get("result"); // if (result instanceof Map) { // Map resultMap = (Map) result; // Integer resultCode = (Integer) resultMap.get("code"); // if (resultCode==200){ // Object innerData = resultMap.get("data"); // if (innerData instanceof List) { // List> innerDataList = (List>) innerData; // for (Map innerEntry : innerDataList) { // Integer innerCode = (Integer) innerEntry.get("code"); // System.out.println("Inner Code: " + innerCode); // if (innerCode==200){ // for (DcDevice dcDevice : dcDevices) { // if (String.valueOf(dcDevice.getId()).equals(device)){ // dcDevice.setDeviceState("1"); // } // } // }else { // for (DcDevice dcDevice : dcDevices) { // if (String.valueOf(dcDevice.getId()).equals(device)){ // dcDevice.setDeviceState("0"); // } // } // } // } // } // }else { // for (DcDevice dcDevice : dcDevices) { // if (String.valueOf(dcDevice.getId()).equals(device)){ // dcDevice.setDeviceState("0"); // } // } // } // // } // } // } // // } return AjaxResult.success(dcDevices); } /** * 根据id查询设备信息 * * @param id id * @return 查询结果 */ @ApiOperation("根据id查询设备信息") // @PreAuthorize("@ss.hasPermi('iot:device:query')") @GetMapping("{id}") public AjaxResult getDevice(@PathVariable String id) { return AjaxResult.success(dcDeviceService.getDevice(id)); } /** * 根据网段查询设备 */ @ApiOperation("根据网段查询设备") @GetMapping("/networkSegment/{networkSegment}") public AjaxResult getDeviceByNetworkSegment(@PathVariable String networkSegment) { return AjaxResult.success(dcDeviceService.getDeviceByNetworkSegment(networkSegment)); } /** * 根据网段分组查询分组设备 */ @ApiOperation("根据网段分组查询分组设备") @GetMapping("/networkSegment") public AjaxResult getGroupingDeviceByNetworkSegment() { return AjaxResult.success(dcDeviceService.getGroupingDeviceByNetworkSegment()); } /** * 新增 * * @param dcDevice 新增参数 * @return 新增操作结果 */ @ApiOperation("新增") // @PreAuthorize("@ss.hasPermi('iot:device:add')") @Log(title = "新增设备", businessType = BusinessType.INSERT) @PostMapping public AjaxResult addDevice(@Valid @RequestBody DcDevice dcDevice) { return toAjax(dcDeviceService.addDevice(dcDevice)); } /** * 修改 * * @param dcDevice 修改参数 * @return 修改操作结果 */ @ApiOperation("修改") // @PreAuthorize("@ss.hasPermi('iot:device:edit')") @Log(title = "修改设备", businessType = BusinessType.UPDATE) @PutMapping public AjaxResult editDevice(@Valid @RequestBody DcDevice dcDevice) { return toAjax(dcDeviceService.editDevice(dcDevice)); } /** * 删除 * * @param ids id集 * @return 删除操作结果 */ @ApiOperation("删除") // @PreAuthorize("@ss.hasPermi('iot:device:remove')") @Log(title = "删除", businessType = BusinessType.DELETE) @DeleteMapping("{ids}") public AjaxResult removeDevice(@PathVariable List ids) { return toAjax(dcDeviceService.removeDevice(ids)); } /** * 导出 * * @param response 响应 * @param iotDevice 导入数据结果 */ // @PreAuthorize("@ss.hasPermi('iot:device:export')") @Log(title = "导出设备", businessType = BusinessType.EXPORT) @PostMapping("export") public void exportDevice(HttpServletResponse response, DcDevice iotDevice) { List list = dcDeviceService.listDevice(iotDevice); ExcelUtil util = new ExcelUtil<>(DcDevice.class); util.exportExcel(response, list, UniversalEnum.EQUIPMENT_DATA.getValue()); } //***********************************物联设备接口************************************** /** * 根据物联产品id获取设备数据 * * @param productId 物联产品id * @return 获取设备数据操作结果 */ @ApiOperation("根据物联产品id获取设备数据") @GetMapping("/devices/{productId}") public AjaxResult getDeviceByProductId(@PathVariable @Parameter(description = "产品ID") String productId) throws HttpException, IOException { if (!StringUtils.hasText(productId)) { return AjaxResult.error(UniversalEnum.THE_PRODUCT_ID_CANNOT_BE_EMPTY.getValue()); } OkHttp okHttp = new OkHttp(); Response response // 请求响应 = okHttp .url(iotAddress + UniversalEnum.GET_DEVICE_DATA_BASED_ON_IOT_PRODUCT_ID.getValue() + productId) // 请求地址 .get(); // 请求方法 return JSON.parseObject(response.body().string(), AjaxResult.class); } /** * 根据物联产品id获取设备数据 * * @param iotDeviceId 物联产品id * @return 获取设备数据操作结果 */ @ApiOperation("根据物联产品id获取设备数据") @GetMapping("/getDeviceByIotDeviceId/{iotDeviceId}") public AjaxResult getDeviceByIotDeviceId(@PathVariable @Parameter(description = "设备ID") String iotDeviceId) throws HttpException, IOException { return dcDeviceService.getDeviceByIotDeviceId(iotDeviceId); } /** * 根据物联设备id获取最新属性数据 * * @param deviceId 物联设备id SolarPanelTimingTask * @return 获取属性数据操作结果 */ @ApiOperation("获取设备最新属性数据") @GetMapping("/properties/latest/{deviceId}") public AjaxResult getDeviceLatestProperties(@PathVariable @Parameter(description = "设备ID") String deviceId) throws HttpException, IOException { if (!StringUtils.hasText(deviceId)) { return AjaxResult.error(UniversalEnum.DEVICE_NOT_CONNECTED.getValue()); } OkHttp okHttp = new OkHttp(); Response response // 请求响应 = okHttp .url(iotAddress + UniversalEnum.OBTAIN_THE_LATEST_DEVICE_PROPERTY_DATA.getValue() + deviceId) // 请求地址 .get(); // 请求方法 return JSON.parseObject(response.body().string(), AjaxResult.class); } @ApiOperation("获取太阳能设备属性数据") @GetMapping("/properties/solarEnergy") public AjaxResult getDeviceLatestSolarEnergy() throws HttpException, IOException { Map 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"); // StakeMarkUtils.stakeMarkToInt() //facilitiesType List dcDevices = dcDeviceService.devicePileNumberQueryDevice(parameter); List> dcDeviceList = new ArrayList<>(); OkHttp okHttp = new OkHttp(); for (DcDevice dcDevice : dcDevices) { String iotDeviceId = dcDevice.getIotDeviceId(); Response response // 请求响应 = okHttp .url(iotAddress + UniversalEnum.OBTAIN_THE_LATEST_DEVICE_PROPERTY_DATA.getValue() + iotDeviceId) // 请求地址 .get(); // 请求方法 // 解析JSON字符串 JsonElement jsonElement = JsonParser.parseString(response.body().string()); JsonObject jsonObject = jsonElement.getAsJsonObject(); if (jsonObject.has("data") && jsonObject.get("data").isJsonArray()) { JsonArray dataArray = jsonObject.getAsJsonArray("data"); // 构建Map Map attributeMap = new HashMap<>(); for (JsonElement element : dataArray) { if (element.isJsonObject()) { JsonObject item = element.getAsJsonObject(); if (item.has("property") && item.has("formatValue")) { String property = item.get("property").getAsString(); String formatValue = item.get("formatValue").getAsString(); attributeMap.put(property, formatValue); } } } dcDevice.setAttributeData(attributeMap); } } return AjaxResult.success(dcDevices); } @ApiOperation("太阳能状况统计") @GetMapping("/properties/history/oneDay/{propertyId}") public AjaxResult queryDevicePropertiesDay(@PathVariable @Parameter(description = "属性ID") String propertyId) throws HttpException, IOException, ParseException { // HashMap props = new HashMap<>(); // // 设置查询条件的键为“timestamp$BTW”,表示时间戳在一定范围内 // props.put("terms[0].column", "timestamp$BTW"); // ArrayList 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 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 allDevicesHourlyAggregates = new TreeMap<>(); // // List 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> 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 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 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 allDevicesHourlyAggregates= redisCache.getCacheObject(propertyId); return AjaxResult.success(allDevicesHourlyAggregates); } public void solarEnergyConditionStatisticsOne() { RedisCache redisCache = SpringUtils.getBean(RedisCache.class); Map stringDoubleMap = solarEnergyConditionStatistics("dailyAccumulatedCharge"); if (stringDoubleMap != null) { redisCache.setCacheObject("dailyAccumulatedCharge", stringDoubleMap); } } public void solarEnergyConditionStatisticsTwo(){ RedisCache redisCache = SpringUtils.getBean(RedisCache.class); Map stringDoubleMap = solarEnergyConditionStatistics("cumulativeElectricityConsumptionOnTheDay"); if (stringDoubleMap!=null) { redisCache.setCacheObject("cumulativeElectricityConsumptionOnTheDay", stringDoubleMap); } } public void solarEnergyConditionStatisticsThree(){ RedisCache redisCache = SpringUtils.getBean(RedisCache.class); Map stringDoubleMap = solarEnergyConditionStatistics("generatingPower"); if (stringDoubleMap!=null){ redisCache.setCacheObject("generatingPower", stringDoubleMap); } } public Map solarEnergyConditionStatistics (String propertyId) { IDcDeviceService dcDeviceService = SpringUtils.getBean(IDcDeviceService.class); HashMap props = new HashMap<>(); // 设置查询条件的键为“timestamp$BTW”,表示时间戳在一定范围内 props.put("terms[0].column", "timestamp$BTW"); ArrayList 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 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 allDevicesHourlyAggregates = new TreeMap<>(); List dcDevices = dcDeviceService.devicePileNumberQueryDevice(parameter); for (DcDevice dcDevice : dcDevices) { 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 null; } // 定义时间格式 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> 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 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 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)); }); } } return allDevicesHourlyAggregates; } @ApiOperation("太阳能重点数据") @GetMapping("/properties/latestOne") public AjaxResult getDeviceLatest() throws HttpException, IOException { Map parameters = new HashMap<>(); String[] endStakeMark = {"208", "979"}; String[] startStakeMark = {"054", "378"}; parameters.put("deviceType", "15"); parameters.put("endStakeMark", endStakeMark); parameters.put("startStakeMark", startStakeMark); // parameters.put("deviceState", "1"); // List propertyIds = Arrays.asList("visibility", "wetSlipperyCoefficient", "waterFilmIceSnowValue"); //generatingPower 发电功率 //"cumulativeElectricityConsumptionInTheYear", //当年累计用电量 List propertyIds = Arrays.asList("cumulativeElectricityConsumptionInTheYear", //当年累计用电量 "cumulativeElectricityConsumptionOnTheDay",//当日累计用电量 "theAccumulatedChargeOfTheYear",//当年累计充电量 "dailyAccumulatedCharge"//当日累计充电量 ); List dcDevices = dcDeviceService.devicePileNumberQueryDevice(parameters); Map attributeMap = new HashMap<>(); DecimalFormat decimalFormat = new DecimalFormat("#.##"); decimalFormat.setRoundingMode(RoundingMode.HALF_UP); for (DcDevice dcDevice : dcDevices) { String deviceId = dcDevice.getIotDeviceId(); // for (String propertyId : propertyIds) { try (Response response = new OkHttpClient().newCall(new Request.Builder() .url(iotAddress + UniversalEnum.GETS_THE_LATEST_DATA_ABOUT_THE_SPECIFIED_ATTRIBUTES_OF_A_DEVICE.getValue() + deviceId + UniversalEnum.SLASH.getValue()) .build()).execute()) { String responseBody = response.body().string(); // JsonObject jsonObject = JsonParser.parseString(responseBody).getAsJsonObject(); JSONObject jsonObject = JSONObject.parseObject(responseBody); JSONArray jsonArray = jsonObject.getJSONArray("data"); if (jsonArray!=null)// 确认 "data" 字段是否存在 { // JsonArray data = jsonObject.getAsJsonArray("data"); List cumulativeElectricityConsumptionInTheYearList = jsonArray.stream().filter(item -> ((JSONObject) JSON.toJSON(item)).getString("property").equals("cumulativeElectricityConsumptionInTheYear")).collect(Collectors.toList()); String cumulativeElectricityConsumptionInTheYear = ""; if (cumulativeElectricityConsumptionInTheYearList.size()>0) { cumulativeElectricityConsumptionInTheYear = ((JSONObject) JSON.toJSON(cumulativeElectricityConsumptionInTheYearList.get(0))).getString("formatValue").replaceAll("[^\\d.]", ""); }else { cumulativeElectricityConsumptionInTheYear = "0"; } List cumulativeElectricityConsumptionOnTheDayList = jsonArray.stream().filter(item -> ((JSONObject) JSON.toJSON(item)).getString("property").equals("cumulativeElectricityConsumptionOnTheDay")).collect(Collectors.toList()); String cumulativeElectricityConsumptionOnTheDay = ""; if (cumulativeElectricityConsumptionOnTheDayList.size()>0) { cumulativeElectricityConsumptionOnTheDay = ((JSONObject) JSON.toJSON(cumulativeElectricityConsumptionOnTheDayList.get(0))).getString("formatValue").replaceAll("[^\\d.]", ""); }else { cumulativeElectricityConsumptionOnTheDay = "0"; } List theAccumulatedChargeOfTheYearList = jsonArray.stream().filter(item -> ((JSONObject) JSON.toJSON(item)).getString("property").equals("theAccumulatedChargeOfTheYear")).collect(Collectors.toList()); String theAccumulatedChargeOfTheYear = ""; if (theAccumulatedChargeOfTheYearList.size()>0) { theAccumulatedChargeOfTheYear = ((JSONObject) JSON.toJSON(theAccumulatedChargeOfTheYearList.get(0))).getString("formatValue").replaceAll("[^\\d.]", ""); }else { theAccumulatedChargeOfTheYear = "0"; } List dailyAccumulatedChargeList = jsonArray.stream().filter(item -> ((JSONObject) JSON.toJSON(item)).getString("property").equals("dailyAccumulatedCharge")).collect(Collectors.toList()); String dailyAccumulatedCharge = ""; if (theAccumulatedChargeOfTheYearList.size()>0) { dailyAccumulatedCharge = ((JSONObject) JSON.toJSON(dailyAccumulatedChargeList.get(0))).getString("formatValue").replaceAll("[^\\d.]", ""); }else { dailyAccumulatedCharge = "0"; } // String property = data.get("property").getAsString(); // String formatValueStr = data.get("formatValue").getAsString(); // String valueWithoutUnit = formatValueStr.replaceAll("[^\\d.]", ""); // // double value2 = Double.parseDouble(valueWithoutUnit); // double value = Double.parseDouble(decimalFormat.format(value2)); // // 在合并时重新应用格式化 attributeMap.merge("cumulativeElectricityConsumptionInTheYear", Double.parseDouble(decimalFormat.format(Double.parseDouble(cumulativeElectricityConsumptionInTheYear))), (oldVal, newVal) -> Double.parseDouble(decimalFormat.format(oldVal + newVal))); attributeMap.merge("cumulativeElectricityConsumptionOnTheDay", Double.parseDouble(decimalFormat.format(Double.parseDouble(cumulativeElectricityConsumptionOnTheDay))), (oldVal, newVal) -> Double.parseDouble(decimalFormat.format(oldVal + newVal))); attributeMap.merge("theAccumulatedChargeOfTheYear", Double.parseDouble(decimalFormat.format(Double.parseDouble(theAccumulatedChargeOfTheYear))), (oldVal, newVal) -> Double.parseDouble(decimalFormat.format(oldVal + newVal))); attributeMap.merge("dailyAccumulatedCharge", Double.parseDouble(decimalFormat.format(Double.parseDouble(dailyAccumulatedCharge))), (oldVal, newVal) -> Double.parseDouble(decimalFormat.format(oldVal + newVal))); // attributeMap.merge(property, value, (oldVal, newVal) -> Double.parseDouble(decimalFormat.format(oldVal + newVal))); } } // } } // 计算碳减排 碳减排(kg)=光伏发电量(kWh)*0.7119 double carbonEmissionReduction = attributeMap.getOrDefault("theAccumulatedChargeOfTheYear", 0.0) * 0.7119; double carbonEmissionReductionCoal = Double.parseDouble(decimalFormat.format(carbonEmissionReduction)); attributeMap.put("carbonEmissionReduction", carbonEmissionReductionCoal); //等效植树(棵)=碳减排(kg)/5.023 double equivalentTree = attributeMap.getOrDefault("carbonEmissionReduction", 0.0) / 5.023; double equivalentTreeCoal = Double.parseDouble(decimalFormat.format(equivalentTree)); attributeMap.put("equivalentTree", equivalentTreeCoal); //标准煤(kg)=碳减排(kg)/2.493 double standardCoal = attributeMap.getOrDefault("carbonEmissionReduction", 0.0) / 2.493; double formattedStandardCoal = Double.parseDouble(decimalFormat.format(standardCoal)); attributeMap.put("standardCoal", formattedStandardCoal); /* attributeMap.forEach((key, value) -> System.out.println(String.format("属性:%s,格式值:%s", key, value))); System.out.println(carbonEmissionReduction); */ return AjaxResult.success(attributeMap); } /** * 太阳能设备统计 */ @ApiOperation("太阳能设备统计") @GetMapping("/properties/solarDeviceStatistics") public AjaxResult solarDeviceStatistics() throws HttpException, IOException { Map parameters = new HashMap<>(); String[] endStakeMark = {"208", "979"}; String[] startStakeMark = {"054", "378"}; parameters.put("deviceType", "15"); parameters.put("endStakeMark", endStakeMark); parameters.put("startStakeMark", startStakeMark); int i=0; Map attributeMap = new HashMap<>(); // parameters.put("deviceState", "1"); List dcDevices = dcDeviceService.devicePileNumberQueryDevice(parameters); OkHttp okHttp = new OkHttp(); for (DcDevice dcDevice : dcDevices) { if (dcDevice.getDeviceState().equals("1")){ String iotDeviceId = dcDevice.getIotDeviceId(); Response response // 请求响应 = okHttp .url(iotAddress + UniversalEnum.OBTAIN_THE_LATEST_DEVICE_PROPERTY_DATA.getValue() + iotDeviceId) // 请求地址 .get(); // 请求方法 // 解析JSON字符串 JsonElement jsonElement = JsonParser.parseString(response.body().string()); JsonObject jsonObject = jsonElement.getAsJsonObject(); if (jsonObject.has("data") && jsonObject.get("data").isJsonArray()) { JsonArray dataArray = jsonObject.getAsJsonArray("data"); // 构建Map for (JsonElement element : dataArray) { if (element.isJsonObject()) { JsonObject item = element.getAsJsonObject(); if (item.has("property") && item.has("formatValue")) { //todo 判断属性是否为 dischargeEquipmentStatus if (item.get("property").getAsString().equals("dischargeEquipmentStatus")){//dischargeEquipmentStatus if (item.get("formatValue").getAsString().equals("故障")){ i++; } } } } } } }else{ i++; } attributeMap.put("count",i); attributeMap.put("size",dcDevices.size()); } return AjaxResult.success(attributeMap); } /** * 查询当天设备指定属性列表 * * @param deviceId 设备id * @param propertyId 属性id * @return 属性列表 */ @ApiOperation("查询当天设备指定属性列表") @GetMapping("/properties/history/day/{deviceId}/{propertyId}") public AjaxResult queryDevicePropertiesOneDay(@PathVariable @Parameter(description = "设备ID") String deviceId, @PathVariable @Parameter(description = "属性ID") String propertyId) throws HttpException, IOException { HashMap props = new HashMap<>(); // 设置查询条件的键为“timestamp$BTW”,表示时间戳在一定范围内 props.put("terms[0].column", "timestamp$BTW"); ArrayList dateList = new ArrayList<>(); // 添加当前日期的开始和结束时间到列表,用于设定时间范围 dateList.add(DateUtil.beginOfDay(new Date()).toString()); dateList.add(DateUtil.endOfDay(new Date()).toString()); // 将日期列表以逗号分隔并设置为查询条件的值 props.put("terms[0].value", String.join(UniversalEnum.COMMA.getValue(), dateList)); props.put("paging", false); props.put("sorts[0].order", "asc"); props.put("sorts[0].name", "timestamp"); AjaxResult ajaxResult = queryDeviceProperties(deviceId, propertyId, props); if (!ajaxResult.get("code").equals(UniversalEnum.TWO_HUNDRED.getNumber())) { return ajaxResult; } Object data = JSON.parseObject(queryDeviceProperties(deviceId, propertyId, props).get("data").toString()).get("data"); JSONArray dataArray = JSON.parseArray(data.toString()); List> list = new ArrayList<>(); dataArray.forEach(o -> { Map map = new HashMap<>(); JSONObject jsonObject = JSON.parseObject(o.toString()); JSONObject formatValue = JSON.parseObject(jsonObject.get("formatValue").toString()); map.put(UniversalEnum.ONE.getValue(), formatValue.get(UniversalEnum.ONE.getValue())); map.put(UniversalEnum.THREE.getValue(), formatValue.get(UniversalEnum.THREE.getValue())); map.put("timestamp", formatValue.get("equipmentReportingTime") == null ? UniversalEnum.EMPTY_STRING.getValue() : Long.valueOf(formatValue.get("equipmentReportingTime").toString())); list.add(map); }); List> newList = list.stream() .filter(map -> !map.get("timestamp").equals(UniversalEnum.EMPTY_STRING.getValue())) .collect(Collectors.toList()); Collections.sort(newList, new Comparator>() { @Override public int compare(Map map1, Map map2) { return map1.get("timestamp").toString().compareTo(map2.get("timestamp").toString()); } }); return AjaxResult.success(newList); } /** * 查询设备指定属性列表 * * @param deviceId 设备id * @param propertyId 属性id * @param props 查询条件 * @return 属性列表 */ @ApiOperation("获取设备历史属性列表") @GetMapping("/properties/history/{deviceId}/{propertyId}") public AjaxResult queryDeviceProperties(@PathVariable @Parameter(description = "设备ID") String deviceId, @PathVariable @Parameter(description = "属性ID") String propertyId, @Parameter(hidden = true) HashMap props) throws HttpException, IOException { if (!StringUtils.hasText(deviceId) || !StringUtils.hasText(propertyId)) { return AjaxResult.error(UniversalEnum.DEVICE_NOT_CONNECTED.getValue()); } OkHttp okHttp = new OkHttp(); RequestParams requestParams = new RequestParams(props); Response response // 请求响应 = okHttp .url(iotAddress + UniversalEnum.OBTAIN_THE_DEVICE_HISTORY_ATTRIBUTE_LIST.getValue() + deviceId + UniversalEnum.SLASH.getValue() + propertyId) // 请求地址 .data(requestParams) .get(); // 请求方法 return JSON.parseObject(response.body().string(), AjaxResult.class); } /** * 根据物联设备id获取最新属性数据 * * @param deviceId 物联设备id * @param propertyId 属性id * @return 获取属性数据操作结果 */ @ApiOperation("获取设备指定属性最新数据") @GetMapping("/properties/latest/{deviceId}/{propertyId}") public AjaxResult getDeviceLatestProperty(@PathVariable @Parameter(description = "设备ID") String deviceId, @PathVariable @Parameter(description = "属性ID") String propertyId) throws HttpException, IOException { if (!StringUtils.hasText(deviceId) || !StringUtils.hasText(propertyId)) { return AjaxResult.error(UniversalEnum.DEVICE_NOT_CONNECTED.getValue()); } OkHttp okHttp = new OkHttp(); String requestUrl = iotAddress + UniversalEnum.GETS_THE_LATEST_DATA_ABOUT_THE_SPECIFIED_ATTRIBUTES_OF_A_DEVICE.getValue() + deviceId + UniversalEnum.SLASH.getValue() + propertyId; Response response = okHttp.url(requestUrl).get(); AjaxResult ajaxResult = JSON.parseObject(response.body().string(), AjaxResult.class); if (ajaxResult.get("code").toString().equals("200")){ return ajaxResult; }else { return AjaxResult.success("") ; } } /** * 获取物联设备实时属性值 * * @param deviceId 物联设备id * @param propertyId 属性 * @return 属性实时数据 */ @ApiOperation("获取设备指定属性实时数据") @GetMapping("/properties/realtime/{deviceId}/{propertyId}") public AjaxResult getDeviceRealtimeProperty( @PathVariable String deviceId, @PathVariable String propertyId, @RequestParam HashMap props) throws HttpException, IOException { if (!StringUtils.hasText(deviceId) || !StringUtils.hasText(propertyId)) { return AjaxResult.error(UniversalEnum.DEVICE_NOT_CONNECTED.getValue()); } OkHttp okHttp = new OkHttp(); RequestParams requestParams = new RequestParams(props); Response response // 请求响应 = okHttp .url(iotAddress + UniversalEnum.GET_REAL_TIME_DATA_ABOUT_THE_SPECIFIED_PROPERTIES_OF_THE_DEVICE.getValue() + deviceId + UniversalEnum.SLASH.getValue() + propertyId) // 请求地址 .data(requestParams) .get(); // 请求方法 return JSON.parseObject(response.body().string(), AjaxResult.class); } /** * 批量获取物联设备实时属性 * * @param deviceId 物联设备id * @param props 属性id集 * @return 属性实时数据 */ @ApiOperation("获取设备属性实时数据") @PostMapping("/properties/realtime/{deviceId}") public AjaxResult getDeviceRealtimeProperties( @PathVariable String deviceId, @RequestBody DeviceGetPropertiesOperateRequest props) throws HttpException, IOException { if (!StringUtils.hasText(deviceId)) { return AjaxResult.error(UniversalEnum.DEVICE_NOT_CONNECTED.getValue()); } OkHttp okHttp = new OkHttp(); String string = JSON.toJSONString(props); JSONObject jsonObject = JSON.parseObject(string); RequestParams requestParams = new RequestParams(jsonObject); Response response // 请求响应 = okHttp .url(iotAddress + UniversalEnum.GET_REAL_TIME_DATA_ABOUT_THE_SPECIFIED_PROPERTIES_OF_THE_DEVICE.getValue() + deviceId) // 请求地址 .data(requestParams) .post(); // 请求方法 return JSON.parseObject(response.body().string(), AjaxResult.class); } /** * 发送设置属性指令到设备 * * @param deviceId 物联设备id * @param props 参数 * @return 设备属性操作结果 */ @ApiOperation("设置设备属性值") @PostMapping("/properties/setting/{deviceId}") public AjaxResult setDeviceProperties( @PathVariable String deviceId, @RequestBody HashMap props ) throws HttpException, IOException { if (!StringUtils.hasText(deviceId)) { return AjaxResult.error(UniversalEnum.DEVICE_NOT_CONNECTED.getValue()); } OkHttp okHttp = new OkHttp(); RequestParams requestParams = new RequestParams(props); Response response // 请求响应 = okHttp .url(iotAddress + UniversalEnum.SET_DEVICE_PROPERTY_VALUES.getValue() + deviceId) // 请求地址 .data(requestParams) .post(); // 请求方法 return JSON.parseObject(response.body().string(), AjaxResult.class); } /** * 设备功能调用 * * @param deviceId 物联设备id * @param functionId 功能id * @param props 调用参数 * @return 调用结果 */ @ApiOperation("设备功能调用") @PostMapping("/functions/{deviceId}/{functionId}") @OperationLog(operUrl = "/business/device/functions/{deviceId}/{functionId}") public AjaxResult invokedFunction( @PathVariable String deviceId, @PathVariable String functionId, @RequestBody HashMap props) throws HttpException, IOException { //public AjaxResult invokedFunction(@PathVariable String deviceId,@PathVariable String functionId,@RequestBody HashMap props,int operType) throws HttpException, IOException { todo return getAjaxResult(deviceId, functionId, props); } @ApiOperation("设备功能调用") @PostMapping("/functions2/{deviceId}/{functionId}") public AjaxResult invokedFunction2( @PathVariable String deviceId, @PathVariable String functionId, @RequestBody HashMap props) throws HttpException, IOException { //public AjaxResult invokedFunction(@PathVariable String deviceId,@PathVariable String functionId,@RequestBody HashMap props,int operType) throws HttpException, IOException { todo if (!StringUtils.hasText(deviceId) || !StringUtils.hasText(functionId)) { return AjaxResult.error(UniversalEnum.DEVICE_NOT_CONNECTED.getValue()); } try { OkHttp okHttp = new OkHttp(); RequestParams requestParams = new RequestParams(props); Response response // 请求响应 = okHttp .url(iotAddress + UniversalEnum.DEVICE_FUNCTION_CALL.getValue() + deviceId + UniversalEnum.SLASH.getValue() + functionId) // 请求地址 .data(requestParams) .post(); // 请求方法 if (response.body() != null) { return AjaxResult.success(); } return AjaxResult.success(); } catch (Exception e) { return AjaxResult.success(); } } public AjaxResult getAjaxResult(String deviceId, String functionId, HashMap props) { if (!StringUtils.hasText(deviceId) || !StringUtils.hasText(functionId)) { return AjaxResult.error(UniversalEnum.DEVICE_NOT_CONNECTED.getValue()); } try { OkHttp okHttp = new OkHttp(); RequestParams requestParams = new RequestParams(props); Response response // 请求响应 = okHttp .url(iotAddress + UniversalEnum.DEVICE_FUNCTION_CALL.getValue() + deviceId + UniversalEnum.SLASH.getValue() + functionId) // 请求地址 .data(requestParams) .post(); // 请求方法 if (response.body() != null) { return JSON.parseObject(response.body().string(), AjaxResult.class); } return AjaxResult.error(); } catch (Exception e) { return AjaxResult.error(UniversalEnum.REQUEST_FAILED.getValue()); } } /** * 批量设备功能调用 * * @param props 调用参数列表 * @return 调用结果 */ @ApiOperation("批量设备功能调用") @PostMapping("/batchFunctions") @OperationLog(operUrl = "/business/device/batchFunctions") //public AjaxResult batchInvokedFunction(@RequestBody Map props,int operType) throws HttpException, IOException, InterruptedException { todo public AjaxResult batchInvokedFunction(@RequestBody Map props) throws HttpException, IOException, InterruptedException, ExecutionException { ArrayList devices = (ArrayList) props.get("devices"); ArrayList functions = (ArrayList) props.get("functions"); JSONArray resultArray = new JSONArray(); JSONObject videoCamera = (JSONObject) JSON.toJSON(functions.get(0)); String videoCameraID = videoCamera.getString("functionId"); if (videoCameraID.equals("videoCamera")) { String cmdType = videoCamera.getString("cmdType"); List> futures = new ArrayList<>(); for (Object dev : devices) { JSONObject device = (JSONObject) JSON.toJSON(dev); String iotDeviceId = device.getString("iotDeviceId"); Future future = executorService.submit(() -> { try { JSONObject responseJson = videoController.PTZControl(iotDeviceId, cmdType, "1"); JSONObject result = new JSONObject(); result.put("device", device.getString("id")); result.put("deviceType", device.getInteger("deviceType")); result.put("functionId", cmdType); result.put("result", responseJson); return result; } catch (Exception e) { throw new RuntimeException(e); } }); futures.add(future); } for (Future future : futures) { JSONObject result = future.get(); // 获取结果,可能会抛出异常 resultArray.add(result); } return AjaxResult.success(resultArray); } for (Object dev : devices) { // 将Object转换为JSONObject JSONObject device = (JSONObject) JSON.toJSON(dev); //JSONObject device = (JSONObject) JSON.toJSON(dev.toString()); String iotDeviceId = device.getString("iotDeviceId"); String deviceType = device.getString("deviceType"); boolean continueToExecute = true; //判断是否为需要执行回滚的设备类型 if (Objects.equals(deviceType, UniversalEnum.TEN.getValue())) { //判断iotDeviceId是否为空 为空则直接整理封装错误数据 否则继续执行调用功能 if (iotDeviceId == null) { for (Object function : functions) { JSONObject functionJSONObject = (JSONObject) JSON.toJSON(function); //JSONObject functionJSONObject = (JSONObject) JSON.toJSON(function.toString()) ; String functionId = functionJSONObject.getString("functionId"); List collect = resultArray.stream().filter(item -> Objects.equals(((JSONObject) JSON.toJSON(item)).getString("device"), device.getString("id"))).collect(Collectors.toList()); if (collect.size() == UniversalEnum.ZERO.getNumber()) { JSONObject result = new JSONObject(); result.put("device", device.getString("id")); result.put("deviceType", device.getInteger("deviceType")); result.put("functionId", functionId); result.put("result", AjaxResult.error()); resultArray.add(result); } else { for (int i = UniversalEnum.ZERO.getNumber(); i < resultArray.size(); i++) { JSONObject jsonObject = (JSONObject) JSON.toJSON(resultArray.get(i)); if (!Objects.equals(jsonObject.getString("device"), device.getString("id"))) { JSONObject result = jsonObject.getJSONObject("result"); if (!Objects.equals(result.getString("code"), UniversalEnum.TWO_HUNDRED.getValue())) { break; } else { result.put("code", UniversalEnum.FIVE_HUNDRED.getValue()); jsonObject.put("result", result); resultArray.add(i, jsonObject); } } else { break; } } } } } else { //获取要回滚的数据 JSONObject mdJSONObject = (JSONObject) JSON.toJSON(getDeviceLatestProperty(iotDeviceId, UniversalEnum.MD.getValue()).get("data")); if (mdJSONObject==null) { JSONObject result = new JSONObject(); result.put("device", device.getString("id")); result.put("deviceType", device.getInteger("deviceType")); result.put("functionId", UniversalEnum.MD.getValue()); result.put("result", AjaxResult.error()); resultArray.add(result); break; } String mdValue = mdJSONObject.getString("value"); JSONObject tmJSONObject = (JSONObject) JSON.toJSON(getDeviceLatestProperty(iotDeviceId, UniversalEnum.TM.getValue()).get("data")); if (tmJSONObject==null) { JSONObject result = new JSONObject(); result.put("device", device.getString("id")); result.put("deviceType", device.getInteger("deviceType")); result.put("functionId", UniversalEnum.TM.getValue()); result.put("result", AjaxResult.error()); resultArray.add(result); break; } String tmValue = tmJSONObject.getString("value"); //循环执行功能 for (Object function : functions) { JSONObject functionJSONObject = (JSONObject) JSON.toJSON(function); //JSONObject functionJSONObject = (JSONObject) JSON.toJSON(function.toString()) ; String functionId = functionJSONObject.getString("functionId"); //判断此设备之前的数据是否失败过 没有失败过则正常执行设备功能调用 否则直接整理封装错误数据 if (continueToExecute) { JSONObject jsonObject = functionJSONObject.getJSONObject("params") != null ? functionJSONObject.getJSONObject("params") : new JSONObject(); JSONObject result = getResult(device, iotDeviceId, functionId, jsonObject); resultArray.add(result); AjaxResult ajaxResult = (AjaxResult) result.get("result"); //判断是否成功 如果不成功则将 continueToExecute 设为失败过 并且判断设备类型是否为15 太阳能板 并且返回结束 if (!Objects.equals(String.valueOf(ajaxResult.get("code")), UniversalEnum.TWO_HUNDRED.getValue())) { continueToExecute = false; if (Objects.equals(device.getString("deviceType"), UniversalEnum.FIFTEEN.getValue())) { return AjaxResult.error(UniversalEnum.TWO_HUNDRED.getNumber(), UniversalEnum.FIVE_HUNDRED.getValue()); } } } else { List collect = resultArray.stream().filter(item -> Objects.equals(((JSONObject) JSON.toJSON(item)).getString("device"), device.getString("id"))).collect(Collectors.toList()); //判断返回结果中是否已经有此设备的数据 如果没有 则整理封装一个失败的结果并加入到返回集合中 否则替换数据 if (collect.size() == UniversalEnum.ZERO.getNumber()) { JSONObject result = new JSONObject(); result.put("device", device.getString("id")); result.put("deviceType", device.getInteger("deviceType")); result.put("functionId", functionId); result.put("result", AjaxResult.error()); resultArray.add(result); } else { //循环结果集合 for (int i = UniversalEnum.ZERO.getNumber(); i < resultArray.size(); i++) { JSONObject jsonObject = (JSONObject) JSON.toJSON(resultArray.get(i)); //判断结果集合中是否存在此设备 不存在则结束此循环 存在则替换数据 if (!Objects.equals(jsonObject.getString("device"), device.getString("id"))) { JSONObject result = jsonObject.getJSONObject("result"); //判断此内容是否为失败 为失败则代表是已经整理过的数据 无需处理直接结束此循环 否则替换数据 将code值200替换为500 if (!Objects.equals(result.getString("code"), UniversalEnum.TWO_HUNDRED.getValue())) { break; } else { result.put("code", UniversalEnum.FIVE_HUNDRED.getValue()); jsonObject.put("result", result); resultArray.add(i, jsonObject); } } else { break; } } } //判断此功能ID是否为SETMD 是则执行回滚数据 if (Objects.equals(functionId, UniversalEnum.SETMD.getValue())) { JSONObject jsonObjectMD = new JSONObject(); jsonObjectMD.put(UniversalEnum.SET.getValue(), mdValue); getAjaxResult(iotDeviceId, functionId, jsonObjectMD.toJavaObject(new TypeReference>() { })); } //判断此功能ID是否为SETTM 是则执行回滚数据 if (Objects.equals(functionId, UniversalEnum.SETTM.getValue())) { JSONObject jsonObjectTM = new JSONObject(); jsonObjectTM.put(UniversalEnum.SET.getValue(), tmValue); getAjaxResult(iotDeviceId, functionId, jsonObjectTM.toJavaObject(new TypeReference>() { })); } } } } } else { for (Object function : functions) { JSONObject functionJSONObject = (JSONObject) JSON.toJSON(function); //JSONObject functionJSONObject = (JSONObject) JSON.toJSON(function.toString()) ; String functionId = functionJSONObject.getString("functionId"); if (continueToExecute) { JSONObject jsonObject = functionJSONObject.getJSONObject("params") != null ? functionJSONObject.getJSONObject("params") : new JSONObject(); JSONObject result = getResult(device, iotDeviceId, functionId, jsonObject); resultArray.add(result); AjaxResult ajaxResult = (AjaxResult) result.get("result"); if (!Objects.equals(String.valueOf(ajaxResult.get("code")), UniversalEnum.TWO_HUNDRED.getValue())) { continueToExecute = false; if (Objects.equals(device.getString("deviceType"), UniversalEnum.FIFTEEN.getValue())) { return AjaxResult.error(UniversalEnum.TWO_HUNDRED.getNumber(), UniversalEnum.FIVE_HUNDRED.getValue()); } } } else { JSONObject result = new JSONObject(); result.put("device", device.getString("id")); result.put("deviceType", device.getInteger("deviceType")); result.put("functionId", functionId); result.put("result", AjaxResult.error()); resultArray.add(result); } } } } return AjaxResult.success(resultArray); } private JSONObject getResult(JSONObject device, String iotDeviceId, String functionId, JSONObject jsonObject) throws HttpException, IOException { HashMap params = jsonObject.toJavaObject(new TypeReference>() { }); JSONObject result = new JSONObject(); result.put("device", device.getString("id")); result.put("deviceType", device.getInteger("deviceType")); result.put("functionId", functionId); if (device.getInteger("deviceType").equals(DeviceTypeConstants.ROAD_SECTION_VOICE_BROADCASTING)) { JSONObject value = broadcastController.nearCamListDistance(jsonObject); AjaxResult ajaxResult = new AjaxResult(); value.keySet().forEach(item -> { ajaxResult.put(item, value.getString(item)); }); if (Objects.equals(String.valueOf(ajaxResult.get("retCode")), UniversalEnum.ZERO.getValue())) { ajaxResult.put("code", UniversalEnum.TWO_HUNDRED.getNumber()); } else { ajaxResult.put("code", UniversalEnum.FIVE_HUNDRED.getNumber()); } result.put("result", ajaxResult); } else { result.put("result", getAjaxResult(iotDeviceId, functionId, params)); } return result; } /** * 批量设备功能调用 * * @param props 调用参数列表 * @return 调用结果 */ @ApiOperation("批量激光疲劳设备功能调用") @PostMapping("/batchLaserFatigueInvokedFunction") public AjaxResult batchLaserFatigueInvokedFunction(@RequestBody Map props) throws HttpException, IOException, InterruptedException { String deviceId = (String) props.get("deviceId"); String functionId = (String) props.get("functionId"); ArrayList params = (ArrayList) props.get("params"); JSONArray resultArray = new JSONArray(); for (Object param : params) { resultArray.add(getAjaxResult(deviceId, functionId, (HashMap) param)); } HashMap hashMap = new HashMap<>(); hashMap.put(UniversalEnum.SET.getValue(), UniversalEnum.SEVEN.getValue()); getAjaxResult(deviceId, UniversalEnum.SETMD.getValue(), hashMap); return AjaxResult.success(resultArray); } /** * 查询物联设备指定事件数据 * * @param deviceId 物联设备id * @param eventId 事件id * @param queryParam 查询条件 * @return 查询事件结果 */ @ApiOperation("查询指定事件历史数据列表") @GetMapping("/events/history/{deviceId}/{eventId}") public AjaxResult queryPagerDeviceEvents( @PathVariable @Parameter(description = "设备ID") String deviceId, @PathVariable @Parameter(description = "事件ID") String eventId, @Parameter(hidden = true) HashMap queryParam ) throws HttpException, IOException { if (!StringUtils.hasText(deviceId) || !StringUtils.hasText(eventId)) { return AjaxResult.error(UniversalEnum.DEVICE_NOT_CONNECTED.getValue()); } OkHttp okHttp = new OkHttp(); RequestParams requestParams = new RequestParams(queryParam); Response response // 请求响应 = okHttp .url(iotAddress + UniversalEnum.EXAMPLE_QUERY_THE_HISTORICAL_DATA_LIST_OF_A_SPECIFIED_EVENT.getValue() + deviceId + UniversalEnum.SLASH.getValue() + eventId) // 请求地址 .data(requestParams) .get(); // 请求方法 return JSON.parseObject(response.body().string(), AjaxResult.class); } /** * 查询物联设备指定事件数据 * * @param deviceId 物联设备id * @param type 类型 * @param queryParam 查询条件 * @return 查询事件结果 */ @ApiOperation("查询物联设备事件数据") @GetMapping("/events/history/{deviceId}/type/{type}") public AjaxResult listPagerDeviceEvents( @PathVariable @Parameter(description = "设备ID") String deviceId, @PathVariable @Parameter(description = "事件ID") String type, @RequestParam @Parameter(hidden = true) HashMap queryParam ) throws HttpException, IOException { if (!StringUtils.hasText(deviceId) || !StringUtils.hasText(type)) { return AjaxResult.error(UniversalEnum.DEVICE_NOT_CONNECTED.getValue()); } if (type.equals(UniversalEnum.ALL.getValue())) { OkHttp okHttp = new OkHttp(); RequestParams requestParams = new RequestParams(queryParam); Response response // 请求响应 = okHttp .url(iotAddress + UniversalEnum.QUERY_EVENT_DATA_OF_IOT_DEVICES.getValue() + deviceId) // 请求地址 .data(requestParams) .get(); // 请求方法 return JSON.parseObject(response.body().string(), AjaxResult.class); } else { return queryPagerDeviceEvents(deviceId, type, queryParam); } } /** * 获取物联设备物模型 * * @param id 物联设备id * @return 更新结果 */ @ApiOperation("获取设备物模型") @GetMapping(value = "/metadata/{id}") public AjaxResult getMetadata(@PathVariable String id) throws HttpException, IOException { OkHttp okHttp = new OkHttp(); Response response // 请求响应 = okHttp .url(iotAddress + UniversalEnum.GET_A_PHYSICAL_MODEL_OF_AN_IOT_DEVICE.getValue() + id) // 请求地址 .get(); // 请求方法 return JSON.parseObject(response.body().string(), AjaxResult.class); } /** * @param stakeMark * @param direction * @return com.ruoyi.common.core.domain.AjaxResult * @Description 查询上游10公里内的情报板 * @author liuwenge * @date 2024/4/15 14:22 */ @ApiOperation("查询上游10公里内的情报板") @PostMapping("/selectNearBoard") public AjaxResult selectNearBoard(@ApiParam(value = "桩号", name = "stakeMark", required = true) @RequestParam("stakeMark") String stakeMark, @ApiParam(value = "方向", name = "direction", required = true) @RequestParam("direction") String direction) { return dcDeviceService.selectNearBoard(stakeMark, direction); } @OperationLog(operUrl = "/business/device/batchFunctions") public AjaxResult batchInvokedFunction(Object object) throws HttpException, IOException, InterruptedException, ExecutionException { //public AjaxResult batchInvokedFunction(Object object,int operType) throws HttpException, IOException, InterruptedException { todo Map map = new ObjectMapper().convertValue(object, Map.class); return batchInvokedFunction(map); } /** * 分页查询设备名称列表 * * @param dcDevice 请求参数 * @return 分页查询结果 */ @GetMapping("/selectDeviceNameList") public TableDataInfo selectDeviceNameList(DcDevice dcDevice) { startPage(); return getDataTable(dcDeviceService.selectDeviceNameList(dcDevice)); } @GetMapping("/deviceParameter") public AjaxResult selectDeviceParameterProperties(DcDevice dcDevice) { return AjaxResult.success(dcDeviceService.selectDeviceParameterProperties(dcDevice)); } /** * 查询设备指定属性属性列表 * param参数 * deviceId 设备id * propertyId 属性id * propertyName 属性名称 * deviceType 设备类型 * dateTime 时间 * * @return 属性列表 */ @PostMapping("/properties/deviceNameData") public AjaxResult queryDevice(@RequestBody HashMap map) throws HttpException, IOException { if (map == null || !map.containsKey("deviceId") || !map.containsKey("deviceType") || !map.containsKey("propertyName") || !map.containsKey("propertyId") || !map.containsKey("dateTime")) { return AjaxResult.error(UniversalEnum.PARAMETER_ERROR.getValue()); } String deviceType = map.get("deviceType").toString();//设备类型 String deviceId = map.get("deviceId").toString();//设备id String propertyId = map.get("propertyId").toString();//属性id String propertyName = map.get("propertyName").toString();//属性名称 HashMap props = new HashMap<>(); // 设置查询条件的键为“timestamp$BTW”,表示时间戳在一定范围内 props.put("terms[0].column", "timestamp$BTW"); ArrayList dateList = new ArrayList<>(); // 添加当前日期的开始和结束时间到列表,用于设定时间范围 SimpleDateFormat dateFormat = new SimpleDateFormat(UniversalEnum.TIME_FORMAT_YEARS_MONTH_DAY.getValue()); try { Date date = dateFormat.parse((String) map.get("dateTime")); dateList.add(DateUtil.beginOfDay(date).toString()); dateList.add(DateUtil.endOfDay(date).toString()); } catch (ParseException e) { e.printStackTrace(); } // 将日期列表以逗号分隔并设置为查询条件的值 props.put("terms[0].value", String.join(UniversalEnum.COMMA.getValue(), dateList)); props.put("paging", false); props.put("sorts[0].order", "asc"); props.put("sorts[0].name", "timestamp"); AjaxResult ajaxResult = queryDeviceProperties(deviceId, propertyId, props); String code = ajaxResult.get("code").toString(); if (UniversalEnum.FIVE_HUNDRED.getValue().equals(code)) { return ajaxResult; } if (UniversalEnum.THIRTEEN.getValue().equals(deviceType) || UniversalEnum.SIXTEEN.getValue().equals(deviceType)) { //判断是否为设备箱/远端机 JSONObject data = (JSONObject) ajaxResult.get("data"); JSONArray dataVale = (JSONArray) data.get("data"); List jsonObjectList = dataVale.toJavaList(JSONObject.class); // 定义一个时间格式转换的工具 SimpleDateFormat sdf = new SimpleDateFormat(UniversalEnum.TIME_FORMAT_ALL.getValue(), Locale.getDefault()); // 使用Stream API提取每个JSONObject中的timestamp和propertyName值 List> results = jsonObjectList.stream() .map(jsonObject -> { long timestamp = jsonObject.getLongValue("timestamp"); // 假设timestamp是long类型 Date date = new Date(timestamp); // 将时间戳转换为Date对象 String formattedTime = sdf.format(date); // 将Date对象格式化为字符串 JSONObject formatValue = jsonObject.getJSONObject("formatValue"); // 获取嵌套的JSONObject String result = formatValue.getString(propertyName); // 从嵌套的JSONObject中获取电压值 Map hashMap = new HashMap<>(); hashMap.put("timestamp", formattedTime); // 使用"timestamp"作为键来存储格式化后的时间 hashMap.put("result", result); // 使用"voltage"作为键来存储电压值 return hashMap; }) .collect(Collectors.toList()); results.sort(Comparator.comparing(hashMap -> hashMap.get("timestamp"))); return AjaxResult.success(results); } if (UniversalEnum.THREE.getValue().equals(deviceType) || UniversalEnum.SEVENTEEN.getValue().equals(deviceType) || UniversalEnum.FIFTEEN.getValue().equals(deviceType)) { //气象预警/ups设备/太阳能板 JSONObject data = (JSONObject) ajaxResult.get("data"); JSONArray dataValue = (JSONArray) data.get("data"); List jsonObjectList = dataValue.toJavaList(JSONObject.class); // 定义一个时间格式转换的工具 SimpleDateFormat sdf = new SimpleDateFormat(UniversalEnum.TIME_FORMAT_ALL.getValue(), Locale.getDefault()); List> results = jsonObjectList.stream() .map(jsonObject -> { long timestamp = jsonObject.getLongValue("timestamp"); // 假设timestamp是long类型 Date date = new Date(timestamp); // 将时间戳转换为Date对象 String formattedTime = sdf.format(date); // 将Date对象格式化为字符串 String result = jsonObject.getString(propertyName); HashMap hashMap = new HashMap<>(); hashMap.put("timestamp", formattedTime); // 使用时间戳作为键可能不是最佳实践,但这里保持与原始逻辑一致 hashMap.put("result", result); return hashMap; }) .collect(Collectors.toList()); results.sort(Comparator.comparing(hashMap -> hashMap.get("timestamp"))); return AjaxResult.success(results); } return null; } /** * 设备箱-设备操作口令校验 */ @GetMapping("/kouling/{secretKey}") public AjaxResult verifySecretKey(@PathVariable String secretKey) { String key = configService.selectConfigByKey(UniversalEnum.SBX_FUN_KL.getValue());//密钥 return AjaxResult.success(key.equals(secretKey)); } //设备分析 @PostMapping("/properties/deviceAnalysis") public AjaxResult deviceAnalysis(@RequestBody HashMap map) throws IOException, HttpException { if (map == null || !map.containsKey("deviceId") || !map.containsKey("deviceType") || !map.containsKey("dateTime")) { return AjaxResult.error(UniversalEnum.PARAMETER_ERROR.getValue()); } String type = map.get("deviceType").toString();//设备类型 String deviceId = map.get("deviceId").toString();//设备id DcDevice dcDevice = new DcDevice(); dcDevice.setDeviceType(type); HashMap props = new HashMap<>(); // 设置查询条件的键为“timestamp$BTW”,表示时间戳在一定范围内 props.put("terms[0].column", "timestamp$BTW"); ArrayList dateList = new ArrayList<>(); // 添加当前日期的开始和结束时间到列表,用于设定时间范围 SimpleDateFormat dateFormat = new SimpleDateFormat(UniversalEnum.TIME_FORMAT_YEARS_MONTH_DAY.getValue()); try { Date date = dateFormat.parse((String) map.get("dateTime")); dateList.add(DateUtil.beginOfDay(date).toString()); dateList.add(DateUtil.endOfDay(date).toString()); } catch (ParseException e) { e.printStackTrace(); } // 将日期列表以逗号分隔并设置为查询条件的值 props.put("terms[0].value", String.join(UniversalEnum.COMMA.getValue(), dateList)); props.put("paging", false); props.put("sorts[0].order", "asc"); props.put("sorts[0].name", "timestamp"); List> mapList = dcDeviceService.selectDeviceParameterProperties(dcDevice);//属性的参数信息 List resultsMapValue = new ArrayList<>(); try { for (HashMap hashMap : mapList) { HashMap resultsMap = new HashMap<>(); String name = hashMap.get("name").toString();//属性名称 String propertyId = hashMap.get("propertyId").toString();//属性id String propertyName = hashMap.get("propertyName").toString();//属性取值 AjaxResult ajaxResult = queryDeviceProperties(deviceId, propertyId, props);//取出属性全部信息 String code = ajaxResult.get("code").toString(); if ("500".equals(code)) { return AjaxResult.success(ajaxResult.get("msg")); } if (UniversalEnum.THIRTEEN.getValue().equals(type) || UniversalEnum.SIXTEEN.getValue().equals(type)) { //判断是否为设备箱/远端机 JSONObject data = (JSONObject) ajaxResult.get("data"); JSONArray dataVale = (JSONArray) data.get("data"); List jsonObjectList = dataVale.toJavaList(JSONObject.class); // 定义一个时间格式转换的工具 SimpleDateFormat sdf = new SimpleDateFormat(UniversalEnum.TIME_FORMAT_ALL.getValue(), Locale.getDefault()); // 使用Stream API提取每个JSONObject中的timestamp和propertyName值 List> results = jsonObjectList.stream() .map(jsonObject -> { long timestamp = jsonObject.getLongValue("timestamp"); // 假设timestamp是long类型 Date date = new Date(timestamp); // 将时间戳转换为Date对象 String formattedTime = sdf.format(date); // 将Date对象格式化为字符串 JSONObject formatValue = jsonObject.getJSONObject("formatValue"); // 获取嵌套的JSONObject String result = formatValue.getString(propertyName); // 从嵌套的JSONObject中获取电压值 Map hashMaps = new HashMap<>(); hashMaps.put("timestamp", formattedTime); // 使用"timestamp"作为键来存储格式化后的时间 hashMaps.put("result", result); // 使用"voltage"作为键来存储电压值 return hashMaps; }).collect(Collectors.toList()); results.sort(Comparator.comparing(hashMaps -> hashMaps.get("timestamp"))); resultsMap.put("name", name); resultsMap.put("results", results); } if (UniversalEnum.THREE.getValue().equals(type) || UniversalEnum.SEVENTEEN.getValue().equals(type) || UniversalEnum.FIFTEEN.getValue().equals(type)||UniversalEnum.SEVENTEEN.getValue().equals(type)) { //气象预警/ups设备/太阳能板/一体机柜 JSONObject data = (JSONObject) ajaxResult.get("data"); JSONArray dataValue = (JSONArray) data.get("data"); List jsonObjectList = dataValue.toJavaList(JSONObject.class); // 定义一个时间格式转换的工具 SimpleDateFormat sdf = new SimpleDateFormat(UniversalEnum.TIME_FORMAT_ALL.getValue(), Locale.getDefault()); List> results = jsonObjectList.stream() .map(jsonObject -> { long timestamp = jsonObject.getLongValue("timestamp"); // 假设timestamp是long类型 Date date = new Date(timestamp); // 将时间戳转换为Date对象 String formattedTime = sdf.format(date); // 将Date对象格式化为字符串 String result = jsonObject.getString(propertyName); HashMap hashMaps = new HashMap<>(); hashMaps.put("timestamp", formattedTime); // 使用时间戳作为键可能不是最佳实践,但这里保持与原始逻辑一致 hashMaps.put("result", result); return hashMaps; }).collect(Collectors.toList()); results.sort(Comparator.comparing(hashMaps -> hashMaps.get("timestamp"))); resultsMap.put("name", name); resultsMap.put("results", results); } resultsMapValue.add(resultsMap); } }catch (Exception e){ e.printStackTrace(); } return AjaxResult.success(resultsMapValue); } ///*** // * 合流区预警设备设备电量不足警告 // */ //@Scheduled(cron = "0 0/1 * * * ?") //public void ConfluenceAreaEarlyWarningDeviceBatteryLowWarning() throws HttpException, IOException { // DcDevice dcDevice = new DcDevice(); // dcDevice.setDeviceType("8"); // List devices = dcDeviceService.listDevice(dcDevice); // for (DcDevice device : devices) { // String iotDeviceId = device.getIotDeviceId(); // if (iotDeviceId != null && !iotDeviceId.equals("")) { // AjaxResult deviceLatestProperty = queryDeviceProperties(iotDeviceId, "batteryCapacity",new HashMap<>()); // System.out.println(deviceLatestProperty.get("code")); // System.out.println(deviceLatestProperty.get("msg")); // } // } //} /*** * 太阳能板设备定时任务 */ //@Scheduled(cron = "0 0/5 * * * ?") public AjaxResult ConfluenceAreaEarlyWarningDeviceBatteryLowWarning() throws HttpException, IOException, InterruptedException { DcDevice dcDevice = new DcDevice(); dcDevice.setDeviceType(UniversalEnum.FIFTEEN.getValue()); dcDevice.setDeviceState(UniversalEnum.ONE.getValue()); IDcDeviceService dcDeviceService = SpringUtils.getBean(IDcDeviceService.class); List dcDeviceList = dcDeviceService.listDevice(dcDevice); ArrayList devices = new ArrayList<>(); for (DcDevice device : dcDeviceList) { String iotDeviceId = device.getIotDeviceId(); if (iotDeviceId != null && !iotDeviceId.equals(UniversalEnum.EMPTY_STRING.getValue())) { JSONObject jsonObject = new JSONObject(); jsonObject.put("id", device.getId()); jsonObject.put("iotDeviceId", device.getIotDeviceId()); jsonObject.put("deviceType", device.getDeviceType()); devices.add(jsonObject); } } ArrayList functions = new ArrayList(); for (int i = UniversalEnum.ZERO.getNumber(); i < UniversalEnum.SIX.getNumber(); i++) { JSONObject function = new JSONObject(); function.put("functionId", UniversalEnum.A.getValue() + (i + UniversalEnum.ONE.getNumber())); function.put("params", new JSONObject()); functions.add(function); } /* JSONObject function = new JSONObject(); function.put("functionId", UniversalEnum.A_ONE.getValue()); function.put("params", new JSONObject()); functions.add(function);*/ JSONObject jsonObject = new JSONObject(); jsonObject.put("devices", devices); jsonObject.put("functions", functions); return batchInvokedFunction2(jsonObject); } //一体机柜定时调用,采数据 //@PostMapping("/integratedCabinetAir") @Scheduled(cron = "0 * * * * ?") public AjaxResult integratedCabinetAirConditioner() throws InterruptedException, IOException, HttpException { DcDevice dcDevice = new DcDevice(); dcDevice.setDeviceType(UniversalEnum.SEVENTEEN.getValue()); dcDevice.setDeviceState(UniversalEnum.ONE.getValue()); IDcDeviceService dcDeviceService = SpringUtils.getBean(IDcDeviceService.class); List dcDeviceList = dcDeviceService.listDevice(dcDevice); ArrayList devices = new ArrayList<>(); for (DcDevice device : dcDeviceList) { String iotDeviceId = device.getIotDeviceId(); if (iotDeviceId != null && !iotDeviceId.equals(UniversalEnum.EMPTY_STRING.getValue())) { JSONObject jsonObject = new JSONObject(); jsonObject.put("id", device.getId()); jsonObject.put("iotDeviceId", device.getIotDeviceId()); jsonObject.put("deviceType", device.getDeviceType()); devices.add(jsonObject); } } ArrayList functions = new ArrayList(); for (int i = UniversalEnum.ONE.getNumber(); i <= UniversalEnum.FOUR.getNumber(); i++) { JSONObject function = new JSONObject(); if (i == 2 || i==1 ||i== 3) { continue; } String valueOf = String.valueOf(i); function.put("functionId", "0" + valueOf); function.put("params", new JSONObject()); functions.add(function); } JSONObject jsonObject = new JSONObject(); jsonObject.put("devices", devices); jsonObject.put("functions", functions); return batchInvokedFunction2(jsonObject); } //一体机柜调用机箱门数据 @PostMapping("/integratedCabinetAir") @Scheduled(cron = "20 * * * * ?") @Transactional() public AjaxResult chassisDoor() throws IOException, HttpException { DcDevice dcDevice = new DcDevice(); dcDevice.setDeviceType(UniversalEnum.SEVENTEEN.getValue()); dcDevice.setDeviceState(UniversalEnum.ONE.getValue()); IDcDeviceService dcDeviceService = SpringUtils.getBean(IDcDeviceService.class); List dcDeviceList = dcDeviceService.listDevice(dcDevice);//取出全部在线的机柜 for (DcDevice device : dcDeviceList) { AjaxResult result = getDeviceLatestProperty(device.getIotDeviceId(), "ChassisDoorInspection"); if (!result.get("code").toString().equals("200")){ continue; } JSONObject data = (JSONObject) result.get("data");//属性全部值 if (data==null){ continue; } String value = data.get("value").toString();//属性值 if ("1".equals(value)){//机箱门状态为开 String cacheMapValue = redisCache.getCacheMapValue(DOORSTATUS, device.getIotDeviceId());//查询缓存 if ((cacheMapValue==null||"".equals(cacheMapValue))||"0".equals(cacheMapValue)){//缓存中不存在或者存在但值不同,加入缓存加入记录 DcDoor dcDoor = new DcDoor(); dcDoor.setCreateTime(DateUtils.getNowDate()); dcDoor.setDeviceName(device.getDeviceName()); dcDoor.setDeviceType(device.getDeviceType()); dcDoor.setDirection(device.getDirection()); dcDoor.setStakeMark(device.getStakeMark()); dcDoor.setOperate("箱门状态:开"); dcDoor.setIotDeviceId(device.getIotDeviceId()); dcDeviceService.insertDoorMonitor(dcDoor); redisCache.setCacheMapValue(DOORSTATUS,device.getIotDeviceId(),value); } if ("1".equals(cacheMapValue)){//机箱最新获取的状态与缓存的状态相同,不做处理 continue; } } if ("0".equals(value)){//机箱门状态为关 String cacheMapValue = redisCache.getCacheMapValue(DOORSTATUS, device.getIotDeviceId());//查询缓存 if ("1".equals(cacheMapValue)){//机箱门状态为关,缓存关开,删除缓存,加入记录 DcDoor dcDoor = new DcDoor(); dcDoor.setCreateTime(DateUtils.getNowDate()); dcDoor.setDeviceName(device.getDeviceName()); dcDoor.setDeviceType(device.getDeviceType()); dcDoor.setDirection(device.getDirection()); dcDoor.setStakeMark(device.getStakeMark()); dcDoor.setOperate("箱门状态:关"); dcDoor.setIotDeviceId(device.getIotDeviceId()); dcDeviceService.insertDoorMonitor(dcDoor); redisCache.delCacheMapValue(DOORSTATUS,device.getIotDeviceId()); }else { continue; } } } for (DcDevice device : dcDeviceList){ AjaxResult result = getDeviceLatestProperty(device.getIotDeviceId(), "SmokeAlarm"); if (!result.get("code").toString().equals("200")){ continue; } JSONObject data = (JSONObject) result.get("data");//属性全部值 if (data==null){ continue; } String value = data.get("value").toString();//属性值 if (Integer.parseInt(value)>=400){ String cacheMapValue = redisCache.getCacheMapValue(SOMKEVALUE, device.getIotDeviceId());//查询缓存 if (cacheMapValue==null||"".equals(cacheMapValue)){//缓存不存在,加入数据加入缓存 DcSmokeRecord dcSmokeRecord = new DcSmokeRecord(); dcSmokeRecord.setDeviceName(device.getDeviceName()); dcSmokeRecord.setDeviceType(device.getDeviceType()); dcSmokeRecord.setDirection(device.getDirection()); dcSmokeRecord.setStakeMark(device.getStakeMark()); dcSmokeRecord.setSmokeValue(value); dcSmokeRecord.setCreateTime(DateUtils.getNowDate()); dcSmokeRecord.setIotDeviceId(device.getIotDeviceId()); dcSmokeRecord.setPushTime(DateUtils.getNowDate()); dcDeviceService.insertSmokeRecord(dcSmokeRecord); redisCache.setCacheMapValue(SOMKEVALUE,device.getIotDeviceId(),value); HashMap hashMap = new HashMap<>(); hashMap.put("content",device.getDeviceName()+"烟感异常,烟感值为"+value); hashMap.put("time",DateUtils.getNowDate()); WebSocketService.broadcast("deviceAlarm",hashMap); }else { if (Integer.parseInt(value)==Integer.parseInt(cacheMapValue)){ //最新值与之前的缓存值一样,不予处理 continue; } //如果缓存存在,并且与当前值不一样,而且当前值大于400,烟感值缓存替换、数据替换 redisCache.delCacheMapValue(SOMKEVALUE,device.getIotDeviceId()); redisCache.setCacheMapValue(SOMKEVALUE,device.getIotDeviceId(),value); DcSmokeRecord dcSmokeRecord = new DcSmokeRecord(); dcSmokeRecord.setIotDeviceId(device.getIotDeviceId()); dcSmokeRecord.setSmokeValue(value); dcSmokeRecord.setUpdateTime(DateUtils.getNowDate()); DcSmokeRecord dcSmokeRecordValue = dcDeviceService.selectSmokeRecordIotId(device.getIotDeviceId()); if (dcSmokeRecordValue!=null&&dcSmokeRecordValue.getPushTime()!=null){ String pushTime = dcSmokeRecordValue.getPushTime().toString(); String nowDate = DateUtils.getNowDate().toString(); // 解析 pushTime(根据实际格式调整) DateTimeFormatter pushTimeFormatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH); // 假设 pushTime 是此格式 LocalDateTime dateTime1 = LocalDateTime.parse(pushTime, pushTimeFormatter); // 解析 nowDate(修复格式) DateTimeFormatter nowDateFormatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH); LocalDateTime dateTime2 = LocalDateTime.parse(nowDate, nowDateFormatter); long diffInMillis = ChronoUnit.MINUTES.between(dateTime1, dateTime2); if (diffInMillis> 30) { // 时间差大于30分钟 dcSmokeRecord.setPushTime(DateUtils.getObtainDateAfter(1)); HashMap hashMap = new HashMap<>(); hashMap.put("content",device.getDeviceName()+"烟感异常,烟感值为"+value); hashMap.put("time",DateUtils.getNowDate()); WebSocketService.broadcast("deviceAlarm",hashMap); } dcDeviceService.updateSmokeValue(dcSmokeRecord);//修改数据值 } } }else { String cacheMapValue = redisCache.getCacheMapValue(SOMKEVALUE, device.getIotDeviceId());//查询缓存 if (cacheMapValue==null||"".equals(cacheMapValue)){ continue; } redisCache.delCacheMapValue(SOMKEVALUE,device.getIotDeviceId()); } } return AjaxResult.success(); } //设备箱机箱门状态采集 //@PostMapping("/integratedCabinetAir") @Scheduled(fixedRate = 30000) @Transactional() public AjaxResult equipmentBoxDoor() throws IOException, HttpException { DcDevice dcDevice = new DcDevice(); dcDevice.setDeviceType(UniversalEnum.THIRTEEN.getValue()); dcDevice.setDeviceState(UniversalEnum.ONE.getValue()); IDcDeviceService dcDeviceService = SpringUtils.getBean(IDcDeviceService.class); List dcDeviceList = dcDeviceService.listDevice(dcDevice);//取出全部在线的设备箱 for (DcDevice device : dcDeviceList) { AjaxResult result = getDeviceLatestProperty(device.getIotDeviceId(), "1ac"); if (!result.get("code").toString().equals("200")) { continue; } JSONObject data = (JSONObject) result.get("data");//属性全部值 if (data==null){ continue; } JSONObject value = (JSONObject) data.get("value"); if (value==null){ continue; } String doorStatus = value.get("door_status").toString();//属性值 if ("1".equals(doorStatus)){//机箱门状态为开 String cacheMapValue = redisCache.getCacheMapValue(DOORSTATUS, device.getIotDeviceId());//查询缓存 if ((cacheMapValue==null||"".equals(cacheMapValue))||"0".equals(cacheMapValue)){//缓存中不存在或者存在但值不同,加入缓存加入记录 DcDoor dcDoor = new DcDoor(); dcDoor.setCreateTime(DateUtils.getNowDate()); dcDoor.setDeviceName(device.getDeviceName()); dcDoor.setDeviceType(device.getDeviceType()); dcDoor.setDirection(device.getDirection()); dcDoor.setStakeMark(device.getStakeMark()); dcDoor.setOperate("箱门状态:开"); dcDoor.setIotDeviceId(device.getIotDeviceId()); dcDeviceService.insertDoorMonitor(dcDoor); redisCache.setCacheMapValue(DOORSTATUS,device.getIotDeviceId(),doorStatus); } if ("1".equals(cacheMapValue)){//机箱最新获取的状态与缓存的状态相同,不做处理 continue; } } if ("0".equals(doorStatus)){//机箱门状态为关 String cacheMapValue = redisCache.getCacheMapValue(DOORSTATUS, device.getIotDeviceId());//查询缓存 if ("1".equals(cacheMapValue)){//机箱门状态为关,缓存关开,删除缓存,加入记录 DcDoor dcDoor = new DcDoor(); dcDoor.setCreateTime(DateUtils.getNowDate()); dcDoor.setDeviceName(device.getDeviceName()); dcDoor.setDeviceType(device.getDeviceType()); dcDoor.setDirection(device.getDirection()); dcDoor.setStakeMark(device.getStakeMark()); dcDoor.setOperate("箱门状态:关"); dcDoor.setIotDeviceId(device.getIotDeviceId()); dcDeviceService.insertDoorMonitor(dcDoor); redisCache.delCacheMapValue(DOORSTATUS,device.getIotDeviceId()); }else { continue; } } } return AjaxResult.success(); } //查询机柜烟感记录 @GetMapping("/dcSmokeRecordList") public TableDataInfo selectSmokeList( DcSmokeRecord dcSmokeRecord){ startPage(); Map redisCacheCacheMap = redisCache.getCacheMap(SOMKEVALUE); if (redisCacheCacheMap==null){ return getDataTable(Collections.emptyList()); } Set strings = redisCacheCacheMap.keySet(); List list = dcDeviceService.selectSmokeList(strings); return getDataTable(list); } //查询机柜门锁记录 @GetMapping("/dcDoorList") public TableDataInfo selectEnergyCircuit( DcDoor dcDoor){ startPage(); List list = dcDeviceService.selectDcDoorList(dcDoor); return getDataTable(list); } //查询开门的设备列表 @GetMapping("/dcDoorOpen") public TableDataInfo dcDoorOpen(){ startPage(); Map redisCacheCacheMap = redisCache.getCacheMap(DOORSTATUS); if (redisCacheCacheMap==null||redisCacheCacheMap.size()==0){ return getDataTable(Collections.emptyList()); } Set strings = redisCacheCacheMap.keySet(); List list = dcDeviceService.selectDcDoorOpen(strings); return getDataTable(list); } //一体机柜空调定时调用,采数据 //@PostMapping("/integratedCabinetAir2") @Scheduled(cron = "40 0,30 * * * *") public AjaxResult airConditioning() throws InterruptedException, IOException, HttpException { DcDevice dcDevice = new DcDevice(); dcDevice.setDeviceType(UniversalEnum.EIGHTEEN.getValue()); dcDevice.setDeviceState(UniversalEnum.ONE.getValue()); IDcDeviceService dcDeviceService = SpringUtils.getBean(IDcDeviceService.class); List dcDeviceList = dcDeviceService.listDevice(dcDevice); ArrayList devices = new ArrayList<>(); for (DcDevice device : dcDeviceList) { String iotDeviceId = device.getIotDeviceId(); if (iotDeviceId != null && !iotDeviceId.equals(UniversalEnum.EMPTY_STRING.getValue())) { JSONObject jsonObject = new JSONObject(); jsonObject.put("id", device.getId()); jsonObject.put("iotDeviceId", device.getIotDeviceId()); jsonObject.put("deviceType", device.getDeviceType()); devices.add(jsonObject); } } ArrayList functions = new ArrayList(); for (int i = UniversalEnum.ONE.getNumber(); i <= UniversalEnum.THREE.getNumber(); i++) { JSONObject function = new JSONObject(); if (i == 2) { continue; } String valueOf = String.valueOf(i); function.put("functionId", "0" + valueOf); function.put("params", new JSONObject()); functions.add(function); } JSONObject jsonObject = new JSONObject(); jsonObject.put("devices", devices); jsonObject.put("functions", functions); return batchInvokedFunction2(jsonObject); } public AjaxResult batchInvokedFunction2(@RequestBody Map props) throws HttpException, IOException, InterruptedException { ArrayList devices = (ArrayList) props.get("devices"); ArrayList functions = (ArrayList) props.get("functions"); JSONArray resultArray = new JSONArray(); for (Object dev : devices) { JSONObject device = (JSONObject) JSON.toJSON(dev); String iotDeviceId = device.getString("iotDeviceId"); for (Object function : functions) { JSONObject functionJSONObject = (JSONObject) JSON.toJSON(function); String functionId = functionJSONObject.getString("functionId"); JSONObject jsonObject = functionJSONObject.getJSONObject("params") != null ? functionJSONObject.getJSONObject("params") : new JSONObject(); JSONObject result = getResult(device, iotDeviceId, functionId, jsonObject); resultArray.add(result); } } return AjaxResult.success(resultArray); } @PostMapping("/snmpUpsAlarm") public AjaxResult snmpUpsAlarm() throws IOException, HttpException { ArrayList objects = new ArrayList<>(); HashMap hashMap = new HashMap<>(); hashMap.put("10.0.81.248-SNMP","大学城UPS-01+10.0.81.248"); hashMap.put("SNMP","大学城UPS-02+10.0.81.250"); hashMap.put("10.0.111.119-SNMP","分中心1号UPS+10.0.111.119"); hashMap.put("10.0.111.118-SNMP","分中心2号UPS+10.0.111.119"); hashMap.put("10.0.11.248-SNMP","长清UPS-01+10.0.11.248");hashMap.put("10.0.11.250-SNMP","长清UPS-02+10.0.11.250"); hashMap.put("10.0.21.248-SNMP","孝里USP-01+10.0.21.248"); hashMap.put("10.0.21.250-SNMP","孝里UPS-02+10.0.21.250"); hashMap.put("10.0.91.248-SNMP","安城UPS-01+10.0.91.248"); hashMap.put("10.0.91.250-SNMP","安城UPS-02+10.0.91.250"); hashMap.put("10.0.31.248-SNMP","平阴USP-01+10.0.31.248"); hashMap.put("10.0.31.250-SNMP","平阴UPS-02+10.0.31.250"); hashMap.put("10.0.41.248-SNMP","平阴南UPS-01+10.0.41.248"); hashMap.put("10.0.41.250-SNMP","平阴南UPS-02+10.0.41.250"); hashMap.put("10.0.51.248-SNMP","东平UPS-01+10.0.51.248");hashMap.put("10.0.51.250-SNMP","东平UPS-02+10.0.51.250"); hashMap.put("10.0.101.248-SNMP","韩岗UPS-01+10.0.101.248"); hashMap.put("10.0.101.250-SNMP","韩岗UPS-02+10.0.101.250"); hashMap.put("10.0.61.248-SNMP","梁山UPS-01+10.0.61.248"); hashMap.put("10.0.61.250-SNMP","梁山UPS-02+10.0.61.250"); hashMap.put("10.0.71.248-SNMP","嘉祥西UPS-01+10.0.71.248"); hashMap.put("10.0.71.250-SNMP","嘉祥西UPS-02+10.0.71.250"); objects.add(hashMap); for (HashMap map:objects) { for (Map.Entry entry : map.entrySet()) { String deviceKey = entry.getKey(); String deviceNameWithIp = entry.getValue(); AjaxResult overloadValue = getDeviceLatestProperty(deviceKey, "1.3.6.1.4.1.935.1.1.1.8.7.4.0");//过载 AjaxResult inverterOutputValue = getDeviceLatestProperty(deviceKey, "1.3.6.1.4.1.935.1.1.1.8.7.5.0");//逆变输出 AjaxResult overTemperatureValue = getDeviceLatestProperty(deviceKey, "1.3.6.1.4.1.935.1.1.1.8.7.6.0");//过温 AjaxResult shortCircuitValue = getDeviceLatestProperty(deviceKey, "1.3.6.1.4.1.935.1.1.1.8.7.7.0");//短路 if (!overloadValue.get("code").toString().equals("200") || !inverterOutputValue.get("code").toString().equals("200") || !overTemperatureValue.get("code").toString().equals("200") || !shortCircuitValue.get("code").toString().equals("200")) { continue; } JSONObject overloadValueData = (JSONObject) overloadValue.get("data");//过载属性全部值 JSONObject inverterOutputValueData = (JSONObject) inverterOutputValue.get("data");//逆变输出属性全部值 JSONObject overTemperatureValueData = (JSONObject) overTemperatureValue.get("data");//过温属性全部值 JSONObject shortCircuitValueData = (JSONObject) shortCircuitValue.get("data");//短路属性全部值 if (overloadValueData == null || inverterOutputValueData == null || overTemperatureValueData == null || shortCircuitValueData == null) { continue; } String overload = overloadValueData.get("value").toString();//过载 String inverterOutput = inverterOutputValueData.get("value").toString();//逆变输出 String overTemperature = overTemperatureValueData.get("value").toString();//过温 String shortCircuit = shortCircuitValueData.get("value").toString();//短路 if (overload == null || inverterOutput == null || overTemperature == null || shortCircuit == null) { continue; } //全部状态正常,跳过 if ("16".equals(overload) && "16".equals(inverterOutput) && "16".equals(overTemperature) && "16".equals(shortCircuit)) { String cacheMapValue = redisCache.getCacheMapValue(ALARMVALUE, deviceKey);//查询缓存 if (cacheMapValue != null && !"".equals(cacheMapValue)) {//状态正常但是缓存有存在值,删除缓存跳过数据 redisCache.delCacheMapValue(ALARMVALUE,deviceKey); } continue; } StringBuilder alarmBuilder = new StringBuilder(); // 检查过载异常 if ("14".equals(overload)) { alarmBuilder.append("过载状态异常"); } // 检查逆变输出异常 if ("14".equals(inverterOutput)) { if (alarmBuilder.length() > 0) { alarmBuilder.append(","); } alarmBuilder.append("逆变输出状态异常"); } // 检查过温异常 if ("14".equals(overTemperature)) { if (alarmBuilder.length() > 0) { alarmBuilder.append(","); } alarmBuilder.append("过温状态异常"); } // 检查短路异常 if ("14".equals(shortCircuit)) { if (alarmBuilder.length() > 0) { alarmBuilder.append(","); } alarmBuilder.append("短路状态异常"); } String[] split = deviceNameWithIp.split("\\+"); DcSnmpAlarm dcSnmpAlarm = new DcSnmpAlarm(); String cacheMapValue = redisCache.getCacheMapValue(ALARMVALUE, deviceKey);//查询缓存 if (cacheMapValue == null || "".equals(cacheMapValue)) {//缓存不存在加入缓存加入数据 dcSnmpAlarm.setContent(split[0] + alarmBuilder.toString()); dcSnmpAlarm.setDeviceName(split[0]); dcSnmpAlarm.setIotDeviceId(deviceKey); dcSnmpAlarm.setIp(split[1]); dcSnmpAlarm.setCreateTime(DateUtils.getNowDate()); dcDeviceService.insertSnmpAlarm(dcSnmpAlarm);//加入数据 redisCache.setCacheMapValue(ALARMVALUE,deviceKey,split[1] + alarmBuilder.toString()); HashMap alarmMap = new HashMap<>(); alarmMap.put("content", split[0] + alarmBuilder.toString()); alarmMap.put("time", DateUtils.getNowDate()); WebSocketService.broadcast("deviceAlarm", alarmMap); }else { //缓存存在更新值 //如果缓存存在,-缓存替换、数据替换 redisCache.delCacheMapValue(ALARMVALUE,deviceKey); redisCache.setCacheMapValue(ALARMVALUE,deviceKey,split[1] + alarmBuilder.toString()); dcSnmpAlarm.setContent(split[0] + alarmBuilder.toString()); dcSnmpAlarm.setIotDeviceId(deviceKey); dcDeviceService.updateSnmpAlarm(dcSnmpAlarm); HashMap alarmMap = new HashMap<>(); alarmMap.put("content", split[0] + alarmBuilder.toString()); alarmMap.put("time", DateUtils.getNowDate()); WebSocketService.broadcast("deviceAlarm", alarmMap); } } } return AjaxResult.success(); } //查询机柜烟感记录 @GetMapping("/dcSnmpUpsAlarmList") public TableDataInfo nmpUpsAlarmList( DcSnmpAlarm dcSnmpAlarm){ startPage(); Map redisCacheCacheMap = redisCache.getCacheMap(ALARMVALUE); if (redisCacheCacheMap==null||redisCacheCacheMap.size()==0){ return getDataTable(Collections.emptyList()); } Set strings = redisCacheCacheMap.keySet(); List list = dcDeviceService.selectSnmpAlarm(strings); return getDataTable(list); } }