使用HTTP请求运行Micropython运行的WeMos D1 mini(ESP8266)引脚

时间:2018-01-05 06:16:11

标签: http esp8266 micropython

我想要最终实现的是控制我的车库门开启器,其中一个继电器连接到WeMos D1 Mini,连接到我家的WiFi。我正在使用openGarageDoor()函数。串行连接一切正常。

我一直在尝试使用this script在WeMos D1 Mini上运行HTTP服务器。

    customertagsAction() -- try:
    import usocket as socket
except:
    import socket


CONTENT = b"""\
HTTP/1.0 200 OK
Hello #%d from MicroPython!
"""

def main(micropython_optimize=False):
    s = socket.socket()

    # Binding to all interfaces - server will be accessible to other hosts!
    ai = socket.getaddrinfo("0.0.0.0", 8080)
    print("Bind address info:", ai)
    addr = ai[0][-1]

    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(addr)
    s.listen(5)
    print("Listening, connect your browser to http://<this_host>:8080/")

    counter = 0
    while True:
        res = s.accept()
        client_sock = res[0]
        client_addr = res[1]
        print("Client address:", client_addr)
        print("Client socket:", client_sock)

        if not micropython_optimize:
            # To read line-oriented protocol (like HTTP) from a socket (and
            # avoid short read problem), it must be wrapped in a stream (aka
            # file-like) object. That's how you do it in CPython:
            client_stream = client_sock.makefile("rwb")
        else:
            # .. but MicroPython socket objects support stream interface
            # directly, so calling .makefile() method is not required. If
            # you develop application which will run only on MicroPython,
            # especially on a resource-constrained embedded device, you
            # may take this shortcut to save resources.
            client_stream = client_sock

        print("Request:")
        req = client_stream.readline()
        print(req)
        while True:
            h = client_stream.readline()
            if h == b"" or h == b"\r\n":
                break
            print(h)
        client_stream.write(CONTENT % counter)

        client_stream.close()
        if not micropython_optimize:
            client_sock.close()
        counter += 1
        print()


main()

正确接收请求,并在print()上显示GET变量。我能做的最好的是

req = client_stream.readline()
    print(req)
    while True:
        h = client_stream.readline()
        if h == b"" or h == b"\r\n":
            break
        print(h)
    client_stream.write(CONTENT % counter)
    //my function here:
    if 'opengaragedoor=1' in req:
        openGarageDoor()
    client_stream.close()

我不知道如何正确解析请求。我只想出这个肮脏的解决方案。这可能会导致请求系统超时,因为Postman等需要等待函数运行。

0 个答案:

没有答案