Get Time in callback function while subscribing to MQTT Topic
18 views (last 30 days)
Show older comments
Hello,
I use the Industrial Communication Toolbox to subscribe to an MQTT Topic. To receive the data, I subscribe to to an MQTT Topic with a Callback Function. The callback function looks like that: function showmessage(topic, data) and therefore has as Input just topic and data. data looks in my example like that:
I need the timestamp from data which here just includes seconds, no milliseconds. But when I use the read(...) function to read from my mqttClient, I get a timetable which includes Time and also milliseconds (not shown on screenshot but could be observed on plots), Topic, but also Data.
Now my question comes up: is it possible to receive the Time like shown in the above screenshot also in the callback function? I tried to have time as third input to my callback function but I get an error when I execute line 32. As other option I tried to use read(...) in my callback function (like line 31), but this also doesn't work. I know both together could not work, it's just in the screenshot to keep my question as short as possible.
Thanks in advance for your help!
2 Comments
Geoff Hayes
on 5 Jul 2022
@Stephan Zimmermann - is the issue that you don't have milliseconds in your time response? Or that you just can't extract the ts from the data json (or something like a json format)?
Accepted Answer
Sudipto
on 19 Jul 2023
I am assuming you are referring to the Time field of the timetable output of the read function. Proceeding with this assumption, you cannot get a timetable like output in the callback functon. Also, the callback is created on the callback stack and won't have access to the workspace variables (for your case mqttclient object, therefore read function won't work.
One possible work around (not a clean way, I understand) is to create a new connection to the mqtt server in the callback function and susbcribe and read to the same topic. Please note that for this to work the message needs to be a retained message. The workflow would look something like this:
mqttclient = mqttclient("xxx-server-name");
subscribe(mqttclient, "TopicName", Callback=@mqttcallback);
write(mqttclient, "TopicName", "value_you_want_to_publish", Retain=true);
mqttcallback.m
function mqttcallback(topic,data)
mq = mqttclient("xxx-server-name");
subscribe(mq, "TopicName");
%Try keeping a pause of 1s, sometimes it takes time for the server to respond.
pause(1);
val=read(m, Topic= "TopicName");
disp(val)
end
0 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!