陈嘉乐
2020-09-02 652243206427f35a256400a149a1734085824cb9
ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs
@@ -30,8 +30,22 @@
        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
                {
@@ -2688,7 +2723,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 +2740,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 +2751,6 @@
                                AllowRemoteCtrl = false;
                                return;
                            }
                            //虽然不知道对挤下线那一块有没有用,不过先这么弄
                            await System.Threading.Tasks.Task.Delay(1500);
                            var responseData = jobject["ResponseData"];
                            if (responseData != null)
@@ -2765,13 +2798,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();
@@ -2786,13 +2821,15 @@
        /// <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();
@@ -2882,6 +2919,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 +2963,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 +3182,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 +3537,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