hxb
2022-09-08 2a01ef5e49422cca49bc7476fc1b8be8c8556561
HDLSDK/HDLLinkLocalSdk/src/main/java/com/hdl/sdk/link/core/connect/HDLUdpConnect.java
File was renamed from HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/socket/HDLAuthSocket.java
@@ -1,55 +1,55 @@
package com.hdl.sdk.connect.socket;
package com.hdl.sdk.link.core.connect;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
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.common.utils.TextUtils;
import com.hdl.sdk.common.utils.ThreadToolUtils;
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.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;
import com.hdl.sdk.connect.protocol.LinkMessageEncoder;
import com.hdl.sdk.socket.client.UdpClient;
import com.hdl.sdk.socket.codec.MessagePipeLine;
import com.hdl.sdk.socket.udp.UdpSocketBoot;
import com.hdl.sdk.socket.udp.UdpSocketOptions;
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.TextUtils;
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.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static com.hdl.sdk.common.config.TopicConstant.DEIVCE_AUTH_REQUEST;
import static com.hdl.sdk.link.common.config.TopicConstant.DEIVCE_AUTH_REQUEST;
/**
 * Created by jlchen on 11/11/21.
 *
 * @Description : HDLAuthSocket 由于前期已经命名好,不做更改,可用作Udp服务端使用
 */
public class HDLAuthSocket {
public class HDLUdpConnect {
    private static final String TAG = "HDLAuth";
    /**
     * udp默认端口
     */
    private static final int UDP_PORT = 8585;
    public static final int UDP_PORT = 8585;
    /**
     * 因为考虑到使用一个端口,要支持接收多网关的数据,所以只允许使用一个
     */
@@ -65,30 +65,26 @@
    /**
     * instance
     */
    private  static final HDLAuthSocket instance=new HDLAuthSocket();
    private volatile static HDLUdpConnect instance;
    private HDLAuthSocket() {
    private HDLUdpConnect() {
        initListenerGatewayEvent();
        initSearchGatewayEvent();
    }
//    public interface CallBack extends BaseCallBack {
//        void onSuccess(String msg);
//    }
    /**
     * getInstance
     *
     * @return HDLAuthSocket
     */
    public  static HDLAuthSocket getInstance() {
//        if (instance == null) {
//            synchronized (HDLAuthSocket.class) {
//        if (instance == null) {
//            instance = new HDLAuthSocket();
//        }
//            }
//        }
    public static synchronized HDLUdpConnect getInstance() {
        if (instance == null) {
            synchronized (HDLLinkConfig.class) {
                if (instance == null) {
                    instance = new HDLUdpConnect();
                }
            }
        }
        return instance;
    }
@@ -107,14 +103,28 @@
     *
     * @return 返回当前对象
     */
    private synchronized UdpSocketBoot getUdpBoot() {
    public synchronized UdpSocketBoot getUdpBoot() {
        if (null == initUdp()) {
            return null;
        }
        return udpSocketBoot;
    }
    /**
     * 初始化udp 监听功能
     *
     * @return 返回当前对象
     */
    public synchronized UdpSocketBoot initUdp() {
        try {
            if (udpSocketBoot == null) {
                udpSocketBoot = UdpClient.init(UDP_PORT, getUdpOptions());
                udpSocketBoot = UdpClient.init("0.0.0.0",UDP_PORT, getUdpOptions());
                udpSocketBoot.bind();
            }
        } catch (Exception e) {
              LogUtils.e("初始化Socket udp异常"+e.getMessage());
            LogUtils.e("初始化网关失败:"+e.getMessage());
            return null;
        }
        return udpSocketBoot;
@@ -133,22 +143,20 @@
        //2.构建监听Listener
//        authEvent =
        //3.监听网关广播的入网指令
        EventDispatcher.getInstance().remove(TopicConstant.GATEWAY_AUTH_BROADCAST);
        EventDispatcher.getInstance().register(TopicConstant.GATEWAY_AUTH_BROADCAST, new EventListener() {
            @Override
            public void onMessage(Object msg) {
                LogUtils.i("收到网关认证信息: ");
                NetworkAccessBroadcastResponse bean = getNetworkAccessBroadcastResponse(msg);
                if (bean != null) {
                    //移除监听
                    EventDispatcher.getInstance().remove(TopicConstant.GATEWAY_AUTH_BROADCAST);
                    LogUtils.i("网关入网广播IP: " + bean.getIPAddress());
                    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");
            }
        });
    }
@@ -175,14 +183,11 @@
        String topic = DEIVCE_AUTH_REQUEST;
        Gson gs = new Gson();
        String requestStr = gs.toJson(request);
        LinkRequest message = new LinkRequest(topic, requestStr);
        LinkRequest message = new LinkRequest(topic, requestStr, false);
        HdlSocketHelper.sendUdp(getUdpBoot(), ip, UDP_PORT, message, new HdlSocketHelper.HdlSocketListener() {
        new HDLConnectHelper(ip, message, requestStr + "_reply", new HDLConnectHelper.HdlSocketListener() {
            @Override
            public void onSucceed(Object msg) {
                LogUtils.i("onSucceed msg:" + msg);
                if (callBack == null) return;
                try {
                    AuthenticateResponse bean = getAuthenticateResponseBean(msg);
@@ -206,10 +211,10 @@
                                HDLLinkConfig.getInstance().saveConfig(localSecret, gatewayId, ipAddress);
                                callBack.onSuccess("认证成功");
                            }
                        } else if (bean.getCode().equals("14013")){
                        } else if (bean.getCode().equals("14013")) {
                            //认证失败,该MAC对应的设备密钥不存在
                            callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_AUTH_MAC_KEY_ERROR_));
                        } else{
                            callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_AUTH_MAC_KEY_ERROR));
                        } else {
                            //认证失败,错误码:
                            LogUtils.e("认证失败,错误码:" + bean.getCode());
                            callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_AUTH_ERROR));
@@ -228,9 +233,8 @@
                if (callBack == null) return;
                callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_TIMEOUT_ERROR));
            }
        });
        }, false).send();
    }
