master
CaesarBao 1 month ago
parent b7820fe7a3
commit 2a708e8c30

@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
@ -6,7 +7,28 @@
namespace Mesnac.DeviceAdapter
{
public delegate void RecvIdentifyData(ushort iLen, byte[] pData, byte Antenna, UInt16 iDeviceId, string strId, string sensorType);
public class TagInfo
{
public byte[] PC = new byte[2];
public int Count;
public int RSSI;
public int Antana;
public byte[] EPC;
public byte[] Data;
public string PCstring = null;
public string EPCstring = null;
public DateTime Time;
}
//public delegate void RecvIdentifyData(ushort iLen, byte[] pData, byte Antenna, UInt16 iDeviceId, string strId, string sensorType);
public delegate void RecvIdentifyData(ushort iLen, List<TagInfo> tagInfos, byte Antenna, UInt16 iDeviceId, string strId, string sensorType);
public enum G2MemBank
{
@ -141,6 +163,8 @@ namespace Mesnac.DeviceAdapter
/// <param name="ReadCounts">失败重读次数</param>
Byte Device_GetOneIdentifyData(ref Byte[] pReadData, Byte Antenna, UInt16 Timedout, int ReadCounts);
List<TagInfo> Device_GetAllIdentifyData(Byte Antenna, UInt16 Timedout, int ReadCounts);
/// <summary>
/// 根据天线号识别单个标签EPC数据只返回一条
/// </summary>
@ -210,6 +234,13 @@ namespace Mesnac.DeviceAdapter
/// <returns>总长度0为失败</returns>
/// <param name="pReadData">获得的自报数据,格式为长度,数据,。。。。。。长度,数据,其中长度占一个字节</param>
UInt16 Device_GetReportData(ref byte[] pReadData, Byte Antenna, UInt32 Timedout);
/// <summary>
/// 点亮报警灯
/// </summary>
/// <param name="port"></param>
/// <returns></returns>
bool Device_WriteAlarmLight(int port, UInt16 Timedout);
}
}

@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Mesnac.DeviceAdapter</RootNamespace>
<AssemblyName>DeviceAdapter</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>

@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>HighWay.Download</RootNamespace>
<AssemblyName>自动更新</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
@ -22,6 +22,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
@ -31,6 +32,7 @@
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>System_Update.ico</ApplicationIcon>

