DiagnosticForm.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  1. using System;
  2. using System.Diagnostics;
  3. using System.Drawing;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Windows.Forms;
  9. using BeiJingComService.Core;
  10. using BeiJingComService.Infrastructure;
  11. using BeiJingComService.Protocols;
  12. namespace BeiJingComService.WinForms
  13. {
  14. public partial class DiagnosticForm : Form
  15. {
  16. private readonly ITransportProtocol[] _protocols;
  17. private TabControl _tabControl;
  18. // 调用测试
  19. private TabPage _tabInvoke;
  20. private Label _lblStatus;
  21. private Label _lblFunc;
  22. private TextBox _txtFunc;
  23. private Label _lblArgs;
  24. private TextBox _txtArgs;
  25. private Label _lblCardInput;
  26. private TextBox _txtCardInput;
  27. private Button _btnReadCard, _btnInvoke, _btnRestart, _btnClear;
  28. private TextBox _txtResult;
  29. // 运行状态
  30. private TabPage _tabStatus;
  31. private ListView _lvStatus;
  32. private Button _btnRefreshStatus;
  33. // 配置
  34. private TabPage _tabConfig;
  35. private ListView _lvConfig;
  36. private Button _btnRefreshConfig;
  37. // 日志
  38. private TabPage _tabLog;
  39. private ComboBox _cmbLogFile;
  40. private TextBox _txtLog;
  41. private Button _btnRefreshLog, _btnOpenLogDir;
  42. // 读卡测试
  43. private TabPage _tabCardCache;
  44. private TextBox _txtCacheCardInput;
  45. private ComboBox _cmbCacheCardClass;
  46. private CheckBox _chkKeepOpen;
  47. private Button _btnFullRead, _btnCacheRead, _btnCompare, _btnClearResult;
  48. private TextBox _txtCacheResult;
  49. public DiagnosticForm(ITransportProtocol[] protocols)
  50. {
  51. _protocols = protocols;
  52. InitializeComponent();
  53. this.Text = "北京本地 COM 通讯服务 · 诊断面板";
  54. this.StartPosition = FormStartPosition.CenterScreen;
  55. this.FormClosing += (s, e) => { e.Cancel = true; this.Hide(); };
  56. RefreshStatus();
  57. RefreshConfig();
  58. LoadLog();
  59. }
  60. private void InitializeComponent()
  61. {
  62. this.SuspendLayout();
  63. _tabControl = new TabControl { Dock = DockStyle.Fill };
  64. // ===== 调用测试 =====
  65. _tabInvoke = new TabPage { Text = "调用测试", Padding = new Padding(10) };
  66. _lblStatus = new Label
  67. {
  68. Text = "网关状态: 检测中...",
  69. AutoSize = true,
  70. Location = new Point(12, 12),
  71. Font = new Font("Microsoft YaHei", 10, FontStyle.Bold)
  72. };
  73. _lblFunc = new Label { Text = "方法(func):", AutoSize = true, Location = new Point(12, 46) };
  74. _txtFunc = new TextBox
  75. {
  76. Location = new Point(110, 43),
  77. Size = new Size(240, 24),
  78. Text = "open"
  79. };
  80. var lblFuncHint = new Label
  81. {
  82. Text = "如 open / close / ReadCardObj / BussniessObj / Trade / TradeAll",
  83. AutoSize = true,
  84. ForeColor = Color.Gray,
  85. Location = new Point(362, 46)
  86. };
  87. _lblArgs = new Label { Text = "参数(args,每行一个):", AutoSize = true, Location = new Point(12, 78) };
  88. _txtArgs = new TextBox
  89. {
  90. Location = new Point(12, 102),
  91. Size = new Size(730, 76),
  92. Multiline = true,
  93. ScrollBars = ScrollBars.Both,
  94. AcceptsReturn = true,
  95. WordWrap = false,
  96. Font = new Font("Consolas", 9),
  97. BackColor = Color.White
  98. };
  99. _lblCardInput = new Label { Text = "读卡入参(input,单行 XML):", AutoSize = true, Location = new Point(12, 186) };
  100. _txtCardInput = new TextBox
  101. {
  102. Location = new Point(12, 208),
  103. Size = new Size(730, 56),
  104. Multiline = true,
  105. ScrollBars = ScrollBars.Horizontal,
  106. AcceptsReturn = false,
  107. WordWrap = false,
  108. Font = new Font("Consolas", 9),
  109. BackColor = Color.White,
  110. Text = "<multiclass>1</multiclass><QRcode></QRcode><businessType>11</businessType><termId>现场MAC(去横线)</termId><termIp>现场IP</termIp><operatorId>工号</operatorId><operatorName>姓名</operatorName><officeId>科室编码</officeId><officeName>科室名</officeName>"
  111. };
  112. _btnReadCard = new Button { Text = "模拟读卡", Location = new Point(12, 272), Size = new Size(110, 32), FlatStyle = FlatStyle.System };
  113. _btnInvoke = new Button { Text = "调用", Location = new Point(130, 272), Size = new Size(110, 32), FlatStyle = FlatStyle.System };
  114. _btnRestart = new Button { Text = "重启网关", Location = new Point(248, 272), Size = new Size(110, 32), FlatStyle = FlatStyle.System };
  115. _btnClear = new Button { Text = "清空结果", Location = new Point(366, 272), Size = new Size(110, 32), FlatStyle = FlatStyle.System };
  116. _txtResult = new TextBox
  117. {
  118. Location = new Point(12, 314),
  119. Size = new Size(730, 170),
  120. Multiline = true,
  121. ReadOnly = true,
  122. ScrollBars = ScrollBars.Both,
  123. WordWrap = false,
  124. BackColor = Color.White,
  125. Font = new Font("Consolas", 9)
  126. };
  127. _btnReadCard.Click += async (s, e) => await OnReadCard();
  128. _btnInvoke.Click += async (s, e) => await OnInvoke();
  129. _btnRestart.Click += (s, e) => OnRestart();
  130. _btnClear.Click += (s, e) => _txtResult.Clear();
  131. _tabInvoke.Controls.AddRange(new Control[] {
  132. _lblStatus, _lblFunc, _txtFunc, lblFuncHint, _lblArgs, _txtArgs,
  133. _lblCardInput, _txtCardInput,
  134. _btnReadCard, _btnInvoke, _btnRestart, _btnClear, _txtResult
  135. });
  136. // ===== 运行状态 =====
  137. _tabStatus = new TabPage { Text = "运行状态", Padding = new Padding(10) };
  138. _lvStatus = new ListView
  139. {
  140. Location = new Point(12, 12),
  141. Size = new Size(730, 420),
  142. View = View.Details,
  143. FullRowSelect = true,
  144. GridLines = true,
  145. HeaderStyle = ColumnHeaderStyle.Nonclickable
  146. };
  147. _lvStatus.Columns.Add("项目", 200);
  148. _lvStatus.Columns.Add("值", 510);
  149. _btnRefreshStatus = new Button { Text = "刷新", Location = new Point(12, 442), Size = new Size(90, 30), FlatStyle = FlatStyle.System };
  150. _btnRefreshStatus.Click += (s, e) => RefreshStatus();
  151. _tabStatus.Controls.AddRange(new Control[] { _lvStatus, _btnRefreshStatus });
  152. // ===== 配置 =====
  153. _tabConfig = new TabPage { Text = "配置信息", Padding = new Padding(10) };
  154. _lvConfig = new ListView
  155. {
  156. Location = new Point(12, 12),
  157. Size = new Size(730, 420),
  158. View = View.Details,
  159. FullRowSelect = true,
  160. GridLines = true,
  161. HeaderStyle = ColumnHeaderStyle.Nonclickable
  162. };
  163. _lvConfig.Columns.Add("配置项", 200);
  164. _lvConfig.Columns.Add("值", 510);
  165. _btnRefreshConfig = new Button { Text = "刷新", Location = new Point(12, 442), Size = new Size(90, 30), FlatStyle = FlatStyle.System };
  166. _btnRefreshConfig.Click += (s, e) => RefreshConfig();
  167. _tabConfig.Controls.AddRange(new Control[] { _lvConfig, _btnRefreshConfig });
  168. // ===== 日志 =====
  169. _tabLog = new TabPage { Text = "日志查看", Padding = new Padding(10) };
  170. _cmbLogFile = new ComboBox
  171. {
  172. Location = new Point(12, 12),
  173. Size = new Size(260, 24),
  174. DropDownStyle = ComboBoxStyle.DropDownList
  175. };
  176. _cmbLogFile.Items.Add(new LogFileItem("运行日志 _Gateway.log", () => Logger.TodayLogFilePath));
  177. _cmbLogFile.Items.Add(new LogFileItem("调用原文 _Trade.log", () => TradeLogger.TodayTradeLogFilePath));
  178. _cmbLogFile.SelectedIndex = 0;
  179. _cmbLogFile.SelectedIndexChanged += (s, e) => LoadLog();
  180. _txtLog = new TextBox
  181. {
  182. Location = new Point(12, 44),
  183. Size = new Size(730, 388),
  184. Multiline = true,
  185. ReadOnly = true,
  186. ScrollBars = ScrollBars.Both,
  187. WordWrap = false,
  188. BackColor = Color.White,
  189. Font = new Font("Consolas", 9)
  190. };
  191. _btnRefreshLog = new Button { Text = "刷新日志", Location = new Point(12, 442), Size = new Size(100, 30), FlatStyle = FlatStyle.System };
  192. _btnOpenLogDir = new Button { Text = "打开日志目录", Location = new Point(120, 442), Size = new Size(120, 30), FlatStyle = FlatStyle.System };
  193. _btnRefreshLog.Click += (s, e) => LoadLog();
  194. _btnOpenLogDir.Click += (s, e) => OpenLogDir();
  195. _tabLog.Controls.AddRange(new Control[] { _cmbLogFile, _txtLog, _btnRefreshLog, _btnOpenLogDir });
  196. // ===== 读卡测试 =====
  197. _tabCardCache = new TabPage { Text = "读卡测试", Padding = new Padding(10) };
  198. var lblCacheInput = new Label { Text = "读卡入参(input,单行 XML):", AutoSize = true, Location = new Point(12, 12) };
  199. _txtCacheCardInput = new TextBox
  200. {
  201. Location = new Point(12, 34),
  202. Size = new Size(730, 56),
  203. Multiline = true,
  204. ScrollBars = ScrollBars.Horizontal,
  205. AcceptsReturn = false,
  206. WordWrap = false,
  207. Font = new Font("Consolas", 9),
  208. BackColor = Color.White,
  209. Text = "<multiclass>1</multiclass><QRcode></QRcode><businessType>11</businessType><termId>现场MAC(去横线)</termId><termIp>现场IP</termIp><operatorId>工号</operatorId><operatorName>姓名</operatorName><officeId>科室编码</officeId><officeName>科室名</officeName>"
  210. };
  211. var lblCacheCardClass = new Label { Text = "card_class(调用方指定):", AutoSize = true, Location = new Point(12, 100) };
  212. _cmbCacheCardClass = new ComboBox
  213. {
  214. Location = new Point(160, 97),
  215. Size = new Size(120, 24),
  216. DropDownStyle = ComboBoxStyle.DropDownList
  217. };
  218. _cmbCacheCardClass.Items.AddRange(new object[] { "(空,由 COM 判定)", "1 本市", "2 异地" });
  219. _cmbCacheCardClass.SelectedIndex = 0;
  220. _chkKeepOpen = new CheckBox
  221. {
  222. Text = "keepSession(本次不空闲关会话)",
  223. AutoSize = true,
  224. Location = new Point(300, 99)
  225. };
  226. _btnFullRead = new Button { Text = "① 完整读卡", Location = new Point(12, 136), Size = new Size(110, 32), FlatStyle = FlatStyle.System };
  227. _btnCacheRead = new Button { Text = "② 指定类别读卡", Location = new Point(130, 136), Size = new Size(130, 32), FlatStyle = FlatStyle.System };
  228. _btnCompare = new Button { Text = "③ perRead vs keepOpen", Location = new Point(268, 136), Size = new Size(160, 32), FlatStyle = FlatStyle.System };
  229. _btnClearResult = new Button { Text = "清空结果", Location = new Point(436, 136), Size = new Size(100, 32), FlatStyle = FlatStyle.System };
  230. _txtCacheResult = new TextBox
  231. {
  232. Location = new Point(12, 178),
  233. Size = new Size(730, 290),
  234. Multiline = true,
  235. ReadOnly = true,
  236. ScrollBars = ScrollBars.Both,
  237. WordWrap = false,
  238. BackColor = Color.White,
  239. Font = new Font("Consolas", 9)
  240. };
  241. _btnFullRead.Click += async (s, e) => await OnCardCacheRead(false);
  242. _btnCacheRead.Click += async (s, e) => await OnCardCacheRead(true);
  243. _btnCompare.Click += async (s, e) => await OnCardCacheCompare();
  244. _btnClearResult.Click += (s, e) => _txtCacheResult.Clear();
  245. _tabCardCache.Controls.AddRange(new Control[] {
  246. lblCacheInput, _txtCacheCardInput,
  247. lblCacheCardClass, _cmbCacheCardClass, _chkKeepOpen,
  248. _btnFullRead, _btnCacheRead, _btnCompare, _btnClearResult,
  249. _txtCacheResult
  250. });
  251. _tabControl.TabPages.AddRange(new TabPage[] { _tabInvoke, _tabStatus, _tabConfig, _tabLog, _tabCardCache });
  252. this.Controls.Add(_tabControl);
  253. this.ClientSize = new Size(770, 540);
  254. this.MinimumSize = new Size(640, 460);
  255. this.ResumeLayout(false);
  256. }
  257. // ===== 调用测试 =====
  258. private async Task OnInvoke()
  259. {
  260. string func = _txtFunc.Text.Trim();
  261. if (string.IsNullOrEmpty(func))
  262. {
  263. AppendResult("方法(func)为空");
  264. return;
  265. }
  266. string[] args = ParseArgs(_txtArgs.Text);
  267. _btnInvoke.Enabled = false;
  268. AppendResult("--- 调用 COM ---");
  269. try
  270. {
  271. ComResult result = await GatewayHost.Instance.ExecuteAsync(func, args);
  272. AppendResult($"方法: {func}");
  273. AppendResult($"结果码: {result.Code}");
  274. AppendResult($"消息: {result.Message}");
  275. AppendResult($"耗时: {result.ElapsedMs} ms");
  276. AppendResult("返回内容:");
  277. AppendResult(string.IsNullOrEmpty(result.Output) ? "(空)" : result.Output);
  278. RefreshStatus();
  279. }
  280. catch (Exception ex)
  281. {
  282. AppendResult($"异常: {ex.Message}");
  283. Logger.Error("诊断面板调用 COM 异常", ex);
  284. }
  285. finally
  286. {
  287. _btnInvoke.Enabled = true;
  288. }
  289. }
  290. /// <summary>模拟读卡:服务端封装 open→GetPersonClass→GetPersonInfo(Nation),这里一键触发并逐步展示。</summary>
  291. private async Task OnReadCard()
  292. {
  293. string input = _txtCardInput.Text.Trim();
  294. if (string.IsNullOrEmpty(input))
  295. {
  296. AppendResult("读卡入参(input)为空");
  297. return;
  298. }
  299. if (input.IndexOf('\n') >= 0 || input.IndexOf('\r') >= 0)
  300. {
  301. AppendResult("读卡入参必须是单行 XML,请勿换行");
  302. return;
  303. }
  304. _btnReadCard.Enabled = false;
  305. AppendResult("=== 模拟读卡开始 ===");
  306. try
  307. {
  308. string payload = CardReaderFlow.WrapInput(input);
  309. _txtFunc.Text = CardReaderFlow.FuncPersonClass;
  310. _txtArgs.Text = payload + "\r\n" + payload;
  311. CardReadResult result = await CardReaderFlow.ReadAsync(payload);
  312. var steps = result.Steps ?? new CardReadStep[0];
  313. foreach (CardReadStep step in steps)
  314. {
  315. AppendResult($"--- 步骤: {step.Func} ---");
  316. AppendResult($"结果码: {step.Code} 耗时: {step.ElapsedMs} ms");
  317. AppendResult($"消息: {step.Message}");
  318. AppendResult($"返回: {(string.IsNullOrEmpty(step.Output) ? "(空)" : step.Output)}");
  319. }
  320. if (result.FuncName != null)
  321. {
  322. _txtFunc.Text = result.FuncName;
  323. }
  324. if (result.Code == 0)
  325. {
  326. AppendResult($"读卡成功: card_class={result.CardClass},采用方法={result.FuncName},总耗时={result.ElapsedMs} ms");
  327. }
  328. else
  329. {
  330. AppendResult($"读卡失败: {result.Message}");
  331. }
  332. RefreshStatus();
  333. }
  334. catch (Exception ex)
  335. {
  336. AppendResult("异常: " + ex.Message);
  337. Logger.Error("诊断面板模拟读卡异常", ex);
  338. }
  339. finally
  340. {
  341. _btnReadCard.Enabled = true;
  342. }
  343. }
  344. // ===== 读卡测试 =====
  345. /// <summary>
  346. /// ① 完整读卡(不传 card_class,由 COM 判定本地/异地);
  347. /// ② 指定类别读卡(传 card_class,跳过 GetPersonClass_Multimedia,少一笔约 1.4~2.6s)。
  348. /// Round49:服务端已无本地缓存,两种读法都不依赖历史状态。
  349. /// </summary>
  350. private async Task OnCardCacheRead(bool useCardClass)
  351. {
  352. string input = _txtCacheCardInput.Text.Trim();
  353. if (string.IsNullOrEmpty(input))
  354. {
  355. AppendCacheResult("读卡入参(input)为空");
  356. return;
  357. }
  358. if (input.IndexOf('\n') >= 0 || input.IndexOf('\r') >= 0)
  359. {
  360. AppendCacheResult("读卡入参必须是单行 XML,请勿换行");
  361. return;
  362. }
  363. string cardClass = useCardClass ? GetCardClassValue() : null;
  364. if (useCardClass && string.IsNullOrEmpty(cardClass))
  365. {
  366. AppendCacheResult("指定类别读卡需要先在 card_class 下拉里选「1 本市」或「2 异地」");
  367. return;
  368. }
  369. bool keepSession = _chkKeepOpen.Checked;
  370. SetCardCacheButtonsEnabled(false);
  371. AppendCacheResult(useCardClass
  372. ? "=== ② 指定类别读卡开始(card_class=" + cardClass + ",将跳过人员类别查询)==="
  373. : "=== ① 完整读卡开始(人员类别由 COM 判定)===");
  374. try
  375. {
  376. string payload = CardReaderFlow.WrapInput(input);
  377. CardReadResult result = await CardReaderFlow.ReadAsync(payload, cardClass, keepSession);
  378. AppendCardResult(result, keepSession);
  379. RefreshStatus();
  380. }
  381. catch (Exception ex)
  382. {
  383. AppendCacheResult("异常: " + ex.Message);
  384. Logger.Error("诊断面板读卡测试异常", ex);
  385. }
  386. finally
  387. {
  388. SetCardCacheButtonsEnabled(true);
  389. }
  390. }
  391. /// <summary>
  392. /// ③ 会话策略对比:同一笔读卡分别按 perRead / keepSession 各跑一次,给出耗时差。
  393. /// 用途是量化「重新 open 一次会话」的真实成本(Round49 决策点 3 的依据)。
  394. /// </summary>
  395. private async Task OnCardCacheCompare()
  396. {
  397. string input = _txtCacheCardInput.Text.Trim();
  398. if (string.IsNullOrEmpty(input))
  399. {
  400. AppendCacheResult("读卡入参(input)为空");
  401. return;
  402. }
  403. if (input.IndexOf('\n') >= 0 || input.IndexOf('\r') >= 0)
  404. {
  405. AppendCacheResult("读卡入参必须是单行 XML,请勿换行");
  406. return;
  407. }
  408. // 两轮用同一个 card_class,避免把"跳过一笔"的差异算进会话策略里
  409. string cardClass = GetCardClassValue();
  410. if (string.IsNullOrEmpty(cardClass)) cardClass = null;
  411. SetCardCacheButtonsEnabled(false);
  412. AppendCacheResult("=== ③ perRead vs keepSession 对比开始 ===");
  413. try
  414. {
  415. string payload = CardReaderFlow.WrapInput(input);
  416. AppendCacheResult("--- 第 1 轮:perRead(读完空闲即关会话,下一笔要重新 open)---");
  417. CardReadResult first = await CardReaderFlow.ReadAsync(payload, cardClass, false);
  418. AppendCardResult(first, false);
  419. AppendCacheResult("--- 第 2 轮:keepSession(保持会话,复用第 1 轮建立的会话)---");
  420. CardReadResult second = await CardReaderFlow.ReadAsync(payload, cardClass, true);
  421. AppendCardResult(second, true);
  422. AppendCacheResult("--- 对比 ---");
  423. AppendCacheResult($"perRead 总耗时: {first.ElapsedMs} ms");
  424. AppendCacheResult($"keepSession 总耗时: {second.ElapsedMs} ms");
  425. long saved = first.ElapsedMs - second.ElapsedMs;
  426. AppendCacheResult(first.ElapsedMs > 0
  427. ? $"差值: {saved} ms({saved * 100.0 / first.ElapsedMs:F1}%)—— 正数表示复用会话省下的时间"
  428. : $"差值: {saved} ms");
  429. RefreshStatus();
  430. }
  431. catch (Exception ex)
  432. {
  433. AppendCacheResult("异常: " + ex.Message);
  434. Logger.Error("诊断面板读卡会话策略对比异常", ex);
  435. }
  436. finally
  437. {
  438. // 第 2 轮把「上一条请求要求保活」的标志留成了 true,这里补一笔 close 收尾:
  439. // 既真的释放读卡器,也把标志复位成默认(false),不给后面的请求留尾巴。
  440. try
  441. {
  442. await GatewayHost.Instance.ExecuteAsync("close", null);
  443. }
  444. catch (Exception ex)
  445. {
  446. Logger.Error("诊断面板对比收尾 close 失败(忽略)", ex);
  447. }
  448. SetCardCacheButtonsEnabled(true);
  449. }
  450. }
  451. /// <summary>card_class 下拉:0=(空)、1=1 本市、2=2 异地。</summary>
  452. private string GetCardClassValue()
  453. {
  454. switch (_cmbCacheCardClass.SelectedIndex)
  455. {
  456. case 1: return "1";
  457. case 2: return "2";
  458. default: return string.Empty;
  459. }
  460. }
  461. private void SetCardCacheButtonsEnabled(bool enabled)
  462. {
  463. _btnFullRead.Enabled = enabled;
  464. _btnCacheRead.Enabled = enabled;
  465. _btnCompare.Enabled = enabled;
  466. }
  467. private void AppendCardResult(CardReadResult result, bool keepOpen)
  468. {
  469. var steps = result.Steps ?? new CardReadStep[0];
  470. foreach (CardReadStep step in steps)
  471. {
  472. AppendCacheResult($"--- 步骤: {step.Func} ---");
  473. AppendCacheResult($"结果码: {step.Code} 耗时: {step.ElapsedMs} ms");
  474. AppendCacheResult($"消息: {step.Message}");
  475. AppendCacheResult($"返回: {(string.IsNullOrEmpty(step.Output) ? "(空)" : step.Output)}");
  476. }
  477. AppendCacheResult($"会话模式: {(keepOpen ? "keepSession" : "perRead")}");
  478. AppendCacheResult($"card_no: {(string.IsNullOrEmpty(result.CardNo) ? "(无)" : result.CardNo)}");
  479. AppendCacheResult($"采用方法: {result.FuncName}");
  480. if (result.Code == 0)
  481. {
  482. AppendCacheResult($"读卡成功: card_class={result.CardClass},总耗时={result.ElapsedMs} ms");
  483. }
  484. else
  485. {
  486. AppendCacheResult($"读卡失败({result.Code}): {result.Message}");
  487. }
  488. }
  489. private void AppendCacheResult(string text)
  490. {
  491. if (_txtCacheResult.InvokeRequired)
  492. {
  493. _txtCacheResult.Invoke(new Action(() => AppendCacheResult(text)));
  494. return;
  495. }
  496. _txtCacheResult.AppendText($"[{DateTime.Now:HH:mm:ss.fff}] {text}\r\n");
  497. }
  498. /// <summary>参数框按行拆分,每行一个参数(按顺序对应 COM 方法的各个 byref 参数);空行忽略。</summary>
  499. private static string[] ParseArgs(string text)
  500. {
  501. if (string.IsNullOrEmpty(text)) return null;
  502. var lines = text.Replace("\r\n", "\n").Replace('\r', '\n').Split('\n')
  503. .Select(line => line.Trim())
  504. .Where(line => line.Length > 0)
  505. .ToArray();
  506. return lines.Length == 0 ? null : lines;
  507. }
  508. private void OnRestart()
  509. {
  510. try
  511. {
  512. GatewayHost.Instance.Reinitialize();
  513. AppendResult("网关已重建");
  514. RefreshStatus();
  515. }
  516. catch (Exception ex)
  517. {
  518. AppendResult($"重建失败: {ex.Message}");
  519. Logger.Error("诊断面板重建网关失败", ex);
  520. }
  521. }
  522. private void AppendResult(string text)
  523. {
  524. if (_txtResult.InvokeRequired)
  525. {
  526. _txtResult.Invoke(new Action(() => AppendResult(text)));
  527. return;
  528. }
  529. _txtResult.AppendText($"[{DateTime.Now:HH:mm:ss.fff}] {text}\r\n");
  530. }
  531. public void SetInitError(string message)
  532. {
  533. if (_lblStatus.InvokeRequired)
  534. {
  535. _lblStatus.Invoke(new Action(() => SetInitError(message)));
  536. return;
  537. }
  538. _lblStatus.Text = "网关状态: 初始化失败 - " + message;
  539. _lblStatus.ForeColor = Color.Red;
  540. AppendResult("[初始化失败] " + message);
  541. }
  542. // ===== 运行状态 =====
  543. private void RefreshStatus()
  544. {
  545. if (_lvStatus.InvokeRequired)
  546. {
  547. _lvStatus.Invoke(new Action(RefreshStatus));
  548. return;
  549. }
  550. var host = GatewayHost.Instance;
  551. _lvStatus.Items.Clear();
  552. bool initialized = host.IsInitialized;
  553. AddStatus("网关状态", initialized ? "已初始化" : "未初始化");
  554. AddStatus("故障标记", host.IsFaulted ? "是(上一笔超时或底层异常)" : "否");
  555. AddStatus("排队调用数", host.PendingCount.ToString());
  556. AddStatus("COM ProgID", host.ProgId);
  557. AddStatus("调用超时", AppConfig.ComTimeoutMs + " ms");
  558. AddStatus("空闲关会话", AppConfig.ComIdleTimeoutMs + " ms");
  559. AddStatus("HTTP 端口", AppConfig.HttpPort.ToString());
  560. AddStatus("HTTP 监听", IsHttpListening() ? "是" : "否");
  561. AddStatus("累计调用数", host.InvokeCount.ToString());
  562. AddStatus("最近调用时间", host.LastInvokeTime.HasValue ? host.LastInvokeTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "-");
  563. AddStatus("最近耗时", host.LastInvokeTime.HasValue ? host.LastElapsedMs + " ms" : "-");
  564. AddStatus("最后错误", string.IsNullOrEmpty(host.LastError) ? "-" : host.LastError);
  565. _lblStatus.Text = initialized ? "网关状态: 已初始化" : "网关状态: 未初始化";
  566. _lblStatus.ForeColor = initialized ? Color.Green : Color.OrangeRed;
  567. }
  568. private bool IsHttpListening()
  569. {
  570. foreach (var protocol in _protocols)
  571. {
  572. var http = protocol as HttpProtocol;
  573. if (http != null && http.IsListening) return true;
  574. }
  575. return false;
  576. }
  577. private void AddStatus(string name, string value)
  578. {
  579. var item = new ListViewItem(name);
  580. item.SubItems.Add(value ?? "");
  581. _lvStatus.Items.Add(item);
  582. }
  583. // ===== 配置 =====
  584. private void RefreshConfig()
  585. {
  586. if (_lvConfig.InvokeRequired)
  587. {
  588. _lvConfig.Invoke(new Action(RefreshConfig));
  589. return;
  590. }
  591. _lvConfig.Items.Clear();
  592. AddConfig("HttpPort", AppConfig.HttpPort.ToString());
  593. AddConfig("MaxRequestSize", AppConfig.MaxRequestSize.ToString());
  594. AddConfig("AccessToken", string.IsNullOrEmpty(AppConfig.AccessToken) ? "(未设置,不校验)" : "(已设置)");
  595. AddConfig("CorsAllowOrigin", AppConfig.CorsAllowOrigin);
  596. AddConfig("ComProgId", AppConfig.ComProgId);
  597. AddConfig("ComTimeoutMs", AppConfig.ComTimeoutMs.ToString());
  598. AddConfig("ComIdleTimeoutMs", AppConfig.ComIdleTimeoutMs.ToString());
  599. AddConfig("ServiceName", AppConfig.ServiceName);
  600. AddConfig("AutoStart", AppConfig.AutoStart.ToString());
  601. AddConfig("LogDirectory", AppConfig.LogDirectory);
  602. AddConfig("LogRetainDays", AppConfig.LogRetainDays.ToString());
  603. AddConfig("TradeLogEnabled", AppConfig.TradeLogEnabled.ToString());
  604. AddConfig("TradeLogMaskSensitive", AppConfig.TradeLogMaskSensitive.ToString());
  605. AddConfig("TradeLogMaxChars", AppConfig.TradeLogMaxChars == 0 ? "0(不截断)" : AppConfig.TradeLogMaxChars.ToString());
  606. AddConfig("TradeLog文件", AppConfig.TradeLogEnabled
  607. ? Path.GetFileName(TradeLogger.TodayTradeLogFilePath)
  608. : "(已关闭)");
  609. }
  610. private void AddConfig(string name, string value)
  611. {
  612. var item = new ListViewItem(name);
  613. item.SubItems.Add(value ?? "");
  614. _lvConfig.Items.Add(item);
  615. }
  616. // ===== 日志 =====
  617. private void LoadLog()
  618. {
  619. try
  620. {
  621. var item = _cmbLogFile.SelectedItem as LogFileItem;
  622. string filePath = item != null ? item.Path : Logger.TodayLogFilePath;
  623. if (!File.Exists(filePath))
  624. {
  625. _txtLog.Text = "(日志文件不存在)\r\n" + filePath;
  626. return;
  627. }
  628. var lines = File.ReadLines(filePath, Encoding.UTF8).Reverse().Take(200).Reverse();
  629. _txtLog.Text = string.Join("\r\n", lines);
  630. _txtLog.SelectionStart = _txtLog.Text.Length;
  631. _txtLog.ScrollToCaret();
  632. }
  633. catch (Exception ex)
  634. {
  635. _txtLog.Text = "读取日志失败: " + ex.Message;
  636. }
  637. }
  638. private void OpenLogDir()
  639. {
  640. try
  641. {
  642. Directory.CreateDirectory(Logger.LogDirectoryPath);
  643. Process.Start(Logger.LogDirectoryPath);
  644. }
  645. catch (Exception ex)
  646. {
  647. MessageBox.Show($"无法打开日志目录: {ex.Message}", "错误",
  648. MessageBoxButtons.OK, MessageBoxIcon.Error);
  649. }
  650. }
  651. private sealed class LogFileItem
  652. {
  653. private readonly Func<string> _pathProvider;
  654. public LogFileItem(string displayName, Func<string> pathProvider)
  655. {
  656. DisplayName = displayName;
  657. _pathProvider = pathProvider;
  658. }
  659. public string DisplayName { get; private set; }
  660. /// <summary>动态取路径,跨零点后自动切到当天日志文件。</summary>
  661. public string Path
  662. {
  663. get { return _pathProvider(); }
  664. }
  665. public override string ToString()
  666. {
  667. return DisplayName;
  668. }
  669. }
  670. protected override void Dispose(bool disposing)
  671. {
  672. if (disposing)
  673. {
  674. if (_cmbLogFile != null) _cmbLogFile.Dispose();
  675. if (_tabControl != null) _tabControl.Dispose();
  676. }
  677. base.Dispose(disposing);
  678. }
  679. }
  680. }