Пример #1
0
        static void Main(string[] args)
        {
            //Connecting the reader and setting base parameters
            Reader r = Reader.Create("tmr:///COM3");

            r.Connect();
            r.ParamSet("/reader/region/id", Reader.Region.NA); //Region
            r.ParamSet("/reader/radio/readPower", 2000);       //Read power
            r.ParamSet("/reader/gen2/t4", 3000);               //3ms continuous wave

            //Defining the Select command to the tag
            Gen2.Select tempSelect = new Gen2.Select(false, Gen2.Bank.USER, 0xE0, 0, new byte[0]);

            //Storing Temperature data in reserved memory bank pointed at 0xE
            TagOp tempRead = new Gen2.ReadData(Gen2.Bank.RESERVED, 0xE, 1);

            SimpleReadPlan readPlan = new SimpleReadPlan(new int[] { 1 }, TagProtocol.GEN2, tempSelect, tempRead, 100);

            r.ParamSet("/reader/read/plan", readPlan);
            TagReadData[] tempReadResults = r.Read(75); //Read for 75ms

            foreach (TagReadData result in tempReadResults)
            {
                string EPC         = result.EpcString;
                string frequency   = result.Frequency.ToString();
                string tempCodeHex = ByteFormat.ToHex(result.Data, ", ");
                int    tempCode    = Convert.ToInt32(tempCodeHex, 16);
                if (tempCode > 1000 && tempCode < 3500)
                {
                    Console.WriteLine("EPC: " + EPC + "Frequency(kHz): " + frequency + "Temperature Code: " + tempCode);
                }
            }
        }
Пример #2
0
        /// <summary>
        /// Read tag memory for readers or modules other the M5e variants
        /// </summary>
        /// <param name="bank">Gen2 memory bank</param>
        /// <param name="filter">filter</param>
        /// <param name="MemData">Data read from tag memory</param>
        private void ReadMemoryM6eVariants(Gen2.Bank bank, TagFilter filter, ref ushort[] MemData)
        {
            try
            {
                // Read tag memory with zero as start address and lenght of words to read as zero
                TagOp op = new Gen2.ReadData(bank, 0, 0);
                MemData = (ushort[])objectReader.ExecuteTagOp(op, filter);

                if (MemData.Length < 64)
                {
                    // If data read is less then 64 words, then perform read word by word to make sure
                    // all the data is read from the tag memory
                    ReadTagMemoryWordByWord(bank, filter, ref MemData);
                }
                else
                {
                    // If data read is more then 64 words then perform read with start address as 64 words
                    // and length as zero
                    ReadLargeTagMemory(bank, filter, ref MemData);
                }
            }
            catch (Exception ex)
            {
                if ((ex is FAULT_PROTOCOL_BIT_DECODING_FAILED_Exception) || ((ex is FAULT_NO_TAGS_FOUND_Exception)))
                {
                    // Perform read when the tag has mem more then 128 bytes and doesn't support
                    // Zero start address and number of words to read as zero
                    ReadLargeTagMemoryWithoutZeroLengthSupport(bank, filter, ref MemData);
                }
                else
                {
                    throw;
                }
            }
        }
Пример #3
0
 public string ReadPassword(uint byteIndex, uint length)
 {
     try
     {
         DateTime timeBeforeRead = DateTime.Now;
         byte[]   data           = null;
         using (Reader reader = Reader.Create("tmr:///" + Vars.comport.ToLower()))
         {
             reader.Connect();
             TagOp          tagOp = new Gen2.ReadData(Gen2.Bank.RESERVED, byteIndex, (byte)length);
             SimpleReadPlan plan  = new SimpleReadPlan(null, TagProtocol.GEN2, null, tagOp, 1000);
             reader.ParamSet("/reader/read/plan", plan);
             data = reader.ReadTagMemBytes(tagData, (int)Gen2.Bank.RESERVED, (int)byteIndex, (int)length);
         }
         DateTime timeAfterRead = DateTime.Now;
         TimeSpan timeElapsed   = timeAfterRead - timeBeforeRead;
         commandTotalTimeTextBox.Text = timeElapsed.TotalSeconds.ToString();
         return(ByteFormat.ToHex(data));
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
         return("");
     }
 }
        public bool CheckAccessPasswordIsLocked()
        {
            try
            {
                string reservedBankData = string.Empty;
                //Read access password
                var op           = new Gen2.ReadData(Gen2.Bank.RESERVED, 2, 2);
                var reservedData = (ushort[])_reader.ExecuteTagOp(op, null);

                if (null != reservedData)
                {
                    reservedBankData = ByteFormat.ToHex(ByteConv.ConvertFromUshortArray(reservedData), "", " ");
                }

                var accessPassword = reservedBankData.Trim(' ');
                return(false);
            }
            catch (Exception ex)
            {
                if (ex is FAULT_GEN2_PROTOCOL_MEMORY_LOCKED_Exception)
                {
                    return(true);
                }
                Trace.TraceError("Error checking access password. " + ex.Message + ex.StackTrace);
                return(false);
            }
        }
Пример #5
0
 /// <summary>
 /// Read tag memory word by word. If FAULT_GEN2_PROTOCOL_MEMORY_OVERRUN_BAD_PC_Exception
 /// or Non-specific reader error or General Tag Error or Tag data access failed exception
 /// is received. Memory reading is stopped and the already read data is returned
 /// </summary>
 /// <param name="bank">Gen2 memory bank</param>
 /// <param name="filter">Select filter</param>
 /// <param name="data">Read tag memory data is returned</param>
 private void ReadTagMemoryWordByWord(Gen2.Bank bank, TagFilter filter, ref ushort[] data)
 {
     lock (new Object())
     {
         List <ushort> dataTemp     = new List <ushort>();
         uint          startaddress = 0;
         if (data != null)
         {
             // if the data variable already contains the data, then add that data
             // to data temp and change the start address to total data length
             dataTemp.AddRange(data);
             startaddress = (uint)data.Length;
         }
         int   words = 1;
         TagOp op;
         bool  isAllDataReceived = false;
         while (false == isAllDataReceived)
         {
             try
             {
                 // Read tag memory word by word
                 op = new Gen2.ReadData(bank, startaddress, Convert.ToByte(words));
                 dataTemp.AddRange(((ushort[])objectReader.ExecuteTagOp(op, filter)));
                 startaddress += 1;
             }
             catch (Exception exception)
             {
                 if (exception is FAULT_GEN2_PROTOCOL_MEMORY_OVERRUN_BAD_PC_Exception || (-1 != exception.Message.IndexOf("Non-specific reader error")) || (-1 != exception.Message.IndexOf("General Tag Error")) || (-1 != exception.Message.IndexOf("Tag data access failed")) || (exception.Message.Contains("Tag memory overrun error") ||
                                                                                                                                                                                                                                                                                     (exception.Message.Contains("Gen2 unspecific error"))))
                 {
                     if (dataTemp.Count > 0)
                     {
                         // Just skip the exception and move on. So as not to lose the already read data.
                         isAllDataReceived = true;
                     }
                     else
                     {
                         // throw the exception if the data received is null for the first iteration itself
                         throw;
                     }
                 }
                 else
                 {
                     throw;
                 }
             }
         }
         data = dataTemp.ToArray();
     }
 }
Пример #6
0
        public static string SaveSimpleReadPlan(Object value)
        {
            string   readPlan = string.Empty;
            ReadPlan rp       = (ReadPlan)value;

            readPlan += "SimpleReadPlan:[";
            SimpleReadPlan srp = (SimpleReadPlan)rp;

            readPlan += "Antennas=" + ArrayToString(srp.Antennas);
            readPlan += "," + "Protocol=" + srp.Protocol.ToString();
            if (srp.Filter != null)
            {
                if (srp.Filter is Gen2.Select)
                {
                    Gen2.Select sf = (Gen2.Select)srp.Filter;
                    readPlan += "," + string.Format("Filter=Gen2.Select:[Invert={0},Bank={1},BitPointer={2},BitLength={3},Mask={4}]",
                                                    (sf.Invert?"true" : "false"), sf.Bank, sf.BitPointer, sf.BitLength, ByteFormat.ToHex(sf.Mask));
                }
                else
                {
                    Gen2.TagData td = (Gen2.TagData)srp.Filter;
                    readPlan += "," + string.Format("Filter=TagData:[EPC={0}]", td.EpcString);
                }
            }
            else
            {
                readPlan += ",Filter=null";
            }
            if (srp.Op != null)
            {
                if (srp.Op is Gen2.ReadData)
                {
                    Gen2.ReadData rd = (Gen2.ReadData)srp.Op;
                    readPlan += "," + string.Format("Op=ReadData:[Bank={0},WordAddress={1},Len={2}]", rd.Bank, rd.WordAddress, rd.Len);
                }
                else
                {
                    readPlan += ",Op=null";
                }
            }
            else
            {
                readPlan += ",Op=null";
            }
            readPlan += "," + "UseFastSearch=" + srp.UseFastSearch.ToString();
            readPlan += "," + "Weight=" + srp.Weight.ToString() + "]";
            return(readPlan);
        }
