Skip to content

Instantly share code, notes, and snippets.

@anecdata
Last active April 1, 2024 04:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anecdata/1fd8d799fd9dc42ddea35a8f3dd8594e to your computer and use it in GitHub Desktop.
Save anecdata/1fd8d799fd9dc42ddea35a8f3dd8594e to your computer and use it in GitHub Desktop.
Changing the port for an MDNS service-protocol
# SPDX-FileCopyrightText: 2024 anecdata
#
# SPDX-License-Identifier: MIT
# > service_type and protocol can only occur on one port. Any call after the first will update the entry’s port.
# https://docs.circuitpython.org/en/latest/shared-bindings/mdns/index.html#mdns.Server.advertise_service
'''
1. Start up with web workflow enabled https://docs.circuitpython.org/en/latest/docs/workflows.html#web
2. Commandeer the Web Workflow MDNS HTTP Server service-protocol onto a new port
3. run an MDNS-enabled HTTP Server on the new port in code.py
4. Relinquish the code.py MDNS service-protocol back to the Web Workflow port
5. Web Workflow is operational again
'''
import wifi
import socketpool
import mdns
import adafruit_httpserver
from adafruit_httpserver import Server, Request, Response
PORT = 8080 # make sure this is different from settings.toml CIRCUITPY_WEB_API_PORT
def connect():
while not wifi.radio.connected:
print (f"Connecting to wifi AP...")
try:
wifi.radio.connect(os.getenv('WIFI_SSID'), os.getenv('WIFI_PASSWORD'))
except Exception as ex:
traceback.print_exception(ex, ex, ex.__traceback__)
print (f"{wifi.radio.ipv4_address=}")
time.sleep(3) # wait for serial
connect()
mdns_server = mdns.Server(wifi.radio)
mdns_server.hostname = "hostname-code-py"
print(f"http://{mdns_server.hostname}.local.:{PORT}")
# change the mdns_server to the new port for _http._tcp, and serve the device IP address:port
try:
mdns_server.advertise_service(service_type="_http", protocol="_tcp", port=PORT)
except RuntimeError as ex:
traceback.print_exception(ex, ex, ex.__traceback__)
pool = socketpool.SocketPool(wifi.radio)
http_server = Server(pool, "/static", debug=True)
@http_server.route("/")
def base(request: Request):
return Response(request, f"code.py HTTP Server http://{wifi.radio.ipv4_address}:{PORT}")
http_server.start(str(wifi.radio.ipv4_address), port=PORT)
start = time.monotonic_ns()
while time.monotonic_ns() < (start + 15_000_000_000):
connect()
http_server.poll()
# OK, we allowed 15 seconds after reset to advertise the IP address, so change the mdns_server back to the web workflow port
http_server.stop()
try:
mdns_server.advertise_service(service_type="_http", protocol="_tcp", port=os.getenv("CIRCUITPY_WEB_API_PORT"))
except RuntimeError as ex:
traceback.print_exception(ex, ex, ex.__traceback__)
while True:
# now, do the real work here...
print(".", end="")
time.sleep(15)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment