zhouzeyu 1 год назад
Родитель
Сommit
12db6d65d5

+ 0 - 1
src/main/java/com/tuoren/forward/App.java

@@ -21,7 +21,6 @@ public class App {
 	 * @title 项目启动 
 	 * @param args
 	 */
-
 	public static void main(String[] args) {
 		SpringApplication.run(App.class, args);
 	}

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

@@ -15,15 +15,10 @@ public class UserConfig {
     private String id;
 
     @Schema(description = "wifi信息:[{“name”:'tuoren1',“password”:'12345678'},{},{},...]")
-//    @JsonDeserialize(using = WifiListDeserializer.class)
     private String wifi;
 
-
-    @Schema(description = "医院数据对接服务地址")
-    private String localAddress;
-
-    @Schema(description = "医院数据对接服务端口")
-    private Integer localPort;
+    @Schema(description = "医院数据对接服务地址和端口:[{“network”:'NB-IOT',“address”:'192.168.0.14',“port”:'5014'},{},{},...]")
+    private String address;
 
     @Schema(description = "设备密钥")
     private String deviceSecret;

+ 5 - 4
src/main/java/com/tuoren/forward/entity/dto/RegistLogDto.java

@@ -1,6 +1,7 @@
 package com.tuoren.forward.entity.dto;
 
 import com.tuoren.forward.entity.Log;
+import com.tuoren.forward.entity.RegistLog;
 import lombok.Data;
 import lombok.EqualsAndHashCode;
 import lombok.ToString;
@@ -10,7 +11,7 @@ import java.util.Date;
 @Data
 @ToString(callSuper = true)
 @EqualsAndHashCode(callSuper = true)
-public class RegistLogDto extends Log{
+public class RegistLogDto extends RegistLog {
 	
 	private String sort;  //排序字段
 	
@@ -18,7 +19,7 @@ public class RegistLogDto extends Log{
 	
 	private String keyWord; //搜索内容
 	
-	private Date startTime; //开始时间
-	
-	private Date endTime; //结束时间
+//	private Date startTime; //开始时间
+//
+//	private Date endTime; //结束时间
 }

+ 8 - 4
src/main/java/com/tuoren/forward/netty/AES.java

@@ -94,10 +94,14 @@ public class AES {
         String cKey = "tuorenzhinenghua";
 //        String cSrc = "3431228A1936013C&a1xJ4qC587v&"; 
         JSONObject json = new JSONObject();
-//        json.put("deviceId", "1234567");
-        json.put("deviceId", "7654321");
-        json.put("network", "wifi");
-        json.put("userId", "0001");
+//        json.put("deviceId", "11111");
+//        json.put("platform", "aliyun");
+        json.put("version", 1);
+        json.put("deviceId", "51258111303002A9");
+        json.put("networkProtocol", 4);
+        json.put("productId", "");
+        json.put("networkType", 3);
+        json.put("userId", "1000");
 
         System.out.println(json.toString());
         // 加密 

+ 98 - 101
src/main/java/com/tuoren/forward/netty/AliDeviceHttp.java

@@ -11,6 +11,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
+
 import java.time.LocalDateTime;
 import java.time.ZoneOffset;
 import java.util.HashMap;
@@ -18,107 +19,103 @@ import java.util.Map;
 
 @Component
 public class AliDeviceHttp {
-	//定义一个私有的静态Logger实例,用于记录AliDeviceHttp类的日志信息
-	private static Logger logger = LoggerFactory.getLogger(AliDeviceHttp.class);
-	@Autowired
-	 YmlConfig ymlConfig;
-	/**
-	 * 构建初始化参数
-	 * @return 包含初始化参数的Map对象,用于后续的请求配置
-	 */
-
-	public  Map<String, String> getInitParameter() {
-		String timestamp = LocalDateTimeUtil.format(LocalDateTime.now(ZoneOffset.UTC), "yyyy-MM-dd'T'HH:mm:ss'Z'");
-		Map<String, String> map = new HashMap<String, String>();
-		// 公共参数
-		map.put("Format", "JSON");
-		map.put("Version", "2018-01-20");
-		map.put("AccessKeyId", ymlConfig.getAccessKey());
-		map.put("SignatureMethod", "HMAC-SHA1");
-		map.put("Timestamp", timestamp);
-		map.put("SignatureVersion", "1.0");
-		map.put("SignatureNonce", RandomUtil.randomNumbers(14));
-		map.put("RegionId", ymlConfig.getRegionId());
-		return map;
-	}
-	/**
-	 * 查询设备详情
-	 * @param deviceName  设备名称
-	 * @return 返回设备的详细信息的JSONObject对象 返回阿里云设备参数
-	 */
-
-	public JSONObject deviceQuery(String deviceName,String userId,String network) {
-		JSONObject data = new JSONObject();
-		Map<String, String> map = getInitParameter();
-		map.put("Action", "QueryDeviceDetail");
-		if (StringUtils.isNotEmpty(ymlConfig.getInstanceId())) {
-			map.put("IotInstanceId", ymlConfig.getInstanceId());
-		}
-		if ("wifi".equalsIgnoreCase(network)){
-			map.put("userId", userId);
-			map.put("network", network);
-			map.put("DeviceName", deviceName);
-
-		}else {
-			map.put("DeviceName", deviceName);
-		}
-		map.put("ProductKey", ymlConfig.getProductKey());
-
-		try {
-			String signature = SignatureUtils.generate("GET", map, ymlConfig.getAccessKeySecret());
-			map.put("Signature", signature);
-			Map<String, Object> httpParamMap = new HashMap<String, Object>(map);
-			String result = HttpUtil.get(Config.API_ADDRESS, httpParamMap);
-			System.out.println("result=====" + result);
-			JSONObject queryJson = (JSONObject) JSONObject.parse(result);
-			if (queryJson.getBoolean("Success")) {
-				data = queryJson.getJSONObject("Data");
-			}
-		} catch (Exception e) {
-			logger.error("物联网平台设备查询失败", e);
-		}
-		return data;
-	}
-	/**
-	 * 设备注册函数
-	 * 该函数用于向物联网平台注册一个新的设备
-	 * @param deviceName  设备名称,用于标识待注册的设备
-	 * @return 返回一个包含注册结果的JSONObject对象,包括设备的相关信息和状态
-	 */
-	public  JSONObject deviceRegist(String deviceName,String userId,String network) {
-
-		JSONObject data = new JSONObject();
-		Map<String, String> map = getInitParameter();
-
-		map.put("Action", "RegisterDevice");
-		if (StringUtils.isNotEmpty(ymlConfig.getInstanceId())) {
-			map.put("IotInstanceId", ymlConfig.getInstanceId());
-		}
-		//把设备名称和产品key加入请求的参数中
-		if ("wifi".equalsIgnoreCase(network)){
-			map.put("userId", userId);
-			map.put("network", network);
-			map.put("DeviceName", deviceName);
-		}else {
-			map.put("DeviceName", deviceName);
-		}
-		map.put("ProductKey", ymlConfig.getProductKey());
-
-		try {
-			String signature = SignatureUtils.generate("GET", map, ymlConfig.getAccessKeySecret());
-			map.put("Signature", signature);
-			Map<String, Object> httpParamMap = new HashMap<String, Object>(map);
-			String result = HttpUtil.get(Config.API_ADDRESS, httpParamMap);
-			System.out.println("result====" + result);
-			JSONObject queryJson = (JSONObject) JSONObject.parse(result);
-			if (queryJson.getBoolean("Success")) {
-				data = queryJson.getJSONObject("Data");
-			}
-		} catch (Exception e) {
-			logger.error("物联网平台设备查询失败", e);
-		}
-		return data;
-	}
+    //定义一个私有的静态Logger实例,用于记录AliDeviceHttp类的日志信息
+    private static Logger logger = LoggerFactory.getLogger(AliDeviceHttp.class);
+    @Autowired
+    YmlConfig ymlConfig;
+
+    /**
+     * 构建初始化参数
+     *
+     * @return 包含初始化参数的Map对象,用于后续的请求配置
+     */
+
+    public Map<String, String> getInitParameter() {
+        String timestamp = LocalDateTimeUtil.format(LocalDateTime.now(ZoneOffset.UTC), "yyyy-MM-dd'T'HH:mm:ss'Z'");
+        Map<String, String> map = new HashMap<String, String>();
+        // 公共参数
+        map.put("Format", "JSON");
+        map.put("Version", "2018-01-20");
+        map.put("AccessKeyId", ymlConfig.getAccessKey());
+        map.put("SignatureMethod", "HMAC-SHA1");
+        map.put("Timestamp", timestamp);
+        map.put("SignatureVersion", "1.0");
+        map.put("SignatureNonce", RandomUtil.randomNumbers(14));
+        map.put("RegionId", ymlConfig.getRegionId());
+        return map;
+    }
+
+    /**
+     * 查询设备详情
+     *
+     * @param deviceName 设备名称
+     * @return 返回设备的详细信息的JSONObject对象 返回阿里云设备参数
+     */
+
+    public JSONObject deviceQuery(String deviceName) {
+        JSONObject data = new JSONObject();
+        Map<String, String> map = getInitParameter();
+        map.put("Action", "QueryDeviceDetail");
+        if (StringUtils.isNotEmpty(ymlConfig.getInstanceId())) {
+            map.put("IotInstanceId", ymlConfig.getInstanceId());
+        }
+
+        map.put("DeviceName", deviceName);
+        map.put("ProductKey", ymlConfig.getProductKey());
+
+        try {
+            String signature = SignatureUtils.generate("GET", map, ymlConfig.getAccessKeySecret());
+            map.put("Signature", signature);
+            Map<String, Object> httpParamMap = new HashMap<String, Object>(map);
+            String result = HttpUtil.get(Config.API_ADDRESS, httpParamMap);
+            System.out.println("result=====" + result);
+            JSONObject queryJson = (JSONObject) JSONObject.parse(result);
+            if (queryJson.getBoolean("Success")) {
+                data = queryJson.getJSONObject("Data");
+            }
+        } catch (Exception e) {
+            logger.error("物联网平台设备查询失败", e);
+        }
+        return data;
+    }
+
+    /**
+     * 设备注册函数
+     * 该函数用于向物联网平台注册一个新的设备
+     *
+     * @param deviceName 设备名称,用于标识待注册的设备
+     * @return 返回一个包含注册结果的JSONObject对象,包括设备的相关信息和状态
+     */
+    public JSONObject deviceRegist(String deviceName) {
+
+        JSONObject data = new JSONObject();
+        Map<String, String> map = getInitParameter();
+
+        map.put("Action", "RegisterDevice");
+        if (StringUtils.isNotEmpty(ymlConfig.getInstanceId())) {
+            map.put("IotInstanceId", ymlConfig.getInstanceId());
+        }
+        //把设备名称和产品key加入请求的参数中
+        map.put("DeviceName", deviceName);
+        map.put("ProductKey", ymlConfig.getProductKey());
+
+        try {
+            String signature = SignatureUtils.generate("GET", map, ymlConfig.getAccessKeySecret());
+            map.put("Signature", signature);
+            Map<String, Object> httpParamMap = new HashMap<String, Object>(map);
+            String result = HttpUtil.get(Config.API_ADDRESS, httpParamMap);
+            System.out.println("result====" + result);
+            JSONObject queryJson = (JSONObject) JSONObject.parse(result);
+            if (queryJson.getBoolean("Success")) {
+                data = queryJson.getJSONObject("Data");
+            }
+        } catch (Exception e) {
+            logger.error("物联网平台设备查询失败", e);
+        }
+        return data;
+    }
+
+
 
 
 }

+ 182 - 59
src/main/java/com/tuoren/forward/netty/MyServer.java

@@ -4,6 +4,9 @@ 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.netty.common.NetworkProtocol;
+import com.tuoren.forward.netty.common.NetworkType;
+import com.tuoren.forward.netty.common.Platform;
 import com.tuoren.forward.entity.RegistLog;
 import com.tuoren.forward.entity.User;
 import com.tuoren.forward.entity.UserConfig;
@@ -11,9 +14,11 @@ import com.tuoren.forward.mapper.RegistLogMapper;
 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.RegistLogService;
-import com.tuoren.forward.util.JsonExtractor;
+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;
 import io.netty.buffer.ByteBuf;
 import io.netty.channel.*;
@@ -148,7 +153,7 @@ class MyServerHandler extends ChannelInboundHandlerAdapter {
             registLog.setResult(jsonString);//保存结果
 
             int code = jsonObject.getIntValue("code");
-            if (code == 0){
+            if (code == 200){
                 registLog.setStatus("0");//成功
             }else {
                 registLog.setStatus("1");//失败
@@ -189,78 +194,139 @@ class MyServerHandler extends ChannelInboundHandlerAdapter {
 
     private String handleRegister(String msgStr) throws Exception {
         JSONObject json = new JSONObject();
-        json.put("code", 200);
+        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();
         }
+
         JSONObject paramJson = JSONObject.parseObject(msgStr);
-        String network = paramJson.getString("network");
-        if (StrUtil.isEmpty(network)) {
-            json.put("network", "NB-IoT");
-        }
-        String protocol = paramJson.getString("protocol");
-        if (StrUtil.isEmpty(protocol)) {
-            json.put("protocol", "CoAP");
-        }
-        String deviceName = paramJson.getString("deviceId"); //device表中的mac
-        String userId = paramJson.getString("userId"); // user表中的code
-        if (StrUtil.isEmpty(userId)) {
-            json.put("userId", "1000");
-        }
-        String version = paramJson.getString("version");
-        if (StrUtil.isEmpty(version)) {
-            json.put("version", "1.0");
+
+        //网络类型
+        Integer networkCode = null;
+        try {
+            networkCode = paramJson.getIntValue("networkType");
+
+        } catch (Exception e) {
+            logger.warn("如果networkType为空或者不是整数, 使用默认值: NB-IoT", e);
         }
-        if ("WIFI".equalsIgnoreCase(network)) {
-            JSONObject registerData = getRegisterData(deviceName, userId, network);
-            //如果注册数据不为空,则构建响应消息
-            if (!registerData.isEmpty()) {
-                json.put("code", 0);
-                json.put("type", 0x15);
-                json.put("deviceId", deviceName);
-
-                User user = userMapper.selectByCode(userId);
-                String id = user.getId();
-                UserConfig userConfig = userConfigMapper.selectByPrimaryKey(id);
-                String wifi = userConfig.getWifi();
-                Integer port = userConfig.getLocalPort();
-                String address = userConfig.getLocalAddress();
-
-                // 将WiFi字符串转换成JSON数组
-                JSONArray wifiArray = JSON.parseArray(wifi);
-                json.put("address", address);
-                json.put("port", port);
-                json.put("wifi", wifiArray);
-            }
-        } else {
+        NetworkType network = NetworkType.NetworkTypeName(networkCode);
+
+
+        //判断是否为老代码
+        boolean isOldCode = paramJson.containsKey("platform");
+        if (isOldCode) {
+            /**
+             * 老代码处理
+             */
+            String deviceName = paramJson.getString("deviceId"); //device表中的mac
+
             //执行设备注册操作或查询操作
-            JSONObject registerData = getRegisterData(deviceName, userId, network);
-            //如果注册数据不为空,则构建响应消息
-            if (!registerData.isEmpty()) {
-                json.put("code", 0);
-                json.put("deviceId", deviceName);
+            JSONObject registData = aliDeviceHttp.deviceRegist(deviceName);
+            if (registData.isEmpty()) {
+                registData = aliDeviceHttp.deviceQuery(deviceName);
+            }
+            if (!registData.isEmpty()) {
+                json.put("code", NExcCode.SUCCESS.getCode());
                 json.put("type", 0x15);
                 json.put("address", Config.COAP_ADDRESS);
                 json.put("port", Config.COAP_PORT);
-                json.put("deviceSecret", registerData.getString("DeviceSecret"));
-                json.put("productKey", registerData.getString("ProductKey"));
+                json.put("deviceName", deviceName);
+                json.put("deviceSecret", registData.getString("DeviceSecret"));
+                json.put("productKey", registData.getString("ProductKey"));
             }
 
-        }
-        return json.toString();
+        }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");
+            //如果为空,则默认为1dbfd476b7nm2
+            productId = StrUtil.isBlank(productId) ? "1dbfd476b7nm2" : productId;
+
+            //设备编号
+            String deviceName = paramJson.getString("deviceId"); //device表中的mac
+
+            //编码
+            String userId = paramJson.getString("userId"); // user表中的code
+
+            /**
+             * 先判断UserId和DeviceId是否存在
+             * 如果存在进行注册,如果不存在返回code 401
+             *
+             */
+            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();
+            }
 
-    }
 
-    // 获取注册数据
-    public JSONObject getRegisterData(String deviceName, String userId, String network) {
-        JSONObject registData = aliDeviceHttp.deviceRegist(deviceName, userId, network);
-        if (registData.isEmpty()) {
-            registData = aliDeviceHttp.deviceQuery(deviceName, userId, network);
+            //根据网络类型进行判断
+            if (NetworkType.WIFI.equals(network)) {
+                /**
+                 * wifi泵
+                 */
+                platform = Platform.PlatformName(Platform.LOCAL.getCode());
+                // 处理WiFi注册
+                json = handleWifiRegistration(paramJson, network, platform, protocol, productId, deviceName, userId);
+
+            } else {
+
+                /**
+                 * 新NB,4G泵
+                 */
+                platform = Platform.PlatformName(Platform.ALIYUN.getCode());
+
+                //执行设备注册操作或查询操作
+                JSONObject registData = aliDeviceHttp.deviceRegist(deviceName);
+                if (registData.isEmpty()) {
+                    registData = aliDeviceHttp.deviceQuery(deviceName);
+                }
+                //如果注册数据不为空,则构建响应消息
+                if (!registData.isEmpty()) {
+
+                    json.put("code", NExcCode.SUCCESS.getCode());
+                    json.put("type", 0x15);
+                    json.put("version", version);
+                    json.put("platform", platform.getCode());
+                    json.put("networkType", network.getCode());
+                    json.put("networkProtocol", protocol.getCode());
+                    json.put("productId", productId);
+                    json.put("deviceId", deviceName);
+                    json.put("userId", userId);
+                    json.put("address", Config.COAP_ADDRESS);
+                    json.put("port", Config.COAP_PORT);
+                    json.put("deviceSecret", registData.getString("DeviceSecret"));
+                    json.put("productKey", registData.getString("ProductKey"));
+                }
+
+            }
         }
-        return registData;
+        return json.toString();
     }
 
+
     //获取参数中的deviceId
     private String extractDeviceId(String msgStr) {
         try {
@@ -271,7 +337,6 @@ class MyServerHandler extends ChannelInboundHandlerAdapter {
         }
     }
 
-
     //截取JSON数组中的数据
     private JSONObject validateAndParseJson(String jsonString) throws Exception {
         try {
@@ -283,6 +348,64 @@ class MyServerHandler extends ChannelInboundHandlerAdapter {
     }
 
 
-}
 
 
+    //新wifi注册信息
+    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;
+
+        json.put("code", NExcCode.SUCCESS.getCode());
+        json.put("type", 0x15);
+        json.put("version", version);
+        json.put("platform", platform.getCode());
+        json.put("networkType", network.getCode());
+        json.put("networkProtocol", protocol.getCode());
+        json.put("productId", 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();
+
+        // 将地址数据转换成JSON数组
+        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("address", networkInfo.getString("address"));
+                json.put("port", networkInfo.getIntValue("port"));
+                found = true;
+                break;
+            }
+        }
+
+        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;
+        }
+
+        // 将WiFi字符串转换成JSON数组
+        JSONArray wifiArray = JSON.parseArray(wifi);
+        // 调用方法转换wifi数据
+        JSONArray transformWifiArray = WifiDataTrans.transformWifiArray(wifiArray);
+        json.put("deviceSecret",deviceSecret);
+        json.put("wifi", transformWifiArray);
+
+        return json;
+    }
+
+
+}

+ 8 - 64
src/main/java/com/tuoren/forward/netty/YmlConfig.java

@@ -1,5 +1,6 @@
 package com.tuoren.forward.netty;
 
+import lombok.Data;
 import org.springframework.boot.context.properties.ConfigurationProperties;
 import org.springframework.context.annotation.PropertySource;
 import org.springframework.stereotype.Component;
@@ -11,79 +12,22 @@ import org.springframework.stereotype.Component;
  * @Description Yml文件数据
  */
 @ConfigurationProperties(prefix = "register")
+@Data
 public class YmlConfig {
     private int port;
+
     private String accessKey;
+
     private String accessKeySecret;
+
     private String productKey;
+
     private String productSecret;
+
     private String instanceId;
+
     private String regionId;
 
     private String logPath;
 
-
-    public String getLogPath() {
-        return logPath;
-    }
-
-    public void setLogPath(String logPath) {
-        this.logPath = logPath;
-    }
-
-    public int getPort() {
-        return port;
-    }
-
-    public void setPort(int port) {
-        this.port = port;
-    }
-
-    public String getAccessKey() {
-        return accessKey;
-    }
-
-    public void setAccessKey(String accessKey) {
-        this.accessKey = accessKey;
-    }
-
-    public String getAccessKeySecret() {
-        return accessKeySecret;
-    }
-
-    public void setAccessKeySecret(String accessKeySecret) {
-        this.accessKeySecret = accessKeySecret;
-    }
-
-    public String getProductKey() {
-        return productKey;
-    }
-
-    public void setProductKey(String productKey) {
-        this.productKey = productKey;
-    }
-
-    public String getProductSecret() {
-        return productSecret;
-    }
-
-    public void setProductSecret(String productSecret) {
-        this.productSecret = productSecret;
-    }
-
-    public String getInstanceId() {
-        return instanceId;
-    }
-
-    public void setInstanceId(String instanceId) {
-        this.instanceId = instanceId;
-    }
-
-    public String getRegionId() {
-        return regionId;
-    }
-
-    public void setRegionId(String regionId) {
-        this.regionId = regionId;
-    }
 }

+ 17 - 10
src/main/java/com/tuoren/forward/util/JsonExtractor.java → src/main/java/com/tuoren/forward/netty/common/JsonExtractor.java

@@ -1,4 +1,4 @@
-package com.tuoren.forward.util;
+package com.tuoren.forward.netty.common;
 
 import com.alibaba.fastjson2.JSON;
 import com.alibaba.fastjson2.JSONObject;
@@ -19,26 +19,33 @@ public class JsonExtractor {
             //创建新的JSON对象
             JSONObject newJson = new JSONObject();
 
+
             //从原始JSON中提取需要的字段
+            newJson.put("code", orginalObj.getIntValue("code"));
+            newJson.put("version", orginalObj.getIntValue("version"));
+            newJson.put("platform", orginalObj.getIntValue("platform"));
+            newJson.put("networkType", orginalObj.getIntValue("networkType"));
+            newJson.put("networkProtocol", orginalObj.getIntValue("networkProtocol"));
+            newJson.put("productId", orginalObj.getString("productId"));
+            newJson.put("userId", orginalObj.getString("userId"));
             newJson.put("deviceId", orginalObj.getString("deviceId"));
-            newJson.put("network", orginalObj.getString("network"));
-            newJson.put("address", orginalObj.getString("address"));
-            newJson.put("port", orginalObj.getString("port"));
-            newJson.put("protocol", orginalObj.getString("protocol"));
-
-            // 处理 wifi 字段,确保它是一个 JSON 数组
+            newJson.put("deviceSecret", orginalObj.getString("deviceSecret"));
             Object wifi = orginalObj.get("wifi");
             if (wifi instanceof String) {
                 // 如果 wifi 是字符串,尝试将其解析为 JSON 数组
                 wifi = JSON.parseArray((String) wifi);
             }
             newJson.put("wifi", wifi);
-            newJson.put("userId", orginalObj.getString("userId"));
-            newJson.put("version", orginalObj.getString("version"));
+
+            //老版本
+            newJson.put("address", orginalObj.getString("address"));
+            newJson.put("port", orginalObj.getIntValue("port"));
+            newJson.put("deviceName", orginalObj.getString("deviceName"));
+            newJson.put("deviceSecret", orginalObj.getString("deviceSecret"));
+            newJson.put("productKey", orginalObj.getString("productKey"));
 
             //将新的JSON对象转换成字符串
             return newJson.toJSONString();
-//            return newJson.toString();
         } catch (Exception e) {
 
             e.printStackTrace();

+ 2 - 2
src/main/java/com/tuoren/forward/service/RegistLogService.java

@@ -33,8 +33,8 @@ public class RegistLogService {
 
     public ResultPage<RegistLog> search(RegistLogSearchReq req) {
         Page<Object> page = PageHelper.startPage(req.getPage(), req.getSize());
-//        RegistLogDto RegistLogDto = new RegistLogDto();
-//        BeanUtils.copyProperties(req, RegistLogDto);
+        RegistLogDto RegistLogDto = new RegistLogDto();
+        BeanUtils.copyProperties(req, RegistLogDto);
         List<RegistLog> registLogs = registLogMapper.QueryCondition(req);
 
         return ResultPage.success(registLogs,page.getTotal());

+ 6 - 9
src/main/java/com/tuoren/forward/service/UserConfigService.java

@@ -33,20 +33,17 @@ public class UserConfigService {
         /**
          * 如果id是空进行添加,如果id存在进行修改
          */
-        if (StringUtils.isAnyEmpty(req.getId())) {
-            return ResultData.fail(CommonConstant.LACK_PARAM);
-        }
-        UserConfig key = userConfigMapper.selectByPrimaryKey(req.getId());
-        if (key == null){
-            Date date = new Date();
+        //获取当前时间
+        Date date = new Date();
+        //尝试根据id获取用户配置
+        UserConfig existingConfig = userConfigMapper.selectByPrimaryKey(req.getId());
+        if (existingConfig == null) {
             req.setCreatetime(date);
             userConfigMapper.insert(req);
-        }else {
-            Date date = new Date();
+        } else {
             req.setModifytime(date);
             userConfigMapper.updateByPrimaryKeySelective(req);
         }
-
         return Result.success();
 
     }

+ 0 - 41
src/main/java/com/tuoren/forward/util/WifiListDeserializer.java

@@ -1,41 +0,0 @@
-package com.tuoren.forward.util;
-
-import com.fasterxml.jackson.core.JacksonException;
-import com.fasterxml.jackson.core.JsonParser;
-import com.fasterxml.jackson.databind.DeserializationContext;
-import com.fasterxml.jackson.databind.JsonDeserializer;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-import java.io.IOException;
-import java.util.Iterator;
-
-/**
- * @Author zzy
- * @Data 2024/9/19
- * @Version 1.0
- * @Description XXX
- */
-public class WifiListDeserializer extends JsonDeserializer<String>{
-    @Override
-    public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException {
-        ObjectMapper mapper = (ObjectMapper) p.getCodec();
-        JsonNode node = mapper.readTree(p);
-
-        StringBuilder wifiStringBuilder = new StringBuilder();
-
-        if (node.isArray()) {
-            for (Iterator<JsonNode> it = node.elements(); it.hasNext(); ) {
-                JsonNode wifiNode = it.next();
-                String name = wifiNode.get("name").asText();
-                String password = wifiNode.get("password").asText();
-                wifiStringBuilder.append("{\"name\":\"").append(name).append("\",\"password\":\"").append(password).append("\"}");
-                if (it.hasNext()) {
-                    wifiStringBuilder.append(",");
-                }
-            }
-        }
-
-        return "[" + wifiStringBuilder.toString() + "]";
-    }
-}

+ 15 - 13
src/main/resources/application.yml

@@ -85,21 +85,23 @@ spring:
       username: forward
       password: 1qaz!QAZ
 mqtt:
-    hostUrl: tcp://192.168.100.32:1883        # 你自己服务器的地址和端口,这个需要改
-    clientId: fe80aba1dfd66b3576ce                            # 这个改不改随意,但不同的客户端肯定不能一样
-    username: server
-    password: 1qaz!QAZ
-    timeout: 100
-    keepalive: 100
+  hostUrl: tcp://192.168.100.32:1883        # 你自己服务器的地址和端口,这个需要改
+  clientId: fe80aba1dfd66b3576ce                            # 这个改不改随意,但不同的客户端肯定不能一样
+  username: server
+  password: 1qaz!QAZ
+  timeout: 100
+  keepalive: 100
 
 register:
-    port: 8888
-    accessKey: LTAI5tRaK95AqvWiQ9LspZ3q
-    accessKeySecret: wZUpYGeztNcV4tGbBLfK2OvxnZzZF3
-    productKey: k0g9w9xRhhi
-    productSecret: TLkQNSgJnEDP2Rx7
-    instanceId: iot-06z00hi2guq5qi3
-    regionId: cn-shanghai
+  port: 8888
+  accessKey: LTAI5tRaK95AqvWiQ9LspZ3q
+  accessKeySecret: wZUpYGeztNcV4tGbBLfK2OvxnZzZF3
+  productKey: k0g9w9xRhhi
+  productSecret: TLkQNSgJnEDP2Rx7
+  instanceId: iot-06z00hi2guq5qi3
+  regionId: cn-shanghai
+
+
 
 
 

+ 4 - 1
src/main/resources/mapper/RegistLogMapper.xml

@@ -131,6 +131,9 @@
         and createtime = #{createtime,jdbcType=VARCHAR}
       </if>
     </where>
-    ORDER BY createtime DESC
+    <if test="sort != null and sort != ''">
+    ORDER BY ${sort}
+      <if test="order !=null "> ${order} </if>
+    </if>
   </select>
 </mapper>

+ 107 - 118
src/main/resources/mapper/UserConfigMapper.xml

@@ -1,124 +1,113 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 <mapper namespace="com.tuoren.forward.mapper.UserConfigMapper">
-  <resultMap id="BaseResultMap" type="com.tuoren.forward.entity.UserConfig">
-    <id column="id" jdbcType="VARCHAR" property="id" />
-    <result column="wifi" jdbcType="VARCHAR" property="wifi" />
-    <result column="local_address" jdbcType="VARCHAR" property="localAddress" />
-    <result column="local_port" jdbcType="INTEGER" property="localPort" />
-    <result column="device_secret" jdbcType="VARCHAR" property="deviceSecret" />
-    <result column="createtime" jdbcType="TIMESTAMP" property="createtime" />
-    <result column="modifytime" jdbcType="TIMESTAMP" property="modifytime" />
-  </resultMap>
-  <sql id="Base_Column_List">
-    id, wifi, local_address, local_port, device_secret, createtime, modifytime
-  </sql>
-  <select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
-    select
-    <include refid="Base_Column_List" />
-    from user_config
-    where id = #{id,jdbcType=VARCHAR}
-  </select>
-  <delete id="deleteByPrimaryKey" parameterType="java.lang.String">
-    delete from user_config
-    where id = #{id,jdbcType=VARCHAR}
-  </delete>
-  <insert id="insert" parameterType="com.tuoren.forward.entity.UserConfig">
-    insert into user_config (id, wifi, local_address,
-      local_port,device_secret, createtime, modifytime
-      )
-    values (#{id,jdbcType=VARCHAR}, #{wifi,jdbcType=VARCHAR}, #{localAddress,jdbcType=VARCHAR},
-      #{localPort,jdbcType=INTEGER}, #{deviceSecret,jdbcType=VARCHAR}, #{createtime,jdbcType=TIMESTAMP}, #{modifytime,jdbcType=TIMESTAMP}
-      )
-  </insert>
-  <insert id="insertSelective" parameterType="com.tuoren.forward.entity.UserConfig">
-    insert into user_config
-    <trim prefix="(" suffix=")" suffixOverrides=",">
-      <if test="id != null">
-        id,
-      </if>
-      <if test="wifi != null">
-        wifi,
-      </if>
-      <if test="localAddress != null">
-        local_address,
-      </if>
-      <if test="localPort != null">
-        local_port,
-      </if>
-      <if test="deviceSecret != null">
-        device_secret,
-      </if>
-      <if test="createtime != null">
-        createtime,
-      </if>
-      <if test="modifytime != null">
-        modifytime,
-      </if>
-    </trim>
-    <trim prefix="values (" suffix=")" suffixOverrides=",">
-      <if test="id != null">
-        #{id,jdbcType=VARCHAR},
-      </if>
-      <if test="wifi != null">
-        #{wifi,jdbcType=VARCHAR},
-      </if>
-      <if test="localAddress != null">
-        #{localAddress,jdbcType=VARCHAR},
-      </if>
-      <if test="localPort != null">
-        #{localPort,jdbcType=INTEGER},
-      </if>
-      <if test="deviceSecret != null">
-        #{deviceSecret,jdbcType=VARCHAR},
-      </if>
-      <if test="createtime != null">
-        #{createtime,jdbcType=TIMESTAMP},
-      </if>
-      <if test="modifytime != null">
-        #{modifytime,jdbcType=TIMESTAMP},
-      </if>
-    </trim>
-  </insert>
-  <update id="updateByPrimaryKeySelective" parameterType="com.tuoren.forward.entity.UserConfig">
-    update user_config
-    <set>
-      <if test="wifi != null">
-        wifi = #{wifi,jdbcType=VARCHAR},
-      </if>
-      <if test="localAddress != null">
-        local_address = #{localAddress,jdbcType=VARCHAR},
-      </if>
-      <if test="localPort != null">
-        local_port = #{localPort,jdbcType=INTEGER},
-      </if>
-      <if test="deviceSecret != null">
-        device_secret = #{deviceSecret,jdbcType=VARCHAR},
-      </if>
-      <if test="createtime != null">
-        createtime = #{createtime,jdbcType=TIMESTAMP},
-      </if>
-      <if test="modifytime != null">
-        modifytime = #{modifytime,jdbcType=TIMESTAMP},
-      </if>
-    </set>
-    where id = #{id,jdbcType=VARCHAR}
-  </update>
-  <update id="updateByPrimaryKey" parameterType="com.tuoren.forward.entity.UserConfig">
-    update user_config
-    set wifi = #{wifi,jdbcType=VARCHAR},
-      local_address = #{localAddress,jdbcType=VARCHAR},
-      local_port = #{localPort,jdbcType=INTEGER},
-      device_secret = #{deviceSecret,jdbcType=VARCHAR},
-      createtime = #{createtime,jdbcType=TIMESTAMP},
-      modifytime = #{modifytime,jdbcType=TIMESTAMP}
-    where id = #{id,jdbcType=VARCHAR}
-  </update>
+    <resultMap id="BaseResultMap" type="com.tuoren.forward.entity.UserConfig">
+        <id column="id" jdbcType="VARCHAR" property="id"/>
+        <result column="wifi" jdbcType="VARCHAR" property="wifi"/>
+        <result column="address" jdbcType="VARCHAR" property="address"/>
+        <result column="device_secret" jdbcType="VARCHAR" property="deviceSecret"/>
+        <result column="createtime" jdbcType="TIMESTAMP" property="createtime"/>
+        <result column="modifytime" jdbcType="TIMESTAMP" property="modifytime"/>
+    </resultMap>
+    <sql id="Base_Column_List">
+        id, wifi, address , device_secret, createtime, modifytime
+    </sql>
+    <select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
+        select
+        <include refid="Base_Column_List"/>
+        from user_config
+        where id = #{id,jdbcType=VARCHAR}
+    </select>
+    <delete id="deleteByPrimaryKey" parameterType="java.lang.String">
+        delete
+        from user_config
+        where id = #{id,jdbcType=VARCHAR}
+    </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},
+                #{localAddress,jdbcType=VARCHAR},
+                #{createtime,jdbcType=TIMESTAMP},
+                #{modifytime,jdbcType=TIMESTAMP})
+    </insert>
+    <insert id="insertSelective" parameterType="com.tuoren.forward.entity.UserConfig">
+        insert into user_config
+        <trim prefix="(" suffix=")" suffixOverrides=",">
+            <if test="id != null">
+                id,
+            </if>
+            <if test="wifi != null">
+                wifi,
+            </if>
+            <if test="address != null">
+                address,
+            </if>
+            <if test="deviceSecret != null">
+                device_secret,
+            </if>
+            <if test="createtime != null">
+                createtime,
+            </if>
+            <if test="modifytime != null">
+                modifytime,
+            </if>
+        </trim>
+        <trim prefix="values (" suffix=")" suffixOverrides=",">
+            <if test="id != null">
+                #{id,jdbcType=VARCHAR},
+            </if>
+            <if test="wifi != null">
+                #{wifi,jdbcType=VARCHAR},
+            </if>
+            <if test="address != null">
+                #{address,jdbcType=VARCHAR},
+            </if>
+            <if test="deviceSecret != null">
+                #{deviceSecret,jdbcType=VARCHAR},
+            </if>
+            <if test="createtime != null">
+                #{createtime,jdbcType=TIMESTAMP},
+            </if>
+            <if test="modifytime != null">
+                #{modifytime,jdbcType=TIMESTAMP},
+            </if>
+        </trim>
+    </insert>
+    <update id="updateByPrimaryKeySelective" parameterType="com.tuoren.forward.entity.UserConfig">
+        update user_config
+        <set>
+            <if test="wifi != null">
+                wifi = #{wifi,jdbcType=VARCHAR},
+            </if>
+            <if test="address != null">
+                address = #{address,jdbcType=VARCHAR},
+            </if>
+            <if test="deviceSecret != null">
+                device_secret = #{deviceSecret,jdbcType=VARCHAR},
+            </if>
+            <if test="createtime != null">
+                createtime = #{createtime,jdbcType=TIMESTAMP},
+            </if>
+            <if test="modifytime != null">
+                modifytime = #{modifytime,jdbcType=TIMESTAMP},
+            </if>
+        </set>
+        where id = #{id,jdbcType=VARCHAR}
+    </update>
+    <update id="updateByPrimaryKey" parameterType="com.tuoren.forward.entity.UserConfig">
+        update user_config
+        set wifi          = #{wifi,jdbcType=VARCHAR},
+            address       = #{address,jdbcType=VARCHAR},
+            device_secret = #{deviceSecret,jdbcType=VARCHAR},
+            createtime    = #{createtime,jdbcType=TIMESTAMP},
+            modifytime    = #{modifytime,jdbcType=TIMESTAMP}
+        where id = #{id,jdbcType=VARCHAR}
+    </update>
 
-  <select id="selectOneOr" resultMap="BaseResultMap">
-    select
-    <include refid="Base_Column_List" />
-    from user_config
-    where wifi = #{wifi,jdbcType=VARCHAR} or  local_address = #{localAddress,jdbcType=VARCHAR} or local_port = #{localPort,jdbcType=INTEGER}, limit 1
+    <select id="selectOneOr" resultMap="BaseResultMap">
+        select
+        <include refid="Base_Column_List"/>
+        from user_config
+        where wifi = #{wifi,jdbcType=VARCHAR}  limit 1
     </select>
 </mapper>