import network, time, ubinascii, machine
from umqtt.simple import MQTTClient
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASS = ""
BROKER = "test.mosquitto.org"
UID = ubinascii.hexlify(machine.unique_id()).decode()
CLIENT_ID = "kpi-node-" + UID
BASE = "iot/kpi/ia42-node13"
T_TELE = BASE + "/telemetry"
T_STATUS = BASE + "/status" # online / offline (Last Will)
T_CMD = BASE + "/cmd" # ON / OFF / BLINK
# варіант N = 13
BASE_DELAY = 2 # 1 + (13 mod 3)
FACTOR = 3 # 13 непарне
CAP = 35 # 20 + (13 mod 5) * 5
led = machine.Pin(2, machine.Pin.OUT)
def wifi_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
wlan.connect(WIFI_SSID, WIFI_PASS)
t0 = time.time()
while not wlan.isconnected():
if time.time() - t0 > 15: # тайм-аут
raise OSError("Wi-Fi timeout")
time.sleep(0.5)
print("Wi-Fi OK:", wlan.ifconfig()[0])
return wlan
def blink(times=3):
state = led.value()
for i in range(times):
led.value(1)
print("blink", i + 1)
time.sleep(0.5)
led.value(0)
time.sleep(0.5)
led.value(state) # повертаємо попередній стан
def on_command(topic, msg):
cmd = msg.decode().strip().upper()
print("CMD:", cmd)
if cmd == "ON":
led.value(1)
elif cmd == "OFF":
led.value(0)
elif cmd == "BLINK": # команда варіанта (13 mod 3 = 1)
blink(3)
# невідому команду ігноруємо
print("LED =", led.value())
def mqtt_connect():
c = MQTTClient(CLIENT_ID, BROKER, keepalive=30)
c.set_last_will(T_STATUS, b"offline", retain=True, qos=1)
c.set_callback(on_command)
c.connect()
c.publish(T_STATUS, b"online", retain=True, qos=1)
c.subscribe(T_CMD, qos=1)
print("MQTT OK, subscribed to", T_CMD)
return c
def backoff_delay(attempt):
return min(BASE_DELAY * (FACTOR ** attempt), CAP)
def read_sensor():
import urandom
return 20 + urandom.getrandbits(4) / 10
def run():
client = None
attempt = 0
last_pub = 0
while True:
try:
if client is None:
wifi_connect()
client = mqtt_connect()
attempt = 0 # успіх: скидаємо лічильник
client.check_msg()
if time.time() - last_pub >= 5:
payload = '{{"t": {:.1f}}}'.format(read_sensor())
client.publish(T_TELE, payload, qos=1)
print("PUB:", payload)
last_pub = time.time()
time.sleep(0.2)
except OSError as e:
delay = backoff_delay(attempt)
print("Link lost:", e, "-> retry in", delay, "s (attempt", attempt, ")")
try:
if client:
client.disconnect()
except Exception:
pass
client = None
time.sleep(delay)
attempt += 1
run()Loading
esp32-devkit-c-v4
esp32-devkit-c-v4