/
CoapOption.cs
96 lines (82 loc) · 2 KB
/
CoapOption.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using System;
using System.Text;
namespace Waher.Networking.CoAP
{
/// <summary>
/// Base class for all CoAP options.
/// </summary>
public abstract class CoapOption : ICoapOption
{
internal int originalOrder = 0;
/// <summary>
/// Base class for all CoAP options.
/// </summary>
public CoapOption()
{
}
/// <summary>
/// Option number.
/// </summary>
public abstract int OptionNumber
{
get;
}
/// <summary>
/// If the option is critical or not. Messages containing critical options that are not processed, must be discarded.
/// </summary>
public abstract bool Critical
{
get;
}
/// <summary>
/// Gets the option value.
/// </summary>
/// <returns>Binary value. Can be null, if option does not have a value.</returns>
public abstract byte[] GetValue();
/// <summary>
/// Creates a new CoAP option.
/// </summary>
/// <param name="Value">Option value.</param>
/// <returns>Newly created CoAP option.</returns>
public abstract CoapOption Create(byte[] Value);
/// <summary>
/// Transforms an unsigned integer to a variable sized option value.
/// </summary>
/// <param name="Value">Value.</param>
/// <returns>Binary variable length option value.</returns>
public static byte[] ToBinary(ulong Value)
{
ulong Temp = Value;
int NrBytes = 0;
while (Temp > 0)
{
NrBytes++;
Temp >>= 8;
}
byte[] Result = new byte[NrBytes];
while (NrBytes > 0)
{
NrBytes--;
Result[NrBytes] = (byte)Value;
Value >>= 8;
}
return Result;
}
/// <summary>
/// Transforms a string to a variable sized option value.
/// </summary>
/// <param name="Value">Value.</param>
/// <returns>Binary variable length option value.</returns>
public static byte[] ToBinary(string Value)
{
return Encoding.UTF8.GetBytes(Value);
}
/// <summary>
/// <see cref="object.ToString()"/>
/// </summary>
public override string ToString()
{
return this.OptionNumber.ToString() + ". " + this.GetType().Name;
}
}
}