@ -19,7 +19,7 @@ namespace HighWay.Download.Properties {
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
@ -47,8 +47,8 @@ namespace HighWay.Download.Properties {
}
/// <summary>
/// 重写当前线程的 CurrentUICulture 属性
/// 重写当前线程的 CurrentUICulture 属性
/// 重写当前线程的 CurrentUICulture 属性,对
/// 使用此强类型资源类的所有资源查找执行重写。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {

@ -12,7 +12,7 @@ namespace HighWay.Download.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.1.0.0")]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.9.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

@ -1,3 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/></startup></configuration>

@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31515.178
# Visual Studio Version 17
VisualStudioVersion = 17.9.34723.18
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HighWayAssemble", "HighWayAssemble\HighWayAssemble.csproj", "{BD5F6AA1-B451-4D2B-BCD3-E69A2D1699EF}"
EndProject
@ -25,6 +25,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "DeviceAdapter", "DeviceAdap
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Highway.Assemble.SqlSugar", "Highway.Assemble.SqlSugar\Highway.Assemble.SqlSugar.csproj", "{59C06619-BED8-45D8-85CF-ED55D6516C65}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mesnac.DeviceAdapter.RFly_I160", "Mesnac.DeviceAdapter.RFly_I160\Mesnac.DeviceAdapter.RFly_I160.csproj", "{786B9D51-D67A-4235-B082-78E9CF4FCFB6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -67,6 +69,10 @@ Global
{59C06619-BED8-45D8-85CF-ED55D6516C65}.Debug|Any CPU.Build.0 = Debug|Any CPU
{59C06619-BED8-45D8-85CF-ED55D6516C65}.Release|Any CPU.ActiveCfg = Release|Any CPU
{59C06619-BED8-45D8-85CF-ED55D6516C65}.Release|Any CPU.Build.0 = Release|Any CPU
{786B9D51-D67A-4235-B082-78E9CF4FCFB6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{786B9D51-D67A-4235-B082-78E9CF4FCFB6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{786B9D51-D67A-4235-B082-78E9CF4FCFB6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{786B9D51-D67A-4235-B082-78E9CF4FCFB6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -76,6 +82,7 @@ Global
{A19A79D7-D43B-4284-9892-CA27B37AC32C} = {A015D4C2-0D7E-459A-87F0-40475DBF636B}
{86E4F08E-6155-4130-A6C7-C13CFB30FFDC} = {A015D4C2-0D7E-459A-87F0-40475DBF636B}
{4FADD98F-9C73-4D2F-9AC1-CF8993265D8E} = {5533A820-067D-4632-85DB-0D1D4610357A}
{786B9D51-D67A-4235-B082-78E9CF4FCFB6} = {A015D4C2-0D7E-459A-87F0-40475DBF636B}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {A184E143-CBFB-4809-9DE1-6FCD90C60186}

@ -4,12 +4,12 @@
<section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="CollectID" value="101" />
<add key="SqlString" value="Persist Security Info=True;Password=123456;User ID=sa;Initial Catalog=Newzhongjianjian;Data Source=127.0.0.1;Connection Timeout=5" />
<!--<add key="SqlString" value="Persist Security Info=True;Password=haiwei@123;User ID=sa;Initial Catalog=Newzhongjianjian;Data Source=172.18.29.24;Connection Timeout=5" />-->
<!--<add key="SqlString" value="Persist Security Info=True;Password=123456;User ID=sa;Initial Catalog=Newzhongjianjian;Data Source=127.0.0.1;Connection Timeout=5" />-->
<add key="SqlString" value="Persist Security Info=True;Password=haiwei@123;User ID=sa;Initial Catalog=XJMIDDBTOMES;Data Source=119.45.202.115;Connection Timeout=5" />
<add key="UpdateUrl" value="ftp://118.24.158.141" />
<!--定时删除日志时间间隔(单位:月)-->
<add key="DeleteLogIntervel" value="2" />
@ -157,7 +157,31 @@
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.5.0.0" newVersion="3.5.0.0" />
<bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Threading.Tasks.Extensions" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.1" newVersion="4.2.0.1" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Numerics.Vectors" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.4.0" newVersion="4.1.4.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>

@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>HighWayAssemble</RootNamespace>
<AssemblyName>HighWayAssemble</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<TargetFrameworkProfile />
@ -60,8 +60,11 @@
<SpecificVersion>False</SpecificVersion>
<HintPath>dll\log4net.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=3.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.3.5.8\lib\35\Newtonsoft.Json.dll</HintPath>
<Reference Include="Microsoft.Bcl.AsyncInterfaces, Version=8.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Bcl.AsyncInterfaces.8.0.0\lib\netstandard2.0\Microsoft.Bcl.AsyncInterfaces.dll</HintPath>
</Reference>
<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="OPCControls">
<HintPath>..\dll\OPCControls.dll</HintPath>
@ -81,8 +84,33 @@
<HintPath>..\Highway.Assemble.SqlSugar\bin\Debug\SqlSugar.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\netstandard1.1\System.Buffers.dll</HintPath>
</Reference>
<Reference Include="System.configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Memory, Version=4.0.1.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Memory.4.5.5\lib\netstandard1.1\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=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Text.Encodings.Web, Version=8.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Text.Encodings.Web.8.0.0\lib\netstandard2.0\System.Text.Encodings.Web.dll</HintPath>
</Reference>
<Reference Include="System.Text.Json, Version=8.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Text.Json.8.0.5\lib\netstandard2.0\System.Text.Json.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\portable-net45+win8+wp8+wpa81\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\netstandard1.0\System.ValueTuple.dll</HintPath>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Xml.Linq" />
@ -93,11 +121,20 @@
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="TouchSocket, Version=2.0.0.0, Culture=neutral, PublicKeyToken=e66400a0f8ce7abb, processorArchitecture=MSIL">
<HintPath>..\packages\TouchSocket.2.0.0-beta.130\lib\net45\TouchSocket.dll</HintPath>
<Reference Include="TouchSocket, Version=3.1.0.0, Culture=neutral, PublicKeyToken=5f39d7da98dac6a9, processorArchitecture=MSIL">
<HintPath>..\packages\TouchSocket.3.1.0\lib\net45\TouchSocket.dll</HintPath>
</Reference>
<Reference Include="TouchSocket.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=e66400a0f8ce7abb, processorArchitecture=MSIL">
<HintPath>..\packages\TouchSocket.Core.2.0.0-beta.130\lib\net45\TouchSocket.Core.dll</HintPath>
<Reference Include="TouchSocket.Core, Version=3.1.0.0, Culture=neutral, PublicKeyToken=d6c415a2f58eda72, processorArchitecture=MSIL">
<HintPath>..\packages\TouchSocket.Core.3.1.0\lib\net45\TouchSocket.Core.dll</HintPath>
</Reference>
<Reference Include="TouchSocket.Http, Version=3.1.0.0, Culture=neutral, PublicKeyToken=ecea290704fb8ddd, processorArchitecture=MSIL">
<HintPath>..\packages\TouchSocket.Http.3.1.0\lib\net45\TouchSocket.Http.dll</HintPath>
</Reference>
<Reference Include="TouchSocket.Rpc, Version=3.1.0.0, Culture=neutral, PublicKeyToken=15eb0d7aa187fa38, processorArchitecture=MSIL">
<HintPath>..\packages\TouchSocket.Rpc.3.1.0\lib\net45\TouchSocket.Rpc.dll</HintPath>
</Reference>
<Reference Include="TouchSocket.WebApi, Version=3.1.0.0, Culture=neutral, PublicKeyToken=004e630594e1cb25, processorArchitecture=MSIL">
<HintPath>..\packages\TouchSocket.WebApi.3.1.0\lib\net45\TouchSocket.WebApi.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
@ -116,8 +153,9 @@
<Compile Include="Main\FrmDisplayModel.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Protocol\ApiServer.cs" />
<Compile Include="Protocol\MesHttpClient.cs" />
<Compile Include="Protocol\MsgUtil.cs" />
<Compile Include="Protocol\MyFixedHeaderCustomDataHandlingAdapter.cs" />
<Compile Include="SetCollectIDView.cs">
<SubType>Form</SubType>
</Compile>
@ -181,6 +219,10 @@
<Project>{a19a79d7-d43b-4284-9892-ca27b37ac32c}</Project>
<Name>Mesnac.DeviceAdapter.HWKC_81600</Name>
</ProjectReference>
<ProjectReference Include="..\Mesnac.DeviceAdapter.RFly_I160\Mesnac.DeviceAdapter.RFly_I160.csproj">
<Project>{786b9d51-d67a-4235-b082-78e9cf4fcfb6}</Project>
<Name>Mesnac.DeviceAdapter.RFly_I160</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Content Include="cloud_computing_128px_1222169_easyicon.net.ico" />
@ -188,6 +230,11 @@
<ItemGroup>
<WCFMetadata Include="Service References\" />
</ItemGroup>
<ItemGroup>
<Analyzer Include="..\packages\TouchSocket.Core.3.1.0\analyzers\dotnet\cs\TouchSocket.Core.SourceGenerator.dll" />
<Analyzer Include="..\packages\TouchSocket.Rpc.3.1.0\analyzers\dotnet\cs\TouchSocket.Rpc.SourceGenerator.dll" />
<Analyzer Include="..\packages\TouchSocket.WebApi.3.1.0\analyzers\dotnet\cs\TouchSocket.WebApi.SourceGenerator.dll" />
</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.

@ -6,15 +6,19 @@ using Highway.Assemble.Sql;
using Highway.Assemble.SqlSugar.serviceImpl;
using Highway.SocketServer;
using HighWayAssemble.Protocol;
using RRQMCore.XREF.Newtonsoft.Json.Serialization;
using RRQMSocket;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Http;
using TouchSocket.Rpc;
using TouchSocket.Sockets;
using IPHost = TouchSocket.Sockets.IPHost;
using SocketClient = TouchSocket.Sockets.SocketClient;
@ -34,11 +38,12 @@ namespace HighWayAssemble
// IConfigInfo configInfo = null;
ISoftInfo SoftInfo = null;
public static IAsyncSocketServer SocketServer = null;
public static MesHttpClient MesHttpClient = null;
IBoxDB m_BoxDB = null;
IEquipClient m_EquipClient = null;
private List<IOInfo> IO_Infolist = new List<IOInfo>();
private List<IOInfo> IO_OUTfolist = new List<IOInfo>();
private List<SocketClient> onLineClient;
private List<TcpSessionClient> onLineClient;
private SimpleTcpService tcpService;
private TcpService m_service;
List<byte[]> bufferlit = new List<byte[]>();
@ -65,11 +70,42 @@ namespace HighWayAssemble
Sql = App.Make<ISql>(SoftInfo.CollectInfo.sqlstring);
GetSoftInfo();
m_EquipClient = App.Make<IEquipClient>();
//创建webapi
var t = Task.Run(async delegate
{
await Task.Delay(10);
CreateTcp();
MesHttpClient = new MesHttpClient();
MesHttpClient.init();
var service = new HttpService();
await service.SetupAsync(new TouchSocketConfig()
.SetListenIPHosts(6001)
.ConfigureContainer(a =>
{
a.AddConsoleLogger();
a.AddRpcStore(store =>
{
store.RegisterServer<ApiServer>();//注册服务
});
})
.ConfigurePlugins(a =>
{
a.UseCheckClear();
a.UseWebApi()
.ConfigureConverter(converter =>
{
converter.AddJsonSerializerFormatter(new Newtonsoft.Json.JsonSerializerSettings() { Formatting = Newtonsoft.Json.Formatting.None });
});
//此插件是http的兜底插件应该最后添加。作用是当所有路由不匹配时返回404.且内部也会处理Option请求。可以更好的处理来自浏览器的跨域探测。
a.UseDefaultHttpServicePlugin();
}
));
await service.StartAsync();
await m_service.StartAsync();//启动
//CreatSocketServer();
InitEquipClient();
if (IsOPCFlag == 1)
@ -134,7 +170,7 @@ namespace HighWayAssemble
public int Length;
public byte[] data;
public long time;
internal SocketClient SocketClient;
internal TcpSessionClient SocketClient;
}
/// <summary>
/// 创建OPC客户端
@ -313,7 +349,7 @@ namespace HighWayAssemble
}
else
{
info = MsgUtil.bytesToHexStr(data, data.Length);
//info = MsgUtil.bytesToHexStr(data, data.Length);
}
App.TriggerHalt(EventSystem.updateSensorListInfo, id, info);
//Sql.InsertReadData(id.ToString(), info, 0);
@ -321,12 +357,12 @@ namespace HighWayAssemble
}
else
{
Head head = new Head();
head.start = 0x56;
short addr = GetMESCallback(id);
head.addr = addr;
head.mstaseq = 241;
head.control = 125 + 4;
//Head head = new Head();
//head.start = 0x56;
//short addr = GetMESCallback(id);
//head.addr = addr;
//head.mstaseq = 241;
//head.control = 125 + 4;
byte[] dataInfo;
string info = "";
if (data == null)
@ -345,39 +381,48 @@ namespace HighWayAssemble
}
else
{
dataInfo = data;// dataInfo = Encoding.ASCII.GetBytes(MsgUtil.bytesToHexStr(data, data.Length));//dataInfo = data;
info = MsgUtil.bytesToHexStr(data, data.Length);
if (data != null && data.Any())
{
info = string.Join(",", data.Select(item => item.EPCstring));
}
else
{
info = string.Empty; // 处理空集合的情况
}
//dataInfo = data;
// dataInfo = Encoding.ASCII.GetBytes(MsgUtil.bytesToHexStr(data, data.Length));//dataInfo = data;
//info = MsgUtil.bytesToHexStr(data, data.Length);
//info = Encoding.ASCII.GetString(data, 0, data.Length);
}
var num = BitConverter.GetBytes(id);
// = Encoding.ASCII.GetBytes(data);
head.length = (Int16)(4 + dataInfo.Length);
var headbuf = MsgUtil.StructToBytes(head);
byte[] sendbuf = new byte[7 + 4 + dataInfo.Length + 3];
Array.Copy(headbuf, 0, sendbuf, 0, headbuf.Length);
Array.Copy(num, 0, sendbuf, 7, num.Length);
Array.Copy(dataInfo, 0, sendbuf, 7 + 4, dataInfo.Length);
byte[] Verify = MsgUtil.CalculateVerify(sendbuf, sendbuf.Length - 3);
// Message[Message.Length - 2] = Verify;
Array.Copy(Verify, 0, sendbuf, sendbuf.Length - 3, 2);
sendbuf[sendbuf.Length - 1] = 0x86;
//var num = BitConverter.GetBytes(id);
//head.length = (Int16)(4 + dataInfo.Length);
//var headbuf = MsgUtil.StructToBytes(head);
//byte[] sendbuf = new byte[7 + 4 + dataInfo.Length + 3];
//Array.Copy(headbuf, 0, sendbuf, 0, headbuf.Length);
//Array.Copy(num, 0, sendbuf, 7, num.Length);
//Array.Copy(dataInfo, 0, sendbuf, 7 + 4, dataInfo.Length);
//byte[] Verify = MsgUtil.CalculateVerify(sendbuf, sendbuf.Length - 3);
//Array.Copy(Verify, 0, sendbuf, sendbuf.Length - 3, 2);
//sendbuf[sendbuf.Length - 1] = 0x86;
App.TriggerHalt(EventSystem.updateSensorListInfo, id, info);
var token = SendMessageToClient(addr, sendbuf);
FrmDisplayView.LogInfo.Info(string.Format("发送MES主动读取到的数据 MES地址:{0},消息内容:{1} --{2}", addr, MsgUtil.bytesToHexStr(sendbuf, sendbuf.Length), token == null ? "MES断开" : ""));
//var token = SendMessageToClient(addr, sendbuf);
//FrmDisplayView.LogInfo.Info(string.Format("发送MES主动读取到的数据 MES地址:{0},消息内容:{1} --{2}", addr, MsgUtil.bytesToHexStr(sendbuf, sendbuf.Length), token == null ? "MES断开" : ""));
//2022-11-17 添加注释等待时间10s
//Sql.InsertReadData(id.ToString(), info, 0);
await InsertRealWorkData(id.ToString(), info, 0);
//await InsertRealWorkData(id.ToString(), info, 0);
}
});
//传感器数据回调 主动读取EPC 125+3
m_EquipClient.RecSendData(async (id, data) =>
{
Head head = new Head();
head.start = 0x56;
short addr = GetMESCallback(id);
head.addr = addr;
head.mstaseq = 241;
head.control = 125 + 3;
//Head head = new Head();
//head.start = 0x56;
//short addr = GetMESCallback(id);
//head.addr = addr;
//head.mstaseq = 241;
//head.control = 125 + 3;
byte[] dataInfo;
string info = "";
if (data == null)
@ -394,36 +439,51 @@ namespace HighWayAssemble
}
else
{
dataInfo = data;// dataInfo = Encoding.ASCII.GetBytes(MsgUtil.bytesToHexStr(data, data.Length));//dataInfo = data;
info = MsgUtil.bytesToHexStr(data, data.Length);
if (data != null && data.Any())
{
info = string.Join(",", data.Select(item => item.EPCstring));
}
else
{
info = string.Empty; // 处理空集合的情况
}
//dataInfo = data;// dataInfo = Encoding.ASCII.GetBytes(MsgUtil.bytesToHexStr(data, data.Length));//dataInfo = data;
//info = MsgUtil.bytesToHexStr(data, data.Length);
//info = Encoding.ASCII.GetString(data, 0, data.Length);
}
var num = BitConverter.GetBytes(id);
// byte[] dataInfo = Encoding.ASCII.GetBytes(data);
head.length = (Int16)(4 + dataInfo.Length);
var headbuf = MsgUtil.StructToBytes(head);
byte[] sendbuf = new byte[7 + 4 + dataInfo.Length + 3];
Array.Copy(headbuf, 0, sendbuf, 0, headbuf.Length);
Array.Copy(num, 0, sendbuf, 7, num.Length);
Array.Copy(dataInfo, 0, sendbuf, 7 + 4, dataInfo.Length);
byte[] Verify = MsgUtil.CalculateVerify(sendbuf, sendbuf.Length - 3);
Array.Copy(Verify, 0, sendbuf, sendbuf.Length - 3, 2);
sendbuf[sendbuf.Length - 1] = 0x86;
//var num = BitConverter.GetBytes(id);
//// byte[] dataInfo = Encoding.ASCII.GetBytes(data);
//head.length = (Int16)(4 + dataInfo.Length);
//var headbuf = MsgUtil.StructToBytes(head);
//byte[] sendbuf = new byte[7 + 4 + dataInfo.Length + 3];
//Array.Copy(headbuf, 0, sendbuf, 0, headbuf.Length);
//Array.Copy(num, 0, sendbuf, 7, num.Length);
//Array.Copy(dataInfo, 0, sendbuf, 7 + 4, dataInfo.Length);
//byte[] Verify = MsgUtil.CalculateVerify(sendbuf, sendbuf.Length - 3);
//Array.Copy(Verify, 0, sendbuf, sendbuf.Length - 3, 2);
//sendbuf[sendbuf.Length - 1] = 0x86;
App.TriggerHalt(EventSystem.updateSensorListInfo, id, info);
var token = SendMessageToClient(addr, sendbuf);
FrmDisplayView.LogInfo.Info(string.Format("发送MES触发读取数据 MES地址:{0},消息内容:{1} --{2}", addr, MsgUtil.bytesToHexStr(sendbuf, sendbuf.Length), token == null ? "MES断开" : ""));
//var token = SendMessageToClient(addr, sendbuf);
//FrmDisplayView.LogInfo.Info(string.Format("发送MES触发读取数据 MES地址:{0},消息内容:{1} --{2}", addr, MsgUtil.bytesToHexStr(sendbuf, sendbuf.Length), token == null ? "MES断开" : ""));
//2022-11-17 添加注释等待时间10s
//Sql.InsertReadData(id.ToString(), info, 2);
await InsertRealWorkData(id.ToString(), info, 2);
MesParaData mesParaData = new MesParaData();
mesParaData.EQUID = id.ToString();
mesParaData.EPCID = info;
mesParaData.READSTATUS = info == "NoData" ? "1" : "0";
mesParaData.READTIME = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
//MesHttpClient.autoread(mesParaData);
//await InsertRealWorkData(id.ToString(), info, 2);
});
//自报数据回调
m_EquipClient.RecAutoData(async (id, data) =>
{
//if (IsRepeat(id, data)) //判断光电抖动
//{
// return;
//}
//MesHttpClient.autoread();
string info = "";
byte[] dataInfo;
if (data == null)
@ -698,7 +758,7 @@ namespace HighWayAssemble
}
else
{
tokens[i].SendAsync(Heartbuf, 0, 10);
tokens[i].SendAsync(Heartbuf);
FrmDisplayView.LogInfo.ErrorFormat("已连接MES软件编号" + tokens[i].Id + ",MES软件地址{0} ,端口号:{1},发送MES软件心跳报文:{2}", tokens[i].IP, tokens[i].Port, MsgUtil.bytesToHexStr(Heartbuf, Heartbuf.Length));
}
@ -971,35 +1031,29 @@ namespace HighWayAssemble
{
if (m_service == null)
{
onLineClient = new List<SocketClient>();
onLineClient = new List<TcpSessionClient>();
m_service = new TcpService();
m_service.Connected = this.M_service_Connected;//有客户端连接
m_service.Disconnected = this.M_service_Disconnected;//有客户端断开连接
//m_service.Connected = this.M_service_Connected;//有客户端连接
//m_service.Closed = this.M_service_Disconnected;//有客户端断开连接
//这里应该引入多线程并加锁处理
m_service.Received += (client, byteBlock, requestInfo) =>
{
//接收信息在CustomDataHandlingAdapter派生的适配器中byteBlock将为nullrequestInfo将为适配器定义的泛型
if (requestInfo is MyRequestInfo myRequestInfo)
{
FrmDisplayView.LogInfo.Info("》》》接收[" + client.IP + ":" + client.Port + "]客户端原始消息: " + MsgUtil.bytesToHexStr(myRequestInfo.Header, (int)myRequestInfo.Header.Length) + MsgUtil.bytesToHexStr(myRequestInfo.Body, (int)myRequestInfo.Body.Length) + "\r\n");
//此处可以处理MyFixedHeaderRequestInfo的相关信息了。
ParsingMessages(client, myRequestInfo);
string body = Encoding.UTF8.GetString(myRequestInfo.Body, 0, myRequestInfo.Body.Length);
}
};
//m_service.Received += (client,e) =>
//{
// //从客户端收到信息
// var mes = e.ByteBlock.Span;
// //FrmDisplayView.LogInfo.Info("》》》接收[" + client.IP + ":" + client.Port + "]客户端原始消息: " + MsgUtil.bytesToHexStr(myRequestInfo.Header, (int)myRequestInfo.Header.Length) + MsgUtil.bytesToHexStr(myRequestInfo.Body, (int)myRequestInfo.Body.Length) + "\r\n");
// //此处可以处理MyFixedHeaderRequestInfo的相关信息了。
// ParsingMessages(client, e.ByteBlock);
//};
}
m_service.Setup(new TouchSocketConfig()//载入配置
.SetListenIPHosts(new IPHost[] { new IPHost("0.0.0.0:" + SoftInfo.CollectInfo.Port) })//同时监听两个地址
.SetTcpDataHandlingAdapter(() => { return new MyFixedHeaderCustomDataHandlingAdapter(); })//配置适配器
//.SetTcpDataHandlingAdapter(() => { return new MyFixedHeaderCustomDataHandlingAdapter(); })//配置适配器
.SetMaxCount(10000)
.SetThreadCount(1000)
.SetCacheTimeoutEnable(false)
.ConfigureContainer(a =>//容器的配置顺序应该在最前面
{
@ -1010,8 +1064,7 @@ namespace HighWayAssemble
(timeSpan: TimeSpan.FromMinutes(1))
.SetCheckClearType(clearType: CheckClearType.OnlyReceive);
}))
.Start();//启动
}));
}
/// <summary>
@ -1019,7 +1072,7 @@ namespace HighWayAssemble
/// </summary>
/// <param name="socket"></param>
/// <param name="e"></param>
private void M_service_Disconnected(TouchSocket.Sockets.SocketClient socket, DisconnectEventArgs e)
private void M_service_Disconnected(TouchSocket.Sockets.TcpSessionClient socket, ClosedEventArgs e)
{
try
{
@ -1071,7 +1124,7 @@ namespace HighWayAssemble
/// </summary>
/// <param name="client"></param>
/// <param name="e"></param>
private void M_service_Connected(TouchSocket.Sockets.SocketClient client, TouchSocketEventArgs e)
private void M_service_Connected(TcpSessionClient client, ConnectedEventArgs e)
{
this.onLineClient.Add(client);
}
@ -1081,11 +1134,11 @@ namespace HighWayAssemble
/// </summary>
/// <param name="client">客户端连接信息</param>
/// <param name="myRequestInfo">接收消息内容</param>
private async void ParsingMessages(SocketClient client, MyRequestInfo myRequestInfo)
private async void ParsingMessages(TcpSessionClient client, byte[] myRequestInfo)
{
byte[] buffer = new byte[myRequestInfo.Header.Length + myRequestInfo.Body.Length];
Array.Copy(myRequestInfo.Header, 0, buffer, 0, myRequestInfo.Header.Length);
Array.Copy(myRequestInfo.Body, 0, buffer, myRequestInfo.Header.Length, myRequestInfo.Body.Length);
byte[] buffer = new byte[myRequestInfo.Length];
Array.Copy(myRequestInfo, 0, buffer, 0, myRequestInfo.Length);
//Array.Copy(myRequestInfo.Body, 0, buffer, myRequestInfo.Header.Length, myRequestInfo.Body.Length);
byte[] hbt = new byte[7];
Array.Copy(buffer, 0, hbt, 0, 7);
@ -1265,7 +1318,7 @@ namespace HighWayAssemble
/// <param name="client">客户端连接信息</param>
/// <param name="byteBlock">接收消息内容</param>
/// <param name="iLength">消息长度</param>
public void SignIn(SocketClient client, byte[] byteBlock, int iLength)
public void SignIn(TcpSessionClient client, byte[] byteBlock, int iLength)
{
try
{
@ -1306,7 +1359,7 @@ namespace HighWayAssemble
SoftInfo.mesSoftList[mesid].AdatperIP = client.IP;
SoftInfo.mesSoftList[mesid].AdapterPort = client.Port.ToString();
SoftInfo.mesSoftList[mesid].State = 1;
client.ResetId(flag.ToString());
client.ResetIdAsync(flag.ToString());
App.TriggerHalt(EventSystem.UpdateMesListInfo, SoftInfo.mesSoftList);
}
//Sql.InsertSoftState(flag.ToString(), 1);

@ -19,7 +19,7 @@ namespace HighWayAssemble.Properties {
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {

@ -12,7 +12,7 @@ namespace HighWayAssemble.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.10.0.0")]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.9.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

@ -0,0 +1,96 @@
using CatLib;
using Highway.Assemble.common;
using Highway.Assemble.Common;
using Highway.Assemble.EquipClient;
using log4net;
using Mesnac.DeviceAdapter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Rpc;
using TouchSocket.WebApi;
namespace HighWayAssemble.Protocol
{
[Router("/[api]/[action]")]
public class ApiServer : SingletonRpcServer
{
IEquipClient m_EquipClient = null;
public ApiServer()
{
m_EquipClient = App.Make<IEquipClient>();
}
[WebApi(Method = HttpMethodType.Post)]
public async Task<ApiResponse<MesParaData>> RFIDcontrol(MesParaData mesParaData)
{
return new ApiResponse<MesParaData>
{
Code = 200,
Data = null,
Msg = "sucess",
};
}
/// <summary>
/// MES主动请求读取标签
/// </summary>
/// <param name="EQUID"></param>
/// <param name="requesttime"></param>
/// <returns></returns>
[WebApi(Method = HttpMethodType.Post)]
public async Task<ApiResponse<MesReadRespon>> readAsync(MesReadPara mesReadPara)
{
FrmDisplayView.LogInfo.InfoFormat("接收MES主动读取指令{0},{1}",mesReadPara.EQUID ,mesReadPara.requesttime);
MesReadRespon mesReadRespon = new MesReadRespon();
List<TagInfo> rfid = null;
m_EquipClient.ReadRFID(Int32.Parse(mesReadPara.EQUID), out rfid);
if (rfid != null && rfid.Count > 0)
{
if (rfid.Count > 1)
{
if (rfid != null && rfid.Any())
{
mesReadRespon.EPCID = string.Join(",", rfid.Select(item => item.EPCstring));
}
}
else
{
mesReadRespon.EPCID = rfid[0].EPCstring;
}
mesReadRespon.Respontime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
return new ApiResponse<MesReadRespon>
{
Code = 200,
Data = mesReadRespon,
Msg = "sucess",
};
}
/// <summary>
/// MES主动回复处理结果控制报警灯
/// </summary>
/// <param name="EQUID"></param>
/// <param name="requesttime"></param>
/// <returns></returns>
[WebApi(Method = HttpMethodType.Post)]
public async Task<ApiResponse<MesParaData>> revresult(MesAlarmLightPara mesAlarmLightPara)
{
FrmDisplayView.LogInfo.InfoFormat("接收MES控制报警灯指令{0},{1}", mesAlarmLightPara.EQUID, mesAlarmLightPara.Sendtime);
m_EquipClient.WriteAlarmLight(Int32.Parse(mesAlarmLightPara.EQUID), mesAlarmLightPara.Code);
return new ApiResponse<MesParaData>
{
Code = 200,
Data = null,
Msg = "sucess",
};
}
}
}

@ -0,0 +1,70 @@
using CatLib;
using Highway.Assemble.common;
using Highway.Assemble.Common;
using Highway.Assemble.EquipClient;
using log4net;
using Newtonsoft.Json.Linq;
using RRQMSocket;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Xml;
using TouchSocket.Core;
using TouchSocket.Rpc;
using TouchSocket.Sockets;
using TouchSocket.WebApi;
namespace HighWayAssemble.Protocol
{
public class MesHttpClient
{
public static WebApiClient _MeshttpClient;
public MesHttpClient()
{
}
public async void init()
{
try
{
_MeshttpClient = new WebApiClient();
await _MeshttpClient.SetupAsync(new TouchSocketConfig()
.SetRemoteIPHost("127.0.0.1:6001")
.ConfigurePlugins(a =>
{
}));
await _MeshttpClient.ConnectAsync();
}
catch (Exception ex)
{
FrmDisplayView.LogInfo.Error("ERROR: " + ex.Message);
}
}
public ApiResponse<MesParaData> autoread(MesParaData mesParaData)
{
try
{
var requestForPost = new WebApiRequest();
requestForPost.Method = HttpMethodType.Post;
requestForPost.Body = new MesParaData() { EQUID = mesParaData.EQUID, EPCID = mesParaData.EPCID, READSTATUS = mesParaData.READSTATUS, ERRORMSG = mesParaData.ERRORMSG, READTIME = mesParaData.READTIME };
JToken responseValue = _MeshttpClient.InvokeT<JToken>("/ApiServer/RFIDcontrol", null, requestForPost);
return MsgUtil.JTokenToEntity<ApiResponse<MesParaData>>(responseValue);
}
catch (Exception ex)
{
FrmDisplayView.LogInfo.Error("ERROR: " + ex.Message);
return null;
}
}
}
}

@ -1,6 +1,8 @@
using System;
using Newtonsoft.Json.Linq;
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
namespace HighWayAssemble
{
@ -107,6 +109,22 @@ namespace HighWayAssemble
}
return sb.ToString();
}
public static T JTokenToEntity<T>(JToken value) where T : class
{
if (value == null)
{
return null;
}
string json = value.ToString();
if (string.IsNullOrEmpty(json))
{
return null;
}
T ResponseEntity;
ResponseEntity = JsonSerializer.Deserialize<T>(json);
return ResponseEntity;
}
}

@ -1,76 +0,0 @@
using System;
using TouchSocket.Core;
using TouchSocket.Sockets;
namespace HighWayAssemble.Protocol
{
internal class MyFixedHeaderCustomDataHandlingAdapter : CustomFixedHeaderDataHandlingAdapter<MyRequestInfo>
{
public override int HeaderLength => 7;
protected override MyRequestInfo GetInstance()
{
return new MyRequestInfo();
}
}
public class MyRequestInfo : IFixedHeaderRequestInfo
{
private byte[] m_sync;
private int m_bodyLength;
private byte[] m_length = new byte[2];
private byte[] body;
public int BodyLength { get => m_bodyLength; }
/// <summary>
/// 报文头:5AA5
/// </summary>
public byte[] Header { get => m_sync; set => m_sync = value; }
/// <summary>
/// 自定义属性,标识实际数据
/// </summary>
public byte[] Body { get => body; set => body = value; }
public bool OnParsingBody(byte[] body)
{
if (body.Length == this.m_bodyLength)
{
this.body = body;
return true;
}
return false;
}
/// <summary>
/// 接收客户端消息头
/// </summary>
/// <param name="header"></param>
/// <returns></returns>
public bool OnParsingHeader(byte[] header)
{
try
{
if (header.Length == 7)
{
using (ByteBlock byteBlock = new ByteBlock(header))
{
string m_BarcodeGroupCount = "";
int i_BarcodeGroupCount = 0;
byteBlock.Pos = 0;
byteBlock.Read(out m_sync, 7);
Array.Copy(header, 5, m_length, 0, 2);
i_BarcodeGroupCount = BitConverter.ToUInt16(header, 5);
this.m_bodyLength = i_BarcodeGroupCount + 3;//先把crc校验和end都获取。
}
}
return true;
}
catch (Exception ex)
{
return false;
}
}
}
}

@ -1,6 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="3.5.8" targetFramework="net452" />
<package id="TouchSocket" version="2.0.0-beta.130" targetFramework="net452" />
<package id="TouchSocket.Core" version="2.0.0-beta.130" targetFramework="net452" />
<package id="Microsoft.Bcl.AsyncInterfaces" version="8.0.0" targetFramework="net461" />
<package id="Newtonsoft.Json" version="13.0.3" targetFramework="net452" />
<package id="System.Buffers" version="4.5.1" targetFramework="net452" requireReinstallation="true" />
<package id="System.Memory" version="4.5.5" targetFramework="net452" requireReinstallation="true" />
<package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net461" />
<package id="System.Runtime.CompilerServices.Unsafe" version="6.0.0" targetFramework="net461" />
<package id="System.Text.Encodings.Web" version="8.0.0" targetFramework="net461" />
<package id="System.Text.Json" version="8.0.5" targetFramework="net461" />
<package id="System.Threading.Tasks.Extensions" version="4.5.4" targetFramework="net452" requireReinstallation="true" />
<package id="System.ValueTuple" version="4.5.0" targetFramework="net452" requireReinstallation="true" />
<package id="TouchSocket" version="3.1.0" targetFramework="net452" />
<package id="TouchSocket.Core" version="3.1.0" targetFramework="net452" />
<package id="TouchSocket.Http" version="3.1.0" targetFramework="net452" />
<package id="TouchSocket.Rpc" version="3.1.0" targetFramework="net452" />
<package id="TouchSocket.WebApi" version="3.1.0" targetFramework="net452" />
</packages>

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Highway.Assemble.Common
{
public class ApiResponse<T>
{
/// <summary>
/// 状态码(如 200 成功400 失败500 错误)
/// </summary>
public int Code { get; set; }
/// <summary>
/// 消息(如 "操作成功"、"参数错误"
/// </summary>
public string Msg { get; set; }
/// <summary>
/// 返回数据
/// </summary>
public T Data { get; set; }
}
}

@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Highway.Assemble.Common</RootNamespace>
<AssemblyName>Highway.Assemble.Common</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
@ -52,10 +52,15 @@
</ItemGroup>
<ItemGroup>
<Compile Include="Adapter.cs" />
<Compile Include="ApiResponse.cs" />
<Compile Include="Collect.cs" />
<Compile Include="DeviceState.cs" />
<Compile Include="Equip.cs" />
<Compile Include="IBOXDB.cs" />
<Compile Include="MesAlarmLightPara.cs" />
<Compile Include="MesReadRespon.cs" />
<Compile Include="MesReadPara.cs" />
<Compile Include="MesParaData.cs" />
<Compile Include="mesSoft.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RealWorkdata.cs" />

@ -0,0 +1,12 @@
namespace Highway.Assemble.common
{
public class MesAlarmLightPara
{
public string EQUID { get; set; }
public string Sendtime { get; set; }
public string Code { get; set; }
public string msg { get; set; }
}
}

@ -0,0 +1,15 @@
namespace Highway.Assemble.common
{
public class MesParaData
{
public MesParaData()
{
}
public string EQUID { get; set; }
public string EPCID { get; set; }
public string READSTATUS { get; set; }
public string ERRORMSG { get; set; }
public string READTIME { get; set; }
}
}

@ -0,0 +1,10 @@
namespace Highway.Assemble.common
{
public class MesReadPara
{
public string EQUID { get; set; }
public string requesttime { get; set; }
}
}

@ -0,0 +1,10 @@
namespace Highway.Assemble.common
{
public class MesReadRespon
{
public string EPCID { get; set; }
public string Respontime { get; set; }
}
}

@ -18,9 +18,9 @@ namespace Highway.Assemble.EquipClient
public Action<List<DeviceInfo>> EquipStateAction;
public Action<int, byte[]> ReadDataAction;
public Action<int, List<TagInfo>> ReadDataAction;
public Action<int, byte[]> RecSendDataAction;
public Action<int, List<TagInfo>> RecSendDataAction;
public Action<int, int, int> RecGetDataAction;
@ -160,6 +160,7 @@ namespace Highway.Assemble.EquipClient
{
item.m_ConnectState = 0;
}
if (item.m_ConnectState == 0)
{
if (pDeviceAdapter.Device_Init_Id((CommType)item.m_iConnectMode, item.m_strConnectStr, item.m_iDeviceId))
@ -168,8 +169,8 @@ namespace Highway.Assemble.EquipClient
{
pDeviceAdapter.RecvIdentifyDataEvent -= RecvIdentifyData_Instance;
pDeviceAdapter.RecvIdentifyDataEvent += RecvIdentifyData_Instance;
pDeviceAdapter.RecvIdentifyData_ToMES_Event -= RecvIdentifyDataToMES_Instance;
pDeviceAdapter.RecvIdentifyData_ToMES_Event += RecvIdentifyDataToMES_Instance;
//pDeviceAdapter.RecvIdentifyData_ToMES_Event -= RecvIdentifyDataToMES_Instance;
//pDeviceAdapter.RecvIdentifyData_ToMES_Event += RecvIdentifyDataToMES_Instance;
switch (pDeviceAdapter.Device_SendHeartPack())
{
case 1:
@ -259,7 +260,7 @@ namespace Highway.Assemble.EquipClient
LogInfo.Info("------------------------------------------------------------------------------------------------------");
LogInfo.Info("MES主动读取合并编号[" + iCombineId + "]的第[" + Antenna + "]号传感器,自报数据:" + Encoding.ASCII.GetString(pData, 0, pData.Length) + ",原始数据:" + bytesToHexStr(pData, pData.Length));
LogInfo.Info("------------------------------------------------------------------------------------------------------");
ReadDataAction?.Invoke(Convert.ToInt32(iCombineId), pData);
//ReadDataAction?.Invoke(Convert.ToInt32(iCombineId), pData);
}
else
{
@ -307,7 +308,7 @@ namespace Highway.Assemble.EquipClient
/// <param name="iDeviceId">设备编号</param>
/// <param name="strId">传感器编号</param>
/// <param name="sensorType">传感器类型</param>
public void RecvIdentifyData_Instance(ushort iLen, byte[] pData, byte Antenna, ushort iDeviceId, string strId, string sensorType)
public void RecvIdentifyData_Instance(ushort iLen, List<TagInfo> tagInfos, byte Antenna, ushort iDeviceId, string strId, string sensorType)
{
uint iCombineId = 0u;
try
@ -319,16 +320,16 @@ namespace Highway.Assemble.EquipClient
}
if (iLen > 0)
{
if (iLen == 1)
{
LogInfo.Info("------------------------------------------------------------------------------------------------------");
LogInfo.Info("光电自报合并编号[" + iCombineId + "]的第[" + Antenna + "]号传感器,原始数据:" + bytesToHexStr(pData, pData.Length));
LogInfo.Info("------------------------------------------------------------------------------------------------------");
RecAutoDataAction?.Invoke(Convert.ToInt32(iCombineId), pData);
return;
}
//if (iLen == 1)
//{
// LogInfo.Info("------------------------------------------------------------------------------------------------------");
// LogInfo.Info("光电自报合并编号[" + iCombineId + "]的第[" + Antenna + "]号传感器,原始数据:" + bytesToHexStr(pData, pData.Length));
// LogInfo.Info("------------------------------------------------------------------------------------------------------");
// RecAutoDataAction?.Invoke(Convert.ToInt32(iCombineId), pData);
// return;
//}
LogInfo.Info("------------------------------------------------------------------------------------------------------");
LogInfo.Info("读写器自报合并编号[" + iCombineId + "]的第[" + Antenna + "]号传感器,自报数据:" + Encoding.ASCII.GetString(pData, 0, pData.Length) + ",原始数据:" + bytesToHexStr(pData, pData.Length));
//LogInfo.Info("读写器自报合并编号[" + iCombineId + "]的第[" + Antenna + "]号传感器,自报数据:" + Encoding.ASCII.GetString(pData, 0, pData.Length) + ",原始数据:" + bytesToHexStr(pData, pData.Length));
LogInfo.Info("------------------------------------------------------------------------------------------------------");
AntInfo[] antList = AntList;
foreach (AntInfo item in antList)
@ -336,16 +337,9 @@ namespace Highway.Assemble.EquipClient
if (item.m_iCombineId == iCombineId)
{
item.IsReading = false;
item.ReadData = new byte[pData.Length];
Array.Copy(pData, 0, item.ReadData, 0, pData.Length);
if (item.readType == 2)
{
ReadDataAction?.Invoke(Convert.ToInt32(iCombineId), pData);
}
else
{
RecSendDataAction?.Invoke(Convert.ToInt32(iCombineId), pData);
}
item.ReadData = new byte[tagInfos[0].EPC.Length];
Array.Copy(tagInfos[0].EPC, 0, item.ReadData, 0, tagInfos[0].EPC.Length);
RecSendDataAction?.Invoke(Convert.ToInt32(iCombineId), tagInfos);
}
}
}
@ -409,7 +403,7 @@ namespace Highway.Assemble.EquipClient
LogInfo.Info("------------------------------------------------------------------------------------------------------");
LogInfo.Info("MES主动读取数据成功合并编号[" + num + "],读取标签数据:" + Encoding.ASCII.GetString(pReadData, 0, pReadData.Length) + ",原始数据:" + bytesToHexStr(pReadData, pReadData.Length));
LogInfo.Info("------------------------------------------------------------------------------------------------------");
ReadDataAction?.Invoke(num, pReadData);
//ReadDataAction?.Invoke(num, pReadData);
}
else
{
@ -565,13 +559,13 @@ namespace Highway.Assemble.EquipClient
try
{
LogInfo.Info("合并编号:" + id + ",识别单次标签命令自报");
array = GetOneEpcByCombineId(Convert.ToUInt32(id));
//array = GetOneEpcByCombineId(Convert.ToUInt32(id));
if (array != null)
{
LogInfo.Info("-------------------------------------------------------------------------------------------------------------");
LogInfo.Info("识别单次标签成功,合并编号[" + id + "],读取标签数据:" + Encoding.ASCII.GetString(array, 0, array.Length) + ",原始数据:" + bytesToHexStr(array, array.Length));
LogInfo.Info("-------------------------------------------------------------------------------------------------------------");
ReadDataAction?.Invoke(id, array);
//ReadDataAction?.Invoke(id, array);
}
else
{
@ -589,13 +583,50 @@ namespace Highway.Assemble.EquipClient
});
}
public void ReadRFID(int id,out List<TagInfo> rfiddata)
{
List<TagInfo> tags = new List<TagInfo>();
byte[] array = null;
rfiddata = null;
try
{
LogInfo.Info("合并编号:" + id + ",识别单次标签命令自报");
tags = GetOneEpcByCombineId(Convert.ToUInt32(id));
if (tags != null)
{
//LogInfo.Info("-------------------------------------------------------------------------------------------------------------");
//LogInfo.Info("识别单次标签成功,合并编号[" + id + "],读取标签数据:" + Encoding.ASCII.GetString(array, 0, array.Length) + ",原始数据:" + bytesToHexStr(array, array.Length));
//LogInfo.Info("-------------------------------------------------------------------------------------------------------------");
//rfiddata = Encoding.ASCII.GetString(array, 0, array.Length);
rfiddata = tags;
ReadDataAction?.Invoke(id, tags);
}
else
{
LogInfo.Info("------------------------------------------------------------------------------------------------------");
LogInfo.Info("识别单次标签成功,合并编号[" + id + "]读取标签数据NoData");
LogInfo.Info("------------------------------------------------------------------------------------------------------");
ReadDataAction?.Invoke(id, null);
}
}
catch (Exception ex)
{
LogInfo.Info("Deal_IdentifyOneEpc异常:" + ex.ToString());
ReadDataAction?.Invoke(id, null);
}
}
/// <summary>
/// 根据合并编号主动读取EPC返回原始数据
/// </summary>
/// <param name="iCombineId">传感器编号</param>
/// <returns>原始数据</returns>
private byte[] GetOneEpcByCombineId(uint iCombineId)
private List<TagInfo> GetOneEpcByCombineId(uint iCombineId)
{
List<TagInfo> tagInfos = null;
byte[] pReturnResult = null;
IDeviceAdapter pDeviceAdapter = null;
byte iEpcLen = 0;
@ -608,15 +639,15 @@ namespace Highway.Assemble.EquipClient
pDeviceAdapter = GetDeviceAdapterByDeviceId(Convert.ToUInt16(m_SensorInfoList[i].deviceId));
if (pDeviceAdapter != null)
{
iEpcLen = ((!(m_SensorInfoList[i].returnImm == "1")) ? pDeviceAdapter.Device_GetOneIdentifyData(ref pReturnResult, Convert.ToByte(m_SensorInfoList[i].sensorser), Convert.ToUInt16(m_SensorInfoList[i].DelayTime), 1) : pDeviceAdapter.Device_GetOneIdentifyData(ref pReturnResult, Convert.ToByte(m_SensorInfoList[i].sensorser), Convert.ToUInt16(m_SensorInfoList[i].DelayTime), 1));
if (iEpcLen > 0)
tagInfos = pDeviceAdapter.Device_GetAllIdentifyData(Convert.ToByte(m_SensorInfoList[i].sensorser), Convert.ToUInt16(m_SensorInfoList[i].DelayTime), 1);
if (tagInfos.Count > 0)
{
return pReturnResult;
return tagInfos;
}
return null;
}
}
return pReturnResult;
return tagInfos;
}
/// <summary>
@ -652,12 +683,12 @@ namespace Highway.Assemble.EquipClient
RecGetDataAction = action;
}
public void RecSendData(Action<int, byte[]> action)
public void RecSendData(Action<int, List<TagInfo>> action)
{
RecSendDataAction = action;
}
public void RetReadData(Action<int, byte[]> action)
public void RetReadData(Action<int, List<TagInfo>> action)
{
ReadDataAction = action;
}
@ -906,14 +937,14 @@ namespace Highway.Assemble.EquipClient
try
{
LogInfo.Info("合并编号:" + id + ",识别单次标签命令");
pEpc = GetOneEpcByCombineId(Convert.ToUInt32(id));
//pEpc = GetOneEpcByCombineId(Convert.ToUInt32(id));
if (pEpc != null)
{
LogInfo.Info("-------------------------------------------------------------------------------------------------------------");
LogInfo.Info("识别单次标签成功,合并编号[" + id + "],读取标签数据:" + Encoding.ASCII.GetString(pEpc, 0, pEpc.Length) + ",原始数据:" + bytesToHexStr(pEpc, pEpc.Length));
LogInfo.Info("-------------------------------------------------------------------------------------------------------------");
m_data = Encoding.ASCII.GetString(pEpc, 0, pEpc.Length);
ReadDataAction?.Invoke(id, pEpc);
//ReadDataAction?.Invoke(id, pEpc);
}
else
{
@ -930,6 +961,31 @@ namespace Highway.Assemble.EquipClient
}
return m_data;
}
public void WriteAlarmLight(int num,string code)
{
bool flag = false;
try
{
DeviceInfo deviceInfo = null;
//Sensor sensor = null;
deviceInfo = GetIDeviceInfoByCombineId(Convert.ToUInt32(num));
//sensor = GetSensorInfoByCombineId(Convert.ToUInt32(num));
if (deviceInfo.m_IDeviceAdapter != null)
{
flag = deviceInfo.m_IDeviceAdapter.Device_WriteAlarmLight(int.Parse(code), 2000);
//Thread.Sleep(3000);
//flag = deviceInfo.m_IDeviceAdapter.Device_WriteAlarmLight(2,2000);
//Thread.Sleep(3000);
//flag = deviceInfo.m_IDeviceAdapter.Device_WriteAlarmLight(3,2000);
}
}
catch (Exception ex)
{
}
}
}
}

@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Highway.Assemble.EquipClient</RootNamespace>
<AssemblyName>Highway.Assemble.EquipClient</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />

@ -1,4 +1,5 @@
using Highway.Assemble.common;
using Mesnac.DeviceAdapter;
using Mesnac.DeviceAdapterNet;
using System;
using System.Collections.Generic;
@ -18,7 +19,9 @@ namespace Highway.Assemble.EquipClient
Task ReadEPC(int id);
void RecSendData(Action<int, byte[]> action);
void ReadRFID(int id, out List<TagInfo> rfiddata);
void RecSendData(Action<int, List<TagInfo>> action);
void RecAutoData(Action<int, byte[]> action);
@ -26,7 +29,7 @@ namespace Highway.Assemble.EquipClient
void ReadData(int num, byte filterMembank, ushort filterWordPtr, ushort filterWordCnt, byte[] filterData, byte Membank, ushort WordPtr, ushort WordCnt);
void RetReadData(Action<int, byte[]> action);
void RetReadData(Action<int, List<TagInfo>> action);
void WriteData(int num, byte filterMembank, ushort filterWordPtr, ushort filterWordCnt, byte[] filterData, byte Membank, ushort WordPtr, ushort WordCnt, byte[] pWriteData, byte Antenna);
@ -40,6 +43,6 @@ namespace Highway.Assemble.EquipClient
string ReadEPCData(int id);
void WriteAlarmLight(int num, string code);
}
}

