MQTT in MATLAB App

3 views (last 30 days)
GEONU KIM
GEONU KIM on 20 Apr 2022
Answered: Vinayak on 12 Jan 2024
properties (Access = private)
MQTT = mqtt("tcp://test.mosquitto.org");
sub_topic = "/devices/test/Control";
Sub = subscribe(mqtt("tcp://test.mosquitto.org"),"/devices/KICTtest/Control");
first_sub = 1;
end
methods (Access = private)
function MQTT_Sub_Callback(app, topic, msg)
disp_msg = strcat("topic ",topic," : ",msg);
if(app.first_sub == 1)
app.MessageHistoryTextArea_2.Value = disp_msg;
app.first_sub = 0;
else
app.MessageHistoryTextArea_2.Value = [app.MessageHistoryTextArea_2.Value; disp_msg];
end
end
end
% Button pushed function: CREATEButton
function CREATEButtonPushed(app, event)
char Broker_Address;
Broker_Address = app.BrokerAddressEditField.Value;
app.MQTT = mqtt(Broker_Address));
end
% Button pushed function: SETButton_2
function SETButton_2Pushed(app, event)
app.sub_topic = app.TopicEditField_2.Value;
end
% Button pushed function: SubscribeButton
function SubscribeButtonPushed(app, event)
app.Sub = subscribe(app.MQTT,app.sub_topic, 'QoS', 2,'Callback', @MQTT_Sub_Callback);
end
end
I want to make an app that operates MQTT.
I already did publish message in MQTT.
But I didn't subscribe message in MQTT yet.
What is wrong?
Please Help me.

Answers (1)

Vinayak
Vinayak on 12 Jan 2024
Hi GEONU,
While reviewing the code, I found out that the callback function is not being triggered, which could be due to incorrect syntax.
You should use "@(src,data) app.MQTT_Sub_Callback(src, data)" instead of just using "@MQTT_Sub_Callback".
Additionally, there's a syntax error involving an extra set of parentheses during the MQTT initialization in the 'CREATEButtonPushed' method.
Additionally, you will also need to make some adjustments to the Callback function as the data which it receives is different than what it expects. You may consider modifying the function along these lines:
function MQTT_Sub_Callback(app, ~, data)
topic = data.Topic;
msg = char(data.Message);
% Your previous code
end
You can refer to the documentation on MQTT and App designer for more information:

Categories

Find more on Develop Apps Using App Designer in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!