Пример #1
0
class FlightListener(olympe.EventListener):

    # This set a default queue size for every listener method
    default_queue_size = 100

    def __init__(self, *args, **kwds):
        super().__init__(*args, **kwds)
        self.has_observed_takeoff = False

    @olympe.listen_event(PositionChanged())
    def onPositionChanged(self, event, scheduler):
        casey(moveTo(event.args["latitude"],  event.args["longitude"], 0.86, MoveTo_Orientation_mode.TO_TARGET, 0.0))
        print(
            "latitude = {latitude} longitude = {longitude} altitude = {altitude}".format(
                **event.args
            )
        )

    @olympe.listen_event(AttitudeChanged())
    def onAttitudeChanged(self, event, scheduler):
        print("roll = {roll} pitch = {pitch} yaw = {yaw}".format(**event.args))

    @olympe.listen_event(AltitudeAboveGroundChanged())
    def onAltitudeAboveGroundChanged(self, event, scheduler):
        print("height above ground = {altitude}".format(**event.args))

    @olympe.listen_event(SpeedChanged())
    def onSpeedChanged(self, event, scheduler):
        print("speedXYZ = ({speedX}, {speedY}, {speedZ})".format(**event.args))

    # You can also handle multiple message types with the same method
    @olympe.listen_event(
        FlyingStateChanged() | AlertStateChanged() | NavigateHomeStateChanged()
    )
    def onStateChanged(self, event, scheduler):
        # Here, since every "*StateChanged" message has a `state` argument
        # we can handle them uniformly to print the current associated state
        print("{} = {}".format(event.message.name, event.args["state"]))

    # You can also monitor a sequence of event using the complete Olympe DSL syntax
    @olympe.listen_event(
        FlyingStateChanged(state="takingoff", _timeout=1.)
        >> FlyingStateChanged(state="hovering", _timeout=5.)
    )
    def onTakeOff(self, event, scheduler):
        # This method will be called once for each completed sequence of event
        # FlyingStateChanged: motor_ramping -> takingoff -> hovering
        caseyTakeOff()
        print("The drone has taken off!")
        self.has_observed_takeoff = True

    # The `default` listener method is only called when no other method
    # matched the event message The `olympe.listen_event` decorator usage
    # is optional for the default method, but you can use it to further
    # restrict the event messages handled by this method or to limit the
    # maximum size of it associated event queue (remember that the oldest
    # events are dropped silently when the event queue is full).
    @olympe.listen_event(queue_size=10)
    def default(self, event, scheduler):
        print_event(event)
