jczic / MicroWebSrv2

The last Micro Web Server for IoTs (MicroPython) or large servers (CPython), that supports WebSockets, routes, template engine and with really optimized architecture (mem allocations, async I/Os). Ready for ESP32, STM32 on Pyboard, Pycom's chipsets (WiPy, LoPy, ...). Robust, efficient and documented!
https://github.com/jczic/MicroWebSrv2
MIT License
662 stars 97 forks source link

Scheduled background task feature request. #55

Open HH0718 opened 4 years ago

HH0718 commented 4 years ago

I apologize if this is the wrong place or if this is unrelated specifically to MicroWebSrv2.

I will be deploying an ESP32 and was hoping for to be a webserver and found your code.

Like Flask and Celery, is there a way to get MicroWebSrv2 to run scheduled tasks (such as monitoring IO sensors)?

Thanks for your awesome work!

dalymople commented 3 years ago

@HH0718 Unless I am missing something, you should be able to achieve this pretty simply? This package does its work in new thread/s, so you can just spawn the web server and carry on to do your sensor work?

I have modified the basic example below to update all connected web sockets with periodic data from a sensor. NB. this is untested

from MicroWebSrv2 import *
import time
import json

connected_sockets = []

def on_web_socket_accepted(_, web_socket):
    connected_sockets.append(web_socket)
    print(F'New WebSocket accepted from {web_socket.Request.UserAddress}.')

def on_text_message(web_socket, msg):
    print(F'New WebSocket message from {web_socket.Request.UserAddress} `{msg}`.')

def on_closed(web_socket):
    connected_sockets.remove(web_socket)
    print(F'WebSocket closed from {web_socket.Request.UserAddress}.')

def read_sensor_data():
    # customise to read data from your sensor
    return {'sensor_1': 1, 'sensor_2': 2}

mws2 = MicroWebSrv2()
wsMod = MicroWebSrv2.LoadModule('WebSockets')
wsMod.OnWebSocketAccepted = on_web_socket_accepted
wsMod.OnTextMessage = on_text_message
wsMod.onClosed = on_closed
mws2.StartManaged()

try:
    while True:
        while time.time() % 10:
            time.sleep(0.01)

        data = read_sensor_data()

        for socket in connected_sockets:
            socket.SendTextMessage(json.dumps(data))

        time.sleep(1) # to prevent re-triggering immediately. There are probably better ways to achieve this

except KeyboardInterrupt:
    mws2.Stop()