MainForm.cs 21 KB

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