package com.zc.business.controller; import cn.hutool.core.date.DateUtil; 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.enums.BusinessType; 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.DcEvent; 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.common.core.httpclient.OkHttp; import com.zc.common.core.httpclient.exception.HttpException; import com.zc.common.core.httpclient.request.RequestParams; 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.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; 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.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 IDcDeviceService dcDeviceService; @Resource private VideoController videoController; private static final int THREAD_POOL_SIZE = 100; // 线程池大小 private ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE); /* @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(UniversalEnum.COMMA.getValue(), 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(queryDeviceProperties(dcDevice.getIotDeviceId(), propertyId, props).get("data").toString()).get("data"); JSONArray dataArray = JSON.parseArray(data.toString()); // 创建一个映射来存储单个设备按小时汇总的数据 Map deviceHourlyAggregates = new TreeMap<>(); List> list = new ArrayList<>(); 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 formatValue = Double.parseDouble(valueWithoutUnit); double parsedValue = Double.parseDouble(valueWithoutUnit); // 保留两位小数 double formatValue = Double.parseDouble(decimalFormat.format(parsedValue)); // 汇总每个小时的数据 deviceHourlyAggregates.merge(key, formatValue, Double::sum); } // 将设备的数据合并到所有设备的汇总数据中 for (String key : deviceHourlyAggregates.keySet()) { allDevicesHourlyAggregates.merge(key, deviceHourlyAggregates.get(key), Double::sum); } } return AjaxResult.success(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() + propertyId) .build()).execute()) { String responseBody = response.body().string(); JsonObject data = JsonParser.parseString(responseBody).getAsJsonObject().getAsJsonObject("data"); 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(property, value, (oldVal, newVal) -> 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(); Response response // 请求响应 = okHttp .url(iotAddress + UniversalEnum.GETS_THE_LATEST_DATA_ABOUT_THE_SPECIFIED_ATTRIBUTES_OF_A_DEVICE.getValue() + deviceId + UniversalEnum.SLASH.getValue() + propertyId) // 请求地址 .get(); // 请求方法 return JSON.parseObject(response.body().string(), AjaxResult.class); } /** * 获取物联设备实时属性值 * * @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); } 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 11/10 * * * ?") 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) { 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); } }