belyalov / tinyweb

Simple and lightweight HTTP async server for micropython
MIT License
247 stars 40 forks source link

How to run (in proper way) second function in parallel? #23

Closed mvincm closed 4 years ago

mvincm commented 4 years ago

Hello,

Thanks for your code. Nice job!

I have one question. I'm looking for a proper method to run a function in parallel to web server. I would like to check every 30 seconds my temperature and send values to MQTT server. This should be independent of normal web server activity. What is the best way to do this (assuming that I would like to use uasyncio as tinyweb do).

Best regards, MvincM

mvincm commented 4 years ago

My way below (based on hello_world example). Is is correct?

async def simple_loop_one():
    i = 0
    global th_1_i
    while True:
        i += 1
        th_1_i = i
        print("thread one: ",i)
        await asyncio.sleep(5)

async def simple_loop_two():
    i = 0
    global th_2_i
    while True:
        i += 1
        th_2_i = i
        print("thread two: ",i)
        await asyncio.sleep(10)

def run():
    app.loop.create_task(simple_loop_one())
    app.loop.create_task(simple_loop_two())
    app.run(host='0.0.0.0', port=8081)
belyalov commented 4 years ago

Hi @mvincm

Thanks for warm words.. :)

That seems correct to me. The only thing to mention - your mqtt client implementation must be async friendly, otherwise it will block entire process (there are no threads in micropython, at least it was as of 2017).

Regards

mvincm commented 4 years ago

Hello.

Thanks for tip about mqtt. I will try.

About threads. If you are talking about my strings from function "thread one/two", it is only a name/ text ;) As far as I know, Threads in micropython are in the experimental stage but there is one micropython webserver project on github which is based on threads (but it is to havey for esp8266).

Your project looks very good for my needs. It's light and fast, REEST API out of the box, usefull examples. I have build my own firmware for esp8266 (with uasyncio, logging, tinyweb) - pretty small and I have space for some other stuff. Now is time for MQTT and driver for W5500 (ethernet shield for esp8266 - SPI communication).

Once again thanks!

belyalov commented 4 years ago

BTW, something reminded me that few years ago I was looking for good mqtt micropython implementation but wasn't able to found working one.

So I did simple mqtt client https://github.com/belyalov/tinymqtt - you may found it somewhere useful, but there is no documentation / examples etc.

Nowadays I switched all my hobby projects to use STM32 with pure C :)

Good luck with your projects! :)

mvincm commented 4 years ago

Hello,

About mqtt client. Thanks for this! Please see an "issue" on tinymqtt github. Some questions to you ;)

About STM32. I'm still on esp8266 and Micropython stage and for now, it is enough for me ;)

Once again thanks for your time and help.