黄学彪
2019-11-20 5174e95a428876018ce3372f3dbc24b2861ea472
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
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
 
using Shared.Common;
using ZigBee.Device;
 
 
namespace ZigBee.Common
{
    public static class Application
    {
        public static bool isInited;
        static bool isEncry;
        /// <summary>
        /// 是否正在搜索网关
        /// </summary>
        public static bool IsSearchingGateway = false;
        /// <summary>
        /// 新发现的网关通知
        /// </summary>
        public static Action<ZigBee.Device.ZbGateway> NewGateWayAction;
 
        public static void Init()
        {
            if (isInited)
            {
                return;
            }
            isInited = true;
 
            new System.Threading.Thread(async () =>
            {
                var gateWayList = new List<ZbGateway> { };
                var searchCount = 0;
                var oldHomeID = string.Empty;
                var broadBytes = new byte[44];// byteHomeId[0] ,//H
                broadBytes[0] = 0xfe;
                broadBytes[1] = 0x29;
                broadBytes[2] = 0x00;
                broadBytes[3] = 0x00;
                broadBytes[4] = 0x00;
                broadBytes[5] = 0x00;
                broadBytes[6] = 0x00;
                broadBytes[43] = 0x02;
                while (true)
                {
                    try
                    {
                        if (string.IsNullOrEmpty(Shared.Common.Config.Instance.HomeId))
                        {
                            System.Threading.Thread.Sleep(1000);
                            continue;
                        }
                        //首次进入网关,和切换住宅会清除网关列表,重新搜索存储
                        if (Shared.Common.Config.Instance.HomeId != oldHomeID)
                        {
                            //因为那一瞬间,有可能mqtt会加回来,所以先加缓存
                            var list = new List<ZbGateway>();
                            list.AddRange(ZbGateway.GateWayList);
                            //然后清空掉
                            ZbGateway.GateWayList.Clear();
                            //最后再断开mqtt连接
                            for (int i = 0; i < list.Count; i++)
                            {
                                list[i].DisConnect("1");
                            }
                            list.Clear();
                            oldHomeID = Shared.Common.Config.Instance.HomeId;
                            var tempBytes = System.Text.Encoding.UTF8.GetBytes(Shared.Common.Config.Instance.HomeId);
                            System.Array.Copy(tempBytes, 0, broadBytes, 7, 36 < tempBytes.Length ? 36 : tempBytes.Length);
                            //住宅中已经存在的网关如果局域网不存在,需要在当前住宅中虚拟一个网关ID相同的网关
                            var gateWayFileList = Global.FileListByHomeId().FindAll(obj => obj.StartsWith("Gateway_"));
                            foreach (var filePath in gateWayFileList)
                            {
                                var paths = filePath.Split('_');
                                if (paths.Length < 3)
                                    continue;
 
                                var gateWay = ZbGateway.GateWayList.Find(obj => (obj != null) && (obj.getGatewayBaseInfo != null) && (obj.getGatewayBaseInfo.gwID == paths[2]));
                                if (gateWay == null)
                                {
                                    gateWay = new ZbGateway { IsVirtual = true };
                                    gateWay.getGatewayBaseInfo.gwID = paths[2];
                                    gateWay.getGatewayBaseInfo.HomeId = Shared.Common.Config.Instance.HomeId;
                                    ZbGateway.GateWayList.Add(gateWay);
                                }
                            }
                        }
 
                        var broadcastIpAddress = new Shared.Net.NetWiFi().BroadcastIpAddress;
 
                        if (0 < gateWayList.Count)
                        {
                            searchCount = 4;
                            ZbGateway.IsRemote = false;
                        }
                        else
                        {
                            if (searchCount <= 0)
                            {
                                gateWayList.Clear();
                                ZbGateway.IsRemote = true;
                            }
                        }
 
                        searchCount--;
 
                        #region 2秒搜索一次网关
                        //每0.5秒广播发现一次网关,共2s
                        int count = 4;
                        new System.Threading.Thread(() =>
                        {
                            while (0 < count--)
                            {
                                try
                                {
                                    //点对点发送(先发一条已有的点播,回复几率高一点)
                                    for (int i = 0; i < gateWayList.Count; i++)
                                    {
                                        FindGateWaySocket.BeginSend(new System.Net.IPEndPoint(System.Net.IPAddress.Parse(gateWayList[i].getGatewayBaseInfo.IpAddress), 7624), broadBytes);
                                    }
                                    //广播发送
                                    if (broadcastIpAddress.ToString() != "0.0.0.0")
                                    {
                                        FindGateWaySocket.BeginSend(new System.Net.IPEndPoint(broadcastIpAddress, 7624), broadBytes);
                                    }
                                }
                                catch { }
                                System.Threading.Thread.Sleep(500);
                            }
                        })
                        { IsBackground = true }.Start();
 
                        while (0 < count)
                        {
                            try
                            {
                                if (FindGateWaySocket.busSocket == null)
                                {
                                    System.Threading.Thread.Sleep(100);
                                    continue;
                                }
                                var bytes = new byte[1024];
 
                                var len = FindGateWaySocket.busSocket.Receive(bytes, bytes.Length, System.Net.Sockets.SocketFlags.None);
 
                                if (bytes[43] == 0xA2)
                                {
                                    //广播回复网关的基本信息处理
                                    var ipAddress = $"{bytes[3]}.{bytes[4]}.{bytes[5]}.{bytes[6]}";
                                    var homeID = System.Text.Encoding.UTF8.GetString(bytes, 7, 36);
                                    homeID = homeID.Replace('\0', ' ').Trim();
                                    var isMainGateWay = bytes[44] == 1;
                                    var time = (bytes[48] & 0xff) << 24 | (bytes[47] & 0xff) << 16 | (bytes[46] & 0xff) << 8 | (bytes[45] & 0xff);
                                    var gwNameLength = bytes[49];
                                    var gwName = System.Text.Encoding.UTF8.GetString(bytes, 50, gwNameLength);
                                    var gwIdLength = bytes[49 + gwNameLength + 1];
                                    var id = Encoding.UTF8.GetString(bytes, 49 + gwNameLength + 2, gwIdLength);
                                    var pubKeyLengthByte0 = bytes[49 + gwNameLength + 1 + gwIdLength + 1];
                                    var pubKeyLengthByte1 = bytes[49 + gwNameLength + 1 + gwIdLength + 2];
                                    int pubKeyLength = ((pubKeyLengthByte1 & 0xff) << 8 | (pubKeyLengthByte0 & 0xff));
                                    var pubKey = Encoding.UTF8.GetString(bytes, 49 + gwNameLength + 1 + gwIdLength + 2 + 1, pubKeyLength);
                                    var zbGateWay = new ZbGateway
                                    {
                                        getGatewayBaseInfo = new ZbGateway.GatewayBaseInfo
                                        {
                                            IpAddress = ipAddress,
                                            Time = time,
                                            GwName = gwName,
                                            HomeId = homeID,
                                            IsMainGateWay = isMainGateWay,
                                            gwID = id,
                                        },
                                        GatewayOnlineFlage = true,
                                        PubKey = pubKey
                                    };
                                    //通讯到网关列表
                                    if (gateWayList.Find(obj => obj.getGatewayBaseInfo.gwID == zbGateWay.getGatewayBaseInfo.gwID) == null)
                                    {
                                        //网关匹配当前住宅中到网关
                                        if (Shared.Common.Config.Instance.HomeId == homeID)
                                        {
                                            gateWayList.Add(zbGateWay);
                                        }
                                        //UI界面正在搜索,不必配当前住宅到到网关此时也通讯
                                        else if (IsSearchingGateway)
                                        {
                                            gateWayList.Add(zbGateWay);
                                        }
                                        //网关中到住宅ID为空此时也通讯
                                        else if (homeID == string.Empty)
                                        {
                                            gateWayList.Add(zbGateWay);
                                        }
                                    }
                                    //网关列表存储处理
                                    var gateWay = ZbGateway.GateWayList.Find(obj => obj.getGatewayBaseInfo != null && obj.getGatewayBaseInfo.gwID == zbGateWay.getGatewayBaseInfo.gwID);
                                    if (gateWay == null)
                                    {
                                        await zbGateWay.StartLocalMqtt(ipAddress);
                                        ZbGateway.GateWayList.Add(zbGateWay);
                                        NewGateWayAction?.Invoke(zbGateWay);
                                    }
                                    else
                                    {
                                        gateWay.IsVirtual = false;
                                        //将该网关标识为【可搜索到,即:在线】
                                        gateWay.GatewayOnlineFlage = true;
                                        if (gateWay.getGatewayBaseInfo.IpAddress != ipAddress)
                                        {
                                            gateWay.DisConnect("2");
                                            ZbGateway.GateWayList.Remove(gateWay);
                                            gateWay = zbGateWay;
                                            await zbGateWay.StartLocalMqtt(ipAddress);
                                            ZbGateway.GateWayList.Add(gateWay);
                                        }
                                        else
                                        {
                                            gateWay.PubKey = pubKey;
                                            gateWay.getGatewayBaseInfo.Time = time;
                                            gateWay.getGatewayBaseInfo.GwName = gwName;
                                            gateWay.getGatewayBaseInfo.HomeId = homeID;
                                            await gateWay.StartLocalMqtt(ipAddress);
                                        }
 
                                        //主网关设置
                                        if (isMainGateWay && oldHomeID == gateWay.getGatewayBaseInfo.HomeId)
                                        {
                                            for (int i = 0; i < ZbGateway.GateWayList.Count; i++)
                                            {
                                                var gw = ZbGateway.GateWayList[i];
                                                //网关ID不是当前的网关,则把网关列表中其他网关标记为不是主网关
                                                if (gw.getGatewayBaseInfo.gwID != id && oldHomeID == gw.getGatewayBaseInfo.HomeId)
                                                {
                                                    gw.getGatewayBaseInfo.IsMainGateWay = false;
                                                }
                                            }
                                            //标记当前网关是主网关
                                            gateWay.getGatewayBaseInfo.IsMainGateWay = true;
                                        }
                                    }
                                }
                            }
                            catch { }
                        }
                        #endregion
                    }
                    catch { }
                    System.Threading.Thread.Sleep(500);
                }
            })
            { IsBackground = true }.Start();
 
            ///远程主网关更新
            new System.Threading.Thread(async () =>
            {
                while (true)
                {
                    try
                    {
                        //定时检测远程连接情况
                        await ZbGateway.StartCloudMqtt(); 
                        if (!ZbGateway.IsRemote)
                        {
                            System.Threading.Thread.Sleep(500);
                            continue;
                        }
                        var gateWayList =ZbGateway.GateWayList.FindAll(obj => obj.getGatewayBaseInfo.HomeId == Shared.Common.Config.Instance.HomeId);
 
                        if (gateWayList.Count == 1)
                        {
                            gateWayList[0].getGatewayBaseInfo.IsMainGateWay = true;
                        }
                        else
                        {
                            if (gateWayList.Find((obj) => obj.getGatewayBaseInfo.IsMainGateWay) == null)
                            {
                                for (int i = 0; i < gateWayList.Count; i++)
                                {
                                    var gateWay = gateWayList[i];
                                    var info = await gateWay.GetZbGwInfoAsync();
                                    if (info == null || info.getGwData == null)
                                    {
                                        continue;
                                    }
                                    if (info.getGwData.IsDominant == 1)
                                    {
                                        gateWay.getGatewayBaseInfo.IsMainGateWay = true;
                                        for (int j = i + 1; j < gateWayList.Count; j++)
                                        {
                                            gateWayList[j].getGatewayBaseInfo.IsMainGateWay = false;
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    catch { }
                    System.Threading.Thread.Sleep(2000);
                }
            })
            { IsBackground = true }.Start();
        }
 
 
        /// <summary>
        /// 接收处理UDP数据包
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public static class FindGateWaySocket
        {
            //本地Socket
            public static System.Net.Sockets.Socket busSocket;
 
            /// <summary>
            /// 启动Socket接收和发送功能
            /// </summary>
            /// <param name="port"></param>
            public static void Start(int port = 7624)
            {
                if (IsRunning)
                {
                    return;
                }
                //定义网络类型,数据连接类型和网络协议UDP
                busSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                busSocket.EnableBroadcast = true;
                busSocket.ReceiveTimeout = 1000;
                busSocket.SendTimeout = 1000;
                busSocket.Bind(new IPEndPoint(IPAddress.Any, port));
            }
 
            /// <summary>
            /// 停止Socket
            /// </summary>
            public static void Stop()
            {
                if (!IsRunning)
                {
                    return;
                }
                try
                {
                    busSocket.Close();
                }
                catch { }
                busSocket = null;
 
                Console.WriteLine("BusSocket关闭成功!");
            }
 
            /// <summary>
            /// 当前的Socket是否运行
            /// </summary>
            public static bool IsRunning
            {
                get
                {
                    return null == busSocket ? false : true;
                }
            }
 
            /// <summary>
            /// 异步发送数据
            /// </summary>
            /// <param name="tempPacket"></param>
            public static void BeginSend(System.Net.IPEndPoint iPEndPoint, byte[] bytes)
            {
                try
                {
                    Start(7624);
                    busSocket.BeginSendTo(bytes, 0, bytes.Length, SocketFlags.None, iPEndPoint, new AsyncCallback(asyncEndSend), null);
                }
                catch { }
            }
 
            /// <summary>
            /// 异步发送数据结束
            /// </summary>
            /// <param name="iar"></param>
            private static void asyncEndSend(IAsyncResult iar)
            {
                try
                {
                    int bytesSent = busSocket.EndSendTo(iar);
                }
                catch { }
            }
        }
    }
}