Exemplo n.º 1
1
    def requestSITL(self, lat, lon):
        for i in range(len(self.drone_list)):
            if self.drone_list[i][0] == None:
                fo = open("logs/{:%Y-%m-%d..%H.%M.%S}..{}.txt".format(datetime.datetime.now(),i), "w")
                self.drone_list[i][2] = fo
                start_lat = 41.833474
                start_lon = -87.626819
                import dronekit_sitl
                sitl = dronekit_sitl.start_default(start_lat, start_lon)
                address = sitl.connection_string()
                self.drone_list[i][0] = drone.Drone(address, lat, lon, altitude=10, output=fo)
                return i

        return -1
Exemplo n.º 2
0
	def __init__(self):
		
		QtGui.QMainWindow.__init__(self)

		# UI created by QT Designer 
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)

		# default value = 5 m
		self.launchAlt = 5 

		#Set up option parsing to get connection string
		import argparse  
		parser = argparse.ArgumentParser(description='Tracks GPS position of your computer (Linux only). Connects to SITL on local PC by default.')
		parser.add_argument('--connect', help="vehicle connection target.")
		args = parser.parse_args()

		self.connection_string = args.connect
		self.sitl = None

		#Start SITL if no connection string specified
		if not self.connection_string:
			import dronekit_sitl
			self.sitl = dronekit_sitl.start_default()
			self.connection_string = self.sitl.connection_string()

		# Connect to the Vehicle
		print 'Connecting to vehicle on: %s' % self.connection_string
		self.vehicle = connect(self.connection_string, wait_ready=True)

		# Display Flight Mode
		self.updateFlightModeGUI(self.vehicle.mode)
		self.addObserverAndInit(
			'mode'
			,lambda vehicle,name,mode: self.updateFlightModeGUI(mode) ) 

		# Display Location Info
		self.updateLocationGUI(self.vehicle.location)
		self.addObserverAndInit(
			'location'
			,lambda vehicle, name, location: self.updateLocationGUI(location) )
Exemplo n.º 3
0
import sys
import wave
from communication import Communication

# Connect to xBee
COM_CONNECTION_STRING = '/dev/ttyUSB0'      #potential option
com = Communication(COM_CONNECTION_STRING, 0.1)

# This block of code connects to the UAV over its serial connection, Pi -> PixHawk
# It also initalizes the vehicle object referenced throughout this file.
# When the connection information is known, fill out the portInformation variable to disable auto-start of SITL.
portInformation = '/dev/ttyAMA0' #'127.0.0.1:14550'
testSITL = None

if not portInformation:
    testSITL = dronekit_sitl.start_default()
    portInformation = testSITL.connection_string()
    print ("Starting SITL Test Environment, No UAV Detected")

#file = open("test.txt", "w+")
#file.write("running")
#file.close()
time.sleep(30)

print("Connecting to UAV.")
UAV = connect(portInformation, wait_ready=True, baud=57600)
print(" Autopilot Firmware version: %s" % UAV.version)
# wait for radio transmission from ground station UI, store transmitted values into this array
# 0-1 are ISU 1 lat/long, 2-3 ISU 2 lat/long, 4-5 gnd station lat/long
# these default coordinates are locations around Palmer Park's drone field, and are default locations the drone can go to if communications fails
# SAFETY NOTE: DON'T MESS UP YOUR COORDINATES. EVEN AN ERROR IN THE TENTH'S PLACE CAN SEND THE DRONE MILES AWAY
Exemplo n.º 4
0
import dronekit_sitl
from time import sleep

if __name__ == '__main__':
    sitl = dronekit_sitl.start_default(lat=38.145206, lon=-76.428473)
    print("Connection String:", sitl.connection_string())

    try:
        while True:
            sleep(1)
    except:
        sitl.stop()
Exemplo n.º 5
0
import dronekit_sitl

sitl = dronekit_sitl.start_default(20.735517, -103.457499)

from dronekit import connect, VehicleMode, LocationGlobalRelative
import time
Exemplo n.º 6
0
messages = position_messages_from_tlog(args.tlog)
print(" Generated %d waypoints from tlog" % len(messages))
if len(messages) == 0:
    print("No position messages found in log")
    exit(0)

#Start SITL if no connection string specified
if args.connect:
    connection_string = args.connect
    sitl = None
else:
    start_lat = messages[0].lat/1.0e7
    start_lon = messages[0].lon/1.0e7

    import dronekit_sitl
    sitl = dronekit_sitl.start_default(lat=start_lat,lon=start_lon)
    connection_string = sitl.connection_string()

# Connect to the Vehicle
print('Connecting to vehicle on: %s' % connection_string)
vehicle = connect(connection_string, wait_ready=True)


# Now download the vehicle waypoints
cmds = vehicle.commands
cmds.wait_ready()


cmds = vehicle.commands
cmds.clear()
for pt in messages:
Exemplo n.º 7
0
if len(sys.argv) != 5:
    print "Incorrect number of arguments, invoke this script with: \n \
    python launch.py adressname target-latitude target-longitude flag. \n \
    Addressname of sitl will run it in a simulation \n \
    If flag is 1, a new terminal will be created, if it is 0, it will run on the open terminal"

    sys.exit()

if sys.argv[4] == "1":
    subprocess.Popen("python launch.py %s %s %s 0" %
                     (sys.argv[1], sys.argv[2], sys.argv[3]),
                     creationflags=subprocess.CREATE_NEW_CONSOLE)
    sys.exit()

address = sys.argv[1]
lat = float(sys.argv[2])
lon = float(sys.argv[3])

if address == "sitl":
    start_lat = 41.833474
    start_lon = -87.626819
    import dronekit_sitl
    sitl = dronekit_sitl.start_default(start_lat, start_lon)
    address = sitl.connection_string()

d = drone.Drone(address, lat, lon)
d.connect()
d.run()
d.wait()
d.close()
Exemplo n.º 8
0
 def build_simulated_connect(self):
     import dronekit_sitl
     sitl = dronekit_sitl.start_default()
     self.connection_string = sitl.connection_string()
Exemplo n.º 9
0
messages = position_messages_from_tlog(args.tlog)
print(" Generated %d waypoints from tlog" % len(messages))
if len(messages) == 0:
    print("No position messages found in log")
    exit(0)

#Start SITL if no connection string specified
if args.connect:
    connection_string = args.connect
    sitl = None
else:
    start_lat = messages[0].lat / 1.0e7
    start_lon = messages[0].lon / 1.0e7

    import dronekit_sitl
    sitl = dronekit_sitl.start_default(lat=start_lat, lon=start_lon)
    connection_string = sitl.connection_string()

# Connect to the Vehicle
print('Connecting to vehicle on: %s' % connection_string)
vehicle = connect(connection_string, wait_ready=True)

# Now download the vehicle waypoints
cmds = vehicle.commands
cmds.wait_ready()

cmds = vehicle.commands
cmds.clear()
for pt in messages:
    #print "Point: %d %d" % (pt.lat, pt.lon,)
    lat = pt.lat
Exemplo n.º 10
0
def quick_scan_autonomy(configs, autonomyToCV, gcs_timestamp,
                        connection_timestamp):
    print(
        "\n######################## STARTING QUICK SCAN AUTONOMY ########################"
    )
    autonomy.configs = configs

    # If comms is simulated, start comm simulation thread
    if configs["quick_scan_specific"]["comms_simulated"]["toggled_on"]:
        comm_sim = Thread(target=comm_simulation,
                          args=(
                              configs["quick_scan_specific"]["comms_simulated"]
                              ["comm_sim_file"],
                              xbee_callback,
                          ))
        comm_sim.start()
    # Otherwise, set up XBee device and add callback
    else:
        comm_sim = None
        autonomy.xbee = setup_xbee()
        autonomy.gcs_timestamp = gcs_timestamp
        autonomy.connection_timestamp = connection_timestamp
        autonomy.xbee.add_data_received_callback(xbee_callback)

    # Generate waypoints after start_mission = True
    while not autonomy.start_mission:
        pass

    # Generate waypoints
    waypoints = generate_waypoints(configs, search_area)

    # Start SITL if vehicle is being simulated
    if (configs["vehicle_simulated"]):
        import dronekit_sitl
        sitl = dronekit_sitl.start_default(lat=35.328423, lon=-120.752505)
        connection_string = sitl.connection_string()
    else:
        if (configs["3dr_solo"]):
            connection_string = "udpin:0.0.0.0:14550"
        else:
            connection_string = "/dev/serial0"

    # Connect to vehicle
    vehicle = connect(connection_string, wait_ready=True)

    # Starts the update thread
    update = Thread(target=update_thread,
                    args=(vehicle, configs["mission_control_MAC"]))
    update.start()

    # Send mission to vehicle
    quick_scan_adds_mission(vehicle, waypoints[1], configs["altitude"])

    # Start the mission
    start_auto_mission(vehicle)

    # Change vehicle status to running
    change_status("running")

    # Fly about spiral pattern
    while vehicle.commands.next != vehicle.commands.count:
        print(vehicle.location.global_frame)
        time.sleep(1)
        # Holds the copter in place if receives pause
        if autonomy.pause_mission:
            vehicle.mode = VehicleMode("ALT_HOLD")
        # Lands the vehicle if receives stop mission
        elif autonomy.stop_mission:
            land(vehicle)
            return
        # Continues path
        else:
            vehicle.mode = VehicleMode("AUTO")

    # Switch to detailed search if role switching is enabled
    if configs["quick_scan_specific"]["role_switching"]:
        autonomy.mission_completed = True
        update.join()
        detailed_search(vehicle)
    else:
        land(vehicle)

        # Ready for a new mission
        autonomy.mission_completed = True

        # Wait for update thread to end
        update.join()

    # Wait for comm simulation thread to end
    if comm_sim:
        comm_sim.join()
    else:
        autonomy.xbee.close()
