feat(driver): discover controller via udp and rediscover on reconnect
Made-with: Cursor
This commit is contained in:
27
src/main.py
27
src/main.py
@@ -10,6 +10,7 @@ import time
|
||||
import select
|
||||
import socket
|
||||
import ubinascii
|
||||
from hello import discover_controller_udp
|
||||
|
||||
BROADCAST_MAC = b"\xff\xff\xff\xff\xff\xff"
|
||||
CONTROLLER_TCP_PORT = 8765
|
||||
@@ -122,14 +123,13 @@ sta_if.active(True)
|
||||
sta_if.config(pm=network.WLAN.PM_NONE)
|
||||
|
||||
mac = sta_if.config("mac")
|
||||
hello = {
|
||||
hello_payload = {
|
||||
"v": "1",
|
||||
"device_name": settings.get("name", ""),
|
||||
"mac": ubinascii.hexlify(mac).decode().lower(),
|
||||
"type": "led",
|
||||
}
|
||||
hello_bytes = json.dumps(hello).encode("utf-8")
|
||||
hello_line = hello_bytes + b"\n"
|
||||
hello_bytes = json.dumps(hello_payload).encode("utf-8")
|
||||
|
||||
if settings["transport_type"] == "espnow":
|
||||
sta_if.disconnect()
|
||||
@@ -152,6 +152,22 @@ elif settings["transport_type"] == "wifi":
|
||||
while not sta_if.isconnected():
|
||||
time.sleep(1)
|
||||
print(f"WiFi connected {sta_if.ifconfig()[0]}")
|
||||
controller_ip = discover_controller_udp(
|
||||
device_name=settings.get("name", ""),
|
||||
wdt=wdt,
|
||||
)
|
||||
if not controller_ip:
|
||||
raise SystemExit("No controller IP discovered for Wi-Fi transport")
|
||||
|
||||
def pick_controller_ip(current):
|
||||
ip = discover_controller_udp(
|
||||
device_name=settings.get("name", ""),
|
||||
wdt=wdt,
|
||||
)
|
||||
if ip and ip != current:
|
||||
print("Controller IP updated to", ip)
|
||||
return ip if ip else current
|
||||
|
||||
reconnect_ms = 1000
|
||||
next_connect_at = 0
|
||||
client = None
|
||||
@@ -165,8 +181,7 @@ elif settings["transport_type"] == "wifi":
|
||||
c = None
|
||||
try:
|
||||
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
c.connect((settings["server_ip"], CONTROLLER_TCP_PORT))
|
||||
c.send(hello_line)
|
||||
c.connect((controller_ip, CONTROLLER_TCP_PORT))
|
||||
c.setblocking(False)
|
||||
p = select.poll()
|
||||
p.register(c, select.POLLIN)
|
||||
@@ -180,6 +195,7 @@ elif settings["transport_type"] == "wifi":
|
||||
c.close()
|
||||
except Exception:
|
||||
pass
|
||||
controller_ip = pick_controller_ip(controller_ip)
|
||||
next_connect_at = utime.ticks_add(now, reconnect_ms)
|
||||
|
||||
if client is not None and poller is not None:
|
||||
@@ -221,6 +237,7 @@ elif settings["transport_type"] == "wifi":
|
||||
client = None
|
||||
poller = None
|
||||
buf = b""
|
||||
controller_ip = pick_controller_ip(controller_ip)
|
||||
next_connect_at = utime.ticks_add(now, reconnect_ms)
|
||||
|
||||
presets.tick()
|
||||
|
||||
Reference in New Issue
Block a user