|
|
@@ -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);
|
|
|
+ }
|
|
|
+ }
|
|
|
|
|
|
-}
|
|
|
+}
|