添加项目文件。

dep
wangsr 2 years ago
parent fd42c38ca2
commit 52321d7987

@ -0,0 +1,65 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" 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>{89A1EDD9-D79E-468D-B6D3-7D07B8843562}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>HighWayIot.Common</RootNamespace>
<AssemblyName>HighWayIot.Common</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<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>
</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>
</PropertyGroup>
<ItemGroup>
<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="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="JsonChange.cs" />
<Compile Include="MsgUtil.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="StringChange.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\HighWayIot.Log4net\HighWayIot.Log4net.csproj">
<Project>{deabc30c-ec6f-472e-bd67-d65702fdaf74}</Project>
<Name>HighWayIot.Log4net</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

@ -0,0 +1,115 @@
using HighWayIot.Log4net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Xml.Linq;
namespace HighWayIot.Common
{
public class JsonChange
{
private static readonly Lazy<JsonChange> lazy = new Lazy<JsonChange>(() => new JsonChange());
public static JsonChange Instance
{
get
{
return lazy.Value;
}
}
private LogHelper log = LogHelper.Instance;
private JsonChange() { }
/// <summary>
/// Model 实体转json
/// </summary>
/// <param name="Model">可以是单个实体也可是实体集ToList()</param>
/// <returns></returns>
public string ModeToJson(object Model)
{
string str = "";
JavaScriptSerializer serializer = new JavaScriptSerializer();
try
{
str = serializer.Serialize(Model);
}
catch (Exception ex)
{
log.Error("Model转Json异常",ex);
}
return str;
}
/// <summary>
/// json实体转Model
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonStr"></param>
/// <returns></returns>
public T JsonToMode<T>(string jsonStr)
{
T info = default(T);
JavaScriptSerializer serializer = new JavaScriptSerializer();
try
{
info = serializer.Deserialize<T>(jsonStr);
}
catch (Exception ex)
{
log.Error("Json转Model异常" ,ex);
}
return info;
}
/// <summary>
/// object转dictionary
/// </summary>
/// <param name="jsonData"></param>
/// <returns></returns>
public Dictionary<string, object> objectToDictionary(string jsonData)
{
Dictionary<string, object> result = new Dictionary<string, object>();
var inf = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonData);
foreach (KeyValuePair<string, object> item in inf)
{
if (item.Value != null)
{
var type = item.Value.GetType();
if (type == typeof(JObject))
{
var info = objectToDictionary(JsonConvert.SerializeObject(item.Value));
foreach (KeyValuePair<string, object> ite in info)
{
result.Add(ite.Key, ite.Value);
}
continue;
}
else if (type == typeof(JArray))
{
JArray array = (JArray)item.Value;
var info = objectToDictionary(JsonConvert.SerializeObject(array[0]));
foreach (KeyValuePair<string, object> ite in info)
{
result.Add(item.Key + ite.Key, ite.Value);
}
continue;
}
}
result.Add(item.Key, item.Value);
}
return result;
}
}
}

@ -0,0 +1,511 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace HighWayIot.Common
{
/// <summary>
/// 工具类
/// </summary>
public sealed class MsgUtil
{
private static readonly Lazy<MsgUtil> lazy = new Lazy<MsgUtil>(() => new MsgUtil());
public static MsgUtil Instance
{
get
{
return lazy.Value;
}
}
private MsgUtil() { }
#region 数据解析公共方法
/// <summary>
/// 字节数组转换成结构体
/// </summary>
/// <param name="buf"></param>
/// <param name="len"></param>
/// <param name="type"></param>
/// <returns></returns>
public static object BytesToStruct(byte[] buf, int len, Type type)
{
object rtn;
IntPtr buffer = Marshal.AllocHGlobal(len);
Marshal.Copy(buf, 0, buffer, len);
try
{
rtn = Marshal.PtrToStructure(buffer, type);
Marshal.FreeHGlobal(buffer);
}
catch (Exception)
{
return null;
}
return rtn;
}
public 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;
}
//// <summary>
/// 结构体转byte数组
/// </summary>
/// <param name="structObj">要转换的结构体</param>
/// <returns>转换后的byte数组</returns>
public static byte[] StructToBytes(object structObj)
{
//得到结构体的大小
int size = Marshal.SizeOf(structObj);
//创建byte数组
byte[] bytes = new byte[size];
//分配结构体大小的内存空间
IntPtr structPtr = Marshal.AllocHGlobal(size);
//将结构体拷到分配好的内存空间
Marshal.StructureToPtr(structObj, structPtr, false);
//从内存空间拷到byte数组
Marshal.Copy(structPtr, bytes, 0, size);
//释放内存空间
Marshal.FreeHGlobal(structPtr);
//返回byte数组
return bytes;
}
#endregion
#region 消息验证方法
/// <summary>
/// CS和校验
/// </summary>
/// <param name="Abyte"></param>
/// <returns></returns>
public byte Check_CS(byte[] Abyte)
{
byte result = new byte();
try
{
int num = 0;
for (int i = 0; i < Abyte.Length; i++)
{
num = (num + Abyte[i]) % 256;
}
result = (byte)num;
}
catch
{
result = 0;
}
return result;
}
/// <summary>
/// BCC异或取反校验
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public string getBCC(byte[] data)
{
String ret = "";
byte[] BCC = new byte[1];
for (int i = 0; i < data.Length; i++)
{
BCC[0] = (byte)(BCC[0] ^ data[i]);
}
String hex = ((~BCC[0]) & 0xFF).ToString("X");//取反操作
if (hex.Length == 1)
{
hex = '0' + hex;
}
ret += hex.ToUpper();
return ret;
}
static int BytesToInt(byte[] b, int length)
{
int temp = 0;
for (int i = 0; i <= length - 1 && i < 4; i++)
{
temp += (int)(b[i] << (i * 8));
}
return temp;
}
public static byte[] CalculateVerify(byte[] pMessage, int iLength)
{
UInt16 i;
int iVerify = 0;
iVerify = pMessage[0];
for (i = 0; i < iLength - 1; i++)
{
iVerify = iVerify + pMessage[i + 1];
}
return BitConverter.GetBytes(Convert.ToUInt16(iVerify));
}
#endregion
public 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;
}
/// <summary>
/// 将字符串强制转换成int转换失败则返回0
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public int ParseToInt(string str)
{
int returnInt = 0;
if (str == null || str.Trim().Length < 1)
{
return returnInt;
}
if (int.TryParse(str, out returnInt))
{
return returnInt;
}
else
{
return 0;
}
}
public byte[] HexToString(string Str)
{
byte[] str = new byte[Str.Length / 2];
for (int i = 0; i < str.Length; i++)
{
int temp = Convert.ToInt32(Str.Substring(i * 2, 2), 16);
str[i] = (byte)temp;
}
return str;
}
public string ConverToString(byte[] data)
{
string str;
StringBuilder stb = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
if ((int)data[i] > 15)
{
stb.Append(Convert.ToString(data[i], 16).ToUpper()); //添加字符串
}
else //如果是小于0F需要加个零
{
stb.Append("0" + Convert.ToString(data[i], 16).ToUpper());
}
}
str = stb.ToString();
return str;
}
public string bytesToHexStr(byte[] bytes, int iLen)
{
StringBuilder sb = new StringBuilder();
if (bytes != null)
{
for (int i = 0; i < iLen; i++)
{
sb.Append(bytes[i].ToString("X2"));
}
}
return sb.ToString();
}
/// <summary>
/// 从十进制转换到十六进制
/// </summary>
/// <param name="ten"></param>
/// <returns></returns>
public string Ten2Hex(string ten)
{
ulong tenValue = Convert.ToUInt64(ten);
ulong divValue, resValue;
string hex = "";
do
{
//divValue = (ulong)Math.Floor(tenValue / 16);
divValue = (ulong)Math.Floor((decimal)(tenValue / 16));
resValue = tenValue % 16;
hex = tenValue2Char(resValue) + hex;
tenValue = divValue;
}
while (tenValue >= 16);
if (tenValue != 0)
hex = tenValue2Char(tenValue) + hex;
return hex;
}
public static string tenValue2Char(ulong ten)
{
switch (ten)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
return ten.ToString();
case 10:
return "A";
case 11:
return "B";
case 12:
return "C";
case 13:
return "D";
case 14:
return "E";
case 15:
return "F";
default:
return "";
}
}
}
#region 消息公用的头尾
/// <summary>
/// 能源通讯协议结构体
/// </summary>
public enum CallbackSendData
{
_LoginIn = 0XA1,
_SetTime = 0X08,
_HeartBeat = 0XA4,
_ERealFlag = 0XB3,
_SRealFlag = 0XB4,
_TRealFlag = 0XB5,
_IRealFlag = 0XB6,
_EFlag = 0XC3,
_SFlag = 0XC4,
_TFlag = 0XC5,
_IFlag = 0XC6,
}
public struct struFrame
{
//帧开始
public byte BeginChar_State;
//采集器类型
public byte Collection_Type;
//采集器地址
public byte[] Collection_Addr;
//命令序列号
public byte[] Command_Id;
//起始符
public byte StartChar_State;
//控制码
public byte Ctrl_State;
//数据长度
public byte[] DataLen_State;
//数据域
public byte[] Data_State;
//校验码
public byte CSChar_State;
//结束符
public byte EndChar_State;
//终端类型
public byte flagDTN;
//逻辑编号
public byte[] addrDNL;
//主站地址
public byte flagMSTA;
//帧内序号
public byte flagISEQ;
//帧序号
public byte flagFSEQ;
//控制码
public byte flagCtrl;
//传送方向
public byte flagCtrlD;
//异常标志
public byte flagCtrlE;
//功能标志
public byte flagCtrlF;
//数据长度
public int lenData;
//数据字符串
public byte[] strData;
public object userData;
public string tName;
public object userData2;
//public bool isCtrl;
//public bool isData;
public bool isTimeCorrectting;
};
/// <summary>
/// 头文件
/// </summary>
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct Head
{
public byte start; //起始
public short addr; //软件地址
public byte mstaseq; //主站地址与命令序号
public byte control; //控制码
public short length; //数据长度
}
/// <summary>
/// 结尾
/// </summary>
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct Tail
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public byte[] verifica; //校验码
public byte end; //结束码
}
#endregion
#region 与MES通讯协议
//识别一条EPC数据 125+3
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct ReadEPC
{
public Head head;
public int num;//合并编号
public Tail tail;
}
/// <summary>
/// 写入反馈 125+5
/// </summary>
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct RecWrite
{
public Head head;
public int num;//合并编号
public byte state;//1成功0失败2写失败读成功
public Tail tail;
}
//
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct RecDataCell
{
public byte len;//Data长度
public byte[] data;//len 长度个字节数据
}
/// <summary>
/// 自报数据 125+6
/// </summary>
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct RecAutoData
{
public Head head;
public int num;//合并编号
public RecDataCell recDatas;//自报数据
public Tail tail;
}
/// <summary>
///心跳 101
/// </summary>
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct Heart
{
public Head head;
public Tail tail;
}
#endregion
#region 与上层应用层 消息指令
/// <summary>
/// 收到的消息指令
/// </summary>
enum RecAppMsgType
{
_ReadEpc = 125 + 3,
_ReadData = 125 + 4,
_WirteData = 125 + 5,
_AutoSendData,
_HeartBeat = 101,
_ReadEquipState = 125 + 102,
_SendGetSoftState = 125 + 103,
}
/// <summary>
/// 发送的消息指令
/// </summary>
enum RetAppMsgType
{
_RetEpc = 125 + 3,
_RetData = 125 + 4,
_RetDataBack = 125 + 5,
_RetAutoSendData,
_RetEquipState = 125 + 102,
_RetGetSoftState = 125 + 103,
}
#endregion
#region 与设备层 适配层消息指令
//收到设备层消息
enum RecEquipMsgType
{
_GetEquipInfo = 0X01, //收到适配软件所需设备信息
_GetSensor = 0x02, //收到适配软件传感器信息
_EPCinfo = 0x03, //收到设备返回数据 将数据发送MES 并保存数据库
_SendData = 0x04, //收到读取到的数据 收到数据后上传给MES并保存数据库
_RecGetData = 0x05, //收到写入的数据是否成功反馈
_RecAutoData = 0x06, //收到设备自报数据
_HeartBeat = 101, //心跳
_EquipState, //设备状态
}
//发送给设备层消息
enum RetEquipMsgType
{
_RetEquipInfo = 0X01, //获取适配软件所需设备信息
_RetSensor = 0x02, //获取适配软件传感器信息
_GetEPCinfo = 0x03, //向设备发送命令识别EPC数据
_GetData = 0x04, //向设备发送命令,读取数据
_WirteData = 0x05, //向设备发送命令,写入数据
_RetAutoData = 0x06, //收到设备自爆数据反馈
}
#endregion
}

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("HighWayIot.Common")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HighWayIot.Common")]
[assembly: AssemblyCopyright("Copyright © 2023")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("89a1edd9-d79e-468d-b6d3-7d07b8843562")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -0,0 +1,216 @@
using HighWayIot.Log4net;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HighWayIot.Common
{
public class StringChange
{
private static readonly Lazy<StringChange> lazy = new Lazy<StringChange>(() => new StringChange());
public static StringChange Instance
{
get
{
return lazy.Value;
}
}
private StringChange() { }
/// <summary>
/// 将字符串强制转换成int转换失败则返回0
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public int ParseToInt(string str)
{
int returnInt = 0;
if (str == null || str.Trim().Length < 1)
{
return returnInt;
}
if (int.TryParse(str, out returnInt))
{
return returnInt;
}
else
{
return 0;
}
}
/// <summary>
/// char数组转Array
/// </summary>
/// <param name="cha"></param>
/// <param name="len"></param>
/// <returns></returns>
public string CharArrayToString(char[] cha, int len)
{
string str = "";
for (int i = 0; i < len; i++)
{
str += string.Format("{0}", cha[i]);
}
return str;
}
public 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;
}
public 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 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 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 byte[] Swap16Bytes(byte[] OldU16)
{
byte[] ReturnBytes = new byte[2];
ReturnBytes[1] = OldU16[0];
ReturnBytes[0] = OldU16[1];
return ReturnBytes;
}
/// <param name="strbase64">64Base码</param>
/// <param name="path">保存路径</param>
/// <param name="filename">文件名称</param>
/// <returns></returns>
public bool Base64ToImage(string strbase64, string path, string filename)
{
bool Flag = false;
try
{
//base64编码的文本 转为 图片
//图片名称
byte[] arr = Convert.FromBase64String(strbase64);//将指定的字符串(它将二进制数据编码为 Base64 数字)转换为等效的 8 位无符号整数数组。
using (MemoryStream ms = new MemoryStream(arr))
{
Bitmap bmp = new Bitmap(ms);//加载图像
if (!Directory.Exists(path))//判断保存目录是否存在
{
Directory.CreateDirectory(path);
}
bmp.Save((path + "\\" + filename + ".png"),System.Drawing.Imaging.ImageFormat.Png);//将图片以JPEG格式保存在指定目录(可以选择其他图片格式)
ms.Close();//关闭流并释放
if (File.Exists(path + "\\" + filename + ".png"))//判断是否存在
{
Flag = true;
}
}
}
catch (Exception ex)
{
Console.WriteLine("图片保存失败:" + ex.Message);
}
return Flag;
}
/// <summary>
/// 获取时间戳
/// </summary>
/// <returns></returns>
public long GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds);
}
public byte[] ConvertFloatToINt(byte[] floatBytes)
{
byte[] intBytes = new byte[floatBytes.Length / 2];
for (int i = 0; i < intBytes.Length; i++)
{
intBytes[i] = floatBytes[i * 2 + 1];
}
return intBytes;
}
//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;
}
public 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;
}
}
}

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="13.0.3" targetFramework="net452" />
</packages>

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

