Kaynağa Gözat

update:添加注册后设备添加和修改功能

zhouzeyu 1 yıl önce
ebeveyn
işleme
66593f48ae

+ 1 - 1
src/main/java/com/tuoren/forward/entity/UserConfig.java

@@ -17,7 +17,7 @@ public class UserConfig {
     @Schema(description = "wifi信息:[{“name”:'tuoren1',“password”:'12345678'},{},{},...]")
     private String wifi;
 
-    @Schema(description = "医院数据对接服务地址和端口:[{“network”:'NB-IOT',“address”:'192.168.0.14',“port”:'5014'},{},{},...]")
+    @Schema(description = "医院数据对接服务地址和端口:[{“network”:'NB-IOT',“address”:'192.168.0.14',“port”:'5014'},{},{},...],平台 1:aliyun 2:tuoren 3:local")
     private String address;
 
     @Schema(description = "设备密钥")

+ 180 - 123
src/main/java/com/tuoren/forward/netty/MyServer.java

@@ -4,6 +4,8 @@ import cn.hutool.core.util.StrUtil;
 import com.alibaba.fastjson2.JSON;
 import com.alibaba.fastjson2.JSONArray;
 import com.alibaba.fastjson2.JSONObject;
+import com.tuoren.forward.entity.Device;
+import com.tuoren.forward.mapper.DeviceMapper;
 import com.tuoren.forward.netty.common.NetworkProtocol;
 import com.tuoren.forward.netty.common.NetworkType;
 import com.tuoren.forward.netty.common.Platform;
@@ -15,8 +17,8 @@ import com.tuoren.forward.mapper.UserConfigMapper;
 import com.tuoren.forward.mapper.UserMapper;
 import com.tuoren.forward.netty.aliutil.Config;
 import com.tuoren.forward.netty.excepetion.NExcCode;
+import com.tuoren.forward.service.DeviceService;
 import com.tuoren.forward.service.RegistLogService;
-import com.tuoren.forward.netty.common.JsonExtractor;
 import com.tuoren.forward.util.UUIDUtil;
 import com.tuoren.forward.netty.common.WifiDataTrans;
 import io.netty.bootstrap.ServerBootstrap;
@@ -56,8 +58,13 @@ public class MyServer implements CommandLineRunner {
             serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                     .childHandler(myServerInitializer);
             ChannelFuture channelFuture = serverBootstrap.bind(ymlConfig.getPort()).sync();
+            log.info("Netty服务器已绑定到端口: {}", ymlConfig.getPort());
             channelFuture.channel().closeFuture().sync();
+            log.info("Netty服务器关闭...");
+        }catch (Exception e){
+            log.error("Netty服务器启动失败",e);
         } finally {
+            log.info("关闭EventLoopGroups...");
             bossGroup.shutdownGracefully();
             workerGroup.shutdownGracefully();
         }
@@ -84,16 +91,11 @@ class MyServerInitializer extends ChannelInitializer<SocketChannel> {
     }
 }
 