Пример #7
0
        // read multiple registers from one tag singulated by its EPC
        public static short[] ReadMemBlockByEpc(Reader reader, TagReadData tag, Gen2.Bank bank, int address, int length, int attempts)
        {
            Gen2.Select resetFilter = CreateGen2Select(4, 4, Gen2.Bank.TID, 0x00, 16, new byte[] { 0xE2, 0x82 });
            Gen2.Select epcFilter   = CreateGen2Select(4, 0, Gen2.Bank.EPC, 0x20, tag.Epc.Length * 8, tag.Epc);
            MultiFilter selects     = new MultiFilter(new Gen2.Select[] { resetFilter, epcFilter });

            Gen2.ReadData  operation = new Gen2.ReadData(bank, (uint)address, (byte)length);
            SimpleReadPlan config    = new SimpleReadPlan(new int[] { tag.Antenna }, TagProtocol.GEN2, selects, operation, 1000);

            short[] values = null;
            try
            {
                reader.ParamSet("/reader/read/plan", config);
                for (int i = 0; i < attempts; i++)
                {
                    if (values != null)
                    {
                        break;
                    }
                    TagReadData[] readResults = reader.Read(readTime);
                    foreach (TagReadData readResult in readResults)
                    {
                        if (tag.EpcString.Equals(readResult.EpcString))
                        {
                            byte[] dataBytes = readResult.Data;
                            if (dataBytes.Length != 0)
                            {
                                values = ConvertByteArrayToShortArray(dataBytes);
                                break;
                            }
                        }
                    }
                }
            }
            catch (ReaderException e)
            {
                Console.WriteLine("Error: " + e.ToString());
                Environment.Exit(-1);
            }
            if (values == null)
            {
                throw new SystemException("Tag not found");
            }
            return(values);
        }
Пример #8
0
        /// <summary>
        /// Read additional reserved memory for m5e variants
        /// </summary>
        /// <param name="bank"></param>
        /// <param name="startAddress"></param>
        /// <param name="filter"></param>
        /// <param name="data"></param>
        private void ReadAdditionalReservedMemDataM5eVariants(Gen2.Bank bank, uint startAddress, TagFilter filter, out ushort[] data)
        {
            data = null;
            int   words = 1;
            TagOp op;

            while (true)
            {
                try
                {
                    op   = new Gen2.ReadData(bank, startAddress, Convert.ToByte(words));
                    data = (ushort[])objReader.ExecuteTagOp(op, filter);
                    words++;
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
Пример #9
0
 /// <summary>
 /// Read tag memory for M5e Variants. If FAULT_GEN2_PROTOCOL_MEMORY_OVERRUN_BAD_PC_Exception
 /// or Non-specific reader error or General Tag Error or Tag data access failed exception
 /// is received. Memory reading is stopped and the already read data is returned
 /// </summary>
 /// <param name="bank">Gen2 memory bank</param>
 /// <param name="filter">Select filter</param>
 /// <param name="data">Read tag memory data is returned</param>
 private void ReadMemoryM5eVariants(Gen2.Bank bank, TagFilter filter, ref ushort[] data)
 {
     lock (new Object())
     {
         List <ushort> dataTemp     = new List <ushort>();
         uint          startaddress = 0;
         int           words        = 64;
         if (data != null)
         {
             // if the data variable already contains the data, then add that data
             // to data temp and change the start address to total data length
             dataTemp.AddRange(data);
             startaddress = (uint)data.Length;
         }
         TagOp op;
         bool  isAllDataReceived = false;
         while (false == isAllDataReceived)
         {
             try
             {
                 // Read tag memory
                 op = new Gen2.ReadData(bank, startaddress, Convert.ToByte(words));
                 dataTemp.AddRange(((ushort[])objectReader.ExecuteTagOp(op, filter)));
                 startaddress += 64;
             }
             catch (Exception exception)
             {
                 if (exception is FAULT_GEN2_PROTOCOL_MEMORY_OVERRUN_BAD_PC_Exception || (-1 != exception.Message.IndexOf("Non-specific reader error")) || (-1 != exception.Message.IndexOf("General Tag Error")) || (-1 != exception.Message.IndexOf("Tag data access failed")))
                 {
                     data = dataTemp.ToArray();
                     ReadTagMemoryWordByWord(bank, filter, ref data);
                     isAllDataReceived = true;
                 }
                 else
                 {
                     throw;
                 }
             }
         }
     }
 }
Пример #10
0
        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 ((r is SerialReader) || (r is LlrpReader))
                    {
                        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();
                        }
                        Gen2.Password pass = new Gen2.Password(0x0);
                        r.ParamSet("/reader/gen2/accessPassword", pass);

                        //Use first antenna for operation
                        if (antennaList != null)
                        {
                            r.ParamSet("/reader/tagop/antenna", antennaList[0]);
                        }

                        // BlockWrite and read using ExecuteTagOp

                        Gen2.BlockWrite blockwrite = new Gen2.BlockWrite(Gen2.Bank.USER, 0, new ushort[] { 0xFFF1, 0x1122 });
                        r.ExecuteTagOp(blockwrite, null);

                        Gen2.ReadData read     = new Gen2.ReadData(Gen2.Bank.USER, 0, 2);
                        ushort[]      readData = (ushort[])r.ExecuteTagOp(read, null);

                        foreach (ushort word in readData)
                        {
                            Console.Write(" {0:X4}", word);
                        }
                        Console.WriteLine();


                        // BlockWrite and read using embedded read command

                        SimpleReadPlan readplan;
                        TagReadData[]  tagreads;

                        blockwrite = new Gen2.BlockWrite(Gen2.Bank.USER, 0, new ushort[] { 0x1234, 0x5678 });
                        readplan   = new SimpleReadPlan(antennaList, TagProtocol.GEN2,
                                                        //null,
                                                        new TagData("1234567890ABCDEF"),
                                                        blockwrite, 0);
                        r.ParamSet("/reader/read/plan", readplan);
                        r.Read(500);

                        readplan = new SimpleReadPlan(antennaList, TagProtocol.GEN2,
                                                      null,
                                                      new Gen2.ReadData(Gen2.Bank.USER, 0, 2),
                                                      0);
                        r.ParamSet("/reader/read/plan", readplan);
                        tagreads = r.Read(500);
                        foreach (TagReadData trd in tagreads)
                        {
                            foreach (byte b in trd.Data)
                            {
                                Console.Write(" {0:X2}", b);
                            }
                            Console.WriteLine("    " + trd);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Error: This codelet works only for Serial Readers and Llrp Readers");
                    }
                }
            }
            catch (ReaderException re)
            {
                Console.WriteLine("Error: " + re.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }
Пример #11
0
        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]);
                }
                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();
                }

                // 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).
                        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
                            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
                            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
                        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.
                        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();
                    }
                }
                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);
            }
        }
Пример #12
0
        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 ((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) ||
                        "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);
            }
        }
Пример #13
0
        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]);
                    }
                    Gen2ReadAllMemoryBanks prgm = new Gen2ReadAllMemoryBanks();
                    prgm.reader = r;

                    // 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) ||
                        "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;
                    }
                    prgm.PerformWriteOperation();

                    SimpleReadPlan srp = new SimpleReadPlan(antennaList, TagProtocol.GEN2, null, null, 1000);
                    r.ParamSet("/reader/read/plan", srp);

                    TagReadData[] tagReadsFilter = r.Read(500);

                    if (tagReadsFilter.Length == 0)
                    {
                        Console.WriteLine("No tags found");
                        return;
                    }

                    TagFilter filter = new TagData(tagReadsFilter[0].EpcString);

                    Console.WriteLine("Perform embedded and standalone tag operation - read only user memory without filter");
                    Console.WriteLine();
                    TagOp op = new Gen2.ReadData(Gen2.Bank.USER, 0, length);
                    prgm.PerformReadAllMemOperation(null, op);
                    Console.WriteLine();

                    Console.WriteLine("Perform embedded and standalone tag operation - read user memory, reserved memory, tid memory and epc memory without filter");
                    Console.WriteLine();
                    op = null;
                    op = new Gen2.ReadData(Gen2.Bank.USER | Gen2.Bank.GEN2BANKUSERENABLED | Gen2.Bank.GEN2BANKRESERVEDENABLED | Gen2.Bank.GEN2BANKEPCENABLED | Gen2.Bank.GEN2BANKTIDENABLED, 0, length);
                    prgm.PerformReadAllMemOperation(null, op);
                    Console.WriteLine();

                    Console.WriteLine("Perform embedded and standalone tag operation - read only user memory with filter");
                    Console.WriteLine();
                    op = null;
                    op = new Gen2.ReadData(Gen2.Bank.USER, 0, length);
                    prgm.PerformReadAllMemOperation(filter, op);
                    Console.WriteLine();

                    Console.WriteLine("Perform embedded and standalone tag operation - read user memory, reserved memory with filter");
                    Console.WriteLine();
                    op = null;
                    op = new Gen2.ReadData(Gen2.Bank.USER | Gen2.Bank.GEN2BANKUSERENABLED | Gen2.Bank.GEN2BANKRESERVEDENABLED, 0, length);
                    prgm.PerformReadAllMemOperation(filter, op);
                    Console.WriteLine();

                    Console.WriteLine("Perform embedded and standalone tag operation - read user memory, reserved memory and tid memory with filter");
                    Console.WriteLine();
                    op = null;
                    op = new Gen2.ReadData(Gen2.Bank.USER | Gen2.Bank.GEN2BANKUSERENABLED | Gen2.Bank.GEN2BANKRESERVEDENABLED | Gen2.Bank.GEN2BANKTIDENABLED, 0, length);
                    prgm.PerformReadAllMemOperation(filter, op);
                    Console.WriteLine();

                    Console.WriteLine("Perform embedded and standalone tag operation - read user memory, reserved memory, tid memory and epc memory with filter");
                    Console.WriteLine();
                    op = null;
                    op = new Gen2.ReadData(Gen2.Bank.USER | Gen2.Bank.GEN2BANKUSERENABLED | Gen2.Bank.GEN2BANKRESERVEDENABLED | Gen2.Bank.GEN2BANKEPCENABLED | Gen2.Bank.GEN2BANKTIDENABLED, 0, length);
                    prgm.PerformReadAllMemOperation(filter, op);
                    Console.WriteLine();
                }
            }
            catch (ReaderException re)
            {
                Console.WriteLine("Error: " + re.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }
Пример #14
0
        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);
            }
        }