Exemplo n.º 11
0
def main():
    #vehicle = connect('/dev/serial0', wait_ready=False, baud=57600)
    import dronekit_sitl
    sitl = dronekit_sitl.start_default()
    connection_string = sitl.connection_string()
    vehicle = connect(
        connection_string,
        wait_ready=False,
    )
    # NOTE these are *very inappropriate settings*
    # to make on a real vehicle. They are leveraged
    # exclusively for simulation. Take heed!!!
    vehicle.parameters['FS_GCS_ENABLE'] = 0
    vehicle.parameters['FS_EKF_THRESH'] = 100

    arm_and_takeoff(vehicle, 10)

    # navigate to video  and log files.
    filestring = r"../../../Landing_Tests/7-18-18 landing vids"
    fileDir = os.path.dirname(os.path.realpath('__file__'))
    dataDir = os.path.join(fileDir, filestring)
    dataDir = os.path.abspath(os.path.realpath(dataDir))
    fileNames = os.listdir(dataDir)

    vidNames = [f for f in fileNames if f.endswith('.avi')]
    vidfilepath = os.path.join(dataDir, vidNames[1])  # select fourth video

    # start input video stream
    #vs = PiVideoStream(resolution=(og_horz_resolution, og_vert_resolution)).start()

    # vs.read() returns a tuple. I want the second item, Item 1. I want to dynamically replace every instance of vs.read() with vs.read()[1]. How do I override that function? With this class.
    class vidstream_wrapper():
        def __init__(self, vs):
            self.vs = vs

        def read(self):
            return self.vs.read()[1]

    vs = vidstream_wrapper(cv2.VideoCapture(vidfilepath))

    # wait for the camera to start
    time.sleep(0.5)

    fps = getFPS(vs, vehicle)

    # label this capture
    start_time = datetime.datetime.now().replace(
        microsecond=0).strftime('%y-%m-%d %H.%M.%S')

    # Define the codec and create VideoWriter object
    fourcc = cv2.cv.CV_FOURCC(*'DIVX')
    video_file = "Captures/camera_cap_" + start_time + ".avi"

    out = cv2.VideoWriter(video_file, fourcc, fps.fps(),
                          (horizontal_resolution, vertical_resolution))

    # Make Log headers
    log_name = 'Log/Bot_' + start_time + '.txt'
    make_headers(log_name)
    # control loop
    state = Restart_State()

    while (repr(state) != "Landed_State"):
        try:
            # show frame. Note: this destroys a frame.
            frame = vs.read()
            cv2.imshow('frame', frame)

            if cv2.waitKey(10) & 0xFF == ord('q'):
                break

            state.executeControl(vs, vehicle, out, log_name)
            state = state.transition()

        except (KeyboardInterrupt, SystemExit):
            break

    terminate_flight(vehicle)

    out.release()
    vehicle.close()
    cv2.destroyAllWindows()
    vs.stop()
Exemplo n.º 12
0
import dronekit_sitl
from time import sleep

if __name__ == '__main__':
    sitl = dronekit_sitl.start_default(lat=38.870604, lon=-77.322292)
    print("Connection String:", sitl.connection_string())

    try:
        while True:
            sleep(1)
    except:
        sitl.stop()
Exemplo n.º 13
0
def connectmycopter():
    import dronekit_sitl
    sitl = dronekit_sitl.start_default()
    connection_string = sitl.connection_string()
    vehicle = connect(connection_string, wait_ready=True)
    return vehicle
# Importing appropriate libraries
from dronekit import connect, VehicleMode, LocationGlobalRelative
import time
import math

# Set up option parsing to get connection string
import argparse
parser = argparse.ArgumentParser(description='commands')
parser.add_argument('--connect')
args = parser.parse_args()
connection_string = args.connect

# Start SITL if no connection string specified
if not connection_string:
    import dronekit_sitl
    sitl = dronekit_sitl.start_default(wp0lat, wp0long)
    connection_string = sitl.connection_string()

# Connect to the Vehicle
print("connection to the vehicle on %s" % connection_string)
vehicle = connect(connection_string, wait_ready=True)

