Matomat/RFIDIdReader/RfidClass/RFIDReaderClass.cs

101 lines
2.9 KiB
C#
Raw Normal View History

2011-10-25 19:01:15 +02:00
using System;
using System.Diagnostics;
using System.Threading;
using System.IO.Ports;
using System.Text.RegularExpressions;
namespace RfidClass
{
public class RFIDReaderClass
{
private Thread t;
private SerialPort s;
private long id;
private bool _stop;
private Exception e;
public RFIDReaderClass(string com)
{
this.t = new Thread(this.reader);
s = new SerialPort(com, 9600, Parity.None, 8, StopBits.One);
}
private void reader()
{
while (!_stop)
{
Process r = new Process();
r.StartInfo.FileName = "librfid-tool.exe";
r.StartInfo.Arguments = "-s";
r.StartInfo.UseShellExecute = false;
r.StartInfo.RedirectStandardOutput = true;
r.StartInfo.RedirectStandardError = true;
try
{
r.Start();
}
catch (Exception exeption)
{
this.e = exeption;
return;
}
string a = r.StandardOutput.ReadToEnd();
string err = r.StandardError.ReadToEnd();
if (err.Contains("No OpenPCD found either"))
{
this.e = new Exception("No OpenPCD found");
return;
}
if (a.Contains("Layer 2 success") && a.Contains("Protocol success"))
{
string ids = a.Substring(a.IndexOf("):")+2,13);
ids = Regex.Replace(ids.Trim(), @"[^0-9a-fA-F]", "");
try
{
this.id = Int64.Parse(ids, System.Globalization.NumberStyles.HexNumber);
}
catch (Exception exeption)
{
this.e = exeption;
return;
}
}
Thread.Sleep(1000);
}
}
public long readKey()
{
this.t = new Thread(this.reader);
this.id = 0;
this._stop = false;
try
{
this.s.Open();
}
catch (Exception exeption)
{
//throw exeption;
}
this.t.Start();
while (!this.t.IsAlive) ;
while (this.t.IsAlive)
{
if (this.id != 0 || this.e != null)
{
this._stop = true;
}
}
if (this.e != null)
{
throw this.e;
}
return this.id;
}
public void abort()
{
this._stop = true;
}
}
}