Passing serial data to javascript via Flask

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-22 09:53:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!