MainForm.cs 18 KB

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