Пример #1
0
 def __init__(self, test=False):
     cmd.Cmd.__init__(self)
     console.clear()
     console.white("# argon : dronekit-based flight control console \n")
     console.white("connecting to drone")
     try:
         console.white("... waiting on connection")
         if test == True:
             self.vehicle = dronekit.connect('tcp:127.0.0.1:5760',
                     vehicle_class=IRIS,
                     status_printer=self._status_printer,
                     wait_ready=True,
                     heartbeat_timeout=30,   # 30 second timeout
                 )
         else:
             self.vehicle = dronekit.connect('/dev/cu.usbserial-DJ00DSDS',
                     baud=57600,
                     vehicle_class=IRIS,
                     status_printer=self._status_printer,
                     wait_ready=True,
                     heartbeat_timeout=30,   # 30 second timeout
                 )
         console.white("... connected \n")
     except KeyboardInterrupt:
         console.white("... canceling connection attempt \n")
         return True
     except Exception:
         console.white("... unable to connect \n")
         return True
Пример #2
0
    def bringup_drone(self, connection_string=None):
        """Connect to a dronekit vehicle or instantiate an sitl simulator.

        Call this once everything is set up and you're ready to fly.
        
        This is some deep magic related to running multiple drones at once. We
        don't technically need it, since the network architecture I've set up
        has the drones all be independant (if you want to simulate multiple
        drones with the current setup you run multiple instances of the SITL
        simulator). Chris got this all working by talking with the dronekit
        devs, so he knows a lot more about it than I do.

        connection_string -- Connect to an existing mavlink (SITL or the actual
                             ArduPilot). Provide None and it'll start its own
                             simulator.
        """
        if not connection_string:
            # Start SITL if no connection string specified
            print "Starting SITL"
            self.sitl = dronekit_sitl.SITL()
            self.sitl.download('copter', '3.3', verbose=True)
            sitl_args = ['--model', 'quad',
                         '--home=32.990756,-117.128362,243,0',
                         '--speedup', str(Pilot.sim_speedup),
                         '--instance', str(self.instance)]
            working_dir = tempfile.mkdtemp()
            self.sitl.launch(sitl_args,
                             verbose=True,
                             await_ready=True,
                             restart=True,
                             wd=working_dir)
            time.sleep(6)  # Allow time for the parameter to go back to EEPROM
            connection_string = "tcp:127.0.0.1:{0}".format(5760 + 10 * self.instance)
            #connection_string = "tcp:127.0.0.1:14550")
            new_sysid = self.instance + 1
            vehicle = dronekit.connect(connection_string, wait_ready=True)
            while vehicle.parameters["SYSID_THISMAV"] != new_sysid:
                vehicle.parameters["SYSID_THISMAV"] = new_sysid
                time.sleep(0.1)
            time.sleep(5)  # allow eeprom write
            vehicle.close()
            self.sitl.stop()
            # Do it again, and this time SYSID_THISMAV will have changed
            self.sitl.launch(sitl_args,
                             verbose=True,
                             await_ready=True,
                             restart=True,
                             use_saved_data=True,
                             wd=working_dir)
            self.vehicle = dronekit.connect(connection_string, wait_ready=True)
            print vehicle
        else:
            # Connect to existing vehicle
            print 'Connecting to vehicle on: %s' % connection_string
            print "Connect to {0}, instance {1}".format(connection_string, self.instance)
            self.vehicle = dronekit.connect(connection_string, wait_ready=True)
            print "Success {0}".format(connection_string)
Пример #3
0
def initializeDrone(connectionString, isSimulator):
    if isSimulator:
        sitl = SITL()
        sitl.download('copter', '3.3', verbose=True)
        sitl_args = [
            '-I0', '--model', 'quad', '--home=-35.363261,149.165230,584,353'
        ]
        sitl.launch(sitl_args, await_ready=True, restart=True)
        print "Connecting to vehicle on: 'tcp:127.0.0.1:5760'"
        vehicle = connect('tcp:127.0.0.1:5760', wait_ready=True)
        # print information about vehicle
        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  #NED
        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 "Battery: %s" % vehicle.battery
        print "EKF OK?: %s" % vehicle.ekf_ok
        print "Last Heartbeat: %s" % vehicle.last_heartbeat
        print "Rangefinder: %s" % vehicle.rangefinder
        print "Rangefinder distance: %s" % vehicle.rangefinder.distance
        print "Rangefinder voltage: %s" % vehicle.rangefinder.voltage
        print "Heading: %s" % vehicle.heading
        print "Is Armable?: %s" % vehicle.is_armable
        print "System status: %s" % vehicle.system_status.state
        print "Mode: %s" % vehicle.mode.name  # settable
        print "Armed: %s" % vehicle.armed
    else:
        # Connect to the Vehicle
        print 'Connecting to vehicle;'
        vehicle = connect(connectionString, wait_ready=True)
        # print information about vehicle
        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  #NED
        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 "Battery: %s" % vehicle.battery
        print "EKF OK?: %s" % vehicle.ekf_ok
        print "Last Heartbeat: %s" % vehicle.last_heartbeat
        print "Rangefinder: %s" % vehicle.rangefinder
        print "Rangefinder distance: %s" % vehicle.rangefinder.distance
        print "Rangefinder voltage: %s" % vehicle.rangefinder.voltage
        print "Heading: %s" % vehicle.heading
        print "Is Armable?: %s" % vehicle.is_armable
        print "System status: %s" % vehicle.system_status.state
        print "Mode: %s" % vehicle.mode.name  # settable
        print "Armed: %s" % vehicle.armed
Пример #4
0
	def __init__(self , connectionString,mode):

         
            if mode =='r': #run on vihcle
                print 'Connecting to vehicle on: %s' % connectionString
                self.vehicle = connect(connectionString, baud=57600)
        
            if mode =='s': #run on simultor
                self.sitl = SITL()
                self.sitl.download('copter', '3.3', verbose=True)
                self.sitl_args = ['-I0','--gimbal' ,'--model', 'quad', '--home=31.7396,35.1956,3,-1']
                self.sitl.launch(self.sitl_args, await_ready=True, restart=True)
                self.vehicle = connect('tcp:127.0.0.1:5760', wait_ready=True)
Пример #5
0
def test_115(connpath):
    v = connect(connpath, await_params=True)

    # Dummy callback
    def mavlink_callback(*args):
        mavlink_callback.count += 1
    mavlink_callback.count = 0

    # Set the callback.
    v.set_mavlink_callback(mavlink_callback)

    # Change the vehicle into STABILIZE mode
    v.mode = VehicleMode("STABILIZE")
    # NOTE wait crudely for ACK on mode update
    time.sleep(3)

    # Expect the callback to have been called
    assert mavlink_callback.count > 0

    # Unset the callback.
    v.unset_mavlink_callback()
    savecount = mavlink_callback.count

    # Disarm. A callback of None should not throw errors
    v.armed = False
    # NOTE wait crudely for ACK on mode update
    time.sleep(3)

    # Expect the callback to have been called
    assert_equals(savecount, mavlink_callback.count)

    # Re-arm should not throw errors.
    v.armed = True
    # NOTE wait crudely for ACK on mode update
    time.sleep(3)
