Command.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. using FunnyCommon.Shared;
  8. namespace FunnyCommon.Remoting.Protocol
  9. {
  10. public class Command
  11. {
  12. public CommandType Type { get; set; }
  13. public byte Value { get; set; }
  14. public override string ToString()
  15. {
  16. return $"{Type} {Value}";
  17. }
  18. public byte[] ToBytes()
  19. {
  20. var buf = new byte[2];
  21. buf[0] = (byte)Type;
  22. buf[1] = Value;
  23. return buf;
  24. }
  25. private static readonly HashSet<byte> CommandTypeValues =
  26. new HashSet<byte>(Enum.GetValues(typeof(CommandType)).Cast<byte>());
  27. public static Command ReadFromStream(Stream stream)
  28. {
  29. using (var br = new BinaryReader(stream, Encoding.UTF8, true))
  30. {
  31. var read = br.ReadByte();
  32. if (!CommandTypeValues.Contains(read)) throw new InvalidDataException(nameof(CommandType) + $"<{read}>");
  33. var type = (CommandType)read;
  34. var obj = new Command
  35. {
  36. Type = type,
  37. Value = br.ReadByte(),
  38. };
  39. return obj;
  40. }
  41. }
  42. public Response Execute(IPiGpoutManager manager)
  43. {
  44. string mesg = null;
  45. switch (Type)
  46. {
  47. case CommandType.AllocateGpio:
  48. switch (manager.Allocate(Value))
  49. {
  50. case true:
  51. mesg = $"Rob pin_{Value}";
  52. break;
  53. case false:
  54. mesg = $"Norm Allocated pin_{Value}";
  55. break;
  56. case null:
  57. mesg = $"Already Allocated pin_{Value}";
  58. break;
  59. default:
  60. throw new ArgumentOutOfRangeException(nameof(Nullable<bool>));
  61. }
  62. break;
  63. case CommandType.FreeGpio:
  64. manager.Free(Value);
  65. mesg = $"Norm Free gpio{Value}";
  66. break;
  67. case CommandType.SetHeight:
  68. manager.WritePin(Value, true);
  69. mesg = $"Norm SetHeight gpio{Value}";
  70. break;
  71. case CommandType.SetLow:
  72. manager.WritePin(Value, false);
  73. mesg = $"Norm SetLow gpio{Value}";
  74. break;
  75. case CommandType.Sleep:
  76. Thread.Sleep(Value);
  77. mesg = $"Norm Sleeped {Value}ms";
  78. break;
  79. default:
  80. throw new ArgumentOutOfRangeException(nameof(Type));
  81. }
  82. return new Response { Success = true, Message = mesg };
  83. }
  84. }
  85. }