I have an MQTT client receiving data at frequency of almost 10 messages per second.
The data contains sound source information from different directions.
I displayed this information on Polar Histogram using Matplotlib.
I have used plt.pause(time) function to make the graph animated. But by using this method there is a significant delay, and polar plot updates very slowly as compared to data I am receiving.
Is there any way to make this process faster, or is there any better approach which I can use? I have tried to change the value of time from 1e-60 to 1e-3 but it didn't seem to make any difference.
Any help would be much appreciated.
(Note: I have tried to use matplotlib.animation() but the problem with that is, there are two loops which are supposed to be executed simultaneously (one for mqtt messages and another one for matplotlib animation). So in that case only one loop executes at one time. The problem is explained here. https://www.raspberrypi.org/forums/viewtopic.php?t=236811)
import os, sys, json, datetime
import paho.mqtt.client as mqtt
import numpy as np
import matplotlib.pyplot as plt
import math
ax = plt.subplot(111, projection='polar')
plt.title('Data from Sound Source')
theta = [0]*4
radii = [0]*4
bars = ax.bar(theta, radii, width=0.05, bottom=0.0)
#MQTT function for receiving messages periodically
def on_message(client, userdata, msg):
global theta, radii
ax.clear()
theta = [0]*4
radii = [0]*4
sources = json.loads(msg.payload)
length = len(sources)
for i in range(length):
x = (sources[i]['x'][0])
y = (sources[i]['x'][1])
theta[i] = math.atan2(y,x)
radii[i] = math.sqrt(x**2 + y**2)
bars = ax.bar(theta, radii, width=0.1, bottom=0.0, tick_label=None)
plt.pause(1e-2) #to make graph wait to update the data
# MQTT variables
host = "localhost"
port = 1883
topic = "hark/data/sentenceinfo"
client = mqtt.Client("HRSUB") #create new instance
client.connect(host, port) #connect to broker
print("Subscribing to topic", topic)
client.subscribe(topic)
client.on_message = on_message
client.loop_forever()