# Projet PyRobot 2022 . Bertrand Hoareau
# https://host974.com/pyrobot/ 


import cv2
import numpy as np
import face_recognition
import os

import RPi.GPIO as GPIO
import time

GPIO.setwarnings(False)
#GPIO.setmode(GPIO.BOARD)
GPIO.setmode(GPIO.BCM)    # Numerotation  BCM choisie  pour les E/S

# Configuration des sorties :
GPIO.setup(20, GPIO.OUT)
GPIO.setup(21, GPIO.OUT)


# Lecture mot série sous interruption

def lire_entree(a):
	global compteur_bit
	
	data.append(GPIO.input(16))
	compteur_bit = compteur_bit + 1
	#print (compteur_bit)

# Configuration des entrées :
GPIO.setup(16, GPIO.IN)  # Data (D0 du Pic)
GPIO.setup(12, GPIO.IN)  # horloge (D1 du pic)
GPIO.add_event_detect(12, GPIO.RISING, callback = lire_entree, bouncetime = 1)
data =[]
compteur_bit = 0
compteur_passage = 0

# Attention, le signal recu sera inversé à cause des transistors
def envoyer(valeur):
	
	# data sur sortie 21 : B0 du pic
	for i in range(8):   # message sur 8 bits
		reste = valeur%2
		valeur = valeur//2
		
		if reste == 0:
			#print ("envoie 0",end=" ")
			GPIO.output(21, GPIO.LOW)
		else:
			#print ("envoie 1",end=" ")
			GPIO.output(21, GPIO.HIGH)
		
		# Horloge sortie 20 : B1 du PIC
#		GPIO.output(20, GPIO.LOW)
#		time.sleep(0.01)		
		GPIO.output(20, GPIO.HIGH)
		time.sleep(0.01)
		GPIO.output(20, GPIO.LOW)
		time.sleep(0.01)
	
	#print ()
	#print ("---")		

def convertir(data, nbit):
	valeur = 0
	for i in range(nbit):
		valeur = valeur + data[i]*2**i
	
	return valeur
	
print ("Projet PyRobot")

# camera usb 640 * 480

path = 'ImagesAttendance'
images = []
classNames = []
myList = os.listdir(path)
print (myList)
for cl in myList:
	curImg = cv2.imread(f'{path}/{cl}')
	images.append(curImg)
	classNames.append(os.path.splitext(cl)[0])
	
print (classNames)

def findEncodings(images):
	encodeList = []
	for img in images:
		img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
		encode= face_recognition.face_encodings(img)[0]
		encodeList.append(encode)
	return encodeList

encodeListKnow = findEncodings(images)
#print(len(encodeListKnow))
print ("Encodage terminé")

cap = cv2.VideoCapture(0)

while True:
	success, img = cap.read()
	imgS = cv2.resize(img,(0,0),None,0.25,0.25)
	imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)
	
	facesCurFrame = face_recognition.face_locations(imgS)
	encodeCurFrame = face_recognition.face_encodings(imgS,facesCurFrame)
	
	for encodeFace, faceLoc in zip(encodeCurFrame,facesCurFrame):
		matches = face_recognition.compare_faces(encodeListKnow,encodeFace)
		faceDis = face_recognition.face_distance(encodeListKnow,encodeFace)
		#print (faceDis)
		matchIndex = np.argmin(faceDis)
		
		if matches[matchIndex]:
			name = classNames[matchIndex].upper()
			#print (name)
			y1,x2,y2,x1 = faceLoc
			y1,x2,y2,x1 = y1*4,x2*4,y2*4,x1*4 
			cv2.rectangle(img,(x1,y1),(x2,y2),(0,255,0),2)
			cv2.rectangle(img,(x1,y2-35),(x2,y2),(0,255,0),cv2.FILLED)
			cv2.putText(img,name,(x1+6,y2-6),cv2.FONT_HERSHEY_COMPLEX,1,(0,0,255),2)
			print ("x1,y1 = " , x1,y1," x2,y2 =",x2,y2)  
			
			compteur_passage = compteur_passage + 1
			if compteur_passage >0: 
				if x1<100 :
					envoyer(5)  # rotation gauche camera rapide
					compteur_passage = 0
				if 100<= x1 <200:
					envoyer(1)  # rotation gauche camera lent
					compteur_passage = 0
						
				if x1>500 :
					envoyer(6)   # rotation droite camera rapide
					compteur_passage = 0
				if 500 >= x1 > 400 :
					envoyer(2)   # rotation droite camera lent
					compteur_passage = 0				
				
				
				if y1<50 :
					envoyer(7)  # rotation Haut rapide
					compteur_passage = -1
				if 50<= y1 < 150 :
					envoyer(3)  # rotation Haut lent
					compteur_passage = -1					
					
					
				if y1>350 :
					envoyer(8) # rotation  Bas	rapide
					compteur_passage = -2
				if 350>= y1> 250 :
					envoyer(4) # rotation  Bas	lent
					compteur_passage = -2			
					
	#cv2.imshow('webcam',img)
	cv2.waitKey(1)
	
# Projet PyRobot 2022 . Bertrand Hoareau
# https://host974.com/pyrobot/ 	
	



