-
-
Notifications
You must be signed in to change notification settings - Fork 33
/
BLeBeacon.cs
78 lines (59 loc) · 2.36 KB
/
BLeBeacon.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
using ShortDev.Networking;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net.NetworkInformation;
using System.Text;
namespace ShortDev.Microsoft.ConnectedDevices.Transports;
public sealed record BLeBeacon(DeviceType DeviceType, PhysicalAddress MacAddress, string DeviceName)
{
[Flags]
enum BeaconFlags : byte
{
MyDevice,
Public
}
public static bool TryParse(byte[] beaconData, [MaybeNullWhen(false)] out BLeBeacon data)
{
data = null;
if (beaconData == null)
return false;
EndianReader reader = new(Endianness.BigEndian, beaconData);
var scenarioType = (ScenarioType)reader.ReadByte();
if (scenarioType != ScenarioType.Bluetooth)
return false;
var deviceType = (DeviceType)reader.ReadByte();
var versionAndFlags = reader.ReadByte();
if (versionAndFlags >> 5 != 1)
return false; // wrong version
var flags = (BeaconFlags)(versionAndFlags & 0x1f);
if ((int)flags >= 2)
return false; // wrong flags
/* deviceStatus */
_ = (ExtendedDeviceStatus)reader.ReadByte();
if (flags != BeaconFlags.Public)
return false;
data = new(
deviceType,
new PhysicalAddress(BinaryConvert.ToReversed(reader.ReadBytes(6))),
Encoding.UTF8.GetString(reader.ReadToEnd())
);
return true;
}
public byte[] ToArray()
{
EndianWriter writer = new(Endianness.LittleEndian);
writer.Write((byte)ScenarioType.Bluetooth);
writer.Write((byte)DeviceType);
byte versionAndFlags = (byte)BeaconFlags.Public;
versionAndFlags |= Constants.BLeBeaconVersion << 5;
writer.Write(versionAndFlags);
var deviceStatus = ExtendedDeviceStatus.RemoteSessionsNotHosted | ExtendedDeviceStatus.NearShareAuthPolicyPermissive;
writer.Write((byte)deviceStatus);
writer.Write(BinaryConvert.ToReversed(MacAddress.GetAddressBytes()));
// ToDo: Don't crop characters wider that 2 bytes!
ReadOnlySpan<byte> deviceNameBuffer = Encoding.UTF8.GetBytes(DeviceName);
var deviceNameLength = Math.Min(deviceNameBuffer.Length, Constants.BLeBeaconDeviceNameMaxByteLength);
writer.Write(deviceNameBuffer[..deviceNameLength]);
return writer.Buffer.ToArray();
}
}