From a4246a571c78ac6c46e7bf7dbfc123b7148caed8 Mon Sep 17 00:00:00 2001
From: JLChen <551775569@qq.com>
Date: 星期二, 16 十一月 2021 13:43:48 +0800
Subject: [PATCH] 2021-11-16 1.更新

---
 HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/socket/HDLAuthSocket.java |  363 +++++++++++++++++++++++++++++++++------------------
 1 files changed, 237 insertions(+), 126 deletions(-)

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 3f5e5b6..b6e525a 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
@@ -1,21 +1,29 @@
 package com.hdl.sdk.connect.socket;
 
 import android.text.TextUtils;
-import android.util.Log;
 
 import com.google.gson.Gson;
 import com.google.gson.JsonObject;
 import com.google.gson.reflect.TypeToken;
-import com.hdl.sdk.common.config.AuthenticateConfig;
+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.LogUtils;
+import com.hdl.sdk.connect.bean.response.AuthenticateResponse;
+import com.hdl.sdk.connect.bean.response.NetworkAccessBroadcastResponse;
+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.common.config.TopicConstant;
 import com.hdl.sdk.common.utils.IdUtils;
 import com.hdl.sdk.common.utils.IpUtils;
 import com.hdl.sdk.common.utils.gson.GsonConvert;
-import com.hdl.sdk.connect.bean.AuthenticateRequest;
-import com.hdl.sdk.connect.bean.AuthenticateRequest.AuthenticateDeviceInfoBean;
-import com.hdl.sdk.connect.bean.BaseLocalResponse;
-import com.hdl.sdk.connect.bean.DeviceControlRequest;
-import com.hdl.sdk.connect.bean.GatewaySearchBean;
+import com.hdl.sdk.connect.bean.request.AuthenticateRequest;
+import com.hdl.sdk.connect.bean.response.BaseLocalResponse;
+import com.hdl.sdk.connect.bean.request.DeviceControlRequest;
+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.protocol.LinkMessageDecoder;
@@ -24,10 +32,9 @@
 import com.hdl.sdk.socket.SocketOptions;
 import com.hdl.sdk.socket.client.UdpClient;
 import com.hdl.sdk.socket.codec.MessagePipeLine;
+import com.hdl.sdk.socket.listener.SendListener;
 
 import java.io.UnsupportedEncodingException;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
 import java.util.List;
 
 import static com.hdl.sdk.common.config.TopicConstant.DEIVCE_AUTH_REQUEST;
@@ -38,23 +45,26 @@
  * @Description : HDLAuthSocket
  */
 public class HDLAuthSocket {
+    private static final String TAG = "HDLAuth";
     /**
      * udp榛樿绔彛
      */
     private static final int UDP_PORT = 8585;
     private static SocketBoot updBoot;
+//    private EventListener authEvent;
+    /**
+     * udp榛樿缁勬挱ip
+     */
+    private static final String UDP_GROUP_IP = "239.0.168.188";
+
     /**
      * instance
      */
     private volatile static HDLAuthSocket instance;
 
-    public interface CallBack {
-
-        void onError(String error);
-
-        void onSuccess(String data);
-
-    }
+//    public interface CallBack extends BaseCallBack {
+//        void onSuccess(String msg);
+//    }
 
     /**
      * getInstance
@@ -63,7 +73,7 @@
      */
     public static synchronized HDLAuthSocket getInstance() {
         if (instance == null) {
-            synchronized (AuthenticateConfig.class) {
+            synchronized (HDLLinkConfig.class) {
                 if (instance == null) {
                     instance = new HDLAuthSocket();
                 }
@@ -90,12 +100,43 @@
         return updBoot;
     }
 
-    private String getOid() {
-        return "000101EA9B8C1C22";
+    /**
+     * 寮�濮嬬洃鍚拰鍙戣捣鍏ョ綉鍙婅璇佽姹�
+     *
+     * @param request  璁よ瘉璇锋眰淇℃伅
+     * @param callBack 缁撴灉鍥炶皟
+     */
+    public void startAuthenticateRequest(AuthenticateRequest request, HDLLinkCallBack callBack) {
+        HDLLinkConfig.getInstance().clearConfig();
+        //1.鍚姩Socket 寮�鍚洃鍚�
+        getUdpBoot(IpUtils.getBroadcastAddress());
+        //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");
+            }
+        });
     }
 
-    private String getSid() {
-        return "000101EA9B8C1C2202010001021A";
+    /**
+     * 缁撴潫鐩戝惉鍏ョ綉鍙婅璇佸箍鎾�
+     */
+    public void endAuthenticateRequest(){
+        //绉婚櫎鐩戝惉
+        EventDispatcher.getInstance().remove(TopicConstant.GATEWAY_AUTH_BROADCAST);
     }
 
     /**
@@ -105,9 +146,9 @@
      * @param request  璁よ瘉璇锋眰淇℃伅
      * @param callBack 缁撴灉鍥炶皟
      */
-    public void sendAuthenticateRequest(String ip, AuthenticateRequest request, CallBack callBack) {
+    public void sendAuthenticateRequest(String ip, AuthenticateRequest request, HDLLinkCallBack callBack) {
         if (request == null) {
-            callBack.onError("request null");
+            callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_DATA_NULL_ERROR));
         }
         String topic = DEIVCE_AUTH_REQUEST;
         Gson gs = new Gson();
@@ -117,68 +158,73 @@
         HdlSocketHelper.send(getUdpBoot(ip), message, new HdlSocketHelper.HdlSocketListener() {
             @Override
             public void onSucceed(Object msg) {
-                callBack.onSuccess(msg.toString());
+                if(callBack == null) return;
+                AuthenticateResponse bean = getAuthenticateResponseBean(msg);
+                if(bean != null){
+                    String localSecret = bean.getAuth().getLocalSecret();
+                    String gatewayId = bean.getObjects().getGatewayID();
+                    String ipAddress = bean.getObjects().getIPAddress();
+                    HDLLinkConfig.getInstance().saveConfig(localSecret,gatewayId,ipAddress);
+                    callBack.onSuccess("璁よ瘉鎴愬姛");
+                }else{
+                    callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_DATA_ERROR));
+                }
+
             }
 
             @Override
             public void onFailure() {
-                Log.i("TAG", "onFailure: ");
-                callBack.onError("瓒呮椂");
+                LogUtils.i(TAG, "onFailure: ");
+                if(callBack == null) return;
+                callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_TIMEOUT_ERROR));
             }
         });
     }
 
