import numpy as np
import socket
import struct

camconn = None
width = None
height = None
depth = None

def _recv_block():
    block_size = struct.unpack('<Q', camconn.recv(8, socket.MSG_WAITALL))[0]
    if block_size == 0:
        return b''
    else:
        return camconn.recv(block_size, socket.MSG_WAITALL)

def connect(cambuffer_ip, cambuffer_port):
    global camconn, width, height, depth

    camconn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    camconn.connect((cambuffer_ip, cambuffer_port))

    width, height, depth, fmt = _recv_block().decode('ascii').split(' ', 3)
    width = int(width)
    height = int(height)
    depth = int(depth)

    assert fmt == 'B8G8R8', 'Unexpected format {}'.format(fmt)

def next_image():
    #`Send image request
    camconn.send(b'?')
    response = _recv_block()
    if len(response) == 0: # no images are available
        return None, None

    # Extract image data and timestamp
    img = np.fromstring(response[:-8], np.uint8).reshape(height, width, depth)
    ts = struct.unpack('<d', response[-8:])[0]
    return img, ts
