chenyi406 4 rokov pred
rodič
commit
90e4c28b1a

+ 11 - 17
src/main/java/com/zy/bms/config/mqtt/MqttCallbackHandler.java

@@ -7,7 +7,6 @@ import com.zy.bms.model.*;
 import com.zy.bms.redis.DeviceManager;
 import com.zy.bms.redis.DeviceManager;
 import com.zy.bms.service.*;
 import com.zy.bms.service.*;
 import com.zy.bms.utils.*;
 import com.zy.bms.utils.*;
-import com.zy.bms.utils.CodeGenerator;
 import com.zy.bms.utils.CoordTransformUtil;
 import com.zy.bms.utils.CoordTransformUtil;
 import com.zy.bms.utils.GaoDeApiUtil;
 import com.zy.bms.utils.GaoDeApiUtil;
 import com.zy.bms.websocket.WebSocketServer;
 import com.zy.bms.websocket.WebSocketServer;
@@ -33,8 +32,6 @@ public class MqttCallbackHandler {
     @Resource
     @Resource
     private DeviceLocationService deviceLocationService;
     private DeviceLocationService deviceLocationService;
     @Resource
     @Resource
-    private GaoDeApiUtil gaoDeApiService;
-    @Resource
     private DeviceManager deviceRedisService;
     private DeviceManager deviceRedisService;
     @Resource
     @Resource
     private WebSocketServer webSocketServer;
     private WebSocketServer webSocketServer;
@@ -58,13 +55,13 @@ public class MqttCallbackHandler {
         //根据报文标识代码 M 处理消息
         //根据报文标识代码 M 处理消息
         switch (msgObject.getM()) {
         switch (msgObject.getM()) {
             case Constant.M_CODE_REGISTER://设备端注册报文
             case Constant.M_CODE_REGISTER://设备端注册报文
-                registerDevice(msgObject);
+                registerDeviceHandler(msgObject);
                 break;
                 break;
             case Constant.M_CODE_UPLOAD_LOCATION:// 设备位置信息上报
             case Constant.M_CODE_UPLOAD_LOCATION:// 设备位置信息上报
-                LocationHandler(msgObject);
+                uploadLocationHandler(msgObject);
                 break;
                 break;
             case Constant.M_CODE_UPLOAD_CALL_RECORD://设备上传通话记录
             case Constant.M_CODE_UPLOAD_CALL_RECORD://设备上传通话记录
-                CallRecordsHandler(msgObject);
+                uploadCallRecordsHandler(msgObject);
                 break;
                 break;
         }
         }
     }
     }
@@ -72,7 +69,7 @@ public class MqttCallbackHandler {
     /**
     /**
      * 注册设备
      * 注册设备
      */
      */
-    private void registerDevice(MqttMsgDto obj) {
+    private void registerDeviceHandler(MqttMsgDto obj) {
         String num = obj.getString("num");
         String num = obj.getString("num");
         //查询数据库中是否有此设备
         //查询数据库中是否有此设备
         Device device = deviceService.getByNum(num);
         Device device = deviceService.getByNum(num);
@@ -81,16 +78,16 @@ public class MqttCallbackHandler {
             device = createDevice(num);
             device = createDevice(num);
         }
         }
         //发送消息
         //发送消息
-        setToDeviceService.returnCodeToDevice(device.getNum(), device.getClientId(), device.getPassword());
+        setToDeviceService.returnCodeToDevice(device);
     }
     }
 
 
     /**
     /**
      * 处理上传位置
      * 处理上传位置
      */
      */