+
 @Component
 @ChannelHandler.Sharable
 class MyServerHandler extends ChannelInboundHandlerAdapter {
 
-    private static Logger logger = LoggerFactory.getLogger(MyServerHandler.class);
-    //加密解密密钥
-    String key = "tuorenzhinenghua";
-    AliDeviceRegist register = new AliDeviceRegist();
-
-
     @Autowired
     UserConfigMapper userConfigMapper;
     @Autowired
@@ -101,12 +103,25 @@ class MyServerHandler extends ChannelInboundHandlerAdapter {
     @Autowired
     UserMapper userMapper;
 
+    @Autowired
+    DeviceMapper deviceMapper;
+
+    @Autowired
+    DeviceService deviceService;
+
     @Autowired
     RegistLogMapper registLogMapper;
 
     @Autowired
     RegistLogService registLogService;
 
+    private static Logger logger = LoggerFactory.getLogger(MyServerHandler.class);
+    //加密解密密钥
+    String key = "tuorenzhinenghua";
+//    AliDeviceRegist register = new AliDeviceRegist();
+
+
+
     @Override
     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
         // TODO Auto-generated method stub
@@ -141,7 +156,7 @@ class MyServerHandler extends ChannelInboundHandlerAdapter {
             registLog.setWaste(String.valueOf(duration));
 
 
-            int maxLength = 800;
+            int maxLength = 1000;
             if (jsonString != null && !jsonString.isEmpty()) {
                 if (jsonString.length() > maxLength) {
                     jsonString = jsonString.substring(0, maxLength);
@@ -193,38 +208,29 @@ class MyServerHandler extends ChannelInboundHandlerAdapter {
 
     }
 
+
     private String handleRegister(String msgStr) throws Exception {
         JSONObject json = new JSONObject();
         json.put("code", NExcCode.SUCCESS.getCode());
 
         if (StrUtil.isBlank(msgStr)) {
-            json.put("code", NExcCode.ERROR_PARAM.getCode());
-            json.put("msg", NExcCode.ERROR_PARAM.getMsg());
-            return json.toString();
+            return buildErrorResponse(NExcCode.ERROR_PARAM, json);
         }
 
         JSONObject paramJson = JSONObject.parseObject(msgStr);
+        //版本
+        int version = paramJson.getIntValue("version");
 
-        //网络类型
-        Integer networkCode = null;
-        try {
-            networkCode = paramJson.getIntValue("networkType");
-
-        } catch (Exception e) {
-            logger.warn("如果networkType为空或者不是整数, 使用默认值: NB-IoT", e);
-        }
-        NetworkType network = NetworkType.NetworkTypeName(networkCode);
-
-
-        boolean isOldCode = paramJson.containsKey("platform");
-        if (isOldCode) {
+        /**
+         * 新老判断依据 : 通过版本号 1 0 "";
+         */
+        //判断传入的version是0或者为空
+        if (version == 0 || StrUtil.isBlank(String.valueOf(version))) {
             String deviceName = paramJson.getString("deviceId"); //device表中的mac
 
             //执行设备注册操作或查询操作
-            JSONObject registData = aliDeviceHttp.deviceRegist(deviceName);
-            if (registData.isEmpty()) {
-                registData = aliDeviceHttp.deviceQuery(deviceName);
-            }
+            JSONObject registData = DeviceRegistrationOrQuery(deviceName);
+
             if (!registData.isEmpty()) {
                 json.put("code", 0);
                 json.put("type", 0x15);
@@ -234,82 +240,153 @@ class MyServerHandler extends ChannelInboundHandlerAdapter {
                 json.put("deviceSecret", registData.getString("DeviceSecret"));
                 json.put("productKey", registData.getString("ProductKey"));
             }
-
-        } else {
-            //平台
-            Platform platform = null;
-            //版本
-            int version = paramJson.getIntValue("version", 1);//如果版本为空,则默认1
-
-            //网络协议
-            Integer protocolCode = null;
-            try {
-                protocolCode = paramJson.getIntValue("networkProtocol");
-            } catch (Exception e) {
-                // 如果没有找到 networkType 或者它不是一个整数,则使用默认值
-                logger.warn("如果networkProtocol为空或者不是整数, 使用默认值: CoAP", e);
-            }
-            NetworkProtocol protocol = NetworkProtocol.NetworkProtocolName(protocolCode);
-
-            //产品编号
-            String productId = paramJson.getString("productId");
-            productId = StrUtil.isBlank(productId) ? "1dbfd476b7nm2" : productId;
-
-            //设备编号
-            String deviceName = paramJson.getString("deviceId");
+        }
+        else if (version == 1) {
+            //网络类型
+            Integer networkCode = paramJson.getIntValue("networkType");
+            NetworkType network = NetworkType.NetworkTypeName(networkCode);
 
             //编码
             String userId = paramJson.getString("userId");
-
+            //查询userId是否存在
             User userIdCode = userMapper.selectByCode(userId);
             if (userIdCode == null || StrUtil.isBlank(userIdCode.getCode())) {
-                json.put("code", NExcCode.ERROR_USERID.getCode());
-                json.put("msg", NExcCode.ERROR_USERID.getMsg());
-                logger.error("注册失败:userId不存在", json.toJSONString());
-                return json.toString();
+                return buildErrorResponse(NExcCode.ERROR_USERID, json);
             }
 
+            //产品编号
+            String productId = paramJson.getString("productId");
+            if (StrUtil.isBlank(productId)){
+                return buildErrorResponse(NExcCode.ERROR_PRODUCTID, json);
+            }
 
-            //根据网络类型进行判断
-            if (NetworkType.WIFI.equals(network)) {
+            //网络协议
+            Integer protocolCode = paramJson.getIntValue("networkProtocol");
+            NetworkProtocol protocol = NetworkProtocol.NetworkProtocolName(protocolCode);
 
-                platform = Platform.PlatformName(Platform.LOCAL.getCode());
-                // 处理WiFi注册
-                json = handleWifiRegistration(paramJson, network, platform, protocol, productId, deviceName, userId);
+            //设备编号
+            String deviceName = paramJson.getString("deviceId");
 
-            } else {
+            //SIM卡号
+            String sim = paramJson.getString("sim");
+
+            //通过查询获取到参数
+            String id = userIdCode.getId();
+            //查找用户id
+            UserConfig userConfig = userConfigMapper.selectByPrimaryKey(id);
+            // 根据用户ID获取用户配置
+            String wifi = userConfig.getWifi();
+            String addressArray = userConfig.getAddress();
+            String deviceSecret = userConfig.getDeviceSecret();
+            JSONArray addressArrayJson = JSON.parseArray(addressArray);
+
+            //从地址数组中找到匹配的网络类型获取平台
+            Integer platform = null;
+            String remoteAddress = null;
+            int remotePort = 0;
+            for (Object item : addressArrayJson){
+                JSONObject networkInfo = (JSONObject) item;
+                if (network.getName().equalsIgnoreCase(networkInfo.getString("networkType"))) {
+                    //平台
+                    platform = networkInfo.getIntValue("platform");
+                    //地址
+                    remoteAddress = networkInfo.getString("address");
+                    //端口
+                    remotePort = networkInfo.getIntValue("port");
+                    break;
+                }
+            }
 
+            if (platform == null) {
+                return buildErrorResponse(NExcCode.ERROR_PLATFORM_TYPE, json);
+            }
 
-                platform = Platform.PlatformName(Platform.ALIYUN.getCode());
+            //查询数据库是否存在该设备
+            Device deviceMac = deviceMapper.selectByMac(deviceName);
+            if (deviceMac == null){
+                //不存在,则新增设备
+                //添加操作
+                Device NewDevice = new Device();
+                NewDevice.setId(UUIDUtil.get32UUID());
+                NewDevice.setMac(deviceName);
+                NewDevice.setSim(sim);
+                NewDevice.setProductId(productId);
+                NewDevice.setCreatetime(new Date());
+                NewDevice.setTenantId(id);
+                deviceMapper.insertSelective(NewDevice);
+            }else {
+                //如果存在,检查productId是否一致
+                if (!productId.equals(deviceMac.getProductId())){
+                    //更新数据库中的productId
+                    deviceMac.setProductId(productId);
+                    deviceMac.setModifytime(new Date());
+                    deviceMapper.updateByMac(deviceMac);
+                }else if (StrUtil.isBlank(deviceMac.getSim()) || !sim.equals(deviceMac.getSim())){
+                    //更新数据库中的sim
+                    deviceMac.setSim(sim);
+                    deviceMac.setModifytime(new Date());
+                    deviceMapper.updateByMac(deviceMac);
+                }else if (!id.equals(deviceMac.getTenantId())){
+                    deviceMac.setTenantId(id);
+                    deviceMac.setModifytime(new Date());
+                    deviceMapper.updateByMac(deviceMac);
+                }
 
+            }
+            if (Platform.ALIYUN.getCode() == platform) {
+                //阿里云注册
                 //执行设备注册操作或查询操作
-                JSONObject registData = aliDeviceHttp.deviceRegist(deviceName);
-                if (registData.isEmpty()) {
-                    registData = aliDeviceHttp.deviceQuery(deviceName);
-                }
+                JSONObject registData = DeviceRegistrationOrQuery(deviceName);
+
                 //如果注册数据不为空,则构建响应消息
                 if (!registData.isEmpty()) {
-
                     json.put("code", NExcCode.SUCCESS.getCode());
                     json.put("version", version);
-                    json.put("platform", platform.getCode());
+                    json.put("platform", platform);
                     json.put("networkType", network.getCode());
                     json.put("networkProtocol", protocol.getCode());
                     json.put("productId", productId);
                     json.put("deviceId", deviceName);
                     json.put("userId", userId);
-                    json.put("remoteAddress", Config.COAP_ADDRESS);
+                    json.put("sim", sim);
+                    json.put("remoteAddress", productId+Config.COAP_ADDRESS );
                     json.put("remotePort", Config.COAP_PORT);
                     json.put("deviceSecret", registData.getString("DeviceSecret"));
                     json.put("productKey", registData.getString("ProductKey"));
                 }
 
             }
+            else if (Platform.LOCAL.getCode() == platform) {
+                //WiFi注册
+                if (NetworkType.WIFI.equals(network)) {
+                    LocalReturnParam(paramJson, json, network, protocol, deviceName, userId, productId, remoteAddress, remotePort, deviceSecret);
+                    JSONArray wifiArray = JSON.parseArray(wifi);
+                    JSONArray transformWifiArray = WifiDataTrans.transformWifiArray(wifiArray);
+                    json.put("wifi", transformWifiArray);
+                }
+                // 4G注册
+                else if (NetworkType.LTE.equals(network)){
+                    LocalReturnParam(paramJson, json, network, protocol, deviceName, userId, productId, remoteAddress, remotePort, deviceSecret);
+                    json.put("sim", sim);
+                }
+                // NB注册
+                else if (NetworkType.NB_IOT.equals(network)){
+                    LocalReturnParam(paramJson, json, network, protocol, deviceName, userId, productId, remoteAddress, remotePort, deviceSecret);
+                    json.put("sim", sim);
+                }
+            }
+
+        }
+
+        else {
+            //如果传入的版本不是2以上的版本报错
+            return buildErrorResponse(NExcCode.ERROR_VERSION_TYPE, json);
         }
         return json.toString();
-    }
 
 
+    }
+
     private String extractDeviceId(String msgStr) {
         try {
             JSONObject json = JSON.parseObject(msgStr);
@@ -320,66 +397,46 @@ class MyServerHandler extends ChannelInboundHandlerAdapter {
         }
     }
 
-    private JSONObject validateAndParseJson(String jsonString) throws Exception {
-        try {
-            return JSONObject.parseObject(jsonString);
-        } catch (Exception e) {
-            logger.error("Invalid JSON: {}", jsonString, e);
-            throw new Exception("Invalid JSON: " + jsonString, e);
-        }
-    }
-
-
-    private JSONObject handleWifiRegistration(JSONObject paramJson, NetworkType network, Platform platform, NetworkProtocol protocol, String productId, String deviceName, String userId) throws Exception {
-        JSONObject json = new JSONObject();
-        int version = paramJson.getIntValue("version");
-        // 如果版本为空,则默认为1
-        version = version == 0 ? 1 : version;
 
+    //Local 平台返回参数
+    private void LocalReturnParam(JSONObject paramJson,JSONObject json, NetworkType network, NetworkProtocol protocol, String deviceName, String userId, String productId, String remoteAddress, int remotePort, String deviceSecret) {
         json.put("code", NExcCode.SUCCESS.getCode());
-        json.put("version", version);
-        json.put("platform", platform.getCode());
+        json.put("version", paramJson.getString("version"));
+        json.put("platform", Platform.LOCAL.getCode());
         json.put("networkType", network.getCode());
         json.put("networkProtocol", protocol.getCode());
-        json.put("productId", productId);
+        json.put("productId", paramJson.getString("productId"));
         json.put("deviceId", deviceName);
-        json.put("userId", userId);
-
-        // 根据用户ID获取用户配置
-        User user = userMapper.selectByCode(userId);
-        String id = user.getId();
-        UserConfig userConfig = userConfigMapper.selectByPrimaryKey(id);
-        String wifi = userConfig.getWifi();
-        String addressArray = userConfig.getAddress();
-        String deviceSecret = userConfig.getDeviceSecret();
-
-        JSONArray addressArrayJson = JSON.parseArray(addressArray);
-
-        boolean found = false;
-        for (Object item : addressArrayJson) {
-            JSONObject networkInfo = (JSONObject) item;
-            if (network.getName().equalsIgnoreCase(networkInfo.getString("networkType"))) {
-                json.put("remoteAddress", networkInfo.getString("address"));
-                json.put("remotePort", networkInfo.getIntValue("port"));
-                found = true;
-                break;
-            }
-        }
+        json.put("userId", paramJson.getString("userId"));
+        json.put("remoteAddress", remoteAddress);
+        json.put("remotePort", remotePort);
+        json.put("deviceSecret", deviceSecret);
+    }
 
-        if (!found) {
-            json.put("code", NExcCode.ERROR_NETWORK_TYPE.getCode());
-            json.put("msg", NExcCode.ERROR_NETWORK_TYPE.getMsg());
-            logger.error("注册失败:未找到匹配的网络类型:" + network.getName(), json.toJSONString());
-            return json;
+    //aliyun 平台注册或查询设备
+    private JSONObject DeviceRegistrationOrQuery(String deviceName) {
+        JSONObject registData = aliDeviceHttp.deviceRegist(deviceName);
+        if (registData.isEmpty()) {
+            registData = aliDeviceHttp.deviceQuery(deviceName);
         }
+        return registData;
+    }
 
-        JSONArray wifiArray = JSON.parseArray(wifi);
-        JSONArray transformWifiArray = WifiDataTrans.transformWifiArray(wifiArray);
-        json.put("deviceSecret", deviceSecret);
-        json.put("wifi", transformWifiArray);
-
-        return json;
+    //错误请求
+    private String buildErrorResponse(NExcCode excCode, JSONObject response) {
+        response.put("code", excCode.getCode());
+        response.put("msg", excCode.getMsg());
+        logger.error(excCode.getMsg(), response.toJSONString());
+        return response.toJSONString();
     }
 
+    private JSONObject validateAndParseJson(String jsonString) throws Exception {
+        try {
+            return JSONObject.parseObject(jsonString);
+        } catch (Exception e) {
+            logger.error("Invalid JSON: {}", jsonString, e);
+            throw new Exception("Invalid JSON: " + jsonString, e);
+        }
+    }
 
-}
+}

+ 5 - 2
src/main/java/com/tuoren/forward/netty/common/NetworkType.java

@@ -1,5 +1,7 @@
 package com.tuoren.forward.netty.common;
 
+import com.tuoren.forward.netty.excepetion.NExcCode;
+
 /**
  * @Author zzy
  * @Data 2024/10/15
@@ -31,13 +33,14 @@ public enum NetworkType {
 
     public static NetworkType NetworkTypeName(Integer code) {
         if (code == null) {
-            return NB_IOT;//默认值
+            throw new IllegalArgumentException("网络类型不能为空");
         }
         for (NetworkType type : values()) {
             if (type.getCode() == code) {
                 return type;
             }
         }
-        return NB_IOT; // 如果code 不匹配任何一直类型,则返回默认值
+        throw new IllegalArgumentException("未知的网络类型: " + code);
     }
+
 }

+ 6 - 1
src/main/java/com/tuoren/forward/netty/excepetion/NExcCode.java

@@ -17,7 +17,12 @@ public enum NExcCode {
     SUCCESS(200,"成功"),
     ERROR_PARAM(400,"参数为空"),
     ERROR_USERID(401,"userId不存在"),
-    ERROR_NETWORK_TYPE(402,"网络类型不存在");
+    ERROR_NETWORK_TYPE(402,"网络类型不存在"),
+    ERROR_VERSION_TYPE(403,"版本类型不存在"),
+    ERROR_PLATFORM_TYPE(404,"平台类型不存在"),
+    ERROR_PRODUCTID(405,"产品编号不存在");
+
+
 
 
     @Getter

+ 4 - 2
src/main/resources/mapper/UserConfigMapper.xml

@@ -10,7 +10,7 @@
         <result column="modifytime" jdbcType="TIMESTAMP" property="modifytime"/>
     </resultMap>
     <sql id="Base_Column_List">
-        id, wifi, address , device_secret, createtime, modifytime
+        id, wifi, address,device_secret, createtime, modifytime
     </sql>
     <select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
         select
@@ -25,7 +25,9 @@
     </delete>
     <insert id="insert" parameterType="com.tuoren.forward.entity.UserConfig">
         insert into user_config (id, wifi, address, device_secret, createtime, modifytime)
-        values (#{id,jdbcType=VARCHAR}, #{wifi,jdbcType=VARCHAR}, #{address,jdbcType=VARCHAR},
+        values (#{id,jdbcType=VARCHAR},
+                #{wifi,jdbcType=VARCHAR},
+                #{address,jdbcType=VARCHAR},
                 #{deviceSecret,jdbcType=VARCHAR},
                 #{createtime,jdbcType=TIMESTAMP},
                 #{modifytime,jdbcType=TIMESTAMP})