不确定如何处理SerialPort DataReceived。 方案
我有一个与设备通信的应用程序,该设备返回状态。这发生在不同的阶段EG
public enum ActionState { 开始, 进行中, 已完成 等等... }
现在,如果我要使用DataReceivedEventHandler,我怎么知道Method正在执行什么?例如Action1或Action2等......? 我还希望在从设备中获取内容时包含某种超时。 任何例子或建议?
public ActionState Action1
{
serialPort.write(myData);
string result=serialPort.ReadExisting());
//convertTo ActionState and return
return ConvertToActionState(result);
}
public ActionState Action2
{
serialPort.write(myData);
string result=serialPort.ReadExisting());
//convertTo ActionState and return
return ConvertToActionState(result);
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//How can I use this to detect which method is firing and set the actionState Enum accordingly?
}
private ActionState(string result)
{
if(result==1)
return ActionState.Started;
else if (result==2)
return ActionState.Completed
etc...
}
答案 0 :(得分:1)
当有一些数据要读取时,事件DataReceived由串口触发,甚至收到Eof字符。 Tipicaly此事件用于获取数据并使用它或存储启动进程。例如,serialport读取条形码并在数据库中找到它。
private static void DataReceivedHandler(
object sender,
SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
if(!String.IsEmptyOrNull( indata))
{
AddProductToCart(indata);
}
}