Dreamine.PLC.Core 1.0.1
Dreamine.PLC.Core 산업 자동화 및 I/O 기능을 제공합니다.
로딩중...
검색중...
일치하는것 없음
PlcSimulatorProtocol.cs
이 파일의 문서화 페이지로 가기
1using System.Globalization;
2
4
13public static class PlcSimulatorProtocol
14{
23 public const string ReadBits = "READ_BITS";
24
33 public const string ReadWords = "READ_WORDS";
34
43 public const string WriteBits = "WRITE_BITS";
44
53 public const string WriteWords = "WRITE_WORDS";
54
79 public static string Ok(string? payload = null)
80 {
81 return string.IsNullOrWhiteSpace(payload) ? "OK" : $"OK {payload}";
82 }
83
108 public static string Error(string message)
109 {
110 return $"ERR {message.Replace('\r', ' ').Replace('\n', ' ')}";
111 }
112
137 public static string FormatBits(IEnumerable<bool> values)
138 {
139 return string.Join(',', values.Select(x => x ? "1" : "0"));
140 }
141
166 public static string FormatWords(IEnumerable<short> values)
167 {
168 return string.Join(',', values.Select(x => x.ToString(CultureInfo.InvariantCulture)));
169 }
170
203 public static bool[] ParseBits(string payload)
204 {
205 return SplitValues(payload)
206 .Select(ParseBit)
207 .ToArray();
208 }
209
250 public static short[] ParseWords(string payload)
251 {
252 return SplitValues(payload)
253 .Select(x => short.Parse(x, CultureInfo.InvariantCulture))
254 .ToArray();
255 }
256
289 public static string ReadOkPayload(string line)
290 {
291 if (line.StartsWith("OK", StringComparison.OrdinalIgnoreCase))
292 {
293 return line.Length > 2 ? line[3..].Trim() : string.Empty;
294 }
295
296 if (line.StartsWith("ERR", StringComparison.OrdinalIgnoreCase))
297 {
298 var message = line.Length > 3 ? line[4..].Trim() : "PLC simulator error.";
299 throw new InvalidOperationException(message);
300 }
301
302 throw new InvalidOperationException($"Invalid PLC simulator response: {line}");
303 }
304
329 private static string[] SplitValues(string payload)
330 {
331 return payload.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
332 }
333
366 private static bool ParseBit(string text)
367 {
368 return text switch
369 {
370 "1" => true,
371 "0" => false,
372 _ when bool.TryParse(text, out var value) => value,
373 _ => throw new FormatException($"Invalid bit value: {text}")
374 };
375 }
376}
static string FormatWords(IEnumerable< short > values)
static string FormatBits(IEnumerable< bool > values)