Here is a sample dashboard which publishes and subscribe to MQTT messages using plotly dash
. Upon receiving the message from a particular topic in JSON
, a dataframe is created and is populated to a dbc.Table.from_dataframe
having id = gw_table
. The requirement is when a new JSON data is received the data table needs to be appended with a new row , where as now in the below script it repopulates the 1st row with new received data.
Reading from the documentation and other similar question I tried with dcc.store
but was not successful.
import dash
import dash_html_components as html
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import flask
from dash.dependencies import Input, Output, State
import json
import dash_mqtt
import pandas as pd
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
server = flask.Flask(__name__)
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.config.suppress_callback_exceptions = True
TEST_SERVER = 'localhost'
TEST_SERVER_PORT = 1884
#TEST_SERVER_PATH = 'websockets'
MQTT_TOPIC_Registration = 'posttopic'
MQTT_TOPIC_Registration_Response = '#'
app.layout = html.Div([
dcc.Tabs([
dcc.Tab(id = 'gw_id_tab', label='Registration', children = [
html.Div([
dash_mqtt.DashMqtt(
id='mqtt',
broker_url=TEST_SERVER,
broker_port = TEST_SERVER_PORT,
#broker_path = TEST_SERVER_PATH,
topics=[MQTT_TOPIC_Registration, MQTT_TOPIC_Registration_Response]
),
html.Div([
html.Button('Register', id='post-val', n_clicks=0)
],style = {'marginTop': 50, 'margin-left' : '600px'}),
html.Br(),
html.Div(
id= 'gw_table'
),
html.Div([
dcc.ConfirmDialog(
id='confirm',
message='Are you sure you want to continue ?',
)]),
],style={'width':'100%', 'margin': 20})
]),
dcc.Tab(label='TAB2', children = [
html.Div([
html.H3('Tab content 2')
])
])
]),
html.Div(id='tabs-content')
])
@app.callback(
Output('confirm', 'displayed'),
[Input('post-val', 'n_clicks')]
)
def display_confirm(clicked):
if clicked:
return True
return False
@app.callback(
Output('gw_table','children'),
[Input('mqtt', 'incoming')]
)
def update_table(incoming_message):
if (incoming_message):
gw_json = incoming_message['payload']
gw_table = pd.DataFrame([pd.read_json(gw_json, typ='series')])
return dbc.Table.from_dataframe(gw_table)
else:
return dash.no_update
if __name__ == '__main__':
app.run_server(host='0.0.0.0',port=8050,debug=True)
So, How to append a new row to the dbc.Table.from_dataframe
when new JSON data is received?