liufumingren 1dc3404eae fix(osd): 空闲回退写回摄像头名,不再写工作台名
- DesiredText:60 秒没扫到时还原成**摄像头自己的名字**(摄像头没名字才退回工作台名,
  避免把通道名写空)
- 配置里被移除的摄像头同样还原成摄像头名
- 同步注释与文档(桌面 README / 根 README / 后端接口注释)
- 实测(真实 NVR 通道 35/37):首次="测试A/测试B"、扫码="测试A 7734… / 测试B 7734…"、
  70 秒后回退="测试A/测试B",三个阶段的并行时间差 50~103ms

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-01 06:55:07 +08:00

94 lines
3.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Text;
using YuncangTrace.LocalService.Services.Hik;
namespace YuncangTrace.LocalService.Services.Scan;
/// <summary>
/// OSD 文本拼装(录像机通道名,GBK,最多 <see cref="MaxBytes"/> 字节)。
///
/// 现场要求:扫到运单号后,把「摄像头名 + 空格 + 运单号」写到该工作台所有摄像头的 OSD;
/// 没扫码时还原成**摄像头自己的名字**。设备只认 GBK 且字段只有 31 字节——
/// **运单号必须完整**(它才是取证要看的),所以超长时先压摄像头名,压完还超才截运单号。
/// </summary>
internal static class OsdText
{
/// <summary>通道名字段 32 字节,留 1 字节给结尾 \0</summary>
internal const int MaxBytes = HikSdk.ChannelNameMaxBytes;
/// <summary>
/// 拼「摄像头名 + 运单号」。设备上看到的示例:<c>2号线面单 SF1164748936737</c>。
/// </summary>
internal static string Combine(string? cameraName, string? code)
{
var name = Clean(cameraName);
var number = Clean(code);
if (number.Length == 0) return TruncateGbk(name, MaxBytes);
if (name.Length == 0) return TruncateGbk(number, MaxBytes);
var full = $"{name} {number}";
if (GbkLength(full) <= MaxBytes) return full;
// 先保运单号:给摄像头名留出剩余空间(至少 1 个汉字 = 2 字节才值得留)
var budget = MaxBytes - GbkLength(number) - 1;
if (budget >= 2)
{
var prefix = TruncateGbk(name, budget);
if (prefix.Length > 0) return $"{prefix} {number}";
}
// 运单号本身就把字段占满了(极少见):只能截断它
return TruncateGbk(number, MaxBytes);
}
/// <summary>按 GBK 字节数截断,**不切断汉字**(切断会变成 `?`)</summary>
internal static string TruncateGbk(string? text, int maxBytes)
{
var value = text ?? string.Empty;
if (value.Length == 0 || maxBytes <= 0) return string.Empty;
if (GbkLength(value) <= maxBytes) return value;
var builder = new StringBuilder(value.Length);
var used = 0;
foreach (var ch in value)
{
if (char.IsSurrogate(ch)) continue;
var bytes = GbkLength(ch.ToString());
if (used + bytes > maxBytes) break;
builder.Append(ch);
used += bytes;
}
return builder.ToString().TrimEnd();
}
/// <summary>去掉换行/控制字符(设备上会显示成方块),并把连续空格压成一个</summary>
internal static string Clean(string? text)
{
if (string.IsNullOrWhiteSpace(text)) return string.Empty;
var builder = new StringBuilder(text.Length);
var lastSpace = true; // 开头的空格不要
foreach (var ch in text)
{
var normalized = char.IsControl(ch) ? ' ' : ch;
if (normalized == ' ')
{
if (lastSpace) continue;
lastSpace = true;
builder.Append(' ');
continue;
}
lastSpace = false;
builder.Append(normalized);
}
return builder.ToString().Trim();
}
internal static int GbkLength(string? text) => HikSdk.EncodeGbk(text).Length;
}