2017-08-11 8 views
0

私は、TCPを介してデータを読み込み、保存してプロットしようとしています。これまでのところ、データを読み込んでテキストファイルに保存していますが、プロットに問題があります。データが文字列として来て、intに変換する方法や浮動小数点に変換する方法がわかりませんでした。または配列に値を渡してプロットする方法。ここで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ソケットへの接続を作成していて、情報を印刷するためにアニメーショングラフを作成した後で、サーバーからデータを読み込むためにTrueを使用しないようにしています。

# 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() 
関連する問題