Пример #15
0
        static void Main(string[] args)
        {
            // Program setup
            if (args.Length != 1)
            {
                Console.WriteLine("Please provide reader URL, such as:\n"
                                  + "tmr:///com4\n"
                                  + "tmr://my-reader.example.com\n");
                Environment.Exit(1);
            }

            // 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();
                    }
                    else
                    {
                        r.ParamSet("/reader/region/id", supportedRegions[0]);
                    }
                }

                // 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();

                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(null, 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).
                        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(null, 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
                        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(null, 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.
                        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();
                    }
                }
                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.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }
Пример #16
0
        static void Main(string[] args)
        {
            // Program setup
            if (1 > args.Length)
            {
                Usage();
            }
            TagFilter filter = 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 (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();
                    }
                    //Use first antenna for operation
                    if (antennaList != null)
                    {
                        r.ParamSet("/reader/tagop/antenna", antennaList[0]);
                    }

                    // This select filter matches all Gen2 tags where bits 32-48 of the EPC are 0x0123
#if ENABLE_FILTER
                    filter = new Gen2.Select(false, Gen2.Bank.EPC, 32, 16, new byte[] { 0x01, 0x23 });
#endif

                    //Gen2.TagData epc = new Gen2.TagData(new byte[] {
                    //    0x01, 0x23, 0x45, 0x67, 0x89, 0xAB,
                    //    0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67,
                    //});
                    //Gen2.WriteTag tagop = new Gen2.WriteTag(epc);
                    //r.ExecuteTagOp(tagop, null);

                    // Reads data from a tag memory bank after writing data to the requested memory bank without powering down of tag
#if ENABLE_READ_AFTER_WRITE
                    {
                        //create a tagopList with write tagop followed by read tagop
                        TagOpList tagopList = new TagOpList();
                        byte      wordCount;
                        ushort[]  readData;

                        //Write one word of data to USER memory and read back 8 words from EPC memory using WriteData and ReadData
                        {
                            ushort[] writeData = { 0x9999 };
                            wordCount = 8;
                            Gen2.WriteData wData = new Gen2.WriteData(Gen2.Bank.USER, 2, writeData);
                            Gen2.ReadData  rData = new Gen2.ReadData(Gen2.Bank.EPC, 0, wordCount);
                            //Gen2.WriteTag wTag = new Gen2.WriteTag(epc);

                            // assemble tagops into list
                            tagopList.list.Add(wData);
                            tagopList.list.Add(rData);

                            Console.WriteLine("###################Embedded Read after write######################");
                            // uncomment the following for embedded read after write.
                            embeddedReadAfterWrite(null, tagopList);

                            // call executeTagOp with list of tagops
                            //readData = (ushort[])r.ExecuteTagOp(tagopList, null);
                            //Console.WriteLine("ReadData: ");
                            //foreach (ushort word in readData)
                            //{
                            //    Console.Write(" {0:X4}", word);
                            //}
                            //Console.WriteLine("\n");
                        }

                        //clearing the list for next operation
                        tagopList.list.Clear();

                        //Write 12 bytes(6 words) of EPC and read back 8 words from EPC memory using WriteTag and ReadData
                        {
                            Gen2.TagData epc1 = new Gen2.TagData(new byte[] {
                                0x11, 0x22, 0x33, 0x44, 0x55, 0x66,
                                0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc,
                            });
                            wordCount = 8;
                            Gen2.WriteTag wtag  = new Gen2.WriteTag(epc1);
                            Gen2.ReadData rData = new Gen2.ReadData(Gen2.Bank.EPC, 0, wordCount);

                            // assemble tagops into list
                            tagopList.list.Add(wtag);
                            tagopList.list.Add(rData);

                            // call executeTagOp with list of tagops
                            //readData = (ushort[])r.ExecuteTagOp(tagopList, null);
                            //Console.WriteLine("ReadData: ");
                            //foreach (ushort word in readData)
                            //{
                            //    Console.Write(" {0:X4}", word);
                            //}
                            //Console.WriteLine("\n");
                        }
                    }
#endif
                }
            }
            catch (ReaderException re)
            {
                Console.WriteLine("Error: " + re.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }
Пример #17
0
 /// <summary>
 /// Read tag memory when tag has more then 64 words or 128 bytes. And module doesn't supports zero address and zero length.
 /// Reads the tag memory with 0 address and length of words as 64. If memory overrun received. Initiates reading of tag
 /// word by word with start address as length of already read data and length of words to read as 0. Returns the data read from
 /// tag memory.
 /// </summary>
 /// <param name="bank">Gen2 memory bank</param>
 /// <param name="filter">filter</param>
 /// <param name="data">Data read from tag memory</param>
 private void ReadLargeTagMemoryWithoutZeroLengthSupport(Gen2.Bank bank, TagFilter filter, ref ushort[] data)
 {
     lock (new Object())
     {
         data = null;
         // Data from tag memory
         List <ushort> dataTemp = new List <ushort>();
         // Number of words to read
         int words = 64;
         // Start address
         uint  startaddress = 0;
         TagOp op;
         bool  isAllDataReceived = false;
         // Read till all the data from the tag memory is read
         while (false == isAllDataReceived)
         {
             try
             {
                 op = new Gen2.ReadData(bank, startaddress, Convert.ToByte(words));
                 dataTemp.AddRange(((ushort[])objectReader.ExecuteTagOp(op, filter)));
                 // Increment the start address to 64 and keep length of words to read as 64 for
                 // all the iterations
                 startaddress += 64;
             }
             catch (Exception ex)
             {
                 try
                 {
                     if (ex is FAULT_GEN2_PROTOCOL_MEMORY_OVERRUN_BAD_PC_Exception || (-1 != ex.Message.IndexOf("Non-specific reader error")) || (-1 != ex.Message.IndexOf("General Tag Error")) || (-1 != ex.Message.IndexOf("Tag data access failed")))
                     {
                         // If the memory to read requested is more then the available memory in the tag, then initiate
                         // reading the tag memory word by word with start address as length of already read data if exists
                         // and length of words to read is 1
                         if (dataTemp.Count > 0)
                         {
                             // If some data is already read then include this data also so that
                             // reading of memory doesn't continue from zero and the list should
                             // not contain same data twice
                             data = dataTemp.ToArray();
                         }
                         ReadTagMemoryWordByWord(bank, filter, ref data);
                         // Come out of main while loop. And read the already read data
                         isAllDataReceived = true;
                     }
                     else
                     {
                         throw;
                     }
                 }
                 catch (Exception exception)
                 {
                     // If more then once the below exceptions are received then come out of the loop.
                     if (exception is FAULT_GEN2_PROTOCOL_MEMORY_OVERRUN_BAD_PC_Exception || (-1 != exception.Message.IndexOf("Non-specific reader error")) || (-1 != exception.Message.IndexOf("General Tag Error")) || (-1 != exception.Message.IndexOf("Tag data access failed")))
                     {
                         if (dataTemp.Count > 0)
                         {
                             // Just skip the exception and move on. So as not to lose the already read data.
                             isAllDataReceived = false;
                         }
                         else
                         {
                             // throw the exception if the data received is null for the first iteration itself
                             throw;
                         }
                     }
                     else
                     {
                         throw;
                     }
                 }
             }
         }
     }
 }
Пример #18
0
        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);
            }
        }
