HDL Home App 第二版本 旧平台金堂用 正在使用
hxb
2022-08-30 25429f085093d89d543a0b90e30d0d62d1b7dac9
ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs
@@ -26,12 +26,26 @@
        /// <summary>
        /// 主网关
        /// </summary>
        /// <value>The main gate way.</value>
        [Newtonsoft.Json.JsonIgnore]
        public static ZbGateway MainGateWay
        {
            get
            {
                return GateWayList.Find((obj) => { return obj.HomeId == Shared.Common.Config.Instance.HomeId && obj.IsMainGateWay; });
            {
                ZbGateway mainWay = null;
                for (int i = 0; i < GateWayList.Count; i++)
                {
                    if (GateWayList[i].HomeId == Config.Instance.HomeId)
                    {
                        //2020.07.16变更:别管那么多,如果住宅ID一样,先确定就是它了(不然有时候经常返回null,有可能是刷新不到)
                        mainWay = GateWayList[i];
                        if (mainWay.IsMainGateWay == true)
                        {
                            //然后如果它确实是主网关,直接break
                            break;
                        }
                    }
                }
                return mainWay;
            }
        }
@@ -2335,7 +2349,7 @@
        /// </summary>
        static Guid currentGuid = Guid.NewGuid();
        public async System.Threading.Tasks.Task SendAesKey()
        public async Task SendAesKey()
        {
            if (PubKey != null)
            {
@@ -2354,12 +2368,11 @@
            }
        }
        public async System.Threading.Tasks.Task StartLocalMqtt(string brokerName)
        public async Task StartLocalMqtt(string brokerName)
        {
            if (localMqttIsConnecting
                       || !Shared.Common.Config.Instance.IsLogin
                       || Shared.Common.Config.Instance.HomeId == ""
                       || localIsConnected)
                || Shared.Common.Config.Instance.HomeId == ""
                || localIsConnected)
            {
                return;
            }
@@ -2400,6 +2413,11 @@
                            {
                                DebugPrintLog($" 本地连接成功_网关IP:{brokerName}_网关是否加:{IsEncry}_当前密码:{Password}");
                                IsRemote = false;
                                //Log写入(调试用)
                                if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
                                {
                                    Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(2, "本地连接成功");
                                }
                            });
                        }
