master
rszn 6 months ago
parent e1efbf7282
commit 10ca37e4e4

@ -75,7 +75,8 @@ public class TcpServer<TH, TD, TE> : IDisposable where TH : IChannelHandler
public void Dispose()
{
Log.Info(this + " Dispose");
bossGroup?.ShutdownGracefullyAsync();
bossGroup?.ShutdownGracefullyAsync().Wait();
workerGroup?.ShutdownGracefullyAsync().Wait();
}
private void ResolveEncode(IChannelPipeline pipeline)

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?><configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.DependencyInjection.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Logging" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Logging.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Primitives" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

@ -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();
}
}
}

@ -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")]

@ -0,0 +1,162 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"
Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"/>
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{053079C7-C9EE-49F4-B9CB-F06D14AEB027}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Rfid</RootNamespace>
<AssemblyName>Rfid</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<LangVersion>10</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="DotNetty.Buffers, Version=0.7.5.0, Culture=neutral, PublicKeyToken=bc13ca065fa06c29, processorArchitecture=MSIL">
<HintPath>..\packages\DotNetty.Buffers.0.7.5\lib\net472\DotNetty.Buffers.dll</HintPath>
</Reference>
<Reference Include="DotNetty.Codecs, Version=0.7.5.0, Culture=neutral, PublicKeyToken=bc13ca065fa06c29, processorArchitecture=MSIL">
<HintPath>..\packages\DotNetty.Codecs.0.7.5\lib\net472\DotNetty.Codecs.dll</HintPath>
</Reference>
<Reference Include="DotNetty.Codecs.Http, Version=0.7.5.0, Culture=neutral, PublicKeyToken=bc13ca065fa06c29, processorArchitecture=MSIL">
<HintPath>..\packages\DotNetty.Codecs.Http.0.7.5\lib\net472\DotNetty.Codecs.Http.dll</HintPath>
</Reference>
<Reference Include="DotNetty.Common, Version=0.7.5.0, Culture=neutral, PublicKeyToken=bc13ca065fa06c29, processorArchitecture=MSIL">
<HintPath>..\packages\DotNetty.Common.0.7.5\lib\net472\DotNetty.Common.dll</HintPath>
</Reference>
<Reference Include="DotNetty.Handlers, Version=0.7.5.0, Culture=neutral, PublicKeyToken=bc13ca065fa06c29, processorArchitecture=MSIL">
<HintPath>..\packages\DotNetty.Handlers.0.7.5\lib\net472\DotNetty.Handlers.dll</HintPath>
</Reference>
<Reference Include="DotNetty.Transport, Version=0.7.5.0, Culture=neutral, PublicKeyToken=bc13ca065fa06c29, processorArchitecture=MSIL">
<HintPath>..\packages\DotNetty.Transport.0.7.5\lib\net472\DotNetty.Transport.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=2.0.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.2.0.15\lib\net45\log4net.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Bcl.AsyncInterfaces, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Bcl.AsyncInterfaces.5.0.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Configuration.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.Abstractions, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Configuration.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.Binder, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.Binder.2.2.4\lib\netstandard2.0\Microsoft.Extensions.Configuration.Binder.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.DependencyInjection, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.DependencyInjection.5.0.0\lib\net461\Microsoft.Extensions.DependencyInjection.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.5.0.0\lib\net461\Microsoft.Extensions.DependencyInjection.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Logging, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Logging.5.0.0\lib\net461\Microsoft.Extensions.Logging.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Logging.Abstractions, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Logging.Abstractions.5.0.0\lib\net461\Microsoft.Extensions.Logging.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore, Version=8.0.0.0, Culture=neutral, PublicKeyToken=5d1104efbd0e675d, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Logging.Log4Net.AspNetCore.8.0.0\lib\netstandard2.0\Microsoft.Extensions.Logging.Log4Net.AspNetCore.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Options, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Options.5.0.0\lib\net461\Microsoft.Extensions.Options.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Primitives, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Primitives.5.0.0\lib\net461\Microsoft.Extensions.Primitives.dll</HintPath>
</Reference>
<Reference Include="mscorlib" />
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="SRGReaderAPI">
<HintPath>lib\SRGReaderAPI.dll</HintPath>
</Reference>
<Reference Include="System"/>
<Reference Include="System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll</HintPath>
</Reference>
<Reference Include="System.Collections.Immutable, Version=1.2.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Collections.Immutable.1.5.0\lib\netstandard2.0\System.Collections.Immutable.dll</HintPath>
</Reference>
<Reference Include="System.Configuration" />
<Reference Include="System.Core"/>
<Reference Include="System.Data"/>
<Reference Include="System.Diagnostics.DiagnosticSource, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Diagnostics.DiagnosticSource.5.0.0\lib\net46\System.Diagnostics.DiagnosticSource.dll</HintPath>
</Reference>
<Reference Include="System.Memory, Version=4.0.1.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Memory.4.5.4\lib\net461\System.Memory.dll</HintPath>
</Reference>
<Reference Include="System.Numerics" />
<Reference Include="System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.5.0.0\lib\net45\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Tasks.Extensions, Version=4.2.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.ValueTuple.4.5.0\lib\net47\System.ValueTuple.dll</HintPath>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Xml"/>
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs"/>
<Compile Include="Properties\AssemblyInfo.cs"/>
<Compile Include="Rfid\HttpHandler.cs" />
<Compile Include="Rfid\RfidMgr.cs" />
<Compile Include="Rfid\RfidReadModel.cs" />
<Compile Include="Rfid\RfidReadWriteTool.cs" />
<Compile Include="Rfid\RfidServer.cs" />
<Compile Include="Rfid\ViewEventArgs.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Content Include="log4net.config">
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets"/>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

