Ejemplo n.º 1
0
class RelayService:
    def __init__(self, url, username, password):
        self.client = AsyncClient(
            url=url,
            username=username,
            password=password,
        )
        self.last_telemetry = time()

    def telemetry(self, lat, lon, alt, heading):
        t = Telemetry(latitude=lat,
                      longitude=lon,
                      altitude_msl=alt,
                      uas_heading=heading)
        self.client.post_telemetry(t)

        new_time = time()
        print 1/(new_time-self.last_telemetry)
        self.last_telemetry = new_time

        return True

    def server_info(self):
        info = self.client.get_server_info().result()
        return str(info.message)
Ejemplo n.º 2
0
class ApiBridge(object):
    def __init__(self):
        # client = interop.Client(url='http://172.17.0.1:8000', username='******',password='******')
        # missions = client.get_missions()
        # print(missions)
        # stationary_obstacles, moving_obstacles = client.get_obstacles()
        # print(stationary_obstacles, moving_obstacles)
        server = os.getenv('TEST_INTEROP_SERVER', 'http://localhost:8000')
        username = os.getenv('TEST_INTEROP_USER', 'testuser')
        password = os.getenv('TEST_INTEROP_USER_PASS', 'testpass')
        admin_username = os.getenv('TEST_INTEROP_ADMIN', 'testadmin')
        admin_password = os.getenv('TEST_INTEROP_ADMIN_PASS', 'testpass')
        """Create a logged in Client."""
        # Create an admin client to clear cache.
        self.admin_client = Client(server, admin_username, admin_password)
        self.admin_client.get('/api/clear_cache')
        # Test rest with non-admin clients.
        self.client = Client(server, username, password)
        self.async_client = AsyncClient(server, username, password)

    def getObsta(self):
        """Test getting missions."""
        async_future = self.async_client.get_obstacles()
        async_stationary, async_moving = async_future.result()
        return async_stationary, async_moving

    def getMis(self):
        """Test getting missions."""
        # missions = self.client.get_missions()
        async_missions = self.async_client.get_missions().result()
        return async_missions
Ejemplo n.º 3
0
def myfunc():
    server = os.getenv('TEST_INTEROP_SERVER', 'http://localhost:8000')
    username = os.getenv('TEST_INTEROP_USER', 'testuser')
    password = os.getenv('TEST_INTEROP_USER_PASS', 'testpass')
    admin_username = os.getenv('TEST_INTEROP_ADMIN', 'testadmin')
    admin_password = os.getenv('TEST_INTEROP_ADMIN_PASS', 'testpass')
    admin_client = Client(server, admin_username, admin_password)
    admin_client.get('/api/clear_cache')
    async_client = AsyncClient(server, username, password)
    async_missions = async_client.get_missions().result()
    return async_missions
Ejemplo n.º 4
0
 def __init__(self, url, username, password):
     self.client = AsyncClient(
         url=url,
         username=username,
         password=password,
     )
     self.last_telemetry = time()
Ejemplo n.º 5
0
 def __init__(self):
     # client = interop.Client(url='http://172.17.0.1:8000', username='******',password='******')
     # missions = client.get_missions()
     # print(missions)
     # stationary_obstacles, moving_obstacles = client.get_obstacles()
     # print(stationary_obstacles, moving_obstacles)
     server = os.getenv('TEST_INTEROP_SERVER', 'http://localhost:8000')
     username = os.getenv('TEST_INTEROP_USER', 'testuser')
     password = os.getenv('TEST_INTEROP_USER_PASS', 'testpass')
     admin_username = os.getenv('TEST_INTEROP_ADMIN', 'testadmin')
     admin_password = os.getenv('TEST_INTEROP_ADMIN_PASS', 'testpass')
     """Create a logged in Client."""
     # Create an admin client to clear cache.
     self.admin_client = Client(server, admin_username, admin_password)
     self.admin_client.get('/api/clear_cache')
     # Test rest with non-admin clients.
     self.client = Client(server, username, password)
     self.async_client = AsyncClient(server, username, password)
