import serial
import time

# DATABASE CONNECTOR 
import mysql.connector
mydb = mysql.connector.connect(
	host="localhost",
	user="arduino",
	passwd="arduino",
	database="arduino"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT ID from users")
myresult = mycursor.fetchall()
print(myresult)


print("Start")
port="/dev/"+str(input(">>> Please enter your port\n")) #This will be different for various devices and on windows it will probably be a COM port.
#port=str("/dev/rfcomm0")
bluetooth=serial.Serial(port, 9600)#Start communications with the bluetooth unit
print("Connected")

while(1):
	print("Please choose your command.")
	print(">> 1 : Listen to coordinator.")
	print(">> 2 : Ask for temperature.")
	print(">> 3 : Ask for humidity.")
	cmd = int(input(">>> "))
	if (cmd==1):
		print("----------- START mode 1 -----------")
		bluetooth.flushInput() #This gives the bluetooth a little kick
		input_data=bluetooth.readline()
		print(input_data.decode())#These are bytes coming in so a decode is needed
		idNumber = input_data.decode()
		mycursor.execute("SELECT * from users WHERE id = "+str(idNumber))
		myresult = mycursor.fetchall()
		print(myresult)
		if myresult:
			#myresult = mycursor.fetchall()
			bluetooth.write(b"AUTH_"+str.encode(str("OK")))#These need to be bytes not unicode, plus a number
		else:
			bluetooth.write(b"AUTH_"+str.encode(str("NO")))#These need to be bytes not unicode, plus a number
		#bluetooth.write(b"BOOP "+str.encode(str(420)))#These need to be bytes not unicode, plus a number
		time.sleep(0.1) #A pause between bursts
		print("----------- END -----------")
	elif(cmd==2):
		bluetooth.write(b""+str.encode(str("CMD_TMP")))#These need to be bytes not unicode, plus a number		
		time.sleep(1)
		print("----------- START mode 2 -----------")
		bluetooth.flushInput()
		input_data=bluetooth.readline()
		print(input_data.decode())
		print("----------- END -----------")
	elif(cmd==3):
		bluetooth.write(b""+str.encode(str("CMD_HMD")))#These need to be bytes not unicode, plus a number		
		time.sleep(1)
		print("----------- START mode 2 -----------")
		bluetooth.flushInput()
		input_data=bluetooth.readline()
		print(input_data.decode())
		print("----------- END -----------")

bluetooth.close()
print("done")
