I am using a RFID reader to scan multiple RFID tags. The readings are placed into a list. I am trying to check if a tag is in the reading. Using the 'if in' method is not working for me.
import mercury
import time
reader = mercury.Reader("tmr:///dev/ttyUSB0")
reader.set_region("EU3")
reader.set_read_plan([1], "GEN2")
tag1 = 'E2004005730702602190360B'
tag2 = 'E20040057307026421903619'
while True:
a = reader.read()
print (a)
print(type(a))
if tag1 in a:
print('tag1')
time.sleep(0.2)
break
if tag2 in a:
print('tag2')
time.sleep(0.2)
break
time.sleep(0.2)
My terminal is output is:
['E20040057307026421903619', 'E2004005730702602190360B']
<type 'list'>
So the if conditions is not executed when tag1 or tag2 are in a.
I can't seem to make it enter the if condition. Any advice?
3 Answers 3
It turns out the below answer doesn't work here, since "reader" is an object other than a file and a is a list already. A better solution for you might be to change your "if in"s to if any(tag1 == tag.epc for tag in a). Printing is misleading in this case since it seems the list is actually filled with objects that print as strings but won't compare equal to strings.
I'm going to leave the earlier answer since it might be helpful to people with similar problems.
=======================================================================
Assuming "reader" is a file, using reader.read() doesn't return a list. It returns a string. You won't get an interpreter error because strings are iterable, but you also won't get the results you expect!
EDIT: Using string1 in string2 will return True iff string1 is a substring of string2. However, it is still important to be careful, because other operations that are valid (like a[0]) will return unexpected results.
Try
import ast
a = ast.literal_eval(reader.read())
That will try to interpret the result of .read() as a list. If that doesn't work for you, look into regular expressions.
3 Comments
if tag1 in a works (substring test).Looking at the documentation, it appears that you do not get a list of str, butTagReadData objects.
Try along these lines:
tag1 = b'E2004005730702602190360B'
tag2 = b'E20040057307026421903619'
a = reader.read()
for tag in a:
if tag1 == tag.epc:
print('tag1')
Comments
You should propably print the context of list object a ( reader.read() ) It will tell you the content or the purposed object, then understand what is the comparison about (the if statement)
type(a)as well? and paste the output of your console as text not as image (so we can try to reproduce)print(a[0],type(a[0])to be sure of the type of the items and which they are ? (sorry, I should have asked earlier)