from mpl_toolkits.mplot3d import axes3d
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from socket import *
import time

# Объявляем все глобальные переменные

HOST = '192.168.0.76'
PORT = 21566
BUFSIZ = 512
ADDR = (HOST, PORT)

bad_packet = 0
good_packet = 0
# fig, ax = plt.subplots()

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Socket
# tcpCliSock = socket(AF_INET, SOCK_STREAM)
# tcpCliSock.connect(ADDR)
# Запрет на ожидание
plt.ion()

tstart = time.time()
# real-time plotting loop

X, Y, Z = [], [], []

while True:
    try:
        # читаем данные из сети
        tcpCliSock.c
        data = tcpCliSock.recv(BUFSIZ)
        if data:
            print(len(X), data)
            data = data.decode().split(',')
            if len(data) == 9:
                # print('Data received', data)
                # tcpCliSock.send(b'Ok')

                good_packet += 1
            else:
                bad_packet += 1

        # читаем данные из сети
        data = tcpCliSock.recv(BUFSIZ)
        X.append(data[0])
        Y.append(data[1])
        Z.append(data[2])

        frame = ax.scatter(X, Y, Z, c='b', marker='o')

        # Remove old line collection before drawing
        #if oldcol is not None:
        #    ax.collections.remove(oldcol)

        plt.pause(0.001 / len(X))


    except KeyboardInterrupt:
        tcpCliSock.close()
        print('FPS: %f' % (len(X) / (time.time() - tstart)))
        break
