2017-08-11 75 views
0

我正在嘗試通過TCP讀取數據,並將其保存並在同一時間繪製。到目前爲止,我正在讀取數據並保存到一個文本文件,但我有繪製它的問題。數據是以字符串形式出現的,我無法弄清楚如何將其轉換爲int或float。或者如何將這些值傳遞給一個數組來繪圖。如何繪製來自TCP的數據?

這裏是我的代碼:

服務器:

import socket 
import mraa 
import time 
import numpy 

host = '172.20.61.19' 
port = 5000 

x = mraa.Gpio(20) 
x.dir(mraa.DIR_OUT) 

s = socket.socket() 
s.bind((host, port)) 

s.listen(1) 
c, addr = s.accept() 

print "Connection from: " + str(addr) 
while True: 
     x.write(1) 
     time.sleep(2) 
     data = x.read() 
     print str(data) 
     c.send(str(data)) 
     x.write(0) 
     time.sleep(0.5) 
     data = x.read() 
     print str(data) 
     c.send(str(data)) 
s.close() 

客戶:

import socket 
from collections import deque 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 

plt.ion() 

fig = plt.figure() 
ax = fig.add_subplot(111) 

host = '172.20.61.19' 
port = 5000 

s = socket.socket() 
s.connect((host,port)) 

while True: 
    data = s.recv(1024) 
    print data 
    secPlot = ax.plot(int(data), 'b-') 
    fig.canvas.draw() 
s.close() 

誰能幫助我?

提前致謝!

回答

0

處理來自TCP的裸二進制數據很混亂。您可能希望在一側串行化您的數據,以便它可以通過TCP連接傳輸並在另一側恢復,然後您可能需要定義分隔符來分割串行化數據的各個部分。例如,您可以將數據串行化爲JSON格式,並將'\0'作爲分隔符。因此,在服務器端,你發:

{'data':[1,2,3,4,5]}\0{'data':[6,7,8]}\0{'data':...

而在客戶端,你繼續接收,直到達到「\ 0」,將接收到的部分回Python的字典,並繼續接收下一個行李箱。

看一看https://github.com/mdebbar/jsonsocket/blob/master/jsonsocket.py爲一個很好的簡單例子。

0

我想你可以按照這個例子創建一個到TCP套接字的連接,然後我創建一個動畫圖形來打印信息(避免使用while來從服務器讀取數據)。

# get the information (tcp connector, you can keep your client) 
    reader = DataReader() 
    reader.connect(ip=args.ip, port= args.port) 
    # configure x axis (time data) 
    plt.gca().xaxis.set_major_locator(mdates.HourLocator()) 
    plt.gca().xaxis.set_minor_locator(mdates.MinuteLocator()) 
    # define a figure 
    fig, ax = plt.subplots() 
    # this method is in charge of read the data 
    values = [[],[]] 
    def animate(i): 
     # obtain a message from the socket (s.recv(1024)) 
     message = reader.get_message() 
     data_x = message['x'] 
     data_y = message['y'] 
     values[0].append(data_x) 
     values[1].append(data_y) 
     # clear graph 
     ax.clear() 
     # plot the information   
     ax.plot(values[0],values[1],'o-', label= 'my data') 
     # legends 
     ax.legend() 
     xfmt = mdates.DateFormatter('%H:%M:%S') 
     ax.xaxis.set_major_formatter(xfmt) 

    # animate (this line help us replace the while true) 
    # the interval is the time refresh for our graph 
    ani = animation.FuncAnimation(fig, animate, interval=500) 
    # finally we show the image 
    plt.show()