瀏覽代碼

地图首页接口错误修复,查询天气信息

zhj 1 年之前
父節點
當前提交
13f0f1b043

+ 6 - 0
pom.xml

@@ -143,6 +143,12 @@
             <version>20230227</version>
         </dependency>
 
+        <dependency>
+            <groupId>co.ipdata.client</groupId>
+            <artifactId>ipdata-java-client</artifactId>
+            <version>0.2.0</version>
+        </dependency>
+
         <dependency>
             <groupId>org.gavaghan</groupId>
             <artifactId>geodesy</artifactId>

+ 45 - 0
src/main/java/com/welampiot/controller/DataController.java

@@ -6,8 +6,10 @@ import com.welampiot.dto.*;
 import com.welampiot.service.*;
 import com.welampiot.utils.ExcelUtil;
 import com.welampiot.utils.ToolUtils;
+import com.welampiot.utils.WeatherUtil;
 import com.welampiot.utils.WebUtils;
 import com.welampiot.vo.*;
+import io.ipdata.client.model.IpdataModel;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.CrossOrigin;
@@ -50,6 +52,8 @@ public class DataController {
     private LampInfoCacheByDayService lampInfoCacheByDayService;
     @Autowired
     private SectionCacheByDayService sectionCacheByDayService;
+    @Autowired
+    private GlobalLocationService globalLocationService;
 
     @RequestMapping(value = "/info",method = RequestMethod.POST)
     public BaseResult<InfoResponseVO> info(HttpServletRequest request){
@@ -655,4 +659,45 @@ public class DataController {
         lampInfoCacheByDayVO.setPath(path);
         return toolUtils.response(InterfaceResultEnum.OPERATION_SUCCESS,version,lampInfoCacheByDayVO);
     }
+
+    /**
+     * 获取天气信息
+     */
+    @RequestMapping(value = "/getWeatherInfo", method = RequestMethod.POST)
+    public BaseResult<?> getWeatherInfo(LocationVO locationVO) {
+        Integer version = locationVO.getVersion();
+        double longitude = 0, latitude = 0;
+        if (locationVO.getSectionId() != null && locationVO.getSectionId() != 0) {
+            GlobalLocationDTO globalLocationDTO = globalLocationService.getLocationBySectionId(locationVO.getSectionId());
+            if (globalLocationDTO != null) {
+                longitude = globalLocationDTO.getLongitude();
+                latitude = globalLocationDTO.getLatitude();
+            }
+        } else if (locationVO.getAreaId() != null) {
+            GlobalLocationDTO dto = globalLocationService.getGlobalLocationDTOById(locationVO.getAreaId(), version);
+            if (dto != null) {
+                longitude = dto.getLongitude();
+                latitude = dto.getLatitude();
+            }
+        } else if (locationVO.getCityId() != null) {
+            GlobalLocationDTO dto = globalLocationService.getGlobalLocationDTOById(locationVO.getCityId(), version);
+            if (dto != null) {
+                longitude = dto.getLongitude();
+                latitude = dto.getLatitude();
+            }
+        } else if (locationVO.getProvinceId() != null) {
+            GlobalLocationDTO dto = globalLocationService.getGlobalLocationDTOById(locationVO.getProvinceId(), version);
+            if (dto != null) {
+                longitude = dto.getLongitude();
+                latitude = dto.getLatitude();
+            }
+        } else {
+            IpdataModel ipDataModel = ToolUtils.getIpDataModel(ToolUtils.getPublicIp());
+            latitude = ipDataModel.latitude();
+            longitude = ipDataModel.longitude();
+        }
+
+        WeatherDTO weatherInfo = WeatherUtil.getTodayWeatherInfo(String.valueOf(longitude), String.valueOf(latitude));
+        return toolUtils.response(InterfaceResultEnum.OPERATION_SUCCESS, version, weatherInfo);
+    }
 }

+ 5 - 3
src/main/java/com/welampiot/controller/MapController.java

@@ -2258,6 +2258,7 @@ public class MapController{
     public BaseResult<?> newData(HttpServletRequest request){
         Integer version = (Integer) toolUtils.getRequestContent(request,"version",1);
         String type = (String) toolUtils.getRequestContent(request,"type",2);
+        String username = (String) toolUtils.getRequestContent(request,"username",2);
         Integer isJuhe = (Integer) toolUtils.getRequestContent(request,"isJuhe",1);
         Integer deviceType = (Integer) toolUtils.getRequestContent(request,"deviceType",1);
         Integer carType = (Integer) toolUtils.getRequestContent(request,"carType",1);
@@ -2277,10 +2278,11 @@ public class MapController{
         List sectionList = toolUtils.getSectionList(request);
         mapDataVO.setSectionList(sectionList);
 
+        UserDTO userDTO = userService.queryUserIdByUsername(username);
         // 路灯
-        String[] split = toolUtils.getUser().getPrivilege().split(",");
+        String[] split = userDTO.getPrivilegeList().split(",");
         List<String> strings = Arrays.asList(split);
-        Integer role = toolUtils.getUser().getRole();
+        Integer role = userDTO.getRole();
         ListResponseVO listResponseVO = new ListResponseVO();
         List<Object> objects = new ArrayList<>();
         List dTypeArr = Arrays.asList(dType.split(","));
@@ -2373,7 +2375,7 @@ public class MapController{
         }
 
 
-
+        listResponseVO.setLampTotal(objects.size());
         listResponseVO.setList(objects);
         return toolUtils.response(InterfaceResultEnum.OPERATION_SUCCESS,version,listResponseVO);
     }

+ 1 - 0
src/main/java/com/welampiot/dao/GlobalLocationDao.java

@@ -52,4 +52,5 @@ public interface GlobalLocationDao {
     GlobalLocationDTO getDataByDto(GlobalLocationDTO dto);
     List<GlobalLocationDTO> getAreaList(GlobalLocationDTO dto);
     GlobalLocationDTO getTimeZoneData(SectionDTO dto);
+    GlobalLocationDTO getLocationBySectionId(@Param("sectionId") Integer sectionId);
 }

+ 1 - 0
src/main/java/com/welampiot/dto/WeatherDTO.java

@@ -30,5 +30,6 @@ public class WeatherDTO {
     private String sunrise; // 日出时间
     private String sunset; // 日落时间
     private String weatherText;
+    private String weatherInfo;
     private String weatherCode;
 }

+ 1 - 0
src/main/java/com/welampiot/service/GlobalLocationService.java

@@ -37,4 +37,5 @@ public interface GlobalLocationService {
     GlobalLocationDTO getDataByDto(GlobalLocationDTO dto);
     List<GlobalLocationDTO> getAreaList(GlobalLocationDTO dto);
     GlobalLocationDTO getTimeZoneData(SectionDTO dto);
+    GlobalLocationDTO getLocationBySectionId(Integer sectionId);
 }

+ 5 - 0
src/main/java/com/welampiot/service/impl/GlobalLocationServiceImpl.java

@@ -252,4 +252,9 @@ public class GlobalLocationServiceImpl implements GlobalLocationService {
     public GlobalLocationDTO getTimeZoneData(SectionDTO dto){
         return globalLocationDao.getTimeZoneData(dto);
     }
+
+    @Override
+    public GlobalLocationDTO getLocationBySectionId(Integer sectionId) {
+        return globalLocationDao.getLocationBySectionId(sectionId);
+    }
 }

+ 90 - 5
src/main/java/com/welampiot/utils/ToolUtils.java

@@ -14,6 +14,10 @@ import com.welampiot.dto.*;
 import com.welampiot.handle.MqttHandler;
 import com.welampiot.service.*;
 import com.welampiot.vo.DevEnumVO;
+import io.ipdata.client.Ipdata;
+import io.ipdata.client.error.IpdataException;
+import io.ipdata.client.model.IpdataModel;
+import io.ipdata.client.service.IpdataService;
 import org.apache.commons.httpclient.HttpClient;
 import org.apache.commons.httpclient.methods.PostMethod;
 import org.eclipse.paho.client.mqttv3.MqttClient;
@@ -28,18 +32,18 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
 import org.springframework.web.multipart.MultipartFile;
 
 import javax.servlet.http.HttpServletRequest;
 import java.io.*;
 import java.lang.reflect.Field;
-import java.net.HttpURLConnection;
-import java.net.InetAddress;
-import java.net.URL;
-import java.net.URLConnection;
+import java.net.*;
 import java.text.DecimalFormat;
 import java.text.SimpleDateFormat;
 import java.util.*;
+import java.util.concurrent.TimeUnit;
 import java.util.regex.Pattern;
 import java.util.stream.Collectors;
 import java.util.zip.CRC32;
@@ -2169,7 +2173,7 @@ System.out.println(res);
      */
     public boolean openCloseLoop(String sn, String deviceId, Integer status) {
         String sendTopic = "/gateway/commandIn/" + sn;
-        String backTopic = "gateway/commandOut/" + sn;
+        String backTopic = "/gateway/commandOut/" + sn;
 
         if (status == 0) { // 这里0是闭合
             status = 1; // 发MQTT消息里面1就是开
@@ -2206,4 +2210,85 @@ System.out.println(res);
         int err = (int) dataJson.get("err");
         return err != 1;
     }
+
+    /**
+     * 获取本机IP地址
+     * @return 本机IP地址
+     */
+    public static String getIpAddress() throws UnknownHostException {
+        InetAddress localHost = InetAddress.getLocalHost();
+        return localHost.getHostAddress();
+    }
+
+    /**
+     * 获取请求IP地址
+     */
+    public static String getPostIpAddress() {
+        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
+        if (attributes == null) return null;
+
+        HttpServletRequest request = attributes.getRequest();
+        // 从请求头部获取客户端IP地址
+        String clientIp = request.getHeader("X-Forwarded-For");
+        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
+            clientIp = request.getHeader("X-Real-IP");
+        }
+        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
+            clientIp = request.getRemoteAddr();
+        }
+        return clientIp;
+    }
+
+    /**
+     * 获取IP数据
+     */
+    public static IpdataModel getIpDataModel(String ipAddress) {
+        try {
+            URL url = new URL("https://api.ipdata.co");
+            IpdataService ipdataService = Ipdata.builder().url( url)
+                    .withCache()
+                    .timeout(30, TimeUnit.MINUTES)
+                    .maxSize(8 * 1024)
+                    .registerCacheConfig()
+                    .key("ca96d4ab11053ad63f4a7dbcf7cb8751394a0772abafdaa5d509ac55")
+                    .get();
+            return ipdataService.ipdata(ipAddress);
+        } catch (MalformedURLException | IpdataException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /**
+     * 获取公网IP
+     * @return 公网IP
+     */
+    public static String getPublicIp() {
+        try {
+            URL url = new URL("https://api.ipify.org?format=json");
+            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+            conn.setRequestMethod("GET");
+
+            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
+            String inputLine;
+            StringBuilder response = new StringBuilder();
+            while ((inputLine = in.readLine()) != null) {
+                response.append(inputLine);
+            }
+            in.close();
+
+            // 从API的响应中解析出IP地址
+            String publicIp = response.toString().replaceAll("[{}\"]","");
+            // 去除多余的字符
+            publicIp = publicIp.split(":")[1];
+            // 取出IP地址部分
+            return publicIp;
+        } catch (IOException e) {
+            e.printStackTrace();
+            return null;
+        }
+    }
+
+    public static void main(String[] args) {
+        System.out.println(getPublicIp());
+    }
 }

+ 35 - 6
src/main/java/com/welampiot/utils/WeatherUtil.java

@@ -37,9 +37,8 @@ public class WeatherUtil {
      * @param longitude 经度
      * @param latitude 纬度
      * @return 返回天气信息
-     * @throws Exception 异常
      */
-    public static WeatherDTO getNowWeatherInfo(String longitude, String latitude) throws Exception {
+    public static WeatherDTO getNowWeatherInfo(String longitude, String latitude) {
         // 实时天气
         String url = "https://devapi.qweather.com/v7/weather/now?location=" + longitude + "," + latitude +
                 "&key=2dca03c7d95c442ba8fbce9d7a96db78";
@@ -96,14 +95,43 @@ public class WeatherUtil {
         return weatherDTO;
     }
 
+    /**
+     * 获取当天天气,日出日落时间
+     * @param longitude 经度
+     * @param latitude 纬度
+     * @return 返回天气信息
+     */
+    public static WeatherDTO getTodayWeatherInfo(String longitude, String latitude) {
+        String url = "https://devapi.qweather.com/v7/weather/3d?location=" + longitude + "," + latitude +
+                "&key=2dca03c7d95c442ba8fbce9d7a96db78";
+
+        RestTemplate restTemplate = new RestTemplate();
+        byte[] oResult = restTemplate.exchange(url, HttpMethod.GET, null, byte[].class).getBody();
+        String unGZipResult = unGZip(oResult);
+
+        JSONObject jsonObject = new JSONObject(unGZipResult);
+        JSONArray dailyArray = jsonObject.getJSONArray("daily");
+        JSONObject object = dailyArray.getJSONObject(0);
+        String sunrise = object.getString("sunrise");
+        String sunset = object.getString("sunset");
+        String iconDay = object.getString("iconDay");
+        String textDay = object.getString("textDay");
+
+        WeatherDTO weatherDTO = new WeatherDTO();
+        weatherDTO.setSunrise(sunrise);
+        weatherDTO.setSunset(sunset);
+        weatherDTO.setWeatherCode(iconDay);
+        weatherDTO.setWeatherInfo(textDay);
+        return weatherDTO;
+    }
+
     /**
      * 获取最近7天气信息
      * @param longitude 经度
      * @param latitude 纬度
      * @return 返回天气信息
-     * @throws Exception 异常
      */
-    public static List<WeatherDTO> getNearWeatherInfo(String longitude, String latitude) throws Exception {
+    public static List<WeatherDTO> getNearWeatherInfo(String longitude, String latitude) {
         // 实时天气
         String url = "https://devapi.qweather.com/v7/weather/now?location=" + longitude + "," + latitude +
                 "&key=2dca03c7d95c442ba8fbce9d7a96db78";
@@ -152,7 +180,7 @@ public class WeatherUtil {
         return weatherList;
     }
 
-    public static String unGZip(byte[] oResult) throws Exception {
+    public static String unGZip(byte[] oResult) {
         try (InputStream inputStream = new ByteArrayInputStream(oResult);
              ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
              GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream)) {
@@ -163,7 +191,8 @@ public class WeatherUtil {
             }
             return new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
         } catch (IOException e) {
-            throw new Exception(e);
+            e.printStackTrace();
+            return null;
         }
     }
 

+ 1 - 0
src/main/java/com/welampiot/vo/ListResponseVO.java

@@ -8,4 +8,5 @@ import java.util.List;
 public class ListResponseVO {
     private List list;
     private Integer total;
+    private Integer lampTotal;
 }

+ 13 - 0
src/main/java/com/welampiot/vo/LocationVO.java

@@ -0,0 +1,13 @@
+package com.welampiot.vo;
+
+import lombok.Data;
+
+@Data
+public class LocationVO {
+    private Integer sectionId;
+    private Integer areaId;
+    private Integer cityId;
+    private Integer provinceId;
+    private Integer version;
+    private String username;
+}

+ 7 - 7
src/main/resources/mapper/EnvmonitorMapper.xml

@@ -636,28 +636,28 @@
             </foreach>
         </if>
         <if test="keyword != null and !keyword.isEmpty()">
-            and E.number like "%#{keyword}%"
+            and E.number like '%${keyword}%'
         </if>
         <choose>
             <when test="!lngLow.isEmpty() and !lngHigh.isEmpty() and Double.parseDouble(lngLow) > Double.parseDouble(lngHigh)">
-                and ((L.longitude >= #{lngLow} and L.longitude &lt;= 180) or (L.longitude &lt;= #{lngLow} and L.longitude >= -180))
+                and ((E.longitude >= #{lngLow} and E.longitude &lt;= 180) or (E.longitude &lt;= #{lngLow} and E.longitude >= -180))
             </when>
             <otherwise>
                 <if test="!lngLow.isEmpty()">
-                    and L.longitude >= #{lngLow}
+                    and E.longitude >= #{lngLow}
                 </if>
                 <if test="!lngHigh.isEmpty()">
-                    and L.longitude &lt;= #{lngHigh}
+                    and E.longitude &lt;= #{lngHigh}
                 </if>
             </otherwise>
         </choose>
         <if test="!latLow.isEmpty()">
-            and L.latitude >= #{latLow}
+            and E.latitude >= #{latLow}
         </if>
         <if test="!latHigh.isEmpty()">
-            and L.latitude &lt;= #{latHigh}
+            and E.latitude &lt;= #{latHigh}
         </if>
-        group by L.id
+        group by E.id
     </select>
 
     <select id="getOneEnvmonitor" parameterType="HashMap" resultType="EnvmonitorDTO">

+ 9 - 2
src/main/resources/mapper/GlobalLocationMapper.xml

@@ -19,10 +19,17 @@
     </select>
 
     <select id="getListByPid" resultType="com.welampiot.dto.GlobalLocationDTO" parameterType="Integer">
-        select id,chinese_name chineseName
+        select id,chinese_name chineseName,longitude,latitude
         from global_location where pid = #{pid}
     </select>
 
+    <select id="getLocationBySectionId" resultType="com.welampiot.dto.GlobalLocationDTO">
+        select g.id,g.chinese_name as chineseName,g.longitude,g.latitude
+        from global_location g
+        left join section s on s.pid = g.id
+        where s.id = #{sectionId}
+    </select>
+
     <select id="getListByPidList" resultType="com.welampiot.dto.GlobalLocationDTO" parameterType="java.util.List">
         select id,chinese_name chineseName
         from global_location where 1=1
@@ -94,7 +101,7 @@
 
     <select id="getGlobalLocationDTOById" resultType="com.welampiot.dto.GlobalLocationDTO">
         select
-            g.id,g.pid
+            g.id,g.pid,g.longitude,g.latitude
         <choose>
             <when test="version == 0">
                 ,g.chinese_name as `name`

+ 7 - 7
src/main/resources/mapper/LampMapper.xml

@@ -1095,7 +1095,7 @@
             </foreach>
         </if>
         <if test="keyword != null and !keyword.isEmpty()">
-            and L.number like "%#{keyword}%"
+            and L.number like '%${keyword}%'
         </if>
         <choose>
             <when test="!lngLow.isEmpty() and !lngHigh.isEmpty() and Double.parseDouble(lngLow) > Double.parseDouble(lngHigh)">
@@ -1131,26 +1131,26 @@
             </foreach>
         </if>
         <if test="keyword != null and !keyword.isEmpty()">
-            and L.number like "%#{keyword}%"
+            and L.number like '%${keyword}%'
         </if>
         <choose>
             <when test="!lngLow.isEmpty() and !lngHigh.isEmpty() and Double.parseDouble(lngLow) > Double.parseDouble(lngHigh)">
-                and ((L.longitude >= #{lngLow} and L.longitude &lt;= 180) or (L.longitude &lt;= #{lngLow} and L.longitude >= -180))
+                and ((L.longitude <![CDATA[ >= ]]> #{lngLow} and L.longitude <![CDATA[ <= ]]> 180) or (L.longitude <![CDATA[ <= ]]> #{lngLow} and L.longitude <![CDATA[ >= ]]> -180))
             </when>
             <otherwise>
                 <if test="!lngLow.isEmpty()">
-                    and L.longitude >= #{lngLow}
+                    and L.longitude <![CDATA[ >= ]]> #{lngLow}
                 </if>
                 <if test="!lngHigh.isEmpty()">
-                    and L.longitude &lt;= #{lngHigh}
+                    and L.longitude <![CDATA[ <= ]]> #{lngHigh}
                 </if>
             </otherwise>
         </choose>
         <if test="!latLow.isEmpty()">
-            and L.latitude >= #{latLow}
+            and L.latitude <![CDATA[ >= ]]> #{latLow}
         </if>
         <if test="!latHigh.isEmpty()">
-            and L.latitude &lt;= #{latHigh}
+            and L.latitude <![CDATA[ <= ]]> #{latHigh}
         </if>
         group by L.id
     </select>

+ 1 - 1
src/main/resources/mapper/UserMapper.xml

@@ -214,7 +214,7 @@
     </select>
 
     <select id="queryUserIdByUsername" resultType="UserDTO">
-        select u.id,u.role
+        select u.id,u.role,u.privilege_list as privilegeList
         from user u
         where u.username = #{username}
     </select>