添加项目文件。

This commit is contained in:
2026-04-30 11:34:41 +08:00
parent a8539ccaac
commit 80635aa46e
181 changed files with 16378 additions and 0 deletions

View File

@@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SamplePre.Communication
{
/// <summary>
/// 通讯协议类型枚举
/// </summary>
public enum CommProtocolType
{
S7 = 0,
ModbusTcp = 1,
ModbusRtu = 2
}
/// <summary>
/// 通讯状态枚举
/// </summary>
public enum CommunicationState
{
Disconnected = 0,
Connected = 1,
Connecting = 2,
Error = 3
}
/// <summary>
/// 通讯数据类型枚举
/// </summary>
public enum CommDataType
{
Bit, // 位
Byte, // 字节
Int16, // 16位整数
Int32, // 32位整数
Float // 浮点型
}
}

View File

@@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SamplePre.Communication
{
public interface ICommunication
{
/// <summary>
/// 下发下位机指令
/// </summary>
/// <param name="Dbno"></param>
/// <param name="start"></param>
/// <param name="bytes"></param>
/// <returns></returns>
bool WriteArraysBtye<T>(int Dbno, int start, T[] bytes);
/// <summary>
/// 读取监控数据,读取数组
/// </summary>
/// <returns></returns>
ushort[] ReadArraysShort(int Dbno, int start, int lenth);
/// <summary>
/// 写入数据
/// </summary>
/// <param name="address">地址(如"M0.0", "DB1.DBW2"</param>
/// <param name="value">要写入的值</param>
/// <returns>是否写入成功</returns>
public bool WriteSingleData(string address, object value);
}
}

View File

@@ -0,0 +1,236 @@
using Modbus.Device;
using S7.Net;
using SamplePre.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace SamplePre.Communication.Communication
{
public class ModbusTcpCommunicator : ICommunication, IDisposable
{
IModbusMaster _modbusMaster = null;
TcpClient _tcpClient = null;
private readonly string _ipAddress;
private readonly int _port;
/// <summary>
/// 是否连接
/// </summary>
private bool _isConnected = false;
/// <summary>
/// 是否连接
/// </summary>
public bool IsConnected
{
get => _isConnected;
set
{
if (_isConnected != value)
{
_isConnected = value;
ConnectionStatusChanged?.Invoke(value);
}
}
}
/// <summary>
/// 连接状态变化事件
/// </summary>
public event Action<bool> ConnectionStatusChanged;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="ipAddress">IP地址</param>
/// <param name="port">端口号</param>
public ModbusTcpCommunicator(string ipAddress, int port=502)
{
try
{
_ipAddress = ipAddress;
_port = port;
_tcpClient = new TcpClient(ipAddress, port);//Modbus主设备
_modbusMaster = ModbusIpMaster.CreateIp(_tcpClient);
_modbusMaster.Transport.ReadTimeout = 2000;
_modbusMaster.Transport.Retries = 3;
IsConnected = true;
}
catch (Exception ex)
{
LoggerHelper.Logger.Error("初始化ModbusTcpCommunicator失败" + ex.Message);
}
}
/// <summary>
/// 连接PLC
/// </summary>
/// <returns>是否连接成功</returns>
public bool Connect()
{
try
{
if (IsConnected)
{
LoggerHelper.Logger.Info("已经处于连接状态!");
return true;
}
// 如果之前的连接对象已释放,创建新的
if (_modbusMaster == null)
{
_tcpClient = new TcpClient(_ipAddress, _port);//Modbus主设备
_modbusMaster = ModbusIpMaster.CreateIp(_tcpClient);
_modbusMaster.Transport.ReadTimeout = 2000; //
_modbusMaster.Transport.Retries = 3;
}
LoggerHelper.Logger.Info("PLC连接成功");
IsConnected = true;
return IsConnected;
}
catch (Exception ex)
{
LoggerHelper.Logger.Info($"连接PLC失败: {ex.Message}");
IsConnected = false;
return false;
}
}
/// <summary>
/// 断开连接
/// </summary>
public void Disconnect()
{
try
{
if (IsConnected)
{
_modbusMaster.Dispose();
_tcpClient.Close();
IsConnected = false;
LoggerHelper.Logger.Info("PLC连接已断开");
}
}
catch (Exception ex)
{
LoggerHelper.Logger.Info($"断开PLC连接失败: {ex.Message}");
}
}
/// <summary>
/// 写入数组数据
/// </summary>
/// <param name="Dbno"></param>
/// <param name="start"></param>
/// <param name="bytes"></param>
/// <returns></returns>
public bool WriteArraysBtye<T>(int Dbno, int start, T[] data)
{
try
{
if (!IsConnected && !Connect())
{
return false;
}
ushort[] ushorts = data.Cast<ushort>().ToArray();
_modbusMaster.WriteMultipleRegisters((byte)Dbno, (ushort)start, ushorts);
return true;
}
catch (Exception ex)
{
LoggerHelper.Logger.Info($"写入数组失败: {ex.Message}");
return false;
}
}
/// <summary>
/// 读取数组
/// </summary>
/// <returns></returns>
public ushort[] ReadArraysShort(int Dbno, int start, int lenth)
{
//try
//{
// if (!IsConnected && !Connect())
// {
// return null;
// }
// //public object? Read(DataType dataType, int db, int startByteAdr, VarType varType, int varCount, byte bitAdr = 0)
// ushort[] datas = _plc.Read(DataType.DataBlock, Dbno, start, VarType.Word, lenth) as ushort[];
// return datas;
//}
//catch (Exception ex)
//{
// LoggerHelper.Logger.Info($"读取数组失败: {ex.Message}");
// return null;
//}
return null;
}
/// <summary>
/// 释放资源
/// </summary>
public void Dispose()
{
// 释放托管资源
Disconnect();
}
public bool WriteSingleData(string address, object value)
{
throw new NotImplementedException();
}
~ModbusTcpCommunicator()
{
Dispose();
}
}
}

