Last active
December 5, 2025 18:29
-
-
Save dupontgu/de375cff8c64f20372105d79833c13fc to your computer and use it in GitHub Desktop.
CircuitPython WiFi HTTP Sensor Template
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 socketpool | |
| import wifi | |
| import mdns | |
| from adafruit_httpserver import (GET, JSONResponse, Request, Server) | |
| WIFI_SSID = "your-wifi" | |
| WIFI_PASSWORD = "your-password" | |
| POLL_INTERVAL_S = 31 | |
| PORT = 9001 | |
| global_data = { | |
| "temperature": 70, | |
| "unit": "f" | |
| } | |
| def update_readings(): | |
| # You would actually poll your sensor here | |
| global_data["temperature"] = 69 # nice | |
| def connect_wifi(): | |
| for attempt in range(3): | |
| try: | |
| wifi.radio.connect(WIFI_SSID, WIFI_PASSWORD) | |
| print("WiFi connected!") | |
| return True | |
| except Exception as e: | |
| print(f"WiFi attempt {attempt + 1} failed: {e}") | |
| if attempt < 2: | |
| time.sleep(2) | |
| return False | |
| update_readings() | |
| last_update = time.monotonic() | |
| if not connect_wifi(): | |
| # idk restart or something if you want | |
| pass | |
| mdns_server = mdns.Server(wifi.radio) | |
| # you'll be able to hit http://sensor_name.local:[PORT]/sensor to get the data as JSON | |
| mdns_server.hostname = "sensor_name" | |
| mdns_server.advertise_service(service_type="_http", protocol="_tcp", port=PORT) | |
| pool = socketpool.SocketPool(wifi.radio) | |
| server = Server(pool, debug=True) | |
| @server.route("/sensor", [GET], append_slash=True) | |
| def api(request: Request): | |
| return JSONResponse(request, global_data) | |
| server.start(str(wifi.radio.ipv4_address), PORT) | |
| while True: | |
| try: | |
| if (time.monotonic() - last_update > POLL_INTERVAL_S): | |
| update_readings() | |
| last_update = time.monotonic() | |
| pool_result = server.poll() | |
| except OSError as error: | |
| print(error) | |
| continue |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment