MainForm.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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 (Exception ex)
  255. {
  256. await App.LogHelper.Error($"{file}导入完成后移动到备份目录失败",ex);
  257. }
  258. }
  259. else
  260. {
  261. LogUI.Error($"星历文件[{file}]自动导入失败.{res.msg}").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(Exception ex)
  271. {
  272. await App.LogHelper.Error($"{file}导入失败后移动到备份目录失败",ex);
  273. }
  274. }
  275. }
  276. catch (Exception ex)
  277. {
  278. LogUI.Error($"星历文件[{file}]自动导入失败", ex).Wait(5000);
  279. try
  280. {
  281. //导入完成的文件放在备份目录
  282. var newFile = Path.Combine(backupFailed, Path.GetFileName(file));
  283. if (File.Exists(newFile))
  284. File.Delete(newFile);
  285. File.Move(file, newFile);
  286. }
  287. catch(Exception ex2)
  288. {
  289. await App.LogHelper.Error($"{file}导入失败后移动到备份目录失败", ex2);
  290. }
  291. await Task.Delay(5000);
  292. }
  293. finally
  294. {
  295. await Task.Delay(2000);
  296. }
  297. }
  298. }
  299. }
  300. //清理1年之前导入的星历
  301. private async Task XlClear()
  302. {
  303. while (true)
  304. {
  305. try
  306. {
  307. List<XlInfo> clearData = new List<XlInfo>();
  308. using (MySqlContext db = new MySqlContext())
  309. {
  310. DateTime dt = DateTime.Now.AddYears(-1);
  311. clearData = await db.XlInfos.Where(p => p.UpdateTime < dt).Take(1000).ToListAsync();
  312. if (clearData.Any())
  313. {
  314. db.XlInfos.RemoveRange(clearData);
  315. await db.SaveChangesAsync();
  316. }
  317. }
  318. if (!clearData.Any())
  319. {
  320. await Task.Delay(60 * 1000);
  321. }
  322. }
  323. catch (Exception ex)
  324. {
  325. await LogUI.Error("清理过期星历异常", ex);
  326. }
  327. finally
  328. {
  329. await Task.Delay(2000);
  330. }
  331. }
  332. }
  333. //计算星历的轨道经度
  334. private async Task XlLonCalc()
  335. {
  336. while (true)
  337. {
  338. try
  339. {
  340. List<XlInfo> calcItems = null;
  341. List<SatInfo> satInfo = null;
  342. using (MySqlContext db = new MySqlContext())
  343. {
  344. calcItems = await db.XlInfos.Where(p => p.Lon == null).OrderByDescending(p => p.SatCode).Take(100).ToListAsync();
  345. satInfo = await db.SatInfos.ToListAsync();
  346. }
  347. if (calcItems != null && calcItems.Any())
  348. {
  349. var firstUpdateItems = calcItems.Where(p => satInfo.Any(t => t.SatCode == p.SatCode)).ToList();
  350. await Task.Run(() =>
  351. {
  352. List<XlInfo> Level1 = new List<XlInfo>();
  353. foreach (var item in firstUpdateItems)
  354. {
  355. try
  356. {
  357. var eph = EphHelper.Calc(item.TwoLine, item.TimeUTC);
  358. item.Lon = Math.Round(PhysicsHelper.EcefToGeo((eph.X, eph.Y, eph.Z)).lon, 1);
  359. Level1.Add(item);
  360. calcItems.Remove(item);
  361. }
  362. catch (Exception ex)
  363. {
  364. item.Lon = -999;
  365. LogUI.Error($"[{item.TwoLine}]推算XYZ星历出错!", ex).Wait(5000);
  366. }
  367. }
  368. if (Level1.Any())
  369. {
  370. using (MySqlContext db = new MySqlContext())
  371. {
  372. db.XlInfos.AddOrUpdate(Level1.ToArray());
  373. db.SaveChanges();
  374. }
  375. }
  376. List<XlInfo> Level2 = new List<XlInfo>();
  377. foreach (var item in calcItems)
  378. {
  379. try
  380. {
  381. var eph = EphHelper.Calc(item.TwoLine, item.TimeUTC);
  382. item.Lon = Math.Round(PhysicsHelper.EcefToGeo((eph.X, eph.Y, eph.Z)).lon, 1);
  383. Level2.Add(item);
  384. }
  385. catch (Exception ex)
  386. {
  387. item.Lon = -999;
  388. LogUI.Error($"[{item.TwoLine}]推算XYZ星历出错!", ex).Wait(5000);
  389. }
  390. }
  391. if (Level2.Any())
  392. {
  393. using (MySqlContext db = new MySqlContext())
  394. {
  395. db.XlInfos.AddOrUpdate(Level2.ToArray());
  396. db.SaveChanges();
  397. }
  398. }
  399. });
  400. await Task.Delay(2000);
  401. }
  402. else
  403. {
  404. await Task.Delay(60 * 1000);
  405. }
  406. }
  407. catch (Exception ex)
  408. {
  409. LogUI.Error($"推算XYZ星历出错!", ex).Wait(5000);
  410. }
  411. finally
  412. {
  413. await Task.Delay(5000);
  414. }
  415. }
  416. }
  417. //清理10分钟之前的文件
  418. private async Task ClearLocalFile()
  419. {
  420. while (true)
  421. {
  422. try
  423. {
  424. var uploadFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot");
  425. var files = Directory.EnumerateFiles(uploadFolder);
  426. foreach (var file in files)
  427. {
  428. FileInfo info = new FileInfo(file);
  429. if (info.CreationTime < DateTime.Now.AddMinutes(-10))
  430. {
  431. try
  432. {
  433. info.Delete();
  434. }
  435. catch
  436. {
  437. }
  438. }
  439. }
  440. }
  441. catch (Exception ex)
  442. {
  443. await LogUI.Error("清理wwwroot历史文件异常", ex);
  444. }
  445. await Task.Delay(60 * 1000);
  446. }
  447. }
  448. private async Task ClearLog()
  449. {
  450. while (true)
  451. {
  452. using (MySqlContext db = new MySqlContext())
  453. {
  454. try
  455. {
  456. var time1 = DateTime.Today.AddDays(-7);
  457. var time2 = DateTime.Today.AddDays(-30);
  458. var delItems = await db.LogRes.Where(p => p.LogTime < time1 && p.LogType != Entity.EnumLogType.Error).Take(500).ToListAsync();
  459. db.LogRes.RemoveRange(delItems);
  460. var delItems2 = await db.LogRes.Where(p => p.LogTime < time2 && p.LogType == Entity.EnumLogType.Error).Take(500).ToListAsync();
  461. db.LogRes.RemoveRange(delItems2);
  462. await db.SaveChangesAsync();
  463. if (!delItems.Any() && !delItems2.Any())
  464. {
  465. break;
  466. }
  467. }
  468. catch (Exception ex)
  469. {
  470. await LogUI.Error("清理日志信息异常", ex);
  471. await Task.Delay(10000);
  472. }
  473. finally
  474. {
  475. await Task.Delay(5000);
  476. }
  477. }
  478. }
  479. }
  480. private void btn_ItemClick(object sender, ItemClickEventArgs e)
  481. {
  482. this.tablePanel1.Visible = false;
  483. var btnTxt = e?.Item?.Caption?.Trim() ?? "任务管理";
  484. BaseDocument doc = null;
  485. doc = tabbedView1.Documents.Find(p => p.Control.GetType() == ctrlTypes[btnTxt]).FirstOrDefault();
  486. if (doc == null)
  487. {
  488. doc = tabbedView1.AddDocument((Control)Activator.CreateInstance(ctrlTypes[btnTxt]), btnTxt);
  489. if (doc.Control is Form form)
  490. {
  491. form.Text = "";
  492. doc.Caption = btnTxt;
  493. }
  494. if (btnTxt == "任务管理")
  495. doc.Properties.AllowClose = DevExpress.Utils.DefaultBoolean.False;
  496. else
  497. doc.Properties.AllowClose = DevExpress.Utils.DefaultBoolean.True;
  498. }
  499. tabbedView1.ActivateDocument(doc.Control);
  500. }
  501. protected override void OnFormClosing(FormClosingEventArgs e)
  502. {
  503. if (e.CloseReason == CloseReason.UserClosing)
  504. {
  505. if (!DxHelper.MsgBoxHelper.ShowConfirm("确定要退出当前系统吗?"))
  506. {
  507. e.Cancel = true;
  508. return;
  509. }
  510. }
  511. KillProcess();
  512. Application.Exit();
  513. }
  514. private void btnOpenApi_ItemClick(object sender, ItemClickEventArgs e)
  515. {
  516. if (SysConfig.Config == null)
  517. {
  518. DxHelper.MsgBoxHelper.ShowWarning($"请在系统设置中配置基础信息");
  519. return;
  520. }
  521. string addr = $"http://{IpHelper.GetLocalIp()}:{SysConfig.Config.HttpPort}/swagger";
  522. try
  523. {
  524. System.Diagnostics.Process.Start(addr);
  525. }
  526. catch
  527. {
  528. DxHelper.MsgBoxHelper.ShowError($"无法打开默认浏览器,请手动打开浏览器查看接口文档.地址{addr}");
  529. }
  530. }
  531. private void StartProcess()
  532. {
  533. Task.Run(() =>
  534. {
  535. KillProcess();
  536. Process pro = new Process();
  537. var servicesDir = Directory.GetDirectories(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Service\\"), "*", SearchOption.TopDirectoryOnly);
  538. foreach (var item in servicesDir)
  539. {
  540. try
  541. {
  542. string exeName = Path.GetFileNameWithoutExtension(item);
  543. string exeFile = $"{item}\\{exeName}.exe";
  544. pro.StartInfo.FileName = exeFile;
  545. pro.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  546. pro.StartInfo.Arguments = $"http://127.0.0.1:{SysConfig.Config.HttpPort}";
  547. pro.Start();
  548. }
  549. catch (Exception ex)
  550. {
  551. XdCxRhDW.Framework.LogHelper.Error($"启动【{item}】中的服务异常", ex);
  552. DxHelper.MsgBoxHelper.ShowError($"启动【{item}】中的服务异常");
  553. }
  554. }
  555. });
  556. }
  557. private void KillProcess()
  558. {
  559. try
  560. {
  561. List<Process> list = new List<Process>();
  562. var servicesDir = Directory.GetDirectories(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Service\\"), "*", SearchOption.TopDirectoryOnly);
  563. foreach (var item in servicesDir)
  564. {
  565. string exeName = Path.GetFileNameWithoutExtension(item);
  566. list.AddRange(Process.GetProcessesByName(exeName));
  567. }
  568. foreach (var item in list)
  569. {
  570. try
  571. {
  572. item.Kill();
  573. }
  574. catch
  575. {
  576. }
  577. }
  578. }
  579. catch
  580. { }
  581. }
  582. }
  583. }