import serial
import pyautogui
import time

# Replace with the correct COM port for your ESP32 (e.g., COM3, /dev/ttyUSB0, etc.)
esp32_port = "COM14"  # Example for Windows, use the correct port for your setup
baud_rate = 115200

# Open the serial connection to the ESP32
ser = serial.Serial(esp32_port, baud_rate)

# Variables to track push-ups and key presses for tw  o players
player_data = {
    '1': {'pushup_count': 0, 'pushup_started': False, 'last_key_press_time': 0},
    '2': {'pushup_count': 0, 'pushup_started': False, 'last_key_press_time': 0},
}

# Read data from ESP32 and process it w
while True:
    if ser.in_waiting > 0:
        # Read a line of data from the serial buffer
        data = ser.readline().decode('utf-8').strip()
        
        try:
            # Identify the player (first character) and split the data
            player_id, values = data.split(':')
            x, y, z = map(int, values.split(','))

            # Get the player's data dictionary
            player = player_data.get(player_id)
            if not player:
                continue  # Skip if the player ID is invalid

            # Check for push-up starting position
            if z > 600 and y < 100:
                if not player['pushup_started']:
                    print(f"Player {player_id}: Keep It Up")  # Display motivational message
                player['pushup_started'] = True
 
            # Check for push-up completion position
            if player['pushup_started'] and 200 < z < 400:
                player['pushup_count'] += 1
                print(f"Player {player_id} Push-up Count: {player['pushup_count']}")  # Print the push-up count
                player['pushup_started'] = False  # Reset push-up tracking

            # Check if y exceeds 800 and press the appropriate key
            if y > 800:
                current_time = time.time() * 1000  # Get current time in milliseconds
                
                # Ensure a 400ms delay between key presses
                if current_time - player['last_key_press_time'] > 400:
                    if player_id == '1':
                        pyautogui.press('Space')  # Player 1 presses space 
                        print("Player 1: Space key pressed!")
                    elif player_id == '2':
                        pyautogui.press('w')  # Player 2 presses 'w'
                        print("Player 2: W key pressed!")
                    
                    player['last_key_press_time'] = current_time  # Update the time when the key was pressed

        except ValueError:
            pass  # Ignore invalid data
