using System.Text; namespace ZB.MOM.WW.OtOpcUa.Driver.TwinCAT; /// /// Decodes an IEC STRING(n) / WSTRING(n) buffer read at the PLC's own declared width. /// The driver reads string symbols as raw bytes and decodes them here instead of letting the /// Beckhoff marshaller pick an encoding, because that marshaller falls back to the HOST's ANSI code /// page (CultureInfo.CurrentCulture.TextInfo.ANSICodePage) for a non-UTF-8 target — so a /// TwinCAT 2 string would decode differently on a Polish (1250) or Cyrillic (1251) server. /// /// /// Two rules, both ported from the ignitionoee TwinCAT driver and both found on a real PLC: /// /// A value ENDS at its first NUL — 0x00 for a STRING, an aligned 0x00 0x00 /// code unit for a WSTRING. Whatever follows is stale content a longer earlier value left in the /// buffer (live on the Elma cleaner Z33856: work order 67504440 read back with a stale /// "\0" + "1" tail). /// A STRING is single-byte Windows-1252 (umlauts, ° in alarm texts), unless /// the target reports UTF-8 string data (TwinCAT 3.1 4026+ "UTF8 Encoding for STRING"). /// ISO-8859-1 is the fallback on a runtime without code-page support — identical outside /// 0x80–0x9F. /// /// internal static class TwinCATStringCodec { private static readonly Encoding Windows1252 = CreateWindows1252(); private static Encoding CreateWindows1252() { try { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); return Encoding.GetEncoding(1252); } catch (Exception) { return Encoding.Latin1; } } /// Decodes an IEC STRING(n) buffer: ends at the first NUL, Windows-1252 unless . /// The raw symbol bytes (n+1 for a STRING(n)). /// True when the target reports UTF-8 string data. /// The decoded value. public static string DecodeString(ReadOnlySpan bytes, bool utf8) { var end = bytes.IndexOf((byte)0); if (end >= 0) bytes = bytes[..end]; return (utf8 ? Encoding.UTF8 : Windows1252).GetString(bytes); } // Strict encoders for the WRITE side: a character the target encoding cannot hold is refused rather // than silently replaced with '?' (the replacement would be written to the PLC as if it were the value). private static readonly Encoding StrictWindows1252 = CreateStrict(Windows1252.CodePage); private static readonly Encoding StrictUtf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); private static readonly Encoding StrictUtf16 = new UnicodeEncoding(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: true); private static Encoding CreateStrict(int codePage) => Encoding.GetEncoding(codePage, EncoderFallback.ExceptionFallback, DecoderFallback.ReplacementFallback); /// /// Encodes a value into an IEC STRING(n) buffer of the PLC's declared width (n+1 bytes): the /// inverse of — Windows-1252 unless , NUL-terminated /// and NUL-padded so no stale tail of a longer earlier value survives. /// /// The value to write. /// The PLC symbol's byte width (n+1 for a STRING(n)). /// True when the target reports UTF-8 string data. /// Exactly bytes. /// The value does not fit STRING(n), or holds a character the /// target encoding cannot represent. public static byte[] EncodeString(string value, int byteWidth, bool utf8) => Encode(value, byteWidth, utf8 ? StrictUtf8 : StrictWindows1252, terminatorBytes: 1, "STRING"); /// /// Encodes a value into an IEC WSTRING(n) buffer (UTF-16LE, 2(n+1) bytes): the inverse of /// , terminated by an aligned U+0000 and zero-padded. /// /// The value to write. /// The PLC symbol's byte width. /// Exactly bytes. /// The value does not fit WSTRING(n). public static byte[] EncodeWString(string value, int byteWidth) => Encode(value, byteWidth, StrictUtf16, terminatorBytes: 2, "WSTRING"); private static byte[] Encode(string value, int byteWidth, Encoding encoding, int terminatorBytes, string kind) { ArgumentNullException.ThrowIfNull(value); byte[] encoded; try { encoded = encoding.GetBytes(value); } catch (ArgumentException ex) // EncoderFallbackException: a character the encoding cannot hold { throw new OverflowException($"'{value}' cannot be represented in the PLC's {kind} encoding: {ex.Message}", ex); } if (encoded.Length + terminatorBytes > byteWidth) throw new OverflowException( $"'{value}' is {encoded.Length} B but the PLC {kind} holds {Math.Max(0, byteWidth - terminatorBytes)} B"); var buffer = new byte[byteWidth]; encoded.CopyTo(buffer, 0); return buffer; } /// Decodes an IEC WSTRING(n) buffer (UTF-16LE): ends at the first aligned U+0000. /// The raw symbol bytes (2(n+1) for a WSTRING(n)). /// The decoded value. public static string DecodeWString(ReadOnlySpan bytes) { var end = bytes.Length & ~1; // whole UTF-16 code units only — a trailing odd byte is ignored for (var i = 0; i + 1 < end; i += 2) { if (bytes[i] == 0 && bytes[i + 1] == 0) { end = i; break; } } return Encoding.Unicode.GetString(bytes[..end]); } }