Hi All, I am building an application to publish and subscribe to MQTT topic, Though I am able to publish to the topic, I cannot subscribe and display the response receive in a particular topic. Below is my code:
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 paho.mqtt.client as mqtt
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
app.layout = html.Div([
html.Div([
html.Button('Register', id='post-val', n_clicks=0)
],style = {'marginTop': 50, 'margin-left' : '600px'}),
html.Br(),
html.Div(
id='textarea-state-example-output', style={'whiteSpace': 'pre-line'}
),
html.Div(
id='textarea-state-example-output1', style={'whiteSpace': 'pre-line'}
),
],style={'width':'100%', 'margin': 20})
MQTT_HOST = "172.17.0.2"
#MQTT_HOST = 'localhost'
MQTT_PORT = 1883
MQTT_KEEPALIVE_INTERVAL = 45
MQTT_TOPIC_Registration = "gw/register"
MQTT_TOPIC_Registration_Response = "gw/registerresponse"
mqttc = mqtt.Client()
mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)
@app.callback(
Output('textarea-state-example-output1', 'children'),
[Input('post-val', 'n_clicks')]
)
def display_Output(clicked):
if clicked:
def on_message(client, userdata, msg):
global p
r= msg.topic
p= msg.payload
return p
return on_message()
@app.callback(
Output('textarea-state-example-output', 'children'),
[Input('post-val', 'n_clicks')])
def update_output(clicked):
if clicked:
MQTT_MSG=json.dumps({"gw_macid": "[32,74,2,255,255,144,255,203]",
"zigbee_mac_id": "60A423FFFE4292F1",
"gw_ip" : "192.168.0.105",
"gw_fw_version": "19.4.h-597",
"status_report_interval": 1,
"net_config": 2,
"network_gateway_ip": 171986689,
"device_net_mask": 4294967040 });
mqttc.publish(MQTT_TOPIC_Registration, MQTT_MSG)
res = mqttc.subscribe(MQTT_TOPIC_Registration_Response)
if len(res)> 0:
return "Gateway with MAC id" +gw_mac_id +"registered successfully"
return "Gateway cannot be registered :("
if __name__ == '__main__':
app.run_server(host='0.0.0.0',port=8050,debug=True)
I am receiving the response because variable “res” is not equal to zero, but unfortunately I am not able to print the output for the response topic. The error is as follows,
TypeError: on_message() missing 3 required positional arguments: 'client', 'userdata', and 'msg'
Help is appreciated. Thank you.