@ -0,0 +1,55 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" 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>{DEABC30C-EC6F-472E-BD67-D65702FDAF74}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>HighWayIot.Log4net</RootNamespace>
<AssemblyName>HighWayIot.Log4net</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<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>
</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>
</PropertyGroup>
<ItemGroup>
<Reference Include="log4net">
<HintPath>..\HighWayIot.Library\log4net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="LogHelper.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="config\log4net.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

@ -0,0 +1,147 @@
using log4net.Config;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HighWayIot.Log4net
{
public class LogHelper
{
private static readonly Lazy<LogHelper> lazy = new Lazy<LogHelper>(() => new LogHelper());
public static LogHelper Instance
{
get
{
return lazy.Value;
}
}
private readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");
private readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror");
private readonly log4net.ILog logView = log4net.LogManager.GetLogger("viewlog");
private readonly log4net.ILog sqllog = log4net.LogManager.GetLogger("sqllog");
private readonly log4net.ILog semaphorelog = log4net.LogManager.GetLogger("semaphorelog");
private readonly log4net.ILog logPlc = log4net.LogManager.GetLogger("plclog");
private readonly log4net.ILog logRfid = log4net.LogManager.GetLogger("rfidlog");
/**
*
*
*/
//private readonly string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.config");
private readonly string fileName = "Z:\\Desktop\\日常代码\\HighWayIot\\HighWayIot.Log4net\\config\\log4net.config";
private LogHelper()
{
if (File.Exists(fileName))
{
XmlConfigurator.Configure(new FileInfo(fileName));
}
}
/// <summary>
/// 记录Info日志
/// </summary>
/// <param name="msg"></param>
/// <param name="ex"></param>
public void Info(string msg)
{
if (loginfo.IsInfoEnabled)
{
loginfo.Info(msg);
}
}
/// <summary>
/// 记录PLC日志
/// </summary>
/// <param name="msg"></param>
public void PlcLog(string msg)
{
if (logPlc.IsInfoEnabled)
{
logPlc.Info(msg);
}
}
/// <summary>
/// 记录Rfid日志
/// </summary>
/// <param name="msg"></param>
public void RfidLog(string msg)
{
if (logRfid.IsInfoEnabled)
{
logRfid.Info(msg);
}
}
/// <summary>
/// 界面日志
/// </summary>
/// <param name="msg"></param>
public void ViewLog(string msg)
{
if (logView.IsInfoEnabled)
{
logView.Info(msg);
}
}
public void SqlLog(string msg)
{
if (sqllog.IsInfoEnabled)
{
sqllog.Info(msg);
}
}
public void SemaphoreLog(string msg)
{
if (semaphorelog.IsInfoEnabled)
{
semaphorelog.Info(msg);
}
}
/// <summary>
/// 记录Error日志
/// </summary>
/// <param name="errorMsg"></param>
/// <param name="ex"></param>
public void Error(string info, Exception ex = null)
{
if (!string.IsNullOrEmpty(info) && ex == null)
{
logerror.ErrorFormat("【附加信息】 : {0}<br>", new object[] { info });
}
else if (!string.IsNullOrEmpty(info) && ex != null)
{
string errorMsg = BeautyErrorMsg(ex);
logerror.ErrorFormat("【附加信息】 : {0}<br>{1}", new object[] { info, errorMsg });
}
else if (string.IsNullOrEmpty(info) && ex != null)
{
string errorMsg = BeautyErrorMsg(ex);
logerror.Error(errorMsg);
}
}
/// <summary>
/// 美化错误信息
/// </summary>
/// <param name="ex">异常</param>
/// <returns>错误信息</returns>
private string BeautyErrorMsg(Exception ex)
{
string errorMsg = string.Format("【异常类型】:{0} <br>【异常信息】:{1} <br>【堆栈调用】:{2}", new object[] { ex.GetType().Name, ex.Message, ex.StackTrace });
errorMsg = errorMsg.Replace("\r\n", "<br>");
errorMsg = errorMsg.Replace("位置", "<strong style=\"color:red\">位置</strong>");
return errorMsg;
}
}
}

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

@ -0,0 +1,153 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
</configSections>
<appSettings>
</appSettings>
<log4net>
<!--错误日志类-->
<logger name="logerror">
<level value="ALL" />
<appender-ref ref="ErrorAppender" />
</logger>
<!--信息日志类-->
<logger name="loginfo">
<level value="ALL" />
<appender-ref ref="InfoAppender" />
</logger>
<!--PLC日志类-->
<logger name="plclog">
<level value="ALL" />
<appender-ref ref="PlcAppender" />
</logger>
<!--RFID日志类-->
<logger name="rfidlog">
<level value="ALL" />
<appender-ref ref="RfidAppender" />
</logger>
<!--RFID日志类-->
<logger name="viewlog">
<level value="ALL" />
<appender-ref ref="ViewAppender" />
</logger>
<!--Sql日志类-->
<logger name="sqllog">
<level value="ALL" />
<appender-ref ref="SqlAppender" />
</logger>
<!--信号量日志类-->
<logger name="semaphorelog">
<level value="ALL" />
<appender-ref ref="SemaphoreAppender" />
</logger>
<!--错误日志附加介质-->
<appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\" />
<param name="AppendToFile" value="true" />
<param name="MaxSizeRollBackups" value="100" />
<param name="MaxFileSize" value="10240" />
<param name="StaticLogFileName" value="false" />
<param name="DatePattern" value='yyyy-MM-dd/"LogError.html"'/>
<param name="RollingStyle" value="Date" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="&lt;HR COLOR=red&gt;%n异常时间%d [%t] &lt;BR&gt;%n异常级别%-5p &lt;BR&gt;%n异 常 类:%c [%x] &lt;BR&gt;%n%m &lt;BR&gt;%n &lt;HR Size=1&gt;" />
</layout>
</appender>
<!--信息日志附加介质-->
<appender name="InfoAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\" />
<param name="AppendToFile" value="true" />
<param name="MaxFileSize" value="10240" />
<param name="MaxSizeRollBackups" value="100" />
<param name="StaticLogFileName" value="false" />
<param name="DatePattern" value='yyyy-MM-dd/"LogInfo.txt"' />
<param name="RollingStyle" value="Date" />
<!--信息日志布局-->
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="&lt;--------------&gt;%n日志时间%d [%t] %n日志级别%-5p %n日志内容%m %n " />
</layout>
</appender>
<!--PLC日志附加介质-->
<appender name="PlcAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\" />
<param name="AppendToFile" value="true" />
<param name="MaxFileSize" value="10240" />
<param name="MaxSizeRollBackups" value="100" />
<param name="StaticLogFileName" value="false" />
<param name="DatePattern" value='yyyy-MM-dd/"PlcLog.txt"' />
<param name="RollingStyle" value="Date" />
<!--信息日志布局-->
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="&lt;--------------&gt;%n日志时间%d [%t] %n日志级别%-5p %n日志内容%m %n " />
</layout>
</appender>
<!--Rfid日志附加介质-->
<appender name="RfidAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\" />
<param name="AppendToFile" value="true" />
<param name="MaxFileSize" value="10240" />
<param name="MaxSizeRollBackups" value="100" />
<param name="StaticLogFileName" value="false" />
<param name="DatePattern" value='yyyy-MM-dd/"RfidLog.txt"' />
<param name="RollingStyle" value="Date" />
<!--信息日志布局-->
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="&lt;--------------&gt;%n日志时间%d [%t] %n日志级别%-5p %n日志内容%m %n " />
</layout>
</appender>
<appender name="ViewAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\" />
<param name="AppendToFile" value="true" />
<param name="MaxFileSize" value="10240" />
<param name="MaxSizeRollBackups" value="100" />
<param name="StaticLogFileName" value="false" />
<param name="DatePattern" value='yyyy-MM-dd/"ViewLog.txt"' />
<param name="RollingStyle" value="Date" />
<!--信息日志布局-->
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="&lt;--------------&gt;%n日志时间%d [%t] %n日志级别%-5p %n日志内容%m %n " />
</layout>
</appender>
<appender name="SqlAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\" />
<param name="AppendToFile" value="true" />
<param name="MaxFileSize" value="10240" />
<param name="MaxSizeRollBackups" value="100" />
<param name="StaticLogFileName" value="false" />
<param name="DatePattern" value='yyyy-MM-dd/"SqlLog.txt"' />
<param name="RollingStyle" value="Date" />
<!--信息日志布局-->
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="&lt;--------------&gt;%n日志时间%d [%t] %n日志级别%-5p %n日志内容%m %n " />
</layout>
</appender>
<appender name="SemaphoreAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\" />
<param name="AppendToFile" value="true" />
<param name="MaxFileSize" value="10240" />
<param name="MaxSizeRollBackups" value="100" />
<param name="StaticLogFileName" value="false" />
<param name="DatePattern" value='yyyy-MM-dd/"SemaphoreLog.txt"' />
<param name="RollingStyle" value="Date" />
<!--信息日志布局-->
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="&lt;--------------&gt;%n日志时间%d [%t] %n日志级别%-5p %n日志内容%m %n " />
</layout>
</appender>
</log4net>
</configuration>

@ -0,0 +1,55 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" 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>{CD9B8712-0E09-42D2-849B-B8EAB02C7AB8}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>HighWayIot.Mqtt</RootNamespace>
<AssemblyName>HighWayIot.Mqtt</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<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>
</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>
</PropertyGroup>
<ItemGroup>
<Reference Include="log4net">
<HintPath>..\HighWayIot.Library\log4net.dll</HintPath>
</Reference>
<Reference Include="MQTTnet">
<HintPath>..\HighWayIot.Library\MQTTnet.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="MqttClient.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