@ -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<DefaultHttpRequest>
{
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();
}

@ -0,0 +1,65 @@
namespace Rfid;
public static class RfidMgr
{
private static RfidReadWriteTool RfidReadWriteTool = new RfidReadWriteTool("172.0.30.100");
/// <summary>
/// 连接
/// </summary>
/// <returns></returns>
public static bool Connect()
{
RfidReadWriteTool.CloseRfid();
bool bResult = RfidReadWriteTool.ConnectRfid();
return bResult;
}
/// <summary>
/// 连接
/// </summary>
/// <returns></returns>
public static bool Connected()
{
return RfidReadWriteTool.IsConnected;
}
/// <summary>
/// 断开
/// </summary>
/// <returns></returns>
public static bool CloseRfid()
{
bool bResult = RfidReadWriteTool.CloseRfid();
return bResult;
}
/// <summary>
/// 开始读
/// </summary>
/// <returns></returns>
public static bool BeginRead()
{
bool bResult = RfidReadWriteTool.ScanRfidUserDataTag();
return bResult;
}
/// <summary>
/// 停止读
/// </summary>
/// <returns></returns>
public static bool StopRead()
{
bool bResult = RfidReadWriteTool.StopRfidResult();
return bResult;
}
/// <summary>
/// 读取信息
/// </summary>
/// <returns></returns>
public static RfidReadModel? ReadRifd()
{
return RfidReadWriteTool.RfidReadModel;
}
}

@ -0,0 +1,25 @@
namespace Rfid;
public class RfidReadModel
{
/// <summary>
/// 1成功 0:失败
/// </summary>
public int Result { get; set; }
/// <summary>
/// 车辆VIN码
/// </summary>
public string VelVin { get; set; }
/// <summary>
/// 车辆MAC地址
/// </summary>
public string? VelMac { set; get; }
/// <summary>
/// 车辆车牌号
/// </summary>
public string VelNo { set; get; }
}

