103 lines
3.2 KiB
C#
Raw Normal View History

using HslCommunication.Profinet.Siemens;
2024-11-07 20:17:39 +08:00
using Infrastructure;
using MiniExcelLibs;
2024-11-07 20:17:39 +08:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DOAN.Infrastructure.PLC
{
2024-11-08 08:42:33 +08:00
public class PLCTool
2024-11-07 20:17:39 +08:00
{
// 私有连接对象
private SiemensS7Net siemensTcpNet = null;
private readonly string plcAddress;
2024-11-13 15:53:15 +08:00
public PLCTool()
2024-11-07 20:17:39 +08:00
{
plcAddress = AppSettings.GetConfig("PLCConfig:Address");
this.siemensTcpNet = new SiemensS7Net(SiemensPLCS.S200Smart, plcAddress)
2024-11-07 20:17:39 +08:00
{
ConnectTimeOut = 5000
};
2024-11-13 15:53:15 +08:00
}
/// <summary>
/// 尝试连接到PLC
/// </summary>
/// <returns>连接成功返回true失败返回false</returns>
public bool ConnectPLC()
2024-11-13 15:53:15 +08:00
{
try
2024-11-07 20:17:39 +08:00
{
var connect = siemensTcpNet.ConnectServer();
2024-11-13 15:53:15 +08:00
if (connect.IsSuccess)
{
Console.WriteLine($"PLC连接成功,地址{plcAddress}");
2024-11-13 15:53:15 +08:00
return true;
}
else
{
Console.WriteLine($"PLC连接失败,地址{plcAddress}: {connect.Message}");
return false;
2024-11-13 15:53:15 +08:00
}
2024-11-07 20:17:39 +08:00
}
2024-11-13 15:53:15 +08:00
catch (Exception e)
2024-11-07 20:17:39 +08:00
{
Console.WriteLine($"PLC连接失败,地址{plcAddress}: {e.Message}");
2024-11-07 20:17:39 +08:00
return false;
}
2024-11-07 21:27:56 +08:00
}
2024-11-08 08:42:33 +08:00
/// <summary>
/// 向PLC写入单个bit值
2024-11-08 08:42:33 +08:00
/// </summary>
/// <param name="addr">PLC地址</param>
/// <param name="value">要写入的bool值</param>
/// <returns>写入成功返回true失败返回false</returns>
public bool WriteBit(string addr, bool value)
2024-11-07 21:27:56 +08:00
{
var write = siemensTcpNet.Write(addr, value);
2024-11-08 08:42:33 +08:00
return write.IsSuccess;
2024-11-07 20:17:39 +08:00
}
2024-11-08 10:10:59 +08:00
/// <summary>
/// 从PLC读取单个bit值
2024-11-08 10:10:59 +08:00
/// </summary>
/// <param name="addr">PLC地址</param>
/// <returns>读取到的bool值</returns>
public bool ReadBit(string addr)
2024-11-08 10:10:59 +08:00
{
return siemensTcpNet.ReadBool(addr).Content;
2024-11-08 10:10:59 +08:00
}
2025-01-16 10:13:50 +08:00
/// <summary>
/// 从PLC读取多个连续的二进制数据并转为字节数组
2025-01-16 10:13:50 +08:00
/// </summary>
/// <param name="addr">起始PLC地址默认为"VB100"</param>
/// <param name="length">要读取的字节数默认为12</param>
/// <returns>读取到的字节数组如果失败返回null</returns>
2025-01-16 10:13:50 +08:00
public byte[] ReadAllValue(string addr = "VB100", ushort length = 12)
{
var result = siemensTcpNet.Read(addr, length);
2025-01-16 10:13:50 +08:00
if (result.IsSuccess)
{
return result.Content;
2025-01-16 10:13:50 +08:00
}
else
{
Console.WriteLine($"PLC IO 取值失败,PLC地址{plcAddress},访问地址为{addr},地址个数为{length}");
2025-01-16 10:13:50 +08:00
return null;
}
}
/// <summary>
/// 关闭与PLC的连接
/// </summary>
public void ConnectClose()
2024-11-07 20:17:39 +08:00
{
siemensTcpNet.ConnectClose();
}
}
}