packServer/desktop/Services/SingleInstance.cs
liufumingren f8aa4c4899 feat(工作台): 成员扫码登入、面单摄像头与虚拟通道
- 工作台成员扫码登入:workstation_login_records 记录谁在什么时候登入/下线了哪台工作台,
  超时(团购 1h / 散单 30min)由 schedule/workstation_idle_offline 自动下线;
  运单查询的 packers 取当时的登入成员
- 面单摄像头识别:workstation_cameras.is_label_camera + service/label_scan 下发本机该跑的识别配置,
  设备端(桌面端 LabelScan 工作线程)按配置做面单识别并上报
- 虚拟通道 CAM-<工作台id>:工作台没接扫码枪时,面单摄像头那一路顶替扫码枪上报,records 规则按 ws_type 区分
- 桌面端:新增 LabelScanMonitor/LabelScanWorker/ScanDeviceKind 与面单预览页,扫描通道支持改名,静默窗口 5s

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-29 17:19:24 +08:00

133 lines
4.5 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Text;
using System.Threading;
namespace YuncangTrace.LocalService.Services;
/// <summary>
/// 单实例 + 参数转发(命名管道)
///
/// 场景:窗口已经开着,用户又点了一次 WMS 页面上的「查看打包视频」→ 系统按协议再启动一次本程序。
/// 这时第二个实例**不应该**去抢 17300 端口,而是把 `yuncang://open?code=xxx` 通过管道送给第一个实例,
/// 由它把窗口激活并查询那个运单号。
/// </summary>
public sealed class SingleInstance : IDisposable
{
/// <summary>第二个实例「只想把界面叫出来」(双击快捷方式,没带任何参数)</summary>
public const string ShowCommand = "--show";
private readonly Mutex _mutex;
private readonly string _pipeName;
private readonly Action<string[]> _onArgs;
private readonly CancellationTokenSource _cts = new();
private readonly bool _ownsMutex;
/// <summary>本次是否是第一个实例(不是的话调用 <see cref="SendArgs"/> 后就可以退出了)</summary>
public bool IsFirstInstance { get; }
public SingleInstance(string name, Action<string[]> onArgs)
{
_onArgs = onArgs;
_pipeName = $"{name}.pipe";
// 全局命名互斥体:跨会话也能认出来(同一个用户下就够了,用 Local\ 前缀)
_mutex = new Mutex(initiallyOwned: true, $@"Local\{name}.mutex", out var createdNew);
_ownsMutex = createdNew;
IsFirstInstance = createdNew;
}
/// <summary>第一个实例调用:开一个后台线程等第二个实例送参数过来</summary>
public void StartListening()
{
var thread = new Thread(ListenLoop)
{
IsBackground = true,
Name = "single-instance-pipe",
};
thread.Start();
}
/// <summary>
/// 第二个实例调用:把命令行参数送给已运行的实例。
/// 返回 false = 送不出去(常见原因:第一个实例是**管理员权限**,中完整性的第二个实例写不进它的管道)。
///
/// ⚠️ 没有参数(双击快捷方式)也要送一条 <see cref="ShowCommand"/>:以前这里直接 return true 什么都不发,
/// 第二个实例紧接着就退出 → 用户看到的就是「点图标没反应,主界面打不开」。
/// </summary>
public bool SendArgs(string[] args)
{
var payload = args is { Length: > 0 } ? args : new[] { ShowCommand };
try
{
using var client = new NamedPipeClientStream(".", _pipeName, PipeDirection.Out);
client.Connect(1500);
using var writer = new StreamWriter(client, new UTF8Encoding(false)) { AutoFlush = true };
foreach (var arg in payload) writer.WriteLine(arg);
return true;
}
catch (Exception ex)
{
// 以前这里静默吞掉 → 用户看到的就是“唤起没反应”;现在返回给调用方提示
AppLog.Write($"[single] 参数转发失败(第一个实例可能是管理员权限):{ex.Message}");
return false;
}
}
private void ListenLoop()
{
while (!_cts.IsCancellationRequested)
{
try
{
using var server = new NamedPipeServerStream(
_pipeName, PipeDirection.In, NamedPipeServerStream.MaxAllowedServerInstances,
PipeTransmissionMode.Byte, PipeOptions.None);
server.WaitForConnection();
var args = new List<string>();
using (var reader = new StreamReader(server, new UTF8Encoding(false)))
{
string? line;
while ((line = reader.ReadLine()) is not null)
{
if (line.Length > 0) args.Add(line);
}
}
if (args.Count > 0) _onArgs(args.ToArray());
}
catch (Exception)
{
if (_cts.IsCancellationRequested) return;
Thread.Sleep(200);
}
}
}
public void Dispose()
{
_cts.Cancel();
if (_ownsMutex)
{
try
{
_mutex.ReleaseMutex();
}
catch (ApplicationException)
{
// 不持有互斥体(理论上不会发生)
}
}
_mutex.Dispose();
_cts.Dispose();
}
}