@ -0,0 +1,153 @@
using MQTTnet.Client;
using MQTTnet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Security.Authentication;
namespace HighWayIot.Mqtt
{
public sealed class MqttClient
{
public delegate void PrintMessageReceived(string message);
public event PrintMessageReceived PrintMessageReceivedEvent;
private IMqttClient client;
private static readonly Lazy<MqttClient> lazy = new Lazy<MqttClient>(() => new MqttClient());
public static MqttClient Instance
{
get
{
return lazy.Value;
}
}
private MqttClient() { }
/// <summary>
/// 链接服务器
/// </summary>
/// <param name="ip"></param>
/// <param name="port"></param>
/// <param name="clientId"></param>
/// <param name="username"></param>
/// <param name="password"></param>
public async void Connect(string ip, int port, string clientId, string username, string password)
{
try
{
MqttClientOptions options = new MqttClientOptionsBuilder()
.WithTcpServer(ip, port)
.WithClientId(clientId)
.WithCredentials(username, password)
.WithTls(o => //开启ssl
{
o.CertificateValidationHandler = _ => true;
o.SslProtocol = SslProtocols.Tls12;
}).Build();
client = new MqttFactory().CreateMqttClient();
client.ApplicationMessageReceivedAsync += MqttClient_ApplicationMessageReceived;
MqttClientConnectResult result = await client.ConnectAsync(options);
if (result != null)
{
if (result.ResultCode == MQTTnet.Client.MqttClientConnectResultCode.Success)
{
PrintMessageReceivedEvent?.Invoke($"连接服务器成功{ip}:{port}");
}
else
{
PrintMessageReceivedEvent?.Invoke($"连接服务器失败");
}
}
}
catch (Exception ex)
{
PrintMessageReceivedEvent?.Invoke($"连接服务器异常:{ex.Message}");
}
}
/// <summary>
/// 断开链接
/// </summary>
public void DisConnect()
{
client.DisconnectAsync();
PrintMessageReceivedEvent?.Invoke($"断开连接");
}
/// <summary>
/// 订阅主题
/// </summary>
/// <param name="topic"></param>
public async void SubscriptionAsync(string topic)
{
try
{
var mqttFactory = new MqttFactory();
var mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder()
.WithTopicFilter(
f =>
{
f.WithTopic(topic);
})
.Build();
MqttClientSubscribeResult result = await client.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None);
PrintMessageReceivedEvent?.Invoke($"订阅主题:{topic}");
}
catch (Exception ex)
{
PrintMessageReceivedEvent?.Invoke($"订阅主题异常:{ex.Message}");
}
}
/// <summary>
/// 取消订阅
/// </summary>
/// <param name="topic"></param>
public void Unsubscribe(string topic)
{
client.UnsubscribeAsync(topic);
PrintMessageReceivedEvent?.Invoke($"取消订阅,主题:{topic}");
}
/// <summary>
/// 推送消息
/// </summary>
/// <param name="topic"></param>
/// <param name="message"></param>
public void Publish(string topic, string message)
{
try
{
var msg = new MqttApplicationMessageBuilder().WithTopic(topic).WithPayload(message)
.Build();
client.PublishAsync(msg, CancellationToken.None);
PrintMessageReceivedEvent?.Invoke($"向服务端推送成功,主题:{topic};内容:{message}");
}
catch (Exception ex)
{
PrintMessageReceivedEvent?.Invoke($"向服务端推送消息异常:{ex.Message}");
}
}
private async Task MqttClient_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs eventArgs)
{
var info = $"接收到主题:{eventArgs.ApplicationMessage.Topic}的消息,内容:{Encoding.UTF8.GetString(eventArgs.ApplicationMessage.Payload)}";
PrintMessageReceivedEvent?.Invoke(info);
}
}
}

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("HighWayIot.Mqtt")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HighWayIot.Mqtt")]
[assembly: AssemblyCopyright("Copyright © 2023")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("cd9b8712-0e09-42d2-849b-b8eab02c7ab8")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -0,0 +1,65 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" 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>{4EE4C3E2-AC45-4275-8017-E99D70FC1F52}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>HighWayIot.Plc</RootNamespace>
<AssemblyName>HighWayIot.Plc</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<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>
</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>
</PropertyGroup>
<ItemGroup>
<Reference Include="HslCommunication">
<HintPath>..\HighWayIot.Library\HslCommunication.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Impl\InovancePlc.cs" />
<Compile Include="Impl\OmronNJPlc.CS" />
<Compile Include="Impl\SiemensPlc.cs" />
<Compile Include="IPlc.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\HighWayIot.Common\HighWayIot.Common.csproj">
<Project>{89a1edd9-d79e-468d-b6d3-7d07b8843562}</Project>
<Name>HighWayIot.Common</Name>
</ProjectReference>
<ProjectReference Include="..\HighWayIot.Log4net\HighWayIot.Log4net.csproj">
<Project>{deabc30c-ec6f-472e-bd67-d65702fdaf74}</Project>
<Name>HighWayIot.Log4net</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

@ -0,0 +1,117 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HighWayIot.Plc
{
public interface IPlc
{
bool IsConnected { get; set; }
/// <summary>
/// 建立连接
/// </summary>
/// <param name="IP"></param>
/// <param name="port"></param>
/// <returns></returns>
bool Connect(string IP, int port);
/// <summary>
/// 断开连接
/// </summary>
/// <returns></returns>
bool DisConnect();
/// <summary>
/// 通过地址和长度读取PLC数据
/// </summary>
/// <param name="len"></param>
/// <param name="address"></param>
/// <returns></returns>
byte[] readValueByAddress(int len, string address);
/// <summary>
/// 通过PLC地址写入int类型数据
/// </summary>
/// <param name="value"></param>
/// <param name="address"></param>
/// <returns></returns>
bool writeValueByAddress(int value, string address);
/// <summary>
/// 通过PLC地址清零数据
/// </summary>
/// <param name="address"></param>
/// <param name="len"></param>
/// <returns></returns>
bool resetByAddress(string address, int len);
/// <summary>
/// 通过PLC地址读取EA值
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
string readEaByAddress(string address);
/// <summary>
/// 通过PLC地址读取交互信号
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
int readInteractiveSignal(string address);
/// <summary>
/// 通过PLC地址读取int32类型数据
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
int readInt32ByAddress(string address);
/// <summary>
/// 通过PLC地址写入int32类型数据
/// </summary>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
bool writeInt32ByAddress(string address, int value);
/// <summary>
/// 通过PLC地址读取string类型数据
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
string readStringByAddress(string address, ushort length);
/// <summary>
/// 通过PLC地址写入String类型数据
/// </summary>
/// <param name="address"></param>
/// <param name="SFC"></param>
/// <returns></returns>
bool writeStringByAddress(string address, string value);
/// <summary>
/// 通过PLC地址读取Bool类型数据
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
bool readBoolByAddress(string address);
/// <summary>
/// 通过PLC地址写入Bool类型数据
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
bool writeBoolByAddress(string address, bool value);
/// <summary>
/// 通过PLC地址写入Double类型数据
/// </summary>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
bool writeDoubleByAddress(string address, int value);
}
}

@ -0,0 +1,487 @@
using HslCommunication;
using HslCommunication.Profinet.Inovance;
using HighWayIot.Common;
using System;
using HighWayIot.Log4net;
namespace HighWayIot.Plc.Impl
{
/// <summary>
/// 汇川PLC
/// </summary>
public class InovancePlc : IPlc
{
private LogHelper log = LogHelper.Instance;
private StringChange stringChange = StringChange.Instance;
private InovanceTcpNet inovanceTcp = null;
public InovancePlc()
{
if (!HslCommunication.Authorization.SetAuthorizationCode("ed1415f8-e06a-43ad-95f7-c04f7ae93b41"))
{
log.Info("HslCommunication激活失败");
return;
}
log.Info("HslCommunication 11.0.6.0激活成功");
this.inovanceTcp = new InovanceTcpNet();
this.inovanceTcp.ConnectTimeOut = 2000;
}
public bool IsConnected { get; set; }
/// <summary>
/// 建立连接
/// </summary>
/// <param name="IP"></param>
/// <param name="port"></param>
/// <returns></returns>
public bool Connect(string IP, int port)
{
inovanceTcp?.ConnectClose();
log.PlcLog("汇川PLC连接开始");
inovanceTcp.IpAddress = IP;
inovanceTcp.Port = 502;
inovanceTcp.DataFormat = HslCommunication.Core.DataFormat.CDAB;
try
{
OperateResult connect = inovanceTcp.ConnectServer();
if (connect.IsSuccess)
{
this.IsConnected = true;
log.PlcLog("汇川PLC建立连接成功");
return true;
}
else
{
this.IsConnected = false;
log.PlcLog("汇川PLC建立连接失败");
return false;
}
}
catch (Exception ex)
{
this.IsConnected = false;
log.Error("欧姆龙NJ系列PLC建立连接异常", ex);
return false;
}
}
/// <summary>
/// 断开连接
/// </summary>
/// <returns></returns>
public bool DisConnect()
{
return inovanceTcp.ConnectClose().IsSuccess;
}
/// <summary>
/// 通过地址和长度读取PLC数据
/// </summary>
/// <param name="len"></param>
/// <param name="address"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public byte[] readValueByAddress(int len, string address)
{
//log.PlcLog("开始通过PLC地址和长度读取PLC数据");
try
{
OperateResult<byte[]> read = inovanceTcp.Read(address, (ushort)(len));
if (read.IsSuccess)
{
byte[] result = stringChange.ConvertFloatToINt(read.Content);
log.PlcLog(String.Format("通过地址和长度读取PLC数据成功{0}",stringChange.bytesToHexStr(result, result.Length)));
return result;
}
else
{
log.PlcLog("通过地址和长度读取PLC数据失败");
this.IsConnected = false;
return new byte[0];
}
}
catch (Exception ex)
{
log.Error("通过地址和长度读取PLC数据异常", ex);
this.IsConnected = false;
return new byte[0];
}
}
/// <summary>
/// 通过PLC地址写入int类型数据,模切汇川PLC复位逻辑
/// </summary>
/// <param name="value"></param>
/// <param name="address"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool writeValueByAddress(int value, string address)
{
//log.PlcLog(String.Format("开始通过PLC地址{0}写入int类型数据{1}", address, value));
OperateResult operateResult = new OperateResult();
try
{
int s = 0;
string[] strArry = address.Split('.');
//先读取整个块的内容
var info = inovanceTcp.ReadInt16(strArry[0]);
if (info.Content == 0)
{
int length = stringChange.ParseToInt(strArry[1]) + 1;
string[] array = new string[length];
for(int i=0;i< length;i++)
{
if(i == stringChange.ParseToInt(strArry[1]))
{
array[i] = value.ToString();
}
else
{
array[i] = "0";
}
}
//反转
Array.Reverse(array);
byte[] buffer = new byte[array.Length];
string result = "";
for(int i = 0; i < array.Length; i++)
{
result += (byte)Convert.ToInt32(array[i], 16);
}
s = Convert.ToInt32(result.Trim(), 2);
operateResult = inovanceTcp.Write(strArry[0], (ushort)s);
}
else
{
var inf2 = Convert.ToString(info.Content, 2);
string[] infoArray = new string[inf2.Length];
for (int i = 0; i < inf2.Length; i++)
{
infoArray[i] = inf2.Substring(i, 1);
}
Array.Reverse(infoArray);
infoArray[stringChange.ParseToInt(strArry[1])] = value.ToString();
string result = "";
foreach (var item in infoArray)
{
result = result + item;
}
s = Convert.ToInt32(result.Trim(), 10);
operateResult = inovanceTcp.Write(strArry[0], s);
}
if (operateResult.IsSuccess)
{
log.PlcLog(String.Format("开始通过PLC地址{0}写入int类型数据{1}成功", address, value));
return true;
}
log.PlcLog(String.Format("开始通过PLC地址{0}写入int类型数据{1}失败!!!", address, value));
this.IsConnected = false;
return false;
}
catch (Exception ex)
{
log.Error("通过PLC地址写入int类型数据", ex);
this.IsConnected = false;
return false;
}
}
/// <summary>
/// 通过PLC地址清零数据
/// </summary>
/// <param name="address"></param>
/// <param name="len"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool resetByAddress(string address, int len)
{
// log.PlcLog(String.Format("开发通过PLC地址{0}清零数据", address));
try
{
byte[] write = new byte[len * 2];
for (int i = 0; i < len * 2; i++)
{
write[i] = 0;
}
OperateResult operateResult = inovanceTcp.Write(address, write);
if (operateResult.IsSuccess)
{
log.PlcLog(String.Format("通过PLC地址{0}清零数据成功", address));
return true;
}
log.PlcLog(String.Format("通过PLC地址{0}清零数据失败!!!", address));
this.IsConnected = false;
return false;
}
catch (Exception ex)
{
log.Error(String.Format("通过PLC地址{0}清零数据异常", address), ex);
this.IsConnected = false;
return false;
}
}
/// <summary>
/// 通过PLC地址读取EA值
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public string readEaByAddress(string address)
{
//log.PlcLog(String.Format("通过PLC地址{0}读取EA值", address));
try
{
OperateResult<Byte[]> read = inovanceTcp.Read(address, (ushort)(8));
if (read.IsSuccess && read.Content != null)
{
string result = Convert.ToString(read.Content);
log.PlcLog(String.Format("通过PLC地址{0}读取EA值成功{1}", address, result));
return result;
}
else
{
log.PlcLog(String.Format("通过PLC地址{0}读取EA值失败", address));
this.IsConnected = false;
return "";
}
}
catch (Exception ex)
{
log.Error("通过PLC地址读取EA值异常", ex);
this.IsConnected = false;
return "";
}
}
/// <summary>
/// 通过PLC地址读取交互信号
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
public int readInteractiveSignal(string address)
{
// log.PlcLog(String.Format("开始通过PLC地址{0}读取交互信号", address));
try
{
OperateResult<short> read = inovanceTcp.ReadInt16(address);
if (read.IsSuccess)
{
log.PlcLog(String.Format("通过PLC地址{0}读取交互信号成功:{1}", address, read.Content));
return read.Content;
}
log.PlcLog(String.Format("通过PLC地址{0}读取交互信号失败!!!", address));
this.IsConnected = false;
return 0;
}
catch (Exception ex)
{
log.Error("通过PLC地址读取交互信号异常", ex);
this.IsConnected = false;
return 0;
}
}
/// <summary>
/// 通过PLC地址读取int32类型数据
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
public int readInt32ByAddress(string address)
{
//log.PlcLog(String.Format("开始通过PLC地址{0}读取int32类型数据", address));
try
{
OperateResult<short> read = inovanceTcp.ReadInt16(address);
if (read.IsSuccess)
{
log.PlcLog(String.Format("通过PLC地址{0}读取int32类型数据成功{1}", address, read.Content));
return read.Content;
}
log.PlcLog(String.Format("通过PLC地址{0}读取int32类型数据失败", address));
this.IsConnected = false;
return 0;
}
catch (Exception ex)
{
log.Error("通过PLC地址读取int32类型数据异常", ex);
this.IsConnected = false;
return 0;
}
}
/// <summary>
/// 通过PLC地址写入int32类型数据
/// </summary>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool writeInt32ByAddress(string address, int value)
{
//log.PlcLog(String.Format("开始通过PLC地址{0}写入int32类型数据{1}", address, value));
try
{
OperateResult write = inovanceTcp.Write(address, short.Parse(Convert.ToString(value)));
if (write.IsSuccess)
{
log.PlcLog(String.Format("通过PLC地址{0}写入int32类型数据{1}成功", address, value));
return true;
}
log.PlcLog(String.Format("通过PLC地址{0}写入int32类型数据{1}失败!!!", address, value));
return false;
}
catch (Exception ex)
{
log.Error(String.Format("通过PLC地址{0}写入int32类型数据异常", address), ex);
return false;
}
}
/// <summary>
/// 通过PLC地址写入String类型数据
/// </summary>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool writeStringByAddress(string address, string value)
{
//log.PlcLog(String.Format("通过PLC地址{0}写入String类型数据{1}", address, value));
try
{
OperateResult operateResult = inovanceTcp.Write(address, value);
if (operateResult.IsSuccess)
{
log.PlcLog(String.Format("通过PLC地址{0}写入String类型数据{1}成功", address, value));
return true;
}
log.PlcLog(String.Format("通过PLC地址{0}写入String类型数据{1}失败!!!", address, value));
return false;
}
catch (Exception ex)
{
log.Error(String.Format("通过PLC地址{0}写入String类型数据异常", address), ex);
return false;
}
}
/// <summary>
/// 通过PLC地址读取string类型数据
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public string readStringByAddress(string address, ushort length)
{
//log.PlcLog(String.Format("开始通过PLC地址{0}读取string类型数据", address));
try
{
OperateResult<String> read = inovanceTcp.ReadString(address, length);
if (read.IsSuccess)
{
log.PlcLog(String.Format("通过PLC地址{0}读取string类型数据成功{1}", address, read.Content));
return read.Content;
}
log.PlcLog(String.Format("通过PLC地址{0}读取string类型数据失败", address));
return "";
}
catch (Exception ex)
{
log.Error("通过PLC地址读取int32类型数据异常", ex);
return "";
}
}
/// <summary>
/// 通过PLC地址读取Bool类型数据
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool readBoolByAddress(string address)
{
//log.PlcLog(String.Format("开始通过PLC地址{0}读取bool类型数据", address));
try
{
OperateResult<bool> read = inovanceTcp.ReadBool(address);
if (read.IsSuccess)
{
log.PlcLog(String.Format("通过PLC地址{0}读取bool类型数据成功{1}", address, read.Content));
return read.Content;
}
log.PlcLog(String.Format("通过PLC地址{0}读取bool类型数据失败", address));
return false;
}
catch (Exception ex)
{
log.Error("通过PLC地址读取bool类型数据异常", ex);
return false;
}
}
/// <summary>
/// 通过PLC地址写入Bool类型数据
/// </summary>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool writeBoolByAddress(string address, bool value)
{
// log.PlcLog(String.Format("开始通过PLC地址{0}写入bool类型数据{1}", address, value));
try
{
OperateResult write = inovanceTcp.Write(address, value);
if (write.IsSuccess)
{
log.PlcLog(String.Format("通过PLC地址{0}写入bool类型数据{1}成功", address, value));
return true;
}
log.PlcLog(String.Format("通过PLC地址{0}写入bool类型数据{1}失败!!!", address, value));
return false;
}
catch (Exception ex)
{
log.Error(String.Format("通过PLC地址{0}写入bool类型数据异常", address), ex);
return false;
}
}
/// <summary>
/// 写入Double类型
/// </summary>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
public bool writeDoubleByAddress(string address, int value)
{
try
{
OperateResult write = inovanceTcp.Write(address, Convert.ToDouble(value));
if (write.IsSuccess)
{
log.PlcLog(String.Format("通过PLC地址{0}写入Double类型数据{1}成功", address, value));
return true;
}
log.PlcLog(String.Format("通过PLC地址{0}写入Double类型数据{1}失败!!!", address, value));
return false;
}
catch (Exception ex)
{
log.Error(String.Format("通过PLC地址{0}写入Double类型数据异常", address), ex);
return false;
}
}
}
}

@ -0,0 +1,444 @@
using HighWayIot.Common;
using HighWayIot.Log4net;
using HslCommunication;
using HslCommunication.Profinet.Omron;
using System;
namespace HighWayIot.Plc.Impl
{
/// <summary>
/// 欧姆龙NJ系列PLC
/// </summary>
public class OmronNJPlc : IPlc
{
private LogHelper log = LogHelper.Instance;
private StringChange stringChange = StringChange.Instance;
private OmronFinsNet omronFinsNet = null;
public OmronNJPlc()
{
if (!HslCommunication.Authorization.SetAuthorizationCode("ed1415f8-e06a-43ad-95f7-c04f7ae93b41"))
{
log.Info("HslCommunication 11.0.6.0激活失败");
return;
}
log.Info("HslCommunication 11.0.6.0激活成功");
this.omronFinsNet = new OmronFinsNet();
this.omronFinsNet.ConnectTimeOut = 2000;
}
public bool IsConnected { get; set; }
/// <summary>
/// 建立连接
/// </summary>
/// <param name="IP"></param>
/// <param name="port"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool Connect(string IP, int port)
{
log.PlcLog("欧姆龙NJ系列PLC连接开始");
omronFinsNet.IpAddress = IP;
omronFinsNet.Port = 9600;
omronFinsNet.SA1 = (byte)192;
omronFinsNet.DA1 = (byte)239;
omronFinsNet.DA2 = (byte)0;
try
{
OperateResult connect = omronFinsNet.ConnectServer();
if (connect.IsSuccess)
{
this.IsConnected = true;
log.PlcLog("欧姆龙NJ系列PLC建立连接成功");
return true;
}
else
{
this.IsConnected = false;
log.PlcLog("欧姆龙NJ系列PLC建立连接失败");
return false;
}
}
catch (Exception ex)
{
this.IsConnected = false;
log.Error("欧姆龙NJ系列PLC建立连接异常", ex);
return false;
}
}
/// <summary>
/// 断开连接
/// </summary>
/// <returns></returns>
public bool DisConnect()
{
return omronFinsNet.ConnectClose().IsSuccess;
}
/// <summary>
/// 通过地址和长度读取PLC数据
/// </summary>
/// <param name="len"></param>
/// <param name="address"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public byte[] readValueByAddress(int len, string address)
{
//log.PlcLog("开始通过PLC地址和长度读取PLC数据");
try
{
OperateResult<byte[]> read = omronFinsNet.Read(address, (ushort)(len));
if (read.IsSuccess)
{
byte[] result = stringChange.ConvertFloatToINt(read.Content);
log.PlcLog(String.Format("通过地址和长度读取PLC数据成功{0}", stringChange.bytesToHexStr(result, result.Length)));
return result;
}
else
{
log.PlcLog("通过地址和长度读取PLC数据失败");
this.IsConnected = false;
return new byte[0];
}
}
catch (Exception ex)
{
log.Error("通过地址和长度读取PLC数据异常", ex);
this.IsConnected = false;
return new byte[0];
}
}
/// <summary>
/// 通过PLC地址写入int类型数据
/// </summary>
/// <param name="value"></param>
/// <param name="address"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool writeValueByAddress(int value, string address)
{
//log.PlcLog(String.Format("开始通过PLC地址{0}写入int类型数据{1}",address,value));
try
{
OperateResult operateResult = omronFinsNet.Write(address, Convert.ToInt32(value));
if (operateResult.IsSuccess)
{
log.PlcLog(String.Format("开始通过PLC地址{0}写入int类型数据{1}成功", address, value));
return true;
}
log.PlcLog(String.Format("开始通过PLC地址{0}写入int类型数据{1}失败!!!", address, value));
this.IsConnected = false;
return false;
}
catch (Exception ex)
{
log.Error("通过PLC地址写入int类型数据", ex);
this.IsConnected = false;
return false;
}
}
/// <summary>
/// 通过PLC地址清零数据
/// </summary>
/// <param name="address"></param>
/// <param name="len"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool resetByAddress(string address, int len)
{
//log.PlcLog(String.Format("开发通过PLC地址{0}清零数据", address));
try
{
byte[] write = new byte[len * 2];
for (int i = 0; i < len * 2; i++)
{
write[i] = 0;
}
OperateResult operateResult = omronFinsNet.Write(address, write);
if (operateResult.IsSuccess)
{
log.PlcLog(String.Format("通过PLC地址{0}清零数据成功", address));
return true;
}
log.PlcLog(String.Format("通过PLC地址{0}清零数据失败!!!", address));
return false;
}
catch (Exception ex)
{
log.Error(String.Format("通过PLC地址{0}清零数据异常",address), ex);
return false;
}
}
/// <summary>
/// 通过PLC地址读取EA值
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public string readEaByAddress(string address)
{
//log.PlcLog(String.Format("通过PLC地址{0}读取EA值", address));
try
{
OperateResult<Byte[]> read = omronFinsNet.Read(address, (ushort)(8));
if (read.IsSuccess && read.Content != null)
{
string result = Convert.ToString(read.Content);
log.PlcLog(String.Format("通过PLC地址{0}读取EA值成功{1}", address,result));
return result;
}
else
{
log.PlcLog(String.Format("通过PLC地址{0}读取EA值失败", address));
this.IsConnected = false;
return "";
}
}
catch (Exception ex)
{
log.Error("通过PLC地址读取EA值异常", ex);
this.IsConnected = false;
return "";
}
}
/// <summary>
/// 通过PLC地址读取交互信号
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
public int readInteractiveSignal(string address)
{
//log.PlcLog(String.Format("开始通过PLC地址{0}读取交互信号", address));
try
{
OperateResult<short> read = omronFinsNet.ReadInt16(address);
if (read.IsSuccess)
{
log.PlcLog(String.Format("通过PLC地址{0}读取交互信号成功:{1}", address, read.Content));
return read.Content;
}
log.PlcLog(String.Format("通过PLC地址{0}读取交互信号失败!!!", address));
this.IsConnected = false;
return 0;
}
catch (Exception ex)
{
log.Error("通过PLC地址读取交互信号异常", ex);
this.IsConnected = false;
return 0;
}
}
/// <summary>
/// 通过PLC地址读取int32类型数据
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
public int readInt32ByAddress(string address)
{
//log.PlcLog(String.Format("开始通过PLC地址{0}读取int32类型数据",address));
try
{
OperateResult<short> read = omronFinsNet.ReadInt16(address);
if (read.IsSuccess)
{
log.PlcLog(String.Format("通过PLC地址{0}读取int32类型数据成功{1}", address, read.Content));
return read.Content;
}
log.PlcLog(String.Format("通过PLC地址{0}读取int32类型数据失败", address));
this.IsConnected = false;
return 0;
}
catch (Exception ex)
{
log.Error("通过PLC地址读取int32类型数据异常", ex);
this.IsConnected = false;
return 0;
}
}
/// <summary>
/// 通过PLC地址写入int32类型数据
/// </summary>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool writeInt32ByAddress(string address, int value)
{
log.PlcLog(String.Format("开始通过PLC地址{0}写入int32类型数据{1}", address,value));
try
{
OperateResult write = omronFinsNet.Write(address, short.Parse(Convert.ToString(value)));
if (write.IsSuccess)
{
log.PlcLog(String.Format("通过PLC地址{0}写入int32类型数据{1}成功", address,value));
return true;
}
log.PlcLog(String.Format("通过PLC地址{0}写入int32类型数据{1}失败!!!", address,value));
this.IsConnected = false;
return false;
}
catch (Exception ex)
{
log.Error(String.Format("通过PLC地址{0}写入int32类型数据异常", address),ex);
this.IsConnected = false;
return false;
}
}
/// <summary>
/// 通过PLC地址写入String类型数据
/// </summary>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool writeStringByAddress(string address, string value)
{
//log.PlcLog(String.Format("通过PLC地址{0}写入String类型数据{1}",address,value));
try
{
OperateResult operateResult = omronFinsNet.Write(address, value);
if (operateResult.IsSuccess)
{
log.PlcLog(String.Format("通过PLC地址{0}写入String类型数据{1}成功", address, value));
return true;
}
log.PlcLog(String.Format("通过PLC地址{0}写入String类型数据{1}失败!!!", address, value));
//this.IsConnected = false;
return false;
}
catch (Exception ex)
{
log.Error(String.Format("通过PLC地址{0}写入String类型数据异常", address),ex);
//this.IsConnected = false;
return false;
}
}
/// <summary>
/// 通过PLC地址读取string类型数据
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public string readStringByAddress(string address,ushort length)
{
//log.PlcLog(String.Format("开始通过PLC地址{0}读取string类型数据", address));
try
{
OperateResult<String> read = omronFinsNet.ReadString(address, length);
if (read.IsSuccess)
{
log.PlcLog(String.Format("通过PLC地址{0}读取string类型数据成功{1}", address, read.Content));
return read.Content;
}
log.PlcLog(String.Format("通过PLC地址{0}读取string类型数据失败", address));
this.IsConnected = false;
return "";
}
catch (Exception ex)
{
log.Error("通过PLC地址读取int32类型数据异常", ex);
return "";
}
}
/// <summary>
/// 通过PLC地址读取Bool类型数据
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool readBoolByAddress(string address)
{
//log.PlcLog(String.Format("开始通过PLC地址{0}读取bool类型数据", address));
try
{
OperateResult<bool> read = omronFinsNet.ReadBool(address);
if (read.IsSuccess)
{
log.PlcLog(String.Format("通过PLC地址{0}读取bool类型数据成功{1}", address, read.Content));
return read.Content;
}
log.PlcLog(String.Format("通过PLC地址{0}读取bool类型数据失败", address));
this.IsConnected = false;
return false;
}
catch (Exception ex)
{
log.Error("通过PLC地址读取int32类型数据异常", ex);
this.IsConnected = false;
return false;
}
}
/// <summary>
/// 通过PLC地址写入Bool类型数据
/// </summary>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
public bool writeBoolByAddress(string address, bool value)
{
//log.PlcLog(String.Format("开始通过PLC地址{0}写入bool类型数据{1}", address, value));
try
{
OperateResult write = omronFinsNet.Write(address, short.Parse(stringChange.ParseToInt(value ? "1" : "0").ToString()));
if (write.IsSuccess)
{
log.PlcLog(String.Format("通过PLC地址{0}写入bool类型数据{1}成功", address, value));
return true;
}
log.PlcLog(String.Format("通过PLC地址{0}写入bool类型数据{1}失败!!!", address, value));
this.IsConnected = false;
return false;
}
catch (Exception ex)
{
log.Error(String.Format("通过PLC地址{0}写入bool类型数据异常", address), ex);
this.IsConnected = false;
return false;
}
}
/// <summary>
/// 写入Double类型
/// </summary>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
public bool writeDoubleByAddress(string address, int value)
{
try
{
OperateResult write = omronFinsNet.Write(address, Convert.ToDouble(value));
if (write.IsSuccess)
{
log.PlcLog(String.Format("通过PLC地址{0}写入Double类型数据{1}成功", address, value));
return true;
}
log.PlcLog(String.Format("通过PLC地址{0}写入Double类型数据{1}失败!!!", address, value));
return false;
}
catch (Exception ex)
{
log.Error(String.Format("通过PLC地址{0}写入Double类型数据异常", address), ex);
return false;
}
}
}
}

@ -0,0 +1,405 @@
using HighWayIot.Common;
using HighWayIot.Log4net;
using HslCommunication;
using HslCommunication.Profinet.Siemens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HighWayIot.Plc.Impl
{
public class SiemensPlc
{
private LogHelper logHelper = LogHelper.Instance;
private StringChange stringChange = StringChange.Instance;
private const SiemensPLCS type = SiemensPLCS.S200Smart;
private SiemensS7Net s7 = new SiemensS7Net(type);
public SiemensPlc()
{
if (!HslCommunication.Authorization.SetAuthorizationCode("30c15272-3960-4853-9fab-3087392ee5cd"))
{
logHelper.Info("HslCommunication激活失败");
return;
}
}
public bool IsConnected { get; set; }
/// <summary>
/// 建立连接
/// </summary>
/// <param name="IP"></param>
/// <param name="port"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool Connect(string IP, int port)
{
logHelper.PlcLog("西门子S7系列PLC连接开始");
s7.IpAddress = IP;
s7.Port = 102;
try
{
OperateResult connect = s7.ConnectServer();
if (connect.IsSuccess)
{
this.IsConnected = true;
logHelper.PlcLog("西门子S7系列PLC建立连接成功");
return true;
}
else
{
this.IsConnected = false;
logHelper.PlcLog("西门子S7系列PLC建立连接失败");
return false;
}
}
catch (Exception ex)
{
this.IsConnected = false;
logHelper.Error("西门子S7系列PLC建立连接异常", ex);
return false;
}
}
/// <summary>
/// 通过地址和长度读取PLC数据
/// </summary>
/// <param name="len"></param>
/// <param name="address"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public byte[] readValueByAddress(int len, string address)
{
//logHelper.PlcLog("开始通过PLC地址和长度读取PLC数据");
try
{
OperateResult<byte[]> read = s7.Read(address, (ushort)(len));
if (read.IsSuccess)
{
byte[] result = stringChange.ConvertFloatToINt(read.Content);
logHelper.PlcLog(String.Format("通过地址和长度读取PLC数据成功{0}", stringChange.bytesToHexStr(result, result.Length)));
return result;
}
else
{
logHelper.PlcLog("通过地址和长度读取PLC数据失败");
this.IsConnected = false;
return new byte[0];
}
}
catch (Exception ex)
{
logHelper.Error("通过地址和长度读取PLC数据异常", ex);
this.IsConnected = false;
return new byte[0];
}
}
/// <summary>
/// 通过PLC地址写入int类型数据
/// </summary>
/// <param name="value"></param>
/// <param name="address"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool writeValueByAddress(int value, string address)
{
//logHelper.PlcLog(String.Format("开始通过PLC地址{0}写入int类型数据{1}",address,value));
try
{
OperateResult operateResult = s7.Write(address, Convert.ToInt32(value));
if (operateResult.IsSuccess)
{
logHelper.PlcLog(String.Format("开始通过PLC地址{0}写入int类型数据{1}成功", address, value));
return true;
}
logHelper.PlcLog(String.Format("开始通过PLC地址{0}写入int类型数据{1}失败!!!", address, value));
this.IsConnected = false;
return false;
}
catch (Exception ex)
{
logHelper.Error("通过PLC地址写入int类型数据", ex);
this.IsConnected = false;
return false;
}
}
/// <summary>
/// 通过PLC地址清零数据
/// </summary>
/// <param name="address"></param>
/// <param name="len"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool resetByAddress(string address, int len)
{
//logHelper.PlcLog(String.Format("开发通过PLC地址{0}清零数据", address));
try
{
byte[] write = new byte[len * 2];
for (int i = 0; i < len * 2; i++)
{
write[i] = 0;
}
OperateResult operateResult = s7.Write(address, write);
if (operateResult.IsSuccess)
{
logHelper.PlcLog(String.Format("通过PLC地址{0}清零数据成功", address));
return true;
}
logHelper.PlcLog(String.Format("通过PLC地址{0}清零数据失败!!!", address));
return false;
}
catch (Exception ex)
{
logHelper.Error(String.Format("通过PLC地址{0}清零数据异常", address), ex);
return false;
}
}
/// <summary>
/// 通过PLC地址读取EA值
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public string readEaByAddress(string address)
{
//logHelper.PlcLog(String.Format("通过PLC地址{0}读取EA值", address));
try
{
OperateResult<Byte[]> read = s7.Read(address, (ushort)(8));
if (read.IsSuccess && read.Content != null)
{
string result = Convert.ToString(read.Content);
logHelper.PlcLog(String.Format("通过PLC地址{0}读取EA值成功{1}", address, result));
return result;
}
else
{
logHelper.PlcLog(String.Format("通过PLC地址{0}读取EA值失败", address));
this.IsConnected = false;
return "";
}
}
catch (Exception ex)
{
logHelper.Error("通过PLC地址读取EA值异常", ex);
this.IsConnected = false;
return "";
}
}
/// <summary>
/// 通过PLC地址读取交互信号
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
public int readInteractiveSignal(string address)
{
//logHelper.PlcLog(String.Format("开始通过PLC地址{0}读取交互信号", address));
try
{
OperateResult<short> read = s7.ReadInt16(address);
if (read.IsSuccess)
{
logHelper.PlcLog(String.Format("通过PLC地址{0}读取交互信号成功:{1}", address, read.Content));
return read.Content;
}
logHelper.PlcLog(String.Format("通过PLC地址{0}读取交互信号失败!!!", address));
this.IsConnected = false;
return 0;
}
catch (Exception ex)
{
logHelper.Error("通过PLC地址读取交互信号异常", ex);
this.IsConnected = false;
return 0;
}
}
/// <summary>
/// 通过PLC地址读取int32类型数据
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
public int readInt32ByAddress(string address)
{
//logHelper.PlcLog(String.Format("开始通过PLC地址{0}读取int32类型数据",address));
try
{
OperateResult<short> read = s7.ReadInt16(address);
if (read.IsSuccess)
{
logHelper.PlcLog(String.Format("通过PLC地址{0}读取int32类型数据成功{1}", address, read.Content));
return read.Content;
}
logHelper.PlcLog(String.Format("通过PLC地址{0}读取int32类型数据失败", address));
this.IsConnected = false;
return 0;
}
catch (Exception ex)
{
logHelper.Error("通过PLC地址读取int32类型数据异常", ex);
this.IsConnected = false;
return 0;
}
}
/// <summary>
/// 通过PLC地址写入int32类型数据
/// </summary>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool writeInt32ByAddress(string address, int value)
{
logHelper.PlcLog(String.Format("开始通过PLC地址{0}写入int32类型数据{1}", address, value));
try
{
OperateResult write = s7.Write(address, short.Parse(Convert.ToString(value)));
if (write.IsSuccess)
{
logHelper.PlcLog(String.Format("通过PLC地址{0}写入int32类型数据{1}成功", address, value));
return true;
}
logHelper.PlcLog(String.Format("通过PLC地址{0}写入int32类型数据{1}失败!!!", address, value));
this.IsConnected = false;
return false;
}
catch (Exception ex)
{
logHelper.Error(String.Format("通过PLC地址{0}写入int32类型数据异常", address), ex);
this.IsConnected = false;
return false;
}
}
/// <summary>
/// 通过PLC地址写入String类型数据
/// </summary>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool writeStringByAddress(string address, string value)
{
//logHelper.PlcLog(String.Format("通过PLC地址{0}写入String类型数据{1}",address,value));
try
{
OperateResult operateResult = s7.Write(address, value);
if (operateResult.IsSuccess)
{
logHelper.PlcLog(String.Format("通过PLC地址{0}写入String类型数据{1}成功", address, value));
return true;
}
logHelper.PlcLog(String.Format("通过PLC地址{0}写入String类型数据{1}失败!!!", address, value));
//this.IsConnected = false;
return false;
}
catch (Exception ex)
{
logHelper.Error(String.Format("通过PLC地址{0}写入String类型数据异常", address), ex);
//this.IsConnected = false;
return false;
}
}
/// <summary>
/// 通过PLC地址读取string类型数据
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public string readStringByAddress(string address, ushort length)
{
//logHelper.PlcLog(String.Format("开始通过PLC地址{0}读取string类型数据", address));
try
{
OperateResult<String> read = s7.ReadString(address, length);
if (read.IsSuccess)
{
logHelper.PlcLog(String.Format("通过PLC地址{0}读取string类型数据成功{1}", address, read.Content));
return read.Content;
}
logHelper.PlcLog(String.Format("通过PLC地址{0}读取string类型数据失败", address));
this.IsConnected = false;
return "";
}
catch (Exception ex)
{
logHelper.Error("通过PLC地址读取int32类型数据异常", ex);
return "";
}
}
/// <summary>
/// 通过PLC地址读取Bool类型数据
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool readBoolByAddress(string address)
{
//logHelper.PlcLog(String.Format("开始通过PLC地址{0}读取bool类型数据", address));
try
{
OperateResult<bool> read = s7.ReadBool(address);
if (read.IsSuccess)
{
logHelper.PlcLog(String.Format("通过PLC地址{0}读取bool类型数据成功{1}", address, read.Content));
return read.Content;
}
logHelper.PlcLog(String.Format("通过PLC地址{0}读取bool类型数据失败", address));
this.IsConnected = false;
return false;
}
catch (Exception ex)
{
logHelper.Error("通过PLC地址读取int32类型数据异常", ex);
this.IsConnected = false;
return false;
}
}
/// <summary>
/// 通过PLC地址写入Bool类型数据
/// </summary>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
public bool writeBoolByAddress(string address, bool value)
{
//logHelper.PlcLog(String.Format("开始通过PLC地址{0}写入bool类型数据{1}", address, value));
try
{
OperateResult write = s7.Write(address, short.Parse(stringChange.ParseToInt(value ? "1" : "0").ToString()));
if (write.IsSuccess)
{
logHelper.PlcLog(String.Format("通过PLC地址{0}写入bool类型数据{1}成功", address, value));
return true;
}
logHelper.PlcLog(String.Format("通过PLC地址{0}写入bool类型数据{1}失败!!!", address, value));
this.IsConnected = false;
return false;
}
catch (Exception ex)
{
logHelper.Error(String.Format("通过PLC地址{0}写入bool类型数据异常", address), ex);
this.IsConnected = false;
return false;
}
}
}
}

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

@ -0,0 +1,89 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" 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>{D0DC3CFB-6748-4D5E-B56A-76FDC72AB4B3}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>HighWayIot.Repository</RootNamespace>
<AssemblyName>HighWayIot.Repository</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<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>
</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>
</PropertyGroup>
<ItemGroup>
<Reference Include="MySql.Data, Version=8.0.16.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>Z:\Desktop\日常代码\HighWayIot\HighWayIot.Library\MySql.Data.dll</HintPath>
</Reference>
<Reference Include="Oracle.ManagedDataAccess">
<HintPath>..\HighWayIot.Library\Oracle.ManagedDataAccess.dll</HintPath>
</Reference>
<Reference Include="SqlSugar">
<HintPath>Z:\Desktop\日常代码\HighWayIot\HighWayIot.Library\SqlSugar.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Data.SQLite">
<HintPath>Z:\Desktop\日常代码\HighWayIot\HighWayIot.Library\System.Data.SQLite.dll</HintPath>
</Reference>
<Reference Include="System.Management" />
<Reference Include="System.Numerics" />
<Reference Include="System.Transactions" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="domain\BaseBomInfo.cs" />
<Compile Include="domain\SysUserInfo.cs" />
<Compile Include="domain\BaseDeviceinfo.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Repository.cs" />
<Compile Include="service\IBaseBomInfoService.cs" />
<Compile Include="service\Impl\BaseBomInfoServiceImpl.cs" />
<Compile Include="service\ISysUserInfoService.cs" />
<Compile Include="service\IBaseDeviceinfoService.cs" />
<Compile Include="service\Impl\BaseSysUserInfoServiceImpl.cs" />
<Compile Include="service\Impl\BaseDeviceinfoServiceImpl.cs" />
<Compile Include="SqlSugarHelper.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\HighWayIot.Common\HighWayIot.Common.csproj">
<Project>{89a1edd9-d79e-468d-b6d3-7d07b8843562}</Project>
<Name>HighWayIot.Common</Name>
</ProjectReference>
<ProjectReference Include="..\HighWayIot.Log4net\HighWayIot.Log4net.csproj">
<Project>{deabc30c-ec6f-472e-bd67-d65702fdaf74}</Project>
<Name>HighWayIot.Log4net</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("HighWayIot.Repository")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HighWayIot.Repository")]
[assembly: AssemblyCopyright("Copyright © 2023")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("d0dc3cfb-6748-4d5e-b56a-76fdc72ab4b3")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -0,0 +1,40 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HighWayIot.Repository
{
public class Repository<T> : SimpleClient<T> where T : class, new()
{
public Repository(dynamic configId)
{
/**
* configId
*/
base.Context = SqlSugarHelper.Db.GetConnectionScope(configId);
//.NET自带IOC: base.Context = 你存储的Services.GetService<ISqlSugarClient>();
//Furion: base.Context=App.GetService<ISqlSugarClient>();
//Furion脚手架: base.Context=DbContext.Instance
//SqlSugar.Ioc: base.Context=DbScoped.SugarScope;
//手动去赋值: base.Context=DbHelper.GetDbInstance()
//动态添加
//if (!SqlSugarHelper.Db.IsAnyConnection("用户读出来的数据库ConfigId"))
//{
// SqlSugarHelper.Db.AddConnection(new ConnectionConfig() { 数据库读出来信息 });
//}
//base.Context = SqlSugarHelper.Db.GetConnectionScope("用户读出来的数据库ConfigId");
}
public SqlSugarScope _db()
{
return base.Context as SqlSugarScope;
}
}
}

@ -0,0 +1,79 @@
using HighWayIot.Common;
using HighWayIot.Log4net;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HighWayIot.Repository
{
internal class SqlSugarHelper //不能是泛型类
{
private static LogHelper logHelper = LogHelper.Instance;
private static JsonChange jsonChange = JsonChange.Instance;
#region 连接字符串
/**
* Sqlite:debug
* private static string sqliteConnStr = $"Data Source={Path.GetFullPath("data\\data.db")};Version=3";
*/
//private static string sqliteConnStr = "Data Source=Z:\\Desktop\\日常代码\\HighWayIot\\HighWayIot\\bin\\Debug\\data\\data.db;Version=3";
/**
* Mysql
*/
private static string mysqlConnStr = "Data Source=127.0.0.1;Port=6000;Initial Catalog=ry-cloud;uid=root;pwd=123456;Charset=utf8mb4;SslMode=none";
//private static string oracleConnStr = "Data Source=175.27.215.92/helowin;User ID=aucma_mes;Password=aucma";
#endregion
//如果是固定多库可以传 new SqlSugarScope(List<ConnectionConfig>,db=>{}) 文档:多租户
//如果是不固定多库 可以看文档Saas分库
//用单例模式
public static SqlSugarScope Db = new SqlSugarScope(
// new List<ConnectionConfig>()
//{
//new ConnectionConfig()
//{
// ConfigId = "sqlite",
// ConnectionString = sqliteConnStr,
// DbType = DbType.Sqlite,
// InitKeyType = InitKeyType.Attribute,
// IsAutoCloseConnection = true
//},
new ConnectionConfig()
{
ConfigId = "mysql",
ConnectionString = mysqlConnStr,
DbType = DbType.MySql,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
},
//},
//new ConnectionConfig()
//{
// ConfigId = "aucma_mes",
// ConnectionString = oracleConnStr,
// DbType = DbType.Oracle,
// InitKeyType = InitKeyType.Attribute,
// IsAutoCloseConnection = true
//}
//},
db =>
{
//(A)全局生效配置点
//调试SQL事件可以删掉
db.Aop.OnLogExecuting = (sql, pars) =>
{
logHelper.SqlLog($"{sql};参数:{jsonChange.ModeToJson(pars)}");
};
});
}
}

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="MySql.Data" publicKeyToken="c5687fc88969c44d" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-8.1.0.0" newVersion="8.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Data.SQLite" publicKeyToken="db937bc2d44ff139" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.0.116.0" newVersion="1.0.116.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>
</assemblyBinding>
</runtime>
</configuration>

@ -0,0 +1,22 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HighWayIot.Repository.domain
{
[SugarTable("BASE_BOMINFO")]
public class BaseBomInfo
{
/// <summary>
/// 主键标识
///</summary>
[SugarColumn(ColumnName = "OBJID", IsPrimaryKey = true, IsIdentity = true)]
public int ObjId { get; set; }
[SugarColumn(ColumnName = "BOM_CODE")]
public string bomCode { get; set; }
}
}

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using SqlSugar;
namespace HighWayIot.Repository.domain
{
/// <summary>
/// 设备信息
///</summary>
[SugarTable("base_deviceInfo")]
public class BaseDeviceinfo
{
/// <summary>
/// 主键标识
///</summary>
[SugarColumn(ColumnName="objId" ,IsPrimaryKey = true ,IsIdentity = true )]
public int ObjId { get; set; }
/// <summary>
/// 机台编号
///</summary>
[SugarColumn(ColumnName="process_Id" )]
public int? ProcessId { get; set; }
/// <summary>
/// 位置编号
///</summary>
[SugarColumn(ColumnName="position_Id" )]
public int? PositionId { get; set; }
/// <summary>
/// 设备编号
///</summary>
[SugarColumn(ColumnName="device_Id" )]
public int? DeviceId { get; set; }
/// <summary>
/// 设备名称
///</summary>
[SugarColumn(ColumnName="device_Name" )]
public string DeviceName { get; set; }
/// <summary>
/// 设备 IP
///</summary>
[SugarColumn(ColumnName="device_Ip" )]
public string DeviceIp { get; set; }
/// <summary>
/// 设备端口
///</summary>
[SugarColumn(ColumnName="device_Port" )]
public int? DevicePort { get; set; }
/// <summary>
/// 设备天线
///</summary>
[SugarColumn(ColumnName="device_Ant" )]
public int? DeviceAnt { get; set; }
/// <summary>
/// 设备类型
///</summary>
[SugarColumn(ColumnName="device_Type" )]
public string DeviceType { get; set; }
}
}

@ -0,0 +1,37 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
namespace HighWayIot.Repository.domain
{
/// <summary>
/// 用户信息
///</summary>
[SugarTable("sys_user")]
public class SysUserInfo
{
/// <summary>
/// 用户Id自增主键
///</summary>
[SugarColumn(ColumnName = "user_id", IsPrimaryKey = true, IsIdentity = true)]
public int userId { get; set; }
/// <summary>
/// 用户名称
///</summary>
[SugarColumn(ColumnName = "user_name")]
public string userName { get; set; }
/// <summary>
/// 用户密码
///</summary>
[SugarColumn(ColumnName = "password")]
public string password { get; set; }
}
}

@ -0,0 +1,14 @@
using HighWayIot.Repository.domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HighWayIot.Repository.service
{
public interface IBaseBomInfoService
{
List<BaseBomInfo> GetBomInfos();
}
}

@ -0,0 +1,20 @@
using HighWayIot.Repository.domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HighWayIot.Repository.service
{
public interface IBaseDeviceinfoService
{
/// <summary>
/// 根据工序编号获取设备集合
/// </summary>
/// <param name="ProcessId"></param>
/// <returns></returns>
List<BaseDeviceinfo> GetDeviceInfoListByProcessId(int ProcessId);
}
}

@ -0,0 +1,19 @@
using HighWayIot.Repository.domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HighWayIot.Repository.service
{
public interface ISysUserInfoService
{
/// <summary>
/// 获取用户列表
/// </summary>
/// <returns></returns>
List<SysUserInfo> GetUserInfos( );
}
}

@ -0,0 +1,30 @@
using HighWayIot.Log4net;
using HighWayIot.Repository.domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HighWayIot.Repository.service.Impl
{
public class BaseBomInfoServiceImpl:IBaseBomInfoService
{
Repository<BaseBomInfo> _bomInfoRepository => new Repository<BaseBomInfo>("aucma_mes");
private LogHelper logHelper = LogHelper.Instance;
public List<BaseBomInfo> GetBomInfos()
{
try
{
var info = _bomInfoRepository.GetList();
return info;
}catch(Exception ex)
{
logHelper.Error("获取BOM集合异常", ex);
return null;
}
}
}
}

@ -0,0 +1,23 @@
using HighWayIot.Repository.domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace HighWayIot.Repository.service.Impl
{
public class BaseDeviceinfoServiceImpl : IBaseDeviceinfoService
{
Repository<BaseDeviceinfo> _deviceInfoRepository => new Repository<BaseDeviceinfo>("mysql");
public List<BaseDeviceinfo> GetDeviceInfoListByProcessId(int ProcessId)
{
Expression<Func<BaseDeviceinfo, bool>> exp = s1 => s1.ProcessId == ProcessId;
List<BaseDeviceinfo> deviceinfos = _deviceInfoRepository.GetList(exp);
return deviceinfos;
}
}
}

@ -0,0 +1,30 @@
using HighWayIot.Log4net;
using HighWayIot.Repository.domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace HighWayIot.Repository.service.Impl
{
public class BaseSysUserInfoServiceImpl : ISysUserInfoService
{
private LogHelper log = LogHelper.Instance;
Repository<SysUserInfo> _repository => new Repository<SysUserInfo>("mysql");
public List<SysUserInfo> GetUserInfos()
{
try
{
List<SysUserInfo> deviceInfo = _repository.GetList();
return deviceInfo;
}catch (Exception ex)
{
log.Error("用户信息获取异常", ex);
return null;
}
}
}
}

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HighWayIot.Rfid.Dto
{
public class MessagePack
{
//public byte m_beginChar1 = 0xBB; //开始包
public byte[] m_pData = null; //发送数据
//public byte m_EndChar1 = 0x0D; //结束包
}
}

@ -0,0 +1,66 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" 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>{29813574-49C0-4979-A5A6-47EB7C4288A0}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>HighWayIot.Rfid</RootNamespace>
<AssemblyName>HighWayIot.Rfid</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<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>
</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>
</PropertyGroup>
<ItemGroup>
<Reference Include="GRreader">
<HintPath>..\HighWayIot.Library\GRreader.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Dto\MessagePack.cs" />
<Compile Include="ICommunicateService.cs" />
<Compile Include="IDeviceAdapter.cs" />
<Compile Include="Impl\BgTcpClient.cs" />
<Compile Include="Impl\RFLY_I160ADAPTER.CS" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\HighWayIot.Common\HighWayIot.Common.csproj">
<Project>{89a1edd9-d79e-468d-b6d3-7d07b8843562}</Project>
<Name>HighWayIot.Common</Name>
</ProjectReference>
<ProjectReference Include="..\HighWayIot.Log4net\HighWayIot.Log4net.csproj">
<Project>{deabc30c-ec6f-472e-bd67-d65702fdaf74}</Project>
<Name>HighWayIot.Log4net</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

@ -0,0 +1,18 @@
using HighWayIot.Rfid.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HighWayIot.Rfid
{
public interface ICommunicateService
{
void Init(string strIp, int iPort, object objetcter);
bool SendMessage(MessagePack pMessagePack);
bool Connect();
bool GetState();
bool DisConnect();
}
}

@ -0,0 +1,216 @@
using GRreader;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HighWayIot.Rfid
{
public delegate void RecvIdentifyData(ushort iLen, byte[] pData, byte Antenna, UInt16 iDeviceId, string strId);
public enum G2MemBank
{
RESERVED = 0, //保留区
EPC = 1,
TID = 2,
USER = 3,
};
public enum CommType
{
RJ45 = 1, //网口
RS232 = 2, //com口
RS485 = 3, //485接口
};
public enum DeviceType
{
Mesnac_PKRK = 1, //软控物联网读写器一体机_GRUI160
Alien_9650 = 2, //Alien9650
ThingMagic_Vega = 3, //ThingMagic车载读写器
Mesnac_LD = 4, //软控磊德
Mesnac_GRUV100 = 5, //软控物联网车载读写器_GRUV100
Mesnac_GRUR445 = 6, //软控物联网四端口读写器
GzgDevice = 7, //干燥柜
ZlanIO_101 = 101, //卓岚IO
Moxa_E1212 = 102, //摩砂E1212
HwIo8 = 103, //海威
RFU620 = 620, //SICK 读写器
RFly_I160 = 160,//金瑞铭RFly-I160读写器
HWKC_81600 = 81600,//海威IO设备
Fuchs = 104
};
public enum WriteOrRead
{
Write = 1, //写
Read = 2, //读
};
/// <summary>
/// 设备适配层接口
/// </summary>
public interface IDeviceAdapter
{
event RecvIdentifyData RecvIdentifyDataEvent;
/// <summary>
/// 设备初始化
/// </summary>
/// <returns>true成功false失败</returns>
/// <param name="iCommType">通讯类型 1RJ45 2串口。</param>
/// <param name="pUrl">连接字符串 当iCommType为1时pUrl格式“192.168.1.100:23”为2时pUrl格式为“Com1:9600“</param>
/// <param name="iDeviceType">详见DeviceType</param>
bool Device_Init(CommType iCommType, string pUrl, DeviceType iDeviceType);
/// <summary>
/// 设备初始化
/// </summary>
/// <returns>true成功false失败</returns>
/// <param name="iCommType">通讯类型 1RJ45 2串口。</param>
/// <param name="pUrl">连接字符串 当iCommType为1时pUrl格式“192.168.1.100:23”为2时pUrl格式为“Com1:9600“</param>
/// <param name="iDeviceType">详见DeviceType</param>
bool Device_Init_Id(CommType iCommType, string pUrl, UInt16 iDeviceId);
/// <summary>
/// 连接设备
/// </summary>
/// <returns>true成功false失败</returns>
bool Device_Connect();
/// <summary>
/// 重新连接设备
/// </summary>
/// <returns>true成功false失败</returns>
bool Device_ReConnect();
/// <summary>
/// 设备销毁
/// </summary>
void Device_Destroy();
/// <summary>
/// 设备状态
/// </summary>
/// <returns>true正常false异常</returns>
bool Device_GetState();
/// <summary>
/// 根据天线号读取单个标签数据,只返回一条
/// //只有在天线号为0的时候可以读写其他区的数据
/// </summary>
/// <returns>实际读取到的长度0为读取失败</returns>
/// <param name="filterMembank">过滤数据区域 1保留区 2TID区 3EPC区 4USER区</param>
/// <param name="filterWordPtr">过滤写入起始偏移地址单位byte</param>
/// <param name="filterWordCnt">过滤长度单位byte</param>
/// <param name="filterData">过滤数据</param>
/// <param name="Membank">数据区哉 1保留区 2TID区 3EPC区 4USER区</param>
/// <param name="WordPtr">读取起始偏移地址单位byte必须为偶数。</param>
/// <param name="WordCnt">读取长度单位byte必须为偶数。</param>
/// <param name="pReadData">读取数据存放区。</param>
/// <param name="Antenna">天线号0为本机255为所有天线</param>
UInt16 Device_Read(G2MemBank filterMembank, UInt16 filterWordPtr, UInt16 filterWordCnt, Byte[] filterData, G2MemBank Membank, UInt16 WordPtr, UInt16 WordCnt, ref Byte[] pReadData, byte Antenna);
/// <summary>
/// 根据天线号写单个标签数据
/// //只有在天线号为0的时候可以写其他区的数据
/// </summary>
/// <returns>0写失败 1写入成功 2写入和读取的不一致</returns>
/// <param name="filterMembank">过滤数据区哉 1保留区 2TID区 3EPC区 4USER区</param>
/// <param name="filterWordPtr">过滤写入起始偏移地址单位byte</param>
/// <param name="filterWordCnt">过滤写入长度单位byte</param>
/// <param name="filterData">过滤数据</param>
/// <param name="Membank">数据区哉 1保留区 2TID区 3EPC区 4USER区</param>
/// <param name="WordPtr">写入起始偏移地址单位byte必须为偶数。</param>
/// <param name="WordCnt">写入长度单位byte必须为偶数。</param>
/// <param name="pWriteData">待写入的数据</param>
/// <param name="Antenna">天线号0为本机255为所有天线</param>
UInt16 Device_Write(G2MemBank filterMembank, UInt16 filterWordPtr, UInt16 filterWordCnt, Byte[] filterData,
G2MemBank Membank, UInt16 WordPtr, UInt16 WordCnt, Byte[] pWriteData, byte Antenna);
/// <summary>
/// 根据天线号识别单个标签EPC数据只返回一条
/// </summary>
/// <returns>识别的标签EPC长度0为识别失败</returns>
/// <param name="pReadData">识别到的数据缓存区</param>
/// <param name="Antenna">天线号0为本机255为所有天线</param>
/// <param name="Timedout">超时时间,单位毫秒,识别到立即返回,未识别到等待超时返回</param>
Byte Device_GetOneIdentifyData(ref Byte[] pReadData, Byte Antenna, UInt16 Timedout);
/// <summary>
/// 根据天线号识别单个标签EPC数据只返回一条
/// </summary>
/// <returns>识别的标签EPC长度0为识别失败</returns>
/// <param name="pReadData">识别到的数据缓存区</param>
/// <param name="Antenna">天线号0为本机255为所有天线</param>
/// <param name="Timedout">超时时间,单位毫秒,统计时间内读到的次数,返回次数最多的一条</param>
Byte Device_GetOneIdentifyData_Finish(ref Byte[] pReadData, Byte Antenna, UInt16 Timedout);
/// <summary>
/// 根据天线号识别单个标签EPC数据只返回一条
/// </summary>
/// <returns>EPC数据例"4A474730303130323332",为""时失败</returns>
/// <param name="Antenna">天线号0为本机255为所有天线</param>
/// <param name="Timedout">超时时间,单位毫秒,识别到立即返回,未识别到等待超时返回</param>
string Device_GetOneIdentifyData(Byte Antenna, UInt16 Timedout);
/// <summary>
/// 根据天线号识别单个标签EPC数据只返回一条
/// </summary>
/// <returns>EPC数据例"4A474730303130323332",为""时失败</returns>
/// <param name="Antenna">天线号0为本机255为所有天线</param>
/// <param name="Timedout">超时时间,单位毫秒,统计时间内读到的次数,返回次数最多的一条</param>
string Device_GetOneIdentifyData_Finish(Byte Antenna, UInt16 Timedout);
/// <summary>
/// 开始工作,读写器为开始识别,其他设备待定义
/// </summary>
/// <returns>true正常false异常</returns>
/// <param name="AutoReport">是否自动上报1自动0不自动默认0</param>
/// <param name="Filter">过滤规则默认为0无规则, 后续待定</param>
bool Device_BeginIdentify();
/// <summary>
/// 停止识别,读写器为停止识别,其他设备待定义
/// </summary>
/// <returns>true正常false异常</returns>
bool Device_StopIdentify();
/// <summary>
/// 获取工作期间的所有数据
/// </summary>
/// <returns>实际读取到数据的总长度包括每组数据所占的字节0为读取失败</returns>
/// <param name="pReadData">数据存放区,多组数据时格式为:1字节长度+天线号+每组数据...</param>
/// <param name="Antenna">天线号0为本机255为读取所有天线</param>
UInt16 Device_GetIdentifyData(ref Byte[] pReadData, Byte Antenna);
/// <summary>
/// 设置天线收发功率
/// </summary>
/// <returns>true为设置成功false为设置失败</returns>
/// <param name="iDbi">识别到的数据缓存区</param>
/// <param name="Antenna">天线号0为本机255为所有天线</param>
/// <param name="RorW">Write为写Read为读</param>
bool Device_SetRf(int iDbi, Byte Antenna, WriteOrRead RorW);
/// <summary>
/// 发送心跳报文
/// </summary>
/// <returns>1成功2为通讯成功设备未返回3为发送失败</returns>
byte Device_SendHeartPack();
/// <summary>
/// 获取自报数据
/// </summary>
/// <returns>总长度0为失败</returns>
/// <param name="pReadData">获得的自报数据,格式为长度,数据,。。。。。。长度,数据,其中长度占一个字节</param>
UInt16 Device_GetReportData(ref byte[] pReadData, Byte Antenna, UInt32 Timedout);
/// <summary>
/// 四通道读写器按时间段读取数据
/// </summary>
/// <param name="DeviceType"></param>
/// <returns></returns>
List<TagInfo> Device_GetTagInfoList(DeviceType DeviceType,int time);
}
}

@ -0,0 +1,817 @@
using HighWayIot.Common;
using HighWayIot.Log4net;
using HighWayIot.Rfid.Dto;
using HighWayIot.Rfid.Impl;
using MaterialTraceability.Rfid.Impl;
using System;
using System.Collections;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace HighWayIot.Rfid.Impl
{
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
{
private LogHelper log = LogHelper.Instance;
private StringChange stringChange = StringChange.Instance;
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;
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)
{
//LogService.Instance.Debug("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)
{
log.RfidLog(m_FsIP + ":" + m_FnPort + " RFly-I160接收原始报文:" + bytesToHexStr(buff, nCount));
PareReceiveBufferData(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;
}
log.Error("Socket接收数据线程退出",ex);
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)
{
log.RfidLog("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;
log.RfidLog("Socket处理数据线程正常退出");
Exitevent.Reset();
return;
}
}
catch (Exception ex)
{
e.Cancel = true;
log.Error("Socket处理数据异常",ex);
return;
}
if (this.m_bgwDeal.CancellationPending)
{
log.RfidLog("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); //数据域
log.RfidLog(m_FsIP + ":" + m_FnPort + " RFly-I160发送原始报文:" + bytesToHexStr(SendBuffer, pMessagePack.m_pData.Length));
int nCount = m_ClientSock.Send(SendBuffer, pMessagePack.m_pData.Length, SocketFlags.None);
if (nCount > 0) //发送成功
{
//LogInfo.Fatal("m_ClientSock.Send函数发送成功");
return true;
}
else
{
log.RfidLog("连接已断开,数据发送失败");
return false;
}
}
catch (Exception ex)
{
log.Error("发送报文异常", ex);
return false;
}
}
#region 初始化一套函数
public bool Connect()
{
//连接
try
{
Exitevent.Reset();
if (m_FsIP == "" || m_FnPort == 0)
{
log.RfidLog("IP和端口号不能为空连接失败");
return false;
}
if (m_ClientSock != null && GetState())
{
log.RfidLog("已经连接了");
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)
{
//启动接收线程
m_bgwReceive.DoWork += new DoWorkEventHandler(bgwReceive_DoWork);
m_bgwReceive.RunWorkerAsync();
}
else
{
log.RfidLog("接收线程正在运行");
}
//启动处理线程
if (!m_bgwDeal.IsBusy)
{
m_bgwDeal.DoWork += new DoWorkEventHandler(bgwDeal_DoWork);
m_bgwDeal.RunWorkerAsync();
}
else
{
log.RfidLog("处理线程正在运行");
}
return true;
}
catch (Exception ex)
{
log.Error("创建后台线程异常 ",ex);
return true;
}
}
else
{
return false;
}
}
catch (Exception ex)
{
log.Error("Socket连接异常 ",ex);
return false;
}
}
public bool DisConnect()
{
try
{
Exitevent.Set();
Thread.Sleep(100);
m_Fsem.Release();
if (m_ClientSock != null)
{
log.Info("关闭Socket连接 ");
m_ClientSock.Disconnect(false);
m_ClientSock.Close();
m_ClientSock = null;
}
return true;
}
catch (Exception ex)
{
log.Error("Socket连接异常 ",ex);
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)
{
Exitevent.Reset();
m_FsIP = strIp;
m_FnPort = iPort;
m_RFly_I160Adapter = objetcter as RFly_I160Adapter;
}
#endregion
/// <summary>
/// 状态机函数
/// </summary>
/// <param name="buffer"></param>
/// <param name="iLen"></param>
public void PareReceiveData(byte[] buffer, int iLen)
{
//LogService.Instance.Debug("RFly-I160进入状态机");
m_szFullMessage = new byte[iLen];
for (int i = 0; i < iLen; i++)
{
switch (enumRecvState)
{
case RecvState.WaitingBeginChar1_State: //开始接受数据帧1 0xBB
//LogService.Instance.Debug("RFly-I160等待接收帧同步字符WaitingBeginChar1_State:0XBB");
Array.Clear(m_szFullMessage, 0, iLen);//清空为0
if (buffer[i] == 0xBB)
{
//LogService.Instance.Debug("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
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
{
//LogService.Instance.Debug("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
{
//LogService.Instance.Debug("RFly-I160等待接受WaitingForEndChar_State:心跳");
m_szFullMessage[m_iPosition] = buffer[i];
m_iPosition++;
enumRecvState = RecvState.WaitingForEndChar_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];
//LogService.Instance.Debug("RFU620等待接受WaitingForEndChar_State:Noread");
lock (m_FrecvData)
{
m_FrecvData.Add(m_szFullMessage);
}
m_Fsem.Release();
m_iPosition = 0;
i = iLen;
enumRecvState = RecvState.WaitingBeginChar1_State;
//LogService.Instance.Debug("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);
//LogService.Instance.Debug("解析的数据为: " + 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;
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 && buffer[3] != 0x90) //此处为Noread数据显示
{
//LogService.Instance.Debug("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[i] == 0x00) //获取温度
{
//m_szFullMessage[3] = 0x90;
//m_iPosition++;
Array.Copy(buffer, 0, m_szFullMessage, 0, 8);
i = 8;
lock (m_FrecvData)
{
m_FrecvData.Add(m_szFullMessage);
}
m_Fsem.Release();
//add by wenjy 2022-09-03
//m_iPosition = 0;
//i = iLen;
//enumRecvState = RecvState.WaitingBeginChar1_State;
}
else if (buffer[i] == 0x11)
{
//m_szFullMessage[3] = 0x00;
Array.Copy(buffer, 0, m_szFullMessage, 0, 7);
i = 7;
lock (m_FrecvData)
{
m_FrecvData.Add(m_szFullMessage);
}
m_Fsem.Release();
}
else if (buffer[i] == 0x01)
{
//m_szFullMessage[3] = 0x00;
Array.Copy(buffer, 0, m_szFullMessage, 0, 8);
i = 8;
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)
{
//LogService.Instance.Debug("RFly-I160准备发送");
lock (m_FrecvData)
{
m_FrecvData.Add(m_szFullMessage);
}
m_Fsem.Release();
}
}
m_iPosition = 0;
enumRecvState = RecvState.WaitingBeginChar1_State;
//LogService.Instance.Debug("RFly-I160状态机结束。");
break;
}
}
}
/// <summary>
/// 状态机函数 Add By WenJy 2022-09-26
/// </summary>
/// <param name="buffer"></param>
/// <param name="iLen"></param>
public void PareReceiveBufferData(byte[] buffer, int iLen)
{
var bufferStr = stringChange.bytesToHexStr(buffer, iLen);
log.RfidLog(String.Format("进入状态机函数:{0}", bufferStr));
m_szFullMessage = new byte[iLen];
for (int i = 0; i < iLen; i++)
{
switch (enumRecvState)
{
case RecvState.WaitingBeginChar1_State: //开始接受数据帧1 0xBB
Array.Clear(m_szFullMessage, 0, iLen);//清空为0
if (buffer[i] == 0xBB)
{
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
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
{
//LogService.Instance.Debug("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
{
//LogService.Instance.Debug("RFly-I160等待接受WaitingForEndChar_State:心跳");
m_szFullMessage[m_iPosition] = buffer[i];
m_iPosition++;
enumRecvState = RecvState.WaitingForEndChar_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];
//LogService.Instance.Debug("RFU620等待接受WaitingForEndChar_State:Noread");
lock (m_FrecvData)
{
m_FrecvData.Add(m_szFullMessage);
}
m_Fsem.Release();
m_iPosition = 0;
i = iLen;
enumRecvState = RecvState.WaitingBeginChar1_State;
//LogService.Instance.Debug("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_iPosition = m_iPosition + iBarcodeLength; //m_iPosition = 39
i = i + iBarcodeLength - 1; //i = 39
enumRecvState = RecvState.WaitingForXor_State;
break;
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 && buffer[3] != 0x90) //此处为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[0] == 0xBB && buffer[1] == 0xDD && buffer[2] == 0x04 && buffer[3] == 0xBF)
{
Array.Copy(buffer, 0, m_szFullMessage, 0, 11);
i = 11;
lock (m_FrecvData)
{
m_FrecvData.Add(m_szFullMessage);
}
m_Fsem.Release();
i = iLen;
}
else if (buffer[i] == 0x00) //获取温度
{
Array.Copy(buffer, 0, m_szFullMessage, 0, 8);
i = 8;
lock (m_FrecvData)
{
m_FrecvData.Add(m_szFullMessage);
}
m_Fsem.Release();
i = iLen;
}
else if (buffer[i] == 0x11)
{
Array.Copy(buffer, 0, m_szFullMessage, 0, 7);
i = 7;
lock (m_FrecvData)
{
m_FrecvData.Add(m_szFullMessage);
}
m_Fsem.Release();
}
else if (buffer[i] == 0x01)
{
Array.Copy(buffer, 0, m_szFullMessage, 0, 8);
i = 8;
lock (m_FrecvData)
{
m_FrecvData.Add(m_szFullMessage);
}
m_Fsem.Release();
}
else
{
m_szFullMessage[m_iPosition] = buffer[i];
m_iPosition++;
if (buffer[i] == 0x0D)
{
lock (m_FrecvData)
{
m_FrecvData.Add(m_szFullMessage);
}
m_Fsem.Release();
}
}
m_iPosition = 0;
enumRecvState = RecvState.WaitingBeginChar1_State;
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;
}
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("HighWayIot.Rfid")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HighWayIot.Rfid")]
[assembly: AssemblyCopyright("Copyright © 2023")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("29813574-49c0-4979-a5a6-47eb7c4288a0")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -0,0 +1,65 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" 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>{DD18A634-1F9C-409A-8C32-C3C81B1B55B5}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>HighWayIot.TouchSocket</RootNamespace>
<AssemblyName>HighWayIot.TouchSocket</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<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>
</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>
</PropertyGroup>
<ItemGroup>
<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="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
<Reference Include="TouchSocket, Version=2.0.0.0, Culture=neutral, PublicKeyToken=5f39d7da98dac6a9, processorArchitecture=MSIL">
<HintPath>..\packages\TouchSocket.2.0.0-beta.253\lib\net45\TouchSocket.dll</HintPath>
</Reference>
<Reference Include="TouchSocket.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=d6c415a2f58eda72, processorArchitecture=MSIL">
<HintPath>..\packages\TouchSocket.Core.2.0.0-beta.253\lib\net45\TouchSocket.Core.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="SocketConnect.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Analyzer Include="..\packages\TouchSocket.Core.2.0.0-beta.253\analyzers\dotnet\cs\TouchSocket.Core.SourceGenerator.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

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

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Sockets;
namespace HighWayIot.TouchSocket
{
public class SocketConnect
{
public void SocketMonitor()
{
var service = new TcpService();
service.Connecting = (client, e) => { return EasyTask.CompletedTask; };//有客户端正在连接
service.Connected = (client, e) => { return EasyTask.CompletedTask; };//有客户端成功连接
service.Disconnecting = (client, e) => { return EasyTask.CompletedTask; };//有客户端正在断开连接,只有当主动断开时才有效。
service.Disconnected = (client, e) => { return EasyTask.CompletedTask; };//有客户端断开连接
service.Received = (client, e) =>
{
//从客户端收到信息
var mes = Encoding.UTF8.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);//注意数据长度是byteBlock.Len
client.Logger.Info($"已从{client.Id}接收到信息:{mes}");
return EasyTask.CompletedTask;
};
service.Setup(new TouchSocketConfig()//载入配置
.SetListenIPHosts("192.168.11.211:6501", "192.168.11.212:6502", "192.168.11.213:6503", "192.168.11.214:6504")//同时监听两个地址
.ConfigureContainer(a =>//容器的配置顺序应该在最前面
{
a.AddConsoleLogger();//添加一个控制台日志注入注意在maui中控制台日志不可用
})
.ConfigurePlugins(a =>
{
//a.Add();//此处可以添加插件
}));
service.Start();//启动
}
}
}

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="13.0.3" targetFramework="net48" />
<package id="TouchSocket" version="2.0.0-beta.253" targetFramework="net48" />
<package id="TouchSocket.Core" version="2.0.0-beta.253" targetFramework="net48" />
</packages>

@ -0,0 +1,73 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.6.33723.286
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HighWayIot", "HighWayIot\HighWayIot.csproj", "{DFFFA7B9-62AF-4E3F-B802-A68B135490CA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HighWayIot.Log4net", "HighWayIot.Log4net\HighWayIot.Log4net.csproj", "{DEABC30C-EC6F-472E-BD67-D65702FDAF74}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HighWayIot.Common", "HighWayIot.Common\HighWayIot.Common.csproj", "{89A1EDD9-D79E-468D-B6D3-7D07B8843562}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HighWayIot.Repository", "HighWayIot.Repository\HighWayIot.Repository.csproj", "{D0DC3CFB-6748-4D5E-B56A-76FDC72AB4B3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HighWayIot.Plc", "HighWayIot.Plc\HighWayIot.Plc.csproj", "{4EE4C3E2-AC45-4275-8017-E99D70FC1F52}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HighWayIot.Rfid", "HighWayIot.Rfid\HighWayIot.Rfid.csproj", "{29813574-49C0-4979-A5A6-47EB7C4288A0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HighWayIot.TouchSocket", "HighWayIot.TouchSocket\HighWayIot.TouchSocket.csproj", "{DD18A634-1F9C-409A-8C32-C3C81B1B55B5}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HighWayIot.Mqtt", "HighWayIot.Mqtt\HighWayIot.Mqtt.csproj", "{CD9B8712-0E09-42D2-849B-B8EAB02C7AB8}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RFIDSocket", "RFIDSocket\RFIDSocket.csproj", "{B632CAA9-47D5-47DC-A49F-2106166096BA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{DFFFA7B9-62AF-4E3F-B802-A68B135490CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DFFFA7B9-62AF-4E3F-B802-A68B135490CA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DFFFA7B9-62AF-4E3F-B802-A68B135490CA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DFFFA7B9-62AF-4E3F-B802-A68B135490CA}.Release|Any CPU.Build.0 = Release|Any CPU
{DEABC30C-EC6F-472E-BD67-D65702FDAF74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DEABC30C-EC6F-472E-BD67-D65702FDAF74}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DEABC30C-EC6F-472E-BD67-D65702FDAF74}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DEABC30C-EC6F-472E-BD67-D65702FDAF74}.Release|Any CPU.Build.0 = Release|Any CPU
{89A1EDD9-D79E-468D-B6D3-7D07B8843562}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{89A1EDD9-D79E-468D-B6D3-7D07B8843562}.Debug|Any CPU.Build.0 = Debug|Any CPU
{89A1EDD9-D79E-468D-B6D3-7D07B8843562}.Release|Any CPU.ActiveCfg = Release|Any CPU
{89A1EDD9-D79E-468D-B6D3-7D07B8843562}.Release|Any CPU.Build.0 = Release|Any CPU
{D0DC3CFB-6748-4D5E-B56A-76FDC72AB4B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D0DC3CFB-6748-4D5E-B56A-76FDC72AB4B3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D0DC3CFB-6748-4D5E-B56A-76FDC72AB4B3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D0DC3CFB-6748-4D5E-B56A-76FDC72AB4B3}.Release|Any CPU.Build.0 = Release|Any CPU
{4EE4C3E2-AC45-4275-8017-E99D70FC1F52}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4EE4C3E2-AC45-4275-8017-E99D70FC1F52}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4EE4C3E2-AC45-4275-8017-E99D70FC1F52}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4EE4C3E2-AC45-4275-8017-E99D70FC1F52}.Release|Any CPU.Build.0 = Release|Any CPU
{29813574-49C0-4979-A5A6-47EB7C4288A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{29813574-49C0-4979-A5A6-47EB7C4288A0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{29813574-49C0-4979-A5A6-47EB7C4288A0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{29813574-49C0-4979-A5A6-47EB7C4288A0}.Release|Any CPU.Build.0 = Release|Any CPU
{DD18A634-1F9C-409A-8C32-C3C81B1B55B5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DD18A634-1F9C-409A-8C32-C3C81B1B55B5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DD18A634-1F9C-409A-8C32-C3C81B1B55B5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DD18A634-1F9C-409A-8C32-C3C81B1B55B5}.Release|Any CPU.Build.0 = Release|Any CPU
{CD9B8712-0E09-42D2-849B-B8EAB02C7AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CD9B8712-0E09-42D2-849B-B8EAB02C7AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CD9B8712-0E09-42D2-849B-B8EAB02C7AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CD9B8712-0E09-42D2-849B-B8EAB02C7AB8}.Release|Any CPU.Build.0 = Release|Any CPU
{B632CAA9-47D5-47DC-A49F-2106166096BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B632CAA9-47D5-47DC-A49F-2106166096BA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B632CAA9-47D5-47DC-A49F-2106166096BA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B632CAA9-47D5-47DC-A49F-2106166096BA}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {7AD8B4D0-04C9-45D5-A242-7AD45121F5DF}
EndGlobalSection
EndGlobal

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="MySql.Data" publicKeyToken="c5687fc88969c44d" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-8.1.0.0" newVersion="8.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Data.SQLite" publicKeyToken="db937bc2d44ff139" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.0.116.0" newVersion="1.0.116.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>
</assemblyBinding>
</runtime>
</configuration>

@ -0,0 +1,76 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" 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>{DFFFA7B9-62AF-4E3F-B802-A68B135490CA}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>HighWayIot</RootNamespace>
<AssemblyName>HighWayIot</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</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="MySql.Data, Version=8.0.16.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>Z:\Desktop\日常代码\HighWayIot\HighWayIot.Library\MySql.Data.dll</HintPath>
</Reference>
<Reference Include="Oracle.ManagedDataAccess">
<HintPath>..\HighWayIot.Library\Oracle.ManagedDataAccess.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data.SQLite">
<HintPath>Z:\Desktop\日常代码\HighWayIot\HighWayIot.Library\System.Data.SQLite.dll</HintPath>
</Reference>
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\HighWayIot.Log4net\HighWayIot.Log4net.csproj">
<Project>{DEABC30C-EC6F-472E-BD67-D65702FDAF74}</Project>
<Name>HighWayIot.Log4net</Name>
</ProjectReference>
<ProjectReference Include="..\HighWayIot.Repository\HighWayIot.Repository.csproj">
<Project>{d0dc3cfb-6748-4d5e-b56a-76fdc72ab4b3}</Project>
<Name>HighWayIot.Repository</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

@ -0,0 +1,34 @@
using HighWayIot.Log4net;
using HighWayIot.Repository.service;
using HighWayIot.Repository.service.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HighWayIot
{
internal class Program
{
private static LogHelper logger = LogHelper.Instance;
//private static IBaseDeviceinfoService sqliteTest = new BaseDeviceinfoServiceImpl();
//private static ISysUserInfoService mysqlTest = new BaseSysUserInfoServiceImpl();
//private static IBaseBomInfoService oracleTest = new BaseBomInfoServiceImpl();
static void Main(string[] args)
{
logger.Info("初始化启动");
//var info = sqliteTest.GetDeviceInfoListByProcessId(3);
//var info2 = mysqlTest.GetUserInfos();
//var info3 = oracleTest.GetBomInfos();
}
}
}

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

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

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RFIDSocket
{
internal static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new RFIDSocket());
}
}
}

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

@ -0,0 +1,71 @@
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本: 4.0.30319.42000
//
// 对此文件的更改可能导致不正确的行为,如果
// 重新生成代码,则所做更改将丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace RFIDSocket.Properties
{
/// <summary>
/// 强类型资源类,用于查找本地化字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// 返回此类使用的缓存 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("RFIDSocket.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 重写当前线程的 CurrentUICulture 属性,对
/// 使用此强类型资源类的所有资源查找执行重写。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

@ -0,0 +1,30 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace RFIDSocket.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

@ -0,0 +1,47 @@
namespace RFIDSocket
{
partial class RFIDSocket
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// RFIDSocket
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1643, 1064);
this.Name = "RFIDSocket";
this.Text = "小件日志";
this.ResumeLayout(false);
}
#endregion
}
}

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RFIDSocket
{
public partial class RFIDSocket : Form
{
public RFIDSocket()
{
InitializeComponent();
}
}
}

@ -0,0 +1,83 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" 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>{B632CAA9-47D5-47DC-A49F-2106166096BA}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>RFIDSocket</RootNamespace>
<AssemblyName>RFIDSocket</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</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="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="RFIDSocket.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="RFIDSocket.Designer.cs">
<DependentUpon>RFIDSocket.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<EmbeddedResource Include="RFIDSocket.resx">
<DependentUpon>RFIDSocket.cs</DependentUpon>
</EmbeddedResource>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
Loading…
Cancel
Save