@ -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 字段属性
/// <summary>
/// IP地址
/// </summary>
private string _ipaddr = "172.0.30.9";
/// <summary>
/// RFID连接IP地址
/// </summary>
public string IpAddr
{
get { return _ipaddr; }
set { _ipaddr = value; }
}
/// <summary>
/// 子网掩码
/// </summary>
private string _subnet = "255.255.255.0";
/// <summary>
/// RFID连接的子网掩码
/// </summary>
public string Subnet
{
get { return _subnet; }
set { _subnet = value; }
}
/// <summary>
/// 网关
/// </summary>
private string _gateway = "172.0.30.1";
/// <summary>
/// RFID连接的网关
/// </summary>
public string Gateway
{
get { return _gateway; }
set { _gateway = value; }
}
/// <summary>
/// 端口
/// </summary>
private int _port = 9090;
/// <summary>
/// RFID连接端口
/// </summary>
public int Port
{
get { return _port; }
set { _port = value; }
}
/// <summary>
/// 连接超时时间(ms)
/// </summary>
private int _timeout = 1000;
/// <summary>
/// 连接超时时间(ms)
/// </summary>
public int TimeOut
{
get { return _timeout; }
set { _timeout = value; }
}
/// <summary>
/// 读写器
/// </summary>
private SReader _rfid_reader = null;
/// <summary>
/// RFID连接客户端
/// </summary>
public SReader RfidReader
{
get { return _rfid_reader; }
set { _rfid_reader = value; }
}
/// <summary>
/// 客户端目前连接状态
/// </summary>
private bool _isconnected = false;
/// <summary>
/// 通讯是否连接
/// </summary>
public bool IsConnected
{
get { return _isconnected; }
set { _isconnected = value; }
}
/// <summary>
/// UserData
/// </summary>
private byte[] _user_datas = null;
#endregion 字段属性
#region 事件定义
/// <summary>
/// 连接状态
/// </summary>
public event EventHandler<ViewEventArgs> ConnectedChanged;
/// <summary>
/// 数据已接收
/// </summary>
public event EventHandler<ViewMsgEventArgs> DataReceived;
/// <summary>
/// 已发送的数据
/// </summary>
public event EventHandler<ViewMsgEventArgs> DataSended;
/// <summary>
/// 设置监听事件
/// </summary>
/// <param name="isConnected">是否监听</param>
/// <param name="msgContent">监听消息事件</param>
private void SetConnectEvent(bool isConnected, string msgContent)
{
EventHandler<ViewEventArgs> ConnectedHandler;
ConnectedHandler = ConnectedChanged;
if (ConnectedHandler != null)
{
ConnectedHandler.Invoke(this, new ViewEventArgs() { IsConnected = isConnected, MsgContent = msgContent });
}
}
/// <summary>
/// 设置接收消息事件
/// </summary>
/// <param name="msgContent">消息内容</param>
private void SetRecvMsgEvent(string msgContent)
{
EventHandler<ViewMsgEventArgs> RecvedHandler;
RecvedHandler = DataReceived;
if (RecvedHandler != null)
{
RecvedHandler.Invoke(this, new ViewMsgEventArgs() { MsgContent = msgContent });
}
}
/// <summary>
/// 设置发送消息事件
/// </summary>
/// <param name="msgContent">消息内容</param>
private void SetSendMsgEvent(string msgContent)
{
EventHandler<ViewMsgEventArgs> 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;
/// <summary>
/// RFID读写器连接
/// </summary>
/// <param name="ipAddress"></param>
/// <param name="nPort"></param>
/// <returns>-1:初始默认值0:连接成功1:超时2:无响应</returns>
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;
}
/// <summary>
/// 标签触发读取方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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();
}
}
/// <summary>
/// RFID读写器关闭
/// </summary>
/// <returns>-1:初始默认值0:连接成功1:超时2:无响应</returns>
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;
}
/// <summary>
/// 写入单个标签值
/// </summary>
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;
}
}
/// <summary>
/// 盘点电子标签用户区数据
/// </summary>
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;
}
}
/// <summary>
/// 停读
/// </summary>
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;
}
}
/// <summary>
/// 获取16进制字符串的字节数组
/// </summary>
/// <param name="hexString">hexString 16进制字符串</param>
/// <returns>字节数组</returns>
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;
}
}

@ -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<TcpServerSocketChannel>() // 设置通道模式为TcpSocket
.Option(ChannelOption.SoKeepalive, true) //保持连接
.Handler(new LoggingHandler())
.ChildHandler(new ActionChannelInitializer<ISocketChannel>(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();
}
}

