MainForm.cs 23 KB

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