matplotlib从TCP数据中绘制动态图

时间:2018-01-22 01:36:58

标签: python python-2.7 matplotlib tk python-multiprocessing

对于工作,我使用一些软件来分析数据总线消息,我需要在x,y图中显示一些数据。该软件有一个python解释器,但不幸的是,它与线程/进程和交互式pyplot不能很好地导致它崩溃。我想也许我可以使用localhost TCP服务器在软件和外部pyplot进程之间传递数据。 我已经在线浏览了一些简单的多处理TCP服务器/客户端示例,到目前为止已经发布了下面发布的内容。

我遇到的问题是这个数字(虽然它确实更新)没有反应,但这并不好。我尝试在自己的进程中运行绘图并使用全局队列来获取数据,但是即使作为参数传递,绘图也无法看到客户端线程使用的全局队列,但我能够以交互模式运行绘图。无论如何,我放弃了这一点,而且我最终得到了这个。

有人可以帮我解决这个问题或提供更好的解决方案吗?

Server.py

import socket
import sys
import traceback
from threading import Thread
import matplotlib.pyplot as plt
import json
from multiprocessing import Process



class Figure(object):
    def __init__(self):
        self.fig = plt.figure()
        proc = Process(target=start_server, args=(self,))
        proc.start()

    def Plot(self, data):
        f = self.fig.add_subplot(111)
        d = json.loads(data)
        print "Plot data: ", d
        f.plot(d[0], d[1], d[2])
        self.fig.canvas.draw()
        plt.ion()
        plt.show()
        #plt.show(block=False)
        #plt.draw()


def start_server(fig):
    host = "localhost"
    port = 8888
    soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        soc.bind((host, port))
    except:
        print("Bind failed. Error : " + str(sys.exc_info()))
        sys.exit()
    soc.listen(5)       # queue up to 5 requests
    print("Awaiting Connection...")

    while True:
        connection, address = soc.accept()
        ip, port = str(address[0]), str(address[1])
        print("Connected with " + ip + ":" + port)
        try:
            Thread(target=client_thread, args=(connection, ip, port, fig)).start()
        except:
            print("ERROR - Thread did not start.")
            traceback.print_exc()


def client_thread(connection, ip, port, fig, max_buffer_size = 5120):

    print "Awaiting Data..."
    while True:
        print dir()
        client_input = connection.recv(max_buffer_size)
        fig.Plot(client_input)
        print("Data Received: {}".format(client_input))


if __name__ == "__main__":
    figure = Figure()

Client.py

import socket
import sys
import json
import random

def Main():
    soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = "localhost"
    port = 8888

    try:
        soc.connect((host, port))
        print "connected"
    except:
        print("Connection error")
        sys.exit()

    message = json.dumps(([random.randint(1, 10), random.randint(1, 10), random.randint(1, 10)], [random.randint(1, 10), random.randint(1, 10), random.randint(1, 10)], random.choice(["r", "b"])))

    while message != 'quit':
        soc.sendall(message)
        raw_input("Press 'Retrun' to draw plot.")
        message = json.dumps(([random.randint(1, 10), random.randint(1, 10), random.randint(1, 10)], [random.randint(1, 10), random.randint(1, 10), random.randint(1, 10)], random.choice(["r", "b"])))

    soc.send(b'--quit--')

if __name__ == "__main__":
    Main()

0 个答案:

没有答案