MessageReceiver.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using System.Text;
  3. namespace Vinno.FIS.Sonopost.Features.Oled
  4. {
  5. public class MessageReceiver
  6. {
  7. public static OKResult OK = new OKResult();
  8. public static WrongHeaderResult WrongHeader = new WrongHeaderResult();
  9. public static ErrorResult Error = new ErrorResult();
  10. public static CommonErrorResult CommonError = new CommonErrorResult();
  11. public static IReceiveResult Parse(byte[] data, byte command)
  12. {
  13. if (ParseHeader(data, command))
  14. {
  15. if (command == (byte)MessageType.SearchPage)
  16. {
  17. return ParseSearchCommand(data);
  18. }
  19. return ParseNormalCommand(data);
  20. }
  21. return WrongHeader;
  22. }
  23. private static IReceiveResult ParseNormalCommand(byte[] data)
  24. {
  25. int dataLength = data[3];
  26. var returnValue = new byte[dataLength];
  27. Buffer.BlockCopy(data, 4, returnValue, 0, dataLength);
  28. var result = Encoding.UTF8.GetString(returnValue);
  29. if (result == "OK")
  30. {
  31. return OK;
  32. }
  33. return Error;
  34. }
  35. private static IReceiveResult ParseSearchCommand(byte[] data)
  36. {
  37. int dataLength = data[3];
  38. var pageCount = data[4];
  39. var returnValue = new byte[dataLength - 1];
  40. Buffer.BlockCopy(data, 5, returnValue, 0, dataLength - 1);
  41. var result = Encoding.UTF8.GetString(returnValue);
  42. if (result == "OK")
  43. {
  44. return new SearchPageResult(pageCount);
  45. }
  46. return Error;
  47. }
  48. private static bool ParseHeader(byte[] data, byte command)
  49. {
  50. return data[0] == 0XAA && data[1] == command && data[2] == 0xff;
  51. }
  52. }
  53. }