# Allow time for the mission planner to download parameters
time.sleep(10)

#### Define Functions ####


# Define the function for arm and takeoff
def arm_and_takeoff(aTargetAltitude):
    """
Exemplo n.º 15
0
        lat, lng = position.offset(heading, distance_as_km).to_string('D')
        return (float(lat), float(lng))

    def do_camera(self, args):
        ''' trigger camera to capture a photo '''
        # check vehicle status and mode
        console.white('... capturing image')
        self.vehicle.trigger_camera()
        self._wait()    # wait 3 seconds for clean shot
        console.blank()



if __name__ == '__main__':

    # check for the --test flag from the command line
    test = True if '--test' in ' '.join(sys.argv) else False

    # if running in test mode, start the simulator in another process
    if test:
        sitl = dronekit_sitl.start_default(lat=41.9751961, lon=-87.6636616)

    # enter the console application
    app = App(test=test)
    app.cmdloop()

    # if running in test mode, end the simulator before finishing
    if test:
        sitl.stop()

Exemplo n.º 16
0
import time
from dronekit import connect, VehicleMode, LocationGlobalRelative, Command, LocationGlobal
#import RPi.GPIO as GPIO
import dronekit_sitl
from pymavlink import mavutil

#Arm and Takeoff.

sitl = dronekit_sitl.start_default(20.737641, -103.457018)
connection_string = sitl.connection_string


def arm_and_takeoff(TargetAltitude):
    #Vehicle Connection
    print("Executing Takeoff")

    while not drone.is_armable:
        print("Vehicle is not armable, waiting...")
        time.sleep(1)

    print("Ready to arm")
    drone.mode = VehicleMode("GUIDED")
    drone.armed = True

    while not drone.armed:
        print("Waiting for arming...")
        time.sleep(1)

    print("Ready for takeoff, taking off...")
    drone.simple_takeoff(TargetAltitude)
Exemplo n.º 17
0
import dronekit as dk
import dronekit_sitl as dk_sitl
import time

print "Start  simulator (SITL)"

sitl = dk_sitl.start_default()
connect_string = sitl.connection_string()



# Exception to throw in the event of a failed connection
class NoConnectionError(Exception):
    def __init__(self):
        Exception.__init__(self)




# Drone Autopilot Class
class DronePilot:


    # Constructor Method
    def _init__(self):
        self.connect_string     = None
        self.drone              = None

    # Method to initiate drone connection
    def connect(self,connect_string):
import dronekit_sitl
from dronekit import connect, VehicleMode

# Connection
try:
    print("Connecting to vehicle on '/dev/ttyACM0'")
    vehicle = connect('/dev/ttyACM0', wait_ready=True, baud=57600)
    sitl = False
except:
    print("Can't connect to physical vehicle.")
    print("Starting simulated vehicle.")

    sitl = dronekit_sitl.start_default()  # Simulator
    connection_string = sitl.connection_string()

    print("Connecting to vehicle on {}".format(connection_string))
    vehicle = connect(connection_string, wait_ready=True)

print("Get some vehicle attributes (state):")
print("Autopilot Firmware version: %s" % vehicle.version)
print("Autopilot capabilities (supports ftp): %s" % vehicle.capabilities.ftp)
print("Global Location: %s" % vehicle.location.global_frame)
print("Global Location (relative altitude): %s" %
      vehicle.location.global_relative_frame)
print("Local Location: %s" % vehicle.location.local_frame)
print("Attitude: %s" % vehicle.attitude)
print("Velocity: %s" % vehicle.velocity)
print("GPS: %s" % vehicle.gps_0)
print("Groundspeed: %s" % vehicle.groundspeed)
print("Airspeed: %s" % vehicle.airspeed)
print("Gimbal status: %s" % vehicle.gimbal)
Exemplo n.º 19
0
        print("Waiting for arming..")
        time.sleep(1)

    print("Taking off!")
    vehicle.simple_takeoff(aTargetAltitude)

    # Wait until the vehicle reaches a safe height before processing the goto
    # (otherwise the command after Vehicle.simple_takeoff will execute inmediately).
    while True:
        print(" Altitude: ", vehicle.location.global_relative_frame.alt)
        # Break and return from function just below target altitude.
        if vehicle.location.global_relative_frame.alt >= aTargetAltitude * 0.95:
            print("Reached target altitude")
            break
        time.sleep(1)


if __name__ == "__main__":
    sitl = dronekit_sitl.start_default()  # basic ArduCopter simulator
    connection_string = sitl.connection_string()

    print("Connecting to vehicle on {}".format(connection_string))
    vehicle = connect(connection_string, wait_ready=True)

    # Start mission
    point1 = LocationGlobalRelative(-35.361354, 149.165218, 20)
    point2 = LocationGlobalRelative(-35.363244, 149.168801, 20)

    mission(20, 5, [point1, point2], [7, 10], True)
    sitl.stop()  # Stop simulation
Exemplo n.º 20
0
parser = argparse.ArgumentParser(
    description='Commands vehicle using vehicle.simple_goto.')
parser.add_argument(
    '--connect',
    help=
    "Vehicle connection target string. If not specified, SITL automatically started and used."
)
args = parser.parse_args()

connection_string = args.connect
sitl = None

# Start SITL if no connection string specified
if not connection_string:
    import dronekit_sitl
    sitl = dronekit_sitl.start_default(24.180956, 120.649184)
    connection_string = sitl.connection_string()

# Connect to the Vehicle
print('Connecting to vehicle on: %s' % connection_string)
# print("(Connecting to vehicle on: /dev/ttyAMA0)")
# vehicle = connect('/dev/ttyAMA0', wait_ready=True, baud=57600)
vehicle = connect(connection_string, wait_ready=True, baud=921600)


# Function to arm and then takeoff to a user specified altitude
def arm_and_takeoff(aTargetAltitude):
    """
        Arms vehicle and fly to aTargetAltitude.
        """
    print("\n Basic pre-arm checks")
Exemplo n.º 21
0
#first we new to connect to apm with cmd or terminal using the next commands.
#this command is to make the drone house insede the campus #dronekit-sitl copter --home=20.7377382,-103.4570051,1357,180
#then we need to make the connection with #mavproxy.py --master tcp:127.0.0.1:5760 --out udp:127.0.0.1:14551 --out udp:10.43.14.246:14550
#this is a group of codes that are already givven by dronekit in this case
import time
from dronekit import connect, VehicleMode, LocationGlobalRelative
from pymavlink import mavutil
import Tkinter as tk
import dronekit_sitl

sitl = dronekit_sitl.start_default(20.735892, -103.457091)
connection_string = sitl.connection_string


def arm_and_takeoff(TargetAltitude):
    #Vehicle connection
    print("Executing Takeoff")
    #At this part our drone is not ready to arm. we give him the order to don't armed yet.
    while not drone.is_armable:
        print("Vehicle is not armable, waiting...")
        time.sleep(1)
#When the drone is also ready he is going to tell us that is ready to arm and start the guided mode that is guided by coordenates.
    print("Ready to arm")
    drone.mode = VehicleMode("GUIDED")
    drone.armed = True
    #Sometimes the drone take more time to be ready. So in line 21-24 our drone will tell us he is taking more time to be ready to arm
    while not drone.armed:
        print("waiting for arming...")
        time.sleep(1)
#note:time.sleep(x) is the time in seconds that the program is going to stop.
#When the drone finished all the steps before he is going to tell us. The drone will start to fly at this point and he is going to reach an altitude that we decide to.
Exemplo n.º 22
0
    def __init__(self):
        sitl = dronekit_sitl.start_default()
        connection_string = sitl.connection_string()

        vehicle = connect(connection_string, wait_ready=True)
        print("!!! Connection to the vehicle on: {} !!!".format(connection_string))
Exemplo n.º 23
0
import dronekit_sitl
from time import sleep
"""
runs dronekit which is necessary for connecting to the Mission planner simulator. 
"""

if __name__ == '__main__':
    sitl = dronekit_sitl.start_default(lat=29.867295, lon=77.898946)
    print("Connection String:", sitl.connection_string())

    try:
        while True:
            sleep(1)
    except:
        sitl.stop()
Exemplo n.º 24
0
parser = argparse.ArgumentParser(
    description='Commands vehicle using vehicle.simple_goto.')
parser.add_argument(
    '--connect',
    help=
    "Vehicle connection target string. If not specified, SITL automatically started and used."
)
args = parser.parse_args()

connection_string = args.connect
sitl = None

#Start SITL if no connection string specified
if not connection_string:
    import dronekit_sitl
    sitl = dronekit_sitl.start_default()
    connection_string = sitl.connection_string()

# Connect to the Vehicle
print('Connecting to vehicle on: %s' % connection_string)
vehicle = connect(connection_string,
                  wait_ready=True,
                  baud=57600,
                  heartbeat_timeout=120)


def arm_and_takeoff(aTargetAltitude):
    """
    Arms vehicle and fly to aTargetAltitude.
    """
Exemplo n.º 25
0
    def startProtocol(self):
        try:
            print "Started application"
            print "Init dronekit object"
            #connection_string = None
            #connection_string = 'com3' #window
            #connection_string = '/dev/cu.usbmodem1' #macos
            connection_string = '/dev/ttyACM0'  #ubuntu
            sitl = None
            #Start SITL if no connection string specified
            if not connection_string:
                import dronekit_sitl
                sitl = dronekit_sitl.start_default()
                connection_string = sitl.connection_string()
            #Connect to vehicle
            print '\nConnecting to vehicle on: %s' % connection_string
            vehicle = connect(connection_string, wait_ready=True, baud=57600)
            vehicle.wait_ready('autopilot_version')

            self.vehicle = vehicle
            #init pixhaw obj
            self.pho = BaseJsonObj()
            self.pho.Vehicle = {
                'Velocity': self.vehicle.velocity,
                'Heading': self.vehicle.heading,
                'Battery': {
                    'Voltage': self.vehicle.battery.voltage,
                    'Current': self.vehicle.battery.current,
                    'Level': self.vehicle.battery.level
                }
            }
            self.pho.LocationGlobal = {
                'Lat': self.vehicle.location.global_frame.lat,
                'Lon': self.vehicle.location.global_frame.lon,
                'Alt': self.vehicle.location.global_frame.alt
            }
            self.pho.GpsInfo = {
                'Eph': self.vehicle.gps_0.eph,
                'Epv': self.vehicle.gps_0.epv,
                'Fix_Type': self.vehicle.gps_0.fix_type,
                'Satellites_Visible': self.vehicle.gps_0.satellites_visible,
            }
            self.pho.SystemStatus = {'State': self.vehicle.system_status.state}
            self.pho.Attitude = {
                'Yaw': self.vehicle.attitude.yaw,
                'Pitch': self.vehicle.attitude.pitch,
                'Roll': self.vehicle.attitude.roll
            }
            #mapping attribute change
            self.vehicle.add_attribute_listener('velocity',
                                                self.velocity_callback)
            self.vehicle.add_attribute_listener('battery',
                                                self.battery_callback)
            self.vehicle.add_attribute_listener('gps_0', self.gps0_callback)
            self.vehicle.add_attribute_listener('location.global_frame',
                                                self.location_callback)
            self.vehicle.add_attribute_listener('system_status',
                                                self.status_callback)
            self.vehicle.add_attribute_listener('heading',
                                                self.heading_callback)
            self.vehicle.add_attribute_listener('attitude',
                                                self.attitude_callback)
            print 'started GNU thread'
            gnuThread.start()

        except [[KeyboardInterrupt]]:
            usrb_object.stop()
            self.vehicle.remove_attribute_listener('velocity',
                                                   self.velocity_callback)
            self.vehicle.remove_attribute_listener('battery',
                                                   self.battery_callback)
            self.vehicle.remove_attribute_listener('gps_0', self.gps0_callback)
            self.vehicle.remove_attribute_listener('location.global_frame',
                                                   self.location_callback)
            self.vehicle.remove_attribute_listener('system_status',
                                                   self.status_callback)
            self.vehicle.remove_attribute_listener('heading',
                                                   self.heading_callback)
            self.vehicle.remove_attribute_listener('attitude',
                                                   self.attitude_callback)
            self.vehicle.close()
            pass
Exemplo n.º 26
0
import drone
import subprocess

if len(sys.argv) != 5:
    print ("Incorrect number of arguments, invoke this script with: \n \
    python launch.py adressname target-latitude target-longitude flag. \n \
    Addressname of sitl will run it in a simulation \n \
    If flag is 1, a new terminal will be created, if it is 0, it will run on the open terminal")
    sys.exit()

if sys.argv[4] == "1":
    subprocess.Popen("python launch.py %s %s %s 0" % (sys.argv[1], sys.argv[2], sys.argv[3]), creationflags = subprocess.CREATE_NEW_CONSOLE)
    sys.exit()

address = sys.argv[1]
lat = float(sys.argv[2])
lon = float(sys.argv[3])

if address == "sitl":
    start_lat = 41.833474
    start_lon = -87.626819
    import dronekit_sitl
    sitl = dronekit_sitl.start_default(start_lat, start_lon)
    address = sitl.connection_string()


d = drone.Drone(address, lat, lon)
d.connect()
d.run()
d.wait()
d.close()
Exemplo n.º 27
0
import argparse  
parser = argparse.ArgumentParser(description='Print out vehicle state information. Connects to SITL on local PC by default.')
parser.add_argument('--connect', 
                   help="vehicle connection target string. If not specified, SITL automatically started and used.")
args = parser.parse_args()
sitl = None

connection_string = '127.0.0.1:14551'

HOST = '127.0.0.1'  # The server's hostname or IP address
PORT = 65432        # The port used by the server

#Start SITL if no connection string specified
if not connection_string:
    import dronekit_sitl as sim
    sitl = sim.start_default()
    connection_string = sitl.connection_string()

print("\nConnecting to vehicle on: %s" % connection_string)
vta = connect(connection_string, wait_ready=False, baud=57600, heartbeat_timeout=180)

vta.wait_ready('autopilot_version')
print("\nConnected to: %s" % connection_string)


#float tetherLength=


def arm(vehicle):
    """
    Arms vehicle.
