import serial
import threading
import time
import sys

# The name of the actual serial port will depend on the operating system
# and your computer's configuration. The easiet way to find it is to try
# read the tags in a serial terminal emulation program (as discussed in
# the project description)
port = '/dev/cu.usbserial-AH012QEW'

# This is the data rate of the RFID reader
baud = 2400

# Open a connection to the serial port using the information above
serial_port = serial.Serial(port, baud, timeout=0)

# This is a stub of a 'data handler' that will get called by the rest of the 
# program when a complete tag comes in from the reader
def handle_data(data):
      print("data=",data)
      # This is where you would use the data for something.
	  # Right now it simply shows it on screen.

# This is a short program that reads data coming from the RFID reader, one
# character at a time. The data coming in is 10 chararcters of useful information
# followed by 2 characters that indicate the end of the tag. It takes each incoming
# character and decides if it's a character a human can read or if it's one of the special
# end-of-tag characters. When it thinks it's done with the tag, it calls the 'handle_data()'
# progam we defined just above.
def read_from_port(ser):
	  # Let's start with an empty storage area for the incoming data
      new_data = ""
      while True:
			# Read in one character
            reading = ser.read(1)
			# If we got one, the 'length' will be 1. If not, we have nothing to look at
            if len(reading) > 0:
				  # A standard CR character (ASCII 13, or 0x0D) tells us we have all the data
                  if b'\r' == reading:
						# If the data is complete, call our data handler to do something with it
                        handle_data(new_data)
						# clear the storage area and get ready for new data
                        new_data = ""
                  elif reading >= b'0' and reading <= b'F':
						# The character is human readable and will be in the range 0-9 or A-F,
						# so stick it on the end of the storage area to build up the incoming data string
                        new_data = new_data + reading.decode()
 
# read_from_port() is intended to run in the background as a separate thread
thread = threading.Thread(target=read_from_port, args=(serial_port,))
thread.start()

# With the data collection thread running, we can go do something else.
print ("Go ahead and wave a tag near the reader.")

# This test program has nothing else to do. Yours might and this is where you'd
# do that.
while True:
      # wait here forever. You have to have something in the loop so
	  # we'll just keep assigning the value 0 to the variable a. It's
	  # wasting time while the other thread does all the work.
	  # You could have the program do something else if you wanted to.
      a = 0
