RFID – MIMO Prototype based on GnuRadio
Bachelor Thesis
written by
Amelia Jiménez Sánchez
July 2014
Submitted to
Institute of Digital Signal Processing
Prof. Dr. - Ing. Thomas Kaiser
University Duisburg-Essen
.
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Abstract
2
Abstract This thesis discusses the possibility of setting up a prototyping MIMO RFID testbed based on USRP devices and GnuRadio implementation for UHF RFID systems. The performance improvements will be compared to existing commercial and USRP single antenna solutions.
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Acronyms
3
Acronyms AGC ASK BLF CRC CW DR DSB EGC EPC EPC Gen 2 ETSI FCC ISM MAC MIMO MRC MSB PHY PIE PR R=>T RF RFID RN16 RSSI RTcal SC SDR SNR SSB SWOT T=>R TRcal UHF USRP
Automatic Gain Control Amplitude-Shift Keying Backscatter Link Frequency Cyclic Redundancy Check Continuous RF-Wave Divide Ratio Double-SideBand Modulation Equal Gain Combining Electronic Product Code Electronic Product Code Generation 2 European Telecommunication Standards Institute Federal Communication Commission Industrial, Scientific and Medical Media Access Control Multiple Input Multiple Output Maximal Ratio Combining Most Significant Bit Physical Pulse Interval Encoding Phase Reversal Interrogator-to-Tag Radio Frequency Radio Frequency Identification 16-bit Random Number Received Signal Strength Indicator Interrogator-to-Tag calibration Selection Combining Software Defined Radio Signal-to-Noise Ratio Single-SideBand Modulation Strengths, Weaknesses, Opportunities, Threats Tag-to-Interrogator Tag-to-Interrogator calibration Ultra High Frequency Universal Software Radio Peripheral
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Contents
4
Contents
Abstract ...................................................................................................................... 2
Acronyms .................................................................................................................... 3
Contents ..................................................................................................................... 4
List of Figures ............................................................................................................. 6
List of Pictures ............................................................................................................ 7
List of Tables .............................................................................................................. 8
Motivation ................................................................................................................... 9
I. Introduction ........................................................................................................ 10
II. Background ........................................................................................................ 12
1. Physical interface ............................................................................................ 13
1.1. Interrogator-to-Tag (R=>T) communications ............................................ 13
1.2. Tag-to-Interrogator (T=>R) communications ............................................ 17
1.3. Transmission Order .................................................................................. 21
1.4. CRC ......................................................................................................... 21
1.1. Link Timing ............................................................................................... 22
2. Logical interface .............................................................................................. 23
2.1. Sessions and inventoried flags ................................................................. 23
2.2. Selected flag ............................................................................................ 24
2.3. Tag states and slot counter ...................................................................... 24
2.4. Tag random or pseudo-random number generator .................................. 24
2.5. Managing Tag populations ....................................................................... 24
2.6. Inventorying Tag populations ................................................................... 25
3. Electronic Product Code (EPC) ...................................................................... 28
4. Diversity Combining techniques ...................................................................... 28
III. Implementation ............................................................................................... 31
IV. Experimental Results ...................................................................................... 37
V. Summary and Conclusion .................................................................................. 42
References ............................................................................................................... 43
Annex ....................................................................................................................... 44
1. Gen2 RFID Listener ........................................................................................ 44
2. Gen2 RFID Listener with SC ........................................................................... 49
3. Listener Reader Monitor Cmd Gate ................................................................ 54
4. Listener Tag Monitor ....................................................................................... 61
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Contents
5
5. SC Block C++ ................................................................................................. 72
6. SC Block .h ..................................................................................................... 74
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio List of Figures
6
List of Figures Figure 1: Reader message and tag response ........................................................... 12
Figure 2: Uplink and downlink communication .......................................................... 13 Figure 3: PIE symbols [From [9] ] ............................................................................. 14 Figure 4: Interrogator power-up and power-down RF envelope [From [9]] ............... 15 Figure 5: R=>T preamble and frame-sync [From [9]] ................................................ 16 Figure 6: FMO symbols and sequences [From [9]] .................................................. 17
Figure 7: Terminating FMO transmissions [From [9]] .............................................. 17 Figure 8: FM0 T=>R preamble [From [9]] ................................................................. 17 Figure 9: Miller basis functions and generator state diagram [From [9]] ................... 18 Figure 10: Subcarrier sequences [From [9]] ............................................................. 18 Figure 11: Terminating subcarrier transmissions [From [9]] ..................................... 18
Figure 12: Subcarrier T=>R preamble [From [9]] ..................................................... 19
Figure 13: FM0 basis functions and generator state diagram [From [9]] .................. 19
Figure 14: Link timing [From [9]] ............................................................................... 22 Figure 15: Session diagram [From [9]] ..................................................................... 23 Figure 16: The EPC Query Process ......................................................................... 27 Figure 17: Basic format of an EPC [From [18]] ......................................................... 28 Figure 18: Monitor system diagram [From [1]] ......................................................... 31
Figure 19: Block diagram of the implemented RFID Listener ................................... 31 Figure 20: Block diagram of SC implementation ....................................................... 35
Figure 21: Block diagram of SC implementation simplified ....................................... 35 Figure 22: Possible block diagram for MRC ............................................................. 36
Figure 23: Topology used for the experiment ........................................................... 37 Figure 24: Performance achieved for the RFID Listener. Rx .................................... 40
Figure 25: Performance achieved for the RFID Listener. Rx2 .................................. 40 Figure 26: Performance achieved for the RFID Listener. SC .................................... 40
Figure 27: Listener-Success Ratio ............................................................................ 41
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio List of Pictures
7
List of Pictures Picture 1: Sheldon using RFID tags [From http://goo.gl/jxo7Rz] ................................. 9
Picture 2: Changes to make a decision .................................................................... 32 Picture 3: Inventory commands ................................................................................ 33 Picture 4: Bits of the query command ....................................................................... 33 Picture 5: Changes to print out ................................................................................. 33 Picture 6: Setting of the parameters ......................................................................... 34
Picture 7: Implementation of Tag Messages ............................................................. 34 Picture 8: Header of EPC ......................................................................................... 34 Picture 9: Signal processing of SC block .................................................................. 36 Picture 10: RFID deployment .................................................................................... 37
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio List of Tables
8
List of Tables Table 1: Interrogator power-up waveform parameters [From [9]] ............................. 15
Table 2: Interrogator power-down waveform parameters [From [9]] ......................... 15 Table 3: Tag-to-Interrogator link frequencies [From [9]] ........................................... 21 Table 4: Tag-to-Interrogator data rates [From [9]] .................................................... 21 Table 5: Query command ......................................................................................... 25 Table 6: Tag reply to a Query command .................................................................. 25
Table 7: QueryAdjust command ............................................................................... 26 Table 8: Tag reply to a QueryAdjust command ........................................................ 26
Table 9: QueryRep command ................................................................................... 26 Table 10: Tag reply to a QueryRep command .......................................................... 26
Table 11: ACK command .......................................................................................... 27 Table 12: Tag reply to a successful ACK command ................................................. 27
Table 13: NAK command .......................................................................................... 27
Table 14: , , and for Rx ................................ 38
Table 15: , , and for Rx2 .............................. 38
Table 16: , , and for SC................................ 38
Table 17: L-SR, CRC Error Ratio and CRC Miss Ratio for Rx .................................. 39 Table 18: L-SR, CRC Error Ratio and CRC Miss Ratio for Rx2 ................................ 39 Table 19: L-SR, CRC Error Ratio and CRC Miss Ratio for SC ................................. 39
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Motivation
9
Motivation In order to write my Bachelor Thesis, the first question that came out to me was: which topic should I choose? To answer this, I refer a video1 from The Big Bang Theory that is a scientific spreading serie and also, one of my favorite.
Picture 1: Sheldon using RFID tags
[From http://goo.gl/jxo7Rz]
As we could see in the video, Sheldon has an imperative necessity about identifying easily and fast his clothes, his socks in this particular case. He wants to simplify the task of packing. Although, he is not the only one who has this need. For many persons in the world or work, persons in society, institutions, etc., they have similar needs. Sheldon found a solution using RFID tags. This technology has been developed and has become a solution in several fields like: Asset management, Retail, Entertainment, Healthcare, Logistics and The Internet of Things. It has been developed by engineers working on technological companies or researching. My project: RFID-MIMO Prototype based on GnuRadio is a possible improvement to an existing solution.
1 https://www.youtube.com/watch?v=m5pTKqKaElA
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Introduction
10
I. Introduction Why would you use RFID tags? In several research projects it has already proven its benefits for the transport and logistics industry. The enterprises have now a much better overview what is going on in the different steps of the supply chain and can organize their transport and deliveries more efficiently. But not only for transport and logistics industry, there are several fields of application: retail (store inventory, stock checking, accuracy of pricing, to eliminate out of stock situations, etc); government (border security, ePassport reading, etc); warehouse & distribution; public transport (baggage reconciliation, contactless ticketing, access control, etc); health care (patient identification, medication management, diagnosis information, etc); construction (recording of working hours, disaster recovery, site access control); leisure (ticketing, person identification, GPS tracking, captioning photography). More information can be found in [16]. RFID is a wireless technology that allows small inexpensive computer chips to be remotely powered and interrogated for identification and other information. In other words, we can say that our solution must be cheap and flexible, this is possible using Software Defined Radio (SDR). Though, the Future Store, where the RFID technology will replace the stock keeping as well as the current cashing systems with their barcodes, didn't progress since the early days of RFID. Common problems are the reliable detection of the different articles, even under extreme condition, e.g. articles overlapping or hiding each other, the big amount of articles together with the costs of the tag compared to barcodes. In order to reduce these costs for the tags our research interest focusses on PHY algorithms on the RFID reader side. We want to improve current implementations by making use of more advanced digital signal processing mainly in terms of MIMO. In order to combat multipath propagation today‟s RFID readers utilize several receive antenna multiplexing. They simply multiplex the receive signals from the various receive antennas in a regular fashion. Diversity Combining is the technique applied to combine the multiple received signals of a diversity reception device into a single improved signal. Various diversity combining techniques can be distinguished: Equal Gain Combining (EGC), Maximal Ratio Combining (MRC), Switched Combining, Selection Combining (SC). Sometimes more than one combining technique is used, for example, lucky imaging uses SC to choose (typically) the best 10% images, followed by EGC of the selected images. With this work we designed a digital RFID listener performing SC. Selection
Combining of the received signals, the strongest signal is selected. When the signals are independent and Rayleigh distributed, the expected diversity gain has been shown to be
∑
expressed as a power ratio. We also proposed a possible implementation for MRC. Thus, regarding the total signal to noise ratio (SNR) output, it combines the signal of two antennas in an optimal way. The advantage in contrast to antenna multiplexing is
obvious: First, antenna multiplexing needs to multiplex all receive antennas to identify the antenna with the highest SNR. Second, MRC always results in a stronger SNR than each of the single antenna receive paths. The trade-off is the increased signal processing complexity.
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Introduction
11
First, in Section II a background of RFID communication is given. In Section III we describe the process that was followed in this experiment. The experimental results that were obtained are presented in Section IV with an interpretation of them. In Section V we conclude and summarize our paper. Then, some references are given. Finally, in Annex the source codes can be found at the end of the document.
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Background
12
II. Background How do RFID tags work? From [1], we know that we can develop a low cost software radio based platform for monitoring EPC Gen 2 RFID traffic. One of the main advantages of using SDR, compared to tradition hardware implementations, it is the possibility of to implement various radios in the same hardware, or to change the configuration by adjusting the software parameters. Another one, as we said before, it is that this implementation is going to be cheap and flexible. Our monitoring system is going to consist of only a N210 USRP or B210, an Impinj Speedway Reader and a laptop. By using the open source GNU Radio toolkit, in our laptop, to process signals on the host, the software is free and can be easily modified by researchers. In the conventional design, the reader combines in a single physical device transmission (to the tags) and reception (from the tags) functions, but there is an alternative approach, where receive functions are performed by a separate device called "RFID Listener" [2]. Gen 2 standard allows for great flexibility in terms of both physical layer configuration and the sequence of reader commands that can be used to inventory tags. Gen 2 tags are fully passive, which means that they do not have their own source of energy. Also, they cannot communicate with each other or even hear other tags transmissions; this is one of the reasons why Gen 2 MAC protocol is based on Framed Slotted Aloha. Communication is achieved via "backscatter" transmission. Tags do not technically transmit any energy; instead, they manipulate how well they reflect the incident CW as we can see in Figure 1, this picture has been taken from [2].
Figure 1: Reader message and tag response
[From [1]] In Figure 2, we can see that in the forward link communication (addressed as uplink), the reader interrogates the tag with a data transfer that utilizes an ASK modulation scheme; the return data transfer, from tag to reader (addressed as downlink), utilizes a backscattered modulation scheme as we mentioned before.
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Background
13
Figure 2: Uplink and downlink communication
Uplink modulation is determined by two parameters specified by the reader; uplink frequency and data encoding. Gen 2 specifies four encoding schemes that differ in the number of cycles per symbol (FM0 or Miller-2/4/8) that vary in how many cycles they use per symbol, with more cycles reducing the data rate but being more robust to noise. Although there are some regulations according to devices working on the ISM band, transmission could collide. Regulations have the aim to reduce any interference or disturbances to other bands or health regulations. They do not handle collisions; collisions must be handled by the different standards. Tags do not "tune" to different channels, so when multiple readers are active in an area their transmission will collide at tags even if the readers are on different channels. We know from [6] that single antenna receivers are only capable of recovering from collisions of two tags and that multiple antenna receivers can recover from a collision of up to M tags if M is less than the number of receiving antennas and the channel is known at the receiver. Thus, our future system with two receiver antennas will suppose an advantage over a single antenna system in terms of reliable detection. The operation procedure defines the physical and logical requirements for an Interrogator-talks-first, random-slotted collision arbitration, RFID system operating in the 860 – 960 MHz frequency range, 868 MHz is for Europe (ETSI) and 915 MHz is for US (FCC).
1. Physical interface The physical interface between an Interrogator and a Tag may be viewed as the signaling layer in a layered network communication system. The signaling interface defines frequencies, modulation, data coding, RF envelope, data formates, and other parameters required for RF communications.
1.1. Interrogator-to-Tag (R=>T) communications An Interrogator communicates with one or more Tags by modulating an RF carrier using DSB-ASK, SSB-ASK, or PR-ASK with PIE encoding. Interrogators shall use a fixed modulation format and data rate for the duration of an inventory round, where “inventory round” is defined in 4.1 from [9]. The Interrogator sets the data rate by means of the preamble that initiates the inventory round.
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Background
14
1.1.1. Modulation Interrogators shall communicate using DSB-ASK, SSB-ASK, or PR-ASK modulation, detailed in Annex H from [9]. Tags shall be able to demodulate all three modulation types.
1.1.2. Data encoding The R=>T link shall use PIE, shown in Figure 3. Tari is the reference time interval for Interrogator-to-Tag signaling, and is the duration of a data-0. High values represent transmitted CW; low values represent attenuated CW. Pulse modulation depth, rise time, fall time, and PW shall be as specified in [9], and shall be the same for a data-0 and a data-1. Interrogators shall use a fixed modulation depth, rise time, fall time, PW, Tari, data-0 length, and data-1 length for the duration of an inventory round.
Figure 3: PIE symbols
[From [9] ]
1.1.3. Tari values Interrogators shall communicate using Tari values in the range of 6.25µs to 25µs. Interrogator compliance shall be evaluated using at least one Tari value between 6.25µs and 25µs with at least one value of the parameter x. The tolerance on all parameters specified in units of Tari shall be +/-1%. The choice of Tari value and x shall be in accordance with local radio regulations.
1.1.4. Interrogator power-up waveform The Interrogator power-up RF envelope shall comply with Figure 4 and Table 1. Once the carrier level has risen above the 10% level, the power-up
envelope shall rise monotonically until at least the ripple limit .The RF envelope shall not fall below the 90% point in Figure 4 during interval
.Interrogators shall not issue commands before the end of the maximum
settling-time interval in Table 1 (i.e. before the end of . Interrogators shall meet the frequency-accuracy requirement specified in [9] by the end of interval
in Figure 4.
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Background
15
Figure 4: Interrogator power-up and power-down RF envelope
[From [9]]
Table 1: Interrogator power-up waveform parameters
[From [9]]
Table 2: Interrogator power-down waveform parameters
[From [9]]
1.1.5. Interrogator power-down waveform The Interrogator power-down RF envelope shall comply with Figure 4 and Table 2. Once the carrier level has fallen below the 90% level, the power-down envelope shall fall monotonically until the power-off limit Ms. Once powered off, an Interrogator shall remain powered off for a least 1ms before powering up again.
1.1.6. R=>T preamble and frame-sync An Interrogator shall begin all R=>T signaling with either a preamble or a frame-sync, both of which are shown in Figure 5. A preamble shall precede a Query command and denotes the start of an inventory round. All other signaling shall begin with a frame-sync.
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Background
16
Figure 5: R=>T preamble and frame-sync [From [9]]
A preamble shall comprise a fixed-length start delimiter, a data-0 symbol, an R=>T calibration (RTcal) symbol, and a T=>R calibration (TRcal) symbol.
RTcal: An Interrogator shall set RTcal equal to the length of a data-0
symbol plus the length of a data-1 symbol( ). A
Tag shall measure the length of RTcal and compute pivot = RTcal / 2. A Tag shall interpret subsequent Interrogator symbols shorter than pivot to be data-0s, and subsequent Interrogator symbols longer than pivot to be data-1s. A Tag shall interpret symbols longer than 4 RTcal to be invalid. Prior to changing RTcal, an Interrogator shall transmit CW for a minimum of 8 RTcal.
TRcal: An interrogator shall specify a Tag‟s backscatter link frequency (its FM0 data-rate of its Miller subcarrier) using the TRcal and divide ratio (DR) in the preamble and payload, respectively, of a Query command that initiates an inventory round. Equation 1 specifies the relationship between the backscatter link frequency (BLF), TRcal and DR. A Tag shall measure the length of TRcal, compute BLF, and adjust its T=>R link rate to be equal to BLF. The TRcal and RTcal that an Interrogator uses in any inventory round shall meet the constraints in Equation 2.
( )
( )
A frame-sync is identical to a preamble, minus the TRcal symbol. An Interrogator, for the duration of an inventory round, shall use the same length RTcal in a frame-sync as it used in the preamble that initiated the round.
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Background
17
1.2. Tag-to-Interrogator (T=>R) communications A Tag communicates with an Interrogator using backscatter modulation, in which the Tag switches the reflection coefficient of its antenna between two states in accordance with the data being sent.
A Tag shall backscatter using a fixed modulation format, data encoding, and data rate for the duration of an inventory round. The Tag selects the modulation format; the Interrogator selects the data encoding and data rate by means of the Query command that initiates the round. The low values in Figure 7, Figure 8, Figure 9, Figure 10, Figure 11, Figure 12 and Figure 12 correspond to the antenna-reflectivity state the Tag exhibits during the CW period prior to a T=>R preamble (e.g. ASK Tag absorbing power), whereas the high values correspond to the antenna-reflectivity state the Tag exhibits during the first high pulse of a T=>R preamble (e.g. ASK Tag reflecting power).
Figure 6: FMO symbols and sequences
[From [9]]
Figure 7: Terminating FMO transmissions
[From [9]]
Figure 8: FM0 T=>R preamble
[From [9]]
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Background
18
Figure 9: Miller basis functions and generator state diagram
[From [9]]
Figure 10: Subcarrier sequences
[From [9]]
Figure 11: Terminating subcarrier transmissions
[From [9]]
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Background
19
Figure 12: Subcarrier T=>R preamble
[From [9]]
1.2.1. Modulation Tag backscatter shall use ASK and/or PSK modulation. The Tag manufacturer selects the modulation format. Interrogators shall demodulate both modulation types.
1.2.2. Data encoding Tags shall encode the backscattered data as either FM0 baseband or Miller modulation of a subcarrier at the data rate. The Interrogator specifies the encoding type.
FM0 baseband Figure 13 shows basis functions and a state diagram for generating FM0 (bi-phase space) encoding. FM0 inverts the baseband phase at every symbol boundary; a data-0 has an additional mid-symbol phase inversion. The state diagram in Figure 13 maps a logical data sequence to the FM0 basis functions
that are transmitted. The state labels, , indicate four possible FM0-encoded symbols, represented by the two phases of each of the FM0 labels on the state transitions indicate the logical values of the data sequence to be
encoded. For example, a transition from state to is disallowed because the resulting transmission would not have a phase inversion on a symbol boundary.
Figure 13: FM0 basis functions and generator state diagram
[From [9]]
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Background
20
Figure 6 shows generated baseband FM0 symbols and sequences. The duty cycle of a 00 or 11 sequence, measured at the modulator output, shall be a minimum of 45% and a maximum of 55%, with a nominal value of 50%. FM0 encoding has memory; consequently, the choice of FM0 sequences in Figure 6 depends on prior transmissions. FM0 signaling shall always end with a “dummy” data-1 bit at the end of a transmission, as shown in Figure 7.
FM0 preamble T=>R FM0 signaling shall begin with one of the two preambles shown in Figure 8. The choice depends on the TRext value specified in the Query that initiated the inventory round, unless a Tag is replying to a command that uses a delayed or in-process reply (further information in [9]), in which case a Tag shall use the extended preamble regardless of TRext. The “v” shown in Figure 8 indicates an FM0 violation (i.e. a phase inversion should have occurred but did not).
Miller-modulated subcarrier Figure 9 shows basis functions and a state diagram for generating Miller encoding. Baseband Miller inverts its phase between two data-0s in sequence. Baseband Miller also places a phase inversion in the middle of a data-1 symbol. The state diagram in Figure 9 maps a logical data sequence to
baseband Miller basis functions. The state labels, , indicate four possible Miller-encoded symbols, represented by the two phases of each of the Miller basis functions. The state labels also represent the baseband Miller waveform that is generated upon entering the state. The transmitted waveform is the baseband waveform multiplied by a square-wave at M times the symbol rate. The labels on the state transitions indicate the logical values of the data
sequence to be encoded. For example, a transition from state to is disallowed because the resulting transmission would have a phase inversion on a symbol boundary between a data-0 and a data-1.
Figure 10 shows Miller-modulated subcarrier sequences; the Miller sequence shall contain exactly two, four, or eight subcarrier cycles per bit, depending on the M value specified in the Query command that initiated the inventory round (see Table 4). The duty cycle of a 0 or 1 symbol, measured at the modulator output, shall be a minimum of 45% and a maximum of 55%, with a nominal value of 50%. Miller encoding has memory; consequently, the choice of Miller sequences in Figure 10 depends on prior transmissions. Miller signaling shall always end with a “dummy” data-1 bit at the end of a transmission, as shown in Figure 11.
Miller subcarrier preamble T=>R subcarrier signaling shall begin with one of the two preambles shown in Figure 12. The choice depends on the TRext value specified in the Query that initiated the inventory round, unless a Tag is replying to a command that uses a delayed or in-process reply (see [9]), in which case a Tag shall use the extended preamble regardless of TRext.
1.2.3. Tag supported Tari values and backscatter link rates Tags shall support all R=>T Tari values in the range of 6.25µs to 25µs, over all parameters allowed by [9].
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Background
21
Tags shall support the T=>R link frequencies and tolerances specified in Table 3 and the T=>R data rates specified in Table 4. The frequency-variation requirement in Table 3 includes both frequency drift and short-term frequency variation during Tag response to an Interrogator command. The Query command that initiates an inventory round specifies DR in Table 3 and M in Table 4; the preamble that precedes the Query specifies TRcal. BLF is computed using Equation 1. These four parameters together define the backscatter frequency, modulation type (FM0 or Miller), and T=>R data rate for the round.
Table 3: Tag-to-Interrogator link frequencies
[From [9]]
Table 4: Tag-to-Interrogator data rates
[From [9]]
1.3. Transmission Order
The transmission order for all R=>T and T=>R communications shall be most-significant bit (MSB) first.
Within each message, the most-significant word shall be transmitted first.
Within each word, the MSB shall be transmitted first.
1.4. CRC A CRC is a cyclic-redundancy check that a Tag uses to ensure the validity of certain R=>T commands, and an Interrogator uses to ensure the validity of certain backscattered T=>R replies. This protocol uses two CRC types: (i) a CRC-16, and (ii) a CRC-5. Annex F from [9] describes both CRC types.
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Background
22
1.1. Link Timing Figure 14 illustrates R=>T and T=>R link timing. The figure (not drawn to scale) defines Interrogator interactions with a Tag population. Tags and Interrogators shall meet all timing requirements specified in [9]. RTcal is defined in R=>T
preamble and frame-sync; is the T=>R link period . As
described before, an Interrogator shall use a fixed R=>T link rate for the duration of an inventory round; prior to changing the R=>T link rate an Interrogator shall transmit CW for a minimum of 8 RTcal. Figure 14 illustrates three types of Tag reply timing denoted inmediate, delayed, and in-process.
Figure 14: Link timing
[From [9]]
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Background
23
2. Logical interface The logical interface between an Interrogator and a Tag may be viewed as the lowest level in the data link layer of a layered network communication system. The logical interface defines Tag memory, flags, states, selection, inventory and access.
2.1. Sessions and inventoried flags Interrogators shall support and Tags shall provide 4 sessions (denoted S0, S1, S2, and S3). Tags shall participate in one and only one session during an inventory round. Two or more Interrogators can use sessions to independently inventory a common Tag population. The sessions concept is illustrated in Figure 15.
Figure 15: Session diagram
[From [9]]
A Tag shall maintain an independent inventoried flag for each of its four sessions. Each inventoried flag has two values, denoted A and B. At the beginning of each and every inventory round an Interrogator chooses to inventory either A or B Tags in one of the four sessions. Tags participating in an inventory round in one session shall neither use nor modify an inventoried flag for a different session. The inventoried flags are the only resource that a Tag provides separately and independently to a session; all other Tag resources are shared among sessions. After singulating a Tag an Interrogator may issue a command that causes the tag
to invert its inventoried flag for that session (i.e. or ). The following example illustrates how two Interrogators can use sessions and inventoried flags to independently and completely inventory a common Tag population, on a time-interleaved basis:
Interrogator #1 powers-on then, o It initiates an inventory round during which it singulates A Tags in
session S2 to B, o It powers off.
Interrogator #2 powers-on then,
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Background
24
o It initiates an inventory round during which it singulates B Tags in session S3 to A,
o It powers off. This process repeats until Interrogator #1 has placed all Tags in session S2 into B, after which it inventories the Tags in session S2 from B back to A. Similarly, Interrogator #2 places all Tags in session S3 into A, after which it inventories the Tags in session S3 from A back to B. By this multi-step procedure each Interrogator can independently inventory all Tags in its field, regardless of the initial state of their inventoried flags.
2.2. Selected flag A Tag shall implement a selected flag, SL, which an Interrogator may assert or deassert using a Select command. The Sel parameter in the Query command allows an Interrogator to inventory Tags that have SL either asserted or deasserted (i.e. SL or ~SL), or to ignore the flag and inventory Tags regardless of their SL value. SL is not associated with any particular session; SL may be used in any session, and is common to all sessions.
2.3. Tag states and slot counter A Tag shall implement the states: ready, arbitrate, reply, acknowledged, open, secured and killed; and slot counter shown in Figure 6.21 from [9].
2.4. Tag random or pseudo-random number generator A Tag shall implement a random or pseudo-random number generator (RNG). The RNG shall meet the following randomness criteria independent of the strength of the energizing RF field, the R=>T link rate, and the data stored in the Tag. Tags shall generate 16-bit random or pseudo-random numbers (RN16) using the RNG, and shall have the ability to extract Q-bit subsets from its RNG to preload the Tag‟s slot counter. Tag shall have the ability to temporarily store at least two RN16s while powered, to use, for example, as a handle and a 16-bit cover-code during password transactions. Probability of a single RN16: The probability that any RN16 drawn from the
RNG has value RN16 = j, for any j, shall be bounded by .
Probability of simultaneously identical sequences: For a Tag population of up to 10,000 Tags, the probability that any two or more Tags simultaneously generate the same sequence of RN16s shall be less than 0.1%, regardless of when the Tags are energized.
Probability of predicting an RN16: An RN16 drawn from a Tag‟s RNG 10ms
after the end of in Figure 4 shall not be predictable with a probability greater than 0.025% if the outcomes of prior draws from the RNG, performed under identical conditions, are known.
2.5. Managing Tag populations Interrogators manage Tag populations using three basics operators: Select, Inventory and Access. Each of these operations comprises multiple commands. The operations are defined as follows:
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Background
25
i. Select. Choosing a Tag population. A reader may use a Select command to select one or more Tags based on a value or values in Tag memory, and may use a Challenge command to challenge one or more
ii. Inventory. Identifying individual Tags. An interrogator begins an inventory
round by transmitting a Query command in one of four sessions. One or more Tags may reply. The Interrogator detects a single Tag reply and requests the Tag's EPC. Inventory comprises multiple commands.
iii. Access. Communicating with an identified Tag. The reader may perform a
core operation such as reading, writing, locking, or killing the Tag; a security-related operation such as authenticating the Tag; or a file-related operation such as opening a particular file in the Tag's user memory. Access comprises multiple commands.
2.6. Inventorying Tag populations The inventory command set includes Query, QueryAdjust, QueryRep, ACK, and NAK.
Interrogator and Tags shall implement the Query command shown in Table 5. Query initiates and specifies and inventory round. It includes the following fields:
DR (TRcal divide ratio) sets the T=>R link frequency.
M (cycles per symbol) sets the T=>R data rate and modulation format.
TRext chooses whether a tag prepends the T=>R preamble with a pilot tone. A Tag‟s reply to a command that uses a delayed or an in-process reply always uses an extended preamble regardless of the TRext value.
Sel chooses a session for the inventory round.
Target selects whether Tags whose inventoried flag is A or B participate in the inventory round. Tags may change their inventoried flags from A to B (or vice versa) as a result of being singulated.
Q sets the number of slots in the round.
Command DR M TRext Sel Session Target Q CRC
# of bits 4 1 2 1 2 2 1 4 5
descriptio
n
1000 0: DR=8
1: DR=64/3
00: M=1
01: M=2
10: M=4
11: M=8
0: No pilot
tone
1: Use
pilot tone
00: All
01: All
10: ~SL
11:SL
00: S0
01: S1
10: S2
11: S3
0: A
1: B
0-15 CRC-5
Table 5: Query command
Reply
# of bits 16 description RN16
Table 6: Tag reply to a Query command
Interrogator and Tags shall implement the QueryAdjust command shown in Table 7. QueryAdjust adjusts Q (i.e. the number of slots in an inventory round) without changing any other round parameters.
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Background
26
QueryAdjust includes the following fields:
Session corroborates the session number for the inventory round. If a Tag receives a QueryAdjust whose session number is different from the session number in the Query that initiated the round it shall ignore the command.
UpDn determines whether and how the Tag adjusts Q, as follows: o 110: Increment Q (i.e. Q = Q + 1). o 000: No change to Q. o 011: Decrement Q (i.e. Q = Q - 1).
Command Session UpDn
# of bits 4 2 3
description 1001 00: S0
01: S1
10: S2
11: S3
110: Q = Q + 1
000: No change to Q
011: Q = Q - 1
Table 7: QueryAdjust command
Reply
# of bits 16 description RN16
Table 8: Tag reply to a QueryAdjust command
Interrogator and Tags shall implement the QueryRep command shown in Table 9. QueryRep instructs Tags to decrement their slot counters and, if slot=0 after decrementing, to backscatter an RN16 to the Interrogator. QueryRep includes the following field:
Session corroborates the session number for the inventory round. If a Tag receives a QueryRep whose session number is different from the session number in the Query that initiated the round it shall ignore the command.
Command Session
# of bits 2 2 description 00 00: S0
01: S1
10: S2
11: S3
Table 9: QueryRep command
Reply
# of bits 16 description RN16
Table 10: Tag reply to a QueryRep command
Interrogator and Tags shall implement the ACK command shown in Table 11. An Interrogator sends an ACK to acknowledge a single Tag. ACK echoes the Tag‟s backscattered RN16.
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Background
27
Command RN # of bits 2 16 description 01 Echoed RN16 or handle
Table 11: ACK command
Reply
# of bits 21 to 33,328 description See Table 6.17 from [9]
Table 12: Tag reply to a successful ACK command
Interrogator and Tags shall implement the NAK command shown in Table 13. A Tag receives a NAK shall return to the arbitrate state without changing its inventoried flag, unless the Tag is in ready or killed, in which case it shall ignore the NAK and remain in its current state. A Tag shall not reply to a NAK.
Command # of bits 8
description 11000000
Table 13: NAK command
Query contains a slot-count parameter Q. Upon receiving a Query participating
Tags pick a random value in the range , inclusive, and load this value into their slot counter. Tags that pick a zero transition to the reply state and reply immediately. Tags that pick a nonzero value transition to the arbitrate state and await a QueryAdjust or QueryRep command. Assuming a single Tag replies, the Electronic Product Code (EPC) Query Process can be illustrated in Figure 16 and work as follows:
Figure 16: The EPC Query Process
In this way the first thing to look for was the tag to reader preamble followed by an inventory command. Normally after this step, as an acknowledgement the tag then backscatters the signal replying with a 16 bit random number (RN16). Once the reader has received the RN16 it responds with a frame sync and an
Reader Tag QUERY
RN16
ACK
EPC CRC-16
1.
2.
3.
4.
5.
PR
PT
FS
PT
PR: Preamble of Reader
PT: Preamble of Tag
FS: Frame-Sync
RN16: 16-Bit Random Number
PC
QREP FS
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Background
28
acknowledgement in the form of a standard command of two bits „01‟ and the RN16 used by the tag. This command allows the reader to focus on an individual tag as that RN16 should serve as a reasonably unique identifier and other tags receiving the incorrect RN16 will then ignore the subsequent communication.
3. Electronic Product Code (EPC) The EPC is a universal identifier that gives a unique identity to a specific physical object. We can see in Figure 17 that the code has different fields. The Header identifies the length, type, structure, version, and generation of the EPC. The EPC Manager Number is the entity responsible for maintaining the subsequent partitions. The Object Class identifies a class of objects and the Serial Number identifies the instance.
Figure 17: Basic format of an EPC
[From [18]]
4. Diversity Combining techniques One of the most powerful techniques to mitigate the effects of fading is to use diversity-combining of independently-fading signal paths. Diversity-combining relies on the fact that independent signal paths have a low probability of experiencing deep fading simultaneously. Hence, the idea is to send the same data over independent-fading paths. How can we achieve independent fading paths in a wireless system? There are several ways. One method is to use multiple transmit or receive antennas, known as antenna array, where the elements are separated in distance. This type of diversity is referred to as space diversity. Another method consists in frequency diversity. In this case, the independent paths are performed using uncorrelated frequency channels. However, frequency diversity could not be applied to combat multipath fading because all the channels are correlated. These independent paths are combined in such a way that the fading of the resultant signal is reduced. How can we combine these paths? For example, by selecting the antenna with the strongest signal, this is known as selection combining (SC). Other diversity techniques that have potential benefits are mentioned next. In maximal ratio combining (MRC), the branch signals are weighted and combined so as to yield in the highest instantaneous SNR possible with any linear combining technique. In equal gain combining (EGC) all of the weights have the same magnitude but an opposite phase to that of the signal in the respective branch. However, MRC or EGC diversity techniques require important modification in commercial readers. In terms of maximum SNR, the optimal combination method of multiple copies of the receive signal is maximal ratio combining:
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Background
29
∑ ( )
(3)
The complex signal at antenna i and the combined signal are denoted as and respectively, while denotes the noise power at antenna i, and is the total
number of receive antennas. The tag states are: the absorb state and the reflect state . The channel coefficient corresponds to the two-way reader-to-tag-reader channel, but not to the carrier interference. Its complex conjugate is denoted as
. As maximal ratio combining requires the knowledge of the channel coefficients and the noise power, channel estimation is required. Channel estimation The channel coefficients are concluded from the tag states and are estimated separately for each antenna i. The absorb state is estimated during ensured tag
absorb times, i.e. between a reader command and the tag response (time interval in the EPCglobal standard [9]). The temporal mean and the variance of the complex
receive signal during that interval are used as an estimate for the absorb state and the noise power respectively:
{ [ ]} (4)
{ [ ] }
{ [ ]} (5)
{ } denotes the averaged value over time period , and k is the sample index.
With the tag starting to backscatter the carrier, the receive signal moves away from the absorb state in the reader receivers baseband I/Q plane. During the period of the first bit of the preamble of the tag response , the tag reflect state is
estimated as the point at the largest distance from the tag absorb state in the I/Q plane:
{| [ ] |} (6)
As soon as both states on all antennas are estimated, we first subtract the carrier interference, which does not carry any information. This basically shifts the I/Q constellation of both antennas to the origin. Hence, each channel coefficient is reflected by the magnitude and phase of the shifted reflect state in the I/Q plane of each antenna:
(7)
It is important to note that the SNR on the various receive antennas may result from different receive signal powers or different noise levels in the individual receiver chains. A different receive signal strength is caused by different fading realizations on the various antennas. Distinct noise power levels can result from different transmitter / receiver decoupling schemes: If all receive branches are decoupled from the
transmitter by separated antennas, equal noise power can be expected, and thus
can be omitted in Equation 3. If however the transmitter and one receive branch share one single antenna and the decoupling is achieved via a circulator or directional coupler, the noise power in this receive branch may be significantly higher, as noise generated by the transmit power amplifier leaks into the receiver via the circulator. Realization After the estimation of the channel coefficients the various receive paths are combined according to Equation 3. The complex multiplications in this Equation are
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Background
30
split into phase shifts and multiplications of magnitudes. The phase shift rotates the constellation at each antenna to 0 degrees. Then, a threshold is set in the middle of the new, combined reflect and absorb states in order to discriminate optimally between them (according to a maximum likelihood detection).
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Implementation
31
III. Implementation In this section, we will explain in details all the process that was carried out.
Figure 18: Monitor system diagram [From [1]]
Our starting point will be the Gen2 RFID Listener from CGRAN [9], [11] and the
objective will be to compare its performance against the new implementation with two
receiver antennas (SIMO). For this purpose, we started studying the files given in the
mentioned project. The block diagram of this project is depicted in Figure 19.
Figure 19: Block diagram of the implemented RFID Listener
First, we analyzed those blocks, getting to know how they work. Our process had two
phases: in the first one we wanted the RFID Listener to work with only one antenna
and in the second one, the new system had two antennas and we will need to
implement a diversity combining technique.
We have a Python file with which we can run the RFID Listener from the terminal. As
USRP to_mag MF Reader CR Tag sink A
Hardware subsystem
Software subsystem
to_mag: Complex-to-magnitude MF: Matched filter A: Amplifier Reader: Reader-Monitor-cmd-gate CR: Clock Recovery
Tag: Tag-Monitor
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Implementation
32
we are using USRP N210, it was necessary to adapt the code because it was
prepared for older USRPs. We realized that the signal was not large enough before
the Reader-Monitor-cmd-gate so we decided to add an amplifying block. Although,
we needed to change the gain of that amplifier from time to time, because with minor
changes in the measurement setup, e.g. antenna direction, the needed gain changes
too. For future implementations, I would suggest to use an AGC (Automatic Gain
Control).
With the purpose of changing the behavior of the RFID Listener, there are two C++
files that we can modify: Reader-Monitor-cmd-gate and Tag-Monitor, one of them
affects to the reader and the other to the decoding of the tag.
Analyzing the bits from the R=>T messages, in particular the bits of the preamble of the Query, one gets the missing parameters like: BLF, M (Miller) that are need to run the RFID Listener. These bits were stored together with the decoded message in a log file in order to verify the command against the tables from 2.6 Inventorying Tag populations in the Background section. Depending on the length of each pulse, we decided between a „1‟ and „0‟, as it was explained in 1.1.6 R=>T preamble and frame-sync from the Background chapter, where they use a pivot to make a decision. For our particular case, the length of a data-0 resulted to be approximately 40 cycles and for a data-1, 80 cycles. So, in the Reader-Monitor-cmd-gate file we created a stream to store the sequence of bits and make a decision depending on the length of the pulse.
Picture 2: Changes to make a decision
This is valid only for the current measurement setup so if we wanted our code to be more general, we should use the pivot because it depends on the length of the RTcal. In Picture 3, the results are shown and we can check out with Table 5, Table 9, Table 11 and Table 13 that the commands correspond to their respective message.
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Implementation
33
Picture 3: Inventory commands
Once that we achieved correct bits, the next thing to do was looking deeper in the QUERY-message so we can get to know right values for the parameters that we mentioned before: M, DR, RTcal and TRcal. The value of M can be found in the sequence of bits of the Query command, we can see in the Picture 4 that in our scenario these two bits were „10‟ so comparing with
Table 5, and the Divide Ratio, .
Picture 4: Bits of the query command
In order to get to know RTcal and TRcal, a possibility was to store the length of the pulses in a new stream, concatenate them to the bits stream and printed them out in the log file.
Picture 5: Changes to print out
Moreover, we said before that RTcal is the result of a data-1 length plus a data-0 length, thus, . With
RTcal and Equation 2 we get:
The variable us_per_sample was set to 0.5, so we can express TRcal in .
We decided to take the lower extreme of the interval with some extra decimals, in order to have an integer value for the BLF, , so
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Implementation
34
These values for BLF and TRcal, can be checked in Table 3 .
Picture 6: Setting of the parameters
Once that everything was working fine in the Reader-Monitor-cmd-gate file, we noticed than we had ACK messages but the tag_log.out file was empty. Why? Because in the Python file there was an implementation to print out in a file the messages from the reader but not from the tag, so this was our first task. From the tag, we can have four different kinds of messages: CRC_OK, CRC_ERR, RN16_OK and RN16_ERR.
Picture 7: Implementation of Tag Messages
After those changes were made in the Python file the tag_log.out file was no longer empty but we only had CRC messages. That was because the RN16 messages were not implemented yet in the Tag-Monitor file. Depending on the message from the interrogator, the reply should be a CRC or a RN16, in order to establish this difference we had a variable d_rn16 that can take „true‟ or „false‟ as value, when it is true the message will be a RN16 type (OK or error) and when it is false, a CRC message. Finally, we took a decision for this variable d_rn16 and it was to check a typical commercial tags Header with standard EPC code. This typical value for the Header is „0011000000‟. These lines of code were written after the preamble was found.
Picture 8: Header of EPC
Therefor when the number of bits decoded is equal to the number of EPC bits and d_rn16 is false, the message that the tag will send it will be a CRC. There is a function defined with which you can check if the bits are correct or not, in case that the CRC is fine we will get the EPC of the tag in the tag_log.out file with its RSSI.
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Implementation
35
The Received Signal Strength Indicator (RSSI) is a measurement of the power of the signal backscattered by a tag and measured by the reader at its antenna ports. When the number of bits decoded is equal to sixteen and d_rn16 is true, the message that the tag will send it will be a RN16. In order to check if this message is correct, there is another variable called STATE.bit_error. We took an idea for this variable from a similar project found in CGRAN, STATE.bit_error is set to false when it is close to 0.5. The second phase of the process was to implement a diversity combining technique. We implemented successfully SC and proposed a possible solution for MRC. To implement SC technique, we needed to create a new block with two inputs, one output and a variable. We used gr_modtool2, a tool from GnuRadio to create the required block.
Figure 20: Block diagram of SC implementation
The signal processing in this block is simple; the block has to compare the two inputs Rx and Rx2 during a period of time (or number of samples) and output the strongest signal, as it is shown in Picture 9. After this block, all the processing is the same that we had with only one antenna as depicted in Figure 21.
Figure 21: Block diagram of SC implementation simplified
As we had limited time to finish this thesis, we could only propose a possible implementation for MRC but we did not have enough time to carry out all the process. In the Background chapter this technique is explained and channel estimation is needed. For that reason, we need to calculate the tag reflect state and the tag absorb state. Therefore, apart from the two inputs, we need two extra signals to know when we have to compute the absorb and reflect states, because the absorb state is evaluated during the period of time between a reader command and the tag response and the reflect state during the period of the first bit of the preamble of the tag response. In Figure 22, it is shown a possible block diagram for this proposed technique.
2 Out-of-tree modules from [12]
RX2
RX
sink
USRP to_mag
MF Reader CR Tag SC
USRP to_mag
RX2
RX USRP to_mag
Gen2 RFID Listener
USRP to_mag
SC
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Implementation
36
Picture 9: Signal processing of SC block
Figure 22: Possible block diagram for MRC
RX
RX2
USRP
RX
RXS
to_mag MF A Reader CR Tag sink
MRC
to_mag MF A Reader CR Tag sink
Reader->tag
Preamble found
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Experimental Results
37
IV. Experimental Results This section presents some preliminary experiments performed to test the correct operation of the listener implementation. The experiment was conducted in the laboratory of the first floor of the BB Building. The RFID deployment consist of one Speedway Reader3 equipped with a circular antenna4; two USRPs N210 connected to two antennas that were positioned on a poster board and one tag, as it can be seen in Picture 10. The RFID Listener was used on a general purpose PC (Intel Core I5 processor 430M @ 2.26GHz, 3MB L3 cache). The detailed topology used is described in Figure 23. The communication took place between Speedway and the Tag, the Listener only observes this communication.
Picture 10: RFID deployment
Figure 23: Topology used for the experiment
3 More information about the Speedway Reader can be found in
http://www.impinj.com/products/speedway/ 4 More information about the circular antenna can be found in http://www.meshedsystems.com/rfid-
komponenten/uhf-rfid-antennen/uhf-rfid-antennen-mti-wireless/index.php
Circular antenna
Speedway Reader
Tag USRP N210
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Experimental Results
38
According to the processing power limitations of the laptop that we had, we decided to launch the script first with only one antenna (Rx, then Rx2) and after with both, we run the script in which we implemented SC. For the experiment we let the reader and listener active for 2 minutes and record the following counters:
# of ACKs issued by the reader.
# of successful EPC readings by the listener.
# of erroneous EPC readings by the listener due to CRC
errors.
# of EPC messages missed by the listener.
It holds that . Note that was not
measured by the listener in real-time, we calculated it according to the previous equation. In Table 14, Table 15 and Table 16 are depicted the measures of these counters corresponding to Rx, Rx2 and SC.
Rx
0 cm 1910 244 1092 574 10 cm 2089 640 1116 333 20 cm 1770 93 452 1225 30 cm 1770 93 452 1225 40 cm 1960 1262 593 105 50 cm 2099 208 1037 854 60 cm 2274 5 78 2191
Table 14: , , and for Rx
Rx2
0 cm 2090 1664 247 179 10 cm 296 106 29 161 20 cm 1900 954 666 280 30 cm 2225 80 560 1585 40 cm 1998 1325 593 80 50 cm 2247 68 718 1461 60 cm 1613 81 222 1310
Table 15: , , and for Rx2
SC
0 cm 1997 342 975 680 10 cm 2130 566 795 769 20 cm 1896 1223 307 366 30 cm 2114 1321 501 292 40 cm 2146 1213 589 344 50 cm 2435 798 1197 440 60 cm 1713 15 128 1570
Table 16: , , and for SC
We calculated the Listener Success Ratio (L-SR), defined as . We also
calculate separately the percentage of EPC messages decoded by the listener due to
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Experimental Results
39
CRC failure ( ) and the percentage of missed EPC messages
( ).
In Table 17, Table 18 and Table 19 are shown the values that were calculated for the counters obtained according to the previous formulas.
Rx L-SR (%) CRC Error Ratio (%) CRC Miss Ratio (%)
0 cm 12,7749 57,1728 30,0523 10 cm 30,6367 53,4227 15,9406 20 cm 72,3858 18,6294 8,9848 30 cm 5,2542 25,5367 69,2091 40 cm 64,3878 30,2551 5,3571 50 cm 9,9095 49,4045 40,686 60 cm 0,2199 3,4301 96,35
Table 17: L-SR, CRC Error Ratio and CRC Miss Ratio for Rx
Rx2 L-SR (%) CRC Error Ratio (%) CRC Miss Ratio (%)
0 cm 79,6172 11,8182 8,5646 10 cm 35,8108 9,7973 54,3919 20 cm 50,2105 35,0526 14,7369 30 cm 3,5955 25,1685 71,236 40 cm 66,3163 29,6797 4,004 50 cm 3,0263 31,9537 65,02 60 cm 5,0217 13,7632 81,2151
Table 18: L-SR, CRC Error Ratio and CRC Miss Ratio for Rx2
SC L-SR (%) CRC Error Ratio (%) CRC Miss Ratio (%)
0 cm 17,1257 48,8232 34,0511 10 cm 26,5728 37,3239 36,1033 20 cm 64,5042 16,192 19,3038 30 cm 62,4882 23,6991 13,8127 40 cm 56,5238 27,4464 16,0298 50 cm 32,7721 49,1581 18,0698 60 cm 0,8757 7,4723 91,652
Table 19: L-SR, CRC Error Ratio and CRC Miss Ratio for SC
The performance achieved for the RFID Listener is shown in Figure 24, Figure 26, Figure 27 and Figure 27. We observe that the L-SR is not as high as we have read in other papers, for example in [2] but there is also a percentage of messages that are tagged as error and they can be correct. In Figure 27 the Success Ratio of the Listener is represented for the three different simulations. We can observe that in the range between 30 and 50 cm the behavior of both Rx and Rx2 is the same. The best performance is achieved by the second antenna, which was positioned in front of the tag, at 0 cm. We expected the L-SR with SC to behave either as Rx or Rx2, but we found out a different behavior. An explanation for this can possibly be that the simulations were not carried out simultaneously. They were performed at different times due to the characteristic of the laptop, which was not able to process at the same time. Also, the SC curve is less steep; this could be a positive thing because the behavior is more constant than the rest.
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Experimental Results
40
Figure 24: Performance achieved for the RFID Listener. Rx
Figure 25: Performance achieved for the RFID Listener. Rx2
Figure 26: Performance achieved for the RFID Listener. SC
0
10
20
30
40
50
60
70
80
90
100
0 10 20 30 40 50 60
%
Distance (cm)
L - SR
CRC Error Ratio
CRC Miss Ratio
0
10
20
30
40
50
60
70
80
90
100
0 10 20 30 40 50 60
%
Distance (cm)
L - SR
CRC Error Ratio
CRC Miss Ratio
0
10
20
30
40
50
60
70
80
90
100
0 10 20 30 40 50 60
%
Distance (cm)
L - SR
CRC Error Ratio
CRC Miss Ratio
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Experimental Results
41
Figure 27: Listener-Success Ratio
0
10
20
30
40
50
60
70
80
90
100
0 10 20 30 40 50 60
%
Distance (cm)
Rx
Rx2
SC
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Summary and Conclusion
42
V. Summary and Conclusion I would like to conclude quoting some words of Steven Johnson from a TED Talk: Where good ideas come from5. “We have this rich vocabulary to describe a moment of inspiration: Flash, Stroke, Eureka! People tend to think that an idea is a simple thing, it is something that often happens in a wonderful illuminating moment”. This perception is wrong. “An idea is a network on the most elemental level. I mean this is what is happening inside your brain. An idea, a new idea is a network of neurons firing in sync with each other inside your brain. It is a new configuration that has never formed before.” I hope I have started an idea with the project that will keep growing. Ideas have very long incubation period, they are like “slow hunch”. Favorable space and environment contribute to them. In my case it was the laboratory of this department with Marc Hoffmann, my tutor, and the rest of the person that I met in the laboratory. In this way, we have been able to reach three achievements:
1. Fully adapt the project that we took from CGRAN to run in the laboratory. 2. Learn how to create a new block with gr_modtool and be able to import it from
a python file. 3. Implement a DCT, designed a SC block and have some results. Proposed a
possible implementation for MRC. The next step for this project could be to improve the performance of this SC technique. Also, it could be possible to follow the advices given to implement MRC. This document will be submitted with CC (BY, NC, SA) to the University of Duisburg-Essen and the University of Granada. It will also be available in slideshare6.
5 http://www.ted.com/talks/steven_johnson_where_good_ideas_come_from
6 http://www.slideshare.net/amejs
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio References
43
References
[1] M. Buettner and D. Wetherall. A “Gen 2” RFID Monitor Based on the USRP. ACM SIGCOMM Computer Communication Review, vol. 40, issue 3, pp 41-47, July 2010.
[2] D. de Donno, F. Ricciato, L. Catarinucci, A. Coluccia, and L. Tarricone. Challenge: Towards Distributed RFID Sensing with Software-Defined Radio. ACM 978-1-4503-0181-7/10/09, pp 97-110, September 2010.
[3] M. Buettner and D. Wetherall. A Flexible Software Radio Transceiver for UHF RFID Experimentation. UW TR: UW-CSE-09-10-02.
[4] A. Lazaro, D. Girbau, and R. Villarino. Effects of Interferences in UHF RFID
Systems. Progress In Electromagnetics Research, PIER 98, pp 425-443, 2009.
[5] C. Angerer, R. Langwieser, G. Maier, and M. Rupp. Maximal Ratio Combining Receivers for Dual Antenna RFID Readers. IEEE MTT-S International Microwave Workshop on Wireless Sensing, Local Positioning, and RFID, 2009.
[6] J. Kaitovic, R. Langwieser, M. Rupp. RFID Reader with Multi Antenna Physical Layer Collision Recovery Receivers, 2011.
[7] R. Langwieser, C. Angerer, A. L. Scholtz. A UHF Frontend for MIMO Applications
in RFID, 2010.
[8] C. Angerer, R. Langwieser, G. Maier, and M. Rupp. Experimental Performance Evaluation of Dual Antenna Diversity Receivers for RFID Readers. EURASIP Workshop on RFID Technology, September 2010.
[9] “EPCglobal specification for RFID air interface.” EPC Radio Frequency Identity Protocols. Class-1 Generation-2 UHF RFID Protocol for Communication at 860 MHz-960 MHz version 1.0.9, January 2005.
[10] The Comprehensive GNU Radio Archive Network (CGRAN). https://cgran.org [11] Michael Buettner. Gen2 RFID Reader project website.
https://cgran.org/wiki/Gen2 [12] GNU Radio. http://gnuradio.org [13] Ettus Research LLC. http://www.ettus.com/
[14] ETSI. EN 302 208 RFID standard. http://www.etsi.org
[15] D. De Donno, F. Ricciato, L. Catarinucci, and L. Tarricone, “Design and
Application of a Software-Defined Listener for UHF RFID Systems,” 2011 IEEE
MTT-S International Microwave Symposium Digest, pp. 1-4, Baltimora, MD, USA,
June 2011.
[16] Technology Solutions (UK) Ltd. http://www.tsl.uk.com/
[17] C. Bolan, “Spoofing Attack Against an EPC Class One RFID System”,
December 2009.
[18] EPC-RFID INFO. http://www.epc-rfid.info/
[19] Youtube: The Big Bang Theory - RFID tags
https://www.youtube.com/watch?v=m5pTKqKaElA
[20] TED Talk, Steven Johnson: Where good ideas come from
http://www.ted.com/talks/steven_johnson_where_good_ideas_come_from
[21] Slideshare, Amelia Jiménez Sánchez http://www.slideshare.net/amejs
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
44
Annex
1. Gen2 RFID Listener #!/usr/bin/env python
# coding: utf-8
'''
###########################################################################
###########################################################################
#########
GEN2 RFID LISTENER v.2
This is an improvement version of the RFID Listener previously released.
The main modifications we introduced concern matched filtering, clock
recovery and Tag ID decoding.
###########################################################################
###########################################################################
#########
EXECUTION INFOs
sudo PYTHONPATH=/usr/local/lib/python2.6/dist-packages/ GR_SCHEDULER=TPB
nice -n -20 ./Gen2_RFID_Listener_v2.py -f freq
- /usr/local/lib/python2.6/dist-packages/ --> substitute with your python
installation directory
- nice -n -20 --> high priority for the process
- GR_SCHEDULER=TPB --> GNUradio default Thread-Per-
Block scheduler
###########################################################################
###########################################################################
#########
'''
from gnuradio import gr, gru, window, listener
from gnuradio import uhd
from gnuradio import eng_notation
from gnuradio.gr import firdes
#from gnuradio.blks2impl import psk
from gnuradio.eng_option import eng_option
from string import split
from string import strip
from string import atoi
from optparse import OptionParser
import time
import os
import sys
import math
from gnuradio import blocks
'''
SETTINGS IMPORTANT PARAMETERS
In order to detect the preamble and correctly decode the messages
transmitted by the tag some preliminary considerations must be taken into
account. According to the Gen2 standard the reader chooses the up-link
parameters and communicates them to the tags using the opening symbols of
each packet (reader’s commands preamble). For this reason, decoding
reader commands is required to access the up-link parameters and best tune-
up in real-time both the "matched filter" and the “Tag Decoder― block
(ref. Figure 7 of the Mobicom 2010 paper). Since this new Listener is
optimized for Tag deconding instead of Reader deconding, we suggest to run
first the previous version as to obtain the BLF and the number of Miller
subcarrier your reader use. Then you can set accordingly the parameters
listed below.
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
45
We suggest to try this code together with the Buettner's reader you find on
CGRAN. This permits best tuning of all parameters. Use the following code
if you run the listener and the Buettner's reader on two separate USRP.
Otherwise, if you want listener and reader on the same USRP/PC run the
"Gen2_RFID_Reader_Listener.py" code you find in this project folder.
'''
up_link_freq = 320 # BLF your reader communicates to tags -->
value used by Buettner's reader )41.667( )320( )33(
miller = 4 # Number of Miller sub-carriers your reader
communicates to tags )8(
rtcal = 60 # Reader-To-Tag calibration (in microsec) of
your reader --> value used by Buettner's reader )72( )60=120/2(
dec_rate = 50 # decimation factor at USRP )100(
sw_dec = 1 # software decimation
samples_per_pulse = 6 # samples per pulse of the tag signal. It's
calculated according as (1/(2*up_link_freq*1000))/((dec_rate*sw_dec)/100e6)
)6( )30(
'''
With the previous defined decimation you can capture 2 MHz of band centered
around the tuning frequency of the USRP. So if you choose 866.5 MHz as
center frequency you can capture the entire UHF RFID band in Europe. If you
are in US, since RFID occupies about 25 MHz of band, with such
configuration you'll capture tags when the reader hops to a frequency that
falls in the 2 MHz band you have set.
'''
# Block connections
class my_top_block(gr.top_block):
def __init__(self, rx, matched_filter, reader_monitor_cmd_gate, cr,
tag_monitor):
gr.top_block.__init__(self)
# ASK/PSK demodulator
to_mag = gr.complex_to_mag()
amplifier = blocks.multiply_const_vff((1000000, ))
# Null sink for terminating the graph
null_sink = gr.null_sink(gr.sizeof_float*1)
# Enable real-time scheduling
r = gr.enable_realtime_scheduling()
if r != gr.RT_OK:
print "Warning: failed to enable realtime scheduling"
# Create flow-graph
self.connect(rx, to_mag, matched_filter, amplifier,
reader_monitor_cmd_gate, cr, tag_monitor, null_sink)
# File sink for monitoring block output
file_sink = gr.file_sink(gr.sizeof_float, "matched_filter.out") #
Change to "gr.sizeof_gr_complex" if "block_x" is "rx" ;; gr.sizeof_float for other blocks
self.connect(amplifier, file_sink) ## rx.out -> rx.dat
# Main program
def main():
# Parsing command line parameter
parser = OptionParser (option_class=eng_option)
parser.add_option("-f", "--freq", type="eng_float", dest="freq",
default=865.7, help="set USRP center frequency (provide frequency in MHz)")
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
46
(options, args) = parser.parse_args()
which_usrp = 0
fpga = "std_2rxhb_2tx.rbf"
freq = options.freq # Default value = 866.5 --> center frequency of 2
MHz European RFID Band
freq = freq*1e6
rxgain = 10
us_per_sample = float (1 / (100.0 / (dec_rate*sw_dec))) #USRP N210 ->
100 MS/s
samp_freq = (100 / dec_rate) * 1e6 #Sample frequency is defined here
# LISTENER HARDWARE SUB-SYSTEM (USRP )
rx = uhd.usrp_source(
device_addr="addr=192.168.1.212",
stream_args=uhd.stream_args(
cpu_format="fc32",
channels=range(1),
),
)
rx.set_samp_rate(samp_freq)
rx.set_center_freq(freq, 0)
rx.set_gain(rxgain, 0)
rx.set_antenna("TX/RX", 0)
print ""
print "*************************************************************"
print "****************** Gen2 RFID Listener ***********************"
print "*************************************************************\n"
print "USRP center frequency: %s MHz" % str(freq/1e6)
print "Sampling Frequency: "+ str(samp_freq/1e6) + " MHz" + " ---
microsec. per Sample: " + str(us_per_sample)
# LISTENER SOFTWARE SUB-SYSTEM (GNU-Radio flow-graph)
# MATCHED FILTER (MF)
num_taps = int(100000 / (dec_rate * up_link_freq * 4))
taps = []
for i in range(0,int(num_taps)):
taps.append(float(1))
matched_filter = gr.fir_filter_fff(sw_dec, taps)
# Tag Decoding Block --> the boolean value in input indicate if real-
time output of EPC is enabled or not
tag_monitor = listener.tag_monitor(True, int(miller),
float(up_link_freq))
# Clock recovery
cr = listener.clock_recovery(samples_per_pulse, us_per_sample,
tag_monitor.STATE_PTR, float(up_link_freq))
# Reader Decoding Block and Command gate--> the boolean value indicate
if real-time output of reader commands is enabled or not
reader_monitor_cmd_gate = listener.reader_monitor_cmd_gate(False,
us_per_sample, tag_monitor.STATE_PTR, float(up_link_freq), float(rtcal))
# Create GNU-Radio flow-graph
tb = my_top_block(rx, matched_filter, reader_monitor_cmd_gate, cr,
tag_monitor)
# END LISTENER SOFTWARE SUB-SYSTEM (GNU-Radio flow-graph)
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
47
# Start application
tb.start()
while 1:
c = raw_input("\nPRESS 'q' for STOPPING capture\n")
if c == "Q" or c == "q":
break
# Stop application
tb.stop()
# GETTING LOGs
log_READER = reader_monitor_cmd_gate.get_reader_log()
log_TAG = tag_monitor.get_tag_log()
print "Listener collected %s Entries for READER LOG" %
str(log_READER.count())
print "Listener collected %s Entries for TAG LOG" %
str(log_TAG.count())
c = raw_input("PRESS 'f' to write LOG files, 'q' to QUIT\n")
if c == "q":
print "\n Shutting Down...\n"
return
if c == "f":
print "\n Writing READER LOG on file...\n\n"
reader_file = open("reader_log.out","w")
reader_file.close()
reader_file = open("reader_log.out","a")
i = log_READER.count()
for k in range(0, i):
decode_reader_log_msg(log_READER.delete_head_nowait(),reader_file)
k = k + 1
reader_file.close()
print "\n Writing TAG LOG on file...\n"
tag_file = open("tag_log.out","w")
tag_file.close()
tag_file = open("tag_log.out","a")
i = log_TAG.count();
for k in range(0, i):
decode_tag_log_msg(log_TAG.delete_head_nowait(),tag_file)
k = k + 1
tag_file.close()
# Decode Reader Messages
def decode_reader_log_msg(msg,reader_file):
LOG_QUERY, LOG_QREP, LOG_ACK, LOG_NAK, LOG_PWR_UP, LOG_ERROR,
LOG_OKAY = range(7)
if msg.type() == LOG_QUERY:
fields = split(strip(msg.to_string()), " ")
reader_file.write(fields[-1] + "\tQUERY" + "\t\t" +
fields[0] + "\n");
if msg.type() == LOG_QREP:
fields = split(strip(msg.to_string()), " ")
reader_file.write(fields[-1] + "\tQREP" + "\t\t" + fields[0]
+ "\n");
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
48
if msg.type() == LOG_ACK:
fields = split(strip(msg.to_string()), " ")
reader_file.write(fields[-1] + "\tACK" + "\t\t" + fields[0]
+ "\n");
if msg.type() == LOG_NAK:
fields = split(strip(msg.to_string()), " ")
reader_file.write(fields[-1] + "\tNAK" + "\t\t" + fields[0]
+ "\n");
if msg.type() == LOG_PWR_UP:
fields = split(strip(msg.to_string()), " ")
reader_file.write(fields[-1] + "\tPOWER UP\n");
# Decode Tag Messages
def decode_tag_log_msg(msg,tag_file):
LOG_RN16, LOG_EPC, LOG_ERROR, LOG_OKAY = range(4)
if msg.type() == LOG_EPC:
fields = split(strip(msg.to_string()), " ")
epc = fields[0].split(",")[0]
rssi = strip(fields[0].split(",")[1])
epc = epc[16:112]
tmp = atoi(epc,2)
if msg.arg2() == LOG_ERROR:
tag_file.write("%s\tCRC_ERR\t\tEPC: %024X\tRSSI:
%s\n" % (fields[-1],tmp,rssi));
else:
tag_file.write("%s\tCRC_OK\t\tEPC: %024X\tRSSI:
%s\n" % (fields[-1],tmp,rssi));
if msg.type() == LOG_RN16:
fields = split(strip(msg.to_string()), " ")
rn16 = fields[0].split(",")[0]
rssi = strip(fields[0].split(",")[1])
if msg.arg2() == LOG_ERROR:
tag_file.write("%s\tRN16_ERR\tRN16: %s\t\tRSSI:
%s\n" % (fields[-1],rn16,rssi));
else:
tag_file.write("%s\tRN16_OK\t\tRN16: %s\t\tRSSI:
%s\n" % (fields[-1],rn16,rssi));
# Gen2 RFID Listener v.2
if __name__ == '__main__':
main ()
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
49
2. Gen2 RFID Listener with SC #!/usr/bin/env python
# coding: utf-8
'''
###########################################################################
###########################################################################
#########
GEN2 RFID LISTENER v.2
This is an improvement version of the RFID Listener previously released.
The main modifications we introduced concern matched filtering, clock
recovery and Tag ID decoding.
###########################################################################
###########################################################################
#########
EXECUTION INFOs
sudo PYTHONPATH=/usr/local/lib/python2.6/dist-packages/ GR_SCHEDULER=TPB
nice -n -20 ./Gen2_RFID_Listener_v2.py -f freq
- /usr/local/lib/python2.6/dist-packages/ --> substitute with your python
installation directory
- nice -n -20 --> high priority for the process
- GR_SCHEDULER=TPB --> GNUradio default Thread-Per-
Block scheduler
###########################################################################
###########################################################################
#########
'''
from gnuradio import gr, gru, window, listener
from gnuradio import uhd
from gnuradio import eng_notation
from gnuradio.gr import firdes
#from gnuradio.blks2impl import psk
from gnuradio.eng_option import eng_option
from string import split
from string import strip
from string import atoi
from optparse import OptionParser
import time
import os
import sys
import math
from gnuradio import blocks
import amemodule
'''
SETTINGS IMPORTANT PARAMETERS
In order to detect the preamble and correctly decode the messages
transmitted by the tag some preliminary considerations must be taken into
account. According to the Gen2 standard the reader chooses the up-link
parameters and communicates them to the tags using the opening symbols of
each packet (reader’s commands preamble). For this reason, decoding
reader commands is required to access the up-link parameters and best tune-
up in real-time both the "matched filter" and the “Tag Decoder― block
(ref. Figure 7 of the Mobicom 2010 paper). Since this new Listener is
optimized for Tag deconding instead of Reader deconding, we suggest to run
first the previous version as to obtain the BLF and the number of Miller
subcarrier your reader use. Then you can set accordingly the parameters
listed below.
We suggest to try this code together with the Buettner's reader you find on
CGRAN. This permits best tuning of all parameters. Use the following code
if you run the listener and the Buettner's reader on two separate USRP.
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
50
Otherwise, if you want listener and reader on the same USRP/PC run the
"Gen2_RFID_Reader_Listener.py" code you find in this project folder.
'''
up_link_freq = 320 # BLF your reader communicates to tags -->
value used by Buettner's reader )41.667( )320( )33(
miller = 4 # Number of Miller sub-carriers your reader
communicates to tags )8(
rtcal = 60 # Reader-To-Tag calibration (in microsec) of
your reader --> value used by Buettner's reader )72( )60=120/2(
dec_rate = 50 # decimation factor at USRP )100(
sw_dec = 1 # software decimation
samples_per_pulse = 6 # samples per pulse of the tag signal. It's
calculated according as (1/(2*up_link_freq*1000))/((dec_rate*sw_dec)/100e6)
)6( )30(
'''
With the previous defined decimation you can capture 2 MHz of band centered
around the tuning frequency of the USRP. So if you choose 866.5 MHz as
center frequency you can capture the entire UHF RFID band in Europe. If you
are in US, since RFID occupies about 25 MHz of band, with such
configuration you'll capture tags when the reader hops to a frequency that
falls in the 2 MHz band you have set.
'''
# Block connections
class my_top_block(gr.top_block):
def __init__(self, rx, rx2, scomb, matched_filter,
reader_monitor_cmd_gate, cr, tag_monitor):
gr.top_block.__init__(self)
# ASK/PSK demodulator
to_mag = gr.complex_to_mag()
to_mag2 = gr.complex_to_mag()
# Amplifier
amplifier = blocks.multiply_const_vff((1000000, ))
# Null sink for terminating the graph
null_sink = gr.null_sink(gr.sizeof_float*1)
# Enable real-time scheduling
r = gr.enable_realtime_scheduling()
if r != gr.RT_OK:
print "Warning: failed to enable realtime scheduling"
# Create flow-graph
self.connect(rx, to_mag, (scomb,0))
self.connect(rx2, to_mag2, (scomb,1))
self.connect(scomb, matched_filter, amplifier,
reader_monitor_cmd_gate, cr, tag_monitor, null_sink)
# Main program
def main():
# Parsing command line parameter
parser = OptionParser (option_class=eng_option)
parser.add_option("-f", "--freq", type="eng_float", dest="freq",
default=865.7, help="set USRP center frequency (provide frequency in MHz)")
(options, args) = parser.parse_args()
which_usrp = 0
fpga = "std_2rxhb_2tx.rbf"
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
51
freq = options.freq # Default value = 866.5 --> center frequency of 2
MHz European RFID Band
freq = freq*1e6
rxgain = 10
us_per_sample = float (1 / (100.0 / (dec_rate*sw_dec))) #USRP N210 ->
100 MS/s
samp_freq = (100 / dec_rate) * 1e6 #Sample frequency is defined here
# LISTENER HARDWARE SUB-SYSTEM (USRP )
rx = uhd.usrp_source(
device_addr="addr=192.168.1.211",
stream_args=uhd.stream_args(
cpu_format="fc32",
channels=range(1),
),
)
rx.set_samp_rate(samp_freq)
rx.set_center_freq(freq, 0)
rx.set_gain(rxgain, 0)
rx.set_antenna("TX/RX", 0)
rx2 = uhd.usrp_source(
device_addr="addr=192.168.1.213",
stream_args=uhd.stream_args(
cpu_format="fc32",
channels=range(1),
),
)
rx2.set_samp_rate(samp_freq)
rx2.set_center_freq(freq, 0)
rx2.set_gain(rxgain, 0)
rx2.set_antenna("TX/RX", 0)
print ""
print "*************************************************************"
print "****************** Gen2 RFID Listener ***********************"
print "*************************************************************\n"
print "USRP center frequency: %s MHz" % str(freq/1e6)
print "Sampling Frequency: "+ str(samp_freq/1e6) + " MHz" + " ---
microsec. per Sample: " + str(us_per_sample)
# LISTENER SOFTWARE SUB-SYSTEM (GNU-Radio flow-graph)
# MATCHED FILTER (MF)
num_taps = int(100000 / (dec_rate * up_link_freq * 4))
taps = []
for i in range(0,int(num_taps)):
taps.append(float(1))
matched_filter = gr.fir_filter_fff(sw_dec, taps)
# Tag Decoding Block --> the boolean value in input indicate if real-
time output of EPC is enabled or not
tag_monitor = listener.tag_monitor(True, int(miller),
float(up_link_freq))
# Clock recovery
cr = listener.clock_recovery(samples_per_pulse, us_per_sample,
tag_monitor.STATE_PTR, float(up_link_freq))
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
52
# Reader Decoding Block and Command gate--> the boolean value indicate
if real-time output of reader commands is enabled or not
reader_monitor_cmd_gate = listener.reader_monitor_cmd_gate(False,
us_per_sample, tag_monitor.STATE_PTR, float(up_link_freq), float(rtcal))
# Selection Combining
scomb = amemodule.select_ff(200)
# Create GNU-Radio flow-graph
tb = my_top_block(rx, rx2, scomb, matched_filter,
reader_monitor_cmd_gate, cr, tag_monitor)
# END LISTENER SOFTWARE SUB-SYSTEM (GNU-Radio flow-graph)
# Start application
tb.start()
while 1:
c = raw_input("\nPRESS 'q' for STOPPING capture\n")
if c == "Q" or c == "q":
break
# Stop application
tb.stop()
# GETTING LOGs
log_READER = reader_monitor_cmd_gate.get_reader_log()
log_TAG = tag_monitor.get_tag_log()
print "Listener collected %s Entries for READER LOG" %
str(log_READER.count())
print "Listener collected %s Entries for TAG LOG" %
str(log_TAG.count())
c = raw_input("PRESS 'f' to write LOG files, 'q' to QUIT\n")
if c == "q":
print "\n Shutting Down...\n"
return
if c == "f":
print "\n Writing READER LOG on file...\n\n"
reader_file = open("reader_log.out","w")
reader_file.close()
reader_file = open("reader_log.out","a")
i = log_READER.count()
for k in range(0, i):
decode_reader_log_msg(log_READER.delete_head_nowait(),reader_file)
k = k + 1
reader_file.close()
print "\n Writing TAG LOG on file...\n"
tag_file = open("tag_log.out","w")
tag_file.close()
tag_file = open("tag_log.out","a")
i = log_TAG.count();
for k in range(0, i):
decode_tag_log_msg(log_TAG.delete_head_nowait(),tag_file)
k = k + 1
tag_file.close()
# Decode Reader Messages
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
53
def decode_reader_log_msg(msg,reader_file):
LOG_QUERY, LOG_QREP, LOG_ACK, LOG_NAK, LOG_PWR_UP, LOG_ERROR,
LOG_OKAY = range(7)
if msg.type() == LOG_QUERY:
fields = split(strip(msg.to_string()), " ")
reader_file.write(fields[-1] + "\tQUERY" + "\t\t" +
fields[0] + "\n");
if msg.type() == LOG_QREP:
fields = split(strip(msg.to_string()), " ")
reader_file.write(fields[-1] + "\tQREP" + "\t\t" + fields[0]
+ "\n");
if msg.type() == LOG_ACK:
fields = split(strip(msg.to_string()), " ")
reader_file.write(fields[-1] + "\tACK" + "\t\t" + fields[0]
+ "\n");
if msg.type() == LOG_NAK:
fields = split(strip(msg.to_string()), " ")
reader_file.write(fields[-1] + "\tNAK" + "\t\t" + fields[0]
+ "\n");
if msg.type() == LOG_PWR_UP:
fields = split(strip(msg.to_string()), " ")
reader_file.write(fields[-1] + "\tPOWER UP\n");
# Decode Tag Messages
def decode_tag_log_msg(msg,tag_file):
LOG_RN16, LOG_EPC, LOG_ERROR, LOG_OKAY = range(4)
if msg.type() == LOG_EPC:
fields = split(strip(msg.to_string()), " ")
epc = fields[0].split(",")[0]
rssi = strip(fields[0].split(",")[1])
epc = epc[16:112]
tmp = atoi(epc,2)
if msg.arg2() == LOG_ERROR:
tag_file.write("%s\tCRC_ERR\t\tEPC: %024X\tRSSI:
%s\n" % (fields[-1],tmp,rssi));
else:
tag_file.write("%s\tCRC_OK\t\tEPC: %024X\tRSSI:
%s\n" % (fields[-1],tmp,rssi));
if msg.type() == LOG_RN16:
fields = split(strip(msg.to_string()), " ")
rn16 = fields[0].split(",")[0]
rssi = strip(fields[0].split(",")[1])
if msg.arg2() == LOG_ERROR:
tag_file.write("%s\tRN16_ERR\tRN16: %s\t\tRSSI:
%s\n" % (fields[-1],rn16,rssi));
else:
tag_file.write("%s\tRN16_OK\t\tRN16: %s\t\tRSSI:
%s\n" % (fields[-1],rn16,rssi));
# Gen2 RFID Listener v.2
if __name__ == '__main__':
main ()
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
54
3. Listener Reader Monitor Cmd Gate
/* -*- c++ -*- */
/*
* Copyright 2004,2006 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* GNU Radio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <listener_reader_monitor_cmd_gate.h>
#include <gr_io_signature.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <float.h>
#include <math.h>
#include "listener_vars.h"
// using namespace std;
// Calculate maximum
inline float max(float a, float b)
{
return a >= b ? a : b;
}
/* Print vector
void Print(int v[], int size)
{
for (int j = 0; j < size; j++) printf("%d ",v[j]);
}
// Fill vector with zeros
void FillNullVector(int v[], int size)
{
for(int k = 0; k < size; k++) v[k] = 8;
}
// New vector without zeros, returns the number of elements of the vector
int WithoutZeros(int v1[], int v2[],int size)
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
55
{
int aux=0;
for (int i=0; i<size; i++){
if (v1[i]!=0) {
v2[aux]=v1[i];
aux++;
}
}
return aux;
}*/
/////////////////////////////////////////////////////////////////
// INITIAL SETUP
////////////////////////////////////////////////////////////////
listener_reader_monitor_cmd_gate_sptr
listener_make_reader_monitor_cmd_gate (bool real_time, float us_per_sample,
state * reader_state, float blf, float rtcal)
{
return listener_reader_monitor_cmd_gate_sptr (new
listener_reader_monitor_cmd_gate (real_time, us_per_sample, reader_state,
blf, rtcal));
}
listener_reader_monitor_cmd_gate::listener_reader_monitor_cmd_gate(bool
real_time, float us_per_sample, state * reader_state, float blf, float
rtcal)
: gr_block("listener_reader_monitor_cmd_gate",
gr_make_io_signature (1,1,sizeof(float)),
gr_make_io_signature (1,1,sizeof(float))),
d_real_time(real_time), d_us_per_sample(us_per_sample), d_blf(blf),
d_rtcal(rtcal)
{
// Initialize state
d_reader_state = reader_state;
d_reader_state->blf = d_blf; // -> blf is an object of d_reader
state
d_reader_state->zc=0;
d_reader_state->cum_zc_count=0;
pwrd_dwn = false;
d_thresh=6000;
// According to gen2 standard determine when tag responds after a
reader command
Tpri = (1/d_blf)*1000;
T1 = max(d_rtcal,10*Tpri); //dallo standard gen2
// Gen2 defines at least 1ms of power-down period --> 0.8 ms is a
good choice to ensure power-down detection
pwrd_down_time = 800; //in microsec.
log_reader = gr_make_msg_queue(300000); // message queue -->
decoded in Python
}
// END INITIAL SETUP
///////////////////////////////////////////////////////////////////////////
///////////////////////
listener_reader_monitor_cmd_gate::~listener_reader_monitor_cmd_gate()
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
56
{
}
///////////////////////////////////////////////////////////////////////////
////////////////////////
// GENERAL WORK
///////////////////////////////////////////////////////////////////////////
///////////////////////
int listener_reader_monitor_cmd_gate::general_work(int noutput_items,
gr_vector_int &ninput_items,
gr_vector_const_void_star
&input_items,
gr_vector_void_star
&output_items)
{
const float * in = (const float *)input_items[0];
float * out = (float * )output_items[0];
double avg, max, min;
double max_RSSI, avg_RSSI;
static long high_cnt=0;
static long low_cnt=0;
static long l_pulse;
int n_out = 0;
// Declaration of the chains that I'm going to use to store the
bits (0, 1)
char chain[400], query[400]="", qrep[400]="", ack[21]="",
nak[11]="";
char temp[300]=",";
//First possibility to determine threshold (don't permit SNR
calculation)
/*
if (d_reader_state->tag==false) {
max_min(in, noutput_items, &max, &min, &avg);
max_RSSI = max;
avg_RSSI = avg;
d_thresh = max * .7;
}
*/
static int num_pulses = 0;
static int aux = 0;
//static int zeros=0;
//static int ones=0;
for(int i = 0; i < noutput_items; i++) {
// Detect the last command transmitted by the reader and
ungate after that
if(d_reader_state->tag==false) {
static bool edge_fell = false;
if(!edge_fell){
if(in[i] < d_thresh){
edge_fell = true; // Edge fell
}
} else {
if(in[i] > d_thresh && d_thresh > 5000) {
num_pulses++; // New pulse, +1
edge_fell = false; // Edge rise
}
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
57
}
if(in[i] < d_thresh) {
low_cnt++;
if(low_cnt * d_us_per_sample >
pwrd_down_time) { // Detected reader power-down period
pwrd_dwn=true;
num_pulses=-1;
}
}
if( (in[i] > d_thresh) && (d_thresh > 5000) ) {
if (low_cnt > 0) {
// *** Adding changes here *** //
l_pulse = low_cnt + high_cnt;
if ( aux < 200 ){
//printf("\n aux %d \n",
aux);
if ( (l_pulse > 30) &&
(l_pulse < 50) ) { // 0 -> l_pulse = 40
chain[aux]='0';
}
if ( (l_pulse > 70) &&
(l_pulse < 90) ) { // 1 -> l_pulse = 80
chain[aux]='1';
}
/*if ( (l_pulse > 110) &&
(l_pulse < 130) ) { // Rtcal = O_len + 1_len
chain[aux]='R';
}
if ( (l_pulse > 130) &&
(l_pulse < 360) ) { // 1.1 Rtcal <= Trcal <= 3 Rtcal
chain[aux]='T';
}*/
if ( (l_pulse < 30) || (
(l_pulse > 50) && (l_pulse < 70) ) || (l_pulse > 90) ){
chain[aux]='Z';
sprintf(temp,"%s,%d",temp,l_pulse); // OK, I checked that in 'temp' the
values of l_pulse are stored
//printf("\n Temp
%s",temp);
}
aux++;
}
low_cnt=0;
high_cnt=0;
}
high_cnt++;
if (pwrd_dwn==true) {
// Second possibility for threshold
calculation (use this for future implementation of SNR calculation)
max_min(in, noutput_items, &max,
&min, &avg);
max_RSSI = max;
avg_RSSI = avg;
d_thresh = max * .7; // New
threshold
pwrd_dwn=false;
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
58
if (d_real_time==true) printf("READER
SIGNAL: Powered-Up after detected power-down period\n");
log_msg(LOG_PWR_UP, NULL, LOG_OKAY);
}
}
if (num_pulses==26 && high_cnt*d_us_per_sample > T1)
{
if (d_real_time==true) printf("READER SIGNAL:
QUERY\n");
strncpy(query, chain, 26); // OK
//printf("\nTemp: %s",temp);
strcat(query, temp);
//printf("\n Query + temp %s", query);
log_msg(LOG_QUERY, query, LOG_OKAY);
num_pulses=0;
aux=0;
temp[0]='\0'; // to "clean" the string
}
if (num_pulses==7 && high_cnt*d_us_per_sample > T1)
{
if (d_real_time==true) printf("READER SIGNAL:
QREP\n");
strncpy(qrep, chain, 7);
strcat(qrep, temp);
// printf("\nLong qrep: %d\n", strlen(qrep));
log_msg(LOG_QREP, qrep, LOG_OKAY);
num_pulses=0;
aux=0;
temp[0]='\0';
}
if (num_pulses==21 && high_cnt*d_us_per_sample > T1)
{
if (d_real_time==true) {
printf("READER SIGNAL: ACK\n");
printf("EXPECTED EPC message from
Tag\n");
}
strncpy(ack, chain, 21);
ack[21]='\0';
//printf("\n ACK: %s",ack);
//printf("\n");
log_msg(LOG_ACK, ack, LOG_OKAY);
num_pulses=0;
aux=0;
temp[0]='\0';
// Open gate --> expected EPC message from
Tag
d_reader_state->tag=true;
d_reader_state->blf = d_blf;
d_reader_state->zc=0;
d_reader_state->cum_zc_count=0;
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
59
}
if (num_pulses==11 && high_cnt*d_us_per_sample > T1)
{
if (d_real_time==true) printf("READER SIGNAL:
NAK\n");
strncpy(nak, chain, 11);
nak[11]='\0';
//printf("\n%s",nak);
//printf("\n");
log_msg(LOG_NAK, nak, LOG_OKAY);
num_pulses=0;
aux=0;
temp[0]='\0';
}
if (num_pulses>0 && high_cnt*d_us_per_sample > T1) {
num_pulses=0;
aux=0;
temp[0]='\0';
}
}
// Send out expected tag signal
if (d_reader_state->tag==true ) {
out[n_out++] = in[i];
}
}
consume_each(noutput_items);
return n_out;
}
// END GENERAL WORK
///////////////////////////////////////////////////////////////////////////
///////////////
///////////////////////////////////////////////////////////////////////////
///////////////
// CALCULATE MAX AND MIN OF THE SIGNAL
///////////////////////////////////////////////////////////////////////////
///////////////
int listener_reader_monitor_cmd_gate::max_min(const float * buffer, int
len, double * max, double * min, double * avg )
{
double tmp_avg = 0;
double tmp_std_dev = 0;
for (int i = 0; i < len; i++) {
tmp_avg += buffer[i];
if(buffer[i] > * max) {
*max = buffer[i];
}
if(buffer[i] < * min) {
*min = buffer[i];
}
}
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
60
tmp_avg = tmp_avg / len;
*avg = tmp_avg;
return 1;
}
// END CALCULATE MAX AND MIN OF THE SIGNAL
///////////////////////////////////////////////////////////////////////////
///////////////
///////////////////////////////////////////////////////////////////////////
//////////////
// CREATE LOG MSG
///////////////////////////////////////////////////////////////////////////
/////////////
void
listener_reader_monitor_cmd_gate::log_msg(int message, char * text, int
error){
if(LOGGING_READER){
char msg[1000];
timeval time;
gettimeofday(&time, NULL);
tm * t_info = gmtime(&time.tv_sec);
int len = 0;
if(text != NULL){
len = sprintf(msg, "%s Time: %d.%03ld\n", text,
(t_info->tm_hour*3600)+(t_info->tm_min*60)+t_info->tm_sec,
time.tv_usec/1000);
}
else{
len = sprintf(msg,"Time: %d.%03ld\n", (t_info-
>tm_hour*3600)+ (t_info->tm_min*60)+t_info->tm_sec, time.tv_usec/1000 );
}
gr_message_sptr log_msg = gr_make_message(message, 0, error,
len);
memcpy(log_msg->msg(), msg, len);
log_reader->insert_tail(log_msg);
}
}
// END LOG MSG
///////////////////////////////////////////////////////////////////////////
// FORECAST
///////////////////////////////////////////////////////////////////////////
///////////////
void listener_reader_monitor_cmd_gate::forecast (int noutput_items,
gr_vector_int &ninput_items_required)
{
unsigned ninputs = ninput_items_required.size ();
for (unsigned i = 0; i < ninputs; i++){
ninput_items_required[i] = noutput_items;
}
}
// END FORECAST
///////////////////////////////////////////////////////////////////////////
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
61
4. Listener Tag Monitor
/* -*- c++ -*- */
/*
* Copyright 2004,2006 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* GNU Radio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <listener_tag_monitor.h>
#include <gr_io_signature.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "listener_vars.h"
#include <sys/time.h>
#include <float.h>
#include <string.h>
/////////////////////////////////////////////////////////////////
// INITIAL SETUP
////////////////////////////////////////////////////////////////
listener_tag_monitor_sptr
listener_make_tag_monitor(bool real_time, int miller, float blf)
{
return listener_tag_monitor_sptr(new listener_tag_monitor(real_time,
miller, blf));
}
listener_tag_monitor::listener_tag_monitor(bool real_time, int miller,
float blf): gr_block("listener_tag_monitor", gr_make_io_signature (1, 1,
sizeof(float)), gr_make_io_signature (1,1,sizeof(float))),
d_real_time(real_time) , d_miller(miller), d_blf(blf)
{
;
// Initialize state
STATE.tag=false;
STATE.blf = d_blf;
STATE.zc=0;
STATE.cum_zc_count=0;
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
62
log_tag = gr_make_msg_queue(300000); // message queue --> decoded
in Python
d_sample_buffer = (float *)malloc(MAX_INPUT_ITEMS * 4 *
sizeof(float)); // store input samples
d_tag_bit_vector = (char *)malloc(max_tag_response_len *
sizeof(char)); // store tag bits
// Encoding parameters definition
if (d_miller == 0) { // FM0 encoding
STATE.tag_preamble = fm0_preamble;
STATE.tag_preamble_len = len_fm0_preamble;
STATE.tag_one = fm0_one_vec; //
ideal bit '1'
STATE.tag_zero = fm0_zero_vec; // ideal bit '0'
STATE.tag_one_bis = fm0_one_vec_bis; //
ideal bit '1'
STATE.tag_zero_bis = fm0_zero_vec_bis; //
ideal bit '0'
STATE.tag_one_len = len_fm0_one;
}
if (d_miller == 2) { // Miller-2 encoding
STATE.tag_preamble = m2_preamble;
STATE.tag_preamble_len = len_m2_preamble;
STATE.tag_one = m2_one_vec; //
ideal bit '1'
STATE.tag_zero = m2_zero_vec; // ideal bit '0'
STATE.tag_one_bis = m2_one_vec_bis; //
ideal bit '1'
STATE.tag_zero_bis = m2_zero_vec_bis; //
ideal bit '0'
STATE.tag_one_len = len_m2_one;
}
if (d_miller == 4) { // Miller-4 encoding
STATE.tag_preamble = m4_preamble;
STATE.tag_preamble_len = len_m4_preamble;
STATE.tag_one = m4_one_vec; //
ideal bit '1'
STATE.tag_zero = m4_zero_vec; //
ideal bit '0'
STATE.tag_one_bis = m4_one_vec_bis; //
ideal bit '1'
STATE.tag_zero_bis = m4_zero_vec_bis; //
ideal bit '0'
STATE.tag_one_len = len_m4_one;
}
if (d_miller == 8) { // Miller-8 encoding
STATE.tag_preamble = m8_preamble;
STATE.tag_preamble_len = len_m8_preamble;
STATE.tag_one = m8_one_vec; //
ideal bit '1'
STATE.tag_zero = m8_zero_vec; //
ideal bit '0'
STATE.tag_one_bis = m8_one_vec_bis; //
ideal bit '1'
STATE.tag_zero_bis = m8_zero_vec_bis; //
ideal bit '0'
STATE.tag_one_len = len_m8_one;
}
DEFAULT_NUM_INPUT_ITEMS = STATE.tag_preamble_len;
d_items_copied = 0;
d_reads = 0;
//Set STATE pointer
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
63
STATE_PTR = &STATE;
reset_receive_state(); // reset receiver to initial state
}
// END SETUP INIZIALE
///////////////////////////////////////////////////////////////////////////
///////////////////////
listener_tag_monitor::~listener_tag_monitor()
{
}
///////////////////////////////////////////////////////////////////////////
////////////////////////
// GENERAL WORK
///////////////////////////////////////////////////////////////////////////
///////////////////////
int listener_tag_monitor::general_work(int noutput_items,
gr_vector_int &ninput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items)
{
const float * in = (const float *)input_items[0];
float * out = (float * )output_items[0];
int nout = 0;
int consumed = d_num_input_items;
int num_samples = 0;
int i = 0;
num_samples = d_items_copied + d_num_input_items;
memcpy(&d_sample_buffer[d_items_copied], in, ninput_items[0] *
sizeof(float));
while(i < int(num_samples - history())){
// Correlate for preamble
if(STATE.found_preamble == false) {
double sum = 0.;
double total_pwr = 0.;
float score = 0.;
for(int j = 0; j < STATE.tag_preamble_len; j++) {
total_pwr += fabs(d_sample_buffer[i + j]);
sum += STATE.tag_preamble[j] * (d_sample_buffer[i +
j]);
}
score = fabs(sum) / total_pwr; // SCORE
// printf("\n Score: %f",score);
if(score > .45 && score < .55){ // Maybe an error
STATE.bit_error = true;
}
if(d_last_score != 0 && score < d_last_score){ // Max
correlation --> found preamble
set_history(STATE.tag_one_len);
STATE.found_preamble = true;
STATE.blf = d_blf;
STATE.zc=0;
STATE.cum_zc_count=0;
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
64
//printf("FOUND PREAMBLE \n");
d_skip_cnt = STATE.tag_preamble_len - 1;
STATE.TAG_POWER = (total_pwr /
STATE.tag_preamble_len); // the power of the tag is the total power divided
by
} // the length of the preamble
else{
if(score > .9){ // Store last score
double max, min, avg;
max_min(&d_sample_buffer[i],
STATE.tag_preamble_len, &max, &min, &avg);
if(fabs(max + min) < max){ // max min should
be centered
d_last_score = score;
}
}
}
//Preamble not detected
if(d_find_preamble_count++ > STATE.tag_preamble_len * 10){
STATE.tag=false;
reset_receive_state();
STATE.blf = d_blf;
STATE.zc=0;
STATE.cum_zc_count=0;
}
} // End correlating preamble
else{ // PREAMBLE FOUND --> decode bits
// Correlate for bits
// Early/late gate correlation decoding
int adjust = 0;
int best_pos_0 = 0;
int best_pos_1 = 0;
float best_score_0 = 0;
float best_score_1 = 0;
float best_score_0_int = 0;
float best_score_1_int = 0;
double sum_0 = 0;
double sum_1 = 0;
double sum_0_bis = 0;
double sum_1_bis = 0;
double total_pwr = 0;
double avg_pwr = 0;
float score_0 = 0;
float score_1 = 0;
float score_0_bis = 0;
float score_1_bis = 0;
// Center the signal
for(int j = 0; j < STATE.tag_one_len; j++){
avg_pwr += d_sample_buffer[i + j];
}
avg_pwr = avg_pwr / (float)STATE.tag_one_len;
for(int j = 0; j < STATE.tag_one_len; j++){
total_pwr += fabs(avg_pwr - d_sample_buffer[i + j]);
sum_0 += STATE.tag_zero[j] * (avg_pwr -
d_sample_buffer[i + j]);
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
65
sum_1 += STATE.tag_one[j] * (avg_pwr - d_sample_buffer[i +
j]);
sum_0_bis += STATE.tag_zero_bis[j] * (avg_pwr -
d_sample_buffer[i + j]); // 0 bis
sum_1_bis += STATE.tag_one_bis[j] * (avg_pwr -
d_sample_buffer[i + j]); // 1 bis
}
score_0 = fabs(sum_0) / total_pwr;
score_1 = fabs(sum_1) / total_pwr;
score_0_bis = fabs(sum_0_bis) / total_pwr;
score_1_bis = fabs(sum_1_bis) / total_pwr;
best_score_0 = std::max(score_0, score_0_bis);
best_score_1 = std::max(score_1, score_1_bis);
avg_symbol_pwr = avg_symbol_pwr + (total_pwr /
STATE.tag_one_len);
// Maximum deviation of early/late correlator
int max_dev=1;
if (d_miller==0 || d_miller==2) max_dev=0;
else max_dev=1;
// Early/late gate correlator for Miller
for(int k = -max_dev; k <= max_dev && k!=0; k++){
sum_0 = sum_1 = sum_0_bis = sum_1_bis = 0; // back
to zero all the values
total_pwr = avg_pwr = 0;
score_0 = score_1 = score_0_bis = score_1_bis = 0;
for(int j = 0; j < STATE.tag_one_len; j++){
if ((i+j+k)>=0 &&
(i+j+k)<(MAX_INPUT_ITEMS*4)) {
avg_pwr +=
d_sample_buffer[i + j + k];
}
}
avg_pwr = avg_pwr / (float)STATE.tag_one_len;
for(int j = 0; j < STATE.tag_one_len; j++){
if ((i+j+k)>=0 &&
(i+j+k)<(MAX_INPUT_ITEMS*6)) {
total_pwr += fabs(avg_pwr -
d_sample_buffer[i + j + k]);
sum_0 += STATE.tag_zero[j] *
(avg_pwr - d_sample_buffer[i + j + k]);
sum_1 += STATE.tag_one[j] * (avg_pwr
- d_sample_buffer[i + j + k]);
sum_0_bis +=
STATE.tag_zero_bis[j] * (avg_pwr - d_sample_buffer[i + j + k]);
sum_1_bis += STATE.tag_one_bis[j] *
(avg_pwr - d_sample_buffer[i + j + k]);
}
}
score_0 = fabs(sum_0) / total_pwr;
score_1 = fabs(sum_1) / total_pwr;
score_0_bis = fabs(sum_0_bis) / total_pwr;
score_1_bis = fabs(sum_1_bis) / total_pwr;
score_0 = std::max(score_0,score_0_bis);
score_1 = std::max(score_1,score_1_bis);
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
66
// Calculate best position
if( (score_0 > best_score_0_int) && (score_0 >
best_score_0) ){
best_score_0_int = score_0;
best_pos_0 = k;
}
if( (score_1 > best_score_1_int) && (score_1 > best_score_1)
){
best_score_1_int = score_1;
best_pos_1 = k;
}
}//End early/late gate correlator
if (best_score_1 > best_score_0) {
adjust = best_pos_1;
//printf("\n Best_score_1: %f > best_score_0: %f
'1'", best_score_1, best_score_0);
d_tag_bit_vector[STATE.num_bits_decoded++] = '1';
}
else {
adjust = best_pos_0;
//printf("\n Best_score_1: %f < best_score_0: %f
'0'", best_score_1, best_score_0);
d_tag_bit_vector[STATE.num_bits_decoded++] = '0';
}
// Adjust position of the next samples
d_skip_cnt = STATE.tag_one_len+adjust;
// Optimized request size
d_num_input_items = STATE.tag_one_len * (num_EPC_bits -
STATE.num_bits_decoded);
// EPC MESSAGE (Based on typical commercial Tags with
standard EPC code -> Header's EPC: 00 110000)
if( (STATE.num_bits_decoded==(num_RN16_bits-1)) &&
d_tag_bit_vector[0]=='0' && d_tag_bit_vector[1]=='0' &&
d_tag_bit_vector[2]=='1' && d_tag_bit_vector[3]=='1' &&
d_tag_bit_vector[4]=='0' && d_tag_bit_vector[5]=='0' &&
d_tag_bit_vector[6]=='0' && d_tag_bit_vector[7]=='0' ){
d_rn16 = false;
}
// EPC MESSAGE
if ( (STATE.num_bits_decoded == num_EPC_bits) && (d_rn16 ==
false ) ) {
STATE.tag=false; // Close gate
STATE.blf = d_blf;
STATE.zc=0;
STATE.cum_zc_count=0;
float tag_RSSI = avg_symbol_pwr / num_EPC_bits;
int pass = check_crc(d_tag_bit_vector,
STATE.num_bits_decoded);
if(pass == 1) {
// Printf bits
//printf("\n d_tag_bit_vector %s
",d_tag_bit_vector);
//for(int i = 0; i <
STATE.num_bits_decoded;i++){
// printf("%c", d_tag_bit_vector[i]);
//}
//printf("\n");
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
67
d_reads++;
//printf("Tag reads = %d \n",d_reads);
// Real time printf of EPC message
if (d_real_time == true) {
printf("CORRECT TAG FOUND !! RSSI =
%.2f \n",tag_RSSI);
int HEADER = 0;
int EPC_MANAGER = 0;
int OBJECT_CLASS = 0;
int SERIAL_NUMBER = 0;
for(int i = 16; i < 112;i++){ //
Total EPC: 96 bits
if ((i-16)>=0 && (i-16)<8) {
// HEADER FIELD: 8 bits
HEADER = HEADER * 2 +
d_tag_bit_vector[i] -'0';
}
if ((i-16)>=8 && (i-16)<36) {
// EPC MANAGER FIELD: 28 bits
EPC_MANAGER =
EPC_MANAGER * 2 + d_tag_bit_vector[i] -'0';
}
if ((i-16)>=36 && (i-16)<60)
{ // OBJECT CLASS FIELD: 24 bits
OBJECT_CLASS =
OBJECT_CLASS * 2 + d_tag_bit_vector[i] -'0';
}
if ((i-16)>=60 && (i-16)<96)
{ // SERIAL NUMBER FIELD: 36 bits
SERIAL_NUMBER =
SERIAL_NUMBER * 2 + d_tag_bit_vector[i] -'0';
}
}
printf("EPC:\t%X %07X %X
%X\n",HEADER,EPC_MANAGER,OBJECT_CLASS,SERIAL_NUMBER);
printf("\n");
}
// Create log message
d_tag_bit_vector[STATE.num_bits_decoded] =
'\0';
char tmp[500];
char tmp2[500];
strcpy(tmp, d_tag_bit_vector);
sprintf(tmp2, ",%f\n", tag_RSSI);
strcat(tmp, tmp2);
log_msg(LOG_EPC, tmp, LOG_OKAY);
}
else{ // Failed CRC
if (d_real_time == true) {
printf("!! ERROR: UNCORRECT CRC !!
\n");
}
float tag_RSSI = avg_symbol_pwr /
num_EPC_bits;
d_tag_bit_vector[STATE.num_bits_decoded] =
'\0';
char tmp[500];
char tmp2[500];
strcpy(tmp, d_tag_bit_vector);
sprintf(tmp2, ",%f\n", tag_RSSI);
strcat(tmp, tmp2);
log_msg(LOG_EPC, tmp, LOG_ERROR);
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
68
}
reset_receive_state();
break;
}
// RN16 MESSAGE
if( (STATE.num_bits_decoded == num_RN16_bits) &&
(d_rn16==true) ){
float tag_RSSI = avg_symbol_pwr / num_RN16_bits;
// Possible bad RN16
if(STATE.bit_error) {
// Printf RN16 Error
//printf("RN16 MESSAGE ERROR !! RSSI = %.2f
\n",tag_RSSI);
//for(int i = 0; i <
STATE.num_bits_decoded;i++){
//printf("%c", d_tag_bit_vector[i]);
//}
//printf("\n");
d_tag_bit_vector[STATE.num_bits_decoded] =
'\0';
char tmp[500];
char tmp2[500];
strcpy(tmp, d_tag_bit_vector);
sprintf(tmp2, ",%f\n", tag_RSSI);
strcat(tmp, tmp2);
log_msg(LOG_RN16, tmp, LOG_ERROR);
}
// Correct RN16
else {
// Printf RN16 message
//printf("RN16 MESSAGE !! RSSI = %.2f
\n",tag_RSSI);
//for(int i = 0; i <
STATE.num_bits_decoded;i++){
// printf("%c", d_tag_bit_vector[i]);
//}
//printf("\n");
d_tag_bit_vector[STATE.num_bits_decoded] =
'\0';
char tmp[500];
char tmp2[500];
strcpy(tmp, d_tag_bit_vector);
sprintf(tmp2, ",%f\n", tag_RSSI);
strcat(tmp, tmp2);
log_msg(LOG_RN16, tmp, LOG_OKAY);
}
reset_receive_state();
break;
}
} // END BIT DECODING
if(d_skip_cnt > 0){
i = i + d_skip_cnt;
}
else{
i++;
}
} // END WHILE
d_items_copied = num_samples - i;
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
69
memcpy(d_sample_buffer, &d_sample_buffer[num_samples - d_items_copied],
d_items_copied * sizeof(float));
consume_each(consumed);
return consumed;
}
// END GENERAL WORK
///////////////////////////////////////////////////////////////////////////
///////////////
///////////////////////////////////////////////////////////////////////////
///////////////
// FORECAST
///////////////////////////////////////////////////////////////////////////
///////////////
void listener_tag_monitor::forecast (int noutput_items, gr_vector_int
&ninput_items_required)
{
unsigned ninputs = ninput_items_required.size ();
for (unsigned i = 0; i < ninputs; i++){
ninput_items_required[i] = d_num_input_items;
}
}
// END FORECAST
///////////////////////////////////////////////////////////////////////////
///////////////
///////////////////////////////////////////////////////////////////////////
///////////////
// CALCULATE MAX AND MIN
///////////////////////////////////////////////////////////////////////////
///////////////
void listener_tag_monitor::max_min(const float * buffer, int len, double *
max, double * min, double * avg )
{
*max = DBL_MIN;
*min = DBL_MAX;
double tmp = 0;
for (int i = 0; i < len; i++){
tmp += buffer[i];
if(buffer[i] > * max){
*max = buffer[i];
}
if(buffer[i] < * min){
*min = buffer[i];
}
}
*avg = tmp / len;
}
// END MAX_MIN
///////////////////////////////////////////////////////////////////////////
///////////////
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
70
///////////////////////////////////////////////////////////////////////////
//////////////
// RESET RECEIVE STATE
///////////////////////////////////////////////////////////////////////////
/////////////
void listener_tag_monitor::reset_receive_state()
{
set_history(STATE.tag_preamble_len);
d_num_input_items = DEFAULT_NUM_INPUT_ITEMS;
d_rn16 = true;
STATE.found_preamble = false;
STATE.bit_error = false;
STATE.num_bits_decoded = 0;
d_skip_cnt = 0;
d_last_score = 0.;
avg_symbol_pwr = 0.;
d_find_preamble_count = 0;
}
// END RESET RECEIVE STATE
///////////////////////////////////////////////////////////////////////////
///////////////
///////////////////////////////////////////////////////////////////////////
//////////////
// CHECK CRC 16 bit
///////////////////////////////////////////////////////////////////////////
/////////////
int listener_tag_monitor::check_crc(char * bits, int num_bits){
register unsigned short i, j;
register unsigned short crc_16, rcvd_crc;
unsigned char * data;
int num_bytes = num_bits / 8;
data = (unsigned char* )malloc(num_bytes );
int mask;
for(i = 0; i < num_bytes; i++){
mask = 0x80;
data[i] = 0;
for(j = 0; j < 8; j++){
if (bits[(i * 8) + j] == '1'){
data[i] = data[i] | mask;
}
mask = mask >> 1;
}
}
rcvd_crc = (data[num_bytes - 2] << 8) + data[num_bytes -1];
crc_16 = 0xFFFF;
for (i=0; i < num_bytes - 2; i++) {
crc_16^=data[i] << 8;
for (j=0;j<8;j++) {
if (crc_16&0x8000) {
crc_16 <<= 1;
crc_16 ^= 0x1021; // (CCITT) x16 + x12 + x5 +
1
}
else {
crc_16 <<= 1;
}
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
71
}
}
crc_16 = ~crc_16;
if(rcvd_crc != crc_16){
//printf("Failed CRC\n");
return -1;
}
else{
return 1;
}
}
// END CHECK CRC16
///////////////////////////////////////////////////////////////////////////
///////////////
///////////////////////////////////////////////////////////////////////////
//////////////
// CREATE LOG MSG
///////////////////////////////////////////////////////////////////////////
/////////////
void
listener_tag_monitor::log_msg(int message, char * text, int error){
if(LOGGING_TAG){
char msg[1000];
timeval time;
gettimeofday(&time, NULL);
tm * t_info = gmtime(&time.tv_sec);
int len = 0;
if(text != NULL){
len = sprintf(msg, "%s Time: %d.%03ld\n", text,
(t_info->tm_hour*3600)+(t_info->tm_min*60)+t_info->tm_sec,
time.tv_usec/1000);
}
else{
len = sprintf(msg,"Time: %d.%03ld\n", (t_info-
>tm_hour*3600)+ (t_info->tm_min*60)+t_info->tm_sec, time.tv_usec/1000 );
}
gr_message_sptr log_msg = gr_make_message(message, 0, error,
len);
memcpy(log_msg->msg(), msg, len);
log_tag->insert_tail(log_msg);
}
}
// END LOG MSG
///////////////////////////////////////////////////////////////////////////
///////////////
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
72
5. SC Block C++ /* -*- c++ -*- */
/*
* Copyright 2014 <+YOU OR YOUR COMPANY+>.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <gr_io_signature.h>
#include "select_ff_impl.h"
#include <float.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
namespace gr {
namespace amemodule {
select_ff::sptr
select_ff::make(int nsamples)
{
return gnuradio::get_initial_sptr
(new select_ff_impl(nsamples));
}
/*
* The private constructor
*/
select_ff_impl::select_ff_impl(int nsamples)
: gr_block("select_ff",
gr_make_io_signature(2, 2, sizeof(float)),
gr_make_io_signature(1, 1, sizeof(float))),
d_nsamples(nsamples)
{}
/*
* Our virtual destructor.
*/
select_ff_impl::~select_ff_impl()
{
}
void
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
73
select_ff_impl::forecast (int noutput_items, gr_vector_int
&ninput_items_required)
{
unsigned ninputs = ninput_items_required.size();
for(unsigned i = 0; i<ninputs; i++){
ninput_items_required[i] = noutput_items;
}
}
int
select_ff_impl::general_work (int noutput_items,
gr_vector_int &ninput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items)
{
const float *in0 = (const float *) input_items[0];
const float *in1 = (const float *) input_items[1];
float *out = (float *) output_items[0];
float mean_in0 = 0;
float mean_in1 = 0;
for(int i=0; i<noutput_items;i++){
if( i<d_nsamples ){
mean_in0 += in0[i];
mean_in1 += in1[i];
out[i]=in0[i];
}
if( i>=d_nsamples ){
if( mean_in0 > mean_in1)
out[i]=in0[i];
else
out[i]=in1[i];
}
}
consume_each (noutput_items);
// Tell runtime system how many output items we produced.
return noutput_items;
}
} /* namespace amemodule */
} /* namespace gr */
Amelia Jiménez Sánchez
RFID – MIMO Prototype based on GNU Radio Annex
74
6. SC Block .h
/* -*- c++ -*- */
/*
* Copyright 2014 <+YOU OR YOUR COMPANY+>.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
by
* the Free Software Foundation; either version 3, or (at your
option)
* any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef INCLUDED_AMEMODULE_SELECT_FF_IMPL_H
#define INCLUDED_AMEMODULE_SELECT_FF_IMPL_H
#include <amemodule/select_ff.h>
namespace gr {
namespace amemodule {
class select_ff_impl : public select_ff
{
private:
int d_nsamples;
public:
select_ff_impl(int nsamples);
~select_ff_impl();
// Where all the action really happens
void forecast (int noutput_items, gr_vector_int
&ninput_items_required);
int general_work(int noutput_items,
gr_vector_int &ninput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items);
};
} // namespace amemodule
} // namespace gr
#endif /* INCLUDED_AMEMODULE_SELECT_FF_IMPL_H */