@@ -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
0 commit comments