@ -0,0 +1,25 @@

using System;
namespace Rfid;
public class ViewEventArgs : EventArgs
{
/// <summary>
/// 连接状态
/// </summary>
public bool IsConnected { get; set; }
/// <summary>
/// 连接结果消息
/// </summary>
public string MsgContent { get; set; }
}
public class ViewMsgEventArgs : EventArgs
{
/// <summary>
/// 发送或接收消息
/// </summary>
public string MsgContent { get; set; }
}

Binary file not shown.

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<log4net>
<!-- 控制台日志配置 -->
<appender name="Console" type="log4net.Appender.ConsoleAppender">
<!-- 日志输出格式 -->
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %5level [%thread] (%file:%line) - %message%newline"/>
</layout>
</appender>
<!-- 文件存储日志配置 -->
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<!-- 保存文件的名称 -->
<file value="logs\rfid.log"/>
<appendToFile value="true"/>
<!-- 文件的编码方式 -->
<param name="Encoding" value="UTF-8"/>
<!-- 每个文件的大小 -->
<maximumFileSize value="100MB"/>
<!-- 保存文件数量 -->
<maxSizeRollBackups value="2"/>
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<!-- 日志输出格式 -->
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level %thread %logger - %message%newline"/>
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="Console"/>
<appender-ref ref="RollingFile"/>
</root>
</log4net>

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="DotNetty.Buffers" version="0.7.5" targetFramework="net48" />
<package id="DotNetty.Codecs" version="0.7.5" targetFramework="net48" />
<package id="DotNetty.Codecs.Http" version="0.7.5" targetFramework="net48" />
<package id="DotNetty.Common" version="0.7.5" targetFramework="net48" />
<package id="DotNetty.Handlers" version="0.7.5" targetFramework="net48" />
<package id="DotNetty.Transport" version="0.7.5" targetFramework="net48" />
<package id="Microsoft.Bcl.AsyncInterfaces" version="5.0.0" targetFramework="net48" />
<package id="Microsoft.Extensions.Configuration" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.Extensions.Configuration.Abstractions" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.Extensions.Configuration.Binder" version="2.2.4" targetFramework="net48" />
<package id="Microsoft.Extensions.DependencyInjection" version="5.0.0" targetFramework="net48" />
<package id="Microsoft.Extensions.DependencyInjection.Abstractions" version="5.0.0" targetFramework="net48" />
<package id="Microsoft.Extensions.Logging" version="5.0.0" targetFramework="net48" />
<package id="Microsoft.Extensions.Logging.Abstractions" version="5.0.0" targetFramework="net48" />
<package id="Microsoft.Extensions.Logging.Log4Net.AspNetCore" version="8.0.0" targetFramework="net48" />
<package id="Microsoft.Extensions.Options" version="5.0.0" targetFramework="net48" />
<package id="Microsoft.Extensions.Primitives" version="5.0.0" targetFramework="net48" />
<package id="Newtonsoft.Json" version="13.0.3" targetFramework="net48" />
<package id="System.Buffers" version="4.5.1" targetFramework="net48" />
<package id="System.Collections.Immutable" version="1.5.0" targetFramework="net48" />
<package id="System.Diagnostics.DiagnosticSource" version="5.0.0" targetFramework="net48" />
<package id="System.Memory" version="4.5.4" targetFramework="net48" />
<package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net48" />
<package id="System.Runtime.CompilerServices.Unsafe" version="5.0.0" targetFramework="net48" />
<package id="System.Threading.Tasks.Extensions" version="4.5.4" targetFramework="net48" />
<package id="System.ValueTuple" version="4.5.0" targetFramework="net48" />
<package id="log4net" version="2.0.15" targetFramework="net48" />
</packages>

@ -24,4 +24,10 @@
<ProjectReference Include="..\Repository\Repository.csproj"/>
</ItemGroup>
<ItemGroup>
<Reference Include="SRGReaderAPI">
<HintPath>bin\Debug\net6.0\SRGReaderAPI.dll</HintPath>
</Reference>
</ItemGroup>
</Project>

@ -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}

Loading…
Cancel
Save