1

I'd like to run a http server and a USB-Serial button box key press watcher in the same script. To poll the button box for a response, there is a loop endlessly polling "did anything happen yet." (poll_for_response() + has_response())

On Linux, this goes as expected -- both components appear to respond independently.

On Windows, the function with the tight loop runs well but the http side is unresponsive. adding asyncio.sleep() with an impossibly small wait time to the inner loop unblocks http.

Is this expected? Is there a better way forward? Response timing precision is a concern.


#!/usr/bin/env python
import asyncio
import sys
from tornado.httpserver import HTTPServer
from tornado.web import RequestHandler, Application

# using pyxid2 and class wrapper IRL
DEV = CEDRUS_USB_SERIAL_BUTTON_BOX_FD2XXX

class HttpTTL(RequestHandler):
    def get(self, msg):
        self.write(f"{msg}")

def http_run():
    app = Application([('/(.*)', HttpTTL)])
    server = HTTPServer(app)
    server.listen(4444)

async def watch():
    while True:
        # TIGHT LOOP. polling for button box responses
        # percision timing is important
        while not DEV.has_response():
            DEV.poll_for_response()
            # needed on windows, not on linux?
            await asyncio.sleep(.0001)

        # have response ready to do things with it
        resp = DEV.get_next_response()
        print(resp)
        sys.stdout.flush()


async def main():
    # without sleep in watch() http is nonresponsive
    http_run()
    await asyncio.create_task(watch())

asyncio.run(main())
Will
  • 1,206
  • 9
  • 22

0 Answers0