// See https://aka.ms/new-console-template for more information using HardwareControl.Core.HardwareServiceImpl; using HardwareControl.Core.HardwareServiceImpl.HardwareService; using HardwareControl.Core.UsbCamera; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; var host = Host.CreateDefaultBuilder(args) .ConfigureServices(services => { services.Configure(opt => { opt.DeviceNameKeyword = null; // 取第一个相机 opt.PreferredFormatKeyword = "MJPG"; // 找不到就回退第一个 opt.ReconnectBaseDelayMs = 1000; opt.ReconnectMaxDelayMs = 10_000; }); services.AddSingleton(); services.AddLogging(b => b.AddConsole()); }) .Build(); var service = host.Services.GetRequiredService(); service.StatusChanged += (_, e) => Console.WriteLine($"[状态] 已连接={e.IsConnected},{e.Message}"); var frameCount = 0; service.FrameArrived += async (_, e) => { frameCount++; Console.WriteLine( $"收到帧 #{e.FrameIndex},{e.Width}x{e.Height} {e.Format.PixelFormat} {e.MimeType}," + $"大小 {e.ImageData.Length} 字节," + $"相对时间 {e.Timestamp:mm\\:ss\\.fff},绝对时间 {e.CapturedAt:HH:mm:ss.fff}"); if (frameCount <= 5) { var extension = e.MimeType switch { "image/png" => "png", "image/bmp" => "bmp", _ => "jpg", }; var path = Path.Combine( AppContext.BaseDirectory, $"frame_{frameCount}.{extension}"); await File.WriteAllBytesAsync(path, e.ImageData); Console.WriteLine($"已保存:{path}"); } }; await service.ConnectAsync(); Console.WriteLine("已连接。按回车断开并退出。"); Console.ReadLine(); await service.DisconnectAsync();