Responder.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. namespace S7.Net.UnitTest;
  6. internal static class Responder
  7. {
  8. private const string Comment = "//";
  9. private static char[] Space = " ".ToCharArray();
  10. public static byte[] Respond(RequestResponsePair pair, byte[] request)
  11. {
  12. var offset = 0;
  13. var matches = new Dictionary<string, byte>();
  14. var res = new List<byte>();
  15. using var requestReader = new StringReader(pair.RequestPattern);
  16. string line;
  17. while ((line = requestReader.ReadLine()) != null)
  18. {
  19. var tokens = line.Split(Space, StringSplitOptions.RemoveEmptyEntries);
  20. foreach (var token in tokens)
  21. {
  22. if (token.StartsWith(Comment)) break;
  23. if (offset >= request.Length)
  24. {
  25. throw new Exception("Request pattern has more data than request.");
  26. }
  27. var received = request[offset];
  28. if (token.Length == 2 && byte.TryParse(token, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var value))
  29. {
  30. // Number, exact match
  31. if (value != received)
  32. {
  33. throw new Exception($"Incorrect data at offset {offset}. Expected {value:X2}, received {received:X2}.");
  34. }
  35. }
  36. else
  37. {
  38. matches[token] = received;
  39. }
  40. offset++;
  41. }
  42. }
  43. if (offset != request.Length) throw new Exception("Request contained more data than request pattern.");
  44. using var responseReader = new StringReader(pair.ResponsePattern);
  45. while ((line = responseReader.ReadLine()) != null)
  46. {
  47. var tokens = line.Split(Space, StringSplitOptions.RemoveEmptyEntries);
  48. foreach (var token in tokens)
  49. {
  50. if (token.StartsWith(Comment)) break;
  51. if (token.Length == 2 && byte.TryParse(token, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var value))
  52. {
  53. res.Add(value);
  54. }
  55. else
  56. {
  57. if (!matches.TryGetValue(token, out var match))
  58. {
  59. throw new Exception($"Unmatched token '{token}' in response.");
  60. }
  61. res.Add(match);
  62. }
  63. }
  64. }
  65. return res.ToArray();
  66. }
  67. }