Пример #2
0
class FlightListener(olympe.EventListener):

    # This set a default queue size for every listener method
    default_queue_size = 100

    def __init__(self, *args, **kwds):
        super().__init__(*args, **kwds)
        self.takeoff_count = 0

    @olympe.listen_event(PositionChanged(_policy="wait"))
    def onPositionChanged(self, event, scheduler):
        print(
            "latitude = {latitude} longitude = {longitude} altitude = {altitude}".format(
                **event.args
            )
        )

    @olympe.listen_event(AttitudeChanged(_policy="wait"))
    def onAttitudeChanged(self, event, scheduler):
        print("roll = {roll} pitch = {pitch} yaw = {yaw}".format(**event.args))

    @olympe.listen_event(AltitudeAboveGroundChanged(_policy="wait"))
    def onAltitudeAboveGroundChanged(self, event, scheduler):
        print("height above ground = {altitude}".format(**event.args))

    @olympe.listen_event(SpeedChanged(_policy="wait"))
    def onSpeedChanged(self, event, scheduler):
        print("speedXYZ = ({speedX}, {speedY}, {speedZ})".format(**event.args))

    # You can also handle multiple message types with the same method
    @olympe.listen_event(
        FlyingStateChanged(_policy="wait")
        | AlertStateChanged(_policy="wait")
        | NavigateHomeStateChanged(_policy="wait")
    )
    def onStateChanged(self, event, scheduler):
        # Here, since every "*StateChanged" message has a `state` argument
        # we can handle them uniformly to print the current associated state
        print("{} = {}".format(event.message.name, event.args["state"]))

    # You can also monitor a sequence of event using the complete Olympe DSL syntax.
    # Command expectations here won't send any message
    @olympe.listen_event(
        FlyingStateChanged(state="landed")
        >> TakeOff()
    )
    def onTakeOff(self, event, scheduler):
        # This method will be called once for each completed sequence of event
        # FlyingStateChanged: takeoff command >> takingoff -> hovering
        print("The drone has taken off!")
        self.takeoff_count += 1

    # Command message don't take implicit `None` parameters so every argument
    # should be provided
    @olympe.listen_event(moveBy(dX=None, dY=None, dZ=None, dPsi=None))
    def onMoveBy(self, event, scheduler):
        # This is called when the `moveByEnd` event (the `moveBy` command
        # expectation) is received
        print("moveByEnd({dX}, {dY}, {dZ}, {dPsi})".format(**event.args))

    @olympe.listen_event(GetState.as_event(_policy="wait"))
    def onCamera2GetState(self, event, scheduler):
        print(f"onCamera2GetState {event}")

    # The `default` listener method is only called when no other method
    # matched the event message The `olympe.listen_event` decorator usage
    # is optional for the default method, but you can use it to further
    # restrict the event messages handled by this method or to limit the
    # maximum size of it associated event queue (remember that the oldest
    # events are dropped silently when the event queue is full).
    @olympe.listen_event(queue_size=100)
    def default(self, event, scheduler):
        print_event(event)
