#!/usr/bin/env python3
"""
The ULTIMATE control server for Orange Pi. (Final, With Keep-Alive & Ultrasonic)
- Provides a clean camera feed without visual overlays.
- Adds an HC-SR04 ultrasonic sensor for proactive obstacle avoidance.
- Uses OPi.GPIO library for Orange Pi compatibility.
- **NEW**: Includes a background keep-alive thread to prevent the Roomba from sleeping.
"""
import os, time, threading, base64, struct, serial, sys, atexit
import cv2
import numpy as np
from flask import Flask, jsonify, request
import OPi.GPIO as GPIO # Import for Orange Pi Ultrasonic Sensor

print("Server starting... waiting 2 seconds for hardware to stabilize...")
time.sleep(2)

# --- CONFIGURATION ---
ROOMBA_PORT  = "/dev/ttyUSB0"; BAUD_RATE = 115200; WIDTH, HEIGHT= 480, 480; JPEG_Q = 75; DRIVE_SPEED = 150; TURN_SPEED = 100
OP = {"START":bytes([128]),"SAFE":bytes([131]),"FULL":bytes([132]),"STOP_STREAM":bytes([150,0]),"DRIVE_DIRECT":145,"SENSORS":142,"MOTORS":138}
app = Flask(__name__); lock = threading.Lock(); ser, cam = None, None

# --- ULTRASONIC SENSOR CONFIG ---
PIN_TRIGGER = 3    # Physical header pin 3
PIN_ECHO    = 5   # Physical header pin 5
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering

# --- INITIALIZATION ---
try:
    print(f"Opening serial port {ROOMBA_PORT}..."); ser = serial.Serial(ROOMBA_PORT, BAUD_RATE, timeout=1)
    print("Resetting Roomba state..."); ser.write(OP["STOP_STREAM"]); time.sleep(0.2); ser.write(OP["START"]); time.sleep(0.2); ser.write(OP["SAFE"]); time.sleep(0.2)
    ser.reset_input_buffer(); print("✅ Roomba is awake, silent, and ready for commands.")
except Exception as e: print(f"❌ Roomba init failed: {e}"); ser = None

# --- NEW: ROOMBA KEEP-ALIVE THREAD ---
def roomba_keep_alive():
    """
    Sends a SAFE command to the Roomba every 45 seconds to prevent it
    from going into standby mode while waiting for AI commands.
    """
    global ser
    while True:
        time.sleep(45) # Wait 45 seconds
        if ser:
            try:
                with lock:
                    print("...sending keep-alive ping to Roomba...")
                    ser.write(OP["SAFE"])
            except Exception as e:
                print(f"⚠️ Keep-alive failed: {e}")

def find_and_init_camera():
    for i in range(10):
        print(f"Initializing camera index {i}...")
        temp_cam = cv2.VideoCapture(i)
        if temp_cam and temp_cam.isOpened():
            temp_cam.set(cv2.CAP_PROP_FRAME_WIDTH, WIDTH); temp_cam.set(cv2.CAP_PROP_FRAME_HEIGHT, HEIGHT); time.sleep(1.5)
            print(f"✅ Camera initialized successfully on index {i}."); return temp_cam
    return None
try:
    cam = find_and_init_camera()
    if cam is None: raise RuntimeError("Could not find any working camera.")
except Exception as e: print(f"❌ Camera init failed: {e}"); cam = None

def get_ultrasonic_distance_cm():
    try:
        GPIO.setup(PIN_TRIGGER, GPIO.OUT)
        GPIO.output(PIN_TRIGGER, GPIO.LOW)
        time.sleep(0.05)
        GPIO.output(PIN_TRIGGER, GPIO.HIGH)
        time.sleep(0.00001)
        GPIO.output(PIN_TRIGGER, GPIO.LOW)
        GPIO.setup(PIN_ECHO, GPIO.IN)
        start_time = time.time()
        timeout = start_time + 0.04
        while GPIO.input(PIN_ECHO) == 0:
            if time.time() > timeout: return 999.0
        pulse_start = time.time()
        timeout = pulse_start + 0.04
        while GPIO.input(PIN_ECHO) == 1:
            if time.time() > timeout: return 999.0
        pulse_end = time.time()
        pulse_duration = pulse_end - pulse_start
        distance_cm = (pulse_duration * 34300) / 2
        return distance_cm
    except Exception as e:
        print(f"[Ultrasonic] Read failed: {e}")
        return 999.0

# (API Endpoints remain unchanged)
@app.route('/image')
def image():
    if not cam: return jsonify(error='camera-offline'), 503
    with lock:
        for _ in range(3): cam.read()
        ok, frame = cam.read()
        if not ok: return jsonify(error='frame-grab-failed'), 500
        ok, buf = cv2.imencode('.jpg', frame, [cv2.IMWRITE_JPEG_QUALITY, JPEG_Q])
        if not ok: return jsonify(error='jpeg-encoding-failed'), 500
    return jsonify(image_base64=base64.b64encode(buf).decode('utf-8'))

