Exemplo n.º 1
0
import bezier.curve as bc
from modules.lib import mp_module
from modules import mavproxy_database
from modules import mavproxy_mission
import numpy as np
import json
import time
# import modules.mavproxy_sda.sda_util as sda_util
import mavproxy_logging
from modules.server.views.views_utils import json_serial

logger = mavproxy_logging.create_logger("sda_plane_pred")
class PlanePredictionModule(mp_module.MPModule):

    def __init__(self, mpstate, step=1):
        super(PlanePredictionModule, self).__init__(mpstate, "plane_prediction", "sda module", public=True)
        self.curr_waypoint_index = -1
        self.waypoints = []
        self.waypoint_times =[]
        self.curves = []
        self.curve_end_times = []
        self.step_time = step
        self.initialize_convert()
        self.mission_module = mavproxy_mission.get_mission_mod()
        self.last_update = -float("inf")
        self.min_update_time = 1 #number of seconds between updates (cannot update splines if they were updated less than this time ago)

    def update_waypoints(self,tm=None):
        db = mavproxy_database.get_db_mod()
        wps = mavproxy_database.get_db_mod().get_waypoints()
        self.curr_waypoint_index = mavproxy_database.get_db_mod().get_current_wp()
Exemplo n.º 2
0
from modules.server.urls import app
from modules.mavproxy_calibration import get_cali_mod
from modules.mavproxy_rcsetup import get_rcsetup_mod
import modules.server.views.decorators as decs
from modules.server.data import Data
from flask import request
from flask import jsonify
import sys
import os
import traceback

import mavproxy_logging

logger = mavproxy_logging.create_logger("calibration")

@app.route('/ground/api/v3/cali/accel', methods=['POST'])
@decs.trace_errors(logger, 'Failed to start accelerometer calibration')
def accel_start():
    try:
        token = request.headers.get('token')
    except:
        return "Error: wrong headers", 400
    if token != Data.password:
        return "Error: Invalid token", 403

    get_cali_mod().start_accel_cal()
    return "Started accelerometer calibration."


@app.route('/ground/api/v3/cali/accel', methods=['PUT'])
@decs.trace_errors(logger, 'Failed to continue accelerometer calibrations')
Exemplo n.º 3
0
import json
import mavproxy_logging
from modules.server.urls import app
import modules.server.views.decorators as decs
from modules.mavproxy_simcoverage import get_simcoverage_mod

logger = mavproxy_logging.create_logger("Simulated Coverage")


@app.route('/ground/api/v3/simcoverage', methods=['GET'])
@decs.trace_errors(logger, 'Simulating Coverage')
def get_simulated_coverage():
    get_simcoverage_mod().simulate()
    return json.dumps(True)
Exemplo n.º 4
0
from modules.server.urls import app
from modules.server.data import Data
from modules.mavproxy_sda.sda_engine import get_sda_mod
from modules.mavproxy_sda.sda_util import Convert
from modules.mavproxy_database import get_db_mod
from modules.mavproxy_wp import get_wp_mod
from modules.mavproxy_obstacle_prediction.obstacle_prediction import get_sda_obst_pred_mod
import modules.server.views.decorators as decs
from modules.mavproxy_plane_prediction.plane_prediction import get_sda_plane_pred_mod
from traceback import format_exc
from flask import request
import json

import mavproxy_logging

logger = mavproxy_logging.create_logger("sda")


@app.route('/ground/api/v3/sda_obst_state')
def get_sda_obst_state():
    if not get_sda_obst_pred_mod().check_precondition():
        return "Not enough data points to generate predictive model", 412
    #return prediction_module.function_in_other_file()
    return get_sda_obst_pred_mod().get_obst_state()


@app.route('/ground/api/v3/sda_plane_state')
@decs.trace_errors(logger, "Failed to get plane state")
def get_sda_plane_state():
    if not get_sda_plane_pred_mod().check_precondition():
        return "Not enough waypoints or plane data to generate predictive model", 412
Exemplo n.º 5
0
import json
import time
import traceback
import re

from flask import request
from .views_utils import json_serial
import modules.server.views.decorators as decs

from modules.mavproxy_database import get_db_mod
from modules.mavproxy_mission import get_mission_mod
import modules.server.views.decorators as decs
from modules.mavproxy_plane_prediction.plane_prediction import get_sda_plane_pred_mod
import mavproxy_logging

logger = mavproxy_logging.create_logger("status")

# Can anyone think of a cleaner way to do this?
mpstate = get_db_mod().mpstate
if mpstate.airapi:
    base_url = "/air/api/v3/status"
else:
    base_url = "/ground/api/v3/status"

###################
#
#
#    Logic
#
#
####################
Exemplo n.º 6
0
import mavproxy_logging
from modules.server.urls import app
from modules.mavproxy_distributed import get_distributed_mod
from modules.mavproxy_coverage.coverage_engine import get_coverage_mod
from modules.mavproxy_gimbal import get_gimbal_mod

import modules.server.views.decorators as decs
import flask
from flask import request
import json

logger = mavproxy_logging.create_logger("distributed")


@app.route('/ground/api/v3/distributed', methods=['POST'])
@decs.trace_errors(logger, "failed to start the distributed server")
def start_stop():
    if request.method == 'POST':
        try:
            j = request.get_json()
        except:
            return "Error: JSON cannot be read", 400
        if 'url' not in j.keys() or 'username' not in j.keys() or 'password' not in j.keys():
            return "Error: invalid POST format", 400

        try:
            with open(get_distributed_mod().get_server_file(), 'w+') as server_file:
                server_file.write(json.dumps(j))
        except:
            logger.error('Error: unable to save distributed data')
Exemplo n.º 7
0
import json

import mavproxy_logging
import modules.server.views.decorators as decs
from modules.server.urls import app
from modules.server.data import Data
from modules.mavproxy_param import get_param_mod
import modules.server.views.schemas as schemas

logger = mavproxy_logging.create_logger("Parameters")


@app.route('/ground/api/v3/params')
@decs.trace_errors(logger, 'Failed to get parameter data')
def get_params():
    return json.dumps(Data.params)


@app.route('/ground/api/v3/params/max')
@decs.trace_errors(logger, 'Failed to get param max')
def get_params_max():
    return str(Data.max_param_num)


# USAGE: Post JSON  {'pname': parameter_name, 'value': value}
# See schemas.py for full details.
@app.route('/ground/api/v3/params', methods=['POST'])
@decs.trace_errors(logger, 'update_param failed')
@decs.require_headers({'token': Data.password})
@decs.validate_json(logger, schemas.parameters)
def update_param(parameter):
Exemplo n.º 8
0
instance = None

FEET_TO_METERS_FACTOR = 3.2808399
TRIES_BEFORE_FAILURE = 3
WAYPOINT_THRESHOLD_DISTANCE_FEET = 50
MOVING_AVERAGE_SIZE = 30
POST_ATTEMPT_MAX = 1
POST_TIMEOUT_SECONDS = 2
GET_UPDATE_RATE = .1

# CUAir is using custom logging rather than printing this year
# If it doesn't find the CUAir logger it'll just use a generic one
# that essentially acts the same as a print statement
try:
    import mavproxy_logging
    logger = mavproxy_logging.create_logger("interop")
except:
    import logging
    logger = logging.getLogger("interop")
    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)
    formatter = logging.Formatter("%(message)s")
    ch.setFormatter(formatter)
    logger.addHandler(ch)

print("interop1")


