问题
I've been poking around with pushing data from Flask to Javascript, mainly by modifying the code found here: https://github.com/clebio/flask-d3
Now I'm trying to read data from a COM Port and pass it through Flask to Javascript. I've done some of this before using PySerial, but am not sure the right way to approach combining it into Flask.
I feel comfortable implementing something where, with each request, the port is opened, reads a line, and is closed.
That's not very efficient, so ideally I would be able to open the COM port once, run a readline when Flask receives a request from the client, and close only when it receives a command to explicitly do so. I suspect this involves threading, but that is outside of my experience. Any thoughts?
回答1:
I've done something similar using Tornado for an Arduino + Raspberry Pi project:
https://github.com/lilspikey/train
Basically I would run a separate thread to read from the serial port and then decode the data, before sending it as JSON data via websockets.
You could probably do something similar. Just store the data you've read somewhere that can later be read by the Flash app. This could be a simple in memory data structure (will need to be threadsafe) or as complex as writing it to a database. You'd need to make sure you removed old data as it gets read by the Flash app, but that would be the crux of it.
来源:https://stackoverflow.com/questions/34881133/passing-serial-data-to-javascript-via-flask