Created
April 25, 2024 15:13
-
-
Save jepler/f479119ce7526d95106b1db924df92ac to your computer and use it in GitHub Desktop.
This file contains 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 gc | |
import os | |
import ssl | |
from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K | |
import adafruit_connection_manager | |
from digitalio import DigitalInOut | |
import board | |
import busio | |
cs = DigitalInOut(board.W5500_CS) | |
reset = DigitalInOut(board.W5500_RST) | |
spi_bus = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) | |
# Initialize ethernet interface with DHCP | |
radio = WIZNET5K(spi_bus, cs, reset=reset) | |
# Initialize a requests session | |
pool = adafruit_connection_manager.get_radio_socketpool(radio) | |
HOST = "" # see below | |
PORT = 443 | |
BACKLOG = 2 | |
MAXBUF = 256 | |
def resp(body): | |
r = b"HTTP/1.1 200 OK\r\n" | |
r += b"Content-Length: {}\r\n".format(len(body)) | |
r += b"\r\n" | |
r += body | |
return r | |
#time.sleep(3) # wait for serial | |
HOST = str(radio.pretty_ip(radio.ip_address)) | |
print("Create TCP Server socket", (HOST, PORT)) | |
s = pool.socket(pool.AF_INET, pool.SOCK_STREAM) | |
ssl_context = ssl.create_default_context() | |
ssl_context.load_verify_locations(cadata="") | |
ssl_context.load_cert_chain("cert.pem", "key.pem") | |
ss = ssl_context.wrap_socket(s, server_side=True) | |
ss.bind((HOST, PORT)) | |
ss.listen(BACKLOG) | |
print("Listening\n") | |
buf = bytearray(MAXBUF) | |
while True: | |
print(f"Accepting connections (mem={gc.mem_free()})") | |
conn, addr = ss.accept() | |
print("Accepted from", addr) | |
try: | |
conn.settimeout(None) | |
size = conn.recv_into(buf, MAXBUF) | |
print("Received", buf[:size], size, "bytes") | |
conn.send(resp(b"nano-https-server")) | |
print(f"Sent response (mem={gc.mem_free()})\n") | |
finally: | |
conn.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment