123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600 |
- using DevExpress.XtraBars;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using DevExpress.XtraBars.Docking2010.Views;
- using XdCxRhDW.App.UserControl;
- using DevExpress.XtraBars.Ribbon;
- using System.Threading;
- using DevExpress.XtraEditors;
- using ExtensionsDev;
- using DevExpress.XtraBars.Forms;
- using XdCxRhDW.App.CorTools;
- using System.Data.Entity;
- using System.IO;
- using System.Data.Entity.Migrations;
- using XdCxRhDW.Dto;
- using XdCxRhDW.Entity;
- using XdCxRhDW.Repostory;
- using XdCxRhDW.Api;
- using System.Net.Http;
- using XdCxRhDW.App.App.Properties;
- using System.Windows.Documents;
- using XdCxRhDW.App;
- using System.Diagnostics;
- using DevExpress.Utils.Extensions;
- using System.Net;
- using XdCxRhDW.WebApi;
- using XdCxRhDW.DataEmulation;
- using DxHelper;
- using System.Runtime.InteropServices;
- using System.Runtime.InteropServices.ComTypes;
- using DevExpress.LookAndFeel.Design;
- using System.Configuration;
- using XdCxRhDW.Framework;
- using XdCxRhDW.UI.Lib;
- using DevExpress.XtraBars.Docking2010.Views.Tabbed;
- using MySql.Data.EntityFramework;
- using MySql.Data.MySqlClient;
- namespace XdCxRhDW
- {
- public partial class MainForm : DevExpress.XtraBars.Ribbon.RibbonForm
- {
- Dictionary<string, Type> ctrlTypes = new Dictionary<string, Type>();
- public MainForm()
- {
- InitializeComponent();
- ribbon.UseDefault();
- tabbedView1.UseDefault();
- ctrlTypes.Add("任务管理", typeof(CtrlHome));
- ctrlTypes.Add("参估结果", typeof(CtrlCgRes));
- ctrlTypes.Add("绘图管理", typeof(CtrlDraw));
- ctrlTypes.Add("星历管理", typeof(CtrlXl));
- ctrlTypes.Add("卫星管理", typeof(CtrlSat));
- ctrlTypes.Add("天线管理", typeof(CtrlTx));
- ctrlTypes.Add("固定站管理", typeof(CtrlFixedStation));
- ctrlTypes.Add("信号管理", typeof(CtrlSignal));
- ctrlTypes.Add("目标管理", typeof(CtrlTarget));
- ctrlTypes.Add("系统设置", typeof(CtrlSysSettings));
- ctrlTypes.Add("变采样", typeof(ResampleForm));
- ctrlTypes.Add("GPU参估", typeof(GpuCalcForm));
- ctrlTypes.Add("检测参估", typeof(DetectToolForm));
- ctrlTypes.Add("星历推算", typeof(XlCalculateForm));
- ctrlTypes.Add("信号仿真", typeof(SignalEmulation));
- ctrlTypes.Add("服务状态", typeof(CtrlSvrs));
- ctrlTypes.Add("服务日志", typeof(CtrlSvrLog));
- DxHelper.WaitHelper.UpdateSplashMessage("正在检查数据库环境...");
- CheckDb();
- }
- private string text;
- private async void MainForm_Load(object sender, EventArgs e)
- {
- this.text = this.Text;
- this.HtmlText = $"<size=12>{this.text}";
- this.ribbonPageGroup1.Enabled = false;
- this.ribbonPageGroup2.Enabled = false;
- btnXlCalculate.Enabled = false;
- txtSvrLog.Enabled = false;
- string con = AppConfigHelper.GetConnectionString("MySql");
- string conWithTimeout = con;
- if (!con.Contains("ConnectionTimeout"))
- {
- conWithTimeout = $"{con}ConnectionTimeout=5;";
- }
- tabbedView1.DocumentActivated += (s, arg) => this.tablePanel1.Visible = false;
- tabbedView1.DocumentRemoved += (s, arg) => this.tablePanel1.Visible = tabbedView1.ActiveDocument == null;
- bool dbEnable = false;
- using (MySqlConnection myCon = new MySqlConnection(conWithTimeout))
- {
- txtMsg.Text = $"正在连接MySql...";
- await Task.Run(() =>
- {
- try
- {
- myCon.Open();
- dbEnable = true;
- }
- catch
- {
- }
- });
- }
- if (!dbEnable)
- {
- txtMsg.Text = $"无法连接到MySql=>{con}";
- return;
- }
- using (MySqlSync ctx = new MySqlSync())
- {
- ctx.SyncDb();
- }
- using (MySqlContext ctx = new MySqlContext())
- {
- SysConfig.Config =await ctx.SysSetings.FirstOrDefaultAsync();
- }
- this.ribbonPageGroup1.Enabled = true;
- this.ribbonPageGroup2.Enabled = true;
- btnXlCalculate.Enabled = true;
- txtSvrLog.Enabled = true;
- if (SysConfig.Config != null)
- {
- StartWebApi();
- }
- btn_ItemClick(null, null);
- ServerContext.Instance.Init();
- if (SysConfig.Config == null)
- {
- var size = new Size(500, 600);
- XtraForm frm = new XtraForm() { StartPosition = FormStartPosition.CenterScreen, CloseBox = false, MinimizeBox = false, MaximizeBox = false };
- frm.MinimumSize = frm.MaximumSize = frm.Size = size;
- new CtrlSysSettings() { Dock = DockStyle.Fill, Parent = frm };
- if (frm.ShowDialog() != DialogResult.Cancel)
- StartWebApi();
- else
- {
- this.Close();
- return;
- }
- }
- this.HtmlText = $"<size=12>{text}(<size=9>{SysConfig.Config.TimeZoneDisplayName}</size>)";
- Messenger.Defalut.Sub<SysSetings>("时区改变", settings =>
- {
- this.HtmlText = $"<size=12>{text}(<size=9>{settings.TimeZoneDisplayName}</size>)";
- });
- StartProcess();
- _ = XlScan();
- _ = XlClear();
- _ = ClearLocalFile();
- _ = ClearLog();
- _ = MonitorCpuAndMemory();
- await XlLonCalc();
- }
- private Task MonitorCpuAndMemory()
- {
- if (!AppConfigHelper.Get("UseGatherDevState", true)) return Task.CompletedTask;
- return Task.Run(() =>
- {
- try
- {
- int interval = 30000;
- CpuMonitor sys = new CpuMonitor();
- const int GB_DIV = 1024 * 1024 * 1024;
- while (true)
- {
- //第二章方法获取系统CPU和内存使用情况
- LogUI.Info($"设备CPU:{sys.CpuLoad:f1}%,设备内存:{(sys.PhysicalMemory - sys.MemoryAvailable) / GB_DIV:f2}GB/{sys.PhysicalMemory / (double)GB_DIV:f2}GB,平台内存:{sys.ProcessMemory() / (double)GB_DIV:f2}GB,平台线程:{sys.ProcessThread()}").Wait();
- Thread.Sleep(interval);
- }
- }
- catch
- { }
- });
- }
- private void CheckDb()
- {
- try
- {
- //using (MySqlContext db = new MySqlContext())
- //{
- // db.SyncDb();
- //}
- }
- catch (Exception ex)
- {
- LogUI.Error("同步数据库结构异常", ex).Wait(5000);
- }
- }
- private void StartWebApi()
- {
- try
- {
- Startup.Start(SysConfig.Config.HttpPort, $"{Process.GetCurrentProcess().ProcessName}.Xml", "XdCxRhDW.Dto.xml", SysConfig.Config.TimeZoneUTC);
- }
- catch (System.Reflection.TargetInvocationException ex)
- {
- XdCxRhDW.Framework.LogHelper.Error($"启动Http服务失败!", ex);
- if (ex.InnerException is HttpListenerException)
- {
- DxHelper.MsgBoxHelper.ShowWarning($"启动Http服务失败,{ex.InnerException.Message}");
- }
- else
- {
- DxHelper.MsgBoxHelper.ShowWarning($"启动Http服务失败!");
- }
- }
- catch (Exception ex)
- {
- XdCxRhDW.Framework.LogHelper.Error($"启动Http服务失败!", ex);
- DxHelper.MsgBoxHelper.ShowWarning($"启动Http服务失败!");
- }
- }
- //自动导入Tle
- private async Task XlScan()
- {
- while (true)
- {
- await Task.Delay(10000);
- if (SysConfig.Config == null
- || string.IsNullOrWhiteSpace(SysConfig.Config.XLDirectory)
- || !Directory.Exists(SysConfig.Config.XLDirectory))
- {
- continue;
- }
- DirectoryInfo dir = new DirectoryInfo(SysConfig.Config.XLDirectory);
- var backupSucceed = Path.Combine(dir.FullName, "Backup", "Succeed");
- var backupFailed = Path.Combine(dir.FullName, "Backup", "Failed");
- Directory.CreateDirectory(backupSucceed);
- Directory.CreateDirectory(backupFailed);
- var files = Directory.EnumerateFiles(SysConfig.Config.XLDirectory, "*", SearchOption.TopDirectoryOnly);
- foreach (string file in files)
- {
- bool succeed = false;
- try
- {
- var fileName = await HttpHelper.UploadFileAsync(file, SysConfig.GetBaseUrl());
- XlImportDto dto = new XlImportDto() { File = fileName };
- var res = await HttpHelper.PostRequestAsync<RecordRes>(SysConfig.GetUrl("Xl/ImportTleAsync"), dto);
- if (res.code == 200)
- {
- LogUI.Info($"星历文件[{file}]自动导入成功!").Wait(5000);
- try
- {
- //导入完成的文件放在备份目录
- var newFile = Path.Combine(backupSucceed, Path.GetFileName(file));
- if (File.Exists(newFile))
- File.Delete(newFile);
- File.Move(file, newFile);
- }
- catch
- {
- }
- }
- else
- {
- LogUI.Error($"星历文件[{file}]自动导入失败.{res.msg}").Wait(5000);
- try
- {
- //导入完成的文件放在备份目录
- var newFile = Path.Combine(backupFailed, Path.GetFileName(file));
- if (File.Exists(newFile))
- File.Delete(newFile);
- File.Move(file, newFile);
- }
- catch
- {
- }
- }
- }
- catch (Exception ex)
- {
- LogUI.Error($"星历文件[{file}]自动导入失败", ex).Wait(5000);
- try
- {
- //导入完成的文件放在备份目录
- var newFile = Path.Combine(backupFailed, Path.GetFileName(file));
- if (File.Exists(newFile))
- File.Delete(newFile);
- File.Move(file, newFile);
- }
- catch
- {
- }
- await Task.Delay(5000);
- }
- finally
- {
- await Task.Delay(2000);
- }
- }
- }
- }
- //清理1年之前导入的星历
- private async Task XlClear()
- {
- while (true)
- {
- try
- {
- List<XlInfo> clearData = new List<XlInfo>();
- using (MySqlContext db = new MySqlContext())
- {
- DateTime dt = DateTime.Now.AddYears(-1);
- clearData = await db.XlInfos.Where(p => p.UpdateTime < dt).Take(1000).ToListAsync();
- if (clearData.Any())
- {
- db.XlInfos.RemoveRange(clearData);
- await db.SaveChangesAsync();
- }
- }
- if (!clearData.Any())
- {
- await Task.Delay(60 * 1000);
- }
- }
- catch (Exception ex)
- {
- await LogUI.Error("清理过期星历异常", ex);
- }
- finally
- {
- await Task.Delay(2000);
- }
- }
- }
- //计算星历的轨道经度
- private async Task XlLonCalc()
- {
- while (true)
- {
- try
- {
- List<XlInfo> calcItems = null;
- List<SatInfo> satInfo = null;
- using (MySqlContext db = new MySqlContext())
- {
- calcItems = await db.XlInfos.Where(p => p.Lon == null).OrderByDescending(p => p.SatCode).Take(100).ToListAsync();
- satInfo = await db.SatInfos.ToListAsync();
- }
- if (calcItems != null && calcItems.Any())
- {
- var firstUpdateItems = calcItems.Where(p => satInfo.Any(t => t.SatCode == p.SatCode)).ToList();
- await Task.Run(() =>
- {
- List<XlInfo> Level1 = new List<XlInfo>();
- foreach (var item in firstUpdateItems)
- {
- try
- {
- var eph = EphHelper.Calc(item.TwoLine, item.TimeUTC);
- item.Lon = Math.Round(PhysicsHelper.EcefToGeo((eph.X, eph.Y, eph.Z)).lon, 1);
- Level1.Add(item);
- calcItems.Remove(item);
- }
- catch (Exception ex)
- {
- item.Lon = -999;
- LogUI.Error($"[{item.TwoLine}]推算XYZ星历出错!", ex).Wait(5000);
- }
- }
- if (Level1.Any())
- {
- using (MySqlContext db = new MySqlContext())
- {
- db.XlInfos.AddOrUpdate(Level1.ToArray());
- db.SaveChanges();
- }
- }
- List<XlInfo> Level2 = new List<XlInfo>();
- foreach (var item in calcItems)
- {
- try
- {
- var eph = EphHelper.Calc(item.TwoLine, item.TimeUTC);
- item.Lon = Math.Round(PhysicsHelper.EcefToGeo((eph.X, eph.Y, eph.Z)).lon, 1);
- Level2.Add(item);
- }
- catch (Exception ex)
- {
- item.Lon = -999;
- LogUI.Error($"[{item.TwoLine}]推算XYZ星历出错!", ex).Wait(5000);
- }
- }
- if (Level2.Any())
- {
- using (MySqlContext db = new MySqlContext())
- {
- db.XlInfos.AddOrUpdate(Level2.ToArray());
- db.SaveChanges();
- }
- }
- });
- await Task.Delay(2000);
- }
- else
- {
- await Task.Delay(60 * 1000);
- }
- }
- catch (Exception ex)
- {
- LogUI.Error($"推算XYZ星历出错!", ex).Wait(5000);
- }
- finally
- {
- await Task.Delay(5000);
- }
- }
- }
- //清理10分钟之前的文件
- private async Task ClearLocalFile()
- {
- while (true)
- {
- try
- {
- var uploadFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot");
- var files = Directory.EnumerateFiles(uploadFolder);
- foreach (var file in files)
- {
- FileInfo info = new FileInfo(file);
- if (info.CreationTime < DateTime.Now.AddMinutes(-10))
- {
- try
- {
- info.Delete();
- }
- catch
- {
- }
- }
- }
- }
- catch (Exception ex)
- {
- await LogUI.Error("清理wwwroot历史文件异常", ex);
- }
- await Task.Delay(60 * 1000);
- }
- }
- private async Task ClearLog()
- {
- while (true)
- {
- using (MySqlContext db = new MySqlContext())
- {
- try
- {
- var time1 = DateTime.Today.AddDays(-7);
- var time2 = DateTime.Today.AddDays(-30);
- var delItems = await db.LogRes.Where(p => p.LogTime < time1 && p.LogType != Entity.EnumLogType.Error).Take(500).ToListAsync();
- db.LogRes.RemoveRange(delItems);
- var delItems2 = await db.LogRes.Where(p => p.LogTime < time2 && p.LogType == Entity.EnumLogType.Error).Take(500).ToListAsync();
- db.LogRes.RemoveRange(delItems2);
- await db.SaveChangesAsync();
- if (!delItems.Any() && !delItems2.Any())
- {
- break;
- }
- }
- catch (Exception ex)
- {
- await LogUI.Error("清理日志信息异常", ex);
- await Task.Delay(10000);
- }
- finally
- {
- await Task.Delay(5000);
- }
- }
- }
- }
- private void btn_ItemClick(object sender, ItemClickEventArgs e)
- {
- this.tablePanel1.Visible = false;
- var btnTxt = e?.Item?.Caption?.Trim() ?? "任务管理";
- BaseDocument doc = null;
- doc = tabbedView1.Documents.Find(p => p.Control.GetType() == ctrlTypes[btnTxt]).FirstOrDefault();
- if (doc == null)
- {
- doc = tabbedView1.AddDocument((Control)Activator.CreateInstance(ctrlTypes[btnTxt]), btnTxt);
- if (doc.Control is Form form)
- {
- form.Text = "";
- doc.Caption = btnTxt;
- }
- if (btnTxt == "任务管理")
- doc.Properties.AllowClose = DevExpress.Utils.DefaultBoolean.False;
- else
- doc.Properties.AllowClose = DevExpress.Utils.DefaultBoolean.True;
- }
- tabbedView1.ActivateDocument(doc.Control);
- }
- protected override void OnFormClosing(FormClosingEventArgs e)
- {
- if (e.CloseReason == CloseReason.UserClosing)
- {
- if (!DxHelper.MsgBoxHelper.ShowConfirm("确定要退出当前系统吗?"))
- {
- e.Cancel = true;
- return;
- }
- }
- KillProcess();
- Application.Exit();
- }
- private void btnOpenApi_ItemClick(object sender, ItemClickEventArgs e)
- {
- if (SysConfig.Config == null)
- {
- DxHelper.MsgBoxHelper.ShowWarning($"请在系统设置中配置基础信息");
- return;
- }
- string addr = $"http://{IpHelper.GetLocalIp()}:{SysConfig.Config.HttpPort}/swagger";
- try
- {
- System.Diagnostics.Process.Start(addr);
- }
- catch
- {
- DxHelper.MsgBoxHelper.ShowError($"无法打开默认浏览器,请手动打开浏览器查看接口文档.地址{addr}");
- }
- }
- private void StartProcess()
- {
- Task.Run(() =>
- {
- KillProcess();
- Process pro = new Process();
- var servicesDir = Directory.GetDirectories(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Service\\"), "*", SearchOption.TopDirectoryOnly);
- foreach (var item in servicesDir)
- {
- try
- {
- string exeName = Path.GetFileNameWithoutExtension(item);
- string exeFile = $"{item}\\{exeName}.exe";
- pro.StartInfo.FileName = exeFile;
- pro.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
- pro.StartInfo.Arguments = $"http://127.0.0.1:{SysConfig.Config.HttpPort}";
- pro.Start();
- }
- catch (Exception ex)
- {
- XdCxRhDW.Framework.LogHelper.Error($"启动【{item}】中的服务异常", ex);
- DxHelper.MsgBoxHelper.ShowError($"启动【{item}】中的服务异常");
- }
- }
- });
- }
- private void KillProcess()
- {
- try
- {
- List<Process> list = new List<Process>();
- var servicesDir = Directory.GetDirectories(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Service\\"), "*", SearchOption.TopDirectoryOnly);
- foreach (var item in servicesDir)
- {
- string exeName = Path.GetFileNameWithoutExtension(item);
- list.AddRange(Process.GetProcessesByName(exeName));
- }
- foreach (var item in list)
- {
- try
- {
- item.Kill();
- }
- catch
- {
- }
- }
- }
- catch
- { }
- }
- }
- }
|