[Python] pico W server response header problems

Discussão em 'Python' iniciado por Stack, Outubro 1, 2024.

  1. Stack

    Stack Membro Participativo


    I tried to set up a small server on which I could live detect the value of all the GPIO pins on the pico pi W first I found this example which worked perfectly then i added the function to add the states of the GPIO pins to the html after some stuff I made it work but I did not save it. And now I can not figure out how to get it to work. Line where I get: OSError -1
    ​

    conn.send(f'HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')

    I also tried a different headers for example:

    conn.send(f'HTTP/1.0 200 OK\r\nContent-type: text/html\r\nContent-Length: {len(response)}\r\n\r\n')

    But None of them seemed to work

    Whole code for reference:


    # 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"<tr><td>{pin_number}</td><td>{state}</td></tr>"
    return gpio_html
    # HTML template for the webpage

    def webpage(random_value, state,gpio_states):
    gpio_states =gpio_states
    html = f"""
    <html>
    <head>
    <title>Pico Web Server</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
    <h1>Raspberry Pi Pico Web Server</h1>
    <h2>Led Control</h2>
    <form action="./lighton">
    <input type="submit" value="Light on">
    </form><br>
    <form action="./lightoff">
    <input type="submit" value="Light off">
    </form>
    <p>LED state: {state}</p>
    <h2>Fetch New Value</h2>
    <form action="./value">
    <input type="submit" value="Fetch value">
    </form>
    <p>Fetched value: {random_value}</p>
    <h1>GPIO States</h1>
    <table border="1">
    <tr>
    <th>GPIO Pin</th>
    <th>State</th>
    </tr>
    {gpio_states}
    </table>
    </body>
    </html>
    """
    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()

    Continue reading...

Compartilhe esta Página