diff --git a/HybirdFrameworkDriver/TcpServer/TcpServer.cs b/HybirdFrameworkDriver/TcpServer/TcpServer.cs index 1da7a28..1625c69 100644 --- a/HybirdFrameworkDriver/TcpServer/TcpServer.cs +++ b/HybirdFrameworkDriver/TcpServer/TcpServer.cs @@ -30,14 +30,14 @@ public class TcpServer : IDisposable where TH : IChannelHandler private static ServerBootstrap? bootstrap; private int _port = 9000; - + public LogLevel? LogLevel { get; set; } - + public Action? ChannelInActiveAction { get; set; } public void InitBootstrap() { - + if (LogLevel != null) { InternalLoggerFactory.DefaultFactory.AddProvider(new Log4NetProvider()); @@ -75,7 +75,8 @@ public class TcpServer : IDisposable where TH : IChannelHandler public void Dispose() { Log.Info(this + " Dispose"); - bossGroup?.ShutdownGracefullyAsync(); + bossGroup?.ShutdownGracefullyAsync().Wait(); + workerGroup?.ShutdownGracefullyAsync().Wait(); } private void ResolveEncode(IChannelPipeline pipeline) @@ -135,4 +136,4 @@ public class TcpServer : IDisposable where TH : IChannelHandler Task? channel = bootstrap?.BindAsync(_port); Log.Info($"netty success listen {_port}"); } -} \ No newline at end of file +} diff --git a/Rfid/App.config b/Rfid/App.config new file mode 100644 index 0000000..d9dbf31 --- /dev/null +++ b/Rfid/App.config @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Rfid/Program.cs b/Rfid/Program.cs new file mode 100644 index 0000000..fafcf28 --- /dev/null +++ b/Rfid/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.IO; +using DotNetty.Handlers.Logging; +using log4net.Config; + +namespace Rfid +{ + internal class Program + { + public static void Main(string[] args) + { + XmlConfigurator.ConfigureAndWatch(new FileInfo(AppDomain.CurrentDomain.BaseDirectory + @"\log4net.xml")); + + RfidServer rfidServer = new RfidServer() + { + LogLevel = LogLevel.TRACE + }; + rfidServer.Start(); + Console.In.ReadLine(); + } + } +} diff --git a/Rfid/Properties/AssemblyInfo.cs b/Rfid/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..095f14d --- /dev/null +++ b/Rfid/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Rfid")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Rfid")] +[assembly: AssemblyCopyright("Copyright © 2024")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("053079C7-C9EE-49F4-B9CB-F06D14AEB027")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/Rfid/Rfid.csproj b/Rfid/Rfid.csproj new file mode 100644 index 0000000..71ff1f2 --- /dev/null +++ b/Rfid/Rfid.csproj @@ -0,0 +1,162 @@ + + + + + Debug + AnyCPU + {053079C7-C9EE-49F4-B9CB-F06D14AEB027} + Exe + Properties + Rfid + Rfid + v4.8 + 512 + true + 10 + enable + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\DotNetty.Buffers.0.7.5\lib\net472\DotNetty.Buffers.dll + + + ..\packages\DotNetty.Codecs.0.7.5\lib\net472\DotNetty.Codecs.dll + + + ..\packages\DotNetty.Codecs.Http.0.7.5\lib\net472\DotNetty.Codecs.Http.dll + + + ..\packages\DotNetty.Common.0.7.5\lib\net472\DotNetty.Common.dll + + + ..\packages\DotNetty.Handlers.0.7.5\lib\net472\DotNetty.Handlers.dll + + + ..\packages\DotNetty.Transport.0.7.5\lib\net472\DotNetty.Transport.dll + + + ..\packages\log4net.2.0.15\lib\net45\log4net.dll + + + ..\packages\Microsoft.Bcl.AsyncInterfaces.5.0.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll + + + ..\packages\Microsoft.Extensions.Configuration.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Configuration.dll + + + ..\packages\Microsoft.Extensions.Configuration.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Configuration.Abstractions.dll + + + ..\packages\Microsoft.Extensions.Configuration.Binder.2.2.4\lib\netstandard2.0\Microsoft.Extensions.Configuration.Binder.dll + + + ..\packages\Microsoft.Extensions.DependencyInjection.5.0.0\lib\net461\Microsoft.Extensions.DependencyInjection.dll + + + ..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.5.0.0\lib\net461\Microsoft.Extensions.DependencyInjection.Abstractions.dll + + + ..\packages\Microsoft.Extensions.Logging.5.0.0\lib\net461\Microsoft.Extensions.Logging.dll + + + ..\packages\Microsoft.Extensions.Logging.Abstractions.5.0.0\lib\net461\Microsoft.Extensions.Logging.Abstractions.dll + + + ..\packages\Microsoft.Extensions.Logging.Log4Net.AspNetCore.8.0.0\lib\netstandard2.0\Microsoft.Extensions.Logging.Log4Net.AspNetCore.dll + + + ..\packages\Microsoft.Extensions.Options.5.0.0\lib\net461\Microsoft.Extensions.Options.dll + + + ..\packages\Microsoft.Extensions.Primitives.5.0.0\lib\net461\Microsoft.Extensions.Primitives.dll + + + + ..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll + + + lib\SRGReaderAPI.dll + + + + ..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll + + + ..\packages\System.Collections.Immutable.1.5.0\lib\netstandard2.0\System.Collections.Immutable.dll + + + + + + ..\packages\System.Diagnostics.DiagnosticSource.5.0.0\lib\net46\System.Diagnostics.DiagnosticSource.dll + + + ..\packages\System.Memory.4.5.4\lib\net461\System.Memory.dll + + + + ..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.5.0.0\lib\net45\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + ..\packages\System.ValueTuple.4.5.0\lib\net47\System.ValueTuple.dll + + + + + + + + + + + + + + + + + + + + + true + Always + PreserveNewest + + + + + + diff --git a/Rfid/Rfid/HttpHandler.cs b/Rfid/Rfid/HttpHandler.cs new file mode 100644 index 0000000..1a50834 --- /dev/null +++ b/Rfid/Rfid/HttpHandler.cs @@ -0,0 +1,92 @@ +using System; +using System.Text; +using DotNetty.Buffers; +using DotNetty.Codecs.Http; +using DotNetty.Common.Utilities; +using DotNetty.Transport.Channels; +using log4net; +using Newtonsoft.Json; + +namespace Rfid; + +public class HttpHandler : SimpleChannelInboundHandler +{ + private static readonly ILog Log = LogManager.GetLogger(typeof(HttpHandler)); + + static readonly AsciiString TypePlain = AsciiString.Cached("text/plain; charset=utf-8"); + static readonly AsciiString TypeJson = AsciiString.Cached("application/json; charset=utf-8"); + static readonly AsciiString OkLength = AsciiString.Cached(Encoding.UTF8.GetBytes("true").Length.ToString()); + static readonly AsciiString FailLength = AsciiString.Cached(Encoding.UTF8.GetBytes("false").Length.ToString()); + static readonly AsciiString ServerName = AsciiString.Cached("Netty"); + static readonly AsciiString ContentTypeEntity = HttpHeaderNames.ContentType; + static readonly AsciiString DateEntity = HttpHeaderNames.Date; + static readonly AsciiString ContentLengthEntity = HttpHeaderNames.ContentLength; + static readonly AsciiString ServerEntity = HttpHeaderNames.Server; + + protected override void ChannelRead0(IChannelHandlerContext ctx, DefaultHttpRequest req) + { + Log.Info($"{req.Uri}, {req}"); + + DefaultFullHttpResponse response = null; + switch (req.Uri) + { + case "/Api/ReadRfidData": + + RfidReadModel? model = RfidMgr.ReadRifd(); + if (model != null) + { + byte[] json = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(model)); + this.WriteResponse(ctx, Unpooled.WrappedBuffer(json), TypeJson, new AsciiString(json.Length.ToString())); + } + else + { + response = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.NoContent, Unpooled.Empty, false); + ctx.WriteAndFlushAsync(response); + } + + break; + case "/Api/BeginRead": + bool beginRead = RfidMgr.BeginRead(); + this.WriteResponse(ctx, Unpooled.WrappedBuffer(Encoding.UTF8.GetBytes(beginRead.ToString())), TypePlain, beginRead?OkLength: FailLength); + break; + case "/Api/StopRead": + var stopRead = RfidMgr.StopRead(); + this.WriteResponse(ctx, Unpooled.WrappedBuffer(Encoding.UTF8.GetBytes(stopRead.ToString())), TypePlain, stopRead?OkLength: FailLength); + break; + case "/Api/Open": + var connected = RfidMgr.Connect(); + this.WriteResponse(ctx, Unpooled.WrappedBuffer(Encoding.UTF8.GetBytes(connected.ToString())), TypePlain, connected?OkLength: FailLength); + break; + case "/Api/Close": + var closeRfid = RfidMgr.CloseRfid(); + this.WriteResponse(ctx, Unpooled.WrappedBuffer(Encoding.UTF8.GetBytes(closeRfid.ToString())), TypePlain, closeRfid?OkLength: FailLength); + break; + default: + response = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.NotFound, Unpooled.Empty, false); + ctx.WriteAndFlushAsync(response); + break; + } + + + } + + void WriteResponse(IChannelHandlerContext ctx, IByteBuffer buf, ICharSequence contentType, + ICharSequence contentLength) + { + DateTime dateTime = DateTime.UtcNow; + // Build the response object. + var response = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK, buf, false); + HttpHeaders headers = response.Headers; + headers.Set(ContentTypeEntity, contentType); + headers.Set(ServerEntity, ServerName); + headers.Set(DateEntity, AsciiString.Cached($"{dateTime.DayOfWeek}, {dateTime:dd MMM yyyy HH:mm:ss z}")); + headers.Set(ContentLengthEntity, contentLength); + + // Close the non-keep-alive connection after the write operation is done. + ctx.WriteAsync(response); + } + + public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) => context.CloseAsync(); + + public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush(); +} diff --git a/Rfid/Rfid/RfidMgr.cs b/Rfid/Rfid/RfidMgr.cs new file mode 100644 index 0000000..0c93804 --- /dev/null +++ b/Rfid/Rfid/RfidMgr.cs @@ -0,0 +1,65 @@ +namespace Rfid; + +public static class RfidMgr +{ + private static RfidReadWriteTool RfidReadWriteTool = new RfidReadWriteTool("172.0.30.100"); + + /// + /// 连接 + /// + /// + public static bool Connect() + { + RfidReadWriteTool.CloseRfid(); + bool bResult = RfidReadWriteTool.ConnectRfid(); + return bResult; + } + + /// + /// 连接 + /// + /// + public static bool Connected() + { + return RfidReadWriteTool.IsConnected; + } + + /// + /// 断开 + /// + /// + public static bool CloseRfid() + { + bool bResult = RfidReadWriteTool.CloseRfid(); + return bResult; + } + + /// + /// 开始读 + /// + /// + public static bool BeginRead() + { + bool bResult = RfidReadWriteTool.ScanRfidUserDataTag(); + return bResult; + } + + /// + /// 停止读 + /// + /// + public static bool StopRead() + { + bool bResult = RfidReadWriteTool.StopRfidResult(); + return bResult; + } + + /// + /// 读取信息 + /// + /// + public static RfidReadModel? ReadRifd() + { + return RfidReadWriteTool.RfidReadModel; + } +} diff --git a/Rfid/Rfid/RfidReadModel.cs b/Rfid/Rfid/RfidReadModel.cs new file mode 100644 index 0000000..e0d6a57 --- /dev/null +++ b/Rfid/Rfid/RfidReadModel.cs @@ -0,0 +1,25 @@ +namespace Rfid; + +public class RfidReadModel +{ + /// + /// 1:成功 0:失败 + /// + public int Result { get; set; } + + /// + /// 车辆VIN码 + /// + public string VelVin { get; set; } + + + /// + /// 车辆MAC地址 + /// + public string? VelMac { set; get; } + + /// + /// 车辆车牌号 + /// + public string VelNo { set; get; } +} diff --git a/Rfid/Rfid/RfidReadWriteTool.cs b/Rfid/Rfid/RfidReadWriteTool.cs new file mode 100644 index 0000000..b72e67c --- /dev/null +++ b/Rfid/Rfid/RfidReadWriteTool.cs @@ -0,0 +1,421 @@ +using System; +using System.Text; +using log4net; +using SRGReaderAPI; + +namespace Rfid; + +public class RfidReadWriteTool +{ + private static readonly ILog Log = LogManager.GetLogger(typeof(RfidReadWriteTool)); + + #region 字段属性 + + /// + /// IP地址 + /// + private string _ipaddr = "172.0.30.9"; + + /// + /// RFID连接IP地址 + /// + public string IpAddr + { + get { return _ipaddr; } + set { _ipaddr = value; } + } + + /// + /// 子网掩码 + /// + private string _subnet = "255.255.255.0"; + + /// + /// RFID连接的子网掩码 + /// + public string Subnet + { + get { return _subnet; } + set { _subnet = value; } + } + + /// + /// 网关 + /// + private string _gateway = "172.0.30.1"; + + /// + /// RFID连接的网关 + /// + public string Gateway + { + get { return _gateway; } + set { _gateway = value; } + } + + /// + /// 端口 + /// + private int _port = 9090; + + /// + /// RFID连接端口 + /// + public int Port + { + get { return _port; } + set { _port = value; } + } + + /// + /// 连接超时时间(ms) + /// + private int _timeout = 1000; + + /// + /// 连接超时时间(ms) + /// + public int TimeOut + { + get { return _timeout; } + set { _timeout = value; } + } + + /// + /// 读写器 + /// + private SReader _rfid_reader = null; + + /// + /// RFID连接客户端 + /// + public SReader RfidReader + { + get { return _rfid_reader; } + set { _rfid_reader = value; } + } + + /// + /// 客户端目前连接状态 + /// + private bool _isconnected = false; + + /// + /// 通讯是否连接 + /// + public bool IsConnected + { + get { return _isconnected; } + set { _isconnected = value; } + } + + /// + /// UserData + /// + private byte[] _user_datas = null; + + #endregion 字段属性 + + #region 事件定义 + + /// + /// 连接状态 + /// + public event EventHandler ConnectedChanged; + + /// + /// 数据已接收 + /// + public event EventHandler DataReceived; + + /// + /// 已发送的数据 + /// + public event EventHandler DataSended; + + + /// + /// 设置监听事件 + /// + /// 是否监听 + /// 监听消息事件 + private void SetConnectEvent(bool isConnected, string msgContent) + { + EventHandler ConnectedHandler; + ConnectedHandler = ConnectedChanged; + if (ConnectedHandler != null) + { + ConnectedHandler.Invoke(this, new ViewEventArgs() { IsConnected = isConnected, MsgContent = msgContent }); + } + } + + /// + /// 设置接收消息事件 + /// + /// 消息内容 + private void SetRecvMsgEvent(string msgContent) + { + EventHandler RecvedHandler; + RecvedHandler = DataReceived; + if (RecvedHandler != null) + { + RecvedHandler.Invoke(this, new ViewMsgEventArgs() { MsgContent = msgContent }); + } + } + + /// + /// 设置发送消息事件 + /// + /// 消息内容 + private void SetSendMsgEvent(string msgContent) + { + EventHandler SendedHandler; + SendedHandler = DataSended; + if (SendedHandler != null) + { + SendedHandler.Invoke(this, new ViewMsgEventArgs() { MsgContent = msgContent }); + } + } + + #endregion 事件定义 + + #region 结构体 + + public RfidReadWriteTool() + { + } + + public RfidReadWriteTool(string ipaddr) + { + _ipaddr = ipaddr; + } + + public RfidReadWriteTool(string ipaddr, string subnet, string gateway, int port) + { + _ipaddr = ipaddr; + _subnet = subnet; + _gateway = gateway; + _port = port; + } + + #endregion 结构体 + + public RfidReadModel RfidReadModel; + + /// + /// RFID读写器连接 + /// + /// + /// + /// -1:初始默认值;0:连接成功;1:超时;2:无响应 + public bool ConnectRfid() + { + Log.Info($"begin to connect tcp://{_ipaddr}"); + _rfid_reader = SReader.Create("tcp://" + _ipaddr); + try + { + _rfid_reader.Connect(); + IsConnected = true; + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + IsConnected = false; + } + + Log.Info($"connect tcp://{_ipaddr} {IsConnected}"); + + SetConnectEvent(_isconnected, "RFID读写器连接成功!"); + _rfid_reader.TagRead += _rfid_reader_TagRead; + return true; + } + + /// + /// 标签触发读取方法 + /// + /// + /// + private void _rfid_reader_TagRead(object sender, TagReadDataEventArgs tagData) + { + try + { + byte[] userDatas = tagData.TagData.Data; + + string strResult = ""; + string[] strTemps = null; + string strVelNo = ""; + if (userDatas != null) + { + string strUser = Encoding.ASCII.GetString(userDatas); + if (!string.IsNullOrEmpty(strUser)) + { + strResult = strUser.Replace("\0", "").Replace(" ", ""); + } + + strTemps = strResult.Split(';'); + + if (strTemps.Length == 4) + { + if (strTemps[3] != "") + { + byte[] bytesVelNo = ToByteByHexStr(strTemps[3]); + Encoding gbEcoding = Encoding.GetEncoding("gb2312"); + strVelNo = gbEcoding.GetString(bytesVelNo); + } + } + } + + strResult = "VIN码:" + strTemps[0] + ";车型号:" + strTemps[1] + ";车辆MAC:" + strTemps[2] + ";车牌号:" + strVelNo; + SetRecvMsgEvent(strResult); + + RfidReadModel = new RfidReadModel() + { + Result = 1, + VelVin = strTemps[0], + VelMac = strTemps[2], + VelNo = strTemps[3], + }; + } + catch (Exception ex) + { + ex.ToString(); + } + } + + /// + /// RFID读写器关闭 + /// + /// -1:初始默认值;0:连接成功;1:超时;2:无响应 + public bool CloseRfid() + { + if (_rfid_reader != null) + { + _rfid_reader.ShutDown(); + _rfid_reader.TagRead -= _rfid_reader_TagRead; //删除事件 + _isconnected = false; + SetConnectEvent(true, "RFID读写器断开成功!"); + return true; + } + + return true; + } + + /// + /// 写入单个标签值 + /// + public bool WriteRfidSingleTagResult(byte[] writeResult) + { + try + { + if (writeResult != null) + { + StopRfidResult(); + + //标签内存区。RESERVED (0x0),EPC (0x1),TID (0x2),USER (0x3); + Gen2.Bank userBank = Gen2.Bank.USER; + //起始地址,单位:字 + int wordPtrUser = 0; + //字节长度,单位:字 + int wordLenUser = 0; + //要写入的数据 + _user_datas = writeResult; + //访问密码,若没有锁定,可为0 + int accessPsd = 0; + wordLenUser = _user_datas.Length / 2; //长度必须偶数 + + //写数据对象 + Gen2.WriteData dataWrtUser = + new Gen2.WriteData(userBank, wordPtrUser, wordLenUser, _user_datas, accessPsd); + + //天线 + UInt16 ant = 0x01; + _rfid_reader.WriteMemory(ant, dataWrtUser, null); + SetRecvMsgEvent("RFID电子标签USER区:写入成功!"); + } + + return true; + } + catch (ReaderCommException e) + { + SetRecvMsgEvent(e.ToString()); + return false; + } + } + + /// + /// 盘点电子标签用户区数据 + /// + public bool ScanRfidUserDataTag() + { + try + { + if (_rfid_reader != null) + { + UInt16 ant = 0x01; + //标签内存区。RESERVED (0x0),EPC (0x1),TID (0x2),USER (0x3); + Gen2.Bank userBank = Gen2.Bank.USER; + //读取地址,单位:字 + int readAdrUser = 0; + //读取长度,单位:字 + int readLenUser = 36; + //访问密码,若没有锁定,可为0 + int accessPsd = 0; + Gen2.EmbedTagOp mixEmbedTag = new Gen2.EmbedTagOp(userBank, readAdrUser, readLenUser, accessPsd); + //_rfid_reader.Inventry(ant, null); + //Thread.Sleep(10); + _rfid_reader.Inventry_mix(ant, mixEmbedTag, null); + return true; + } + + return false; + } + catch (Exception ex) + { + ex.ToString(); + return false; + } + } + + /// + /// 停读 + /// + public bool StopRfidResult() + { + try + { + if (_rfid_reader != null) + { + _rfid_reader.Inventry_stop(); + SetRecvMsgEvent("RFID电子标签:停止扫读成功"); + return true; + } + + return false; + } + catch (Exception ex) + { + SetRecvMsgEvent("RFID电子标签:停止扫读失败"); + ex.ToString(); + return false; + } + } + + /// + /// 获取16进制字符串的字节数组 + /// + /// hexString 16进制字符串 + /// 字节数组 + public byte[] ToByteByHexStr(string hexString) + { + if (hexString == null) + return null; + + hexString = hexString.Replace(" ", ""); + if ((hexString.Length % 2) != 0) + hexString += " "; + byte[] returnBytes = new byte[hexString.Length / 2]; + for (int i = 0; i < returnBytes.Length; i++) + returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); + return returnBytes; + } +} diff --git a/Rfid/Rfid/RfidServer.cs b/Rfid/Rfid/RfidServer.cs new file mode 100644 index 0000000..a5a18b9 --- /dev/null +++ b/Rfid/Rfid/RfidServer.cs @@ -0,0 +1,71 @@ +using System; +using DotNetty.Codecs.Http; +using DotNetty.Common.Internal.Logging; +using DotNetty.Handlers.Logging; +using DotNetty.Handlers.Streams; +using DotNetty.Handlers.Timeout; +using DotNetty.Transport.Bootstrapping; +using DotNetty.Transport.Channels; +using DotNetty.Transport.Channels.Sockets; +using log4net; +using Microsoft.Extensions.Logging; +using LogLevel = DotNetty.Handlers.Logging.LogLevel; + +namespace Rfid; + +public class RfidServer: IDisposable +{ + private static readonly ILog Log = LogManager.GetLogger(typeof(RfidServer)); + + private static MultithreadEventLoopGroup? bossGroup; + private static MultithreadEventLoopGroup? workerGroup; + private static ServerBootstrap? bootstrap; + + private int _port = 9000; + + public LogLevel? LogLevel { get; set; } + + + private void InitBootstrap() + { + if (LogLevel != null) + { + InternalLoggerFactory.DefaultFactory.AddProvider(new Log4NetProvider()); + } + + bossGroup = new MultithreadEventLoopGroup(); + workerGroup = new MultithreadEventLoopGroup(); + bootstrap = new ServerBootstrap(); + bootstrap + .Group(bossGroup, workerGroup) // 设置主和工作线程组 + .Channel() // 设置通道模式为TcpSocket + .Option(ChannelOption.SoKeepalive, true) //保持连接 + .Handler(new LoggingHandler()) + .ChildHandler(new ActionChannelInitializer(channel => + { + var pipeline = channel.Pipeline; + pipeline.AddLast(new LoggingHandler()); + //业务handler ,这里是实际处理业务的Handler + pipeline.AddLast(new HttpServerCodec()); + + pipeline.AddLast(new HttpHandler()); + })); + } + + public void Start(int port = 9000) + { + if (bossGroup == null) + { + InitBootstrap(); + } + + IChannel channel = bootstrap.BindAsync(_port).Result; + Log.Info($"server listen {_port}"); + } + + public void Dispose() + { + bossGroup.ShutdownGracefullyAsync().Wait(); + workerGroup.ShutdownGracefullyAsync().Wait(); + } +} diff --git a/Rfid/Rfid/ViewEventArgs.cs b/Rfid/Rfid/ViewEventArgs.cs new file mode 100644 index 0000000..9b6cf80 --- /dev/null +++ b/Rfid/Rfid/ViewEventArgs.cs @@ -0,0 +1,25 @@ + +using System; + +namespace Rfid; + + +public class ViewEventArgs : EventArgs +{ + /// + /// 连接状态 + /// + public bool IsConnected { get; set; } + /// + /// 连接结果消息 + /// + public string MsgContent { get; set; } +} + +public class ViewMsgEventArgs : EventArgs +{ + /// + /// 发送或接收消息 + /// + public string MsgContent { get; set; } +} diff --git a/Rfid/lib/SRGReaderAPI.dll b/Rfid/lib/SRGReaderAPI.dll new file mode 100644 index 0000000..06ebe84 Binary files /dev/null and b/Rfid/lib/SRGReaderAPI.dll differ diff --git a/Rfid/log4net.config b/Rfid/log4net.config new file mode 100644 index 0000000..555d107 --- /dev/null +++ b/Rfid/log4net.config @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Rfid/packages.config b/Rfid/packages.config new file mode 100644 index 0000000..0b77b09 --- /dev/null +++ b/Rfid/packages.config @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Service/Service.csproj b/Service/Service.csproj index 433e1ae..e8b6d9a 100644 --- a/Service/Service.csproj +++ b/Service/Service.csproj @@ -24,4 +24,10 @@ + + + bin\Debug\net6.0\SRGReaderAPI.dll + + + diff --git a/WinFormStarter/Program.cs b/WinFormStarter/Program.cs index 72a6f73..124c974 100644 --- a/WinFormStarter/Program.cs +++ b/WinFormStarter/Program.cs @@ -58,4 +58,4 @@ internal static class Program var result = MessageBox.Show("系统发生错误,您需要退出系统吗?", "异常", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) Application.Exit(); } -} \ No newline at end of file +} diff --git a/hnBackVehicle.sln b/hnBackVehicle.sln index a044641..020f84f 100644 --- a/hnBackVehicle.sln +++ b/hnBackVehicle.sln @@ -27,6 +27,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Framework", "Framework", "{ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Business", "Business", "{C9515084-B676-4C33-9FE7-E0B860493A4F}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rfid", "Rfid\Rfid.csproj", "{053079C7-C9EE-49F4-B9CB-F06D14AEB027}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -69,6 +71,10 @@ Global {17044C11-3794-4938-BA80-C061BD871AE0}.Debug|Any CPU.Build.0 = Debug|Any CPU {17044C11-3794-4938-BA80-C061BD871AE0}.Release|Any CPU.ActiveCfg = Release|Any CPU {17044C11-3794-4938-BA80-C061BD871AE0}.Release|Any CPU.Build.0 = Release|Any CPU + {053079C7-C9EE-49F4-B9CB-F06D14AEB027}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {053079C7-C9EE-49F4-B9CB-F06D14AEB027}.Debug|Any CPU.Build.0 = Debug|Any CPU + {053079C7-C9EE-49F4-B9CB-F06D14AEB027}.Release|Any CPU.ActiveCfg = Release|Any CPU + {053079C7-C9EE-49F4-B9CB-F06D14AEB027}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -83,6 +89,7 @@ Global {C2380814-15D4-491D-ADF2-ADC68617C3FA} = {C9515084-B676-4C33-9FE7-E0B860493A4F} {01D2CC15-F1FD-4E22-845A-2D2473662860} = {C9515084-B676-4C33-9FE7-E0B860493A4F} {A6C2AA7F-B2A2-4AE0-AE84-49BE36B990EC} = {C9515084-B676-4C33-9FE7-E0B860493A4F} + {053079C7-C9EE-49F4-B9CB-F06D14AEB027} = {E0B949DC-17FE-414D-8898-937A317BB853} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {3E10BF3D-9914-44B1-A6AA-FCF013C3F155}