@app.route('/get_ultrasonic_distance', methods=["POST", "GET"])
def get_ultrasonic_distance_route():
    try:
        dist = get_ultrasonic_distance_cm()
        return jsonify(distance_cm=round(dist, 2), status="ok")
    except Exception as e:
        return jsonify(distance_cm=999.0, status="error", error=str(e)), 500

@app.route('/status')
def status():
    if not ser: return jsonify(error='roomba-offline'), 503
    with lock:
        try:
            ser.reset_input_buffer(); ser.write(bytes([OP["SENSORS"], 21])); time.sleep(0.05)
            data = ser.read(1); is_docked = (data[0] != 0) if data else False
            return jsonify(battery_percent=100.0, docked=is_docked)
        except Exception as e: return jsonify(battery_percent=100.0, docked=True, error=str(e))
@app.route('/undock', methods=['POST'])
def undock():
    if not ser: return jsonify(error='roomba-offline'), 503
    with lock:
        try:
            ser.write(OP["FULL"]); time.sleep(0.2)
            drive_pkt = struct.pack('>Bhh', OP["DRIVE_DIRECT"], -DRIVE_SPEED, -DRIVE_SPEED); ser.write(drive_pkt); time.sleep(1.5)
            stop_pkt = struct.pack('>Bhh', OP["DRIVE_DIRECT"], 0, 0); ser.write(stop_pkt)
            ser.write(OP["SAFE"]); time.sleep(0.2)
            return jsonify(status="undock sequence complete")
        except Exception as e: return jsonify(error=str(e)), 500
@app.route('/vacuum', methods=['POST'])
def vacuum():
    if not ser: return jsonify(error='roomba-offline'), 503
    with lock:
        try:
            data=request.get_json() or {}; is_on=data.get("on", False)
            motors_byte = 0b00000111 if is_on else 0b00000000
            vacuum_pkt = struct.pack('BB', OP["MOTORS"], motors_byte); ser.write(vacuum_pkt)
            print(f"Vacuum motors turned {'ON' if is_on else 'OFF'}")
            return jsonify(status=f"vacuum {'on' if is_on else 'off'}")
        except Exception as e: return jsonify(error=str(e)), 500
@app.route('/bumper')
def get_bumper():
    if not ser: return jsonify(error='roomba-offline'), 503
    with lock:
        try:
            ser.reset_input_buffer(); ser.write(bytes([OP["SENSORS"], 7])); time.sleep(0.05)
            data = ser.read(1); is_pressed = bool(data[0] & 0b00000011) if data else False
            return jsonify(bumped=is_pressed)
        except Exception as e: return jsonify(bumped=False, error=str(e))
@app.route('/move', methods=['POST'])
def move():
    if not ser: return jsonify(error='roomba-offline'), 503
    data=request.get_json() or {}; maneuver=data.get('maneuver','stop'); duration=float(data.get('duration',0))
    mapping={'forward':(DRIVE_SPEED,DRIVE_SPEED),'backward':(-DRIVE_SPEED,-DRIVE_SPEED),'left':(-TURN_SPEED,TURN_SPEED),'right':(TURN_SPEED,-TURN_SPEED),'stop':(0,0)}
    right_vel, left_vel = mapping.get(maneuver,(0,0))
    with lock:
        try:
            ser.write(OP["SAFE"]); time.sleep(0.05)
            drive_pkt = struct.pack('>Bhh', OP["DRIVE_DIRECT"], right_vel, left_vel); ser.write(drive_pkt)
            if duration > 0: time.sleep(duration)
            # Important: Explicitly stop after timed maneuver
            stop_pkt = struct.pack('>Bhh', OP["DRIVE_DIRECT"], 0, 0); ser.write(stop_pkt)
            return jsonify(status=f"executed {maneuver}")
        except Exception as e: return jsonify(error=str(e)), 500

def cleanup_on_shutdown():
    print("Server shutting down. Cleaning up GPIO...")
    GPIO.cleanup()

if __name__ == '__main__':
    atexit.register(cleanup_on_shutdown)
    if ser is None or cam is None:
        print('🚫 Missing hardware; API will error out.')
    else:
        # Start the keep-alive thread as a daemon
        keep_alive_thread = threading.Thread(target=roomba_keep_alive, daemon=True)
        keep_alive_thread.start()
        print('✅ Server ready for Orange Pi. Keep-alive thread started.')
    
    app.run(host='0.0.0.0', port=5000, threaded=True)
