pyserial读取串口并在烧瓶中的网页上显示

时间:2017-08-20 08:22:41

标签: python flask runtime-error pyserial

我想在pyserial中使用Flask从串口读取和写入数据。我想通过网页来做到这一点。代码如下所示。我在网页上写数据没有任何问题,但我无法读取数据,我在阅读过程中遇到运行时错误。我该如何实施解决方案?

我实际上是在尝试从串口读取数据的所有方法。但我不知道哪种方式适合我。对于我来说,从串口向连接到网页的用户显示数据的最佳方法是什么?

我收到了错误消息:

   0
def serial runtime error
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 505, in run
    self.__target(*self.__args, **self.__kwargs)
  File "__init__.py", line 46, in serialRead
    return jsonify(result='serial runtime error')
  File "/usr/local/lib/python2.7/dist-packages/flask/json.py", line 251, in jsonify
    if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not request.is_xhr:
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 347, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 306, in _get_current_object
    return self.__local()
  File "/usr/local/lib/python2.7/dist-packages/flask/globals.py", line 51, in _find_app
    raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in a way.  To solve
this set up an application context with app.app_context().  See the
documentation for more information.

python代码:

 app = Flask(__name__)
    app.secret_key = "asds"

    @app.route('/run_write', methods=["GET","POST"])
def serialWrite():

            print "click"
            message="selam zafer"
            if request.method == "POST":
                attempted_writeData = request.form['writeData']
                message=attempted_writeData
            try:
                if seri.isOpen():
                    print "Serial is open!"
                    seri.write(message)
                    session['serial_write'] = True
                    flash(message+" mesajiniz gonderildi..",'write')
                    return redirect(url_for("usart"))
            except Exception as e:
                    session['serial_write'] = False
                    flash(message+" mesajiniz gonderilemedi...",'write')
                    return redirect(url_for("usart"))

def serialRead():
        data =""
#        seri = serial.Serial(port = "/dev/ttyO1", baudrate=9600) seri.close() seri.open()
        while 1:
                if seri.isOpen():
                 try:
#                       seri.write("hello")
                        data=seri.read()
                        print data
            if data:
                #flash(data,'read')
                return jsonify(result=data)
                 except RuntimeError:
                        print 'def serial runtime error'
                        return jsonify(result='serial runtime error')
                        seri.close()
                 except KeyboardInterrupt:
                        print 'def serial klavye hatasi'
                        seri.close()


@app.route('/background_process')
def background_process():
    try:
                print 'background '
        threadSerial = Thread(target=serialRead)
#       threadSerial.daemon = True
        threadSerial.start()
        return jsonify(result='serial runtime error')
    except Exception as e:
        flash(e)



@app.route('/')
def homepage():
    try:
        return render_template("pages/Beagle.html")
    except Exception as e:
        flash(e)

@app.route('/usart/',methods=["GET","POST"])
def usart():
    #return ("hi")
    if not seri.isOpen():
        flash("Seri baglanti kurulamadi",'connect')
        session['serial_con'] = False
    else:
        flash("Seri baglati basarili",'connect')
        session['serial_con'] = True

    return render_template("pages/usart.html")



if __name__ == "__main__":
    UART.setup("UART1")
    seri = serial.Serial(port = "/dev/ttyO1", baudrate=9600)
        seri.close()
        seri.open()

    try:

        app.run(host='0.0.0.0', port=8082)
    except SerialException as e:
        pass

和网页代码

   {% extends "pages/Beagle.html" %}

{% block body %}

<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script type=text/javascript>
            $(function() {
              $('a#process_input').bind('click', function() {
                $.getJSON('/background_process', function(data) {
                  $("#result").text(data.result);
                });
                return false;
              });
            });
        </script>

</head>

<body class="body">

  <div id="page-wrapper">
            <div class="row">
                <div class="col-lg-12">
                    <h1 class="page-header">BeagleBone Communation</h1>
                </div>
                <!-- /.col-lg-12 -->
            </div>
            <!-- /.row -->
            <div class="row">
                <div class="col-lg-12">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                             Usart Data
                        </div>
                        <div class="panel-body">
                            <div class="row">
                                <div class="col-lg-6">
                                 <div class="panel panel-default">
                                    <div class="panel-heading">
                                    Read Data BeagleBone
                                    </div>
                                        <div class="panel-body">
                                            <label>Send Data Input</label>
                                            <form class="form-signin" action="/run_write" method="post" role="form">
                                            <input name="writeData" class="form-control">
                                            <p class="help-block">Writing Data via USART on BeagleBone.</p>
                                            <button type="submit" class="btn btn-primary btn-lg btn-block">Send Button</button>
                                            {% with messages= get_flashed_messages(category_filter=["write"]) %}
                                            {% if messages %}
                                            {% for message in messages %}
                                              {% if session.serial_write %}
                                                 <div  class="alert alert-success alert-dismissible pull-right" role="alert" style="position: relative;"> 
                                                 <button type="button" class="close" data-dismiss="alert" aria-label="close"<span aria-hidden="true">&times;</span></button>
                                                 {% else %}
                                                  <div  class="alert alert-danger alert-dismissible pull-right" role="alert" style="position: relative;"> 
                                                 <button type="button" class="close" data-dismiss="alert" aria-label="close"<span aria-hidden="true">&times;</span></button>
                                                 {% endif %}
                                                 {{message}}
                                                 </div>
                                             {%endfor%}
                                             {% endif %}
                                             {% endwith %}
                                            </form>
                                        </div>  

                                        <!-- <button type="reset" class="btn btn-default">Reset Button</button> -->
                                    </div>
                                </div>
                                <!-- /.col-lg-6 (nested) -->
                                <div class="col-lg-6">

                    <div class="panel panel-default">
                            <div class="panel-heading">
                            Read Data BeagleBone
                            </div>
                        <div class="panel-body">

                            <!-- <h2>heading 2 -->
                                <!-- <small>sub-heading</small> -->
                            <!-- </h2> -->
                            <h3>Value read:
                                <form>
                                <small id= result  name=proglang></small>
                                <a href='#' id=process_input> <button type="submit" class="btn btn-primary btn-lg btn-block">Start Read </button></a>

                                </form>
                            </h3> 

                        </div>
                        <!-- /.panel-body -->
                    </div>
                    <!-- /.panel -->
                </div>
                                </div>
                                <!-- /.col-lg-6 (nested) -->
                            </div>
                            <!-- /.row (nested) -->
                        </div>
                        <!-- /.panel-body -->
                    </div>
                    <!-- /.panel -->
                </div>
                <!-- /.col-lg-12 -->
            </div>
            <!-- /.row -->
        </div>
        <!-- /#page-wrapper -->

</body>

{% endblock %}

非常感谢

0 个答案:

没有答案