SerialPort를 사용하여 하드웨어와 인터페이스해야하는 C# 다중 스레드 응용 프로그램이 있습니다.serialport 다중 스레드 원치 않는 메시지
프로그램은 대부분 명령 응답 시퀀스이지만 하드웨어는 내부 오류로 인해 원치 않는 "RESET"메시지를 보낼 수 있습니다.이 메시지는 소프트웨어가 특정 값을 설정하는 일련의 명령을 보내서 다시 초기화해야합니다. (스레드에서)
더 이상의 스레드 내가 datareceived 이벤트에 응답을 확인하고 TryInitialize()와 TakeSampleNow에서 다른 스레드에 대한 잠금을 기다릴 수
public class ALComm
{
private readonly AutoLoaderManager _manager;
private readonly AutoResetEvent dataArrived = new AutoResetEvent(false);
private SerialPort _alPort;
private string _alResponse;
.... Code to init _alPort and attach datareceived event etc
public void TakeSampleNow()
{
if (Monitor.TryEnter(_alPort, 1000)) //let's wait a second
{
_manager.MessageList.Enqueue("Try sampling");
try
{
Send("Command1");
string response = Receive();
switch(response)
{
case "X": blah blah..
case "Y": blah blah..
}
Send("Command2");
string response = Receive();
while(response != "OK")
{
Send("Command3");
string response = Receive();
Send("Command2");
string response = Receive();
}
}
finally
{
Console.WriteLine("Releasing port");
//Thread.CurrentThread.Priority = ThreadPriority.Normal;
Monitor.Exit(_alPort);
}
else
{
_manager.MessageList.Enqueue("Port is busy!!!");
}
}
public string Receive()
{
string inString = null;
dataArrived.WaitOne(1000);
inString = _alResponse;
return inString;
}
private void AlPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
_alResponse = _alPort.ReadLine();
//if (_alResponse.ToUpper().Contains("RESET"))
//{
// _alState = AlState.Reset;
// TryInitialize();
//}
dataArrived.Set();
}
private void TryInitialize()
{
Monitor.Enter(_alPort); //lock so other threads do not access samplenow during initialization
try
{
string response;
Console.WriteLine("Initializing ... The AutoLoader");
_alPort.DiscardInBuffer();
Send("CommandX");
response = Receive();
--- blah blah
_alResponse = "";
}
finally
{
Monitor.Exit(_alPort);
}
}
TakeSampleNow()를 수행하려고 할 수 있습니다 잠금을 해제하려면 _alResponse에 "RESET"이 포함되어 있고 메서드에서 반환되는 경우 각 응답을 확인해야합니다. 어느 것이 더 복잡한가.
내가 더 잘할 수있는 방법에 대한 제안. 나는 그것이 상태 기계 일 수 있지만 그것을 개념화 할 수 없다고 생각한다.
원치 않는 응답은 큰 문제입니다. 특히 "RESET"이라고 말하면 "나 빠졌고 나는 일어날 수 없다"는 반응입니다. 당신이 노력해야 할 것은 결코 그런 반응을 얻지 않는 것입니다. 그게 장치이기 때문에 당신이 그것을 얻을 때 또는 재부 팅 기계. –
서비스를 다시 시작하고 싶습니다. 그러나 브라우저를 통해 사용자가 모니터링하는 Windows 서비스입니다. – cheedep