MainForm.cs 17 KB

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