Пример #19
0
        /// <summary>
        /// Populate keys of the tag
        /// </summary>
        private void PopulateAuthenticateData()
        {
            try
            {
                Mouse.SetCursor(Cursors.Wait);
                ResetUntraceableFields();
                if ((bool)rbFirstTagAuthenticateTb.IsChecked)
                {
                    antenna = GetSelectedAntennaList()[0];
                }
                objReader.ParamSet("/reader/tagop/antenna", antenna);

                if ((bool)rbSelectedTagAuthenticateTb.IsChecked)
                {
                    if (lblSelectFilter.Content.ToString().Contains("EPC ID"))
                    {
                        searchSelect = new TagData(currentEPC);
                    }
                    else
                    {
                        int    dataLength       = 0;
                        byte[] SearchSelectData = ByteFormat.FromHex(txtData.Text);
                        if (null != SearchSelectData)
                        {
                            dataLength = SearchSelectData.Length;
                        }

                        searchSelect = new Gen2.Select(false, selectMemBank, Convert.ToUInt16(startAddress * 16), Convert.ToUInt16(dataLength * 8), SearchSelectData);
                    }
                }
                else
                {
                    searchSelect = new TagData(currentEPC);
                }


                TagOp op;
                try
                {
                    ushort[] Key0           = null;
                    string   CurrentKeyZero = string.Empty;
                    op   = new Gen2.ReadData(Gen2.Bank.USER, 0xC0, 8);
                    Key0 = (ushort[])objReader.ExecuteTagOp(op, searchSelect);

                    if (null != Key0)
                    {
                        CurrentKeyZero = ByteFormat.ToHex(ByteConv.ConvertFromUshortArray(Key0), "", " ");
                    }

                    crntKey0Value.Content  = CurrentKeyZero;
                    txtbxKeyZero.IsEnabled = true;
                    txtbxKeyZero.Text      = CurrentKeyZero;
                }
                catch (Exception ex)
                {
                    if (ex is FAULT_GEN2_PROTOCOL_MEMORY_OVERRUN_BAD_PC_Exception)
                    {
                        crntKey0Value.Content  = "Key0 is inserted and activated";
                        txtbxKeyZero.IsEnabled = false;
                    }
                }
                try
                {
                    ushort[] Key1          = null;
                    string   CurrentKeyOne = string.Empty;
                    op   = new Gen2.ReadData(Gen2.Bank.USER, 0xD0, 8);
                    Key1 = (ushort[])objReader.ExecuteTagOp(op, searchSelect);

                    if (null != Key1)
                    {
                        CurrentKeyOne = ByteFormat.ToHex(ByteConv.ConvertFromUshortArray(Key1), "", " ");
                    }

                    crntKey1Value.Content = CurrentKeyOne;
                    txtbxKeyOne.IsEnabled = true;
                    txtbxKeyOne.Text      = CurrentKeyOne;
                }
                catch (Exception ex)
                {
                    if (ex is FAULT_GEN2_PROTOCOL_MEMORY_OVERRUN_BAD_PC_Exception)
                    {
                        crntKey1Value.Content = "Key1 is inserted and activated";
                        txtbxKeyOne.IsEnabled = false;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                Mouse.SetCursor(Cursors.Arrow);
            }
        }
Пример #20
0
        /// <summary>
        /// Populate access password of the tag
        /// </summary>
        private void PopulateUntraceableData()
        {
            try
            {
                Mouse.SetCursor(Cursors.Wait);
                spUntraceableFields.IsEnabled = true;
                ResetUntraceableActionCheckBoxes();
                if ((bool)rbFirstTagUntraceableTb.IsChecked)
                {
                    antenna = GetSelectedAntennaList()[0];
                }

                objReader.ParamSet("/reader/tagop/antenna", antenna);


                if ((bool)rbSelectedTagUntraceableTb.IsChecked)
                {
                    if (lblSelectFilter.Content.ToString().Contains("EPC ID"))
                    {
                        searchSelect = new TagData(currentEPC);
                    }
                    else
                    {
                        int    dataLength       = 0;
                        byte[] SearchSelectData = ByteFormat.FromHex(txtData.Text);
                        if (null != SearchSelectData)
                        {
                            dataLength = SearchSelectData.Length;
                        }

                        searchSelect = new Gen2.Select(false, selectMemBank, Convert.ToUInt16(accessPwddStartAddress * 16), Convert.ToUInt16(dataLength * 8), SearchSelectData);
                    }
                }
                else
                {
                    searchSelect = new TagData(currentEPC);
                }

                //Read Reserved memory bank data
                TagOp    op;
                ushort[] reservedData = null;
                txtbxAccesspaasword.Text = "";
                try
                {
                    string reservedBankData = string.Empty;
                    //Read access password
                    op           = new Gen2.ReadData(Gen2.Bank.RESERVED, 2, 2);
                    reservedData = (ushort[])objReader.ExecuteTagOp(op, searchSelect);

                    if (null != reservedData)
                    {
                        reservedBankData = ByteFormat.ToHex(ByteConv.ConvertFromUshortArray(reservedData), "", " ");
                    }

                    txtbxAccesspaasword.Text = reservedBankData.Trim(' ');
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Пример #21
0
        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();
        }
Пример #22
0
        static void Main(string[] args)
        {
            bool      enableFilter = false;
            TagFilter filter       = null;

            // 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();
                    }

                    //Use first antenna for operation
                    if (antennaList != null)
                    {
                        r.ParamSet("/reader/tagop/antenna", antennaList[0]);
                    }

                    if (enableFilter)
                    {
                        // If select filter is to be enabled
                        byte[] mask = new byte[] { (byte)0x30, (byte)0x28, (byte)0x35, (byte)0x4D,
                                                   (byte)0x82, (byte)0x02, (byte)0x02, (byte)0x80, (byte)0x00, (byte)0x01,
                                                   (byte)0x04, (byte)0xAC };
                        filter = new Gen2.Select(false, Gen2.Bank.EPC, 32, 96, mask);
                    }

                    //Get Sensor Data of EM4325 tag
                    bool sendUid       = true;
                    bool sendNewSample = true;
                    Gen2.EMMicro.EM4325.GetSensorData getSensorOp = new Gen2.EMMicro.EM4325.GetSensorData(sendUid, sendNewSample);
                    try
                    {
                        Console.WriteLine("****Executing standalone tag operation of Get sensor Data command of EM4325 tag****");
                        byte[] response = (byte[])r.ExecuteTagOp(getSensorOp, filter);

                        // Parse the response of GetSensorData
                        Console.WriteLine("****Get sensor Data command is success****");
                        GetSensorDataResponse rData = new GetSensorDataResponse(response);
                        Console.WriteLine(rData.ToString());
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception from executing get Sensor Data command: " + ex.Message);
                    }

                    //Embedded tag operation of Get sensor data
                    try
                    {
                        Console.WriteLine("****Executing embedded tag operation of Get sensor Data command of EM4325 tag****");
                        embeddedRead(TagProtocol.GEN2, filter, getSensorOp);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception from embedded get sensor data: " + ex.Message);
                    }

                    //Reset alarms command
                    // Read back the temperature control word at 0xEC address to verify reset enable alarm bit is set before executing reset alarm tag op.
                    Console.WriteLine("Reading Temperature control word 1 before resetting alarms to ensure reset enable bit is set to 1");
                    byte[]        filterMask = new byte[] { (byte)0x04, (byte)0xc2 };
                    Gen2.Select   select     = new Gen2.Select(false, Gen2.Bank.EPC, 0x70, 16, filterMask);
                    Gen2.ReadData rdata      = new Gen2.ReadData(Gen2.Bank.USER, 0xEC, (byte)0x1);
                    ushort[]      resp       = (ushort[])r.ExecuteTagOp(rdata, select);
                    Console.WriteLine("Temp control word 1: ");
                    foreach (ushort i in resp)
                    {
                        Console.Write(" {0:X4}", i);
                    }
                    Console.WriteLine("\n");

                    // If temperature control word is not 0x4000, write the data
                    if (resp[0] != 0x4000)
                    {
                        ushort[]       writeData = new ushort[] { 0x4000 };
                        Gen2.WriteData wData     = new Gen2.WriteData(Gen2.Bank.USER, 0xEC, writeData);
                        r.ExecuteTagOp(wData, select);
                    }
                    Gen2.EMMicro.EM4325.ResetAlarms resetAlarmsOp = new Gen2.EMMicro.EM4325.ResetAlarms();
                    try
                    {
                        Console.WriteLine("****Executing standalone tag operation of Reset alarms command of EM4325 tag****");
                        r.ExecuteTagOp(resetAlarmsOp, filter);
                        Console.WriteLine("****Reset Alarms command is success****");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception from executing reset alarms : " + ex.Message);
                    }

                    //Embedded tag operation of reset alarms command
                    try
                    {
                        Console.WriteLine("****Executing embedded tag operation of reset alarms command of EM4325 tag****");
                        embeddedRead(TagProtocol.GEN2, filter, resetAlarmsOp);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception from embedded reset alarms command: " + ex.Message);
                    }
                }
            }
            catch (ReaderException re)
            {
                Console.WriteLine("Error: " + re.Message);
                Console.Out.Flush();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }
Пример #23
0
        private void ReadReservedMemData(Gen2.Bank bank, TagFilter filter)
        {
            ushort [] reservedData;
            TagOp     op;

            try
            {
                try
                {
                    // Read kill password
                    op           = new Gen2.ReadData(Gen2.Bank.RESERVED, 0, 2);
                    reservedData = (ushort[])objReader.ExecuteTagOp(op, filter);
                    if (null != reservedData)
                    {
                        txtKillPassword.Text = ByteFormat.ToHex(ByteConv.ConvertFromUshortArray(reservedData), "", " ");
                    }
                    else
                    {
                        txtKillPassword.Text = "";
                    }
                }
                catch (Exception ex)
                {
                    if (ex is FAULT_GEN2_PROTOCOL_MEMORY_OVERRUN_BAD_PC_Exception)
                    {
                        txtKillPassword.Text = "Read Error";
                    }
                    else
                    {
                        txtKillPassword.Text = ex.Message;
                    }
                }

                try
                {
                    // Read access password
                    reservedData = null;
                    op           = new Gen2.ReadData(Gen2.Bank.RESERVED, 2, 2);
                    reservedData = (ushort[])objReader.ExecuteTagOp(op, filter);
                    if (null != reservedData)
                    {
                        txtAcessPassword.Text = ByteFormat.ToHex(ByteConv.ConvertFromUshortArray(reservedData), "", " ");
                    }
                    else
                    {
                        txtAcessPassword.Text = "";
                    }
                }
                catch (Exception ex)
                {
                    if (ex is FAULT_GEN2_PROTOCOL_MEMORY_OVERRUN_BAD_PC_Exception)
                    {
                        txtAcessPassword.Text = "Read Error";
                    }
                    else
                    {
                        txtAcessPassword.Text = ex.Message;
                    }
                }

                // Read additional memory password
                try
                {
                    reservedData = null;
                    if (model.Equals("M5e") || model.Equals("M5e EU") || model.Equals("M5e Compact") || model.Equals("M5e PRC") || model.Equals("Astra"))
                    {
                        ReadAdditionalReservedMemDataM5eVariants(Gen2.Bank.RESERVED, 4, filter, out reservedData);
                    }
                    else
                    {
                        op           = new Gen2.ReadData(Gen2.Bank.RESERVED, 4, 0);
                        reservedData = (ushort[])objReader.ExecuteTagOp(op, filter);
                    }

                    if (null != reservedData)
                    {
                        txtReservedMemUnusedValue.Text = ByteFormat.ToHex(ByteConv.ConvertFromUshortArray(reservedData), "", " ");
                        // Visible additional memory textboxes
                        lblAdditionalReservedMem.Visibility    = System.Windows.Visibility.Visible;
                        txtReservedMemUnusedValue.Visibility   = System.Windows.Visibility.Visible;
                        lblAdditionalReservedMemAdd.Visibility = System.Windows.Visibility.Visible;
                    }
                    else
                    {
                        txtReservedMemUnusedValue.Text = "";
                    }
                }
                catch
                {
                    // catch the exception and move on. Only some tags has aditional memory
                    txtReservedMemUnusedValue.Text = "";
                    // Hide additional memory textboxes
                    lblAdditionalReservedMem.Visibility    = System.Windows.Visibility.Collapsed;
                    txtReservedMemUnusedValue.Visibility   = System.Windows.Visibility.Collapsed;
                    lblAdditionalReservedMemAdd.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        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)
                {
                }
            }
        }
Пример #25
0
 /// <summary>
 /// Read tag memory which has more then 64 words or 128 bytes. Returns the data read from tag memory.
 /// Stops reading the tag memory if FAULT_PROTOCOL_BIT_DECODING_FAILED_Exception exception is received
 /// more then once. If the data read from tag memory is less then 64 words then initiates reading tag
 /// memory word by word
 /// </summary>
 /// <param name="bank"> Gen2 memory bank</param>
 /// <param name="filter">filter</param>
 /// <param name="data">Memory data obtained from the tag</param>
 private void ReadLargeTagMemory(Gen2.Bank bank, TagFilter filter, ref ushort[] data)
 {
     lock (new Object())
     {
         List <ushort> dataTemp = new List <ushort>();
         if (data != null)
         {
             dataTemp.AddRange(data);
         }
         int   words        = 0;
         uint  startaddress = 64;
         TagOp op;
         bool  isAllDataReceived = false;
         while (false == isAllDataReceived)
         {
             try
             {
                 op = new Gen2.ReadData(bank, startaddress, Convert.ToByte(words));
                 ushort[] tempDataReceived = (ushort[])objectReader.ExecuteTagOp(op, filter);
                 dataTemp.AddRange(tempDataReceived);
                 startaddress += 64;
                 if (tempDataReceived.Length < 64)
                 {
                     isAllDataReceived = true;
                     // If data received is less then 64 words, perform word by word with start address as length
                     // of the data and number of words to read is 1
                     data = dataTemp.ToArray();
                     ReadTagMemoryWordByWord(bank, filter, ref data);
                 }
             }
             catch (Exception ex)
             {
                 if (ex is FAULT_PROTOCOL_BIT_DECODING_FAILED_Exception)
                 {
                     try
                     {
                         // If read is success then continue the while loop with incremented start address and length as 0
                         words = 64;
                         op    = new Gen2.ReadData(bank, startaddress, Convert.ToByte(words));
                         dataTemp.AddRange(((ushort[])objectReader.ExecuteTagOp(op, filter)));
                         startaddress += 64;
                         words         = 0;
                     }
                     catch (Exception et)
                     {
                         // If consecutively we get FAULT_PROTOCOL_BIT_DECODING_FAILED_Exception exception blindly come out of the loop to avoid
                         // dead lock
                         if (et is FAULT_PROTOCOL_BIT_DECODING_FAILED_Exception)
                         {
                             isAllDataReceived = true;
                         }
                         else
                         {
                             throw;
                         }
                     }
                 }
                 else
                 {
                     throw;
                 }
             }
         }
         data = dataTemp.ToArray();
     }
 }
Пример #26
0
 /// <summary>
 /// Read tag memory which has more then 64 words or 128 bytes. Returns the data read from tag memory. 
 /// Stops reading the tag memory if FAULT_PROTOCOL_BIT_DECODING_FAILED_Exception exception is received
 /// more then once. If the data read from tag memory is less then 64 words then initiates reading tag
 /// memory word by word
 /// </summary>
 /// <param name="bank"> Gen2 mem bank</param>
 /// <param name="filter">filter</param>
 /// <param name="data">Mem data obtained from the tag</param>
 private void ReadLargeTagMemory(Gen2.Bank bank, TagFilter filter, ref ushort[] data)
 {
     lock (new Object())
     {
         List<ushort> dataTemp = new List<ushort>();
         if (data != null)
         {
             dataTemp.AddRange(data);
         }
         int words = 0;
         uint startaddress = 64;
         TagOp op;
         bool isAllDatareceived = true;
         while (isAllDatareceived)
         {
             try
             {
                 op = new Gen2.ReadData(bank, startaddress, Convert.ToByte(words));
                 ushort[] tempDataReceived = (ushort[])objectReader.ExecuteTagOp(op, filter);
                 dataTemp.AddRange(tempDataReceived);
                 startaddress += 64;
                 if (tempDataReceived.Length < 64)
                 {
                     isAllDatareceived = false;
                     // If data received is less then 64 words, perform word by word with start address as length
                     // of the data and numer of words to read is 1 
                     ReadTagMemoryWordByWord(bank, filter, ref data);
                 }
             }
             catch (Exception ex)
             {
                 if (ex is FAULT_PROTOCOL_BIT_DECODING_FAILED_Exception)
                 {
                     try
                     {
                         // If read is success then continue the while loop with incremented start address and length as 0 
                         words = 64;
                         op = new Gen2.ReadData(bank, startaddress, Convert.ToByte(words));
                         dataTemp.AddRange(((ushort[])objectReader.ExecuteTagOp(op, filter)));
                         startaddress += 64;
                         words = 0;
                     }
                     catch (Exception et)
                     {
                         // If consecutively we get FAULT_PROTOCOL_BIT_DECODING_FAILED_Exception exception blindly come out of the loop to avoid
                         // dead lock
                         if (et is FAULT_PROTOCOL_BIT_DECODING_FAILED_Exception)
                         {
                             isAllDatareceived = false;
                         }
                         else
                         {
                             throw;
                         }
                     }
                 }
                 else
                 {
                     throw;
                 }
             }
         }
         data = dataTemp.ToArray();
     }
 }
Пример #27
0
 /// <summary>
 /// Read tag memory word by word. If FAULT_GEN2_PROTOCOL_MEMORY_OVERRUN_BAD_PC_Exception 
 /// or Non-specific reader error or General Tag Error or Tag data access failed exception
 /// is recieved. Memory reading is stopped and the already read data is returned
 /// </summary>
 /// <param name="bank">Gen2 memory bank</param>
 /// <param name="filter">Select filter</param>
 /// <param name="data">Read tag memory data is returned</param>
 private void ReadTagMemoryWordByWord(Gen2.Bank bank, TagFilter filter, ref ushort[] data)
 {
     lock (new Object())
     {
         List<ushort> dataTemp = new List<ushort>();
         uint startaddress = 0;
         if (data != null)
         {
             // if the data varibale already contains the data, then add that data 
             // to data temp and chnage the start address to total data length
             dataTemp.AddRange(data);
             startaddress = (uint)data.Length;
         }
         int words = 1;
         TagOp op;
         bool isAllDatareceived = true;
         while (isAllDatareceived)
         {
             try
             {
                 // Read tag memory word by word
                 op = new Gen2.ReadData(bank, startaddress, Convert.ToByte(words));
                 dataTemp.AddRange(((ushort[])objectReader.ExecuteTagOp(op, filter)));
                 startaddress += 1;
             }
             catch (Exception exception)
             {
                 if (exception is FAULT_GEN2_PROTOCOL_MEMORY_OVERRUN_BAD_PC_Exception || (-1 != exception.Message.IndexOf("Non-specific reader error")) || (-1 != exception.Message.IndexOf("General Tag Error")) || (-1 != exception.Message.IndexOf("Tag data access failed")))
                 {
                     if (dataTemp.Count > 0)
                     {
                         // Just skip the exception and move on. So as not to lose the already read data.
                         isAllDatareceived = false;
                     }
                     else
                     {
                         // throw the exception if the data received is null for the first iteration itself
                         throw;
                     }
                 }
                 else
                 {
                     throw;
                 }
             }
         }
         data = dataTemp.ToArray();
     }
 }
Пример #28
0
        /// <summary>
        /// Read tag memory for readers or modules other the M5e variants
        /// </summary>
        /// <param name="bank">Gen2 memory bank</param>
        /// <param name="filter">filter</param>
        /// <param name="MemData">Data read from tag memory</param>
        private void ReadMemoryM6eVariants(Gen2.Bank bank, TagFilter filter, ref ushort[] MemData)
        {
            try
            {
                // Read tag memory with zero as start address and lenght of words to read as zero
                TagOp op = new Gen2.ReadData(bank, 0, 0);
                MemData = (ushort[])objectReader.ExecuteTagOp(op, filter);

                if (MemData.Length < 64)
                {
                    // If data read is less then 64 words, then perform read word by word to make sure 
                    // all the data is read from the tag memory
                    ReadTagMemoryWordByWord(bank, filter, ref MemData);
                }
                else
                {
                    // If data read is more then 64 words then perform read with start address as 64 words
                    // and length as zero
                    ReadLargeTagMemory(bank, filter, ref MemData);
                }
            }
            catch (Exception ex)
            {
                if ((ex is FAULT_PROTOCOL_BIT_DECODING_FAILED_Exception) || ((ex is FAULT_NO_TAGS_FOUND_Exception)))
                {
                    // Perform read when the tag has mem more then 128 bytes and doesn't support 
                    // Zero start address and number of words to read as zero
                    ReadLargeTagMemoryWithoutZeroLengthSupport(bank, filter, ref MemData);
                }
                else
                {
                    throw;
                }
            }
        }
Пример #29
0
        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 = (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();
                        }
                        //Use first antenna for operation
                        if (antennaList != null)
                        {
                            r.ParamSet("/reader/tagop/antenna", antennaList[0]);
                        }
                    }
                    else
                    {
                        if (antennaList != null)
                        {
                            Console.WriteLine("Module doesn't support antenna input");
                            Usage();
                        }
                    }

                    // This select filter matches all Gen2 tags where bits 32-48 of the EPC are 0x0123
#if ENABLE_FILTER
                    TagFilter filter = new Gen2.Select(false, Gen2.Bank.EPC, 32, 16, new byte[] { 0x01, 0x23 });
#endif
                    if (!model.Equals("M3e"))
                    {
                        //Gen2.TagData epc = new Gen2.TagData(new byte[] {
                        //    0x01, 0x23, 0x45, 0x67, 0x89, 0xAB,
                        //    0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67,
                        //});
                        //Gen2.WriteTag tagop = new Gen2.WriteTag(epc);
                        //r.ExecuteTagOp(tagop, null);
                    }

                    // Reads data from a tag memory bank after writing data to the requested memory bank without powering down of tag
#if ENABLE_READ_AFTER_WRITE
                    {
                        //create a tagopList with write tagop followed by read tagop
                        TagOpList tagopList = new TagOpList();
                        byte      wordCount;
                        ushort[]  readData;

                        //Write one word of data to USER memory and read back 8 words from EPC memory using WriteData and ReadData
                        {
                            ushort[] writeData = { 0x9999 };
                            wordCount = 8;
                            Gen2.WriteData wData = new Gen2.WriteData(Gen2.Bank.USER, 2, writeData);
                            Gen2.ReadData  rData = new Gen2.ReadData(Gen2.Bank.EPC, 0, wordCount);
                            //Gen2.WriteTag wTag = new Gen2.WriteTag(epc);

                            // assemble tagops into list
                            tagopList.list.Add(wData);
                            tagopList.list.Add(rData);

                            Console.WriteLine("###################Embedded Read after write######################");
                            // uncomment the following for embedded read after write.
                            embeddedRead(TagProtocol.GEN2, null, tagopList);

                            // call executeTagOp with list of tagops
                            //readData = (ushort[])r.ExecuteTagOp(tagopList, null);
                            //Console.WriteLine("ReadData: ");
                            //foreach (ushort word in readData)
                            //{
                            //    Console.Write(" {0:X4}", word);
                            //}
                            //Console.WriteLine("\n");
                        }

                        //clearing the list for next operation
                        tagopList.list.Clear();

                        //Write 12 bytes(6 words) of EPC and read back 8 words from EPC memory using WriteTag and ReadData
                        {
                            Gen2.TagData epc1 = new Gen2.TagData(new byte[] {
                                0x11, 0x22, 0x33, 0x44, 0x55, 0x66,
                                0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc,
                            });
                            wordCount = 8;
                            Gen2.WriteTag wtag  = new Gen2.WriteTag(epc1);
                            Gen2.ReadData rData = new Gen2.ReadData(Gen2.Bank.EPC, 0, wordCount);

                            // assemble tagops into list
                            tagopList.list.Add(wtag);
                            tagopList.list.Add(rData);

                            // call executeTagOp with list of tagops
                            //readData = (ushort[])r.ExecuteTagOp(tagopList, null);
                            //Console.WriteLine("ReadData: ");
                            //foreach (ushort word in readData)
                            //{
                            //    Console.Write(" {0:X4}", word);
                            //}
                            //Console.WriteLine("\n");
                        }
                    }
#endif

                    // Perform read and print UID and tagtype of tag found
                    SimpleReadPlan plan = new SimpleReadPlan(antennaList, TagProtocol.ISO15693, null, null, 1000);
                    r.ParamSet("/reader/read/plan", plan);
                    TagReadData[] tagReads = r.Read(1000);
                    Console.WriteLine("UID: " + tagReads[0].EpcString);
                    Console.WriteLine("TagType:  " + (Iso15693.TagType)(tagReads[0].TagType));
                    MemoryType  type;
                    MultiFilter mulfilter = null;
                    UInt32      address;
                    byte        length;

#if ENABLE_M3E_FILTER
                    //Initialize filter
                    // Filters the tag based on tagtype
                    TagFilter tagTypeFilter = new Select_TagType((UInt64)((Iso15693.TagType)(tagReads[0].TagType)));
                    // Filters the tag based on UID
                    TagFilter uidFilter = new Select_UID(32, ByteFormat.FromHex(tagReads[0].Tag.EpcString.Substring(0, 8)));
                    // Initialize multi filter
                    mulfilter = new MultiFilter(new TagFilter[] { tagTypeFilter, uidFilter });
#endif

#if ENABLE_M3E_BLOCK_READ_WRITE
                    //Initialize all the fields required for Read Data Tag operation
                    type    = MemoryType.BLOCK_MEMORY;
                    address = 0;
                    length  = 1;

                    // Read memory before write
                    ReadMemory bRead    = new ReadMemory(type, address, length);
                    byte[]     dataRead = (byte[])r.ExecuteTagOp(bRead, mulfilter);

                    // prints the data read
                    Console.WriteLine("Read Data before performing block write: ");
                    foreach (byte i in dataRead)
                    {
                        Console.Write(" {0:X2}", i);
                    }
                    Console.WriteLine("\n");
                    // Uncomment this to enable Embedded read memory
                    //embeddedRead(TagProtocol.ISO15693, mulfilter, bRead);

                    // Initialize write memory
                    byte[]      data    = new byte[] { 0x11, 0x22, 0x33, 0x44 };
                    WriteMemory writeOp = new WriteMemory(type, address, data);

                    // Execute the tagop
                    r.ExecuteTagOp(writeOp, mulfilter);
                    // Uncomment this to enable Embedded write data
                    //embeddedRead(TagProtocol.ISO15693, mulfilter, writeOp);

                    //Read memory after block write
                    ReadMemory readOp   = new ReadMemory(type, address, length);
                    byte[]     readData = (byte[])r.ExecuteTagOp(readOp, mulfilter);

                    // prints the data read
                    Console.WriteLine("Read Data after performing block write operation: ");
                    foreach (byte i in readData)
                    {
                        Console.Write(" {0:X2}", i);
                    }
                    Console.WriteLine("\n");
#endif

#if ENABLE_M3E_SYSTEM_INFORMATION_MEMORY
                    //Get the system information of tag. Address and length fields have no significance if memory type is BLOCK_SYSTEM_INFORMATION_MEMORY.
                    type    = MemoryType.BLOCK_SYSTEM_INFORMATION_MEMORY;
                    address = 0;
                    length  = 0;
                    ReadMemory sysInfoOp  = new ReadMemory(type, address, length);
                    byte[]     systemInfo = (byte[])r.ExecuteTagOp(sysInfoOp, mulfilter);

                    // parsing the system info response
                    if (systemInfo.Length > 0)
                    {
                        parseGetSystemInfoResponse(systemInfo);
                    }
#endif

#if ENABLE_M3E_SECURE_ID
                    // Read secure id of tag. Address and length fields have no significance if memory type is SECURE_ID.
                    type    = MemoryType.SECURE_ID;
                    address = 0;
                    length  = 0;
                    ReadMemory secureIdOp = new ReadMemory(type, address, length);
                    byte[]     rspData    = (byte[])r.ExecuteTagOp(secureIdOp, mulfilter);

                    // parse secure id operation response.
                    if (rspData.Length > 0)
                    {
                        parseSecureIdResponse(rspData);
                    }
#endif

#if ENABLE_M3E_BLOCK_PROTECTION_STATUS
                    // Get the block protection status of block 0.
                    type    = MemoryType.BLOCK_PROTECTION_STATUS_MEMORY;
                    address = 0;
                    length  = 1;
                    ReadMemory blkProtectionOp = new ReadMemory(type, address, length);
                    byte[]     statusData      = (byte[])r.ExecuteTagOp(blkProtectionOp, mulfilter);

                    // parse the block protection status response.
                    if (statusData.Length == length)
                    {
                        parseGetBlockProtectionStatusResponse(statusData, address, length);
                    }
#endif
                }
            }
            catch (ReaderException re)
            {
                Console.WriteLine("Error: " + re.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }
Пример #30
0
 /// <summary>
 /// Read tag memory when tag has more then 64 words or 128 bytes. And module doesn't supports zero address and zero length.
 /// Reads the tag memory with 0 address and length of words as 64. If memory overrun received. Initiates reading of tag 
 /// word by word with start address as length of alread read data and length of words to read as 0. Returns the data read from 
 /// tag memory.
 /// </summary>
 /// <param name="bank">Gen2 mem bank</param>
 /// <param name="filter">filter</param>
 /// <param name="data">Data read from tag memory</param>
 private void ReadLargeTagMemoryWithoutZeroLengthSupport(Gen2.Bank bank, TagFilter filter, ref ushort[] data)
 {
     lock (new Object())
     {
         data = null;
         // Data from tag memory
         List<ushort> dataTemp = new List<ushort>();
         // Number of words to read
         int words = 64;
         // Start address
         uint startaddress = 0;
         TagOp op;
         bool isAllDatareceived = true;
         // Read till all the data from the tag memory is read
         while (isAllDatareceived)
         {
             try
             {
                 op = new Gen2.ReadData(bank, startaddress, Convert.ToByte(words));
                 dataTemp.AddRange(((ushort[])objectReader.ExecuteTagOp(op, filter)));
                 // Increment the start address to 64 and keep length of wrods to read as 64 for
                 // all the iterations
                 startaddress += 64;
             }
             catch (Exception ex)
             {
                 try
                 {
                     if (ex is FAULT_GEN2_PROTOCOL_MEMORY_OVERRUN_BAD_PC_Exception || (-1 != ex.Message.IndexOf("Non-specific reader error")) || (-1 != ex.Message.IndexOf("General Tag Error")) || (-1 != ex.Message.IndexOf("Tag data access failed")))
                     {
                         // If the memory to read requested is more then the available memory in the tag, then initiate 
                         // reading the tag memory word by word with start address as length of already read data if exists 
                         // and lenght of words to read is 1
                         ushort[] wordData = null;
                         if (dataTemp.Count > 0)
                         {
                             // If some data is already read then include this data also so that 
                             // reading of memory doesn't continue from zero and the list sholud 
                             // not contain same data twice
                             wordData = dataTemp.ToArray();
                         }
                         ReadTagMemoryWordByWord(bank, filter, ref wordData);
                         dataTemp.AddRange(wordData);
                         // Come out of main while loop. And read the already read data
                         isAllDatareceived = false;
                     }
                     else
                     {
                         throw;
                     }
                 }
                 catch (Exception exception)
                 {
                     // If more then once the below exceptions are recieved then come out of the loop.
                     if (exception is FAULT_GEN2_PROTOCOL_MEMORY_OVERRUN_BAD_PC_Exception || (-1 != exception.Message.IndexOf("Non-specific reader error")) || (-1 != exception.Message.IndexOf("General Tag Error")) || (-1 != exception.Message.IndexOf("Tag data access failed")))
                     {
                         if (dataTemp.Count > 0)
                         {
                             // Just skip the exception and move on. So as not to lose the already read data.
                             isAllDatareceived = false;
                         }
                         else
                         {
                             // throw the exception if the data received is null for the first iteration itself
                             throw;
                         }
                     }
                     else
                     {
                         throw;
                     }
                 }
             }
         }
         data = dataTemp.ToArray();
     }
 }
Пример #31
0
        static void Main(string[] args)
        {
            try
            {
                // connect to and initialize reader
                Reader reader = Common.EstablishReader();

                // setup sensor activation commands and filters ensuring On-Chip RSSI Min Filter is applied
                Gen2.Select tempsensorEnable = Common.CreateGen2Select(4, 4, Gen2.Bank.TID, 0x00, 16, new byte[] { (byte)0xE2, (byte)0x82 });
                Gen2.Select ocrssiMinFilter  = Common.CreateGen2Select(4, 0, Gen2.Bank.USER, 0xA0, 8, new byte[] { (byte)(0x20 | ocrssiMin - 1) });
                Gen2.Select ocrssiMaxFilter  = Common.CreateGen2Select(4, 2, Gen2.Bank.USER, 0xA0, 8, new byte[] { ocrssiMax });
                MultiFilter selects          = new MultiFilter(new Gen2.Select[] { tempsensorEnable, ocrssiMinFilter, ocrssiMaxFilter });

                Gen2.ReadData operation;
                if (moistureMode)
                {
                    // read parameters for moisture code
                    operation = new Gen2.ReadData(Gen2.Bank.RESERVED, 0xB, (byte)1);
                }
                else
                {
                    // read parameters for on-chip RSSI code
                    operation = new Gen2.ReadData(Gen2.Bank.RESERVED, 0xD, (byte)1);
                }

                // create configuration
                SimpleReadPlan config = new SimpleReadPlan(Common.antennas, TagProtocol.GEN2, selects, operation, 1000);
                reader.ParamSet("/reader/read/plan", config);

                for (int i = 1; i <= readAttempts; i++)
                {
                    Console.WriteLine("Read Attempt #" + i);

                    // attempt to read sensor tags
                    TagReadData[] results = reader.Read(Common.readTime);

                    if (results.Length != 0)
                    {
                        foreach (TagReadData tag in results)
                        {
                            String epc = tag.EpcString;
                            Console.WriteLine("* EPC: " + epc);
                            byte[]  dataBytes = tag.Data;
                            short[] dataWords = Common.ConvertByteArrayToShortArray(dataBytes);
                            if (dataWords.Length != 0)
                            {
                                if (moistureMode)
                                {
                                    Console.WriteLine("  - Moisture: " + dataWords[0] + " at " + tag.Frequency + " kHz");
                                }
                                else
                                {
                                    Console.WriteLine("  - On-Chip RSSI: " + dataWords[0]);
                                }
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("No tag(s) found");
                    }
                    Console.WriteLine();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.ToString());
                Environment.Exit(-1);
            }
        }
Пример #32
0
        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 ((r is SerialReader) || (r is LlrpReader))
                    {
                        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]);
                            }
                        }
                        Gen2.Password pass = new Gen2.Password(0x0);
                        r.ParamSet("/reader/gen2/accessPassword", pass);


                        // BlockWrite and read using ExecuteTagOp

                        Gen2.BlockWrite blockwrite = new Gen2.BlockWrite(Gen2.Bank.USER, 0, new ushort[] { 0xFFF1, 0x1122 });
                        r.ExecuteTagOp(blockwrite, null);

                        Gen2.ReadData read     = new Gen2.ReadData(Gen2.Bank.USER, 0, 2);
                        ushort[]      readData = (ushort[])r.ExecuteTagOp(read, null);

                        foreach (ushort word in readData)
                        {
                            Console.Write(String.Format(" {0:X4}", word));
                        }
                        Console.WriteLine();


                        // BlockWrite and read using embedded read command

                        SimpleReadPlan readplan;
                        TagReadData[]  tagreads;

                        blockwrite = new Gen2.BlockWrite(Gen2.Bank.USER, 0, new ushort[] { 0x1234, 0x5678 });
                        readplan   = new SimpleReadPlan(null, TagProtocol.GEN2,
                                                        //null,
                                                        new TagData("1234567890ABCDEF"),
                                                        blockwrite, 0);
                        r.ParamSet("/reader/read/plan", readplan);
                        r.Read(500);

                        readplan = new SimpleReadPlan(null, TagProtocol.GEN2,
                                                      null,
                                                      new Gen2.ReadData(Gen2.Bank.USER, 0, 2),
                                                      0);
                        r.ParamSet("/reader/read/plan", readplan);
                        tagreads = r.Read(500);
                        foreach (TagReadData trd in tagreads)
                        {
                            foreach (byte b in trd.Data)
                            {
                                Console.Write(String.Format(" {0:X2}", b));
                            }

                            Console.WriteLine("    " + trd.ToString());
                        }
                    }
                    else
                    {
                        Console.WriteLine("Error: This codelet works only for Serial Readers and Llrp Readers");
                    }
                }
            }
            catch (ReaderException re)
            {
                Console.WriteLine("Error: " + re.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }
Пример #33
0
        static void Main(string[] args)
        {
            try
            {
                // connect to and initialize reader
                Reader reader = Common.EstablishReader();

                // setup sensor activation commands and filters ensuring On-Chip RSSI Min Filter is applied
                Gen2.Select globalEnable    = Common.CreateGen2Select(4, 2, Gen2.Bank.USER, 0x3B0, 8, new byte[] { (byte)0x00 });
                Gen2.Select ocrssiMinFilter = Common.CreateGen2Select(4, 0, Gen2.Bank.USER, 0x3D0, 8, new byte[] { (byte)(0x20 | ocrssiMin - 1) });
                Gen2.Select ocrssiMaxFilter = Common.CreateGen2Select(4, 2, Gen2.Bank.USER, 0x3D0, 8, new byte[] { ocrssiMax });
                MultiFilter selects         = new MultiFilter(new Gen2.Select[] { globalEnable, ocrssiMinFilter, ocrssiMaxFilter });

                // parameters to read all three sensor codes at once
                Gen2.ReadData operation = new Gen2.ReadData(Gen2.Bank.RESERVED, 0xA, (byte)5);

                // create configuration
                SimpleReadPlan config = new SimpleReadPlan(Common.antennas, TagProtocol.GEN2, selects, operation, 1000);

                for (int i = 1; i <= readAttempts; i++)
                {
                    Console.WriteLine("\nRead Attempt #" + i);

                    // optimize settings for reading sensors
                    reader.ParamSet("/reader/read/plan", config);
                    reader.ParamSet("/reader/gen2/t4", (UInt32)9000);  // CW delay in microseconds
                    reader.ParamSet("/reader/gen2/session", Common.session);
                    reader.ParamSet("/reader/gen2/q", new Gen2.DynamicQ());

                    // attempt to read sensor tags
                    TagReadData[] results = reader.Read(Common.readTime);

                    reader.ParamSet("/reader/gen2/t4", (UInt32)300);
                    reader.ParamSet("/reader/gen2/session", Gen2.Session.S0);
                    reader.ParamSet("/reader/gen2/q", new Gen2.StaticQ(0));

                    if (results.Length != 0)
                    {
                        foreach (TagReadData tag in results)
                        {
                            String epc = tag.EpcString;
                            Console.WriteLine("* EPC: " + epc);
                            byte[]  dataBytes = tag.Data;
                            short[] dataWords = Common.ConvertByteArrayToShortArray(dataBytes);
                            if (dataWords.Length != 0)
                            {
                                int backport1Code   = dataWords[0];
                                int backport2Code   = dataWords[1];
                                int moistureCode    = dataWords[2];
                                int ocrssiCode      = dataWords[3];
                                int temperatureCode = dataWords[4];

                                // On-Chip RSSI Sensor
                                Console.WriteLine("  - On-Chip RSSI: " + ocrssiCode);

                                // Moisture Sensor
                                String moistureStatus;
                                if (ocrssiCode < 5)
                                {
                                    moistureStatus = "power too low";
                                }
                                else if (ocrssiCode > 21)
                                {
                                    moistureStatus = "power too high";
                                }
                                else
                                {
                                    moistureStatus = moistureCode + " at " + tag.Frequency + " kHz";
                                }
                                Console.WriteLine("  - Moisture: " + moistureStatus);

                                // Temperature Sensor
                                String temperatureStatus;
                                if (ocrssiCode < 5)
                                {
                                    temperatureStatus = "power too low";
                                }
                                else if (ocrssiCode > 18)
                                {
                                    temperatureStatus = "power too high";
                                }
                                else if (temperatureCode < 1000 || 3500 < temperatureCode)
                                {
                                    temperatureStatus = "bad read";
                                }
                                else
                                {
                                    try
                                    {
                                        // read, decode and apply calibration one tag at a time
                                        short[] calibrationWords   = Common.ReadMemBlockByEpc(reader, tag, Gen2.Bank.USER, 0x12, 4);
                                        TemperatureCalibration cal = new TemperatureCalibration(calibrationWords);
                                        if (cal.valid)
                                        {
                                            double temperatureValue = cal.slope * temperatureCode + cal.offset;
                                            temperatureStatus = temperatureValue.ToString("0.00") + " degC";
                                        }
                                        else
                                        {
                                            temperatureStatus = "invalid calibration";
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        temperatureStatus = "failed to read calibration";
                                    }
                                }
                                Console.WriteLine("  - Temperature: " + temperatureStatus);

                                // Backport 1 Sensor
                                String backport1Status;
                                if (ocrssiCode < 5)
                                {
                                    backport1Status = "power too low";
                                }
                                else if (ocrssiCode > 18)
                                {
                                    backport1Status = "power too high";
                                }
                                else
                                {
                                    backport1Status = backport1Code + "";
                                }
                                Console.WriteLine("  - Backport 1: " + backport1Status);

                                // Backport 1 Sensor
                                String backport2Status;
                                if (ocrssiCode < 5)
                                {
                                    backport2Status = "power too low";
                                }
                                else if (ocrssiCode > 18)
                                {
                                    backport2Status = "power too high";
                                }
                                else
                                {
                                    backport2Status = backport2Code + "";
                                }
                                Console.WriteLine("  - Backport 2: " + backport2Status);
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("No tag(s) found");
                    }
                    Console.WriteLine();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.ToString());
                Environment.Exit(-1);
            }
        }
Пример #34
0
        public ReadPlan LoadSimpleReadPlan(string valstr)
        {
            Object value = ParseValue(valstr);
            string str   = string.Empty;

            //Reamoves leading string for ex: SimpleReadPlan:
            str = valstr.Remove(0, 15);
            SimpleReadPlan srp = new SimpleReadPlan();
            //Regular expression to remove leading and trailing square brackets
            string remove = Regex.Replace(str, @"]$|^\[", "");

            //Regular expression to split the string
            string[]  lines = Regex.Split(remove, @",(?![^\[\]]*\])");
            TagFilter tf    = null;
            TagOp     op    = null;

            foreach (string line in lines)
            {
                if (-1 != line.IndexOf("Antennas"))
                {
                    ArrayList list    = new ArrayList();
                    int[]     antList = null;
                    object    value1  = ParseValue(line.Split('=')[1]);
                    if (value1 != null)
                    {
                        antList = (int[])((ArrayList)value1).ToArray(typeof(int));
                    }
                    srp.Antennas = antList;
                }
                else if (-1 != line.IndexOf("Protocol"))
                {
                    srp.Protocol = (TagProtocol)Enum.Parse(typeof(TagProtocol), line.Split('=')[1], true);
                }
                else if (-1 != line.IndexOf("Filter"))
                {
                    string filterData = line.Split('=')[1];
                    if (-1 != filterData.IndexOf("Gen2.Select"))
                    {
                        str = line.Remove(0, 19);
                        //Regular expression to remove leading and trailing square brackets
                        str = Regex.Replace(str, @"]$|^\[", "");
                        //Regular expression to split the string
                        string[]  select     = Regex.Split(str, @"[ ,;]+");
                        bool      Invert     = false;
                        Gen2.Bank bank       = Gen2.Bank.EPC;
                        uint      BitPointer = 0;
                        ushort    BitLength  = 0;
                        byte[]    mask       = null;
                        if (select.Length != 5)
                        {
                            throw new Exception("Invalid number of arguments for ReadPlan filter");
                        }
                        foreach (string arg in select)
                        {
                            if (-1 != arg.IndexOf("Invert"))
                            {
                                Invert = Convert.ToBoolean(arg.Split('=')[1]);
                            }
                            else if (-1 != arg.IndexOf("Bank"))
                            {
                                bank = (Gen2.Bank)Enum.Parse(typeof(Gen2.Bank), arg.Split('=')[1], true);
                            }
                            else if (-1 != arg.IndexOf("BitPointer"))
                            {
                                BitPointer = Convert.ToUInt32(arg.Split('=')[1]);
                            }
                            else if (-1 != arg.IndexOf("BitLength"))
                            {
                                BitLength = Convert.ToUInt16(arg.Split('=')[1]);
                            }
                            else if (-1 != arg.IndexOf("Mask"))
                            {
                                mask = StringToByteArray(arg.Split('=')[1]);
                            }
                            else
                            {
                                throw new Exception("Invalid Argument in ReadPlan");
                            }
                        }
                        tf = new Gen2.Select(Invert, bank, BitPointer, BitLength, mask);
                    }
                    else if (-1 != filterData.IndexOf("EPC"))
                    {
                        str = line.Remove(0, 15);
                        str = Regex.Replace(str, @"]$|^\[", "");
                        tf  = new TagData(StringToByteArray((str.Split('=')[1])));
                    }
                    else
                    {
                        if (!filterData.Equals("null"))
                        {
                            throw new Exception("Invalid Argument in ReadPlan");
                        }
                    }
                }
                else if (-1 != line.IndexOf("Op"))
                {
                    string tagOpData = line.Split('=')[1];
                    if (tagOpData != null)
                    {
                        if (-1 != tagOpData.IndexOf("ReadData"))
                        {
                            str = line.Remove(0, 12);
                            //Regular expression to remove leading and trailing square brackets
                            str = Regex.Replace(str, @"]$|^\[", "");
                            //Regular expression to split the string
                            string[]  select      = Regex.Split(str, @"[ ,;]+");
                            Gen2.Bank bank        = Gen2.Bank.EPC;
                            uint      wordAddress = 0;
                            byte      length      = 0;
                            foreach (string arg in select)
                            {
                                if (-1 != arg.IndexOf("Bank"))
                                {
                                    bank = (Gen2.Bank)Enum.Parse(typeof(Gen2.Bank), arg.Split('=')[1], true);
                                }
                                else if (-1 != arg.IndexOf("WordAddress"))
                                {
                                    wordAddress = Convert.ToUInt32(arg.Split('=')[1]);
                                }
                                else if (-1 != arg.IndexOf("Len"))
                                {
                                    length = Convert.ToByte(arg.Split('=')[1]);
                                }
                                else
                                {
                                    throw new Exception("Invalid Argument in ReadPlan TagOp");
                                }
                            }
                            op = new Gen2.ReadData(bank, wordAddress, length);
                        }
                        else
                        {
                            if (!tagOpData.Equals("null"))
                            {
                                throw new Exception("Invalid Argument in ReadPlan");
                            }
                        }
                    }
                }
                else if (-1 != line.IndexOf("UseFastSearch"))
                {
                    srp.UseFastSearch = Convert.ToBoolean(line.Split('=')[1]);
                }
                else if (-1 != line.IndexOf("Weight"))
                {
                    srp.Weight = Convert.ToInt32(lines[5].Split('=')[1]);
                }
                else
                {
                    throw new Exception("Invalid Argument in ReadPlan");
                }
            }
            srp.Filter = tf;
            srp.Op     = op;
            return(srp);
        }