Simple HTTP server



  • I repurposed some generic micropython HTTP server code to run on the gpy

    import machine; from machine import Pin
    pins = [machine.Pin(i, machine.Pin.IN) for i in ('P23', 'P22', 'P21')]
    print (pins)
    html = """<!DOCTYPE html>
    <html>
        <head> <title>ESP8266 Pins</title> </head>
        <body> <h1>ESP8266 Pins</h1>
            <table border="1"> <tr><th>Pin</th><th>Value</th></tr> %s </table>
        </body>
    </html>
    """
    
    import socket
    addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
    
    s = socket.socket()
    s.bind(addr)
    s.listen(1)
    
    print('listening on', addr)
    
    while True:
        cl, addr = s.accept()
        print('client connected from', addr)
        cl_file = cl.makefile('rwb', 0)
        while True:
            line = cl_file.readline()
            if not line or line == b'\r\n':
                break
        rows = ['<tr><td>%s</td><td>%d</td></tr>' % (str(p), p.value()) for p in pins]
        response = html % '\n'.join(rows)
        cl.send(response)
        cl.close()
    

    It's supposed to show the status of the pins in a table but when I run it & try to login I get

    [Pin('P23', mode=Pin.IN, pull=None, alt=-1), Pin('P22', mode=Pin.IN, pull=None, alt=-1), Pin('P21', mode=Pin.IN, pull=None, alt=-1)]
    listening on ('0.0.0.0', 80)
    client connected from ('192.168.4.2', 58649)
    Traceback (most recent call last):
      File "<stdin>", line 26, in <module>
    ValueError: invalid argument(s) value
    

    I can't find any docs on makefile so I was wondering if anyone can tell me what the problem is with

    cl_file = cl.makefile('rwb', 0)
    


  • Spot on with the cl.makefile('wb') Eric, although I can't tell how you figured that out from that doc page. No matter it works now! If I change 'import socket' to 'import usocket as socket' it runs the same so the pycom library must have both?



  • According to documentation (https://docs.pycom.io/firmwareapi/micropython/usocket.html) makefile seem have only one argument and not two. Logically i don't know any system where when you have write acces you haven't read access, so i propose you to try

    cl_file = cl.makefile('wb')
    

    Please note that's "import usocket" and not "import socket" as in your code with pycom library, if you use a different lib have a look at your provider's library documentation


Log in to reply
 

Pycom on Twitter