使用 Digital Persona U.are.U 4500 读取器采集指纹。如何在Windows服务中检测设备并捕获指纹图像?

问题描述 投票:0回答:1

我正在尝试使用 Topshelf 在 Windows 服务中使用数字角色 U.are.U 4500,该服务目前在控制台中运行良好,但当我尝试将其安装为 Windows 中的服务时,它不起作用,我什至无法获取读者或捕获并保存图像。我使用 4500 U.are.U 3.2.0.89 驱动程序

Program.cs

using System;
using System.Drawing.Imaging;
using System.Drawing;
using DPUruNet;
using DPXUru;
using System.Threading;
using Topshelf;
using DigitalPersonaConsole;
using log4net;
//Am using 4500 U.are.U 3.2.0.89 driver
namespace FingerprintReaderApp 
{
    class Program 
    {
        private static readonly ILog _log = LogManager.GetLogger(typeof(Program));
  
    static void Main(string[] args)
{


                  HostFactory.Run(x =>
                {
                   // x.DependsOn("DpHost");
                    x.Service<MyService>(s =>
                    {
                        s.ConstructUsing(service => new MyService());
                        s.WhenStarted(service => service.Start());
                        s.WhenStopped(service => service.Stop());

                    });
                    x.RunAsLocalSystem();
                    x.SetServiceName("DigitalPersonaService");
                    x.SetDisplayName("Digital Persona Service");
                    x.SetDescription("This is Digital persona service test");
                });
             




}


    }
}

然后是我的服务文件:MyService.cs

using DPUruNet;
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FingerprintReaderApp;
using log4net;

namespace DigitalPersonaConsole
{
    public class MyService
    {
        private readonly ILog _log = LogManager.GetLogger(typeof(MyService));


        public Thread thread = null;

        public Reader currentReader;


        private ManualResetEventSlim fingerprintCapturedEvent = new ManualResetEventSlim(false);



        public MyService() {
            thread = new Thread(new ThreadStart(initService));
        }
        public void Start()
        {
            _log.Info("Start service....");
            thread.Start();
            ////
        }

        public void Stop()
        {

            _log.Info("Stop service....");
            thread.Join();
            ////
        }

        public void initService()
        {
            // Finger print reader index 
            int selectedReader = 1; 
            // Initialize the reader
            var readers = ReaderCollection.GetReaders();
            _log.Info($"No of connceted readers: {readers.Count}");
            currentReader = readers[selectedReader];
            ///////////////////////////////////////////////
            foreach (Reader reader in readers)
            {
                _log.Info(reader.Description.SerialNumber);

            }
            if (!OpenReader(currentReader))
            {
                //this.Close();
            }

            if (!StartCaptureAsync(OnCaptured))
            {
                //this.Close();
            }
            fingerprintCapturedEvent.Wait();
        }
        public bool OpenReader(Reader currentReader)
        {
            Constants.ResultCode result = Constants.ResultCode.DP_DEVICE_FAILURE;
            // Open reader
            result = currentReader.Open(Constants.CapturePriority.DP_PRIORITY_EXCLUSIVE);
            if (result != Constants.ResultCode.DP_SUCCESS)
            {
                _log.Info("Error:  " + result);
                return false;
            }

            return true;
        }


        public void OnCaptured(CaptureResult captureResult)
        {
            // _log.Info($"Finger print captured:::::");
            try
            {
                // Check capture quality and throw an error if bad.
                if (!CheckCaptureResult(captureResult)) return;

                // Create bitmap
                foreach (Fid.Fiv fiv in captureResult.Data.Views)
                {
                    _log.Info($"Finger print captured:::::");
                    string outputPath = "fingerprint.bmp";
                    Bitmap bmp = CreateBitmap(fiv.RawImage, fiv.Width, fiv.Height);
                    //SendMessage(Action.SendBitmap, bmp);
                    bmp.Save(outputPath, ImageFormat.Bmp);
                }
            }
            catch (Exception ex)
            {
                // Send error message, then close form
                // SendMessage(Action.SendMessage,

                _log.Info("Error:  " + ex.Message);
            }
        }



        public bool CheckCaptureResult(CaptureResult captureResult)
        {
            if (captureResult.Data == null || captureResult.ResultCode != Constants.ResultCode.DP_SUCCESS)
            {
                if (captureResult.ResultCode != Constants.ResultCode.DP_SUCCESS)
                {
                    throw new Exception(captureResult.ResultCode.ToString());
                }

                // Send message if quality shows fake finger
                if ((captureResult.Quality != Constants.CaptureQuality.DP_QUALITY_CANCELED))
                {
                    throw new Exception("Quality - " + captureResult.Quality);
                }
                return false;
            }
            return true;
        }



        public bool CaptureFingerAsync()
        {
            try
            {
                GetStatus();

                Constants.ResultCode captureResult = currentReader.CaptureAsync(Constants.Formats.Fid.ANSI, Constants.CaptureProcessing.DP_IMG_PROC_DEFAULT, currentReader.Capabilities.Resolutions[0]);
                if (captureResult != Constants.ResultCode.DP_SUCCESS)
                {
                    throw new Exception("" + captureResult);
                }

                return true;
            }
            catch (Exception ex)
            {
                _log.Info("Error:  " + ex.Message);
                return false;
            }
        }


        public Bitmap CreateBitmap(byte[] bytes, int width, int height)
        {
            byte[] rgbBytes = new byte[bytes.Length * 3];

            for (int i = 0; i <= bytes.Length - 1; i++)
            {
                rgbBytes[(i * 3)] = bytes[i];
                rgbBytes[(i * 3) + 1] = bytes[i];
                rgbBytes[(i * 3) + 2] = bytes[i];
            }
            Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);

            BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);

            for (int i = 0; i <= bmp.Height - 1; i++)
            {
                IntPtr p = new IntPtr(data.Scan0.ToInt64() + data.Stride * i);
                System.Runtime.InteropServices.Marshal.Copy(rgbBytes, i * bmp.Width * 3, p, bmp.Width * 3);
            }

            bmp.UnlockBits(data);

            return bmp;
        }


        public bool StartCaptureAsync(Reader.CaptureCallback OnCaptured)
        {
            // Activate capture handler
            currentReader.On_Captured += new Reader.CaptureCallback(OnCaptured);

            // Call capture
            if (!CaptureFingerAsync())
            {
                return false;
            }

            return true;
        }


        public void GetStatus()
        {
            Constants.ResultCode result = currentReader.GetStatus();

            if ((result != Constants.ResultCode.DP_SUCCESS))
            {
                throw new Exception("" + result);
            }

            if ((currentReader.Status.Status == Constants.ReaderStatuses.DP_STATUS_BUSY))
            {
                Thread.Sleep(50);
            }
            else if ((currentReader.Status.Status == Constants.ReaderStatuses.DP_STATUS_NEED_CALIBRATION))
            {
                currentReader.Calibrate();
            }
            else if ((currentReader.Status.Status != Constants.ReaderStatuses.DP_STATUS_READY))
            {
                throw new Exception("Reader Status - " + currentReader.Status.Status);
            }
        }




        public void CancelCaptureAndCloseReader(Reader.CaptureCallback OnCaptured)
        {
            if (currentReader != null)
            {
                currentReader.CancelCapture();

                // Dispose of reader handle and unhook reader events.
                currentReader.Dispose();

                //if (reset)
                // {
                /// CurrentReader = null;
                //  }
            }
        }


    }
}
c# topshelf digital-persona-sdk
1个回答
0
投票
I looked at your publication and based on your code I gave myself the task of making the code you need.
If you like, you can use it as a base for your own system or perhaps objectives.

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
using DPUruNet;  // Ensure this library is compatible with .NET Core
using System.Drawing.Imaging;
using System.Drawing;
using Microsoft.Extensions.DependencyInjection;
using static Program;

public class Program
{
    // Entry point of the application
    public static async Task Main(string[] args)
    {
        // Build and configure the host
        var host = CreateHostBuilder(args).Build();

        // Get the required services from the service container
        var captureService = host.Services.GetRequiredService<FingerprintCaptureService>();
        var validateService = host.Services.GetRequiredService<FingerprintValidateService>();

        // Print welcome message and show the main menu
        Console.WriteLine("Welcome to the Fingerprint Management System.");
        await Task.Run(() => MainMenu(captureService, validateService));

        // Run the host to start the services
        await host.RunAsync();
    }

    // Configure the host builder for dependency injection and logging
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                // Register fingerprint services with scoped and hosted service types
                services.AddScoped<FingerprintCaptureService>();
                services.AddHostedService<FingerprintCaptureService>();
                services.AddScoped<FingerprintValidateService>();
                services.AddHostedService<FingerprintValidateService>();
            })
            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.AddConsole();
            });

    // Main menu for selecting operations
    static void MainMenu(FingerprintCaptureService captureService, FingerprintValidateService validateService)
    {
        while (true)
        {
            Console.WriteLine("Select an option by number:");
            Console.WriteLine("\nMain Menu:");
            Console.WriteLine("1. Capture Fingerprints");
            Console.WriteLine("2. Validate Fingerprints");
            Console.WriteLine("ESC. Exit");
            Console.Write("Select an option: ");

            var key = Console.ReadKey(true);
            switch (key.Key)
            {
                case ConsoleKey.D1:
                case ConsoleKey.NumPad1:
                    SubMenu(captureService, "capture");
                    break;
                case ConsoleKey.D2:
                case ConsoleKey.NumPad2:
                    SubMenu(validateService, "validation");
                    break;
                case ConsoleKey.Escape:
                    return;
            }
        }
    }
    // Sub-menu for specific service operations
    public static void SubMenu(IBaseFingerprintService service, string action)
    {
        while (true)
        {
            Console.WriteLine($"\nMenu for {action} of fingerprints:");
            Console.WriteLine("S. Start service");
            Console.WriteLine("D. Stop service");
            Console.WriteLine("ESC. Return");
            Console.Write("Select an option: ");

            var key = Console.ReadKey(true);
            switch (key.Key)
            {
                case ConsoleKey.S:
                    service.IniciarServicio();
                    Console.WriteLine("The " + action + " service has been started.");
                    break;
                case ConsoleKey.D:
                    service.DetenerServicio();
                    Console.WriteLine("The " + action + " service has been stopped.");
                    break;
                case ConsoleKey.Escape:
                    return;
            }
        }
    }
}

// Interface to define common service operations
public interface IBaseFingerprintService
{
    void IniciarServicio();
    void DetenerServicio();
}

// Fingerprint capture service implementation
public class FingerprintCaptureService : BackgroundService, IBaseFingerprintService
{
    private readonly ILogger<FingerprintCaptureService> _logger;
    private ManualResetEventSlim shutdownSignal = new ManualResetEventSlim(false);
    private ManualResetEventSlim captureSignal = new ManualResetEventSlim(false);
    private CaptureDP captureHandler;

    // Constructor initializes the service with a logger and a capture handler
    public FingerprintCaptureService(ILogger<FingerprintCaptureService> logger)
    {
        _logger = logger;
        captureHandler = new CaptureDP();
    }

    // Main execution loop of the service, handles service shutdown and operation
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Fingerprint Reader Service running.");
        stoppingToken.Register(() => shutdownSignal.Set());

        captureHandler.InitService();

        while (!stoppingToken.IsCancellationRequested)
        {
            WaitHandle.WaitAny(new WaitHandle[] { shutdownSignal.WaitHandle, stoppingToken.WaitHandle });
            if (stoppingToken.IsCancellationRequested)
            {
                break;
            }

            captureSignal.Reset();
        }

        captureHandler.CleanUp();
    }

    // Start or restart the service
    public void IniciarServicio()
    {
        shutdownSignal.Reset();
        _logger.LogInformation("Service starting or restarting...");
        captureHandler.InitService();
    }

    // Stop the service and clean up resources
    public void DetenerServicio()
    {
        shutdownSignal.Set();
        _logger.LogInformation("Service stopping...");
        captureHandler.CleanUp();
    }
}

// Fingerprint validation service implementation
public class FingerprintValidateService : BackgroundService, IBaseFingerprintService
{
    private readonly ILogger<FingerprintValidateService> _logger;
    private ManualResetEventSlim shutdownSignal = new ManualResetEventSlim(false);
    private ManualResetEventSlim captureSignal = new ManualResetEventSlim(false);
    private ValidateDP validateDP;

    // Constructor initializes the service with a logger and a validation handler
    public FingerprintValidateService(ILogger<FingerprintValidateService> logger)
    {
        _logger = logger;
        validateDP = new ValidateDP();
    }

    // Main execution loop of the service, handles service shutdown and operation
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Fingerprint Validation Service running.");
        stoppingToken.Register(() => shutdownSignal.Set());

        validateDP.InitService();

        while (!stoppingToken.IsCancellationRequested)
        {
            WaitHandle.WaitAny(new WaitHandle[] { shutdownSignal.WaitHandle, stoppingToken.WaitHandle });
            if (stoppingToken.IsCancellationRequested)
            {
                break;
            }

            captureSignal.Reset();
        }

        validateDP.CleanUp();
    }

    // Start or restart the service
    public void IniciarServicio()
    {
        shutdownSignal.Reset();
        _logger.LogInformation("Service starting or restarting...");
        validateDP.InitService();
    }

    // Stop the service and clean up resources
    public void DetenerServicio()
    {
        shutdownSignal.Set();
        _logger.LogInformation("Service stopping...");
        validateDP.CleanUp();
    }
}


If you need more help just reply to the message
© www.soinside.com 2019 - 2024. All rights reserved.