static void Main(string[] args) { // Program setup if (1 > args.Length) { Usage(); } for (int nextarg = 1; nextarg < args.Length; nextarg++) { string arg = args[nextarg]; if (arg.Equals("--ant")) { if (null != antennaList) { Console.WriteLine("Duplicate argument: --ant specified more than once"); Usage(); } antennaList = ParseAntennaList(args, nextarg); nextarg++; } else { Console.WriteLine("Argument {0}:\"{1}\" is not recognized", nextarg, arg); Usage(); } } try { // Create Reader object, connecting to physical device. // Wrap reader in a "using" block to get automatic // reader shutdown (using IDisposable interface). using (r = Reader.Create(args[0])) { //Uncomment this line to add default transport listener. //r.Transport += r.SimpleTransportListener; r.Connect(); if (Reader.Region.UNSPEC == (Reader.Region)r.ParamGet("/reader/region/id")) { Reader.Region[] supportedRegions = (Reader.Region[])r.ParamGet("/reader/region/supportedRegions"); if (supportedRegions.Length < 1) { throw new FAULT_INVALID_REGION_Exception(); } r.ParamSet("/reader/region/id", supportedRegions[0]); } string model = r.ParamGet("/reader/version/model").ToString(); if ((model.Equals("M6e Micro") || model.Equals("M6e Nano") || model.Equals("Sargas")) && antennaList == null) { Console.WriteLine("Module doesn't has antenna detection support please provide antenna list"); Usage(); } // Create a simplereadplan which uses the antenna list created above SimpleReadPlan plan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, null, null, 1000); // Set the created readplan r.ParamSet("/reader/read/plan", plan); //Use first antenna for operation if (antennaList != null) { r.ParamSet("/reader/tagop/antenna", antennaList[0]); } ushort[] Key0 = new ushort[] { 0x0123, 0x4567, 0x89AB, 0xCDEF, 0x0123, 0x4567, 0x89AB, 0xCDEF }; ushort[] Key1 = new ushort[] { 0x1122, 0x3344, 0x5566, 0x7788, 0x1122, 0x3344, 0x5566, 0x7788 }; ushort[] Ichallenge = new ushort[] { 0x0123, 0x4567, 0x89AB, 0xCDEF, 0xABCD }; Gen2.Select filter = new Gen2.Select(false, Gen2.Bank.EPC, 32, 96, new byte[] { 0xDE, 0xAD, 0xBE, 0xEF, 0xDE, 0xAD, 0xBE, 0xEF, 0xDE, 0xAD, 0xBE, 0xEF }); bool SendRawData = true; bool _isNMV2DTag = false; byte[] Response; Gen2.NXP.AES.Tam1Authentication tam1Auth; Gen2.NXP.AES.Tam2Authentication tam2Auth; //Uncomment this to enable Authenticate with TAM1 with key0 for NXPUCODE AES tag tam1Auth = new Gen2.NXP.AES.Tam1Authentication(Gen2.NXP.AES.KeyId.KEY0, Key0, Ichallenge, SendRawData); Gen2.NXP.AES.Authenticate auth = new Gen2.NXP.AES.Authenticate(tam1Auth); Response = (byte[])r.ExecuteTagOp(auth, null); if (SendRawData) { byte[] Challenge = DecryptIchallenge(Response, ByteConv.ConvertFromUshortArray(Key0)); Array.Copy(Challenge, 6, Challenge, 0, 10); Array.Resize(ref Challenge, 10); Console.WriteLine("Returned Ichallenge:" + ByteFormat.ToHex(Challenge, "", " ")); } //Uncomment this to enable Authenticate with TAM1 with Key1 //tam1Auth = new Gen2.NXP.AES.Tam1Authentication(Gen2.NXP.AES.KeyId.KEY1, Key1, Ichallenge, SendRawData); //Gen2.NXP.AES.Authenticate tam1AuthKey1 = new Gen2.NXP.AES.Authenticate(tam1Auth); //Response = (byte[])r.ExecuteTagOp(tam1AuthKey1, null); //if (SendRawData) //{ // byte[] Challenge = DecryptIchallenge(Response, ByteConv.ConvertFromUshortArray(Key1)); // Array.Copy(Challenge, 6, Challenge, 0, 10); // Array.Resize(ref Challenge, 10); // Console.WriteLine("Returned Ichallenge:" + ByteFormat.ToHex(Challenge, "", " ")); //} //Uncomment this to enable Authenticate with TAM2 with key1 //ushort Offset = 0; //ushort BlockCount = 1; ////supported protMode value is 1 for NXPUCODE AES //ushort ProtMode = 1; //tam2Auth = new Gen2.NXP.AES.Tam2Authentication(Gen2.NXP.AES.KeyId.KEY1, Key1, Ichallenge, Gen2.NXP.AES.Profile.EPC, // Offset, BlockCount, ProtMode, SendRawData); //Gen2.NXP.AES.Authenticate tam2AuthKey1 = new Gen2.NXP.AES.Authenticate(tam2Auth); //Response = (byte[])r.ExecuteTagOp(tam2AuthKey1, null); //if (SendRawData) //{ // byte[] IV = new byte[16]; // byte[] CipherData = new byte[16]; // Array.Copy(Response, 0, IV, 0, 16); // Array.Copy(Response, 16, CipherData, 0, 16); // Console.WriteLine("Custom Data: " + DecryptCustomData(CipherData, ByteConv.ConvertFromUshortArray(Key1), (byte[])IV.Clone())); // byte[] Challenge = DecryptIchallenge(IV, ByteConv.ConvertFromUshortArray(Key1)); // Array.Copy(Challenge, 6, Challenge, 0, 10); // Array.Resize(ref Challenge, 10); // Console.WriteLine("Returned Ichallenge:" + ByteFormat.ToHex(Challenge, "", " ")); //} //else //{ // Console.WriteLine("Data: " + ByteFormat.ToHex(Response, "", " ")); //} // Embedded tag operations #region EmbeddedTagOperations { //Uncomment this to execute embedded tagop for TAM1 Authentication using Key0 //tam1Auth = new Gen2.NXP.AES.Tam1Authentication(Gen2.NXP.AES.KeyId.KEY0, Key0, Ichallenge, SendRawData); //Gen2.NXP.AES.Authenticate embeddedauth = new Gen2.NXP.AES.Authenticate(tam1Auth); //Response = performEmbeddedOperation(null, embeddedauth); //if (SendRawData) //{ // byte[] Challenge = DecryptIchallenge(Response, ByteConv.ConvertFromUshortArray(Key0)); // Array.Copy(Challenge, 6, Challenge, 0, 10); // Array.Resize(ref Challenge, 10); // Console.WriteLine("Returned Ichallenge:" + ByteFormat.ToHex(Challenge, "", " ")); //} //Uncomment this to execute embedded tagop for Authenticate with TAM1 using Key1 //tam1Auth = new Gen2.NXP.AES.Tam1Authentication(Gen2.NXP.AES.KeyId.KEY1, Key1, Ichallenge, SendRawData); //Gen2.NXP.AES.Authenticate embeddedtam1AuthKey1 = new Gen2.NXP.AES.Authenticate(tam1Auth); //Response = performEmbeddedOperation(null, embeddedtam1AuthKey1); //if (SendRawData) //{ // byte[] Challenge = DecryptIchallenge(Response, ByteConv.ConvertFromUshortArray(Key1)); // Array.Copy(Challenge, 6, Challenge, 0, 10); // Array.Resize(ref Challenge, 10); // Console.WriteLine("Returned Ichallenge:" + ByteFormat.ToHex(Challenge, "", " ")); //} //Uncomment this to execute embedded tagop for Authenticate with TAM2 with key1 //ushort EmbeddedOffset = 0; //ushort EmbeddedBlockCount = 1; ////supported protMode value is 1 for NXPUCODE AES //ushort EmbeddedProtMode = 1; //tam2Auth = new Gen2.NXP.AES.Tam2Authentication(Gen2.NXP.AES.KeyId.KEY1, Key1, Ichallenge, Gen2.NXP.AES.Profile.EPC, // EmbeddedOffset, EmbeddedBlockCount, EmbeddedProtMode, SendRawData); //Gen2.NXP.AES.Authenticate embeddedtam2AuthKey1 = new Gen2.NXP.AES.Authenticate(tam2Auth); //Response = performEmbeddedOperation(null, embeddedtam2AuthKey1); //if (SendRawData) //{ // byte[] IV = new byte[16]; // byte[] CipherData = new byte[16]; // Array.Copy(Response, 0, IV, 0, 16); // Array.Copy(Response, 16, CipherData, 0, 16); // Console.WriteLine("Custom Data: " + DecryptCustomData(CipherData, ByteConv.ConvertFromUshortArray(Key1), (byte[])IV.Clone())); // byte[] Challenge = DecryptIchallenge(IV, ByteConv.ConvertFromUshortArray(Key1)); // Array.Copy(Challenge, 6, Challenge, 0, 10); // Array.Resize(ref Challenge, 10); // Console.WriteLine("Returned Ichallenge:" + ByteFormat.ToHex(Challenge, "", " ")); //} //else //{ // Console.WriteLine("Data: " + ByteFormat.ToHex(Response, "", " ")); //} } #endregion EmbeddedTagOperations //Enable flag _isNMV2DTag for TAM1/TAM2 Authentication with KEY0 for NMV2D Tag if (_isNMV2DTag) { // NMV2D tag only supports KEY0 // Uncomment this to enable TAM1 Authentication with KEY0 ushort[] Key0_NMV2D = new ushort[] { 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000 }; //tam1Auth = new Gen2.NXP.AES.Tam1Authentication(Gen2.NXP.AES.KeyId.KEY0, Key0_NMV2D, Ichallenge, SendRawData); //Gen2.NXP.AES.Authenticate tam1AuthKey0 = new Gen2.NXP.AES.Authenticate(tam1Auth); //Response = (byte[])r.ExecuteTagOp(tam1AuthKey0, null); //if (SendRawData) //{ // byte[] Challenge = DecryptIchallenge(Response, ByteConv.ConvertFromUshortArray(Key0_NMV2D)); // Array.Copy(Challenge, 6, Challenge, 0, 10); // Array.Resize(ref Challenge, 10); // Console.WriteLine("Returned Ichallenge:" + ByteFormat.ToHex(Challenge, "", " ")); //} //else //{ // Console.WriteLine("Data: " + ByteFormat.ToHex(Response, "", " ")); //} //TAM2 Authentication with KEY0 ushort offset = 0; ushort blockCount = 1; //supported protMode values are 0x00, 0x01, 0x02, 0x03 ushort protMode = 0; tam2Auth = new Gen2.NXP.AES.Tam2Authentication(Gen2.NXP.AES.KeyId.KEY0, Key0_NMV2D, Ichallenge, Gen2.NXP.AES.Profile.EPC, offset, blockCount, protMode, SendRawData); Gen2.NXP.AES.Authenticate tam2AuthKey0 = new Gen2.NXP.AES.Authenticate(tam2Auth); Response = (byte[])r.ExecuteTagOp(tam2AuthKey0, null); if (SendRawData) { byte[] IV = new byte[16]; byte[] CipherData = new byte[16]; Array.Copy(Response, 0, IV, 0, 16); Array.Copy(Response, 16, CipherData, 0, 16); if (protMode == 1 || protMode == 3) { Console.WriteLine("Custom Data: " + DecryptCustomData(CipherData, ByteConv.ConvertFromUshortArray(Key0_NMV2D), (byte[])IV.Clone())); } else { Console.WriteLine("Custom Data: " + ByteFormat.ToHex(CipherData, "", " ")); } byte[] Challenge = DecryptIchallenge(IV, ByteConv.ConvertFromUshortArray(Key0_NMV2D)); Array.Copy(Challenge, 6, Challenge, 0, 10); Array.Resize(ref Challenge, 10); Console.WriteLine("Returned Ichallenge:" + ByteFormat.ToHex(Challenge, "", " ")); } else { Console.WriteLine("Data: " + ByteFormat.ToHex(Response, "", " ")); } } } } catch (ReaderException re) { Console.WriteLine("Error: " + re.Message); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
private void btnConnect_Click(object sender, EventArgs e) { try { if (btnConnect.Text.Equals("Connect")) { String model = string.Empty; string readeruri = comboBox1.SelectedItem.ToString(); objReader = Reader.Create(string.Concat("eapi:///", readeruri)); objReader.Connect(); model = (string)objReader.ParamGet("/reader/version/model"); Reader.Region regionToSet = (Reader.Region)objReader.ParamGet("/reader/region/id"); if (objReader is SerialReader) { if (regionToSet == Reader.Region.UNSPEC) { if (model.Equals("M6e PRC")) { regionToSet = Reader.Region.PRC; } else { regionToSet = Reader.Region.NA; } } } objReader.ParamSet("/reader/region/id", regionToSet); if (model.Equals("M6e Micro")) { SimpleReadPlan plan = new SimpleReadPlan(new int[] { 1, 2 }, TagProtocol.GEN2); objReader.ParamSet("/reader/read/plan", plan); } btnConnect.Text = "Disconnect"; btnReadOnce.Enabled = true; comboBox1.Enabled = false; btnRefresh.Enabled = false; lblReadTimeout.Enabled = true; tbxReadTimeout.Enabled = true; UpdateGrid(); } else { objReader.Destroy(); objReader = null; btnReadOnce.Enabled = false; comboBox1.Enabled = true; lblReadTimeout.Enabled = false; tbxReadTimeout.Enabled = false; btnConnect.Text = "Connect"; btnRefresh.Enabled = true; lblTotalTagCount.Text = "0"; lblUniqueTagCount.Text = "0"; } } catch (IOException ex) { MessageBox.Show(ex.Message, "Error"); objReader.Destroy(); objReader = null; btnReadOnce.Enabled = false; btnConnect.Text = "Connect"; } catch (Exception ex) { MessageBox.Show(ex.Message, "Reader message"); } }
public MainWindow() { InitializeComponent(); if (fclient != null) { //MessageBox.Show("The connection to database has been successfully established"); } FirebaseConfig fconfig = new FirebaseConfig { AuthSecret = "ihUcWjzjav9Y4ZxY9oqh3xdxC7u9bE1oXT1uGeRl", BasePath = "https://hightemperturelocatingsystem.firebaseio.com/" }; fclient = new FirebaseClient(fconfig); try { reader.Connect(); } catch (IOException e) { Console.WriteLine(e.Message); return; } string[] functionList = reader.ParamList(); Reader.Region[] regions = (Reader.Region[])reader.ParamGet("/reader/region/supportedRegions"); reader.ParamSet(functionList[51], Reader.Region.TW); reader.ParamSet(functionList[40], 100); //max 2700 (27dBm) //reading delay of 1s int timeout = 1000; //select the antenna, protocol int[] antennaList = null; string str = "1,1"; antennaList = Array.ConvertAll(str.Split(','), int.Parse); TagProtocol protocol = TagProtocol.GEN2; SimpleReadPlan simpleplan = new SimpleReadPlan(antennaList, protocol, null, null, timeout); reader.ParamSet("/reader/read/plan", simpleplan); //reader.ParamSet("/reader/read/plan", 2700); MessageBox.Show("The antenna has been successfully connected to the PC"); positioning(0, 0, 0); //reader.StartReading(); //reader.TagRead += OnTagRead; }
static void Main(string[] args) { // Program setup if (1 > args.Length) { Usage(); } int[] antennaList = null; for (int nextarg = 1; nextarg < args.Length; nextarg++) { string arg = args[nextarg]; if (arg.Equals("--ant")) { if (null != antennaList) { Console.WriteLine("Duplicate argument: --ant specified more than once"); Usage(); } antennaList = ParseAntennaList(args, nextarg); nextarg++; } else { Console.WriteLine("Argument {0}:\"{1}\" is not recognized", nextarg, arg); Usage(); } } try { // Create Reader object, connecting to physical device. // Wrap reader in a "using" block to get automatic // reader shutdown (using IDisposable interface). using (Reader r = Reader.Create(args[0])) { //Uncomment this line to add default transport listener. //r.Transport += r.SimpleTransportListener; r.Connect(); if (Reader.Region.UNSPEC == (Reader.Region)r.ParamGet("/reader/region/id")) { r.ParamSet("/reader/region/id", Reader.Region.NA); } string model = r.ParamGet("/reader/version/model").ToString(); if ((model.Equals("M6e Micro") || model.Equals("M6e Nano") || model.Equals("Sargas")) && antennaList == null) { Console.WriteLine("Module doesn't has antenna detection support please provide antenna list"); Usage(); } if ((model.Equals("M6e Micro") || model.Equals("M6e Micro USBPro") || model.Equals("M6e Micro USB"))) { r.ParamSet("/reader/antenna/checkPort", true); } // Create a simplereadplan which uses the antenna list created above SimpleReadPlan plan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, null, null, 1000); // Set the created readplan r.ParamSet("/reader/read/plan", plan); // Request all reader stats r.ParamSet("/reader/stats/enable", Reader.Stat.StatsFlag.ALL); Console.WriteLine("Get requested reader stats : " + r.ParamGet("/reader/stats/enable").ToString()); TagReadData[] tagReads; Reader.Stat.Values objRdrStats = null; #region Perform sync read for (int iteration = 1; iteration <= 4; iteration++) { Console.WriteLine("Iteration: " + iteration); Console.WriteLine("Performing the search operation for 1 sec"); tagReads = null; objRdrStats = null; // Read tags tagReads = r.Read(1000); Console.WriteLine("Search is completed. Get the reader stats"); objRdrStats = (Reader.Stat.Values)r.ParamGet("/reader/stats"); Console.WriteLine(objRdrStats.ToString()); Console.WriteLine(); Int16[][] objAntennaReturnLoss = (Int16[][])r.ParamGet("/reader/antenna/returnLoss"); Console.WriteLine("Antenna Return Loss"); foreach (short[] antennaLoss in objAntennaReturnLoss) { Console.WriteLine(" Antenna {0:D} | {1:D}", antennaLoss[0], antennaLoss[1]); } Console.WriteLine(); } #endregion Perform sync read #region Perform async read Console.WriteLine(); Console.WriteLine("Performing async read for 1 sec"); #region Create and add listeners // Create and add tag listener r.TagRead += delegate(Object sender, TagReadDataEventArgs e) { Console.WriteLine("Background read: " + e.TagReadData); }; // Create and add read exception listener r.ReadException += r_ReadException; // Add reader stats listener r.StatsListener += r_StatsListener; #endregion Create and add listeners // Search for tags in the background r.StartReading(); Console.WriteLine("\r\n<Do other work here>\r\n"); Thread.Sleep(500); Console.WriteLine("\r\n<Do other work here>\r\n"); Thread.Sleep(500); r.StopReading(); #endregion Perform async read } } catch (ReaderException re) { Console.WriteLine("Error: " + re.Message); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
static void Main(string[] args) { // Program setup if (1 > args.Length) { Usage(); } for (int nextarg = 1; nextarg < args.Length; nextarg++) { string arg = args[nextarg]; if (arg.Equals("--ant")) { if (null != antennaList) { Console.WriteLine("Duplicate argument: --ant specified more than once"); Usage(); } antennaList = ParseAntennaList(args, nextarg); nextarg++; } else { Console.WriteLine("Argument {0}:\"{1}\" is not recognized", nextarg, arg); Usage(); } } try { // Create Reader object, connecting to physical device. // Wrap reader in a "using" block to get automatic // reader shutdown (using IDisposable interface). using (Reader r = Reader.Create(args[0])) { //Uncomment this line to add default transport listener. //r.Transport += r.SimpleTransportListener; r.Connect(); if (Reader.Region.UNSPEC == (Reader.Region)r.ParamGet("/reader/region/id")) { Reader.Region[] supportedRegions = (Reader.Region[])r.ParamGet("/reader/region/supportedRegions"); if (supportedRegions.Length < 1) { throw new FAULT_INVALID_REGION_Exception(); } r.ParamSet("/reader/region/id", supportedRegions[0]); } if (r.isAntDetectEnabled(antennaList)) { Console.WriteLine("Module doesn't has antenna detection support please provide antenna list"); Usage(); } // Create a simplereadplan which uses the antenna list created above SimpleReadPlan plan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, null, null, 1000); // Set the created readplan r.ParamSet("/reader/read/plan", plan); //Use first antenna for operation if (antennaList != null) { r.ParamSet("/reader/tagop/antenna", antennaList[0]); } DenatranIAVCustomTagOperations denatranIavCustomTagOp = new DenatranIAVCustomTagOperations(); denatranIavCustomTagOp.reader = r; #region EnablingGEN2DenatranIAVTagOps // Serial reader condition is bypassed to add support for Network readers. Console.WriteLine(String.Format("Get Protocol Extension : {0}", r.ParamGet("/reader/gen2/protocolExtension"))); Console.WriteLine(); #endregion #region Initialsettings //Initial settings //Set tagencoding Console.WriteLine(String.Format("Get tagencoding : {0}", r.ParamGet("/reader/gen2/tagEncoding"))); Console.WriteLine("Set tagencoding"); r.ParamSet("/reader/gen2/tagEncoding", Gen2.TagEncoding.FM0); Console.WriteLine(String.Format("Get tagencoding : {0}", r.ParamGet("/reader/gen2/tagEncoding"))); Console.WriteLine(); //Set BLF 320KHZ Console.WriteLine(String.Format("Get BLF : {0}", r.ParamGet("/reader/gen2/blf"))); Console.WriteLine("Set BLF to 320KHZ"); r.ParamSet("/reader/gen2/blf", Gen2.LinkFrequency.LINK320KHZ); Console.WriteLine(String.Format("Get BLF : {0}", r.ParamGet("/reader/gen2/blf"))); Console.WriteLine(); //Set tari Console.WriteLine(String.Format("Get tari : {0}", r.ParamGet("/reader/gen2/tari"))); Console.WriteLine("Set tari"); r.ParamSet("/reader/gen2/tari", Gen2.Tari.TARI_6_25US); Console.WriteLine(String.Format("Get tari : {0}", r.ParamGet("/reader/gen2/tari"))); Console.WriteLine(); //Set session Console.WriteLine(String.Format("Get session : {0}", r.ParamGet("/reader/gen2/session"))); Console.WriteLine("Set session"); r.ParamSet("/reader/gen2/session", Gen2.Session.S0); Console.WriteLine(String.Format("Get session : {0}", r.ParamGet("/reader/gen2/session"))); Console.WriteLine(); //Set target Console.WriteLine(String.Format("Get target : {0}", r.ParamGet("/reader/gen2/target"))); Console.WriteLine("Set target"); r.ParamSet("/reader/gen2/target", Gen2.Target.AB); Console.WriteLine(String.Format("Get target : {0}", r.ParamGet("/reader/gen2/target"))); Console.WriteLine(); //Set Q Console.WriteLine(String.Format("Get Q : {0}", r.ParamGet("/reader/gen2/q"))); Console.WriteLine("Set Q"); Gen2.StaticQ staticQ = new Gen2.StaticQ(0); r.ParamSet("/reader/gen2/q", staticQ); Console.WriteLine(String.Format("Get Q : {0}", r.ParamGet("/reader/gen2/q"))); Console.WriteLine(); #endregion Initialsettings TagReadData[] tagReads; // Read tagReads = r.Read(500); if (tagReads.Length == 0) { Console.WriteLine("Error : No tags found"); } else { #region Filter initialization //Gen2Select filter Gen2.Select selectfilter = new Gen2.Select(false, Gen2.Bank.EPC, 32, (ushort)(tagReads[0].Epc.Length * 8), ByteFormat.FromHex(tagReads[0].EpcString)); //TagData filter TagFilter tagdataFilter = new TagData(ByteFormat.FromHex(tagReads[0].EpcString)); #endregion Filter initialization #region Tag Operation Initialization byte payload = 0x80; byte OBUAuthID = 0x00; byte OBUAuthFullPass = 0x01; byte OBUAuthFullPass1 = 0x02; ushort readptr = 0xFFFF; ushort wordAddress = 0xFFFF; ushort word = 0xFFFF; //Read ptr for readsec tagop ushort readSecReadPtr = 0x0000; //Set the tag Identification and writeCredentials Gen2.DenatranIAVWriteCredential writeCredential = new Gen2.DenatranIAVWriteCredential (new byte [] { 0x80, 0x10, 0x00, 0x12, 0x34, 0xAD, 0xBD, 0xC0 }, new byte [] { 0xDE, 0xAD, 0xBE, 0xEF, 0xDE, 0xAD, 0xBE, 0xEF, 0xDE, 0xAD, 0xBE, 0xEF, 0xDE, 0xAD, 0xBE, 0xEF }); //Set the data and writeCredentials for WriteSec Gen2.DenatranIAVWriteSecCredential writeSecCredential = new Gen2.DenatranIAVWriteSecCredential (new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66 }, new byte[] { 0x35, 0x49, 0x87, 0xbd, 0xb2, 0xab, 0xd2, 0x7c, 0x2e, 0x34, 0x78, 0x8b, 0xf2, 0xf7, 0x0b, 0xa2 }); //IAVDenatran secure tag operation - ActivateSecureMode denatranIavCustomTagOp.tagOpActivateSecureMode = new Gen2.Denatran.IAV.ActivateSecureMode(payload); //IAVDenatran secure tag operation - AuthenticateOBU denatranIavCustomTagOp.tagOpAuthenticateOBU = new Gen2.Denatran.IAV.AuthenticateOBU(payload); //IAVDenatran secure tag operation - ActivateSiniavMode denatranIavCustomTagOp.tagOpActivateSiniavMode = new Gen2.Denatran.IAV.ActivateSiniavMode(0x81, new byte[] { 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef }); //IAVDenatran secure tag operation - OBUAuthFullPass1 denatranIavCustomTagOp.tagOpOBUAuthFullPass1 = new Gen2.Denatran.IAV.OBUAuthFullPass1(payload); //IAVDenatran secure tag operation - OBUAuthFullPass2 denatranIavCustomTagOp.tagOpOBUAuthFullPass2 = new Gen2.Denatran.IAV.OBUAuthFullPass2(payload); //IAVDenatran secure tag operation - OBUAuthID denatranIavCustomTagOp.tagOpOBUAuthID = new Gen2.Denatran.IAV.OBUAuthID(payload); //IAVDenatran secure tag operation - OBUReadFromMemMap denatranIavCustomTagOp.tagOpOBUReadFromMemMap = new Gen2.Denatran.IAV.OBUReadFromMemMap (payload, readptr); //IAVDenatran secure tag operation - OBUWriteToMemMap denatranIavCustomTagOp.tagOpOBUWriteToMemMap = new Gen2.Denatran.IAV.OBUWriteToMemMap (payload, wordAddress, word, writeCredential); //IAVDenatran secure tag operation - OBUAuthFullPass denatranIavCustomTagOp.tagOpOBUAuthFullPass = new Gen2.Denatran.IAV.OBUAuthFullPass(payload); //IAVDenatran secure tag operation - GetTokenId denatranIavCustomTagOp.tagOpGetTokenId = new Gen2.Denatran.IAV.GetTokenId(); //IAVDenatran secure tag operation - ReadSec denatranIavCustomTagOp.tagOpReadSec = new Gen2.Denatran.IAV.ReadSec (payload, readSecReadPtr); //IAVDenatran secure tag operation - WriteSec denatranIavCustomTagOp.tagOpWriteSec = new Gen2.Denatran.IAV.WriteSec (payload, writeSecCredential); // For G0 Tag denatranIavCustomTagOp.tagOpG0PAOBUAuth = new Gen2.Denatran.IAV.G0PAOBUAuth((byte)(payload | OBUAuthID)); denatranIavCustomTagOp.tagOpG0PAOBUAuthFullPass = new Gen2.Denatran.IAV.G0PAOBUAuth((byte)(payload | OBUAuthFullPass)); denatranIavCustomTagOp.tagOpG0PAOBUAuthFullPass1 = new Gen2.Denatran.IAV.G0PAOBUAuth((byte)(payload | OBUAuthFullPass1)); //Uncomment this for PA tag //denatranIavCustomTagOp.tagOpG0PAOBUAuth = new Gen2.Denatran.IAV.G0PAOBUAuth(payload); #endregion Tag Operation Initialization #region Standalonetagoperations //Standalone tagop Console.WriteLine("Standalone tagop without filter : "); Console.WriteLine(); denatranIavCustomTagOp.ExecuteTagOpFilter(null); Console.WriteLine("Standalone tagop with tagdata filter : "); Console.WriteLine(); denatranIavCustomTagOp.ExecuteTagOpFilter(tagdataFilter); Console.WriteLine("Standalone tagop with gen2Select filter : "); Console.WriteLine(); denatranIavCustomTagOp.ExecuteTagOpFilter(selectfilter); #endregion Standalonetagoperations #region Embeddedtagoperations //Embedded tagop Console.WriteLine("Embedded tagop without filter and fastsearch : "); Console.WriteLine(); denatranIavCustomTagOp.EmbeddedTagOpFilter(null, false); Console.WriteLine("Embedded tagop with tagdata filter and fastsearch enabled : "); Console.WriteLine(); denatranIavCustomTagOp.EmbeddedTagOpFilter(tagdataFilter, true); Console.WriteLine("Embedded tagop with gen2select filter and fast search enabled : "); Console.WriteLine(); denatranIavCustomTagOp.EmbeddedTagOpFilter(selectfilter, true); #endregion Embeddedtagoperations } } } catch (ReaderException re) { Console.WriteLine("Error: " + re.Message); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
private void ReadtheTags() { try { // Make sure reader is connected ReadMgr.GetReader(); System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); if (btnStartReads.Text == "Start Reads") { Cursor.Current = Cursors.WaitCursor; try { //Check the battery power level if (CoreDLL.GetSystemPowerStatusEx(status, false) == 1) { if (status.BatteryLifePercent <= 5) { if (status.ACLineStatus == 0) { MessageBox.Show("Battery level is low to read tags"); return; } } } properties["isreading"] = "yes"; Utilities.SaveConfigurations(properties); //disable read power coverage tbTXPower.Enabled = false; ReadMgr.GetReader().ParamSet("/reader/transportTimeout", 2000); int powerLevel = Convert.ToInt32(properties["readpower"]); ReadMgr.GetReader().ParamSet("/reader/radio/readPower", powerLevel); Utilities.SwitchRegion(properties["region"]); ReadMgr.GetReader().ParamSet("/reader/antenna/txRxMap", new int[][] { new int[] { 1, 1, 1 } }); ant.Add(1); SimpleReadPlan plan = new SimpleReadPlan(ant.ToArray(), TagProtocol.GEN2); ReadMgr.GetReader().ParamSet("/reader/read/plan", plan); //int readPower = Convert.ToInt32(properties["readpower"].ToString()) * 100; //tbTXPower.Value = (readPower - 1000) / 50; tmrBackLightControl.Enabled = true; miGoToMain.Enabled = false; //set properties ReadMgr.GetReader().ParamSet("/reader/read/asyncOffTime", 50); ReadMgr.GetReader().ParamSet("/reader/powerMode", Reader.PowerMode.FULL); //set the tag population settings ReadMgr.GetReader().ParamSet("/reader/gen2/target", Gen2.Target.A);//default target string tagPopulation = properties["tagpopulation"]; switch (tagPopulation) { case "small": ReadMgr.GetReader().ParamSet("/reader/gen2/q", new Gen2.StaticQ(2)); ReadMgr.GetReader().ParamSet("/reader/gen2/session", Gen2.Session.S0); ReadMgr.GetReader().ParamSet("/reader/gen2/tagEncoding", Gen2.TagEncoding.M4); break; case "medium": ReadMgr.GetReader().ParamSet("/reader/gen2/q", new Gen2.StaticQ(4)); ReadMgr.GetReader().ParamSet("/reader/gen2/session", Gen2.Session.S1); ReadMgr.GetReader().ParamSet("/reader/gen2/tagEncoding", Gen2.TagEncoding.M4); break; case "large": ReadMgr.GetReader().ParamSet("/reader/gen2/q", new Gen2.StaticQ(6)); ReadMgr.GetReader().ParamSet("/reader/gen2/session", Gen2.Session.S1); ReadMgr.GetReader().ParamSet("/reader/gen2/tagEncoding", Gen2.TagEncoding.M2); break; default: break; } if (null != properties) { Utilities.SetReaderSettings(ReadMgr.GetReader(), properties); } else { MessageBox.Show("properties are null"); } //set the read plan and filter TagFilter filter; int addressToRead = int.Parse(properties["selectionaddress"]); Gen2.Bank bank = Gen2.Bank.EPC; switch (properties["tagselection"].ToLower()) { case "None": case "epc": bank = Gen2.Bank.EPC; break; case "tid": bank = Gen2.Bank.TID; break; case "user": bank = Gen2.Bank.USER; break; case "reserved": bank = Gen2.Bank.RESERVED; break; default: break; } if ("yes" == properties["ismaskselected"]) { filter = new Gen2.Select(true, bank, (uint)addressToRead * 8, (ushort)(properties["selectionmask"].Length * 4), ByteFormat.FromHex(properties["selectionmask"])); } else { filter = new Gen2.Select(false, bank, (uint)addressToRead * 8, (ushort)(properties["selectionmask"].Length * 4), ByteFormat.FromHex(properties["selectionmask"])); } SimpleReadPlan srp; if (properties["tagselection"].ToLower() == "none") { srp = new SimpleReadPlan(new int[] { 1 }, TagProtocol.GEN2, null, 0); } else { srp = new SimpleReadPlan(new int[] { 1 }, TagProtocol.GEN2, filter, 0); } ReadMgr.GetReader().ParamSet("/reader/read/plan", srp); btnStartReads.Text = "Stop Reads"; setStatus("Reading", System.Drawing.Color.DarkGoldenrod); ReadMgr.GetReader().ReadException += ReadException; ReadMgr.GetReader().TagRead += PrintTagRead; ReadMgr.GetReader().StartReading(); if (properties["audiblealert"].ToLower() == "yes") { if (readTriggeredByTap) { playStartSound(); } } } catch (Exception ex) { logger.Error(ex.ToString()); tbTXPower.Enabled = true; //MessageBox.Show("Error connecting to reader: " + ex.Message.ToString(), "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); btnStartReads.Text = "Start Reads"; setStatus(Status.IDLE); ReadMgr.GetReader().ParamSet("/reader/powerMode", Reader.PowerMode.MAXSAVE); miGoToMain.Enabled = true; tmrBackLightControl.Enabled = false; properties["isreading"] = "no"; Utilities.SaveConfigurations(properties); throw ex; } finally { Cursor.Current = Cursors.Default; } } else if (btnStartReads.Text == "Stop Reads") { logger.Debug("Stop Reads pressed: Calling StopReads from ReadtheTags"); StopReads(); logger.Debug("Stop Reads pressed: Called StopReads from ReadtheTags"); } } catch (Exception ex) { logger.Error(ex.ToString()); if (-1 != ex.Message.IndexOf("RFID reader was not found")) { MessageBox.Show(ex.Message, "Error"); } else { btnStartReads.Text = "Start Reads"; setStatus(Status.IDLE); properties["isreading"] = "no"; Utilities.SaveConfigurations(properties); throw ex; } } }
public MainWindow() { InitializeComponent(); fclient = new FirebaseClient(fconfig); if (fclient != null) { MessageBox.Show("The connection to database has been successfully established"); } Reader reader = Reader.Create(uri); try { reader.Connect(); } catch (IOException e) { Console.WriteLine(e.Message); return; } //select regions and function ([51] = read) string[] functionList = reader.ParamList(); Reader.Region[] regions = (Reader.Region[])reader.ParamGet("/reader/region/supportedRegions"); reader.ParamSet(functionList[51], Reader.Region.TW); //Reader.WriteTag[] regions = (Reader.Region[])reader.ParamGet("/reader/gen2/q"); //reader.ParamSet(functionList[51], Reader.Region.TW); //reading delay of 1s int timeout = 100; //select the antenna, protocol int[] antennaList = null; string str = "1,1"; antennaList = Array.ConvertAll(str.Split(','), int.Parse); TagProtocol protocol = TagProtocol.GEN2; SimpleReadPlan simpleplan = new SimpleReadPlan(antennaList, protocol, null, null, timeout); reader.ParamSet("/reader/read/plan", simpleplan); //reader.ParamSet("/reader/tagop/antenna", 1); //Gen2.WriteTag(); //start reading //TagReadData[] tags = new TagReadData[10]; //tags = reader.Read(timeout); //if (!File.Exists(filePath)) //{ // File.Create(filePath).Close(); //} //Gen2.TagData epc = new Gen2.TagData(new byte[] {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67,}); //0123456789ABCDEF01234567 //Gen2.TagData TargetEpc = new Gen2.TagData(new byte[] { 0x30, 0x05, 0xFB, 0x63, 0xAC, 0x1F, 0x36, 0x81, 0xEC, 0x88, 0x04, 0x68,}); //3005FB63AC1F3681EC880468 //Gen2.WriteTag tagop = new Gen2.WriteTag(TargetEpc); //reader.ExecuteTagOp(tagop, epc); reader.StartReading(); reader.TagRead += OnTagRead; //StopOnTagCount tagCount = new StopOnTagCount(); //tagCount.N = 20; //StopTriggerReadPlan stopReadPlan = new StopTriggerReadPlan(tagCount); //reader.ParamSet("/reader/read/plan", stopReadPlan); //read synchronously //using (StreamWriter sw = File.CreateText("C:/Users/FCUCE-2/Documents/Data/tagsAsync.txt")) //{ // // Write some text into the file. // for (int i = 0; i < tags.Length; i++) // { // sw.WriteLine(i + " : " + tags[i]); // } //} }
static void Main(string[] args) { // Program setup if (1 > args.Length) { Usage(); } int[] antennaList = null; for (int nextarg = 1; nextarg < args.Length; nextarg++) { string arg = args[nextarg]; if (arg.Equals("--ant")) { if (null != antennaList) { Console.WriteLine("Duplicate argument: --ant specified more than once"); Usage(); } antennaList = ParseAntennaList(args, nextarg); nextarg++; } else { Console.WriteLine("Argument {0}:\"{1}\" is not recognized", nextarg, arg); Usage(); } } try { // Create Reader object, connecting to physical device. // Wrap reader in a "using" block to get automatic // reader shutdown (using IDisposable interface). using (Reader r = Reader.Create(args[0])) { // Uncomment this line to add default transport listener. // r.Transport += r.SimpleTransportListener; r.Connect(); if (Reader.Region.UNSPEC == (Reader.Region)r.ParamGet("/reader/region/id")) { Reader.Region[] supportedRegions = (Reader.Region[])r.ParamGet("/reader/region/supportedRegions"); if (supportedRegions.Length < 1) { throw new FAULT_INVALID_REGION_Exception(); } r.ParamSet("/reader/region/id", supportedRegions[0]); } string model = r.ParamGet("/reader/version/model").ToString(); if ((model.Equals("M6e Micro") || model.Equals("M6e Nano") || model.Equals("Sargas")) && antennaList == null) { Console.WriteLine("Module doesn't has antenna detection support please provide antenna list"); Usage(); } TagReadData[] tagReads; TagFilter filter; byte[] mask = new byte[4]; Gen2.Impinj.Monza4.QTPayload payLoad; Gen2.Impinj.Monza4.QTControlByte controlByte; Gen2.Impinj.Monza4.QTReadWrite readWrite; uint accesspassword = 0; //Use first antenna for operation if (antennaList != null) { r.ParamSet("/reader/tagop/antenna", antennaList[0]); } Gen2.Session session = Gen2.Session.S0; r.ParamSet("/reader/gen2/session", session); SimpleReadPlan readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, null, null, 1000); r.ParamSet("/reader/read/plan", readPlan); // Reading tags with a Monza 4 public EPC in response Console.WriteLine("Reading tags with a Monza 4 public EPC in response"); tagReads = r.Read(1000); foreach (TagReadData tagData in tagReads) { Console.WriteLine("Monza4 tag epc: " + tagData.EpcString); } Console.WriteLine(); // Initialize the payload and the controlByte of Monza4 payLoad = new Gen2.Impinj.Monza4.QTPayload(); controlByte = new Gen2.Impinj.Monza4.QTControlByte(); Console.WriteLine("Changing to private Mode "); // Executing Monza4 QT Write Set Private tagop payLoad.QTMEM = false; payLoad.QTSR = false; controlByte.QTReadWrite = true; controlByte.Persistence = true; readWrite = new Gen2.Impinj.Monza4.QTReadWrite(accesspassword, payLoad, controlByte); r.ExecuteTagOp(readWrite, null); Console.WriteLine(); // Setting the session to S2 session = Gen2.Session.S2; r.ParamSet("/reader/gen2/session", session); // Enable filter mask[0] = (byte)0x20; mask[1] = (byte)0x01; mask[2] = (byte)0xB0; mask[3] = (byte)0x00; filter = new Gen2.Select(true, Gen2.Bank.TID, 0x04, 0x18, mask); Console.WriteLine("Reading tags private Mode with session s2 "); readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, null, 1000); r.ParamSet("/reader/read/plan", readPlan); // Reading tags with a Monza 4 FastID with TID in response Console.WriteLine("Reading tags with a Monza 4 FastID with TID in response"); tagReads = r.Read(1000); foreach (TagReadData tagData in tagReads) { Console.WriteLine("Monza4 tag epc: " + tagData.EpcString); } Console.WriteLine(); Console.WriteLine("Setting the session to S0"); // Setting the session to S0 session = Gen2.Session.S0; r.ParamSet("/reader/gen2/session", session); mask[0] = (byte)0xE2; mask[1] = (byte)0x80; mask[2] = (byte)0x11; mask[3] = (byte)0x05; filter = new Gen2.Select(false, Gen2.Bank.TID, 0x00, 0x20, mask); Console.WriteLine("Reading tags private Mode with session s0 "); readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, null, 1000); r.ParamSet("/reader/read/plan", readPlan); // Reading tags with a Monza 4 FastID with NO TID in response Console.WriteLine("Reading tags with a Monza 4 FastID with NO TID in response"); tagReads = r.Read(1000); foreach (TagReadData tagData in tagReads) { Console.WriteLine("Monza4 tag epc: " + tagData.EpcString); } Console.WriteLine(); Console.WriteLine("Converting to public mode"); // Executing Monza4 QT Write Set Public tagop payLoad.QTMEM = true; payLoad.QTSR = false; controlByte.QTReadWrite = true; controlByte.Persistence = true; readWrite = new Gen2.Impinj.Monza4.QTReadWrite(accesspassword, payLoad, controlByte); r.ExecuteTagOp(readWrite, null); Console.WriteLine(); // Enable filter mask[0] = (byte)0x20; mask[1] = (byte)0x01; mask[2] = (byte)0xB0; mask[3] = (byte)0x00; filter = new Gen2.Select(true, Gen2.Bank.TID, 0x04, 0x18, mask); Console.WriteLine("Reading tags public Mode with session s0 "); readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, null, 1000); r.ParamSet("/reader/read/plan", readPlan); // Reading tags with a Monza 4 FastID with TID in response tagReads = r.Read(1000); foreach (TagReadData tagData in tagReads) { Console.WriteLine("Monza4 tag epc: " + tagData.EpcString); } Console.WriteLine(); Console.WriteLine("Reset the Read protect on "); // Reset the Read protect on payLoad.QTMEM = false; payLoad.QTSR = false; controlByte.QTReadWrite = false; controlByte.Persistence = false; readWrite = new Gen2.Impinj.Monza4.QTReadWrite(accesspassword, payLoad, controlByte); r.ExecuteTagOp(readWrite, null); } } catch (ReaderException re) { Console.WriteLine("Error: " + re.Message); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
static void Main(string[] args) { // Program setup if (1 != args.Length) { Console.WriteLine(String.Join("\r\n", new string[] { "Please provide reader URL, such as:", "tmr:///com4", "tmr://my-reader.example.com", })); Environment.Exit(1); } try { // Create Reader object, connecting to physical device. // Wrap reader in a "using" block to get automatic // reader shutdown (using IDisposable interface). using (Reader r = Reader.Create(args[0])) { //Uncomment this line to add default transport listener. //r.Transport += r.SimpleTransportListener; r.Connect(); if (Reader.Region.UNSPEC == (Reader.Region)r.ParamGet("/reader/region/id")) { Reader.Region[] supportedRegions = (Reader.Region[])r.ParamGet("/reader/region/supportedRegions"); if (supportedRegions.Length < 1) { throw new FAULT_INVALID_REGION_Exception(); } else { r.ParamSet("/reader/region/id", supportedRegions[0]); } } TagReadData[] tagReads; // Read Plan byte length; string model = (string)r.ParamGet("/reader/version/model"); if ("M6e".Equals(model) || "M6e PRC".Equals(model) || "M6e Micro".Equals(model) || "Mercury6".Equals(model) || "Astra-EX".Equals(model)) { // Specifying the readLength = 0 will return full TID for any tag read in case of M6e varients, M6 and Astra-EX reader. length = 0; } else { length = 2; } TagOp op = new Gen2.ReadData(Gen2.Bank.TID, 0, length); SimpleReadPlan plan = new SimpleReadPlan(null, TagProtocol.GEN2, null, op, 1000); r.ParamSet("/reader/read/plan", plan); // Read tags tagReads = r.Read(500); // Print tag reads foreach (TagReadData tr in tagReads) { Console.WriteLine(tr.ToString()); if (0 < tr.Data.Length) { Console.WriteLine(" Data:" + ByteFormat.ToHex(tr.Data, "", " ")); } } } } catch (ReaderException re) { Console.WriteLine("Error: " + re.Message); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
static void Main(string[] args) { // Program setup if (1 > args.Length) { Usage(); } int[] antennaList = null; for (int nextarg = 1; nextarg < args.Length; nextarg++) { string arg = args[nextarg]; if (arg.Equals("--ant")) { if (null != antennaList) { Console.WriteLine("Duplicate argument: --ant specified more than once"); Usage(); } antennaList = ParseAntennaList(args, nextarg); nextarg++; } else { Console.WriteLine("Argument {0}:\"{1}\" is not recognized", nextarg, arg); Usage(); } } try { // Create Reader object, connecting to physical device. // Wrap reader in a "using" block to get automatic // reader shutdown (using IDisposable interface). using (Reader r = Reader.Create(args[0])) { //Uncomment this line to add default transport listener. //r.Transport += r.SimpleTransportListener; r.Connect(); if (Reader.Region.UNSPEC == (Reader.Region)r.ParamGet("/reader/region/id")) { Reader.Region[] supportedRegions = (Reader.Region[])r.ParamGet("/reader/region/supportedRegions"); if (supportedRegions.Length < 1) { throw new FAULT_INVALID_REGION_Exception(); } r.ParamSet("/reader/region/id", supportedRegions[0]); } // Read Plan byte length; string model = (string)r.ParamGet("/reader/version/model"); if ((model.Equals("M6e Micro") || model.Equals("M6e Nano") || model.Equals("Sargas")) && antennaList == null) { Console.WriteLine("Module doesn't has antenna detection support please provide antenna list"); Usage(); } if ("M6e".Equals(model) || "M6e PRC".Equals(model) || "M6e JIC".Equals(model) || "M6e Micro".Equals(model) || "Mercury6".Equals(model) || "Astra-EX".Equals(model) || "Sargas".Equals(model)) { // Specifying the readLength = 0 will return full TID for any tag read in case of M6e varients, M6 and Astra-EX reader. length = 0; } else { length = 2; } // Embedded Secure Read Tag Operation - Standalone operation not supported Gen2.Password password = new Gen2.Password(0); Gen2.SecureReadData secureReadDataTagOp = new Gen2.SecureReadData(Gen2.Bank.TID, 0, (byte)0, Gen2.SecureTagType.HIGGS3, password);; SimpleReadPlan plan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, null, secureReadDataTagOp, 1000); r.ParamSet("/reader/read/plan", plan); // Create and add tag listener r.TagRead += delegate(Object sender, TagReadDataEventArgs e) { Console.WriteLine("Background read: " + e.TagReadData); if (0 < e.TagReadData.Data.Length) { Console.WriteLine("Requested data: " + ByteFormat.ToHex(e.TagReadData.Data)); } }; // Create and add read exception listener r.ReadException += r_ReadException; // Create and add read authenticate listener r.ReadAuthentication += r_ReadAuthenticationListener; // Search for tags in the background r.StartReading(); Console.WriteLine("\r\n<Do other work here>\r\n"); Thread.Sleep(500); Console.WriteLine("\r\n<Do other work here>\r\n"); Thread.Sleep(500); r.StopReading(); } } catch (ReaderException re) { Console.WriteLine("Error: " + re.Message); Console.Out.Flush(); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
static void Main(string[] args) { // Program setup if (1 > args.Length) { Usage(); } for (int nextarg = 1; nextarg < args.Length; nextarg++) { string arg = args[nextarg]; if (arg.Equals("--ant")) { if (null != antennaList) { Console.WriteLine("Duplicate argument: --ant specified more than once"); Usage(); } antennaList = ParseAntennaList(args, nextarg); nextarg++; } else { Console.WriteLine("Argument {0}:\"{1}\" is not recognized", nextarg, arg); Usage(); } } try { // Create Reader object, connecting to physical device. // Wrap reader in a "using" block to get automatic // reader shutdown (using IDisposable interface). using (r = Reader.Create(args[0])) { //Uncomment this line to add default transport listener. //r.Transport += r.SimpleTransportListener; r.Connect(); if (Reader.Region.UNSPEC == (Reader.Region)r.ParamGet("/reader/region/id")) { Reader.Region[] supportedRegions = (Reader.Region[])r.ParamGet("/reader/region/supportedRegions"); if (supportedRegions.Length < 1) { throw new FAULT_INVALID_REGION_Exception(); } r.ParamSet("/reader/region/id", supportedRegions[0]); } if (r.isAntDetectEnabled(antennaList)) { Console.WriteLine("Module doesn't has antenna detection support please provide antenna list"); Usage(); } // Create a simplereadplan which uses the antenna list created above SimpleReadPlan plan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, null, null, 1000); // Set the created readplan r.ParamSet("/reader/read/plan", plan); //Use first antenna for operation if (antennaList != null) { r.ParamSet("/reader/tagop/antenna", antennaList[0]); } // Set the session to S0 r.ParamSet("/reader/gen2/session", Gen2.Session.S0); ushort[] Key0 = new ushort[] { 0x0123, 0x4567, 0x89AB, 0xCDEF, 0x0123, 0x4567, 0x89AB, 0xCDEF }; ushort[] Key1 = new ushort[] { 0x1122, 0x3344, 0x5566, 0x7788, 0x1122, 0x3344, 0x5566, 0x7788 }; // Change enable filter to true inorder to enable filter. bool enableFilter = false; Gen2.Select filter = null; if (enableFilter) { filter = new Gen2.Select(false, Gen2.Bank.EPC, 32, 96, new byte[] { 0xDE, 0xAD, 0xBE, 0xEF, 0xDE, 0xAD, 0xBE, 0xEF, 0xDE, 0xAD, 0xBE, 0xEF }); } int EpcLength; Gen2.Password accesspassword; bool SendRawData = false; Gen2.NXP.AES.Tam1Authentication auth; // Read tag epc before performing untraceable action ReadTags(r); // Untraceable with TAM1 using Key0 EpcLength = 4; //words auth = new Gen2.NXP.AES.Tam1Authentication(Gen2.NXP.AES.KeyId.KEY0, Key0, SendRawData); Gen2.Untraceable UntraceWithTam1WithKey0 = new Gen2.NXP.AES.Untraceable(Gen2.Untraceable.EPC.HIDE, EpcLength, Gen2.Untraceable.TID.HIDE_NONE, Gen2.Untraceable.UserMemory.SHOW, Gen2.Untraceable.Range.NORMAL, auth); r.ExecuteTagOp(UntraceWithTam1WithKey0, filter); ReadTags(r); //Uncomment this to enable untraceable with TAM2 using Key1 //EpcLength = 6; //words //auth = new Gen2.NXP.AES.Tam1Authentication(Gen2.NXP.AES.KeyId.KEY1, Key1, SendRawData); //accesspassword = new Gen2.Password(0x00000000); //r.ParamSet("/reader/gen2/accessPassword", accesspassword); //Gen2.Untraceable UntraceWithTam1WithKey1 = new Gen2.NXP.AES.Untraceable(Gen2.Untraceable.EPC.HIDE, EpcLength, // Gen2.Untraceable.TID.HIDE_NONE, Gen2.Untraceable.UserMemory.SHOW, Gen2.Untraceable.Range.NORMAL, auth); //r.ExecuteTagOp(UntraceWithTam1WithKey1, filter); //ReadTags(r); //Uncomment this to enable untraceable with Access //EpcLength = 3; //accesspassword = new Gen2.Password(0x00000001); //r.ParamSet("/reader/gen2/accessPassword", accesspassword); //Gen2.Untraceable UntraceWithAccess = new Gen2.NXP.AES.Untraceable(Gen2.Untraceable.EPC.HIDE, EpcLength, // Gen2.Untraceable.TID.HIDE_NONE, Gen2.Untraceable.UserMemory.SHOW, Gen2.Untraceable.Range.NORMAL, accesspassword.Value); //r.ExecuteTagOp(UntraceWithAccess, filter); //ReadTags(r); #region EmbeddedTagOperations { // Uncomment this to execute Untraceable with TAM1 using Key0 //EpcLength = 4; //words //auth = new Gen2.NXP.AES.Tam1Authentication(Gen2.NXP.AES.KeyId.KEY0, Key0, SendRawData); //Gen2.Untraceable embeddedUntraceWithTam1WithKey0 = new Gen2.NXP.AES.Untraceable(Gen2.Untraceable.EPC.HIDE, EpcLength, // Gen2.Untraceable.TID.HIDE_NONE, Gen2.Untraceable.UserMemory.SHOW, Gen2.Untraceable.Range.NORMAL, auth); //performEmbeddedOperation(filter, embeddedUntraceWithTam1WithKey0); //ReadTags(r); //Uncomment this to execute untraceable with TAM2 using Key1 //EpcLength = 6; //words //auth = new Gen2.NXP.AES.Tam1Authentication(Gen2.NXP.AES.KeyId.KEY1, Key1, SendRawData); //Gen2.Untraceable EmbeddedUntraceWithTam1WithKey1 = new Gen2.NXP.AES.Untraceable(Gen2.Untraceable.EPC.HIDE, EpcLength, // Gen2.Untraceable.TID.HIDE_NONE, Gen2.Untraceable.UserMemory.SHOW, Gen2.Untraceable.Range.NORMAL, auth); //performEmbeddedOperation(filter, EmbeddedUntraceWithTam1WithKey1); //ReadTags(r); //Uncomment this to execute untraceable with Access //EpcLength = 3; //accesspassword = new Gen2.Password(0x00000000); //Gen2.Untraceable EmbeddedUntraceWithAccess = new Gen2.NXP.AES.Untraceable(Gen2.Untraceable.EPC.HIDE, EpcLength, // Gen2.Untraceable.TID.HIDE_NONE, Gen2.Untraceable.UserMemory.SHOW, Gen2.Untraceable.Range.NORMAL, accesspassword.Value); //performEmbeddedOperation(filter, EmbeddedUntraceWithAccess); //ReadTags(r); } #endregion EmbeddedTagOperations } } catch (ReaderException re) { Console.WriteLine("Error: " + re.Message); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
static void Main(string[] args) { // Program setup if (1 > args.Length) { Usage(); } int[] antennaList = null; for (int nextarg = 1; nextarg < args.Length; nextarg++) { string arg = args[nextarg]; if (arg.Equals("--ant")) { if (null != antennaList) { Console.WriteLine("Duplicate argument: --ant specified more than once"); Usage(); } antennaList = ParseAntennaList(args, nextarg); nextarg++; } else { Console.WriteLine("Argument {0}:\"{1}\" is not recognized", nextarg, arg); Usage(); } } // Create Reader object, connecting to physical device try { Reader r; TagReadData[] tagReads, filteredTagReads; TagFilter filter; r = Reader.Create(args[0]); //Uncomment this line to add default transport listener. //r.Transport += r.SimpleTransportListener; r.Connect(); if (Reader.Region.UNSPEC == (Reader.Region)r.ParamGet("/reader/region/id")) { Reader.Region[] supportedRegions = (Reader.Region[])r.ParamGet("/reader/region/supportedRegions"); if (supportedRegions.Length < 1) { throw new FAULT_INVALID_REGION_Exception(); } r.ParamSet("/reader/region/id", supportedRegions[0]); } if (r.isAntDetectEnabled(antennaList)) { Console.WriteLine("Module doesn't has antenna detection support please provide antenna list"); Usage(); } // In the current system, sequences of Gen2 operations require Session 0, // since each operation resingulates the tag. In other sessions, // the tag will still be "asleep" from the preceding singulation. Gen2.Session oldSession = (Gen2.Session)r.ParamGet("/reader/gen2/session"); Gen2.Session newSession = Gen2.Session.S0; Console.WriteLine("Changing to Session " + newSession + " (from Session " + oldSession + ")"); r.ParamSet("/reader/gen2/session", newSession); Console.WriteLine(); SimpleReadPlan srp = new SimpleReadPlan(antennaList, TagProtocol.GEN2); r.ParamSet("/reader/read/plan", srp); //To perform standalone operations if (antennaList != null) { r.ParamSet("/reader/tagop/antenna", antennaList[0]); } try { Console.WriteLine("Unfiltered Read:"); // Read the tags in the field tagReads = r.Read(500); foreach (TagReadData tr in tagReads) { Console.WriteLine(tr.ToString()); } Console.WriteLine(); if (0 == tagReads.Length) { Console.WriteLine("No tags found."); } else { // A TagData object may be used as a filter, for example to // perform a tag data operation on a particular tag. Console.WriteLine("Filtered Tagop:"); // Read kill password of tag found in previous operation filter = tagReads[0].Tag; Console.WriteLine("Read kill password of tag {0}", filter); Gen2.ReadData tagop = new Gen2.ReadData(Gen2.Bank.RESERVED, 0, 2); try { ushort[] data = (ushort[])r.ExecuteTagOp(tagop, filter); foreach (ushort word in data) { Console.Write("{0:X4}", word); } Console.WriteLine(); } catch (ReaderException ex) { Console.WriteLine("Can't read tag: {0}", ex.Message); } Console.WriteLine(); // Filter objects that apply to multiple tags are most useful in // narrowing the set of tags that will be read. This is // performed by setting a read plan that contains a filter. // A TagData with a short EPC will filter for tags whose EPC // starts with the same sequence. filter = new TagData(tagReads[0].Tag.EpcString.Substring(0, 4)); Console.WriteLine("EPCs that begin with {0}:", filter); r.ParamSet("/reader/read/plan", new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, 1000)); filteredTagReads = r.Read(500); foreach (TagReadData tr in filteredTagReads) { Console.WriteLine(tr.ToString()); } Console.WriteLine(); // A filter can also be an full Gen2 Select operation. For // example, this filter matches all Gen2 tags where bits 8-19 of // the TID are 0x003 (that is, tags manufactured by Alien // Technology). // In case of Network readers, ensure that bitLength is a multiple of 8. Console.WriteLine("Tags with Alien Technology TID"); filter = new Gen2.Select(false, Gen2.Bank.TID, 8, 12, new byte[] { 0, 0x30 }); r.ParamSet("/reader/read/plan", new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, 1000)); filteredTagReads = r.Read(500); foreach (TagReadData tr in filteredTagReads) { Console.WriteLine(tr.ToString()); } Console.WriteLine(); if (r is SerialReader) { // A filter can also be Gen2 Truncate Select operation. // Truncate indicates whether a Tag’s backscattered reply shall be truncated to those EPC bits that follow Mask. // For example, truncated select starting with PC word start address and length of 16 bits // In case of Network readers, ensure that bitLength is a multiple of 8. Console.WriteLine("GEN2 Select Truncate Operation"); filter = new Gen2.Select(false, Gen2.Bank.GEN2EPCTRUNCATE, 16, 40, new byte[] { 0x30, 0x00, 0xDE, 0xAD, 0xCA }); r.ParamSet("/reader/read/plan", new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, 1000)); filteredTagReads = r.Read(500); foreach (TagReadData tr in filteredTagReads) { Console.WriteLine(tr.ToString()); } Console.WriteLine(); // A filter can also perform Gen2 Tag Filtering. // Major advantage of this feature is to limit the EPC response to user specified length field and all others will be rejected by firmware. // invert, bitPointer, mask : Parameters will be ignored when TMR_GEN2_EPC_LENGTH_FILTER is used // maskBitLength : Specified EPC Length used for filtering // For example, Tag filtering will be applied on EPC with 128 bits length, rest of the tags will be ignored // In case of Network readers, ensure that bitLength is a multiple of 8. Console.WriteLine("GEN2 Tag Filter Based on EPC Length"); filter = new Gen2.Select(false, Gen2.Bank.GEN2EPCLENGTHFILTER, 16, 128, new byte[] { 0x30, 0x00 }); r.ParamSet("/reader/read/plan", new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, 1000)); filteredTagReads = r.Read(500); foreach (TagReadData tr in filteredTagReads) { Console.WriteLine(tr.ToString()); } Console.WriteLine(); } // Gen2 Select may also be inverted, to give all non-matching tags // In case of Network readers, ensure that bitLength is a multiple of 8. Console.WriteLine("Tags without Alien Technology TID"); filter = new Gen2.Select(true, Gen2.Bank.TID, 8, 12, new byte[] { 0, 0x30 }); r.ParamSet("/reader/read/plan", new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, 1000)); filteredTagReads = r.Read(500); foreach (TagReadData tr in filteredTagReads) { Console.WriteLine(tr.ToString()); } Console.WriteLine(); // Filters can also be used to match tags that have already been // read. This form can only match on the EPC, as that's the only // data from the tag's memory that is contained in a TagData // object. // Note that this filter has invert=true. This filter will match // tags whose bits do not match the selection mask. // Also note the offset - the EPC code starts at bit 32 of the // EPC memory bank, after the StoredCRC and StoredPC. // In case of Network readers, ensure that bitLength is a multiple of 8. filter = new Gen2.Select(true, Gen2.Bank.EPC, 32, 2, new byte[] { (byte)0xC0 }); Console.WriteLine("EPCs with first 2 bits equal to zero (post-filtered):"); foreach (TagReadData tr in tagReads) // unfiltered tag reads from the first example { if (filter.Matches(tr.Tag)) { Console.WriteLine(tr.ToString()); } } Console.WriteLine(); /** * Multi filter creation and initialization. This filter will match those tags whose bits matches the * selection mask of both tidFilter(tags manufactured by Alien Technology) and epcFilter(epc of first * tag read from tagReads[0]). Target and action are the two new parameters of Gen2.Select class whose * default values could be "Gen2.Select.Target.Select" and "Gen2.Select.Action.ON_N_OFF" respectively * if not provided by the user. * * Gen2 Select Action indicates which Select action to take * (See Gen2 spec /Select commands / Tag response to Action parameter) * |-----------------------------------------------------------------------------| * | Action | Tag Matching | Tag Not-Matching | * |----------|--------------------------------|---------------------------------| * | 0x00 | Assert SL or Inventoried->A | Deassert SL or Inventoried->B | * | 0x01 | Assert SL or Inventoried->A | Do nothing | * | 0x02 | Do nothing | Deassert SL or Inventoried->B | * | 0x03 | Negate SL or (A->B,B->A) | Do nothing | * | 0x04 | Deassert SL or Inventoried->B | Assert SL or Inventoried->A | * | 0x05 | Deassert SL or Inventoried->B | Do nothing | * | 0x06 | Do nothing | Assert SL or Inventoried->A | * | 0x07 | Do nothing | Negate SL or (A->B,B->A) | * * * To improve readability and ease typing, these names abbreviate the official terminology of the Gen2 spec. * <A>_N_<B>: The "_N_" stands for "Non-Matching". * The <A> clause before the _N_ describes what happens to Matching tags. * The <B> clause after the _N_ describes what happens to Non-Matching tags. * (Alternately, you can pronounce "_N_" as "and", or "&"; i.e., * the pair of Matching / Non-Matching actions is known as "<A> and <B>".) * * ON: assert SL or inventoried -> A * OFF: deassert SL or inventoried -> B * NEG: negate SL or (A->B, B->A) * NOP: do nothing * * The enum is simply a transliteration of the Gen2 spec's table: "Tag response to Action parameter" */ // create and initialize tidFilter // In case of Network readers, ensure that bitLength is a multiple of 8. Gen2.Select tidFilter = new Gen2.Select(false, Gen2.Bank.TID, 32, 16, new byte[] { (byte)0x01, (byte)0x2E }); tidFilter.target = Gen2.Select.Target.Select; tidFilter.action = Gen2.Select.Action.ON_N_OFF; // create and initialize epcFilter // In case of Network readers, ensure that bitLength is a multiple of 8. Gen2.Select epcFilter = new Gen2.Select(false, Gen2.Bank.EPC, 32, 16, new byte[] { (byte)0x11, (byte)0x22 }); epcFilter.target = Gen2.Select.Target.Select; epcFilter.action = Gen2.Select.Action.ON_N_OFF; // Initialize multifilter with tagFilter array containing list of filters // In case of Network readers, ensure that bitLength is a multiple of 8. MultiFilter multiFilter = new MultiFilter(new TagFilter[] { tidFilter, epcFilter }); r.ParamSet("/reader/read/plan", new SimpleReadPlan(antennaList, TagProtocol.GEN2, multiFilter, 1000)); Console.WriteLine("Reading tags which matches multi filter criteria \n", filter.ToString()); filteredTagReads = r.Read(500); foreach (TagReadData tr in filteredTagReads) { Console.WriteLine(tr.ToString()); } Console.WriteLine(); } } finally { // Restore original settings Console.WriteLine("Restoring Session " + oldSession); r.ParamSet("/reader/gen2/session", oldSession); } // Shut down reader r.Destroy(); } catch (ReaderException re) { Console.WriteLine("Error: " + re.Message); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
// Dictionary<string, TagReadData> tagbuf = new Dictionary<string, TagReadData>(); void ReadFunc() { int firsttagtime = 0; int hassetfirsttime = 0; int totalreadtimes = 0; while (isInventory) { try { if (hassetfirsttime == 0) { firsttagtime = Environment.TickCount; hassetfirsttime = 1; } // int ee = Environment.TickCount; TagReadData[] reads = modulerdr.Read(rParms.readdur); // Console.WriteLine("read dur: " + (Environment.TickCount - ee) + ":" + reads.Length.ToString()); /*如果需要驱动gpo * //if (reads.Length != 0) * //{ * // if (rParms.setGPO1) * // { * // modulerdr.GPOSet(1, true); * // Thread.Sleep(20); * // modulerdr.GPOSet(1, false); * // } * //} * */ //if (reads.Length != 0) // PlaySound("ding.wav", IntPtr.Zero, PlaySoundFlags.SND_SYNC); foreach (TagReadData read in reads) { // Console.WriteLine("Rssi: " + read.Rssi); AddTagToDic(read); } totalreadtimes++; if (rParms.isReadFixCount) { if (totalreadtimes == rParms.FixReadCount) { this.BeginInvoke(new AutoStopReaderHandler(StopFixTimesRead)); readtimedur = Environment.TickCount - firsttagtime; return; } } //gen2多标签读取,如果需要改变天线搜索顺序 if (rParms.isRevertAnts) { SimpleReadPlan pl = modulerdr.ParamGet("ReadPlan") as SimpleReadPlan; if (pl != null) { if (pl.Protocol == TagProtocol.GEN2) { int[] neworder = new int[pl.Antennas.Length]; for (int j = 0; j < pl.Antennas.Length; ++j) { neworder[j] = pl.Antennas[pl.Antennas.Length - 1 - j]; } modulerdr.ParamSet("ReadPlan", new SimpleReadPlan(TagProtocol.GEN2, neworder)); } } } // Thread.Sleep(rParms.sleepdur); } catch (OpFaidedException exxx) { Debug.WriteLine("inventory failed --------------------------------------------------"); this.BeginInvoke(new OpFailedHandler(ShowOpFailedMsg), exxx); // Debug.WriteLine(exxx.ToString()); Debug.WriteLine(DateTime.Now.ToString()); } catch (Exception ex) { Debug.WriteLine("fatal error --------------------------------------------------"); Debug.WriteLine(DateTime.Now.ToString()); // Debug.WriteLine("33333333333"); this.BeginInvoke(new ReconnectHandler(Reconnect), ex); // Debug.WriteLine("4444444444444"); return; } } // Debug.WriteLine("5555555555555555"); readtimedur = Environment.TickCount - firsttagtime; }
static void Main(string[] args) { // Program setup if (1 > args.Length) { Usage(); } for (int nextarg = 1; nextarg < args.Length; nextarg++) { string arg = args[nextarg]; if (arg.Equals("--ant")) { if (null != antennaList) { Console.WriteLine("Duplicate argument: --ant specified more than once"); Usage(); } antennaList = ParseAntennaList(args, nextarg); nextarg++; } else { Console.WriteLine("Argument {0}:\"{1}\" is not recognized", nextarg, arg); Usage(); } } try { // Create Reader object, connecting to physical device. // Wrap reader in a "using" block to get automatic // reader shutdown (using IDisposable interface). using (r = Reader.Create(args[0])) { //Uncomment this line to add default transport listener. //r.Transport += r.SimpleTransportListener; r.Connect(); if (Reader.Region.UNSPEC == (Reader.Region)r.ParamGet("/reader/region/id")) { Reader.Region[] supportedRegions = (Reader.Region[])r.ParamGet("/reader/region/supportedRegions"); if (supportedRegions.Length < 1) { throw new FAULT_INVALID_REGION_Exception(); } r.ParamSet("/reader/region/id", supportedRegions[0]); } if (r.isAntDetectEnabled(antennaList)) { Console.WriteLine("Module doesn't has antenna detection support please provide antenna list"); Usage(); } // Create a simplereadplan which uses the antenna list created above SimpleReadPlan plan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, null, null, 1000); // Set the created readplan r.ParamSet("/reader/read/plan", plan); //Use first antenna for operation if (antennaList != null) { r.ParamSet("/reader/tagop/antenna", antennaList[0]); } ushort[] Key0 = new ushort[] { 0x0123, 0x4567, 0x89AB, 0xCDEF, 0x0123, 0x4567, 0x89AB, 0xCDEF }; ushort[] Key1 = new ushort[] { 0x1122, 0x3344, 0x5566, 0x7788, 0x1122, 0x3344, 0x5566, 0x7788 }; // Change enable filter to true inorder to enable filter. bool enableFilter = false; Gen2.Select filter = null; if (enableFilter) { filter = new Gen2.Select(false, Gen2.Bank.EPC, 32, 96, new byte[] { 0xDE, 0xAD, 0xBE, 0xEF, 0xDE, 0xAD, 0xBE, 0xEF, 0xDE, 0xAD, 0xBE, 0xEF }); } bool SendRawData = true; bool _isNMV2DTag = false; Gen2.NXP.AES.Tam1Authentication tam1Auth; Gen2.NXP.AES.Tam2Authentication tam2Auth; byte[] Response; //ReadBuffer with TAM1 using Key0 //tam1Auth = new Gen2.NXP.AES.Tam1Authentication(Gen2.NXP.AES.KeyId.KEY0, Key0, SendRawData); //Gen2.ReadBuffer tagOp = new Gen2.NXP.AES.ReadBuffer(0, 128, tam1Auth); //Response = (byte[])r.ExecuteTagOp(tagOp, filter); //if (SendRawData) //{ // parseTAM1Response(Response, ByteConv.ConvertFromUshortArray(Key0)); //} //else //{ // Console.WriteLine("Generated Ichallenge:" + ByteFormat.ToHex(Response, "", " ")); //} // Uncomment this to enable ReadBuffer with TAM1 using Key1 //tam1Auth = new Gen2.NXP.AES.Tam1Authentication(Gen2.NXP.AES.KeyId.KEY1, Key1, SendRawData); //Gen2.ReadBuffer Tam1RdBufWithKey0 = new Gen2.NXP.AES.ReadBuffer(0, 128, tam1Auth); //Response = (byte[])r.ExecuteTagOp(Tam1RdBufWithKey0, filter); //if (SendRawData) //{ // parseTAM1Response(Response, ByteConv.ConvertFromUshortArray(Key1)); //} //else //{ // Console.WriteLine("Generated Ichallenge:" + ByteFormat.ToHex(Response, "", " ")); //} //Uncomment this to enable ReadBuffer with TAM2 using key1 ushort Offset = 0; ushort BlockCount = 1; // supported protMode value is 1 for NXPUCODE AES tag ushort ProtMode = 1; tam2Auth = new Gen2.NXP.AES.Tam2Authentication(Gen2.NXP.AES.KeyId.KEY1, Key1, Gen2.NXP.AES.Profile.EPC, Offset, BlockCount, ProtMode, SendRawData); Gen2.ReadBuffer Tam2RdBufWithKey1 = new Gen2.NXP.AES.ReadBuffer(0, 256, tam2Auth); Response = (byte[])r.ExecuteTagOp(Tam2RdBufWithKey1, filter); if (SendRawData) { parseTAM2Response(Response, ByteConv.ConvertFromUshortArray(Key1), ProtMode); } else { byte[] generatedIChallenge = new byte[10]; byte[] dataRequested = new byte[16]; Array.Copy(Response, 0, generatedIChallenge, 0, 10); Console.WriteLine("Generated Ichallenge:" + ByteFormat.ToHex(generatedIChallenge, "", " ")); Array.Copy(Response, 10, dataRequested, 0, 16); Console.WriteLine("Data :" + ByteFormat.ToHex(dataRequested, "", " ")); } // Embedded tag operations #region EmbeddedTagOperations { //Uncomment this to execute embedded tagop for ReadBuffer with TAM1 using Key0 //tam1Auth = new Gen2.NXP.AES.Tam1Authentication(Gen2.NXP.AES.KeyId.KEY0, Key0, SendRawData); //Gen2.ReadBuffer embeddedTagOp = new Gen2.NXP.AES.ReadBuffer(0, 128, tam1Auth); //Response = performEmbeddedOperation(filter, embeddedTagOp); //if (SendRawData) //{ // parseTAM1Response(Response, ByteConv.ConvertFromUshortArray(Key0)); //} //else //{ // Console.WriteLine("Generated Ichallenge:" + ByteFormat.ToHex(Response, "", " ")); //} //Uncomment this to execute embedded tagop for ReadBuffer with TAM1 using Key1 //tam1Auth = new Gen2.NXP.AES.Tam1Authentication(Gen2.NXP.AES.KeyId.KEY1, Key1, SendRawData); //Gen2.ReadBuffer embeddedTam1RdBufWithKey0 = new Gen2.NXP.AES.ReadBuffer(0, 128, tam1Auth); //Response = performEmbeddedOperation(filter, embeddedTam1RdBufWithKey0); //if (SendRawData) //{ // parseTAM1Response(Response, ByteConv.ConvertFromUshortArray(Key1)); //} //else //{ // Console.WriteLine("Generated Ichallenge:" + ByteFormat.ToHex(Response, "", " ")); //} //Uncomment this to execute embedded tagop for ReadBuffer with TAM2 using key1 //ushort EmbeddedOffset = 0; //ushort EmbeddedBlockCount = 1; //// supported protMode value is 1 for NXPUCODE AES tag //ushort EmbeddedProtMode = 1; //tam2Auth = new Gen2.NXP.AES.Tam2Authentication(Gen2.NXP.AES.KeyId.KEY1, Key1, // Gen2.NXP.AES.Profile.EPC, EmbeddedOffset, EmbeddedBlockCount, EmbeddedProtMode, SendRawData); //Gen2.ReadBuffer embeddedTam2RdBufWithKey1 = new Gen2.NXP.AES.ReadBuffer(0, 256, tam2Auth); //Response = performEmbeddedOperation(filter, embeddedTam2RdBufWithKey1); //if (SendRawData) //{ // parseTAM2Response(Response, ByteConv.ConvertFromUshortArray(Key1), EmbeddedProtMode); //} //else //{ // byte[] generatedIChallenge = new byte[10]; // byte[] dataRequested = new byte[16]; // Array.Copy(Response, 0, generatedIChallenge, 0, 10); // Console.WriteLine("Generated Ichallenge:" + ByteFormat.ToHex(generatedIChallenge, "", " ")); // Array.Copy(Response, 10, dataRequested, 0, 16); // Console.WriteLine("Data :" + ByteFormat.ToHex(dataRequested, "", " ")); //} } #endregion EmbeddedTagOperations //Enable flag _isNMV2DTag for ReadBuffer with TAM1/TAM2 Authentication using KEY0 for NMV2D Tag if (_isNMV2DTag) { // NMV2D tag only supports KEY0 ushort[] Key0_NMV2D = new ushort[] { 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000 }; //Uncomment this to enable ReadBuffer with TAM1 with Key0 //tam1Auth = new Gen2.NXP.AES.Tam1Authentication(Gen2.NXP.AES.KeyId.KEY0, Key0_NMV2D, SendRawData); //// Pass bitCount value as 128 for TAM1 //Gen2.ReadBuffer tagOp = new Gen2.NXP.AES.ReadBuffer(0, 128, tam1Auth); //Response = (byte[])r.ExecuteTagOp(tagOp, filter); //if (SendRawData) //{ // parseTAM1Response(Response, ByteConv.ConvertFromUshortArray(Key0_NMV2D)); //} //else //{ // Console.WriteLine("Generated Ichallenge:" + ByteFormat.ToHex(Response, "", " ")); //} //ReadBuffer with TAM2 with key0 //ushort offset = 0; //ushort blockCount = 1; ////supported protMode values are 0,1,2,3 //ushort protMode = 0; //ushort bitCount = 0; //tam2Auth = new Gen2.NXP.AES.Tam2Authentication(Gen2.NXP.AES.KeyId.KEY0, Key0_NMV2D, // Gen2.NXP.AES.Profile.EPC, offset, blockCount, protMode, SendRawData); //// Pass bitCount value as 256 for protModes = 0, 1 and 352 for protModes = 2, 3 for TAM2 //if (protMode == 0 || protMode == 1) //{ // bitCount = 256; //} //else if (protMode == 2 || protMode == 3) //{ // bitCount = 352; //} //Gen2.ReadBuffer Tam2RdBufWithKey0 = new Gen2.NXP.AES.ReadBuffer(0, bitCount, tam2Auth); //Response = (byte[])r.ExecuteTagOp(Tam2RdBufWithKey0, filter); //if (SendRawData) //{ // parseTAM2Response(Response, ByteConv.ConvertFromUshortArray(Key0_NMV2D), protMode); //} //else //{ // byte[] generatedIChallenge = new byte[10]; // byte[] dataRequested = new byte[16]; // Array.Copy(Response, 0, generatedIChallenge, 0, 10); // Console.WriteLine("Generated Ichallenge:" + ByteFormat.ToHex(generatedIChallenge, "", " ")); // Array.Copy(Response, 10, dataRequested, 0, 16); // Console.WriteLine("Data :" + ByteFormat.ToHex(dataRequested, "", " ")); //} } } } catch (ReaderException re) { Console.WriteLine("Error: " + re.Message); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
private void Running() { while (Runningl) { try { ReaderType[] types = new ReaderType[] { ReaderType.MT_TWOANTS, ReaderType.MT_FOURANTS, ReaderType.MT_THREEANTS, ReaderType.MT_ONEANT, ReaderType.PR_ONEANT, ReaderType.MT_A7_FOURANTS, ReaderType.MT_A7_TWOANTS, ReaderType.SL_FOURANTS, ReaderType.M6_A7_FOURANTS, ReaderType.MT100, ReaderType.MT200 }; mf.Rd = Reader.Create(sparmas.Comv, ModuleTech.Region.PRC, types[sparmas.ReaderType]); Funpercent(30, "创建读写器完毕"); dlog.WirteLog("创建读写器完毕\r\n"); // if (!(types[sparmas.ReaderType] == ReaderType.M6_A7_FOURANTS && sparmas.AntType == 2)) { mf.Rd.ParamSet("CheckAntConnection", sparmas.CheckAnt); Funpercent(40, "检测天线"); dlog.WirteLog("检测天线\r\n"); } AntPower[] apwrs = new AntPower[sparmas.AntType]; for (int i = 0; i < apwrs.Length; i++) { apwrs[i].AntId = (byte)(i + 1); apwrs[i].ReadPower = ushort.Parse(sparmas.ReadPw[i]); apwrs[i].WritePower = ushort.Parse(sparmas.WritePw[i]); } mf.Rd.ParamSet("AntPowerConf", apwrs); Funpercent(50, "配置天线功率"); dlog.WirteLog("配置天线功率\r\n"); mf.Rd.ParamSet("TagopAntenna", sparmas.Opant); Funpercent(60, "配置默认天线"); dlog.WirteLog("配置默认天线\r\n"); int[] connectedants = (int[])mf.Rd.ParamGet("ConnectedAntennas"); SimpleReadPlan gen2srp = null; SimpleReadPlan iso6bsrp = null; if (connectedants.Length > 0 && (sparmas.AntType != 2 && types[sparmas.ReaderType] != ReaderType.M6_A7_FOURANTS)) { sparmas.Connectants = connectedants; gen2srp = new SimpleReadPlan(TagProtocol.GEN2, connectedants, 30); iso6bsrp = new SimpleReadPlan(TagProtocol.ISO180006B, connectedants, 30); } else { sparmas.Connectants = null; gen2srp = new SimpleReadPlan(TagProtocol.GEN2, new int[] { sparmas.Opant }, 30); iso6bsrp = new SimpleReadPlan(TagProtocol.ISO180006B, new int[] { sparmas.Opant }, 30); } if (sparmas.Protocol == 0) { mf.Rd.ParamSet("ReadPlan", gen2srp); } else if (sparmas.Protocol == 1) { mf.Rd.ParamSet("ReadPlan", iso6bsrp); } else { List <SimpleReadPlan> Lrp = new List <SimpleReadPlan>(); //List<ReadPlan> Lrp = new List<ReadPlan>(); Lrp.Add(gen2srp); Lrp.Add(iso6bsrp); MultiReadPlan mrp = new MultiReadPlan(Lrp.ToArray()); mf.Rd.ParamSet("ReadPlan", mrp); } Funpercent(70, "配置盘点方式"); dlog.WirteLog("配置盘点方式\r\n"); mf.Rd.ParamSet("Gen2Session", (ModuleTech.Gen2.Session)sparmas.Session); Funpercent(80, "配置会话模式"); dlog.WirteLog("配置会话模式\r\n"); ModuleTech.Region[] mregion = new ModuleTech.Region[] { ModuleTech.Region.UNSPEC, ModuleTech.Region.CN, ModuleTech.Region.EU, ModuleTech.Region.EU2, ModuleTech.Region.EU3, ModuleTech.Region.IN, ModuleTech.Region.KR, ModuleTech.Region.JP, ModuleTech.Region.NA, ModuleTech.Region.PRC, ModuleTech.Region.OPEN, ModuleTech.Region.OPEN }; mf.Rd.ParamSet("Region", mregion[sparmas.Region]); Funpercent(90, "配置区域"); dlog.WirteLog("配置区域" + mregion[sparmas.Region].ToString() + "\r\n"); if (sparmas.CustomFrequency) { List <uint> htb = new List <uint>(); for (int i = 0; i < sparmas.Frequencys.Length; i++) { htb.Add(uint.Parse(sparmas.Frequencys[i])); //dlog.WirteLog(sparmas.Frequencys[i].ToString()+"\r\n"); } try { mf.Rd.ParamSet("FrequencyHopTable", htb.ToArray()); Funpercent(90, "配置频率表"); dlog.WirteLog("配置频率表\r\n"); } catch (System.Exception ex) { } } try { //case 0x00: // pm = SerialReader.PowerMode.FULL; // break; //case 0x01: // pm = SerialReader.PowerMode.MINSAVE; // break; //case 0x02: // pm = SerialReader.PowerMode.MEDSAVE; // break; //case 0x03: // pm = SerialReader.PowerMode.MAXSAVE; // break; //case 0x04: // pm = SerialReader.PowerMode.SLEEP; mf.Rd.ParamSet("PowerMode", (byte)sparmas.PowerMode);//0x03 mf.Rd.ParamSet("IsTransmitPowerSave", true); } catch// (Exception omitex) { } Funpercent(100, "配置完毕,读写器工作就绪"); } catch (System.Exception ex) { string msg = string.Empty; if (ex is ModuleLibrary.FatalInternalException) { msg = Convert.ToString(((ModuleLibrary.FatalInternalException)ex).ErrCode, 16); } if (ex is ModuleLibrary.HardwareAlertException) { msg = Convert.ToString(((ModuleLibrary.HardwareAlertException)ex).ErrCode, 16); } if (ex is ModuleLibrary.ModuleException) { msg = Convert.ToString(((ModuleLibrary.ModuleException)ex).ErrCode, 16); } if (ex is ModuleLibrary.OpFaidedException) { msg = Convert.ToString(((ModuleLibrary.OpFaidedException)ex).ErrCode, 16); } if (mf.Rd != null) { mf.Rd.Disconnect(); } Funpercent(0, "连接失败" + ex.Message + " :" + msg); if (dlog != null) { dlog.WirteLog(ex.Message + ":" + msg + ex.StackTrace); } } Thread.Sleep(1000); Runningl = false; } IsExit = false; Funpercent(-100, string.Empty); }
private void btnRead_Click(object sender, RoutedEventArgs e) { Mouse.SetCursor(Cursors.Wait); TagReadData[] tagReads = null; try { if (btnRead.Content.Equals("Read")) { SimpleReadPlan srp = new SimpleReadPlan(((null != GetSelectedAntennaList()) ? (new int[] { GetSelectedAntennaList()[0] }) : null), TagProtocol.GEN2, null, 0); objReader.ParamSet("/reader/read/plan", srp); tagReads = objReader.Read(500); if ((null != tagReads) && (tagReads.Length > 0)) { currentEPC = tagReads[0].EpcString; txtEpc.Text = tagReads[0].EpcString; lblSelectFilter.Content = "Showing tag: EPC ID = " + tagReads[0].EpcString; if (tagReads.Length > 1) { lblUserMemoryError.Content = "Warning: More than one tag responded"; lblUserMemoryError.Visibility = System.Windows.Visibility.Visible; } else { lblUserMemoryError.Visibility = System.Windows.Visibility.Collapsed; } } else { txtEpc.Text = ""; currentEPC = string.Empty; MessageBox.Show("No tags found", "Error", MessageBoxButton.OK, MessageBoxImage.Error); txtblkSpMAXSizeHexByteSp64BytesAvailable.Text = "00"; txtblkSpMAXSizeCharsAvailable.Text = "00"; txtblkRemainingCharsAvailableCount.Text = "00 characters remaining"; txtASCIIData.IsEnabled = false; RemoveGeneratedControl(); return; } } else { rbSelectedTagUserMemTb.IsChecked = true; } //Display user bank data PopulateUserData(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } finally { Mouse.SetCursor(Cursors.Arrow); } }
public void defaultSettings() { String x; String y; String z; int[] antennaList = null; TagFilter filter0; filter0 = new TagData("AA"); Reader r = Reader.Create("tmr:///com25"); r.Connect(); TagOp op = new Gen2.ReadData(Gen2.Bank.USER, 0x104, 3); SimpleReadPlan plan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter0, op, true, 150); r.ParamSet("/reader/gen2/blf", Gen2.LinkFrequency.LINK640KHZ); // r.ParamSet("/reader/gen2/target", Gen2.Target.AB); // MultiReadPlan testMultiReadPlan = new MultiReadPlan(readPlans); // r.ParamSet("/reader/read/plan", testMultiReadPlan); //r.ParamSet("/reader/read/asyncOnTime", 25000); //r.ParamSet("/reader/read/asyncOffTime", 200); r.ParamSet("/reader/region/id", Reader.Region.EU3); Gen2.BAPParameters bap = (Gen2.BAPParameters)r.ParamGet("/reader/gen2/bap"); bap.FREQUENCYHOPOFFTIME = 20; bap.POWERUPDELAY = 3; r.ParamSet("/reader/gen2/bap", bap); // r.ParamSet("/reader/baudRate", 921600); r.ParamSet("/reader/read/plan", plan); r.TagRead += delegate(Object sender, TagReadDataEventArgs e) { //Debug.Print("I am here"); String userMem = ByteFormat.ToHex(e.TagReadData.Data).ToString(); // convert the input into a hex string // Debug.Print(userMem); String abc = e.TagReadData.EpcString; Debug.Print(abc); userMem.Trim(); int length = 4; int substringposition = 2; if (abc == "AAA2") { while (substringposition < 3) // split the string into small chunks per value and convert to INT { Debug.Print("I am in this loop"); x = userMem.Substring(substringposition, length); xInt = Convert.ToInt32(x, 16); substringposition = substringposition + length; bufferX = xInt.ToString(); Debug.Print(bufferX); y = userMem.Substring(substringposition, length); yInt = Convert.ToInt32(y, 16); substringposition = substringposition + length; bufferY = yInt.ToString(); z = userMem.Substring(substringposition, length); zInt = Convert.ToInt32(z, 16); substringposition = substringposition + length; bufferZ = zInt.ToString(); //updateText(xInt, yInt, zInt); Debug.Print(x + " " + y + " " + z); // updateProgressBars(xInt, yInt, zInt); } } Action action = delegate() { updateText(); updateProgressBars(); }; Dispatcher.BeginInvoke(DispatcherPriority.Normal, action); }; r.StartReading(); // Console.WriteLine("\r\n<Do other work here>\r\n"); // Thread.Sleep(50000000); // r.Dispose(); }
/// <summary> /// Execute embedded tag operations /// </summary> /// <param name="filter"> filter </param> /// <param name="isFastSearch"> fast search enable</param> private void EmbeddedTagOpFilter(TagFilter filter, bool isFastSearch) { TagReadData[] tagReads = null; SimpleReadPlan readPlan = null; try { //ActivateSecureMode tag operation if (!isFastSearch) { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpActivateSecureMode, 10); } else { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpActivateSecureMode, isFastSearch, 10); Console.WriteLine("Fast search enable : " + isFastSearch.ToString()); } reader.ParamSet("/reader/read/plan", readPlan); Console.WriteLine("Read Plan : " + readPlan.ToString()); tagReads = reader.Read(1000); Console.WriteLine("Activate secure mode tag operation : "); foreach (TagReadData tr in tagReads) { Console.WriteLine("Data : {0}", ByteFormat.ToHex(tr.Data)); Console.WriteLine("Data length : " + tr.Data.Length); } Console.WriteLine(); //AuthenticateOBU tag operation tagReads = null; readPlan = null; if (!isFastSearch) { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpAuthenticateOBU, 10); } else { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpAuthenticateOBU, isFastSearch, 10); Console.WriteLine("Fast search enable : " + isFastSearch.ToString()); } reader.ParamSet("/reader/read/plan", readPlan); Console.WriteLine("Read Plan : " + readPlan.ToString()); tagReads = reader.Read(1000); Console.WriteLine("AuthenticateOBU tag operation : "); foreach (TagReadData tr in tagReads) { Console.WriteLine("Data : {0}", ByteFormat.ToHex(tr.Data)); Console.WriteLine("Data length : " + tr.Data.Length); } Console.WriteLine(); //ActivateSiniavMode tag operation tagReads = null; readPlan = null; if (!isFastSearch) { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpActivateSiniavMode, 10); } else { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpActivateSiniavMode, isFastSearch, 10); Console.WriteLine("Fast search enable : " + isFastSearch.ToString()); } reader.ParamSet("/reader/read/plan", readPlan); Console.WriteLine("Read Plan : " + readPlan.ToString()); tagReads = reader.Read(1000); Console.WriteLine("Activate siniav mode tag operation : "); foreach (TagReadData tr in tagReads) { Console.WriteLine("Data : {0}", ByteFormat.ToHex(tr.Data)); Console.WriteLine("Data length : " + tr.Data.Length); } Console.WriteLine(); //OBUAuthFullPass1 tag operation tagReads = null; readPlan = null; if (!isFastSearch) { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpOBUAuthFullPass1, 10); } else { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpOBUAuthFullPass1, isFastSearch, 10); Console.WriteLine("Fast search enable : " + isFastSearch.ToString()); } reader.ParamSet("/reader/read/plan", readPlan); Console.WriteLine("Read Plan : " + readPlan.ToString()); tagReads = reader.Read(1000); Console.WriteLine("OBUAuthFullPass1 tag operation : "); foreach (TagReadData tr in tagReads) { Console.WriteLine("Data : {0}", ByteFormat.ToHex(tr.Data)); Console.WriteLine("Data length : " + tr.Data.Length); } Console.WriteLine(); //OBUAuthFullPass2 tag operation tagReads = null; readPlan = null; if (!isFastSearch) { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpOBUAuthFullPass2, 10); } else { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpOBUAuthFullPass2, isFastSearch, 10); Console.WriteLine("Fast search enable : " + isFastSearch.ToString()); } reader.ParamSet("/reader/read/plan", readPlan); Console.WriteLine("Read Plan : " + readPlan.ToString()); tagReads = reader.Read(1000); Console.WriteLine("OBUAuthFullPass2 tag operation : "); foreach (TagReadData tr in tagReads) { Console.WriteLine("Data : {0}", ByteFormat.ToHex(tr.Data)); Console.WriteLine("Data length : " + tr.Data.Length); } Console.WriteLine(); //OBUAuthID tag operation tagReads = null; readPlan = null; if (!isFastSearch) { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpOBUAuthID, 10); } else { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpOBUAuthID, isFastSearch, 10); Console.WriteLine("Fast search enable : " + isFastSearch.ToString()); } reader.ParamSet("/reader/read/plan", readPlan); Console.WriteLine("Read Plan : " + readPlan.ToString()); tagReads = reader.Read(1000); Console.WriteLine("OBUAuthID tag operation : "); foreach (TagReadData tr in tagReads) { Console.WriteLine("Data : {0}", ByteFormat.ToHex(tr.Data)); Console.WriteLine("Data length : " + tr.Data.Length); } Console.WriteLine(); //OBUReadFromMemMap tag operation tagReads = null; readPlan = null; if (!isFastSearch) { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpOBUReadFromMemMap, 10); } else { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpOBUReadFromMemMap, isFastSearch, 10); Console.WriteLine("Fast search enable : " + isFastSearch.ToString()); } reader.ParamSet("/reader/read/plan", readPlan); Console.WriteLine("Read Plan : " + readPlan.ToString()); tagReads = reader.Read(1000); Console.WriteLine("OBUReadFromMemMap tag operation : "); foreach (TagReadData tr in tagReads) { Console.WriteLine("Data : {0}", ByteFormat.ToHex(tr.Data)); Console.WriteLine("Data length : " + tr.Data.Length); } Console.WriteLine(); //OBUWriteToMemMap tag operation tagReads = null; readPlan = null; if (!isFastSearch) { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpOBUWriteToMemMap, 10); } else { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpOBUWriteToMemMap, isFastSearch, 10); Console.WriteLine("Fast search enable : " + isFastSearch.ToString()); } reader.ParamSet("/reader/read/plan", readPlan); Console.WriteLine("Read Plan : " + readPlan.ToString()); tagReads = reader.Read(1000); Console.WriteLine("OBUWriteToMemMap tag operation : "); foreach (TagReadData tr in tagReads) { Console.WriteLine("Data : {0}", ByteFormat.ToHex(tr.Data)); Console.WriteLine("Data length : " + tr.Data.Length); } Console.WriteLine(); //OBUAuthFullPass tag operation tagReads = null; readPlan = null; if (!isFastSearch) { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpOBUAuthFullPass, 10); } else { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpOBUAuthFullPass, isFastSearch, 10); Console.WriteLine("Fast search enable : " + isFastSearch.ToString()); } reader.ParamSet("/reader/read/plan", readPlan); Console.WriteLine("Read Plan : " + readPlan.ToString()); tagReads = reader.Read(1000); Console.WriteLine("OBUAuthFullPass tag operation : "); foreach (TagReadData tr in tagReads) { Console.WriteLine("Data : {0}", ByteFormat.ToHex(tr.Data)); Console.WriteLine("Data length : " + tr.Data.Length); } Console.WriteLine(); //GetTokenId tag operation tagReads = null; readPlan = null; if (!isFastSearch) { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpGetTokenId, 10); } else { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpGetTokenId, isFastSearch, 10); Console.WriteLine("Fast search enable : " + isFastSearch.ToString()); } reader.ParamSet("/reader/read/plan", readPlan); Console.WriteLine("Read Plan : " + readPlan.ToString()); tagReads = reader.Read(1000); Console.WriteLine("GetTokenId tag operation : "); foreach (TagReadData tr in tagReads) { Console.WriteLine("Data : {0}", ByteFormat.ToHex(tr.Data)); Console.WriteLine("Data length : " + tr.Data.Length); } Console.WriteLine(); //ReadSec tag operation tagReads = null; readPlan = null; if (!isFastSearch) { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpReadSec, 10); } else { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpReadSec, isFastSearch, 10); Console.WriteLine("Fast search enable : " + isFastSearch.ToString()); } reader.ParamSet("/reader/read/plan", readPlan); Console.WriteLine("Read Plan : " + readPlan.ToString()); tagReads = reader.Read(1000); Console.WriteLine("ReadSec tag operation : "); foreach (TagReadData tr in tagReads) { Console.WriteLine("Data : {0}", ByteFormat.ToHex(tr.Data)); Console.WriteLine("Data length : " + tr.Data.Length); } Console.WriteLine(); //WriteSec tag operation tagReads = null; readPlan = null; if (!isFastSearch) { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpWriteSec, 10); } else { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpWriteSec, isFastSearch, 10); Console.WriteLine("Fast search enable : " + isFastSearch.ToString()); } reader.ParamSet("/reader/read/plan", readPlan); Console.WriteLine("Read Plan : " + readPlan.ToString()); tagReads = reader.Read(1000); Console.WriteLine("WriteSec tag operation : "); foreach (TagReadData tr in tagReads) { Console.WriteLine("Data : {0}", ByteFormat.ToHex(tr.Data)); Console.WriteLine("Data length : " + tr.Data.Length); } Console.WriteLine(); //tagOpG0PAOBUAuth tag operation tagReads = null; readPlan = null; if (!isFastSearch) { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpG0PAOBUAuth, 10); } else { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpG0PAOBUAuth, isFastSearch, 10); Console.WriteLine("Fast search enable : " + isFastSearch.ToString()); } reader.ParamSet("/reader/read/plan", readPlan); Console.WriteLine("Read Plan : " + readPlan.ToString()); tagReads = reader.Read(1000); Console.WriteLine("G0PAOBUAuth tag operation : "); foreach (TagReadData tr in tagReads) { Console.WriteLine("Data : {0}", ByteFormat.ToHex(tr.Data)); Console.WriteLine("Data length : " + tr.Data.Length); } Console.WriteLine(); //tagOpG0PAOBUAuthFullPass tag operation tagReads = null; readPlan = null; if (!isFastSearch) { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpG0PAOBUAuthFullPass, 10); } else { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpG0PAOBUAuthFullPass, isFastSearch, 10); Console.WriteLine("Fast search enable : " + isFastSearch.ToString()); } reader.ParamSet("/reader/read/plan", readPlan); Console.WriteLine("Read Plan : " + readPlan.ToString()); tagReads = reader.Read(1000); Console.WriteLine("G0PAOBUAuthFullPass tag operation : "); foreach (TagReadData tr in tagReads) { Console.WriteLine("Data : {0}", ByteFormat.ToHex(tr.Data)); Console.WriteLine("Data length : " + tr.Data.Length); } Console.WriteLine(); //tagOpG0PAOBUAuthFullPass1 tag operation tagReads = null; readPlan = null; if (!isFastSearch) { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpG0PAOBUAuthFullPass1, 10); } else { readPlan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter, tagOpG0PAOBUAuthFullPass1, isFastSearch, 10); Console.WriteLine("Fast search enable : " + isFastSearch.ToString()); } reader.ParamSet("/reader/read/plan", readPlan); Console.WriteLine("Read Plan : " + readPlan.ToString()); tagReads = reader.Read(1000); Console.WriteLine("G0PAOBUAuthFullPass1 tag operation : "); foreach (TagReadData tr in tagReads) { Console.WriteLine("Data : {0}", ByteFormat.ToHex(tr.Data)); Console.WriteLine("Data length : " + tr.Data.Length); } Console.WriteLine(); } catch (ReaderException re) { throw re; } catch (Exception ex) { throw ex; } }
private void readtimer2_Tick(object sender, EventArgs e) { tagMutex3.WaitOne(); int[] ant = (int[])activedr.ParamGet("ConnectedAntennas"); SimpleReadPlan readplan = new SimpleReadPlan(TagProtocol.GEN2, ant); activedr.ParamSet("ReadPlan", readplan); int flag = 0; int count = 0; TagReadData[] reads = activedr.Read(500); //如果读取到数据 if (reads.Length != 0) { //遍历独到的数组的每一个值 foreach (TagReadData tag in reads) { //如果不是以D开头的则抛弃 if (tag.EPCString.First() != 'D') { continue; } //将该标签的EPC和时间戳存到临时变量里 string studentid = tag.EPCString; string time = tag.Time.ToString(); //判断连接的天线 if (tag.Antenna == 2) { //判断得到的EPC是否在刷新列表中 foreach (string epc in libraryrefreshlist) { if (studentid == epc) { //如果在列表中,则flag置为1,避免后续继续判断 flag = 1; } } if (flag == 0) { //pictureBox4.Visible = true; //try //{ // pictureBox4.Image = Image.FromFile(Application.StartupPath + "\\image\\" + studentid + ".jpg"); //} //catch (Exception ee) //{ // pictureBox4.Image = Image.FromFile(Application.StartupPath + "\\image\\人.jpg"); //} label10.Text = studentid; label10.Visible = true; label14.Visible = true; label14.Text = time; string str1 = "select * from activetime where studentid = '" + studentid + "' and place = '图书馆'"; bool exist = DataAccess.sql_exist(str1); if (exist) { string str2 = "select top 1 state from activetime where studentid = '" + studentid + "' and place = '图书馆' order by id desc"; DataSet ds = DataAccess.GetDataSetBySql(str2); string state = ds.Tables[0].Rows[0][0].ToString(); if (state == "进入") { string str3 = "update activetime set finishtime = '" + time + "',state = '离开' where studentid = '" + studentid + "' and state = '进入'"; DataAccess.sql_command(str3); libraryrefreshlist.Add(studentid); foreach (PictureBox pic in pb) { if (studentid == pic.Tag.ToString()) { leave(pic); } } } if (state == "离开") { string str3 = "insert into activetime(studentid,begintime,place,state) values ('" + studentid + "','" + time + "','图书馆','进入')"; DataAccess.sql_command(str3); libraryrefreshlist.Add(studentid); foreach (PictureBox pic in pb) { if (studentid == pic.Tag.ToString()) { enterlibrary(pic); } } } } else { string str3 = "insert into activetime(studentid,begintime,place,state) values ('" + studentid + "','" + time + "','图书馆','进入')"; DataAccess.sql_command(str3); libraryrefreshlist.Add(studentid); foreach (PictureBox pic in pb) { if (studentid == pic.Tag.ToString()) { enterlibrary(pic); } } } } } //判断连接的天线 if (tag.Antenna == 1) { foreach (string epc in classrefreshlist1) { if (studentid == epc) { flag = 1; } } if (flag == 0) { //pictureBox2.Visible = true; //try //{ // pictureBox2.Image = Image.FromFile(Application.StartupPath + "\\image\\" + studentid + ".jpg"); //} //catch (Exception ee) //{ // pictureBox2.Image = Image.FromFile(Application.StartupPath + "\\image\\人.jpg"); //} label8.Text = studentid; label8.Visible = true; label12.Visible = true; label12.Text = time; string str1 = "select * from activetime where studentid = '" + studentid + "' and place = '教室1'"; bool exist = DataAccess.sql_exist(str1); if (exist) { string str2 = "select top 1 state from activetime where studentid = '" + studentid + "' and place = '教室1' order by id desc"; DataSet ds = DataAccess.GetDataSetBySql(str2); string state = ds.Tables[0].Rows[0][0].ToString(); if (state == "进入") { string str3 = "update activetime set finishtime = '" + time + "',state = '离开' where studentid = '" + studentid + "' and state = '进入' "; DataAccess.sql_command(str3); classrefreshlist1.Add(studentid); foreach (PictureBox pic in pb) { if (studentid == pic.Tag.ToString()) { leave(pic); } } } if (state == "离开") { string str3 = "insert into activetime(studentid,begintime,place,state) values ('" + studentid + "','" + time + "','教室1','进入')"; DataAccess.sql_command(str3); classrefreshlist1.Add(studentid); foreach (PictureBox pic in pb) { if (studentid == pic.Tag.ToString()) { enterclassroom1(pic); } } } } else { string str3 = "insert into activetime(studentid,begintime,place,state) values ('" + studentid + "','" + time + "','教室1','进入')"; DataAccess.sql_command(str3); classrefreshlist1.Add(studentid); foreach (PictureBox pic in pb) { if (studentid == pic.Tag.ToString()) { enterclassroom1(pic); } } } } } //判断连接的天线 if (tag.Antenna == 3) { foreach (string epc in classrefreshlist2) { if (studentid == epc) { flag = 1; } } if (flag == 0) { //pictureBox3.Visible = true; //try //{ // pictureBox3.Image = Image.FromFile(Application.StartupPath + "\\image\\" + studentid + ".jpg"); //} //catch (Exception ee) //{ // pictureBox3.Image = Image.FromFile(Application.StartupPath + "\\image\\人.jpg"); //} label9.Text = studentid; label9.Visible = true; label13.Text = time; label13.Visible = true; string str1 = "select * from activetime where studentid = '" + studentid + "' and place = '教室2'"; bool exist = DataAccess.sql_exist(str1); if (exist) { string str2 = "select top 1 state from activetime where studentid = '" + studentid + "' and place = '教室2' order by id desc"; DataSet ds = DataAccess.GetDataSetBySql(str2); string state = ds.Tables[0].Rows[0][0].ToString(); if (state == "进入") { string str3 = "update activetime set finishtime = '" + time + "',state = '离开' where studentid = '" + studentid + "' and state = '进入'"; DataAccess.sql_command(str3); classrefreshlist2.Add(studentid); foreach (PictureBox pic in pb) { if (studentid == pic.Tag.ToString()) { leave(pic); } } } if (state == "离开") { string str3 = "insert into activetime(studentid,begintime,place,state) values ('" + studentid + "','" + time + "','教室2','进入')"; DataAccess.sql_command(str3); classrefreshlist2.Add(studentid); foreach (PictureBox pic in pb) { if (studentid == pic.Tag.ToString()) { enterclassroom2(pic); } } } } else { string str3 = "insert into activetime(studentid,begintime,place,state) values ('" + studentid + "','" + time + "','教室2','进入')"; DataAccess.sql_command(str3); classrefreshlist2.Add(studentid); foreach (PictureBox pic in pb) { if (studentid == pic.Tag.ToString()) { enterclassroom2(pic); } } } } } //判断连接的天线 if (tag.Antenna == 4) { foreach (string epc in computerrefreshlist) { if (studentid == epc) { flag = 1; } } if (flag == 0) { //pictureBox5.Visible = true; //try //{ // pictureBox5.Image = Image.FromFile(Application.StartupPath + "\\image\\" + studentid + ".jpg"); //} //catch (Exception ee) //{ // pictureBox5.Image = Image.FromFile(Application.StartupPath + "\\image\\人.jpg"); //} label11.Text = studentid; label11.Visible = true; label15.Text = time; label15.Visible = true; string str1 = "select * from activetime where studentid = '" + studentid + "' and place = '机房'"; bool exist = DataAccess.sql_exist(str1); if (exist) { string str2 = "select top 1 state from activetime where studentid = '" + studentid + "' and place = '机房' order by id desc"; DataSet ds = DataAccess.GetDataSetBySql(str2); string state = ds.Tables[0].Rows[0][0].ToString(); if (state == "进入") { string str3 = "update activetime set finishtime = '" + time + "',state = '离开' where studentid = '" + studentid + "' and state = '进入'"; DataAccess.sql_command(str3); computerrefreshlist.Add(studentid); foreach (PictureBox pic in pb) { if (studentid == pic.Tag.ToString()) { leave(pic); } } } if (state == "离开") { string str3 = "insert into activetime(studentid,begintime,place,state) values ('" + studentid + "','" + time + "','机房','进入')"; DataAccess.sql_command(str3); computerrefreshlist.Add(studentid); foreach (PictureBox pic in pb) { if (studentid == pic.Tag.ToString()) { computerroom(pic); } } } } else { string str3 = "insert into activetime(studentid,begintime,place,state) values ('" + studentid + "','" + time + "','机房','进入')"; DataAccess.sql_command(str3); computerrefreshlist.Add(studentid); foreach (PictureBox pic in pb) { if (studentid == pic.Tag.ToString()) { computerroom(pic); } } } } } } } tagMutex3.ReleaseMutex(); }
static void Main(string[] args) { // Program setup if (1 > args.Length) { Usage(); } int[] antennaList = null; for (int nextarg = 1; nextarg < args.Length; nextarg++) { string arg = args[nextarg]; if (arg.Equals("--ant")) { if (null != antennaList) { Console.WriteLine("Duplicate argument: --ant specified more than once"); Usage(); } antennaList = ParseAntennaList(args, nextarg); nextarg++; } else { Console.WriteLine("Argument {0}:\"{1}\" is not recognized", nextarg, arg); Usage(); } } try { // Create Reader object, connecting to physical device. // Wrap reader in a "using" block to get automatic // reader shutdown (using IDisposable interface). using (Reader r = Reader.Create(args[0])) { //Uncomment this line to add default transport listener. //r.Transport += r.SimpleTransportListener; r.Connect(); if (Reader.Region.UNSPEC == (Reader.Region)r.ParamGet("/reader/region/id")) { Reader.Region[] supportedRegions = (Reader.Region[])r.ParamGet("/reader/region/supportedRegions"); if (supportedRegions.Length < 1) { throw new FAULT_INVALID_REGION_Exception(); } r.ParamSet("/reader/region/id", supportedRegions[0]); } string model = (string)r.ParamGet("/reader/version/model").ToString(); if (!model.Equals("M3e")) { if (r.isAntDetectEnabled(antennaList)) { Console.WriteLine("Module doesn't has antenna detection support please provide antenna list"); Usage(); } } // Create a simplereadplan which uses the antenna list created above SimpleReadPlan plan = new SimpleReadPlan(antennaList, TagProtocol.GEN2); // Set the created readplan r.ParamSet("/reader/read/plan", plan); // Read tags TagReadData[] tagReads = r.Read(500); // Print tag reads foreach (TagReadData tr in tagReads) { Console.WriteLine(tr.ToString()); } } } catch (ReaderException re) { Console.WriteLine("Error: " + re.Message); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
private void readtimer1_Tick(object sender, EventArgs e) { tagMutex1.WaitOne(); int flag = 0; int[] ant = (int[])doordr.ParamGet("ConnectedAntennas"); SimpleReadPlan readplan = new SimpleReadPlan(TagProtocol.GEN2, ant); doordr.ParamSet("ReadPlan", readplan); //doordr.ParamGet("RfPowerMax"); TagReadData[] reads = doordr.Read(500); //如果读取到数据 if (reads.Length != 0) { //遍历独到的数组的每一个值 foreach (TagReadData tag in reads) { //如果不是以D开头的则抛弃 if (tag.EPCString.First() != 'D') { continue; } //将该标签的EPC和时间戳存到临时变量里 string studentid = tag.EPCString; string time = tag.Time.ToString(); //判断连接的天线 if (tag.Antenna == 1) { //判断得到的EPC是否在刷新列表中 foreach (string epc in refreshlist) { if (studentid == epc) { //如果在列表中,则flag置为1,避免后续继续判断 flag = 1; } } //foreach (string key in refreshdictionary.Keys) //{ // if (studentid == key) // { // flag = 1; // } //} if (flag == 0) { pictureBox1.Visible = true; try { pictureBox1.Image = Image.FromFile(Application.StartupPath + "\\image\\" + studentid + ".jpg"); } catch (Exception ee) { pictureBox1.Image = Image.FromFile(Application.StartupPath + "\\image\\人.jpg"); } label6.Text = studentid; label6.Visible = true; label7.Text = time; label7.Visible = true; string str1 = "select * from doortime where studentid = '" + studentid + "'"; bool exist = DataAccess.sql_exist(str1); if (exist) { refreshlist.Add(studentid); //refreshdictionary.Add(studentid, tag.Time.AddSeconds(10)); string str2 = "select top 1 state from doortime where studentid = '" + studentid + "' order by id desc"; DataSet ds = DataAccess.GetDataSetBySql(str2); string state = ds.Tables[0].Rows[0][0].ToString(); if (state == "进入") { string str3 = "insert into doortime values ('" + studentid + " ','" + time + " ','离开')"; DataAccess.sql_command(str3); } if (state == "离开") { string str3 = "insert into doortime values ('" + studentid + " ','" + time + " ','进入')"; DataAccess.sql_command(str3); } } else { string str3 = "insert into doortime values ('" + studentid + " ','" + time + " ','进入')"; DataAccess.sql_command(str3); } } } } } tagMutex1.ReleaseMutex(); }
static void Main(string[] args) { // Program setup if (1 > args.Length) { Usage(); } int[] antennaList = null; for (int nextarg = 1; nextarg < args.Length; nextarg++) { string arg = args[nextarg]; if (arg.Equals("--ant")) { if (null != antennaList) { Console.WriteLine("Duplicate argument: --ant specified more than once"); Usage(); } antennaList = ParseAntennaList(args, nextarg); nextarg++; } else { Console.WriteLine("Argument {0}:\"{1}\" is not recognized", nextarg, arg); Usage(); } } try { // Create Reader object, connecting to physical device. // Wrap reader in a "using" block to get automatic // reader shutdown (using IDisposable interface). using (Reader r = Reader.Create(args[0])) { //Uncomment this line to add default transport listener. //r.Transport += r.SimpleTransportListener; r.Connect(); if (Reader.Region.UNSPEC == (Reader.Region)r.ParamGet("/reader/region/id")) { Reader.Region[] supportedRegions = (Reader.Region[])r.ParamGet("/reader/region/supportedRegions"); if (supportedRegions.Length < 1) { throw new FAULT_INVALID_REGION_Exception(); } r.ParamSet("/reader/region/id", supportedRegions[0]); } // Read Plan byte length; string model = r.ParamGet("/reader/version/model").ToString(); if (r.isAntDetectEnabled(antennaList)) { Console.WriteLine("Module doesn't has antenna detection support please provide antenna list"); Usage(); } if ("M6e".Equals(model) || "M6e PRC".Equals(model) || "M6e JIC".Equals(model) || "M6e Micro".Equals(model) || "Mercury6".Equals(model) || "Sargas".Equals(model) || "Astra-EX".Equals(model)) { // Specifying the readLength = 0 will return full TID for any tag read in case of M6e varients, M6 and Astra-EX reader. length = 0; } else { length = 2; } TagOp op = new Gen2.ReadData(Gen2.Bank.TID, 0, length); SimpleReadPlan plan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, null, op, 1000); r.ParamSet("/reader/read/plan", plan); // Read tags TagReadData[] tagReads = r.Read(500); // Print tag reads foreach (TagReadData tr in tagReads) { Console.WriteLine(tr.ToString()); if (0 < tr.Data.Length) { Console.WriteLine(" Data:" + ByteFormat.ToHex(tr.Data, "", " ")); } } } } catch (ReaderException re) { Console.WriteLine("Error: " + re.Message); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
static void Main(string[] args) { // Program setup if (1 > args.Length) { Usage(); } int[] antennaList = null; for (int nextarg = 1; nextarg < args.Length; nextarg++) { string arg = args[nextarg]; if (arg.Equals("--ant")) { if (null != antennaList) { Console.WriteLine("Duplicate argument: --ant specified more than once"); Usage(); } antennaList = ParseAntennaList(args, nextarg); nextarg++; } else { Console.WriteLine("Argument {0}:\"{1}\" is not recognized", nextarg, arg); Usage(); } } try { // Create Reader object, connecting to physical device. // Wrap reader in a "using" block to get automatic // reader shutdown (using IDisposable interface). using (Reader r = Reader.Create(args[0])) { //Uncomment this line to add default transport listener. //r.Transport += r.SimpleTransportListener; //Change ISO180006BTagOps flag to true for performing ISO180006b Tag Operation //ISO180006b Tag Operation : WriteData, ReadData, LockTag bool ISO180006BTagOps = false; string EPCForTagOps = ""; r.Connect(); if (Reader.Region.UNSPEC == (Reader.Region)r.ParamGet("/reader/region/id")) { Reader.Region[] supportedRegions = (Reader.Region[])r.ParamGet("/reader/region/supportedRegions"); if (supportedRegions.Length < 1) { throw new FAULT_INVALID_REGION_Exception(); } r.ParamSet("/reader/region/id", supportedRegions[0]); } string model = r.ParamGet("/reader/version/model").ToString(); if ((model.Equals("M6e Micro") || model.Equals("M6e Nano") || model.Equals("Sargas")) && antennaList == null) { Console.WriteLine("Module doesn't has antenna detection support please provide antenna list"); Usage(); } //Set delimiter to 1 r.ParamSet("/reader/iso180006b/delimiter", Iso180006b.Delimiter.DELIMITER1); // Read Plan Iso180006b.Select filter = new Iso180006b.Select(false, Iso180006b.SelectOp.NOTEQUALS, 0, 0xff, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); SimpleReadPlan plan = new SimpleReadPlan(antennaList, TagProtocol.ISO180006B, filter, null, 1000); r.ParamSet("/reader/read/plan", plan); // Create and add tag listener r.TagRead += delegate(Object sender, TagReadDataEventArgs e) { Console.WriteLine("Background read: " + e.TagReadData); if (string.IsNullOrEmpty(EPCForTagOps)) { EPCForTagOps = e.TagReadData.EpcString; } }; // Create and add read exception listener r.ReadException += new EventHandler <ReaderExceptionEventArgs>(r_ReadException); // Search for tags in the background r.StartReading(); Console.WriteLine("\r\n<Do other work here>\r\n"); Thread.Sleep(500); Console.WriteLine("\r\n<Do other work here>\r\n"); Thread.Sleep(500); r.StopReading(); if (ISO180006BTagOps) { if (!String.IsNullOrEmpty(EPCForTagOps)) { Console.WriteLine("\n****************ISO180006b Tag Operation********************"); //Use first antenna for operation if (antennaList != null) { r.ParamSet("/reader/tagop/antenna", antennaList[0]); } // tag to be filtered TagFilter filterToUse = new TagData(EPCForTagOps); // write data to a particular address location of tag byte address = 0x28; byte[] writedata = new byte[] { 0xAA, 0x34, 0x56, 0x78 }; Iso180006b.WriteData writeOp = new Iso180006b.WriteData(address, writedata); r.ExecuteTagOp(writeOp, filterToUse); Console.WriteLine("Write Data Successfull"); //read data from a specified memory location works only with tag data filter Iso180006b.ReadData readtagop = new Iso180006b.ReadData(address, 4); object data = r.ExecuteTagOp(readtagop, filterToUse); Console.WriteLine("Read Data : " + BitConverter.ToString((byte[])data)); // Lock the tag at the specified address // Uncomment Below Code to Perfrom Lock Operation //Iso180006b.LockTag lockOp = new Iso180006b.LockTag(address); //r.ExecuteTagOp(lockOp, filterToUse); //Console.WriteLine("Lock Tag Successfull"); } else { throw new Exception("No ISO180006B Tags found."); } } } } catch (ReaderException re) { Console.WriteLine("Error: " + re.Message); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
public void Go(string comPort, int duration, string checkBitEnable, int rangeFromReader, int angleFromReader) { Thread.Sleep(1000); Console.Clear(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("*************** Jack Mode ENGAGED ****************"); Thread.Sleep(1000); Console.Write("Establishing connection"); for (int i = 0; i < 30; i++) { Console.Write("."); i++; Thread.Sleep(100); } Console.WriteLine("."); EM4325Tag tag = new EM4325Tag { Range = rangeFromReader, Angle = angleFromReader, Check = checkBitEnable, FullRead = false }; int[] antennaList = null; double maxTick = 0; double minTick = 100; double tBuff = 0; float goodFrame = 0; float badFrame = 0; float frameRecieved = 0; TagFilter filter0; var csv = new StringBuilder(); csv.Capacity = 1000000; // Need a nice large sized CSV file. int testDuration = duration; DateTime now = DateTime.Now; filter0 = new TagData(tag.defaultEPCHeader); Reader r = Reader.Create(comPort); try { r.Connect(); Console.WriteLine("Connection Successful"); //csv.AppendLine("Time" + "," + "X" + "," + "Y" + "," + "Z"); TagOp op = new Gen2.ReadData(Gen2.Bank.USER, tag.UserMemoryLocation, 3); if (checkBitEnable == "Y") { op = new Gen2.ReadData(Gen2.Bank.USER, tag.UserMemoryLocation, 4); } if (tag.FullRead) { op = new Gen2.ReadData(Gen2.Bank.USER, tag.UserMemoryLocation, 6); } SimpleReadPlan plan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter0, op, true, 150); Gen2.BAPParameters bap = (Gen2.BAPParameters)r.ParamGet("/reader/gen2/bap"); bap.FREQUENCYHOPOFFTIME = 20; bap.POWERUPDELAY = 3; // r.ParamSet("/reader/gen2/Q", new Gen2.StaticQ(2)); r.ParamSet("/reader/gen2/blf", Gen2.LinkFrequency.LINK640KHZ); // this is required to get the desired speed. r.ParamSet("/reader/read/asyncOnTime", testDuration); r.ParamSet("/reader/read/asyncOffTime", 5); r.ParamSet("/reader/read/plan", plan); int checkInt1 = 0; int buffcheck = 0; double tBuffstart = 0; // Create and add tag listeners Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); r.TagRead += delegate(Object sender, TagReadDataEventArgs e) { TimeSpan tsB = stopWatch.Elapsed; tBuffstart = tsB.TotalMilliseconds; double tempV = tBuffstart - tBuff; tag.RSSI = e.TagReadData.Rssi.ToString(); tag.UserMemory = ByteFormat.ToHex(e.TagReadData.Data).ToString(); // convert the input into a hex string tag.EPC = e.TagReadData.EpcString; tag.UserMemory.Trim(); int length = 4; int substringposition = 2; // need to offset two, due to return hex eg 0x2000 if (tag.EPC == tag.defaultEPCHeader) { //SimpleReadPlan planA = new SimpleReadPlan(antennaList, TagProtocol.GEN2, filter1, op, true, 50); while (substringposition < 3) // split the string into small chunks per value and convert to INT { tag.mem1 = tag.UserMemory.Substring(substringposition, length); tag.mem1Int = Convert.ToInt32(tag.mem1, 16); substringposition = substringposition + length; tag.XString = tag.XInteger.ToString(); tag.X = tag.UserMemory.Substring(substringposition, length); tag.YInteger = Convert.ToInt32(tag.Y, 16); substringposition = substringposition + length; tag.YString = tag.YInteger.ToString(); tag.Y = tag.UserMemory.Substring(substringposition, length); tag.ZInteger = Convert.ToInt32(tag.Z, 16); substringposition = substringposition + length; tag.ZString = tag.ZInteger.ToString(); if (checkBitEnable == "Y") { tag.Check = tag.UserMemory.Substring(substringposition, length); checkInt1 = Convert.ToInt32(tag.Check, 16); substringposition = substringposition + length; buffcheck = tag.XInteger + tag.YInteger + tag.ZInteger; } } } if (checkInt1 != buffcheck && checkBitEnable == "Y") // Essentially looking to see if the total sum is correct, if not report a bad frame. { badFrame++; frameRecieved++; } if (checkInt1 == buffcheck || checkBitEnable == "N") { goodFrame++; tsB = stopWatch.Elapsed; tBuff = tsB.TotalMilliseconds; if (tempV > 0.0002) { if (tempV > maxTick) { maxTick = tempV; } if (tempV < minTick) { minTick = tempV; } } frameRecieved++; } }; Console.WriteLine(""); r.StartReading(); Thread.Sleep(testDuration); // File.WriteAllText("C:\\dmp\\testingCrap.csv", csv.ToString()); float ratio = (badFrame / frameRecieved) * 100; float ptime = testDuration / frameRecieved; float accelHZ = (goodFrame / testDuration) * 1000; Console.WriteLine("------------------------------------------"); Console.WriteLine("Summary of stats"); Console.WriteLine("Test conducted " + now.TimeOfDay); Console.WriteLine("EPC : " + tag.EPC); Console.WriteLine("------------------------------------------"); Console.WriteLine("Test Ran for : " + testDuration + " ms "); Console.WriteLine("Number of Packets recieved : " + frameRecieved); Console.WriteLine("CORRUPT Packets : " + badFrame); Console.WriteLine("GOOD Packets : " + goodFrame); Console.WriteLine("Effective Packet loss = " + ratio + " %"); Console.WriteLine("Estimated Packet time : " + ptime + " ms"); Console.WriteLine("Min Packet time : " + minTick + " ms"); Console.WriteLine("Max Packet time : " + maxTick + " ms"); Console.WriteLine("Effective Accel Update rate = " + accelHZ + " Hz"); Console.WriteLine("Reader Range " + tag.Range); Console.WriteLine("Reader Angle " + tag.Angle); csv.AppendLine("------------------------------------------"); csv.AppendLine("Summary of stats"); csv.AppendLine("Test conducted " + now.TimeOfDay); csv.AppendLine("EPC : " + tag.EPC); csv.AppendLine("------------------------------------------"); csv.AppendLine("Test Ran for : " + testDuration + " ms "); csv.AppendLine("Number of Packets recieved : " + frameRecieved); csv.AppendLine("CORRUPT Packets : " + badFrame); csv.AppendLine("GOOD Packets : " + goodFrame); csv.AppendLine("Effective Packet loss = " + ratio + " %"); csv.AppendLine("Estimated Packet time : " + ptime + " ms"); csv.AppendLine("Min Packet time : " + minTick + " ms"); csv.AppendLine("Max Packet time : " + maxTick + " ms"); csv.AppendLine("Effective Accel Update rate = " + accelHZ + " Hz"); csv.AppendLine("Reader Range " + tag.Range); csv.AppendLine("Reader Angle " + tag.Angle); r.Dispose(); Console.WriteLine(""); Console.WriteLine(""); string filename = DateTime.Now.ToString("yyyy-MM-d--HH-mm-ss--Angle--" + angleFromReader); string dateNow = @"C:\temp\" + filename + ".csv"; // The program will log data to a file with a correct Timestamp. try { File.WriteAllText(dateNow, csv.ToString()); } catch (ArgumentException e) { // Console.WriteLine("Can't write file."); Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message); } Console.WriteLine("Preparing for next run"); for (int i = 0; i < 30; i++) { Console.Write("."); i++; Thread.Sleep(100); } Console.WriteLine("."); stopWatch.Stop(); Thread.Sleep(2500); Console.Clear(); Console.WriteLine(""); } catch { Console.WriteLine("Connection Failed."); Console.WriteLine("Please retry (press any key or crtl-c to exit)"); if (Console.ReadKey() != null) { } } }
/// <summary> /// 连接采集设备 /// </summary> private void Running() { while (Runningl) { try { reader = Reader.Create(sparmas.Comv, (ModuleTech.Region)sparmas.Region, (ReaderType)sparmas.ReaderType); Funpercent(30, "创建读写器完毕"); // reader.ParamSet("CheckAntConnection", sparmas.CheckAnt); Funpercent(40, "检测天线"); AntPower[] apwrs = new AntPower[sparmas.AntType]; for (int i = 0; i < apwrs.Length; i++) { apwrs[i].AntId = (byte)(i + 1); apwrs[i].ReadPower = ushort.Parse(sparmas.ReadPw[i]); apwrs[i].WritePower = ushort.Parse(sparmas.WritePw[i]); } reader.ParamSet("AntPowerConf", apwrs); Funpercent(50, "配置天线功率"); reader.ParamSet("TagopAntenna", sparmas.Opant); Funpercent(60, "配置默认天线"); int[] connectedants = (int[])reader.ParamGet("ConnectedAntennas"); SimpleReadPlan gen2srp = null; SimpleReadPlan iso6bsrp = null; if (connectedants.Length > 0) { sparmas.Connectants = connectedants; gen2srp = new SimpleReadPlan(TagProtocol.GEN2, connectedants); iso6bsrp = new SimpleReadPlan(TagProtocol.ISO180006B, connectedants); } else { sparmas.Connectants = null; gen2srp = new SimpleReadPlan(TagProtocol.GEN2, new int[] { sparmas.Opant }); iso6bsrp = new SimpleReadPlan(TagProtocol.ISO180006B, new int[] { sparmas.Opant }); } if (sparmas.Protocol == 0) { reader.ParamSet("ReadPlan", gen2srp); Funpercent(70, "配置盘点方式"); } else if (sparmas.Protocol == 1) { reader.ParamSet("ReadPlan", iso6bsrp); Funpercent(70, "配置盘点方式"); } else { ReadPlan[] rp = new ReadPlan[2]; rp[0] = gen2srp; rp[1] = iso6bsrp; MultiReadPlan mrp = new MultiReadPlan(rp); reader.ParamSet("ReadPlan", rp); Funpercent(70, "配置盘点方式"); } reader.ParamSet("Gen2Session", (ModuleTech.Gen2.Session)sparmas.Session); Funpercent(80, "配置会话模式"); if (sparmas.CustomFrequency) { List <uint> htb = new List <uint>(); for (int i = 0; i < sparmas.Frequencys.Length; i++) { htb.Add(uint.Parse(sparmas.Frequencys[i])); } reader.ParamSet("FrequencyHopTable", htb.ToArray()); Funpercent(90, "配置频率表"); } else { reader.ParamSet("Region", (ModuleTech.Region)sparmas.Region); Funpercent(90, "配置频率表"); } try { reader.ParamSet("PowerMode", (byte)sparmas.PowerMode); reader.ParamSet("IsTransmitPowerSave", true); } catch (Exception omitex) { } Funpercent(100, "配置完毕,读写器工作就绪"); } catch (System.Exception ex) { string msg = string.Empty; if (ex is ModuleLibrary.FatalInternalException) { msg = Convert.ToString(((ModuleLibrary.FatalInternalException)ex).ErrCode, 16); } if (ex is ModuleLibrary.HardwareAlertException) { msg = Convert.ToString(((ModuleLibrary.HardwareAlertException)ex).ErrCode, 16); } if (ex is ModuleLibrary.ModuleException) { msg = Convert.ToString(((ModuleLibrary.ModuleException)ex).ErrCode, 16); } if (ex is ModuleLibrary.OpFaidedException) { msg = Convert.ToString(((ModuleLibrary.OpFaidedException)ex).ErrCode, 16); } if (reader != null) { reader.Disconnect(); } Funpercent(0, "连接失败" + ex.Message + " :" + msg); dlog.WirteLog(ex.Message + ":" + msg + ex.StackTrace); } Thread.Sleep(1000); Runningl = false; } IsExit = false; Funpercent(-100, string.Empty); }
/// <summary> /// 连接采集设备 /// </summary> private void Running() { while (Runningl) { try { reader = Reader.Create(sparmas.Comv, (ModuleTech.Region)sparmas.Region, (ReaderType)sparmas.ReaderType); Funpercent(30, "创建读写器完毕"); // reader.ParamSet("CheckAntConnection", sparmas.CheckAnt); Funpercent(40, "检测天线"); AntPower[] apwrs = new AntPower[sparmas.AntType]; for (int i = 0; i < apwrs.Length; i++) { apwrs[i].AntId = (byte)(i + 1); apwrs[i].ReadPower = ushort.Parse(sparmas.ReadPw[i]); apwrs[i].WritePower = ushort.Parse(sparmas.WritePw[i]); } reader.ParamSet("AntPowerConf", apwrs); Funpercent(50, "配置天线功率"); reader.ParamSet("TagopAntenna", sparmas.Opant); Funpercent(60, "配置默认天线"); int[] connectedants = (int[])reader.ParamGet("ConnectedAntennas"); SimpleReadPlan gen2srp = null; SimpleReadPlan iso6bsrp = null; if (connectedants.Length > 0) { sparmas.Connectants = connectedants; gen2srp = new SimpleReadPlan(TagProtocol.GEN2, connectedants); iso6bsrp = new SimpleReadPlan(TagProtocol.ISO180006B, connectedants); } else { sparmas.Connectants = null; gen2srp = new SimpleReadPlan(TagProtocol.GEN2, new int[] { sparmas.Opant }); iso6bsrp = new SimpleReadPlan(TagProtocol.ISO180006B, new int[] { sparmas.Opant }); } if (sparmas.Protocol == 0) { reader.ParamSet("ReadPlan", gen2srp); Funpercent(70, "配置盘点方式"); } else if (sparmas.Protocol == 1) { reader.ParamSet("ReadPlan", iso6bsrp); Funpercent(70, "配置盘点方式"); } else { ReadPlan[] rp = new ReadPlan[2]; rp[0] = gen2srp; rp[1] = iso6bsrp; MultiReadPlan mrp = new MultiReadPlan(rp); reader.ParamSet("ReadPlan", rp); Funpercent(70, "配置盘点方式"); } reader.ParamSet("Gen2Session", (ModuleTech.Gen2.Session)sparmas.Session); Funpercent(80, "配置会话模式"); if (sparmas.CustomFrequency) { List<uint> htb = new List<uint>(); for (int i = 0; i < sparmas.Frequencys.Length; i++) { htb.Add(uint.Parse(sparmas.Frequencys[i])); } reader.ParamSet("FrequencyHopTable", htb.ToArray()); Funpercent(90, "配置频率表"); } else { reader.ParamSet("Region", (ModuleTech.Region)sparmas.Region); Funpercent(90, "配置频率表"); } try { reader.ParamSet("PowerMode", (byte)sparmas.PowerMode); reader.ParamSet("IsTransmitPowerSave", true); } catch (Exception omitex) { } Funpercent(100, "配置完毕,读写器工作就绪"); } catch (System.Exception ex) { string msg = string.Empty; if (ex is ModuleLibrary.FatalInternalException) msg = Convert.ToString(((ModuleLibrary.FatalInternalException)ex).ErrCode, 16); if (ex is ModuleLibrary.HardwareAlertException) msg = Convert.ToString(((ModuleLibrary.HardwareAlertException)ex).ErrCode, 16); if (ex is ModuleLibrary.ModuleException) msg = Convert.ToString(((ModuleLibrary.ModuleException)ex).ErrCode, 16); if (ex is ModuleLibrary.OpFaidedException) msg = Convert.ToString(((ModuleLibrary.OpFaidedException)ex).ErrCode, 16); if (reader != null) reader.Disconnect(); Funpercent(0, "连接失败" + ex.Message + " :" + msg); dlog.WirteLog(ex.Message + ":" + msg + ex.StackTrace); } Thread.Sleep(1000); Runningl = false; } IsExit = false; Funpercent(-100, string.Empty); }
private void LoadAscmReadingHead() { List<AscmReadingHead> listAscmReadingHead = null; m_readerWriterLock_readingHead.AcquireReaderLock(10000); try { //listAscmReadingHead = AscmWsInterface.GetInstance().GetAllAscmReadingHeadList(); listAscmReadingHead = AscmReadingHeadService.GetInstance().GetList(null, null, null, "", ""); if (listAscmReadingHead != null) { listAscmReadingHead = listAscmReadingHead.Where(P => P.ip.Trim() != "0.0.0.0").ToList(); } // } catch (Exception ex) { this.AddLog("加载读写器异常:" + ex.Message); } m_readerWriterLock_readingHead.ReleaseReaderLock(); try { //增加 foreach (AscmReadingHead ascmReadingHead in listAscmReadingHead) { ReadingHead readingHead = listReadingHead.Find(e => e.ascmReadingHead.id == ascmReadingHead.id); if (readingHead == null) { readingHead = new ReadingHead(); readingHead.ascmReadingHead = ascmReadingHead; //readingHead.StartThread(); ReadingHeadThreadClass readingHeadThreadClass = new ReadingHeadThreadClass(WriteLogFile, readingHead); //线程终止后不能重启 if (readingHead.thread != null) { readingHead.thread.Abort(); } //this.AddLog("加载读写器:" + ascmReadingHead.ip); try { //连接 //ascmReadingHead.ip = "192.168.1.100"; //readingHead.modulerReader = Reader.Create(ascmReadingHead.ip, ModuleTech.Region.NA, 16); readingHead.modulerReader = Reader.Create(ascmReadingHead.ip, ModuleTech.Region.NA, 4); readingHead.moduleTech_isConnect = true; //设置天线 int[] ants = new int[] { 1,2,3,4};//天线全部是四天线; SimpleReadPlan plan = new SimpleReadPlan(ants); readingHead.modulerReader.ParamSet("ReadPlan", plan); //设置功率 List<AntPower> antspwr = new List<AntPower>(); antspwr.Add(new AntPower((byte)1, 3000, 3000)); antspwr.Add(new AntPower((byte)2, 3000, 3000)); antspwr.Add(new AntPower((byte)3, 3000, 3000)); antspwr.Add(new AntPower((byte)4, 3000, 3000)); readingHead.modulerReader.ParamSet("AntPowerConf", antspwr.ToArray()); //设置格式 readingHead.modulerReader.ParamSet("Gen2Session", ModuleTech.Gen2.Session.Session1); //设置读取位置 EmbededCmdData ecd = new EmbededCmdData(ModuleTech.Gen2.MemBank.EPC, 2, 4); readingHead.modulerReader.ParamSet("EmbededCmdOfInventory", ecd); //开启线程 readingHead.thread = new Thread(readingHeadThreadClass.Read); readingHead.thread.IsBackground = true; readingHead.bThread = true; readingHead.thread.Start(); listReadingHead.Add(readingHead); } catch (Exception ex) { this.AddLog("加载读写器失败[" + ascmReadingHead.ip + "]:" + ex.Message); } } } //删除没有的设备或失败的线程 for (int iReadingHead = listReadingHead.Count - 1; iReadingHead >= 0; iReadingHead--) { ReadingHead readingHead = listReadingHead[iReadingHead]; AscmReadingHead ascmReadingHead = listAscmReadingHead.Find(e => readingHead.ascmReadingHead.id == e.id); if (ascmReadingHead == null || readingHead.thread == null || !readingHead.bThread) { readingHead.StopThread(); listReadingHead.RemoveAt(iReadingHead); } } } catch (Exception ex) { this.AddLog("加载读写器异常:" + ex.Message); } }
static void Main(string[] args) { // Program setup if (1 != args.Length) { Console.WriteLine(String.Join("\r\n", new string[] { "Please provide reader URL, such as:", "tmr:///com4", "tmr://my-reader.example.com", })); Environment.Exit(1); } try { // Create Reader object, connecting to physical device. // Wrap reader in a "using" block to get automatic // reader shutdown (using IDisposable interface). using (Reader r = Reader.Create(args[0])) { //Uncomment this line to add default transport listener. //r.Transport += r.SimpleTransportListener; r.Connect(); if (Reader.Region.UNSPEC == (Reader.Region)r.ParamGet("/reader/region/id")) { Reader.Region[] supportedRegions = (Reader.Region[])r.ParamGet("/reader/region/supportedRegions"); if (supportedRegions.Length < 1) { throw new FAULT_INVALID_REGION_Exception(); } else { r.ParamSet("/reader/region/id", supportedRegions[0]); } } // Read Plan byte length; string model = (string)r.ParamGet("/reader/version/model"); if ("M6e".Equals(model) || "M6e PRC".Equals(model) || "M6e Micro".Equals(model) || "Mercury6".Equals(model) || "Astra-EX".Equals(model)) { // Specifying the readLength = 0 will return full TID for any tag read in case of M6e varients, M6 and Astra-EX reader. length = 0; } else { length = 2; } // Embedded Secure Read Tag Operation - Standalone operation not supported Gen2.Password password = new Gen2.Password(0); Gen2.SecureReadData secureReadDataTagOp = new Gen2.SecureReadData(Gen2.Bank.TID, 0, (byte)0, Gen2.SecureTagType.HIGGS3, password);; SimpleReadPlan plan = new SimpleReadPlan(null, TagProtocol.GEN2, null, secureReadDataTagOp, 1000); r.ParamSet("/reader/read/plan", plan); // Create and add tag listener r.TagRead += delegate(Object sender, TagReadDataEventArgs e) { Console.WriteLine("Background read: " + e.TagReadData); Console.WriteLine("Requested data: " + ByteFormat.ToHex(e.TagReadData.Data)); }; // Create and add read exception listener r.ReadException += r_ReadException; // Create and add read authenticate listener r.ReadAuthentication += r_ReadAuthenticationListener; // Search for tags in the background r.StartReading(); Console.WriteLine("\r\n<Do other work here>\r\n"); Thread.Sleep(500); Console.WriteLine("\r\n<Do other work here>\r\n"); Thread.Sleep(500); r.StopReading(); } } catch (ReaderException re) { Console.WriteLine("Error: " + re.Message); Console.Out.Flush(); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
public void resetParams() { isIpModify = false; isM5eModify = false; fisrtLoad = true; ip = ""; subnet = ""; gateway = ""; macstr = ""; hasIP = false; isGetIp = false; Gen2Qval = -2; isCheckConnection = false; isMultiPotl = false; antcnt = -1; SixteenDevsrp = null; SixteenDevConAnts = null; isRevertAnts = false; weightgen2 = 30; weight180006b = 30; weightipx64 = 30; weightipx256 = 30; isChangeColor = true; isUniByEmd = false; isUniByAnt = false; isIdtAnts = false; IdtAntsType = 0; DurIdtval = 0; AfterIdtWaitval = 0; FixReadCount = 0; isReadFixCount = false; isOneReadOneTime = false; usecase_ishighspeedblf = false; usecase_tagcnt = -1; usecase_readperform = -1; usecase_antcnt = -1; }
static void Main(string[] args) { // Program setup if (1 > args.Length) { Usage(); } string readerName = null; int[] antennaList = null; Dictionary <string, int[]> readerPort = new Dictionary <string, int[]>(); for (int nextarg = 0; nextarg < args.Length; nextarg++) { string arg = args[nextarg]; if (arg.Equals("--ant")) { if (null != readerName) { if (null != antennaList) { Console.WriteLine("Duplicate argument: --ant specified more than once"); Usage(); } antennaList = ParseAntennaList(args, nextarg); nextarg++; } else { Usage(); } } else { if (null != readerName) { readerPort.Add(readerName, antennaList); antennaList = null; } readerName = arg; } } if (null != readerName) { // Output the previously-parsed reader name and antenna list readerPort.Add(readerName, antennaList); readerName = null; antennaList = null; } try { Reader[] r = new Reader[readerPort.Count]; int i = 0; foreach (KeyValuePair <string, int[]> pair in readerPort) { r[i] = Reader.Create(pair.Key); //Uncomment this line to add default transport listener. //r[i].Transport += r[i].SimpleTransportListener; Console.WriteLine("Created Reader {0},{1}", i, (string)r[i].ParamGet("/reader/uri")); r[i].Connect(); if (Reader.Region.UNSPEC == (Reader.Region)r[i].ParamGet("/reader/region/id")) { Reader.Region[] supportedRegions = (Reader.Region[])r[i].ParamGet("/reader/region/supportedRegions"); if (supportedRegions.Length < 1) { throw new FAULT_INVALID_REGION_Exception(); } r[i].ParamSet("/reader/region/id", supportedRegions[0]); } if (r[i].isAntDetectEnabled(antennaList) && readerPort[pair.Key] == null) { Console.WriteLine("Module doesn't has antenna detection support please provide antenna list"); Usage(); } r[i].NoofMultiReaders = true; // Create a simplereadplan which uses the antenna list created above SimpleReadPlan plan = new SimpleReadPlan(pair.Value, TagProtocol.GEN2, null, null, 1000); // Set the created readplan r[i].ParamSet("/reader/read/plan", plan); // Create and add tag listener r[i].TagRead += PrintTagreads; // Create and add read exception listener r[i].ReadException += new EventHandler <ReaderExceptionEventArgs>(r_ReadException); // Search for tags in the background r[i].StartReading(); i++; } Console.WriteLine("\r\n<Do other work here>\r\n"); Thread.Sleep(5000); Console.WriteLine("\r\n<Do other work here>\r\n"); Thread.Sleep(5000); for (int j = 0; j < readerPort.Count; j++) { r[j].StopReading(); r[j].Destroy(); } //r[i].NoofMultiReaders = false; } catch (ReaderException re) { Console.WriteLine("Error: " + re.Message); Console.Out.Flush(); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
static void Main(string[] args) { // Program setup if (1 > args.Length) { Usage(); } int[] antennaList = null; for (int nextarg = 1; nextarg < args.Length; nextarg++) { string arg = args[nextarg]; if (arg.Equals("--ant")) { if (null != antennaList) { Console.WriteLine("Duplicate argument: --ant specified more than once"); Usage(); } antennaList = ParseAntennaList(args, nextarg); nextarg++; } else { Console.WriteLine("Argument {0}:\"{1}\" is not recognized", nextarg, arg); Usage(); } } // Create Reader object, connecting to physical device try { Reader r; TagReadData[] filteredTagReads; r = Reader.Create(args[0]); //Uncomment this line to add default transport listener. r.Transport += r.SimpleTransportListener; r.Connect(); if (Reader.Region.UNSPEC == (Reader.Region)r.ParamGet("/reader/region/id")) { Reader.Region[] supportedRegions = (Reader.Region[])r.ParamGet("/reader/region/supportedRegions"); if (supportedRegions.Length < 1) { throw new FAULT_INVALID_REGION_Exception(); } r.ParamSet("/reader/region/id", supportedRegions[0]); } if (r.isAntDetectEnabled(antennaList)) { Console.WriteLine("Module doesn't has antenna detection support please provide antenna list"); Usage(); } ////To perform standalone operations if (antennaList != null) { r.ParamSet("/reader/tagop/antenna", antennaList[0]); } try { Gen2.Select tidFilter = new Gen2.Select(false, Gen2.Bank.TID, 32, 16, new byte[] { (byte)0x01, (byte)0x2E }); tidFilter.target = Gen2.Select.Target.Inventoried_S1; tidFilter.action = Gen2.Select.Action.ON_N_OFF; Gen2.Select epcFilter = new Gen2.Select(false, Gen2.Bank.EPC, 32, 16, new byte[] { (byte)0x11, (byte)0x22 }); epcFilter.target = Gen2.Select.Target.Inventoried_S1; epcFilter.action = Gen2.Select.Action.NEG_N_NOP; CustomAntConfigPerAntenna sig = new CustomAntConfigPerAntenna(Gen2.Session.S1, Gen2.Target.A, tidFilter, 1); CustomAntConfigPerAntenna sig2 = new CustomAntConfigPerAntenna(Gen2.Session.S1, Gen2.Target.A, epcFilter, 2); List <CustomAntConfigPerAntenna> CustomConfigAnt = new List <CustomAntConfigPerAntenna>(); CustomConfigAnt.Add(sig); CustomConfigAnt.Add(sig2); //parameters in the CustomAntConfig //1. No. of antennas //2. List of CustomAntConfigPerAntenna //3. Fast search enabled / disabled //4. Dynamic - 1(default)/ Equal //5. Tagreadtimeout CustomAntConfig cnf = new CustomAntConfig(2, CustomConfigAnt, false, 1, 50000); SimpleReadPlan srp = new SimpleReadPlan(antennaList, TagProtocol.GEN2, null, cnf); r.ParamSet("/reader/read/plan", srp); ////Sync Read //// //filteredTagReads = r.Read(5000); //foreach (TagReadData tr in filteredTagReads) // Console.WriteLine(tr.ToString()); //Console.WriteLine(); ////Async read r.TagRead += delegate(Object sender, TagReadDataEventArgs e) { Console.WriteLine("Background read: " + e.TagReadData); }; // Create and add read exception listener r.ReadException += new EventHandler <ReaderExceptionEventArgs>(r_ReadException); // Search for tags in the background r.StartReading(); Console.WriteLine("\r\n<Do other work here>\r\n"); Thread.Sleep(500); r.StopReading(); } finally { } // Shut down reader r.Destroy(); } catch (ReaderException re) { Console.WriteLine("Error: " + re.Message); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
static void Main(string[] args) { uint timeout = 0; uint configFlags = 0; List <byte> buffer = new List <byte>(); byte flags = 0; PassThrough passThroughOp; byte[] passThroughResp; // Program setup if (1 > args.Length) { Usage(); } try { // Create Reader object, connecting to physical device. // Wrap reader in a "using" block to get automatic // reader shutdown (using IDisposable interface). using (Reader r = Reader.Create(args[0])) { //Uncomment this line to add default transport listener. //r.Transport += r.SimpleTransportListener; r.Connect(); // Perform sync read for 500ms SimpleReadPlan plan = new SimpleReadPlan(null, TagProtocol.ISO15693, null, null, 1000); // Set the created readplan r.ParamSet("/reader/read/plan", plan); // Read tags TagReadData[] tagReads = r.Read(500); // Print first tag read epc byte[] epc = tagReads[0].Epc; Console.WriteLine("Tag ID: " + tagReads[0].EpcString); //Select Tag timeout = 500; //timeout in milliseconds. flags = 0x22; configFlags = (uint)(ConfigFlags.ENABLE_TX_CRC | ConfigFlags.ENABLE_RX_CRC | ConfigFlags.ENABLE_INVENTORY); //Frame payload data as per 15693 protocol(ICODE Slix-S) buffer.Add(flags); buffer.Add(OPCODE_SELECT_TAG); //Append UID(reverse). buffer.AddRange(appendReverseUID(epc)); //Execute passthrough tag op to select a tag passThroughOp = new PassThrough(timeout, configFlags, buffer); passThroughResp = (byte[])r.ExecuteTagOp(passThroughOp, null); if (passThroughResp.Length > 0) { Console.WriteLine("Select Tag| Data(" + passThroughResp.Length + "): " + ByteFormat.ToHex(passThroughResp, "", "")); } //Reset command buffer buffer.Clear(); //Get random number // Initialize passthrough tag operation with all the required fields flags = 0x12; configFlags = (uint)(ConfigFlags.ENABLE_TX_CRC | ConfigFlags.ENABLE_RX_CRC | ConfigFlags.ENABLE_INVENTORY); //Extract random number from response(ICODE Slix-S) buffer.Add(flags); buffer.Add(GET_RANDOM_NUMBER); buffer.Add(IC_MFG_CODE_NXP); passThroughOp = new PassThrough(timeout, configFlags, buffer); passThroughResp = (byte[])r.ExecuteTagOp(passThroughOp, null); if (passThroughResp.Length > 0) { Console.WriteLine("RN number | Data(" + passThroughResp.Length + "): " + ByteFormat.ToHex(passThroughResp, "", "")); } } } catch (ReaderException re) { Console.WriteLine("Error: " + re.Message); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
static void Main(string[] args) { // Program setup if (1 > args.Length) { Usage(); } int[] antennaList = null; for (int nextarg = 1; nextarg < args.Length; nextarg++) { string arg = args[nextarg]; if (arg.Equals("--ant")) { if (null != antennaList) { Console.WriteLine("Duplicate argument: --ant specified more than once"); Usage(); } antennaList = ParseAntennaList(args, nextarg); nextarg++; } else { Console.WriteLine("Argument {0}:\"{1}\" is not recognized", nextarg, arg); Usage(); } } try { // Create Reader object, connecting to physical device. // Wrap reader in a "using" block to get automatic // reader shutdown (using IDisposable interface). using (Reader r = Reader.Create(args[0])) { //Uncomment this line to add default transport listener. //r.Transport += r.SimpleTransportListener; r.Connect(); if (Reader.Region.UNSPEC == (Reader.Region)r.ParamGet("/reader/region/id")) { Reader.Region[] supportedRegions = (Reader.Region[])r.ParamGet("/reader/region/supportedRegions"); if (supportedRegions.Length < 1) { throw new FAULT_INVALID_REGION_Exception(); } r.ParamSet("/reader/region/id", supportedRegions[0]); } string model = (string)r.ParamGet("/reader/version/model").ToString(); if (!model.Equals("M3e")) { if (r.isAntDetectEnabled(antennaList)) { Console.WriteLine("Module doesn't has antenna detection support please provide antenna list"); Usage(); } } else { if (antennaList != null) { Console.WriteLine("Module doesn't support antenna input"); Usage(); } } // Create a simplereadplan which uses the antenna list created above SimpleReadPlan plan; if (model.Equals("M3e")) { // initializing the simple read plan plan = new SimpleReadPlan(antennaList, TagProtocol.ISO14443A, null, null, 1000); } else { plan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, null, null, 1000); } // Set the created readplan r.ParamSet("/reader/read/plan", plan); // Create and add tag listener CountMatchListener cml = new CountMatchListener(0xE2); r.TagRead += cml.TagRead; // Create and add read exception listener r.ReadException += new EventHandler <ReaderExceptionEventArgs>(r_ReadException); // Search for tags in the background r.StartReading(); Thread.Sleep(500); r.StopReading(); r.TagRead -= cml.TagRead; // Print results of search, accumulated in listener object Console.WriteLine("Matching tags: " + cml.Matched); Console.WriteLine("Non-matching tags: " + cml.NonMatched); } } catch (ReaderException re) { Console.WriteLine("Error: " + re.Message); Console.Out.Flush(); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
// TODO: Merge common functionality between KeyboardWedgeRead and ReadTags.ReadtheTags private void KeyboardWedgeRead() { List<SendInputWrapper.INPUT> inputList = new List<SendInputWrapper.INPUT>(); string startIndicator = "."; // Signal start of read inputList.Clear(); AddKeypresses(inputList, startIndicator); SendInput(inputList); properties = Utilities.GetProperties(); SoundPlayer startSound = new SoundPlayer(properties["startscanwavefile"]); if (properties["audiblealert"].ToLower() == "yes") { startSound.Play(); } SoundPlayer stopSound = new SoundPlayer(properties["endscanwavefile"]); stopSound.LoadAsync(); CoreDLL.SYSTEM_POWER_STATUS_EX status = new CoreDLL.SYSTEM_POWER_STATUS_EX(); //Check the battery power level if (CoreDLL.GetSystemPowerStatusEx(status, false) == 1) { if (status.BatteryLifePercent <= 5) { if (status.ACLineStatus == 0) { MessageBox.Show("Battery level is low to read tags"); return; } } } try { TagReadData[] reads; //Utilities.PowerManager.PowerNotify += new PowerManager.PowerEventHandler(PowerManager_PowerNotify); using (ThingMagic.RFIDSearchLight.ReadMgr.Session rsess = ThingMagic.RFIDSearchLight.ReadMgr.GetSession()) { #if DEBUG if (properties["audiblealert"].ToLower() == "yes") { startSound.Play(); } #endif int radioPower = 0; if (properties["readpower"].ToString() == "") { radioPower = 2300;//While reading read power should be max } else { radioPower = Convert.ToInt32(properties["readpower"].ToString()); } //Set the region string region = properties["region"]; try { Utilities.SwitchRegion(region); } catch (ArgumentException) { MessageBox.Show( "Unknown Region: " + region + "\r\n" + "Please run RFIDSearchLight to initialize the region." ); } rsess.Reader.ParamSet("/reader/powerMode", Reader.PowerMode.FULL); rsess.Reader.ParamSet("/reader/radio/readPower", radioPower); rsess.Reader.ParamSet("/reader/antenna/txRxMap", new int[][] { new int[] { 1, 1, 1 } }); List<int> ant = new List<int>(); ant.Add(1); //set the tag population settings rsess.Reader.ParamSet("/reader/gen2/target", Gen2.Target.A);//default target string tagPopulation = properties["tagpopulation"]; switch (tagPopulation) { case "small": rsess.Reader.ParamSet("/reader/gen2/q", new Gen2.StaticQ(2)); rsess.Reader.ParamSet("/reader/gen2/session", Gen2.Session.S0); rsess.Reader.ParamSet("/reader/gen2/tagEncoding", Gen2.TagEncoding.M4); break; case "medium": rsess.Reader.ParamSet("/reader/gen2/q", new Gen2.StaticQ(4)); rsess.Reader.ParamSet("/reader/gen2/session", Gen2.Session.S1); rsess.Reader.ParamSet("/reader/gen2/tagEncoding", Gen2.TagEncoding.M4); break; case "large": rsess.Reader.ParamSet("/reader/gen2/q", new Gen2.StaticQ(6)); rsess.Reader.ParamSet("/reader/gen2/session", Gen2.Session.S2); rsess.Reader.ParamSet("/reader/gen2/tagEncoding", Gen2.TagEncoding.M2); break; default: break; } //set the read plan and filter TagFilter filter; int addressToRead = int.Parse(properties["selectionaddress"]); Gen2.Bank bank = Gen2.Bank.EPC; switch (properties["tagselection"].ToLower()) { case "None": case "epc": bank = Gen2.Bank.EPC; break; case "tid": bank = Gen2.Bank.TID; break; case "user": bank = Gen2.Bank.USER; break; case "reserved": bank = Gen2.Bank.RESERVED; break; default: break; } if ("yes" == properties["ismaskselected"]) { filter = new Gen2.Select(true, bank, (uint)addressToRead * 8, (ushort)(properties["selectionmask"].Length * 4), ByteFormat.FromHex(properties["selectionmask"])); } else { filter = new Gen2.Select(false, bank, (uint)addressToRead * 8, (ushort)(properties["selectionmask"].Length * 4), ByteFormat.FromHex(properties["selectionmask"])); } //set the read plan SimpleReadPlan srp; if (properties["tagselection"].ToLower() == "none") { srp = new SimpleReadPlan(new int[] { 1 }, TagProtocol.GEN2, null, 0); } else { srp = new SimpleReadPlan(new int[] { 1 }, TagProtocol.GEN2, filter, 0); } rsess.Reader.ParamSet("/reader/read/plan", srp); double readDuration = Convert.ToDouble(properties["scanduration"].ToString()) * 1000; int readTimeout = Convert.ToInt32(readDuration); //Do a sync read for the readduration #if DEBUG if (properties["audiblealert"].ToLower() == "yes") { startSound.Play(); } #endif reads = rsess.Reader.Read(readTimeout); rsess.Reader.ParamSet("/reader/powerMode", Reader.PowerMode.MINSAVE); if (properties["audiblealert"].ToLower() == "yes") { stopSound.Play(); } // Clear start indicator inputList.Clear(); for (int i = 0; i < startIndicator.Length; i++) { AddKeypresses(inputList, new byte[] { // Don't send Backspace -- that's one of our hotkeys, // so it'll put us in an infinite loop. (byte)Keys.Left, (byte)Keys.Delete, }); } SendInput(inputList); } inputList.Clear(); //HideWindow(); bool timestamp = false, rssi = false, position = false; string[] metadata = properties["metadatatodisplay"].Split(','); //Metadata boolean variables foreach (string mdata in metadata) { switch (mdata.ToLower()) { case "timestamp": timestamp = true; break; case "rssi": rssi = true; break; case "position": position = true; break; default: break; } } string metadataseparator = properties["metadataseparator"]; byte metadataseparatorInByte = 0x00; switch (metadataseparator.ToLower()) { //The byte representation of special characters can be found here - http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx case "comma": metadataseparatorInByte = 0xBC; break; case "space": metadataseparatorInByte = 0x20; break; case "enter": metadataseparatorInByte = 0x0D; break; case "tab": metadataseparatorInByte = 0x09; break; default: break; } //Print the epc in caps AddKeypress(inputList, (byte)Keys.Capital); // Toggle Caps Lock //Print the tag reads foreach (TagReadData dat in reads) { string tagData = string.Empty; string epc = string.Empty; if (properties["displayformat"] == "base36") { epc = ConvertEPC.ConvertHexToBase36(dat.EpcString); } else { epc = dat.EpcString; } AddKeypresses(inputList, properties["prefix"].ToUpper()); AddKeypresses(inputList, epc.ToUpper()); AddKeypresses(inputList, properties["suffix"].ToUpper()); if (timestamp) { AddKeypress(inputList, metadataseparatorInByte); AddKeypresses(inputList, dat.Time.ToString("yyyy-MM-dd-HH-mm-ss")); } if (rssi) { AddKeypress(inputList, metadataseparatorInByte); AddKeypresses(inputList, dat.Rssi.ToString()); } if (position) { AddKeypress(inputList, metadataseparatorInByte); AddKeypresses(inputList, GpsMgr.LatLonString); } switch (properties["multipletagseparator"].ToLower()) { case "comma": AddKeypress(inputList, 0xBC); break; case "space": AddKeypress(inputList, 0x20); break; case "enter": AddKeypress(inputList, 0x0D); break; case "tab": AddKeypress(inputList, 0x09); break; case "pipe": AddInput(inputList, SHIFT_DOWN); AddKeypress(inputList, 0xDC); AddInput(inputList, SHIFT_UP); break; default: break; } // Send keystrokes after each tag read record -- input buffer // isn't big enough to hold more than a few lines SendInput(inputList); inputList.Clear(); } //Turn caps lock back off AddKeypress(inputList, (byte)Keys.Capital); // Toggle Caps Lock SendInput(inputList); } catch (Exception ex) { logger.Error("In KeyboardWedgeRead(): " + ex.ToString()); //MessageBox.Show(ex.Message); //Debug.Log(ex.ToString()); } }
private void btnRead_Click(object sender, RoutedEventArgs e) { Mouse.SetCursor(Cursors.Wait); TagReadData[] tagReads = null; try { rbEPCAscii.IsEnabled = true; rbEPCBase36.IsEnabled = true; if (btnRead.Content.Equals("Read")) { SimpleReadPlan srp = new SimpleReadPlan(((null != GetSelectedAntennaList()) ? (new int[] { GetSelectedAntennaList()[0] }) : null), TagProtocol.GEN2, null, 0); objReader.ParamSet("/reader/read/plan", srp); tagReads = objReader.Read(500); if ((null != tagReads) && (tagReads.Length > 0)) { currentEPC = tagReads[0].EpcString; if ((bool)rbEPCAscii.IsChecked) { txtEpc.Text = Utilities.HexStringToAsciiString(tagReads[0].EpcString); } else if ((bool)rbEPCBase36.IsChecked) { txtEpc.Text = Utilities.ConvertHexToBase36(tagReads[0].EpcString); } else { txtEpc.Text = tagReads[0].EpcString; } lblSelectFilter.Content = "Showing tag: EPC ID = " + tagReads[0].EpcString; if (tagReads.Length > 1) { lblTagInspectorError.Content = "Warning: More than one tag responded"; lblTagInspectorError.Visibility = System.Windows.Visibility.Visible; } else { lblTagInspectorError.Visibility = System.Windows.Visibility.Collapsed; } } else { txtEpc.Text = ""; currentEPC = string.Empty; MessageBox.Show("No tags found", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } else { rbSelectedTagIns.IsChecked = true; } PopulateData(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } finally { Mouse.SetCursor(Cursors.Arrow); } }