Ejemplo n.º 6
0
def main():
    #initialize logging
    logging.basicConfig(
        level=logging.INFO,
        stream=sys.stdout,
        format='%(asctime)s: %(name)s: %(levelname)s: %(message)s')

    #parse command line args.
    parser = argparse.ArgumentParser(description='Async interop CLI.')
    parser.add_argument('--url', required=True, help='URL for server.')
    parser.add_argument('--username',
                        required=True,
                        help='Username for server login.')
    parser.add_argument('--password', help='Password for server login.')

    subparsers = parser.add_subparsers(help='Sub-command help.')

    subparser = subparsers.add_parser(
        'targets',
        help='Upload Targets.',
        description='''Download or upload targets to/from the interoperability
server.

Without extra arguments, this prints all targets that have been uploaded to the
server.

With --target_dir, this uploads new targets to the server.

This tool searches for target JSON and images files within --target_dir
conforming to the 2017 Object File Format and uploads the target
characteristics and thumbnails to the interoperability server.

Alternatively, if --legacy_filepath is specified, that file is parsed as the
legacy 2016 tab-delimited target file format. Image paths referenced in the
file are relative to --target_dir.

There is no deduplication logic. Targets will be uploaded multiple times, as
unique targets, if the tool is run multiple times.''',
        formatter_class=argparse.RawDescriptionHelpFormatter)
    subparser.set_defaults(func=targets)
    subparser.add_argument(
        '--legacy_filepath',
        help='Target file in the legacy 2016 tab-delimited format.')
    subparser.add_argument(
        '--target_dir',
        help='Enables target upload. Directory containing target data.')

    # Parse args, get password
    args = parser.parse_args()
    if args.password:
        password = args.password
    else:
        password = getpass.getpass('Interoperability Password: ')

    # Create client and dispatch subcommand.
    client = AsyncClient(args.url, args.username, password)
    args.func(args, client)
Ejemplo n.º 7
0
class RelayService:
    def __init__(self, url, username, password):
        self.client = AsyncClient(url=url,
                                  username=username,
                                  password=password)
        self.last_telemetry = time()

    def telemetry(self, lat, lon, alt, heading):
        t = Telemetry(latitude=lat,
                      longitude=lon,
                      altitude_msl=alt,
                      uas_heading=heading)
        self.client.post_telemetry(t)

        new_time = time()
        print(1 / (new_time - self.last_telemetry))
        self.last_telemetry = new_time

        return True

    def get_obstacles(self):
        async_future = self.client.get_obstacles()
        async_stationary, async_moving = async_future.result()
        #print("here")
        # stat_ob, moving_ob = self.client.get_obstacles()
        async_radii_stationary = [o.cylinder_radius for o in async_stationary]
        async_lat_stationary = [o.latitude for o in async_stationary]
        async_lng_stationary = [o.longitude for o in async_stationary]
        async_height_stationary = [o.cylinder_height for o in async_stationary]
        async_radii_moving = [o.sphere_radius for o in async_moving]
        async_lat_moving = [o.latitude for o in async_moving]
        async_lng_moving = [o.longitude for o in async_moving]
        async_height_moving = [o.altitude_msl for o in async_moving]
        
        return async_radii_stationary, async_lat_stationary, async_lng_stationary, async_height_stationary, async_radii_moving, async_lat_moving, async_lng_moving, async_height_moving
	
	def get_moving_obstacles(self):
	
		return True

    def server_info(self):
        info = self.client.get_server_info().result()
        return str(info.message), str(info.message_timestamp), str(info.server_time)
Ejemplo n.º 8
0
def main(url,
         username,
         password,
         interop_time,
         generator,
         flightsim_kml_path=None):
    """Probes the interop server.

    Args:
        url: The interoperability URL.
        username: The interoperability username.
        password: The interoperability password.
        interop_time: The time between interop requests.
        generator: The data generator name to use.
        flightsim_kml_path: The KML path to use if flightsim generator.
    """
    # Create client and data generator.
    client = AsyncClient(url, username, password)
    if generator == 'zeros':
        data_generator = datagen.ZeroValueGenerator()
    else:
        data_generator = flightsim.KmlGenerator(flightsim_kml_path)

    # Continually execute interop requests until signaled to stop.
    while True:
        start_time = datetime.datetime.now()
        telemetry = data_generator.get_uas_telemetry(start_time)

        telemetry_resp = client.post_telemetry(telemetry)
        obstacle_resp = client.get_obstacles()
        telemetry_resp.result()
        obstacle_resp.result()

        end_time = datetime.datetime.now()
        elapsed_time = (end_time - start_time).total_seconds()
        logging.info('Executed interop. Total latency: %f', elapsed_time)

        delay_time = interop_time - elapsed_time
        if delay_time > 0:
            try:
                time.sleep(delay_time)
            except KeyboardInterrupt:
                sys.exit(0)
