[問題] 串列埠的委派接收要怎介面化

作者: chuinzong (阿榮)   2020-06-09 18:11:09
各位好:
目前可以執行的程式Serial Port的接收端程式
由於現在想要在介面中添加SerialDataReceivedEventHandler,
以方便後面做單元測試(就是要開介面)。
// 程式碼To Do部分
想詢問各位高手,介面開啟後
event SerialDataReceivedEventHandler PortDataReceived
要找尋什麼資料,現在用委派的Function要怎麼轉介面化?目前卡關在這邊。
public interface ISerialPort
{
void Open();
void Close();
void WriteLine(byte[] ByteData);
// To Do
// event SerialDataReceivedEventHandler PortDataReceived;
bool CheckOpenStaus();
}
public class DevicePort : ISerialPort
{
private SerialPort _serialPort;
private Queue<byte> _dataReceive;
public DevicePort()
{
_dataReceive = new Queue<byte>();
_serialPort = new SerialPort($"COM4", 19200);
_serialPort.DataReceived += new
SerialDataReceivedEventHandler(PortDataReceived);
}
public void Open()
{
_serialPort.Open();
}
public void Close()
{
_serialPort.Close();
}
public void WriteLine(byte[] ByteData)
{
_serialPort.Write(ByteData, 0, ByteData.Length);
_dataReceive.Clear();
}
private void PortDataReceived(object sender,
SerialDataReceivedEventArgs e)
{
byte[] buffer = new byte[4];
int length = (sender as SerialPort).Read(buffer, 0,
buffer.Length);
foreach (byte i in buffer)
_dataReceive.Enqueue(i);
}
public bool CheckOpenStaus()
{
return _serialPort.IsOpen;
}
}
以上
謝謝
作者: Litfal (Litfal)   2020-06-15 20:35:00
介面一樣宣告成event然後實作event把資料丟出去https://docs.microsoft.com/zh-tw/dotnet/csharp/language-reference/keywords/event

Links booklink

Contact Us: admin [ a t ] ucptt.com