c# .net core 指纹协议对接

Startup类注入和使用

//注入监听串口
services.AddSingleton<SerialSerice>();

//开启监听,放在Configure函数
var serialSerice = app.ApplicationServices.GetService<SerialSerice>();
serialSerice.ZWStartSerialPortMonitor();

使用

//注入
private SerialSerice serialSerice;

string result = await serialSerice.ReadFingerPrintGetTZZ();

SerialSerice类,实现监听和发送指令和接收返回数据

using Amib.Threading;
using flyfire.IO.Ports;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Tools
{
  public  class SerialSerice
    {

        private readonly IHubContext<MyHub> _hubContext;
        private static SmartThreadPool smartThreadPool => new SmartThreadPool(new STPStartInfo() { MinWorkerThreads = 1, MaxWorkerThreads = 1, AreThreadsBackground = true });

        public SerialSerice(IHubContext<MyHub> hubContext)
        {
            _hubContext = hubContext;
        }
        #region 串口监听

        private int tryCount = 0;
        private int zwTryCount = 0;
        private SerialPort serialPort = null;
        private SerialPort serialZWPort = null;

        #region 指纹

        #region 对接命令
        /// <summary>
        /// 取 DSP 模块内部序列号(命令/应答均为 8 字节)
        /// </summary>
        public async Task<string> QDSPMKNBXLH()
        {
            Byte[] buffer = new Byte[5];
            buffer[0] = 0x2A;
            buffer[1] = 0;
            buffer[2] = 0;
            buffer[3] = 0;
            buffer[4] = 0;
            return await ZWWrite5ByteAsync(buffer);
        }

        /// <summary>
        /// 使模块进入休眠状态(命令/应答均为 8 字节)
        /// </summary>
        public async Task<string> SleepZW()
        {
            Byte[] buffer = new Byte[5];
            buffer[0] = 0x2C;
            buffer[1] = 0;
            buffer[2] = 0;
            buffer[3] = 0;
            buffer[4] = 0;
            return await ZWWrite5ByteAsync(buffer);
        }

        /// <summary>
        /// 设置指纹添加模式(命令/应答均为 8 字节)
        /// </summary>
        /// <param name="model">0:允许重复 1:禁止重复</param>
        /// <returns></returns>
        public async Task<string> SetAddModel(Byte model = 0)
        {
            Byte[] buffer = new Byte[5];
            buffer[0] = 0x2D;
            buffer[1] = 0;
            buffer[2] = model;
            buffer[3] = 0;
            buffer[4] = 0;
            return await ZWWrite5ByteAsync(buffer);
        }

        /// <summary>
        /// 读取指纹添加模式(命令/应答均为 8 字节)
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetAddModel()
        {
            Byte[] buffer = new Byte[5];
            buffer[0] = 0x2D;
            buffer[1] = 0;
            buffer[2] = 0;
            buffer[3] = 1;
            buffer[4] = 0;
            return await ZWWrite5ByteAsync(buffer);
        }

        /// <summary>
        /// 添加指纹 命令/应答均为 8 字节)
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="addNum">第几次 0x01-第一次 0x02-第二次 0x03-第三次</param>
        /// <returns></returns>
        public async Task<string> AddFingerPrint(int userId,Byte addNum)
        {
            if (GetHL8(userId, out int h8, out int l8))
            {
                Byte[] buffer = new Byte[5];
                buffer[0] = addNum;
                buffer[1] = (byte)h8;
                buffer[2] = (byte)l8;
                buffer[3] = 0x01;
                buffer[4] = 0;
                return await ZWWrite5ByteAsync(buffer,200);
            }
            else {
                throw new Ex.ParameterException("用户id错误");
            }
        }

        /// <summary>
        /// 删除指定用户(命令/应答均为 8 字节)
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<string> DeleteFingerPrint(int userId)
        {
            if (GetHL8(userId, out int h8, out int l8))
            {
                Byte[] buffer = new Byte[5];
                buffer[0] = 0x04;
                buffer[1] = (byte)h8;
                buffer[2] = (byte)l8;
                buffer[3] = 0;
                buffer[4] = 0;
                return await ZWWrite5ByteAsync(buffer, 200);
            }
            else
            {
                throw new Ex.ParameterException("用户id错误");
            }
        }

        /// <summary>
        /// 删除所有用户(命令/应答均为 8 字节)
        /// </summary>
        /// <param name="power">0-删除全部用户 1/2/3 删除权限为1/2/3的用户</param>
        /// <returns></returns>
        public async Task<string> DeleteFingerPrintAll(Byte power)
        {
            Byte[] buffer = new Byte[5];
            buffer[0] = 0x05;
            buffer[1] = 0;
            buffer[2] = 0;
            buffer[3] = power;
            buffer[4] = 0;
            return await ZWWrite5ByteAsync(buffer, 200);

        }

        /// <summary>
        /// 取用户总数(命令/应答均为 8 字节)
        /// </summary>
        /// <param name="type">0-用户总数 0xFF-指纹容量</param>
        /// <returns></returns>
        public async Task<string> GetFingerPrintCount(Byte type)
        {
            Byte[] buffer = new Byte[5];
            buffer[0] = 0x09;
            buffer[1] = 0;
            buffer[2] = 0;
            buffer[3] = type;
            buffer[4] = 0;
            return await ZWWrite5ByteAsync(buffer, 200);
        }

        /// <summary>
        /// 比对 1:1(命令/应答均为 8 字节)
        /// </summary>
        /// <param name="userId">用户id</param>
        /// <returns></returns>
        public async Task<string> FingerPrintOneToOne(int userId)
        {
            if (GetHL8(userId, out int h8, out int l8))
            {
                Byte[] buffer = new Byte[5];
                buffer[0] = 0x0B;
                buffer[1] = (byte)h8;
                buffer[2] = (byte)l8;
                buffer[3] = 0;
                buffer[4] = 0;
                return await ZWWrite5ByteAsync(buffer, 200);
            }
            else
            {
                throw new Ex.ParameterException("用户id错误");
            }
        }

        /// <summary>
        /// 比对 1:N(命令/应答均为 8 字节)
        /// </summary>
        /// <returns></returns>
        public async Task<string> FingerPrintOneToN()
        {
            Byte[] buffer = new Byte[5];
            buffer[0] = 0x0C;
            buffer[1] = 0;
            buffer[2] = 0;
            buffer[3] = 0;
            buffer[4] = 0;
            return await ZWWrite5ByteAsync(buffer, 200);
        }

        /// <summary>
        /// 2.12 取用户权限(命令/应答均为 8 字节)
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetUserPower(int userId)
        {
            if (GetHL8(userId, out int h8, out int l8))
            {
                Byte[] buffer = new Byte[5];
                buffer[0] = 0x0A;
                buffer[1] = (byte)h8;
                buffer[2] = (byte)l8;
                buffer[3] = 0;
                buffer[4] = 0;
                return await ZWWrite5ByteAsync(buffer, 200);
            }
            else
            {
                throw new Ex.ParameterException("用户id错误");
            }
        }

        /// <summary>
        /// 取 DSP 模块版本号(命令为 8 字节/应答>8 字节)
        /// </summary>
        public async Task<string> QDSPMKBBH()
        {
            Byte[] buffer = new Byte[5];
            buffer[0] = 0x26;
            buffer[1] = 0;
            buffer[2] = 0;
            buffer[3] = 0;
            buffer[4] = 0;
            return await ZWWrite5ByteAsync(buffer);
        }

        /// <summary>
        /// 设置比对等级(命令/应答均为 8 字节)
        /// </summary>
        /// <param name="model">0-9 越大越严格 默认5</param>
        /// <returns></returns>
        public async Task<string> SetToModel(Byte model)
        {
            Byte[] buffer = new Byte[5];
            buffer[0] = 0x28;
            buffer[1] = 0;
            buffer[2] = model;
            buffer[3] = 0;
            buffer[4] = 0;
            return await ZWWrite5ByteAsync(buffer);
        }

        /// <summary>
        /// 读取比对等级(命令/应答均为 8 字节)
        /// </summary>
        public async Task<string> GetToModel()
        {
            Byte[] buffer = new Byte[5];
            buffer[0] = 0x28;
            buffer[1] = 0;
            buffer[2] = 0;
            buffer[3] = 1;
            buffer[4] = 0;
            return await ZWWrite5ByteAsync(buffer);
        }

        /// <summary>
        /// 2.15采集图像并上传(命令为 8 字节/应答>8 字节)---图像数据长度 Len 恒为 9800 字节。
        /// </summary>
        public async Task<string> ReadFingerPrintGetPic()
        {
            Byte[] buffer = new Byte[5];
            buffer[0] = 0x24;
            buffer[1] = 0;
            buffer[2] = 0;
            buffer[3] = 0;
            buffer[4] = 0;
            return await ZWWrite5ByteAsync(buffer, 200);
        }

        /// <summary>
        /// 2.16采集图像并提取特征值上传(命令为 8 字节/应答>8 字节) ---特征值数据长度 Len - 3 恒为 193 字节。
        /// </summary>
        public async Task<string> ReadFingerPrintGetTZZ()
        {
            Byte[] buffer = new Byte[5];
            buffer[0] = 0x23;
            buffer[1] = 0;
            buffer[2] = 0;
            buffer[3] = 0;
            buffer[4] = 0;
            return await ZWWrite5ByteAsync(buffer,200);
        }

        /// <summary>
        /// 2.18 上传指纹特征值与 DSP 模块数据库指纹比对 1:1(命令>8 字节/应答为 8 字节)
        /// </summary>
        /// <param name="id">指纹id</param>
        /// <param name="featuresStr">特征值 从2.16获取</param>
        /// <returns></returns>
        public async Task<string> UpFingerPrintFeatures(int id,string featuresStr)
        {
            if (GetHL8(id, out int h8, out int l8))
            {
                Byte[] buffer = new Byte[5];
                buffer[0] = 0x42;
                buffer[1] = 0;
                buffer[2] = 0xC4;
                buffer[3] = 0;
                buffer[4] = 0;

                Byte[] packBuffer = new Byte[196];
                packBuffer[0] = (byte)h8;
                packBuffer[1] = (byte)l8;
                packBuffer[2] = 0;
                for (int i = 0; i < 193; i++)
                {
                    packBuffer[i+3] =(byte)Convert.ToInt32(featuresStr.Substring(i * 2, 2), 16);
                }
                return await ZWWrite5ByteAndPackAsync(buffer, packBuffer, 200);
            }
            else
            {
                throw new Ex.ParameterException("id错误");
            }
        }

        /// <summary>
        /// 2.19 上传指纹特征值与 DSP 模块数据库指纹比对 1:N(命令>8 字节/应答为 8 字节)
        /// </summary>
        /// <param name="featuresStr">特征值 从2.16获取</param>
        /// <returns></returns>
        public async Task<string> UpFingerPrintFeaturesOneToN(string featuresStr)
        {
            
                Byte[] buffer = new Byte[5];
                buffer[0] = 0x43;
                buffer[1] = 0;
                buffer[2] = 0xC4;
                buffer[3] = 0;
                buffer[4] = 0;

                Byte[] packBuffer = new Byte[196];
                packBuffer[0] = 0;
                packBuffer[1] = 0;
                packBuffer[2] = 0;
                for (int i = 0; i < 193; i++)
                {
                    packBuffer[i + 3] = (byte)Convert.ToInt32(featuresStr.Substring(i * 2, 2), 16);
                }
                return await ZWWrite5ByteAndPackAsync(buffer, packBuffer, 200);
            
        }

        /// <summary>
        /// 2.22取已登录所有用户用户号及权限(命令为 8 字节/应答>8 字节)
        /// </summary>
        public async Task<string> GetLoginUser()
        {
            Byte[] buffer = new Byte[5];
            buffer[0] = 0x2B;
            buffer[1] = 0;
            buffer[2] = 0;
            buffer[3] = 0;
            buffer[4] = 0;
            return await ZWWrite5ByteAsync(buffer);
        }

        /// <summary>
        /// 2.23 设置指纹采集等待超时时间(命令/应答均为 8 字节)
        /// </summary>
        /// <param name="time">time 为 0-255       time*T0(0.2~0.3) 为具体时间 </param>
        /// <returns></returns>
        public async Task<string> SetReadFingerPrintTime(Byte time)
        {
            Byte[] buffer = new Byte[5];
            buffer[0] = 0x2E;
            buffer[1] = 0;
            buffer[2] = time;
            buffer[3] = 0;
            buffer[4] = 0;
            return await ZWWrite5ByteAsync(buffer);
        }

        /// <summary>
        /// 2.23 读取指纹采集等待超时时间(命令/应答均为 8 字节)
        /// </summary>
        public async Task<string> GetReadFingerPrintTime()
        {
            Byte[] buffer = new Byte[5];
            buffer[0] = 0x2E;
            buffer[1] = 0;
            buffer[2] = 0;
            buffer[3] = 1;
            buffer[4] = 0;
            return await ZWWrite5ByteAsync(buffer);
        }

        /// <summary>
        /// 2.24 设置添加等级(命令/应答均为 8 字节)- 仅限某些模块有此协议
        /// </summary>
        /// <param name="level">添加等级取值为 0-9,取值越大添加越严格,默认值为 4</param>
        /// <returns></returns>
        public async Task<string> SetAddLevel(Byte level)
        {
            Byte[] buffer = new Byte[5];
            buffer[0] = 0x27;
            buffer[1] = 0;
            buffer[2] = level;
            buffer[3] = 0;
            buffer[4] = 0;
            return await ZWWrite5ByteAsync(buffer);
        }

        /// <summary>
        /// 2.24 读取添加等级(命令/应答均为 8 字节)- 仅限某些模块有此协议
        /// </summary>
        public async Task<string> GetAddLevel()
        {
            Byte[] buffer = new Byte[5];
            buffer[0] = 0x27;
            buffer[1] = 0;
            buffer[2] = 0;
            buffer[3] = 1;
            buffer[4] = 0;
            return await ZWWrite5ByteAsync(buffer);
        }

        #endregion

        #region 接入准备

        public void ZWStartSerialPortMonitor()
        {
            List<string> comList = GetComlist(false); //首先获取本机关联的串行端口列表
            if (comList.Count == 0)
            {
                //提示信息,当前设备不存在串行端口
            }
            else
            {
                #region 指纹
                string targetZWCOMPort = ConfigHelper.GetValue("ZWCOMPort");
                //判断串口列表中是否存在目标串行端口
                if (!comList.Contains(targetZWCOMPort))
                {
                    zwTryCount++;
                    //提示信息,当前设备不存在配置的指纹串行端口
                    SignalrTool _signalr = new SignalrTool(_hubContext);
                    MsgInfo msgInfo = new MsgInfo();
                    msgInfo.Title = "连接指纹模块失败,没找到串口。请联系管理员!";
                    msgInfo.Type = (int)Utility.Enums.StateEnum.SingRType.Erro;
                    msgInfo.State = 0;
                    msgInfo.PName = "";
                    _signalr.SendMessage(msgInfo);
                    Thread.Sleep(1000);
                    ZWStartSerialPortMonitor();
                    return;
                }

                serialZWPort = new SerialPort();
                //设置参数               
                serialZWPort.PortName = targetZWCOMPort; //通信端口
                serialZWPort.BaudRate = Int32.Parse(ConfigHelper.GetValue("ZWBaudRate"));//串行波特率               
                serialZWPort.DataBits = 8; //每个字节的标准数据位长度
                serialZWPort.StopBits = StopBits.One; //设置每个字节的标准停止位数
                serialZWPort.Parity = Parity.None; //设置奇偶校验检查协议
                serialZWPort.ReadTimeout = 3000; //单位毫秒
                serialZWPort.WriteTimeout = 3000; //单位毫秒
                                                  //串口控件成员变量,字面意思为接收字节阀值,
                                                  //串口对象在收到这样长度的数据之后会触发事件处理函数
                                                  //一般都设为1
                serialZWPort.ReceivedBytesThreshold = 1;
                serialZWPort.DataReceived += new SerialDataReceivedEventHandler(ZWCommDataReceived); //设置数据接收事件(监听)               
                try
                {
                    serialZWPort.Open(); //打开串口
                    ZhuoShang.Infrastructure.Core.Tools.LogHelper.Info("指纹串口监听打开成功");
                }
                catch (Exception ex)
                {
                    zwTryCount++;
                    ZhuoShang.Infrastructure.Core.Tools.LogHelper.Error("提示信息, 指纹串行端口打开失败!重新尝试次数" + zwTryCount + ",具体原因:" + ex.ToString());
                    SignalrTool _signalr = new SignalrTool(_hubContext);
                    MsgInfo msgInfo = new MsgInfo();
                    msgInfo.Title = "连接指纹模块失败,正在重新尝试连接";
                    msgInfo.Type = (int)Utility.Enums.StateEnum.SingRType.Erro;
                    msgInfo.State = 0;
                    msgInfo.PName = "";
                    _signalr.SendMessage(msgInfo);
                    Thread.Sleep(1000);
                    ZWStartSerialPortMonitor();
                    return;
                }
                #endregion
            }
            if (tryCount > 0)
            {
                SignalrTool _signalr = new SignalrTool(_hubContext);
                MsgInfo msgInfo = new MsgInfo();
                msgInfo.Title = "连接指纹模块成功";
                msgInfo.Type = (int)Utility.Enums.StateEnum.SingRType.Erro;
                msgInfo.State = 0;
                msgInfo.PName = "";
                _signalr.SendMessage(msgInfo);
            }
        }

        string ZWByteData = "";
        List<string> ZWByteDataList = new List<string>();

        /// <summary>
        /// 串口数据处理函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ZWCommDataReceived(Object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                int len = serialZWPort.BytesToRead;
                //指纹串口监听接收信息
                Byte[] readBufferdata = new Byte[len];
                serialZWPort.Read(readBufferdata, 0, len); //将数据读入缓存               
                string returnStr = "";
                if (readBufferdata != null)
                {
                    for (int i = 0; i < readBufferdata.Length; i++)
                    {
                        returnStr += readBufferdata[i].ToString("X2");
                    }
                    ZWByteData += returnStr;
                }
                //指纹串口监听接收信息
                if (ZWByteDataList.Count >= 100)
                    ZWByteDataList.RemoveRange(0, 10);
                ZWByteDataList.Add(ZWByteData);
            }
            catch (Exception ex)
            {
                //提示信息,指纹串口数据处理函数接收返回消息异常!具体原因:" + ex.Message);
            }
        }

        bool hasSend = false;

        /// <summary>
        /// 发送指纹指令异步获取接收信息
        /// </summary>
        public async Task<string> ZWWrite5ByteAsync(Byte[] buffer, int waitHM = 50) {
            bool canSend = await ZWSendBefore();
            if (!canSend)
                return "";
            ZWWriteByte(buffer);
            return await ZWSendAfter(waitHM);
        }

        /// <summary>
        /// 发送指纹指令异步获取接收信息
        /// </summary>
        public async Task<string> ZWWrite5ByteAndPackAsync(Byte[] buffer,Byte[] packBuffer, int waitHM = 50)
        {
            ZWSendBefore();
            ZWWriteByteAndPack(buffer, packBuffer);
            return await ZWSendAfter(waitHM);
        }

        /// <summary>
        /// 发送之前
        /// </summary>
        public async Task<bool> ZWSendBefore() {
            int sleepMs = 100;
            int forCount = 100;
            return await Task.Run(() =>
            {
                if (hasSend)
                {
                    int readForCount = 0;
                    while (hasSend)
                    {
                        if (readForCount >= forCount)
                        {
                            //指纹指令发送之前运行循环超时,等待时间(s):"+sleepMs*forCount/1000);
                            return false;
                        }
                        readForCount++;
                        if (forCount % 20 == 0) {
                            //指纹指令发送之前运行循环,等待时间(s):" + sleepMs * readForCount / 1000);
                        }
                        Thread.Sleep(sleepMs);
                    }
                }
                ZWByteData = "";
                return true;
            });
        }
        /// <summary>
        /// 发送之后
        /// </summary>
        /// <returns></returns>
        public async Task<string> ZWSendAfter(int waitHM)
        {
            hasSend = true;
            return await Task.Run(() =>
            {
                int tIndex = 0;
                while (true)
                {
                    Thread.Sleep(waitHM);
                    if(tIndex % 50 == 0 && tIndex>0)
                        //指纹指令发送之后等待结果运行循环次数:"+ tIndex);
                    if (!string.IsNullOrEmpty(ZWByteData))
                    {
                        if (ZWByteData.StartsWith("F5") && ZWByteData.EndsWith("F5")) {
                            //指纹指令发送之后返回结果:" + ZWByteData);
                            hasSend = false;
                            return ZWByteData;
                        }
                    }
                    if (tIndex* waitHM >= 60000) {//大于1分钟为强制超时
                        //指纹指令发送之后等待结果强制超时:等待时间" + tIndex * waitHM+"毫秒");
                        hasSend = false;
                        return "";
                    }
                    tIndex++;
                }
            });
        }

        /// <summary>
        /// 发送Byte指令(不用传递帧头帧尾F5,并自动对比异或值)
        /// </summary>
        public void ZWWriteByte(Byte[] bytes)
        {
            string writeStr = "";
            ZWIsOpen();
            try
            {
                Byte[] buffer = new Byte[8];
                buffer[0] = 0xF5;
                buffer[1] = bytes[0];
                buffer[2] = bytes[1];
                buffer[3] = bytes[2];
                buffer[4] = bytes[3];
                buffer[5] = bytes[4];
                int mycheck = 0;
                for (int i = 1; i < 6; i++)
                {
                    mycheck ^= (int)buffer[i];
                }
                buffer[6] = (byte)mycheck;
                buffer[7] = 0xF5;
                writeStr = "";
                for (int i = 0; i < buffer.Length; i++)
                {
                    writeStr += buffer[i].ToString("X2");
                }
                serialZWPort.Write(buffer, 0, 8);
                //指纹指令写入成功:"+ writeStr);
            }
            catch (Exception ex)
            {
                //提示信息, 指纹指令("+ writeStr + ")写入失败!具体原因:" + ex.Message);
            }
        }

        /// <summary>
        /// 发送Byte指令和数据包(不用传递帧头帧尾F5,并自动对比异或值)
        /// </summary>
        public void ZWWriteByteAndPack(Byte[] bytes,Byte[] packs)
        {
            string writeStr = "";
            ZWIsOpen();
            try
            {
                Byte[] buffer = new Byte[8];
                buffer[0] = 0xF5;
                buffer[1] = bytes[0];
                buffer[2] = bytes[1];
                buffer[3] = bytes[2];
                buffer[4] = bytes[3];
                buffer[5] = bytes[4];
                int mycheck = 0;
                for (int i = 1; i < 6; i++)
                {
                    mycheck ^= (int)buffer[i];
                }
                buffer[6] = (byte)mycheck;
                buffer[7] = 0xF5;
                writeStr = "";
                for (int i = 0; i < buffer.Length; i++)
                {
                    writeStr += buffer[i].ToString("X2");
                }
                serialZWPort.Write(buffer, 0, 8);
                //指纹指令头写入成功:" + writeStr);

                Byte[] packBuffer = new Byte[199];
                packBuffer[0] = 0xF5;
                for (int i = 0; i < packs.Length; i++)
                {
                    packBuffer[i + 1] = packs[i];

                }
                int myPackCheck = 0;
                for (int i = 1; i < 197; i++)
                {
                    myPackCheck ^= (int)packBuffer[i];
                }
                packBuffer[197] = (byte)myPackCheck;
                packBuffer[198] = 0xF5;
                writeStr = "";
                for (int i = 0; i < packBuffer.Length; i++)
                {
                    writeStr += packBuffer[i].ToString("X2");
                }
                serialZWPort.Write(packBuffer, 0, 199);
                //指纹指令包写入成功:" + writeStr);
            }
            catch (Exception ex)
            {
                //提示信息, 指纹指令(" + writeStr + ")写入失败!具体原因:" + ex.Message);
            }
        }

        public void ZWIsOpen() {
            if (!serialZWPort.IsOpen)
            {
                serialZWPort = new SerialPort();
                //设置参数               
                serialZWPort.PortName = ZhuoShang.Infrastructure.Core.Tools.ConfigHelper.GetValue("ZWCOMPort"); //通信端口
                serialZWPort.BaudRate = Int32.Parse(ZhuoShang.Infrastructure.Core.Tools.ConfigHelper.GetValue("ZWBaudRate"));//串行波特率               
                serialZWPort.DataBits = 8; //每个字节的标准数据位长度
                serialZWPort.StopBits = StopBits.One; //设置每个字节的标准停止位数
                serialZWPort.Parity = Parity.None; //设置奇偶校验检查协议
                serialZWPort.ReadTimeout = 3000; //单位毫秒
                serialZWPort.WriteTimeout = 3000; //单位毫秒
                //串口控件成员变量,字面意思为接收字节阀值,
                //串口对象在收到这样长度的数据之后会触发事件处理函数
                //一般都设为1
                serialZWPort.ReceivedBytesThreshold = 1;
                try
                {
                    serialZWPort.Open(); //打开串口
                    Console.WriteLine("打开成功");
                }
                catch (Exception ex)
                {
                    //提示信息, 指纹串口打开写入指令失败!具体原因:" + ex.Message);
                }
            }
        }

        /// <summary>
        /// 关闭串口
        /// </summary>
        private void ZWStop()
        {
            serialZWPort.Close();
        }

        /// <summary>
        /// 获取数字高八位第八位
        /// </summary>
        /// <param name="CRC">指纹模块限制只能为1-0xFFF(4095)</param>
        /// <param name="CRLH">高八位</param>
        /// <param name="CRCL">第八位</param>
        /// <returns></returns>
        private bool GetHL8(int CRC,out int CRLH, out int CRCL) {
            CRCL = 0;
            CRLH = 0;
            if (CRC >= 1 && CRC <= 0XFFF) {
                string S = Convert.ToString(CRC, 16);//转换为16进制字符串0x6398

                int CrcL = CRC % 256;                //低8位,取余
                CRCL = CRC & (0XFF);             //取低8位,152

                int CrcH = CRC / 256;                //高8位,除256
                CRLH = (CRC >> 8) & 0XFF;
                return true;
            }
            return false;
        }

        /// <summary>
        /// 高八位第八位转换成int
        /// </summary>
        /// <param name="h">高八位</param>
        /// <param name="l">低八位</param>
        /// <returns></returns>
        public static int GetHL8Int(string h, string l)
        {
            return GetHL8Int(Convert.ToInt32(h, 16), Convert.ToInt32(l, 16));
        }

        /// <summary>
        /// 高八位第八位转换成int
        /// </summary>
        /// <param name="l">高八位</param>
        /// <param name="h">低八位</param>
        /// <returns></returns>
        public static int GetHL8Int(int h,int l)
        {
            return l + h * 256;
        }

        /// <summary>
        /// 获取16进制字符串指定下标数字(每两位算一个数字 F5>0 00>1 25>2 36>3)
        /// </summary>
        /// <param name="hex"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public static int GetBitInt(string hex, int index) {
            if (hex.Length / 2 <= index) {
                return 0;
            }
            return Convert.ToInt32(hex.Substring(index * 2, 2), 16);
        }
        #endregion

        #endregion
        /// <summary>
        /// 获取本机串口列表
        /// </summary>
        /// <param name="isUseReg"></param>
        /// <returns></returns>
        private List<string> GetComlist(bool isUseReg)
        {
            List<string> list = new List<string>();
            try
            {
                if (isUseReg)
                {
                    RegistryKey RootKey = Registry.LocalMachine;
                    RegistryKey Comkey = RootKey.OpenSubKey(@"HARDWARE\DEVICEMAP\SERIALCOMM");

                    String[] ComNames = Comkey.GetValueNames();

                    foreach (String ComNamekey in ComNames)
                    {
                        string TemS = Comkey.GetValue(ComNamekey).ToString();
                        list.Add(TemS);

                        ZhuoShang.Infrastructure.Core.Tools.LogHelper.Error("IsUseReg:"+ComNamekey+"|"+ TemS);
                    }
                }
                else
                {
                    foreach (string com in SerialPort.GetPortNames())  //自动获取串行口名称  
                        list.Add(com);
                }
            }
            catch
            {
                ZhuoShang.Infrastructure.Core.Tools.LogHelper.Error("提示信息, 串行端口检查异常!");
                System.Environment.Exit(0); //彻底退出应用程序   
            }
            return list;
        }

        #endregion 串口监听
       

    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SmartThreadPool是大名鼎鼎的.Net线程池项目,基于.Net开发,比.Net内置的线程池更胜一筹。1、为什么需要使用线程池(Thread Pool)减少线程间上下文切换。线程执行一定的时间片后,系统会自动把cpu切换给另一个线程使用,这时还需要保存当 前的线程上下文状态,并加载新线程的上下文状态。当程序中有大量的线程时,每个线程分得的时间片会越来越少,可能会出现线程未处理多少操作,就需要切换到 另一线程,这样频繁的线程间上下文切换会花费大量的cpu时间。减少内存占用。系统每创建一条物理线程,需要大概花费1MB的内存空间,许多程序喜欢先创建多条物理线程,并 周期轮询来处理各自的任务,这样既消耗了线程上下文切换的时间,还浪费了内存。这些任务可能只需要一条线程就能满足要求。假如某一任务需要执行较长的周 期,线程池还可以自动增加线程,并在空闲时,销毁线程,释放占用的内存。2、为什么不使用.Net默认的线程池.Net默认的线程池(ThreadPool)是一个静态类,所以是没办法自己创建一个新的程序池的。默认的线程池与应用程序域 (AppDomain)挂钩,一个AppDomain只有一个线程池。假如在线程池中执行了一个周期较长的任务,一直占用着其中一个线程,可能就会影响到 应用程序域中的其他程序的性能。例如,假如在Asp.Net的线程池中执行一个周期较长的任务,就会影响请求的并发处理能力(线程池默认有个最大线程 数)。 3、SmartThreadPool特性和优点    SmartThreadPool特性如下:可创建线程池实例。可动态调整线程池工作线程数量。WorkItem 可以返回信息。未执行 WorkItem 可被取消。WorkItem 执行时可使用调用者上下文。调用者可等待多个或全部 WorkItem 执行结束。WorkItem 允许拥有一个执行结束时被执行的 PostExecute 回调委托。可以向 WorkItem 传递一个状态对象,并且会在执行结束时自动调用 IDisposable.Dispose()。WorkItem 异常会传递给调用者。支持 WorkItem 分组。可挂起线程池或分组。可以设置 WorkItem 优先级。可以设置线程优先级。4、使用示例 最简单的使用方法:// 创建一个线程池 SmartThreadPool smartThreadPool = new SmartThreadPool();    // 执行任务 smartThreadPool.QueueWorkItem(() => {      Console.WriteLine("Hello World!"); });带返回值的任务:// 创建一个线程池 SmartThreadPool smartThreadPool = new SmartThreadPool();   // 执行任务 var result = smartThreadPool.QueueWorkItem(() => {     var sum = 0;     for (var i = 0; i  {     //模拟计算较长时间     Thread.Sleep(5000);       return 3; });   var result2 = smartThreadPool.QueueWorkItem(() => {     //模拟计算较长时间     Thread.Sleep(3000);       return 5; });   bool success = SmartThreadPool.WaitAll(     new IWorkItemResult[] { result1, result2 });   if (success) {     // 输出结果     Console.WriteLine(result1.Result);     Console.WriteLine(result2.Result); }5、结论 使用SmartThreadPool可以简单就实现支持多线程的程序,由线程池来管理线程,可以减少死锁的出现。SmartThreadPool还支持简单的生产者-消费者模式,当不需要对任务进行持久化时,还是很好用的。 6、扩展阅读 http://www.codeproject.com/KB/threads/smartthreadpool.aspx http://smartthreadpool.codeplex.com/http://www.albahari.com/threading/ 标签:线程池

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值