import pi_servo_hat
import time

# Function to rescale web interface controls
def scale(x, in_min, in_max, out_min, out_max):
	return (x - in_min)*(out_max - out_min)/(in_max - in_min) + out_min

########################################################################
# Main Function:
########################################################################

# Initialize Servo Hat
servohat = pi_servo_hat.PiServoHat()

# Restart Servo Hat
servohat.restart()

pan_setting_old = 0
tilt_setting_old = 0

while True:
	pipein = open("/var/www/html/FIFO_pipan", 'r')
	line = pipein.readline()
	line_array = line.split(' ')
	if line_array[0] == "servo":

		# Rescales Left/Right position values
		#	web controls:		Left = 250;	Right = 50
		#	library controls:	Left =  90;	Right =  0
		pan_setting = scale(int(line_array[1]), 50, 250, 0, 90)

		# Rescales Up/Down position values
		#	web controls:		Down = 220;	Up = 80
		#	library controls:	Down =  90;	Up =  0
		tilt_setting = scale(int(line_array[2]), 80, 220, 0, 90)

		if pan_setting != pan_setting_old:
			pan_setting_old = pan_setting
			servohat.move_servo_position(0, pan_setting, 90)
			time.sleep(.05)

		if tilt_setting != tilt_setting_old:
			tilt_setting_old = tilt_setting
			servohat.move_servo_position(1, tilt_setting, 90)
			time.sleep(.05)

pipein.close()
