MainForm.cs 23 KB

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