| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873 |
- using System;
- using System.Collections.Concurrent;
- using System.Diagnostics;
- using System.Reflection;
- using System.Runtime.InteropServices;
- using System.Threading;
- using System.Threading.Tasks;
- using BeiJingComService.Infrastructure;
- namespace BeiJingComService.Core
- {
- /// <summary>
- /// 本地首信医保 COM(MedicareCom.Outpatient)通讯网关。
- ///
- /// 会话策略(方案 B:每次读卡 open → 读 → close,用完即关):
- /// 1) COM 实例在 Initialize 时创建一次,进程生命周期内常驻复用,
- /// 绝不在每次调用时 CreateInstance / FinalReleaseComObject,也不做 GC.Collect;
- /// 唯一例外是第 4 条的自愈最后一级(open 连 9008 两次),才销毁重建实例;
- /// 2) 读卡序列开始时按需真实 open,序列结束后由工作线程在"队列空闲达到阈值"时主动 close,
- /// 即用完即关、不再长期独占读卡器;下一次读卡再重新 open,
- /// 从根本上规避长驻会话陈旧后对已打开设备重复 open 触发"打开设备失败(9008)";
- /// 3) 读卡/PSAM 等为独占设备,同一时刻只允许一笔调用进入 COM,
- /// 采用"单 STA 工作线程 + 队列串行"执行,而非加锁。
- /// 4) close 的成败要判定(报文 success + 耗时):没关干净就标记脏会话,
- /// open 撞 9008 时依次"补 close → 重开 → 销毁重建实例再开"自愈,
- /// 避免一次慢 close 导致后续读卡永久 9008(详见 Round43 方案文档)。
- ///
- /// 调用约定(对应 HIS 侧 ObjectClass / CardReader_BJ 的反射调用形态):
- /// func + args[] → 变参 InvokeMember,全部参数按 byref(out)传入;
- /// args 为空时使用 1 个 byref 参数(open/close/Trade/TradeAll 形态);
- /// args 长度为 N 时使用 N 个 byref 参数,返回值取最后一个参数的最终值。
- /// </summary>
- public sealed class ComGateway : IComGateway
- {
- private readonly string _progId;
- private readonly int _defaultTimeoutMs;
- private readonly int _lingerMs;
- /// <summary>close 耗时超过该值即视为「可能没关干净」(正常 6~12ms,实测异常时 3186ms)。</summary>
- private const int CloseSlowThresholdMs = 500;
- /// <summary>设备已被打开的错误码(首信组件返回 state.success=false / error no=9008)。</summary>
- private const string ErrorDeviceAlreadyOpen = "9008";
- /// <summary>
- /// 未插社保卡的错误号(首信 error no=2011 下,0xfffffffe = 未插卡,0xfffffff8 = 通讯错误)。
- /// Round59:两者共用 no=2011,必须按错误号区分,不能按 no 判。
- /// </summary>
- private const string ErrorNoCard = "0xfffffffe";
- /// <summary>
- /// Round59:未插卡(0xfffffffe)返回耗时超过该值即判定读卡器亚健康,主动关闭会话。
- /// 0 = 禁用。取自 AppConfig.NoCardSlowCloseMs,构造时读取一次。
- /// </summary>
- private readonly int _noCardSlowCloseMs;
- private readonly object _sync = new object();
- private Type _comType;
- private object _comInstance;
- private bool _opened;
- private string _lastOpenOutput;
- /// <summary>上次 close 未确认成功(报文失败或耗时异常),设备可能仍被占用;下次 open 前先补一次 close。</summary>
- private volatile bool _sessionDirty;
- /// <summary>open 撞 9008 时是否允许销毁并重建 COM 实例(= 人工「重建网关」的自动化版本)。默认 true。</summary>
- private volatile bool _allowInstanceRecreate = true;
- /// <summary>最近一次 close 的原始报文(显式 close 时原样返回给调用方)。</summary>
- private string _lastCloseOutput;
- private BlockingCollection<WorkItem> _queue;
- private Thread _worker;
- private volatile bool _initialized;
- private volatile bool _faulted;
- private volatile bool _disposed;
- /// <summary>是否允许队列空闲达到阈值后自动 close。true(默认)=用完即关;false=会话常驻不关(keepOpen 测试模式)。</summary>
- private volatile bool _allowIdleClose = true;
- /// <summary>
- /// 上一条请求是否要求保住会话(WorkItem.KeepSession)。
- /// Round49:会话策略从"网关上的全局开关"改成"随请求走的标志",
- /// 空闲关会话的判定改为「上一条请求没要求保活」才关,
- /// 这样 keepOpen 不会再泄漏到 /api/com/invoke 等其它入口,也不会因异常残留。
- /// </summary>
- private volatile bool _lastKeepSession;
- public ComGateway() : this(AppConfig.ComProgId)
- {
- }
- /// <summary>按指定 ProgID 创建网关(用于次要 COM 组件,如中药订单共享 EachCommunicationCom.Outpatient)。</summary>
- public ComGateway(string progId)
- {
- _progId = string.IsNullOrWhiteSpace(progId) ? AppConfig.ComProgId : progId;
- _defaultTimeoutMs = AppConfig.ComTimeoutMs;
- // 队列空闲达到该阈值即主动 close(用完即关);下限 50ms 防止配置为 0 时工作线程空转
- _lingerMs = Math.Max(50, AppConfig.ComIdleTimeoutMs);
- // Round59:慢速未插卡的主动关会话阈值(0 = 禁用本行为)
- _noCardSlowCloseMs = Math.Max(0, AppConfig.NoCardSlowCloseMs);
- }
- public bool IsInitialized
- {
- get { return _initialized; }
- }
- public int PendingCount
- {
- get { return _queue != null ? _queue.Count : 0; }
- }
- public bool IsFaulted
- {
- get { return _faulted; }
- }
- /// <summary>
- /// 是否允许会话在队列空闲达到阈值后自动关闭。
- /// true(默认)= 用完即关(方案 B);false = 会话常驻不关(keepOpen 测试模式,只 Open 一次)。
- /// </summary>
- public bool AllowIdleClose
- {
- get { return _allowIdleClose; }
- set { _allowIdleClose = value; }
- }
- /// <summary>
- /// open 撞 9008(设备已被占用)时,是否允许销毁并重建 COM 实例后再试一次。
- /// 默认 true —— 等价于把人工「重建网关」自动化,是自愈的最后一级。
- /// </summary>
- public bool AllowInstanceRecreate
- {
- get { return _allowInstanceRecreate; }
- set { _allowInstanceRecreate = value; }
- }
- public string ProgId
- {
- get { return _progId; }
- }
- public void Initialize()
- {
- if (_initialized) return;
- lock (_sync)
- {
- if (_initialized) return;
- _comType = Type.GetTypeFromProgID(_progId);
- if (_comType == null)
- {
- throw new InvalidOperationException($"未找到本地 COM 组件: {_progId}。请确认首信医保组件已正确安装注册。");
- }
- // 常驻实例:进程内只创建这一次
- _comInstance = Activator.CreateInstance(_comType);
- if (_comInstance == null)
- {
- throw new InvalidOperationException($"创建 COM 实例失败: {_progId}");
- }
- _opened = false;
- _sessionDirty = false;
- _lastOpenOutput = null;
- _lastCloseOutput = null;
- StartWorker();
- _faulted = false;
- _initialized = true;
- Logger.Info($"COM 网关初始化成功,ProgID={_progId},实例已常驻内存,超时={_defaultTimeoutMs}ms,空闲关会话阈值={_lingerMs}ms(用完即关)");
- }
- }
- public void Reinitialize()
- {
- Logger.Info("COM 网关重新初始化开始");
- StopWorker();
- DisposeComInstance();
- _initialized = false;
- _faulted = false;
- _sessionDirty = false;
- Initialize();
- Logger.Info("COM 网关重新初始化完成");
- }
- public async Task<ComResult> InvokeAsync(string func, string[] args, int timeoutMs = 0, bool keepSession = false)
- {
- if (timeoutMs <= 0) timeoutMs = _defaultTimeoutMs;
- if (!_initialized) return ComResult.Fail(-3, "网关未初始化");
- if (_disposed) return ComResult.Fail(-3, "网关已释放");
- if (string.IsNullOrWhiteSpace(func)) return ComResult.Fail(-4, "COM 方法名为空");
- var item = new WorkItem
- {
- Func = func,
- Args = args,
- KeepSession = keepSession,
- Completion = new TaskCompletionSource<ComResult>()
- };
- try
- {
- _queue.Add(item);
- }
- catch (InvalidOperationException)
- {
- return ComResult.Fail(-3, "网关已停止,无法受理调用");
- }
- catch (Exception ex)
- {
- return ComResult.Fail(-1, "调用入队失败: " + ex.Message);
- }
- var stopwatch = Stopwatch.StartNew();
- Task finished = await Task.WhenAny(item.Completion.Task, Task.Delay(timeoutMs)).ConfigureAwait(false);
- stopwatch.Stop();
- if (!object.ReferenceEquals(finished, item.Completion.Task))
- {
- // 超时:工作线程仍在 COM 内部执行,绝不能重复提交,本次结果作废
- _faulted = true;
- Logger.Error($"COM 调用超时({timeoutMs}ms),方法={func},结果作废,请勿重复提交");
- return new ComResult
- {
- Code = -2,
- Message = $"调用超时({timeoutMs}ms)。请求已提交至 COM,请勿重复提交。",
- ElapsedMs = stopwatch.ElapsedMilliseconds
- };
- }
- try
- {
- ComResult result = await item.Completion.Task.ConfigureAwait(false);
- result.ElapsedMs = stopwatch.ElapsedMilliseconds;
- _faulted = !result.Success;
- return result;
- }
- catch (Exception ex)
- {
- Logger.Error($"COM 调用执行失败,方法={func}", ex);
- return ComResult.Fail(-1, "调用执行失败: " + ex.Message, stopwatch.ElapsedMilliseconds);
- }
- }
- public ComResult Invoke(string func, string[] args, int timeoutMs = 0, bool keepSession = false)
- {
- return InvokeAsync(func, args, timeoutMs, keepSession).GetAwaiter().GetResult();
- }
- public void Dispose()
- {
- if (_disposed) return;
- _disposed = true;
- StopWorker();
- DisposeComInstance();
- _initialized = false;
- Logger.Info("COM 网关已释放");
- }
- // ===================== 工作线程 =====================
- private void StartWorker()
- {
- _queue = new BlockingCollection<WorkItem>();
- _worker = new Thread(WorkerLoop);
- _worker.IsBackground = true;
- _worker.Name = "ComGatewayWorker";
- // 医保 COM/OCX 控件绝大多数要求 STA 单元
- _worker.SetApartmentState(ApartmentState.STA);
- _worker.Start();
- }
- private void WorkerLoop()
- {
- // Round57:CBT 钩子必须装「本线程」—— COM 弹框是这个线程创建的,
- // 装在外层 StartWorker() 等于装在调用方线程上,收不到任何窗口事件。
- // 内部已 try/catch,失败只记日志,不影响读卡。
- DialogTopmostWatcher.InstallForCurrentThread();
- while (true)
- {
- WorkItem item;
- bool got;
- try
- {
- // 带超时等待:超时返回 false 说明队列已空闲,此时主动关会话(用完即关)
- got = _queue.TryTake(out item, _lingerMs);
- }
- catch (ObjectDisposedException) { break; }
- catch (InvalidOperationException) { break; }
- if (got)
- {
- // Round49:会话保活随请求走 —— 只有这一笔要求保活,后续空闲期才不关会话
- _lastKeepSession = item.KeepSession;
- try
- {
- ComResult result = CallNative(item.Func, item.Args);
- item.Completion.TrySetResult(result);
- }
- catch (Exception ex)
- {
- _faulted = true;
- Logger.Error($"COM 底层调用异常,方法={item.Func}", ex);
- item.Completion.TrySetException(ex);
- }
- continue;
- }
- // 队列已停止且取空(或已被 CompleteAdding):退出工作线程
- if (_queue.IsAddingCompleted) break;
- // 空闲达到阈值:在 STA 工作线程上执行 close,释放读卡器。
- // _allowIdleClose=false(诊断面板强制 keepOpen)或上一条请求要求保活时跳过。
- if (_allowIdleClose && !_lastKeepSession) CloseSessionQuietly();
- }
- }
- private void StopWorker()
- {
- if (_queue != null)
- {
- try { _queue.CompleteAdding(); }
- catch (Exception ex) { Logger.Error("关闭调用队列失败", ex); }
- WorkItem pending;
- while (_queue.TryTake(out pending))
- {
- pending.Completion.TrySetException(new InvalidOperationException("网关正在重新初始化,调用已取消"));
- }
- }
- if (_worker != null && _worker.IsAlive)
- {
- if (!_worker.Join(TimeSpan.FromSeconds(5)))
- {
- Logger.Error("COM 工作线程未能在 5 秒内退出");
- }
- }
- // Round57:线程已退出,摘掉装在该线程上的 CBT 钩子并停看门狗。
- // 重新初始化(Reinitialize)后由新的工作线程重新安装。
- DialogTopmostWatcher.Uninstall();
- if (_queue != null)
- {
- _queue.Dispose();
- _queue = null;
- }
- _worker = null;
- }
- // ===================== COM 调用 =====================
- private ComResult CallNative(string func, string[] args)
- {
- // Round57:一笔调用期间允许弹框置顶(钩子 + 看门狗)。结束无论成败都要复位,
- // 否则看门狗会在空闲期白扫;钩子本身不受影响,等下一次调用。
- DialogTopmostWatcher.BeginCall();
- try
- {
- return CallNativeCore(func, args);
- }
- finally
- {
- DialogTopmostWatcher.EndCall();
- }
- }
- private ComResult CallNativeCore(string func, string[] args)
- {
- if (_comType == null || _comInstance == null)
- {
- throw new InvalidOperationException("COM 实例不可用");
- }
- bool isOpen = string.Equals(func, "open", StringComparison.OrdinalIgnoreCase);
- bool isClose = string.Equals(func, "close", StringComparison.OrdinalIgnoreCase);
- if (isOpen)
- {
- return OpenSession();
- }
- if (isClose)
- {
- bool ok = CloseSessionInternal("显式 close", args);
- // 关闭报文原样回给调用方;连报文都没有(调用抛异常)才判失败
- if (ok || _lastCloseOutput != null) return FromOutput(_lastCloseOutput);
- return ComResult.Fail(-1, "关闭读卡设备失败(详见运行日志)");
- }
- // 其它调用:先确保会话可用,再执行真正的调用。
- // 用完不在这里关——由工作线程在队列空闲达到阈值后统一 close(用完即关),
- // 这样同一次读卡序列(类别 + 参保信息两笔)共用一次 open/close。
- ComResult openResult = OpenSession();
- if (!openResult.Success)
- {
- return openResult;
- }
- // ★ OpenSession 里可能已重建过 COM 实例,这里必须重新取字段,否则会用旧句柄
- Type comType = _comType;
- object comInstance = _comInstance;
- if (comType == null || comInstance == null)
- {
- throw new InvalidOperationException("COM 实例不可用");
- }
- var watch = Stopwatch.StartNew();
- string output;
- try
- {
- output = InvokeCom(comType, comInstance, func, args);
- }
- finally
- {
- watch.Stop();
- }
- // Round59:未插卡但返回迟缓 → 读卡器已亚健康,主动关会话,避免残留状态演变成 f8
- TryCloseOnSlowNoCard(func, output, watch.ElapsedMilliseconds);
- return FromOutput(output);
- }
- /// <summary>
- /// 确保 COM 会话可用(方案 B:用完即关)。
- /// 会话由工作线程在队列空闲达到阈值后主动 close,故这里只区分两种情形:
- /// - 已打开 → 直接复用(跳过真实 open,保证同一读卡序列的读卡速度);
- /// - 未打开 → 执行真实 open。
- ///
- /// 打开失败时按三级自愈(Round43):
- /// 第 0 级:上次 close 未确认干净 → 先补一次 close 清理;
- /// 第 1 级:open 撞 9008(设备已被占用)→ close 后重开一次;
- /// 第 2 级:仍 9008 → 销毁并重建 COM 实例后重开(等价人工「重建网关」)。
- /// </summary>
- private ComResult OpenSession()
- {
- if (_opened)
- {
- return new ComResult { Code = 0, Message = "OK", Output = _lastOpenOutput };
- }
- // 第 0 级:上次 close 不干净,先补一次 close 把它抹掉(正常只要 6~12ms)
- if (_sessionDirty)
- {
- Logger.Info("上次会话未确认关闭,open 前先补一次 close 清理");
- CloseSessionInternal("open 前清理", null);
- }
- ComResult result = TryOpenOnce();
- if (result.Success) return result;
- if (!IsDeviceAlreadyOpen(result.Output)) return result;
- // 第 1 级:9008 = 设备已经开着 → close 后再 open 一次
- Logger.Error("open 返回 9008(设备已被占用),执行 close 后重试一次");
- CloseSessionInternal("9008 自愈-close", null);
- result = TryOpenOnce();
- if (result.Success) return result;
- if (!IsDeviceAlreadyOpen(result.Output)) return result;
- // 第 2 级:仍是 9008 → 销毁并重建 COM 实例(把人工「重建网关」自动化)
- if (_allowInstanceRecreate)
- {
- Logger.Error("close 后仍返回 9008,销毁并重建 COM 实例后重试(自愈最后一级)");
- try
- {
- RecreateComInstance();
- }
- catch (Exception ex)
- {
- Logger.Error("重建 COM 实例失败(自愈最后一级)", ex);
- _sessionDirty = true;
- return result;
- }
- result = TryOpenOnce();
- if (result.Success) return result;
- }
- // 三级都失败:标记脏会话,交给下一笔继续清理
- _sessionDirty = true;
- return result;
- }
- /// <summary>
- /// 单次 open:调用 + 成功判定 + 落日志。
- /// 失败结果带 <see cref="ComResult.StageOpen"/> 标记,便于上层区分"设备打不开"与"读卡方法失败"。
- /// </summary>
- private ComResult TryOpenOnce()
- {
- var watch = Stopwatch.StartNew();
- string output = null;
- Exception error = null;
- try
- {
- output = InvokeCom(_comType, _comInstance, "open", null);
- }
- catch (Exception ex)
- {
- error = ex;
- Logger.Error("COM 会话建立异常(open)", ex);
- }
- watch.Stop();
- bool ok = error == null && IsSuccess(output);
- LogSession("open", output, watch.ElapsedMilliseconds, ok);
- if (ok)
- {
- _opened = true;
- _lastOpenOutput = output;
- _sessionDirty = false;
- _faulted = false;
- Logger.Info($"COM 会话已建立(open),耗时={watch.ElapsedMilliseconds}ms");
- return new ComResult { Code = 0, Message = "OK", Output = output };
- }
- _opened = false;
- _lastOpenOutput = null;
- string message = error != null
- ? "打开读卡设备失败(COM 异常):" + error.Message
- : "打开读卡设备失败(" + ExtractErrorNo(output) + "),请检查设备是否被占用或需要重新插拔:" + Summarize(output);
- Logger.Error($"COM 会话建立失败(open),耗时={watch.ElapsedMilliseconds}ms:" + Summarize(output));
- return new ComResult
- {
- Code = -1,
- Stage = ComResult.StageOpen,
- Message = message,
- Output = output
- };
- }
- /// <summary>反射调用 COM 方法:全部参数按 byref 传出,返回值取最后一个参数的最终值。</summary>
- private static string InvokeCom(Type comType, object comInstance, string func, string[] args)
- {
- int count = (args == null || args.Length == 0) ? 1 : args.Length;
- object[] paramArray = new object[count];
- for (int i = 0; i < count; i++)
- {
- paramArray[i] = (args != null && i < args.Length && args[i] != null)
- ? (object)args[i]
- : string.Empty;
- }
- ParameterModifier[] paramMods = new ParameterModifier[1];
- paramMods[0] = new ParameterModifier(count);
- for (int i = 0; i < count; i++)
- {
- paramMods[0][i] = true; // 全部按 byref 传出
- }
- object returnValue = comType.InvokeMember(func,
- BindingFlags.Default | BindingFlags.InvokeMethod,
- null,
- comInstance,
- paramArray,
- paramMods,
- null,
- null);
- object last = paramArray[count - 1];
- if (last != null) return last.ToString();
- return returnValue == null ? string.Empty : returnValue.ToString();
- }
- /// <summary>
- /// Round59:未插卡(0xfffffffe)但耗时超过阈值 → 读卡器响应迟缓,会话已处于亚健康。
- /// 主动 close 让下一次读卡从全新会话开始,避免残留状态演变成 f8。
- ///
- /// 只关会话、不重建实例:重建虽然一定有效,但会重置实例、抹掉现场状态,无法定位根因。
- /// close 失败时由 CloseSessionInternal 置 _sessionDirty,下一笔 open 前补清理,
- /// 仍不行则走既有的 Round43 三级自愈(open 9008 → close → 重建实例)。
- ///
- /// 运行在 STA 工作线程上(CallNativeCore 内),故可安全触碰 COM。
- /// </summary>
- private void TryCloseOnSlowNoCard(string func, string output, long elapsedMs)
- {
- if (_noCardSlowCloseMs <= 0) return;
- if (elapsedMs < _noCardSlowCloseMs) return;
- if (string.IsNullOrEmpty(output)) return;
- if (output.IndexOf(ErrorNoCard, StringComparison.OrdinalIgnoreCase) < 0) return;
- // 会话已经关了就没必要再 close:必返 9009,只会平白污染 _sessionDirty
- if (!_opened) return;
- Logger.Error("[NoCardSlow] 未插卡但响应迟缓(耗时=" + elapsedMs + "ms > "
- + _noCardSlowCloseMs + "ms),主动关闭会话,方法=" + func);
- bool ok = CloseSessionInternal("未插卡超时-自愈", null);
- if (ok)
- {
- Logger.Info("[NoCardSlow] 会话已关闭,下次读卡将重新 open");
- }
- else
- {
- Logger.Info("[NoCardSlow] 会话关闭失败,已标记脏会话,下次 open 前补清理");
- }
- }
- /// <summary>
- /// 队列空闲后关闭会话(用完即关)。运行在 STA 工作线程上,故可安全触碰 COM。
- /// 关闭失败仅记录日志、不抛异常:会话标记为脏,下次 open 前会补一次清理。
- /// </summary>
- private void CloseSessionQuietly()
- {
- if (!_opened) return;
- CloseSessionInternal("空闲关闭", null);
- }
- /// <summary>
- /// 真实的 close:判报文 + 判耗时 + 落日志,并把「没关干净」变成脏会话标记。
- /// 只有报文成功 **且** 耗时正常才认为设备已释放;否则下次 open 前先补一次 close。
- /// 返回报文是否成功(报文都没拿到时返回 false)。
- /// </summary>
- private bool CloseSessionInternal(string reason, string[] args)
- {
- bool ok = false;
- _lastCloseOutput = null;
- if (_comType == null || _comInstance == null)
- {
- _opened = false;
- _sessionDirty = false;
- return true;
- }
- var watch = Stopwatch.StartNew();
- string output = null;
- try
- {
- output = InvokeCom(_comType, _comInstance, "close", args);
- ok = IsSuccess(output);
- }
- catch (Exception ex)
- {
- Logger.Error("COM 会话关闭异常(" + reason + ")", ex);
- }
- watch.Stop();
- LogSession("close", output, watch.ElapsedMilliseconds, ok);
- _opened = false;
- _lastOpenOutput = null;
- _lastCloseOutput = output;
- // ★ 关键:报文失败,或者耗时异常(设备忙)都算「没关干净」
- bool slow = watch.ElapsedMilliseconds > CloseSlowThresholdMs;
- _sessionDirty = !ok || slow;
- if (_sessionDirty)
- {
- Logger.Error("COM 会话关闭未确认(" + reason + "),耗时=" + watch.ElapsedMilliseconds
- + "ms,报文结果=" + (ok ? "成功" : "失败") + ",标记为脏会话,下次 open 前会重新清理:"
- + Summarize(output));
- }
- else
- {
- Logger.Info("COM 会话已关闭(" + reason + "),耗时=" + watch.ElapsedMilliseconds + "ms");
- }
- return ok;
- }
- /// <summary>
- /// 在 STA 工作线程上销毁并重建 COM 实例(自愈最后一级)。
- /// 与人工点「重建网关」等价,但不重启工作线程、不影响在途调用。
- /// </summary>
- private void RecreateComInstance()
- {
- object old = _comInstance;
- _comInstance = null;
- _opened = false;
- _lastOpenOutput = null;
- _lastCloseOutput = null;
- if (old != null && Marshal.IsComObject(old))
- {
- try
- {
- Marshal.FinalReleaseComObject(old);
- }
- catch (Exception ex)
- {
- Logger.Error("释放旧 COM 实例失败(已忽略)", ex);
- }
- }
- Type comType = Type.GetTypeFromProgID(_progId);
- if (comType == null)
- {
- throw new InvalidOperationException("未找到本地 COM 组件: " + _progId);
- }
- _comType = comType;
- _comInstance = Activator.CreateInstance(comType);
- if (_comInstance == null)
- {
- throw new InvalidOperationException("重建 COM 实例失败: " + _progId);
- }
- Logger.Info("COM 实例已重建(自愈): " + _progId);
- }
- /// <summary>
- /// open/close 不走 GatewayHost 的埋点,这里单独把原文补进 *_Trade.log。
- /// 上次事故就是因为查不到 close 报文,只能靠耗时推测设备是否真的关了。
- /// </summary>
- private static void LogSession(string func, string output, long elapsedMs, bool ok)
- {
- try
- {
- TradeLogger.Write(func, string.Empty, output, ok ? 0 : -1, ok ? "OK" : "会话失败", elapsedMs, ok);
- }
- catch
- {
- // 日志失败不影响主流程
- }
- }
- /// <summary>从报文里取 error 的 no 属性(如 9008),取不到返回 "?"。</summary>
- private static string ExtractErrorNo(string xml)
- {
- if (string.IsNullOrEmpty(xml)) return "?";
- int start = xml.IndexOf("<error", StringComparison.OrdinalIgnoreCase);
- if (start < 0) return "?";
- string value = ExtractAttributeValue(xml.Substring(start), "no");
- return string.IsNullOrEmpty(value) ? "?" : value;
- }
- /// <summary>报文是否表示「设备已被打开」(error no=9008)。</summary>
- private static bool IsDeviceAlreadyOpen(string xml)
- {
- return string.Equals(ExtractErrorNo(xml), ErrorDeviceAlreadyOpen, StringComparison.Ordinal);
- }
- /// <summary>取 XML 里某个属性的值(报文可能不规范,故用手写扫描而非 XmlDocument)。</summary>
- private static string ExtractAttributeValue(string xml, string attributeName)
- {
- if (string.IsNullOrEmpty(xml)) return null;
- int searchFrom = 0;
- while (true)
- {
- int index = xml.IndexOf(attributeName, searchFrom, StringComparison.OrdinalIgnoreCase);
- if (index < 0) return null;
- int i = index + attributeName.Length;
- while (i < xml.Length && char.IsWhiteSpace(xml[i])) i++;
- if (i < xml.Length && xml[i] == '=')
- {
- i++;
- while (i < xml.Length && char.IsWhiteSpace(xml[i])) i++;
- if (i < xml.Length && (xml[i] == '"' || xml[i] == '\''))
- {
- char quote = xml[i];
- i++;
- int end = i;
- while (end < xml.Length && xml[end] != quote) end++;
- if (end < xml.Length) return xml.Substring(i, end - i);
- }
- }
- searchFrom = index + attributeName.Length;
- }
- }
- /// <summary>报文里 state 元素用属性 success="true" 表示成功。</summary>
- private static bool IsSuccess(string xml)
- {
- if (string.IsNullOrEmpty(xml)) return false;
- const string attr = "success";
- int searchFrom = 0;
- while (true)
- {
- int index = xml.IndexOf(attr, searchFrom, StringComparison.OrdinalIgnoreCase);
- if (index < 0) return false;
- int i = index + attr.Length;
- while (i < xml.Length && char.IsWhiteSpace(xml[i])) i++;
- if (i < xml.Length && xml[i] == '=')
- {
- i++;
- while (i < xml.Length && char.IsWhiteSpace(xml[i])) i++;
- if (i < xml.Length && (xml[i] == '"' || xml[i] == '\''))
- {
- char quote = xml[i];
- i++;
- int end = i;
- while (end < xml.Length && xml[end] != quote) end++;
- if (end < xml.Length)
- {
- string value = xml.Substring(i, end - i);
- return string.Equals(value, "true", StringComparison.OrdinalIgnoreCase);
- }
- }
- }
- searchFrom = index + attr.Length;
- }
- }
- private static ComResult FromOutput(string output)
- {
- return new ComResult { Code = 0, Message = "OK", Output = output };
- }
- /// <summary>失败时给出便于排查的报文片段(过长则截断)。</summary>
- private static string Summarize(string text)
- {
- if (string.IsNullOrEmpty(text)) return "(无返回报文)";
- const int limit = 300;
- return text.Length > limit ? text.Substring(0, limit) + "...(已截断)" : text;
- }
- private void DisposeComInstance()
- {
- lock (_sync)
- {
- if (_comInstance != null)
- {
- if (_opened)
- {
- try
- {
- object[] paramArray = new object[1] { string.Empty };
- ParameterModifier[] paramMods = new ParameterModifier[1];
- paramMods[0] = new ParameterModifier(1);
- paramMods[0][0] = true;
- _comType.InvokeMember("close",
- BindingFlags.Default | BindingFlags.InvokeMethod,
- null, _comInstance, paramArray, paramMods, null, null);
- }
- catch (Exception ex)
- {
- Logger.Error("释放实例前 close 失败(已忽略)", ex);
- }
- }
- try
- {
- if (Marshal.IsComObject(_comInstance))
- {
- Marshal.FinalReleaseComObject(_comInstance);
- }
- }
- catch
- {
- // 忽略
- }
- _comInstance = null;
- }
- _comType = null;
- _opened = false;
- }
- }
- private sealed class WorkItem
- {
- public string Func;
- public string[] Args;
- /// <summary>true = 这一笔之后不要空闲关会话(只 Open 一次,测试用)。</summary>
- public bool KeepSession;
- public TaskCompletionSource<ComResult> Completion;
- }
- }
- }
|