Ejemplo n.º 9
0
def main():
    """Configures the interoperability binary."""
    # Setup logging
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    stream = logging.StreamHandler(sys.stdout)
    stream.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        '%(asctime)s. %(name)s. %(levelname)s. %(message)s')
    stream.setFormatter(formatter)
    logger.addHandler(stream)

    # Get parameters from command line
    parser = argparse.ArgumentParser(description='Interoperability prober.')
    parser.add_argument(
        'interop_server_host',
        type=str,
        help='Host and port of interoperability server. E.g. localhost:80')
    parser.add_argument(
        'interop_time',
        type=float,
        help='Time between interoperability request sets. Floating point '
        'seconds.')
    parser.add_argument('username',
                        type=str,
                        help='Username for interoperability login.')
    parser.add_argument('password',
                        type=str,
                        help='Password for interoperability login.')
    parser.add_argument('generator',
                        type=str,
                        choices=['zeros', 'flightsim'],
                        help='Data generation implementation.')
    parser.add_argument('flightsim_kml_path',
                        nargs='?',
                        type=str,
                        help='Path to the KML file for flightsim generation.')
    args = parser.parse_args()

    logging.info('Interop host: %s.', args.interop_server_host)
    logging.info('Interop time: %f.', args.interop_time)
    logging.info('Interop username: %s', args.username)
    logging.info('Generator: %s', args.generator)

    # Create client and data generator from parameters
    client = AsyncClient(args.interop_server_host, args.username,
                         args.password)
    if args.generator == 'zeros':
        data_generator = datagen.ZeroValueGenerator()
    else:
        data_generator = flightsim.KmlGenerator(args.flightsim_kml_path)

    # Launch prober
    run(client, data_generator, args.interop_time, logger)
Ejemplo n.º 10
0
class Telemetria(mp_module.MPModule):
    def __init__(self, mpstate):
        super(Telemetria, self).__init__(mpstate, "telemetria",
                                         "telemetria module")
        self.add_command('zrobCos', self.cmd_zrobCos, "zrobCos commands")
        self.client = AsyncClient(INTEROP_URL, INTEROP_USERNAME,
                                  INTEROP_PASSWORD)

    def mavlink_packet(self, m):
        '''handle a mavlink packet'''
        if m.get_type() == 'GLOBAL_POSITION_INT':
            telemetry = Telemetry(
                float(m.lat) / 10000000,
                float(m.lon) / 10000000,
                float(m.alt) / 1000,
                float(m.hdg) / 100)
            self.client.post_telemetry(telemetry)

    def cmd_zrobCos(self, args):
        print "Niby co"
Ejemplo n.º 11
0
class RelayService:
    def __init__(self, url, username, password):
        self.client = AsyncClient(url=url,
                                  username=username,
                                  password=password)
        self.last_telemetry = time()

    def telemetry(self, lat, lon, alt, heading):
        t = Telemetry(latitude=lat,
                      longitude=lon,
                      altitude_msl=alt,
                      uas_heading=heading)
        self.client.post_telemetry(t)

        new_time = time()
        print(1 / (new_time - self.last_telemetry))
        self.last_telemetry = new_time

        return True

    def server_info(self):
        info = self.client.get_server_info().result()
        return str(info.message)
