MATLAB: How to create a continually updating graph from MQTT subscription data

mqttserver

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

Best Answer

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).