MainForm.cs 20 KB

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