Пример #6
0
	def connection(self,args):
		args=str(args)
		if args is 'sitl' or args is None:
			self._log("Starting copter simulator (SITL)")
			from dronekit_sitl import SITL
			sitl = SITL()
			self.sitl=sitl
			sitl.download('copter', '3.3', verbose=True)
			sitl_args = ['-I0', '--model', 'quad', '--home=-35.363261,149.165230,584,0']
			sitl.launch(sitl_args, await_ready=True, restart=True)
			connection_string='tcp:127.0.0.1:5760'
		elif args=='0':
			connection_string='/dev/ttyACM0'
		elif args=='1': 
			connection_string='/dev/ttyACM1'
		else:
			connection_string=str(args)
		self._log('Connecting to vehicle on: %s' % connection_string)
		vehicle = connect(connection_string, wait_ready=True)

		# Register observers
		vehicle.add_attribute_listener('location',self.location_callback)
		#vehicle.add_attribute_listener('battery',self.battery_callback)
		#vehicle.add_attribute_listener('heading',self.heading_callback)
		return vehicle
Пример #7
0
def main():
    configureLogger("agent")
    ListenMQTTThread()
    registerAgent()  # Call the register endpoint and register Device I
    print "\nConnecting to vehicle on: %s" % CONNECTION_TARGET
    print "----------------------------------------------------------------------"
    vehicle = connect(CONNECTION_TARGET, wait_ready=True, baud=BAUD)
    while (True):
        if(iotUtils.IS_REGISTERED):
            currentTime = calendar.timegm(time.gmtime())
            PUSH_DATA = iotUtils.SENSOR_STATS + '"time":'+str(currentTime)+'},"payloadData":{"quatanium_val_q1":'+0\
                        +',"quatanium_val_q2":'+0+',"quatanium_val_q3":'+0+',"quatanium_val_q4":'+0+',"velocity_x":'\
                        +str(vehicle.velocity[0])+',"velocity_y":'+str(vehicle.velocity[1])+',"velocity_z":'\
                        +str(vehicle.velocity[2])+',"global_location_lat":'+str(vehicle.location.global_relative_frame.lat)\
                        +',"global_location_alt":'+str(vehicle.location.global_relative_frame.alt)\
                        +',"global_location_lon":'+str(vehicle.location.global_relative_frame.lon)+',"battery_level":'\
                        +str(vehicle.battery.level)+',"battery_voltage":'+str(vehicle.battery.voltage)+',"pitch":'\
                        +str(vehicle.attitude.pitch)+',"roll":'+str(vehicle.attitude.roll)+',"yaw":'\
                        +str(vehicle.attitude.yaw)+',"deviceType":"IRIS_DRONE"}}}';
            mqttHandler.sendSensorValue(PUSH_DATA)
            print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Publishing Device-Data ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
            print ('PUBLISHED DATA: ' + PUSH_DATA)
            time.sleep(PUSH_INTERVAL)
        else:
            registerAgent()
            time.sleep(PUSH_INTERVAL)
        print "-------------------------------------------------------------------------------------------------"
Пример #8
0
	def __init__(self):
		self.vehicle = connect('udpin:0.0.0.0:14550', await_params=False)
		self.vehicle.add_attribute_observer('local_position', self.location_callback)
		if not self.vehicle.armed:
			self.start_vehicle(5)
		self.x = 0
		self.y = 0