Пример #3
0
class FlightListener(olympe.EventListener):

    # This set a default queue size for every listener method
    default_queue_size = 100

    def __init__(self, *args, **kwds):
        super().__init__(*args, **kwds)
        self.has_observed_takeoff = False

    @olympe.listen_event(PositionChanged())
    def onPositionChanged(self, event, scheduler):
        lat = event.args["latitude"]
        lon = event.args["longitude"]
        c_poi = (lat, lon)
        poi = (21.371518, -157.71161)
        print('\n ------->')
        print('\n ------->')
        print('\n ------->')
        meters = haversine(poi, c_poi, unit='m')
        print(meters)
        print(meters < 2)
        print('\n ------->')
        print('\n ------->')
        print('\n ------->')

        two_lat = event.args["latitude"]
        two_lon = event.args["longitude"]

        if meters < 8:
            casey(
                moveToChanged(status="CANCELED") >> moveTo(
                    21.370950, -157.709998, 10, MoveTo_Orientation_mode.
                    TO_TARGET, 0.0) >> moveToChanged(status="DONE"))
            donatello(
                moveToChanged(status="CANCELED") >> moveTo(
                    21.370950, -157.709998, 20, MoveTo_Orientation_mode.
                    TO_TARGET, 0.0) >> moveToChanged(status="DONE"))
            leonardo(
                moveToChanged(status="CANCELED") >> moveTo(
                    21.370950, -157.709998, 15, MoveTo_Orientation_mode.
                    TO_TARGET, 0.0) >> moveToChanged(status="DONE"))
            two_lat = 21.370950
            two_lon = -157.709998

        casey_coords = findOffset(two_lat, two_lon, -5, 0)
        donatello_coords = findOffset(two_lat, two_lon, 5, 0)
        leonardo_coords = findOffset(two_lat, two_lon, 0, 5)

        michelangelo_coords = findOffset(event.args["latitude"],
                                         event.args["longitude"], 0, -10)
        raphael_coords = findOffset(event.args["latitude"],
                                    event.args["longitude"], 10, 10)
        splinter_coords = findOffset(event.args["latitude"],
                                     event.args["longitude"], -10, -10)

        casey(
            moveTo(casey_coords[0], casey_coords[1], 10,
                   MoveTo_Orientation_mode.TO_TARGET, 0.0))
        donatello(
            moveTo(donatello_coords[0], donatello_coords[1], 15,
                   MoveTo_Orientation_mode.TO_TARGET, 0.0))
        leonardo(
            moveTo(leonardo_coords[0], leonardo_coords[1], 20,
                   MoveTo_Orientation_mode.TO_TARGET, 0.0))
        michelangelo(
            moveTo(michelangelo_coords[0], michelangelo_coords[1], 25,
                   MoveTo_Orientation_mode.TO_TARGET, 0.0))
        raphael(
            moveTo(raphael_coords[0], raphael_coords[1], 30,
                   MoveTo_Orientation_mode.TO_TARGET, 0.0))
        splinter(
            moveTo(splinter_coords[0], splinter_coords[1], 35,
                   MoveTo_Orientation_mode.TO_TARGET, 0.0))

        print(
            "latitude = {latitude} longitude = {longitude} altitude = {altitude}"
            .format(**event.args))

    @olympe.listen_event(AttitudeChanged())
    def onAttitudeChanged(self, event, scheduler):
        print("roll = {roll} pitch = {pitch} yaw = {yaw}".format(**event.args))

    @olympe.listen_event(AltitudeAboveGroundChanged())
    def onAltitudeAboveGroundChanged(self, event, scheduler):
        print("height above ground = {altitude}".format(**event.args))

    @olympe.listen_event(SpeedChanged())
    def onSpeedChanged(self, event, scheduler):
        print("speedXYZ = ({speedX}, {speedY}, {speedZ})".format(**event.args))

    # You can also handle multiple message types with the same method
    @olympe.listen_event(FlyingStateChanged() | AlertStateChanged()
                         | NavigateHomeStateChanged())
    def onStateChanged(self, event, scheduler):
        # Here, since every "*StateChanged" message has a `state` argument
        # we can handle them uniformly to print the current associated state
        print("{} = {}".format(event.message.name, event.args["state"]))

    # You can also monitor a sequence of event using the complete Olympe DSL syntax
    @olympe.listen_event(
        FlyingStateChanged(state="takingoff", _timeout=1.) >>
        FlyingStateChanged(state="hovering", _timeout=5.))
    def onTakeOff(self, event, scheduler):
        # This method will be called once for each completed sequence of event
        # FlyingStateChanged: motor_ramping -> takingoff -> hovering
        followerTakeOff(casey)

        followerTakeOff(donatello)
        followerTakeOff(leonardo)
        followerTakeOff(michelangelo)
        followerTakeOff(raphael)
        followerTakeOff(splinter)

        print("The drone has taken off!")
        self.has_observed_takeoff = True

    # The `default` listener method is only called when no other method
    # matched the event message The `olympe.listen_event` decorator usage
    # is optional for the default method, but you can use it to further
    # restrict the event messages handled by this method or to limit the
    # maximum size of it associated event queue (remember that the oldest
    # events are dropped silently when the event queue is full).
    @olympe.listen_event(queue_size=10)
    def default(self, event, scheduler):
        print_event(event)
Пример #4
0
        | FlyingStateChanged(state="flying", _policy="check")
        | (GPSFixStateChanged(fixed=1, _timeout=10, _policy="check_wait") >>
           (TakeOff(_no_expect=True)
            & FlyingStateChanged(
                state="hovering", _timeout=10, _policy="check_wait")))).wait()


for drone in swarm:
    takeOff(drone)

casey(
    moveBy(10, 0, 0, math.pi) >> PCMD(1, 0, 0, 0, 0, 0) >> FlyingStateChanged(
        state="hovering", _timeout=5)).wait().success()

casey_location = casey.get_state(GpsLocationChanged)
casey_poi_changed = casey.get_state(PositionChanged)
print(casey_poi_changed)

# poi = makeLineFormation(casey_location["latitude"],  casey_location["longitude"])

