import camera
import network
import socket
import time

# ---------- Wi-Fi Setup ----------
ssid = 'KRISHTEC'
password = 'KRISHtec@5747'

sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(ssid, password)

while not sta_if.isconnected():
    pass

print("📶 Connected to Wi-Fi:", sta_if.ifconfig())

# ---------- Camera Init ----------
def init_camera():
    try:
        if camera.init():
            print("✅ Camera initialized")
            return True
        else:
            print("❌ Camera init failed")
            return False
    except Exception as e:
        print("⚠️ Camera error:", e)
        return False

# ---------- Web Server with MJPEG Stream ----------
def start_stream_server():
    addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]

    s = socket.socket()
    s.bind(addr)
    s.listen(1)

    print("🌐 MJPEG stream server running at:", addr)

    while True:
        cl, addr = s.accept()
        print("👤 Client connected from", addr)

        request = cl.recv(1024)
        request = str(request)

        if "/stream" in request:
            print("🔁 Starting MJPEG stream...")

            cl.send("HTTP/1.1 200 OK\r\n")
            cl.send("Content-Type: multipart/x-mixed-replace; boundary=frame\r\n\r\n")

            try:
                while True:
                    img = camera.capture()
                    if img:
                        cl.send("--frame\r\n")
                        cl.send("Content-Type: image/jpeg\r\n")
                        cl.send("Content-Length: {}\r\n\r\n".format(len(img)))
                        cl.send(img)
                        cl.send("\r\n")
                        time.sleep(0.1)  # small delay to reduce load
                    else:
                        print("❌ Failed to capture image")
                        break
            except Exception as e:
                print("⚠️ Streaming error:", e)
            finally:
                cl.close()
                print("📴 Client disconnected from stream")

        else:
            # Serve a simple HTML page to view the stream
            response = """\
HTTP/1.1 200 OK

<html>
    <head><title>ESP32-CAM Stream</title></head>
    <body>
        <h2>ESP32-CAM Live Stream</h2>
        <img src="/stream" style="width: 100%; max-width: 480px;" />
    </body>
</html>
"""
            cl.send(response)
            cl.close()

# ---------- Run ----------
if init_camera():
    start_stream_server()
else:
    print("❌ Could not start stream server")


