我正在尝试创建一个从mqtt服务器接收数据的python程序。它接收两个参数之一,即值('val')和开关数据('s')。因此,当开关断开时(即s = 0),数据不断传来,并且使用matplotlib动画功能实时绘制了绘图。当开关关闭时(即s = 1),需要中断输入数据,并且程序必须停止执行并关闭所有窗口,包括动画人物和命令提示终端。我尝试在plt.close('all')之后使用exit()函数,但是在plt.close('all')之后似乎没有执行任何操作。该图已关闭,但终端未关闭。我已在此处附上代码供您参考。
import paho.mqtt.client as mqttClient
import time
import json
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import array as arr
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, title = 'Analog Reading', ylabel = 'analog value', xlabel = 'count')
xs = []
ys = []
fields = ['Xaxis']
def on_connect(client, userdata, flags, rc):
if rc == 0:
global Connected
Connected = True
else:
print("Connection failed")
def on_message(client, userdata, message):
global val, s
msg = json.loads(message.payload)
val = msg['V']
s = msg['S']
if s==1:
shutdown()
def shutdown():
ani.event_source.stop()
plt.close('all')
exit()
def animate(i, xs, ys):
xs.append(i)
ys.append(val)
ax.plot(xs,ys,'C1')
Connected = False
broker_address= "10.56.10.173" #Broker address
port = 1883 #Broker port
client = mqttClient.Client("ESP8266Client-") #create new instance
client.on_connect= on_connect #attach function to callback
client.on_message= on_message #attach function to callback
client.connect(broker_address, port=port) #connect to broker
client.loop_start() #start the loop
while Connected != True:#Wait for connection
time.sleep(0.1)
client.subscribe("outTopic")
ani = animation.FuncAnimation(fig, animate, fargs=(xs, ys), interval=200)
plt.show()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
client.disconnect()
client.loop_stop()
exit()