libplctag / libplctag.NET

A .NET wrapper for libplctag.
https://libplctag.github.io/
Mozilla Public License 2.0
214 stars 53 forks source link

Custom UDT mapper with string #326

Closed patopat closed 1 year ago

patopat commented 1 year ago

Hi, Could you provide a short example about how to write a string from the following Custom UDT ? I use a CompactLogix controller 5370 and string is defined as LEN - DINT, DATA - SINT[82].

    public class CustomTagPlcPlcMapper : PlcMapperBase<CustomTagPlc>, IPlcMapper<CustomTagPlc>
    {
        public override int? ElementSize => 4 + 86;

        public override CustomTagPlc Decode(Tag tag, int offset)
        {
            var DINT0 = tag.GetInt32(offset + 0);
            var STRING0 = tag.GetString(offset + 4);

            var customTag = new CustomTagPlc
            {
                Id= DINT0,
                Datetime = STRING0
            };

            return customTag;
        }

        public override void Encode(Tag tag, int offset, CustomTagPlc value)
        {
            tag.SetInt32(offset + 0, value.Id);
            tag.SetString(offset + 4, value.Datetime);
        }
    }

    public class CustomTagPlc
    {
        public int Id { get; set; }
        public string Datetime { get; set; }
    }

image

Regards, Pat

timyhac commented 1 year ago

The code before change might be useful: https://github.com/libplctag/libplctag.NET/commit/fc7c18b374a60590896180346e62d1906cfd070b#diff-73f7e73fbc97c01ccd0cadbd895bab88133cd4a602da23a91fa449d223af81b6L67.

Be careful that you're using the right encodings - it looks like we previously assumed ASCII encoding but make sure its appropriate to your application.

When developing the UDT martialling logic it can be useful to use the GetBuffer() method to access the entire buffer, and inspect it using a hexdump tool. I normally use hexed.it.

If you're looking to use the string configuration properties it might be possible to set them in the Encode/Decode functions.

patopat commented 1 year ago

@timyhac ,

Yes, very useful thank you.

timyhac commented 1 year ago

Thanks!