Skip to content

Commit be3a1e7

Browse files
committed
add: 多加几个接口和属性
1 parent 9373b7a commit be3a1e7

File tree

2 files changed

+71
-3
lines changed

2 files changed

+71
-3
lines changed

llcomNext/LLCOM/Models/Channels/BaseChannel.cs

Lines changed: 60 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,64 @@ public class BaseChannel(int bufferSize = 1024 * 10)
1212
private int _bufferLength = 0;
1313

1414
/// <summary>
15-
/// 当数据被添加之后,被触发
15+
/// 通道事件
1616
/// </summary>
17-
public EventHandler<int>? DataAddedEvent;
17+
public EventHandler<ChannelEvent>? ChannelEvent;
18+
19+
20+
/// <summary>
21+
/// 获取当前buffer的长度
22+
/// </summary>
23+
public virtual int BufferSize => bufferSize;
24+
25+
/// <summary>
26+
/// 获取当前buffer中已存储的数据长度
27+
/// </summary>
28+
public virtual int BufferToRead => _bufferLength;
29+
30+
/// <summary>
31+
/// 是否打开了通道
32+
/// </summary>
33+
public virtual bool IsOpen { get; set; } = false;
34+
35+
/// <summary>
36+
/// 打开通道
37+
/// </summary>
38+
public virtual void Open()
39+
{
40+
IsOpen = true;
41+
_bufferLength = 0; // Reset buffer length when opening
42+
ChannelEvent?.Invoke(this, Channels.ChannelEvent.Opened);
43+
}
44+
45+
/// <summary>
46+
/// 关闭通道
47+
/// </summary>
48+
public virtual void Close()
49+
{
50+
IsOpen = false;
51+
_bufferLength = 0; // Clear buffer when closing
52+
ChannelEvent?.Invoke(this, Channels.ChannelEvent.Closed);
53+
}
54+
55+
/// <summary>
56+
/// 发送数据到通道
57+
/// </summary>
58+
/// <param name="data">数据</param>
59+
/// <param name="options">选项,给mqtt之类的用</param>
60+
/// <returns>是否发送成功</returns>
61+
public virtual bool SendData(Span<byte> data, Object? options = null)
62+
{
63+
if (!IsOpen)
64+
return false;
65+
66+
if (data.Length == 0)
67+
return true; // Nothing to send
68+
69+
// Simulate sending data
70+
ChannelEvent?.Invoke(this, Channels.ChannelEvent.DataSent);
71+
return true; // Assume sending is always successful for this base class
72+
}
1873

1974
/// <summary>
2075
/// 向buffer中添加数据
@@ -34,7 +89,9 @@ public int AddData(Span<byte> data)
3489
data[..lengthToCopy].CopyTo(_buffer.AsSpan(_bufferLength));
3590
_bufferLength += lengthToCopy;
3691

37-
DataAddedEvent?.Invoke(this, lengthToCopy); // Trigger the event after data is added
92+
ChannelEvent?.Invoke(this, Channels.ChannelEvent.DataReceived); // Trigger the event after data is added
93+
if(_bufferLength == BufferSize)
94+
ChannelEvent?.Invoke(this, Channels.ChannelEvent.BufferFull); // Trigger the event if buffer is full
3895
return lengthToCopy;
3996
}
4097

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
namespace LLCOM.Models.Channels;
2+
3+
public enum ChannelEvent
4+
{
5+
Opened, // 通道已打开
6+
Closed, // 通道已关闭
7+
DataReceived, // 通道接收到数据
8+
DataSent, // 通道发送了数据
9+
Error, // 通道发生错误
10+
BufferFull, // 通道缓冲区已满
11+
}

0 commit comments

Comments
 (0)