Ejemplo n.º 12
0
class RelayService:
    def __init__(self, url, username, password):
        self.client = AsyncClient(url=url,
                                  username=username,
                                  password=password)
        self.last_telemetry = time()

    def telemetry(self, lat, lon, alt, heading):
        t = Telemetry(latitude=lat,
                      longitude=lon,
                      altitude_msl=alt,
                      uas_heading=heading)
        self.client.post_telemetry(t)

        new_time = time()
        print(1 / (new_time - self.last_telemetry))
        self.last_telemetry = new_time

        return True

    # POSTs target data, where target is a json object conforming to the
    # interop Target class specifications
    def target_data(self, target):
        # the ** operator unwraps the dictionary (here a json object)
        # into an actual argument list, and then we use that to create
        # an instance of the interop Target class
        t = Target(**target)
        self.client.post_target(t)

    # GETs all target info as a json object and prints it
    def get_target_data(self):
        return str(self.client.get_targets().result())

    def server_info(self):
        info = self.client.get_server_info().result()
        return str(info.server_time)
Ejemplo n.º 13
0
    os.execvp("mavproxy.py", args)

#launch interop_cli.py in a new process
ic_pid = os.fork()
if (ic_pid == 0):  #new process
    args = [
        "interop_cli.py", "--url", url, "--username", username, "--password",
        password, "mavlink", "--device", mavlink_stream
    ]
    os.execv("interop_cli.py", args)
    exit(0)


#make sure the execed processes gets exited on ^c
def signal_handler(signal, frame):
    os.kill(mp_pid, signal)
    os.kill(ic_pid, signal)
    exit(0)


signal.signal(signal.SIGINT, signal_handler)

client_instance = AsyncClient(url, username, password)
while (True):
    obstacles = client_instance.get_obstacles()

    #for type in obstacles.result(timeout=1):
    #for obstacle in type:
    #print obstacle
    time.sleep(1)
Ejemplo n.º 14
0
def main():
    # Setup logging
    logging.basicConfig(
        level=logging.INFO,
        stream=sys.stdout,
        format='%(asctime)s: %(name)s: %(levelname)s: %(message)s')

    # Parse command line args.
    parser = argparse.ArgumentParser(description='AUVSI SUAS Interop CLI.')
    parser.add_argument('--url',
                        required=True,
                        help='URL for interoperability.')
    parser.add_argument('--username',
                        required=True,
                        help='Username for interoperability.')
    parser.add_argument('--password', help='Password for interoperability.')

    subparsers = parser.add_subparsers(help='Sub-command help.')

    subparser = subparsers.add_parser('missions', help='Get missions.')
    subparser.set_defaults(func=missions)

    subparser = subparsers.add_parser(
        'targets',
        help='Upload targets.',
        description='''Download or upload targets to/from the interoperability
server.

Without extra arguments, this prints all targets that have been uploaded to the
server.

With --target_dir, this uploads new targets to the server.

This tool searches for target JSON and images files within --target_dir
conforming to the 2017 Object File Format and uploads the target
characteristics and thumbnails to the interoperability server.

Alternatively, if --legacy_filepath is specified, that file is parsed as the
legacy 2016 tab-delimited target file format. Image paths referenced in the
file are relative to --target_dir.

There is no deduplication logic. Targets will be uploaded multiple times, as
unique targets, if the tool is run multiple times.''',
        formatter_class=argparse.RawDescriptionHelpFormatter)
    subparser.set_defaults(func=targets)
    subparser.add_argument(
        '--legacy_filepath',
        help='Target file in the legacy 2016 tab-delimited format.')
    subparser.add_argument(
        '--target_dir',
        help='Enables target upload. Directory containing target data.')
    subparser.add_argument(
        '--team_id',
        help='''The username of the team on whose behalf to submit targets.
Must be admin user to specify.''')
    subparser.add_argument(
        '--actionable_override',
        help='''Manually sets all the targets in the target dir to be
actionable. Must be admin user to specify.''')

    subparser = subparsers.add_parser('probe', help='Send dummy requests.')
    subparser.set_defaults(func=probe)
    subparser.add_argument('--interop_time',
                           type=float,
                           default=1.0,
                           help='Time between sent requests (sec).')

    subparser = subparsers.add_parser(
        'mavlink',
        help='''Receive MAVLink GLOBAL_POSITION_INT packets and
forward as telemetry to interop server.''')
    subparser.set_defaults(func=mavlink)
    subparser.add_argument(
        '--device',
        type=str,
        help='pymavlink device name to read from. E.g. tcp:localhost:8080.')

    # Parse args, get password if not provided.
    args = parser.parse_args()
    if args.password:
        password = args.password
    else:
        password = getpass.getpass('Interoperability Password: ')

    # Create client and dispatch subcommand.
    client = AsyncClient(args.url, args.username, password)
    args.func(args, client)
