MainForm.cs 23 KB

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