From f71e74b5f0d2716fbf05da016cdaa18d64e09f80 Mon Sep 17 00:00:00 2001
From: xm <1271024303@qq.com>
Date: 星期四, 31 十二月 2020 17:01:18 +0800
Subject: [PATCH] 又换完成最新门锁。空气质量传感器完成数据和基本配置功能。开发图表和自动化的同事可下载此代码

---
 ZigbeeApp/Shared/Phone/ZigBee/Common/Application.cs |  484 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 484 insertions(+), 0 deletions(-)

diff --git a/ZigbeeApp/Shared/Phone/ZigBee/Common/Application.cs b/ZigbeeApp/Shared/Phone/ZigBee/Common/Application.cs
new file mode 100755
index 0000000..05a7aae
--- /dev/null
+++ b/ZigbeeApp/Shared/Phone/ZigBee/Common/Application.cs
@@ -0,0 +1,484 @@
+锘縰sing 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
+    {
+        #region 鈻� 鍙橀噺澹版槑___________________________
+
+        public static bool isInited;
+        /// <summary>
+        /// 鏄惁姝e湪鎼滅储缃戝叧
+        /// </summary>
+        public static bool IsSearchingGateway = false;
+        /// <summary>
+        /// 鍙戦�佺殑鏃堕棿闂撮殧(鍗曚綅:绉�)
+        /// </summary>
+        public static int SendTime = 3;
+        /// <summary>
+        /// 涓婁竴娆$殑浣忓畢ID
+        /// </summary>
+        private static string oldHomeID = string.Empty;
+        /// <summary>
+        /// 鎺ユ敹鐨処P
+        /// </summary>
+        private static List<string> listReceiveIP = new List<string>();
+
+        #endregion
+
+        #region 鈻� 鍒濆鍖朹____________________________
+
+        public static void Init()
+        {
+            if (isInited)
+            {
+                return;
+            }
+            isInited = true;
+
+            //鍒濆鍖朣ocket
+            FindGateWaySocket.Start();
+
+            //鍙戦�佸箍鎾暟鎹�
+            StartSendBroadcastData();
+
+            //鎺ユ敹骞挎挱鏁版嵁
+            StartReceiveBroadcastData();
+
+            ///寮�鍚繙绋嬭繛鎺�
+            StartRemoteMqtt();
+        }
+
+        #endregion
+
+        #region 鈻� 鍙戦�佸箍鎾暟鎹甠______________________
+
+        /// <summary>
+        /// 鍙戦�佸箍鎾暟鎹�
+        /// </summary>
+        private static void StartSendBroadcastData()
+        {
+            new System.Threading.Thread(() =>
+            {
+                var broadBytes = new byte[44];
+                var waitCount = 0;
+
+                while (true)
+                {
+                    try
+                    {
+                        //妫�娴嬭兘鍚﹀彂閫佸箍鎾� 0:涓嶈兘鍙戦�佸箍鎾� 1:鍙互鍙戦�佸箍鎾� 2:浣忓畢ID鍙樻洿
+                        int result = CheckCanSendBroadcast();
+                        if (result == 0)
+                        {
+                            continue;
+                        }
+                        if (result == 2)
+                        {
+                            //閲嶆柊鍒濆鍖栧箍鎾暟鎹�
+                            broadBytes = new byte[44];
+                            broadBytes[0] = 0xfe;
+                            broadBytes[1] = 0x29;
+                            broadBytes[2] = 0x00;
+                            broadBytes[3] = 0x00;
+                            broadBytes[4] = 0x00;
+                            broadBytes[5] = 0x00;
+                            broadBytes[6] = 0x00;
+                            broadBytes[43] = 0x02;
+                            var tempBytes = System.Text.Encoding.UTF8.GetBytes(oldHomeID);
+                            System.Array.Copy(tempBytes, 0, broadBytes, 7, 36 < tempBytes.Length ? 36 : tempBytes.Length);
+                        }
+
+                        var broadcastIpAddress = new Shared.Net.NetWiFi().BroadcastIpAddress;
+                        
+                        //娓呯┖鎺ユ敹鍒扮殑IP
+                        listReceiveIP.Clear();
+                        if (broadcastIpAddress.ToString() != "0.0.0.0")
+                        {
+                            //骞挎挱鍑哄幓
+                            FindGateWaySocket.BeginSend(new System.Net.IPEndPoint(broadcastIpAddress, 7624), broadBytes);
+                        }
+                        //绛夊緟3绉�,涓嬮潰鐨勬帴鏀舵柟娉曚細鍘绘帴鏀跺箍鎾�
+                        System.Threading.Thread.Sleep(SendTime * 1000);
+
+                        if (listReceiveIP.Count > 0)
+                        {
+                            waitCount = 0;
+                            //灞�鍩熺綉鑳藉骞挎挱寰楀埌缃戝叧
+                            ZbGateway.IsRemote = false;
+                            //褰撶綉鍏崇殑杩炴帴鏂瑰紡鏀瑰彉鏃�,璁板綍褰撳墠鐨勮繛鎺ユ柟寮�
+                            Shared.Phone.UserCenter.HdlGatewayLogic.Current.CheckGatewayByConnectChanged(Shared.Phone.UserCenter.GatewayConnectMode.WIFI);
+                        }
+                        else
+                        {
+                            waitCount++;
+                            if (waitCount >= 2)
+                            {
+                                //涓ゆ閮芥悳涓嶅埌,鎵嶆爣璁颁负杩滅▼
+                                continue;
+                            }
+                            waitCount = 0;
+                            //灞�鍩熺綉骞挎挱涓嶅埌缃戝叧
+                            ZbGateway.IsRemote = true;
+                            //褰撶綉鍏崇殑杩炴帴鏂瑰紡鏀瑰彉鏃�,璁板綍褰撳墠鐨勮繛鎺ユ柟寮�
+                            Shared.Phone.UserCenter.HdlGatewayLogic.Current.CheckGatewayByConnectChanged(Shared.Phone.UserCenter.GatewayConnectMode.Remote);
+                        }
+                    }
+                    catch { }
+                }
+            })
+            { IsBackground = true }.Start();
+        }
+
+        #endregion
+
+        #region 鈻� 鎺ユ敹骞挎挱鏁版嵁_______________________
+
+        /// <summary>
+        /// 鎺ユ敹骞挎挱鏁版嵁
+        /// </summary>
+        private static void StartReceiveBroadcastData()
+        {
+            //鏁版嵁鎺ユ敹
+            new System.Threading.Thread(async () =>
+            {
+                while (true)
+                {
+                    try
+                    {
+                        if (FindGateWaySocket.udpClient == null || FindGateWaySocket.udpClient.Available <= 0)
+                        {
+                            System.Threading.Thread.Sleep(500);
+                            continue;
+                        }
+                        var ipEndPoint = new System.Net.IPEndPoint(IPAddress.Any, 0);
+                        var bytes = FindGateWaySocket.udpClient.Receive(ref ipEndPoint);
+                        if (bytes.Length > 43 && 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
+                            {
+                                GwIP = ipAddress,
+                                GwName = gwName,
+                                HomeId = homeID,
+                                IsMainGateWay = isMainGateWay,
+                                GwId = id,
+                                PubKey = pubKey
+                            };
+                            //閫氳鍒扮綉鍏冲垪琛�
+                            if (listReceiveIP.Find(obj => obj == zbGateWay.GwId) == null)
+                            {
+                                //缃戝叧鍖归厤褰撳墠浣忓畢涓埌缃戝叧
+                                if (Shared.Common.Config.Instance.HomeId == homeID)
+                                {
+                                    listReceiveIP.Add(ipAddress);
+                                }
+                                //UI鐣岄潰姝e湪鎼滅储锛屼笉蹇呴厤褰撳墠浣忓畢鍒板埌缃戝叧姝ゆ椂涔熼�氳
+                                else if (IsSearchingGateway)
+                                {
+                                    listReceiveIP.Add(ipAddress);
+                                }
+                                //2020.08.07杩藉姞:鍗充娇绌虹殑浣忓畢id涔熷缓绔嬮摼鎺�,瀵瑰簲鎵嬪姩鎭㈠缃戝叧鍑哄巶璁剧疆鏃�,鍥犱负娌℃湁瑙g粦,浣嗘槸浣忓畢id涓虹┖鐨勯棶棰�
+                                else if (Shared.Phone.UserCenter.HdlGatewayLogic.Current.HomeIdIsEmpty(homeID) == true)
+                                {
+                                    listReceiveIP.Add(ipAddress);
+                                }
+                            }
+                            //缃戝叧鍒楄〃瀛樺偍澶勭悊
+                            var gateWay = ZbGateway.GateWayList.Find(obj => obj.GwId == zbGateWay.GwId);
+                            if (gateWay == null)
+                            {
+                                //鍒锋柊缃戝叧鐨勫湪绾挎椂闂寸偣
+                                Shared.Phone.UserCenter.HdlGatewayLogic.Current.RefreshGatewayOnlineTime(zbGateWay.GwId);
+
+                                ZbGateway.GateWayList.Add(zbGateWay);
+                                await zbGateWay.StartLocalMqtt(ipAddress);
+                            }
+                            else
+                            {
+                                //鍒锋柊缃戝叧鐨勫湪绾挎椂闂寸偣
+                                Shared.Phone.UserCenter.HdlGatewayLogic.Current.RefreshGatewayOnlineTime(gateWay.GwId);
+
+                                gateWay.IsVirtual = false;
+                                if (gateWay.GwIP != ipAddress)
+                                {
+                                    await gateWay.DisConnectLocalMqttClient("2");
+                                    ZbGateway.GateWayList.Remove(gateWay);
+                                    gateWay = zbGateWay;
+                                    ZbGateway.GateWayList.Add(gateWay);
+                                    await zbGateWay.StartLocalMqtt(ipAddress);
+                                }
+                                else
+                                {
+                                    gateWay.PubKey = pubKey;
+                                    gateWay.GwName = gwName;
+                                    gateWay.HomeId = homeID;
+                                    await gateWay.StartLocalMqtt(ipAddress);
+                                }
+
+                                //涓荤綉鍏宠缃�
+                                if (isMainGateWay && oldHomeID == gateWay.HomeId)
+                                {
+                                    for (int i = 0; i < ZbGateway.GateWayList.Count; i++)
+                                    {
+                                        var gw = ZbGateway.GateWayList[i];
+                                        //缃戝叧ID涓嶆槸褰撳墠鐨勭綉鍏筹紝鍒欐妸缃戝叧鍒楄〃涓叾浠栫綉鍏虫爣璁颁负涓嶆槸涓荤綉鍏�
+                                        if (gw.GwId != id && oldHomeID == gw.HomeId)
+                                        {
+                                            gw.IsMainGateWay = false;
+                                        }
+                                    }
+                                    //鏍囪褰撳墠缃戝叧鏄富缃戝叧
+                                    gateWay.IsMainGateWay = true;
+                                }
+                            }
+
+                            //娴嬭瘯鑳藉惁骞挎挱寰楀埌缃戝叧,閫氬父鎯呭喌涓嬩笉妫�娴�
+                            if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.CheckCanReceiveGateway == 1)
+                            {
+                                if (Shared.Phone.UserCenter.UserCenterResourse.DicReceiveGatewayTest == null)
+                                {
+                                    //闃叉寮傚父,铏界劧鍑犵巼寰堜綆
+                                    Shared.Phone.UserCenter.UserCenterResourse.HideOption.CheckCanReceiveGateway = 0;
+                                    continue;
+                                }
+                                if (Shared.Phone.UserCenter.UserCenterResourse.DicReceiveGatewayTest.ContainsKey(id) == false)
+                                {
+                                    if (gateWay == null)
+                                    {
+                                        Shared.Phone.UserCenter.UserCenterResourse.DicReceiveGatewayTest[id] = zbGateWay;
+                                    }
+                                    else
+                                    {
+                                        Shared.Phone.UserCenter.UserCenterResourse.DicReceiveGatewayTest[id] = gateWay;
+                                    }
+                                }
+                            }
+                        }
+                        else
+                        {
+                            //璋冭瘯鐢�
+                            if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSocketReceiveDataToFile == 1)
+                            {
+                                var data33 = Encoding.UTF8.GetString(bytes).Replace("锟�)", string.Empty).TrimStart('\0').TrimEnd('\0');
+                                Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(3, data33);
+                            }
+                        }
+                        await System.Threading.Tasks.Task.Delay(20);
+                    }
+                    catch (Exception ex)
+                    {
+                        //璋冭瘯鐢�
+                        if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSocketReceiveDataToFile == 1)
+                        {
+                            Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(3, "Receive寮傚父\r\n" + ex.Message);
+                        }
+                    }
+                }
+            })
+            { IsBackground = true }.Start();
+        }
+
+        #endregion
+
+        #region 鈻� 寮�鍚繙绋嬭繛鎺______________________
+
+        /// <summary>
+        /// 寮�鍚繙绋嬭繛鎺�
+        /// </summary>
+        private static void StartRemoteMqtt()
+        {
+            new System.Threading.Thread(async () =>
+            {
+                while (true)
+                {
+                    try
+                    {
+                        //瀹氭椂妫�娴嬭繙绋嬭繛鎺ユ儏鍐�
+                        await ZbGateway.StartRemoteMqtt();
+                    }
+                    catch { }
+                    System.Threading.Thread.Sleep(2000);
+                }
+            })
+            { IsBackground = true }.Start();
+        }
+
+        #endregion
+
+        #region 鈻� 涓�鑸柟娉昣__________________________
+
+        /// <summary>
+        /// 閲嶆柊鎼滅储,娉ㄦ剰锛氳皟鐢ㄨ鏂规硶,鍒欎績浣垮叏閮ㄧ綉鍏崇殑mqtt鍏ㄩ儴鏂紑,鐒跺悗閲嶆柊鎼滅储(鍙兘浼氭湁1绉掑欢杩�)
+        /// </summary>
+        public static void ReSearch()
+        {
+            //涓轰簡閭d箞澶氬皯涓囧垎涔嬩竴鐨勫嚑鐜�,杩欓噷璁剧疆鎴愬埆鐨勫彟涓�绫荤殑鍊�
+            oldHomeID = "**";
+        }
+
+        /// <summary>
+        /// 妫�娴嬭兘鍚﹀彂閫佸箍鎾�(0:涓嶈兘鍙戦�佸箍鎾� 1:鍙互鍙戦�佸箍鎾� 2:浣忓畢ID鍙樻洿)
+        /// </summary>
+        /// <returns></returns>
+        private static int CheckCanSendBroadcast()
+        {
+            if (string.IsNullOrEmpty(Config.Instance.HomeId))
+            {
+                //浣忓畢ID涓虹┖鍙湁涓�绉嶅彲鑳藉氨鏄��鍑轰簡鐧诲綍锛岃繖閲岀殑涓婁竴娆′綇瀹匢D瑕佹竻绌�
+                oldHomeID = "?";
+                System.Threading.Thread.Sleep(1000);
+                return 0;
+            }
+            //棣栨杩涘叆缃戝叧锛屽拰鍒囨崲浣忓畢浼氭竻闄ょ綉鍏冲垪琛紝閲嶆柊鎼滅储瀛樺偍
+            if (Config.Instance.HomeId == oldHomeID)
+            {
+                return 1;
+            }
+
+            //鍥犱负閭d竴鐬棿锛屾湁鍙兘mqtt浼氬姞鍥炴潵,鎵�浠ュ厛鍔犵紦瀛�
+            var list = new List<ZbGateway>();
+            list.AddRange(ZbGateway.GateWayList);
+            //鐒跺悗娓呯┖鎺�
+            ZbGateway.GateWayList.Clear();
+            //鏈�鍚庡啀鏂紑mqtt杩炴帴
+            for (int i = 0; i < list.Count; i++)
+            {
+                list[i]?.DisConnectLocalMqttClient("1");
+            }
+            list.Clear();
+
+            //浣忓畢涓凡缁忓瓨鍦ㄧ殑缃戝叧濡傛灉灞�鍩熺綉涓嶅瓨鍦紝闇�瑕佸湪褰撳墠浣忓畢涓櫄鎷熶竴涓綉鍏矷D鐩稿悓鐨勭綉鍏�
+            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.GwId == paths[2]));
+                if (gateWay == null)
+                {
+                    gateWay = new ZbGateway { IsVirtual = true };
+                    gateWay.GwId = paths[2];
+                    gateWay.HomeId = Config.Instance.HomeId;
+                    ZbGateway.GateWayList.Add(gateWay);
+                }
+            }
+            //浣忓畢ID鍙樻洿
+            oldHomeID = Config.Instance.HomeId;
+
+            return 2;
+        }
+
+        #endregion
+
+        #region 鈻� Socket_____________________________
+
+        /// <summary>
+        /// 鎺ユ敹澶勭悊UDP鏁版嵁鍖�
+        /// </summary>
+        /// <typeparam name="T"></typeparam>
+        public static class FindGateWaySocket
+        {
+            //鏈湴Socket
+            public static UdpClient udpClient;
+
+            /// <summary>
+            /// 鍚姩Socket鎺ユ敹鍜屽彂閫佸姛鑳�
+            /// </summary>
+            /// <param name="port"></param>
+            public static bool Start()
+            {
+                if (udpClient != null)
+                {
+                    return true;
+                }
+
+                //鑾峰彇鎵嬫満鐨剋ifi鍦板潃
+                var netwifi = new Shared.Net.NetWiFi();
+                string phoneIp = netwifi.GetIPAddress();
+                //"127.0.0.1"鏄簳灞傚簱閲岄潰璁剧疆鐨勫垵濮嬮粯璁ゅ��
+                if (phoneIp != "127.0.0.1")
+                {
+                    udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse(phoneIp), 7624));
+                    udpClient.EnableBroadcast = true;
+                    return true;
+                }
+                return false;
+            }
+
+            /// <summary>
+            /// 鍋滄Socket
+            /// </summary>
+            public static void Stop()
+            {
+                try
+                {
+                    udpClient?.Close();
+                }
+                catch { }
+                udpClient = null;
+
+                Console.WriteLine("BusSocket鍏抽棴鎴愬姛!");
+            }
+
+            /// <summary>
+            /// 寮傛鍙戦�佹暟鎹�
+            /// </summary>
+            /// <param name="tempPacket"></param>
+            public static void BeginSend(System.Net.IPEndPoint iPEndPoint, byte[] bytes)
+            {
+                try
+                {
+                    if (Start() == false)
+                    {
+                        //璋冭瘯鐢�
+                        if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSocketReceiveDataToFile == 1)
+                        {
+                            Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(3, "udp New涓嶈捣鏉�");
+                        }
+                        return;
+                    }
+                    int value = udpClient.Send(bytes, bytes.Length, iPEndPoint);
+                    //璋冭瘯鐢�
+                    if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSocketReceiveDataToFile == 1)
+                    {
+                        Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(3, "鍙戦�侀暱搴�(BeginSendTo)锛�" + value + "  鍙戦�佸唴瀹�:" + System.Text.Encoding.UTF8.GetString(bytes));
+                    }
+                }
+                catch (Exception ex)
+                {
+                    //璋冭瘯鐢�
+                    if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSocketReceiveDataToFile == 1)
+                    {
+                        Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(3, "鍙戦�佸紓甯�(BeginSendTo)\r\n" + ex.Message);
+                    }
+                }
+            }
+        }
+
+        #endregion
+    }
+}
\ No newline at end of file

--
Gitblit v1.8.0