在烧瓶中实施MQTT

时间:2016-11-10 10:13:01

标签: python-2.7 flask 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。所以我决定尝试自己实现它。

我想问你对此的看法。

提前致谢。

1 个答案:

答案 0 :(得分:0)

我不太了解flask以提供一个工作示例,但是您需要将所有mqtt代码移动到一个可以连续运行的单独线程中。然后onMessage函数仍然可以将到达的消息存储在数据库中。

然后你可以直接从数据库中渲染结果。

相关问题