wxr
2024-09-27 acc8caee31c4be90bd38d1af18136b0e84f6fe94
HDL_ON/Common/ApiUtlis.cs
@@ -1,9 +1,10 @@
using System;
using System.Collections.Generic;
using HDL_ON;
using HDL_ON.DAL;
using System.Net.Http;
using System.Threading.Tasks;
using HDL_ON.DAL.Server;
using HDL_ON.Entity;
using HDL_ON.UI;
using HDL_ON.UI.UI2.FuntionControlView.Video;
using HDL_ON.UI.UI2.Intelligence.Automation;
using Newtonsoft.Json;
@@ -72,13 +73,23 @@
        /// 下载数据完成标记
        /// </summary>
        public bool DownloadDataComplete = false;
        /// <summary>
        /// token是否有效
        /// </summary>
        public bool IsValidToken = false;
        public bool hadInternet = true;
        /// <summary>
        /// 下载数据
        /// </summary>
        public void DownloadData()
        {
            if (MainPage.InternetStatus == 0 || MainPage.NoLoginMode)
            if (MainPage.NoLoginMode)
            {
                DownloadDataComplete = true;
                return;
            }
            endTime1 = DateTime.Now.AddSeconds(25);
            complateDevice = complateScene = false;
@@ -89,26 +100,161 @@
            var waitPage = new Loading();
            MainPage.BaseView.AddChidren(waitPage);
            waitPage.Start(Language.StringByID(StringId.PleaseWait));
            string code = StateCode.SUCCESS;
            Inverter.Ins.H5Page = null;//重置光伏页面
            var downloadDataThread = new System.Threading.Thread(() =>
            {
                try
                {
                    //增加3秒云服务器连接检测,连不上服务器的时候不刷新数据
                    //hadInternet = true;
                    var dataList = new List<GlobalRegionListRes>();
                    var requestJson = HttpUtil.GetSignRequestJson(new GetRegionListObj() { regionMark = HttpUtil.RegionMark });
                    var revertObj = HttpUtil.RequestHttpsPost(NewAPI.API_POST_GlobalRegionList, requestJson, HttpUtil.GlobalRequestHttpsHost, "", 3);
                    if (revertObj == null || revertObj.Code != StateCode.SUCCESS)
                    {
                        DownloadDataComplete = true;
                        hadInternet = false;
                        try
                        {
                            var spatialInfoDataBytes = FileUtlis.Files.ReadFile("SpatialInfoData");
                            if (spatialInfoDataBytes != null)
                            {
                                var spatialInfoDataString = System.Text.Encoding.UTF8.GetString(spatialInfoDataBytes);
                                if (spatialInfoDataString != null && !string.IsNullOrEmpty(spatialInfoDataString))
                                {
                                    var spatialInfoDataList = JsonConvert.DeserializeObject<List<SpatialInfo>>(spatialInfoDataString);
                                    SpatialInfo.CurrentSpatial.UpdateSpatialList(spatialInfoDataList);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            MainPage.Log("Error",$"{this.GetType()}:加载缓存房间数据异常:{ex.StackTrace}");
                        }
                        try
                        {
                            var fileList = Common.FileUtlis.Files.ReadFiles();
                            foreach (var file in fileList)
                            {
                                FunctionList.List.IniFunctionList(file, true);
                            }
                            Room.CurrentSpatial.InitRoomListFunctions();
                        }
                        catch (Exception ex)
                        {
                            MainPage.Log("Error", $"{this.GetType()}:加载缓存设备数据异常:{ex.StackTrace}");
                        }
                        return;
                    }
                    else
                    {
                        hadInternet = true;
                    }
                }
                catch (Exception ex)
                {
                    MainPage.Log("Error", $"下载数据1:{ex.StackTrace}");
                    DownloadDataComplete = true;
                    return;
                }
                finally
                {
                    MainPage.Log("服务器连接状态:" + hadInternet);
                    if (!hadInternet)
                    {
                        Application.RunOnMainThread(() =>
                        {
                            if (waitPage != null)
                            {
                                waitPage.Hide();
                                waitPage.RemoveFromParent();
                            }
                        });
                    }
                }
                MainPage.Log($"进入读取云端数据线程");
                //===================刷新Token=======================
                code = Ins.HttpRequest.RefreshToken();
                if (code != StateCode.SUCCESS)
                {
                    DownloadDataComplete = true;
                    IsValidToken= false;
                    try
                    {
                        var spatialInfoDataBytes = FileUtlis.Files.ReadFile("SpatialInfoData");
                        if (spatialInfoDataBytes != null)
                        {
                            var spatialInfoDataString = System.Text.Encoding.UTF8.GetString(spatialInfoDataBytes);
                            if (spatialInfoDataString != null && !string.IsNullOrEmpty(spatialInfoDataString))
                            {
                                var spatialInfoDataList = JsonConvert.DeserializeObject<List<SpatialInfo>>(spatialInfoDataString);
                                SpatialInfo.CurrentSpatial.UpdateSpatialList(spatialInfoDataList);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MainPage.Log("Error", $"{this.GetType()}:加载缓存房间数据异常:{ex.StackTrace}");
                    }
                    try
                    {
                        var fileList = Common.FileUtlis.Files.ReadFiles();
                        foreach (var file in fileList)
                        {
                            FunctionList.List.IniFunctionList(file, true);
                        }
                        Room.CurrentSpatial.InitRoomListFunctions();
                    }
                    catch (Exception ex)
                    {
                        MainPage.Log("Error", $"{this.GetType()}:加载缓存设备数据异常:{ex.StackTrace}");
                    }
                    MainPage.Log($"刷新token失败");
                    if (waitPage != null)
                    {
                        Application.RunOnMainThread(() =>
                        {
                            try
                            {
                                waitPage.Hide();
                                waitPage.RemoveFromParent();
                                waitPage = null;
                            }
                            catch { }
                        });
                    }
                    return;
                }
                else
                {
                    hadInternet = true;
                }
                MainPage.Log($"刷新token成功");
                //===================刷新住宅信息=======================
                code = Ins.HttpRequest.GetHomePager();
                if (code != StateCode.SUCCESS)
                {
                    if (waitPage != null)
                    {
                        Application.RunOnMainThread(() =>
                        {
                            try
                            {
                                waitPage.Hide();
                                waitPage.RemoveFromParent();
                                waitPage = null;
                            }
                            catch { }
                        });
                    }
                    MainPage.Log($"刷新住宅信息失败");
                    return;
                }
@@ -117,29 +263,23 @@
                code = Ins.HttpRequest.GetUserInfo();
                if (code != StateCode.SUCCESS)
                {
                    if (waitPage != null)
                    {
                        Application.RunOnMainThread(() =>
                        {
                            try
                            {
                                waitPage.Hide();
                                waitPage.RemoveFromParent();
                                waitPage = null;
                            }
                            catch { }
                        });
                    }
                    MainPage.Log($"刷新个人信息失败");
                    return;
                }
                MainPage.Log($"刷新个人信息成功");
                //int count = 0;
                //while (count < 10)
                //{
                //    if (DB_ResidenceData.Instance.CheckWhetherGatewayIdIsNull())
                //    {
                //        System.Threading.Thread.Sleep(200);
                //    }
                //    else
                //    {
                //        break;
                //    }
                //    count++;
                //}
                //if (DB_ResidenceData.Instance.CheckWhetherGatewayIdIsNull())
                //{
                //    return;
                //}
                try
                {
@@ -148,13 +288,26 @@
                    if (roomResult.Code == StateCode.SUCCESS)
                    {
                        MainPage.Log($"读取房间信息成功");
                        var revData = Newtonsoft.Json.JsonConvert.DeserializeObject<SpatialApiPack>(roomResult.Data.ToString());
                        var revData = JsonConvert.DeserializeObject<SpatialApiPack>(roomResult.Data.ToString());
                        if (revData == null)
                        {
                            revData = new SpatialApiPack();
                        }
                        {
                            SpatialInfo.CurrentSpatial.UpdateSpatialList(revData.list);
                            new System.Threading.Thread(() =>
                            {
                                try
                                {
                                    var ssd = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(revData.list));
                                    FileUtlis.Files.WriteFileByBytes("SpatialInfoData", ssd);
                                }
                                catch (Exception ex)
                                {
                                    MainPage.Log("Error", $"{this.GetType()}:保存房间信息异常:{ex.StackTrace}");
                                }
                            })
                            { IsBackground = true }.Start();
                        }
                    }
                    else
@@ -172,9 +325,8 @@
                            if (deviceResult.Code == StateCode.SUCCESS)
                            {
                                FunctionList.List.ClearDatas();
                                MainPage.Log($"============设备============开始" + FunctionList.List.Functions.Count);
                                //MainPage.Log($"读取设备信息成功");
                                //MainPage.Log($"sid列表获取====" + deviceResult.Data.ToString());
                                MainPage.Log($"读取设备信息成功");
                                //MainPage.Log($"sid列表获取====\r\n", deviceResult.Data.ToString());
                                var deviceList = JsonConvert.DeserializeObject<DevcieApiPack>(deviceResult.Data.ToString());
                                if (deviceList == null)
                                {
@@ -198,7 +350,7 @@
                                }
                                finally
                                {
                                }
                                string delFile = "";
@@ -225,15 +377,14 @@
                                    }
                                }
                                //处理剩下的新增功能
                                int iiii = 0;
                                //int iiii = 0;
                                foreach (var newFunction in deviceList.list)
                                {
                                    newFunction.AssembleStatus();
                                    newFunction.SaveFunctionFile();
                                    FunctionList.List.IniFunctionList(newFunction.savePath,true);
                                    MainPage.Log($"============设备============{iiii++}");
                                    FunctionList.List.IniFunctionList(newFunction.savePath, true);
                                    //MainPage.Log($"============设备============{iiii++}");
                                }
@@ -246,7 +397,6 @@
                                //}
                                //======================获取可视对讲设备列表====================
                                bool isInterphoneType_HDL = false;//是否为HDLLinphone可视对讲
                                bool isInterphoneType_FREEVIEW = false;//是否为全视通可视对讲
                                var videoInfo = VideoSend.GetVideoInfoList();
                                if (videoInfo.Code == StateCode.SUCCESS)
@@ -254,8 +404,10 @@
                                    string videoList = videoInfo.Data.ToString();
                                    FunctionList.List.videoIntercom = JsonConvert.DeserializeObject<List<UI.UI2.FuntionControlView.Video.Video>>(videoList);
                                    foreach (var video in FunctionList.List.videoIntercom)
                                    for (int i = 0; i < FunctionList.List.videoIntercom.Count; i++)
                                    {
                                        var video = FunctionList.List.videoIntercom[i];
                                        if (video.interphoneType == InterphoneType.IMOUVISIAL.ToString())
                                        {
                                            UI.UI2.PersonalCenter.PirDevice.PirSend.LcSubAccessToken = video.subAccountToken;
@@ -265,27 +417,37 @@
                                            isInterphoneType_HDL = true;
                                            DB_ResidenceData.Instance.SupportFacePass = true;
                                            DB_ResidenceData.Instance.SaveResidenceData();
                                            Entity.DB_ResidenceData.Instance.SupportFVDevice = true;
                                            DB_ResidenceData.Instance.SupportFVDevice = true;
                                        }
                                        else if (video.interphoneType == InterphoneType.FREEVIEW.ToString())
                                        {
#if __IOS__
                                            try
                                            {
                                                FunctionList.List.videoIntercom.Remove(video);
                                                --i;
                                            }catch(Exception ex)
                                            {
                                                MainPage.Log("Error", $"ios 全视通异常 : {ex.StackTrace}");
                                            }
#else
                                            //为全视通可视对讲
                                            DB_ResidenceData.Instance.SupportFacePass = true;
                                            Entity.DB_ResidenceData.Instance.SupportVisitorManage = true;
                                            Entity.DB_ResidenceData.Instance.SupportFVDevice = true;
                                            //isInterphoneType_HDL = true;
                                            isInterphoneType_FREEVIEW = true;
#endif
                                        }
                                    }
                                }
                                //======================获取Sip账号并且初始化SDK可视对讲设备列表====================
                                //如果检测线程没启动,才继续下面操作 因为App有可能刚启动马上收到推送了,然后才执行到这里
                                if (HDLLinphone.Current.CheckIncomingCallThreadIsNull())
                                {
                                    //当前住宅是HDL可视对讲类型的设备
                                    if (isInterphoneType_HDL)
                                    {
@@ -311,12 +473,29 @@
                                    }
                                }
                                //======================登录全视通====================
                                if (isInterphoneType_FREEVIEW)
                                {
#if __IOS__
                                    //登录全视通
                                    Shared.IOS.HDLFVSDK.Video.Init("", DB_ResidenceData.Instance.CurrentRegion.id);
                                    //string systemVersion = UIKit.UIDevice.CurrentDevice.SystemVersion;
                                    //string errorVersion = "16.2.0";
                                    //if (systemVersion.CompareTo(errorVersion) < 0)///全视通不兼容ios16以上的系统,不要加载这个先
                                    //{
                                    //    List<VisitorTempPassword> dataList = new List<VisitorTempPassword>();
                                    //    Dictionary<string, object> dictionary = new Dictionary<string, object>();
                                    //    dictionary.Add("homeId", Entity.DB_ResidenceData.Instance.CurrentRegion.id);
                                    //    var requestJson = HttpUtil.GetSignRequestJson(dictionary);
                                    //    ResponsePackNew pack = HttpUtil.RequestHttpsPost(NewAPI.Api_Post_GetExtMemberInfo, requestJson);
                                    //    if (pack != null)
                                    //    {
                                    //        var data = JsonConvert.DeserializeObject<FreeviewMemberInfo>(pack.Data.ToString());
                                    //        //登录全视通
                                    //        Shared.IOS.HDLFVSDK.Video.Init("", data.extUserId, DB_ResidenceData.Instance.CurrentRegion.id, "78FF1E4D-FC0A-4E71-9B79-0448E4460BD7", "T0001", "120.77.53.170:9700", "120.77.53.170:21664");
                                    //    }
                                    //}
#endif
                                }
@@ -325,21 +504,82 @@
                            {
                                MainPage.Log($"读取云端设备数据失败:Code:{deviceResult.Code};  Msg:{deviceResult.message}");
                            }
                        }catch (Exception ex)
                        }
                        catch (Exception ex)
                        {
                            MainPage.Log($"============设备============{ex.Message}");
                            MainPage.Log("Error", $"============设备============{ex.StackTrace}");
                        }
                        finally
                        {
                            complateDevice = true;
                            MainPage.Log($"============设备============完成" + FunctionList.List.Functions.Count);
                        }
                    //})
                    //{ IsBackground = true }.Start();
                    ////===================场景==========================
                    //new System.Threading.Thread(() =>
                    //{
                        //======================群控====================
                        if (DB_ResidenceData.Instance.HomeGateway.isSupportGroupControl)
                        {
                            var pack = Ins.HttpRequest.GetGroupControlList();
                            if (pack != null)
                            {
                                if (pack.Code == StateCode.SUCCESS)
                                {
                                    try
                                    {
                                        var groupControlList = JsonConvert.DeserializeObject<List<GroupControl>>(pack.Data.ToString());
                                        var readSidList = new List<string>();
                                        foreach (var temp in groupControlList)
                                        {
                                            FunctionList.List.groupControls.Clear();
                                            readSidList.Add(temp.userDeviceGroupControlId);
                                            if (readSidList.Count >= 20)
                                            {
                                                var data = Ins.httpRequest.GetGroupControInfo(readSidList);
                                                if (data != null)
                                                {
                                                    if (data.Code == StateCode.SUCCESS)
                                                    {
                                                        var groupControlInfoList = JsonConvert.DeserializeObject<List<GroupControl>>(data.Data.ToString());
                                                        FunctionList.List.groupControls.AddRange(groupControlInfoList);
                                                    }
                                                    else
                                                    {
                                                        IMessageCommon.Current.ShowErrorInfoAlter(pack.Code);
                                                    }
                                                }
                                                readSidList.Clear();
                                            }
                                            //FunctionList.List.Functions.AddRange(FunctionList.List.groupControls);
                                        }
                                        if (readSidList.Count > 0)
                                        {
                                            var data = Ins.httpRequest.GetGroupControInfo(readSidList);
                                            if (data != null)
                                            {
                                                if (data.Code == StateCode.SUCCESS)
                                                {
                                                    var groupControlInfoList = JsonConvert.DeserializeObject<List<GroupControl>>(data.Data.ToString());
                                                    FunctionList.List.groupControls.AddRange(groupControlInfoList);
                                                }
                                                else
                                                {
                                                    IMessageCommon.Current.ShowErrorInfoAlter(pack.Code);
                                                }
                                            }
                                            readSidList.Clear();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        MainPage.Log("Error", $"读取组控列表失败:{ex.StackTrace}");
                                    }
                                }
                                else
                                {
                                    IMessageCommon.Current.ShowErrorInfoAlter(pack.Code);
                                }
                            }
                        }
                        //======================场景====================
                        try
                        {
                            complateScene = false;
@@ -392,33 +632,31 @@
                            {
                                MainPage.Log($"读取云端场景数据失败:Code:{pack.Code}; Msg:{pack.message}");
                            }
                        }catch(Exception ex)
                        }
                        catch (Exception ex)
                        {
                            MainPage.Log($"===场景==={ex.Message}");
                            MainPage.Log("Error", $"===场景==={ex.StackTrace}");
                        }
                        finally
                        {
                            complateScene = true;
                        }
                        //======================安防====================
                        GetSecurityList();
                        //===================读取逻辑列表====================
                        Logic.LogicList.Clear();//主页下拉强制刷新自动化列表
                        MainView.GetLogicList();//读取自动化列表
                    })
                    { IsBackground = true }.Start();
                    //===================读取逻辑列表==========================
                    Logic.LogicList.Clear();//主页下拉强制刷新自动化列表
                    //UI.UI2.Intelligence.Automation.MainView.GetLogicList();
                    //======================安防====================
                    GetSecurityList();
                    //======================注册推送====================
                    httpRequest.RegisteredPush();
                }
                catch (Exception ex)
                {
                    MainPage.Log($"数据初始化失败:{ex.Message}");
                    MainPage.Log("Error", $"数据初始化失败:{ex.StackTrace}");
                }
                finally
                {
@@ -437,9 +675,10 @@
                    try
                    {
                        FunctionList.List.Read3tyFunctionStatus();
                    }catch(Exception ex)
                    }
                    catch (Exception ex)
                    {
                        MainPage.Log("读取第三方设备状态失败:"+ex.Message);
                        MainPage.Log("Error", "读取第三方设备状态失败:" + ex.StackTrace);
                    }
                }
            });
