Init - 初始化

master
Wen JY 1 year ago
commit 2836ceaec0

Binary file not shown.

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

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

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

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

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

File diff suppressed because it is too large Load Diff

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

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

@ -0,0 +1,24 @@
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

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

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

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

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

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

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

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

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

@ -0,0 +1,16 @@
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.AssemblyReference.cache
\\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

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

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

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

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

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

@ -0,0 +1,18 @@
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

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

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

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

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

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

File diff suppressed because it is too large Load Diff

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

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

@ -0,0 +1,30 @@
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Plc\bin\Debug\HighWayIot.Plc.dll
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Plc\bin\Debug\HighWayIot.Plc.pdb
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Plc\obj\Debug\HighWayIot.Plc.csproj.AssemblyReference.cache
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Plc\obj\Debug\HighWayIot.Plc.csproj.CoreCompileInputs.cache
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Plc\obj\Debug\HighWayIot.Plc.dll
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Plc\obj\Debug\HighWayIot.Plc.pdb
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Plc\bin\Debug\HighWayIot.Common.dll
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Plc\bin\Debug\HighWayIot.Log4net.dll
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Plc\bin\Debug\HslCommunication.dll
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Plc\bin\Debug\Newtonsoft.Json.dll
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Plc\bin\Debug\log4net.dll
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Plc\bin\Debug\HighWayIot.Common.pdb
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Plc\bin\Debug\HighWayIot.Log4net.pdb
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Plc\bin\Debug\Newtonsoft.Json.xml
Z:\Desktop\日常代码\HighWayIot\HighWayIot.Plc\obj\Debug\HighWayIot.Plc.csproj.CopyComplete
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Plc\bin\Debug\HighWayIot.Plc.dll
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Plc\bin\Debug\HighWayIot.Plc.pdb
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Plc\bin\Debug\HighWayIot.Common.dll
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Plc\bin\Debug\HighWayIot.Log4net.dll
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Plc\bin\Debug\HslCommunication.dll
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Plc\bin\Debug\Newtonsoft.Json.dll
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Plc\bin\Debug\log4net.dll
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Plc\bin\Debug\HighWayIot.Common.pdb
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Plc\bin\Debug\HighWayIot.Log4net.pdb
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Plc\bin\Debug\Newtonsoft.Json.xml
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Plc\obj\Debug\HighWayIot.Plc.csproj.AssemblyReference.cache
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Plc\obj\Debug\HighWayIot.Plc.csproj.CoreCompileInputs.cache
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Plc\obj\Debug\HighWayIot.Plc.csproj.CopyComplete
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Plc\obj\Debug\HighWayIot.Plc.dll
\\Mac\Home\Desktop\日常代码\HighWayIot\HighWayIot.Plc\obj\Debug\HighWayIot.Plc.pdb

@ -0,0 +1,69 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{D0DC3CFB-6748-4D5E-B56A-76FDC72AB4B3}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>HighWayIot.Repository</RootNamespace>
<AssemblyName>HighWayIot.Repository</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="SqlSugar">
<HintPath>Z:\Desktop\日常代码\HighWayIot\HighWayIot.Library\SqlSugar.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data.SQLite">
<HintPath>Z:\Desktop\日常代码\HighWayIot\HighWayIot.Library\System.Data.SQLite.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="domain\BaseDeviceinfo.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Repository.cs" />
<Compile Include="service\IBaseDeviceinfoService.cs" />
<Compile Include="service\Impl\BaseDeviceinfoServiceImpl.cs" />
<Compile Include="SqlSugarHelper.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\HighWayIot.Common\HighWayIot.Common.csproj">
<Project>{89a1edd9-d79e-468d-b6d3-7d07b8843562}</Project>
<Name>HighWayIot.Common</Name>
</ProjectReference>
<ProjectReference Include="..\HighWayIot.Log4net\HighWayIot.Log4net.csproj">
<Project>{deabc30c-ec6f-472e-bd67-d65702fdaf74}</Project>
<Name>HighWayIot.Log4net</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

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

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

@ -0,0 +1,48 @@
using HighWayIot.Common;
using HighWayIot.Log4net;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HighWayIot.Repository
{
internal class SqlSugarHelper //不能是泛型类
{
private static LogHelper logHelper = LogHelper.Instance;
private static JsonChange jsonChange = JsonChange.Instance;
private static string sqliteConnStr = $"Data Source={Path.GetFullPath("data\\data.db")};Version=3";
//如果是固定多库可以传 new SqlSugarScope(List<ConnectionConfig>,db=>{}) 文档:多租户
//如果是不固定多库 可以看文档Saas分库
//用单例模式
public static SqlSugarScope Db = new SqlSugarScope(new List<ConnectionConfig>()
{
new ConnectionConfig()
{
ConfigId = "sqlite",
ConnectionString = sqliteConnStr,
DbType = DbType.Sqlite,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
}
},
db =>
{
//(A)全局生效配置点
//调试SQL事件可以删掉
db.Aop.OnLogExecuting = (sql, pars) =>
{
logHelper.SqlLog($"{sql};参数:{jsonChange.ModeToJson(pars)}");
};
});
}
}

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

Loading…
Cancel
Save