-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArtNetClient.cs
52 lines (43 loc) · 1.37 KB
/
ArtNetClient.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
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
namespace ArtfullySimple;
public class ArtNetClient : UdpClient
{
public event EventHandler<ArtNetPacket>? ReceivedPacket;
CancellationTokenSource tkSrc;
public bool IsListening => _listening;
private bool _listening;
private IPEndPoint ep;
public ArtNetClient(IPAddress ip)
{
ep = new(ip, 6454);
tkSrc = new();
Client = new Socket(ep.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
Client.Bind(ep);
}
public void StartListening()
{
Task.Run(async () => await ListenLoop(tkSrc.Token));
_listening = true;
}
public void StopListening()
{
tkSrc.Cancel();
_listening = false;
}
private async Task ListenLoop(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
var result = await ReceiveAsync();
ArtNetInfo info = new(result.Buffer);
if (!info.IsValid)
continue;
ArtNetReader reader = new(info);
if (reader.TryDecodePacket(out ArtNetPacket packet))
ReceivedPacket?.Invoke(this, packet);
}
}
}