package com.moral.controller; import java.io.*; import java.lang.reflect.Array; import java.math.BigDecimal; import java.net.URLEncoder; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.stream.Collectors; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.databind.ObjectMapper; import com.googlecode.aviator.AviatorEvaluator; import com.googlecode.aviator.Expression; import com.moral.common.bean.Constants; import com.moral.common.bean.JsonData; import com.moral.common.bean.PageResult; import com.moral.common.bean.ResultBean; import com.moral.common.util.BeanUtils; import com.moral.common.util.ParameterUtils; import com.moral.common.util.ValidateUtil; import com.moral.common.util.WebUtils; import com.moral.common.xml.Version; import com.moral.entity.*; import com.moral.entity.alarm.AlarmConfig; import com.moral.entity.alarm.AlarmConfigValue; import com.moral.entity.alarm.AlarmSensorLevel; import com.moral.entity.charts.DataSortCondition; import com.moral.entity.layout.RealTimeDeviceLayout; import com.moral.mapper.HistoryMapper; import com.moral.service.*; import com.moral.util.*; import com.rabbitmq.client.*; import com.rabbitmq.client.Channel; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import io.swagger.models.auth.In; import jdk.nashorn.internal.runtime.regexp.joni.Regex; import net.sf.json.JSONString; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.net.ftp.FTPClient; import org.apache.ibatis.annotations.Param; import org.apache.log4j.Logger; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.springframework.beans.factory.annotation.Value; import org.springframework.cglib.beans.BeanMap; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.util.ObjectUtils; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import org.xml.sax.InputSource; import static com.moral.common.util.ResourceUtil.getValue; import static com.moral.common.util.WebUtils.getParametersStartingWith; import static java.util.Calendar.*; /** * The Class ScreenController.大屏接口 */ @RestController @RequestMapping("/screen") @CrossOrigin(origins = "*", maxAge = 3600) @SuppressWarnings({"rawtypes", "unchecked", "unused"}) @Api(tags = "Screen", description = "大屏接口") public class ScreenController { public static Logger log = Logger.getLogger(ScreenController.class); @Resource private HistoryMapper historyMapper; @Resource AlarmConfigService alarmConfigService; @Resource AreaService areaService; @Resource SensorService sensorService; @Resource SensorUnitService sensorUnitService; @Resource MonitorPointService monitorPointService; @Resource DeviceVersionService deviceVersionService; /* @Resource HistorySpecialService historySpecialService;*/ /** * The screen service. */ @Resource private HistoryService historyService; /** * The account service. */ @Resource private AccountService accountService; /** * The device service. */ @Resource private DeviceService deviceService; @Resource private HistoryHourlyService historyHourlyService; @Resource private HistoryMinutelyService historyMinutelyService; @Resource private MachineActivateService machineActivateService; /** The resource. */ // @Value(value = "classpath:system/alarmLevels.json") // private org.springframework.core.io.Resource resource; /** * The redis template. */ @Resource private RedisTemplate redisTemplate; /** * The level key. */ private String levelKey = "alarm_"; @Resource private AlarmDailyService alarmDailyService; @Resource private OrganizationLayoutService orgLayoutService; @Resource private DeviceVersionService dviceVersionService; @Resource private OrganizationService organizationService; @Resource private DictionaryDataService dictionaryDataService; @Resource private WeatherService weatherService; @Resource private QualityDailyService qualityDailyService; @Resource private DeviceRoadService deviceRoadService; @Resource private ScreenVersionService screenVersionService; @Resource private DeviceAdjustValueTimingService deviceAdjustValueTimingService; @Resource private PollutioSourcePointService pollutioSourcePointService; @Resource private HistoryFiveMinutelyService historyFiveMinutelyService; /** * Screen login. 大屏登录 * * @param request the request * @return the map */ @GetMapping("login") public Map screenLogin(HttpServletRequest request) { Map resultMap = new HashMap(); Map parameters = getParametersStartingWith(request, null); if (!(parameters.containsKey("account") && parameters.containsKey("password"))) { resultMap.put("msg", "用户名及密码不允许为空!"); resultMap.put("accountId", -1); } else { resultMap = accountService.screenLogin(parameters); // 添加返回行政区信息字符串操作 Object orgId = resultMap.get("orgId"); if (resultMap.get("orgId") != null && resultMap.get("orgId") instanceof Integer) { StringBuilder areaNamesBuilder = new StringBuilder("中国"); if (!((Integer) orgId).equals(dictionaryDataService.querySupperOrgId())) { Organization organization = organizationService.getOrganizationById((Integer) orgId); if (organization.getAreaNames() != null) { Map areaNameMap = BeanUtils.beanToMap(organization.getAreaNames()); List names = areaNameMap.entrySet().stream().filter(item -> { return item.getValue() != null; }).map(item -> { return item.getValue(); }).collect(Collectors.toList()); AreaNames areaNames = organization.getAreaNames(); areaNamesBuilder.append("/"); areaNamesBuilder.append(String.join("/", names)); } // 企业用户 if (organization.getRank() != null && organization.getRank() == 0) { resultMap.put("type", "enterprise"); } else { resultMap.put("type", "government"); } Number mapAreaCode = null; if (organization.getVillageCode() != null) { mapAreaCode = organization.getVillageCode(); } else if (organization.getTownCode() != null) { mapAreaCode = organization.getTownCode(); } else if (organization.getAreaCode() != null) { mapAreaCode = organization.getAreaCode(); } else if (organization.getCityCode() != null) { mapAreaCode = organization.getCityCode(); } else if (organization.getProvinceCode() != null) { mapAreaCode = organization.getProvinceCode(); } resultMap.put("mapAreaCode", mapAreaCode.toString()); } resultMap.put("mapPath", areaNamesBuilder.toString()); } } return resultMap; } @GetMapping("loginNew") public Map screenLoginNew(HttpServletRequest request) { Map resultMap = new HashMap(); Map parameters = getParametersStartingWith(request, null); if (!(parameters.containsKey("account") && parameters.containsKey("password"))) { resultMap.put("msg", "用户名及密码不允许为空!"); resultMap.put("accountId", -1); } else { resultMap = accountService.screenLoginNew(parameters); // 添加返回行政区信息字符串操作 Object orgId = resultMap.get("orgId"); if (resultMap.get("orgId") != null && resultMap.get("orgId") instanceof Integer) { StringBuilder areaNamesBuilder = new StringBuilder("中国"); if (!((Integer) orgId).equals(dictionaryDataService.querySupperOrgId())) { Organization organization = organizationService.getOrganizationById((Integer) orgId); if (organization.getAreaNames() != null) { Map areaNameMap = BeanUtils.beanToMap(organization.getAreaNames()); List names = areaNameMap.entrySet().stream().filter(item -> { return item.getValue() != null; }).map(item -> { return item.getValue(); }).collect(Collectors.toList()); AreaNames areaNames = organization.getAreaNames(); areaNamesBuilder.append("/"); areaNamesBuilder.append(String.join("/", names)); } // 企业用户 if (organization.getRank() != null && organization.getRank() == 0) { resultMap.put("type", "enterprise"); } else { resultMap.put("type", "government"); } Number mapAreaCode = null; if (organization.getVillageCode() != null) { mapAreaCode = organization.getVillageCode(); } else if (organization.getTownCode() != null) { mapAreaCode = organization.getTownCode(); } else if (organization.getAreaCode() != null) { mapAreaCode = organization.getAreaCode(); } else if (organization.getCityCode() != null) { mapAreaCode = organization.getCityCode(); } else if (organization.getProvinceCode() != null) { mapAreaCode = organization.getProvinceCode(); } resultMap.put("mapAreaCode", mapAreaCode.toString()); } resultMap.put("mapPath", areaNamesBuilder.toString()); } } return resultMap; } /** * Gets the equipment states. 获取该账号下所有设备的状态 * * @param request the request * @return the equipment states */ @GetMapping("/equipment-state") @PreAuthorize("hasAnyRole('USER', 'ADMIN')") public Map getDeviceStatesByAccount(HttpServletRequest request) { Map parameters = getParametersStartingWith(request, null); return deviceService.getDeviceStatesByAccount(parameters); } /** * Gets the alarm levels. 获取报警配置 * * @param request the request * @return the alarm levels */ @GetMapping("alarm-levels") public Object getAlarmLevels(HttpServletRequest request, Optional orgId, Optional mpId, Optional mac) { List> sensorAlarmList = null; try { AlarmConfig alarmConfig = null; if (orgId.isPresent()) { alarmConfig = alarmConfigService.queryValueByOrganizationId(orgId.get()).get(); } else if (mpId.isPresent()) { alarmConfig = alarmConfigService.queryByMonitorPointId(mpId.get()).get(); } else if (mac.isPresent()) { alarmConfig = alarmConfigService.queryByDeviceMac(mac.get()).get(); } // 返回值处理 if (alarmConfig.getValue() != null && alarmConfig.getValue().getAlarmLevels() != null) { Map alarmLevelMap = alarmConfig.getValue().getAlarmLevels(); // 当前非取默认值,未设值将用默认值覆盖 Map defaultSensorLevelMap = null; if (alarmConfig.getId() != null) { AlarmConfigValue defaultAlarmValue = alarmConfigService.getDefaultAlarmConfigValue(); defaultSensorLevelMap = defaultAlarmValue.getAlarmLevels(); } Map finalDefaultSensorLevelMap = defaultSensorLevelMap; alarmLevelMap.entrySet().stream().forEach(entry -> { // 当 increment都为0时,替换为默认值 AlarmSensorLevel alarmSensorLevel = entry.getValue(); if (alarmSensorLevel.getIncrement() != null) { boolean isAllZero = alarmSensorLevel.getIncrement().stream().allMatch(item -> item == 0); if (isAllZero) { AlarmSensorLevel defaultAlarmSensorLevel = finalDefaultSensorLevelMap == null ? null : finalDefaultSensorLevelMap.get(entry.getKey()); if (defaultAlarmSensorLevel != null) { alarmSensorLevel.setIncrement(defaultAlarmSensorLevel.getIncrement()); } else { List tempList = Arrays.asList(0.0f, 200.0f, 500.0f); alarmSensorLevel.setIncrement(tempList); } } } }); // map to list Map finalAlarmLevelMap = alarmLevelMap; sensorAlarmList = alarmLevelMap.keySet().stream().map(key -> { AlarmSensorLevel alarmSensorLevel = finalAlarmLevelMap.get(key); Map alarmSensorLevelMap = new HashMap<>(BeanMap.create(alarmSensorLevel)); alarmSensorLevelMap.put("key", key); return alarmSensorLevelMap; }).collect(Collectors.toList()); } else { return new ResultBean<>("提供参数有误,未查询到任何数据", ResultBean.FAIL); } } catch (Exception e) { e.printStackTrace(); Map err = new LinkedHashMap(); err.put("msg", "系统错误,请联系管理员!原因如下:" + e.getMessage()); return err; } return sensorAlarmList; } /** * Gets the standard by sensor.获取某传感器标准值 * * @param macKey the request * @return the standard by sensor */ @GetMapping("sensor-standard") public Map getStandardBySensor(@RequestParam("macKey") String macKey) { ValidateUtil.notEmpty(macKey, "param.is.null"); Map result = new HashMap(); result.put("standard", getValue(macKey + "-standard")); return result; } /** * @param dataSortCondition 数据排名查询条件 * @return */ public ResultBean> getOrderData(DataSortCondition dataSortCondition) { ResultBean resultBean = new ResultBean(); if (dataSortCondition.getCode() == null) { resultBean.setCode(ResultBean.FAIL); resultBean.setMessage("code can't be null"); } else if (dataSortCondition.getStyle() == null) { resultBean.setCode(ResultBean.FAIL); resultBean.setMessage("style can't be null"); } String code = dataSortCondition.getCode().toString(); Region region = Region.create(code); if (region == null) { resultBean.setCode(ResultBean.FAIL); resultBean.setMessage("code is not in the correct format"); } // todo return null; } /** * Gets the day AQI by sensor.设备昨日的AQI指标 * * @param request the request * @return the day AQI by sensor */ @GetMapping("day-aqi") public Map getDayAQIByDevice(HttpServletRequest request) { Map parameters = getParametersStartingWith(request, null); return historyMinutelyService.getDayAQIByDevice(parameters); } @GetMapping("hour-aqi") @ApiOperation(value = "获取一小时AQI", notes = "获取一小时AQI") @ApiImplicitParams(value = { @ApiImplicitParam(name = "mac", value = "设备mac地址", required = true, paramType = "query", dataType = "String") }) public Map getHourAQIByDevice(HttpServletRequest request) { Map parameters = getParametersStartingWith(request, null); return historyService.gitHourlyAQIByMacAndTimeslot(parameters); } /** * Gets the average by all. 获取某账号某区域10分钟前到5分钟前所有传感器平均数值排名 * * @param request the request * @return the average by all * @throws Exception */ @GetMapping("all-average") public Map getAllSensorAverageByDevice(HttpServletRequest request) throws Exception { Map parameters = getParametersStartingWith(request, null); return historyService.getAllSensorAverageByDevice(parameters); } /** * Gets the average by sensor.某个传感器一小时内所有设备排名 * * @param request the request * @return the average by sensor */ @GetMapping("sensor-average") public Map getDeviceRankingBySensorAverage(HttpServletRequest request) { Map parameters = getParametersStartingWith(request, null); return historyService.getDeviceRankingBySensorAverage(parameters); } /** * Gets the month average by sensor.设备传感器本月平均值 * * @param request the request * @return the month average by sensor */ @GetMapping("month-sensor-average") public Map getMonthAverageBySensor(HttpServletRequest request) { Map parameters = getParametersStartingWith(request, null); return historyMinutelyService.getAverageBySensor(parameters); } @GetMapping("check-activate") public ResultBean checkActivate(String macCpuCode) { Integer result = machineActivateService.checkActivate(macCpuCode); return new ResultBean(result); } @PostMapping("activate-machine") public ResultBean activateMachine(HttpServletRequest request) { Map parameters = getParametersStartingWith(request, null); Integer result = machineActivateService.activateMachine(parameters); return new ResultBean(result); } /********************************************* * 大屏程序在线升级配置读取 *********************************************/ private String fileName = "Version.xml"; private String ip = "47.96.19.115"; private String userName = "ftp_user"; private String userPwd = "qwer1234"; private int port = 21; private String path = "/"; @RequestMapping(value = "/upgrade", method = RequestMethod.GET) public Version index() { Version version = new Version(); FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(ip, port); ftpClient.login(userName, userPwd); ftpClient.changeWorkingDirectory(path); ftpClient.enterLocalPassiveMode(); // ftpClient.enterLocalActiveMode(); InputStream ins = ftpClient.retrieveFileStream(fileName); BufferedReader reader = new BufferedReader(new InputStreamReader(ins, "utf-8")); String line; StringBuilder builder = new StringBuilder(); while ((line = reader.readLine()) != null) { builder.append(line); } reader.close(); if (ins != null) { ins.close(); } ftpClient.getReply(); String content = builder.toString(); if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } // String urlStr = "http://www.7drlb.com/apps/Version.xml"; // URL realUrl = new URL(urlStr); // URLConnection connection = realUrl.openConnection(); // connection.connect(); // StringBuffer result = new StringBuffer(); // BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")); // String line; // while ((line = in.readLine()) != null) { // result.append(line); // } // String content = result.toString(); SAXReader saxReader = new SAXReader(); Document document = saxReader.read(new InputSource(new ByteArrayInputStream(content.getBytes("utf-8")))); Element root = document.getRootElement(); version.setVer(root.element("Ver").getText()); version.setFileName(root.element("FileName").getText()); version.setFileMD5Hash(root.element("FileMD5Hash").getText()); } catch (Exception e) { e.printStackTrace(); } return version; } public static void main(String[] args) { ScreenController sc = new ScreenController(); Version a = sc.index(); System.out.println(a.getVer()); } /** * 地图接口 开始 */ /** * 地图主页 * * @param model * @param code * @param accountId * @return */ @RequestMapping(value = "/map-page", method = RequestMethod.GET) public ModelAndView map(ModelAndView model, @RequestParam("areaCode") long code, @RequestParam("accountId") int accountId) { Account account = accountService.getAccountById(accountId); String regionName = areaService.queryFullNameByCode(code); if (account != null && regionName != null) { Object sensors = sensorService.queryAll(); JSONObject params = new JSONObject(); params.put("regionCode", code); params.put("regionName", regionName); params.put("accountId", accountId); params.put("orgId", account.getOrganizationId()); params.put("sensors", sensors); String paramsJson = params.toJSONString(); model.addObject("mapParams", paramsJson); model.setViewName("map"); return model; } else { StringBuilder msg = new StringBuilder(); msg.append(" param[0] areaCode:"); msg.append(code); msg.append(" param[0] accountId:"); msg.append(accountId); log.warn(msg); model.setViewName("403"); return model; } } @GetMapping("/getSensorsMap") public List> getSensorsMapOnly(String mac) { List> sensorsMapList = sensorService.getSensorsMaps(mac); return sensorsMapList; } @GetMapping("/getSensorsAllMap") public List> getSensorsAllMap(String mac) { List> sensorsMapList = sensorService.getSensorsAllMap(); return sensorsMapList; } @RequestMapping(value = "/get-monitorpoints", method = RequestMethod.GET) @ResponseBody public ResultBean getMonitorpointList(@RequestParam("orgId") String orgId, MapBounds mapBounds, @RequestParam("regionCode") String regionCode) { ResultBean> resultBean = new ResultBean(); Map paramMap = new HashMap(); paramMap.put("orgId", orgId); paramMap.put("mapBounds", mapBounds); paramMap.put("regionCode", regionCode); ParameterUtils.getRegionType4RegionCode(paramMap); List list = monitorPointService.queryWithStateByMap(paramMap); resultBean.setData(list); resultBean.setCode(ResultBean.SUCCESS); return resultBean; } @RequestMapping(value = "/get-devices", method = RequestMethod.GET) @ResponseBody @ApiOperation(value = "设备信息", notes = "设备信息") @ApiImplicitParams(value = { @ApiImplicitParam(name = "orgId", defaultValue = "5", value = "组织Id", required = true, paramType = "query", dataType = "Integer"), @ApiImplicitParam(name = "regionCode", defaultValue = "320583", value = "地区编码", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "Fe", defaultValue = "31.485018", value = "东北角纬度", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "Ge", defaultValue = "121.378395", value = "东北角经度", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "Ke", defaultValue = "31.296614", value = "西南角纬度", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "Le", defaultValue = "120.59651", value = "西南角经度", required = true, paramType = "query", dataType = "String") }) public ResultBean getDevices(@RequestParam("orgId") Integer orgId, MapBounds mapBounds, @RequestParam("regionCode") String regionCode) { ResultBean> resultBean = new ResultBean(); Map paramMap = new HashMap(); paramMap.put("orgId", orgId); paramMap.put("mapBounds", mapBounds); paramMap.put("regionCode", regionCode); ParameterUtils.getRegionType4RegionCode(paramMap); List list = deviceService.query(paramMap); resultBean.setData(list); resultBean.setCode(ResultBean.SUCCESS); return resultBean; } @RequestMapping(value = "get-devices-for-popup", method = RequestMethod.GET) @ResponseBody public PageResult getDevicesForPopup(@RequestParam("orgId") Integer orgId, String name, Integer pageSize, Integer pageNo) { return deviceService.query(orgId, name, pageSize, pageNo); } @RequestMapping(value = "get-devices-by-mid-oid", method = RequestMethod.GET) @ResponseBody public PageResult getDevicesByMidOid(@RequestParam("orgId") Integer orgId, @RequestParam("mpId") Integer mpId, Integer pageSize, Integer pageNo) { return deviceService.query(orgId, mpId, pageSize, pageNo); } @RequestMapping(value = "/get-real-state-data", method = RequestMethod.POST) @ResponseBody public JsonData getRealStateAndData(@RequestBody JSONObject paramMap) { JsonData jsonData = new JsonData(); Map returnMap = new HashMap(); returnMap.put("layer", paramMap.getString("layer")); // 覆盖控件的数据刷新 if (!CollectionUtils.isEmpty(paramMap.getJSONArray("markerKeys"))) { JSONArray markerKeys = paramMap.getJSONArray("markerKeys"); List> markers = null; if ("equipments".equals(paramMap.getString("layer"))) { markers = deviceService.queryDevicesState(markerKeys.toJavaList(String.class), true); } else {// 返回监控点id和state String orgId = paramMap.getString("orgId"); String areaCode = paramMap.getString("areaCode"); for (Object mPointId : markerKeys) { markers = monitorPointService.queryMonitroPointsState(markerKeys.toJavaList(Integer.class)); } } returnMap.put("markers", markers); } if (paramMap.getJSONArray("popupEquMacs") != null && paramMap.getJSONArray("popupEquMacs").size() > 0) { JSONArray popupEquMacs = paramMap.getJSONArray("popupEquMacs"); List> popupEquWithStates = null; for (Object mac : popupEquMacs) { popupEquWithStates = deviceService.queryDevicesState(popupEquMacs.toJavaList(String.class), false); } // 返回搜索结果的状态 returnMap.put("popupEquStates", popupEquWithStates); } jsonData.setExtData(returnMap); return jsonData; } @GetMapping("monitor_points") public ResultBean> getMonitorPointsByOrganizationId(Integer orgId) { // Map parameters = getParametersStartingWith(request, null); List monitorPoints = monitorPointService.getMonitorPointsByOrganizationId(orgId); return new ResultBean>(monitorPoints); } /* * 参数:monitorPoint=368&mac=p5dnd7a0392018&sensorKey=e92&time=2020-08-11 * 获取传感器均值接口 * */ @GetMapping("report_avg_datas") public ResultBean>> getMonitorPointOrDeviceAvgData(HttpServletRequest request) throws Exception { Map parameters = getParametersStartingWith(request, null); //该方法用于判断时间是具体到年月日 ParameterUtils.getTimeType4Time(parameters); String time1 = (String) parameters.get("time"); time1 = time1.replaceAll(" ", ""); parameters.put("time", time1); String mac1 = (String) parameters.get("mac"); List> list = null; if (mac1 != null && mac1.equals("p5dnd7a0392018") && time1.substring(0, 4).equals("2019")) { list = null; } else { parameters.put("monitorPointId", parameters.remove("monitorPoint")); Object sensorKey = parameters.remove("sensorKey"); parameters.put("sensors", Arrays.asList(sensorKey)); // monitorPointService.isCompensateCalculation(parameters); list = historyMinutelyService.getMonitorPointOrDeviceAvgData(parameters); /* 0点的数据是昨天11点到今天0点的,界面显示1-24点的,所以不需要0点的数据,但需要单独查询24点的数据 因为改动以前24点的数据是23-24,现在24点的数据是第二天0点的数据, */ /*改动范围start-------------------------------------------------------------------------*/ Iterator> iterator = list.iterator(); while (iterator.hasNext()) { Map next = iterator.next(); String hour = next.get("time").toString().substring(11, 13); if ("00".equals(hour)) { iterator.remove(); } } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd"); //获取全格式时间yyyy-MM-dd HH:mm:ss time1 = time1 + " 00:00:00"; Date date = sdf.parse(time1); date = DateUtil.rollDay(date, 1); //将全格式时间截取 String time2 = sdf2.format(date); parameters.put("time", time2); /*查询第二天0点的数据,以24点的形式存进集合中*/ List> nextDayList = historyMinutelyService.getMonitorPointOrDeviceAvgData(parameters); if (!ObjectUtils.isEmpty(nextDayList)) { time1 = time1.replaceAll(" 00:00:00", " 24"); for (Map map : nextDayList) { String time = map.get("time").toString().substring(11, 13); if("00".equals(time)){ map.put("time", time1); list.add(map); } } } /*改动范围end-------------------------------------------------------------------------*/ for (Map map : list) { String time = map.get("time").toString(); time = time.substring(time.length() - 2); map.put("time", Integer.valueOf(time)); /* if (parameters.get("type").equals("day")) { map.put("time", Integer.valueOf(time) + 1); }*/ map.put("value", map.remove(sensorKey)); } } return new ResultBean>>(list); } @GetMapping("report_alarm_datas") public ResultBean>> getAlarmData(HttpServletRequest request) throws Exception { Map parameters = getParametersStartingWith(request, null); ParameterUtils.getTimeType4Time(parameters); // parameters.put("type", "month"); String sensorKey = "list"; if (ObjectUtils.isEmpty(parameters.get("sensorKey"))) { parameters.put("description", "description"); } else { sensorKey = parameters.remove("sensorKey").toString(); List sensorKeys = new ArrayList(); sensorKeys.add(sensorKey); parameters.put("sensors", sensorKeys); } if (!ObjectUtils.isEmpty(parameters.get("organizationId"))) { if (!Constants.isNotSpecialOrgId(Integer.valueOf(parameters.get("organizationId").toString()))) { parameters.remove("organizationId"); } } Map pieData = alarmDailyService.getPieData(parameters); List> list = (List>) pieData.get(sensorKey); return new ResultBean>>(list); } /** * 根据监控点id获取所属设备version数据集 * * @param mptid * @return */ @GetMapping("getvers") public ResultBean> getVersions(Integer mptid) { return new ResultBean<>(monitorPointService.queryVersionsById(mptid)); } @GetMapping("region_ranking_data") @ApiOperation(value = "获取排名数据", notes = "获取排名数据") @ApiImplicitParams(value = { @ApiImplicitParam(name = "regionCode", value = "区域码", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "dimension", value = "维度(profession、region、monitorPoint选一)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "sensorKey", value = "传感器key", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "accountId", value = "账户id", required = true, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "timeType", value = "时间类型(month、day、hour选一)", required = true, paramType = "query", dataType = "int"),}) public ResultBean>> getRegionRankingData(HttpServletRequest request) { Map parameters = getParametersStartingWith(request, null); List> list = historyService.getRegionRankingData(parameters); return new ResultBean>>(list); } // todo @Value(value = "classpath:system/realTimeMonitorLayout.json") private org.springframework.core.io.Resource resource; @ApiOperation(value = "获取实时监控页面布局", notes = "") @ApiImplicitParams(value = { @ApiImplicitParam(name = "primaryKey", defaultValue = "898607b0101730391967", value = "值为:设备mac或监控站id", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "type", defaultValue = "device", value = "值为:'monitorPoint'或'device'", required = true, paramType = "query", dataType = "String"),}) @GetMapping("rtm-layout") public ResultBean realTimeMonitorLayout(String primaryKey, String type) { RealTimeDeviceLayout rtdLayout = null; if (type != null && type.equals("device")) { Device device = deviceService.getDeviceByMac(primaryKey, false); if (device != null && device.getOrganizationIds() != null && device.getOrganizationIds().size() > 0 && device.getDeviceVersionId() != null) { Integer orgId = device.getOrganizationIds().get(0); DeviceVersion deviceVersion = deviceVersionService.queryVersionById(device.getDeviceVersionId()); rtdLayout = orgLayoutService.queryRtdLayoutWithUnit(orgId, deviceVersion.getVersion()); } else { String errMsg = "device 数据异常:" + JSON.toJSONString(device); log.warn(errMsg); return ResultBean.fail(errMsg); } } else { MonitorPoint monitorPoint = monitorPointService.queryMonitorPointById(Integer.parseInt(primaryKey)); List versionList = deviceVersionService.queryByMpointId(monitorPoint.getId()); if (versionList.size() > 0) { List versionNolist = versionList.stream().map(item -> { return item.getVersion(); }).collect(Collectors.toList()); rtdLayout = orgLayoutService.queryRtdLayoutWithUnit(monitorPoint.getOrganizationId(), versionNolist); if (rtdLayout == null) { return ResultBean.fail(); } } } if (rtdLayout != null && rtdLayout.getDefaultMonitorItems().size() == 0) { rtdLayout.getDefaultMonitorItems().addAll(rtdLayout.getCoreMonitorItems()); } return new ResultBean(rtdLayout == null ? new RealTimeDeviceLayout() : rtdLayout); } @GetMapping("report_avg_data") @ApiOperation(value = "获取监测因子月平均值", notes = "获取监测因子月平均值") @ApiImplicitParams(value = { @ApiImplicitParam(name = "monitorPoint", value = "监控站id", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "mac", value = "设备mac", required = false, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "sensorKey", value = "传感器key,如有多个用逗号分隔", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "time", value = "时间,月份(格式:2018-03)", required = true, paramType = "query", dataType = "String"),}) public ResultBean>> getMonitorPointOrDeviceAvgDataBySensorKey(HttpServletRequest request) throws Exception { Map parameters = getParametersStartingWith(request, null); ParameterUtils.getTimeType4Time(parameters); parameters.put("monitorPointId", parameters.remove("monitorPoint")); String[] sensorKeys = parameters.remove("sensorKey").toString().split(","); parameters.put("sensors", Arrays.asList(sensorKeys)); // monitorPointService.isCompensateCalculation(parameters); List> list = historyMinutelyService.getMonitorPointOrDeviceAvgData(parameters); for (Map map : list) { String time = map.get("time").toString(); time = time.substring(time.length() - 2); map.put("time", Integer.valueOf(time)); List values = new ArrayList(); for (String string : sensorKeys) { values.add((Number) map.remove(string)); } map.put("values", values); } return new ResultBean>>(list); } @GetMapping("report_avg_AreaData") @ApiOperation(value = "获取国控因子与监测因子平均值", notes = "获取国控因子与监测因子平均值") @ApiImplicitParams(value = { @ApiImplicitParam(name = "monitorPoint", value = "监控站id", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "mac", value = "设备mac", required = false, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "areaCode", value = "地区代码", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "sensorKey", value = "传感器key", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "time", value = "时间,月份(格式:2018-03)", required = true, paramType = "query", dataType = "String"),}) public ResultBean>> getAreaAvgDataByAreaCode(HttpServletRequest request) throws Exception { Map parameters = getParametersStartingWith(request, null); ParameterUtils.getTimeType4Time(parameters); parameters.put("monitorPointId", parameters.remove("monitorPoint")); parameters.put("areaCode", parameters.remove("areaCode")); String[] sensorKeys = parameters.remove("sensorKey").toString().split(","); String type = parameters.get("type").toString(); String s = sensorKeys[0]; parameters.put("sensors", Arrays.asList(sensorKeys)); parameters.put("sensors2", s); ArrayList> resultList = new ArrayList<>(); List> monitorList = historyMinutelyService.getMonitorPointOrDeviceAvgData(parameters); List> areaList = hangzhouAqiService.getAreaAvgDataByAreaCode(parameters); if (areaList.isEmpty() && monitorList.isEmpty()) { return new ResultBean>>(resultList); } else if (areaList.isEmpty()) { resultList.addAll(monitorList); for (Map resultMap : resultList) { String time = resultMap.get("time").toString(); time = time.substring(time.length() - 2); resultMap.put("time", Integer.valueOf(time)); List values = new ArrayList<>(); values.add(""); values.add(resultMap.remove(s).toString()); resultMap.put("values", values); } return new ResultBean>>(resultList); } else if (monitorList.isEmpty()) { resultList.addAll(areaList); for (Map resultMap : resultList) { String time = resultMap.get("time").toString(); time = time.substring(time.length() - 2); resultMap.put("time", Integer.valueOf(time)); List values = new ArrayList<>(); values.add(resultMap.remove(s).toString()); values.add(""); resultMap.put("values", values); } return new ResultBean>>(resultList); } for (Map map : areaList) { String time = map.get("time").toString(); time = time.substring(time.length() - 2); map.put("time", Integer.valueOf(time)); } for (Map m : monitorList) { String time = m.get("time").toString(); time = time.substring(time.length() - 2); m.put("time", Integer.valueOf(time)); } Integer maxTime; Map areaMap = areaList.get(areaList.size() - 1); Integer areaMax = Integer.valueOf(areaMap.get("time").toString()); Map monitorMap = monitorList.get(monitorList.size() - 1); Integer monitorMax = Integer.valueOf(monitorMap.get("time").toString()); if (type.equals("day")) { if (areaMax >= monitorMax) { maxTime = areaMax + 1; } else { maxTime = monitorMax + 1; } } else { if (areaMax >= monitorMax) { maxTime = areaMax; } else { maxTime = monitorMax; } } for (int i = 0; i < maxTime; i++) { resultList.add(null); } for (Map map : areaList) { Integer time = Integer.valueOf(map.get("time").toString()); if (type.equals("day")) { resultList.set(time, map); } else { resultList.set(time - 1, map); } } for (int i = 0; i < resultList.size(); i++) { if (resultList.get(i) == null) { Map hashMap = new HashMap<>(); if (type.equals("day")) { hashMap.put("time", i); } else { hashMap.put("time", i + 1); } hashMap.put(s, ""); resultList.set(i, hashMap); } } for (Map map1 : monitorList) { ArrayList values = new ArrayList<>(); Integer time = Integer.valueOf(map1.get("time").toString()); Map map; if (type.equals("day")) { map = resultList.get(time); } else { map = resultList.get(time - 1); } values.add(map.remove(s).toString()); values.add(map1.get(s).toString()); map.put("values", values); } for (Map map : resultList) { if (map.containsKey(s)) { ArrayList values = new ArrayList<>(); values.add(map.remove(s).toString()); values.add(""); map.put("values", values); } } Iterator> it = resultList.iterator(); while (it.hasNext()) { Map next = it.next(); ArrayList values = (ArrayList) next.get("values"); if (values.get(0).equals("") && values.get(1).equals("")) { it.remove(); } } return new ResultBean>>(resultList); } @GetMapping("getmpoint-byid") @ApiOperation(value = "获取监测站数据", notes = "获取监测站数据,包含名称、地址、坐标等详细信息") @ApiImplicitParams(value = { @ApiImplicitParam(name = "monitorPointId", defaultValue = "1", value = "监控站id", required = true, paramType = "query", dataType = "Integer"),}) public ResultBean getMonitorPointById(Integer monitorPointId) { MonitorPoint monitorPoint = monitorPointService.queryMonitorPointById(monitorPointId); return new ResultBean<>(monitorPoint); } @Resource HangzhouAqiService hangzhouAqiService; @GetMapping("aqi24hours") @ApiOperation(value = "最近24小时aqi数值", notes = "最近24小时国控aqi数值") @ApiImplicitParams(value = { @ApiImplicitParam(name = "orgid", defaultValue = "5", value = "组织id", required = true, paramType = "query", dataType = "Integer"),}) public ResultBean>> getAqi24HoursNC(@RequestParam("orgid") Integer organizationId) { return new ResultBean<>(hangzhouAqiService.queryAqi24Hours(organizationId)); } @GetMapping("mpt-dev-summary") @ApiOperation(value = "监控总数和设备状态信息", notes = "监控总数和设备状态信息") @ApiImplicitParams(value = { @ApiImplicitParam(name = "orgid", defaultValue = "5", value = "组织id", required = true, paramType = "query", dataType = "Integer"),}) public ResultBean getMptAndDevSummary(@RequestParam("orgid") Integer organizationId) { Map result = new HashMap<>(2); Integer mptCount = monitorPointService.countOfSubOrgs(organizationId); Map monitorPointSummary = new HashMap(); monitorPointSummary.put("all", mptCount); Map deviceSummary = deviceService.queryDeviceStateSummary(organizationId); result.put("monitorPoint", monitorPointSummary); result.put("device", deviceSummary); return new ResultBean<>(result); } @GetMapping("weather") @ApiOperation(value = "获取区域天气情况", notes = "获取区域天气情况") @ApiImplicitParams(value = { @ApiImplicitParam(name = "organizationId", defaultValue = "5", value = "登录账号的组织id", required = true, paramType = "query", dataType = "String")}) public ResultBean> getWeatherDataByRegion(HttpServletRequest request) throws Exception { Map parameters = getParametersStartingWith(request, null); Map map = weatherService.getWeatherDataByRegion(parameters); return new ResultBean>(map); } @GetMapping("actual") @ApiOperation(value = "获取监测因子实时最大值", notes = "获取监测因子实时最大值") @ApiImplicitParams(value = { @ApiImplicitParam(name = "accountId", defaultValue = "1", value = "登录账号的id", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "sensorKey", defaultValue = "e1,e2,e3", value = "传感器key,如有多个用逗号分隔", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "time", defaultValue = "", value = "时间(long类型时间)", required = false, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "interval", defaultValue = "30", value = "时间间隔(秒)", required = true, paramType = "query", dataType = "Integer"),}) public ResultBean> getActualDataByRegion(HttpServletRequest request) throws Exception { Map parameters = getParametersStartingWith(request, null); Map map = historyService.getActualDataByRegion(parameters); return new ResultBean>(map); } @GetMapping("quality") @ApiOperation(value = "获取优良天数", notes = "获取优良天数") @ApiImplicitParams(value = { @ApiImplicitParam(name = "organizationId", defaultValue = "5", value = "登录账号的组织id", required = true, paramType = "query", dataType = "String")}) public ResultBean> getQualityCountDayByRegion(HttpServletRequest request) throws Exception { Map parameters = getParametersStartingWith(request, null); Map map = qualityDailyService.getQualityCountDayByRegion(parameters); return new ResultBean>(map); } @GetMapping("monitorpoints-devices") @ApiOperation(value = "获取监控点以及设备", notes = "获取监控点以及设备") @ApiImplicitParams(value = { @ApiImplicitParam(name = "organizationId", defaultValue = "8", value = "登录账号的组织id", required = true, paramType = "query", dataType = "Integer"), @ApiImplicitParam(name = "regionCode", defaultValue = "320583", value = "区域码", required = true, paramType = "query", dataType = "String")}) public ResultBean> getMonitorPointsAndDevicesByRegion(HttpServletRequest request) throws Exception { Map parameters = WebUtils.getParametersStartingWith(request, null); String regionCode = parameters.get("regionCode").toString(); List monitorPoints = monitorPointService.getMonitorPointsAndDevicesByRegion(parameters); //剔除沧州非本公司设备 if (regionCode.startsWith("1309")) { List orgIds = new ArrayList<>(); Collections.addAll(orgIds, 60, 65, 159, 165, 166); Iterator iter = monitorPoints.iterator(); while (iter.hasNext()) { MonitorPoint next = iter.next(); Integer mpId = next.getId(); Integer orgId = next.getOrganizationId(); if (!orgIds.contains(orgId)) { iter.remove(); } else { if (orgId == 60) { if (mpId != 56) { iter.remove(); } } else if (orgId == 65) { if (mpId != 83 && mpId != 84) { iter.remove(); } } } } } //给每一个monitorPoint下的设备通过device.getName()进行排序 for (MonitorPoint monitorPoint : monitorPoints) { List deviceList = monitorPoint.getDevices(); deviceList.sort((Device o1, Device o2) -> { return o1.getName().compareTo(o2.getName()); }); } return new ResultBean>(monitorPoints); } @GetMapping("devices-state") @ApiOperation(value = "刷新设备状态", notes = "刷新设备状态") @ApiImplicitParams(value = { @ApiImplicitParam(name = "organizationId", defaultValue = "8", value = "登录账号的组织id", required = true, paramType = "query", dataType = "Integer"), @ApiImplicitParam(name = "regionCode", defaultValue = "320583", value = "区域码", required = true, paramType = "query", dataType = "String")}) public ResultBean> getDevicesStateByRegion(HttpServletRequest request) throws Exception { Map parameters = WebUtils.getParametersStartingWith(request, null); Collection monitorPoints = monitorPointService.getDevicesStateByRegion(parameters); return new ResultBean>(monitorPoints); } @Resource private HistoryDailyService historyDailyService; @GetMapping("emissions") @ApiOperation(value = "排放量", notes = "排放量") @ApiImplicitParams(value = { @ApiImplicitParam(name = "organizationId", defaultValue = "5", value = "登录账号的组织id", required = true, paramType = "query", dataType = "Integer"), @ApiImplicitParam(name = "time", defaultValue = "2019", value = "查询的时间", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "sensorKey", defaultValue = "e27", value = "查询的监测因子的key", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "regionCode", defaultValue = "130000", value = "区域码", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "monitorPointId", value = "监测点id(格式:376)", required = false, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "mac", value = "设备mac(格式:vocscxwnm00001)", required = false, paramType = "query", dataType = "String")}) public ResultBean>> getemissionsData(HttpServletRequest request) throws Exception { Map parameters = WebUtils.getParametersStartingWith(request, null); List> result = historyDailyService.getEmissionsData(parameters); return new ResultBean>>(result); } @GetMapping("overproof") @ApiOperation(value = "浓度超标", notes = "浓度超标") @ApiImplicitParams(value = { @ApiImplicitParam(name = "organizationId", defaultValue = "5", value = "登录账号的组织id", required = true, paramType = "query", dataType = "Integer"), @ApiImplicitParam(name = "time", defaultValue = "2019", value = "查询的时间", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "sensorKey", defaultValue = "e27", value = "查询的监测因子的key", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "overproofRatio", defaultValue = "0", value = "超标比例(0,1,2,3)(超标,超标100%,超标200%,超标300%)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "regionCode", defaultValue = "130000", value = "区域码", required = true, paramType = "query", dataType = "String")}) public ResultBean getOverproofData(HttpServletRequest request) throws Exception { Map parameters = WebUtils.getParametersStartingWith(request, null); Map result = historyDailyService.getOverproofData(parameters); return new ResultBean(result); } @GetMapping("limit-device") @ApiOperation(value = "获取设备的警报限值", notes = "获取设备的警报限值") @ApiImplicitParams(value = { @ApiImplicitParam(name = "mac", defaultValue = "p5dnd7a0391956", value = "设备mac码", required = true, paramType = "query", dataType = "String")}) public ResultBean>> getLimitDataByDevice(HttpServletRequest request) throws Exception { Map parameters = WebUtils.getParametersStartingWith(request, null); String density = deviceService.getLimitDataByDevice(parameters); JSONObject parseObject = JSONObject.parseObject(density); List> resuList = new ArrayList>(); for (Map.Entry entry : parseObject.entrySet()) { resuList.add(new HashMap() { { put("key", entry.getKey()); put("limit", entry.getValue()); } }); } return new ResultBean>>(resuList); } /** * @param model * @param request * @return * @throws Exception * @description 根据设备mac,监测因子,时间查询返回界面 * @author ZhuDongming * @date 2019-06-05 10:02:10 */ @GetMapping("/map-traceability") @ApiOperation(value = "获取污染溯源", notes = "获取污染溯源") @ApiImplicitParams(value = { @ApiImplicitParam(name = "monitorPointId", value = "监测点id(格式:319)", required = true, paramType = "query", dataType = "int"), @ApiImplicitParam(name = "mac", value = "设备mac地址(格式:p5dnd7a0391993)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "sensorKey", value = "查询的监测因子的key(格式:e1)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "time", value = "查询时间(格式:2019-09-08)", required = true, paramType = "query", dataType = "String")}) public ModelAndView traceability(ModelAndView model, HttpServletRequest request) throws Exception { Map parameters = WebUtils.getParametersStartingWith(request, null); Integer monitorPointId = Integer.parseInt(parameters.get("monitorPointId").toString()); MonitorPoint monitorPoint = monitorPointService.queryWithRelationById(monitorPointId); String mac = parameters.get("mac").toString(); String sensorKey = parameters.get("sensorKey").toString(); String time = parameters.get("time").toString(); if (monitorPoint != null && mac != null && sensorKey != null && time != null) { Map resultMap = historyDailyService.getTraceabilityData(parameters); JSONObject params = new JSONObject(); Long code = monitorPoint.getAreaCode().longValue(); String regionName = areaService.queryFullNameByCode(code); Device device = deviceService.getDeviceByMac(mac, false); Device deviceSecond = deviceService.getDeviceByLongitudeAsc(mac); params.put("sensorInfo", resultMap); params.put("regionCode", code); params.put("regionName", regionName); params.put("monitorPoint", monitorPoint); params.put("device", device); params.put("deviceSecond", deviceSecond); String paramsJson = params.toJSONString(); model.addObject("traceabilityParams", paramsJson); model.setViewName("traceability"); return model; } else { StringBuilder msg = new StringBuilder(); msg.append(" param[0] monitorPointId:"); msg.append(monitorPointId); msg.append(" param[0] mac:"); msg.append(mac); msg.append(" param[0] sensorKey:"); msg.append(sensorKey); msg.append(" param[0] time:"); msg.append(time); log.warn(msg); model.setViewName("403"); return model; } } /*@GetMapping("getSensor") @ApiOperation(value = "返回单位", notes = "返回单位") @ApiImplicitParams(value = { @ApiImplicitParam(name = "mac", value = "设备MN号", required = true, paramType = "query", dataType = "String") }) public ResultBean> getSensor(HttpServletRequest request) throws Exception { Map parameters = WebUtils.getParametersStartingWith(request, null); String mac = (String) parameters.get("mac"); Map map = sensorUnitService.getSensorByMac(mac); return new ResultBean>(map); }*/ @GetMapping("getSensorByMonitorPointId") @ApiOperation(value = "返回单位", notes = "返回单位") @ApiImplicitParams(value = { @ApiImplicitParam(name = "monitor_point_id", value = "监测站点id", required = true, paramType = "query", dataType = "String") }) public ResultBean>> getSensorByMonitorPointId(HttpServletRequest request) throws Exception { Map parameters = WebUtils.getParametersStartingWith(request, null); String monitor_point_id = (String) parameters.get("monitor_point_id"); List> map = sensorUnitService.getSensorsByMonitPointId2(monitor_point_id); return new ResultBean>>(map); } @GetMapping("getSensorByDeviceId") @ApiOperation(value = "通过设备获取因子", notes = "通过设备获取因子") @ApiImplicitParams(value = { @ApiImplicitParam(name = "id", value = "设备id", required = true, paramType = "query", dataType = "String") }) public ResultBean>> getSensorByDeviceId(HttpServletRequest request) throws Exception { Map parameters = WebUtils.getParametersStartingWith(request, null); String id = (String) parameters.get("id"); List> list = sensorService.getSensorByDeviceId(id); Map map = list.get(0); String monitor_point_id = map.get("monitor_point_id").toString(); List> sensorUnitList = sensorUnitService.getSensorsByMonitPointId2(monitor_point_id); for (Map sensorMap : list) { for (Map sensorUnitMap : sensorUnitList) { if (sensorUnitMap.get("sensor_key").equals(sensorMap.get("sensor_key"))) { sensorMap.put("unit", sensorUnitMap.get("name")); } } } return new ResultBean>>(list); } @GetMapping("getSensorWithUnitByMonitorPointId") @ApiOperation(value = "通过站点获取因子", notes = "通过站点获取因子") @ApiImplicitParams(value = { @ApiImplicitParam(name = "monitor_point_id", value = "站点id", required = true, paramType = "query", dataType = "String") }) public ResultBean>> getSensorWithUnitByMonitorPointId(HttpServletRequest request) throws Exception { Map parameters = WebUtils.getParametersStartingWith(request, null); String monitor_point_id = (String) parameters.get("monitor_point_id"); List> list = sensorService.getSensorByMonitorPointId(monitor_point_id); List> sensorUnitList = sensorUnitService.getSensorsByMonitPointId2(monitor_point_id); for (Map sensorMap : list) { for (Map sensorUnitMap : sensorUnitList) { if (sensorUnitMap.get("sensor_key").equals(sensorMap.get("sensorKey"))) { sensorMap.put("unit", sensorUnitMap.get("name")); } } } return new ResultBean>>(list); } @GetMapping("AIForecast") @ApiOperation(value = "AI预测", notes = "AI预测") @ApiImplicitParams(value = { @ApiImplicitParam(name = "monitorPoint", value = "监控站id", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "mac", value = "设备mac", required = false, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "sensorKey", value = "传感器key,如有多个用逗号分隔", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "time", value = "时间,天(格式:2018-03-06)", required = true, paramType = "query", dataType = "String"), }) public ResultBean>> AIForecast(HttpServletRequest request) throws Exception { Map parameters = getParametersStartingWith(request, null); String monitorPoint = (String) parameters.get("monitorPoint"); String intoTime = parameters.get("time").toString(); Date date = new SimpleDateFormat("yy-MM-dd").parse(intoTime); DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd"); String alterTime = df1.format(date.getTime() - 15 * 24 * 60 * 60 * 1000); parameters.put("time", alterTime); ParameterUtils.getTimeType4Time(parameters); String monitor_point_id = (String) parameters.get("monitorPoint"); parameters.put("monitorPointId", parameters.remove("monitorPoint")); String[] sensorKeys = parameters.remove("sensorKey").toString().split(","); parameters.put("sensors", Arrays.asList(sensorKeys)); List> list = historyMinutelyService.getMonitorPointOrDeviceAvgData(parameters); Map mpMap = new HashMap<>(); mpMap = monitorPointService.selectAllById(monitorPoint); //生命一个map,用来存放查询天气信息是需要的参数 Map weatherParameters = new HashMap<>(); weatherParameters.put("organizationId", mpMap.get("organization_id")); weatherParameters.put("time", intoTime); //获取天气信息 Map weatherMap = new HashMap<>(); Map tempMap = new HashMap<>(); Boolean tf = false; for (int i = 0; i < sensorKeys.length; i++) { if (sensorKeys[i].equals("e7")) { tf = true; } } if (tf) { weatherMap = weatherService.get15DayWeatherDataByRegion(weatherParameters); tempMap = TempAllocationUtils.tempAllocation(weatherMap); } //获取单位信息 Map> sensorUnitMap = sensorUnitService.getSensorsByMonitPointId(monitor_point_id); for (Map map : list) { String time = map.get("time").toString(); time = time.substring(time.length() - 2); map.put("time", Integer.valueOf(time)); if (tempMap != null) { map.put("temp", tempMap.get(map.get("time").toString())); } List values = new ArrayList(); List units = new ArrayList(); for (String string : sensorKeys) { if (sensorUnitMap != null && !sensorUnitMap.isEmpty()) { if (sensorUnitMap.get(string) != null) { units.add(sensorUnitMap.get(string).get("name").toString()); String rules = sensorUnitMap.get(string).get("rules").toString(); rules = rules.replace("{0}", "a"); rules = rules.replace("d", ""); Expression expression = AviatorEvaluator.compile(rules); Double value; Map ev = new HashMap<>(); ev.put("a", map.get(string)); value = (Double) expression.execute(ev); //保留两位小数 DecimalFormat df = new DecimalFormat("#.00"); value = Double.parseDouble(df.format(value)); values.add(value); } else { Map sensorMap = sensorService.getSensorBySensorKey(string); units.add(sensorMap.get("unit").toString()); values.add((Number) map.remove(string)); } } else { Map sensorMap = sensorService.getSensorBySensorKey(string); units.add(sensorMap.get("unit").toString()); values.add((Number) map.remove(string)); } //values.add((Number) map.remove(string)); } map.put("values", values); map.put("units", units); } return new ResultBean>>(list); } @GetMapping("getWeather") @ApiOperation(value = "获取天气信息", notes = "获取天气信息") @ApiImplicitParams(value = { @ApiImplicitParam(name = "organizationId", defaultValue = "5", value = "登录账号的组织id", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "time", value = "时间,天(格式:2018-03-06)", required = true, paramType = "query", dataType = "String"), }) public ResultBean> getWeather(HttpServletRequest request) throws Exception { Map parameters = getParametersStartingWith(request, null); Map map = weatherService.get15DayWeatherDataByRegion(parameters); Map tempMap = TempAllocationUtils.tempAllocation(map); return new ResultBean>(tempMap); } @GetMapping("/uavTrajectory") @ApiOperation(value = "显示无人机飞行轨迹", notes = "显示无人机飞行轨迹") @ApiImplicitParams(value = { @ApiImplicitParam(name = "mac", value = "设备mac(格式:p5dnd7a0392068)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "startTime", value = "开始时间(格式:2019-07-17-17)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "endTime", value = "结束时间(格式:2019-07-17-18)", required = true, paramType = "query", dataType = "String") }) public ModelAndView uavTrajectory(ModelAndView model, HttpServletRequest request) throws Exception { Map parameters = WebUtils.getParametersStartingWith(request, null); String st = parameters.get("startTime").toString(); String startYearAndDay = st.substring(0, st.lastIndexOf("-")); String startHour = st.substring(st.lastIndexOf("-") + 1); String startTime = startYearAndDay + " " + startHour + ":00:00"; String et = parameters.get("endTime").toString(); String endYearAndDay = et.substring(0, et.lastIndexOf("-")); String endHour = et.substring(et.lastIndexOf("-") + 1); int endHourValue = Integer.valueOf(endHour); int startHourValue = Integer.valueOf(startHour); if (endHourValue <= startHourValue) { endHourValue = startHourValue + 1; } String endTime = startYearAndDay + " " + endHourValue + ":00:00"; parameters.put("startTime", startTime); parameters.put("endTime", endTime); String mac = parameters.get("mac").toString(); if (mac != null && mac.length() != 0) { List>> sensorData = historyMinutelyService.getSensorData(parameters); Map sensorsMap = sensorService.getSensorsMap(parameters); List> sensorList = new ArrayList<>(); List> sensorListMin = new ArrayList<>(); List> sensorListMax = new ArrayList<>(); if (sensorData.size() == 3) { sensorList = sensorData.get(0); sensorListMin = sensorData.get(1); sensorListMax = sensorData.get(2); } JSONObject params = new JSONObject(); params.put("sensorInfo", sensorList); params.put("sensorInfoMin", sensorListMin); params.put("sensorInfoMax", sensorListMax); params.put("sensorsMap", sensorsMap); String paramsJson = params.toJSONString(); model.addObject("uavTrajectoryParams", paramsJson); model.setViewName("uavtrajectory"); return model; } else { StringBuilder msg = new StringBuilder(); msg.append(" param[0] mac:"); msg.append(mac); log.warn(msg); model.setViewName("403"); return model; } } @GetMapping("/pollutionSource") @ApiOperation(value = "污染传播来源", notes = "污染传播来源") @ApiImplicitParams(value = { @ApiImplicitParam(name = "mac", value = "设备mac地址(如:898607b0101730392251)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "sensorKey", value = "查询的监测因子的key(格式:e1)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "time", value = "查询时间(格式:2019-09-01-10)", required = true, paramType = "query", dataType = "String")}) public ModelAndView pollutionSource(ModelAndView model, HttpServletRequest request) throws Exception { Map parameters = WebUtils.getParametersStartingWith(request, null); String timeStr = parameters.get("time").toString(); String yearAndDay = timeStr.substring(0, timeStr.lastIndexOf("-")); String Hour = timeStr.substring(timeStr.lastIndexOf("-") + 1); String time = yearAndDay + " " + Hour + ":00:00"; DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime timeLocalDateTime = LocalDateTime.parse(time, dateTimeFormatter); int month = timeLocalDateTime.getMonth().getValue(); parameters.put("yearAndDay", yearAndDay); Point dirPoint = historyHourlyService.getDirPoint(parameters); Map getPollutionSourceData = historyHourlyService.getPollutionSourceDataByHour(parameters); if (MapUtils.isEmpty(getPollutionSourceData)) { getPollutionSourceData = historyHourlyService.getPollutionSourceDataAll(parameters); } if (MapUtils.isEmpty(getPollutionSourceData)) { getPollutionSourceData = new HashMap<>(); } String mac = parameters.get("mac").toString(); Device device = deviceService.getDeviceByMac(mac, false); JSONObject params = new JSONObject(); params.put("device", device); params.put("month", month); params.put("dirPoint", dirPoint); params.put("getPollutionSourceData", getPollutionSourceData); String paramsJson = params.toJSONString(); model.addObject("pollutionSourceParams", paramsJson); model.setViewName("pollutionsource"); return model; } @GetMapping("getAirQualityComparison") @ApiOperation(value = "空气质量对比", notes = "空气质量对比") @ApiImplicitParams(value = { @ApiImplicitParam(name = "organizationId", defaultValue = "5", value = "登录账号的组织id", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "monitor_point_id", defaultValue = "5", value = "监控站点id", required = true, paramType = "query", dataType = "String")}) public ResultBean> getAirQualityComparison(HttpServletRequest request) throws Exception { Map parameters = getParametersStartingWith(request, null); Map map = weatherService.getWeatherDataByRegion(parameters); Map sensorMap = new HashMap<>(); sensorMap.put("e1", Double.parseDouble(map.get("pm25").toString())); sensorMap.put("e2", Double.parseDouble(map.get("pm10").toString())); sensorMap.put("e11", Double.parseDouble(map.get("so2").toString())); sensorMap.put("e16", Double.parseDouble(map.get("no2").toString())); sensorMap.put("e10", Double.parseDouble(map.get("co").toString())); sensorMap.put("e15", Double.parseDouble(map.get("o3").toString())); Map StateControl = AQICalculation.hourlyAQI(sensorMap); Map hourAqi = historyService.gitHourlyAQIByMonitorPointIdAndTimeslot(parameters); Map returnMap = new HashMap<>(); returnMap.put("MonitorPointAQI", hourAqi.get("AQI")); returnMap.put("StateControlAQI", StateControl.get("AQI")); return new ResultBean>(returnMap); } @GetMapping("mointorPointRank") @ApiOperation(value = "获取站点排名", notes = "获取站点排名") @ApiImplicitParams(value = { @ApiImplicitParam(name = "accountId", value = "账号id", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "sensor", value = "因子", required = true, paramType = "query", dataType = "String") }) public ResultBean>> getMointorPointRank(HttpServletRequest request) { Map parameters = WebUtils.getParametersStartingWith(request, null); String id = parameters.get("accountId").toString(); String sensor = parameters.get("sensor").toString(); Map account = accountService.getOrganizationIdByAccountId(id); //通过组织id来获取站点和设备信息 account.put("sensor", sensor); List> rankList = historyService.getMointorPointRankByOrganizationId(account); List> returnList = new ArrayList<>(); for (Map map : rankList) { boolean contains = map.containsKey("sensor"); if (contains) { returnList.add(map); } } return new ResultBean>>(returnList); } @GetMapping("/carTrajectory") @ApiOperation(value = "显示走航车轨迹", notes = "显示走航车轨迹") @ApiImplicitParams(value = { @ApiImplicitParam(name = "mac", value = "设备mac(格式:p5dnd7a0392081)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "startTime", value = "开始时间(格式:2020-03-19-14)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "endTime", value = "结束时间(格式:2020-03-19-17)", required = true, paramType = "query", dataType = "String") }) public ModelAndView carTrajectory(ModelAndView model, HttpServletRequest request) throws Exception { Map parameters = WebUtils.getParametersStartingWith(request, null); String st = parameters.get("startTime").toString(); String startYearAndDay = st.substring(0, st.lastIndexOf("-")); String startHour = st.substring(st.lastIndexOf("-") + 1); String startTime = startYearAndDay + " " + startHour + ":00:00"; String et = parameters.get("endTime").toString(); String endYearAndDay = et.substring(0, st.lastIndexOf("-")); String endHour = et.substring(et.lastIndexOf("-") + 1); String endTime = endYearAndDay + " " + endHour + ":00:00"; /* int endHourValue = Integer.valueOf(endHour); int startHourValue = Integer.valueOf(startHour); if (endHourValue <= startHourValue) { endHourValue = startHourValue + 1; } String endTime = startYearAndDay + " " + endHourValue + ":00:00";*/ parameters.put("startTime", startTime); parameters.put("endTime", endTime); String mac = parameters.get("mac").toString(); if (mac != null && mac.length() != 0) { List>> sensorData = historyService.getCarSensorData(parameters); Map sensorsMap = sensorService.getSensorsMap(parameters); List> sensorList = new ArrayList<>(); if (sensorData.size() == 3) { sensorList = sensorData.get(0); } JSONObject params = new JSONObject(); params.put("sensorInfo", sensorList); params.put("sensorsMap", sensorsMap); String paramsJson = params.toJSONString(); //System.out.println(paramsJson); model.addObject("carTrajectoryParams", paramsJson); model.setViewName("cartrajectory"); return model; } else { StringBuilder msg = new StringBuilder(); msg.append(" param[0] mac:"); msg.append(mac); log.warn(msg); model.setViewName("403"); return model; } } @GetMapping("/carTrajectoryNew") @ApiOperation(value = "显示走航车轨迹", notes = "显示走航车轨迹") @ApiImplicitParams(value = { @ApiImplicitParam(name = "mac", value = "设备mac(格式:p5dnd7a0392081)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "startTime", value = "开始时间(格式:2020-03-19-14)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "endTime", value = "结束时间(格式:2020-03-19-17)", required = true, paramType = "query", dataType = "String") }) public ModelAndView carTrajectoryNew(ModelAndView model, HttpServletRequest request) throws Exception { Map parameters = WebUtils.getParametersStartingWith(request, null); String st = parameters.get("startTime").toString(); String startYearAndDay = st.substring(0, st.lastIndexOf("-")); String startHour = st.substring(st.lastIndexOf("-") + 1); String startTime = startYearAndDay + " " + startHour + ":00:00"; String et = parameters.get("endTime").toString(); String endYearAndDay = et.substring(0, st.lastIndexOf("-")); String endHour = et.substring(et.lastIndexOf("-") + 1); String endTime = endYearAndDay + " " + endHour + ":00:00"; parameters.put("startTime", startTime); parameters.put("endTime", endTime); String mac = parameters.get("mac").toString(); if (mac != null && mac.length() != 0) { List>> sensorData = historyService.getCarSensorData(parameters); Map sensorsMap = sensorService.getSensorsMap(parameters); List> sensorList = new ArrayList<>(); if (sensorData.size() == 3) { sensorList = sensorData.get(0); } JSONObject params = new JSONObject(); params.put("sensorInfo", sensorList); params.put("sensorsMap", sensorsMap); String paramsJson = params.toJSONString(); model.addObject("carTrajectoryParams", paramsJson); model.setViewName("cartrajectoryNew"); return model; } else { StringBuilder msg = new StringBuilder(); msg.append(" param[0] mac:"); msg.append(mac); log.warn(msg); model.setViewName("403"); return model; } } @GetMapping("/trajectoryDataShow") @ApiOperation(value = "轨迹及数据", notes = "轨迹及数据") @ApiImplicitParams(value = { @ApiImplicitParam(name = "mac", value = "设备mac(格式:p5dnd7a0392081)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "startTime", value = "开始时间(格式:2020-03-19-14)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "endTime", value = "结束时间(格式:2020-03-19-17)", required = true, paramType = "query", dataType = "String") }) public ModelAndView trajectoryDataShow(ModelAndView model, HttpServletRequest request) throws Exception { Map parameters = WebUtils.getParametersStartingWith(request, null); String st = parameters.get("startTime").toString(); String startYearAndDay = st.substring(0, st.lastIndexOf("-")); String startHour = st.substring(st.lastIndexOf("-") + 1); String startTime = startYearAndDay + " " + startHour + ":00:00"; String et = parameters.get("endTime").toString(); String endHour = et.substring(et.lastIndexOf("-") + 1); int endHourValue = Integer.valueOf(endHour); int startHourValue = Integer.valueOf(startHour); if (endHourValue <= startHourValue) { endHourValue = startHourValue + 1; } String endTime = startYearAndDay + " " + endHourValue + ":00:00"; parameters.put("startTime", startTime); parameters.put("endTime", endTime); String mac = parameters.get("mac").toString(); if (mac != null && mac.length() != 0) { List>> sensorData = historyService.getCarSensorData(parameters); Map sensorsMap = sensorService.getSensorsMap(parameters); List> sensorList = new ArrayList<>(); if (sensorData.size() == 3) { sensorList = sensorData.get(0); } JSONObject params = new JSONObject(); params.put("sensorInfo", sensorList); params.put("sensorsMap", sensorsMap); String paramsJson = params.toJSONString(); model.addObject("trajectoryParams", paramsJson); model.setViewName("trajectorydatashow"); return model; } else { StringBuilder msg = new StringBuilder(); msg.append(" param[0] mac:"); msg.append(mac); log.warn(msg); model.setViewName("403"); return model; } } @GetMapping("device-excel") @ApiOperation(value = "获取设备数据报表", notes = "获取设备数据报表") @ApiImplicitParams(value = { @ApiImplicitParam(name = "sensorKey", value = "传感器key", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "organizationId", defaultValue = "8", value = "登录账号的组织id", required = true, paramType = "query", dataType = "Integer"), @ApiImplicitParam(name = "regionCode", defaultValue = "320583", value = "区域码", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "time", value = "时间(格式:2020-04-09或2019-04)", required = true, paramType = "query", dataType = "String")}) public ResultBean>> getDevicesDataToExcel(HttpServletRequest request) throws Exception { Map parameters = WebUtils.getParametersStartingWith(request, null); ParameterUtils.getTimeType4Time(parameters); Object sensorKey = parameters.get("sensorKey"); parameters.put("sensorKeys", Arrays.asList(sensorKey)); List macList = new ArrayList<>(); List monitorPoints = monitorPointService.getMonitorPointsAndDevicesByRegion(parameters); for (MonitorPoint m : monitorPoints) { for (Device d : m.getDevices()) { macList.add(d.getMac()); } } parameters.put("macs", macList); List> list = new ArrayList<>(); if (!CollectionUtils.isEmpty(macList)) { list = historyMinutelyService.getDevicesAvgDataToExcel(parameters); } return new ResultBean>>(list); } @RequestMapping(value = "/newMap-page", method = RequestMethod.GET) public ModelAndView newMap(ModelAndView model, @RequestParam("areaCode") long code, @RequestParam("accountId") int accountId) { Account account = accountService.getAccountById(accountId); List monitorPointList = monitorPointService.getMonitorPointListByAccountId(accountId); String regionName = areaService.queryFullNameByCode(code); if (account != null && regionName != null) { Object sensors = sensorService.queryAll(); JSONObject params = new JSONObject(); params.put("regionCode", code); params.put("regionName", regionName); params.put("accountId", accountId); params.put("orgId", account.getOrganizationId()); params.put("sensors", sensors); String paramsJson = params.toJSONString(); model.addObject("mapParams", paramsJson); model.setViewName("newmap"); return model; } else { StringBuilder msg = new StringBuilder(); msg.append(" param[0] areaCode:"); msg.append(code); msg.append(" param[0] accountId:"); msg.append(accountId); log.warn(msg); model.setViewName("403"); return model; } } @GetMapping("/uavDroppoint") @ApiOperation(value = "无人机落点应用", notes = "无人机落点应用") @ApiImplicitParams(value = { @ApiImplicitParam(name = "mac", value = "设备mac(格式:p5dnd7a0392068)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "sensorKey", value = "传感器key", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "startTime", value = "开始时间(格式:2019-07-17-17)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "endTime", value = "结束时间(格式:2019-07-17-18)", required = true, paramType = "query", dataType = "String") }) public ModelAndView uavDroppoint(ModelAndView model, HttpServletRequest request) throws Exception { Map parameters = WebUtils.getParametersStartingWith(request, null); String st = parameters.get("startTime").toString(); String startYearAndDay = st.substring(0, st.lastIndexOf("-")); String startHour = st.substring(st.lastIndexOf("-") + 1); String startTime = startYearAndDay + " " + startHour + ":00:00"; String et = parameters.get("endTime").toString(); String endHour = et.substring(et.lastIndexOf("-") + 1); int endHourValue = Integer.valueOf(endHour); int startHourValue = Integer.valueOf(startHour); if (endHourValue <= startHourValue) { endHourValue = startHourValue + 1; } String endTime = startYearAndDay + " " + endHourValue + ":00:00"; parameters.put("startTime", startTime); parameters.put("endTime", endTime); String mac = parameters.get("mac").toString(); if (mac != null && mac.length() != 0) { List> sensorData = historyService.getUavSensorData(parameters); Map sensorsMap = sensorService.getSensorsMap(parameters); JSONObject params = new JSONObject(); params.put("sensorInfo", sensorData); params.put("sensorsMap", sensorsMap); params.put("sensorKey", parameters.get("sensorKey")); params.put("unit", parameters.get("unit")); params.put("description", parameters.get("description")); String paramsJson = params.toJSONString(); model.addObject("uavDroppointParams", paramsJson); model.setViewName("uavdroppoint"); return model; } else { StringBuilder msg = new StringBuilder(); msg.append(" param[0] mac:"); msg.append(mac); log.warn(msg); model.setViewName("403"); return model; } } @GetMapping("/uavChannel") @ApiOperation(value = "无人机污染源通道应用", notes = "无人机污染源通道应用") @ApiImplicitParams(value = { @ApiImplicitParam(name = "mac", value = "设备mac(格式:p5dnd7a0392068)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "sensorKey", value = "传感器key", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "startTime", value = "开始时间(格式:2019-07-17-17)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "endTime", value = "结束时间(格式:2019-07-17-18)", required = true, paramType = "query", dataType = "String") }) public ModelAndView uavChannel(ModelAndView model, HttpServletRequest request) throws Exception { Map parameters = WebUtils.getParametersStartingWith(request, null); String st = parameters.get("startTime").toString(); String startYearAndDay = st.substring(0, st.lastIndexOf("-")); String startHour = st.substring(st.lastIndexOf("-") + 1); String startTime = startYearAndDay + " " + startHour + ":00:00"; String et = parameters.get("endTime").toString(); String endHour = et.substring(et.lastIndexOf("-") + 1); int endHourValue = Integer.valueOf(endHour); int startHourValue = Integer.valueOf(startHour); if (endHourValue <= startHourValue) { endHourValue = startHourValue + 1; } String endTime = startYearAndDay + " " + endHourValue + ":00:00"; parameters.put("startTime", startTime); parameters.put("endTime", endTime); String mac = parameters.get("mac").toString(); if (mac != null && mac.length() != 0) { List> sensorData = historyService.getUavSensorData(parameters); Map sensorsMap = sensorService.getSensorsMap(parameters); JSONObject params = new JSONObject(); params.put("sensorInfo", sensorData); params.put("sensorsMap", sensorsMap); params.put("sensorKey", parameters.get("sensorKey")); params.put("unit", parameters.get("unit")); params.put("description", parameters.get("description")); String paramsJson = params.toJSONString(); model.addObject("uavChannelParams", paramsJson); model.setViewName("uavchannelnew"); return model; } else { StringBuilder msg = new StringBuilder(); msg.append(" param[0] mac:"); msg.append(mac); log.warn(msg); model.setViewName("403"); return model; } } @GetMapping("/uavTracing") @ApiOperation(value = "无人机溯源应用", notes = "无人机溯源应用") @ApiImplicitParams(value = { @ApiImplicitParam(name = "mac", value = "设备mac(格式:p5dnd7a0392068)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "sensorKey", value = "传感器key", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "startTime", value = "开始时间(格式:2019-07-17-17)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "endTime", value = "结束时间(格式:2019-07-17-18)", required = true, paramType = "query", dataType = "String") }) public ModelAndView uavTracing(ModelAndView model, HttpServletRequest request) throws Exception { Map parameters = WebUtils.getParametersStartingWith(request, null); String st = parameters.get("startTime").toString(); String startYearAndDay = st.substring(0, st.lastIndexOf("-")); String startHour = st.substring(st.lastIndexOf("-") + 1); String startTime = startYearAndDay + " " + startHour + ":00:00"; String et = parameters.get("endTime").toString(); String endHour = et.substring(et.lastIndexOf("-") + 1); int endHourValue = Integer.parseInt(endHour); int startHourValue = Integer.parseInt(startHour); if (endHourValue <= startHourValue) { endHourValue = startHourValue + 1; } String endTime = startYearAndDay + " " + endHourValue + ":00:00"; parameters.put("startTime", startTime); parameters.put("endTime", endTime); String mac = parameters.get("mac").toString(); if (mac != null && mac.length() != 0) { List> sensorData = historyService.getUavSensorData(parameters); Map sensorsMap = sensorService.getSensorsMap(parameters); JSONObject params = new JSONObject(); params.put("sensorInfo", sensorData); params.put("sensorsMap", sensorsMap); params.put("sensorKey", parameters.get("sensorKey")); params.put("unit", parameters.get("unit")); params.put("description", parameters.get("description")); String paramsJson = params.toJSONString(); model.addObject("uavTracingParams", paramsJson); model.setViewName("uavtracing"); return model; } else { StringBuilder msg = new StringBuilder(); msg.append(" param[0] mac:"); msg.append(mac); log.warn(msg); model.setViewName("403"); return model; } } @GetMapping("/purify") @ApiOperation(value = "获取厂区净化率", notes = "获取厂区净化率") @ApiImplicitParams(value = { @ApiImplicitParam(name = "monitorPointId", value = "公司Id", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "sensorKey", value = "因子", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "time", value = "时间(格式:2020-03-19-14)", required = true, paramType = "query", dataType = "String")}) public ModelAndView PurificationRate(HttpServletRequest request, ModelAndView model) { Map parameters = WebUtils.getParametersStartingWith(request, null); String monitPointIdS = (String) parameters.get("monitorPointId"); String sensor = (String) parameters.get("sensorKey"); String time = (String) parameters.get("time"); String YearAndDay = time.substring(0, time.lastIndexOf("-")); String Hour = time.substring(time.lastIndexOf("-") + 1); String Time = YearAndDay + " " + Hour + ":00:00"; int monitPointId = Integer.parseInt(monitPointIdS); JSONObject params = monitorPointService.getMonitorPointById(monitPointId, Time, 1, sensor); String paramsJson = params.toJSONString(); model.addObject("mapParams", paramsJson); model.setViewName("purityMap"); return model; } @GetMapping("/collection") @ApiOperation(value = "获取厂区收集率", notes = "获取厂区收集率") @ApiImplicitParams(value = { @ApiImplicitParam(name = "monitorPointId", value = "公司Id", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "time", value = "时间(格式:2020-03-19-14)", required = true, paramType = "query", dataType = "String")}) public ModelAndView collectionRate(HttpServletRequest request, ModelAndView model) { Map parameters = WebUtils.getParametersStartingWith(request, null); String monitPointIdS = (String) parameters.get("monitorPointId"); String sensor = ""; String time = (String) parameters.get("time"); String YearAndDay = time.substring(0, time.lastIndexOf("-")); String Hour = time.substring(time.lastIndexOf("-") + 1); String Time = YearAndDay + " " + Hour + ":00:00"; int monitPointId = Integer.parseInt(monitPointIdS); //获取公司信息 JSONObject params = monitorPointService.getMonitorPointById(monitPointId, Time, 2, sensor); model.addObject("params", params); model.setViewName("pressureMap"); return model; } @GetMapping("/unorganizedEmissions") @ApiOperation(value = "无组织排放", notes = "无组织排放") @ApiImplicitParams(value = { @ApiImplicitParam(name = "monitorPointId", value = "公司Id", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "sensorKey", value = "因子", required = true, paramType = "query", dataType = "String"), // @ApiImplicitParam(name = "sensorKey", value = "传感器key,如有多个用逗号分隔", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "time", value = "时间(格式:2020-03-19-14)", required = true, paramType = "query", dataType = "String")}) public ModelAndView unorganizedEmissions(HttpServletRequest request, ModelAndView model) { Map parameters = WebUtils.getParametersStartingWith(request, null); String monitPointIdS = (String) parameters.get("monitorPointId"); String sensor = (String) parameters.get("sensorKey"); String time = (String) parameters.get("time"); String YearAndDay = time.substring(0, time.lastIndexOf("-")); String Hour = time.substring(time.lastIndexOf("-") + 1); String Time = YearAndDay + " " + Hour + ":00:00"; int monitPointId = Integer.parseInt(monitPointIdS); //获取公司信息 JSONObject params = monitorPointService.getMonitorPointById(monitPointId, Time, 3, sensor); model.addObject("params", params); model.setViewName("unorganizedMap"); return model; } @GetMapping("/unorganizedEmissionsRealTime") @ApiOperation(value = "无组织排放实时", notes = "无组织排放实时") @ApiImplicitParams(value = { @ApiImplicitParam(name = "monitorPointId", value = "公司Id", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "sensorKey", value = "因子", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "accountId", value = "用户id", required = false, paramType = "query", dataType = "String")}) public ModelAndView unorganizedEmissionsBackups(HttpServletRequest request, ModelAndView model) { Map parameters = WebUtils.getParametersStartingWith(request, null); String monitPointIdS = (String) parameters.get("monitorPointId"); String sensor = (String) parameters.get("sensorKey"); String accountId = (String) parameters.get("accountId"); Account account = accountService.getAccountById(Integer.parseInt(accountId)); int monitPointId = Integer.parseInt(monitPointIdS); JSONObject params = monitorPointService.getMacList(monitPointId); params.put("accountId", accountId); params.put("orgId", account.getOrganizationId()); params.put("sensor", sensor); //获取公司信息 //JSONObject params=monitorPointService.getMonitorPointById(monitPointId,Time,3,sensor); // model.addObject("params",params); model.addObject("params", params); model.setViewName("newUnorganizedMap"); return model; } @GetMapping("/chooseDevice") @ResponseBody public Object unorganizedEmissionsBackups(String wind, String monitPointId) { JSONObject params = new JSONObject(); Double windDir = Double.parseDouble(wind); List deviceList = deviceService.getDeviceById2(Integer.parseInt(monitPointId)); Map longAndLatiMap; List longAndLatiList = new ArrayList<>();//经纬度夹角集合,存放的是windList中两台设备的下标和两台设备夹角与风向角的差值 List preAngleDeviceList = new ArrayList(); //角度减去风向最小的两台设备 for (int f = 0; f < deviceList.size(); f++) { for (int h = 0; h < deviceList.size(); h++) { if (f != h) { longAndLatiMap = new HashMap(); longAndLatiMap.put("h", h); longAndLatiMap.put("f", f); Double angle = mapUtils.getAngle( new MyLatLng((Double) deviceList.get(h).getLongitude(), (Double) deviceList.get(h).getLatitude()), new MyLatLng((Double) deviceList.get(f).getLongitude(), (Double) deviceList.get(f).getLatitude())); Double angleDiff = Math.abs(angle - windDir); longAndLatiMap.put("angle", angleDiff); longAndLatiList.add(longAndLatiMap); } } } Double minAngle = (Double) longAndLatiList.get(0).get("angle"); int indexAngle = 0; for (int j = 1; j < longAndLatiList.size(); j++) { if (minAngle > (Double) longAndLatiList.get(j).get("angle")) { minAngle = (Double) longAndLatiList.get(j).get("angle"); indexAngle = j; } else { indexAngle = indexAngle; } } preAngleDeviceList.add(deviceList.get((Integer) longAndLatiList.get(indexAngle).get("h"))); preAngleDeviceList.add(deviceList.get((Integer) longAndLatiList.get(indexAngle).get("f"))); Double length = mapUtils.getDistance((Double) preAngleDeviceList.get(0).getLongitude(), (Double) preAngleDeviceList.get(0).getLatitude(), (Double) preAngleDeviceList.get(1).getLongitude(), (Double) preAngleDeviceList.get(1).getLatitude()); Double subLength = length / 5; Double subLength1 = length / 6.1; Double angle = mapUtils.getAngle( new MyLatLng((Double) preAngleDeviceList.get(0).getLongitude(), (Double) preAngleDeviceList.get(0).getLatitude()), new MyLatLng((Double) preAngleDeviceList.get(1).getLongitude(), (Double) preAngleDeviceList.get(1).getLatitude())); List locationList = new ArrayList(); String[] firstLocation = mapUtils.calLocationByDistanceAndLocationAndDirection(angle, (Double) preAngleDeviceList.get(0).getLongitude(), (Double) preAngleDeviceList.get(0).getLatitude(), subLength); String[] secondLoction = mapUtils.calLocationByDistanceAndLocationAndDirection(angle, Double.parseDouble(firstLocation[0]), Double.parseDouble(firstLocation[1]), subLength); String[] thirdLocation = mapUtils.calLocationByDistanceAndLocationAndDirection(angle, Double.parseDouble(secondLoction[0]), Double.parseDouble(secondLoction[1]), subLength); String[] fourthLoction = mapUtils.calLocationByDistanceAndLocationAndDirection(angle, Double.parseDouble(thirdLocation[0]), Double.parseDouble(thirdLocation[1]), subLength); String[] fivethLoction = mapUtils.calLocationByDistanceAndLocationAndDirection(angle, Double.parseDouble(fourthLoction[0]), Double.parseDouble(fourthLoction[1]), subLength1); locationList.add(firstLocation); locationList.add(secondLoction); locationList.add(thirdLocation); locationList.add(fourthLoction); locationList.add(fivethLoction); String preAngleDeviceString = JSON.toJSON(preAngleDeviceList).toString(); params.put("preAngleDeviceString", preAngleDeviceString);//两台添加箭头的设备 params.put("locationList", locationList); return params; } @GetMapping("/allDevice") @ResponseBody public Map getAllDevice() { List macList = deviceService.getAllMac(); Map latlngMap = new HashMap(); Map devMap = null; List list = new ArrayList(); for (String mac : macList) { devMap = new HashMap(); if (mac != null) { Device device = deviceService.byMacGetDevice(mac); List list1 = LatLngTransformation.Convert_BD09_To_GCJ02(device.getLatitude(), device.getLongitude()); if (device.getState() != 4 + "") { devMap.put("state", device.getState()); } devMap.put("lat", list1.get(1)); devMap.put("lng", list1.get(0)); devMap.put("monitorPointId", device.getMonitorPointId()); //System.out.println(device); list.add(devMap); } else { continue; } } latlngMap.put("latlng", list); return latlngMap; } @GetMapping("/windAndDeviceData") @ResponseBody public List windAndDeviceData(String monitorPointId) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.MINUTE, (calendar.get(Calendar.MINUTE) - 2)); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); //String time = df.format(calendar.getTime()) + ":00"; int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; String mon; if (month < 10) { mon = "0" + month; } else { mon = "" + month; } String table = "history_five_minutely_" + year + mon; List list = deviceService.byMonitorIdGetDeviceAndWind(monitorPointId, table); return list; } //局部风场 @GetMapping("/windAndDeviceDataByArea") @ResponseBody public List windAndDeviceDataByArea(String monitorPointId) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.MINUTE, (calendar.get(Calendar.MINUTE) - 2)); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); String time = df.format(calendar.getTime()) + ":00"; int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; String mon; if (month < 10) { mon = "0" + month; } else { mon = "" + month; } String table = "history_five_minutely_" + year + mon; List list = deviceService.byMonitorIdGetDeviceAndWindSpecial(monitorPointId, table); return list; } @GetMapping("forecastO3") @ApiOperation(value = "预测和实际臭氧对比", notes = "预测和实际臭氧对比") @ApiImplicitParams(value = { @ApiImplicitParam(name = "monitorPointId", defaultValue = "1", value = "监控站id", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "time", value = "时间(格式:2020-03-19)", required = true, paramType = "query", dataType = "String")}) public ResultBean>> getWeatherNextDayDataByRegion(HttpServletRequest request) throws Exception { Map parameters = getParametersStartingWith(request, null); List sensorKeys = new ArrayList<>(); sensorKeys.add("e15"); parameters.put("sensorKeys", sensorKeys); List> resultList = weatherService.getForecastAndReal(parameters); return new ResultBean>>(resultList); } @GetMapping("forecastPM") @ApiOperation(value = "预测和实测颗粒物对比", notes = "预测和实测颗粒物对比") @ApiImplicitParams(value = { @ApiImplicitParam(name = "monitorPointId", defaultValue = "1", value = "监控站id", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "time", value = "时间(格式:2020-03-19)", required = true, paramType = "query", dataType = "String")}) public ResultBean>> getForecastAndRealPM(HttpServletRequest request) throws Exception { Map parameters = getParametersStartingWith(request, null); List sensorKeys = new ArrayList<>(); sensorKeys.add("e1"); sensorKeys.add("e2"); parameters.put("sensorKeys", sensorKeys); List> resultList = weatherService.getForecastAndReal(parameters); return new ResultBean>>(resultList); } @GetMapping("weatherData") @ApiOperation(value = "根据city查询小时预测和实测数据", notes = "根据city查询小时预测和实测数据") @ApiImplicitParams(value = { @ApiImplicitParam(name = "city", value = "城市名", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "time", value = "时间(格式:2020-03-19)", required = true, paramType = "query", dataType = "String")}) public ResultBean>> getWeatherData(HttpServletRequest request) throws Exception { Map parameters = getParametersStartingWith(request, null); List> weatherList = weatherService.getWeatherData(parameters); return new ResultBean>>(weatherList); } @GetMapping("weatherDataDay") @ApiOperation(value = "根据city查询日实测数据", notes = "根据city查询日实测数据") @ApiImplicitParams(value = { @ApiImplicitParam(name = "city", value = "城市名", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "time", value = "时间(格式:2020-03-19)", required = true, paramType = "query", dataType = "String")}) public ResultBean>> getWeatherDataByDay(HttpServletRequest request) throws Exception { Map parameters = getParametersStartingWith(request, null); List> weatherList = weatherService.getWeatherDataByDay(parameters); return new ResultBean>>(weatherList); } @GetMapping("monitorDeviceData") @ApiOperation(value = "获取微型站5分钟和半小时数据", notes = "获取微型站5分钟和半小时数据") @ApiImplicitParams(value = { @ApiImplicitParam(name = "city", value = "城市名", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "time", value = "时间(格式:2020-03-15)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "type", value = "类型(5分钟:m,半小时:h)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "range", value = "要查看的设备范围(国控站周边:m,全城:a)", required = true, paramType = "query", dataType = "String")}) public ResultBean>> get5MinutesOrHalfHour(HttpServletRequest request) throws Exception { Map parameters = getParametersStartingWith(request, null); List> deviceData = historyMinutelyService.get5MinutesOrHalfHour(parameters); return new ResultBean>>(deviceData); } @PostMapping("updateForecastWeather") public void updateForecastWeather(HttpServletRequest request) { Map parameters = getParametersStartingWith(request, null); weatherService.updateForecastWeather(parameters); } @GetMapping("dataByTimeSlot") @ApiOperation(value = "根据时间类型获取因子的值", notes = "根据时间类型获取因子的值") @ApiImplicitParams(value = { @ApiImplicitParam(name = "mac", value = "mac地址", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "startTime", value = "起始时间(格式:2020-08-03/2020-08-03-13)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "endTime", value = "结束时间(格式:2020-08-04/2020-08-04-14)", required = true, paramType = "query", dataType = "String")}) public ResultBean>> getDataByTimeSlot(HttpServletRequest request) throws Exception { Map parameters = getParametersStartingWith(request, null); String mac = parameters.get("mac").toString(); String startTime = parameters.get("startTime").toString(); String endTime = parameters.get("endTime").toString(); //对时间进行操作的接口 Calendar calendar = getInstance(); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); List> list = new ArrayList(); Map device = deviceService.getAllFieldByMac(parameters); Map monitorPointMap = monitorPointService.selectAllById(device.get("monitor_point_id").toString()); List> device_sensorList = sensorService.getSensorByDeviceId(device.get("id").toString()); Map device_sensorUnit_map = new HashMap<>(); for (Map device_sensorMap : device_sensorList) { device_sensorUnit_map.put(device_sensorMap.get("sensor_key").toString(), device_sensorMap.get("unit")); } Map sensorMap = sensorService.getSensorsMap(parameters); if (startTime.length() == 10 && endTime.length() == 10) { //获取当日时间 Date dd = new Date(); //格式化 SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd"); //获取系统当前时间 String nowTime = sim.format(dd); int days = endTime.compareTo(nowTime); //System.out.println(days); List dayList = DatesUtil.findDaysStr(startTime, endTime); //System.out.println("dayList:"+dayList); /*if (days<0){ Date date=null; try { date = new SimpleDateFormat("yy-MM-dd").parse(endTime); } catch (ParseException e) { e.printStackTrace(); } calendar.setTime(date); int day=calendar.get(Calendar.DATE); calendar.set(Calendar.DATE,day+1); endTime=new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()); }*/ List> sameDayHourlyList = null; if (days >= 0) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //获取系统当前时间 String currentTime = df.format(dd); sameDayHourlyList = historyHourlyService.getDataByTimeSlot(mac, nowTime, currentTime); } List> dataList = historyDailyService.getDataByTimeSlot(mac, startTime, endTime); if (dataList.isEmpty()) { return null; } Set keys = sensorMap.keySet(); for (String key : keys) { Map oneSensorMap = new LinkedHashMap<>(); oneSensorMap.put("monitorPointName", monitorPointMap.get("name")); oneSensorMap.put("deviceName", device.get("name")); oneSensorMap.put("sersorKey", sensorMap.get(key) + "(" + device_sensorUnit_map.get(key) + ")"); for (String day : dayList) { for (Map dataMap : dataList) { JSONObject dataJson = JSONObject.parseObject(dataMap.get("json").toString()); if (dataMap.get("time").toString().equals(day + " 00:00:00.0")) { oneSensorMap.put(dataMap.get("time").toString().substring(0, 10), dataJson.getJSONArray(key).get(0)); break; } else { continue; } } if (!oneSensorMap.containsKey(day)) { oneSensorMap.put(day, ""); } } Double avg = 0.0; if (sameDayHourlyList != null) { for (Map sameDayHourlyMap : sameDayHourlyList) { List arr = new ArrayList<>(); JSONObject hourlyJson = JSONObject.parseObject(sameDayHourlyMap.get("json").toString()); arr.add(Double.parseDouble(hourlyJson.getJSONArray(key).get(0).toString())); Double sum = 0.0; for (int i = 0; i < arr.size(); i++) { sum += arr.get(i); } avg = sum / arr.size(); } oneSensorMap.put(nowTime, avg); } list.add(oneSensorMap); } } else if (startTime.length() == 13 && endTime.length() == 13) { StringBuilder startTime_sb = new StringBuilder(startTime); startTime_sb.replace(10, 11, " "); startTime = startTime_sb.toString() + ":00:00"; StringBuilder endTime_sb = new StringBuilder(endTime); endTime_sb.replace(10, 11, " "); endTime = endTime_sb.toString() + ":00:00"; List hoursList = DatesUtil.findHoursStr(startTime, endTime); //System.out.println("hoursList:"+hoursList); List> hourlyList = historyHourlyService.getDataByTimeSlot(mac, startTime, endTime); if (hourlyList.isEmpty()) { return null; } Set keys = sensorMap.keySet(); for (String key : keys) { Map oneSensorMap = new LinkedHashMap<>(); oneSensorMap.put("monitorPointName", monitorPointMap.get("name")); oneSensorMap.put("deviceName", device.get("name")); oneSensorMap.put("sersorKey", sensorMap.get(key) + "(" + device_sensorUnit_map.get(key) + ")"); for (String hour : hoursList) { for (Map hourlyMap : hourlyList) { JSONObject dataJson = JSONObject.parseObject(hourlyMap.get("json").toString()); if (hourlyMap.get("time").toString().equals(hour + ".0")) { if (dataJson.getJSONArray(key) != null) { oneSensorMap.put(hourlyMap.get("time").toString().substring(0, 19), dataJson.getJSONArray(key).get(0)); break; } } else { continue; } } if (!oneSensorMap.containsKey(hour)) { oneSensorMap.put(hour, ""); } } /*for (Map hourlyMap: hourlyList) { JSONObject hourlyJson = JSONObject.parseObject(hourlyMap.get("json").toString()); oneSensorMap.put(hourlyMap.get("time").toString().substring(0,19),hourlyJson.getJSONArray(key).get(2)); }*/ list.add(oneSensorMap); } } else { return null; } return new ResultBean>>(list); } @GetMapping("/contrastFactor") @ApiOperation(value = "因子对比", notes = "因子对比") @ApiImplicitParams(value = { @ApiImplicitParam(name = "mac", value = "设备mac", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "sensor", value = "因子", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "time", value = "时间(格式:2020-03-19、20、21)", required = true, paramType = "query", dataType = "String")}) public ResultBean>> contrastFactor(HttpServletRequest request) throws Exception { Map parameters = getParametersStartingWith(request, null); List list = historyHourlyService.getDataByMacAndTime(parameters); //System.out.println(list); return new ResultBean>>(list); } @GetMapping("/getAlarm") @ResponseBody public List getAlarm(@Param("windData") String windData, @Param("code") String code, @Param("mac") String mac, @Param("speedLevel") String speedLevel) { List alarmData = deviceRoadService.getAlarmData(windData, code, mac, speedLevel); return alarmData; } @GetMapping("multiDeviceContrast") @ApiOperation(value = "多设备因子对比", notes = "多设备因子对比") @ApiImplicitParams(value = { @ApiImplicitParam(name = "macs", value = "设备mac,如有多个用逗号分隔", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "sensorKey", value = "传感器key", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "time", value = "时间,日期(格式:2018-03-12)", required = true, paramType = "query", dataType = "String"),}) public ResultBean>> multiDeviceSensor(HttpServletRequest request) throws Exception { Map parameters = getParametersStartingWith(request, null); ParameterUtils.getTimeType4Time(parameters); List> list = historyMinutelyService.getMultiDeviceSensorData(parameters); return new ResultBean>>(list); } @PostMapping("/tellAlarm") @ResponseBody public List tellAlarm(String states, String orgId, String accountId, String states1, String regionCode) { JSONArray stateList = JSONArray.parseArray(states);//最新的设备数据 JSONArray stateList1 = JSONArray.parseArray(states1);//前10秒的设备数据 List lookList = new ArrayList<>(); Map params = new HashMap(); String lookString = ""; //判断前十秒数据和现在数据是否相等,如果不相等进入方法 //第一次进入接口前十秒数据为null if (stateList1 != null && !states.equals(states1)) { List listDevice = JSONObject.parseArray(stateList.toJSONString(), Map.class); List listDevice1 = JSONObject.parseArray(stateList1.toJSONString(), Map.class); //将所有设备放到同一个集合下 List deviceList = new ArrayList(); List deviceList1 = new ArrayList(); //存放所有组织的id List orgList = new ArrayList(); for (Map devices : listDevice) { int monitorId = Integer.parseInt((String) devices.get("id")); MonitorPoint monitorPoint = monitorPointService.byIdGetMonitorPoint(monitorId); int org_id = monitorPoint.getOrganizationId(); orgList.add(org_id); List devicesList = (List) devices.get("devices"); if (!devicesList.isEmpty()) { if (devicesList.size() > 1) { for (Map map : devicesList) { deviceList.add(map); } } else { deviceList.add((Map) ((List) devices.get("devices")).get(0)); } } } for (Map devices1 : listDevice1) { int monitorId = Integer.parseInt((String) devices1.get("id")); MonitorPoint monitorPoint = monitorPointService.byIdGetMonitorPoint(monitorId); int org_id = monitorPoint.getOrganizationId(); List devicesList = (List) devices1.get("devices"); if (!devicesList.isEmpty()) { if (devicesList.size() > 1) { for (Map map : devicesList) { deviceList1.add(map); } } else { deviceList1.add((Map) ((List) devices1.get("devices")).get(0)); } } } List macList = new ArrayList(); //获得两个时间的设备状态改变的mac号 for (Map map : deviceList) { String state = (String) map.get("state"); String mac = (String) map.get("mac"); for (Map map1 : deviceList1) { String state1 = (String) map1.get("state"); String mac1 = (String) map1.get("mac"); if (mac.equals(mac1)) { if (Integer.parseInt(state) > Integer.parseInt(state1) && Integer.parseInt(state) != 4 /*&& Integer.parseInt(state1) == 0*/) { macList.add(mac + "-" + state + "-" + state1); } } } } //存放不重合的数组 LinkedHashSet orgS = new LinkedHashSet(orgList); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(System.currentTimeMillis()); Date date1 = new Date(System.currentTimeMillis() - 1000); //系统当前时间 String time = formatter.format(date); //系统当前时间的前一秒 String time1 = formatter.format(date1); List alarmList = new ArrayList(); for (Integer org : orgS) { int orgNum = alarmConfigService.containOrgId(org); Map eMap = new HashMap(); if (orgNum == 1) { String alarmConfig = alarmConfigService.getValueByOrganizationId(Integer.parseInt(String.valueOf(org))); Map hashMap = JSON.parseObject(alarmConfig, HashMap.class); Map alarmLevels = (Map) hashMap.get("alarmLevels"); //数据库因子表只有106个因子 for (int i = 1; i < 106; i++) { if (alarmLevels.containsKey("e" + i)) { Map map = (Map) alarmLevels.get("e" + i); if (!map.isEmpty()) { Integer enable = (Integer) map.get("enable"); List increment = (List) map.get("increment"); if (enable == 1) { if (!(increment.get(0).toString().equals("0") && increment.get(1).toString().equals("0"))) { eMap.put("e" + i, increment); } else { continue; } } else { continue; } } } } } else { String defultAlarm = dictionaryDataService.getDefultAlarm(); Map hashMap = JSON.parseObject(defultAlarm, HashMap.class); Map alarmLevels = (Map) hashMap.get("alarmLevels"); //数据库因子表只有106个因子 for (int i = 1; i < 106; i++) { if (alarmLevels.containsKey("e" + i)) { Map map = (Map) alarmLevels.get("e" + i); if (!map.isEmpty()) { Integer enable = (Integer) map.get("enable"); List increment = (List) map.get("increment"); if (enable == 1) { if (!(increment.get(0).toString().equals("0") && increment.get(1).toString().equals("0"))) { eMap.put("e" + i, increment); } else { continue; } } else { continue; } } } } } Map map = new HashMap(); map.put("eMap", eMap); map.put("org", org); alarmList.add(map); } for (Map aEMap : alarmList) { List values = new ArrayList(); if (macList.size() > 0) { for (String sMac : macList) { String[] aMac = sMac.split("-"); String mac = aMac[0]; //因为数据库数据是两秒钟插入一条,所以通过两个时间区间获取一条数据,防止一个时间获取数据为空的情况 String value = historyService.getValueByMacAndTime(mac, time, time1); Map map = new HashMap(); if (value == null) { Date date2 = new Date(System.currentTimeMillis() - 2000); //系统当前时间的前两秒 String time2 = formatter.format(date1); value = historyService.getValueByMacAndTime(mac, time, time2); if (value == null) { Date date3 = new Date(System.currentTimeMillis() - 3000); //系统当前时间的前三秒 String time3 = formatter.format(date1); value = historyService.getValueByMacAndTime(mac, time, time3); } } if (value != null) { map.put("mac", mac); map.put("value", value); map.put("state", aMac[1]); map.put("state1", aMac[2]); values.add(map); } else { continue; } } } if (values.size() > 0 && values.size() == macList.size()) { for (Map dataMap : values) { String oId = deviceService.byMacGetOrgId((String) dataMap.get("mac")); if (!(aEMap.get("org").toString()).equals(oId)) { continue; } List list = new ArrayList(); Map sensorMap = JSONObject.parseObject((String) dataMap.get("value")); Iterator iter = sensorMap.keySet().iterator(); while (iter.hasNext()) { String key = iter.next(); list.add(key); } String state = (String) dataMap.get("state"); String state1 = (String) dataMap.get("state1"); List mapList = new ArrayList(); for (String key : list) { if (((Map) aEMap.get("eMap")).containsKey(key)) { Double val = Double.valueOf(sensorMap.get(key).toString()); List valueList = (List) ((Map) aEMap.get("eMap")).get(key); Device device = deviceService.byMacGetDevice((String) dataMap.get("mac")); Map sensors = sensorService.getSensorBySensorKey(key); if (key.equals("e1") || key.equals("e2") || key.equals("e10") || key.equals("e11") || key.equals("e15") || key.equals("e16")) { //判断六参因子超标 if ((state1.equals("0") || state1.equals("1")) && Integer.parseInt(state) > 1) { if (val > Double.valueOf(String.valueOf(valueList.get(1)))) { Map lookMap = new HashMap(); lookMap.put("time", time); lookMap.put("name", device.getName()); lookMap.put("sensor", sensors.get("description")); lookMap.put("value", val + "" + sensors.get("unit")); mapList.add(lookMap); //lookString = time+" "+device.getName()+sensors.get("description")+"="+val + sensors.get("unit")+"超标"; //System.out.println(time + "====" + device.getName() + "=====" + sensors.get("description") + "======" + val + sensors.get("unit")); } } } else {//判断非六参因子超标 if (state1.equals("0")) { if (val > Double.valueOf(String.valueOf(valueList.get(0)))) { Map lookMap = new HashMap(); lookMap.put("time", time); lookMap.put("name", device.getName()); lookMap.put("sensor", sensors.get("description")); lookMap.put("value", val + "" + sensors.get("unit")); mapList.add(lookMap); } } } } } if (mapList.size() > 0) { lookList.add(mapList); } else { continue; } } } } } return lookList; } /* @GetMapping("/lianxian") @ApiOperation(value = "连线", notes = "连线" ) @GetMapping("multiDeviceContrast") @ApiOperation(value = "多设备因子对比", notes = "多设备因子对比") @ApiImplicitParams(value = { @ApiImplicitParam(name = "macs", value = "设备mac,如有多个用逗号分隔", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "sensorKey", value = "传感器key", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "time", value = "时间,日期(格式:2018-03-12)", required = true, paramType = "query", dataType = "String"),}) public ResultBean>> multiDeviceSensor(HttpServletRequest request) throws Exception { Map parameters = getParametersStartingWith(request, null); ParameterUtils.getTimeType4Time(parameters); List> list = historyMinutelyService.getMultiDeviceSensorData(parameters); return new ResultBean>>(list); } /* * 根据大屏版本号获取版本更新信息 */ @GetMapping("screenVersion") public Map getScreenVersion(HttpServletRequest request) { Map parameters = getParametersStartingWith(request, null); String version = parameters.get("version").toString(); return screenVersionService.getScreenVersion(version); } @GetMapping("allDeviceExcel") @ApiOperation(value = "所有设备多因子数据报表", notes = "所有设备多因子数据报表") @ApiImplicitParams(value = { @ApiImplicitParam(name = "monitorPoint", value = "监控站点id", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "sensorKey", value = "传感器key,多个逗号隔开", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "startTime", value = "起始时间(格式:2020-08-03)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "endTime", value = "结束时间(格式:2020-08-04)", required = false, paramType = "query", dataType = "String")}) public ResultBean>> getAllDeviceDataToExcel(HttpServletRequest request) throws Exception { Map parameters = WebUtils.getParametersStartingWith(request, null); List> list = historyMinutelyService.getAllDeviceDataToExcel(parameters); return new ResultBean>>(list); } /*@PostMapping("insertAdjustValue") @ApiOperation(value = "所有设备多因子数据报表", notes = "所有设备多因子数据报表") @ApiImplicitParams(value = { @ApiImplicitParam(name = "id", value = "设备id", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "time", value = "时间(格式08:30:00)", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "dataArray", value = "公式", required = false, paramType = "query", dataType = "String")}) public void insertAdjustValue(HttpServletRequest request) throws Exception { Map parameters = WebUtils.getParametersStartingWith(request, null); int device_id = Integer.parseInt(parameters.get("id").toString()); String hour_minute_second = parameters.get("time").toString(); String[] arr = hour_minute_second.split(":"); int seconds = Integer.parseInt(arr[0])*3600+Integer.parseInt(arr[1])*60+Integer.parseInt(arr[2]); String value = parameters.get("dataArray").toString(); deviceAdjustValueTimingService.insertData(device_id,seconds,value);; }*/ @PostMapping("insertAdjustValue") public int insertAdjustValue(@RequestBody HashMap map) { try { int device_id = Integer.parseInt(map.get("id").toString()); String time = map.get("time").toString(); String[] arr = time.split(":"); int seconds = Integer.parseInt(arr[0]) * 3600 + Integer.parseInt(arr[1]) * 60 + Integer.parseInt(arr[2]); //String t = URLEncoder.encode(参数,"UTF-8") List list = (List) map.get("dataArray"); String val = ""; for (int i = 0; i < list.size(); i++) { if (i == 0) { val = val + list.get(i); } else { val = val + "," + list.get(i); } } String value = "{" + val + "}"; deviceAdjustValueTimingService.insertData(device_id, seconds, value); return 1; } catch (Exception e) { log.warn(e); } return 0; } @RequestMapping("/biaozhun") @ResponseBody public List queryDevice(String macOrName) { List deviceList = new ArrayList<>(); if (!macOrName.equals("")) { deviceList = deviceService.getDevice(macOrName); } return deviceList; } @RequestMapping("/getBiaoZhun") @ResponseBody public List getBiaoZhun(String id) { List dataByDeviceid = deviceAdjustValueTimingService.getDataByDeviceid(Integer.parseInt(id)); for (DeviceAdjustValueTiming deviceAdjustValueTiming : dataByDeviceid) { int seconds = Integer.parseInt(deviceAdjustValueTiming.getSeconds()); String hour = String.valueOf(seconds / 3600); int millAndSeconds = seconds % 3600; String mill = String.valueOf(millAndSeconds / 60); String second = String.valueOf(millAndSeconds % 60); if (hour.length() < 2) { hour = "0" + hour; } if (mill.length() < 2) { mill = "0" + mill; } if (second.length() < 2) { second = "0" + second; } String time = hour + ":" + mill + ":" + second; Map value = deviceAdjustValueTiming.getValue(); Collection values = value.values(); deviceAdjustValueTiming.setSeconds(time); } return dataByDeviceid; } @RequestMapping("/getSensor") @ResponseBody public List> getSensor(String id) { List> allSensors = sensorService.getSensorByDeviceId(id); return allSensors; } @RequestMapping("/deleteBiaoZhun") @ResponseBody public int deleteBiaoZhun(String id) { int i = deviceAdjustValueTimingService.delete(id); return i; } @GetMapping("/monitorAVGData") @ApiOperation(value = "monitor平均数据导出", notes = "monitor平均数据导出") @ApiImplicitParams(value = { @ApiImplicitParam(name = "monitorPointIds", value = "多个monitorid", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "time", value = "时间(格式:2020-03-19)", required = true, paramType = "query", dataType = "String")}) public ResultBean>> monitorAVGData(HttpServletRequest request) throws Exception { Map parameters = getParametersStartingWith(request, null); String monitorPointIds = (String) parameters.get("monitorPointIds"); String time = (String) parameters.get("time"); time = time + " 00:00:00"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd mm:HH:ss");//注意月份是MM Date date = simpleDateFormat.parse(time); Calendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.add(calendar.DATE, +1); String date1 = simpleDateFormat.format(date); String date2 = simpleDateFormat.format(calendar.getTime()); String[] mIds = monitorPointIds.split(","); List>> lists = new ArrayList<>(); if (mIds.length == 1 && mIds.length != 0) { String mId = mIds[0]; List> dataAvbByMIdAndTime = historyHourlyService.getDataAvbByMIdAndTime(mId, date1, date2); Double maxO3 = Double.parseDouble(dataAvbByMIdAndTime.get(dataAvbByMIdAndTime.size() - 1).get("maxO3").toString()); Map dailyAvgData = new HashMap<>(); if (dataAvbByMIdAndTime.get(dataAvbByMIdAndTime.size() - 2).get("data") != "") { dailyAvgData = (Map) dataAvbByMIdAndTime.get(dataAvbByMIdAndTime.size() - 2).get("data"); dailyAvgData.put("maxO3_8h", new BigDecimal(maxO3).setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue()); } else { dailyAvgData = historyHourlyService.getAvgDataByMId(mId, date1, date2); if (dailyAvgData != null) { dailyAvgData.put("maxO3_8h", new BigDecimal(maxO3).setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue()); } else { dailyAvgData = new HashMap<>(); dailyAvgData.put("PM2_5", ""); dailyAvgData.put("NO2", ""); dailyAvgData.put("SO2", ""); dailyAvgData.put("PM10", ""); dailyAvgData.put("O3_day", ""); dailyAvgData.put("CO", ""); } } dataAvbByMIdAndTime.remove(dataAvbByMIdAndTime.size() - 1); dataAvbByMIdAndTime.remove(dataAvbByMIdAndTime.size() - 1); Map dayMap = new HashMap<>(); dayMap.put("data", dailyAvgData); dayMap.put("time", date1.substring(0, 11)); dataAvbByMIdAndTime.add(dayMap); for (int i = 0; i < dataAvbByMIdAndTime.size(); i++) { if (i != dataAvbByMIdAndTime.size() - 1) { Map map1 = AQICalculation2.hourlyAQI((Map) dataAvbByMIdAndTime.get(i).get("data")); if (Double.parseDouble(map1.get("AQI").toString()) > 50.0) { ((Map) dataAvbByMIdAndTime.get(i).get("data")).put("primary_pollutants", map1.get("maxSensor")); ((Map) dataAvbByMIdAndTime.get(i).get("data")).put("AQI", map1.get("AQI")); } else { ((Map) dataAvbByMIdAndTime.get(i).get("data")).put("primary_pollutants", "-"); ((Map) dataAvbByMIdAndTime.get(i).get("data")).put("AQI", map1.get("AQI")); } } else { Map map1 = AQICalculation2.dayAQI((Map) dataAvbByMIdAndTime.get(i).get("data")); if (map1.get("AQI").toString().equals("")) { break; } if (Double.parseDouble(map1.get("AQI").toString()) > 50.0) { ((Map) dataAvbByMIdAndTime.get(i).get("data")).put("primary_pollutants", map1.get("maxSensor")); ((Map) dataAvbByMIdAndTime.get(i).get("data")).put("AQI", map1.get("AQI")); } else { ((Map) dataAvbByMIdAndTime.get(i).get("data")).put("primary_pollutants", "-"); ((Map) dataAvbByMIdAndTime.get(i).get("data")).put("AQI", map1.get("AQI")); } } } List timeList = new ArrayList(); for (int q = 0; q < dataAvbByMIdAndTime.size(); q++) { timeList.add(dataAvbByMIdAndTime.get(q).get("time")); } if (dataAvbByMIdAndTime.size() < 25) { for (int j = 1; j < 25; j++) { Map map = null; for (int q = 0; q < dataAvbByMIdAndTime.size(); q++) { if (dataAvbByMIdAndTime.get(q).get("time").toString().length() > 2) { continue; } else { // System.out.println(Integer.parseInt(dataAvbByMIdAndTime.get(q).get("time").toString())+"==="+j); String sj = ""; if (j < 10) { sj = "0" + j; } else { if (j == 24) { sj = "00"; } else { sj = "" + j; } } if (!timeList.contains(sj)) { map = new HashMap<>(); map.put("time", sj); Map map1 = new HashMap(); map1.put("PM2_5", ""); map1.put("NO2", ""); map1.put("primary_pollutants", "-"); map1.put("SO2", ""); map1.put("O3", ""); map1.put("PM10", ""); map1.put("O3_8h", ""); map1.put("CO", ""); map1.put("AQI", ""); map.put("data", map1); dataAvbByMIdAndTime.add(map); break; } else { break; } } } } } /* for (int i1 = 0; i1 < dataAvbByMIdAndTime.size(); i1++) { System.out.println(dataAvbByMIdAndTime.get(i1)); }*/ Collections.sort(dataAvbByMIdAndTime, new Comparator>() { public int compare(Map o1, Map o2) { String name1 = (String) o1.get("time");//name1是从你list里面拿出来的一个 String name2 = (String) o2.get("time"); //name1是从你list里面拿出来的第二个name return name1.compareTo(name2); } }); Map map1 = dataAvbByMIdAndTime.get(0); dataAvbByMIdAndTime.remove(0); dataAvbByMIdAndTime.add(map1); for (int j = 0; j < dataAvbByMIdAndTime.size(); j++) { if (dataAvbByMIdAndTime.get(j).get("time").toString().length() > 2) { Map map2 = dataAvbByMIdAndTime.get(j); dataAvbByMIdAndTime.remove(j); dataAvbByMIdAndTime.add(map2); } } if (dataAvbByMIdAndTime.size() == 1) { dataAvbByMIdAndTime = null; } lists.add(dataAvbByMIdAndTime); //List devicesByMonitorPointId = deviceService.getDevicesByMonitorPointId(Integer.valueOf(mId)); } else { for (int i = 0; i < mIds.length; i++) { List> dataAvbByMIdAndTime = historyHourlyService.getDataAvbByMIdAndTime(mIds[i], date1, date2); Double maxO3 = Double.parseDouble(dataAvbByMIdAndTime.get(dataAvbByMIdAndTime.size() - 1).get("maxO3").toString()); Map dailyAvgData = new HashMap<>(); if (dataAvbByMIdAndTime.get(dataAvbByMIdAndTime.size() - 2).get("data") != "") { dailyAvgData = (Map) dataAvbByMIdAndTime.get(dataAvbByMIdAndTime.size() - 2).get("data"); dailyAvgData.put("maxO3_8h", new BigDecimal(maxO3).setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue()); } else { dailyAvgData = historyHourlyService.getAvgDataByMId(mIds[i], date1, date2); if (dailyAvgData != null) { dailyAvgData.put("maxO3_8h", new BigDecimal(maxO3).setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue()); } else { dailyAvgData = new HashMap<>(); dailyAvgData.put("PM2_5", ""); dailyAvgData.put("NO2", ""); dailyAvgData.put("SO2", ""); dailyAvgData.put("PM10", ""); dailyAvgData.put("O3_day", ""); dailyAvgData.put("CO", ""); } } dataAvbByMIdAndTime.remove(dataAvbByMIdAndTime.size() - 1); dataAvbByMIdAndTime.remove(dataAvbByMIdAndTime.size() - 1); Map dayMap = new HashMap<>(); dayMap.put("data", dailyAvgData); dayMap.put("time", date1.substring(0, 11)); dataAvbByMIdAndTime.add(dayMap); List timeList = new ArrayList(); for (int q = 0; q < dataAvbByMIdAndTime.size(); q++) { timeList.add(dataAvbByMIdAndTime.get(q).get("time")); } if (dataAvbByMIdAndTime.size() < 25) { for (int j = 1; j < 25; j++) { Map map = null; for (int q = 0; q < dataAvbByMIdAndTime.size(); q++) { if (dataAvbByMIdAndTime.get(q).get("time").toString().length() > 2) { continue; } else { // System.out.println(Integer.parseInt(dataAvbByMIdAndTime.get(q).get("time").toString())+"==="+j); String sj = ""; if (j < 10) { sj = "0" + j; } else { if (j == 24) { sj = "00"; } else { sj = "" + j; } } if (!timeList.contains(sj)) { map = new HashMap<>(); map.put("time", sj); Map map1 = new HashMap(); map1.put("PM2_5", ""); map1.put("NO2", ""); map1.put("SO2", ""); map1.put("O3", ""); map1.put("PM10", ""); map1.put("O3_8h", ""); map1.put("CO", ""); map.put("data", map1); dataAvbByMIdAndTime.add(map); break; } else { break; } } } } } Collections.sort(dataAvbByMIdAndTime, new Comparator>() { public int compare(Map o1, Map o2) { String name1 = (String) o1.get("time");//name1是从你list里面拿出来的一个 String name2 = (String) o2.get("time"); //name1是从你list里面拿出来的第二个name return name1.compareTo(name2); } }); Map map1 = dataAvbByMIdAndTime.get(0); dataAvbByMIdAndTime.remove(0); dataAvbByMIdAndTime.add(map1); for (int j = 0; j < dataAvbByMIdAndTime.size(); j++) { if (dataAvbByMIdAndTime.get(j).get("time").toString().length() > 2) { Map map2 = dataAvbByMIdAndTime.get(j); dataAvbByMIdAndTime.remove(j); dataAvbByMIdAndTime.add(map2); } } lists.add(dataAvbByMIdAndTime); } List> dataByMonitorPoints = historyHourlyService.getDataByMonitorPoints(mIds, date1, date2); lists.add(dataByMonitorPoints); } List> rList = new ArrayList<>(); if (lists.size() == 1 && lists.get(0) != null) { for (int i = 0; i < lists.get(0).size(); i++) { List list = new ArrayList(); list.add(lists.get(0).get(i).get("data")); Map map = new HashMap(); map.put("data", list); map.put("time", lists.get(0).get(i).get("time")); rList.add(map); } } else if (lists.size() == 1 && lists.get(0) == null) { rList.add(null); } else { for (int j = 0; j < lists.get(0).size(); j++) { Map listMap = new HashMap(); List mapList = new ArrayList<>(); if (lists.get(0).size() == 1) { mapList.add(null); } else { mapList.add((Map) lists.get(0).get(j).get("data")); } for (int i = 1; i < lists.size(); i++) { if (lists.get(i).size() == 1) { mapList.add(null); listMap.put("data", mapList); } else { if (lists.get(0).get(j).get("time").equals(lists.get(i).get(j).get("time"))) { mapList.add((Map) lists.get(i).get(j).get("data")); } listMap.put("time", lists.get(0).get(j).get("time")); listMap.put("data", mapList); } } rList.add(listMap); } } return new ResultBean>>(rList); } @PostMapping("byAccountGetDevices") public List byAccountGetDevices(@RequestBody Map parameters) { String id =parameters.get("id").toString(); List devicesList = deviceService.getDevicesByAccountId(id); return devicesList; } @GetMapping("/unorganizedEmissionsFiveMinute") @ApiOperation(value = "无组织排放五分钟", notes = "无组织排放五分钟") @ApiImplicitParams(value = { @ApiImplicitParam(name = "monitorPointId", value = "公司Id", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "sensorKey", value = "因子", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "realTime", value = "实时", required = true, paramType = "query", dataType = "String"), @ApiImplicitParam(name = "accountId", value = "用户id", required = false, paramType = "query", dataType = "String")}) public ModelAndView unorganizedEmissionsBackupsV2(HttpServletRequest request, ModelAndView model) { Map parameters = WebUtils.getParametersStartingWith(request, null); String sensorKey = parameters.get("sensorKey").toString(); //第一步,获取污染源点 PollutionSourcePoint pollutionSourcePoint = pollutioSourcePointService.selectByMonitorPointId(539); //获取站点的所有设备 List deviceList = deviceService.getDevicesByMonitorPointId(539); //获取五分钟数据 Map pa = new HashMap<>(); //获取开始时间和结束时间 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar beforeTime = Calendar.getInstance(); Date newTime = beforeTime.getTime(); beforeTime.add(Calendar.MINUTE,-5); Date startTime = beforeTime.getTime(); beforeTime.add(Calendar.MINUTE,6); Date endTime = beforeTime.getTime(); //pa.put("sensorKey","e1"); pa.put("yearAndMonth",sdf.format(newTime).substring(0,7).replace("-","")); pa.put("startTime",startTime); pa.put("endTime",endTime); List macs = new ArrayList<>(); List sensorKeys = new ArrayList<>(); for (Device device:deviceList) { macs.add(device.getMac()); } sensorKeys.add(sensorKey); sensorKeys.add("e18"); sensorKeys.add("e23"); pa.put("macs",macs); pa.put("sensorKeys",sensorKeys); pa.put("macNumber",macs.size()); List> fiveMinuteDataList = historyFiveMinutelyService.getFiveMinutesDataByMacsAndTimeSolt(pa); //声明数组,存放所有设备的数值 double[] allDeviceData = new double[fiveMinuteDataList.size()]; int i = 0; //计算风向 List> windList = new ArrayList<>(); for (Map map:fiveMinuteDataList) { String[] wind_speed = map.get("e18").toString().split(","); if (!map.containsKey("e23")){ continue; } String[] wind_direction = map.get("e23").toString().split(","); Map windMap = new HashMap<>(); windMap.put("wind_speed",wind_speed[0].substring(1,wind_speed[0].length())); windMap.put("wind_direction",wind_direction[0].substring(1,wind_direction[0].length())); windList.add(windMap); String[] sensorArr = map.get(sensorKey).toString().split(","); double sensorData = Double.parseDouble(sensorArr[0].substring(1,sensorArr[0].length())); allDeviceData[i] = sensorData; i = i+1; } //计算平均风向和风速 Map res = WindUtils.getWind_direction_speed(windList); //计算该站点的点与污染源点的角度 Map angleMap = new HashMap(); MyLatLng pollutionSourcePoint_log_lat = new MyLatLng(pollutionSourcePoint.getLongitude(),pollutionSourcePoint.getLatitude()); for (Device device:deviceList) { MyLatLng device_log_lat = new MyLatLng(device.getLongitude(),device.getLatitude()); //以设备为坐标原点,与污染源连线的角度 double angle = mapUtils.getAngle(device_log_lat,pollutionSourcePoint_log_lat); angleMap.put(device.getMac(),angle); } Map disparityMap = new HashMap<>(); for (String key:angleMap.keySet()) { double angleDisparity = Math.abs(angleMap.get(key)-res.get("wind_direction")); if (angleDisparity>180){ angleDisparity = 360-angleDisparity; } disparityMap.put(key,angleDisparity); } Optional> minDisparity = disparityMap.entrySet() .stream() .min(Map.Entry.comparingByValue()); //留下的任务:循环disparityMap,查出与minDisparity相等的值的key,以防出现两个点的角度差一样 List minAngleDisparityMacList = new ArrayList<>(); for (String key:disparityMap.keySet()) { if (disparityMap.get(key) == minDisparity.get().getValue()){ minAngleDisparityMacList.add(minDisparity.get().getKey()); } } //定义一个map,存放设备点 Map fiveMinuteDataMap = new HashMap(); if (minAngleDisparityMacList.size()<2){//只有一个点 for (Map fiveMinuteData:fiveMinuteDataList) { if (fiveMinuteData.get("mac").toString().equals(minAngleDisparityMacList.get(0))){ fiveMinuteDataMap.putAll(fiveMinuteData); break; } } }else { } Device referenceDevice = new Device(); for (Device device:deviceList) { if (device.getMac().equals(fiveMinuteDataMap.get("mac"))){ referenceDevice = device; } } //计算污染平均值 double sum = 0; for (int j=0;j center = new HashMap<>(); center.put("lng",120.997119); center.put("lat",31.451714); //存放各个点位经纬度及数值 List> numericalValueList = new ArrayList<>(); Map numericalValueMap = new HashMap<>(); numericalValueMap.put("lng",120.997119); numericalValueMap.put("lat",31.451714); numericalValueMap.put("count",0.027); numericalValueList.add(numericalValueMap); Map numericalValueMap2 = new HashMap<>(); numericalValueMap2.put("lng",120.99516); numericalValueMap2.put("lat",31.448664); numericalValueMap2.put("count",0.029); numericalValueList.add(numericalValueMap2); Map numericalValueMap3 = new HashMap<>(); numericalValueMap3.put("lng",120.998538); numericalValueMap3.put("lat",31.449289); numericalValueMap3.put("count",0.033); numericalValueList.add(numericalValueMap3); Map numericalValueMap4 = new HashMap<>(); numericalValueMap4.put("lng",120.998628); numericalValueMap4.put("lat",31.452027); numericalValueMap4.put("count",0.025); numericalValueList.add(numericalValueMap4); Map numericalValueMap5 = new HashMap<>(); numericalValueMap5.put("lng",121.000383); numericalValueMap5.put("lat",31.451469); numericalValueMap5.put("count",0.05); numericalValueList.add(numericalValueMap5); Map numericalValueMap6 = new HashMap<>(); numericalValueMap6.put("lng",120.999908); numericalValueMap6.put("lat",31.449389); numericalValueMap6.put("count",0.04); numericalValueList.add(numericalValueMap6); Map numericalValueMap7 = new HashMap<>(); numericalValueMap7.put("lng",120.998519); numericalValueMap7.put("lat",31.450588); numericalValueMap7.put("count",0.10); numericalValueList.add(numericalValueMap7); JSONObject params = new JSONObject(); params.put("accountId",190); params.put("level",17); params.put("center",center); params.put("points",numericalValueList); //获取公司信息 //JSONObject params=monitorPointService.getMonitorPointById(monitPointId,Time,3,sensor); // model.addObject("params",params); model.addObject("params", params); model.setViewName("unorganizedMapV2"); return model; } }