"""
!!!WAŻNE KOD DZIAŁA NA FIZYCZNYM URZĄDZENIU
IoT Lab 03 - Zadanie 2.1: Sensor z interfejsem IP
WiFi + Ethernet (W5500) - sterownik wbudowany
Polaczenia W5500:
- CS -> GPIO 5
- SCK -> GPIO 18
- MISO -> GPIO 19
- MOSI -> GPIO 23
- RST -> GPIO 21
- INT -> GPIO 22
- VCC -> 3.3V
- GND -> GND
Czujnik wilgotnosci:
- SIG -> GPIO 4
- VCC -> 3.3V
- GND -> GND
"""
import machine
import network
import socket
import time
# === KONFIGURACJA PINOW ===
# Czujnik
WATER_SENSOR_PIN = 4
# W5500
CS_PIN = 5
SCK_PIN = 18
MISO_PIN = 19
MOSI_PIN = 23
RST_PIN = 21
INT_PIN = 22
SPI_BUS = 2
# WiFi
WIFI_SSID = "IoT_Lab"$
WIFI_PASSWORD = "IronManLamus"
print("=" * 70)
print("IoT Lab 03 - Zadanie 2.1: Sensor WiFi + Ethernet")
print("=" * 70)
# === INICJALIZACJA CZUJNIKA ===
water_sensor = machine.Pin(WATER_SENSOR_PIN, machine.Pin.IN)
def read_sensor():
val = water_sensor.value()
status = "MOKRO" if val == 1 else "SUCHO"
return status, val
print("Czujnik wilgotnosci: GPIO " + str(WATER_SENSOR_PIN))
# === INICJALIZACJA ETHERNET ===
def init_ethernet():
print("\n[ETH] Startuje Ethernet W5500...")
try:
# Reset sprzetowy
rst = machine.Pin(RST_PIN, machine.Pin.OUT)
rst.value(0)
time.sleep(0.1)
rst.value(1)
time.sleep(0.2)
# SPI
spi = machine.SPI(SPI_BUS, baudrate=2000000, polarity=0, phase=0,
sck=machine.Pin(SCK_PIN),
mosi=machine.Pin(MOSI_PIN),
miso=machine.Pin(MISO_PIN))
print("[ETH] Piny: CS=" + str(CS_PIN) + ", SCK=" + str(SCK_PIN) +
", MISO=" + str(MISO_PIN) + ", MOSI=" + str(MOSI_PIN) +
", RST=" + str(RST_PIN) + ", INT=" + str(INT_PIN))
# Sprawdz czy sterownik W5500 jest dostepny
if not hasattr(network, 'PHY_W5500'):
print("[ETH] BLAD: Brak sterownika W5500 w MicroPythonie!")
print("[ETH] Twoja wersja MicroPython nie obsluguje W5500")
return None
# Inicjalizacja LAN z W5500
nic = network.LAN(0,
phy_type=network.PHY_W5500,
phy_addr=0,
spi=spi,
cs=machine.Pin(CS_PIN),
int=machine.Pin(INT_PIN, machine.Pin.IN, machine.Pin.PULL_UP))
# Unikalny MAC z ESP32
mac = machine.unique_id()
nic.config(mac=mac)
print("[ETH] Aktywuje interfejs...")
nic.active(True)
print("[ETH] Probuje DHCP (moze potrwac do 120s)...")
nic.ifconfig('dhcp')
# Czekaj na IP
timeout = 120
start = time.time()
while not nic.isconnected():
time.sleep(0.5)
print(".", end="")
if time.time() - start > timeout:
print("\n[ETH] TIMEOUT DHCP - brak odpowiedzi")
print("[ETH] Sprawdz: kabel Ethernet podlaczony?")
return None
print("\n[ETH] OK! Polaczono przez DHCP")
eth_config = nic.ifconfig()
print("[ETH] IP: " + eth_config[0])
print("[ETH] Subnet: " + eth_config[1])
print("[ETH] Gateway: " + eth_config[2])
print("[ETH] DNS: " + eth_config[3])
return nic
except Exception as e:
print("[ETH] BLAD inicjalizacji: " + str(e))
import sys
sys.print_exception(e)
return None
# === INICJALIZACJA WiFi ===
def init_wifi():
print("\n[WiFi] Laczenie z siecia: " + WIFI_SSID + "...")
try:
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
timeout = 15
for i in range(timeout):
if wlan.isconnected():
break
time.sleep(1)
print(".", end="")
print()
if wlan.isconnected():
wifi_config = wlan.ifconfig()
print("[WiFi] OK! Polaczono")
print("[WiFi] IP: " + wifi_config[0])
print("[WiFi] Gateway: " + wifi_config[2])
return wlan
else:
print("[WiFi] BLAD: Nie mozna polaczyc")
return None
except Exception as e:
print("[WiFi] BLAD: " + str(e))
return None
# === INICJALIZACJA INTERFEJSOW ===
eth = init_ethernet()
wifi = init_wifi()
wifi_ip = None
eth_ip = None
if wifi and wifi.isconnected():
wifi_ip = wifi.ifconfig()[0]
print("WiFi: OK -> http://" + wifi_ip)
else:
print("WiFi: BLAD")
if eth and eth.isconnected():
eth_ip = eth.ifconfig()[0]
print("Ethernet: OK -> http://" + eth_ip)
print(" Pinguj: ping " + eth_ip)
else:
print("Ethernet: BLAD - sprawdz kabel i polaczenia")
if not wifi_ip and not eth_ip:
print("\n[BLAD] Zaden interfejs nie dziala!")
print("Nie mozna uruchomic serwera HTTP.")
else:
print("\nUruchamianie serwera HTTP...")
# === SERWER HTTP ===
def create_html(status, value, wifi_ip, eth_ip):
html = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sensor IoT - ESP32</title>
<meta http-equiv="refresh" content="5"
</head>
<body>
<div>
<h1>Czujnik Wilgotnosci IoT</h1>
<div>
<p>Status czujnika:</p>
<div>""" + status + """</div>
<p>Wartosc cyfrowa: """ + str(value) + """</p>
</div>
<div>
<p>Interfejsy sieciowe:</p>
<p><strong>WiFi:</strong> """ + (wifi_ip if wifi_ip else "Nieaktywne") + """</p>
<p><strong>Ethernet (W5500):</strong> """ + (eth_ip if eth_ip else "Nieaktywne") + """</p>
</div>
</div>
</body>
</html>"""
return html
# Uruchom serwer HTTP
if wifi_ip or eth_ip:
try:
server = socket.socket()
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('0.0.0.0', 80))
server.listen(1)
print("\n[HTTP] Serwer uruchomiony na porcie 80")
print("[HTTP] Czekam na polaczenia...\n")
while True:
try:
cl, addr = server.accept()
print("[HTTP] Polaczenie od: " + str(addr[0]))
# Odczytaj zadanie
request = cl.recv(1024)
# Odczyt czujnika
status, value = read_sensor()
print("[SENSOR] " + status + " (" + str(value) + ")")
# Generuj HTML
html = create_html(status, value, wifi_ip, eth_ip)
# Wyslij odpowiedz
response = "HTTP/1.1 200 OK\r\n"
response += "Content-Type: text/html; charset=utf-8\r\n"
response += "Connection: close\r\n"
response += "Content-Length: " + str(len(html)) + "\r\n"
response += "\r\n"
response += html
cl.send(response.encode('utf-8'))
cl.close()
print("[HTTP] Odpowiedz wyslana\n")
except OSError as e:
print("[HTTP] Blad polaczenia: " + str(e))
try:
cl.close()
except:
pass
continue
except KeyboardInterrupt:
print("\n\n[STOP] Zatrzymywanie serwera...")
server.close()
print("Serwer zatrzymany.")
except Exception as e:
print("\n[BLAD] " + str(e))
import sys
sys.print_exception(e)
else:
print("\n[INFO] Serwer HTTP nie moze byc uruchomiony - brak polaczenia sieciowego")