commit 3b1278cbe2fd3c4ac801d1e7493cf9d37c2fb037 Author: Luxferre Date: Sat Dec 20 12:48:06 2025 +0200 nethelper upload diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3b72af0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.env +__pycache__ diff --git a/nethelper.py b/nethelper.py new file mode 100644 index 0000000..19e907b --- /dev/null +++ b/nethelper.py @@ -0,0 +1,73 @@ +# T-Deck network helper library for CircuitPython +# Depends on some Adafruit Bundle libs +# Normal flow (provided Wi-Fi creds are in settings.toml): +# +# import nethelper +# status, stext, myip = nethelper.wifi_connect_wait() +# if status: +# requests = nethelper.init_requests() +# # or socket = nethelper.init_socket() if raw sockets are necessary +# while nethelper.my_ip(): +# ... +# +# Created by Luxferre in 2025, released into public domain + +import os, time # standard modules +import wifi # CircuitPython builtins +import adafruit_connection_manager, adafruit_requests # Adafruit Bundle libs + +def wifi_connect(ssid=None, password=None): + ''' + Connect to a Wi-Fi SSID + Use settings.toml for default credentials + ''' + ssid = ssid or os.getenv('CIRCUITPY_WIFI_SSID') + password = password or os.getenv('CIRCUITPY_WIFI_PASSWORD') + try: + wifi.radio.connect(ssid=ssid, password=password) + except ConnectionError as e: + return (False, e) + return (True, 'Connected') + +def my_ip(): + 'Get the local IP address' + return wifi.radio.ipv4_address + +def wifi_connect_wait(ssid=None, password=None, tmout=15, retries=3): + ''' + Connect to a Wi-Fi SSID and wait for successful connection + Usually, you'll want to use this function to connect + ''' + r = 0 + status = False + stext = '' + while not wifi.radio.ipv4_address and r < retries: + status, stext = wifi_connect(ssid, password) + if not status: + time.sleep(tmout) + r += 1 + if not status: + stext = 'Could not connect, out of attempts. Last error: ' + stext + return (status, stext, wifi.radio.ipv4_address) + +def wifi_scan(): + 'Scan for Wi-Fi networks (returns (SSID, rssi) tuple list from strongest to weakest)' + networks = [] + for network in wifi.radio.start_scanning_networks(): + networks.append(network) + wifi.radio.stop_scanning_networks() + networks = sorted(networks, key=lambda net: net.rssi, reverse=True) + return [(net.ssid, net.rssi) for net in networks] + +def ssl_context(): + 'Get the default SSL context for wrapping a raw socket' + return adafruit_connection_manager.get_radio_ssl_context(wifi.radio) + +def init_socket(): + 'Get a socket pool and instantiate a Socket library' + return adafruit_connection_manager.get_radio_socketpool(wifi.radio) + +def init_requests(): + 'Instantiate a Requests library' + return adafruit_requests.Session(init_socket(), ssl_context()) +