c# - 使用 S7netplus 在 C# 中读取 Siemens PLC s7 字符串
问题描述
我无法使用 S7netplus 读取 Siemens PLC S7 1500 的 DB 中的数据。
情况:
- 我有一个 C# 应用程序正在运行。
- 我在PLC上连接得很好。
- 我可以读取 Boolean、UInt、UShot、Bytes 等数据
但我不知道如何读取字符串数据(见下图)
要读取 Boolean 等其他数据,我使用以下调用:
plc.Read("DB105.DBX0.0")
我知道在数据块 105 (DB105) 中读取的数据类型为布尔 (DBX),偏移量为 0.0 我想对字符串应用相同类型的读取。所以我在我的例子中尝试了“DB105.DBB10.0”。但它返回一个字节类型的值“40”(我应该有别的东西)
我看到还有另一种阅读方法
plc.ReadBytes(DataType DB, int DBNumber, int StartByteArray, int lengthToRead)
但是我很难看到如何将它应用到我的示例中(我知道我必须在之后将其转换为字符串)。
继续: - 是否有一种简单的方法可以使用“DB105.DBX0.0”之类的字符串来读取西门子 PLC 中的字符串数据?- 如果不是如何在我的示例中使用 ReadBytes 函数?
谢谢你的帮助
解决方案
我设法通过 ReadBytes 方法读取了我的字符串值。在我的示例中,我需要传递如下值:
plc.Read(DataType.DataBlock, 105, 12, VarType.String, 40);
为什么是12?因为字节字符串的前 2 个八位字节用于长度。所以 10 到 12 返回一个值为 40 的值,即长度。
我已经重写了 read 方法来接受这样的“简单字符串”调用:
public T Read<T>(object pValue)
{
var splitValue = pValue.ToString().Split('.');
//check if it is a string template (3 separation ., 2 if not)
if (splitValue.Count() > 3 && splitValue[1].Substring(2, 1) == "S")
{
DataType dType;
//If we have to read string in other dataType need development to make here.
if (splitValue[0].Substring(0, 2) == "DB")
dType = DataType.DataBlock;
else
throw new Exception("Data Type not supported for string value yet.");
int length = Convert.ToInt32(splitValue[3]);
int start = Convert.ToInt32(splitValue[1].Substring(3, splitValue[1].Length - 3));
int MemoryNumber = Convert.ToInt32(splitValue[0].Substring(2, splitValue[0].Length - 2));
// the 2 first bits are for the length of the string. So we have to pass it
int startString = start + 2;
var value = ReadFull(dType, MemoryNumber, startString, VarType.String, length);
return (T)value;
}
else
{
var value = plc.Read(pValue.ToString());
//Cast with good format.
return (T)value;
}
}
所以现在我可以像这样调用我的读取函数:使用基本的现有调用:
var element = mPlc.Read<bool>("DB10.DBX1.4").ToString();
=> 在数据块 10 中读取字节 1 和八位字节 4 的布尔值var element = mPlc.Read<uint>("DB10.DBD4.0").ToString();
=> 在数据块 10 中读取字节 4 和八位字节 0 的 int 值
对字符串的覆盖调用:
var element = mPlc.Read<string>("DB105.DBS10.0.40").ToString()
=> 在数据块 105 中读取字节 10 和八位字节 0 上的字符串值,长度为 40
希望这对其他人有帮助:)
推荐阅读
- python - 为什么 AffinityPropagation 将 -1 作为集群 ID?
- javascript - 为什么重新分配给另一种类型会触发 VSCode 的类型检查器?
- javascript - 正则表达式检查格式`YYYY-MM-DDTHH:MM:SS.000` - javascript
- java - 如何使用流 API 将二维列表转换为逗号分隔的二维列表的映射
- reporting-services - 如何将行组合并到列组中的一行
- java - Junit 5 的宁静
- c# - 已发布的 Blazor Wasm - 子路径上的 DLL 给出 404 NotFound
- ios - 如何从 JSON 响应正确创建领域对象?
- android - 后退箭头不会触发 onOptionsItemSelected
- javascript - 如何在运行时在nestjs中扫描所有装饰器值