Пример #1
0
 def setup(self):
     #global Drones
     # Create a list of all drones
     # If Tello mode is set then it creates Tello drones
     if GC.TelloMode:
         #self.Drones = [TD.TelloDrone(200,300), TD.TelloDrone(400,300,IP_Address="0.0.0.1")]
         #self.Drones = [TD.TelloDrone(200,300,65*2), TD.TelloDrone(400,300,65*3), TD.TelloDrone(300,200)]
         self.Drones = []
         for i in range(GC.Drone_Number):
             self.Drones.append(TD.TelloDrone(100 + 100*i, 300, MaxSpeed=GC.Uniform_Drones_Speed,
                                              MaxYawSpeed=GC.Uniform_Yaw_Speed, IP_Address=f'0.0.0.{i}'))
     # Otherwise it creates 3 drones with joystick, or 2 without joystick
     else:
         if pygame.joystick.get_count() == 0:
             self.Drones = [Drone.Drone(200, 300, GC.FPS),
                            Drone.Drone(800, 300, GC.FPS, GC.Uniform_Drones_Speed, 0,
                                        pygame.K_j, pygame.K_l,pygame.K_k, pygame.K_i)]
         else:
             self.Drones = [Drone.Drone(200, 300, GC.FPS),
                            Drone.Drone(800, 300, GC.FPS, GC.Uniform_Drones_Speed, 1,
                                        Joystick_xAxis="Axis0", Joystick_yAxis="Axis1"),
                            Drone.Drone(500, 300, GC.FPS, GC.Uniform_Drones_Speed, 2,
                                        "Button13", "Button14", "Button12", "Button11")]
     # Creates collision array for colouring stuff red on collision
     self.DronesCollided = []
     for i in range(len(self.Drones)):
         self.DronesCollided.append(False)
     #self.Drones = [Drone.Drone(200,300), Drone.Drone(820,300), Drone.Drone(510, 100, 1, pygame.K_j, pygame.K_l, pygame.K_k, pygame.K_i),Drone.Drone(510, 500, 1, pygame.K_j, pygame.K_l, pygame.K_k, pygame.K_i)]
     # Sets up the Tello communication object by providing the Tello drones
     for i in self.Drones:
         if i.__class__ == TD.TelloDrone:
             if GC.TelloMode:
                 self.TC.Add_Drone(i)
         else:
             continue
Пример #2
0
 def reinitialize(self):
     
     #supplies available
     
     #This can be stored in a database
     #where values can be updated
     self.supplies = {
             "RBC" : 10,
             "WBC" : 5,
             "Blood plasma" : 9,
             "Platelets" : 8,
             "Anti venom" : 7 
             }
     
     #These are the list of drones
     #available with default values
     
     #This can be stored in a database
     #where values can be changed
     #depending on the data sent
     #by the drone
     
     self.d1 = Drone.drone('1', 0, 50.0, 15.0, 15.0, '', 5.0, 0.0, 150.0, '')
     self.d2 = Drone.drone('2', 0, 600.0, 13.0, 3.0, '', 60.0, 0.0, 100.0, '')
     self.d3 = Drone.drone('3', 1, 300.0, 15.0, 8.0, '', 30.0, 5.0, 150.0, '')
     self.d4 = Drone.drone('4', 1, 50.0, 13.0, 7.0, '', 5.0, 10.0, 100.0, '')
     self.d5 = Drone.drone('5', 1, 1000.0, 14.0, 0.0, '', 100.0, 0.1, 150.0, '')    
     self.drones = [self.d1, self.d2, self.d3, self.d4, self.d5]
     self.selected = None
Пример #3
0
def deliver_most_items_from_product(customer_id, product_id, maximum_load,
                                    weights, order, warehouses, commands,
                                    total_time, deadline, number_of_drones):
    last_drone_id = 0
    number_of_items_left = 1
    drone = Drone.Drone(last_drone_id, maximum_load, warehouses[0].position)
    warehouse_chosen = order.find_next_best_warehouse(drone, warehouses,
                                                      product_id)
    if not warehouse_chosen:
        pass
    while number_of_items_left != 0 and warehouse_chosen:
        next_drone_id = get_next_drone_number(last_drone_id, number_of_drones)
        drone = Drone.Drone(next_drone_id, maximum_load,
                            warehouses[0].position)

        loaded = load_product_from_warehouse_to_drone(product_id, weights,
                                                      number_of_items_left,
                                                      warehouse_chosen, drone,
                                                      order, warehouses,
                                                      total_time, commands, 1)
        if not loaded:
            break
        number_of_items_loaded, total_time = loaded
        total_time = deliver_product_to_location_with_drone(
            customer_id, product_id, weights, number_of_items_loaded, drone,
            order, order.position, total_time, commands, 1)
        if total_time > deadline:
            break
        last_drone_id = drone.drone_id
        number_of_items_left = 0
    return total_time
Пример #4
0
def test_that_udpate_drones_deletes_items_in_drone_list():
    drone_list = [
        Drone(0, AppchannelCommunicate(1)),
        Drone(1, AppchannelCommunicate(1))
    ]
    expected_length = 0
    updateDrones(drone_list)
    actual_length = len(drone_list)
    assert expected_length == actual_length