@@ -2439,7 +2457,12 @@
                    }
                }
                catch (Exception ex)
                {
                {
                    //Log写入(调试用)
                    if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
                    {
                        Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(2, "本地连接异常:\r\n" + ex.Message);
                    }
                    DebugPrintLog($"局域网通讯连接出异常:{ex.Message}");
                }
                finally
@@ -2457,7 +2480,7 @@
        /// 获取当前帐号所有的网关信息
        /// </summary>
        /// <returns></returns>
        static async System.Threading.Tasks.Task initGateWayBaseInfomation()
        static async Task initGateWayBaseInfomation()
        {
            if (AllowRemoteCtrl == false)
            {
@@ -2475,9 +2498,7 @@
                    MainAccountId = Config.Instance.Home.MainUserDistributedMark,
                    SharedHid = Config.Instance.Home.Id
                };
                var listNotShow = new List<string>() { "NotSetAgain" };
                var resultData = await Shared.Phone.UserCenter.UserCenterLogic.GetByteResponseDataByRequestHttps("App/GetSharedHomeApiControl", false, pra, listNotShow);
                var resultData = Shared.Phone.UserCenter.UserCenterLogic.GetByteResponseDataByRequestHttps("App/GetSharedHomeApiControl", false, pra, new List<string> { "NotCheck" });
                if (resultData == null)
                {
                    return;
@@ -2498,7 +2519,7 @@
                pra2.ReqDto.LoginAccessToken = loginToken;
                var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(pra2));
                var result = await CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/App/GetSingleHomeGatewayPagger", bytes, loginToken);
                var result = CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/App/GetSingleHomeGatewayPagger", bytes, loginToken);
                if (result != null)
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(Encoding.UTF8.GetString(result));
@@ -2550,23 +2571,37 @@
        public static IMqttClient RemoteMqttClient = new MqttFactory().CreateMqttClient();
        static bool remoteIsConnected;
        /// <summary>
        /// 远程开始连接的时间点
        /// </summary>
        private static DateTime RemoteConnectTime = DateTime.Now;
        /// <summary>
        /// 启动远程Mqtt
        /// </summary>
        /// <returns>The start.</returns>
        /// <param name="brokerName">Broker name.</param>
        public static async System.Threading.Tasks.Task StartRemoteMqtt()
        public static async Task StartRemoteMqtt()
        {
            //追加:没有远程连接的权限
            if (AllowRemoteCtrl == false
               || remoteMqttIsConnecting
               || !Shared.Common.Config.Instance.IsLogin
               || Shared.Common.Config.Instance.HomeId == ""
               || remoteIsConnected)
            {
                return;
            }
            await System.Threading.Tasks.Task.Factory.StartNew(async () =>
            //如果远程还在连接中
            if (remoteMqttIsConnecting == true)
            {
                //如果这个变量一直处于连接中的状态,但是已经过去了10秒了,还是true的话,说明这里是有点问题的,需要重新创建
                if ((DateTime.Now - RemoteConnectTime).TotalMilliseconds < 10 * 1000)
                {
                    return;
                }
            }
            //记录起这次远程连接的时间点
            RemoteConnectTime = DateTime.Now;
            await Task.Factory.StartNew(async () =>
            {
                try
                {
@@ -2629,44 +2664,50 @@
                                //订阅一个挤下线的主题
                                await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + Config.Instance.ConnEmqClientId + "/Push/NotifySqueeze");
                                await initGateWayBaseInfomation();
                                //没有主网关时主动读取,获取主网关信息
                                var gateWayList = GateWayList.FindAll(obj => obj.HomeId == Shared.Common.Config.Instance.HomeId);
                                if (gateWayList.Find(obj => obj.IsMainGateWay == true) == null)
                                //如果这个函数卡久了的话,会接收到云端推送的挤下线主题,不知道为什么
                                new Thread(async () =>
                                {
                                    if (gateWayList.Count == 1)
                                    await initGateWayBaseInfomation();
                                    //没有主网关时主动读取,获取主网关信息
                                    var gateWayList = GateWayList.FindAll(obj => obj.HomeId == Shared.Common.Config.Instance.HomeId);
                                    if (gateWayList.Find(obj => obj.IsMainGateWay == true) == null)
                                    {
                                        gateWayList[0].IsMainGateWay = true;
                                    }
                                    else
                                    {
                                        for (int i = 0; i < gateWayList.Count; i++)
                                        if (gateWayList.Count == 1)
                                        {
                                            var gateWay = gateWayList[i];
                                            var info = await gateWay.GetZbGwInfoAsync();
                                            if (info == null || info.getGwData == null)
                                            gateWayList[0].IsMainGateWay = true;
                                        }
                                        else
                                        {
                                            for (int i = 0; i < gateWayList.Count; i++)
                                            {
                                                continue;
                                            }
                                            if (info.getGwData.IsDominant == 1)
                                            {
                                                for (int j = 0; j < gateWayList.Count; j++)
                                                var gateWay = gateWayList[i];
                                                var info = await gateWay.GetZbGwInfoAsync();
                                                if (info == null || info.getGwData == null)
                                                {
                                                    if (gateWayList[i].GwId == info.getGwData.GwId)
                                                    {
                                                        gateWayList[i].IsMainGateWay = true;
                                                    }
                                                    else
                                                    {
                                                        gateWayList[i].IsMainGateWay = false;
                                                    }
                                                    continue;
                                                }
                                                break;
                                                if (info.getGwData.IsDominant == 1)
                                                {
                                                    for (int j = 0; j < gateWayList.Count; j++)
                                                    {
                                                        if (gateWayList[i].GwId == info.getGwData.GwId)
                                                        {
                                                            gateWayList[i].IsMainGateWay = true;
                                                        }
                                                        else
                                                        {
                                                            gateWayList[i].IsMainGateWay = false;
                                                        }
                                                    }
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                                })
                                { IsBackground = true }.Start();
                            });
                        }
                        #endregion
@@ -2688,7 +2729,7 @@
                                ["PublishPayloadJsonStr"] = "1"
                            };
                            var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(jsonData));
                            result = await CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/EmqMqtt/GetConnMqttInfo", bytes, Config.Instance.Token);
                            result = CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/EmqMqtt/GetConnMqttInfo", bytes, Config.Instance.Token);
                        }
                        else
                        {
@@ -2705,7 +2746,7 @@
                                ["PublishPayloadJsonStr"] = "1"
                            };
                            var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(jsonData));
                            result = await CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/EmqMqtt/ShareMemberConnMqttInfo", bytes, Config.Instance.Token);
                            result = CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/EmqMqtt/ShareMemberConnMqttInfo", bytes, Config.Instance.Token);
                        }
                        if (result != null)
                        {
@@ -2716,8 +2757,6 @@
                                AllowRemoteCtrl = false;
                                return;
                            }
                            //虽然不知道对挤下线那一块有没有用,不过先这么弄
                            await System.Threading.Tasks.Task.Delay(1500);
                            var responseData = jobject["ResponseData"];
                            if (responseData != null)
@@ -2765,13 +2804,15 @@
        /// <summary>
        /// 断开服务器连接
        /// </summary>
        public async System.Threading.Tasks.Task DisConnectLocalMqttClient(string s)
        public async Task DisConnectLocalMqttClient(string s)
        {
            try
            {
                if (localIsConnected)
                {
                    localIsConnected = false;
                    //这个东西也要弄
                    localMqttIsConnecting = false;
                    DebugPrintLog($"Local主动断开_{s}");
                    //await localMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions {  }, CancellationToken.None);
                    await localMqttClient.DisconnectAsync();
@@ -2781,18 +2822,38 @@
            {
                DebugPrintLog($"Local断开通讯连接出异常:{ex.Message}");
            }
        }
        /// <summary>
        /// 强制断开本地的网关连接
        /// </summary>
        public async Task CloseLocalConnectionOnForce()
        {
            try
            {
                await localMqttClient.DisconnectAsync();
            }
            catch { }
            finally
            {
                localIsConnected = false;
                //这个东西也要弄
                localMqttIsConnecting = false;
            }
        }
        /// <summary>
        /// 断开远程Mqtt的链接
        /// </summary>
        public static async System.Threading.Tasks.Task DisConnectRemoteMqttClient(string s = "")
        public static async Task DisConnectRemoteMqttClient(string s = "")
        {
            try
            {
                if (remoteIsConnected)
                {
                    remoteIsConnected = false;
                    //这个东西也要弄
                    remoteMqttIsConnecting = false;
                    DebugPrintLog($"Remote主动断开_{s}");
                    //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
                    await RemoteMqttClient.DisconnectAsync();
@@ -2801,6 +2862,25 @@
            catch (Exception e)
            {
                DebugPrintLog($"Remote断开通讯连接出异常:{e.Message}");
            }
        }
        /// <summary>
        /// 强制断开远程Mqtt的链接
        /// </summary>
        /// <returns></returns>
        public static async Task CloseRemoteConnectionOnForce()
        {
            try
            {
                await RemoteMqttClient.DisconnectAsync();
            }
            catch { }
            finally
            {
                remoteIsConnected = false;
                //这个东西也要弄
                remoteMqttIsConnecting = false;
            }
        }
@@ -2882,6 +2962,16 @@
                if (Shared.Common.Config.Instance.HomeId == "")
                {
                    return;
                }
                //Log写入(调试用)
                if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
                {
                    string text = "远程发送:";
                    if (IsRemote == false) { text = "本地发送:"; }
                    text += topic + "\r\n";
                    text += Encoding.UTF8.GetString(message) + "\r\n";
                    Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(2, text);
                }
                if (IsRemote)
@@ -2916,6 +3006,11 @@
                            {
                                DebugPrintLog($"局域网——二次发送到网关的主题:{topic}_发送到网关的数据:{System.Text.Encoding.UTF8.GetString(message)}_是否加密:{IsEncry}");
                                await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
                            }
                            //Log写入(调试用)
                            if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
                            {
                                Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(2, "本地连接异常断开");
                            }
                        }
                    }
@@ -3130,6 +3225,14 @@
                    epoint = topic.Split('/')[3];
                    cluID = topic.Split('/')[4];
                    attrId = topic.Split('/')[5];
                }
                //Log写入(调试用)
                if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
                {
                    string text = "网关回复:" + topic + "\r\n";
                    text += message + "\r\n";
                    Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(2, text);
                }
                //全局接收网关推送的的逻辑(为了执行速度,尽可能的别加耗时的操作)
@@ -3477,6 +3580,11 @@
        /// </summary>
        public void ReSave()
        {
            if (Shared.Common.Config.Instance.Home.IsShowTemplate == true)
            {
                //展示模板时,不允许保存文件(防止属性上报用的)
                return;
            }
            Global.WriteFileByBytesByHomeId(FilePath, System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(this)));
        }
        #endregion
@@ -3493,7 +3601,7 @@
#if DEBUG
            if (flage == true)
            {
                //if (msg.Contains("DeviceStatusReport") == false)
                //if (msg.Contains("DeviceInfoRespon") == true)
                {
                    System.Console.WriteLine(msg + "  " + System.DateTime.Now.ToLongTimeString() + " " + System.DateTime.Now.Millisecond);
                }