MainForm.cs 17 KB

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