@@ -475,13 +714,46 @@
                {
                    if (DB_ResidenceData.Instance.CurrentRegion != null)
                    {
#region 读取本地数据
                        //搜索网关
                        DriverLayer.Control.Ins.SearchLoaclGateway();
                        //重新连接mqtt
                        DAL.Mqtt.MqttClient.DisConnectRemote("刷新数据,重连mqtt",false);
#endregion
                        try
                        {
                            #region 读取本地数据
                            //搜索网关
                            DriverLayer.Control.Ins.SearchLoaclGateway();
                            //重新连接mqtt
                            DAL.Mqtt.MqttClient.DisConnectRemote("刷新数据,重连mqtt", false);
                            #endregion
                        }
                        catch (Exception ex){
                            MainPage.Log("Error", $"读取本地数据异常:{ex.StackTrace}");
                        }
                        try
                        {
                            HomePage.LoadEvent_CheckTokenValid();
                            if (IsValidToken && !UserInfo.Current.IsTipedInvalidToken)
                            {
                                UserInfo.Current.IsTipedInvalidToken = true;
                                UserInfo.Current.SaveUserInfo();
                                Application.RunOnMainThread(() =>
                                {
                                    try
                                    {
                                        new PublicAssmebly().TipOptionMsg(StringId.Tip, StringId.TokenInvalidTipMsg, StringId.OfflineControl, StringId.GoLogin, () =>
                                        {
                                            HDLCommon.Current.Logout();
                                        });
                                    }
                                    catch (Exception ex)
                                    {
                                        MainPage.Log("Error", $"提示登录凭证窗口加载异常:{ex.StackTrace}");
                                    }
                                });
                            }
                        }
                        catch (Exception ex)
                        {
                            MainPage.Log("Error", $"更新登录凭证方法调用异常:{ex.StackTrace}");
                        }
                    }
                }
            })
