No Example for uasyncio SSL webserver

Discussion about programs, libraries and tools that work with MicroPython. Mostly these are provided by a third party.
Target audience: All users and developers of MicroPython.
Post Reply
Asanga
Posts: 3
Joined: Tue Jan 12, 2021 4:26 am

No Example for uasyncio SSL webserver

Post by Asanga » Tue Jan 12, 2021 4:31 am

Hi,
I am looking for example code for uasyncio SSL webserver. I went through every example in micropython-lib-master and internet. Still, I didn't manage to run uasyncio SSL webserver. I am looking for support.
Thanks.

cbrand
Posts: 8
Joined: Fri Jan 01, 2021 5:49 pm

Re: No Example for uasyncio SSL webserver

Post by cbrand » Thu Jan 14, 2021 11:25 am

I don't think uasyncio supports this yet directly. However, the socket creation is a plain python wrapper around the "normal" socket:
https://github.com/micropython/micropyt ... eam.py#L74

So you can replicate an asyncio socket by just doing what uasyncio does itself.

Code: Select all

import uasyncio
from uasyncio.stream import Stream
from uasyncio import core
from uerrno import EINPROGRESS
import usocket as socket
import ussl as ssl

async def open_connection(host, port):
    ai = socket.getaddrinfo(host, port)[0]  # TODO this is blocking!
    s = socket.socket()
    s.setblocking(False)
    ssls = ussl.wrap_socket(s)  # Wrap raw socket in SSL socket
    ss = Stream(ssls)
    try:
        s.connect(ai[-1])
    except OSError as er:
        if er.args[0] != EINPROGRESS:
            raise er
    yield core._io_queue.queue_write(s)
    return ss, ss
 

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: No Example for uasyncio SSL webserver

Post by pythoncoder » Fri Jan 15, 2021 10:15 am

I don't think it's that simple. See roadmap to V1.14 which includes as an aim:
non-blocking SSL support in uasyncio
While I may be wrong or out of date, my understanding is that nonblocking sockets don't yet work with SSL/TLS. I believe they do work on the Pyboard D.
Peter Hinch
Index to my micropython libraries.

Asanga
Posts: 3
Joined: Tue Jan 12, 2021 4:26 am

Re: No Example for uasyncio SSL webserver

Post by Asanga » Sun Jan 17, 2021 11:23 pm

Thank you, everyone.
Sorry for forgot it. Actually, I am trying to work with ESP8266. I tried this code in ESP8266. But getting error like below.

"Traceback (most recent call last):
File "main.py", line 2, in <module>
ImportError: no module named 'uasyncio.stream'
MicroPython v1.12 on 2019-12-20; ESP module with ESP8266
"

I spent much time on this and got my sample code working. But, it holds the asyncio other routines of the code while receiving the request.

Code: Select all

import uasyncio as asyncio
from uasyncio import core
import ussl as ssl
import network
import uos

async def start_server(address, port):
    s = socket.socket()
    ai = socket.getaddrinfo(address, port, 0, socket.SOCK_STREAM)
    print("Bind address info:", ai)
    addr = ai[0][-1]
    s.setblocking(False)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(addr)
    s.listen(5)
    print("Listening, connect your browser to https://<this_host>:5978")
    counter = 0
    while True:
        print("\n\nwait for request")
        yield core.IORead(s) 
        s.settimeout(1)
        res =  s.accept()
        client_s = res[0]
        client_addr = res[1]
        print("Client address:", client_addr)
        print("Client socket:", client_s)
        # CPython uses key keyfile/certfile arguments, but MicroPython uses key/cert
        client_s = ssl.wrap_socket(
            client_s, server_side=True, key=key, cert=cert)
        print(client_s)
        print("Request:")
        try:
            req = client_s.readline()
            print(str(req))
            while True:
                h = client_s.readline()
                if h == b"" or h == b"\r\n":
                    break
                print(str(h))
            if req:
                client_s.write(CONTENT1 % counter)
                #yield from writer.awrite( CONTENT1 % counter )
        except Exception as e:
            print("Exception serving request:", e)
        client_s.close()
        counter += 1
        print()
        await asyncio.sleep_ms(1)

CONTENT1 = b"""\
HTTP/1.0 200 OK

Hello #%d from MicroPython!
"""

def main( ):

         loop = asyncio.get_event_loop()
         loop.create_task(start_server(ipaddress, port))
         loop.run_forever()
         loop.close()
main()
Could you comment on this sample code? I know this code is not the perfect one ;) .

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: No Example for uasyncio SSL webserver

Post by pythoncoder » Mon Jan 18, 2021 9:55 am

Calls to client_s.readline() are blocking. Consider using StreamReader. However I have no experience of using this with SSL/TLS on ESP8266. I think it should work as it uses polling on a blocking socket.
Peter Hinch
Index to my micropython libraries.

cbrand
Posts: 8
Joined: Fri Jan 01, 2021 5:49 pm

Re: No Example for uasyncio SSL webserver

Post by cbrand » Mon Jan 18, 2021 2:17 pm

Asanga wrote:
Sun Jan 17, 2021 11:23 pm
Thank you, everyone.
Sorry for forgot it. Actually, I am trying to work with ESP8266. I tried this code in ESP8266. But getting error like below.

"Traceback (most recent call last):
File "main.py", line 2, in <module>
ImportError: no module named 'uasyncio.stream'
MicroPython v1.12 on 2019-12-20; ESP module with ESP8266
"
Hm not quite sure. you can replace Stream with uasyncio.StreamReader as it is the same interface. I only have an ESP32 but it worked fine there.

Asanga
Posts: 3
Joined: Tue Jan 12, 2021 4:26 am

Re: No Example for uasyncio SSL webserver

Post by Asanga » Tue Jan 19, 2021 11:31 pm

Thank you, everyone. I tried to work with stream and to edit asyncio library. But didn't do well. For now, I should wait for the implementation of ssl/ttl socket for asyncio ESP8266 library.

Post Reply