wjc
2025-04-09 87cd5df70918e6ba1af849c5f026d3719bfdb1ac
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
package com.hdl.sdk.link.core.connect;
 
import android.content.Context;
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.link.error.HDLLinkCode;
import com.hdl.sdk.link.HDLLinkLocalSdk;
import com.hdl.sdk.link.bean.LoginRequest;
import com.hdl.sdk.link.common.event.EventDispatcher;
import com.hdl.sdk.link.common.event.EventListener;
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.LinkMessageDecoderUdp;
import com.hdl.sdk.link.gateway.HDLLinkLocalGateway;
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;
    /**
     * 因为考虑到使用一个端口,要支持接收多网关的数据,所以只允许使用一个
     */
    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 LinkMessageDecoderUdp());
//        pipeLine.add(new LinkMessageEncoder());
        options.setHandleMessage(pipeLine);
        return options;
    }
 
 
    /**
     * 获取当前udp对象,如果不存在就创建
     *
     * @return 返回当前对象
     */
    public synchronized UdpSocketBoot getUdpBoot() {
        if (null == initUdp()) {
            return null;
        }
        return udpSocketBoot;
    }
 
 
    /**
     * 初始化udp 监听功能
     *
     * @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())) {
                                    //主网关并且是当前绑定的网关
                                    if ("true".equals(gateway.getMaster().toLowerCase())) {
                                        if (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());//初始化TCP连接
//                                }
                            }
                        }
                    }
                } catch (Exception e) {
 
                }
            }
        };
        EventDispatcher.getInstance().register(TopicConstant.GATEWAY_SEARCH_REPLY, gatewayEvent);
    }
 
    /**
     * 搜索指定网关是否在线,搜索到则返回指定的网关对象
     *
     * @param gatewayId 网关id
     * @param ipAddress 目标的IP地址
     * @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().register(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));
                }
            }
        });
    }
 
 
}