From 99bc815e07e39354f51421b77f4012ffd35594d8 Mon Sep 17 00:00:00 2001
From: wjc <1243177876@qq.com>
Date: 星期三, 28 六月 2023 18:03:00 +0800
Subject: [PATCH] 2023年06月28日18:02:58

---
 HDLLinkLocalSdk/src/main/java/com/hdl/sdk/link/core/connect/HDLUdpConnect.java |  619 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 619 insertions(+), 0 deletions(-)

diff --git a/HDLLinkLocalSdk/src/main/java/com/hdl/sdk/link/core/connect/HDLUdpConnect.java b/HDLLinkLocalSdk/src/main/java/com/hdl/sdk/link/core/connect/HDLUdpConnect.java
new file mode 100644
index 0000000..cff6a99
--- /dev/null
+++ b/HDLLinkLocalSdk/src/main/java/com/hdl/sdk/link/core/connect/HDLUdpConnect.java
@@ -0,0 +1,619 @@
+package com.hdl.sdk.link.core.connect;
+
+import android.content.Context;
+import android.content.Intent;
+import android.net.wifi.WifiManager;
+import android.text.TextUtils;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonObject;
+import com.google.gson.reflect.TypeToken;
+import com.hdl.sdk.link.HDLLinkLocalSdk;
+import com.hdl.sdk.link.common.event.EventDispatcher;
+import com.hdl.sdk.link.common.event.EventListener;
+import com.hdl.sdk.link.common.exception.HDLLinkCode;
+import com.hdl.sdk.link.common.exception.HDLLinkException;
+import com.hdl.sdk.link.common.utils.IpUtils;
+import com.hdl.sdk.link.common.utils.LogUtils;
+import com.hdl.sdk.link.common.utils.ThreadToolUtils;
+import com.hdl.sdk.link.core.bean.LinkRequest;
+import com.hdl.sdk.link.core.bean.LinkResponse;
+import com.hdl.sdk.link.core.bean.gateway.GatewayBean;
+import com.hdl.sdk.link.core.bean.request.AuthenticateRequest;
+import com.hdl.sdk.link.core.bean.response.AuthenticateResponse;
+import com.hdl.sdk.link.core.bean.response.BaseLocalResponse;
+import com.hdl.sdk.link.core.bean.response.GatewaySearchBean;
+import com.hdl.sdk.link.core.bean.response.NetworkAccessBroadcastResponse;
+import com.hdl.sdk.link.core.callback.BaseCallBack;
+import com.hdl.sdk.link.core.callback.HDLLinkCallBack;
+import com.hdl.sdk.link.core.callback.HDLLinkResponseCallBack;
+import com.hdl.sdk.link.common.config.TopicConstant;
+import com.hdl.sdk.link.common.utils.IdUtils;
+import com.hdl.sdk.link.common.utils.gson.GsonConvert;
+import com.hdl.sdk.link.core.config.HDLLinkConfig;
+import com.hdl.sdk.link.core.protocol.LinkMessageDecoder;
+import com.hdl.sdk.link.core.protocol.LinkMessageEncoder;
+import com.hdl.sdk.link.socket.client.UdpClient;
+import com.hdl.sdk.link.socket.codec.MessagePipeLine;
+import com.hdl.sdk.link.socket.udp.UdpSocketBoot;
+import com.hdl.sdk.link.socket.udp.UdpSocketOptions;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static com.hdl.sdk.link.common.config.TopicConstant.DEIVCE_AUTH_REQUEST;
+
+/**
+ * Created by jlchen on 11/11/21.
+ *
+ * @Description : HDLAuthSocket 鐢变簬鍓嶆湡宸茬粡鍛藉悕濂斤紝涓嶅仛鏇存敼锛屽彲鐢ㄤ綔Udp鏈嶅姟绔娇鐢�
+ */
+public class HDLUdpConnect {
+    private static final String TAG = "HDLAuth";
+    /**
+     * udp榛樿绔彛
+     */
+    public static final int UDP_PORT = 8585;
+    /**
+     * 鍥犱负鑰冭檻鍒颁娇鐢ㄤ竴涓鍙o紝瑕佹敮鎸佹帴鏀跺缃戝叧鐨勬暟鎹紝鎵�浠ュ彧鍏佽浣跨敤涓�涓�
+     */
+    private static UdpSocketBoot udpSocketBoot;
+    //    private EventListener authEvent;
+    //鎼滅储缃戝叧
+    private EventListener searchGatewayEvent;
+    /**
+     * udp榛樿缁勬挱ip
+     */
+    private static final String UDP_GROUP_IP = "239.0.168.188";
+
+    private static boolean bindSuccess;
+
+    public static boolean isBindSuccess() {
+        return bindSuccess;
+    }
+
+    /**
+     * instance
+     */
+    private volatile static HDLUdpConnect instance;
+
+    private HDLUdpConnect() {
+        initListenerGatewayEvent();
+        initSearchGatewayEvent();
+    }
+
+    /**
+     * getInstance
+     *
+     * @return HDLAuthSocket
+     */
+    public static synchronized HDLUdpConnect getInstance() {
+        if (instance == null) {
+            synchronized (HDLLinkConfig.class) {
+                if (instance == null) {
+                    instance = new HDLUdpConnect();
+                }
+            }
+        }
+        return instance;
+    }
+
+    private UdpSocketOptions getUdpOptions() {
+        final UdpSocketOptions options = new UdpSocketOptions();
+        WifiManager manager = (WifiManager) HDLLinkLocalSdk.getInstance().getContext().getApplicationContext()
+                .getSystemService(Context.WIFI_SERVICE);
+        options.setWifiManager(manager);
+        final MessagePipeLine pipeLine = new MessagePipeLine();
+        pipeLine.add(new LinkMessageDecoder());
+        pipeLine.add(new LinkMessageEncoder());
+        options.setHandleMessage(pipeLine);
+        return options;
+    }
+
+
+    /**
+     * 鑾峰彇褰撳墠udp瀵硅薄锛屽鏋滀笉瀛樺湪灏卞垱寤�
+     *
+     * @return 杩斿洖褰撳墠瀵硅薄
+     */
+    public synchronized UdpSocketBoot getUdpBoot() {
+        if (null == initUdp()) {
+            return null;
+        }
+        return udpSocketBoot;
+    }
+
+
+    /**
+     * 鍒濆鍖杣dp 鐩戝惉鍔熻兘
+     *
+     * @return 杩斿洖褰撳墠瀵硅薄
+     */
+    public synchronized UdpSocketBoot initUdp() {
+        try {
+            if (udpSocketBoot == null) {
+                udpSocketBoot = UdpClient.init("0.0.0.0",UDP_PORT, getUdpOptions());
+                udpSocketBoot.bind();
+                bindSuccess=true;
+            }
+        } catch (Exception e) {
+            LogUtils.e("鍒濆鍖栫綉鍏冲け璐�:"+e.getMessage());
+            return null;
+        }
+
+        return udpSocketBoot;
+    }
+
+
+    /**
+     * 寮�濮嬬洃鍚拰鍙戣捣鍏ョ綉鍙婅璇佽姹�
+     *
+     * @param request  璁よ瘉璇锋眰淇℃伅
+     * @param callBack 缁撴灉鍥炶皟
+     */
+    public void startAuthenticateRequest(AuthenticateRequest request, HDLLinkCallBack callBack) {
+        HDLLinkConfig.getInstance().clearConfig();
+        //1.鍚姩Socket 寮�鍚洃鍚�
+        getUdpBoot();
+        //2.鏋勫缓鐩戝惉Listener
+//        authEvent =
+        //3.鐩戝惉缃戝叧骞挎挱鐨勫叆缃戞寚浠�
+        EventDispatcher.getInstance().register(TopicConstant.GATEWAY_AUTH_BROADCAST, new EventListener() {
+            @Override
+            public void onMessage(Object msg) {
+                NetworkAccessBroadcastResponse bean = getNetworkAccessBroadcastResponse(msg);
+                if (bean != null) {
+                    LogUtils.i(TAG, "缃戝叧鍏ョ綉骞挎挱IP: " + bean.getIPAddress());
+                    String ipStr = bean.getIPAddress();
+                    if (!TextUtils.isEmpty(ipStr)) {
+                        sendAuthenticateRequest(ipStr, request, callBack);
+                    }
+                }
+                //绉婚櫎鐩戝惉
+                EventDispatcher.getInstance().remove(TopicConstant.GATEWAY_AUTH_BROADCAST);
+                LogUtils.i(TAG, "绉婚櫎鐩戝惉 authEvent");
+            }
+        });
+    }
+
+    /**
+     * 缁撴潫鐩戝惉鍏ョ綉鍙婅璇佸箍鎾�
+     */
+    public void endAuthenticateRequest() {
+        //绉婚櫎鐩戝惉
+        EventDispatcher.getInstance().remove(TopicConstant.GATEWAY_AUTH_BROADCAST);
+    }
+
+    /**
+     * 鍙戦�佸叆缃戝強璁よ瘉璇锋眰
+     *
+     * @param ip       缃戝叧IP
+     * @param request  璁よ瘉璇锋眰淇℃伅
+     * @param callBack 缁撴灉鍥炶皟
+     */
+    public void sendAuthenticateRequest(String ip, AuthenticateRequest request, HDLLinkCallBack callBack) {
+        if (request == null) {
+            callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_DATA_NULL_ERROR));
+        }
+        String topic = DEIVCE_AUTH_REQUEST;
+        Gson gs = new Gson();
+        String requestStr = gs.toJson(request);
+        LinkRequest linkRequest = new LinkRequest(topic, requestStr, false);
+//        linkRequest.setReplyTopic(requestStr + "_reply");
+        new HDLConnectHelper(ip, linkRequest, new HDLConnectHelper.HdlSocketListener() {
+            @Override
+            public void onSucceed(Object msg) {
+                if (callBack == null) return;
+                try {
+                    AuthenticateResponse bean = getAuthenticateResponseBean(msg);
+                    if (bean != null) {
+                        if (bean.getCode().equals("200")) {
+                            String localSecret = "";
+                            String gatewayId = "";
+                            String ipAddress = "";
+                            if (bean.getAuth() != null) {
+                                localSecret = bean.getAuth().getLocalSecret();
+                            }
+                            if (bean.getObjects() != null) {
+                                gatewayId = bean.getObjects().getGatewayID();
+                                ipAddress = bean.getObjects().getIPAddress();
+                            }
+                            //鍒ゆ柇缃戝叧鏄惁宸茬粡娉ㄥ唽鍒颁簯绔�
+                            if (TextUtils.isEmpty(localSecret) || TextUtils.isEmpty(gatewayId)) {
+                                //璁よ瘉澶辫触锛岀綉鍏虫湭娉ㄥ唽鍒颁簯绔�
+                                callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_AUTH_ERROR_GATEWAY_NOT_REGISTERED));
+                            } else {
+                                HDLLinkConfig.getInstance().saveConfig(localSecret, gatewayId, ipAddress);
+                                callBack.onSuccess("璁よ瘉鎴愬姛");
+                            }
+                        } else if (bean.getCode().equals("14013")) {
+                            //璁よ瘉澶辫触锛岃MAC瀵瑰簲鐨勮澶囧瘑閽ヤ笉瀛樺湪
+                            callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_AUTH_MAC_KEY_ERROR));
+                        } else {
+                            //璁よ瘉澶辫触锛岄敊璇爜锛�
+                            LogUtils.e("璁よ瘉澶辫触锛岄敊璇爜锛�" + bean.getCode());
+                            callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_AUTH_ERROR));
+                        }
+                    } else {
+                        callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_DATA_ERROR));
+                    }
+                } catch (Exception e) {
+                    callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_DATA_ERROR));
+                }
+            }
+
+            @Override
+            public void onFailure(HDLLinkCode hdlLinkCode) {
+                LogUtils.i(TAG, "onFailure: ");
+                if (callBack == null) return;
+                callBack.onError(HDLLinkException.getErrorWithCode(hdlLinkCode));
+            }
+        }, false).send();
+    }
+
+//    /**
+//     * 鍙戦�佸叆缃戝強璁よ瘉璇锋眰
+//     *
+//     * @param callBack 缁撴灉鍥炶皟
+//     */
+//    public void sendAuthenticateRequest(CallBack callBack) {
+//        String macStr = "AA000000000000BB";
+//        String secret = "87ae414b7a853f65";
+//        String mac_key = stringToMD5(stringToMD5(macStr + secret));
+//
+//        String versionString = "HDL_V1.0.1";
+//        String time = String.valueOf(System.currentTimeMillis());
+//
+//        //1.璁剧疆璁よ瘉淇℃伅
+//        AuthenticateRequest.RequestBean requestBean = new AuthenticateRequest.RequestBean();
+//        requestBean.setMAC(macStr);
+//        requestBean.setSupplier("HDL");
+//        requestBean.setFirmwareVersion(versionString);
+//        requestBean.setHardwareModel("1956F");
+//        AuthenticateRequest.AuthBean authbean = new AuthenticateRequest.AuthBean();
+//        authbean.setSpk("ir.module");
+//        authbean.setMACKey(mac_key);
+//        authbean.setRequest(requestBean);
+//
+//
+//        //2.璁剧疆璁惧淇℃伅
+//        AuthenticateDeviceInfoBean infoBean = new AuthenticateDeviceInfoBean();
+//        infoBean.setDeviceMAC(macStr);
+//        infoBean.setIPMAC(macStr);
+//        infoBean.setDeviceName("HDL闈㈡澘");
+//        infoBean.setAccessMode("HDL");
+//        infoBean.setOID(getOid());
+//        infoBean.setSid(getSid());
+////        infoBean.set
+//        AuthenticateRequest.VersionBean[] versionBeans = new AuthenticateRequest.VersionBean[]{new AuthenticateRequest.VersionBean("FW", versionString), new AuthenticateRequest.VersionBean("HW", "1956F")};
+//        infoBean.setVersions(versionBeans);
+//        AuthenticateRequest request = new AuthenticateRequest(IdUtils.getUUId(), time, infoBean, authbean);
+//
+//        String ip = IpUtils.getBroadcastAddress();
+//        ip = "192.168.10.102";
+//        sendAuthenticateRequest(ip, request, callBack);
+//    }
+
+    public interface SearchGatewayCallBack extends BaseCallBack {
+        /**
+         * 鎼滅储缃戝叧鎴愬姛
+         *
+         * @param gatewaySearchBean
+         */
+        void onSuccess(GatewaySearchBean gatewaySearchBean);
+    }
+
+
+    /**
+     * 鏆傚仠鎼滅储缃戝叧
+     */
+    public void endSearchAllGateway() {
+
+    }
+
+    /**
+     * 缁勬挱鎼滅储鎸囧畾缃戝叧鏄惁鍦ㄧ嚎锛屾悳绱㈠埌鍒欒繑鍥炴寚瀹氱殑缃戝叧瀵硅薄
+     *
+     * @param callBack 鍥炶皟
+     */
+    public void searchGatewayMulticast(SearchGatewayCallBack callBack) {
+        searchGateway(HDLLinkConfig.getInstance().getGatewayId(), UDP_GROUP_IP, UDP_PORT, callBack);
+    }
+
+    /**
+     * 缁勬挱鎼滅储鎸囧畾缃戝叧鏄惁鍦ㄧ嚎锛屾悳绱㈠埌鍒欒繑鍥炴寚瀹氱殑缃戝叧瀵硅薄
+     *
+     * @param callBack 鍥炶皟
+     */
+    public void searchGatewayBroadcast(SearchGatewayCallBack callBack) {
+        if (!HDLLinkConfig.getInstance().checkIfCertified()) {
+            if (callBack != null) {
+                callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_UNAUTHORIZED_ERROR));
+            }
+            return;
+        }
+        String ip = IpUtils.getBroadcastAddress();
+        searchGateway(HDLLinkConfig.getInstance().getGatewayId(), ip, UDP_PORT, callBack);
+    }
+
+    /**
+     * 閫氱敤鍙戦�佹寚浠�
+     * 1绉掓病鍝嶅簲灏辫浠栭噸鏂板彂閫�,閲嶈瘯3娆�
+     *
+     * @param topic     鍙戦�佹暟鎹�
+     * @param bodyStr   鍥炲鐨勪富棰�
+     * @param broadcast 鏄惁瑕佸箍鎾�
+     * @param 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));
+            }
+            return;
+        }
+
+        if (!HDLLinkConfig.getInstance().checkIfCertified()) {
+            if (callBack != null) {
+                callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_UNAUTHORIZED_ERROR));
+            }
+            return;
+        }
+
+        LinkRequest message = new LinkRequest(topic, bodyStr, false);
+        String ip = HDLLinkConfig.getInstance().getIpAddress();
+        if (broadcast) {
+            ip = IpUtils.getBroadcastAddress();
+        }
+        new HDLConnectHelper(ip, message, new HDLConnectHelper.HdlSocketListener() {
+            @Override
+            public void onSucceed(Object msg) {
+                if (callBack == null) return;
+                callBack.onSuccess((LinkResponse) msg);
+            }
+
+            @Override
+            public void onFailure(HDLLinkCode hdlLinkCode) {
+                if (callBack == null) return;
+                callBack.onError(HDLLinkException.getErrorWithCode(hdlLinkCode));
+            }
+        }
+                , false).send();
+    }
+
+    /**
+     * 閫氱敤鍙戦�佹寚浠� 鍙彂涓�娆★紝涓嶇洃鍚洖澶嶏紝涓嶉噸鍙�
+     *
+     * @param topic     鍙戦�佹暟鎹�
+     * @param bodyStr   鍥炲鐨勪富棰�
+     * @param broadcast 鏄惁骞挎挱
+     */
+    public void udpSendMsg(String topic, String bodyStr, boolean broadcast) {
+        if (TextUtils.isEmpty(topic) || TextUtils.isEmpty(bodyStr)) {
+            LogUtils.e("udpSendMsg", "鍙傛暟涓嶈兘涓虹┖");
+            return;
+        }
+        if (!HDLLinkConfig.getInstance().checkIfCertified()) {
+            LogUtils.e("udpSendMsg", "鏈璇侊紝璇峰厛璁よ瘉");
+            return;
+        }
+        LinkRequest message = new LinkRequest(topic, bodyStr, HDLLinkConfig.getInstance().isLocalEncrypt());
+        String ip = HDLLinkConfig.getInstance().getIpAddress();
+        if (broadcast) {
+            ip = IpUtils.getBroadcastAddress();
+        }
+        new HDLConnectHelper(ip, message, false).send();
+    }
+
+    private GatewaySearchBean getGatewaySearchBean(Object msg) {
+        GatewaySearchBean searchBean = null;
+        if (msg instanceof LinkResponse) {
+            LinkResponse linkResponse = (LinkResponse) msg;
+            String data = linkResponse.getData();
+            if (!TextUtils.isEmpty(data)) {
+                final BaseLocalResponse<GatewaySearchBean> response = GsonConvert.getGson().fromJson(data, new TypeToken<BaseLocalResponse<GatewaySearchBean>>() {
+                }.getType());
+                searchBean = response.getObjects();
+            }
+        }
+        return searchBean;
+    }
+
+    private AuthenticateResponse getAuthenticateResponseBean(Object msg) {
+        AuthenticateResponse mBean = null;
+        if (msg instanceof LinkResponse) {
+            LinkResponse linkResponse = (LinkResponse) msg;
+            String data = linkResponse.getData();
+            if (!TextUtils.isEmpty(data)) {
+                AuthenticateResponse response = GsonConvert.getGson().fromJson(data, new TypeToken<AuthenticateResponse>() {
+                }.getType());
+                mBean = response;
+            }
+
+        }
+        return mBean;
+    }
+
+    private NetworkAccessBroadcastResponse getNetworkAccessBroadcastResponse(Object msg) {
+        NetworkAccessBroadcastResponse mBean = null;
+        if (msg instanceof LinkResponse) {
+            LinkResponse linkResponse = (LinkResponse) msg;
+            String data = linkResponse.getData();
+            if (!TextUtils.isEmpty(data)) {
+                NetworkAccessBroadcastResponse response = GsonConvert.getGson().fromJson(data, new TypeToken<NetworkAccessBroadcastResponse>() {
+                }.getType());
+                mBean = response;
+            }
+
+        }
+        return mBean;
+    }
+
+    /**
+     * 缃戝叧鎼滅储鐩稿叧
+     */
+    private static final int MAX_SEARCH_COUNT = 10;//鎬诲叡鎼滅储娴嬭瘯
+    private final AtomicInteger searchGatewayCount = new AtomicInteger(0);
+    ;
+    private final AtomicBoolean isSearchGatewaySuccess = new AtomicBoolean(true);
+    private String searchGatewayId = "";
+    private SearchGatewayCallBack mSearchGatewayCallBack;
+
+    private void initSearchGatewayEvent() {
+        LogUtils.i("鎼滅储缃戝叧", "initSearchGatewayEvent");
+        searchGatewayEvent = new EventListener() {
+            @Override
+            public void onMessage(Object msg) {
+                try {
+                    if (msg instanceof LinkResponse) {
+                        LinkResponse linkResponse = (LinkResponse) msg;
+                        String data = linkResponse.getData();
+                        if (!TextUtils.isEmpty(data)) {
+                            final BaseLocalResponse<GatewaySearchBean> response = GsonConvert.getGson().fromJson(data, new TypeToken<BaseLocalResponse<GatewaySearchBean>>() {
+                            }.getType());
+                            GatewaySearchBean searchBean = response.getObjects();
+                            if (searchBean != null && !TextUtils.isEmpty(searchBean.getGatewayId())) {
+                                if (searchBean.getGatewayId().contains(searchGatewayId)) {
+                                    removeSearchGatewayEvent();//绉婚櫎鎼滅储缃戝叧鐩戝惉
+                                    isSearchGatewaySuccess.set(true);//鎼滅储鎴愬姛鏍囪
+                                    searchGatewayCount.set(11);//娆℃暟鏍囪
+                                    HDLLinkConfig.getInstance().setLocalEncrypt(searchBean.isLocalEncrypt());//璁剧疆鏄惁鍔犲瘑
+                                    if (mSearchGatewayCallBack != null) {
+                                        mSearchGatewayCallBack.onSuccess(searchBean);
+                                    }
+                                }
+                            }
+                        }
+                    }
+                } catch (Exception e) {
+
+                }
+            }
+        };
+    }
+
+    private void initListenerGatewayEvent() {
+        LogUtils.i("鍒濆鍖栨案涔呯洃鍚綉鍏冲箍鎾簨浠讹紝涓嶇敤绉婚櫎姝や簨浠�");
+        EventListener gatewayEvent = new EventListener() {
+            @Override
+            public void onMessage(Object msg) {
+                try {
+                    if (msg instanceof LinkResponse) {
+                        LinkResponse linkResponse = (LinkResponse) msg;
+                        String data = linkResponse.getData();
+//                        LogUtils.i("鎺ユ敹鍒扮綉鍏充俊鎭細" + data);
+                        if (!TextUtils.isEmpty(data)) {
+                            final BaseLocalResponse<GatewayBean> response = GsonConvert.getGson().fromJson(data, new TypeToken<BaseLocalResponse<GatewayBean>>() {
+                            }.getType());
+                            GatewayBean gateway = response.getObjects();
+                            if (gateway != null) {
+                                if (!TextUtils.isEmpty(HDLLinkConfig.getInstance().getGatewayId())
+                                        && !TextUtils.isEmpty(HDLLinkConfig.getInstance().getHomeId())) {
+                                    //涓荤綉鍏冲苟涓旀槸褰撳墠缁戝畾鐨勭綉鍏�
+                                    if ("true".equals(gateway.getMaster().toLowerCase())) {
+                                        if (gateway.getGatewayId().equals(HDLLinkConfig.getInstance().getGatewayId())
+                                                || gateway.getDevice_mac().equals(HDLLinkConfig.getInstance().getGatewayId())
+                                                || gateway.getOid().equals(HDLLinkConfig.getInstance().getGatewayId())
+                                                || gateway.getHomeId().equals(HDLLinkConfig.getInstance().getHomeId())) {
+                                            HDLLinkConfig.getInstance().setLocalEncrypt(gateway.getIsLocalEncrypt());//璁剧疆鏄惁鍔犲瘑
+                                            HDLLinkConfig.getInstance().setIpAddress(gateway.getIp_address());
+                                            //鏇存柊褰撳墠缃戝叧鐨勪俊鎭�
+                                            HDLLinkConfig.getInstance().reSaveConfig();
+                                        }
+                                    }
+                                }
+
+                                if(TextUtils.isEmpty(gateway.getHomeId())||gateway.getHomeId().equals(HDLLinkConfig.getInstance().getHomeId())) {
+                                    HDLTcpConnect.initTcp(gateway.getIp_address());//鍒濆鍖朤CP杩炴帴
+                                }
+                            }
+                        }
+                    }
+                } catch (Exception e) {
+
+                }
+            }
+        };
+        EventDispatcher.getInstance().registerIo(TopicConstant.GATEWAY_SEARCH_REPLY, gatewayEvent);
+    }
+
+    /**
+     * 鎼滅储鎸囧畾缃戝叧鏄惁鍦ㄧ嚎锛屾悳绱㈠埌鍒欒繑鍥炴寚瀹氱殑缃戝叧瀵硅薄
+     *
+     * @param gatewayId 缃戝叧id
+     * @param ipAddress 鐩爣鐨処P鍦板潃
+     * @param port      鐩爣鐨勭鍙�
+     * @param callBack  鍥炶皟
+     */
+    public void searchGateway(String gatewayId, String ipAddress, int port, SearchGatewayCallBack callBack) {
+        this.searchGatewayId = gatewayId;
+        this.mSearchGatewayCallBack = callBack;
+        //閲嶇疆鍙傛暟
+        searchGatewayCount.set(0);
+        isSearchGatewaySuccess.set(false);
+        String time = String.valueOf(System.currentTimeMillis());
+        JsonObject jsonObject = new JsonObject();
+        jsonObject.addProperty("id", IdUtils.getUUId());
+        jsonObject.addProperty("time_stamp", time);
+        LinkRequest message = new LinkRequest(TopicConstant.GATEWAY_SEARCH,
+                jsonObject.toString(), false);
+        //娉ㄥ唽鎼滅储缃戝叧鐩戝惉
+        registerSearchGatewayEvent();
+        new Thread(new Runnable() {
+            @Override
+            public void run() {
+                while (searchGatewayCount.get() < 10 && (!isSearchGatewaySuccess.get())) {
+                    try {
+                        //鎼滅储缃戝叧
+                        searchGatewayCount.set(searchGatewayCount.get() + 1);
+                        LogUtils.i("鎼滅储缃戝叧绗�" + searchGatewayCount.get() + "娆�");
+                        new HDLConnectHelper(ipAddress, message, false).send();
+                        Thread.sleep(1000L);
+                    } catch (InterruptedException e) {
+                        e.printStackTrace();
+                    }
+                }
+
+                if (!isSearchGatewaySuccess.get()) {
+                    //鎼滅储10娆★紝鎸囧畾缃戝叧閮芥病鍥炲锛屽洖璋冭秴鏃�
+                    callBackSearchGatewayTimeout();
+                    LogUtils.e("鎼滅储10娆★紝鎸囧畾缃戝叧閮芥病鍥炲锛屽洖璋冭秴鏃�");
+                }
+            }
+        }).start();
+    }
+
+
+    /**
+     * 娉ㄥ唽鎼滅储缃戝叧鐩戝惉
+     */
+    private void registerSearchGatewayEvent() {
+        LogUtils.i("娉ㄥ唽鎼滅储缃戝叧鐩戝惉");
+        EventDispatcher.getInstance().registerIo(TopicConstant.GATEWAY_SEARCH_REPLY, searchGatewayEvent);
+    }
+
+    /**
+     * 绉婚櫎鎼滅储缃戝叧鐩戝惉
+     */
+    private void removeSearchGatewayEvent() {
+        LogUtils.i("鎼滅储缃戝叧", "绉婚櫎鎼滅储缃戝叧鐩戝惉");
+        EventDispatcher.getInstance().remove(TopicConstant.GATEWAY_SEARCH_REPLY, searchGatewayEvent);
+    }
+
+    /**
+     * 鍥炶皟鎼滅储缃戝叧瓒呮椂
+     */
+    private void callBackSearchGatewayTimeout() {
+        removeSearchGatewayEvent();
+        ThreadToolUtils.getInstance().runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                if (mSearchGatewayCallBack != null) {
+                    mSearchGatewayCallBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_SEARCH_GATEWAY_TIMEOUT_ERROR));
+                }
+            }
+        });
+    }
+
+
+}

--
Gitblit v1.8.0