ComGateway.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Diagnostics;
  4. using System.Reflection;
  5. using System.Runtime.InteropServices;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using BeiJingComService.Infrastructure;
  9. namespace BeiJingComService.Core
  10. {
  11. /// <summary>
  12. /// 本地首信医保 COM(MedicareCom.Outpatient)通讯网关。
  13. ///
  14. /// 会话策略(方案 B:每次读卡 open → 读 → close,用完即关):
  15. /// 1) COM 实例在 Initialize 时创建一次,进程生命周期内常驻复用,
  16. /// 绝不在每次调用时 CreateInstance / FinalReleaseComObject,也不做 GC.Collect;
  17. /// 唯一例外是第 4 条的自愈最后一级(open 连 9008 两次),才销毁重建实例;
  18. /// 2) 读卡序列开始时按需真实 open,序列结束后由工作线程在"队列空闲达到阈值"时主动 close,
  19. /// 即用完即关、不再长期独占读卡器;下一次读卡再重新 open,
  20. /// 从根本上规避长驻会话陈旧后对已打开设备重复 open 触发"打开设备失败(9008)";
  21. /// 3) 读卡/PSAM 等为独占设备,同一时刻只允许一笔调用进入 COM,
  22. /// 采用"单 STA 工作线程 + 队列串行"执行,而非加锁。
  23. /// 4) close 的成败要判定(报文 success + 耗时):没关干净就标记脏会话,
  24. /// open 撞 9008 时依次"补 close → 重开 → 销毁重建实例再开"自愈,
  25. /// 避免一次慢 close 导致后续读卡永久 9008(详见 Round43 方案文档)。
  26. ///
  27. /// 调用约定(对应 HIS 侧 ObjectClass / CardReader_BJ 的反射调用形态):
  28. /// func + args[] → 变参 InvokeMember,全部参数按 byref(out)传入;
  29. /// args 为空时使用 1 个 byref 参数(open/close/Trade/TradeAll 形态);
  30. /// args 长度为 N 时使用 N 个 byref 参数,返回值取最后一个参数的最终值。
  31. /// </summary>
  32. public sealed class ComGateway : IComGateway
  33. {
  34. private readonly string _progId;
  35. private readonly int _defaultTimeoutMs;
  36. private readonly int _lingerMs;
  37. /// <summary>close 耗时超过该值即视为「可能没关干净」(正常 6~12ms,实测异常时 3186ms)。</summary>
  38. private const int CloseSlowThresholdMs = 500;
  39. /// <summary>设备已被打开的错误码(首信组件返回 state.success=false / error no=9008)。</summary>
  40. private const string ErrorDeviceAlreadyOpen = "9008";
  41. /// <summary>
  42. /// 未插社保卡的错误号(首信 error no=2011 下,0xfffffffe = 未插卡,0xfffffff8 = 通讯错误)。
  43. /// Round59:两者共用 no=2011,必须按错误号区分,不能按 no 判。
  44. /// </summary>
  45. private const string ErrorNoCard = "0xfffffffe";
  46. /// <summary>
  47. /// Round59:未插卡(0xfffffffe)返回耗时超过该值即判定读卡器亚健康,主动关闭会话。
  48. /// 0 = 禁用。取自 AppConfig.NoCardSlowCloseMs,构造时读取一次。
  49. /// </summary>
  50. private readonly int _noCardSlowCloseMs;
  51. private readonly object _sync = new object();
  52. private Type _comType;
  53. private object _comInstance;
  54. private bool _opened;
  55. private string _lastOpenOutput;
  56. /// <summary>上次 close 未确认成功(报文失败或耗时异常),设备可能仍被占用;下次 open 前先补一次 close。</summary>
  57. private volatile bool _sessionDirty;
  58. /// <summary>open 撞 9008 时是否允许销毁并重建 COM 实例(= 人工「重建网关」的自动化版本)。默认 true。</summary>
  59. private volatile bool _allowInstanceRecreate = true;
  60. /// <summary>最近一次 close 的原始报文(显式 close 时原样返回给调用方)。</summary>
  61. private string _lastCloseOutput;
  62. private BlockingCollection<WorkItem> _queue;
  63. private Thread _worker;
  64. private volatile bool _initialized;
  65. private volatile bool _faulted;
  66. private volatile bool _disposed;
  67. /// <summary>是否允许队列空闲达到阈值后自动 close。true(默认)=用完即关;false=会话常驻不关(keepOpen 测试模式)。</summary>
  68. private volatile bool _allowIdleClose = true;
  69. /// <summary>
  70. /// 上一条请求是否要求保住会话(WorkItem.KeepSession)。
  71. /// Round49:会话策略从"网关上的全局开关"改成"随请求走的标志",
  72. /// 空闲关会话的判定改为「上一条请求没要求保活」才关,
  73. /// 这样 keepOpen 不会再泄漏到 /api/com/invoke 等其它入口,也不会因异常残留。
  74. /// </summary>
  75. private volatile bool _lastKeepSession;
  76. public ComGateway() : this(AppConfig.ComProgId)
  77. {
  78. }
  79. /// <summary>按指定 ProgID 创建网关(用于次要 COM 组件,如中药订单共享 EachCommunicationCom.Outpatient)。</summary>
  80. public ComGateway(string progId)
  81. {
  82. _progId = string.IsNullOrWhiteSpace(progId) ? AppConfig.ComProgId : progId;
  83. _defaultTimeoutMs = AppConfig.ComTimeoutMs;
  84. // 队列空闲达到该阈值即主动 close(用完即关);下限 50ms 防止配置为 0 时工作线程空转
  85. _lingerMs = Math.Max(50, AppConfig.ComIdleTimeoutMs);
  86. // Round59:慢速未插卡的主动关会话阈值(0 = 禁用本行为)
  87. _noCardSlowCloseMs = Math.Max(0, AppConfig.NoCardSlowCloseMs);
  88. }
  89. public bool IsInitialized
  90. {
  91. get { return _initialized; }
  92. }
  93. public int PendingCount
  94. {
  95. get { return _queue != null ? _queue.Count : 0; }
  96. }
  97. public bool IsFaulted
  98. {
  99. get { return _faulted; }
  100. }
  101. /// <summary>
  102. /// 是否允许会话在队列空闲达到阈值后自动关闭。
  103. /// true(默认)= 用完即关(方案 B);false = 会话常驻不关(keepOpen 测试模式,只 Open 一次)。
  104. /// </summary>
  105. public bool AllowIdleClose
  106. {
  107. get { return _allowIdleClose; }
  108. set { _allowIdleClose = value; }
  109. }
  110. /// <summary>
  111. /// open 撞 9008(设备已被占用)时,是否允许销毁并重建 COM 实例后再试一次。
  112. /// 默认 true —— 等价于把人工「重建网关」自动化,是自愈的最后一级。
  113. /// </summary>
  114. public bool AllowInstanceRecreate
  115. {
  116. get { return _allowInstanceRecreate; }
  117. set { _allowInstanceRecreate = value; }
  118. }
  119. public string ProgId
  120. {
  121. get { return _progId; }
  122. }
  123. public void Initialize()
  124. {
  125. if (_initialized) return;
  126. lock (_sync)
  127. {
  128. if (_initialized) return;
  129. _comType = Type.GetTypeFromProgID(_progId);
  130. if (_comType == null)
  131. {
  132. throw new InvalidOperationException($"未找到本地 COM 组件: {_progId}。请确认首信医保组件已正确安装注册。");
  133. }
  134. // 常驻实例:进程内只创建这一次
  135. _comInstance = Activator.CreateInstance(_comType);
  136. if (_comInstance == null)
  137. {
  138. throw new InvalidOperationException($"创建 COM 实例失败: {_progId}");
  139. }
  140. _opened = false;
  141. _sessionDirty = false;
  142. _lastOpenOutput = null;
  143. _lastCloseOutput = null;
  144. StartWorker();
  145. _faulted = false;
  146. _initialized = true;
  147. Logger.Info($"COM 网关初始化成功,ProgID={_progId},实例已常驻内存,超时={_defaultTimeoutMs}ms,空闲关会话阈值={_lingerMs}ms(用完即关)");
  148. }
  149. }
  150. public void Reinitialize()
  151. {
  152. Logger.Info("COM 网关重新初始化开始");
  153. StopWorker();
  154. DisposeComInstance();
  155. _initialized = false;
  156. _faulted = false;
  157. _sessionDirty = false;
  158. Initialize();
  159. Logger.Info("COM 网关重新初始化完成");
  160. }
  161. public async Task<ComResult> InvokeAsync(string func, string[] args, int timeoutMs = 0, bool keepSession = false)
  162. {
  163. if (timeoutMs <= 0) timeoutMs = _defaultTimeoutMs;
  164. if (!_initialized) return ComResult.Fail(-3, "网关未初始化");
  165. if (_disposed) return ComResult.Fail(-3, "网关已释放");
  166. if (string.IsNullOrWhiteSpace(func)) return ComResult.Fail(-4, "COM 方法名为空");
  167. var item = new WorkItem
  168. {
  169. Func = func,
  170. Args = args,
  171. KeepSession = keepSession,
  172. Completion = new TaskCompletionSource<ComResult>()
  173. };
  174. try
  175. {
  176. _queue.Add(item);
  177. }
  178. catch (InvalidOperationException)
  179. {
  180. return ComResult.Fail(-3, "网关已停止,无法受理调用");
  181. }
  182. catch (Exception ex)
  183. {
  184. return ComResult.Fail(-1, "调用入队失败: " + ex.Message);
  185. }
  186. var stopwatch = Stopwatch.StartNew();
  187. Task finished = await Task.WhenAny(item.Completion.Task, Task.Delay(timeoutMs)).ConfigureAwait(false);
  188. stopwatch.Stop();
  189. if (!object.ReferenceEquals(finished, item.Completion.Task))
  190. {
  191. // 超时:工作线程仍在 COM 内部执行,绝不能重复提交,本次结果作废
  192. _faulted = true;
  193. Logger.Error($"COM 调用超时({timeoutMs}ms),方法={func},结果作废,请勿重复提交");
  194. return new ComResult
  195. {
  196. Code = -2,
  197. Message = $"调用超时({timeoutMs}ms)。请求已提交至 COM,请勿重复提交。",
  198. ElapsedMs = stopwatch.ElapsedMilliseconds
  199. };
  200. }
  201. try
  202. {
  203. ComResult result = await item.Completion.Task.ConfigureAwait(false);
  204. result.ElapsedMs = stopwatch.ElapsedMilliseconds;
  205. _faulted = !result.Success;
  206. return result;
  207. }
  208. catch (Exception ex)
  209. {
  210. Logger.Error($"COM 调用执行失败,方法={func}", ex);
  211. return ComResult.Fail(-1, "调用执行失败: " + ex.Message, stopwatch.ElapsedMilliseconds);
  212. }
  213. }
  214. public ComResult Invoke(string func, string[] args, int timeoutMs = 0, bool keepSession = false)
  215. {
  216. return InvokeAsync(func, args, timeoutMs, keepSession).GetAwaiter().GetResult();
  217. }
  218. public void Dispose()
  219. {
  220. if (_disposed) return;
  221. _disposed = true;
  222. StopWorker();
  223. DisposeComInstance();
  224. _initialized = false;
  225. Logger.Info("COM 网关已释放");
  226. }
  227. // ===================== 工作线程 =====================
  228. private void StartWorker()
  229. {
  230. _queue = new BlockingCollection<WorkItem>();
  231. _worker = new Thread(WorkerLoop);
  232. _worker.IsBackground = true;
  233. _worker.Name = "ComGatewayWorker";
  234. // 医保 COM/OCX 控件绝大多数要求 STA 单元
  235. _worker.SetApartmentState(ApartmentState.STA);
  236. _worker.Start();
  237. }
  238. private void WorkerLoop()
  239. {
  240. // Round57:CBT 钩子必须装「本线程」—— COM 弹框是这个线程创建的,
  241. // 装在外层 StartWorker() 等于装在调用方线程上,收不到任何窗口事件。
  242. // 内部已 try/catch,失败只记日志,不影响读卡。
  243. DialogTopmostWatcher.InstallForCurrentThread();
  244. while (true)
  245. {
  246. WorkItem item;
  247. bool got;
  248. try
  249. {
  250. // 带超时等待:超时返回 false 说明队列已空闲,此时主动关会话(用完即关)
  251. got = _queue.TryTake(out item, _lingerMs);
  252. }
  253. catch (ObjectDisposedException) { break; }
  254. catch (InvalidOperationException) { break; }
  255. if (got)
  256. {
  257. // Round49:会话保活随请求走 —— 只有这一笔要求保活,后续空闲期才不关会话
  258. _lastKeepSession = item.KeepSession;
  259. try
  260. {
  261. ComResult result = CallNative(item.Func, item.Args);
  262. item.Completion.TrySetResult(result);
  263. }
  264. catch (Exception ex)
  265. {
  266. _faulted = true;
  267. Logger.Error($"COM 底层调用异常,方法={item.Func}", ex);
  268. item.Completion.TrySetException(ex);
  269. }
  270. continue;
  271. }
  272. // 队列已停止且取空(或已被 CompleteAdding):退出工作线程
  273. if (_queue.IsAddingCompleted) break;
  274. // 空闲达到阈值:在 STA 工作线程上执行 close,释放读卡器。
  275. // _allowIdleClose=false(诊断面板强制 keepOpen)或上一条请求要求保活时跳过。
  276. if (_allowIdleClose && !_lastKeepSession) CloseSessionQuietly();
  277. }
  278. }
  279. private void StopWorker()
  280. {
  281. if (_queue != null)
  282. {
  283. try { _queue.CompleteAdding(); }
  284. catch (Exception ex) { Logger.Error("关闭调用队列失败", ex); }
  285. WorkItem pending;
  286. while (_queue.TryTake(out pending))
  287. {
  288. pending.Completion.TrySetException(new InvalidOperationException("网关正在重新初始化,调用已取消"));
  289. }
  290. }
  291. if (_worker != null && _worker.IsAlive)
  292. {
  293. if (!_worker.Join(TimeSpan.FromSeconds(5)))
  294. {
  295. Logger.Error("COM 工作线程未能在 5 秒内退出");
  296. }
  297. }
  298. // Round57:线程已退出,摘掉装在该线程上的 CBT 钩子并停看门狗。
  299. // 重新初始化(Reinitialize)后由新的工作线程重新安装。
  300. DialogTopmostWatcher.Uninstall();
  301. if (_queue != null)
  302. {
  303. _queue.Dispose();
  304. _queue = null;
  305. }
  306. _worker = null;
  307. }
  308. // ===================== COM 调用 =====================
  309. private ComResult CallNative(string func, string[] args)
  310. {
  311. // Round57:一笔调用期间允许弹框置顶(钩子 + 看门狗)。结束无论成败都要复位,
  312. // 否则看门狗会在空闲期白扫;钩子本身不受影响,等下一次调用。
  313. DialogTopmostWatcher.BeginCall();
  314. try
  315. {
  316. return CallNativeCore(func, args);
  317. }
  318. finally
  319. {
  320. DialogTopmostWatcher.EndCall();
  321. }
  322. }
  323. private ComResult CallNativeCore(string func, string[] args)
  324. {
  325. if (_comType == null || _comInstance == null)
  326. {
  327. throw new InvalidOperationException("COM 实例不可用");
  328. }
  329. bool isOpen = string.Equals(func, "open", StringComparison.OrdinalIgnoreCase);
  330. bool isClose = string.Equals(func, "close", StringComparison.OrdinalIgnoreCase);
  331. if (isOpen)
  332. {
  333. return OpenSession();
  334. }
  335. if (isClose)
  336. {
  337. bool ok = CloseSessionInternal("显式 close", args);
  338. // 关闭报文原样回给调用方;连报文都没有(调用抛异常)才判失败
  339. if (ok || _lastCloseOutput != null) return FromOutput(_lastCloseOutput);
  340. return ComResult.Fail(-1, "关闭读卡设备失败(详见运行日志)");
  341. }
  342. // 其它调用:先确保会话可用,再执行真正的调用。
  343. // 用完不在这里关——由工作线程在队列空闲达到阈值后统一 close(用完即关),
  344. // 这样同一次读卡序列(类别 + 参保信息两笔)共用一次 open/close。
  345. ComResult openResult = OpenSession();
  346. if (!openResult.Success)
  347. {
  348. return openResult;
  349. }
  350. // ★ OpenSession 里可能已重建过 COM 实例,这里必须重新取字段,否则会用旧句柄
  351. Type comType = _comType;
  352. object comInstance = _comInstance;
  353. if (comType == null || comInstance == null)
  354. {
  355. throw new InvalidOperationException("COM 实例不可用");
  356. }
  357. var watch = Stopwatch.StartNew();
  358. string output;
  359. try
  360. {
  361. output = InvokeCom(comType, comInstance, func, args);
  362. }
  363. finally
  364. {
  365. watch.Stop();
  366. }
  367. // Round59:未插卡但返回迟缓 → 读卡器已亚健康,主动关会话,避免残留状态演变成 f8
  368. TryCloseOnSlowNoCard(func, output, watch.ElapsedMilliseconds);
  369. return FromOutput(output);
  370. }
  371. /// <summary>
  372. /// 确保 COM 会话可用(方案 B:用完即关)。
  373. /// 会话由工作线程在队列空闲达到阈值后主动 close,故这里只区分两种情形:
  374. /// - 已打开 → 直接复用(跳过真实 open,保证同一读卡序列的读卡速度);
  375. /// - 未打开 → 执行真实 open。
  376. ///
  377. /// 打开失败时按三级自愈(Round43):
  378. /// 第 0 级:上次 close 未确认干净 → 先补一次 close 清理;
  379. /// 第 1 级:open 撞 9008(设备已被占用)→ close 后重开一次;
  380. /// 第 2 级:仍 9008 → 销毁并重建 COM 实例后重开(等价人工「重建网关」)。
  381. /// </summary>
  382. private ComResult OpenSession()
  383. {
  384. if (_opened)
  385. {
  386. return new ComResult { Code = 0, Message = "OK", Output = _lastOpenOutput };
  387. }
  388. // 第 0 级:上次 close 不干净,先补一次 close 把它抹掉(正常只要 6~12ms)
  389. if (_sessionDirty)
  390. {
  391. Logger.Info("上次会话未确认关闭,open 前先补一次 close 清理");
  392. CloseSessionInternal("open 前清理", null);
  393. }
  394. ComResult result = TryOpenOnce();
  395. if (result.Success) return result;
  396. if (!IsDeviceAlreadyOpen(result.Output)) return result;
  397. // 第 1 级:9008 = 设备已经开着 → close 后再 open 一次
  398. Logger.Error("open 返回 9008(设备已被占用),执行 close 后重试一次");
  399. CloseSessionInternal("9008 自愈-close", null);
  400. result = TryOpenOnce();
  401. if (result.Success) return result;
  402. if (!IsDeviceAlreadyOpen(result.Output)) return result;
  403. // 第 2 级:仍是 9008 → 销毁并重建 COM 实例(把人工「重建网关」自动化)
  404. if (_allowInstanceRecreate)
  405. {
  406. Logger.Error("close 后仍返回 9008,销毁并重建 COM 实例后重试(自愈最后一级)");
  407. try
  408. {
  409. RecreateComInstance();
  410. }
  411. catch (Exception ex)
  412. {
  413. Logger.Error("重建 COM 实例失败(自愈最后一级)", ex);
  414. _sessionDirty = true;
  415. return result;
  416. }
  417. result = TryOpenOnce();
  418. if (result.Success) return result;
  419. }
  420. // 三级都失败:标记脏会话,交给下一笔继续清理
  421. _sessionDirty = true;
  422. return result;
  423. }
  424. /// <summary>
  425. /// 单次 open:调用 + 成功判定 + 落日志。
  426. /// 失败结果带 <see cref="ComResult.StageOpen"/> 标记,便于上层区分"设备打不开"与"读卡方法失败"。
  427. /// </summary>
  428. private ComResult TryOpenOnce()
  429. {
  430. var watch = Stopwatch.StartNew();
  431. string output = null;
  432. Exception error = null;
  433. try
  434. {
  435. output = InvokeCom(_comType, _comInstance, "open", null);
  436. }
  437. catch (Exception ex)
  438. {
  439. error = ex;
  440. Logger.Error("COM 会话建立异常(open)", ex);
  441. }
  442. watch.Stop();
  443. bool ok = error == null && IsSuccess(output);
  444. LogSession("open", output, watch.ElapsedMilliseconds, ok);
  445. if (ok)
  446. {
  447. _opened = true;
  448. _lastOpenOutput = output;
  449. _sessionDirty = false;
  450. _faulted = false;
  451. Logger.Info($"COM 会话已建立(open),耗时={watch.ElapsedMilliseconds}ms");
  452. return new ComResult { Code = 0, Message = "OK", Output = output };
  453. }
  454. _opened = false;
  455. _lastOpenOutput = null;
  456. string message = error != null
  457. ? "打开读卡设备失败(COM 异常):" + error.Message
  458. : "打开读卡设备失败(" + ExtractErrorNo(output) + "),请检查设备是否被占用或需要重新插拔:" + Summarize(output);
  459. Logger.Error($"COM 会话建立失败(open),耗时={watch.ElapsedMilliseconds}ms:" + Summarize(output));
  460. return new ComResult
  461. {
  462. Code = -1,
  463. Stage = ComResult.StageOpen,
  464. Message = message,
  465. Output = output
  466. };
  467. }
  468. /// <summary>反射调用 COM 方法:全部参数按 byref 传出,返回值取最后一个参数的最终值。</summary>
  469. private static string InvokeCom(Type comType, object comInstance, string func, string[] args)
  470. {
  471. int count = (args == null || args.Length == 0) ? 1 : args.Length;
  472. object[] paramArray = new object[count];
  473. for (int i = 0; i < count; i++)
  474. {
  475. paramArray[i] = (args != null && i < args.Length && args[i] != null)
  476. ? (object)args[i]
  477. : string.Empty;
  478. }
  479. ParameterModifier[] paramMods = new ParameterModifier[1];
  480. paramMods[0] = new ParameterModifier(count);
  481. for (int i = 0; i < count; i++)
  482. {
  483. paramMods[0][i] = true; // 全部按 byref 传出
  484. }
  485. object returnValue = comType.InvokeMember(func,
  486. BindingFlags.Default | BindingFlags.InvokeMethod,
  487. null,
  488. comInstance,
  489. paramArray,
  490. paramMods,
  491. null,
  492. null);
  493. object last = paramArray[count - 1];
  494. if (last != null) return last.ToString();
  495. return returnValue == null ? string.Empty : returnValue.ToString();
  496. }
  497. /// <summary>
  498. /// Round59:未插卡(0xfffffffe)但耗时超过阈值 → 读卡器响应迟缓,会话已处于亚健康。
  499. /// 主动 close 让下一次读卡从全新会话开始,避免残留状态演变成 f8。
  500. ///
  501. /// 只关会话、不重建实例:重建虽然一定有效,但会重置实例、抹掉现场状态,无法定位根因。
  502. /// close 失败时由 CloseSessionInternal 置 _sessionDirty,下一笔 open 前补清理,
  503. /// 仍不行则走既有的 Round43 三级自愈(open 9008 → close → 重建实例)。
  504. ///
  505. /// 运行在 STA 工作线程上(CallNativeCore 内),故可安全触碰 COM。
  506. /// </summary>
  507. private void TryCloseOnSlowNoCard(string func, string output, long elapsedMs)
  508. {
  509. if (_noCardSlowCloseMs <= 0) return;
  510. if (elapsedMs < _noCardSlowCloseMs) return;
  511. if (string.IsNullOrEmpty(output)) return;
  512. if (output.IndexOf(ErrorNoCard, StringComparison.OrdinalIgnoreCase) < 0) return;
  513. // 会话已经关了就没必要再 close:必返 9009,只会平白污染 _sessionDirty
  514. if (!_opened) return;
  515. Logger.Error("[NoCardSlow] 未插卡但响应迟缓(耗时=" + elapsedMs + "ms > "
  516. + _noCardSlowCloseMs + "ms),主动关闭会话,方法=" + func);
  517. bool ok = CloseSessionInternal("未插卡超时-自愈", null);
  518. if (ok)
  519. {
  520. Logger.Info("[NoCardSlow] 会话已关闭,下次读卡将重新 open");
  521. }
  522. else
  523. {
  524. Logger.Info("[NoCardSlow] 会话关闭失败,已标记脏会话,下次 open 前补清理");
  525. }
  526. }
  527. /// <summary>
  528. /// 队列空闲后关闭会话(用完即关)。运行在 STA 工作线程上,故可安全触碰 COM。
  529. /// 关闭失败仅记录日志、不抛异常:会话标记为脏,下次 open 前会补一次清理。
  530. /// </summary>
  531. private void CloseSessionQuietly()
  532. {
  533. if (!_opened) return;
  534. CloseSessionInternal("空闲关闭", null);
  535. }
  536. /// <summary>
  537. /// 真实的 close:判报文 + 判耗时 + 落日志,并把「没关干净」变成脏会话标记。
  538. /// 只有报文成功 **且** 耗时正常才认为设备已释放;否则下次 open 前先补一次 close。
  539. /// 返回报文是否成功(报文都没拿到时返回 false)。
  540. /// </summary>
  541. private bool CloseSessionInternal(string reason, string[] args)
  542. {
  543. bool ok = false;
  544. _lastCloseOutput = null;
  545. if (_comType == null || _comInstance == null)
  546. {
  547. _opened = false;
  548. _sessionDirty = false;
  549. return true;
  550. }
  551. var watch = Stopwatch.StartNew();
  552. string output = null;
  553. try
  554. {
  555. output = InvokeCom(_comType, _comInstance, "close", args);
  556. ok = IsSuccess(output);
  557. }
  558. catch (Exception ex)
  559. {
  560. Logger.Error("COM 会话关闭异常(" + reason + ")", ex);
  561. }
  562. watch.Stop();
  563. LogSession("close", output, watch.ElapsedMilliseconds, ok);
  564. _opened = false;
  565. _lastOpenOutput = null;
  566. _lastCloseOutput = output;
  567. // ★ 关键:报文失败,或者耗时异常(设备忙)都算「没关干净」
  568. bool slow = watch.ElapsedMilliseconds > CloseSlowThresholdMs;
  569. _sessionDirty = !ok || slow;
  570. if (_sessionDirty)
  571. {
  572. Logger.Error("COM 会话关闭未确认(" + reason + "),耗时=" + watch.ElapsedMilliseconds
  573. + "ms,报文结果=" + (ok ? "成功" : "失败") + ",标记为脏会话,下次 open 前会重新清理:"
  574. + Summarize(output));
  575. }
  576. else
  577. {
  578. Logger.Info("COM 会话已关闭(" + reason + "),耗时=" + watch.ElapsedMilliseconds + "ms");
  579. }
  580. return ok;
  581. }
  582. /// <summary>
  583. /// 在 STA 工作线程上销毁并重建 COM 实例(自愈最后一级)。
  584. /// 与人工点「重建网关」等价,但不重启工作线程、不影响在途调用。
  585. /// </summary>
  586. private void RecreateComInstance()
  587. {
  588. object old = _comInstance;
  589. _comInstance = null;
  590. _opened = false;
  591. _lastOpenOutput = null;
  592. _lastCloseOutput = null;
  593. if (old != null && Marshal.IsComObject(old))
  594. {
  595. try
  596. {
  597. Marshal.FinalReleaseComObject(old);
  598. }
  599. catch (Exception ex)
  600. {
  601. Logger.Error("释放旧 COM 实例失败(已忽略)", ex);
  602. }
  603. }
  604. Type comType = Type.GetTypeFromProgID(_progId);
  605. if (comType == null)
  606. {
  607. throw new InvalidOperationException("未找到本地 COM 组件: " + _progId);
  608. }
  609. _comType = comType;
  610. _comInstance = Activator.CreateInstance(comType);
  611. if (_comInstance == null)
  612. {
  613. throw new InvalidOperationException("重建 COM 实例失败: " + _progId);
  614. }
  615. Logger.Info("COM 实例已重建(自愈): " + _progId);
  616. }
  617. /// <summary>
  618. /// open/close 不走 GatewayHost 的埋点,这里单独把原文补进 *_Trade.log。
  619. /// 上次事故就是因为查不到 close 报文,只能靠耗时推测设备是否真的关了。
  620. /// </summary>
  621. private static void LogSession(string func, string output, long elapsedMs, bool ok)
  622. {
  623. try
  624. {
  625. TradeLogger.Write(func, string.Empty, output, ok ? 0 : -1, ok ? "OK" : "会话失败", elapsedMs, ok);
  626. }
  627. catch
  628. {
  629. // 日志失败不影响主流程
  630. }
  631. }
  632. /// <summary>从报文里取 error 的 no 属性(如 9008),取不到返回 "?"。</summary>
  633. private static string ExtractErrorNo(string xml)
  634. {
  635. if (string.IsNullOrEmpty(xml)) return "?";
  636. int start = xml.IndexOf("<error", StringComparison.OrdinalIgnoreCase);
  637. if (start < 0) return "?";
  638. string value = ExtractAttributeValue(xml.Substring(start), "no");
  639. return string.IsNullOrEmpty(value) ? "?" : value;
  640. }
  641. /// <summary>报文是否表示「设备已被打开」(error no=9008)。</summary>
  642. private static bool IsDeviceAlreadyOpen(string xml)
  643. {
  644. return string.Equals(ExtractErrorNo(xml), ErrorDeviceAlreadyOpen, StringComparison.Ordinal);
  645. }
  646. /// <summary>取 XML 里某个属性的值(报文可能不规范,故用手写扫描而非 XmlDocument)。</summary>
  647. private static string ExtractAttributeValue(string xml, string attributeName)
  648. {
  649. if (string.IsNullOrEmpty(xml)) return null;
  650. int searchFrom = 0;
  651. while (true)
  652. {
  653. int index = xml.IndexOf(attributeName, searchFrom, StringComparison.OrdinalIgnoreCase);
  654. if (index < 0) return null;
  655. int i = index + attributeName.Length;
  656. while (i < xml.Length && char.IsWhiteSpace(xml[i])) i++;
  657. if (i < xml.Length && xml[i] == '=')
  658. {
  659. i++;
  660. while (i < xml.Length && char.IsWhiteSpace(xml[i])) i++;
  661. if (i < xml.Length && (xml[i] == '"' || xml[i] == '\''))
  662. {
  663. char quote = xml[i];
  664. i++;
  665. int end = i;
  666. while (end < xml.Length && xml[end] != quote) end++;
  667. if (end < xml.Length) return xml.Substring(i, end - i);
  668. }
  669. }
  670. searchFrom = index + attributeName.Length;
  671. }
  672. }
  673. /// <summary>报文里 state 元素用属性 success="true" 表示成功。</summary>
  674. private static bool IsSuccess(string xml)
  675. {
  676. if (string.IsNullOrEmpty(xml)) return false;
  677. const string attr = "success";
  678. int searchFrom = 0;
  679. while (true)
  680. {
  681. int index = xml.IndexOf(attr, searchFrom, StringComparison.OrdinalIgnoreCase);
  682. if (index < 0) return false;
  683. int i = index + attr.Length;
  684. while (i < xml.Length && char.IsWhiteSpace(xml[i])) i++;
  685. if (i < xml.Length && xml[i] == '=')
  686. {
  687. i++;
  688. while (i < xml.Length && char.IsWhiteSpace(xml[i])) i++;
  689. if (i < xml.Length && (xml[i] == '"' || xml[i] == '\''))
  690. {
  691. char quote = xml[i];
  692. i++;
  693. int end = i;
  694. while (end < xml.Length && xml[end] != quote) end++;
  695. if (end < xml.Length)
  696. {
  697. string value = xml.Substring(i, end - i);
  698. return string.Equals(value, "true", StringComparison.OrdinalIgnoreCase);
  699. }
  700. }
  701. }
  702. searchFrom = index + attr.Length;
  703. }
  704. }
  705. private static ComResult FromOutput(string output)
  706. {
  707. return new ComResult { Code = 0, Message = "OK", Output = output };
  708. }
  709. /// <summary>失败时给出便于排查的报文片段(过长则截断)。</summary>
  710. private static string Summarize(string text)
  711. {
  712. if (string.IsNullOrEmpty(text)) return "(无返回报文)";
  713. const int limit = 300;
  714. return text.Length > limit ? text.Substring(0, limit) + "...(已截断)" : text;
  715. }
  716. private void DisposeComInstance()
  717. {
  718. lock (_sync)
  719. {
  720. if (_comInstance != null)
  721. {
  722. if (_opened)
  723. {
  724. try
  725. {
  726. object[] paramArray = new object[1] { string.Empty };
  727. ParameterModifier[] paramMods = new ParameterModifier[1];
  728. paramMods[0] = new ParameterModifier(1);
  729. paramMods[0][0] = true;
  730. _comType.InvokeMember("close",
  731. BindingFlags.Default | BindingFlags.InvokeMethod,
  732. null, _comInstance, paramArray, paramMods, null, null);
  733. }
  734. catch (Exception ex)
  735. {
  736. Logger.Error("释放实例前 close 失败(已忽略)", ex);
  737. }
  738. }
  739. try
  740. {
  741. if (Marshal.IsComObject(_comInstance))
  742. {
  743. Marshal.FinalReleaseComObject(_comInstance);
  744. }
  745. }
  746. catch
  747. {
  748. // 忽略
  749. }
  750. _comInstance = null;
  751. }
  752. _comType = null;
  753. _opened = false;
  754. }
  755. }
  756. private sealed class WorkItem
  757. {
  758. public string Func;
  759. public string[] Args;
  760. /// <summary>true = 这一笔之后不要空闲关会话(只 Open 一次,测试用)。</summary>
  761. public bool KeepSession;
  762. public TaskCompletionSource<ComResult> Completion;
  763. }
  764. }
  765. }