View File

@@ -0,0 +1,236 @@
using S7.Net;
using S7.Net.Types;
using SamplePre.Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace SamplePre.Communication
{
public class S7PlcCommunicator : ICommunication, IDisposable
{
public Plc _plc;
private readonly string _ipAddress;
private readonly int _rack;
private readonly int _slot;
private readonly CpuType _cpuType;
/// <summary>
/// 是否连接
/// </summary>
private bool _isConnected = false;
/// <summary>
/// 是否连接
/// </summary>
public bool IsConnected
{
get => _isConnected;
set
{
if (_isConnected != value)
{
_isConnected = value;
ConnectionStatusChanged?.Invoke(value);
}
}
}
/// <summary>
/// 连接状态变化事件
/// </summary>
public event Action<bool> ConnectionStatusChanged;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="cpuType">PLC型号</param>
/// <param name="ipAddress">IP地址</param>
/// <param name="rack">机架号</param>
/// <param name="slot">插槽号</param>
public S7PlcCommunicator(CpuType cpuType, string ipAddress, int rack = 0, int slot = 1)
{
_cpuType = cpuType;
_ipAddress = ipAddress;
_rack = rack;
_slot = slot;
_plc = new Plc(cpuType, ipAddress, (short)rack, (short)slot);
}
/// <summary>
/// 连接PLC
/// </summary>
/// <returns>是否连接成功</returns>
public bool Connect()
{
try
{
if (IsConnected)
{
LoggerHelper.Logger.Info("已经处于连接状态!");
return true;
}
// 如果之前的连接对象已释放,创建新的
if (_plc == null)
{
_plc = new Plc(_cpuType, _ipAddress, (short)_rack, (short)_slot);
}
_plc.Open();
bool connected = _plc.IsConnected;
LoggerHelper.Logger.Info(connected ? "PLC连接成功" : "PLC连接失败");
IsConnected = connected;
return connected;
}
catch (Exception ex)
{
LoggerHelper.Logger.Info($"连接PLC失败: {ex.Message}");
IsConnected = false;
return false;
}
}
/// <summary>
/// 断开连接
/// </summary>
public void Disconnect()
{
try
{
if (IsConnected)
{
_plc.Close();
IsConnected = false;
LoggerHelper.Logger.Info("PLC连接已断开");
}
}
catch (Exception ex)
{
LoggerHelper.Logger.Info($"断开PLC连接失败: {ex.Message}");
}
}
/// <summary>
/// 写入数组数据
/// </summary>
/// <param name="Dbno"></param>
/// <param name="start"></param>
/// <param name="bytes"></param>
/// <returns></returns>
public bool WriteArraysBtye<T>(int Dbno, int start, T[] bytes)
{
try
{
if (!IsConnected && !Connect())
{
return false;
}
byte[] data = bytes.Cast<byte>().ToArray();
_plc.WriteBytes(DataType.DataBlock, Dbno, start, data);
return true;
}
catch (Exception ex)
{
LoggerHelper.Logger.Info($"写入数组失败: {ex.Message}");
return false;
}
}
/// <summary>
/// 读取数组
/// </summary>
/// <returns></returns>
public ushort[] ReadArraysShort(int Dbno,int start,int lenth)
{
try
{
if (!IsConnected && !Connect())
{
return null;
}
//public object? Read(DataType dataType, int db, int startByteAdr, VarType varType, int varCount, byte bitAdr = 0)
ushort[] datas = _plc.Read(DataType.DataBlock, Dbno, start, VarType.Word, lenth) as ushort[];
return datas;
}
catch (Exception ex)
{
LoggerHelper.Logger.Info($"读取数组失败: {ex.Message}");
return null;
}
}
/// <summary>
/// 写入数据
/// </summary>
/// <param name="address">地址(如"M0.0", "DB1.DBW2"</param>
/// <param name="value">要写入的值</param>
/// <returns>是否写入成功</returns>
public bool WriteSingleData(string address, object value)
{
try
{
if (!IsConnected && !Connect())
{
return false;
}
_plc.Write(address, value);
Console.WriteLine($"写入 {address} 成功: {value}");
return true;
}
catch (Exception ex)
{
Console.WriteLine($"写入 {address} 失败: {ex.Message}");
return false;
}
}
/// <summary>
/// 释放资源
/// </summary>
public void Dispose()
{
// 释放托管资源
Disconnect();
//_plc?.Dispose();
_plc = null;
}
~S7PlcCommunicator()
{
Dispose();
}
}
}