# april(
#     moveTo(poi[0],  poi[1], casey_location["altitude"], MoveTo_Orientation_mode.TO_TARGET, 0.0)
#     >> FlyingStateChanged(state="hovering", _timeout=5)
#     >> moveToChanged(latitude=poi[0], longitude=poi[1], altitude=casey_location["altitude"], orientation_mode=MoveTo_Orientation_mode.TO_TARGET, status='DONE', _policy='wait')
#     >> FlyingStateChanged(state="hovering", _timeout=5)
# ).wait()

flying_sub = casey.subscribe(
    lambda event, controller: print("Position State =", event.args["state"]),
    PositionChanged())
Пример #5
0
class FlightListener(olympe.EventListener):
    def set_logger(self, logger):
        self.my_log = logger;
    
    def set_socket(self, websocket):
        self._brain_client = websocket;

    def set_relay(self, relay):
        self._relay = relay

    def set_drone_coordinates(self, coordinates):
        self._drone_coordinates = coordinates

    def set_initialized_socket(self, initialized):
        self._socket_initialized = initialized;

    def set_my_name(self, name):
        self.my_name = name;

    def on_signal_lost (self, func):
        self._on_signal_lost = func;


    @olympe.listen_event(NavigateHomeStateChanged())
    def on_navigation_changed(self, event, scheduler):
        global navigate_home_status_lookup
        try :
            if hasattr(self, "my_log"):
                self.my_log.info("{} = {}".format(event.message.name, event.args["state"]))
            self.emit_status("navigate_home_status_changed", navigate_home_status_lookup.index(event.args["state"]))
        except(Exception) as err :
            if hasattr(self, "my_log"):
                self.my_log.info(err)
           

    @olympe.listen_event(FlyingStateChanged())
    def on_state_changed(self, event, scheduler):
        global flying_status_lookup
        try :
            if hasattr(self, "my_log"):
                self.my_log.info("{} = {}".format(event.message.name, event.args["state"]))
            self.emit_status("flight_status_changed", flying_status_lookup.index(event.args["state"]))
        except(Exception) as err :
            if hasattr(self, "my_log"):
                self.my_log.info(err)
             

    @olympe.listen_event(AlertStateChanged() )
    def on_alert_raised(self, event, scheduler):
        global alert_lookup
        try :
            if hasattr(self, "my_log"):
                self.my_log.info("{} = {}".format(event.message.name, event.args["state"]))
            self.emit_status("on_alert_changed", alert_lookup.index(event.args["state"]))
        except(Exception) as err :
            if hasattr(self, "my_log"):
                self.my_log.info(err)

    @olympe.listen_event(PositionChanged() | moveToChanged())
    def on_position_changed(self, event, scheduler):
        if hasattr(self, "my_log"):
            self.my_log.info(
                "latitude = {} longitude = {} altitude = {}".format(
                  event.args["latitude"],
                  event.args["longitude"],
                  event.args["altitude"]
               )
            )
        if hasattr(self, "_drone_coordinates"):
            self._drone_coordinates.update_position(event.args["latitude"], event.args["longitude"], event.args["altitude"])
            self.on_element_position_update('position_update', event)

    @olympe.listen_event(HomeChanged())
    def on_home_changed(self, event, scheduler):
        if hasattr(self, "my_log"):
              self.my_log.info(
                "latitude = {} longitude = {} altitude = {}".format(
                  event.args["latitude"],
                  event.args["longitude"],
                  event.args["altitude"]
               )
            )
        if hasattr(self, "_relay"):
            self._relay.update_position(event.args["latitude"], event.args["longitude"], event.args["altitude"])
            self.on_element_position_update('home_position_update', event)

    """
    @olympe.listen_event(
        FlyingStateChanged(state="motor_ramping")
        >> FlyingStateChanged(state="takingoff", _timeout=1.)
        >> FlyingStateChanged(state="hovering", _timeout=5.)
    )
    def on_take_off(self, event, scheduler):
        if hasattr(self, "my_log"):
            self.my_log.info("Décollage du drone")
        #event.message.name
        self.emit_status("takeoff", event.args["success"])
    """

    @olympe.listen_event(rssi_changed())
    def on_signal_changed(self, event, scheduler):
        if hasattr(self, "my_log"):
            self.my_log.info(event.args)
        self.on_internal_status_changed(event.message.name, event.args["rssi"])
        if hasattr(self, "_on_signal_lost") and event.args["rssi"] <= -120:
            self._on_signal_lost()

    @olympe.listen_event(NumberOfSatelliteChanged())
    def on_satellite_changed(self, event, scheduler):
        if hasattr(self, "my_log"):
            self.my_log.info(event);
        self.on_internal_status_changed(event.message.name, event.args["numberOfSatellite"])

    @olympe.listen_event(BatteryStateChanged())
    def on_battery_update(self, event, scheduler):
        if hasattr(self, "my_log"):
            self.my_log.info(event);
        self.on_internal_status_changed(event.message.name, event.args["percent"])
  
    @olympe.listen_event(GPSFixStateChanged())
    def on_gps_changed(self, event, scheduler):
        if hasattr(self, "my_log"):
            self.my_log.info(event);
        self.on_internal_status_changed(event.message.name, event.args["fixed"])
  
    def on_internal_status_changed(self, name, value):
        try :
            if hasattr(self, "_socket_initialized") and hasattr(self, "my_name") and hasattr(self,"_brain_client") and self._socket_initialized:
                self._brain_client.emit('internal_status_changed', {"id":self.my_name, "status":name, "result":value})
        except(Exception) as error :
            if hasattr(self, "my_log"):
                self.my_log.error("Une erreur est survenue lors de la mise à jour des états interne")
                self.my_log.error(error)
                self.my_log.error("{} = {}".format(value.message.name, value.args))
                        
    def on_element_position_update(self, event, value): 
        try :
            if hasattr(self, "_socket_initialized") and hasattr(self, "my_name") and hasattr(self,"_brain_client") and self._socket_initialized:
                self._brain_client.emit(event, {"id":self.my_name,"latitude": value.args["latitude"], "longitude": value.args["longitude"], "altitude": value.args["altitude"] })
        except(Exception) as error :
            if hasattr(self, "my_log"):
                self.my_log.error("Une erreur est survenue lors de la mise à jour des positions")
                self.my_log.error(error)
                self.my_log.error("{} = {}".format(value.message.name, value.args))

    def emit_status(self, name, value):
        try :
            if hasattr(self, "_socket_initialized") and hasattr(self, "my_name") and hasattr(self,"_brain_client") and self._socket_initialized:
                self._brain_client.emit(name, {"drone_name":self.my_name, "status":value})
        except(Exception) as error :
            if hasattr(self, "my_log"):
                self.my_log.error("Une erreur est survenue lors de la mise à jour des états interne")
                self.my_log.error(error)
                self.my_log.error("{} = {}".format(value.message.name, value.args))
Пример #6
0
        TakeOff() >> FlyingStateChanged(state="hovering", _timeout=10)).wait()
else:
    print("Drone is already hovering/flying.")

# check flying state again
cur_fly_state = drone.get_state(FlyingStateChanged)['state']
print("Current flying state is: ", cur_fly_state)

# check battery percentage
print("current battery percentage: ",
      drone.get_state(BatteryStateChanged)['percent'])

print("Moving in x-direction by 1m")
state = drone(moveBy(1, 0, 0, 0))  # don't wait. Send command and proceed
# wait until you get a PositionChanged event from drone
while not drone(PositionChanged()):
    pass

# Keep checking response state from moveBy until it's success.
while not state.success():
    # keep checking Global position (GPS) and speed.
    cur_pos = drone.get_state(PositionChanged)
    cur_speed = drone.get_state(SpeedChanged)
    print("current pos(gps): = ", cur_pos)
    print("current speed: = ", cur_speed)
    time.sleep(0.1)

print("Landing")
drone(Landing() >> FlyingStateChanged(state="landing", _timeout=5)).wait()

drone.disconnection()  # disconnect from the drone