Ejemplo n.º 15
0
 def __init__(self, mpstate):
     super(Telemetria, self).__init__(mpstate, "telemetria",
                                      "telemetria module")
     self.add_command('zrobCos', self.cmd_zrobCos, "zrobCos commands")
     self.client = AsyncClient(INTEROP_URL, INTEROP_USERNAME,
                               INTEROP_PASSWORD)
Ejemplo n.º 16
0
 def __init__(self, mpstate):
     super(Misje, self).__init__(mpstate, "misje", "misje module")
     self.client = AsyncClient(INTEROP_URL, INTEROP_USERNAME,
                               INTEROP_PASSWORD)
Ejemplo n.º 17
0
 def __init__(self, url, username, password):
     self.client = AsyncClient(url=url,
                               username=username,
                               password=password)
     self.last_telemetry = time()
Ejemplo n.º 18
0
PRINT_SEC = 10

import datetime
import threading
from time import time

try:
    from interop import AsyncClient
    from interop import Telemetry
except ImportError as e:
    raise ImportError(
        'Failed to import interop libraries. Have you added the libs to '
        'the path? Error: %s' % e)

# Create a client and connect to interop.
client = AsyncClient(INTEROP_URL, INTEROP_USERNAME, INTEROP_PASSWORD)

# Tracks the uploads since last print.
sent_lock = threading.Lock()
last_print = datetime.datetime.now()
sent_since_print = 0


# Tracks upload success and prints any exceptions.
def handle_upload_result(future):
    if future.exception():
        print 'Request Failed. Exception: %s' % str(future.exception())
    else:
        with sent_lock:
            sent_since_print += 1
Ejemplo n.º 19
0
                              uas_heading=mavlink_heading(msg.hdg))
        try:
            client.post_telemetry(telemetry)
        except:
            rospy.logerr('Telemetry Post Error')
            sys.exit(1)
        sent_since_print += 1
        now = rospy.get_time()
        since_print = now - last_print
        if since_print > period:
            telem_rate = sent_since_print / since_print
            pub.publish(telem_rate)
            sent_since_print = 0
            last_print = now


if __name__ == "__main__":
    if len(sys.argv) == 5:
        url = sys.argv[1]
        username = sys.argv[2]
        password = sys.argv[3]
        device = sys.argv[4]
        client = AsyncClient(url, username, password)
    else:
        usage()
        sys.exit(1)
    try:
        rate_publisher(device, client)
    except rospy.ROSInterruptException:
        rospy.logerr('ROSInterruptException Error')
Ejemplo n.º 20
0
# print(stationary_obstacles, moving_obstacles)

server = os.getenv('TEST_INTEROP_SERVER', 'http://localhost:8000')
username = os.getenv('TEST_INTEROP_USER', 'testuser')
password = os.getenv('TEST_INTEROP_USER_PASS', 'testpass')
admin_username = os.getenv('TEST_INTEROP_ADMIN', 'testadmin')
admin_password = os.getenv('TEST_INTEROP_ADMIN_PASS', 'testpass')
"""Create a logged in Client."""
# Create an admin client to clear cache.
admin_client = Client(server, admin_username, admin_password)
admin_client.get('/api/clear_cache')

# Test rest with non-admin clients.
client = Client(server, username, password)
async_client = AsyncClient(server, username, password)
"""Test getting missions."""
missions = client.get_missions()
async_missions = async_client.get_missions().result()

# # Check one mission returned.
# self.assertEqual(1, len(missions))
# self.assertEqual(1, len(async_missions))
# # Check a few fields.
# self.assertTrue(missions[0].active)
# self.assertTrue(async_missions[0].active)
# self.assertEqual(1, missions[0].id)
# self.assertEqual(1, async_missions[0].id)
# self.assertEqual(38.14792, missions[0].home_pos.latitude)
# self.assertEqual(38.14792, async_missions[0].home_pos.latitude)