class Interop(mp_module.MPModule):
    def __init__(self, mpstate):
        super(Interop, self).__init__(mpstate, "interop",
Exemplo n.º 9
0
import mavproxy_logging

from modules.server.urls import app
from modules.server.data import Data
import modules.server.views.decorators as decs
from modules.mavproxy_spot_coverage import get_spot_coverage_mod
import modules.server.views.schemas as schemas
from flask import request
import json

logger = mavproxy_logging.create_logger("spot_coverage")


@app.route('/ground/api/v3/coverage/search_grid', methods=['GET'])
@decs.trace_errors(logger, 'spot coverage search grid get failed')
def get_search_grid():
    return json.dumps(get_spot_coverage_mod().get_searchgrid())


@app.route('/ground/api/v3/coverage/search_grid', methods=['POST'])
@decs.trace_errors(logger, 'sport coverage search grid set failed')
@decs.require_headers({'token': Data.password})
@decs.validate_json(logger, schemas.search_grid)
def set_search_grid():
    data = request.get_json()
    get_spot_coverage_mod().set_searchgrid_data(data)
    return json.dumps(True)


@app.route('/ground/api/v3/coverage', methods=['GET'])
@decs.trace_errors(logger, 'failed to retrieve spot coverage settings')
Exemplo n.º 10
0
from modules.server.urls import app
from modules.mavproxy_gimbal import get_gimbal_mod
import json
from flask import request
import modules.server.views.decorators as decs

import mavproxy_logging

logger = mavproxy_logging.create_logger("gimbal")

# Can anyone think of a cleaner way to do this?
mpstate = get_gimbal_mod().mpstate
if mpstate.airapi:
    base_url = "/air/api/v3/gimbal"
else:
    base_url = "/ground/api/v3/gimbal"

@app.route(base_url + '/point', methods=['POST'])
@decs.trace_errors(logger, 'failed to set gimbal point at angle')
def set_gimbal_angle():
    angle_data = request.get_json()
    get_gimbal_mod().set_gimbal_angle(angle_data)
    return json.dumps(True)

@app.route(base_url + '/roi', methods=['POST','DELETE'])
@decs.trace_errors(logger, 'failed to update gimbal gps roi')
def update_roi():
    if request.method == "POST":
        roi_data = request.get_json()
        get_gimbal_mod().add_gps_rois(roi_data)
    else:
Exemplo n.º 11
0
# Creates webserver to access plane data
# November 2014

import time
import threading
import logging
from datetime import datetime

from modules.lib import mp_module
from pymavlink import mavutil
from modules.server.data import Data
from modules.server.urls import Urls
from modules.mavproxy_param import get_param_mod
import mavproxy_logging

logger = mavproxy_logging.create_logger("webserver")

GPS_COORD_EPSILON = 1e-5
ALTITUDE_EPSILON = 1e-4

instance = None


def get_webserver_module():
    if instance is None:
        raise ValueError("Webserver module has not been initialized")
    return instance


class WebServerModule(mp_module.MPModule):
    def __init__(self, mpstate):
Exemplo n.º 12
0
import json
import time
import numpy as np
from collections import namedtuple
from datetime import datetime
import traceback

import subprocess

import mysql.connector
from mysql.connector.pooling import MySQLConnectionPool

from modules.lib import mp_module
from modules.server.helperFunctions import heading_to_vector, degrees_to_rads

logger = mavproxy_logging.create_logger("database")

TIME_VARIANCE = 5
TIME_VARIANCE_MAX = 10
TIME_HISTORY_MAX = 6000
HEARTBEAT_TIMEOUT = 3
# Number of seconds inconsistency between autopilot time and
# computer to at which to throw an error
TIME_INCONSISTENCY_MAX = 20
TIME_EPSILON_SECONDS = 1

class DatabaseModule(mp_module.MPModule):
    def __init__(self, mpstate):
        super(DatabaseModule, self).__init__(mpstate, "database", "database module", public=True)

        while True:
Exemplo n.º 13
0
from modules.server.urls import app
from modules.server.data import Data
import modules.server.views.decorators as decs
from traceback import format_exc
from flask import request
import json
import mavproxy_logging
from modules.mavproxy_path_planning.path_planning_engine import get_path_planning_mod

logger = mavproxy_logging.create_logger("path_planning")


@app.route('/ground/api/v3/path_planning', methods=['POST'])
@decs.trace_errors(logger, 'Failed to reroute path')
def path_planning():
    params = request.json
    print(params)

    # breakout request body into variables
    route_wp_indices = params["route_wp_indices"]
    geofence = params["geofence"]
    buf = int(params["buffer"])

    get_path_planning_mod().plan(route_wp_indices, geofence, buf)

    return json.dumps(True)


@app.route('/ground/api/v3/path_planning/delete', methods=['DELETE'])
@decs.trace_errors(logger, 'Failed to delete wps')
def delete_sda():
Exemplo n.º 14
0
from flask_socketio import emit
import waypoints
import status
from modules.server.urls import socketio
from modules.server.urls import app
from modules.server.data import Data

import mavproxy_logging

logger = mavproxy_logging.create_logger("sockets")

'''mode'''
'''mav_status/calibration'''

@socketio.on_error()
def on_error():
    logger.error('SocketIO Error')

##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##             
#                                   Parameters                                #
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##

def serve_parameter(name, value):
    with app.test_request_context('/'):
        socketio.emit('parameter', {"name": name, "value": value}, namespace='/socket')

def serve_max_parameter_number(number):
    with app.test_request_context('/'):
        socketio.emit('parameter.max', {"max": number}, namespace='/socket')

##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##             
Exemplo n.º 15
0
from modules.server.urls import app
from modules.mavproxy_mode import get_mode_mod
from modules.mavproxy_arm import get_arm_mod
from modules.mavproxy_misc import get_misc_mod
from modules.server.data import Data
import modules.server.views.decorators as decs
from flask import request
import json
import modules.server.mapcache as mapcache
import mavproxy_logging

logger = mavproxy_logging.create_logger("extras")


@app.route('/ground/api/v3/cachemaps', methods=['POST'])
@decs.trace_errors(logger, 'Failed to add location')
def cachemaps():
    logger.info("Location add request received")
    json = request.get_json()
    if 'name' not in json.keys() or 'lat' not in json.keys(
    ) or 'lng' not in json.keys():
        return 'Error: Invalid POST format', 400
    newJSON = mapcache.cacheLocation(
        json['name'], json['lat'], json['lng'],
        json['zoom'] if 'zoom' in json.keys() else 17)
    logger.info("Location Added")
    return newJSON


@app.route('/ground/api/v3/getlocations', methods=['GET'])
@decs.trace_errors(logger, 'Failed to get locations')
Exemplo n.º 16
0
import json

import mavproxy_logging
import modules.server.views.decorators as decs
from modules.server.urls import app
from modules.mavproxy_coverage.coverage_engine import get_coverage_mod
import modules.server.views.schemas as schemas
import flask


logger = mavproxy_logging.create_logger("Coverage")

@app.route('/ground/api/v3/coverage')
@decs.trace_errors(logger, 'coverage version get failed')
def get_coverage():
    j = json.dumps(get_coverage_mod().version)
    return j


@app.route('/ground/api/v3/coverage', methods=['DELETE'])
@decs.trace_errors(logger, 'Failed to reset coverage image')
def reset_coverage():
    get_coverage_mod().reset_coverage()
    return "Success", 200
Exemplo n.º 17
0
#!/usr/bin/env python
from flask import Flask
from flask import redirect
from flask import request
import datetime
import os
import mavproxy_logging
import traceback
from modules.mavproxy_database import get_db_mod
import logging

log = logging.getLogger('werkzeug')
log.setLevel(logging.WARNING)

logger = mavproxy_logging.create_logger("urls")

mpstate = get_db_mod().mpstate

# these statements must be done BEFORE url imports
app = Flask(__name__)

from .views import status
from .views import gimbal
if not mpstate.airapi:
    from .views import interop_api
    from .views import waypoints
    from .views import parameters
    # from .views import geofences
    # from .views import extras
    # from .views import calibration
    # from .views import distributed
Exemplo n.º 18
0
#!/usr/bin/env python
'''mission progress and planning management'''

from __future__ import division
import sys
import math
from modules.lib import mp_module
from geopy.distance import geodesic as gps_distance
from collections import namedtuple
from pymavlink.mavutil import mavlink
# from modules.mavproxy_sda import sda_util
import numpy

import mavproxy_logging

logger = mavproxy_logging.create_logger("mission")
LANDING_SEQ = 3  # nth to last waypoint, beginning of landing sequence
SPEED_SAMPLE_SIZE = 10  # average speed computed by last n waypoints
MAX_FLIGHT_TIME = 5000  # longest possible flight time in seconds
MIN_FLIGHT_SPEED = 5  # minimum speed in mps to be considered flying

BezierCurve = namedtuple("BezierCurve", ["start", "control1", "control2", "end"])

LOCATION_SCALING_FACTOR_INV = 89.83204953368922 * 1e-7
DEG_TO_RAD = math.pi / 180

SPLINE_CONTROLLER = 2


def constrain(val, min_val, max_val):
    return min(max_val, max(min_val, val))
Exemplo n.º 19
0
from modules.server.urls import app
from modules.mavproxy_fence import get_fence_mod
from flask import request
from modules.server.data import Data
import modules.server.views.decorators as decs

import mavproxy_logging

logger = mavproxy_logging.create_logger("geofences")


# format [{'lat':lat, 'lon':lon}, {'lat':lat, 'lon',lon}...}]
@app.route('/v2/geofence', methods=['POST'])
@decs.trace_errors(logger, 'Failed to add geofence')
def add_fence():
    fence_data = request.get_json()
    for latlon in fence_data:
        if abs(float(latlon['lat'])) > 180 or abs(float(latlon['lon'])) > 180:
            return 'Error: waypoint lat/lon out of range', 400
    fenceMod = get_fence_mod()
    fenceMod.addFence(fence_data)
    return "Added Fence"


# format {password: '******'lat':lat, 'lon':lon}, {'lat':lat, 'lon',lon}...}]}
@app.route('/ground/api/v3/geofence', methods=['POST'])
@decs.trace_errors(logger, 'Failed to add geofence')
def add_fence3():
    try:
        fence_data = request.get_json()
    except: