Search code examples
c#structlibnodave

How to Read/Write struct from PLC with libnodave


i'm writing a little c# application that reads/writes some data to the DB memory of a S7-300 PLC. I'm using PLCSim simulator and DotNetSiemensPLCToolBoxLibrary to perform some tests. As you know DotNetSiemensPLCToolBoxLibrary is a layer over libnodave, so often i used libnodave directly. I can connect with success with PLC and i can write/read Inputs, merker and strings. But i have problems when i try to write/read a struct. Here is the code for writing a struct in the plc :

//PLCTagGeneric
PLCTag<TestStruct> tst = new PLCTag<TestStruct>() { DataBlockNumber = 1, ByteAddress = 0 };
tmpConn.ReadValue(tst);
TestStruct read = tst.GenericValue;
TestStruct wrt = new TestStruct();
wrt.bb = 1;
wrt.cc = true;
wrt.ee = 14;           
wrt.test = "Bin da!";
tst.Controlvalue = wrt;
tmpConn.WriteValue(tst);

This is the code for reading:

PLCTag<TestStruct> tst = new PLCTag<TestStruct>() { DataBlockNumber = 1, ByteAddress = 0 };
tmpConn.ReadValue(tst);

byte[] buf = new byte[18];
int res = tmpConn._dc.readBytes(libnodave.daveDB, 1, 0, 18, buf);
tst._readValueFromBuffer(buf, 0);
TestStruct t = tst.GenericValue; 

This is the struct:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct TestStruct
    {
        public SByte bb;
        public Boolean cc;
        public UInt32 ee;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
        public string test;
    }

The output of the reading is:

bb: 0
ee: 920583
cc: false
test: n da!

Why? I need help. Thank you


Solution

  • SOLVED. In PLCs, data are only a stream of bytes. So if you writes a sequence of Int16|Int32|string, you must read in the same order otherwise you will cause an error in parsing bytes. Hope this helps