HDL Home App 第二版本 旧平台金堂用 正在使用
hxb
2022-08-30 25429f085093d89d543a0b90e30d0d62d1b7dac9
ZigbeeApp/Shared/Phone/ZigBee/Common/Application.cs
@@ -19,6 +19,10 @@
        /// 是否正在搜索网关
        /// </summary>
        public static bool IsSearchingGateway = false;
        /// <summary>
        /// 发送的时间间隔(单位:秒)
        /// </summary>
        public static int SendTime = 3;
        /// <summary>
        /// 上一次的住宅ID
        /// </summary>
@@ -64,78 +68,68 @@
        {
            new System.Threading.Thread(() =>
            {
                var searchCount = 3;
                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;
                var broadBytes = new byte[44];
                var waitCount = 0;
                while (true)
                {
                    try
                    {
                        //检测能否发送广播
                        if (CheckCanSendBroadcast(broadBytes) == false)
                        {
                            continue;
                    {
                        //检测能否发送广播 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;
                        if (Shared.Application.IsWifi)
                        //清空接收到的IP
                        listReceiveIP.Clear();
                        if (broadcastIpAddress.ToString() != "0.0.0.0")
                        {
                            if (0 < listReceiveIP.Count)
                            {
                                searchCount = 3;
                                ZbGateway.IsRemote = false;
                                //当网关的连接方式改变时,记录当前的连接方式
                                Shared.Phone.UserCenter.HdlGatewayLogic.Current.CheckGatewayByConnectChanged(Shared.Phone.UserCenter.GatewayConnectMode.WIFI);
                            }
                            else
                            {
                                if (searchCount < 0)
                                {
                                    ZbGateway.IsRemote = true;
                                    //当网关的连接方式改变时,记录当前的连接方式
                                    Shared.Phone.UserCenter.HdlGatewayLogic.Current.CheckGatewayByConnectChanged(Shared.Phone.UserCenter.GatewayConnectMode.Remote);
                                }
                            }
                            //广播出去
                            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);
                            for (int i = 0; i < ZbGateway.GateWayList.Count; i++)
                            {
                                ZbGateway.GateWayList[i].DisConnectLocalMqttClient("1");
                            }
                            //非wifi情况下,不需要广播
                            System.Threading.Thread.Sleep(1000);
                            continue;
                        }
                        searchCount--;
                        //每秒广播发现一次网关
                        int count = 2;
                        listReceiveIP.Clear();
                        while (0 < count--)
                        {
                            //点对点发送(先发一条已有的点播,回复几率高一点)
                            for (int i = 0; i < listReceiveIP.Count; i++)
                            {
                                FindGateWaySocket.BeginSend(new System.Net.IPEndPoint(System.Net.IPAddress.Parse(listReceiveIP[i]), 7624), broadBytes);
                            }
                            //广播发送
                            if (broadcastIpAddress.ToString() != "0.0.0.0")
                            {
                                FindGateWaySocket.BeginSend(new System.Net.IPEndPoint(broadcastIpAddress, 7624), broadBytes);
                            }
                            System.Threading.Thread.Sleep(1000);
                        }
                    }
                    catch { }
@@ -165,9 +159,9 @@
                            System.Threading.Thread.Sleep(500);
                            continue;
                        }
                        var ipEndPoint = new System.Net.IPEndPoint(0, 0);
                        var ipEndPoint = new System.Net.IPEndPoint(IPAddress.Any, 0);
                        var bytes = FindGateWaySocket.udpClient.Receive(ref ipEndPoint);
                        if (bytes[43] == 0xA2)
                        if (bytes.Length > 43 && bytes[43] == 0xA2)
                        {
                            //广播回复网关的基本信息处理
                            var ipAddress = $"{bytes[3]}.{bytes[4]}.{bytes[5]}.{bytes[6]}";
@@ -190,7 +184,6 @@
                                HomeId = homeID,
                                IsMainGateWay = isMainGateWay,
                                GwId = id,
                                GatewayOnlineFlage = true,
                                PubKey = pubKey
                            };
                            //通讯到网关列表
@@ -216,14 +209,18 @@
                            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;
                                //将该网关标识为【可搜索到,即:在线】
                                gateWay.GatewayOnlineFlage = true;
                                if (gateWay.GwIP != ipAddress)
                                {
                                    await gateWay.DisConnectLocalMqttClient("2");
@@ -288,6 +285,7 @@
                                Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(3, data33);
                            }
                        }
                        await System.Threading.Tasks.Task.Delay(20);
                    }
                    catch (Exception ex)
                    {
@@ -338,57 +336,60 @@
        {
            //为了那么多少万分之一的几率,这里设置成别的另一类的值
            oldHomeID = "**";
        }
        /// <summary>
        /// 检测能否发送广播
        /// </summary>
        /// <returns></returns>
        private static bool CheckCanSendBroadcast(byte[] broadBytes)
        {
            if (string.IsNullOrEmpty(Config.Instance.HomeId))
            {
                //住宅ID为空只有一种可能就是退出了登录,这里的上一次住宅ID要清空
                oldHomeID = "?";
                System.Threading.Thread.Sleep(1000);
                return false;
            }
            //首次进入网关,和切换住宅会清除网关列表,重新搜索存储
            if (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]?.DisConnectLocalMqttClient("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.GwId == paths[2]));
                    if (gateWay == null)
                    {
                        gateWay = new ZbGateway { IsVirtual = true };
                        gateWay.GwId = paths[2];
                        gateWay.HomeId = Config.Instance.HomeId;
                        ZbGateway.GateWayList.Add(gateWay);
                    }
                }
            }
            return true;
        }
        /// <summary>
        /// 检测能否发送广播(0:不能发送广播 1:可以发送广播 2:住宅ID变更)
        /// </summary>
        /// <returns></returns>
        private static int CheckCanSendBroadcast()
        {
            if (string.IsNullOrEmpty(Config.Instance.HomeId))
            {
                //住宅ID为空只有一种可能就是退出了登录,这里的上一次住宅ID要清空
                oldHomeID = "?";
                System.Threading.Thread.Sleep(1000);
                return 0;
            }
            //首次进入网关,和切换住宅会清除网关列表,重新搜索存储
            if (Config.Instance.HomeId == oldHomeID)
            {
                return 1;
            }
            //因为那一瞬间,有可能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();
            //住宅中已经存在的网关如果局域网不存在,需要在当前住宅中虚拟一个网关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.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
@@ -408,13 +409,29 @@
            /// 启动Socket接收和发送功能
            /// </summary>
            /// <param name="port"></param>
            public static void Start()
            public static bool Start()
            {
                if (udpClient!=null)
                if (udpClient != null)
                {
                    return;
                    return true;
                }
                udpClient = new UdpClient { EnableBroadcast = true };
                //获取手机的wifi地址
#if Android
                var netwifi = new Shared.Net.NetWiFi();
                string phoneIp = netwifi.GetIPAddress();
#endif
#if iOS
                string phoneIp = Shared.Net.NetWiFi.GetIPAddress();
#endif
                //"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>
@@ -440,11 +457,21 @@
            {
                try
                {
                    if (udpClient == null)
                    if (Start() == false)
                    {
                        //调试用
                        if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSocketReceiveDataToFile == 1)
                        {
                            Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(3, "udp New不起来");
                        }
                        return;
                    }
                    udpClient.Send(bytes, bytes.Length, iPEndPoint);
                    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)
                {