MainForm.cs 19 KB

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