MainForm.cs 16 KB

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