import uasyncio as asyncio
import json
import machine
from machine import Pin
import network
# --- CONFIGURAZIONE PIN (Esempio per 10 timer) ---
# Ingressi: Pin 1, 2, 4, 5, 6, 7, 8, 9, 10, 11
# Uscite: Pin 12, 13, 14, 15, 16, 17, 18, 21, 38, 39
IN_PINS = [1, 2, 4, 5, 6, 7, 8, 9, 10, 11]
OUT_PINS = [12, 13, 14, 15, 16, 17, 18, 21, 38, 39]
CONFIG_FILE = 'config.json'
# --- FUNZIONI DI SISTEMA ---
def load_config():
try:
with open(CONFIG_FILE, 'r') as f:
return json.load(f)
except:
# Se il file non esiste, crea un default per 10 timer
default = {}
for i in range(10):
default[str(i)] = {
"mode": "TON", # TON, TOFF, TONOFF, PULSE
"t_on": 2000, # ms
"t_off": 2000, # ms
"p_on": 500, # ms (per modalità PULSE)
"p_off": 500 # ms
}
return default
# --- LOGICA CORE DEI TIMER ---
async def run_timer(id, cfg):
in_pin = Pin(IN_PINS[int(id)], Pin.IN, Pin.PULL_UP)
out_pin = Pin(OUT_PINS[int(id)], Pin.OUT)
print(f"Timer {id} attivo su IN:{IN_PINS[int(id)]} OUT:{OUT_PINS[int(id)]}")
while True:
is_pressed = not in_pin.value() # Pulsante premuto (Active Low)
mode = cfg['mode']
if mode == "TON":
if is_pressed:
await asyncio.sleep_ms(cfg['t_on'])
if not in_pin.value(): # Se ancora premuto dopo T_ON
out_pin.value(1)
else:
out_pin.value(0)
elif mode == "TOFF":
if is_pressed:
out_pin.value(1)
else:
await asyncio.sleep_ms(cfg['t_off'])
if in_pin.value(): # Se ancora rilasciato dopo T_OFF
out_pin.value(0)
elif mode == "PULSE":
if is_pressed:
out_pin.value(1)
await asyncio.sleep_ms(cfg['p_on'])
out_pin.value(0)
await asyncio.sleep_ms(cfg['p_off'])
else:
out_pin.value(0)
await asyncio.sleep_ms(20) # Risparmio CPU e debounce
# --- AVVIO CONNESSIONE (WOKWI GUEST) ---
async def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('Wokwi-GUEST', '')
while not wlan.isconnected():
await asyncio.sleep(1)
print('Connesso! IP:', wlan.ifconfig()[0])
# --- MAIN ---
async def main():
# 1. Carica configurazione
config = load_config()
# 2. Connetti al Wi-Fi (Necessario per il Web Server su Wokwi)
await connect_wifi()
# 3. Avvia i 10 Task dei Timer
tasks = []
for t_id, cfg in config.items():
tasks.append(asyncio.create_task(run_timer(t_id, cfg)))
# 4. Avvia il Web Server (simulato qui o importato da web_server.py)
# import web_server
# tasks.append(asyncio.create_task(web_server.app.start(port=80)))
print("Tutti i 10 temporizzatori sono in esecuzione...")
await asyncio.gather(*tasks)
try:
asyncio.run(main())
except KeyboardInterrupt:
print("Sistema arrestato")