Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow changing the default Encoding used in S7String #435

Merged
merged 3 commits into from
Jun 17, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 deletions S7.Net/Types/S7String.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ namespace S7.Net.Types
/// </summary>
public static class S7String
{
/// <summary>
/// The Encoding used when serializing and deserializing S7String (Encoding.ASCII by default)
/// </summary>
public static Encoding StringEncoding { get; set; }

/// <summary>
/// Converts S7 bytes to a string
/// </summary>
Expand All @@ -30,15 +35,15 @@ public static string FromByteArray(byte[] bytes)

try
{
return Encoding.ASCII.GetString(bytes, 2, length);
if (StringEncoding == null) StringEncoding = Encoding.ASCII;
return StringEncoding.GetString(bytes, 2, length);
}
catch (Exception e)
{
throw new PlcException(ErrorCode.ReadData,
$"Failed to parse {VarType.S7String} from data. Following fields were read: size: '{size}', actual length: '{length}', total number of bytes (including header): '{bytes.Length}'.",
e);
}

}

/// <summary>
Expand All @@ -54,9 +59,10 @@ public static byte[] ToByteArray(string value, int reservedLength)
throw new ArgumentNullException(nameof(value));
}

if (reservedLength > 254) throw new ArgumentException($"The maximum string length supported is 254.");

var bytes = Encoding.ASCII.GetBytes(value);
if (reservedLength > 254) throw new ArgumentException($"The maximum string length supported is 254.");

if (StringEncoding == null) StringEncoding = Encoding.ASCII;
var bytes = StringEncoding.GetBytes(value);
if (bytes.Length > reservedLength) throw new ArgumentException($"The provided string length ({bytes.Length} is larger than the specified reserved length ({reservedLength}).");

var buffer = new byte[2 + reservedLength];
Expand All @@ -65,5 +71,13 @@ public static byte[] ToByteArray(string value, int reservedLength)
buffer[1] = (byte)bytes.Length;
return buffer;
}

/// <summary>
/// Initializes default static properties
/// </summary>
static S7String()
{
StringEncoding = Encoding.ASCII;
}
}
}