-    /**
-     * 鍙戦�佸叆缃戝強璁よ瘉璇锋眰
-     *
-     * @param callBack 缁撴灉鍥炶皟
-     */
-    public void sendAuthenticateRequest(CallBack callBack) {
-        String macStr = "AA000000000000BB";
-        String secret = "87ae414b7a853f65";
-        String mac_key = stringToMD5(stringToMD5(macStr + secret));
+//    /**
+//     * 鍙戦�佸叆缃戝強璁よ瘉璇锋眰
+//     *
+//     * @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);
+//    }
 
-        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 {
-        /**
-         * 鎼滅储缁撴潫
-         *
-         * @param error
-         */
-        void onEnd(String error);
-
+    public interface SearchGatewayCallBack extends BaseCallBack{
         /**
          * 鎼滅储缃戝叧鎴愬姛
          *
@@ -204,17 +250,34 @@
     }
 
     /**
+     * 缁勬挱鎼滅储鎸囧畾缃戝叧鏄惁鍦ㄧ嚎锛屾悳绱㈠埌鍒欒繑鍥炴寚瀹氱殑缃戝叧瀵硅薄
+     * @param callBack  鍥炶皟
+     */
+    public void searchGatewayMulticast(SearchGatewayCallBack callBack) {
+        searchGateway(HDLLinkConfig.getInstance().getGatewayId(), UDP_GROUP_IP, callBack);
+    }
+
+    /**
+     * 缁勬挱鎼滅储鎸囧畾缃戝叧鏄惁鍦ㄧ嚎锛屾悳绱㈠埌鍒欒繑鍥炴寚瀹氱殑缃戝叧瀵硅薄
+     * @param callBack  鍥炶皟
+     */
+    public void searchGatewayBroadcast(SearchGatewayCallBack callBack) {
+        String ip = IpUtils.getBroadcastAddress();
+        searchGateway(HDLLinkConfig.getInstance().getGatewayId(), ip, callBack);
+    }
+
+    /**
      * 鎼滅储鎸囧畾缃戝叧鏄惁鍦ㄧ嚎锛屾悳绱㈠埌鍒欒繑鍥炴寚瀹氱殑缃戝叧瀵硅薄
      *
      * @param gatewayId 缃戝叧id
+     * @param ip 鎺ユ敹鐩爣鐨刬p鍦板潃
      * @param callBack  鍥炶皟
      */
-    public void searchGateway(String gatewayId, SearchGatewayCallBack callBack) {
+    public void searchGateway(String gatewayId, String ip, SearchGatewayCallBack callBack) {
         String time = String.valueOf(System.currentTimeMillis());
         JsonObject jsonObject = new JsonObject();
         jsonObject.addProperty("id", IdUtils.getUUId());
         jsonObject.addProperty("time_stamp", time);
-        String ip = IpUtils.getBroadcastAddress();
         LinkRequest message = new LinkRequest(TopicConstant.GATEWAY_SEARCH,
                 jsonObject.toString());
 
@@ -222,19 +285,88 @@
             @Override
             public void onSucceed(Object msg) {
                 GatewaySearchBean searchBean = getGatewaySearchBean(msg);
-                if (searchBean != null && searchBean.getGatewayId() == gatewayId) {
-                    Log.i("TAG", "onSuccess: ");
+                if (searchBean != null && searchBean.getGatewayId().contains(gatewayId)) {
+                    LogUtils.i(TAG, "onSuccess: ");
+                    HDLLinkConfig.getInstance().setCurrentGateway(searchBean);
+                    HDLLinkConfig.getInstance().setLocalEncrypt(searchBean.isLocalEncrypt());
                     callBack.onSuccess(searchBean);
+                }else {
+
                 }
             }
 
             @Override
             public void onFailure() {
-                Log.i("TAG", "onFailure: ");
-                callBack.onEnd("瓒呮椂");
+                LogUtils.i(TAG, "onFailure: ");
+                callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_TIMEOUT_ERROR));
             }
         });
     }
+
+
+
+    /**
+     * 璁惧鎺у埗
+     */
+    public void propertyDown(List<DeviceControlRequest> request, HDLLinkCallBack callBack) {
+        String time = String.valueOf(System.currentTimeMillis());
+        final BaseLocalResponse<List<DeviceControlRequest>> data = new BaseLocalResponse<>();
+        data.setId(IdUtils.getUUId());
+        data.setTime_stamp(time);
+        data.setObjects(request);
+        String topic = HDLLinkConfig.getInstance().getFullTopic(TopicConstant.PROPERTY_DOWN);
+        LinkRequest message = new LinkRequest(topic,
+                GsonConvert.getGson().toJson(data));
+
+        String ip = IpUtils.getBroadcastAddress();
+        HdlSocketHelper.send(getUdpBoot(ip), message, new HdlSocketHelper.HdlSocketListener() {
+            @Override
+            public void onSucceed(Object msg) {
+                if(callBack == null) return;
+                callBack.onSuccess("鎺у埗鎴愬姛");
+            }
+
+            @Override
+            public void onFailure() {
+                if(callBack == null) return;
+                callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_CONTROL_FAILURE_ERROR));
+            }
+        });
+
+    }
+
+    /**
+     * 閫氱敤鍙戦�佹寚浠�
+     * 1绉掓病鍝嶅簲灏辫浠栭噸鏂板彂閫�,閲嶈瘯3娆�
+     * @param topic 鍙戦�佹暟鎹�
+     * @param bodyStr 鍥炲鐨勪富棰�
+     * @param callBack 鍥炶皟
+     */
+    public void udpSendMsg(String topic, String bodyStr, HDLLinkResponseCallBack callBack) {
+        if(TextUtils.isEmpty(topic) || TextUtils.isEmpty(bodyStr)) {
+            if(callBack != null){
+                callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_DATA_NULL_ERROR));
+            }
+            return;
+        }
+        LinkRequest message = new LinkRequest(topic, bodyStr);
+        String ip = IpUtils.getBroadcastAddress();
+        HdlSocketHelper.send(getUdpBoot(ip), message, new HdlSocketHelper.HdlSocketListener() {
+                    @Override
+                    public void onSucceed(Object msg) {
+                        if(callBack == null) return;
+                        callBack.onSuccess((LinkResponse) msg);
+                    }
+
+                    @Override
+                    public void onFailure() {
+                        if(callBack == null) return;
+                        callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_TIMEOUT_ERROR));
+                    }
+                }
+        );
+    }
+
 
     private GatewaySearchBean getGatewaySearchBean(Object msg) {
         GatewaySearchBean searchBean = null;
@@ -251,55 +383,34 @@
         return searchBean;
     }
 
