How can I create a continually updating graph from MQTT subscription data?

6 visualizzazioni (ultimi 30 giorni)
I am trying to create a plot of time vs. temperature. The value for temperature will come from a MQTT data broker that is receiving data every 15 seconds. I have created a function to display the message received, however the MQTT data is retreived as a string rather than a numeric value. I have not been able to find a way to plot the data that I am subscribed to from the MQTT server.
The function to subscribe from the MQTT server is below. I have tried to use the str2num command to change the data and this works. However, then I cannot use this value to plot within the function as the function only recognizes string arguments. And I cannot have the plot command outside of the function because the msg is only retrieved within the function.
% code to connect to an MQTT broker
myMQTT = mqtt('tcp://broker.hivemq.com');
%subscribe to a topic with QoS 0, and tell MATLAB to run myMQTT_Callback
%when a new value is published.
AvgTemp = subscribe(myMQTT,'Average Temperature','QoS',0,'Callback',@myMQTT_Callback);
% This function is automatically called by MATLAB until you close MATLAB,
% unsubscribe, or the connection times out.
function myMQTT_Callback(topic, msg)
fprintf('MQTT callback topic "%s": "%s"\n', topic, msg)
%
end

Risposta accettata

Sylvain
Sylvain il 30 Apr 2020
I have a similar project, though, I think you need to publish timestamp,data in the same message to be abe to plot the real time. Bellow I am using a MATLAB timer to simulate the time axis.
1) create an animated line:
hfig = figure;clf
hax = axes(hfig);
anim_line = animatedline('Parent',hax,'Color','blue' ...
,'MaximumNumPoints',500);
2) create a timer
time0 = tic;
3) insert your code, i modified it to use the anim_line and time0 as input:
myMQTT = mqtt('tcp://broker.hivemq.com');
AvgTemp = subscribe(myMQTT,'Average Temperature','QoS',0,...
'Callback',(topic,data)@myMQTT_Callback(topic,data,anim_line,time0));
in your case you do not need the timer time0
4) modify the callback function
function myMQTT_Callback(topic, msg,anim_line,time0)
addpoints(anim_lineX,toc(time0),str2double(data))
end
So in your case, you would need to split thevariable data to get the timestamp and the Temperature from your original MQTT message. this timestamp would replace the toc(time0).
  2 Commenti
Sylvain
Sylvain il 30 Apr 2020
It would be nice to have more hands-on tutorials for this toolbox.
Faraz Azmi
Faraz Azmi il 15 Mag 2020
at what point in this code is the message being read from the topic? when are the published messages stored in data?

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by