using System.Text;
namespace Khd.Core.Plc
{
///
/// Plc帮助类
///
public static class StaticPlcHelper
{
///
/// 进行高低位转换后,写入Plc地址
///
/// plc
/// 写入地址
/// 值
/// 长度
public static void WriteToPoint(this Plc.S7.Plc plc, string address, object? valueString, string? len)
{
if (len == null)
{
throw new ArgumentException("StaticPlcHelper Ex len is null");
}
if (valueString == null)
{
throw new ArgumentException("StaticPlcHelper Ex valueString is null");
}
plc.Write(address, GetValue(len, valueString));
}
///
/// 写入RFID
///
/// plc
/// 读取地址
/// 长度
/// 读取到的RFID
public static void WriteRFID(this Plc.S7.Plc plc, string address, string value,int len = 15)
{
string[] adds = address.Split(".");
int db = int.Parse(adds[0].Replace("DB", ""));
int startByteAdr = int.Parse(adds[1].Replace("DBX", ""));
// 将 value 转换为字节数组,确保其长度符合要求
byte[] byteArray = Encoding.ASCII.GetBytes(value);
if (byteArray.Length > len)
{
throw new ArgumentException($"Value length exceeds the specified length of {len} bytes.");
}
// 填充字节数组到指定长度
byte[] dataToWrite = new byte[len];
Array.Copy(byteArray, dataToWrite, byteArray.Length);
plc.Write(S7.DataType.DataBlock, db, startByteAdr, dataToWrite);
}
///
/// 读取RFID
///
/// plc
/// 读取地址
/// 长度
/// 读取到的RFID
public static string? ReadRFID(this Plc.S7.Plc plc, string address, int len = 36)
{
string[] adds = address.Split(".");
int db = int.Parse(adds[0].Replace("DB", ""));
int startByteAdr = int.Parse(adds[1].Replace("DBX", ""));
var result = (byte[]?)plc.Read(S7.DataType.DataBlock, db, startByteAdr, S7.VarType.Byte, len);
if (result == null)
{
return null;
}
string res = Encoding.UTF8.GetString(result).Replace("\0", "").Replace("$", "").Replace("\\u", "").Trim();
if (res.Contains("JYHB"))
{
return res[res.IndexOf('J')..].Substring(0, 12);
}
else if (res.Contains('C'))
{
return res[res.IndexOf('C')..];
}
else
{
return "";
}
}
///
/// 电气写入点位高低位转换
///
/// 点位地址位长度
/// 写入数值
///
public static object GetValue(string? len, object value)
{
if (len == "2")
{
return Convert.ToInt16(value);
}
if (len == "4")
{
return Convert.ToInt32(value);
}
if (len == "6")
{
return Convert.ToByte(value);
}
if (len == "8")
{
return Convert.ToString(value);
}
if (len == "10")
{
return Convert.ToBoolean(value);
}
if (len == "12")
{
return Convert.ToSingle(value);
}
throw new ArgumentException("StaticPlcHelper Ex len is not support");
}
}
}