-    /**
-     * 璁惧鎺у埗
-     */
-    public void propertyDown(List<DeviceControlRequest> request, HDLSocket.CallBack callBack) {
+    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;
+            }
 
-//        if (!TextUtils.isEmpty(getGatewayId()) && !TextUtils.isEmpty(getTcpIp())) {
-        String time = String.valueOf(System.currentTimeMillis());
-
-        final BaseLocalResponse<List<DeviceControlRequest>> data = new BaseLocalResponse<>();
-        data.setId(IdUtils.getUUId());
-        data.setTime_stamp(time);
-        data.setObjects(request);
-
-
-        String topic = String.format(TopicConstant.PROPERTY_DOWN, "1406844230123372545");
-        LinkRequest message = new LinkRequest(topic,
-                GsonConvert.getGson().toJson(data));
-
-//        Log.i("TAG", "propertyDown: " + message.toString());
-
-        String ip = IpUtils.getBroadcastAddress();
-        HdlSocketHelper.send(getUdpBoot(ip), message, null);
-
-//        }
+        }
+        return mBean;
     }
 
-    String stringToMD5(String text) {
-        byte[] hash;
-        try {
-            hash = MessageDigest.getInstance("MD5").digest(text.getBytes("UTF-8"));
-        } catch (NoSuchAlgorithmException e) {
-            e.printStackTrace();
-            return null;
-        } catch (UnsupportedEncodingException e) {
-            e.printStackTrace();
-            return null;
-        }
+    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;
+            }
 
-        StringBuilder hex = new StringBuilder(hash.length * 2);
-        for (byte b : hash) {
-            if ((b & 0xFF) < 0x10)
-                hex.append("0");
-            hex.append(Integer.toHexString(b & 0xFF));
         }
-
-        return hex.toString();
+        return mBean;
     }
-
-
-
 
 }

--
Gitblit v1.8.0