# Import ZeroMQ module
import zmq
import json

# A function to flatten the json data
def flatten_json(json_string):
    # The JSON object to return
    out = {}
    
    # Convert the string to JSON object
    json_object = json.loads(json_string)

    # Load the top level properties
    out["lcm_channel"] = json_object["lcm_channel"]
    out["message_type"] =  json_object["message_type"]
    out["num_integers"] = json_object["num_integers"]
    out["num_reals"] = json_object["num_reals"]
    out["pub_id"] = json_object["pub_id"]
    out["pub_sequence"] = json_object["pub_sequence"]
    out["pub_timestamp"] = json_object["pub_timestamp"]
    
    if "integer_list" in json_object:
        for integer_object in json_object['integer_list']:
            out[integer_object['key']] = integer_object['value']
    if "real_list" in json_object:
        for real_object in json_object['real_list']:
            out[real_object['key']] = real_object['value']
    if "string_list" in json_object:
        for string_object in json_object['string_list']:
            out[string_object['key']] = string_object['value']
    if "boolean_list" in json_object:
        for boolean_object in json_object['boolean_list']:
            out[boolean_object['key']] = boolean_object['value']
    return out

# Change these to point to your server and port
host = "coredata-dpkd.dp.mbari.org"
port = "5556"

# Creates a subscriber socket instance
context = zmq.Context()
socket = context.socket(zmq.SUB)

# Connects to a bound socket
socket.connect("tcp://{}:{}".format(host, port))

# Subscribes to all topics
socket.subscribe("ROV_UHS_MSG")

# Receives a multipart message
while(True):
    the_response = socket.recv_multipart()
    payload_s = the_response[-1].decode("utf-8", errors="strict")
    data = flatten_json(payload_s)
    print(str(data['pub_timestamp']) + " " 
    + str(data['rov_wire_length']) + " " 
    + str(data['rov_wire_speed']) + " " 
    + str(data['rov_tension']))
