这是我第一次在这个平台上提问。为了变得更好,请随时指出我应该做什么或避免什么,谢谢。
我试图发送一个Struct对象到MES(制造执行系统),以改变我的工作站的状态。以下是数据结构的说明(2.2):
下面的C#代码就是我所做的。我确信我连接到了MES系统,但是状态没有改变,我认为原因可能与我传输的数据的格式有关。
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
using TcpClient = NetCoreServer.TcpClient;
//the Struct of data
[StructLayout(LayoutKind.Sequential, Pack = 8)]
public struct StateOfRobotino
{
public int ResourceID;
public byte SPSType;
public byte State_info;
}
StateOfRobotino robotino10 = new StateOfRobotino();
robotino10.ResourceID = 10;
robotino10.SPSType = 2;
robotino10.State_info = 0b10000001; //MES mode, Auto
byte[] b_robotino10 = getBytes(robotino10);
//Convert Struct type to byte array through Marshal
byte[] getBytes(StateOfRobotino str)
{
int size = Marshal.SizeOf(str);
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(str, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
return arr;
}
我对结构中的第三个数据表示怀疑,我可以使用一个字节(State_info)来表示8位数据吗?如果没有,我该怎么办?或者,还有其他方法可以尝试传输这种数据吗?谢谢。
发布于 2020-11-02 02:20:39
获取字节数组的编组方法应该可以工作。
现在进入您的数据结构:
ResourceID Int 0
SPSType Byte 2
Auto Mode Bit 3.0
... Bit 3.n
MES Mode Bit 3.7
我提请您注意包含0、2和3.x的数字列
ResourceID
看起来占据了0和1.2个字节在一个Int
中表示你的PLC是16位。C#的int
是32位,占用4个字节,您需要显式地指定Int16
或UInt16
(可能是无符号的UInt16
,除非您期望从UInt16
中得到一个负数)。它们也被称为short
或ushort
,但是在处理外部系统时更明确地指定16位是很好的,以减少混淆。
SPSType
只是一个字节。3.0 ... 3.7
。这是占用字节3的8位(0..7)的表示法。这意味着,是的,您需要发送包含所有位的一个字节。请记住,位0是最正确的位,所以0b00000001
是AutoMode,0b10000000
是MESMode.。
https://stackoverflow.com/questions/64632978
复制相似问题