Пример #5
0
def sequential_build_deliveries(problem, parameters, sorted_savings,
                                client_pairs):
    """This function returns a list of instances of class Delivery calculated with the use of the sequential Clarke
    and Wright algorithm. Single client deliveries are added at the end if necessary."""

    deliveries_list = []
    j = 0
    # clients_restants = problem.clients_list
    client_pairs_modifie = client_pairs
    while j < len(client_pairs) + 1:
        i = -1
        a = 0
        k = 0
        while k < len(client_pairs_modifie):
            pair = client_pairs_modifie[k]
            if sorted_savings[k] >= 0:
                if i < 0:
                    route_a = dro.Route([], problem.depot)
                    delivery_a = dro.Delivery(route_a, parameters)
                else:
                    delivery_a = deliveries_list[-1]
                route_b = dro.Route([pair[0], pair[1]], problem.depot)
                delivery_b = dro.Delivery(route_b, parameters)
                delivery_c = sequential_merge_if_possible(
                    delivery_a, delivery_b)
                # if k == 3 and j == 1:
                #     print (4, delivery_a.clients_list, delivery_b.clients_list, delivery_c)
                if delivery_c:
                    if i < 0:
                        deliveries_list.append(delivery_c)
                        i += 1
                    else:
                        deliveries_list[-1] = delivery_c
                        k = 0
                    # a = 0
                if not delivery_c:
                    a += 1
            k += 1
        if a == len(client_pairs_modifie):
            add_single_client_deliveries(deliveries_list, problem, parameters)
            # for delivery in deliveries_list:
            #     delivery.print()
            return deliveries_list
        client_pairs_modifie = []
        for k, pair in enumerate(client_pairs):
            if (search_deliveries_for_client(pair[0], deliveries_list) is None) and \
                    (search_deliveries_for_client(pair[1], deliveries_list) is None):
                client_pairs_modifie.append(pair)
        # if j == 0:
        #     print(client_pairs_modifie)

        # clients_restants = []
        # for client in problem.clients_list:
        #     if search_deliveries_for_client(client, deliveries_list) is None:
        #         clients_restants.append(client)
        j += 1
Пример #6
0
def test_that_udpate_drones_add_new_drones_to_the_list(mocker):
    drone_list = [
        Drone(0, AppchannelCommunicate(1)),
        Drone(1, AppchannelCommunicate(1))
    ]
    expected_list = ['2', '3']
    mocker.patch('Appchannel.connectToDrone', return_value=[('2', ), ('3', )])
    updateDrones(drone_list)
    actual_list = [i.getId() for i in drone_list]
    assert expected_list == actual_list
Пример #7
0
def test_that_udpate_drones_doesnt_add_already_included_drones(mocker):
    drone_list = [
        Drone(0, AppchannelCommunicate(1)),
        Drone(1, AppchannelCommunicate(1))
    ]
    expected_list = ["2", "3"]
    mocker.patch('Appchannel.connectToDrone',
                 return_value=[("2", ), ("3", ), ("2", )])
    updateDrones(drone_list)
    actual_list = [i.getId() for i in drone_list]
    assert expected_list == actual_list
Пример #8
0
    def __init__(self):
        self.initialize_variables()
        self.initialize_pub_sub()
        # self.uav = Drone(self.vehical_id,2*ID,0) # id, x, y
        self.uav = Drone(self.vehical_id)
        self.uav.desired_pose.pose.position.x = 1 * ID
        self.uav.desired_pose.pose.position.y = 0
        self.uav.desired_pose.pose.position.z = 3
        self.uav.command_format = 0
        # Postion
        self.uav.set_offset(1 * ID, 0)
        self.uav.start_controller = True  # Starts giving the commands.

        # rospy.Timer(rospy.Duration(0.025), self.controller)
        # rospy.Timer(rospy.Duration(0.5), self.update_parameters)
        rospy.Timer(rospy.Duration(0.001), self.get_sensor_data)
Пример #9
0
 def __init__(self):
     self.Aircraft = Drone(async=True)
     self.aircraft_name = "FF " + input("Enter the Aircraft Name for this Drone")
     self.pilot_name = input("Your Name:")
     cmd.Cmd.__init__(self)
     self.intro = "ArcherVMCashew/ArcherVMPeridot 3.4.3 Dronesseus Tarmac \n " + self.Aircraft.aircraft_name
     self.prompt = self.name + ", You are clear for takeoff."
def getObjects():
	trees = set()
	sheep = set()
	wolves = set()
	drones = set()

	for i in range(num_trees):
		trees.add(Tree.Tree())

	for i in range(num_drones):
		drones.add(Drone.Drone(num_sheep))

	for i in range(num_wolves):
		if (i == num_wolves-1):
			wolves.add(Wolf.Wolf(True))
		else:
			wolves.add(Wolf.Wolf(False))

	for i in range(num_sheep):
		if (i == num_sheep-1):
			sheep.add(Sheep.Sheep(True))
		else:
			sheep.add(Sheep.Sheep(False))

	return {"trees": trees, "sheep": sheep, "wolves": wolves, "drones": drones}
Пример #11
0
class DronesseusCockpit(cmd.Cmd):
     def __init__(self):
         self.Aircraft = Drone(async=True)
         self.aircraft_name = "FF " + input("Enter the Aircraft Name for this Drone")
         self.pilot_name = input("Your Name:")
         cmd.Cmd.__init__(self)
         self.intro = "ArcherVMCashew/ArcherVMPeridot 3.4.3 Dronesseus Tarmac \n " + self.Aircraft.aircraft_name
         self.prompt = self.name + ", You are clear for takeoff."
     def do_takeOff(self, arg):
         if input("use arg?:") == "no":
             self.Aircraft.takeoff(arg)
         else: 
             self.aircraft.takeoff()
         self.prompt = "ArcherVMPeridot/ArcherVMCashew Dronesseus - (" + self.Aircraft.get_location()["lng"] + " degrees longitude, " + self.Aircraft.get_location()["lat"] + " degrees latitude)"
    

         
