Created
August 31, 2022 02:03
-
-
Save anecdata/06045da4eb109e7467d9e8068a8dffad to your computer and use it in GitHub Desktop.
CircuitPython mDNS finder for ESP32-S2/S3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import wifi | |
import ipaddress | |
import socketpool | |
import mdns | |
from secrets import secrets | |
MDNSFINDTIMEOUT = 5 | |
pool = socketpool.SocketPool(wifi.radio) | |
def connect(): | |
# to connect in case CP8 web workflow hasn't already, or to reconnect if disconnexted | |
if not wifi.radio.ipv4_address: | |
print (f"Connecting to wifi AP ... ", end="") | |
wifi.radio.connect(secrets["ssid"], secrets["password"]) | |
print (f"{wifi.radio.ipv4_address}") | |
print(f"Starting mDNS server ...\n") | |
m = mdns.Server(wifi.radio) | |
while True: | |
connect() | |
print(f"Finding mDNS hosts from {wifi.radio.ipv4_address} ...\n") | |
try: | |
host = "circuitpython.local" | |
print(f"{host}") | |
# ESP mDNS TTL seems to be 2 minutes | |
# no difference in result with wrong port | |
print(f"{ipaddress.ip_address(pool.getaddrinfo(host, 80)[0][4][0])}") | |
print() | |
except OSError as e: | |
print(f"OSError: {e}") # OSError: -2 | |
for service in m.find(service_type="_circuitpython", protocol="_tcp", timeout=MDNSFINDTIMEOUT): | |
print(f"{service.service_type} {service.protocol}") | |
print(f"{service.instance_name}") | |
localname = ".".join((service.hostname, "local")) | |
print(f"{localname}:{service.port}") | |
print(f"{service.ipv4_address}:{service.port}") | |
print() | |
time.sleep(15) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment