(以虚线方式)使用套接字中的信息实时更新组件[update_graph_live不起作用]

时间:2019-03-29 09:07:43

标签: python sockets plotly real-time plotly-dash

我正在遵循dash.plot.ly的本教程Live Updating Components;在Windows 10的Jupyter Notebook上使用String ss = "A4A12B2B16A1B01A1B23"; List<String> parts = new ArrayList<>(); int len = ss.length(); int partitionSize=5; for (int i=0; i<len; i+=partitionSize) parts.add(ss.substring(i, Math.min(len, i + partitionSize))); for (int i=1; i<parts.size(); i++) { List<String> pairs = new LinkedList<>(); for (int j=0;j<=i;j++) pairs.add(parts.get(j)); while(!pairs.isEmpty()) { String cur1 = pairs.get(0); Iterator<String> it2 = pairs.iterator(); it2.next(); //discard first element which of course exists while(it2.hasNext()) { String cur2 = it2.next(); if(foo(cur1, cur2)) { //... } } pairs.remove(0); } //end processing of the i-th cartesian product } 在python 2.7上运行它。 我有一个来自传感器(用于本地化)的数据流,该数据流转储到localhost:800 socket 。 存在两个app.callback函数。 update_metrics有效,而update_graph_live不起作用。

我使用get_xyz()函数从套接字获取数据:

app.run_server(debug=False)
HOST = 'localhost'
PORT = 800
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
def listen_one_line():
    s.listen(1)
    conn, addr = s.accept()
    data = "".join(iter(lambda:conn.recv(1),"\n"))       
    conn.close()
    return data

类似于本教程,并使用我的功能:

def get_xyz():
    reader = csv.reader(listen_one_line().split('\n'), delimiter=';')
    current={}
    for row in reader:
        current['date']=row[0]
        current['time']=row[1]
        current['milliseconds']=row[2]
        current['tag_address']=row[3]
        current['x_coor']=row[4]
        current['y_coor']=row[5]
        current['z_coor']=row[6]
        #For debugging
        print "get_xyz is returning : "+str(current['x_coor'])+', '+str(current['y_coor'])+', '+str(current['z_coor'])
    return float(row[4]),float(row[5]),float(row[6])         
  • 当我在update_graph_live中使用该get_xyz()函数时,Dash无法渲染3个图。它仅呈现1个plot.ly图,并且保持为空。 如何解决此问题?当update_metrics正常运行时。我的数据解析在这方面是正确的。
  • 它确实可以与本教程中的Satellite代码一起使用。
  • 运行Dash服务器后,笔记本中的一些stdout和stderr:
    external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
    
    app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
    app.layout = html.Div(
        html.Div([
            html.H4('Title'),
            html.Div(id='live-update-text'),
            dcc.Graph(id='live-update-graph'),
            dcc.Interval(
                id='interval-component',
                interval=5*1000, # in milliseconds
                n_intervals=0
            )
        ])
    )
    
    
    @app.callback(Output('live-update-text', 'children'),
                  [Input('interval-component', 'n_intervals')])
    def update_metrics(n):
        x_coor, y_coor, z_coor = get_xyz() #This is working
        style = {'padding': '5px', 'fontSize': '16px'}
        return [
            html.Span('x: {0:.2f}'.format(x_coor), style=style),
            html.Span('y: {0:.2f}'.format(y_coor), style=style),
            html.Span('z: {0:.2f}'.format(z_coor), style=style)
        ]
    
    
    # Multiple components can update everytime interval gets fired.
    @app.callback(Output('live-update-graph', 'figure'),
                  [Input('interval-component', 'n_intervals')])
    def update_graph_live(n):
        data = {
            'time': [],
            'y_coor': [],
            'x_coor': [],
            'z_coor': []
        }
    
        # Collect some data
        for i in range(180):
            time = datetime.datetime.now() - datetime.timedelta(seconds=i*20)
            x_coor, y_coor, z_coor = get_xyz() #This is not working
            data['x_coor'].append(x_coor)
            data['y_coor'].append(y_coor)
            data['z_coor'].append(z_coor)
            data['time'].append(time)
    
        # Create the graph with subplots
        fig = plotly.tools.make_subplots(rows=3, cols=1, vertical_spacing=0.2)
        fig['layout']['margin'] = {
            'l': 70, 'r': 10, 'b': 30, 't': 10
        }
        fig['layout']['legend'] = {'x': 0, 'y': 1, 'xanchor': 'left'}
    
        fig.append_trace({
            'x': data['time'],
            'y': data['x_coor'],
            'name': 'x_coor',
            'mode': 'lines+markers',
            'type': 'scatter'
        }, 1, 1)
        fig.append_trace({
            'x': data['time'],
            'y': data['y_coor'],
            'name': 'y_coor',
            'mode': 'lines+markers',
            'type': 'scatter'
        }, 2, 1)
        fig.append_trace({
            'x': data['time'],
            'y': data['z_coor'],
            'name': 'z_coor',
            'mode': 'lines+markers',
            'type': 'scatter'
        }, 3, 1)
    
        return fig
    
    
    if __name__ == '__main__':
        app.run_server(debug=False)
    
  • 我没有得到下面的输出... 我旨在使用Dash实时绘制xyz传感器数据。
    127.0.0.1 - - [29/Mar/2019 09:57:30] "POST /_dash-update-component HTTP/1.1" 200 -
    get_xyz is returning : 38.27, 16.91, 1.20
    

0 个答案:

没有答案