简体   繁体   中英

While Loop with time.sleep() without reloading page

I am setting a timer for some pumps on my raspberry pi from a website. When I enter how many seconds I want the pump on for I send an mqtt message to the pi to turn it on for the required time. However, if I do this without sleeping until the condition is met I send an excessive amount of mqtt messages to the pi. When I do this WITH the sleep in the code, my website is reloading the entire for the duration I entered. Does anyone have a more efficient way of approaching this problem?

   @app.route("/pump1_timer", methods=["GET", "POST"])
    def pump1_timer():
        if request.method == "POST":
            seconds = float(request.form.get('pump1_timer'))
            t_end = time.time() + (seconds)
            while time.time() <= t_end:
                publish.single("MY TOPIC", "pump1:on", hostname="MY IP")
                time.sleep(seconds)
            else:
                publish.single("MY TOPIC", "pump1:off", hostname="MY IP")
            return main1.html 

您的input需要name属性,而不是表单:

<input name="pump1_timer" ... />

I am new to programming and did not realize the beauty of asynchronous requests at the time of this question. For those that see this post and who are new to programming, these requests can be made using a language like javascript on the front end of your project to make a request without your page reloading and pausing while code runs...which is especially useful if the code uses time.sleep(). This is instead of using flask and built-in html form request methods to send information to and from the client and server.

So, I used this AJAX (javascript library) post method to send data. There are other ways to do this in javascript but I used this one for its simplicity. This can be used inside of a function so that it can send when a button is clicked etc...

$.post('/pump_timer', $('#pump1_timer').val().toString())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM