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, 115200, 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.e = null; this.t = new Thread(this.reader); this.id = 0; this._stop = false; try { if(!s.IsOpen) 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; } Thread.Sleep(10); } if (this.e != null) { throw this.e; } return this.id; } public void abort() { this._stop = true; this.reset(); this.s.Close(); } public void reset() { if (s.IsOpen) this.s.Write("9"); } } }