Recommand · October 14, 2021 0

How to use funcAnimation while using Multiprocessing in python 3

hope you’re all doing great.
I am quite new in Python and am working on a tiny client- server project, where I am receiving data from the client and the goal is that the server plot this data in graphic form in real time.
This is the code from the server part, which I am having struggles right now.

import socket
import sys
import math
import numpy as np
import struct
import time
import os
import ctypes as c
import multiprocessing
import matplotlib.pyplot as plt
from matplotlib import animation
from matplotlib import style

HOST = ''
PORT = 6543
receive_size = 4096

def run_server(shared_data_time, shared_data_signal):   
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:  
        server.bind((HOST, PORT))
        conn, addr = server.accept() 
        with conn:
            print(f"Connected by {addr}")
            while True:
                data = conn.recv(receive_size)
                if len(data) == 4096:                     
                    payload  = np.frombuffer(data, dtype = 'float64')
                    print('received data')
                    deinterleaved = [payload[idx::2] for idx in range(2)] 
                    shared_data_time = deinterleaved[0]   
                    shared_data_signal = deinterleaved[1]
                    print(f'received {len(data)} bytes')  

if __name__ == '__main__':
    HOST = ''
    PORT = 6543
    receive_size = 4096
    shared_data_time = multiprocessing.Array('f', 2048)
    shared_data_signal = multiprocessing.Array('f', 2048)
    process1 = multiprocessing.Process(target = run_server, args =(shared_data_time, shared_data_signal))

    def animate(i, shared_data_time, shared_data_signal):
        ax1.plot(shared_data_time, shared_data_signal)

    fig = plt.figure()
    ax1 = fig.add_subplot(1,1,1)
    ani = animation.FuncAnimation(fig, animate, fargs = (shared_data_time, shared_data_signal), interval = 100) 

The communication between server and client works but I am only getting am empty graph, with no actualization. Could everyone helpe me? I would really appreciate it.