Skip to content

Real-time data visualization

Taipy can display data that is generated in a separate thread. This is useful for displaying real-time data from a sensor or a simulator. For example displaying in a dashboard the information from sensors measuring air pollution around a city, or displaying CPU usage of a server.

Dashboard Example

The dashboard displayed in this image is available here

In this article, we will code a simple example where: - A script will generate a random number and send it through a socket. - A script will receive and display the number in a Taipy application.

VSCode Screenshot

Step 1: Create the Sender Script

Here is the code for the script:
import time
import socket

from random import randint

HOST = ""
PORT = 5050

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    while True:
        random_number = randint(1, 100)
        print(f"Sending: {random_number}")

This script generates a random number between 1 and 100, sends it through a socket, and waits 5 seconds before sending another number.

Step 2: Create the Receiver Script

Coding the receiver script requires multiple steps:

  1. Imports and defining the socket parameters.
import socket
from threading import Thread
from taipy.gui import Gui, State, invoke_callback, get_state_id

HOST = ""
PORT = 5050
  1. We gather the list of state identifiers. These are identifiers of the clients connected to our Taipy application. We need this list to choose which client to send the data to.
state_id_list = []

def on_init(state: State):
    state_id = get_state_id(state)
    if (state_id := get_state_id(state)) is not None:
  1. We create a function to listen to the socket. When the socket receives data, it triggers a callback to send the data to the Taipy application for one of the connected clients.
def client_handler(gui: Gui, state_id_list: list):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((HOST, PORT))
    conn, _ = s.accept()
    while True:
        if data := conn.recv(1024):
            print(f"Data received: {data.decode()}")
            if hasattr(gui, "_server") and state_id_list:
                    gui, state_id_list[0], update_received_data, (int(data.decode()),)
            print("Connection closed")

def update_received_data(state: State, val):
    state.received_data = val
  1. We create the Taipy application to display the data. The client_handler() function and the application itself are run in different threads.
received_data = 0

md = """
Received Data: <|{received_data}|>
gui = Gui(page=md)

t = Thread(
t.start()"Receiver Page")

Step 3: Run the Scripts

Run the script first, then the script in another terminal. The receiver will receive and display the sender's data in the Taipy application.