MQTT in MATLAB App

2 ビュー (過去 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 Center および File ExchangeDevelop 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