change - 更改gitignore

master
SoulStar 1 year ago
parent b799d24606
commit 0050dadc66

@ -1,65 +1,65 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <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')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{89A1EDD9-D79E-468D-B6D3-7D07B8843562}</ProjectGuid> <ProjectGuid>{89A1EDD9-D79E-468D-B6D3-7D07B8843562}</ProjectGuid>
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>HighWayIot.Common</RootNamespace> <RootNamespace>HighWayIot.Common</RootNamespace>
<AssemblyName>HighWayIot.Common</AssemblyName> <AssemblyName>HighWayIot.Common</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion> <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic> <Deterministic>true</Deterministic>
<TargetFrameworkProfile /> <TargetFrameworkProfile />
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath> <OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
<Optimize>true</Optimize> <Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath> <OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL"> <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> <HintPath>..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference> </Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Drawing" /> <Reference Include="System.Drawing" />
<Reference Include="System.Web.Extensions" /> <Reference Include="System.Web.Extensions" />
<Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" /> <Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" /> <Reference Include="System.Data" />
<Reference Include="System.Net.Http" /> <Reference Include="System.Net.Http" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="JsonChange.cs" /> <Compile Include="JsonChange.cs" />
<Compile Include="MsgUtil.cs" /> <Compile Include="MsgUtil.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="StringChange.cs" /> <Compile Include="StringChange.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\HighWayIot.Log4net\HighWayIot.Log4net.csproj"> <ProjectReference Include="..\HighWayIot.Log4net\HighWayIot.Log4net.csproj">
<Project>{deabc30c-ec6f-472e-bd67-d65702fdaf74}</Project> <Project>{deabc30c-ec6f-472e-bd67-d65702fdaf74}</Project>
<Name>HighWayIot.Log4net</Name> <Name>HighWayIot.Log4net</Name>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="packages.config" /> <None Include="packages.config" />
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project> </Project>

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

File diff suppressed because it is too large Load Diff

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

@ -1,216 +1,216 @@
using HighWayIot.Log4net; using HighWayIot.Log4net;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace HighWayIot.Common namespace HighWayIot.Common
{ {
public class StringChange public class StringChange
{ {
private static readonly Lazy<StringChange> lazy = new Lazy<StringChange>(() => new StringChange()); private static readonly Lazy<StringChange> lazy = new Lazy<StringChange>(() => new StringChange());
public static StringChange Instance public static StringChange Instance
{ {
get get
{ {
return lazy.Value; return lazy.Value;
} }
} }
private StringChange() { } private StringChange() { }
/// <summary> /// <summary>
/// 将字符串强制转换成int转换失败则返回0 /// 将字符串强制转换成int转换失败则返回0
/// </summary> /// </summary>
/// <param name="str"></param> /// <param name="str"></param>
/// <returns></returns> /// <returns></returns>
public int ParseToInt(string str) public int ParseToInt(string str)
{ {
int returnInt = 0; int returnInt = 0;
if (str == null || str.Trim().Length < 1) if (str == null || str.Trim().Length < 1)
{ {
return returnInt; return returnInt;
} }
if (int.TryParse(str, out returnInt)) if (int.TryParse(str, out returnInt))
{ {
return returnInt; return returnInt;
} }
else else
{ {
return 0; return 0;
} }
} }
/// <summary> /// <summary>
/// char数组转Array /// char数组转Array
/// </summary> /// </summary>
/// <param name="cha"></param> /// <param name="cha"></param>
/// <param name="len"></param> /// <param name="len"></param>
/// <returns></returns> /// <returns></returns>
public string CharArrayToString(char[] cha, int len) public string CharArrayToString(char[] cha, int len)
{ {
string str = ""; string str = "";
for (int i = 0; i < len; i++) for (int i = 0; i < len; i++)
{ {
str += string.Format("{0}", cha[i]); str += string.Format("{0}", cha[i]);
} }
return str; return str;
} }
public string bytesToHexStr(byte[] bytes, int iLen)//e.g. { 0x01, 0x01} ---> " 01 01" public string bytesToHexStr(byte[] bytes, int iLen)//e.g. { 0x01, 0x01} ---> " 01 01"
{ {
string returnStr = ""; string returnStr = "";
if (bytes != null) if (bytes != null)
{ {
for (int i = 0; i < iLen; i++) for (int i = 0; i < iLen; i++)
{ {
returnStr += bytes[i].ToString("X2"); returnStr += bytes[i].ToString("X2");
} }
} }
return returnStr; return returnStr;
} }
public byte[] HexStrTorbytes(string strHex)//e.g. " 01 01" ---> { 0x01, 0x01} public byte[] HexStrTorbytes(string strHex)//e.g. " 01 01" ---> { 0x01, 0x01}
{ {
strHex = strHex.Replace(" ", ""); strHex = strHex.Replace(" ", "");
if ((strHex.Length % 2) != 0) if ((strHex.Length % 2) != 0)
strHex += " "; strHex += " ";
byte[] returnBytes = new byte[strHex.Length / 2]; byte[] returnBytes = new byte[strHex.Length / 2];
for (int i = 0; i < returnBytes.Length; i++) for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(strHex.Substring(i * 2, 2), 16); returnBytes[i] = Convert.ToByte(strHex.Substring(i * 2, 2), 16);
return returnBytes; return returnBytes;
} }
public string StringToHexString(string s, Encoding encode) public string StringToHexString(string s, Encoding encode)
{ {
byte[] b = encode.GetBytes(s); //按照指定编码将string编程字节数组 byte[] b = encode.GetBytes(s); //按照指定编码将string编程字节数组
string result = string.Empty; string result = string.Empty;
for (int i = 0; i < b.Length; i++) //逐字节变为16进制字符以%隔开 for (int i = 0; i < b.Length; i++) //逐字节变为16进制字符以%隔开
{ {
result += "%" + Convert.ToString(b[i], 16); result += "%" + Convert.ToString(b[i], 16);
} }
return result; return result;
} }
public string HexStringToString(string hs, Encoding encode) public string HexStringToString(string hs, Encoding encode)
{ {
//以%分割字符串,并去掉空字符 //以%分割字符串,并去掉空字符
string[] chars = hs.Split(new char[] { '%' }, StringSplitOptions.RemoveEmptyEntries); string[] chars = hs.Split(new char[] { '%' }, StringSplitOptions.RemoveEmptyEntries);
byte[] b = new byte[chars.Length]; byte[] b = new byte[chars.Length];
//逐个字符变为16进制字节数据 //逐个字符变为16进制字节数据
for (int i = 0; i < chars.Length; i++) for (int i = 0; i < chars.Length; i++)
{ {
b[i] = Convert.ToByte(chars[i], 16); b[i] = Convert.ToByte(chars[i], 16);
} }
//按照指定编码将字节数组变为字符串 //按照指定编码将字节数组变为字符串
return encode.GetString(b); return encode.GetString(b);
} }
public byte[] Swap16Bytes(byte[] OldU16) public byte[] Swap16Bytes(byte[] OldU16)
{ {
byte[] ReturnBytes = new byte[2]; byte[] ReturnBytes = new byte[2];
ReturnBytes[1] = OldU16[0]; ReturnBytes[1] = OldU16[0];
ReturnBytes[0] = OldU16[1]; ReturnBytes[0] = OldU16[1];
return ReturnBytes; return ReturnBytes;
} }
/// <param name="strbase64">64Base码</param> /// <param name="strbase64">64Base码</param>
/// <param name="path">保存路径</param> /// <param name="path">保存路径</param>
/// <param name="filename">文件名称</param> /// <param name="filename">文件名称</param>
/// <returns></returns> /// <returns></returns>
public bool Base64ToImage(string strbase64, string path, string filename) public bool Base64ToImage(string strbase64, string path, string filename)
{ {
bool Flag = false; bool Flag = false;
try try
{ {
//base64编码的文本 转为 图片 //base64编码的文本 转为 图片
//图片名称 //图片名称
byte[] arr = Convert.FromBase64String(strbase64);//将指定的字符串(它将二进制数据编码为 Base64 数字)转换为等效的 8 位无符号整数数组。 byte[] arr = Convert.FromBase64String(strbase64);//将指定的字符串(它将二进制数据编码为 Base64 数字)转换为等效的 8 位无符号整数数组。
using (MemoryStream ms = new MemoryStream(arr)) using (MemoryStream ms = new MemoryStream(arr))
{ {
Bitmap bmp = new Bitmap(ms);//加载图像 Bitmap bmp = new Bitmap(ms);//加载图像
if (!Directory.Exists(path))//判断保存目录是否存在 if (!Directory.Exists(path))//判断保存目录是否存在
{ {
Directory.CreateDirectory(path); Directory.CreateDirectory(path);
} }
bmp.Save((path + "\\" + filename + ".png"),System.Drawing.Imaging.ImageFormat.Png);//将图片以JPEG格式保存在指定目录(可以选择其他图片格式) bmp.Save((path + "\\" + filename + ".png"),System.Drawing.Imaging.ImageFormat.Png);//将图片以JPEG格式保存在指定目录(可以选择其他图片格式)
ms.Close();//关闭流并释放 ms.Close();//关闭流并释放
if (File.Exists(path + "\\" + filename + ".png"))//判断是否存在 if (File.Exists(path + "\\" + filename + ".png"))//判断是否存在
{ {
Flag = true; Flag = true;
} }
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine("图片保存失败:" + ex.Message); Console.WriteLine("图片保存失败:" + ex.Message);
} }
return Flag; return Flag;
} }
/// <summary> /// <summary>
/// 获取时间戳 /// 获取时间戳
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public long GetTimeStamp() public long GetTimeStamp()
{ {
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds); return Convert.ToInt64(ts.TotalSeconds);
} }
public byte[] ConvertFloatToINt(byte[] floatBytes) public byte[] ConvertFloatToINt(byte[] floatBytes)
{ {
byte[] intBytes = new byte[floatBytes.Length / 2]; byte[] intBytes = new byte[floatBytes.Length / 2];
for (int i = 0; i < intBytes.Length; i++) for (int i = 0; i < intBytes.Length; i++)
{ {
intBytes[i] = floatBytes[i * 2 + 1]; intBytes[i] = floatBytes[i * 2 + 1];
} }
return intBytes; return intBytes;
} }
//CRC异或校验 //CRC异或校验
public byte CalculateVerify(byte[] pMessage, int iLength) public byte CalculateVerify(byte[] pMessage, int iLength)
{ {
UInt16 i; UInt16 i;
byte iVerify = 0; byte iVerify = 0;
iVerify = pMessage[0]; iVerify = pMessage[0];
for (i = 1; i < iLength; i++) for (i = 1; i < iLength; i++)
{ {
iVerify = (byte)(iVerify ^ pMessage[i]); iVerify = (byte)(iVerify ^ pMessage[i]);
} }
return iVerify; return iVerify;
} }
public int HexStringToNegative(string strNumber) public int HexStringToNegative(string strNumber)
{ {
int iNegate = 0; int iNegate = 0;
int iNumber = Convert.ToInt32(strNumber, 16); int iNumber = Convert.ToInt32(strNumber, 16);
if (iNumber > 127) if (iNumber > 127)
{ {
int iComplement = iNumber - 1; int iComplement = iNumber - 1;
string strNegate = string.Empty; string strNegate = string.Empty;
char[] binchar = Convert.ToString(iComplement, 2).PadLeft(8, '0').ToArray(); char[] binchar = Convert.ToString(iComplement, 2).PadLeft(8, '0').ToArray();
foreach (char ch in binchar) foreach (char ch in binchar)
{ {
if (Convert.ToInt32(ch) == 48) if (Convert.ToInt32(ch) == 48)
{ {
strNegate += "1"; strNegate += "1";
} }
else else
{ {
strNegate += "0"; strNegate += "0";
} }
} }
iNegate = -Convert.ToInt32(strNegate, 2); iNegate = -Convert.ToInt32(strNegate, 2);
} }
return iNegate; return iNegate;
} }
} }
} }

File diff suppressed because it is too large Load Diff

@ -1,167 +0,0 @@
<?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" />
<appender-ref ref="ConsoleAppender" />
</logger>
<!--信息日志类-->
<logger name="loginfo">
<level value="ALL" />
<appender-ref ref="InfoAppender" />
<appender-ref ref="ConsoleAppender" />
</logger>
<!--PLC日志类-->
<logger name="plclog">
<level value="ALL" />
<appender-ref ref="PlcAppender" />
<appender-ref ref="ConsoleAppender" />
</logger>
<!--RFID日志类-->
<logger name="rfidlog">
<level value="ALL" />
<appender-ref ref="RfidAppender" />
<appender-ref ref="ConsoleAppender" />
</logger>
<!--RFID日志类-->
<logger name="viewlog">
<level value="ALL" />
<appender-ref ref="ViewAppender" />
<appender-ref ref="ConsoleAppender" />
</logger>
<!--Sql日志类-->
<logger name="sqllog">
<level value="ALL" />
<appender-ref ref="SqlAppender" />
<appender-ref ref="ConsoleAppender" />
</logger>
<!--信号量日志类-->
<logger name="semaphorelog">
<level value="ALL" />
<appender-ref ref="SemaphoreAppender" />
<appender-ref ref="ConsoleAppender" />
</logger>
<!-- 将日志输出到控制台 -->
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<!--错误日志附加介质-->
<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>

@ -1,4 +0,0 @@
// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.5.2", FrameworkDisplayName = ".NET Framework 4.5.2")]

@ -1,4 +0,0 @@
// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]

@ -1 +0,0 @@
806fb4fa591413bf7ca81c0fc70c231330502c03d4a20f497ac93a4e58f1ab11

@ -1,49 +0,0 @@
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Common\obj\Debug\HighWayIot.Common.csproj.AssemblyReference.cache
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Common\obj\Debug\HighWayIot.Common.csproj.CoreCompileInputs.cache
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Common\bin\Debug\HighWayIot.Common.dll
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Common\bin\Debug\HighWayIot.Common.pdb
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Common\bin\Debug\HighWayIot.Log4net.dll
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Common\bin\Debug\Newtonsoft.Json.dll
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Common\bin\Debug\log4net.dll
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Common\bin\Debug\HighWayIot.Log4net.pdb
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Common\bin\Debug\Newtonsoft.Json.xml
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Common\obj\Debug\HighWayIot.Common.csproj.CopyComplete
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Common\obj\Debug\HighWayIot.Common.dll
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Common\obj\Debug\HighWayIot.Common.pdb
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Common\bin\Debug\HighWayIot.Common.dll
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Common\bin\Debug\HighWayIot.Common.pdb
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Common\bin\Debug\HighWayIot.Log4net.dll
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Common\bin\Debug\Newtonsoft.Json.dll
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Common\bin\Debug\log4net.dll
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Common\bin\Debug\HighWayIot.Log4net.pdb
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Common\bin\Debug\Newtonsoft.Json.xml
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Common\obj\Debug\HighWayIot.Common.csproj.AssemblyReference.cache
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Common\obj\Debug\HighWayIot.Common.csproj.CoreCompileInputs.cache
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Common\obj\Debug\HighWayIot.Common.csproj.CopyComplete
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Common\obj\Debug\HighWayIot.Common.dll
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Common\obj\Debug\HighWayIot.Common.pdb
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Common\bin\Debug\HighWayIot.Common.dll
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Common\bin\Debug\HighWayIot.Common.pdb
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Common\bin\Debug\HighWayIot.Log4net.dll
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Common\bin\Debug\Newtonsoft.Json.dll
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Common\bin\Debug\log4net.dll
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Common\bin\Debug\HighWayIot.Log4net.pdb
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Common\bin\Debug\Newtonsoft.Json.xml
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Common\obj\Debug\HighWayIot.Common.csproj.AssemblyReference.cache
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Common\obj\Debug\HighWayIot.Common.csproj.CoreCompileInputs.cache
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Common\obj\Debug\HighWayIot.Common.csproj.CopyComplete
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Common\obj\Debug\HighWayIot.Common.dll
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Common\obj\Debug\HighWayIot.Common.pdb
D:\WorkCode\DLML-SCADA\HighWayIot.Common\bin\Debug\config\log4net.config
D:\WorkCode\DLML-SCADA\HighWayIot.Common\bin\Debug\HighWayIot.Common.dll
D:\WorkCode\DLML-SCADA\HighWayIot.Common\bin\Debug\HighWayIot.Common.pdb
D:\WorkCode\DLML-SCADA\HighWayIot.Common\bin\Debug\HighWayIot.Log4net.dll
D:\WorkCode\DLML-SCADA\HighWayIot.Common\bin\Debug\Newtonsoft.Json.dll
D:\WorkCode\DLML-SCADA\HighWayIot.Common\bin\Debug\log4net.dll
D:\WorkCode\DLML-SCADA\HighWayIot.Common\bin\Debug\HighWayIot.Log4net.pdb
D:\WorkCode\DLML-SCADA\HighWayIot.Common\bin\Debug\Newtonsoft.Json.xml
D:\WorkCode\DLML-SCADA\HighWayIot.Common\obj\Debug\HighWayIot.Common.csproj.AssemblyReference.cache
D:\WorkCode\DLML-SCADA\HighWayIot.Common\obj\Debug\HighWayIot.Common.csproj.CoreCompileInputs.cache
D:\WorkCode\DLML-SCADA\HighWayIot.Common\obj\Debug\HighWayI.6D993C3E.Up2Date
D:\WorkCode\DLML-SCADA\HighWayIot.Common\obj\Debug\HighWayIot.Common.dll
D:\WorkCode\DLML-SCADA\HighWayIot.Common\obj\Debug\HighWayIot.Common.pdb

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

@ -1,57 +1,57 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <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')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{DEABC30C-EC6F-472E-BD67-D65702FDAF74}</ProjectGuid> <ProjectGuid>{DEABC30C-EC6F-472E-BD67-D65702FDAF74}</ProjectGuid>
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>HighWayIot.Log4net</RootNamespace> <RootNamespace>HighWayIot.Log4net</RootNamespace>
<AssemblyName>HighWayIot.Log4net</AssemblyName> <AssemblyName>HighWayIot.Log4net</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion> <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic> <Deterministic>true</Deterministic>
<TargetFrameworkProfile /> <TargetFrameworkProfile />
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath> <OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
<Optimize>true</Optimize> <Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath> <OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="log4net"> <Reference Include="log4net">
<HintPath>..\HighWayIot.Library\log4net.dll</HintPath> <HintPath>..\HighWayIot.Library\log4net.dll</HintPath>
</Reference> </Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" /> <Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" /> <Reference Include="System.Data" />
<Reference Include="System.Net.Http" /> <Reference Include="System.Net.Http" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="LogHelper.cs" /> <Compile Include="LogHelper.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="config\log4net.config"> <None Include="config\log4net.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None> </None>
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project> </Project>

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

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

@ -1,167 +0,0 @@
<?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" />
<appender-ref ref="ConsoleAppender" />
</logger>
<!--信息日志类-->
<logger name="loginfo">
<level value="ALL" />
<appender-ref ref="InfoAppender" />
<appender-ref ref="ConsoleAppender" />
</logger>
<!--PLC日志类-->
<logger name="plclog">
<level value="ALL" />
<appender-ref ref="PlcAppender" />
<appender-ref ref="ConsoleAppender" />
</logger>
<!--RFID日志类-->
<logger name="rfidlog">
<level value="ALL" />
<appender-ref ref="RfidAppender" />
<appender-ref ref="ConsoleAppender" />
</logger>
<!--RFID日志类-->
<logger name="viewlog">
<level value="ALL" />
<appender-ref ref="ViewAppender" />
<appender-ref ref="ConsoleAppender" />
</logger>
<!--Sql日志类-->
<logger name="sqllog">
<level value="ALL" />
<appender-ref ref="SqlAppender" />
<appender-ref ref="ConsoleAppender" />
</logger>
<!--信号量日志类-->
<logger name="semaphorelog">
<level value="ALL" />
<appender-ref ref="SemaphoreAppender" />
<appender-ref ref="ConsoleAppender" />
</logger>
<!-- 将日志输出到控制台 -->
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<!--错误日志附加介质-->
<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>

@ -1,167 +1,167 @@
<?xml version="1.0" encoding="utf-8" ?> <?xml version="1.0" encoding="utf-8" ?>
<configuration> <configuration>
<configSections> <configSections>
<section name="log4net" type="System.Configuration.IgnoreSectionHandler"/> <section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
</configSections> </configSections>
<appSettings> <appSettings>
</appSettings> </appSettings>
<log4net> <log4net>
<!--错误日志类--> <!--错误日志类-->
<logger name="logerror"> <logger name="logerror">
<level value="ALL" /> <level value="ALL" />
<appender-ref ref="ErrorAppender" /> <appender-ref ref="ErrorAppender" />
<appender-ref ref="ConsoleAppender" /> <appender-ref ref="ConsoleAppender" />
</logger> </logger>
<!--信息日志类--> <!--信息日志类-->
<logger name="loginfo"> <logger name="loginfo">
<level value="ALL" /> <level value="ALL" />
<appender-ref ref="InfoAppender" /> <appender-ref ref="InfoAppender" />
<appender-ref ref="ConsoleAppender" /> <appender-ref ref="ConsoleAppender" />
</logger> </logger>
<!--PLC日志类--> <!--PLC日志类-->
<logger name="plclog"> <logger name="plclog">
<level value="ALL" /> <level value="ALL" />
<appender-ref ref="PlcAppender" /> <appender-ref ref="PlcAppender" />
<appender-ref ref="ConsoleAppender" /> <appender-ref ref="ConsoleAppender" />
</logger> </logger>
<!--RFID日志类--> <!--RFID日志类-->
<logger name="rfidlog"> <logger name="rfidlog">
<level value="ALL" /> <level value="ALL" />
<appender-ref ref="RfidAppender" /> <appender-ref ref="RfidAppender" />
<appender-ref ref="ConsoleAppender" /> <appender-ref ref="ConsoleAppender" />
</logger> </logger>
<!--RFID日志类--> <!--RFID日志类-->
<logger name="viewlog"> <logger name="viewlog">
<level value="ALL" /> <level value="ALL" />
<appender-ref ref="ViewAppender" /> <appender-ref ref="ViewAppender" />
<appender-ref ref="ConsoleAppender" /> <appender-ref ref="ConsoleAppender" />
</logger> </logger>
<!--Sql日志类--> <!--Sql日志类-->
<logger name="sqllog"> <logger name="sqllog">
<level value="ALL" /> <level value="ALL" />
<appender-ref ref="SqlAppender" /> <appender-ref ref="SqlAppender" />
<appender-ref ref="ConsoleAppender" /> <appender-ref ref="ConsoleAppender" />
</logger> </logger>
<!--信号量日志类--> <!--信号量日志类-->
<logger name="semaphorelog"> <logger name="semaphorelog">
<level value="ALL" /> <level value="ALL" />
<appender-ref ref="SemaphoreAppender" /> <appender-ref ref="SemaphoreAppender" />
<appender-ref ref="ConsoleAppender" /> <appender-ref ref="ConsoleAppender" />
</logger> </logger>
<!-- 将日志输出到控制台 --> <!-- 将日志输出到控制台 -->
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout"> <layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" /> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout> </layout>
</appender> </appender>
<!--错误日志附加介质--> <!--错误日志附加介质-->
<appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender"> <appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\" /> <param name="File" value="Log\" />
<param name="AppendToFile" value="true" /> <param name="AppendToFile" value="true" />
<param name="MaxSizeRollBackups" value="100" /> <param name="MaxSizeRollBackups" value="100" />
<param name="MaxFileSize" value="10240" /> <param name="MaxFileSize" value="10240" />
<param name="StaticLogFileName" value="false" /> <param name="StaticLogFileName" value="false" />
<param name="DatePattern" value='yyyy-MM-dd/"LogError.html"'/> <param name="DatePattern" value='yyyy-MM-dd/"LogError.html"'/>
<param name="RollingStyle" value="Date" /> <param name="RollingStyle" value="Date" />
<layout type="log4net.Layout.PatternLayout"> <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;" /> <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> </layout>
</appender> </appender>
<!--信息日志附加介质--> <!--信息日志附加介质-->
<appender name="InfoAppender" type="log4net.Appender.RollingFileAppender"> <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\" /> <param name="File" value="Log\" />
<param name="AppendToFile" value="true" /> <param name="AppendToFile" value="true" />
<param name="MaxFileSize" value="10240" /> <param name="MaxFileSize" value="10240" />
<param name="MaxSizeRollBackups" value="100" /> <param name="MaxSizeRollBackups" value="100" />
<param name="StaticLogFileName" value="false" /> <param name="StaticLogFileName" value="false" />
<param name="DatePattern" value='yyyy-MM-dd/"LogInfo.txt"' /> <param name="DatePattern" value='yyyy-MM-dd/"LogInfo.txt"' />
<param name="RollingStyle" value="Date" /> <param name="RollingStyle" value="Date" />
<!--信息日志布局--> <!--信息日志布局-->
<layout type="log4net.Layout.PatternLayout"> <layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="&lt;--------------&gt;%n日志时间%d [%t] %n日志级别%-5p %n日志内容%m %n " /> <param name="ConversionPattern" value="&lt;--------------&gt;%n日志时间%d [%t] %n日志级别%-5p %n日志内容%m %n " />
</layout> </layout>
</appender> </appender>
<!--PLC日志附加介质--> <!--PLC日志附加介质-->
<appender name="PlcAppender" type="log4net.Appender.RollingFileAppender"> <appender name="PlcAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\" /> <param name="File" value="Log\" />
<param name="AppendToFile" value="true" /> <param name="AppendToFile" value="true" />
<param name="MaxFileSize" value="10240" /> <param name="MaxFileSize" value="10240" />
<param name="MaxSizeRollBackups" value="100" /> <param name="MaxSizeRollBackups" value="100" />
<param name="StaticLogFileName" value="false" /> <param name="StaticLogFileName" value="false" />
<param name="DatePattern" value='yyyy-MM-dd/"PlcLog.txt"' /> <param name="DatePattern" value='yyyy-MM-dd/"PlcLog.txt"' />
<param name="RollingStyle" value="Date" /> <param name="RollingStyle" value="Date" />
<!--信息日志布局--> <!--信息日志布局-->
<layout type="log4net.Layout.PatternLayout"> <layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="&lt;--------------&gt;%n日志时间%d [%t] %n日志级别%-5p %n日志内容%m %n " /> <param name="ConversionPattern" value="&lt;--------------&gt;%n日志时间%d [%t] %n日志级别%-5p %n日志内容%m %n " />
</layout> </layout>
</appender> </appender>
<!--Rfid日志附加介质--> <!--Rfid日志附加介质-->
<appender name="RfidAppender" type="log4net.Appender.RollingFileAppender"> <appender name="RfidAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\" /> <param name="File" value="Log\" />
<param name="AppendToFile" value="true" /> <param name="AppendToFile" value="true" />
<param name="MaxFileSize" value="10240" /> <param name="MaxFileSize" value="10240" />
<param name="MaxSizeRollBackups" value="100" /> <param name="MaxSizeRollBackups" value="100" />
<param name="StaticLogFileName" value="false" /> <param name="StaticLogFileName" value="false" />
<param name="DatePattern" value='yyyy-MM-dd/"RfidLog.txt"' /> <param name="DatePattern" value='yyyy-MM-dd/"RfidLog.txt"' />
<param name="RollingStyle" value="Date" /> <param name="RollingStyle" value="Date" />
<!--信息日志布局--> <!--信息日志布局-->
<layout type="log4net.Layout.PatternLayout"> <layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="&lt;--------------&gt;%n日志时间%d [%t] %n日志级别%-5p %n日志内容%m %n " /> <param name="ConversionPattern" value="&lt;--------------&gt;%n日志时间%d [%t] %n日志级别%-5p %n日志内容%m %n " />
</layout> </layout>
</appender> </appender>
<appender name="ViewAppender" type="log4net.Appender.RollingFileAppender"> <appender name="ViewAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\" /> <param name="File" value="Log\" />
<param name="AppendToFile" value="true" /> <param name="AppendToFile" value="true" />
<param name="MaxFileSize" value="10240" /> <param name="MaxFileSize" value="10240" />
<param name="MaxSizeRollBackups" value="100" /> <param name="MaxSizeRollBackups" value="100" />
<param name="StaticLogFileName" value="false" /> <param name="StaticLogFileName" value="false" />
<param name="DatePattern" value='yyyy-MM-dd/"ViewLog.txt"' /> <param name="DatePattern" value='yyyy-MM-dd/"ViewLog.txt"' />
<param name="RollingStyle" value="Date" /> <param name="RollingStyle" value="Date" />
<!--信息日志布局--> <!--信息日志布局-->
<layout type="log4net.Layout.PatternLayout"> <layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="&lt;--------------&gt;%n日志时间%d [%t] %n日志级别%-5p %n日志内容%m %n " /> <param name="ConversionPattern" value="&lt;--------------&gt;%n日志时间%d [%t] %n日志级别%-5p %n日志内容%m %n " />
</layout> </layout>
</appender> </appender>
<appender name="SqlAppender" type="log4net.Appender.RollingFileAppender"> <appender name="SqlAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\" /> <param name="File" value="Log\" />
<param name="AppendToFile" value="true" /> <param name="AppendToFile" value="true" />
<param name="MaxFileSize" value="10240" /> <param name="MaxFileSize" value="10240" />
<param name="MaxSizeRollBackups" value="100" /> <param name="MaxSizeRollBackups" value="100" />
<param name="StaticLogFileName" value="false" /> <param name="StaticLogFileName" value="false" />
<param name="DatePattern" value='yyyy-MM-dd/"SqlLog.txt"' /> <param name="DatePattern" value='yyyy-MM-dd/"SqlLog.txt"' />
<param name="RollingStyle" value="Date" /> <param name="RollingStyle" value="Date" />
<!--信息日志布局--> <!--信息日志布局-->
<layout type="log4net.Layout.PatternLayout"> <layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="&lt;--------------&gt;%n日志时间%d [%t] %n日志级别%-5p %n日志内容%m %n " /> <param name="ConversionPattern" value="&lt;--------------&gt;%n日志时间%d [%t] %n日志级别%-5p %n日志内容%m %n " />
</layout> </layout>
</appender> </appender>
<appender name="SemaphoreAppender" type="log4net.Appender.RollingFileAppender"> <appender name="SemaphoreAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\" /> <param name="File" value="Log\" />
<param name="AppendToFile" value="true" /> <param name="AppendToFile" value="true" />
<param name="MaxFileSize" value="10240" /> <param name="MaxFileSize" value="10240" />
<param name="MaxSizeRollBackups" value="100" /> <param name="MaxSizeRollBackups" value="100" />
<param name="StaticLogFileName" value="false" /> <param name="StaticLogFileName" value="false" />
<param name="DatePattern" value='yyyy-MM-dd/"SemaphoreLog.txt"' /> <param name="DatePattern" value='yyyy-MM-dd/"SemaphoreLog.txt"' />
<param name="RollingStyle" value="Date" /> <param name="RollingStyle" value="Date" />
<!--信息日志布局--> <!--信息日志布局-->
<layout type="log4net.Layout.PatternLayout"> <layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="&lt;--------------&gt;%n日志时间%d [%t] %n日志级别%-5p %n日志内容%m %n " /> <param name="ConversionPattern" value="&lt;--------------&gt;%n日志时间%d [%t] %n日志级别%-5p %n日志内容%m %n " />
</layout> </layout>
</appender> </appender>
</log4net> </log4net>
</configuration> </configuration>

@ -1,4 +0,0 @@
// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.5.2", FrameworkDisplayName = ".NET Framework 4.5.2")]

@ -1,4 +0,0 @@
// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]

@ -1 +0,0 @@
9838eac57cd8b6a40084a57069c9b0ca58743284d6829e144889c80041b96e8d

@ -1,32 +0,0 @@
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Log4net\bin\Debug\HighWayIot.Log4net.dll
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Log4net\bin\Debug\HighWayIot.Log4net.pdb
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Log4net\obj\Debug\HighWayIot.Log4net.csproj.AssemblyReference.cache
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Log4net\obj\Debug\HighWayIot.Log4net.csproj.CoreCompileInputs.cache
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Log4net\obj\Debug\HighWayIot.Log4net.dll
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Log4net\obj\Debug\HighWayIot.Log4net.pdb
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Log4net\bin\Debug\log4net.dll
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Log4net\obj\Debug\HighWayIot.Log4net.csproj.CopyComplete
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Log4net\bin\Debug\HighWayIot.Log4net.dll
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Log4net\bin\Debug\HighWayIot.Log4net.pdb
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Log4net\bin\Debug\log4net.dll
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Log4net\obj\Debug\HighWayIot.Log4net.csproj.CoreCompileInputs.cache
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Log4net\obj\Debug\HighWayIot.Log4net.csproj.CopyComplete
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Log4net\obj\Debug\HighWayIot.Log4net.dll
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Log4net\obj\Debug\HighWayIot.Log4net.pdb
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Log4net\bin\Debug\HighWayIot.Log4net.dll
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Log4net\bin\Debug\HighWayIot.Log4net.pdb
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Log4net\bin\Debug\log4net.dll
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Log4net\obj\Debug\HighWayIot.Log4net.csproj.AssemblyReference.cache
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Log4net\obj\Debug\HighWayIot.Log4net.csproj.CoreCompileInputs.cache
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Log4net\obj\Debug\HighWayIot.Log4net.csproj.CopyComplete
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Log4net\obj\Debug\HighWayIot.Log4net.dll
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Log4net\obj\Debug\HighWayIot.Log4net.pdb
D:\WorkCode\DLML-SCADA\HighWayIot.Log4net\bin\Debug\HighWayIot.Log4net.dll
D:\WorkCode\DLML-SCADA\HighWayIot.Log4net\bin\Debug\HighWayIot.Log4net.pdb
D:\WorkCode\DLML-SCADA\HighWayIot.Log4net\bin\Debug\log4net.dll
D:\WorkCode\DLML-SCADA\HighWayIot.Log4net\obj\Debug\HighWayIot.Log4net.csproj.AssemblyReference.cache
D:\WorkCode\DLML-SCADA\HighWayIot.Log4net\obj\Debug\HighWayIot.Log4net.csproj.CoreCompileInputs.cache
D:\WorkCode\DLML-SCADA\HighWayIot.Log4net\obj\Debug\HighWayI.1F38289C.Up2Date
D:\WorkCode\DLML-SCADA\HighWayIot.Log4net\obj\Debug\HighWayIot.Log4net.dll
D:\WorkCode\DLML-SCADA\HighWayIot.Log4net\obj\Debug\HighWayIot.Log4net.pdb
D:\WorkCode\DLML-SCADA\HighWayIot.Log4net\bin\Debug\config\log4net.config

@ -1,55 +1,55 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <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')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{CD9B8712-0E09-42D2-849B-B8EAB02C7AB8}</ProjectGuid> <ProjectGuid>{CD9B8712-0E09-42D2-849B-B8EAB02C7AB8}</ProjectGuid>
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>HighWayIot.Mqtt</RootNamespace> <RootNamespace>HighWayIot.Mqtt</RootNamespace>
<AssemblyName>HighWayIot.Mqtt</AssemblyName> <AssemblyName>HighWayIot.Mqtt</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion> <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic> <Deterministic>true</Deterministic>
<TargetFrameworkProfile /> <TargetFrameworkProfile />
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath> <OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
<Optimize>true</Optimize> <Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath> <OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="log4net"> <Reference Include="log4net">
<HintPath>..\HighWayIot.Library\log4net.dll</HintPath> <HintPath>..\HighWayIot.Library\log4net.dll</HintPath>
</Reference> </Reference>
<Reference Include="MQTTnet"> <Reference Include="MQTTnet">
<HintPath>..\HighWayIot.Library\MQTTnet.dll</HintPath> <HintPath>..\HighWayIot.Library\MQTTnet.dll</HintPath>
</Reference> </Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" /> <Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" /> <Reference Include="System.Data" />
<Reference Include="System.Net.Http" /> <Reference Include="System.Net.Http" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="MqttClient.cs" /> <Compile Include="MqttClient.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project> </Project>

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

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

@ -1,4 +0,0 @@
// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.5.2", FrameworkDisplayName = ".NET Framework 4.5.2")]

@ -1,4 +0,0 @@
// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]

@ -1,27 +0,0 @@
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Mqtt\bin\Debug\HighWayIot.Mqtt.dll
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Mqtt\bin\Debug\HighWayIot.Mqtt.pdb
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Mqtt\bin\Debug\log4net.dll
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Mqtt\obj\Debug\HighWayIot.Mqtt.csproj.AssemblyReference.cache
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Mqtt\obj\Debug\HighWayIot.Mqtt.csproj.CoreCompileInputs.cache
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Mqtt\obj\Debug\HighWayIot.Mqtt.csproj.CopyComplete
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Mqtt\obj\Debug\HighWayIot.Mqtt.dll
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Mqtt\obj\Debug\HighWayIot.Mqtt.pdb
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Mqtt\bin\Debug\MQTTnet.dll
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Mqtt\bin\Debug\HighWayIot.Mqtt.dll
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Mqtt\bin\Debug\HighWayIot.Mqtt.pdb
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Mqtt\bin\Debug\log4net.dll
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Mqtt\bin\Debug\MQTTnet.dll
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Mqtt\obj\Debug\HighWayIot.Mqtt.csproj.AssemblyReference.cache
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Mqtt\obj\Debug\HighWayIot.Mqtt.csproj.CoreCompileInputs.cache
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Mqtt\obj\Debug\HighWayIot.Mqtt.csproj.CopyComplete
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Mqtt\obj\Debug\HighWayIot.Mqtt.dll
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Mqtt\obj\Debug\HighWayIot.Mqtt.pdb
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Mqtt\bin\Debug\HighWayIot.Mqtt.dll
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Mqtt\bin\Debug\HighWayIot.Mqtt.pdb
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Mqtt\bin\Debug\log4net.dll
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Mqtt\bin\Debug\MQTTnet.dll
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Mqtt\obj\Debug\HighWayIot.Mqtt.csproj.AssemblyReference.cache
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Mqtt\obj\Debug\HighWayIot.Mqtt.csproj.CoreCompileInputs.cache
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Mqtt\obj\Debug\HighWayIot.Mqtt.csproj.CopyComplete
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Mqtt\obj\Debug\HighWayIot.Mqtt.dll
C:\项目代码\澳柯玛MES项目\HighWayIot\HighWayIot.Mqtt\obj\Debug\HighWayIot.Mqtt.pdb

@ -1,65 +1,65 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <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')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{4EE4C3E2-AC45-4275-8017-E99D70FC1F52}</ProjectGuid> <ProjectGuid>{4EE4C3E2-AC45-4275-8017-E99D70FC1F52}</ProjectGuid>
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>HighWayIot.Plc</RootNamespace> <RootNamespace>HighWayIot.Plc</RootNamespace>
<AssemblyName>HighWayIot.Plc</AssemblyName> <AssemblyName>HighWayIot.Plc</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion> <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic> <Deterministic>true</Deterministic>
<TargetFrameworkProfile /> <TargetFrameworkProfile />
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath> <OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
<Optimize>true</Optimize> <Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath> <OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="HslCommunication"> <Reference Include="HslCommunication">
<HintPath>..\HighWayIot.Library\HslCommunication.dll</HintPath> <HintPath>..\HighWayIot.Library\HslCommunication.dll</HintPath>
</Reference> </Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" /> <Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" /> <Reference Include="System.Data" />
<Reference Include="System.Net.Http" /> <Reference Include="System.Net.Http" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Impl\InovancePlc.cs" /> <Compile Include="Impl\InovancePlc.cs" />
<Compile Include="Impl\OmronNJPlc.CS" /> <Compile Include="Impl\OmronNJPlc.CS" />
<Compile Include="Impl\SiemensPlc.cs" /> <Compile Include="Impl\SiemensPlc.cs" />
<Compile Include="IPlc.cs" /> <Compile Include="IPlc.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\HighWayIot.Common\HighWayIot.Common.csproj"> <ProjectReference Include="..\HighWayIot.Common\HighWayIot.Common.csproj">
<Project>{89a1edd9-d79e-468d-b6d3-7d07b8843562}</Project> <Project>{89a1edd9-d79e-468d-b6d3-7d07b8843562}</Project>
<Name>HighWayIot.Common</Name> <Name>HighWayIot.Common</Name>
</ProjectReference> </ProjectReference>
<ProjectReference Include="..\HighWayIot.Log4net\HighWayIot.Log4net.csproj"> <ProjectReference Include="..\HighWayIot.Log4net\HighWayIot.Log4net.csproj">
<Project>{deabc30c-ec6f-472e-bd67-d65702fdaf74}</Project> <Project>{deabc30c-ec6f-472e-bd67-d65702fdaf74}</Project>
<Name>HighWayIot.Log4net</Name> <Name>HighWayIot.Log4net</Name>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project> </Project>

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

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

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

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

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save