Files
sy_hx_pbl_backend/Infrastructure/PLC/PLCTool.cs
赵正易 07880805a3 feat: 添加PLC配置并优化后台服务
refactor(PLCTool): 重构PLC工具类,优化连接处理和错误日志
fix: 修正数据库连接字符串和开发环境配置
feat(DoanBackgroundService): 添加新的后台服务实现,改进库存监控逻辑
2025-08-19 09:30:44 +08:00

103 lines
3.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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