MQTT in MATLAB App

8 次查看(过去 30 天)
GEONU KIM
GEONU KIM 2022-4-20
回答: Vinayak 2024-1-12
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.

回答(1 个)

Vinayak
Vinayak 2024-1-12
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:

类别

Help CenterFile Exchange 中查找有关 Develop Apps Using App Designer 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by