@ -126,9 +126,9 @@ namespace Highway.Assemble.Sql
sensorcode.multData = row["multdata"].ToString().Trim();
sensorcode.timeout = row["timedout"].ToString().Trim();
sensorcode.returnImm = row["returnimm"].ToString().Trim();
sensorcode.CallAdapter = Convert.ToInt16(row["calladapter"]);
//sensorcode.CallAdapter = Convert.ToInt16(row["calladapter"]);
//sensorcode.CallAdapterid = row["calladapterid"].ToString().Trim();
sensorcode.CallCombineID = row["callcombineid"].ToString().Trim();
//sensorcode.CallCombineID = row["callcombineid"].ToString().Trim();
// sensorcode.DelayTime = TryToInt(row["DelayTime"].ToString());
sensorcode.mesID = row["MesID"].ToString().Trim();
sensorcode.DelayTime = TryToInt(row["DelayTime"].ToString().Trim());

@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Highway.Assemble.Sql</RootNamespace>
<AssemblyName>Highway.Assemble.Sql</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>

@ -9,9 +9,10 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>AUCMA.SCADA.SqlSugar</RootNamespace>
<AssemblyName>AUCMA.SCADA.SqlSugar</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>

@ -1,11 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Oracle.ManagedDataAccess" publicKeyToken="89b483f429c47342" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.122.1.0" newVersion="4.122.1.0" />
<assemblyIdentity name="Oracle.ManagedDataAccess" publicKeyToken="89b483f429c47342" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.122.1.0" newVersion="4.122.1.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/></startup></configuration>

