Files
fpcollect/agent/Program.cs
T

323 lines
14 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.Collections.Concurrent;
using System.Net.WebSockets;
using System.Text.Json;
using FpCollect.Agent.Analysis;
using FpCollect.Agent.Capture;
using FpCollect.Agent.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
var config = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json", optional: true)
.AddEnvironmentVariables()
.Build();
var sdkDir = config["SdkDir"] ?? @"C:\Program Files (x86)\FingerTest";
var dbFile = string.IsNullOrWhiteSpace(config["DbFile"])
? Path.Combine(AppContext.BaseDirectory, "fpcollect.db")
: config["DbFile"]!;
var db = new Db(dbFile);
var capture = new CaptureService(sdkDir);
// ── 令牌持久化:进程重启后浏览器会话不掉线(record 可正常 JSON 序列化) ──
var tokenFile = Path.Combine(AppContext.BaseDirectory, "tokens.json"); // TokUser 定义见文件末尾
Dictionary<string, TokUser>? loaded = null;
try { loaded = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, TokUser>>(File.Exists(tokenFile) ? File.ReadAllText(tokenFile) : "{}"); } catch { }
var tokens = new ConcurrentDictionary<string, TokUser>(loaded ?? new Dictionary<string, TokUser>());
void SaveTokens() => File.WriteAllText(tokenFile, System.Text.Json.JsonSerializer.Serialize(tokens.ToDictionary(k => k.Key, v => v.Value)));
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseUrls(config["Urls"] ?? "http://0.0.0.0:5090");
builder.Services.AddCors(o => o.AddDefaultPolicy(p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
// WebSocket 遥测 JSON 用 camelCase(与前端字段约定一致)
var wsJsonOpts = new System.Text.Json.JsonSerializerOptions
{
PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase
};
var app = builder.Build();
app.UseCors();
app.UseWebSockets();
// 静态文件明确绑定 exe 旁的 wwwroot,避免受启动工作目录影响
var webRoot = Path.Combine(AppContext.BaseDirectory, "wwwroot");
var fileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(webRoot);
app.UseDefaultFiles(new Microsoft.AspNetCore.Builder.DefaultFilesOptions { FileProvider = fileProvider });
app.UseStaticFiles(new Microsoft.AspNetCore.Builder.StaticFileOptions { FileProvider = fileProvider });
TokUser? Auth(HttpContext ctx)
{
var t = ctx.Request.Headers.Authorization.FirstOrDefault()?.Replace("Bearer ", "");
return t is not null && tokens.TryGetValue(t, out var v) ? v : null;
}
static async Task<Dictionary<string, object?>> ReadJson(HttpContext ctx)
{
using var reader = new StreamReader(ctx.Request.Body);
var txt = await reader.ReadToEndAsync();
if (string.IsNullOrWhiteSpace(txt)) return new();
return JsonSerializer.Deserialize<Dictionary<string, object?>>(txt) ?? new();
}
static string Str(Dictionary<string, object?> d, string key)
=> d.TryGetValue(key, out var v) && v is JsonElement e
? (e.ValueKind == JsonValueKind.String ? e.GetString() ?? "" : e.ToString())
: "";
// 解析 {"ridges":[10个0-40的整数]}(下标 0-9 = 左手拇指…右手小指);
// 长度/取值不合法或全 0(无法计算强度)返回 null
static int[]? ParseRidges(Dictionary<string, object?> d)
{
if (!d.TryGetValue("ridges", out var v) || v is not JsonElement e
|| e.ValueKind != JsonValueKind.Array || e.GetArrayLength() != 10)
return null;
var r = new int[10];
for (var i = 0; i < 10; i++)
if (e[i].ValueKind != JsonValueKind.Number || !e[i].TryGetInt32(out r[i]) || r[i] < 0 || r[i] > 40)
return null;
return r.Sum() > 0 ? r : null;
}
// ── authUser ────────────────────────────────────────────────
app.MapPost("/api/login", async (HttpContext ctx) =>
{
var body = await ReadJson(ctx);
var r = db.Login(Str(body, "name"), Str(body, "pwd"));
if (r is null) return Results.Json(new { ok = false, msg = "验证用户失败,无法登录!" });
var token = Convert.ToHexString(Guid.NewGuid().ToByteArray());
tokens[token] = new TokUser(Str(body, "name"), r.Value.level);
SaveTokens();
return Results.Json(new
{
ok = true,
token,
level = r.Value.level,
role = r.Value.level == 0 ? "录入和数据处理" : "录入"
});
});
// ── 设备状态/控制 ────────────────────────────────────────────
app.MapGet("/api/device", (HttpContext ctx) =>
{
if (Auth(ctx) is null) return Results.Unauthorized();
return Results.Json(capture.GetInfo());
});
app.MapPost("/api/capture/start", async (HttpContext ctx) =>
{
if (Auth(ctx) is null) return Results.Unauthorized();
var body = await ReadJson(ctx);
if (body.TryGetValue("rollMode", out var rm) && rm is JsonElement je)
capture.RollMode = je.ValueKind == JsonValueKind.True || (je.ValueKind == JsonValueKind.False && je.GetBoolean());
var err = capture.Start();
return Results.Json(string.IsNullOrEmpty(err)
? new { ok = true, device = capture.DeviceInfo }
: new { ok = false, msg = err });
});
app.MapPost("/api/capture/stop", (HttpContext ctx) =>
{
if (Auth(ctx) is null) return Results.Unauthorized();
capture.Stop();
return Results.Json(new { ok = true });
});
app.MapPost("/api/capture/rollmode", async (HttpContext ctx) =>
{
if (Auth(ctx) is null) return Results.Unauthorized();
var body = await ReadJson(ctx);
if (body.TryGetValue("rollMode", out var rm) && rm is JsonElement je)
capture.RollMode = je.ValueKind == JsonValueKind.True;
return Results.Json(new { ok = true, rollMode = capture.RollMode });
});
// 对应原版"采集下一张":取最近一帧 PNG → Base64(=原版 photodata)
app.MapGet("/api/capture/snapshot", (HttpContext ctx) =>
{
if (Auth(ctx) is null) return Results.Unauthorized();
var png = capture.Snapshot();
return png is null
? Results.Json(new { ok = false, msg = "尚未采集到帧(先开始采集)" })
: Results.Json(new { ok = true, imageB64 = Convert.ToBase64String(png) });
});
// 拍帧 → 自动纹型分类 + 嵴线计数(FpClassifier:方向场/Poincaré/斗箕弓)
app.MapGet("/api/capture/classify", (HttpContext ctx) =>
{
if (Auth(ctx) is null) return Results.Unauthorized();
var png = capture.Snapshot();
if (png is null) return Results.Json(new { ok = false, msg = "尚未采集到帧(先开始采集)" });
using var ms = new MemoryStream(png);
using var bmp = new System.Drawing.Bitmap(ms);
int w = bmp.Width, h = bmp.Height;
var gray = new byte[w * h];
var rect = new System.Drawing.Rectangle(0, 0, w, h);
var bd = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly,
System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
try
{
for (int y = 0; y < h; y++)
System.Runtime.InteropServices.Marshal.Copy(new IntPtr(bd.Scan0.ToInt64() + y * bd.Stride), gray, y * w, w);
}
finally { bmp.UnlockBits(bd); }
var r = FpCollect.Agent.Analysis.FpClassifier.Classify(gray, w, h);
return r is null
? Results.Json(new { ok = false, msg = "无法识别(图像质量不足)" })
: Results.Json(new { ok = true, pattern = r.Pattern, ridgeCount = r.RidgeCount, coreX = r.CoreX, coreY = r.CoreY, notes = r.Notes });
});
// ── 订单 ────────────────────────────────────────────────────
app.MapGet("/api/orders", (HttpContext ctx) =>
{
if (Auth(ctx) is null) return Results.Unauthorized();
return Results.Json(new
{
ok = true,
orders = db.QueryOrders(ctx.Request.Query["q"], ctx.Request.Query["phone"])
});
});
app.MapPost("/api/orders", async (HttpContext ctx) =>
{
if (Auth(ctx) is null) return Results.Unauthorized();
var body = await ReadJson(ctx);
var id = db.CreateOrder(Str(body, "orderNo"), Str(body, "username"), Str(body, "sex"), Str(body, "birth"));
return Results.Json(new { ok = true, id });
});
app.MapGet("/api/orders/{id:long}", (long id, HttpContext ctx) =>
{
if (Auth(ctx) is null) return Results.Unauthorized();
return Results.Json(new { ok = true, images = db.GetImages(id, withData: true) });
});
app.MapPost("/api/orders/{id:long}/images", async (long id, HttpContext ctx) =>
{
if (Auth(ctx) is null) return Results.Unauthorized();
var body = await ReadJson(ctx);
var items = new List<(int, int, string)>();
if (body.TryGetValue("images", out var arr) && arr is JsonElement je && je.ValueKind == JsonValueKind.Array)
{
foreach (var it in je.EnumerateArray())
{
var ft = it.GetProperty("fingerType").GetInt32();
var num = it.GetProperty("imageNum").GetInt32();
var b64 = it.GetProperty("imageB64").GetString() ?? "";
items.Add((ft, num, b64));
}
}
var n = db.UpsertImages(id, items);
return Results.Json(new { ok = true, saved = n, msg = $"指纹信息上传成功!({n} 张)" });
});
// ── 纹式测评:十指嵴线计数 → 生成报告 ──────────────────────
app.MapPost("/api/orders/{id:long}/ridges", async (long id, HttpContext ctx) =>
{
if (Auth(ctx) is null) return Results.Unauthorized();
var order = db.GetOrder(id);
if (order is null) return Results.Json(new { ok = false, msg = "订单不存在" });
var body = await ReadJson(ctx);
var ridges = ParseRidges(body);
if (ridges is null)
return Results.Json(new { ok = false, msg = "嵴线计数格式错误:需 10 个 0-40 的整数(依次为左手拇指…右手小指),且总和大于 0" });
db.UpsertRidges(id, ridges);
var report = DermEngine.Build(ridges, order.Value.username, order.Value.orderNo, order.Value.sex, order.Value.birth);
db.SaveReport(id, JsonSerializer.Serialize(report));
return Results.Json(new { ok = true, report });
});
app.MapGet("/api/orders/{id:long}/report", (long id, HttpContext ctx) =>
{
if (Auth(ctx) is null) return Results.Unauthorized();
var json = db.GetReport(id);
return json is null
? Results.Json(new { ok = false, msg = "该订单尚未生成测评报告" })
: Results.Json(new { ok = true, report = JsonDocument.Parse(json).RootElement });
});
// 实时预览:query 传 r0..r9,不落库(给前端调值用)
app.MapGet("/api/orders/{id:long}/report/preview", (long id, HttpContext ctx) =>
{
if (Auth(ctx) is null) return Results.Unauthorized();
var order = db.GetOrder(id);
if (order is null) return Results.Json(new { ok = false, msg = "订单不存在" });
var ridges = new int[10];
for (var i = 0; i < 10; i++)
if (!int.TryParse(ctx.Request.Query[$"r{i}"], out ridges[i]) || ridges[i] < 0 || ridges[i] > 40)
return Results.Json(new { ok = false, msg = $"参数 r{i} 无效:需 0-40 的整数" });
if (ridges.Sum() <= 0)
return Results.Json(new { ok = false, msg = "嵴线计数总和必须大于 0" });
return Results.Json(new
{
ok = true,
report = DermEngine.Build(ridges, order.Value.username, order.Value.orderNo, order.Value.sex, order.Value.birth)
});
});
// ── WebSocket 实时画面(对应原版 picbox.Image = fingertmpb) ─
app.Map("/ws", async ctx =>
{
if (!ctx.WebSockets.IsWebSocketRequest) { ctx.Response.StatusCode = 400; return; }
using var ws = await ctx.WebSockets.AcceptWebSocketAsync();
void Send(byte[] jpeg)
{
try
{
if (ws.State == WebSocketState.Open)
ws.SendAsync(jpeg, WebSocketMessageType.Binary, true, CancellationToken.None);
}
catch { }
}
capture.OnFrame += Send;
void SendTelemetry(FpCollect.Agent.Capture.CaptureService.Telemetry t)
{
try
{
if (ws.State == WebSocketState.Open)
{
var json = System.Text.Encoding.UTF8.GetBytes(
System.Text.Json.JsonSerializer.Serialize(t, wsJsonOpts));
ws.SendAsync(json, WebSocketMessageType.Text, true, CancellationToken.None);
}
}
catch { }
}
capture.OnTelemetry += SendTelemetry;
try
{
var buf = new byte[4096];
while (ws.State == WebSocketState.Open)
{
var r = await ws.ReceiveAsync(new ArraySegment<byte>(buf), CancellationToken.None);
if (r.MessageType == WebSocketMessageType.Close) break;
}
}
finally { capture.OnFrame -= Send; capture.OnTelemetry -= SendTelemetry; }
});
// ── 开机自动恢复采集(带重试:崩溃后驱动句柄释放需要几秒) ──
if (string.IsNullOrEmpty(config["AutoStartCapture"]) || config["AutoStartCapture"] == "true")
{
_ = Task.Run(async () =>
{
for (var i = 1; i <= 5; i++)
{
var err = capture.Start();
if (string.IsNullOrEmpty(err))
{
Console.WriteLine($"AutoStartCapture: 已启动 {capture.DeviceInfo}");
return;
}
Console.WriteLine($"AutoStartCapture 第{i}次尝试失败: {err}");
await Task.Delay(3000);
}
Console.WriteLine("AutoStartCapture: 5 次重试均失败,等待手动启动");
});
}
app.Run();
/// <summary>令牌载体(record 供 tokens.json 持久化序列化)。</summary>
public sealed record TokUser(string Name, int Level);