현재 SerialPort
클래스를 사용하고 있지만 카드 판독기가 물리적으로 연결 해제되었는지 확인하기 위해 내 WPF 앱 내에서 포트 (존재 / 없음) 상태를 확인하고 싶습니다.
.NET에서 할 수있는 방법이 있습니까?
내가 사용하는 코드는 다음과 같습니다.
public class Proxi
{
public string proxicard = "";
public DateTime readingtime = DateTime.MinValue;
public bool Ready = false;
public bool Correct = false;
public bool COMreader = false;
public bool COMAccess = false;
public bool COMDataCorrect = false;
public MemoryStream COMdata = new MemoryStream();
public SerialPort port;
// Public Event to allow other classes to subscribe to.
public event EventHandler CardDetected = delegate { };
public Proxi(string portname, bool isCOM)
{
try
{
port = new SerialPort(portname, 9600, Parity.None, 8, StopBits.One)
{
DtrEnable = true,
RtsEnable = true
};
port.Open();
port.DataReceived += new SerialDataReceivedEventHandler(Port_DataReceived);
Ready = true;
COMreader = isCOM;
}
catch
{
proxicard = "There is no port " + portname;
}
}
private void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort serialPort = (SerialPort)sender;
byte[] buffer = new byte[serialPort.BytesToRead];
serialPort.Read(buffer, 0, buffer.Length);
proxicard = "";
if ((int)buffer[0] == 58 && !COMreader)
{
for (int index = 1; index < buffer.Length; ++index)
proxicard = proxicard + ((char)buffer[index]).ToString();
if (proxicard.Length >= 12)
{
byte[] numArray = ConvertHexToByte(proxicard, 6);
byte num = 0;
for (int index = 0; index < numArray.Length - 1; ++index)
num += numArray[index];
Correct = (int)(byte)((uint)~num + 1U) == (int)numArray[numArray.Length - 1];
readingtime = DateTime.Now;
}
else
Correct = false;
}
if ((int)buffer[0] == 1 && COMreader)
{
COMdata = new MemoryStream();
COMAccess = true;
if (buffer.Length > 1)
COMdata.Write(buffer, 1, buffer.Length - 1);
}
if (!COMAccess || !COMreader || COMdata.Length < 7L)
{
// Raise Event, which triggers all method subscribed to it!
CardDetected(this, new EventArgs());
return;
}
MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(new byte[1] { (byte)1 }, 0, 1);
for (int offset = (int)COMdata.Length - 2; offset >= 0; --offset)
memoryStream.Write(COMdata.ToArray(), offset, 1);
Correct = (int)CRC.CRC8(memoryStream.ToArray(), (int)memoryStream.Length) == (int)COMdata.ToArray()[COMdata.Length - 1L];
proxicard = Proxi.GetRecordHEXBytes(COMdata.ToArray(), 1, 5);
COMdata = new MemoryStream();
COMAccess = false;
// Raise Event, which triggers all method subscribed to it!
CardDetected(this, new EventArgs());
}
public static string GetRecordHEXBytes(byte[] data, int position, int length)
{
if (position + length > data.Length)
return "";
string str = "";
for (int index = 0; index < length; ++index)
{
byte num = data[position + index];
str += num.ToString("X2");
}
return str;
}
public byte[] ConvertHexToByte(string HexValue, int length)
{
byte[] numArray = new byte[length];
for (int index = 0; index < length; ++index)
numArray[index] = (byte)Convert.ToChar(Convert.ToUInt32(HexValue.Substring(index * 2, 2), 16));
return numArray;
}
public void Close()
{
port.Close();
}
}
리더가 연결된 것으로 간주하기 위해 충족해야 할 두 가지 조건이 있습니다.
조건 1 만 충족되는 경우 판독기 존재 감지에 전혀 의미가 없음을 명심하십시오. 사용자가 통신 포트를 항상 존재하는 포트 번호로 설정하면 (예 : USB가 아닌 장치) 연결된 포트가 없어도 해당 포트를 열 수 있습니다.
그리고 통신 프로토콜에 따라 리더가 연결되어 있어도 데이터가 전혀 수신되지 않을 수 있으므로 Receive 이벤트 만 처리하는 것으로는 충분하지 않을 수 있습니다.
연속 감지를 위해 정기적으로 직렬 포트를 열고 리더와의 테스트 통신을 수행하는 스레드를 만들고 싶을 것입니다. 이 모든 것이 성공하면 IsConnected
리더가 연결되었음을 나타내는 모델 클래스의 일부 bool 변수 (예 :)를 변경하면 됩니다. 보기 쪽에서는 일부 컨트롤 콘텐츠를 IsConnected
플래그에 바인딩해야합니다 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다