@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
//using System.Threading.Tasks;
using System.Runtime.InteropServices;
@ -415,7 +416,7 @@ namespace Mesnac.DeviceAdapter.Fuchs
//LogService.Instance.Info("接收到数据,第"+Antenna+"号传感器类型readType = " + AntList[Antenna - 1].readType);
if (RecvIdentifyDataEvent != null)
{
RecvIdentifyDataEvent(Convert.ToUInt16(m_OneEpcData.Length), m_OneEpcData, Antenna, m_iDeviceId, m_strIp, "1");
RecvIdentifyDataEvent(Convert.ToUInt16(m_OneEpcData.Length), null, Antenna, m_iDeviceId, m_strIp, "1");
}
}
@ -1497,6 +1498,16 @@ namespace Mesnac.DeviceAdapter.Fuchs
}
}
public bool Device_WriteAlarmLight(int port, UInt16 Timedout)
{
throw new NotImplementedException();
}
public List<TagInfo> Device_GetAllIdentifyData(byte Antenna, ushort Timedout, int ReadCounts)
{
throw new NotImplementedException();
}
//public List<TagInfo> TagInventoryTimePeriod(byte Antenna, int time)
//{
// List<TagInfo> t = new List<TagInfo> { };

@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Mesnac.DeviceAdapter.Fuchs</RootNamespace>
<AssemblyName>Mesnac.DeviceAdapter.Fuchs</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>

