MainForm.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. using DevExpress.XtraBars;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Drawing;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Windows.Forms;
  11. using DevExpress.XtraBars.Docking2010.Views;
  12. using XdCxRhDW.App.UserControl;
  13. using DevExpress.XtraBars.Ribbon;
  14. using System.Threading;
  15. using DevExpress.XtraEditors;
  16. using ExtensionsDev;
  17. using DevExpress.XtraBars.Forms;
  18. using XdCxRhDW.App.CorTools;
  19. using System.Data.Entity;
  20. using System.IO;
  21. using System.Data.Entity.Migrations;
  22. using XdCxRhDW.Dto;
  23. using XdCxRhDW.Entity;
  24. using XdCxRhDW.Repostory;
  25. using XdCxRhDW.Api;
  26. using System.Net.Http;
  27. using XdCxRhDW.App.App.Properties;
  28. using System.Windows.Documents;
  29. using XdCxRhDW.App;
  30. using System.Diagnostics;
  31. using DevExpress.Utils.Extensions;
  32. using System.Net;
  33. using XdCxRhDW.WebApi;
  34. using XdCxRhDW.DataEmulation;
  35. using DxHelper;
  36. using System.Runtime.InteropServices;
  37. using System.Runtime.InteropServices.ComTypes;
  38. using DevExpress.LookAndFeel.Design;
  39. using System.Configuration;
  40. using XdCxRhDW.Framework;
  41. using XdCxRhDW.UI.Lib;
  42. using DevExpress.XtraBars.Docking2010.Views.Tabbed;
  43. using MySql.Data.EntityFramework;
  44. using MySql.Data.MySqlClient;
  45. namespace XdCxRhDW
  46. {
  47. public partial class MainForm : DevExpress.XtraBars.Ribbon.RibbonForm
  48. {
  49. Dictionary<string, Type> ctrlTypes = new Dictionary<string, Type>();
  50. public MainForm()
  51. {
  52. InitializeComponent();
  53. ribbon.UseDefault();
  54. tabbedView1.UseDefault();
  55. ctrlTypes.Add("任务管理", typeof(CtrlHome));
  56. ctrlTypes.Add("参估结果", typeof(CtrlCgRes));
  57. ctrlTypes.Add("绘图管理", typeof(CtrlDraw));
  58. ctrlTypes.Add("星历管理", typeof(CtrlXl));
  59. ctrlTypes.Add("卫星管理", typeof(CtrlSat));
  60. ctrlTypes.Add("天线管理", typeof(CtrlTx));
  61. ctrlTypes.Add("固定站管理", typeof(CtrlFixedStation));
  62. ctrlTypes.Add("信号管理", typeof(CtrlSignal));
  63. ctrlTypes.Add("目标管理", typeof(CtrlTarget));
  64. ctrlTypes.Add("系统设置", typeof(CtrlSysSettings));
  65. ctrlTypes.Add("变采样", typeof(ResampleForm));
  66. ctrlTypes.Add("GPU参估", typeof(GpuCalcForm));
  67. ctrlTypes.Add("检测参估", typeof(DetectToolForm));
  68. ctrlTypes.Add("星历推算", typeof(XlCalculateForm));
  69. ctrlTypes.Add("信号仿真", typeof(SignalEmulation));
  70. ctrlTypes.Add("服务状态", typeof(CtrlSvrs));
  71. ctrlTypes.Add("服务日志", typeof(CtrlSvrLog));
  72. DxHelper.WaitHelper.UpdateSplashMessage("正在检查数据库环境...");
  73. CheckDb();
  74. }
  75. private string text;
  76. private async void MainForm_Load(object sender, EventArgs e)
  77. {
  78. this.text = this.Text;
  79. this.HtmlText = $"<size=12>{this.text}";
  80. this.ribbonPageGroup1.Enabled = false;
  81. this.ribbonPageGroup2.Enabled = false;
  82. btnXlCalculate.Enabled = false;
  83. txtSvrLog.Enabled = false;
  84. string con = AppConfigHelper.GetConnectionString("MySql");
  85. string conWithTimeout = con;
  86. if (!con.Contains("ConnectionTimeout"))
  87. {
  88. conWithTimeout = $"{con}ConnectionTimeout=5;";
  89. }
  90. tabbedView1.DocumentActivated += (s, arg) => this.tablePanel1.Visible = false;
  91. tabbedView1.DocumentRemoved += (s, arg) => this.tablePanel1.Visible = tabbedView1.ActiveDocument == null;
  92. bool dbEnable = false;
  93. using (MySqlConnection myCon = new MySqlConnection(conWithTimeout))
  94. {
  95. txtMsg.Text = $"正在连接MySql...";
  96. await Task.Run(() =>
  97. {
  98. try
  99. {
  100. myCon.Open();
  101. dbEnable = true;
  102. }
  103. catch
  104. {
  105. }
  106. });
  107. }
  108. if (!dbEnable)
  109. {
  110. txtMsg.Text = $"无法连接到MySql=>{con}";
  111. return;
  112. }
  113. using (MySqlContext ctx = new MySqlContext())
  114. {
  115. SysConfig.Config =await ctx.SysSetings.FirstOrDefaultAsync();
  116. }
  117. this.ribbonPageGroup1.Enabled = true;
  118. this.ribbonPageGroup2.Enabled = true;
  119. btnXlCalculate.Enabled = true;
  120. txtSvrLog.Enabled = true;
  121. if (SysConfig.Config != null)
  122. {
  123. StartWebApi();
  124. }
  125. btn_ItemClick(null, null);
  126. ServerContext.Instance.Init();
  127. if (SysConfig.Config == null)
  128. {
  129. var size = new Size(500, 600);
  130. XtraForm frm = new XtraForm() { StartPosition = FormStartPosition.CenterScreen, CloseBox = false, MinimizeBox = false, MaximizeBox = false };
  131. frm.MinimumSize = frm.MaximumSize = frm.Size = size;
  132. new CtrlSysSettings() { Dock = DockStyle.Fill, Parent = frm };
  133. if (frm.ShowDialog() != DialogResult.Cancel)
  134. StartWebApi();
  135. else
  136. {
  137. this.Close();
  138. return;
  139. }
  140. }
  141. this.HtmlText = $"<size=12>{text}(<size=9>{SysConfig.Config.TimeZoneDisplayName}</size>)";
  142. Messenger.Defalut.Sub<SysSetings>("时区改变", settings =>
  143. {
  144. this.HtmlText = $"<size=12>{text}(<size=9>{settings.TimeZoneDisplayName}</size>)";
  145. });
  146. StartProcess();
  147. _ = XlScan();
  148. _ = XlClear();
  149. _ = ClearLocalFile();
  150. _ = ClearLog();
  151. _ = MonitorCpuAndMemory();
  152. await XlLonCalc();
  153. }
  154. private Task MonitorCpuAndMemory()
  155. {
  156. if (!AppConfigHelper.Get("UseGatherDevState", true)) return Task.CompletedTask;
  157. return Task.Run(() =>
  158. {
  159. try
  160. {
  161. int interval = 30000;
  162. CpuMonitor sys = new CpuMonitor();
  163. const int GB_DIV = 1024 * 1024 * 1024;
  164. while (true)
  165. {
  166. //第二章方法获取系统CPU和内存使用情况
  167. 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();
  168. Thread.Sleep(interval);
  169. }
  170. }
  171. catch
  172. { }
  173. });
  174. }
  175. private void CheckDb()
  176. {
  177. try
  178. {
  179. //using (MySqlContext db = new MySqlContext())
  180. //{
  181. // db.SyncDb();
  182. //}
  183. }
  184. catch (Exception ex)
  185. {
  186. LogUI.Error("同步数据库结构异常", ex).Wait(5000);
  187. }
  188. }
  189. private void StartWebApi()
  190. {
  191. try
  192. {
  193. Startup.Start(SysConfig.Config.HttpPort, $"{Process.GetCurrentProcess().ProcessName}.Xml", "XdCxRhDW.Dto.xml", SysConfig.Config.TimeZoneUTC);
  194. }
  195. catch (System.Reflection.TargetInvocationException ex)
  196. {
  197. XdCxRhDW.Framework.LogHelper.Error($"启动Http服务失败!", ex);
  198. if (ex.InnerException is HttpListenerException)
  199. {
  200. DxHelper.MsgBoxHelper.ShowWarning($"启动Http服务失败,{ex.InnerException.Message}");
  201. }
  202. else
  203. {
  204. DxHelper.MsgBoxHelper.ShowWarning($"启动Http服务失败!");
  205. }
  206. }
  207. catch (Exception ex)
  208. {
  209. XdCxRhDW.Framework.LogHelper.Error($"启动Http服务失败!", ex);
  210. DxHelper.MsgBoxHelper.ShowWarning($"启动Http服务失败!");
  211. }
  212. }
  213. //自动导入Tle
  214. private async Task XlScan()
  215. {
  216. while (true)
  217. {
  218. await Task.Delay(10000);
  219. if (SysConfig.Config == null
  220. || string.IsNullOrWhiteSpace(SysConfig.Config.XLDirectory)
  221. || !Directory.Exists(SysConfig.Config.XLDirectory))
  222. {
  223. continue;
  224. }
  225. DirectoryInfo dir = new DirectoryInfo(SysConfig.Config.XLDirectory);
  226. var backupSucceed = Path.Combine(dir.FullName, "Backup", "Succeed");
  227. var backupFailed = Path.Combine(dir.FullName, "Backup", "Failed");
  228. Directory.CreateDirectory(backupSucceed);
  229. Directory.CreateDirectory(backupFailed);
  230. var files = Directory.EnumerateFiles(SysConfig.Config.XLDirectory, "*", SearchOption.TopDirectoryOnly);
  231. foreach (string file in files)
  232. {
  233. bool succeed = false;
  234. try
  235. {
  236. var fileName = await HttpHelper.UploadFileAsync(file, SysConfig.GetBaseUrl());
  237. XlImportDto dto = new XlImportDto() { File = fileName };
  238. var res = await HttpHelper.PostRequestAsync<RecordRes>(SysConfig.GetUrl("Xl/ImportTleAsync"), dto);
  239. if (res.code == 200)
  240. {
  241. LogUI.Info($"星历文件[{file}]自动导入成功!").Wait(5000);
  242. try
  243. {
  244. //导入完成的文件放在备份目录
  245. var newFile = Path.Combine(backupSucceed, Path.GetFileName(file));
  246. if (File.Exists(newFile))
  247. File.Delete(newFile);
  248. File.Move(file, newFile);
  249. }
  250. catch
  251. {
  252. }
  253. }
  254. else
  255. {
  256. LogUI.Error($"星历文件[{file}]自动导入失败.{res.msg}").Wait(5000);
  257. try
  258. {
  259. //导入完成的文件放在备份目录
  260. var newFile = Path.Combine(backupFailed, Path.GetFileName(file));
  261. if (File.Exists(newFile))
  262. File.Delete(newFile);
  263. File.Move(file, newFile);
  264. }
  265. catch
  266. {
  267. }
  268. }
  269. }
  270. catch (Exception ex)
  271. {
  272. LogUI.Error($"星历文件[{file}]自动导入失败", ex).Wait(5000);
  273. try
  274. {
  275. //导入完成的文件放在备份目录
  276. var newFile = Path.Combine(backupFailed, Path.GetFileName(file));
  277. if (File.Exists(newFile))
  278. File.Delete(newFile);
  279. File.Move(file, newFile);
  280. }
  281. catch
  282. {
  283. }
  284. await Task.Delay(5000);
  285. }
  286. finally
  287. {
  288. await Task.Delay(2000);
  289. }
  290. }
  291. }
  292. }
  293. //清理1年之前导入的星历
  294. private async Task XlClear()
  295. {
  296. while (true)
  297. {
  298. try
  299. {
  300. List<XlInfo> clearData = new List<XlInfo>();
  301. using (MySqlContext db = new MySqlContext())
  302. {
  303. DateTime dt = DateTime.Now.AddYears(-1);
  304. clearData = await db.XlInfos.Where(p => p.UpdateTime < dt).Take(1000).ToListAsync();
  305. if (clearData.Any())
  306. {
  307. db.XlInfos.RemoveRange(clearData);
  308. await db.SaveChangesAsync();
  309. }
  310. }
  311. if (!clearData.Any())
  312. {
  313. await Task.Delay(60 * 1000);
  314. }
  315. }
  316. catch (Exception ex)
  317. {
  318. await LogUI.Error("清理过期星历异常", ex);
  319. }
  320. finally
  321. {
  322. await Task.Delay(2000);
  323. }
  324. }
  325. }
  326. //计算星历的轨道经度
  327. private async Task XlLonCalc()
  328. {
  329. while (true)
  330. {
  331. try
  332. {
  333. List<XlInfo> calcItems = null;
  334. List<SatInfo> satInfo = null;
  335. using (MySqlContext db = new MySqlContext())
  336. {
  337. calcItems = await db.XlInfos.Where(p => p.Lon == null).OrderByDescending(p => p.SatCode).Take(100).ToListAsync();
  338. satInfo = await db.SatInfos.ToListAsync();
  339. }
  340. if (calcItems != null && calcItems.Any())
  341. {
  342. var firstUpdateItems = calcItems.Where(p => satInfo.Any(t => t.SatCode == p.SatCode)).ToList();
  343. await Task.Run(() =>
  344. {
  345. List<XlInfo> Level1 = new List<XlInfo>();
  346. foreach (var item in firstUpdateItems)
  347. {
  348. try
  349. {
  350. var eph = EphHelper.Calc(item.TwoLine, item.TimeUTC);
  351. item.Lon = Math.Round(PhysicsHelper.EcefToGeo((eph.X, eph.Y, eph.Z)).lon, 1);
  352. Level1.Add(item);
  353. calcItems.Remove(item);
  354. }
  355. catch (Exception ex)
  356. {
  357. item.Lon = -999;
  358. LogUI.Error($"[{item.TwoLine}]推算XYZ星历出错!", ex).Wait(5000);
  359. }
  360. }
  361. if (Level1.Any())
  362. {
  363. using (MySqlContext db = new MySqlContext())
  364. {
  365. db.XlInfos.AddOrUpdate(Level1.ToArray());
  366. db.SaveChanges();
  367. }
  368. }
  369. List<XlInfo> Level2 = new List<XlInfo>();
  370. foreach (var item in calcItems)
  371. {
  372. try
  373. {
  374. var eph = EphHelper.Calc(item.TwoLine, item.TimeUTC);
  375. item.Lon = Math.Round(PhysicsHelper.EcefToGeo((eph.X, eph.Y, eph.Z)).lon, 1);
  376. Level2.Add(item);
  377. }
  378. catch (Exception ex)
  379. {
  380. item.Lon = -999;
  381. LogUI.Error($"[{item.TwoLine}]推算XYZ星历出错!", ex).Wait(5000);
  382. }
  383. }
  384. if (Level2.Any())
  385. {
  386. using (MySqlContext db = new MySqlContext())
  387. {
  388. db.XlInfos.AddOrUpdate(Level2.ToArray());
  389. db.SaveChanges();
  390. }
  391. }
  392. });
  393. await Task.Delay(2000);
  394. }
  395. else
  396. {
  397. await Task.Delay(60 * 1000);
  398. }
  399. }
  400. catch (Exception ex)
  401. {
  402. LogUI.Error($"推算XYZ星历出错!", ex).Wait(5000);
  403. }
  404. finally
  405. {
  406. await Task.Delay(5000);
  407. }
  408. }
  409. }
  410. //清理10分钟之前的文件
  411. private async Task ClearLocalFile()
  412. {
  413. while (true)
  414. {
  415. try
  416. {
  417. var uploadFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot");
  418. var files = Directory.EnumerateFiles(uploadFolder);
  419. foreach (var file in files)
  420. {
  421. FileInfo info = new FileInfo(file);
  422. if (info.CreationTime < DateTime.Now.AddMinutes(-10))
  423. {
  424. try
  425. {
  426. info.Delete();
  427. }
  428. catch
  429. {
  430. }
  431. }
  432. }
  433. }
  434. catch (Exception ex)
  435. {
  436. await LogUI.Error("清理wwwroot历史文件异常", ex);
  437. }
  438. await Task.Delay(60 * 1000);
  439. }
  440. }
  441. private async Task ClearLog()
  442. {
  443. while (true)
  444. {
  445. using (MySqlContext db = new MySqlContext())
  446. {
  447. try
  448. {
  449. var time1 = DateTime.Today.AddDays(-7);
  450. var time2 = DateTime.Today.AddDays(-30);
  451. var delItems = await db.LogRes.Where(p => p.LogTime < time1 && p.LogType != Entity.EnumLogType.Error).Take(500).ToListAsync();
  452. db.LogRes.RemoveRange(delItems);
  453. var delItems2 = await db.LogRes.Where(p => p.LogTime < time2 && p.LogType == Entity.EnumLogType.Error).Take(500).ToListAsync();
  454. db.LogRes.RemoveRange(delItems2);
  455. await db.SaveChangesAsync();
  456. if (!delItems.Any() && !delItems2.Any())
  457. {
  458. break;
  459. }
  460. }
  461. catch (Exception ex)
  462. {
  463. await LogUI.Error("清理日志信息异常", ex);
  464. await Task.Delay(10000);
  465. }
  466. finally
  467. {
  468. await Task.Delay(5000);
  469. }
  470. }
  471. }
  472. }
  473. private void btn_ItemClick(object sender, ItemClickEventArgs e)
  474. {
  475. this.tablePanel1.Visible = false;
  476. var btnTxt = e?.Item?.Caption?.Trim() ?? "任务管理";
  477. BaseDocument doc = null;
  478. doc = tabbedView1.Documents.Find(p => p.Control.GetType() == ctrlTypes[btnTxt]).FirstOrDefault();
  479. if (doc == null)
  480. {
  481. doc = tabbedView1.AddDocument((Control)Activator.CreateInstance(ctrlTypes[btnTxt]), btnTxt);
  482. if (doc.Control is Form form)
  483. {
  484. form.Text = "";
  485. doc.Caption = btnTxt;
  486. }
  487. if (btnTxt == "任务管理")
  488. doc.Properties.AllowClose = DevExpress.Utils.DefaultBoolean.False;
  489. else
  490. doc.Properties.AllowClose = DevExpress.Utils.DefaultBoolean.True;
  491. }
  492. tabbedView1.ActivateDocument(doc.Control);
  493. }
  494. protected override void OnFormClosing(FormClosingEventArgs e)
  495. {
  496. if (e.CloseReason == CloseReason.UserClosing)
  497. {
  498. if (!DxHelper.MsgBoxHelper.ShowConfirm("确定要退出当前系统吗?"))
  499. {
  500. e.Cancel = true;
  501. return;
  502. }
  503. }
  504. KillProcess();
  505. Application.Exit();
  506. }
  507. private void btnOpenApi_ItemClick(object sender, ItemClickEventArgs e)
  508. {
  509. if (SysConfig.Config == null)
  510. {
  511. DxHelper.MsgBoxHelper.ShowWarning($"请在系统设置中配置基础信息");
  512. return;
  513. }
  514. string addr = $"http://{IpHelper.GetLocalIp()}:{SysConfig.Config.HttpPort}/swagger";
  515. try
  516. {
  517. System.Diagnostics.Process.Start(addr);
  518. }
  519. catch
  520. {
  521. DxHelper.MsgBoxHelper.ShowError($"无法打开默认浏览器,请手动打开浏览器查看接口文档.地址{addr}");
  522. }
  523. }
  524. private void StartProcess()
  525. {
  526. Task.Run(() =>
  527. {
  528. KillProcess();
  529. Process pro = new Process();
  530. var servicesDir = Directory.GetDirectories(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Service\\"), "*", SearchOption.TopDirectoryOnly);
  531. foreach (var item in servicesDir)
  532. {
  533. try
  534. {
  535. string exeName = Path.GetFileNameWithoutExtension(item);
  536. string exeFile = $"{item}\\{exeName}.exe";
  537. pro.StartInfo.FileName = exeFile;
  538. pro.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  539. pro.StartInfo.Arguments = $"http://127.0.0.1:{SysConfig.Config.HttpPort}";
  540. pro.Start();
  541. }
  542. catch (Exception ex)
  543. {
  544. XdCxRhDW.Framework.LogHelper.Error($"启动【{item}】中的服务异常", ex);
  545. DxHelper.MsgBoxHelper.ShowError($"启动【{item}】中的服务异常");
  546. }
  547. }
  548. });
  549. }
  550. private void KillProcess()
  551. {
  552. try
  553. {
  554. List<Process> list = new List<Process>();
  555. var servicesDir = Directory.GetDirectories(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Service\\"), "*", SearchOption.TopDirectoryOnly);
  556. foreach (var item in servicesDir)
  557. {
  558. string exeName = Path.GetFileNameWithoutExtension(item);
  559. list.AddRange(Process.GetProcessesByName(exeName));
  560. }
  561. foreach (var item in list)
  562. {
  563. try
  564. {
  565. item.Kill();
  566. }
  567. catch
  568. {
  569. }
  570. }
  571. }
  572. catch
  573. { }
  574. }
  575. }
  576. }