MainForm.cs 23 KB

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