@ -226,7 +226,7 @@ namespace Mesnac.DeviceAdapter.HWKC_81600
//}
if (RecvIdentifyDataEvent != null)
{
RecvIdentifyDataEvent?.Invoke(1, m_ReadData, m_ReadAntenna, m_iDeviceId, m_strIp, "2");
RecvIdentifyDataEvent?.Invoke(1, null, m_ReadAntenna, m_iDeviceId, m_strIp, "2");
if (m_ReadData[0] == 0xFF)
{
if (m_IsIOSendData == "1")
@ -774,6 +774,16 @@ namespace Mesnac.DeviceAdapter.HWKC_81600
{
return 0;
}
public bool Device_WriteAlarmLight(int port, UInt16 Timedout)
{
throw new NotImplementedException();
}
public List<TagInfo> Device_GetAllIdentifyData(byte Antenna, ushort Timedout, int ReadCounts)
{
throw new NotImplementedException();
}
#endregion
}
}

@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Mesnac.DeviceAdapter.HWKC_81600</RootNamespace>
<AssemblyName>Mesnac.DeviceAdapter.HWKC_81600</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>

@ -0,0 +1,628 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using System.Threading.Tasks;
using System.ComponentModel;
using System.Net.Sockets;
using System.Collections;
using System.Threading;
using System.Net;
using Mesnac.Log;
namespace Mesnac.DeviceAdapter.RFly_I160
{
public enum RecvState
{
//RFly-I160 返回数据 BB DD 00 01 40 41 0D
WaitingBeginChar1_State = 1, //等待接收帧同步字符1 0xBB
WaitingBeginChar2_State = 2, //等待接收帧同步字符2 0xDD
WaitingForBarcodeLength_State = 3, //等待条码长度不固定
WaitingForCode_State = 4, //等待指令编号Code 0x02
WaitingForStus_State = 5, //等待接受状态码 0x00
WaitingForTagCount_State = 6, //等待接受标签组数不固定
WaitingForCount_State = 7, //等待接收第一组标签读取次数 0x01
WaitingForRSSI_State = 8, //等待接收读取信号强度 0xCB
WaitingForAnt_State = 9, //等待接收天线端口 0x01
WaitingForPC1_State = 10, //等待接收EPC区域 0x00
WaitingForPC2_State = 11, //等待接收EPC区域 0x00
WaitingForData_State = 12, //等待接收数据字符
WaitingForXor_State = 13, //等待比对校验位
WaitingForEndChar_State = 14, //等待接收尾字符 0x0D
};
class BgTcpClient : ICommunicateService
{
RecvState enumRecvState = RecvState.WaitingBeginChar1_State;
int m_iPosition = 0;
UInt16 m_iFullMessageLength = 0;
byte m_iVerify = 0;
byte[] m_szFullMessage = new byte[1024]; //此数组用于状态机
int iBarcodeGroupCount = 0; //读取的组数
int iBarcodeLength = 0;//条码长度
int iBarcodeGroupCountFlag = 0;//组数标记
RFly_I160Adapter m_RFly_I160Adapter = null;
public UInt16 m_iDeviceId = 0;
private BackgroundWorker m_bgwReceive = new BackgroundWorker();
private BackgroundWorker m_bgwDeal = new BackgroundWorker();
private string m_FsIP = "";
private Int32 m_FnPort = 0;
private Socket m_ClientSock = null;
private ArrayList m_FrecvData = new ArrayList();
private Semaphore m_Fsem = new Semaphore(0, 100000);
private ManualResetEvent Exitevent = new ManualResetEvent(false);
//接收线程
private void bgwReceive_DoWork(object sender, DoWorkEventArgs e)
{
//m_RFly_I160Adapter.LogInfo.Warn("RFly-I160 进入 bgwReceive_DoWork 线程函数:");
int nPackLen = 1024;
byte[] buff = new byte[nPackLen];
while (true)
{
try
{
if (m_ClientSock != null && m_ClientSock.Connected)
{
int nCount = m_ClientSock.Receive(buff, nPackLen, 0);
if (nCount > 0)
{
m_RFly_I160Adapter.LogInfo.Warn("》》》RFly-I160设备" + m_iDeviceId +",IP:" + m_FsIP + ",接收原始报文:" + bytesToHexStr(buff, nCount));
PareReceiveData(buff, nCount); //调用状态机函数
continue;
}
else //接收错误
{
if (m_ClientSock != null)
{
m_ClientSock.Close();
m_ClientSock = null;
}
e.Cancel = true;
m_Fsem.Release();
}
}
else
{
e.Cancel = true;
if (m_ClientSock != null)
{
m_ClientSock.Close();
m_ClientSock = null;
}
m_Fsem.Release();
return;
}
}
catch (Exception ex)
{
e.Cancel = true;
if (m_ClientSock != null)
{
m_ClientSock.Close();
m_ClientSock = null;
}
m_RFly_I160Adapter.LogInfo.Warn("Socket接收数据线程退出" + ex.ToString());
m_Fsem.Release();
return;
}
if (this.m_bgwReceive.CancellationPending)
{
e.Cancel = true;
if (m_ClientSock != null)
{
m_ClientSock.Close();
m_ClientSock = null;
}
m_Fsem.Release();
return;
}
}
}
//发送线程(包括接收后的处理)
private void bgwDeal_DoWork(object sender, DoWorkEventArgs e)
{
//m_RFly_I160Adapter.LogInfo.Warn("RFly-I160 进入 bgwDeal_DoWork 线程:");
while (true)
{
try
{
m_Fsem.WaitOne();
lock (m_FrecvData)
{
if (m_FrecvData.Count > 0)
{
byte[] buff = (byte[])m_FrecvData[0];
if (m_RFly_I160Adapter != null)
{
m_RFly_I160Adapter.Device_DealValidPack(buff); //处理函数
}
m_FrecvData.RemoveAt(0);
}
}
if (Exitevent.WaitOne(0, false))
{
e.Cancel = true;
m_RFly_I160Adapter.LogInfo.Warn("Socket处理数据线程正常退出");
Exitevent.Reset();
return;
}
}
catch (Exception ex)
{
e.Cancel = true;
m_RFly_I160Adapter.LogInfo.Warn("Socket处理数据异常 " + ex.ToString());
return;
}
if (this.m_bgwDeal.CancellationPending)
{
m_RFly_I160Adapter.LogInfo.Warn("Socket处理数据线程异常退出");
e.Cancel = true;
return;
}
}
}
//发送函数
public bool SendMessage(MessagePack pMessagePack)
{
UInt16 iPos = 0;
byte[] u16byte = new byte[2];
try
{
byte[] SendBuffer = new byte[pMessagePack.m_pData.Length]; //起始字符1
Array.Copy(pMessagePack.m_pData, 0, SendBuffer, iPos, pMessagePack.m_pData.Length); //数据域
m_RFly_I160Adapter.LogInfo.Warn("》》》RFly-I160设备" + m_iDeviceId + ",IP:"+ m_FsIP + ",发送原始报文:" + bytesToHexStr(SendBuffer, pMessagePack.m_pData.Length));
int nCount = m_ClientSock.Send(SendBuffer, pMessagePack.m_pData.Length, SocketFlags.None);
if (nCount > 0) //发送成功
{
//m_RFly_I160Adapter.LogInfo.Warn("m_ClientSock.Send函数发送成功");
return true;
}
else
{
m_RFly_I160Adapter.LogInfo.Warn("连接已断开,数据发送失败");
return false;
}
}
catch (Exception ex)
{
m_RFly_I160Adapter.LogInfo.Warn("发送报文异常: " + ex.ToString());
return false;
}
}
#region 初始化一套函数
public bool Connect()
{
//连接
try
{
Exitevent.Reset();
if (m_FsIP == "" || m_FnPort == 0)
{
m_RFly_I160Adapter.LogInfo.Warn("IP和端口号不能为空连接失败");
return false;
}
if (m_ClientSock != null && GetState())
{
m_RFly_I160Adapter.LogInfo.Warn("已经连接了");
return true;
}
m_ClientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse(m_FsIP), m_FnPort);
m_ClientSock.Connect(iep);
if (m_ClientSock.Connected)
{
try
{
//启动接收线程
//if (m_bgwReceive.IsBusy)
//{
// return false;
//}
m_bgwReceive.DoWork += new DoWorkEventHandler(bgwReceive_DoWork);
m_bgwReceive.RunWorkerAsync();
//启动处理线程
m_bgwDeal.DoWork += new DoWorkEventHandler(bgwDeal_DoWork);
m_bgwDeal.RunWorkerAsync();
return true;
}
catch (Exception ex)
{
m_RFly_I160Adapter.LogInfo.Warn("创建后台线程异常 " + ex.ToString());
return true;
}
}
else
{
return false;
}
}
catch (Exception ex)
{
m_RFly_I160Adapter.LogInfo.Warn("Socket连接异常 " + ex.ToString());
return false;
}
}
public bool DisConnect()
{
try
{
Exitevent.Set();
Thread.Sleep(100);
m_Fsem.Release();
if (m_ClientSock != null)
{
m_ClientSock.Disconnect(false);
m_ClientSock.Close();
m_ClientSock = null;
}
return true;
}
catch (Exception ex)
{
m_RFly_I160Adapter.LogInfo.Warn("Socket连接异常 " + ex.ToString());
return false;
}
}
public bool GetState()
{
bool bResult = false;
bool blockingState = false;
try
{
if (m_ClientSock != null)
{
blockingState = m_ClientSock.Blocking;
byte[] tmp = new byte[1];
m_ClientSock.Blocking = false;
m_ClientSock.Send(tmp, 0, 0);
bResult = true;
Console.WriteLine("Connected!");
}
else
{
bResult = false;
}
}
catch (SocketException e)
{
// 10035 == WSAEWOULDBLOCK
if (e.NativeErrorCode.Equals(10035))
{
bResult = true;
Console.WriteLine("Still Connected, but the Send would block");
}
else
{
bResult = false;
Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);
}
}
finally
{
if (m_ClientSock != null)
{
m_ClientSock.Blocking = blockingState;
}
}
return bResult;
}
public void Init(string strIp, int iPort, object objetcter,ushort DeviceId)
{
Exitevent.Reset();
m_FsIP = strIp;
m_FnPort = iPort;
m_iDeviceId = DeviceId;
m_RFly_I160Adapter = objetcter as RFly_I160Adapter;
}
#endregion
//状态机函数
public void PareReceiveData(byte[] buffer, int iLen)
{
//m_RFly_I160Adapter.LogInfo.Warn("RFly-I160进入状态机");
for (int i = 0; i < iLen; i++)
{
switch (enumRecvState)
{
case RecvState.WaitingBeginChar1_State: //开始接受数据帧1 0xBB
//m_RFly_I160Adapter.LogInfo.Warn("RFly-I160等待接收帧同步字符WaitingBeginChar1_State:0XBB");
Array.Clear(m_szFullMessage, 0, 1024);//清空为0
if (buffer[i] == 0xBB)
{
//m_RFly_I160Adapter.LogInfo.Warn("Buffer数据为: " + StringChange.bytesToHexStr(buffer, buffer.Length));
m_szFullMessage[m_iPosition] = buffer[i];
m_iPosition++;
enumRecvState = RecvState.WaitingBeginChar2_State;
}
else
{
m_iFullMessageLength = 0;
m_iPosition = 0;
enumRecvState = RecvState.WaitingBeginChar1_State;
}
break;
case RecvState.WaitingBeginChar2_State: //开始接受数据帧1 0xDD
//m_RFly_I160Adapter.LogInfo.Warn("RFly-I160等待接收帧同步字符WaitingBeginChar2_State:0XDD");
if (buffer[i] == 0xDD)
{
m_szFullMessage[m_iPosition] = buffer[i];
m_iPosition++;
enumRecvState = RecvState.WaitingForBarcodeLength_State;
}
else
{
m_iFullMessageLength = 0;
m_iPosition = 0;
enumRecvState = RecvState.WaitingBeginChar1_State;
}
break;
case RecvState.WaitingForBarcodeLength_State: //开始接受数据长度(TagCount - EPC)
m_szFullMessage[m_iPosition] = buffer[i];
iBarcodeLength = buffer[i]; //单组标签18两组标签35
m_iPosition++;
enumRecvState = RecvState.WaitingForCode_State;
break;
case RecvState.WaitingForCode_State: //开始接受指令编号
if (buffer[i] == 0x02)
{
m_szFullMessage[m_iPosition] = buffer[i];
m_iPosition++;
enumRecvState = RecvState.WaitingForStus_State;
}
else if (buffer[i] == 0x90) // 如果是心跳BB DD 01 90 00 1F 8E 0D
{
//m_RFly_I160Adapter.LogInfo.Warn("RFly-I160等待接受WaitingForEndChar_State:温度");
m_szFullMessage[m_iPosition] = buffer[i];
m_iPosition++;
enumRecvState = RecvState.WaitingForEndChar_State;
}
else if (buffer[i] == 0xBF) // 如果是心跳BB DD 04 BF 00 00 00 F9 0B 49 0D
{
//m_RFly_I160Adapter.LogInfo.Warn("RFly-I160等待接受WaitingForEndChar_State:心跳");
m_szFullMessage[m_iPosition] = buffer[i];
m_iPosition++;
enumRecvState = RecvState.WaitingForEndChar_State;
}
else if (buffer[i] == 0x51)
{
m_szFullMessage[m_iPosition] = buffer[i];
m_iPosition++;
enumRecvState = RecvState.WaitingForStus_State;
}
else
{
m_iFullMessageLength = 0;
m_iPosition = 0;
enumRecvState = RecvState.WaitingBeginChar1_State;
}
break;
case RecvState.WaitingForStus_State: //开始接受状态码
if (buffer[i] == 0x00)
{
m_szFullMessage[m_iPosition] = buffer[i];
m_iPosition++;
enumRecvState = RecvState.WaitingForTagCount_State;
}
else if (buffer[i] == 0x40)
{
m_szFullMessage[m_iPosition] = buffer[i];
//m_RFly_I160Adapter.LogInfo.Warn("RFU620等待接受WaitingForEndChar_State:Noread");
lock (m_FrecvData)
{
m_FrecvData.Add(m_szFullMessage);
}
m_Fsem.Release();
m_iPosition = 0;
i = iLen;
enumRecvState = RecvState.WaitingBeginChar1_State;
//m_RFly_I160Adapter.LogInfo.Warn("RFly-I160状态机结束。");
}
break;
case RecvState.WaitingForTagCount_State: //开始接受标签组数
Array.Copy(buffer, i, m_szFullMessage, m_iPosition, iBarcodeLength);//m_iPosition = 5
byte[] tempData = new byte[iBarcodeLength];
Array.Clear(tempData, 0, iBarcodeLength);
Array.Copy(buffer, i, tempData, 0, iBarcodeLength);
//m_RFly_I160Adapter.LogInfo.Warn("解析的数据为: " + StringChange.bytesToHexStr(tempData, iBarcodeLength));
//m_szFullMessage[m_iPosition] = buffer[i]; //单组标签01两组标签02
m_iPosition = m_iPosition + iBarcodeLength; //m_iPosition = 39
i = i + iBarcodeLength -1; //i = 39
enumRecvState = RecvState.WaitingForXor_State;
break;
#region 暂时不需要
//case RecvState.WaitingForCount_State:
// if (buffer[i] == 0x01)
// {
// m_szFullMessage[m_iPosition] = buffer[i];
// m_iPosition++;
// enumRecvState = RecvState.WaitingForRSSI_State;
// }
// else
// {
// m_iFullMessageLength = 0;
// m_iPosition = 0;
// enumRecvState = RecvState.WaitingBeginChar1_State;
// }
// break;
//case RecvState.WaitingForRSSI_State: //开始接受功率
// m_szFullMessage[m_iPosition] = buffer[i];
// m_iPosition++;
// enumRecvState = RecvState.WaitingForAnt_State;
// break;
//case RecvState.WaitingForAnt_State: //开始接受天线编号
// m_szFullMessage[m_iPosition] = buffer[i];
// m_iPosition++;
// enumRecvState = RecvState.WaitingForPC1_State;
// break;
//case RecvState.WaitingForPC1_State:
// if (buffer[i] == 0x00)
// {
// m_szFullMessage[m_iPosition] = buffer[i];
// m_iPosition++;
// enumRecvState = RecvState.WaitingForPC2_State;
// }
// else
// {
// m_iFullMessageLength = 0;
// m_iPosition = 0;
// enumRecvState = RecvState.WaitingBeginChar1_State;
// }
// break;
//case RecvState.WaitingForPC2_State:
// if (buffer[i] == 0x00)
// {
// m_szFullMessage[m_iPosition] = buffer[i];
// m_iPosition++;
// enumRecvState = RecvState.WaitingForData_State;
// }
// else
// {
// m_iFullMessageLength = 0;
// m_iPosition = 0;
// enumRecvState = RecvState.WaitingBeginChar1_State;
// }
// break;
//case RecvState.WaitingForData_State:
// iBarcodeLength = 12;
// Array.Copy(buffer, i, m_szFullMessage, m_iPosition, iBarcodeLength);
// m_RFly_I160Adapter.LogInfo.Warn("RFly-I160进入 WaitingForData_State 状态,原始条码数据如下:");
// byte[] tempData = new byte[iBarcodeLength];
// Array.Clear(tempData, 0, iBarcodeLength);
// Array.Copy(buffer, i, tempData, 0, iBarcodeLength);
// m_RFly_I160Adapter.LogInfo.Warn("解析的数据为: "+StringChange.bytesToHexStr(tempData,iBarcodeLength));
// m_iPosition = m_iPosition+iBarcodeLength;
// i = i + iBarcodeLength - 1;
// enumRecvState = RecvState.WaitingForXor_State;
// break;
#endregion
case RecvState.WaitingForXor_State: //开始比对校验位 Rfly160
byte[] m_CRCVerify = new byte[1024]; //此数组用于校验位计算
Array.Clear(m_CRCVerify, 0, m_CRCVerify.Length);
Array.Copy(m_szFullMessage, 2, m_CRCVerify, 0, iBarcodeLength + 3); //校验位计算是从Length - EPC 结束
m_szFullMessage[m_iPosition] = buffer[i];
m_iVerify = m_szFullMessage[m_iPosition];
if (m_iVerify == CalculateVerify(m_CRCVerify, m_CRCVerify.Length))
{
m_iPosition++;
enumRecvState = RecvState.WaitingForEndChar_State;
}
else //如果校验不成功
{
m_iFullMessageLength = 0;
m_iPosition = 0;
enumRecvState = RecvState.WaitingBeginChar1_State;
}
break;
case RecvState.WaitingForEndChar_State:
if (buffer[0] == 0xBB && buffer[1] == 0xDD && buffer[2] == 0x00) //此处为Noread数据显示
{
//m_RFly_I160Adapter.LogInfo.Warn("RFly-I160等待接受WaitingForEndChar_State:Noread");
m_szFullMessage[0] = 0xBB;
m_szFullMessage[1] = 0xDD;
m_szFullMessage[2] = 0x00;
lock (m_FrecvData)
{
m_FrecvData.Add(m_szFullMessage);
}
m_Fsem.Release();
m_iPosition = 0;
i = iLen;
enumRecvState = RecvState.WaitingBeginChar1_State;
}
else if (buffer[i] == 0x00) //获取温度
{
m_szFullMessage[3] = 0x00;
m_iPosition++;
lock (m_FrecvData)
{
m_FrecvData.Add(m_szFullMessage);
}
m_Fsem.Release();
}
else if (buffer[0] == 0xBB && buffer[1] == 0xDD && buffer[2] == 0x04 && buffer[3] == 0xBF)
{
m_szFullMessage[3] = 0xBF;
m_iPosition++;
lock (m_FrecvData)
{
m_FrecvData.Add(m_szFullMessage);
}
m_Fsem.Release();
}
else
{
m_szFullMessage[m_iPosition] = buffer[i];
m_iPosition++;
if (buffer[i] == 0x0D)
{
//m_RFly_I160Adapter.LogInfo.Warn("RFly-I160准备发送");
lock (m_FrecvData)
{
m_FrecvData.Add(m_szFullMessage);
}
m_Fsem.Release();
}
}
m_iPosition = 0;
enumRecvState = RecvState.WaitingBeginChar1_State;
//m_RFly_I160Adapter.LogInfo.Warn("RFly-I160状态机结束。");
break;
}
}
}
//CRC异或校验
public byte CalculateVerify(byte[] pMessage, int iLength)
{
UInt16 i;
byte iVerify = 0;
iVerify = pMessage[0];
for (i = 1; i < iLength; i++)
{
iVerify = (byte)(iVerify ^ pMessage[i]);
}
return iVerify;
}
private byte[] Swap16Bytes(byte[] OldU16)
{
byte[] ReturnBytes = new byte[2];
ReturnBytes[1] = OldU16[0];
ReturnBytes[0] = OldU16[1];
return ReturnBytes;
}
private string bytesToHexStr(byte[] bytes, int iLen)//e.g. { 0x01, 0x01} ---> " 01 01"
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < iLen; i++)
{
returnStr += bytes[i].ToString("X2");
}
}
return returnStr;
}
}
}

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Mesnac.DeviceAdapter.RFly_I160
{
public interface ICommunicateService
{
void Init(string strIp, int iPort, object objetcter, ushort iDeviceId);
bool SendMessage(MessagePack pMessagePack);
bool Connect();
bool GetState();
bool DisConnect();
}
}

