import time
import ujson
from machine import Pin, ADC
import dht
import socket
import network
import _thread
# CONEXIÓN A WIFI (SIMULADA)
def conectar_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Conectando a WiFi...")
wlan.connect("Wokwi-GUEST", "")
intentos = 0
while not wlan.isconnected():
time.sleep(0.3)
intentos += 1
print("Intento:", intentos)
if intentos > 20:
print("ERROR: No se pudo conectar al WiFi.")
return None
print("WiFi conectado!")
print("IP asignada:", wlan.ifconfig()[0])
return wlan
conectar_wifi()
# NODO PERIFERICO (SENSORES)
dht_sensor = dht.DHT22(Pin(15))
pir = Pin(4, Pin.IN)
ldr = ADC(Pin(34))
ldr.atten(ADC.ATTN_11DB)
def leer_sensores():
try:
dht_sensor.measure()
temperatura = dht_sensor.temperature()
humedad = dht_sensor.humidity()
except:
temperatura = None
humedad = None
movimiento = pir.value()
luz = ldr.read()
return {
"temperatura": temperatura,
"humedad": humedad,
"movimiento": movimiento,
"luz": luz
}
# NODO CENTRAL (WEB SERVER)
datos_nodo = {}
def generar_html():
d = datos_nodo
html = f"""
<html>
<head>
<meta http-equiv="refresh" content="1">
<style>
table, th, td {{ border:1px solid black; border-collapse:collapse; padding:6px; }}
</style>
</head>
<body>
<h2>Simulación – Nodo Central</h2>
<p><b>WiFi:</b> Conectado a Wokwi-GUEST</p>
<table>
<tr>
<th>Temperatura</th>
<th>Humedad</th>
<th>Movimiento</th>
<th>Luz</th>
</tr>
<tr>
<td>{d.get('temperatura')}</td>
<td>{d.get('humedad')}</td>
<td>{d.get('movimiento')}</td>
<td>{d.get('luz')}</td>
</tr>
</table>
</body>
</html>
"""
return html
def servidor_web():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 80))
s.listen(5)
print("Servidor web listo en http://0.0.0.0/")
while True:
conn, addr = s.accept()
request = conn.recv(1024)
response = generar_html()
conn.send("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n")
conn.sendall(response)
conn.close()
# Hilo para el servidor web
_thread.start_new_thread(servidor_web, ())
print("Simulación iniciada...")
# BUCLE PRINCIPAL
while True:
datos_nodo.update(leer_sensores())
print("Datos actualizados:", datos_nodo)
time.sleep(1)
void setup() {
Serial.begin(115200);
while (!Serial) {
delay(10); // wait for serial port to connect. Needed for native USB
}
// Now you can safely print message:
Serial.println("Hello, Serial Monitor!");
}