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, string? 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");
}
var value = GetValue(len, valueString);
plc.Write(address, value);
}
///
/// 读取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')..];
}
else if(res.Contains("C"))
{
return res[res.IndexOf('C')..];
}else
{
return "";
}
}
///
/// 电气写入点位高低位转换
///
/// 点位地址位长度
/// 写入数值
///
public static object GetValue(string? len, string? 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);
}
return 0;
}
}
}