@ -0,0 +1,73 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.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>{786B9D51-D67A-4235-B082-78E9CF4FCFB6}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Mesnac.DeviceAdapter.RFly_I160</RootNamespace>
<AssemblyName>Mesnac.DeviceAdapter.RFly_I160</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="log4net, Version=1.2.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\dll\log4net.dll</HintPath>
</Reference>
<Reference Include="Mesnac.Log">
<HintPath>C:\Users\Administrator\Desktop\中间件及动态库设计\Mesnac读写器\动态库\Mesnac.Log.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="BgTcpClient.cs" />
<Compile Include="ICommunicateService.cs" />
<Compile Include="MessagePack.cs" />
<Compile Include="RFly_I160Device.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="StringChange.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DeviceAdapter\Mesnac.IDeviceAdapter.csproj">
<Project>{4c8c8a86-cdd8-49ac-add0-18bf89c46f88}</Project>
<Name>Mesnac.IDeviceAdapter</Name>
</ProjectReference>
</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,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using System.Threading.Tasks;
namespace Mesnac.DeviceAdapter.RFly_I160
{
public class MessagePack
{
//public byte m_beginChar1 = 0xBB; //开始包
public byte[] m_pData = null; //发送数据
//public byte m_EndChar1 = 0x0D; //结束包
}
}

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Mesnac.DeviceAdapter.RFly_I160")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Mesnac.DeviceAdapter.RFly_I160")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: log4net.Config.XmlConfigurator()]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("a305667a-a8e7-4954-8a36-48269280e30a")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

