WEB ESP32
main.py
import network
import time
from machine import Pin
#from led_driver import print_like_console , print_multiline_console
# === НАСТРОЙКИ WI-FI (Измени на свои!) ===
SSID = "ESP32HUB" # ←←← Впиши сюда имя своего Wi-Fi
PASSWORD = "A1b2c3d4" # ←←← Впиши сюда пароль
# === Пин светодиода ===
LED_PIN = 2 # встроенный светодиод на большинстве ESP32
led = Pin(LED_PIN, Pin.OUT)
led.off()
# === Подключаемся к Wi-Fi ===
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
print("Подключаюсь к Wi-Fi...", SSID)
while not wlan.isconnected():
time.sleep(0.5)
print(".", end="")
print("\nПодключено!")
print("IP-адрес:", wlan.ifconfig()[0])
# === HTML-страница (та же красивая) ===
html = """<!DOCTYPE html>
<html>
<head>
<title>ESP32 LED Control</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {font-family: Arial; text-align: center; padding: 50px; background: #1e1e1e; color: #fff;}
h1 {color: #00ff00;}
.button {padding: 20px 40px; font-size: 24px; margin: 20px; border-radius: 15px; border: none; color: white; cursor: pointer;}
.on {background: #4CAF50;}
.off {background: #f44336;}
#state {font-size: 32px; color: #00ff00;}
</style>
</head>
<body>
<h1>Управление светодиодом</h1>
<p>Состояние: <span id="state">?</span></p>
<button class="button on" onclick="send('on')">ВКЛЮЧИТЬ</button>
<button class="button off" onclick="send('off')">ВЫКЛЮЧИТЬ</button>
<script>
function send(cmd) {
fetch('/' + cmd)
.then(r => r.text())
.then(state => {
document.getElementById('state').innerText = state === '1' ? 'ВКЛЮЧЕН' : 'ВЫКЛЮЧЕН';
});
}
// Обновляем состояние при загрузке
fetch('/state').then(r => r.text()).then(s => {
document.getElementById('state').innerText = s === '1' ? 'ВКЛЮЧЕН' : 'ВЫКЛЮЧЕН';
});
</script>
</body>
</html>
"""
# === Запуск веб-сервера ===
import socket
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(5)
print(f"Веб-сервер запущен! Открой в браузере: http://{wlan.ifconfig()[0]}")
while True:
try:
cl, addr = s.accept()
request = cl.recv(1024).decode()
if 'GET / ' in request or request.startswith('GET / HTTP'):
response = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n\r\n" + html
cl.send(response)
elif 'GET /on' in request:
led.on()
print('on')
#print_like_console('ON', x=0, y=0, delay=0.05)
cl.send("HTTP/1.1 200 OK\r\n\r\n1")
elif 'GET /off' in request:
led.off()
print('off')
#print_like_console('OFF', x=0, y=0, delay=0.05)
cl.send("HTTP/1.1 200 OK\r\n\r\n0")
elif 'GET /state' in request:
state = "1" if led.value() else "0"
cl.send(f"HTTP/1.1 200 OK\r\n\r\n{state}")
else:
cl.send("HTTP/1.1 404 Not Found\r\n\r\n")
cl.close()
except Exception as e:
print("Ошибка:", e)
try:
cl.close()
except:
pass


Комментарии
Отправить комментарий