@@ -512,40 +784,54 @@
        /// </summary>
        public void GetSecurityList()
        {
            var pack = Ins.HttpRequest.GetSecurityList();
            if (pack.Code == StateCode.SUCCESS)
            lock (FunctionList.List.securities)
            {
                var packList = JsonConvert.DeserializeObject<List<SecurityAlarm>>(pack.Data.ToString());
                var sidList = new List<string>();
                foreach (var function in packList)
                try
                {
                    sidList.Add(function.sid);
                }
                var infoListPack = Ins.httpRequest.GetSecurityInfo(sidList, new List<string>());
                var infoList = JsonConvert.DeserializeObject<List<SecurityAlarm>>(infoListPack.Data.ToString());
                if (infoList != null)
                {
                    var filePathList = FileUtlis.Files.ReadFiles().FindAll((obj) => obj.StartsWith("SecurityData_"));
                    if (filePathList != null)
                    var pack = Ins.HttpRequest.GetSecurityList();
                    if (pack.Code == StateCode.SUCCESS)
                    {
                        foreach (var file in filePathList)
                        var packList = JsonConvert.DeserializeObject<List<SecurityAlarm>>(pack.Data.ToString());
                        Console.WriteLine("安防总数:" + packList.Count);
                        var sidList = new List<string>();
                        foreach (var function in packList)
                        {
                            FileUtlis.Files.DeleteFile(file);
                            sidList.Add(function.sid);
                        }
                        if (sidList.Count == 0)
                        {
                            return;
                        }
                        var infoListPack = Ins.httpRequest.GetSecurityInfo(sidList, new List<string>());
                        var infoList = JsonConvert.DeserializeObject<List<SecurityAlarm>>(infoListPack.Data.ToString());
                        if (infoList != null)
                        {
                            var filePathList = FileUtlis.Files.ReadFiles().FindAll((obj) => obj.StartsWith("SecurityData_"));
                            if (filePathList != null)
                            {
                                foreach (var file in filePathList)
                                {
                                    FileUtlis.Files.DeleteFile(file);
                                }
                            }
                            FunctionList.List.securities.Clear();
                            foreach (var function in infoList)
                            {
                                function.SaveFile();
                                FunctionList.List.IniFunctionList(function.savePath, true);
                            }
                        }
                    }
                    FunctionList.List.securities.Clear();
                    foreach (var function in infoList)
                    else
                    {
                        function.SaveFile();
                        FunctionList.List.IniFunctionList(function.savePath, true);
                        MainPage.Log($"读取安防列表失败:Code:{pack.Code}; Msg:{pack.message}");
                    }
                }
            }
            else
            {
                MainPage.Log($"读取安防列表失败:Code:{pack.Code}; Msg:{pack.message}");
                catch (Exception ex)
                {
                    MainPage.Log("Error", $"读取安防列表失败:Code:{ex.StackTrace}");
                }
            }
        }
        /// <summary>
@@ -556,6 +842,25 @@
            var pack = Ins.HttpRequest.GetSecurityList();
        }
        //public async Task<bool> CanConnectToHost()
        //{
        //    try
        //    {
        //        using (HttpClient client = new HttpClient())
        //        {
        //            client.Timeout = TimeSpan.FromSeconds(3); // 超时时间
        //            HttpResponseMessage response = await client.GetAsync(HttpUtil.GlobalRequestHttpsHost);
        //            return response.IsSuccessStatusCode;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        MainPage.Log(ex.StackTrace);
        //        return false;
        //    }
        //}
    }
}
}