-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcode.py.bkp
More file actions
81 lines (66 loc) · 2.71 KB
/
Copy pathcode.py.bkp
File metadata and controls
81 lines (66 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import wifi
import socketpool
import time
# set access point credentials
ap_ssid = "myap"
ap_password = "password123" # not used
# Function to start the access point
def start_access_point():
# Stop any existing access point
try:
wifi.radio.stop_ap()
time.sleep(1) # Allow some time for it to shut down
except Exception as e:
print("Error stopping access point:", e)
# Start the access point
try:
wifi.radio.start_ap(ssid=ap_ssid, password=ap_password)
time.sleep(5) # Give it some time to start properly
print("Access point created with SSID: {}, password: {}".format(ap_ssid, ap_password))
print("My IP address is", str(wifi.radio.ipv4_address_ap))
except Exception as e:
print("Error starting access point:", e)
start_access_point()
# create a socket pool
pool = socketpool.SocketPool(wifi.radio)
# function to read html content from a file
def read_html_file(file_name):
try:
with open(file_name, 'r') as f:
return f.read()
except Exception as e:
print(f"error reading file: {e}")
return "<html><body><h1>error loading page</h1></body></html>"
# create a simple http server function
def simple_http_server():
server_socket = pool.socket()
try:
# Bind the server socket to the Pico's IP address and port 80
server_socket.bind(("0.0.0.0", 80))
server_socket.listen(1)
print("server is listening on {}:80".format(wifi.radio.ipv4_address_ap))
while True:
print("waiting for a connection...")
client_socket, client_address = server_socket.accept()
print("accepted connection from:", client_address)
try:
buffer = bytearray(1024) # Create a buffer for reading the request
bytes_received = client_socket.recv_into(buffer) # Read the HTTP request into the buffer
request = buffer[:bytes_received].decode("utf-8") # Decode the received bytes
print("Request received:", request)
except Exception as e:
print("Error reading request:", e)
# HTTP response
http_response = "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n"
html_content = read_html_file('index.html')
# Send the response headers and content
client_socket.sendall(http_response.encode("utf-8"))
client_socket.sendall(html_content.encode("utf-8"))
# Close the client socket
client_socket.close()
print("response sent to:", client_address)
finally:
print("Closing server socket...")
server_socket.close()
# start the http server
simple_http_server()