View File

@@ -0,0 +1,424 @@
using S7.Net;
using S7.Net.Types;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace SamplePre.Communication
{
public class S7PlcCommunicatorBack : IDisposable
{
public Plc _plc;
private readonly string _ipAddress;
private readonly int _rack;
private readonly int _slot;
private readonly CpuType _cpuType;
/// <summary>
/// 是否连接
/// </summary>
public bool IsConnected => _plc?.IsConnected ?? false;
/// <summary>
/// 连接状态变化事件
/// </summary>
public event Action<bool> ConnectionStatusChanged;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="cpuType">PLC型号</param>
/// <param name="ipAddress">IP地址</param>
/// <param name="rack">机架号</param>
/// <param name="slot">插槽号</param>
public S7PlcCommunicatorBack(CpuType cpuType, string ipAddress, int rack = 0, int slot = 1)
{
_cpuType = cpuType;
_ipAddress = ipAddress;
_rack = rack;
_slot = slot;
_plc = new Plc(cpuType, ipAddress, (short)rack, (short)slot);
}
/// <summary>
/// 连接PLC
/// </summary>
/// <returns>是否连接成功</returns>
public bool Connect()
{
try
{
if (IsConnected)
{
Console.WriteLine("已经处于连接状态");
return true;
}
// 如果之前的连接对象已释放,创建新的
if (_plc == null)
{
_plc = new Plc(_cpuType, _ipAddress, (short)_rack, (short)_slot);
}
_plc.Open();
bool connected = _plc.IsConnected;
Console.WriteLine(connected ? "PLC连接成功" : "PLC连接失败");
ConnectionStatusChanged?.Invoke(connected);
return connected;
}
catch (Exception ex)
{
Console.WriteLine($"连接PLC失败: {ex.Message}");
ConnectionStatusChanged?.Invoke(false);
return false;
}
}
/// <summary>
/// 断开连接
/// </summary>
public void Disconnect()
{
try
{
if (IsConnected)
{
_plc.Close();
Console.WriteLine("PLC连接已断开");
ConnectionStatusChanged?.Invoke(false);
}
}
catch (Exception ex)
{
Console.WriteLine($"断开PLC连接失败: {ex.Message}");
}
}
/// <summary>
/// 读取数据
/// </summary>
/// <param name="address">地址(如"M0.0", "DB1.DBW2"</param>
/// <returns>读取的值</returns>
public object ReadData(string address)
{
try
{
if (!IsConnected && !Connect())
{
return null;
}
object value = _plc.Read(address);
Console.WriteLine($"a读取 {address} 成功: {value}");
return value;
}
catch (Exception ex)
{
Console.WriteLine($"读取 {address} 失败: {ex.Message}");
return null;
}
}
/// <summary>
/// 写入数据
/// </summary>
/// <param name="address">地址(如"M0.0", "DB1.DBW2"</param>
/// <param name="value">要写入的值</param>
/// <returns>是否写入成功</returns>
public bool WriteData(string address, object value)
{
try
{
if (!IsConnected && !Connect())
{
return false;
}
_plc.Write(address, value);
Console.WriteLine($"写入 {address} 成功: {value}");
return true;
}
catch (Exception ex)
{
Console.WriteLine($"写入 {address} 失败: {ex.Message}");
return false;
}
}
/// <summary>
/// 批量读取数据
/// </summary>
/// <param name="addresses">地址数组</param>
/// <returns>值数组,与地址数组顺序对应</returns>
public object[] ReadMultipleData(string[] addresses)
{
if (addresses == null || addresses.Length == 0)
return new object[0];
try
{
if (!IsConnected && !Connect())
{
return null;
}
var values = new object[addresses.Length];
for (int i = 0; i < addresses.Length; i++)
{
values[i] = _plc.Read(addresses[i]);
}
Console.WriteLine($"批量读取 {addresses.Length} 个地址成功");
return values;
}
catch (Exception ex)
{
Console.WriteLine($"批量读取失败: {ex.Message}");
return null;
}
}
/// <summary>
/// 写入数组数据
/// </summary>
/// <param name="Dbno"></param>
/// <param name="start"></param>
/// <param name="bytes"></param>
/// <returns></returns>
public bool WriteArraysBtye(int Dbno, int start, byte[] bytes)
{
try
{
if (!IsConnected && !Connect())
{
return false;
}
_plc.WriteBytes(DataType.DataBlock, Dbno, start, bytes);
return true;
}
catch (Exception ex)
{
Console.WriteLine($"写入数组: {ex.Message}");
return false;
}
}
/// <summary>
/// 读取数组
/// </summary>
/// <returns></returns>
public ushort[] ReadArraysShort(int Dbno,int start,int lenth)
{
try
{
if (!IsConnected && !Connect())
{
return null;
}
//public object? Read(DataType dataType, int db, int startByteAdr, VarType varType, int varCount, byte bitAdr = 0)
ushort[] datas = _plc.Read(DataType.DataBlock, Dbno, start, VarType.Word, lenth) as ushort[];
return datas;
}
catch (Exception ex)
{
Console.WriteLine($"读取数组: {ex.Message}");
return null;
}
}
/// <summary>
/// 读结构体
/// </summary>
public T ReadStruct<T>(int dbno, int start)
{
T t;
try
{
if (!IsConnected && !Connect())
{
return default(T);
}
t = (T)_plc.ReadStruct(typeof(T), dbno, start);
return t;
}
catch (Exception)
{
Console.WriteLine($"读结构体失败!");
return default(T);
}
}
/// <summary>
/// 写结构体
/// </summary>
public bool WriteStruct<T>(T t,int dbno,int start)
{
try
{
if (!IsConnected && !Connect())
{
return false;
}
_plc.WriteStruct(t, dbno, start);
return true;
}
catch (Exception)
{
Console.WriteLine($"写入失败!");
return false;
}
}
/// <summary>
/// 读取字符串
/// </summary>
/// <param name="DBno"></param>
/// <param name="startNo"></param>
/// <returns></returns>
public string ReadString(int DBno, int startNo)
{
try
{
if (!IsConnected && !Connect())
{
return "";
}
int totalLenth = (byte)_plc.Read(S7.Net.DataType.DataBlock, DBno, startNo, VarType.Byte, 1);
int len = (byte)_plc.Read(S7.Net.DataType.DataBlock, DBno, startNo + 1, VarType.Byte, 1);
byte[] bytes = _plc.ReadBytes(S7.Net.DataType.DataBlock, DBno, startNo + 2, len);
string mesg = Encoding.ASCII.GetString(bytes);
return mesg;
}
catch (Exception ex)
{
Console.WriteLine($"读取字符串失败!");
return "";
}
}
/// <summary>
/// 写入字符串
/// </summary>
/// <param name="DBno"></param>
/// <param name="startNo"></param>
/// <param name="contextStr"></param>
/// <returns></returns>
public bool WriteString(int DBno,int startNo, string contextStr)
{
try
{
if (!IsConnected && !Connect())
{
return false;
}
_plc.Write(S7.Net.DataType.DataBlock, DBno, startNo + 1, (byte)contextStr.Length);
_plc.Write(S7.Net.DataType.DataBlock, DBno, startNo + 2, contextStr);
Console.WriteLine($"写入字符串成功!");
return true;
}
catch (Exception ex)
{
Console.WriteLine($"写入字符串失败!");
return false;
}
}
/// <summary>
/// 写入bool
/// </summary>
/// <param name="DBno"></param>
/// <param name="startNo"></param>
/// <param name="contextStr"></param>
/// <returns></returns>
public bool WriteBoolen(int DBno, int startByteAdr, int bitAdr, bool val)
{
try
{
if (!IsConnected && !Connect())
{
return false;
}
_plc.WriteBit(DataType.DataBlock, DBno, startByteAdr, bitAdr, val);
Console.WriteLine($"写入成功!");
return true;
}
catch (Exception ex)
{
Console.WriteLine($"写入失败!");
return false;
}
}
/// <summary>
/// 释放资源
/// </summary>
public void Dispose()
{
Disconnect();
//_plc?.Dispose();
_plc = null;
}
}
struct TestA
{
public ushort value1;
public ushort value2;
}
}

View File

@@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace SamplePre.Communication.Communication
{
public class SocketClient
{
// 服务端 IP 和端口(和你服务端一致)
private const string ServerIp = "127.0.0.1";
private const int ServerPort = 8888;
private Socket _clientSocket;
public Action<string> ReceiveMsgAction;
//static async Task Main(string[] args)
//{
// var client = new SocketClient();
// await client.StartClientAsync();
//}
/// <summary>
/// 启动客户端
/// </summary>
public async Task StartClientAsync()
{
try
{
// 创建客户端 Socket
_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ReceiveMsgAction?.Invoke("正在连接服务端...");
// 连接服务端
await _clientSocket.ConnectAsync(IPAddress.Parse(ServerIp), ServerPort);
ReceiveMsgAction?.Invoke("✅ 连接服务端成功!");
// 启动接收消息任务(后台异步监听)
_ = Task.Run(ReceiveMsgAsync);
}
catch (Exception ex)
{
ReceiveMsgAction?.Invoke($"连接失败:{ex.Message}");
}
}
public void CloseConnect()
{
_clientSocket.Close();
ReceiveMsgAction?.Invoke("客户端已断开");
}
/// <summary>
/// 发送消息
/// </summary>
public async Task SendMsgAsync(string msg)
{
if (string.IsNullOrEmpty(msg)) return;
byte[] data = Encoding.UTF8.GetBytes(msg);
await _clientSocket.SendAsync(data, SocketFlags.None);
}
/// <summary>
/// 接收服务端消息
/// </summary>
private async Task ReceiveMsgAsync()
{
byte[] buffer = new byte[1024];
while (true)
{
try
{
int len = await _clientSocket.ReceiveAsync(buffer, SocketFlags.None);
if (len == 0) break;
string recMsg = Encoding.UTF8.GetString(buffer, 0, len);
//回调函数
ReceiveMsgAction?.Invoke($"\n📩 服务端回复:{recMsg}");
}
catch
{
break;
}
}
}
}
}

View File

@@ -0,0 +1,64 @@
using S7.Net;
using SamplePre.Communication.Communication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace SamplePre.Communication
{
public class CommunicationFactory
{
/// <summary>
/// 创建通讯实例
/// </summary>
/// <param name="protocolType">协议类型</param>
/// <param name="connectionParams">连接参数</param>
/// <returns></returns>
/// <exception cref="NotSupportedException"></exception>
public static ICommunication CreateCommunication(CommProtocolType protocolType, string connectionParams)
{
ICommunication comm = null;
switch (protocolType)
{
case CommProtocolType.S7:
comm = CreateS7(connectionParams);
break;
case CommProtocolType.ModbusTcp:
comm = CreateModbusTcp(connectionParams);
break;
case CommProtocolType.ModbusRtu:
break;
default:
break;
}
return comm;
}
public static ICommunication CreateS7(string connectionParams)
{
string[] params1 = connectionParams.Split(':');
if(params1 == null || params1.Length < 3) return null;
//ICommunication comm = new S7PlcCommunicator(CpuType.S71500, "192.168.10.2", 0, 1);
ICommunication comm = new S7PlcCommunicator(CpuType.S71500, params1[0], int.Parse( params1[1]), int.Parse( params1[2]));
return comm;
}
public static ICommunication CreateModbusTcp(string connectionParams)
{
string[] params1 = connectionParams.Split(':');
if (params1 == null || params1.Length < 2) return null;
ICommunication comm = new ModbusTcpCommunicator(params1[0], int.Parse(params1[1]));
return comm;
}
}
}

View File

@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NModbus4" Version="2.1.0" />
<PackageReference Include="S7netplus" Version="0.20.0" />
<PackageReference Include="System.IO.Ports" Version="10.0.5" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SamplePre.Common\SamplePre.Common.csproj" />
</ItemGroup>
</Project>