//    /**
//     * 发送入网及认证请求
@@ -284,14 +288,6 @@
        void onSuccess(GatewaySearchBean gatewaySearchBean);
    }
    /**
     * 开始搜索所有网关,有网关回复就回调,上层自己做去重判断
     *
     * @param callBack 回调
     */
    public void startSearchAllGateway(SearchGatewayCallBack callBack) {
    }
    /**
     * 暂停搜索网关
@@ -325,47 +321,16 @@
        searchGateway(HDLLinkConfig.getInstance().getGatewayId(), ip, UDP_PORT, callBack);
    }
    /**
     * 设备控制
     */
    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.sendUdp(getUdpBoot(), ip, UDP_PORT, 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 topic     发送数据
     * @param bodyStr   回复的主题
     * @param broadcast 是否要广播
     * @param callBack 回调
     * @param callBack  回调
     */
    public void udpSendMsg(String topic, String bodyStr,boolean broadcast,  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));
@@ -380,49 +345,49 @@
            return;
        }
        LinkRequest message = new LinkRequest(topic, bodyStr);
        LinkRequest message = new LinkRequest(topic, bodyStr, false);
        String ip = HDLLinkConfig.getInstance().getIpAddress();
        if(broadcast) {
        if (broadcast) {
            ip = IpUtils.getBroadcastAddress();
        }
        HdlSocketHelper.sendUdp(getUdpBoot(), ip, UDP_PORT, message, new HdlSocketHelper.HdlSocketListener() {
                    @Override
                    public void onSucceed(Object msg) {
                        if (callBack == null) return;
                        callBack.onSuccess((LinkResponse) msg);
                    }
        new HDLConnectHelper(ip, message, topic + "_reply", new HDLConnectHelper.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));
                    }
                }
        );
            @Override
            public void onFailure() {
                if (callBack == null) return;
                callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_TIMEOUT_ERROR));
            }
        }
                , false).send();
    }
    /**
     * 通用发送指令 只发一次,不监听回复,不重发
     *
     * @param topic   发送数据
     * @param bodyStr 回复的主题
     * @param topic     发送数据
     * @param bodyStr   回复的主题
     * @param broadcast 是否广播
     */
    public void udpSendMsg(String topic, String bodyStr,boolean broadcast) {
    public void udpSendMsg(String topic, String bodyStr, boolean broadcast) {
        if (TextUtils.isEmpty(topic) || TextUtils.isEmpty(bodyStr)) {
            LogUtils.e( "参数不能为空,不能发送UDP数据");
            LogUtils.e("udpSendMsg", "参数不能为空");
            return;
        }
        if (!HDLLinkConfig.getInstance().checkIfCertified()) {
            LogUtils.e("未认证,请先认证再调用UDP发送方法");
            LogUtils.e("udpSendMsg", "未认证,请先认证");
            return;
        }
        LinkRequest message = new LinkRequest(topic, bodyStr);
        LinkRequest message = new LinkRequest(topic, bodyStr, HDLLinkConfig.getInstance().isLocalEncrypt());
        String ip = HDLLinkConfig.getInstance().getIpAddress();
        if(broadcast) {
        if (broadcast) {
            ip = IpUtils.getBroadcastAddress();
        }
        HdlSocketHelper.sendUdpOne(getUdpBoot(), ip, UDP_PORT, message);
        new HDLConnectHelper(ip, message, false).send();
    }
    private GatewaySearchBean getGatewaySearchBean(Object msg) {
@@ -435,7 +400,6 @@
                }.getType());
                searchBean = response.getObjects();
            }
        }
        return searchBean;
    }
