refactor(PLCTool): 重构PLC工具类,优化连接处理和错误日志 fix: 修正数据库连接字符串和开发环境配置 feat(DoanBackgroundService): 添加新的后台服务实现,改进库存监控逻辑
103 lines
3.2 KiB
C#
103 lines
3.2 KiB
C#
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();
|
||
}
|
||
}
|
||
} |