From 8b66be08179b026cb0e601733dacd43de97e5b01 Mon Sep 17 00:00:00 2001 From: hxb <hxb@hdlchina.com.cn> Date: 星期二, 21 十二月 2021 10:20:34 +0800 Subject: [PATCH] 完善下网关上网重连功能及广播设备基本数据 --- HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/request/BroadcastRequest.java | 54 ++++ HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/config/HDLLinkConfig.java | 11 HDLSDK/hdl-common/src/main/java/com/hdl/sdk/common/config/TopicConstant.java | 10 HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/SocketOptions.java | 85 ----- HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/SocketBoot.java | 286 ++++++--------------- HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/request/AuthenticateRequest.java | 157 +++++++++++ HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/socket/HDLSocket.java | 51 ++- HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/socket/HdlSocketHelper.java | 2 HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/HDLLink.java | 27 + HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/socket/HDLAuthSocket.java | 14 HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/client/TcpClient.java | 38 ++ HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/client/IClient.java | 5 HDLSDK/app/src/main/java/com/hdl/hdlsdk/MainActivity.java | 20 + 13 files changed, 438 insertions(+), 322 deletions(-) diff --git a/HDLSDK/app/src/main/java/com/hdl/hdlsdk/MainActivity.java b/HDLSDK/app/src/main/java/com/hdl/hdlsdk/MainActivity.java index 2033551..2533b47 100644 --- a/HDLSDK/app/src/main/java/com/hdl/hdlsdk/MainActivity.java +++ b/HDLSDK/app/src/main/java/com/hdl/hdlsdk/MainActivity.java @@ -82,7 +82,7 @@ rv.setLayoutManager(new LinearLayoutManager(this)); checkIfCertified(); - + initDeviceInfo(); registerAllTopicsListener(); ActivityResultLauncher<String[]> launcher = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), new ActivityResultCallback<Map<String, Boolean>>() { @@ -202,6 +202,7 @@ @Override public void onMessage(Object msg) { LinkResponse response = (LinkResponse) msg; + handleLinkResponse(response); } }; HDLLink.getInstance().registerAllTopicsListener(allTopicsListener); @@ -250,6 +251,23 @@ HDLLink.getInstance().removeAllTopicsListener(allTopicsListener); } + void initDeviceInfo() + { + AuthenticateRequest.AuthenticateDeviceInfoBean infoBean = new AuthenticateRequest.AuthenticateDeviceInfoBean(); + infoBean.setDeviceMAC("123456789"); + infoBean.setIPMAC("12345678900"); + infoBean.setDeviceName("闊充箰鎾斁鍣�");//璁惧鍚嶅瓧 + infoBean.setDeviceModel("MCLog.431");//璁惧鍨嬪彿 + infoBean.setAccessMode("WIFI"); + infoBean.setIPGateway("192.168.88.1"); + infoBean.setIPAddress(IpUtils.getIP(this)); + infoBean.setHw_version("HW2.0"); + infoBean.setFw_version("Fw1.0"); + infoBean.setOID("010105000000FE08"); + infoBean.setSid("010105000000FE08110100000000"); + HDLLinkConfig.getInstance().setDeviceInfoBean(infoBean); + } + /** * 鍏ョ綉璁よ瘉 */ diff --git a/HDLSDK/hdl-common/src/main/java/com/hdl/sdk/common/config/TopicConstant.java b/HDLSDK/hdl-common/src/main/java/com/hdl/sdk/common/config/TopicConstant.java index 0ed30c0..9f4a148 100644 --- a/HDLSDK/hdl-common/src/main/java/com/hdl/sdk/common/config/TopicConstant.java +++ b/HDLSDK/hdl-common/src/main/java/com/hdl/sdk/common/config/TopicConstant.java @@ -77,4 +77,14 @@ //8.6鍦烘櫙鍒犻櫎 public static final String SCENE_DELETE = "/user/%s/custom/scene/delete"; + /** + * 璁惧杩炴帴TCP涔嬪墠骞挎挱 + */ + public static final String BROADCAST="/user/all/custom/gateway/broadcast"; + + /** + * 涓荤綉鍏冲洖澶� + */ + public static final String BROADCAST_REPLY="/user/all/custom/gateway/broadcast_reply"; + } diff --git a/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/HDLLink.java b/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/HDLLink.java index fc815f4..debe128 100644 --- a/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/HDLLink.java +++ b/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/HDLLink.java @@ -177,14 +177,25 @@ } /** - * 閫氱敤UDP骞挎挱鍙戦�佹寚浠� + * 閫氱敤UDP鍙戦�佹寚浠� * 1绉掓病鍝嶅簲灏辫浠栭噸鏂板彂閫�,閲嶈瘯3娆� * @param topic 鍙戦�佹暟鎹� * @param bodyStr body鍐呭 * @param callBack 鍥炶皟 */ public void udpSendMsg(String topic, String bodyStr, HDLLinkResponseCallBack callBack) { - HDLAuthSocket.getInstance().udpSendMsg(topic, bodyStr, callBack); + HDLAuthSocket.getInstance().udpSendMsg(topic, bodyStr,false, callBack); + } + + /** + * 閫氱敤骞挎挱UDP鍙戦�佹寚浠� + * 1绉掓病鍝嶅簲灏辫浠栭噸鏂板彂閫�,閲嶈瘯3娆� + * @param topic 鍙戦�佹暟鎹� + * @param bodyStr body鍐呭 + * @param callBack 鍥炶皟 + */ + public void udpBroadcastSendMsg(String topic, String bodyStr, HDLLinkResponseCallBack callBack) { + HDLAuthSocket.getInstance().udpSendMsg(topic, bodyStr,true, callBack); } /** @@ -206,7 +217,17 @@ * @param bodyStr 鍥炲鐨勪富棰� */ public void udpSendMsg(String topic, String bodyStr) { - HDLAuthSocket.getInstance().udpSendMsg(topic, bodyStr); + HDLAuthSocket.getInstance().udpSendMsg(topic, bodyStr,false); + } + + /** + * 閫氱敤骞挎挱鍙戦�佹寚浠� 鍙彂涓�娆★紝涓嶇洃鍚洖澶嶏紝涓嶉噸鍙� + * + * @param topic 鍙戦�佹暟鎹� + * @param bodyStr 鍥炲鐨勪富棰� + */ + public void udpBroadcastSendMsg(String topic, String bodyStr) { + HDLAuthSocket.getInstance().udpSendMsg(topic, bodyStr,true); } /** diff --git a/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/request/AuthenticateRequest.java b/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/request/AuthenticateRequest.java index 1314671..5dbec51 100644 --- a/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/request/AuthenticateRequest.java +++ b/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/request/AuthenticateRequest.java @@ -97,46 +97,197 @@ private String ip_gateway; private String dns1 = "114.114.114.114"; private String dns2 = "8.8.8.8"; - private VersionBean[] versions; + private String gateway_type; + private String hw_version; + private String fw_version; public String getOID() { return oid; } + + /** + * 璁惧Oid + * @param value + */ public void setOID(String value) { this.oid = value; } public String getDeviceMAC() { return device_mac; } + + /** + * 璁惧Mac + * @param value + */ public void setDeviceMAC(String value) { this.device_mac = value; } + /** + * 璁惧鍚� + * @return + */ public String getDeviceName() { return device_name; } + + /** + * 璁惧鍚� + * @param value + */ public void setDeviceName(String value) { this.device_name = value; } + /** + * 璁惧鍨嬪彿 + * @return + */ public String getDeviceModel() { return device_model; } + + /** + * 璁惧鍨嬪彿 + * @param value + */ public void setDeviceModel(String value) { this.device_model = value; } + /** + * 杩炴帴绫诲瀷锛屾湁绾胯繕鏄棤绾� + * @return + */ public String getAccessMode() { return access_mode; } + + /** + * 杩炴帴绫诲瀷锛屾湁绾胯繕鏄棤绾� + * @param value + */ public void setAccessMode(String value) { this.access_mode = value; } + /** + * 璁惧sid + * @return + */ public String getSid() { return sid; } + + /** + * 璁惧sid + * @param value + */ public void setSid(String value) { this.sid = value; } + /** + * 璁惧IPMAC + * @return + */ public String getIPMAC() { return ip_mac; } + + /** + * 璁惧IPMAC + * @param value + */ public void setIPMAC(String value) { this.ip_mac = value; } + /** + * 璁惧IP鍦板潃 + * @return + */ public String getIPAddress() { return ip_address; } + + /** + * 璁惧IP鍦板潃 + * @param value + */ public void setIPAddress(String value) { this.ip_address = value; } + /** + * 瀛愮綉鎺╃爜 + * @return + */ public String getNetmask() { return netmask; } + + /** + * 瀛愮綉鎺╃爜 + * @param value + */ public void setNetmask(String value) { this.netmask = value; } + /** + * 缃戝叧IP + * @return + */ public String getIPGateway() { return ip_gateway; } + + /** + * 缃戝叧IP + * @param value + */ public void setIPGateway(String value) { this.ip_gateway = value; } + /** + * DNS1 + * @return + */ public String getDns1() { return dns1; } + + /** + * DNS1 + * @param value + */ public void setDns1(String value) { this.dns1 = value; } + /** + * DNS2 + * @return + */ public String getDns2() { return dns2; } + + /** + * DNS2 + * @param value + */ public void setDns2(String value) { this.dns2 = value; } - public VersionBean[] getVersions() { return versions; } - public void setVersions(VersionBean[] value) { this.versions = value; } + public VersionBean[] getVersions() {return null; } + public void setVersions(VersionBean[] value) { } + + /** + * 缃戝叧绫诲瀷 + * @return + */ + public String getGateway_type() { + return gateway_type; + } + + /** + * 缃戝叧绫诲瀷 + * @param gateway_type + */ + public void setGateway_type(String gateway_type) { + this.gateway_type = gateway_type; + } + + /** + * 纭欢鐗堟湰 + * @return + */ + public String getHw_version() { + return hw_version; + } + + /** + *纭欢鐗堟湰 + * @param + */ + public void setHw_version(String hw_version) { + this.hw_version = hw_version; + } + + + /** + * 鍥轰欢鐗堟湰 + * @return + */ + public String getFw_version() { + return fw_version; + } + + /** + * 鍥轰欢鐗堟湰 + * @param fw_version + */ + public void setFw_version(String fw_version) { + this.fw_version = fw_version; + } } public static class VersionBean implements Serializable{ diff --git a/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/request/BroadcastRequest.java b/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/request/BroadcastRequest.java new file mode 100644 index 0000000..3092fcd --- /dev/null +++ b/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/request/BroadcastRequest.java @@ -0,0 +1,54 @@ +package com.hdl.sdk.connect.bean.request; + +import java.io.Serializable; + +/** + * Created by jlchen on 11/11/21. + * + * /user/all/custom/gateway/broadcast + */ +public class BroadcastRequest implements Serializable { + private String id; + private String time_stamp; + private AuthenticateRequest.AuthenticateDeviceInfoBean objects;//褰撳墠璁惧鍩烘湰淇℃伅 + private String code;// + + public BroadcastRequest(String id, String time_stamp, AuthenticateRequest.AuthenticateDeviceInfoBean objects, String code) { + this.id = id; + this.time_stamp = time_stamp; + this.objects = objects; + this.code = code; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTime_stamp() { + return time_stamp; + } + + public void setTime_stamp(String time_stamp) { + this.time_stamp = time_stamp; + } + + public AuthenticateRequest.AuthenticateDeviceInfoBean getObjects() { + return objects; + } + + public void setObjects(AuthenticateRequest.AuthenticateDeviceInfoBean objects) { + this.objects = objects; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } +} diff --git a/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/config/HDLLinkConfig.java b/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/config/HDLLinkConfig.java index dd5e830..49c705a 100644 --- a/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/config/HDLLinkConfig.java +++ b/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/config/HDLLinkConfig.java @@ -4,6 +4,7 @@ import com.hdl.sdk.common.config.TopicConstant; import com.hdl.sdk.common.utils.SPUtils; +import com.hdl.sdk.connect.bean.request.AuthenticateRequest; import com.hdl.sdk.connect.bean.response.GatewaySearchBean; @@ -23,6 +24,8 @@ private String ipAddress; private boolean isLocalEncrypt;//缃戝叧鏄惁闇�瑕佸姞瀵嗛�氳 private GatewaySearchBean currentGateway;//褰撳墠缃戝叧 + + private AuthenticateRequest.AuthenticateDeviceInfoBean deviceInfoBean;//褰撳墠璁惧鍩烘湰淇℃伅 /** * instance @@ -160,6 +163,7 @@ return (!topicStr.contains(TopicConstant.GATEWAY_AUTH_BROADCAST) //缃戝叧骞挎挱鍏ョ綉鎸囦护 && !topicStr.contains(TopicConstant.DEIVCE_AUTH_REQUEST) //鍏ョ綉璁よ瘉 && !topicStr.contains(TopicConstant.GATEWAY_SEARCH) //鎼滅储缃戝叧涓婚 + && !topicStr.equals(TopicConstant.BROADCAST) && isLocalEncrypt//鍚敤鍔犲瘑鏍囧織 ); } @@ -174,4 +178,11 @@ return String.format(topicStr, gatewayId); } + public AuthenticateRequest.AuthenticateDeviceInfoBean getDeviceInfoBean() { + return deviceInfoBean; + } + + public void setDeviceInfoBean(AuthenticateRequest.AuthenticateDeviceInfoBean deviceInfoBean) { + this.deviceInfoBean = deviceInfoBean; + } } diff --git a/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/socket/HDLAuthSocket.java b/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/socket/HDLAuthSocket.java index 8442f03..a0dd4ba 100644 --- a/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/socket/HDLAuthSocket.java +++ b/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/socket/HDLAuthSocket.java @@ -359,9 +359,10 @@ * * @param topic 鍙戦�佹暟鎹� * @param bodyStr 鍥炲鐨勪富棰� + * @param broadcast 鏄惁瑕佸箍鎾� * @param callBack 鍥炶皟 */ - public void udpSendMsg(String topic, String bodyStr, HDLLinkResponseCallBack callBack) { + public void udpSendMsg(String topic, String bodyStr,boolean broadcast, HDLLinkResponseCallBack callBack) { if (TextUtils.isEmpty(topic) || TextUtils.isEmpty(bodyStr)) { if (callBack != null) { callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_DATA_NULL_ERROR)); @@ -378,6 +379,9 @@ LinkRequest message = new LinkRequest(topic, bodyStr); String ip = HDLLinkConfig.getInstance().getIpAddress(); + if(broadcast) { + ip = IpUtils.getBroadcastAddress(); + } HdlSocketHelper.sendUdp(getUdpBoot(), ip, UDP_PORT, message, new HdlSocketHelper.HdlSocketListener() { @Override public void onSucceed(Object msg) { @@ -399,8 +403,9 @@ * * @param topic 鍙戦�佹暟鎹� * @param bodyStr 鍥炲鐨勪富棰� + * @param broadcast 鏄惁骞挎挱 */ - public void udpSendMsg(String topic, String bodyStr) { + public void udpSendMsg(String topic, String bodyStr,boolean broadcast) { if (TextUtils.isEmpty(topic) || TextUtils.isEmpty(bodyStr)) { LogUtils.e("udpSendMsg", "鍙傛暟涓嶈兘涓虹┖"); return; @@ -410,7 +415,10 @@ return; } LinkRequest message = new LinkRequest(topic, bodyStr); - String ip = HDLLinkConfig.getInstance().getIpAddress();// IpUtils.getBroadcastAddress(); + String ip = HDLLinkConfig.getInstance().getIpAddress(); + if(broadcast) { + ip = IpUtils.getBroadcastAddress(); + } HdlSocketHelper.sendUdpOne(getUdpBoot(), ip, UDP_PORT, message); } diff --git a/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/socket/HDLSocket.java b/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/socket/HDLSocket.java index b03d0fe..2048b61 100644 --- a/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/socket/HDLSocket.java +++ b/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/socket/HDLSocket.java @@ -3,40 +3,34 @@ import android.text.TextUtils; import com.google.gson.JsonObject; -import com.google.gson.reflect.TypeToken; import com.hdl.sdk.common.config.TopicConstant; import com.hdl.sdk.common.event.EventDispatcher; import com.hdl.sdk.common.event.EventListener; import com.hdl.sdk.common.exception.HDLLinkCode; import com.hdl.sdk.common.exception.HDLLinkException; import com.hdl.sdk.common.utils.IdUtils; -import com.hdl.sdk.common.utils.IpUtils; import com.hdl.sdk.common.utils.LogUtils; -import com.hdl.sdk.common.utils.SPUtils; import com.hdl.sdk.common.utils.ThreadToolUtils; import com.hdl.sdk.common.utils.gson.GsonConvert; +import com.hdl.sdk.connect.bean.request.BroadcastRequest; import com.hdl.sdk.connect.bean.response.BaseLocalResponse; import com.hdl.sdk.connect.bean.request.DeviceControlRequest; import com.hdl.sdk.connect.bean.request.FunctionAttributeRequest; -import com.hdl.sdk.connect.bean.response.GatewaySearchBean; import com.hdl.sdk.connect.bean.LinkRequest; import com.hdl.sdk.connect.bean.LinkResponse; import com.hdl.sdk.connect.bean.request.PropertyReadRequest; -import com.hdl.sdk.connect.bean.request.PropertyUpRequest; -import com.hdl.sdk.connect.callback.BaseCallBack; import com.hdl.sdk.connect.callback.HDLLinkCallBack; +import com.hdl.sdk.connect.callback.HDLLinkResponseCallBack; import com.hdl.sdk.connect.config.HDLLinkConfig; import com.hdl.sdk.connect.protocol.LinkMessageDecoder; import com.hdl.sdk.connect.protocol.LinkMessageEncoder; import com.hdl.sdk.socket.SocketBoot; import com.hdl.sdk.socket.SocketOptions; import com.hdl.sdk.socket.client.TcpClient; -import com.hdl.sdk.socket.client.UdpClient; import com.hdl.sdk.socket.codec.MessagePipeLine; import com.hdl.sdk.socket.listener.ConnectStatusListener; import com.hdl.sdk.socket.listener.SendListener; -import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ScheduledExecutorService; @@ -63,7 +57,7 @@ statusListener = new ConnectStatusListener() { @Override public void onConnecting() { - + broadcastRequest(); } @Override @@ -78,6 +72,29 @@ }; } + /** + * 骞挎挱鑷韩淇℃伅缁欎富缃戝叧 + */ + private void broadcastRequest() { + String time = String.valueOf(System.currentTimeMillis()); + if (null == HDLLinkConfig.getInstance().getDeviceInfoBean()) { + LogUtils.i("DeviceInfoBean涓虹┖锛岃璁剧疆褰撳墠瀵硅薄"); + return; + } + BroadcastRequest request = new BroadcastRequest(IdUtils.getUUId(), time, HDLLinkConfig.getInstance().getDeviceInfoBean(), "200"); + HDLAuthSocket.getInstance().udpSendMsg("/user/all/custom/gateway/broadcast", GsonConvert.getGson().toJson(request), true, new HDLLinkResponseCallBack() { + @Override + public void onSuccess(LinkResponse msg) { + LogUtils.i("骞挎挱淇℃伅缁欎富缃戝叧鎴愬姛锛�"); + } + + @Override + public void onError(HDLLinkException e) { + + } + }); + } + private static class SingletonInstance { private static final HDLSocket INSTANCE = new HDLSocket(); } @@ -86,17 +103,17 @@ return SingletonInstance.INSTANCE; } - + SocketOptions options; private SocketOptions getTcpOptions() { - final SocketOptions options = new SocketOptions(); + if(null!=options){ + return options; + } + options = new SocketOptions(); final MessagePipeLine pipeLine = new MessagePipeLine(); pipeLine.add(new LinkMessageDecoder()); pipeLine.add(new LinkMessageEncoder()); options.setHandleMessage(pipeLine); - options.setEnabledHeartbeat(false);//鏄惁寮�鍚績璺冲寘鍙戦�佹娴� -// options.setHeartbeatTimeInterval(10*1000L); -// options.setHeartbeatData("TCP"); -// options.setEnabledHeartbeat(true);//鏄惁寮�鍚績璺冲寘鍙戦�佹娴� + options.addConnectStatusListener(statusListener); return options; } @@ -389,9 +406,11 @@ if (TextUtils.isEmpty(getTcpIp())) { throw new RuntimeException("璇锋悳绱㈢綉鍏�"); } - if (tcpBoot == null) { + //濡傛灉娌℃湁鍒濆鍖栵紝鎴栬�呯綉鍏矷P鏇存敼浜嗭紝灏遍噸鏂板垵濮嬪寲 + if (tcpBoot == null||!getTcpOptions().getIp().equals(getTcpIp())) { tcpBoot = TcpClient.init(getTcpIp(), getTcpPort(), getTcpOptions()); } + return tcpBoot; } diff --git a/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/socket/HdlSocketHelper.java b/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/socket/HdlSocketHelper.java index 7776163..4bcc51e 100644 --- a/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/socket/HdlSocketHelper.java +++ b/HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/socket/HdlSocketHelper.java @@ -21,7 +21,7 @@ */ public class HdlSocketHelper { - private static final Long DEF_SEND_TIMEOUT = 1000L; + private static final Long DEF_SEND_TIMEOUT = 500L; private static final int DEF_MAX_RETRY = 4; private static final int DEF_SEND_ONE = 1; diff --git a/HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/SocketBoot.java b/HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/SocketBoot.java index b8f557e..8126367 100644 --- a/HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/SocketBoot.java +++ b/HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/SocketBoot.java @@ -27,25 +27,19 @@ public class SocketBoot { private ExecutorService connectThread; - private ScheduledExecutorService heartbeatThread; private ExecutorService sendThread; private ExecutorService receiveThread; - private ScheduledExecutorService delayThread; private final IClient client; + + /** + * tcp鏄惁宸茬粡杩炴帴 + */ + private boolean connected=false; public IClient getClient() { return client; } - - /** - * socket鏄惁鍦ㄨ繍琛� - */ - private final AtomicBoolean isRun = new AtomicBoolean(false); - - private final AtomicBoolean isOpenRetry = new AtomicBoolean(false); - - private final AtomicInteger resendCount = new AtomicInteger(0); private final BlockingQueue<SocketRequest> mMessageQueue = new LinkedBlockingDeque<>(); @@ -53,88 +47,42 @@ public SocketBoot(IClient client) { this.client = client; + initConnectThread(); + initReceiveThread(); + initSendThread(); } - public ScheduledExecutorService getHeartBeat() { - if (heartbeatThread == null) { - heartbeatThread = ThreadToolUtils.getInstance().newScheduledThreadPool(1); - } - return heartbeatThread; - } - - public void connect() { - resendCount.set(0); - resetConnect(true); - isOpenRetry.set(true); - } - - public synchronized void resetConnect(boolean isFirst) { - final int maxRetry = client.getOptions().getMaxRetry(); - if (maxRetry == 0 && resendCount.get() > 0 || - (maxRetry > 0 && maxRetry + 1 < resendCount.get())) { - LogUtils.d("====", "===閲嶈繛娆℃暟杈惧埌鏈�澶�=="); - return; - } - if (!client.isConnect()) { - if (connectThread == null) { - connectThread = ThreadToolUtils.getInstance().newFixedThreadPool(1); - } - connectThread.execute(new Runnable() { - @Override - public void run() { - client.onConnectStatus(ConnectStatus.CONNECTING); - if (!isFirst) { - try { - resendCount.set(resendCount.get() + 1); - Thread.sleep(300L); - LogUtils.d("====", "==閲嶈繛绗�" + resendCount + "娆�=="); - } catch (Exception ignored) { - } - } - try { - client.connect(); - isRun.set(true); - if (client.isConnect()) { - LogUtils.d("====", "====杩炴帴鎴愬姛===="); - startHeartbeat(); - - initSendThread(); - initReceiveThread(); - - client.onConnectStatus(ConnectStatus.CONNECTED); - resendCount.set(0); - } else { - throw new ConnectException(); - } - } catch (Exception e) { - e.printStackTrace(); - LogUtils.d("====", "===杩炴帴澶辫触===" + e); - //鍐嶅垽鏂竴涓嬫湁娌℃湁杩炴帴 - if (!client.isConnect()) { - isRun.set(false); - client.onConnectStatus(ConnectStatus.DISCONNECT); - stopHeartbeat(); - disconnectError(); - } - } - } - }); + /** + * 杩炴帴tcp锛屽唴閮ㄧ淮鎶ゆ帀锛屽彲浠ヤ笉鐢ㄥ紑鏀惧閮紝鏍规嵁杩欎釜涓氬姟鎴戠壒鎬у鐞嗗ソ + */ + private synchronized void connect() { + try { + LogUtils.i("TCP杩炴帴"); + client.onConnectStatus(ConnectStatus.CONNECTING); + Thread.sleep(1500); + client.connect(); + connected=true; + client.onConnectStatus(ConnectStatus.CONNECTED); + }catch(Exception e) { + LogUtils.e(e.getMessage()); } } - public void initSendThread() { + + /** + * 鍒濆鍖栧彂閫佺嚎绋嬶紝鍙渶瑕佸垵濮嬪寲涓�娆� + */ + private void initSendThread() { if (sendThread == null) { sendThread = ThreadToolUtils.getInstance().newFixedThreadPool(1); - } - sendThread.execute(new Runnable() { - @Override - public void run() { - while (isRun.get()) { - if (client.isConnect()) { + sendThread.execute(new Runnable() { + @Override + public void run() { + while (true) { try { SocketRequest socketRequest = mMessageQueue.take(); final String sendStr = new String(socketRequest.getData(), 0, socketRequest.getData().length); - LogUtils.i("鍙戦�佹暟鎹細"+sendStr); + LogUtils.i("鍙戦�佹暟鎹細" + sendStr); final String action = socketRequest.getAction(); try { client.sendMsg(socketRequest.getData()); @@ -145,33 +93,22 @@ } } } catch (Exception e) { + connected = false; + LogUtils.e("鍙戦�佸け璐�:" + e.getMessage()); if (!TextUtils.isEmpty(action)) { SendListener sendListener = sendMap.get(action); if (sendListener != null) { sendListener.onError(); } } - - stopHeartbeat(); - if (sendThread != null) { - sendThread.shutdownNow(); - } - if (isRun.get()) { - disconnectError(); - } - } - } catch (InterruptedException ignored) { + } catch (Exception e) { } - } - } - LogUtils.d("=====", "==鍙戦�佺嚎绋嬪叧闂�=="); - } - }); - + }); + } } /** @@ -183,151 +120,94 @@ receiveThread.execute(new Runnable() { @Override public void run() { - while (isRun.get()) { - if (client.isConnect()) { - try { + while (true) { + try { + if (connected) { //璇诲彇鏁版嵁 client.onHandleResponse(); - } catch (Exception e) { - e.printStackTrace(); - disconnectError(); + } else { + try { + Thread.sleep(1000); + } catch (Exception ee) { + + } } + } catch (Exception e) { + connected = false; + LogUtils.e("鎺ユ敹鏁版嵁绾跨▼寮傚父" + e.getMessage()); } } - LogUtils.i("Socket 绾跨▼閫�鍑烘帴鏀舵暟鎹�"); } }); } } + /** + * 鍒濆鍖栭噸鏂拌繛鎺ョ嚎绋� + */ + private void initConnectThread() { + if (connectThread == null) { + connectThread = ThreadToolUtils.getInstance().newFixedThreadPool(1); + //涓�瀹氭椂闂存娴嬩竴娆¤繛鎺ユ儏鍐碉紝娌℃湁杩炴帴灏辨墽琛岃繛鎺ワ紝杩炴帴缁熶竴鐢辫繖閲岀淮鎶� + connectThread.execute(new Runnable() { + @Override + public void run() { + while (true) { + try { + if (!connected) { + reconect(); + } + Thread.sleep(10*1000); + } catch (Exception e) { - public void startHeartbeat() { - if (heartbeatThread != null) { - heartbeatThread.shutdownNow(); - heartbeatThread = null; - } - if (client.getOptions() == null || client.getOptions().getHeartbeatTimeInterval() <= 0 || !client.getOptions().isEnabledHeartbeat()) { - return; - } - getHeartBeat().scheduleWithFixedDelay(new Runnable() { - @Override - public void run() { - if (isRun.get()) { -// LogUtils.d("====", "===鍙戦�佸績璺冲寘==="); - if (client.getOptions() != null) { - final byte[] heartBeat = client.getOptions().getHeartbeatData(); - if (heartBeat != null) { - sendMsg(heartBeat, false, null); - } else { - sendMsg(new byte[0], false, null); } } } - } - }, client.getOptions().getHeartbeatTimeInterval(), client.getOptions().getHeartbeatTimeInterval(), TimeUnit.MILLISECONDS); - } - - public void stopHeartbeat() { - if (heartbeatThread != null) { - heartbeatThread.shutdownNow(); - heartbeatThread = null; + }); } } + /** + * 閲嶆柊杩炴帴 + */ + private void reconect() { + disconnect(); + connect(); + } + /** + * 鍙戦�佹棤闇�鍥炶皟 + * @param msg 鍙戦�佺殑鏁版嵁 + */ public void sendMsg(byte[] msg) { - sendMsg(msg, true, null); + sendMsg(msg, null); } - public void sendMsg(byte[] msg, SendListener listener) { - sendMsg(msg, true, listener); - } /** * @param listener 涓�鑸儏鍐垫棤闇�鐩戝惉 */ - private void sendMsg(byte[] msg, boolean isRefreshRetry, SendListener listener) { - if (isRefreshRetry) { - //閲嶇疆杩炴帴娆℃暟 - resendCount.set(0); - } + public void sendMsg(byte[] msg, SendListener listener) { try { SocketRequest request = new SocketRequest(msg); if (listener != null && !TextUtils.isEmpty(request.getAction())) { sendMap.put(request.getAction(), listener); } mMessageQueue.put(request); - } catch (InterruptedException ignored) { + } catch (Exception e) { - } - if (!client.isConnect()) { - resetConnect(false); } } /** - * 鍙戠敓閿欒锛岄噸杩� + * 鍏抽棴杩炴帴 */ - private void disconnectError() { - disconnect(); - isRun.set(false); - if (isOpenRetry.get()) { - if (delayThread != null) { - delayThread.shutdownNow(); - } - delayThread = ThreadToolUtils.getInstance().newScheduledThreadPool(1); - delayThread.schedule(new Runnable() { - @Override - public void run() { - if (!client.isConnect() && isOpenRetry.get()) { - resetConnect(false); - } - } - }, 3000, TimeUnit.MILLISECONDS); - } - - } - private synchronized void disconnect() { - if (client.isConnect()) { + try { client.disconnect(); //鏂紑杩炴帴 client.onConnectStatus(ConnectStatus.DISCONNECT); - } - } + } catch (Exception e) { - public synchronized void close() { - isOpenRetry.set(false); - isRun.set(false); - if (connectThread != null) { - connectThread.shutdownNow(); - connectThread = null; } - if (heartbeatThread != null) { - heartbeatThread.shutdownNow(); - heartbeatThread = null; - } - if (sendThread != null) { - sendThread.shutdownNow(); - sendThread = null; - } - if (receiveThread != null) { - receiveThread.shutdownNow(); - receiveThread = null; - } - sendMap.clear(); - client.disconnect(); - mMessageQueue.clear(); - - } - - public synchronized void release() { - close(); - if (client != null && client.getOptions() != null) { - client.getOptions().clearConnectStatusListener(); - } - } - - public boolean isConnect() { - return client.isConnect(); } } diff --git a/HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/SocketOptions.java b/HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/SocketOptions.java index b5e6957..429d646 100644 --- a/HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/SocketOptions.java +++ b/HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/SocketOptions.java @@ -15,19 +15,8 @@ public class SocketOptions { //鍙戦�佺洰鏍囧湴鍧�IP - private String ip; - - //璁剧疆璇诲彇缂撳瓨 - private int readMaxBufferSize = 512; - - //鍙戦�佸績璺冲寘 - private boolean isEnabledHeartbeat = true; - - //蹇冭烦鍖� - private byte[] heartbeatData; - - //蹇冭烦鍖呮椂闂撮棿闅� - private long heartbeatTimeInterval = 300L; + private String ip=""; + private int port; //澶勭悊鏁版嵁 private IHandleMessage handleMessage; @@ -35,21 +24,17 @@ //鐩戝惉鐘舵�� private List<ConnectStatusListener> mConnectStatusListener; - //鏈�澶ч噸杩炴鏁�,灏忎簬0鏃犻檺娆℃暟,绛変簬0涓嶉噸杩� - private int maxRetry = -1; - - private boolean isTcpNoDelay; - private boolean isReuseAddress; - //淇濇寔娲诲姩鐘舵�� - private boolean isKeepAlive; - private boolean isOOBInline; - private int sendBufferSize; - private int receiveBufferSize; - private int soTimeout; - private boolean soLinger; public String getIp() { return ip; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; } public void setIp(String ip) { @@ -62,38 +47,6 @@ public void setHandleMessage(IHandleMessage handleMessage) { this.handleMessage = handleMessage; - } - - public boolean isEnabledHeartbeat() { - return isEnabledHeartbeat; - } - - public void setEnabledHeartbeat(boolean enabledHeartbeat) { - isEnabledHeartbeat = enabledHeartbeat; - } - - public byte[] getHeartbeatData() { - return heartbeatData; - } - - public void setHeartbeatData(byte[] heartbeatData) { - this.heartbeatData = heartbeatData; - } - - public void setHeartbeatData(String heartbeatData) { - try { - this.heartbeatData = heartbeatData.getBytes("utf-8"); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - } - - public long getHeartbeatTimeInterval() { - return heartbeatTimeInterval; - } - - public void setHeartbeatTimeInterval(long heartbeatTimeInterval) { - this.heartbeatTimeInterval = heartbeatTimeInterval; } public void clearConnectStatusListener() { @@ -115,26 +68,8 @@ } } - public List<ConnectStatusListener> getConnectStatusListener() { return mConnectStatusListener; - } - - - public int getMaxRetry() { - return maxRetry; - } - - public void setMaxRetry(int maxRetry) { - this.maxRetry = maxRetry; - } - - public int getReadMaxBufferSize() { - return readMaxBufferSize; - } - - public void setReadMaxBufferSize(int readMaxBufferSize) { - this.readMaxBufferSize = readMaxBufferSize; } } diff --git a/HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/client/IClient.java b/HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/client/IClient.java index e768514..3e6a6da 100644 --- a/HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/client/IClient.java +++ b/HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/client/IClient.java @@ -12,11 +12,6 @@ void disconnect(); - /** - * 鏄惁宸茬粡杩炴帴 - */ - boolean isConnect(); - SocketOptions getOptions(); diff --git a/HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/client/TcpClient.java b/HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/client/TcpClient.java index 4e9d13c..3f3c359 100644 --- a/HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/client/TcpClient.java +++ b/HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/client/TcpClient.java @@ -15,6 +15,7 @@ import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; +import java.util.ArrayList; import java.util.List; @@ -31,12 +32,32 @@ private Socket mSocket; - private byte[] readBuffer; + private final static List<TcpClient> tcpClientList = new ArrayList(); + + /** + * 浠庤繛鎺ユ睜涓壘鍑哄綋鍓岻P鍙婄鍙g殑杩炴帴瀹㈡埛绔� + * @param ipAdderss 杩炴帴IP鍦板潃 + * @param port 杩炴帴绔彛 + * @return + */ + public static TcpClient getTcpClientByIP(String ipAdderss,int port) { + for(TcpClient tcpClient:tcpClientList){ + if(tcpClient.ip.equals(ipAdderss)&&tcpClient.port==port) + { + return tcpClient; + } + } + return null; + } + + private byte[] readBuffer = new byte[4*1024]; private TcpClient(String ip, int port, SocketOptions socketOptions) { this.socketOptions = socketOptions; this.ip = ip; this.port = port; + socketOptions.setIp(ip); + socketOptions.setPort(port); } public static SocketBoot init(String ip, int port, SocketOptions options) { @@ -52,8 +73,11 @@ mSocket.setTcpNoDelay(true); mSocket.setReuseAddress(true); mSocket.setKeepAlive(true); - readBuffer = new byte[options.getReadMaxBufferSize()]; + + tcpClientList.add(this); } + + @Override @@ -66,16 +90,6 @@ } } } - - @Override - public boolean isConnect() { - if (mSocket == null) { - return false; - } - - return mSocket.isConnected() && !mSocket.isClosed(); - } - @Override public synchronized SocketOptions getOptions() { -- Gitblit v1.8.0