MainForm.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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(CtrlXl));
  52. ctrlTypes.Add("卫星管理", typeof(CtrlSat));
  53. ctrlTypes.Add("天线管理", typeof(CtrlTx));
  54. ctrlTypes.Add("信号管理", typeof(CtrlSignal));
  55. ctrlTypes.Add("目标管理", typeof(CtrlTarget));
  56. ctrlTypes.Add("系统设置", typeof(CtrlSysSettings));
  57. ctrlTypes.Add("变采样", typeof(ResampleForm));
  58. ctrlTypes.Add("GPU参估", typeof(GpuCalcForm));
  59. ctrlTypes.Add("检测参估", typeof(DetectToolForm));
  60. ctrlTypes.Add("星历推算", typeof(XlCalculateForm));
  61. ctrlTypes.Add("信号仿真", typeof(SignalEmulation));
  62. ctrlTypes.Add("服务状态", typeof(CtrlSvrs));
  63. ctrlTypes.Add("服务日志", typeof(CtrlSvrLog));
  64. using (RHDWLogContext db = new RHDWLogContext())
  65. {
  66. var qq = db.LogRes.ToList();
  67. }
  68. using (RHDWContext db = new RHDWContext())
  69. {
  70. SysConfig.Config = db.SysSetings.FirstOrDefault();
  71. }
  72. if (SysConfig.Config != null)
  73. {
  74. StartWebApi();
  75. }
  76. btn_ItemClick(null, null);
  77. ServerContext.Instance.Init();
  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. Serilog.Log.Information($"星历文件[{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. Serilog.Log.Information($"星历文件[{file}]自动导入失败.{res.msg}");
  191. }
  192. }
  193. catch (Exception ex)
  194. {
  195. Serilog.Log.Error(ex, $"星历文件[{file}]自动导入失败");
  196. }
  197. }
  198. }
  199. }
  200. //清理180天之前导入的星历
  201. private async Task XlClear()
  202. {
  203. while (true)
  204. {
  205. try
  206. {
  207. using (RHDWContext db = new RHDWContext())
  208. {
  209. DateTime dt = DateTime.Now.AddDays(-180);
  210. var clearData = await db.XlInfos.Where(p => p.UpdateTime < dt).ToListAsync();
  211. if (clearData.Any())
  212. {
  213. db.XlInfos.RemoveRange(clearData);
  214. await db.SaveChangesAsync();
  215. }
  216. }
  217. }
  218. catch (Exception ex)
  219. {
  220. await LogHelper.Error("清理过期星历异常", ex);
  221. }
  222. await Task.Delay(3600 * 1000);
  223. }
  224. }
  225. //计算星历的轨道经度
  226. private async Task XlLonCalc()
  227. {
  228. while (true)
  229. {
  230. try
  231. {
  232. using (RHDWContext db = new RHDWContext())
  233. {
  234. var calcItems = await db.XlInfos.Where(p => p.Lon == null).OrderByDescending(p => p.SatCode).ToListAsync();
  235. if (calcItems.Any())
  236. {
  237. var satInfo = await db.SatInfos.ToListAsync();
  238. var firstUpdateItems = calcItems.Where(p => satInfo.Any(t => t.SatCode == p.SatCode)).ToList();
  239. await Task.Run(() =>
  240. {
  241. foreach (var item in firstUpdateItems)
  242. {
  243. try
  244. {
  245. var eph = EphHelper.Calc(item.TwoLine, item.TimeUTC);
  246. item.Lon = Math.Round(PhysicsHelper.EcefToGeo((eph.X, eph.Y, eph.Z)).lon, 1);
  247. }
  248. catch (Exception ex)
  249. {
  250. item.Lon = -999;
  251. LogHelper.Error($"[{item.TwoLine}]推算XYZ星历出错!", ex).Wait(5000);
  252. }
  253. db.XlInfos.AddOrUpdate(item);
  254. db.SaveChangesAsync();
  255. calcItems.Remove(item);
  256. }
  257. foreach (var item in calcItems)
  258. {
  259. try
  260. {
  261. var eph = EphHelper.Calc(item.TwoLine, item.TimeUTC);
  262. item.Lon = Math.Round(PhysicsHelper.EcefToGeo((eph.X, eph.Y, eph.Z)).lon, 1);
  263. }
  264. catch (Exception ex)
  265. {
  266. item.Lon = -999;
  267. LogHelper.Error($"[{item.TwoLine}]推算XYZ星历出错!", ex).Wait(5000);
  268. }
  269. db.XlInfos.AddOrUpdate(item);
  270. db.SaveChangesAsync();
  271. }
  272. });
  273. }
  274. }
  275. }
  276. catch (Exception ex)
  277. {
  278. LogHelper.Error($"推算XYZ星历出错!", ex).Wait(5000);
  279. }
  280. await Task.Delay(60 * 1000);
  281. }
  282. }
  283. private async Task Rpt()
  284. {
  285. var dto = new SvrStateReportDto()
  286. {
  287. DevId = ConfigurationManager.AppSettings["DevID"].Trim(),
  288. SvrType = EnumSvrType.PosPlatform,
  289. ModuleType = EnumModuleType.Soft,
  290. ModuleState = EnumModuleState.正常,
  291. };
  292. AutofacUtil.GetService<FileWriterService>().WriteStateRes(dto);
  293. await Task.Run(async () =>
  294. {
  295. while (true)
  296. {
  297. try
  298. {
  299. var pro = Process.GetCurrentProcess();
  300. if ((pro.PrivateMemorySize64 >> 20) > 8192)//程序内存大于8个GB
  301. {
  302. var dto2 = new SvrStateReportDto()
  303. {
  304. DevId = ConfigurationManager.AppSettings["DevID"].Trim(),
  305. SvrType = EnumSvrType.PosPlatform,
  306. ModuleType = EnumModuleType.Memory,
  307. ModuleState = EnumModuleState.Error,
  308. };
  309. AutofacUtil.GetService<FileWriterService>().WriteStateRes(dto2);
  310. }
  311. }
  312. catch (Exception ex)
  313. {
  314. LogHelper.Error("端口状态上报异常", ex).Wait(5000);
  315. }
  316. await Task.Delay(10000);
  317. }
  318. });
  319. }
  320. //清理10分钟之前的文件
  321. private async Task ClearLocalFile()
  322. {
  323. while (true)
  324. {
  325. try
  326. {
  327. var uploadFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot");
  328. var files = Directory.EnumerateFiles(uploadFolder);
  329. foreach (var file in files)
  330. {
  331. FileInfo info = new FileInfo(file);
  332. if (info.CreationTime < DateTime.Now.AddMinutes(-10))
  333. {
  334. try
  335. {
  336. info.Delete();
  337. }
  338. catch
  339. {
  340. }
  341. }
  342. }
  343. }
  344. catch (Exception ex)
  345. {
  346. await LogHelper.Error("清理wwwroot历史文件异常", ex);
  347. }
  348. await Task.Delay(60 * 1000);
  349. }
  350. }
  351. private async Task ClearLog()
  352. {
  353. using (RHDWLogContext db = new RHDWLogContext())
  354. {
  355. try
  356. {
  357. var time1 = DateTime.Today.AddDays(-7);
  358. var time2 = DateTime.Today.AddDays(-30);
  359. var delItems = await db.LogRes.Where(p => p.LogTime < time1 && p.LogType != EnumLogType.Error).ToListAsync();
  360. db.LogRes.RemoveRange(delItems);
  361. var delItems2 = await db.LogRes.Where(p => p.LogTime < time2 && p.LogType == EnumLogType.Error).ToListAsync();
  362. db.LogRes.RemoveRange(delItems2);
  363. await db.SaveChangesAsync();
  364. }
  365. catch (Exception ex)
  366. {
  367. Serilog.Log.Error(ex, "清理日志信息异常!");
  368. }
  369. }
  370. await Task.Delay(3600 * 1000);
  371. }
  372. private void btn_ItemClick(object sender, ItemClickEventArgs e)
  373. {
  374. var btnTxt = e?.Item?.Caption?.Trim() ?? "任务管理";
  375. BaseDocument doc = null;
  376. doc = tabbedView1.Documents.Find(p => p.Control.GetType() == ctrlTypes[btnTxt]).FirstOrDefault();
  377. if (doc == null)
  378. {
  379. doc = tabbedView1.AddDocument((Control)Activator.CreateInstance(ctrlTypes[btnTxt]), btnTxt);
  380. if (doc.Control is Form form)
  381. {
  382. form.Text = "";
  383. doc.Caption = btnTxt;
  384. }
  385. if (btnTxt == "任务管理")
  386. doc.Properties.AllowClose = DevExpress.Utils.DefaultBoolean.False;
  387. else
  388. doc.Properties.AllowClose = DevExpress.Utils.DefaultBoolean.True;
  389. }
  390. tabbedView1.ActivateDocument(doc.Control);
  391. }
  392. protected override void OnFormClosing(FormClosingEventArgs e)
  393. {
  394. if (e.CloseReason == CloseReason.UserClosing)
  395. {
  396. if (!DxHelper.MsgBoxHelper.ShowConfirm("确定要退出当前系统吗?"))
  397. {
  398. e.Cancel = true;
  399. return;
  400. }
  401. }
  402. AutofacUtil.GetService<FileWriterService>().WriteStateRes(new SvrStateReportDto()
  403. {
  404. SvrType = EnumSvrType.PosPlatform,
  405. DevId = ConfigurationManager.AppSettings["DevID"].Trim(),
  406. ModuleType = EnumModuleType.Soft,
  407. ModuleState = EnumModuleState.Error,
  408. });
  409. KillProcess();
  410. Application.Exit();
  411. }
  412. private void btnOpenApi_ItemClick(object sender, ItemClickEventArgs e)
  413. {
  414. using (RHDWContext db = new RHDWContext())
  415. {
  416. if (SysConfig.Config == null)
  417. {
  418. DxHelper.MsgBoxHelper.ShowWarning($"请在系统设置中配置基础信息");
  419. return;
  420. }
  421. string addr = $"http://{IpHelper.GetLocalIp()}:{SysConfig.Config.HttpPort}/swagger";
  422. try
  423. {
  424. System.Diagnostics.Process.Start(addr);
  425. }
  426. catch
  427. {
  428. db.Dispose();
  429. DxHelper.MsgBoxHelper.ShowError($"无法打开默认浏览器,请手动打开浏览器查看接口文档.地址{addr}");
  430. }
  431. }
  432. }
  433. private void StartProcess()
  434. {
  435. Task.Run(() =>
  436. {
  437. KillProcess();
  438. Process pro = new Process();
  439. var servicesDir = Directory.GetDirectories(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Service\\"), "*", SearchOption.TopDirectoryOnly);
  440. foreach (var item in servicesDir)
  441. {
  442. try
  443. {
  444. string exeName = Path.GetFileNameWithoutExtension(item);
  445. string exeFile = $"{item}\\{exeName}.exe";
  446. pro.StartInfo.FileName = exeFile;
  447. pro.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  448. pro.StartInfo.Arguments = $"http://127.0.0.1:{SysConfig.Config.HttpPort}";
  449. pro.Start();
  450. }
  451. catch (Exception ex)
  452. {
  453. Serilog.Log.Error(ex, $"启动【{item}】中的服务异常");
  454. DxHelper.MsgBoxHelper.ShowError($"启动【{item}】中的服务异常");
  455. }
  456. }
  457. });
  458. }
  459. private void KillProcess()
  460. {
  461. try
  462. {
  463. List<Process> list = new List<Process>();
  464. var servicesDir = Directory.GetDirectories(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Service\\"), "*", SearchOption.TopDirectoryOnly);
  465. foreach (var item in servicesDir)
  466. {
  467. string exeName = Path.GetFileNameWithoutExtension(item);
  468. list.AddRange(Process.GetProcessesByName(exeName));
  469. }
  470. foreach (var item in list)
  471. {
  472. try
  473. {
  474. item.Kill();
  475. }
  476. catch
  477. {
  478. }
  479. }
  480. }
  481. catch
  482. { }
  483. }
  484. }
  485. }