#!/usr/bin/env python

from __future__ import print_function

import argparse
import errno
import code
import struct
import time

# Insert the parent directory into the module import search path.
import os
import sys

sys.path.insert(1, os.path.dirname(sys.path[0]))

from dronin import uavo, telemetry, uavo_collection

#-------------------------------------------------------------------------------
USAGE = "%(prog)s"
DESC  = """
  Retrieve the configuration of a flight controller.\
"""

#-------------------------------------------------------------------------------
def main():
    tStream = telemetry.get_telemetry_by_args(service_in_iter=False)
    tStream.start_thread()

    settings_objects = tStream.uavo_defs.get_settings_objects()

    tStream.wait_connection()

    remaining = settings_objects[:]

    # try to retrieve every object 3 times
    # this is just intended for robustness; never seen this get an object
    # on anything other than the first try.
    for retry in range(6):
        got = 0
        nack_cnt = 0
        for s in remaining[:]:
            tStream.request_object(s)

            for i in range(3):
                if tStream.last_values.get(s):
                    got = got + 1
                    remaining.remove(s)
                    break

                nacks = tStream.get_nacks()
                for n in nacks:
                    if n in remaining:
                        remaining.remove(n)
                        nack_cnt = nack_cnt + 1

                if nacks:
                    break

                time.sleep(0.05)



        print("got", got)
        print("nack", nack_cnt)

        if not remaining:
            break
    else:
        raise Exception('Did not get all objects')

    missing = []

    for s in settings_objects:
        val = tStream.last_values.get(s)
        if val is not None:
            print(val)
        else:
            missing.append(s._name)

    for s in missing:
        print("No instance of %s" % (s))

#-------------------------------------------------------------------------------

if __name__ == "__main__":
    main()