def start():
    #we create the environment
    e = Environment()
    e.loadEnvironment("test2.map")
    #print(str(e))

    # we create the map
    m = DMap()

    # initialize the pygame module
    pygame.init()
    # load and set the logo
    logo = pygame.image.load("logo32x32.png")
    pygame.display.set_icon(logo)
    pygame.display.set_caption("drone exploration")

    # we position the drone somewhere in the area
    x = randint(0, 19)
    y = randint(0, 19)

    #cream drona
    d = Drone(x, y)

    # create a surface on screen that has the size of 800 x 480
    screen = pygame.display.set_mode((800, 400))
    screen.fill(WHITE)
    screen.blit(e.image(), (0, 0))

    # define a variable to control the main loop
    running = True
    stack.append((x, y))

    # main loop

    while running:

        m.markDetectedWalls(e, d.x, d.y)
        d.moveDSF(m)
        screen.blit(m.image(d.x, d.y), (400, 0))
        pygame.display.flip()
        time.sleep(0.3)
        if not stack:
            running = False

    pygame.quit()
 def place_DRONE_relay(self, starting_position, linked_bs_id,
                       carrier_frequency, amplification_factor,
                       antenna_gain, feeder_loss):
     new_bs = DRONEbs.DroneRelay(len(self.bs_list), linked_bs_id,
                                 amplification_factor, antenna_gain,
                                 feeder_loss, carrier_frequency,
                                 starting_position, self)
     self.bs_list.append(new_bs)
     return new_bs.bs_id
Пример #14
0
    def construct(self) :

        if self.visualize :

            base.cam.setPos(17,17,1)
            base.cam.lookAt(0, 0, 0)

            wp = WindowProperties()
            wp.setSize(1200, 500)
            base.win.requestProperties(wp)

        # World
        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))

        #skybox
        skybox = loader.loadModel('../models/skybox.gltf')
        skybox.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition)
        skybox.setTexProjector(TextureStage.getDefault(), render, skybox)
        skybox.setTexScale(TextureStage.getDefault(), 1)
        skybox.setScale(100)
        skybox.setHpr(0, -90, 0)

        tex = loader.loadCubeMap('../textures/s_#.jpg')
        skybox.setTexture(tex)
        skybox.reparentTo(render)

        render.setTwoSided(True)

        #Light
        plight = PointLight('plight')
        plight.setColor((1.0, 1.0, 1.0, 1))
        plnp = render.attachNewNode(plight)
        plnp.setPos(0, 0, 0)
        render.setLight(plnp)

        # Create Ambient Light
        ambientLight = AmbientLight('ambientLight')
        ambientLight.setColor((0.15, 0.05, 0.05, 1))
        ambientLightNP = render.attachNewNode(ambientLight)
        render.setLight(ambientLightNP)

        #multiple drone initialization

        wrgDistance = True
        positions = []

        self.uavs = [Drone.uav() for i in range(self.actors)]
        [self.world.attachRigidBody(uav.drone) for uav in self.uavs]
        [uav.drone.setDeactivationEnabled(False) for uav in self.uavs]

        #target object
        self.targetObj = loader.loadModel("../models/target.gltf")
        self.targetObj.reparentTo(render)
        self.targetObj.setPos(Vec3(self.target[0], self.target[1], self.target[2]))
Пример #15
0
    def __init__(self):

        self.drone = Drone.Drone()

        try:
            self.settings = MultiwiiSettings.Settings()
            self.serial = self.settings.serial_port
            self.serial.open()
            time.sleep(self.settings.wakeup)
        except ValueError as err:
            print('Serial port exception:' + str(err) + '\n')
Пример #16
0
    def __init__(self, factor, visualize):

        self.visualize = visualize
        self.factor = factor
        self.pos = np.zeros(3)
        self.lastPos = np.zeros(3)
        self.target = np.zeros(3)
        self.ep_rew = 0
        self.done = False

        self.drone = Drone.uav(visualize)
    def place_NR_base_station(self,
                              position,
                              carrier_frequency,
                              numerology,
                              antenna_power,
                              antenna_gain,
                              feeder_loss,
                              available_bandwidth,
                              total_bitrate,
                              drone=False):
        #check if the bandwith is in line with the specified numerology and specified carrier frequency
        fr = -1
        if (carrier_frequency <= 6000):  #below 6GHz
            fr = 0
        elif (carrier_frequency >= 24250
              and carrier_frequency <= 52600):  #between 24.25GHz and 52.6GHz
            fr = 1
        else:
            raise Exception("NR frequency outside admissible ranges")

        if available_bandwidth in NRbs.NRbandwidth_prb_lookup[numerology][fr]:
            prb_size = 15 * (
                2**numerology
            ) * 12  #15KHz*12subcarriers for numerology 0, 30KHz*12subcarriers for numerology 1, etc.
            #  NRbandwidth_prb_lookup defines the number of blocks of 180KHz available in the specified bandwidth with a certain numerology,
            #  so we have to multiply by the number of time slots (sub-frames in LTE terminology) in a time frame
            if drone == False:
                new_bs = NRbs.NRBaseStation(
                    len(self.bs_list), NRbs.NRbandwidth_prb_lookup[numerology]
                    [fr][available_bandwidth] * (10 * 2**numerology), prb_size,
                    12, numerology, antenna_power, antenna_gain, feeder_loss,
                    carrier_frequency, total_bitrate, position, self)
            else:
                new_bs = DRONEbs.DroneBaseStation(
                    len(self.bs_list),
                    DRONEbs.NRbandwidth_prb_lookup[numerology][fr]
                    [available_bandwidth] * (10 * 2**numerology), prb_size, 12,
                    numerology, antenna_power, antenna_gain, feeder_loss,
                    carrier_frequency, total_bitrate, position, self)
        else:
            raise Exception(
                "The choosen bandwidth is not present in 5G NR standard with such numerology and frequency range"
            )

        self.bs_list.append(new_bs)
        return new_bs.bs_id
