-
Notifications
You must be signed in to change notification settings - Fork 1
/
ProtobufStreamMessageSerializer.cs
71 lines (60 loc) · 2.04 KB
/
ProtobufStreamMessageSerializer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using ProtoBuf;
using System.Text;
namespace SmartIOT.Connector.Messages.Serializers;
public class ProtobufStreamMessageSerializer : IStreamMessageSerializer
{
public object? DeserializeMessage(Stream stream)
{
try
{
byte typeValue;
using (BinaryReader reader = new BinaryReader(stream, Encoding.UTF8, true))
{
typeValue = reader.ReadByte();
}
return typeValue switch
{
1 => DeserializeMessage<TagEvent>(stream),
2 => DeserializeMessage<DeviceEvent>(stream),
3 => DeserializeMessage<TagWriteRequestCommand>(stream),
99 => DeserializeMessage<PingMessage>(stream),
_ => throw new InvalidDataException($"Message type {typeValue} is not recognized"),
};
}
catch (EndOfStreamException)
{
return null;
}
}
private T DeserializeMessage<T>(Stream stream)
{
return Serializer.DeserializeWithLengthPrefix<T>(stream, PrefixStyle.Base128);
}
public void SerializeMessage(Stream stream, object message)
{
switch (message)
{
case TagEvent t:
SerializeMessage(1, stream, t);
break;
case DeviceEvent d:
SerializeMessage(2, stream, d);
break;
case TagWriteRequestCommand c:
SerializeMessage(3, stream, c);
break;
case PingMessage p:
SerializeMessage(99, stream, p);
break;
default:
throw new ArgumentException($"Message type {message.GetType().FullName} is not managed", nameof(message));
}
}
private void SerializeMessage<T>(byte typeValue, Stream stream, T message)
{
// serialize the type
stream.WriteByte(typeValue);
// serialize length + payload
Serializer.SerializeWithLengthPrefix<T>(stream, message, PrefixStyle.Base128);
}
}