MainForm.cs 17 KB

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