Exemplo n.º 28
0
Arquivo: pi.py Projeto: whxru/CoUAS
    # To create and start simulators of copter
    sitl = None
    if args.sitl:
        sitls = []
        cnt_strs = []

        def connect_to_monitor(h, p, idx):
            sitls[idx - 1][0].launch(sitls[idx - 1][1], await_ready=True)
            vehicle = connect_vehicle(cnt_strs[idx - 1])
            vehicle.groundspeed = speed
            sitls[idx - 1] = drone.Drone(vehicle, h, p, idx)

        # Preparation for starting multiple separated simulators
        from dronekit_sitl import SITL, start_default
        if args.sitl == 1:
            sitl = start_default(args.lat, args.lon)
            connection_string = sitl.connection_string()
            vehicle = connect_vehicle(connection_string)
            mav = drone.Drone(vehicle, host, port)
            mav.set_speed(speed)
        else:
            for i in range(0, args.sitl):
                sitl = SITL()
                sitl.download('copter', '3.3', verbose=True)
                sitl_args = [
                    '-I%d' % i, '--model', 'quad',
                    '--home=%f,%f,584,353' % (args.lat, args.lon + 5e-5 * i)
                ]
                sitls.append([sitl, sitl_args])
                cnt_strs.append('tcp:127.0.0.1:%d' % (5760 + 10 * i))
                c = Thread(target=connect_to_monitor,
def detailed_search_autonomy(configs, autonomyToCV, gcs_timestamp, connection_timestamp, vehicle=None):
    print("\n######################## STARTING DETAILED SEARCH AUTONOMY ########################")
    autonomy.configs = configs

    # If comms is simulated, start comm simulation thread
    if configs["detailed_search_specific"]["comms_simulated"]["toggled_on"]:
        comm_sim = Thread(target=comm_simulation, args=(configs["detailed_search_specific"]["comms_simulated"]["comm_sim_file"], xbee_callback,))
        comm_sim.start()
    # Otherwise, set up XBee device and add callback
    else:
        comm_sim = None
        autonomy.xbee = setup_xbee()
        autonomy.gcs_timestamp = gcs_timestamp
        autonomy.connection_timestamp = connection_timestamp
        autonomy.xbee.add_data_received_callback(xbee_callback)

    # If detailed search was not role-switched from quick scan, connect to new vehicle and takeoff
    if not vehicle:
        # Start SITL if vehicle is being simulated
        if (configs["vehicle_simulated"]):
            import dronekit_sitl
            sitl = dronekit_sitl.start_default(lat=35.328423, lon=-120.752505)
            connection_string = sitl.connection_string()
        else:
            if (configs["3dr_solo"]):
                connection_string = "udpin:0.0.0.0:14550"
            else:
                connection_string = "/dev/serial0"

        # Connect to vehicle
        vehicle = connect(connection_string, wait_ready=True)

        # Starts the update thread
        update = Thread(target=update_thread, args=(vehicle, configs["mission_control_MAC"]))
        update.start()

        takeoff(vehicle, configs["altitude"])
    else:
        # Starts the update thread
        update = Thread(target=update_thread, args=(vehicle, configs["mission_control_MAC"]))
        update.start()
    
    # Change vehicle status to running
    change_status("running")

    # Continuously fly to POIs
    while not autonomy.stop_mission:
        if not POI_queue.empty() and not autonomy.pause_mission:
            poi = POI_queue.get()
            poi.alt = configs["altitude"]
            vehicle.simple_goto(poi)

            print("At POI, now orbiting")
            # TODO start CV scanning
            orbit_poi(vehicle, poi, configs)
            # Change flight mode to AUTO to start auto mission
            vehicle.mode = VehicleMode("AUTO")
            # print location while orbiting
            while vehicle.commands.next != vehicle.commands.count:
                print(vehicle.location.global_frame)
                print(vehicle.commands.next)
                print(vehicle.commands.count)
                time.sleep(1)
            # TODO stop CV scanning

            # Change flight mode back
            vehicle.mode = VehicleMode("GUIDED")
        else:
            change_status("waiting")    

        # Holds the copter in place if receives pause
        if autonomy.pause_mission:
            vehicle.mode = VehicleMode("ALT_HOLD")
            change_status("paused")
        # Otherwise continue
        else:
            vehicle.mode = VehicleMode("GUIDED")

    land(vehicle)

    # Sets vehicle status to "ready"
    change_status("ready")
    autonomy.mission_completed = True

    update.join()

    # Wait for comm simulation thread to end
    if comm_sim:
        comm_sim.join()
    else:
        autonomy.xbee.close()
Exemplo n.º 30
0
def ConnectToUAV(SimvReal):
    while gbvar.UAVS == "":
        while gbvar.uInputLaunch == "":
            time.sleep(1)
        print("Attempting Connection to SOLO")
        print gbvar.uInputLaunch
        if gbvar.uInputLaunch == "1":
            parser = argparse.ArgumentParser(
                description=
                'Print out vehicle state information. Connects to SITL on local PC by default.'
            )
            parser.add_argument(
                '--connect',
                default='115200',
                help="vehicle connection target. Default '57600'")
            args = parser.parse_args()
            gbvar.UAVS = connect(
                '/dev/serial/by-id/usb-3D_Robotics_PX4_FMU_v2.x_0-if00',
                baud=115200,
                rate=6)

        elif gbvar.uInputLaunch == "0":
            parser = argparse.ArgumentParser(
                description=
                'Print out vehicle state information. Connects to SITL on local PC by default.'
            )
            parser.add_argument(
                '--connect',
                help=
                "Vehicle connection target string. If not specified, SITL automatically started and used."
            )
            args = parser.parse_args()

            import dronekit_sitl
            sitl = dronekit_sitl.start_default()
            connection_string = sitl.connection_string()

            # Connect to the Vehicle
            print 'Connecting to vehicle on: %s' % connection_string
            gbvar.UAVS = connect(connection_string, wait_ready=True)

        elif gbvar.uInputLaunch == "test":
            parser = argparse.ArgumentParser(
                description=
                'Print out vehicle state information. Connects to SITL on local PC by default.'
            )
            parser.add_argument(
                '--connect',
                help=
                "Vehicle connection target string. If not specified, SITL automatically started and used."
            )
            args = parser.parse_args()

            import dronekit_sitl
            sitl_c = dronekit_sitl.start_default()
            connection_string_c = sitl_c.connection_string()

            # manually specifying connection, due to some computer interferance.
            # If running simulation using 2 computers, comment out the below line
            connection_string_c = 'tcp:127.0.0.1:5763'

            # Connect to the Vehicle
            print 'Connecting to vehicle on: %s' % connection_string_c
            gbvar.UAVS = connect(connection_string_c, wait_ready=True)
        time.sleep(1)
Exemplo n.º 31
0
print "Start simulator (SITL)"
import dronekit_sitl
sitl = dronekit_sitl.start_default()
connection_string = sitl.connection_string()

# Import DroneKit-Pythonpip install dronekit-sitl

from dronekit import connect, VehicleMode

# Connect to the Vehicle.
print("Connecting to vehicle on: %s" % (connection_string,))
vehicle = connect(connection_string, wait_ready=True)

# Get some vehicle attributes (state)
print "Get some vehicle attribute values:"
print " GPS: %s" % vehicle.gps_0
print " Battery: %s" % vehicle.battery
print " Last Heartbeat: %s" % vehicle.last_heartbeat
print " Is Armable?: %s" % vehicle.is_armable
print " System status: %s" % vehicle.system_status.state
print " Mode: %s" % vehicle.mode.name    # settable

# Close vehicle object before exiting script
vehicle.close()

# Shut down simulator
sitl.stop()
print("Completed")
Exemplo n.º 32
0
import dronekit as dk
import time
import dronekit_sitl as dks
from mismeth import *
import pymavlink as mav
sitl = dks.start_default(52.9241747, -4.0542528)
connection_string = sitl.connection_string()

vehicle = dk.connect(connection_string, wait_ready=True)

cmds = vehicle.commands
cmds.download()
cmds.wait_ready()
alt = 4

loc1 = dk.LocationGlobalRelative(52.9243403, -4.0539125, alt)
#loc1 = get_location_metres(vehicle.location.global_frame,50,50)
loc2 = dk.LocationGlobalRelative(52.924303, -4.054105, alt)
loc3 = dk.LocationGlobalRelative(52.924393, -4.0539249, alt)
loc4 = dk.LocationGlobalRelative(52.9244998, -4.0537784, alt)

vehicle.groundspeed = 15

arm_takeoff(vehicle, alt)

vehicle.simple_goto(loc2)
stay_in_range(vehicle, loc2)

####### TASK 2 AND TASK 3 ########
vehicle.simple_goto(loc3)
stay_in_range(vehicle, loc3)