Пример #9
0
def test_parameter(connpath):
    # Connect to the Vehicle
    vehicle = connect(connpath, await_params=True)

    # Initial
    cmds = vehicle.commands
    cmds.download()
    cmds.wait_valid()
    assert_equals(len(cmds), 1)

    # After clearing
    cmds.clear()
    vehicle.flush()
    cmds.download()
    cmds.wait_valid()
    assert_equals(len(cmds), 1)

    # Upload
    for command in [
        Command(0, 0, 0, 0, 16, 1, 1, 0.0, 0.0, 0.0, 0.0, -35.3605, 149.172363, 747.0),
        Command(0, 0, 0, 3, 22, 0, 1, 0.0, 0.0, 0.0, 0.0, -35.359831, 149.166334, 100.0),
        Command(0, 0, 0, 3, 16, 0, 1, 0.0, 0.0, 0.0, 0.0, -35.363489, 149.167213, 100.0),
        Command(0, 0, 0, 3, 16, 0, 1, 0.0, 0.0, 0.0, 0.0, -35.355491, 149.169595, 100.0),
        Command(0, 0, 0, 3, 16, 0, 1, 0.0, 0.0, 0.0, 0.0, -35.355071, 149.175839, 100.0),
        Command(0, 0, 0, 3, 113, 0, 1, 0.0, 0.0, 0.0, 0.0, -35.362666, 149.178715, 22222.0),
        Command(0, 0, 0, 3, 115, 0, 1, 2.0, 22.0, 1.0, 3.0, 0.0, 0.0, 0.0),
        Command(0, 0, 0, 3, 16, 0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
    ]:
        cmds.add(command)
    vehicle.flush()

    # After upload
    cmds.download()
    cmds.wait_valid()
    assert_equals(len(cmds), 9)
Пример #10
0
def main():
    global vehicle
    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

    #connection_string = '/dev/serial/by-id/usb-Arduino__www.arduino.cc__Arduino_Mega_2560_740313032373515082D1-if00' #for serial
    connection_string = 'udp:127.0.0.1:14550'

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

    print "kpx,kix,kdx"
    kpx = float(input())
    kix = float(input())
    kdx = float(input())
    print "kpy,kiy,kdy"
    kpy = float(input())
    kiy = float(input())
    kdy = float(input())

    _pid_values = (kpx, kix, kdx, kpy, kiy, kdy)

    print _land
    takeoff(_pid_values)
    arm_and_takeoff(1, _pid_values)
Пример #11
0
def test_timeout(connpath):
    v = connect(connpath, vehicle_class=DummyVehicle)

    while not v.success:
        time.sleep(0.1)

    v.close()
def test_115(connpath):
    v = connect(connpath, wait_ready=True)
    time.sleep(5)
    assert_false(v.capabilities.ftp)

    # versions of ArduCopter prior to v3.3 will send out capabilities
    # flags before they are initialised.  Vehicle attempts to refetch
    # until capabilities are non-zero, but we may need to wait:
    start_time = time.time()
    nonzero_capabilities = True
    slept = False
    while v.capabilities.mission_float == 0:
        if time.time() > start_time + 30:
            nonzero_capabilities = False
            break
        time.sleep(0.1)
        slept = True
    if v.capabilities.mission_float:
        if slept:
            assert_true(v.version.major <= 3)
            assert_true(v.version_minor <= 3)
    else:
        # fail it
        assert_true(v.capabilities.mission_float)

    assert_true(v.version.major is not None)
    assert_true(len(v.version.release_type()) >= 2)
    assert_true(v.version.release_version() is not None)
Пример #13
0
def connectToDrone(dkip, dkport):

   
  #Dronekit connection
  global vehicle
  #connect to vehicle at ip:port
  print("Attempting To Connect to Dronekit")
  vehicle = connect(dkip+':'+dkport, wait_ready=True)
  #set connected bool to True
  global connected 
  connected = True
  
  #initialize globals associated with the vehicle
  #Throttle PWM fail safe value
  global THR_FS_VAL
  THR_FS_VAL = vehicle.parameters['THR_FS_VALUE']
  #Battery capacity failsafe value
  global FS_BATT_MAH
  FS_BATT_MAH = vehicle.parameters['FS_BATT_MAH'] 
  #ID of the ground control station
  global SYSID_MYGCS
  SYSID_MYGCS = vehicle.parameters['SYSID_MYGCS']

  # create thread to update readout information in real time
  thread.start_new_thread(updateVehicleStatus, (vehicle,))
Пример #14
0
def test_parameter(connpath):
    v = connect(connpath, wait_ready=True)

    # Perform a simple parameter check
    assert_equals(type(v.parameters['THR_MIN']), float)

    v.close()
Пример #15
0
def test_can_arm():
    sitl = SITL()
    sitl.download('copter', '3.3')
    sitl.launch(copter_args, verbose=True, await_ready=True)
    vehicle = dronekit.connect("tcp:127.0.0.1:5760", wait_ready=True)
    # Wait for vehicle to be armable
    timeout = time.time() + 10
    while not vehicle.is_armable and time.time() < timeout:
        time.sleep(0.35)
    timed_out = time.time() >= timeout
    if timed_out:
        sitl.stop()
    assert_false(timed_out, "Vehicle init timed out")

    # Arm it
    vehicle.mode = dronekit.VehicleMode("GUIDED")
    vehicle.armed = True

    # Confirm that it armed
    timeout = time.time() + 10
    while not vehicle.armed and time.time() < timeout:
        time.sleep(0.35)
    timed_out = time.time() >= timeout
    vehicle.close()
    sitl.stop()
    assert_false(timed_out, "Vehicle arming timed out")
Пример #16
0
  def connect(self):
    self.disconnect()

    print 'Connecting to vehicle on: %s' % self.dronekit_device
    self.vehicle = dronekit.connect(self.dronekit_device, wait_ready=False)
    
    print "Vehicle Connected!"
Пример #17
0
def test_mode(connpath):
    v = connect(connpath, wait_ready=True)

    # Ensure Mode is an instance of VehicleMode
    assert isinstance(v.mode, VehicleMode)

    v.close()
Пример #18
0
def main():
   target = "udpin:0.0.0.0:14550"
   vehicle = dronekit.connect(target,wait_ready=True)
   vehicle.mode = dronekit.VehicleMode("GUIDED")
   time.sleep(2)
   condition_yaw(vehicle,180);
   vehicle.close()
Пример #19
0
def main():
   target = "udpin:0.0.0.0:14550"
   vehicle = dronekit.connect(target,wait_ready=True)
   vehicle.mode = dronekit.VehicleMode("GUIDED")
   a_location = dronekit.LocationGlobal(35.80004274469795, -78.77133535151027, 154.3443094818955)
   vehicle.simple_goto(a_location,groundspeed=2.0)
   vehicle.close()
Пример #20
0
def test_state(connpath):
    vehicle = connect(connpath, wait_ready=['system_status'])

    assert_equals(type(vehicle.system_status), SystemStatus)
    assert_equals(type(vehicle.system_status.state), str)

    vehicle.close()
Пример #21
0
    def __init__(self, port):
        self.running = True

        # Initialize server
        self.rece_queue = Queue()
        self.send_queue = Queue()
        self.server = server(port, self.rece_queue, self.send_queue)

        # Initialize perception device
        self.dete_queue = Queue()
        self.video_queue = Queue()
        self.detector = Detector(self.dete_queue, self.video_queue)
        self.videoserver = videoserver(port+1, self.video_queue)

        # Initialize vehicle
        #self.vehicle = connect('/dev/ttyACM0', wait_ready=True)
        self.vehicle = connect('tcp:127.0.0.1:5760', wait_ready=True)
        #self.vehicle.home_location = self.vehicle.location.global_frame
        self.vehicle.airspeed = 1.2
        self.vehicle.groundspeed = 2
        self.vehicle.commands.clear()

        # Initialize waypoint
        self.waypoints = []

        # Initialize time variable
        self.last_gps = time()
Пример #22
0
def test_modes_set(connpath):
    vehicle = connect(connpath)

    def listener(self, name, m):
        assert_equals('STABILIZE', self._flightmode)

    vehicle.add_message_listener('HEARTBEAT', listener)
def test_empty_clear(connpath):
    vehicle = connect(connpath)

    # Calling clear() on an empty object should not crash.
    vehicle.commands.clear()
    vehicle.commands.upload()

    assert_equals(len(vehicle.commands), 0)
Пример #24
0
def main():
   target = "udpin:0.0.0.0:14550"
   vehicle = dronekit.connect(target,wait_ready=True)
   time.sleep(2)
   vehicle.gimbal.rotate(0,0,0)
   time.sleep(2)
   vehicle.close()
   time.sleep(2)
Пример #25
0
def quadCopter_create_handle(master_ip):
    """
    connect to vehicle device
    """
    print 'Connecting to vehicle on: %s' % master_ip
    vehicle = connect(master_ip, wait_ready=True)
    vehicle.groundspeed = 3
    return vehicle
Пример #26
0
def connect_to_vehicle():
    log(gcs_logger_name, "Connecting to UAV on: %s" % GCSSettings.UAV_CONNECTION_STRING)
    vehicle = dronekit.connect(GCSSettings.UAV_CONNECTION_STRING, wait_ready=True)
    vehicle.wait_ready('autopilot_version')
    log(gcs_logger_name, "Connected to UAV on: %s" % GCSSettings.UAV_CONNECTION_STRING)
    SUASSystem.suas_logging.log_vehicle_state(vehicle, gcs_logger_name)

    return vehicle
Пример #27
0
	def __init__(self):
		super(BaseDrone, self).__init__()
		self.commands_queque = deque()
		self.debug = True
		self.gps_lock = False
		self.vehicle = connect('/dev/tty.usbserial-DN00BMDJ,57600', await_params = True)
		self.vehicle.add_attribute_observer('gps_0', self.gps_callback)
		self._log("Drone gotten")
Пример #28
0
def test_110(connpath):
    vehicle = connect(connpath, wait_ready=True)

    # 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

    # Await armability.
    while not vehicle.is_armable:
        time.sleep(.1)
    
    # Change the vehicle into STABILIZE mode
    vehicle.mode = VehicleMode("GUIDED")

    # NOTE wait crudely for ACK on mode update
    time.sleep(3)

    # Define example callback for mode
    def armed_callback(vehicle, attribute, value):
        armed_callback.called += 1
    armed_callback.called = 0

    # When the same (event, callback) pair is passed to add_attribute_listener,
    # only one instance of the observer callback should be added.
    vehicle.add_attribute_listener('armed', armed_callback)
    vehicle.add_attribute_listener('armed', armed_callback)
    vehicle.add_attribute_listener('armed', armed_callback)
    vehicle.add_attribute_listener('armed', armed_callback)
    vehicle.add_attribute_listener('armed', armed_callback)

    # arm and see update.
    vehicle.armed = True
    # Wait for ACK.
    time.sleep(3)

    # Ensure the callback was called.
    assert armed_callback.called > 0, "Callback should have been called."

    # Rmove all listeners. The first call should remove all listeners
    # we've added; the second call should be ignored and not throw.
    # NOTE: We test if armed_callback were treating adding each additional callback
    # and remove_attribute_listener were removing them one at a time; in this
    # case, there would be three callbacks still attached.
    vehicle.remove_attribute_listener('armed', armed_callback)
    vehicle.remove_attribute_listener('armed', armed_callback)
    callcount = armed_callback.called

    # Disarm and see update.
    vehicle.armed = False
    # Wait for ack
    time.sleep(3)

    # Ensure the callback was called zero times.
    assert_equals(armed_callback.called, callcount, "Callback should not have been called once removed.")

    vehicle.close()
Пример #29
0
def main():
    print 'starting up'

    global vehicle, IP_adr, number_of_client, client_handler, OBP_tab


    if not internet_on():
        print 'no internet connection'
        exit()

    IP_adr = getIpAdress()
    number_of_client = 0

    client_handler = ClientWebPlugin(cherrypy.engine).subscribe()

    cherrypy.tools.websocket = WebSocketTool()

    cherrypy.config.update({'server.socket_host': IP_adr,
                            'server.socket_port': 8080})

    print 'waiting for drone'
    vehicle = dronekit.connect("udp:localhost:14550", rate=200, heartbeat_timeout=0)    # for local simulated drone
    # vehicle = dronekit.connect('/dev/ttyUSB0', baud=57600, rate=20)                       # for real drone
    print 'drone found, waiting ready'
    # vehicle.parameters['COM_RC_IN_MODE'] = 2;

    # listening on the arm message
    vehicle.add_attribute_listener('armed', arm_callback)

    # listening on all message (the call back is msg_handler)
    vehicle.add_message_listener('*', msg_handler)

    # getting OnBoard parameters
    OBP_tab = sorted(vehicle.parameters.keys())

    threading.Timer(5, send_plot_message).start() # start in 5 seconds

    conf = {
        '/':
        {
            'tools.sessions.on': True,
            'tools.staticdir.root': os.path.abspath(os.getcwd())
        },

        '/ws':
        {
            'tools.websocket.on': True,
            'tools.websocket.handler_cls': WebSocketHandler
        },

        '/static':
        {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': './public'
        }
    }
    cherrypy.quickstart(Cherrypy_server(), '/', conf)
Пример #30
0
def test_mavlink(connpath):
    vehicle = connect(connpath)
    out = MAVConnection('udpin:localhost:15668')
    vehicle._handler.pipe(out)
    out.start()

    vehicle2 = connect('udpout:localhost:15668')

    result = {'success': False}
    @vehicle2.on_attribute('location')
    def callback(*args):
    	result['success'] = True

    i = 20
    while not result['success'] and i > 0:
        time.sleep(1)

    assert result['success']
Пример #31
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import rospy as rp

from dronekit import connect, VehicleMode

import time

from geometry_msgs.msg import Twist, PoseStamped, TwistStamped, Vector3Stamped

# Connect to the Vehicle.
print("\nConnecting to vehicle ")
vehicle = connect('/dev/serial0', wait_ready=True, baud=57600)

while True:
    roll = vehicle.attitude.roll
    pitch = vehicle.attitude.pitch
    yaw = vehicle.attitude.yaw

    print(roll, pitch, yaw)
Пример #32
0
    )
    parser.add_argument('--id')
    args = parser.parse_args()

    connection_string = args.connect
    vehicleid = float(args.id)
    sitl = None

    if not connection_string:
        import dronekit_sitl
        sitl = dronekit_sitl.start_default()
        connection_string = sitl.connection_string()

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

    print " Type: %s" % vehicle._vehicle_type
    print " Armed: %s" % vehicle.armed
    print " System status: %s" % vehicle.system_status.state
    print " GPS: %s" % vehicle.gps_0
    print " Alt: %s" % vehicle.location.global_relative_frame.alt

    vehicle.add_attribute_listener('location', location_callback)

    while not vehicle.home_location:
        cmds = vehicle.commands
        cmds.download()
        cmds.wait_ready()
        if not vehicle.home_location:
            print " Waiting for home location ..."
Пример #33
0
print "Start simulator (SITL)"
import dronekit_sitl
sitl = dronekit_sitl.start_default()
connection_string = sitl.connection_string()

# Import DroneKit-Python
from dronekit import connect, VehicleMode

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

# 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")
Пример #34
0
)
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.
#   Set `wait_ready=True` to ensure default attributes are populated before `connect()` returns.
print("\nConnecting to vehicle on: %s" % connection_string)
vehicle = connect(connection_string, wait_ready=True)

vehicle.wait_ready('autopilot_version')

#os.system('iwconfig wlx9cefd5ff0bcd --connect udpin:0.0.0.14550')
'''        else:
        os.system('iwconfig wlx9cefd5ff0e3f --connect udpin:0.0.0.14550')
        connectionString = 'udpin:0.0.0.14550'
        print("\nConnecting to vehicle on: %s" % connectionString)
        vehicle = connect(connectionString, wait_ready=True)
#serial_port = serial.Serial('/dev/ttyUSB0', 9600)
'''


def print_data(data):
    print(data)
Пример #35
0
import time
from dronekit import connect, VehicleMode, LocationGlobalRelative, Command, LocationGlobal
from pymavlink import mavutil

import tkinter as tk

print('Connecting...')
vehicle = connect('udp:127.0.0.1:14551')

gnd_speed = 5  # [m/s]


def arm_and_takeoff(altitude):

    while not vehicle.is_armable:
        print("waiting to be armable")
        time.sleep(1)

    print("Arming motors")
    vehicle.mode = VehicleMode("GUIDED")
    vehicle.armed = True

    while not vehicle.armed:
        time.sleep(1)

    print("Taking Off")
    vehicle.simple_takeoff(altitude)

    while True:
        v_alt = vehicle.location.global_relative_frame.alt
        print(">> Altitude = %.1f m" % v_alt)
Пример #36
0
    # keep sending this message for `duration` seconds
    for x in range(0, int(duration * freq)):
        vehicle.send_mavlink(msg)
        time.sleep(1 / freq)


# disable dronekit logging first
print_log(
    "Warning: Annoying \"wx index out of bounds\" value is disabled. Mind this if you want to see log from dronekit."
)
dronekit_logger = logging.getLogger("autopilot")
dronekit_logger.disabled = True

# connect to vehicle
vehicle = dronekit.connect('/dev/ttyACM0', wait_ready=True, baud=921600)
print_log("Connection established.")
time.sleep(1)
print_status(vehicle)

try:
    # arm the vehicle
    print_log("Trying to arm vehicle...")
    vehicle.arm(timeout=5)

    # set to guided mode first
    vehicle.mode = dronekit.VehicleMode("GUIDED")

    # take off
    take_off(vehicle, 20)
def main():

    vehicle = connect("udp:localhost:14551", wait_ready=True)
    arm_and_takeoff(vehicle, 10)
    executeMission(vehicle)
    vehicle.mode = VehicleMode("LAND")
Пример #38
0
#arm2
from dronekit import connect, Command, LocationGlobal
#from pymavlink import mavutil
import time, sys, argparse, math

startime = time.time()
print("Connecting")
#connection_string = '127.0.0.1:14540'
connection_string = '/dev/ttyACM0'
arglist = [
    'parameters', 'gps_0', 'armed', 'mode', 'attitude', 'system_status',
    'location'
]
vehicle = connect(connection_string,
                  wait_ready=arglist,
                  heartbeat_timeout=300,
                  baud=57600)

print("Time to connection: %s" % str(time.time() - startime))
print(" Type: %s" % vehicle._vehicle_type)
print(" Armed: %s" % vehicle.armed)
print(" System status: %s" % vehicle.system_status.state)
print(" GPS: %s" % vehicle.gps_0)
print(" Alt: %s" % vehicle.location.global_relative_frame.alt)
print("GPS coordinates %s" % vehicle.location.global_frame)
print("Armed: %s" % vehicle.armed)

print("isarmable: %s" % vehicle.is_armable)

vehicle.armed = True
print("Armed after: %s" % vehicle.armed)
Пример #39
0
#     note:
#       0 = Quit program
#       1 = Disarm
#       2 = Arm

# setting up modules used in the program
from dronekit import connect
import exceptions
import socket
import time
import os

# clear screen
os.system("clear")
# establish connection to the vehicle
vehicle = connect("/dev/ttyS0", heartbeat_timeout=30, baud=57600)
# print action to be carried
print("Set vehicle state to disarm")
# for safety, disarm the vehicle before doing anything
vehicle.armed = False
print("Armed: %s\n" % vehicle.armed)
time.sleep(5)
# clear screen
os.system("clear")

# initialization
a = 1

while (a > 0):

    # print the current vehicle state
Пример #40
0
# import dronekit_sitl
# sitl = dronekit_sitl.start_default()
# connection_string = sitl.connection_string()

# Import DroneKit-Python
from dronekit import connect, VehicleMode

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

# Connect to the Vehicle.
redleader='udpin:0.0.0.0:14550'
solo=redleader
print("Connecting to solo: %s" % (solo))
vehicle = connect(solo, 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()
Пример #41
0
value_lower = 60
value_upper = 180
min_contour_area = 500 # piksel terkecil pada kontur sebelum itu terdaftar sebagai target

#kamera
horizontal_resolution = 1280
vertical_resolution = 720

camera = cv2.VideoCapture(0)

#koneksi ke wahana
connection_string = "/dev/ttyS0"
baud_rate = 57600

print('connecting..')
vehicle = connect(connection_string, baud=baud_rate, wait_ready=True)

print('start visual landing')

def send_land_message(x, y):
    msg = vehicle.message_factory.landing_target_encode(
        0,       
        0,       
        0,       
        (x-horizontal_resolution/2)*horizontal_fov/horizontal_resolution,
        (y-vertical_resolution/2)*vertical_fov/vertical_resolution,
        0,       
        0,0)     
    vehicle.send_mavlink(msg)
    vehicle.flush()
Пример #42
0
def main():
    global rollpitchyaw
    #listener = GestureListener()
    try:
        yaw_on_entry = 0
        left_coming_back = False
        right_coming_back = False
        first_frame = None
        controller = Leap.Controller()
        time.sleep(1)
        roll = 0
        pitch = 0
        yaw = 0
        height = 0
        alpha = 0.2
        print "Leap connected"
        # start_time = time.time()
        rpc_mapper = interp1d([ROLL_PITCH_YAW_MIN, ROLL_PITCH_YAW_MAX],
                              [ROLL_PITCH_YAW_MIN_MAP, ROLL_PITCH_YAW_MAX_MAP])
        throttle_mapper_takeoff = interp1d(
            [THROTTLE_MIN_TAKEOFF, THROTTLE_MAX_TAKEOFF],
            [THROTTLE_MIN_TAKEOFF_MAP, THROTTLE_MAX_TAKEOFF_MAP])
        throttle_mapper_flight = interp1d(
            [THROTTLE_MIN_FLIGHT, THROTTLE_MAX_FLIGHT],
            [THROTTLE_MIN_FLIGHT_MAP, THROTTLE_MAX_FLIGHT_MAP])
        vehicle = connect('com3', wait_ready=True, baud=57600)

        print "Connected"
        vehicle.mode = VehicleMode('STABILIZE')
        vehicle.armed = True
        print "Armed"
        vehicle.add_attribute_listener('attitude', attitude_callback)
        time.sleep(3)
        #controller.add_listener(listener)
        while True:
            #print "inside loop"
            # if time.time() - start_time > 0.01:

            #start_time = time.time()
            #$print(controller.is_paused)
            if controller.is_connected:  #and vehicle.location.global_relative_frame.alt > 0.3:
                frame = controller.frame()
                if len(frame.hands) == 2:
                    if left_coming_back:
                        height = 0
                        left_coming_back = False
                        #if not first_frame:
                        print "After coming back"
                        first_frame = hand_stable(frame, controller)
                        frame = controller.frame()
                    if right_coming_back:
                        right_coming_back = False
                        roll = 0
                        pitch = 0
                        yaw = 0
                    if not first_frame:
                        print "First time"
                        first_frame = hand_stable(frame, controller)
                        frame = controller.frame()
                        time.sleep(0.1)
                        yaw_on_entry = rollpitchyaw.yaw
                        #print "Set throttle to 1500"
                    left_hand, right_hand = get_left_right_hands(frame)
                    #for hand in frame.hands:
                    #print str(hand.is_valid)
                    #if hand.is_left:
                    if height < 0:
                        height = 0
                    elif height > 150:
                        height = 150
                    height = low_pass_filter(
                        height,
                        left_hand.translation(first_frame).y, alpha)

                    # print "Filtered Height: " + str(height) + " Original: " + str(left_hand.translation(first_frame).y)
                    #else:
                    direction = right_hand.direction
                    normal = right_hand.palm_normal
                    yaw = direction.yaw * Leap.RAD_TO_DEG
                    pitch = low_pass_filter(pitch,
                                            direction.pitch * Leap.RAD_TO_DEG,
                                            alpha)
                    roll_error = -clip((normal.roll * Leap.RAD_TO_DEG) / 4, -7,
                                       7) - rollpitchyaw.roll
                    pitch_error = clip((normal.pitch * Leap.RAD_TO_DEG) / 4,
                                       -7, 7) - rollpitchyaw.pitch
                    yaw_error = clip((normal.yaw * Leap.RAD_TO_DEG) / 4, -10,
                                     10) + yaw_on_entry - rollpitchyaw.yaw
                    #roll = low_pass_filter(roll, normal.roll * Leap.RAD_TO_DEG, alpha)
                    roll = normal.roll * Leap.RAD_TO_DEG
                    # yaw = low_pass_filter(yaw, direction.yaw * Leap.RAD_TO_DEG, alpha)
                    # pitch, roll, yaw = direction.pitch * Leap.RAD_TO_DEG
                    # normal.roll * Leap.RAD_TO_DEG
                    # direction.yaw * Leap.RAD_TO_DEG
                    # print "Pitch: " + str(pitch) + " Roll: " + str(roll) + " Yaw: " + str(yaw)

                    #print "Sending roll: " + str(roll) + ' mapped to: ' + str(int(rpc_mapper(roll)))
                    vehicle.channels.overrides['1'] = clip(
                        1498 + 12 * int(roll_error), 989, 2007)
                    # vehicle.channels.overrides['2'] = clip(1501 -  10*int(pitch_error), 992 , 2010)
                    # vehicle.channels.overrides['4'] = clip(1500 -  10*int(yaw_error), 990 , 2010)
                    print " Roll: " + str(roll) + " PWM: " + str(
                        vehicle.channels['1']) + " roll eror: " + str(
                            roll_error) + " drone roll: " + str(
                                rollpitchyaw.roll)
                    # vehicle.channels.overrides['2'] = int(rpc_mapper(pitch))
                    # vehicle.channels.overrides['4'] = int(rpc_mapper(yaw))
                    # vehicle.channels.overrides['3'] = int(throttle_mapper_takeoff(height))
                    time.sleep(0.028)
                elif len(frame.hands) == 1:
                    frame = controller.frame()
                    if frame.hands[0].is_left:
                        left_coming_back = False
                        #if not right_coming_back:
                        #height = 0
                        #right_coming_back = True
                        if not first_frame:
                            height = 0
                            print "After coming back"
                            first_frame = hand_stable(frame, controller)
                            frame = controller.frame()
                        #right_coming_back = True
                        #import pdb; pdb.set_trace()
                        if height < 0:
                            height = 0
                        elif height > 150:
                            height = 150
                        height = low_pass_filter(
                            height, frame.hands[0].translation(first_frame).y,
                            alpha)

                        print "Filtered Height: " + str(
                            height) + " Original: " + str(
                                frame.hands[0].translation(first_frame).y)
                        # vehicle.channels.overrides['3'] = int(throttle_mapper_takeoff(height))
                    else:
                        #right_coming_back = False
                        if not left_coming_back:
                            #left_coming_back = True
                            first_frame = None
                            roll = 0
                            pitch = 0
                            yaw = 0
                        for hand in frame.hands:
                            right_coming_back = False
                            direction = hand.direction
                            normal = hand.palm_normal
                            yaw = direction.yaw * Leap.RAD_TO_DEG
                            pitch = low_pass_filter(
                                pitch, direction.pitch * Leap.RAD_TO_DEG,
                                alpha)
                            roll = low_pass_filter(
                                roll, normal.roll * Leap.RAD_TO_DEG, alpha)
                            yaw = low_pass_filter(
                                yaw, direction.yaw * Leap.RAD_TO_DEG, alpha)
                            print "Pitch: " + str(pitch) + " Roll: " + str(
                                roll) + " Yaw: " + str(yaw)
                            vehicle.channels.overrides['1'] = int(
                                rpc_mapper(roll))
                            # vehicle.channels.overrides['2'] = int(rpc_mapper(pitch))
                            # vehicle.channels.overrides['4'] = int(rpc_mapper(yaw))

                    time.sleep(0.028)
                else:
                    if not left_coming_back and not right_coming_back:
                        # print "Relinquishing control"
                        # vehicle.channels.overrides['3'] = 1300
                        # print "Slowing down motor"
                        # time.sleep(0.1)
                        # vehicle.channels.overrides['1'] = None
                        # vehicle.channels.overrides['2'] = None
                        # vehicle.channels.overrides['3'] = None
                        # vehicle.channels.overrides['4'] = None
                        vehicle.channels.overrides = {}
                        # print "Release channels"
                        time.sleep(0.1)
                        first_frame = None
                        roll = 0
                        pitch = 0
                        yaw = 0
                        height = 0
                        left_coming_back = True
                        right_coming_back = True
            else:
                # print "Relinquishing control"
                # vehicle.channels.overrides['3'] = 1300
                # print "Slowing down motor"
                # time.sleep(0.1)
                # vehicle.channels.overrides['1'] = None
                # vehicle.channels.overrides['2'] = None
                # vehicle.channels.overrides['3'] = None
                # vehicle.channels.overrides['4'] = None
                vehicle.channels.overrides = {}
                # print "Release channels"
                #vehicle.close()
                # print "Close telemetry connection"
                time.sleep(.028)
                #break
    except KeyboardInterrupt, ValueError:
        # print "Relinquishing control"
        # vehicle.channels.overrides['1'] = None
        # vehicle.channels.overrides['2'] = None
        # vehicle.channels.overrides['3'] = None
        # vehicle.channels.overrides['4'] = None
        # time.sleep(1)
        # vehicle.armed = False
        # while vehicle.armed:
        #      print "Disarming"
        # time.sleep(1)
        # vehicle.close()
        # print "Interrupted"
        return
Пример #43
0
            if distance < 220:
                condition_yaw(drone, 90)
                set_velocity_body(drone, 0, .005, 0)
                time.sleep(10)
                distance = getdistance()
                print("90")
                if distance < 220:
                    condition_yaw(drone, 315)
                    set_velocity_body(drone, .005, -.005, 0)
                    time.sleep(10)
                    distance = getdistance()
                    print("315")
                    if distance < 220:
                        condition_yaw(drone, 270)
                        set_velocity_body(drone, 0, -.005, 0)
                        time.sleep(10)
                        distance = getdistance()
                        print("270")
                        if distance < 220:
                            drone.mode = VehicleMode("LAND")
        set_velocity_body(drone, 0.5, 0, 0)
        time.sleep(1)


drone = connect('127.0.0.1:14551', wait_ready=True)

arm_and_takeoff(2)

drone.airspeed = .5

scan()
from dronekit import connect, VehicleMode, time
import dronekit
import os

vehicle = dronekit.connect("/dev/ttyUSB0", baud=57600, wait_ready=True)
vehicle.wait_ready(timeout=120)

while not vehicle.is_armable:
    print(" Waiting for vehicle to initialise...")
    time.sleep(3)
print("Arming motors")
vehicle.mode = VehicleMode("GUIDED")
vehicle.armed = True
# Author  : Akshit Gandhi												                                                #
#															                                                            #
#by running this code, drone will go point A to point B autonomously.												    #
#															                                                            #
# Requrinment: Refer Tutorial Folder											                                        #
#########################################################################################################################


from dronekit import connect, VehicleMode, LocationGlobalRelative
import time




print "connecting to vehicle...."
vehicle = connect('/dev/ttyAMA0', baud = 57600)
print "connected"

#changing vehicle mode to stabilize
print "\nSet Vehicle.mode = (currently: %s)" % vehicle.mode.name
while not vehicle.mode=='GUIDED':
    vehicle.mode = VehicleMode('GUIDED')
    vehicle.flush()

print "vehicle mode: %s" % vehicle.mode

# ARMING the vehicle
vehicle.armed = True
while not vehicle.armed:
    vehicle.armed = True
    vehicle.flush()
Пример #46
0
import argparse  
parser = argparse.ArgumentParser(description='Get a flight from droneshare and send as waypoints to a vehicle. Connects to SITL on local PC by default.')
parser.add_argument('--connect', default='127.0.0.1:14550',
                   help="vehicle connection target. Default '127.0.0.1:14550'")
parser.add_argument('--mission_id', default='101',
                   help="DroneShare Mission ID to replay. Default is '101'")                   
parser.add_argument('--api_server', default='https://api.3drobotics.com',
                   help="API Server. Default is Droneshare API (https://api.3drobotics.com)")
parser.add_argument('--api_key', default='89b511b1.d884d1cb57306e63925fcc07d032f2af',
                   help="API Server Key (default should be fine!)")
args = parser.parse_args()


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



def _decode_list(data):
    """A utility function for decoding JSON strings from unicode"""
    rv = []
    for item in data:
        if isinstance(item, unicode):
            item = item.encode('utf-8')
        elif isinstance(item, list):
            item = _decode_list(item)
        elif isinstance(item, dict):
            item = _decode_dict(item)
        rv.append(item)
    return rv
Пример #47
0
print "Here we go!"

# Import DroneKit-Python
from dronekit import connect, VehicleMode, LocationGlobalRelative, LocationGlobal
from pymavlink import mavutil  # Needed for command message definitions
import time
import math
import requests

# Connect to the Vehicle.
print("\nConnecting to vehicle")
#vehicle = connect(/dev/ttyACM0, wait_ready=True) # pixhawk usb
#vehicle = connect("/dev/ttyUSB0", wait_ready='armed', baud=57600) # telemetry usb
#vehicle = connect("/dev/ttyUSB0", baud=57600) # telemetry usb
vehicle = connect("/dev/ttyS0", baud=57600)  # telemetry usb

# Using the ``wait_ready(True)`` waits on :py:attr:`parameters`, :py:attr:`gps_0`,
# :py:attr:`armed`, :py:attr:`mode`, and :py:attr:`attitude`. In practice this usually
# means that all supported attributes will be populated.

# 'parameters'
#vehicle.wait_ready('gps_0','armed','mode','attitude')
vehicle.wait_ready('gps_0')

# 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
Пример #48
0
#!/usr/bin/python
from dronekit import connect, VehicleMode, LocationGlobalRelative
import time

vehicle = connect('tcp:127.0.0.1:5760', wait_ready=True)
print "Arming motors:"
vehicle.mode = VehicleMode("GUIDED")
print "Global Location (relative altitude): %s" % vehicle.location.global_relative_frame
Пример #49
0
from dronekit import connect, VehicleMode, LocationGlobalRelative
from pymavlink import mavutil
import time

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--connect', default="/dev/ttyACM2")
#parser.add_argument('--connect', default="tcp:127.0.0.1:5760")
args = parser.parse_args()

# Connect to the Vehicle
print 'Connecting to vehicle on: %s' % args.connect
vehicle = connect("/dev/ttyACM2", baud=57600, wait_ready=True)
#vehicle = connect('tcp:127.0.0.1:5760', wait_ready=True)

print "Checks vehicle's armable state"
# Don't let the user try to arm until autopilot is ready
#vehicle.mode    = VehicleMode("STABILIZE")
while not vehicle.is_armable:
    print " Waiting for vehicle to initialise..."
    time.sleep(1)

#if (mission_start=="yes")
print "Arming motors in 5 seconds from now"
time.sleep(5)
# Copter should arm in GUIDED mode
vehicle.mode = VehicleMode("GUIDED")
vehicle.armed = True

#while not vehicle.armed: time.sleep(1)
while not vehicle.armed:
Пример #50
0
def connectVehicle(connection_string):
	global vehicle		 
	# Connect to the Vehicle
	print 'Connecting to vehicle on: %s' % connection_string
	vehicle = connect(connection_string, wait_ready=True, baud=921600)
	print 'Connected!'
from dronekit import connect, VehicleMode, LocationGlobalRelative, LocationGlobal, Command
from pymavlink import mavutil
import cv2
import numpy as np
import math

cap = cv2.VideoCapture(0)

#cap.set(3, 640)# width resolution
#cap.set(4, 480)# heigh resolution

# Connect to the Vehicle
vehicle = connect('/dev/ttyUSB0', wait_ready=True,baud=921600)
#vehicle = connect('127.0.0.1:14550', wait_ready=True)

cmds = vehicle.commands
cmds.download()
cmds.wait_ready()
vel_x = 0
vel_y = 0
vel_z = 0

pointauth = 2
settime = 0
mode_changed = 0
count = 0
dropped = False
once = False
settime = 0

def distance_to_current_waypoint():
Пример #52
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function
from dronekit import connect, VehicleMode, LocationGlobal
import time
import math
import os
import sys

vehicle = connect('127.0.0.1:14551', wait_ready=True, rate=8)

vehicle.wait_ready('autopilot_version')

print("Basic pre-arm checks")

vehicle.parameters["SR0_EXTRA1"] = 8

print("Setting parameters ...")

for param in sys.argv:
    strings = param.split("=")
    if len(strings) == 2:
        vehicle.parameters[strings[0]] = float(strings[1])

print("\nSet Vehicle.armed=True (currently: %s)" % vehicle.armed)
vehicle.armed = True

if not vehicle.armed:
    print(" Waiting for arm")
Пример #53
0
from __future__ import print_function
from dronekit import connect, VehicleMode

v = connect('/dev/ttyACM0', wait_ready=True, baud=57600)

print(v.gps_0)
print("ekf_ok = ", v.ekf_ok)
print("is_armable = ", v.is_armable)
print(v.location.global_relative_frame)
Пример #54
0
def main():
    path_output_dir = "./raw_image"
    create_or_purge_dir(path_output_dir)

    vehicle = None

    if not DEBUG:
        while True:
            try:
                vehicle = dronekit.connect("/dev/ttyUSB0",
                                           wait_ready=True,
                                           baud=1500000)
            except:
                print("Connection failed")
                time.sleep(3)
            else:
                print("Connected")
                break

        while not vehicle.home_location:
            cmds = vehicle.commands
            cmds.download()
            cmds.wait_ready()
            if not vehicle.home_location:
                print(" Waiting for home location ...")
        # We have a home location, so print it!
        print("\n Home location: %s" % vehicle.home_location)

    while not vehicle.armed:
        print("waiting to be armed")
        time.sleep(1)

    vidcap = cv2.VideoCapture(0)

    count = 0

    while vidcap.isOpened():
        success, image = vidcap.read()
        if success:

            current_path = os.path.join(path_output_dir, '%d.JPEG') % count
            cv2.imwrite(current_path, image)

            if DEBUG:
                lat = 1
                lon = 1
                alt = 1
                hdg = 1
            else:
                lat = vehicle.location.global_relative_frame.lat
                lon = vehicle.location.global_relative_frame.lon
                alt = vehicle.location.global_relative_frame.alt
                if alt < 0:
                    alt = 0.15
                hdg = vehicle.heading

            print("Current location is at: lat: %f, lon: %f, alt %f, hdg %f" %
                  (lat, lon, alt, hdg))
            geotag.write_geo_tag(current_path, lat, lon, alt, hdg)

            count += 1
        else:
            break
        time.sleep(3)

    cv2.destroyAllWindows()
    vidcap.release()
Пример #55
0
import time
from dronekit import Vehicle, connect

# vehicle = connect('tcp:127.0.0.1:5760', wait_ready=True, timeout=60)
vehicle = connect('udp:127.0.0.1:14551', wait_ready=True, timeout=60)

#RTL_ALTが変更された際に通知を受け取る
#デコレーターの設定
@vehicle.parameters.on_attribute('RTL_ALT')
def decorated_RTL_ALT_callback(self, attr_name, value):
	print("デコレーター: %s が %s に変更されました!" % (attr_name, value))

while True:
    time.sleep(1)
    #file_name = str(file_name)+".jpg"
    #cv.imwrite(file_name, frame)

    lat_deg = to_deg(lat, ["S", "N"])
    lng_deg = to_deg(lng, ["W", "E"])

    exiv_lat = (change_to_rational(lat_deg[0]), change_to_rational(lat_deg[1]),
                change_to_rational(lat_deg[2]))
    exiv_lng = (change_to_rational(lng_deg[0]), change_to_rational(lng_deg[1]),
                change_to_rational(lng_deg[2]))

    gps_ifd = {
        piexif.GPSIFD.GPSVersionID: (2, 0, 0, 0),
        piexif.GPSIFD.GPSAltitudeRef: 1,
        piexif.GPSIFD.GPSAltitude: change_to_rational(round(altitude)),
        piexif.GPSIFD.GPSLatitudeRef: lat_deg[3],
        piexif.GPSIFD.GPSLatitude: exiv_lat,
        piexif.GPSIFD.GPSLongitudeRef: lng_deg[3],
        piexif.GPSIFD.GPSLongitude: exiv_lng,
    }

    exif_dict = {"GPS": gps_ifd}
    exif_bytes = piexif.dump(exif_dict)
    piexif.insert(exif_bytes, file_name)


if __name__ == '__main__':
    vehicle = connect("127.0.0.1:14550", wait_ready=True)
    print("[INFO] Drone Check Complete")
    hello()
Пример #57
0
print "Start simulator (SITL)"
# import dronekit
# import socket
import exceptions
import dronekit_sitl
sitl = dronekit_sitl.start_default()
connection_string = sitl.connection_string()

from dronekit import connect, VehicleMode, LocationGlobalRelative
import time

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

try:
    vehicle = connect(connection_string, wait_ready=True, heartbeat_timeout=15)

# Bad TCP connection
except socket.error:
    print 'No server exists!'

# Bad TTY connection
except exceptions.OSError as e:
    print 'No serial exists!'

# API Error
except dronekit.APIException:
    print 'Timeout!'

# Other error
except:
Пример #58
0
import time

# Initialization
# Connection string for Ubuntu = /dev/ttyUSB0 | Windows = COMXX | MAVProxy = 127.0.0.1:14551.
connection_string = "127.0.0.1:14551"
gps_save = {}  # Create an empty GPS coordinate dictionary.
gps_save["latitude_longitude"] = [
]  # Insert the dictionary with latitude_longitude variable.

# Opening Messages
print("\n\n---Welcome to TSUPORT Waypoint Calibration Program---\n\n")

# Connect to The Vehicle
print("Connecting to vehicle on: %s" % connection_string)
vehicle = connect(
    connection_string, wait_ready=False, heartbeat_timeout=100, baud=57600
)  # wait_ready = False is used to bypass the paramters loading and connecting the vehicle first.
vehicle.wait_ready(True,
                   timeout=150)  # wait_ready = True is to load parameters now.
#while vehicle.gps_0.fix_type < 6 and vehicle.gps_0.eph <= 200: #and vehicle.gps_0.epv < 200:
while vehicle.gps_0.satellites_visible < 6 and vehicle.gps_0.eph <= 200:
    # EPH = HDOP * 100 | Ideal HDOP <= 1 | Excellent HDOP <= 2 | Good HDOP <= 5 | Moderate HDOP <= 10.
    print "Waiting for GPS...:", vehicle.gps_0.fix_type
    time.sleep(1)
print "Satellites Count = ", vehicle.gps_0.satellites_visible

# Main Menu
waypoint_data = int(raw_input("Please input the number of waypoints: "))
loop = 0
while (loop < waypoint_data):
    click = raw_input("Click enter to take GPS coordinate {}!".format(loop +
Пример #59
0
parser = argparse.ArgumentParser(description='commands')
parser.add_argument('--connect')
parser.add_argument('--destinationLat')
parser.add_argument('--destinationLong')
args = parser.parse_args()

# getting connection string from input arguments
#connection_string = args.connect
connection_string = "/dev/ttyS0"
# getting and setting target lat and lon from input arguments
finalLat = 30.6234573
finalLon = -96.3450102

#Connect to the vehicle
print("Connection to the vehicle on %s" % connection_string)
vehicle = connect(connection_string, baud=57600, wait_ready=False)


#----------------------------dronekit functions----------------------------
def arm_and_takeoff():
    print("Arming motors--2 sec wait")

    time.sleep(2)

    # wating for vehicle to be armable
    #while not vehicle.is_armable:
    #time.sleep(1)

    # once armable vehile set to GUIDED mode
    vehicle.mode = VehicleMode("GUIDED")
    print("--Bot Mode-- %s" % vehicle.mode)
Пример #60
0
from dronekit import connect, VehicleMode
import time

vehicle = connect('/dev/ttyACM0', wait_ready=False)


def arm_and_takeoff(aTargetAltitude):
    """
    Arms vehicle and fly to aTargetAltitude.
    """

    print "Basic pre-arm checks"
    # Don't try to arm until autopilot is ready
    #while not vehicle.is_armable:
    #print " Waiting for vehicle to initialise..."
    #time.sleep(1)

    print "Arming motors"
    # Copter should arm in GUIDED mode
    vehicle.mode = VehicleMode("GUIDED")
    vehicle.armed = True

    # Confirm vehicle armed before attempting to take off
    while not vehicle.armed:
        print " Waiting for arming..."
        time.sleep(1)

    print "Taking off!"
    vehicle.simple_takeoff(aTargetAltitude)  # Take off to target altitude

    # Wait until the vehicle reaches a safe height before processing the goto (otherwise the command