Repository navigation
Expand file tree
/
Copy pathSerialNetworkInterface.cs
More file actions
46 lines (43 loc) · 1.59 KB
/
Copy pathSerialNetworkInterface.cs
File metadata and controls
46 lines (43 loc) · 1.59 KB
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
using System.IO.Ports;
namespace ModemAPI
{
public class SerialNetworkInterface
{
private bool IsSubscribedForIncomingData = false;
private List<Action<byte[]>> Handlers = [];
public SerialPort Port;
public SerialNetworkInterface(SerialPort port)
{
Port = port;
if (NetworkInterfaceLibrary.NetworkInterfaces.ContainsKey(port.PortName))
{
throw new InvalidOperationException("cannot add a new network interface because it is conflicting");
}
NetworkInterfaceLibrary.NetworkInterfaces.Add(port.PortName, this);
Port.DiscardInBuffer();
Port.DiscardOutBuffer();
}
public void OnDataReceived(Action<byte[]> eventBody)
{
Handlers.Add(eventBody);
if (!IsSubscribedForIncomingData)
{
Port.DataReceived += delegate (object handler, SerialDataReceivedEventArgs e)
{
byte[] buffer = new byte[Port.BytesToRead];
Port.Read(buffer, 0, buffer.Length);
List<Action<byte[]>> snapshot = [.. Handlers];
foreach (Action<byte[]> eventHandler in snapshot)
{
eventHandler(buffer);
}
};
IsSubscribedForIncomingData = true;
}
}
public void Write(byte[] data)
{
Port.Write(data, 0, data.Length);
}
}
}