Проблемы с заголовком ответа сервера pico W ⇐ Python
-
Anonymous
Проблемы с заголовком ответа сервера pico W
Я пытался настроить небольшой сервер, на котором я мог бы в реальном времени определять значения всех контактов GPIO на pico pi. Сначала я нашел этот пример, который работал отлично, затем я добавил функцию в добавьте состояния контактов GPIO в html после некоторых вещей, которые у меня заработали, но я не сохранил их. И теперь не могу понять, как заставить его работать.
Строка, в которой я получаю: OSError -1
< р> conn.send(f'HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
Например, я также пробовал другие заголовки:
conn.send(f'HTTP/1.0 200 OK\r\nContent-type: text/html\r\nContent-Length: {len(response)}\r\n\r\n')
Но ни один из них, похоже, не работал
Весь код для справки:
# Import necessary modules
import network
import socket
import time
import random
from machine import Pin
# Create an LED object on pin 'LED'
led = Pin('LED')
# Wi-Fi credentials
ssid = 'SSID'
password = 'PASWORD'
def get_gpio_states():
gpio_html = ""
for pin_number in range(0, 28): # Adjust based on your setup
pin = Pin(pin_number, Pin.IN) # Set GPIO as input
state = pin.value() # Read GPIO state
gpio_html += f"{pin_number}{state}"
return gpio_html
# HTML template for the webpage
def webpage(random_value, state,gpio_states):
gpio_states =gpio_states
html = f"""
Pico Web Server
Raspberry Pi Pico Web Server
Led Control
LED state: {state}
Fetch New Value
Fetched value: {random_value}
GPIO States
GPIO Pin
State
{gpio_states}
"""
return str(html)
# Connect to WLAN
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
# Wait for Wi-Fi connection
connection_timeout = 20
while connection_timeout > 0:
if wlan.status() >= 3:
break
connection_timeout -= 1
print('Waiting for Wi-Fi connection...')
time.sleep(1)
# Check if connection is successful
if wlan.status() != 3:
raise RuntimeError('Failed to establish a network connection')
else:
print('Connection successful!')
network_info = wlan.ifconfig()
print('IP address:', network_info[0])
# Set up socket and start listening
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen()
#print('Listening on', addr)
# Initialize variables
state = "OFF"
random_value = 0
# Main loop to listen for connections
while True:
try:
conn, addr = s.accept()
print('Got a connection from', addr, conn)
# Receive and parse the request
request = conn.recv(1024)
request = str(request)
print('Request content,',repr(request))
if len(request) == 0:
print('Received empty request')
continue # Skip to the next iteration of the loop
try:
request = request.split()[1]
print('Request:', request)
except IndexError as e:
print(e)
continue
# Process the request and update variables
if request == '/lighton?':
print("LED on")
led.on()
state = "ON"
#response = "ON"
elif request == '/lightoff?':
led.off()
state = 'OFF'
elif request == '/value?':
random_value = random.randint(0, 20)
elif request == '/': # Handle the root request
#response = "Welcome to the pico web server"
random_value = 0 # Set default random value if needed
elif request == '/favicon.ico':
print("Favicon requested, ignoring.")
continue # Skip further processing for favicon
# Generate HTML response
gpio_states = get_gpio_states()
response = webpage(random_value, state, gpio_states)
# Send the HTTP response and close the connection
conn.send(f'HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
conn.send(response)
finally:
print('conn closed')
conn.close()
Подробнее здесь: https://stackoverflow.com/questions/790 ... r-problems
Я пытался настроить небольшой сервер, на котором я мог бы в реальном времени определять значения всех контактов GPIO на pico pi. Сначала я нашел этот пример, который работал отлично, затем я добавил функцию в добавьте состояния контактов GPIO в html после некоторых вещей, которые у меня заработали, но я не сохранил их. И теперь не могу понять, как заставить его работать.
Строка, в которой я получаю: OSError -1
< р> conn.send(f'HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
Например, я также пробовал другие заголовки:
conn.send(f'HTTP/1.0 200 OK\r\nContent-type: text/html\r\nContent-Length: {len(response)}\r\n\r\n')
Но ни один из них, похоже, не работал
Весь код для справки:
# Import necessary modules
import network
import socket
import time
import random
from machine import Pin
# Create an LED object on pin 'LED'
led = Pin('LED')
# Wi-Fi credentials
ssid = 'SSID'
password = 'PASWORD'
def get_gpio_states():
gpio_html = ""
for pin_number in range(0, 28): # Adjust based on your setup
pin = Pin(pin_number, Pin.IN) # Set GPIO as input
state = pin.value() # Read GPIO state
gpio_html += f"{pin_number}{state}"
return gpio_html
# HTML template for the webpage
def webpage(random_value, state,gpio_states):
gpio_states =gpio_states
html = f"""
Pico Web Server
Raspberry Pi Pico Web Server
Led Control
LED state: {state}
Fetch New Value
Fetched value: {random_value}
GPIO States
GPIO Pin
State
{gpio_states}
"""
return str(html)
# Connect to WLAN
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
# Wait for Wi-Fi connection
connection_timeout = 20
while connection_timeout > 0:
if wlan.status() >= 3:
break
connection_timeout -= 1
print('Waiting for Wi-Fi connection...')
time.sleep(1)
# Check if connection is successful
if wlan.status() != 3:
raise RuntimeError('Failed to establish a network connection')
else:
print('Connection successful!')
network_info = wlan.ifconfig()
print('IP address:', network_info[0])
# Set up socket and start listening
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen()
#print('Listening on', addr)
# Initialize variables
state = "OFF"
random_value = 0
# Main loop to listen for connections
while True:
try:
conn, addr = s.accept()
print('Got a connection from', addr, conn)
# Receive and parse the request
request = conn.recv(1024)
request = str(request)
print('Request content,',repr(request))
if len(request) == 0:
print('Received empty request')
continue # Skip to the next iteration of the loop
try:
request = request.split()[1]
print('Request:', request)
except IndexError as e:
print(e)
continue
# Process the request and update variables
if request == '/lighton?':
print("LED on")
led.on()
state = "ON"
#response = "ON"
elif request == '/lightoff?':
led.off()
state = 'OFF'
elif request == '/value?':
random_value = random.randint(0, 20)
elif request == '/': # Handle the root request
#response = "Welcome to the pico web server"
random_value = 0 # Set default random value if needed
elif request == '/favicon.ico':
print("Favicon requested, ignoring.")
continue # Skip further processing for favicon
# Generate HTML response
gpio_states = get_gpio_states()
response = webpage(random_value, state, gpio_states)
# Send the HTTP response and close the connection
conn.send(f'HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
conn.send(response)
finally:
print('conn closed')
conn.close()
Подробнее здесь: https://stackoverflow.com/questions/790 ... r-problems