pyserial阅读串口在烧瓶(也许使用gevent) [英] pyserial reading serial port in flask (maybe using gevent)

查看:229
本文介绍了pyserial阅读串口在烧瓶(也许使用gevent)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个网络服务器,它需要读取(并保持读取)它运行的机器的串行端口。

目的是能够读取条码扫描器,并使用服务器发送的事件用读取的条形码更新浏览器。

我正在使用烧瓶来做到这一点。我浏览过,有些实现只需要烧瓶,有些人说我需要像Gevent这样的异步库,有些人甚至说我需要Gevent和Redis或RabbitMQ等类似的队列。

我试着将我的代码放在一个非常简单的例子上,我在stackoverflow上找到此处。我主要工作,但我坚持一些问题;


  • 在Chrome中有一个交叉原点错误,通过添加一个
    Access-Control-Allow-Origin头文件我可以在FireFox中使用
    ,但Chrome仍然无法运行。是否正确,只有FF支持
    SSE跨源?我需要它来支持CORS,因为浏览器
    需要从一个单独的机器加载条形码数据。
  • 每条消息后,浏览器显示控制台中的条形码,但
    然后关闭连接,并在大约3
    秒后再次打开它。这似乎是来自Flask,它给了我
    的数据,然后停止。

  • 另外,我想知道如何在负载下执行。我的意思是,烧瓶
    保持连接为文本/事件流mimetype打开。如果
    多个客户端连接,不会在一段时间后阻塞烧瓶,因为
    所有的连接都会饱和吗?


    我的代码如下(为了清晰起见缩短)

    服务器端:

    <$ p $从瓶子进口烧瓶
    进口烧瓶
    进口系列
    $ b $ app =烧瓶(__ name__)
    app.debug =真

    def event_barcode():
    ser = serial.Serial()
    ser.port = 0
    ser.baudrate = 9600
    ser.bytesize = 8
    ser.parity = serial.PARITY_NONE
    ser.stopbits = serial.STOPBITS_ONE
    ser.open()
    s = ser.read(7)
    yield'data:%s \\\
    \\\
    '%s

    @ app.route('/ barcode')
    def barcode():
    newresponse = flask.Response(event_barcode(),
    newresponse.headers.add('Access-Control-Allow-Origin','*')
    return newresponse

    if __name__ =='__main__':
    app.run (port = 8080,threaded = True)

    客户端:

     <!DOCTYPE HTML> 
    < html>
    < head>
    < meta http-equiv = Content-Type content =text / html; charset = utf-8>
    < title> TEST< / title>
    < script src =https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.jstype =text / javascriptcharset =utf-8 >< /脚本>
    < script>
    $ b $(document).ready(function(){
    if(!! window.EventSource){
    console.log('SSE supported。');
    )var source = new EventSource('http:// localhost:8080 / barcode');

    source.addEventListener('message',function(e){
    console.log(e .data);
    },false);

    source.addEventListener('open',function(e){
    console.log('Connection was opened。');
    ,false);

    source.addEventListener('error',function(e){
    if(e.readyState == EventSource.CLOSED){
    console.log('Connection was closed。');
    }
    },false);

    } else {
    console.log('SSE notsupported'。 );
    }
    });

    < / script>
    < / head>

    < body>

    < / body>
    < / html>

    我在这里查看更多信息:
    http://www.socketubs.net/2012/10/28/Websocket_with_flask_and_gevent/
    http://sdiehl.github.com/gevent-tutorial/#chat-server



    我希望有人能够澄清我的问题,也许可以指出我的一些解决方案,针对交叉来源和3秒延迟问题。

    谢谢。

    解决方案


    $ b


    1. 看来,现在确实只有Firefox支持SSE的CORS - >
      article

    2. 在Janus Troelsen的帮助下,我想出了如何保持
      连接打开并发送se (见代码
      以下)

    3. 性能方面,似乎我只能建立一个连接,但
      可能是因为我只有一个串口,随后的
      连接不能再打开串口了。我认为它可以在烧瓶上工作
      ,但是用socketio和gevents的话可以更好地工作
      ,因为它更适合工作。 此处有一篇有趣的
      文章。

    代码:

      import flask 
    导入序列
    从时间导入睡眠

    app = flask.Flask(__ name__)
    app.debug = True

    def event_barcode() :
    messageid = 0
    ser = serial.Serial()
    ser.port = 0
    ser.baudrate = 9600
    ser.bytesize = 8
    ser.parity = serial.PARITY_NONE
    ser.stopbits = serial.STOPBITS_ONE
    ser.timeout = 0
    try:
    ser.open()
    serial.SerialException ,e:
    yield'event:error \\\
    '+'data:'+'串口错误({0}):{1} \\\
    \\\
    '.format(e.errno,e .strerror)
    messageid = messageid + 1
    str_list = []
    while:
    sleep(0.01)
    nextchar = ser.read()
    如果nextchar:
    str_list.append(nextchar)
    else:
    if len(str_list)> 0:
    yield'id:'+ str(messageid)+'\\\
    '+'data:'+''.join(str_list)+'\\\
    \\\
    '
    messageid = messageid + 1
    str_list = []

    @ app.route('/ barcode')
    def barcode():
    newresponse = flask.Response(event_barcode ),mimetype =text / event-stream)
    newresponse.headers.add('Access-Control-Allow-Origin','*')
    newresponse.headers.add('Cache-Control ','no-cache')
    return newresponse

    if __name__ =='__main__':
    app.run(port = 8080,threaded = True)

    因为我想支持多个浏览器,所以SSE现在不适合我。我将研究websockets并尝试从中获益。


    I'm building a webserver that would need to read (and keep reading) the serial port of the machine it's running on.
    The purpose is to be able to read a barcode scanner, and using Server-Sent Events to update a browser with the read barcode.

    I'm using flask to do this. I've browsed around and some implementations require only flask, some say I would need an async library like Gevent, and some others even say I'd need Gevent and some sort of queue like Redis or RabbitMQ.

    I've tried to base my code on a very simple example I found on stackoverflow here. I have it mostly working, but I am stuck with some questions;

    • In Chrome there is a cross-origin error, by adding an Access-Control-Allow-Origin header I can get it to work in FireFox, but Chrome still doesn't work. Is it correct that only FF supports SSE cross-origin? I need it to support CORS because the browser will need to load the barcode data from a separate machine.
    • After each message, the browser shows the barcode in the console, but it then closes the connection and only opens it again after about 3 seconds. It seems that this originates in Flask, it gives me the data and then just stops.
    • Also, I'm wondering how this will perform under load. I mean, flask keeps a connection open for the text/event-stream mimetype. If multiple clients connect, won't it block flask after a while, because all of the connections will be saturated?

    My code is as follow (shortened for clarity)

    Server-side:

    from flask import Flask
    import flask
    import serial
    
    app = Flask(__name__)
    app.debug = True
    
    def event_barcode():
        ser = serial.Serial()
        ser.port = 0
        ser.baudrate = 9600
        ser.bytesize = 8
        ser.parity = serial.PARITY_NONE
        ser.stopbits = serial.STOPBITS_ONE
        ser.open()
        s = ser.read(7)
        yield 'data: %s\n\n' % s
    
    @app.route('/barcode')
    def barcode():
        newresponse = flask.Response(event_barcode(), mimetype="text/event-stream")
        newresponse.headers.add('Access-Control-Allow-Origin', '*')
        return newresponse
    
    if __name__ == '__main__':
        app.run(port=8080, threaded=True)
    

    Client-side:

        <!DOCTYPE HTML>
    <html>
    <head>
        <meta http-equiv=Content-Type content="text/html; charset=utf-8">
        <title>TEST</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript" charset="utf-8"></script>
        <script>
    
            $(document).ready(function(){
                if (!!window.EventSource) {
                    console.log('SSE supported.');
                    var source = new EventSource('http://localhost:8080/barcode');
    
                    source.addEventListener('message', function(e) {
                      console.log(e.data);
                    }, false);
    
                    source.addEventListener('open', function(e) {
                      console.log('Connection was opened.');
                    }, false);
    
                    source.addEventListener('error', function(e) {
                      if (e.readyState == EventSource.CLOSED) {
                        console.log('Connection was closed.');
                      }
                    }, false);
    
                } else {
                    console.log('SSE notsupported.');
                }
            });
    
        </script>
    </head>
    
    <body>
    
    </body>
    </html>
    

    There is some more information I was looking at here: http://www.socketubs.net/2012/10/28/Websocket_with_flask_and_gevent/ http://sdiehl.github.com/gevent-tutorial/#chat-server

    I hope someone can clear up my questions, and maybe point me towards some solutions, for the cross-origin and the 3 second delay problem.

    Thanks.

    解决方案

    Answering my own questions

    1. It seems that indeed only Firefox supports CORS for SSE for now -> article
    2. With help from Janus Troelsen I figured out how to keep the connection open and send several barcodes across the line (see code below)
    3. Performance-wise it seems that I can only make one connection, but that might be because I have only one serial port, the subsequent connections can't open the serial port anymore. I think it will work from flask, but something with socketio and gevents will perfom better because it's more suited for the job. There's an interesting article here.

    For the code:

    import flask
    import serial
    from time import sleep
    
    app = flask.Flask(__name__)
    app.debug = True
    
    def event_barcode():
        messageid = 0
        ser = serial.Serial()
        ser.port = 0
        ser.baudrate = 9600
        ser.bytesize = 8
        ser.parity = serial.PARITY_NONE
        ser.stopbits = serial.STOPBITS_ONE
        ser.timeout = 0
        try:
            ser.open()
        except serial.SerialException, e:
             yield 'event:error\n' + 'data:' + 'Serial port error({0}): {1}\n\n'.format(e.errno, e.strerror)
             messageid = messageid + 1
        str_list = []
        while True:
            sleep(0.01)
            nextchar = ser.read()
            if nextchar:
                str_list.append(nextchar)
            else:
                if len(str_list) > 0:
                    yield 'id:' + str(messageid) + '\n' + 'data:' + ''.join(str_list) + '\n\n'
                    messageid = messageid + 1
                    str_list = []
    
    @app.route('/barcode')
    def barcode():
        newresponse = flask.Response(event_barcode(), mimetype="text/event-stream")
        newresponse.headers.add('Access-Control-Allow-Origin', '*')
        newresponse.headers.add('Cache-Control', 'no-cache')
        return newresponse
    
    if __name__ == '__main__':
        app.run(port=8080, threaded=True)
    

    Because I want to support multiple browsers, SSE is not the way to go for me right now. I will look into websockets and try and work from that.

    这篇关于pyserial阅读串口在烧瓶(也许使用gevent)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