File diff suppressed because it is too large Load Diff

@ -0,0 +1,235 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Mesnac.DeviceAdapter.RFly_I160
{
public static class StringChange
{
//CRC异或校验
public static byte CalculateVerify(byte[] pMessage, int iLength)
{
UInt16 i;
byte iVerify = 0;
iVerify = pMessage[0];
for (i = 1; i < iLength; i++)
{
iVerify = (byte)(iVerify ^ pMessage[i]);
}
return iVerify;
}
public static byte[] Swap16Bytes(byte[] OldU16)
{
byte[] ReturnBytes = new byte[2];
ReturnBytes[1] = OldU16[0];
ReturnBytes[0] = OldU16[1];
return ReturnBytes;
}
public static bool CompareBytes(byte[] byteA, byte[] byteB, int iLen)
{
for (int i = 0; i < iLen; i++)
{
if (byteA[i] != byteB[i])
{
return false;
}
}
return true;
}
/// <summary>
/// 将byte数组转换成十六进制字符串 //e.g. { 0x01, 0x01} ---> " 01 01"
/// </summary>
/// <param name="bytes">byte数组</param>
/// <param name="iLen">数组长度</param>
/// <returns>十六进制字符串</returns>
public static string bytesToHexStr(byte[] bytes , int iLen)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < iLen; i++)
{
returnStr += bytes[i].ToString("X2");
}
}
return returnStr;
}
public static byte[] HexStrTorbytes(string strHex)//e.g. " 01 01" ---> { 0x01, 0x01}
{
strHex = strHex.Replace(" ", "");
if ((strHex.Length % 2) != 0)
strHex += " ";
byte[] returnBytes = new byte[strHex.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(strHex.Substring(i * 2, 2), 16);
return returnBytes;
}
public static string StringToHexString(string s, Encoding encode)
{
byte[] b = encode.GetBytes(s); //按照指定编码将string编程字节数组
string result = string.Empty;
for (int i = 0; i < b.Length; i++) //逐字节变为16进制字符以%隔开
{
result += "%" + Convert.ToString(b[i], 16);
}
return result;
}
public static string HexStringToString(string hs, Encoding encode)
{
//以%分割字符串,并去掉空字符
string[] chars = hs.Split(new char[] { '%' }, StringSplitOptions.RemoveEmptyEntries);
byte[] b = new byte[chars.Length];
//逐个字符变为16进制字节数据
for (int i = 0; i < chars.Length; i++)
{
b[i] = Convert.ToByte(chars[i], 16);
}
//按照指定编码将字节数组变为字符串
return encode.GetString(b);
}
public static short SwapInt16(this short n)
{
return (short)(((n & 0xff) << 8) | ((n >> 8) & 0xff));
}
public static ushort SwapUInt16(this ushort n)
{
return (ushort)(((n & 0xff) << 8) | ((n >> 8) & 0xff));
}
public static int SwapInt32(this int n)
{
return (int)(((SwapInt16((short)n) & 0xffff) << 0x10) |
(SwapInt16((short)(n >> 0x10)) & 0xffff));
}
public static uint SwapUInt32(this uint n)
{
return (uint)(((SwapUInt16((ushort)n) & 0xffff) << 0x10) |
(SwapUInt16((ushort)(n >> 0x10)) & 0xffff));
}
public static long SwapInt64(this long n)
{
return (long)(((SwapInt32((int)n) & 0xffffffffL) << 0x20) |
(SwapInt32((int)(n >> 0x20)) & 0xffffffffL));
}
public static ulong SwapUInt64(this ulong n)
{
return (ulong)(((SwapUInt32((uint)n) & 0xffffffffL) << 0x20) |
(SwapUInt32((uint)(n >> 0x20)) & 0xffffffffL));
}
public class IOInfo
{
public int id;
public byte[] state;
public DateTime time;
}
public class MethodFilterData
{
private static List<IOInfo> IOInfolist = new List<IOInfo>();
/// <summary>
/// 消除抖动,删除短暂时间内的
/// </summary>
/// <returns></returns>
public static bool EliminatingJitter(int id, byte[] data)
{
var index = IOInfolist.FindIndex((x) => { return x.id == id; });
if (index == -1 || Array.Equals(IOInfolist[index].state, data))
{
IOInfolist.Add(new IOInfo
{
id = id,
state = data,
time = DateTime.Now
});
}
else
{
TimeSpan ts1 = new TimeSpan(IOInfolist[index].time.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
TimeSpan ts3 = ts2.Subtract(ts1); //ts2-ts1
double sumSeconds = Convert.ToDouble(ts3.TotalSeconds.ToString()); //得到相差秒数
if (sumSeconds < 5)
{
return true;
}
else
{
IOInfolist[index] = new IOInfo
{
id = id,
state = data,
time = DateTime.Now
};
}
}
return false;
}
/// <summary>
/// 屏蔽重复条码
/// </summary>
/// <param name="id">传感器编号</param>
/// <param name="data"></param>
/// <returns></returns>
public static bool IsRepeat(int id, byte[] data)
{
var index = IOInfolist.FindIndex((x) => { return x.id == id; });
if (index == -1)
{
IOInfolist.Add(new IOInfo
{
id = id,
state = data,
time = DateTime.Now
});
return false;
}
if (string.Equals(bytesToHexStr(IOInfolist[index].state, IOInfolist[index].state.Length), bytesToHexStr(data, data.Length)))
{
IOInfolist[index].time = DateTime.Now;
return true;
}
else
{
IOInfolist[index].state = data;
return false;
}
}
}
public static int HexStringToNegative(string strNumber)
{
int iNegate = 0;
int iNumber = Convert.ToInt32(strNumber, 16);
if (iNumber > 127)
{
int iComplement = iNumber - 1;
string strNegate = string.Empty;
char[] binchar = Convert.ToString(iComplement, 2).PadLeft(8, '0').ToArray();
foreach (char ch in binchar)
{
if (Convert.ToInt32(ch) == 48)
{
strNegate += "1";
}
else
{
strNegate += "0";
}
}
iNegate = -Convert.ToInt32(strNegate, 2);
}
return iNegate;
}
}
}
Loading…
Cancel
Save