RPCMessage.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.IO;
  3. using InABox.Core;
  4. namespace InABox.Rpc
  5. {
  6. // Note that this implements both ISerializeBinary and ICoreFormattable, which is annoying duplicate code. The reason that these can't be combined
  7. // is that ICoreFormattable *must* be able to be used by netstandard2.0 for Logikal, and therefore must live outside of InABox.Core. Hence, we need
  8. // two interfaces. If we wanted to combine them, the interface for the ISerializeBinary would need to be changed to be able to just use a
  9. // CoreBinaryWriter/Reader, and this would introduce version inconsistency for communications. Hence, this would only be able to be done once we
  10. // switch from old mobile app and therefore can introduce a breaking change for a version (e.g., version 9).
  11. [Serializable]
  12. public partial class RpcMessage : ISerializeBinary, ICoreFormattable
  13. {
  14. public Guid Id { get; set; }
  15. public String Command { get; set; }
  16. public byte[] Payload { get; set; }
  17. public RpcError Error { get; set; }
  18. public override string ToString() => $"{Command} [{Error}]";
  19. public RpcMessage()
  20. {
  21. Id = Guid.NewGuid();
  22. Command = "";
  23. Payload = Array.Empty<byte>();
  24. Error = RpcError.NONE;
  25. }
  26. public RpcMessage(Guid id, string command, byte[] payload) : this()
  27. {
  28. Id = id;
  29. Command = command;
  30. Payload = payload;
  31. Error = RpcError.NONE;
  32. }
  33. public void SerializeBinary(CoreBinaryWriter writer)
  34. {
  35. writer.Write(Id);
  36. writer.Write(Command);
  37. writer.WriteBinaryValue(Payload);
  38. writer.Write(Error.ToString());
  39. }
  40. public void DeserializeBinary(CoreBinaryReader reader)
  41. {
  42. Id = reader.ReadGuid();
  43. Command = reader.ReadString();
  44. Payload = reader.ReadBinaryValue<byte[]>();
  45. if (Enum.TryParse<RpcError>(reader.ReadString(), out var error))
  46. Error = error;
  47. }
  48. public void Write(BinaryWriter writer)
  49. {
  50. writer.Write(Id);
  51. writer.Write(Command);
  52. writer.Write(Payload.Length);
  53. writer.Write(Payload);
  54. writer.Write((Int32)Error);
  55. }
  56. public void Read(BinaryReader reader)
  57. {
  58. Id = reader.ReadGuid();
  59. Command = reader.ReadString();
  60. var _length = reader.ReadInt32();
  61. Payload = reader.ReadBytes(_length);
  62. Error = (RpcError)reader.ReadInt32();
  63. }
  64. }
  65. }