

import serial, time, os, sys, Queue, thread

def reading_thread(port, qin):

	rec =[]
	while runbool:
		instr = port.read()
		if instr:
			rec.append(instr)
			if instr == '\n':
				recstr = ''.join(rec)
				qin.put(recstr)
				rec = []
#				time.sleep(0.001)
		else:
			print 'instring looks like this',repr(instr)

	sys.exit()


def writing_thread(port,qot):

	while runbool:
		ostr = qot.get()
		port.write(ostr)
#		time.sleep(0.001)

	sys.exit()


if __name__ == "__main__":

	port = serial.Serial(0,
				baudrate=115200,       #baudrate
				bytesize=serial.EIGHTBITS,    #number of databits
				parity=serial.PARITY_NONE,    #enable parity checking
				stopbits=serial.STOPBITS_ONE, #number of stopbits
				timeout=0.5,           #set a timeout value, None for waiting forever
				xonxoff=0,             #enable software flow control
				rtscts=0,              #enable RTS/CTS flow control
				)
	port.setRTS(1)
	port.setDTR(1)
	port.flushInput()
	port.flushOutput()
	print 'Characters waiting is:',port.inWaiting()

	qin  = Queue.Queue()
	qot  = Queue.Queue()
	global runbool

	runbool = 1

	in_thread = thread.start_new_thread(reading_thread,(port,qin ))
	ot_thread = thread.start_new_thread(writing_thread,(port,qot ))

	time.sleep(5)

	start_time = time.time()
	count = 0

	qot.put('The quick brown fox jumps over the lazy dog\n')
	qot.put('THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG\n')
	qot.put('Now is the time for all good men to come to\n')
	while count < 1024:
		rec = qin.get()
		print rec[:-1],count
		qot.put(rec)
		count +=1
#		time.sleep(0.001)

	runbool = 0

	tot_time = time.time()-start_time
	print 'That took',tot_time,'seconds -', tot_time*1000/1024, 'Millisecs per record,', 1024/tot_time,'recs per sec'

	time.sleep(1)


