2016-11-10 114 views
0

我想問一個關於如何在燒瓶中實施mqtt的問題。我寫了一些代碼,當我進入特定頁面時,它會接收消息,將消息存儲在數據庫中,然後在該特定頁面的表格中輸出消息。在燒瓶中實施MQTT

下面是我的代碼的片段。

'views.py'

from flask import render_template, request, url_for, redirect, flash 
from flask_wtf import Form 
from flask_login import login_user, logout_user, login_required 
import paho.mqtt.client as mqtt 
from app import app, db 
from models import User, Data 

...other @app.route... 

@app.route('/table') 
@login_required 
def table_data(): 
    def on_connect(client, userdata, flags, rc): 
     flash("connected") 

     client.subscribe("abc123") 

    def on_message(client, userdata, msg, message): 
     message = Data(temperature=msg.temperature, ph=msg.pH, time=msg.time) 

     db.session.add(message) 
     db.session.commit() 

client = mqtt.Client(client_id = "my_visualise", clean_session = True) 
client.username_pw_set("mosquitto", "mosquitto") 
client.on_connect = on_connect 
client.on_message = on_message 

return render_template('table_data.html') 

'models.py'

from app import app, db 

...User table... 

# Data table 
class Data(db.Model): 
    __tablename__= 'data_reading' 
    id = db.Column(db.Integer, primary_key=True) 
    temperature = db.Column(db.Integer, index=True) 
    pH = db.Column(db.Integer, index=True) 
    time = db.Column(db.DateTime, index=True) 

    def __init__(self, temperature, pH, time): 
     self.temperature = temperature 
     self.pH = pH 
     self.time = time 


db.create_all() 

'table_data.html'

... 
<div class="jumbotron"> 
    <div class="container-fluid"> 
     <h2>Data</h2> 
     <p>This table includes the data for temperature, pH value and time</p> 
     <div class="table-responsive"> 
      <table class="table", border=2> 
         {% for value in message.iteritems() %} 
        <thead> 
         <tr> 
          <th>id</th> 
          <th>Temperature</th> 
          <th>pH Value</th> 
          <th>Timestamp</th> 
         </tr> 
        </thead> 
        <tbody> 
         <tr> 
          <td> {{value}} </td> 
         </tr> 
        </tbody> 
        {% endfor %} 
       </table> 
      </div> 
     </div> 

在我的計算機上本地運行的代碼。起初沒有錯誤,但是一旦我進入頁面'/ table',我看到以下錯誤。

「錯誤」

UndefinedError: 'message' is undefined 

我相信這一定是與我在「views.py」寫的劇本,因爲我沒有找到任何例子或者教程,我能理解不夠好方式的問題在燒瓶中實施mqtt。所以我決定嘗試自己實施它。

我想問你對此的看法。

在此先感謝。

+0

如果客戶端只連接了渲染頁面所需的時間,那麼您的模型已損壞,因此它可能永遠不會收到任何消息。 – hardillb

+0

哪一行引發異常? – dirn

+0

@dim我相信'views.py'中的'message = ...'這一行導致了錯誤 – Ling

回答

0

我不太瞭解燒瓶給出​​一個工作示例,但您需要將所有mqtt代碼移動到可以連續運行的單獨線程。然後,onMessage函數仍然可以將到達的消息存儲在數據庫中。

然後,您可以直接從數據庫呈現結果。

+0

感謝您的建議。你提到過將所有的mqtt代碼移動到一個單獨的線程中,你的意思是通過創建一個新文件或在'models.py'中寫入mqtt代碼? – Ling

+0

正如我所說我不知道​​Flask,我不知道它如何工作,所以不能說,但mqtt部分需要與http/web處理分開。 – hardillb