Пример #18
0
    def start(self):
        # init drones
        self.drones = [Drone(i) for i in range(Constants.num_drones)]

        Constants.renderer = MapRenderer(Constants.grid_dimension.x, Constants.grid_dimension.y)
        Constants.network = NetworkLayer(self.drones, self)

        # First get blocks of image points and drones
        self.blocks = Utility.getGridBlocks()

        # Equally Distribute blocks in drones
        self.allocations_list = Utility.get_grid_distribution(self.blocks)

        # Reshuffle without considering relay time already alternated
        self.allocations_list = Utility.shuffle_distribution(self.allocations_list, self.drones)

        self.connected_drones = []
        self.all_connected = False
        self.all_connected_time = None

        self.relay_points = []
        self.near_blocks = []
        self.empty_allocations = []
import Drone
import sys
import time

#here you should interact with the drone
print("booting")

drone1 = Drone.Drone('192.1.1.1', 8889)

#Diagnostics

drone1.printinfo()

drone1.connect()

drone1.battery()

#Action

#ideen er at dronen letter, vender 180grader for at få højdemåleren tættere på trinet.
#flyver 5 gange 26 cm bagud drejer 90 grader mod uret, flyver 5 gange 29cm

drone1.takeOff()

time.sleep(2)

drone1.cw(180)

time.sleep(2)

ymax1 = 0
Пример #20
0
class Simulator(tk.Tk):
    def __init__(self, dt):
        self.WIDTH = 1000.0
        self.HEIGHT = 500.0
        self.time = 0.0
        self.dt = dt
                
        tk.Tk.__init__( self )
        
        self.drone = Drone(self.dt)
        #self.drone2 = Drone(self.dt)
        self.control = Control(self.drone)
        #self.control2 = Control(self.drone2)
        self.drone.setControl(self.control)
        #self.drone2.setControl(self.control2)     

        screen = tk.Frame(self)
        screen.pack()
        
        self.canvas = tk.Canvas(screen, width=self.WIDTH, height=self.HEIGHT,borderwidth=10)
        self.canvas.grid(column=1, row=1)
        
        self.infos = InfoPanel(screen, self.drone)
        self.infos.panel.grid(column=2, row=1)
        #self.infos2 = InfoPanel(screen, self.drone2)
        #self.infos2.panel.grid(column=3, row=1)
       
        # to receive commands
        screen.focus_set()  
        
        self.drone_ui = self.canvas.create_oval(40, self.HEIGHT, 50, self.HEIGHT-10, fill = "red")
        #self.drone2_ui = self.canvas.create_oval(100, self.HEIGHT, 110, self.HEIGHT-10, fill = "blue")       

        def onBtnUpHand(e):
            self.control.onBtnUp()

        def onBtnDownHand(e):
            self.control.onBtnDown()
            
        def onBtnLeftHand(e):
            self.control.onBtnLeft()
            
        def onBtnRightHand(e):
            self.control.onBtnRight()

        def onBtnAHand(e):          
            if self.control.switch == 0:
                self.control.setSwitch(1)
                self.control.load(self.control.stay, self.drone.pos)
                
        def onBtnRHand(e):
            self.control.reset()
            
        def onBtnGHand(e):                        
            if self.control.switch == 0:
                self.control.setSwitch(1)
                self.control.load(self.control.goto, [Vector(0,50), Vector(30,100)])
                
        def onBtnOHand(e):
            self.control.resetControl()

        screen.bind("<Up>", onBtnUpHand)
        screen.bind("<Down>", onBtnDownHand)
        screen.bind("<Left>", onBtnLeftHand)
        screen.bind("<Right>", onBtnRightHand)
        screen.bind("<a>", onBtnAHand)
        screen.bind("<r>", onBtnRHand)
        screen.bind("<g>", onBtnGHand)
        screen.bind("<o>", onBtnOHand)

    def simLoop(self):        
        self.drone.refreshPos()
        #self.drone2.refreshHeight()
        if self.control.switch == 1:
            self.control.run()
            
        #self.control2.load(self.control2.goto, [self.drone.height])
        #self.control2.run()
            
        self.canvas.coords(self.drone_ui, self.drone.pos.coords[0]+40, self.HEIGHT-self.drone.pos.coords[1], self.drone.pos.coords[0]+50, self.HEIGHT-10-self.drone.pos.coords[1])
        #self.canvas.coords(self.drone2_ui, 100, self.HEIGHT-self.drone2.height, 110, self.HEIGHT-10-self.drone2.height)

        self.infos.texts.setUiTexts()
        #self.infos2.texts.setUiTexts()
        
        self.after(int(1000*self.dt), self.simLoop)
Пример #21
0
[0.6453539547210074, 1.3817991909818224, 0.08597045123404019]  <- eddigi legjobb
[1.2265485343557876, 1.9855714793925145, 0.120788504112233]
#################################


[16.095992229752056, [1.9969525844055631, 1.8381537599239324, 0.14317915448451723]]
[4.381782581030109, [2.007821556163127, 0.27615086577017367, 0.44609716664311955]]
[0, [1.2265485343557876, 1.9855714793925145, 0.033788504112233]]

"""

from Vector import *
from Drone import *
from Control import *

drone = Drone(0.05)
control = Control(drone)
control.load(control.stay, Vector( 0,50))
control.run()
drone.refreshPos()
control.setP([1.2265485343557876, 1.9855714793925145, 0.120788504112233])

droneRoute = []
time = 0

while (abs(control.error.len()) > 1 or abs(control.derror.len()) > 1 or abs(drone.speed.len()) > 1) and time < 2000:
    """while program is not empty -> convergence"""
    droneRoute.append(drone.pos.get())
    control.run()
    drone.refreshPos()
    time += 1
def main():
    print 'Start'
 
    random.seed(1)
    mapX=300
    mapY=300
    numStreets=50
    numTargets=10
    numDrones=3
    heuristic=1
    seedNum=1
    Nuisance=0.8    
    
    print '---Generate Map---'
    Map = GenMap(mapX,mapY)
    Map.map(numStreets,Nuisance)
    randNodes=[]
    for i in range(numTargets):
        randNodes.append(Map.RandNode())
 
    print '---Generate HMINT, CAOC, IMINT---'
    
    hmint = HMINT(numTargets, randNodes)
    hmintInQ = LPInputQueue()    
    
    caoc=CAOC(numDrones,heuristic)
    caocInQ = LPInputQueue()    
    
    imint=IMINT(heuristic,numTargets)
    imintInQ = LPInputQueue()
    print 'IMINT total value: ' + str(imint.totalValue)
    
    drone=Drone(0,0,1)
    droneInQ=LPInputQueue()
    
    lp=[hmint,caoc,imint]
    
    print '---Generate Messages---'
    m2Data=[0,80,80,'Vehicle',1,1,randNodes[0],30,0,0]
    m2=Message(2,m2Data,'CAOC','IMINT',0)
    m3Data=[0,'Idle',randNodes[1]]
    m3=Message(3,m3Data,'IMINT','CAOC',1)    
    
    print '---Save and Restore State---'
    
    for i in lp:
        i.localTime=0
        drone.LocalSimTime=0
        i.saveState()
        i.localTime=3
        drone.LocalSimTime=3
        i.saveState()
        i.localTime=7
        drone.LocalSimTime=7
        i.saveState()
        i.localTime=12
        drone.LocalSimTime=12
        i.saveState()
        print str(i.LPID) + ' state queue: ' + str(i.stateQueue)
        print str(i.LPID) + ' state queue length: ' + str(len(i.stateQueue))
    

    #for i in drone.stateQueue:
        #print 'Drone LocalSimTime: ' + str(i.LocalSimTime)
    
    hmint.restoreState(6)
    caoc.restoreState(6)
    imint.restoreState(6)
    drone.restoreState(6)

    for i in lp:
        print str(i.LPID) + ' state queue: ' + str(i.stateQueue)
        print str(i.LPID) + ' local time: ' + str(i.localTime)
        print 'Drone actual local time: ' + str(drone.LocalSimTime)
        i.localTime=13
        i.saveState()
        print str(i.LPID) + ' state queue: ' + str(i.stateQueue)        
    
    
    print 'End'
Пример #23
0
    def __init__(self, dt):
        self.WIDTH = 1000.0
        self.HEIGHT = 500.0
        self.time = 0.0
        self.dt = dt
                
        tk.Tk.__init__( self )
        
        self.drone = Drone(self.dt)
        #self.drone2 = Drone(self.dt)
        self.control = Control(self.drone)
        #self.control2 = Control(self.drone2)
        self.drone.setControl(self.control)
        #self.drone2.setControl(self.control2)     

        screen = tk.Frame(self)
        screen.pack()
        
        self.canvas = tk.Canvas(screen, width=self.WIDTH, height=self.HEIGHT,borderwidth=10)
        self.canvas.grid(column=1, row=1)
        
        self.infos = InfoPanel(screen, self.drone)
        self.infos.panel.grid(column=2, row=1)
        #self.infos2 = InfoPanel(screen, self.drone2)
        #self.infos2.panel.grid(column=3, row=1)
       
        # to receive commands
        screen.focus_set()  
        
        self.drone_ui = self.canvas.create_oval(40, self.HEIGHT, 50, self.HEIGHT-10, fill = "red")
        #self.drone2_ui = self.canvas.create_oval(100, self.HEIGHT, 110, self.HEIGHT-10, fill = "blue")       

        def onBtnUpHand(e):
            self.control.onBtnUp()

        def onBtnDownHand(e):
            self.control.onBtnDown()
            
        def onBtnLeftHand(e):
            self.control.onBtnLeft()
            
        def onBtnRightHand(e):
            self.control.onBtnRight()

        def onBtnAHand(e):          
            if self.control.switch == 0:
                self.control.setSwitch(1)
                self.control.load(self.control.stay, self.drone.pos)
                
        def onBtnRHand(e):
            self.control.reset()
            
        def onBtnGHand(e):                        
            if self.control.switch == 0:
                self.control.setSwitch(1)
                self.control.load(self.control.goto, [Vector(0,50), Vector(30,100)])
                
        def onBtnOHand(e):
            self.control.resetControl()

        screen.bind("<Up>", onBtnUpHand)
        screen.bind("<Down>", onBtnDownHand)
        screen.bind("<Left>", onBtnLeftHand)
        screen.bind("<Right>", onBtnRightHand)
        screen.bind("<a>", onBtnAHand)
        screen.bind("<r>", onBtnRHand)
        screen.bind("<g>", onBtnGHand)
        screen.bind("<o>", onBtnOHand)
Пример #24
0
    next_mission = sql.getNextMission(db, str(int(Id) - 1))  #fianl mission

    while True:
        sql.closeDatabase(db)
        db = MySQLdb.connect(host="120.126.145.102",
                             user="******",
                             passwd="dronemysql",
                             db="106project")
        if sql.findResultMaxId(db) < sql.findMissionMaxId(db):
            sql.printTask(db, sql.findResultMaxId(db))
            #doing mission
            check = raw_input("you want to fly?(Y/n)")
            if check is 'Y':
                next_mission = sql.getNextMission(db, next_mission.mission_id)
                #print "doing things"
                Drone.arm_and_takeoff(vehicle, 7)
                print("set groundspeed to 5m/s.")
                vehicle.airspeed = 5
                Drone.goto_gps(vehicle, next_mission.mission_latitude,
                               next_mission.mission_longitude, 7, logFile)
                time.sleep(5)
                next_mission.setPM25(random.randint(1, 100))
                sql.TaskDone(db, next_mission, False)
                print "Setting RTL mode..."
                vehicle.mode = VehicleMode("RTL")
            elif check is 'n':
                next_mission = sql.getNextMission(db, next_mission.mission_id)
                sql.TaskDone(db, next_mission, True)
            print "Last Task is %s" % sql.findResultMaxId(db)
    print ""
    print "All Task Done !"
import Drone
import sys
import time

# Live drone
#drone_1 = drone.Drone("128.1.1.1", 8889)

# Test drone
# drone start up
drone_1 = Drone.Drone('192.168.10.1', 8889)
drone_1.printInfo(1)
drone_1.connect(1)

#region old
# # Print out start information
# print(drone_1.battery(0.1))
# print(drone_1.time(0.1))
# print(drone_1.sdk(0.1))
# print(drone_1.sn(0.1))

# # Drone flightplan
# drone_1.takeOff(1)
# drone_1.cw("90", 1)
# drone_1.ccw("360", 1)
# drone_1.cw("180", 1)
# drone_1.up("60", 1)
# #drone_1.flip("b", 1)
# drone_1.down("30", 1)
# drone_1.left("20", 1)
# drone_1.right("20", 1)
Пример #26
0
                    square_count = 1
                    pm25_sensor = int(waypoint_mission.pm25_sensor)
                    video_sensor = int(waypoint_mission.video_sensor)
                    photo_sensor = int(waypoint_mission.photo_sensor)
                    point_stay = int(waypoint_mission.mission_staytime)
                    point_height = int(waypoint_mission.mission_height)

                    waypoint_mission.set_point_num(waypoint_counter + 1)

                    logFile.write("Points  " + str(waypoint_counter + 1) +
                                  ":" + "\n")
                    print "Sensor:"
                    print "pm2.5:%d  video:%d  photo:%d" % (
                        pm25_sensor, video_sensor, photo_sensor)
                    if waypoint_counter == 0:
                        Drone.arm_and_takeoff(vehicle, point_height)
                        print "set groundspeed to 5m/s."
                        vehicle.airspeed = 5
                    Drone.goto_gps(vehicle, waypoint_mission.mission_latitude,
                                   waypoint_mission.mission_longitude,
                                   point_height, logFile)
                    pmdata = air.gsleep(air, point_stay)

                    waypoint_mission.set_pm25_data(pmdata)
                    if photo_sensor == 1:
                        Success = True
                        try:
                            Drone.condition_yaw(vehicle, 0)
                            loc = cc.capture(
                                camera, str(Mission_number),
                                str(waypoint_counter + 1) + "_" +
Пример #27
0
__author__ = 'Francisco J. H. Heras'

T = 300  #ms
dt = 0.05  #ms
time_array = arange(0, T + dt, dt)
I = zeros_like(time_array)

fig1 = plt.figure(1)
ax = fig1.add_subplot(211)
ax_t = fig1.add_subplot(212)

fig2 = plt.figure(2)
ax_curr = fig2.add_subplot(211)

V_membrane = -38  #mV
photoreceptor = Drone.Vallet92()
DepolarisePhotoreceptor.WithLight(photoreceptor, V=V_membrane)

fig1.text(0.06,
          0.5,
          'Membrane potential deflection (mV)',
          ha='center',
          va='center',
          rotation='vertical')

for ii in range(5):
    for i, t in enumerate(time_array):
        if 10 <= t <= 110: I[i] = 1e-3 * (-0.02 + 0.01 * ii)  # nA->uA
    DepolarisePhotoreceptor.WithLight(photoreceptor, V=V_membrane)

    V_array, g_Ch = Experiment.inject_current(photoreceptor, I, dt)
Пример #28
0
import time
import math
from droneapi.lib import Location
import argparse
import Mission
import random
import Get_uwb_position
parser = argparse.ArgumentParser()
parser.add_argument('--connect', default='/dev/serial0')
args = parser.parse_args()

vehicle = connect(args.connect, baud=57600, wait_ready=True)

logFile=open("log_velocity.txt","a+")

Drone.arm_and_takeoff(vehicle, 5)

NORTH = 0.3
SOUTH = -0.3

EAST = 0.3
WEST = -0.3

UP = -0.5
DOWN = 0.5

DURATION = 10

msg = Drone.return_send_ned_velocity_mavlink_msg(vehicle,SOUTH,0,0)
msg2 = Drone.return_send_ned_velocity_mavlink_msg(vehicle,NORTH,0,0)
Пример #29
0
import Drone
import time

drone = Drone.Tello()
drone.AIRSIM_ENABLED = False
drone.TELLO_ENABLED = True

drone.connect()

drone.get_battery_status()
drone.get_speed()
drone.takeoff()
drone.forward(50)
drone.left(50)
drone.rotate(90)
drone.forward(50)
drone.rotate(90)
drone.forward(50)
drone.rotate(90)
drone.forward(50)
Пример #30
0
import pytest
import sys
import cflib

sys.path.append("..")
from DroneDTO import *
from Appchannel import AppchannelCommunicate
from Drone import *
from Dronesim import *

drone = Drone(0, AppchannelCommunicate(0))
drone.getChannel().setBattery(90.0)
drone.getChannel().setSpeed(10.0)
drone.getChannel().setState(1)

droneSim = Dronesim(0, 1)
droneSim.setBattery("0.90")
droneSim.setSpeed("10.0")
droneSim.setState("1")


def test_init_sim_in_mission():
    global droneSim
    expected_attributes = [0, 90.0, 10.0, "In mission"]
    actual_attributes = []

    droneDTO = DroneDTO(True, droneSim)

    actual_attributes.append(droneDTO.droneId)
    actual_attributes.append(droneDTO.battery)
    actual_attributes.append(droneDTO.speed)
				ftransfer.making_direc(str(Mission_number))
				for waypoint_mission in next_multi_mission:
					square_count = 1
					pm25_sensor = int(waypoint_mission.pm25_sensor)
					video_sensor = int(waypoint_mission.video_sensor)
					photo_sensor = int(waypoint_mission.photo_sensor)

					waypoint_mission.set_point_num(waypoint_counter+1)
					
					logFile.write("Points  "+str(waypoint_counter+1)+":"+"\n")
					print "Sensor:"
					print "pm2.5:%d  video:%d  photo:%d" % (pm25_sensor,video_sensor,photo_sensor)
					if waypoint_counter == 0:
						home_location.append(vehicle.location.global_relative_frame.latitude
						home_location.append(vehicle.location.global_relative_frame.longitude)
						Drone.arm_and_takeoff(vehicle, 7)
						print "set groundspeed to 5m/s."
						vehicle.airspeed = 5
					Drone.goto_gps(vehicle,waypoint_mission.mission_latitude, waypoint_mission.mission_longitude, 7, logFile)
					pmdata = air.gsleep(air,5)
					
					waypoint_mission.set_pm25_data(pmdata)
					if photo_sensor == 1:
						Success = True
						try:
							loc = cc.capture(camera,str(Mission_number),str(waypoint_counter+1)+"_"+str(square_count))
							sql.passPhoto(db,waypoint_mission,loc)
							print "degree 0 , success"
						except:
							print "except : degree 0"
							Success = False
Пример #32
0
def createNewDrone(uid, droneType,heuristic,Legs):
    print('Creating new drone of type ' + droneType)
    droneref = Drone(uid, droneType,heuristic,Legs)
    droneref.setConnectionParams(PYRO_HOST, PYRO_PORT)
    return droneref
Пример #33
0
    def workDone(self, obj, source_name, dest_name, supplies, order_dist,
                 order_mass, weather):
        self.work_done_cost = 0
        """calculating work_done_cost
        based on geographical location
        and weather conditions"""

        #Number 1 -> Height difference

        l = Location.location(0, 0)
        d = Drone.drone(0, 0, 1, 0, 0, 0, 0, 0, 0, (0, 0, 0, 0))

        source = l.getLatLong(source_name)
        dest = l.getLatLong(dest_name)

        lat1 = math.radians(source[0])
        lat2 = math.radians(dest[0])

        diffLong = math.radians(dest[1] - source[1])

        x = math.sin(diffLong) * math.cos(lat2)
        y = math.cos(lat1) * math.sin(lat2) - (
            math.sin(lat1) * math.cos(lat2) * math.cos(diffLong))

        initial_bearing = math.atan2(x, y)

        initial_bearing = math.degrees(initial_bearing)

        #This is the angle that
        #source makes wrt destination

        compass_bearing = (initial_bearing + 360) % 360

        #Using the formula
        #tanA = height/base
        #so, height = tanA * base

        self.height = d.getDistance(
            source_name, l.getLatLong(dest_name)) * math.tan(compass_bearing)

        #If difference between source and
        #destination altitude is >=
        #70, then we add additional cost
        #Assuming the additional cost
        #per unit of height to be 0.5
        #Replaceable value

        if self.height >= 50:
            self.work_done_cost = self.height * 0.5

        #Number 2 -> weather conditions

        self.wind_speed = weather['Wind_speed']
        self.clouds = weather['Clouds']

        #Assuming 0.5 unit of extra work done
        #for every unit of wind speed, if wind
        #speed >=8 as it will resist the drone
        #Replaceable value

        if self.wind_speed >= 8:
            self.work_done_cost = self.wind_speed * 0.5

        #Assuming 0.5 unit of extra work done
        #for per unit of clouds, if >= 5
        #as it will cause visibility issue
        #Replaceable value

        if self.clouds >= 5:
            self.work_done_cost = self.clouds * 0.5

        #Assuming 1 unit of battery expenditure
        #per unit of distance
        #Replaceable value

        obj.battery = order_dist * 1
        self.cost = self.costCalculation(self.work_done_cost, obj.battery)

        return self.cost
Пример #34
0
import CostFunction as pro
import Drone as pre
import Visualize as post
import matplotlib.pyplot as plt
import numpy as np

drone1 = pre.Drone(70, 7.7, 0.009)
drone2 = pre.Drone(200, 10.5, 0.012)
drone3 = pre.Drone(450, 13.2, 0.018)

wind1 = pre.Wind(np.random.uniform(2.0, 3.5), 0)
# this time, we consider that wind goes from west to east, and its magnitude goes from 2.0 m/s to 3.5 m/s

depot1 = pre.Depot("Chatenay-Malabry", 0, 0)

param1 = pre.DeliveryParameters(drone1, wind1, pro.cost_b)

total_cost = 0
total_savings = 0
for i in range(500):
    print(i)
    problem_i = pre.Problem(depot1)
    problem_i.generate_random_clients(amount=np.random.randint(50, 60),
                                      x=(-6000, 6000),
                                      y=(-3500, 3500),
                                      demand=(5, 60))
    pro.clarke_and_wright(problem_i, param1, version="sequential")
    solution_i = problem_i.solutions_list[0]
    total_cost += solution_i.cost_and_savings()[0]
    total_savings += solution_i.cost_and_savings()[1]
average = total_savings / (total_savings + total_cost)
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)

logFile = open("log_velocity.txt", "a+")

Drone.arm_and_takeoff(vehicle, 5)

NORTH = 0.5
SOUTH = -0.5

EAST = 0.5
WEST = -0.5

UP = -0.5
DOWN = 0.5

DURATION = 2
print vehicle.location.global_relative_frame

Drone.send_ned_velocity(vehicle, NORTH, 0, 0, DURATION)
Drone.send_ned_velocity(vehicle, 0, 0, 0, 1)
Пример #36
0
import pyrealsense2 as rs
import cv2 as cv
import math
import pcl
import sys
import pcl.pcl_visualization
import numpy as np
import pygame 


pygame.init()

Path_Planner = Planner.Planner()           #planner object created
Controller   = Controller.Controller()
FlyBy        = Drone.Drone()

#pcl visualizer
viewer = pcl.pcl_visualization.PCLVisualizering()

#initialize the realsense pipeline for the rgb and depth frames
pipeline = rs.pipeline()
config   = rs.config()
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8,30)

# Start streaming
pipeline.start(config)

# Processing blocks
pc = rs.pointcloud()
Пример #37
0
#!/usr/env/ python

from Map import *
from Drone import *
from Target import *

a=GenMap(480,480)
a.map(50,.8)
ger=LogicalProcess()

drone=Drone(3,ger,1)
drone.setJokerBingo()

drone.setEntry(a.MapEntryPt)
moo=a.RandNode()
drone.target=Target(moo)
#drone.saveState()
#drone.updateTime(800)
#drone.saveState()
#drone.restoreState(0)
#drone.setEntry(mapObj) #MUST PASS THE ENTRY NODE!!! (map.MapEntryPt)
drone.currentNode=a.MapEntryPt #the only time we directly set the current node.
drone.LocalSimTime=drone.localTime
drone.setJokerBingo()
drone.flyTotgt(drone.target.node.xpos,drone.target.node.ypos)
start_time = time.time()
targetcount=0
targetnum=5000
while(targetcount<targetnum):
    
    if(drone.Bingo<0):
Пример #38
0
    def run(self):
        curr_dir = os.path.dirname(os.path.abspath(__file__))
        img_path = os.path.join(curr_dir, "drone.png")
        drone_img = pygame.image.load(img_path)
        drone = Drone.Model(0, 0)
        ppu = 32
        while not self.exit:
            dt = self.clock.get_time() / 1000

            for event in pygame.event.get():  # our event que.

                if event.type == pygame.QUIT:
                    self.exit = True

                # getting user input
                key_stroke = pygame.key.get_pressed()

                if key_stroke[pygame.K_UP]:  # the up key
                    if drone.velocity.x < 0:
                        drone.acceleration = Drone.BRAKE_DEACCELERATION
                    drone.acceleration += 1 * dt
                elif key_stroke[pygame.K_DOWN]:
                    if drone.velocity.x > 0:
                        drone.acceleration = -Drone.BRAKE_DEACCELERATION
                elif key_stroke[pygame.K_SPACE]:
                    if abs(drone.velocity.x) > dt * Drone.BRAKE_DEACCELERATION:
                        drone.acceleration = -copysign(
                            Drone.BRAKE_DEACCELERATION, drone.velocity.x)
                    else:
                        drone.acceleration = -drone.velocity.x / dt
                else:
                    if abs(drone.velocity.x) > dt * Drone.FREE_DEACCELERATION:
                        drone.acceleration = -copysign(
                            Drone.FREE_DEACCELERATION, drone.velocity.x)
                    else:
                        if dt != 0:
                            drone.acceleration = -drone.velocity.x / dt
                drone.acceleration = max(
                    -Drone.MAX_VELOCITY,
                    min(drone.acceleration, Drone.MAX_VELOCITY))

                if key_stroke[pygame.K_RIGHT]:
                    drone.steering -= 30 * dt
                elif key_stroke[pygame.K_LEFT]:
                    drone.steering += 30 * dt
                else:
                    drone.steering = 0
                drone.steering = max(
                    -Drone.MAX_STEERING_ANGLE,
                    min(drone.steering, Drone.MAX_STEERING_ANGLE))

                drone.update(dt)
                # Drawing
                self.screen.fill((0, 0, 0))
                map_img = pygame.image.load(
                    r'C:\Users\97254\PyCharmProjects\DroneSim\.maps\sim_20.png'
                )  # map location
                # self.screen.blit(map_img, (0, 0))
                rotated = pygame.transform.rotate(drone_img, drone.angle)
                rect = rotated.get_rect()
                self.screen.blit(
                    rotated,
                    drone.position * ppu - (rect.width / 2, rect.height / 2))
                pygame.display.flip()

                self.clock.tick(self.ticks)
        pygame.quit()