-    private void LocationHandler(MqttMsgDto msg) {
+    private void uploadLocationHandler(MqttMsgDto msg) {
         DeviceLocation location = MqttMsgToLocation(msg);
         DeviceLocation location = MqttMsgToLocation(msg);
         // 逆地理位置解析
         // 逆地理位置解析
-        location.setSite(gaoDeApiService.regeo(location.getLonGcj(), location.getLatGcj()));
+        location.setSite(GaoDeApiUtil.regeo(location.getLonGcj(), location.getLatGcj()));
         // 保存位置信息--历史记录
         // 保存位置信息--历史记录
         deviceLocationService.save(location);
         deviceLocationService.save(location);
         // 将最新位置信息保存至redis中
         // 将最新位置信息保存至redis中
@@ -100,7 +97,7 @@ public class MqttCallbackHandler {
     /**
     /**
      * 设备上传通话记录
      * 设备上传通话记录
      */
      */
-    private void CallRecordsHandler(MqttMsgDto obj) {
+    private void uploadCallRecordsHandler(MqttMsgDto obj) {
         CallRecords callRecords = new CallRecords();
         CallRecords callRecords = new CallRecords();
         callRecords.setDeviceId(obj.getR().split("/")[1]);
         callRecords.setDeviceId(obj.getR().split("/")[1]);
         callRecords.setCallType(obj.getInt("type"));
         callRecords.setCallType(obj.getInt("type"));
@@ -119,12 +116,9 @@ public class MqttCallbackHandler {
     private Device createDevice(String num) {
     private Device createDevice(String num) {
         Device device = new Device();
         Device device = new Device();
         device.setNum(num);
         device.setNum(num);
-        String md5 = MD5Util.MD5Encode(num);
-        if (md5 == null) {
-            md5 = CodeGenerator.generateUUID();
-        }
-        device.setClientId(md5);
-        device.setPassword(md5.substring(10));
+        String clientId = MD5Util.MD5Encode(num);
+        device.setClientId(clientId);
+        device.setPassword(MD5Util.MD5Encode(clientId));
         device.setGroupId(1);
         device.setGroupId(1);
         deviceService.save(device);
         deviceService.save(device);
         setBaseService.initSetBase(device.getClientId());
         setBaseService.initSetBase(device.getClientId());

+ 1 - 5
src/main/java/com/zy/bms/controller/LocationController.java

@@ -3,7 +3,6 @@ package com.zy.bms.controller;
 import com.zy.bms.common.ServerResponse;
 import com.zy.bms.common.ServerResponse;
 import com.zy.bms.common.io.wechat.DeviceHistoryIO;
 import com.zy.bms.common.io.wechat.DeviceHistoryIO;
 import com.zy.bms.service.DeviceLocationService;
 import com.zy.bms.service.DeviceLocationService;
-import com.zy.bms.redis.DeviceManager;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
@@ -24,15 +23,12 @@ public class LocationController {
     @Resource
     @Resource
     private DeviceLocationService locationService;
     private DeviceLocationService locationService;
 
 
-    @Resource
-    private DeviceManager redisDeviceManager;
-
     /**
     /**
      * 通过设备ID获取最新的定位信息
      * 通过设备ID获取最新的定位信息
      */
      */
     @GetMapping("getLocation.do")
     @GetMapping("getLocation.do")
     public ServerResponse getLocation(String deviceId) {
     public ServerResponse getLocation(String deviceId) {
-        return ServerResponse.createBySuccess(redisDeviceManager.getLocation(deviceId));
+        return ServerResponse.createBySuccess(locationService.getLocation(deviceId));
     }
     }
 
 
     /**
     /**

+ 0 - 16
src/main/java/com/zy/bms/mapper/BaseStationMapper.java

@@ -1,16 +0,0 @@
-package com.zy.bms.mapper;
-
-import com.baomidou.mybatisplus.core.mapper.BaseMapper;
-import org.apache.ibatis.annotations.Mapper;
-import org.springframework.stereotype.Repository;
-
-/**
- * 基站信息
- *
- * @author konglilia
- * Create on 2020/4/10
- */
-@Mapper
-@Repository
-public interface BaseStationMapper extends BaseMapper<BaseStation> {
-}

+ 5 - 0
src/main/java/com/zy/bms/mapper/DeviceLocationMapper.java

@@ -19,6 +19,11 @@ import java.util.List;
 @Repository
 @Repository
 public interface DeviceLocationMapper extends BaseMapper<DeviceLocation> {
 public interface DeviceLocationMapper extends BaseMapper<DeviceLocation> {
 
 
+    /**
+     * 查询数据库中最新的定位信息
+     */
+    DeviceLocation getLatestLocation(String deviceId);
+
     /**
     /**
      * 查看设备历史轨迹
      * 查看设备历史轨迹
      *
      *

+ 0 - 43
src/main/java/com/zy/bms/service/BaseStationService.java

@@ -1,43 +0,0 @@
-package com.zy.bms.service;
-
-import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
-import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
-import com.zy.bms.mapper.BaseStationMapper;
-import org.springframework.stereotype.Service;
-
-import java.time.LocalDateTime;
-import java.util.List;
-import java.util.Map;
-
-/**
- * 基站信息
- *
- * @author chenyi
- * Create on 2020/4/10
- */
-@Service
-public class BaseStationService extends ServiceImpl<BaseStationMapper, BaseStation> {
-    /**
-     * 添加基站信息,保留最新的,有则更新,无则添加
-     *
-     * @param deviceId 设备ID
-     * @param data     设备发来MQTT 消息对象
-     */
-    public void insertBaseStation(String deviceId, Map<String, Object> data) {
-        BaseStation entity = new BaseStation();
-        entity.setCellInf0((String) data.get("cellinf0"));
-        entity.setCellInf1((String) data.get("cellinf1"));
-        entity.setCreateTime(LocalDateTime.now());
-        QueryWrapper<BaseStation> queryWrapper = new QueryWrapper<BaseStation>().eq("deviceId", deviceId);
-        saveOrUpdate(entity, queryWrapper);
-    }
-
-    /**
-     * 通过设备ID查询基站信息
-     *
-     * @param deviceId 设备ID
-     */
-    public List<BaseStation> getByDeviceId(String deviceId) {
-        return baseMapper.selectList(new QueryWrapper<BaseStation>().eq("deviceId", deviceId));
-    }
-}

+ 19 - 0
src/main/java/com/zy/bms/service/DeviceLocationService.java

@@ -5,8 +5,10 @@ import com.zy.bms.common.io.wechat.DeviceHistoryIO;
 import com.zy.bms.common.vo.LocationHistoryVo;
 import com.zy.bms.common.vo.LocationHistoryVo;
 import com.zy.bms.mapper.DeviceLocationMapper;
 import com.zy.bms.mapper.DeviceLocationMapper;
 import com.zy.bms.model.DeviceLocation;
 import com.zy.bms.model.DeviceLocation;
+import com.zy.bms.redis.DeviceManager;
 import org.springframework.stereotype.Service;
 import org.springframework.stereotype.Service;
 
 
+import javax.annotation.Resource;
 import java.util.List;
 import java.util.List;
 
 
 /**
 /**
@@ -18,6 +20,23 @@ import java.util.List;
 @Service
 @Service
 public class DeviceLocationService extends ServiceImpl<DeviceLocationMapper, DeviceLocation> {
 public class DeviceLocationService extends ServiceImpl<DeviceLocationMapper, DeviceLocation> {
 
 
+    @Resource
+    private DeviceManager redisDeviceManager;
+
+    /**
+     * 获取设备的最新位置信息
+     * (优先查询redis缓存,再查询数据库)
+     *
+     * @param deviceId 设备ID
+     */
+    public DeviceLocation getLocation(String deviceId) {
+        DeviceLocation result = redisDeviceManager.getLocation(deviceId);
+        if (result == null) {
+            result = baseMapper.getLatestLocation(deviceId);
+        }
+        return result;
+    }
+
     /**
     /**
      * 查看设备历史轨迹
      * 查看设备历史轨迹
      *
      *

+ 5 - 8
src/main/java/com/zy/bms/service/SetToDeviceService.java

@@ -2,6 +2,7 @@ package com.zy.bms.service;
 
 
 import com.zy.bms.common.Constant;
 import com.zy.bms.common.Constant;
 import com.zy.bms.config.mqtt.MqttGateway;
 import com.zy.bms.config.mqtt.MqttGateway;
+import com.zy.bms.model.Device;
 import com.zy.bms.model.MqttMsgDto;
 import com.zy.bms.model.MqttMsgDto;
 import com.zy.bms.common.io.wechat.*;
 import com.zy.bms.common.io.wechat.*;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
@@ -99,21 +100,17 @@ public class SetToDeviceService {
 
 
     /**
     /**
      * 服务器返回授权码
      * 服务器返回授权码
-     *
-     * @param regNum   设备码
-     * @param clientId MQTT 客户端码
-     * @param password MQTT 客户端连接密码
      */
      */
-    public void returnCodeToDevice(String regNum, String clientId, String password) {
+    public void returnCodeToDevice(Device device) {
         //发送模板消息给设备
         //发送模板消息给设备
         MqttMsgDto msg = new MqttMsgDto();
         MqttMsgDto msg = new MqttMsgDto();
         msg.setM(Constant.M_CODE_RETURN_CODE);
         msg.setM(Constant.M_CODE_RETURN_CODE);
         msg.setR("$regdtx");
         msg.setR("$regdtx");
         msg.setT("$regdrx");
         msg.setT("$regdrx");
         Map<String, Object> data = new HashMap<>();
         Map<String, Object> data = new HashMap<>();
-        data.put("regnum", regNum);
-        data.put("deviceid", clientId);
-        data.put("password", password);
+        data.put("regnum", device.getNum());
+        data.put("deviceid", device.getClientId());
+        data.put("password", device.getPassword());
         msg.setData(data);
         msg.setData(data);
         mqttGateway.sendMsgToMqtt(msg.toJson(), Constant.TOPIC_REGISTER_CLIENT);
         mqttGateway.sendMsgToMqtt(msg.toJson(), Constant.TOPIC_REGISTER_CLIENT);
     }
     }

+ 5 - 13
src/main/java/com/zy/bms/utils/GaoDeApiUtil.java

@@ -3,24 +3,16 @@ package com.zy.bms.utils;
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
 import com.alibaba.fastjson.JSONObject;
 import org.springframework.http.ResponseEntity;
 import org.springframework.http.ResponseEntity;
-import org.springframework.stereotype.Component;
-import org.springframework.web.client.RestTemplate;
-
-import javax.annotation.Resource;
 
 
 /**
 /**
- * 高德API 服务类￿
+ * 高德API 服务类
  *
  *
  * @author yang xiao kun
  * @author yang xiao kun
  * create on 2021/2/4
  * create on 2021/2/4
  */
  */
-@Component
 public class GaoDeApiUtil {
 public class GaoDeApiUtil {
 
 
-    @Resource
-    private RestTemplate restTemplate;
-
-    private static final String url = "https://restapi.amap.com/v3/geocode/regeo?key=10ab24979b475f6ea5eba052c0c2016f&location={1￿}";
+    private static final String url = "https://restapi.amap.com/v3/geocode/regeo?key=10ab24979b475f6ea5eba052c0c2016f&location={1}";
 
 
     /**
     /**
      * 逆地址解析,获取位置的详细描述信息
      * 逆地址解析,获取位置的详细描述信息
@@ -28,11 +20,11 @@ public class GaoDeApiUtil {
      * @param lng 经度
      * @param lng 经度
      * @param lat 纬度
      * @param lat 纬度
      */
      */
-    public String regeo(String lng, String lat) {
+    public static String regeo(String lng, String lat) {
         if (lng == null || lat == null) return null;
         if (lng == null || lat == null) return null;
         try {
         try {
-            ResponseEntity<String> result = restTemplate.getForEntity(url, String.class, lng + "," + lat);
-            JSONObject jsonMap = JSON.parseObject(result.getBody());
+            String result = HttpUtil.getForEntity(url, lng + "," + lat);
+            JSONObject jsonMap = JSON.parseObject(result);
             JSONObject regeoCode = jsonMap.getJSONObject("regeocode");
             JSONObject regeoCode = jsonMap.getJSONObject("regeocode");
             return regeoCode.getString("formatted_address");
             return regeoCode.getString("formatted_address");
         } catch (Exception e) {
         } catch (Exception e) {

+ 12 - 0
src/main/java/com/zy/bms/utils/HttpUtil.java

@@ -3,6 +3,7 @@ package com.zy.bms.utils;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.MediaType;
 import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
 import org.springframework.util.MultiValueMap;
 import org.springframework.util.MultiValueMap;
 import org.springframework.web.client.RestTemplate;
 import org.springframework.web.client.RestTemplate;
 
 
@@ -18,6 +19,17 @@ public class HttpUtil {
 
 
     private static final RestTemplate restTemplate = new RestTemplate();
     private static final RestTemplate restTemplate = new RestTemplate();
 
 
+    /**
+     * 发送 Get 请求
+     *
+     * @param url          请求地址
+     * @param uriVariables 请求参数
+     */
+    public static String getForEntity(String url, Object... uriVariables) {
+        ResponseEntity<String> result = restTemplate.getForEntity(url, String.class, uriVariables);
+        return result.getBody();
+    }
+
     /**
     /**
      * 发送 POST 请求
      * 发送 POST 请求
      * JSON 格式请求信息
      * JSON 格式请求信息

+ 1 - 1
src/main/java/com/zy/bms/utils/MD5Util.java

@@ -32,7 +32,7 @@ public class MD5Util {
             }
             }
             return stringBuilder.toString();
             return stringBuilder.toString();
         } catch (Exception e) {
         } catch (Exception e) {
-            return null;
+            return "MD5";
         }
         }
     }
     }
 }
 }

+ 5 - 5
src/main/java/com/zy/bms/websocket/WebSocketServer.java

@@ -6,8 +6,8 @@ import javax.websocket.*;
 import javax.websocket.server.PathParam;
 import javax.websocket.server.PathParam;
 import javax.websocket.server.ServerEndpoint;
 import javax.websocket.server.ServerEndpoint;
 import java.io.IOException;
 import java.io.IOException;
-import java.util.LinkedList;
-import java.util.List;
+import java.util.HashSet;
+import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentHashMap;
 
 
 @Component
 @Component
@@ -19,7 +19,7 @@ public class WebSocketServer {
      * key : 设备ID
      * key : 设备ID
      * value : 实时接收该设备的web端session
      * value : 实时接收该设备的web端session
      */
      */
-    private static ConcurrentHashMap<String, List<Session>> webSocketMap = new ConcurrentHashMap<>();
+    private static ConcurrentHashMap<String, Set<Session>> webSocketMap = new ConcurrentHashMap<>();
 
 
     /**
     /**
      * 连接成功
      * 连接成功
@@ -27,7 +27,7 @@ public class WebSocketServer {
     @OnOpen
     @OnOpen
     public void onOpen(Session session, @PathParam("deviceId") String deviceId) {
     public void onOpen(Session session, @PathParam("deviceId") String deviceId) {
         //如果该设备没有web端查看,则初始化
         //如果该设备没有web端查看,则初始化
-        if (!webSocketMap.containsKey(deviceId)) webSocketMap.put(deviceId, new LinkedList<>());
+        if (!webSocketMap.containsKey(deviceId)) webSocketMap.put(deviceId, new HashSet<>());
         //添加到集合中
         //添加到集合中
         webSocketMap.get(deviceId).add(session);
         webSocketMap.get(deviceId).add(session);
     }
     }
@@ -52,7 +52,7 @@ public class WebSocketServer {
      * 群发消息
      * 群发消息
      */
      */
     public void massMessage(String deviceId, String message) {
     public void massMessage(String deviceId, String message) {
-        List<Session> sessions = webSocketMap.get(deviceId);
+        Set<Session> sessions = webSocketMap.get(deviceId);
         if (sessions == null || sessions.isEmpty()) return;
         if (sessions == null || sessions.isEmpty()) return;
         // 遍历客户端 发送消息
         // 遍历客户端 发送消息
         for (Session session : sessions) {
         for (Session session : sessions) {

+ 1 - 1
src/main/resources/application.yml

@@ -1,3 +1,3 @@
 spring:
 spring:
   profiles:
   profiles:
-    active: prod
+    active: dev

+ 10 - 0
src/main/resources/mapper/DeviceLocationMapping.xml

@@ -4,6 +4,16 @@
         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 <mapper namespace="com.zy.bms.mapper.DeviceLocationMapper">
 <mapper namespace="com.zy.bms.mapper.DeviceLocationMapper">
 
 
+    <select id="getLatestLocation" resultType="com.zy.bms.model.DeviceLocation">
+        SELECT
+            *
+        FROM
+            zy_location
+        WHERE
+            deviceId = #{deviceId}
+        ORDER BY uploadTime DESC LIMIT 1
+    </select>
+
     <select id="getHistory" resultType="com.zy.bms.common.vo.LocationHistoryVo">
     <select id="getHistory" resultType="com.zy.bms.common.vo.LocationHistoryVo">
         SELECT
         SELECT
             deviceId,
             deviceId,