@@ -494,12 +458,11 @@
                            }.getType());
                            GatewaySearchBean searchBean = response.getObjects();
                            if (searchBean != null && !TextUtils.isEmpty(searchBean.getGatewayId())) {
                                searchBean.setIp_address(linkResponse.getSource_ipAddress());
                                if (searchBean.getGatewayId().contains(searchGatewayId)&&!TextUtils.isEmpty(searchGatewayId)) {
                                if (searchBean.getGatewayId().contains(searchGatewayId)) {
                                    removeSearchGatewayEvent();//移除搜索网关监听
                                    isSearchGatewaySuccess.set(true);//搜索成功标记
                                    searchGatewayCount.set(11);//次数标记
                                    HDLLinkConfig.getInstance().setCurrentGateway(searchBean);//设置当前网关
                                    HDLLinkConfig.getInstance().setLocalEncrypt(searchBean.isLocalEncrypt());//设置是否加密
                                    if (mSearchGatewayCallBack != null) {
                                        mSearchGatewayCallBack.onSuccess(searchBean);
                                    }
@@ -523,22 +486,28 @@
                    if (msg instanceof LinkResponse) {
                        LinkResponse linkResponse = (LinkResponse) msg;
                        String data = linkResponse.getData();
                        LogUtils.i("接收到网关信息:" + data);
//                        LogUtils.i("接收到网关信息:" + data);
                        if (!TextUtils.isEmpty(data)) {
                            final BaseLocalResponse<GatewaySearchBean> response = GsonConvert.getGson().fromJson(data, new TypeToken<BaseLocalResponse<GatewaySearchBean>>() {
                            final BaseLocalResponse<GatewayBean> response = GsonConvert.getGson().fromJson(data, new TypeToken<BaseLocalResponse<GatewayBean>>() {
                            }.getType());
                            GatewaySearchBean gateway = response.getObjects();
                            if (gateway != null && !TextUtils.isEmpty(gateway.getGatewayId())) {
                                //可能网关带过来的ip不对
                                gateway.setIp_address(linkResponse.getSource_ipAddress());
                                //主网关并且是当前绑定的网关
                                if ("true".equals(gateway.getMaster().toLowerCase()) && gateway.getGatewayId().equals(HDLLinkConfig.getInstance().getGatewayId())) {
                                    HDLLinkConfig.getInstance().setCurrentGateway(gateway);//设置当前网关
                                    if(!TextUtils.isEmpty( gateway.getIp_address())) {
                                        HDLLinkConfig.getInstance().setIpAddress(gateway.getIp_address());
                            GatewayBean gateway = response.getObjects();
                            if (gateway != null) {
                                if (!TextUtils.isEmpty(HDLLinkConfig.getInstance().getGatewayId())) {
                                    //主网关并且是当前绑定的网关
                                    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())) {
                                            HDLLinkConfig.getInstance().setLocalEncrypt(gateway.getIsLocalEncrypt());//设置是否加密
                                            HDLLinkConfig.getInstance().setIpAddress(gateway.getIp_address());
                                            //更新当前网关的信息
                                            HDLLinkConfig.getInstance().reSaveConfig();
                                        }
                                    }
                                    //更新当前网关的信息
                                    HDLLinkConfig.getInstance().reSaveConfig();
                                }
                                if(TextUtils.isEmpty(gateway.getGatewayId())||gateway.getGatewayId().equals(HDLLinkConfig.getInstance().getGatewayId())) {
                                    HDLTcpConnect.initTcp(gateway.getIp_address());//初始化TCP连接
                                }
                            }
                        }
@@ -570,7 +539,7 @@
        jsonObject.addProperty("id", IdUtils.getUUId());
        jsonObject.addProperty("time_stamp", time);
        LinkRequest message = new LinkRequest(TopicConstant.GATEWAY_SEARCH,
                jsonObject.toString());
                jsonObject.toString(), false);
        //注册搜索网关监听
        registerSearchGatewayEvent();
        new Thread(new Runnable() {
@@ -580,8 +549,8 @@
                    try {
                        //搜索网关
                        searchGatewayCount.set(searchGatewayCount.get() + 1);
                        LogUtils.i("搜索网关", "搜索网关第" + searchGatewayCount.get() + "次");
                        getUdpBoot().sendMsg(ipAddress, port, message.getSendBytes());
                        LogUtils.i("搜索网关第" + searchGatewayCount.get() + "次");
                        new HDLConnectHelper(ipAddress, message, false).send();
                        Thread.sleep(1000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
@@ -589,11 +558,9 @@
                }
                if (!isSearchGatewaySuccess.get()) {
                    try {
                        LogUtils.e("搜索网关", "搜索10次,指定网关都没回复,回调超时");
                        //搜索10次,指定网关都没回复,回调超时
                        callBackSearchGatewayTimeout();
                    }catch (Exception e){}
                    //搜索10次,指定网关都没回复,回调超时
                    callBackSearchGatewayTimeout();
                    LogUtils.e("搜索10次,指定网关都没回复,回调超时");
                }
            }
        }).start();
@@ -604,7 +571,7 @@
     * 注册搜索网关监听
     */
    private void registerSearchGatewayEvent() {
        LogUtils.i("搜索网关", "注册搜索网关监听");
        LogUtils.i("注册搜索网关监听");
        EventDispatcher.getInstance().registerIo(TopicConstant.GATEWAY_SEARCH_REPLY, searchGatewayEvent);
    }
@@ -621,61 +588,10 @@
     */
    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));
                }
            }
        });
        LogUtils.i("callBackSearchGatewayTimeout onError:搜索网关失败,超时");
        if (mSearchGatewayCallBack != null) {
            mSearchGatewayCallBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_SEARCH_GATEWAY_TIMEOUT_ERROR));
        }
    }
    /**
     * 搜索在线所有的网关,包括当前住宅的及没有绑定过其它住宅的网关
     *
     * @param ipAddress 目标的IP地址
     * @param port      目标的端口
     * @param callBack  回调
     */
    public void searchGateway(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());
        //注册搜索网关监听
        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() + "次");
                        getUdpBoot().sendMsg(ipAddress, port, message.getSendBytes());
                        Thread.sleep(1000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (!isSearchGatewaySuccess.get()) {
                    //搜索10次,指定网关都没回复,回调超时
                    callBackSearchGatewayTimeout();
                    LogUtils.e("搜索网关", "搜索10次,指定网关都没回复,回调超时");
                }
            }
        }).start();
    }
}