コード例 #1
0
ファイル: robot.py プロジェクト: waffelroffel/TDT4113-Ovinger
class BBCON:
    def __init__(self):

        self.behaviors = []
        self.sensobs = []

        self.motob = Motob()
        self.motob.update("brake")
        self.arbitrator = Arbitrator()

    def add_behavior(self, behavior):
        self.behaviors.append(behavior)

    def add_sensob(self, sensob):
        self.sensobs.append(sensob)

    # def activate_behavior(self, behavior):
    #    self.active_behaviors.add(behavior)

    # def deactive_behavior(self, behavior):
    #    self.active_behaviors.remove(behavior)

    def move(self, action):
        self.motob.update(action)

    def run_one_timestep(self, delay=0.667):
        start_time = time()

        # Reflectance sensor index 0
        # Proximity   sensor index 1
        # Camera      sensor index 2

        #self.data = [s.update() for s in self.sensobs]

        self.data = []

        for s in self.sensobs:
            tmp = time()
            self.data.append(s.update())
            print("Time for {0}: {1}".format(s.sensor, round((time() - tmp)*1000, ndigits = 2)))

        mrs = []
        for b in self.behaviors:
            tmp = time()
            mrs.append(b.update())
            print("Time for {0}: {1}".format(b, round((time() - tmp)*1000, ndigits = 2)))
        #tmp = time()
        #mrs = [b.update() for b in self.behaviors]

        print(sorted(mrs, key=lambda x: x[1]))
        action = self.arbitrator.choose_action(mrs)
        print(action)
        self.move(action)

        execution_time = time() - start_time
        #delay = max(delay - execution_time, 0)
        delay = (delay - execution_time) if execution_time < delay else 0
        print("Delay time: ", delay, "\n")
        sleep(delay)
コード例 #2
0
ファイル: robot.py プロジェクト: waffelroffel/TDT4113-Ovinger
class BBCON:
    def __init__(self):

        self.behaviors = []
        self.sensobs = []

        self.motob = Motob()
        self.arbitrator = Arbitrator()

    def add_behavior(self, behavior):
        self.behaviors.append(behavior)

    def add_sensob(self, sensob):
        self.sensobs.append(sensob)

    #def activate_behavior(self, behavior):
    #    self.active_behaviors.add(behavior)

    #def deactive_behavior(self, behavior):
    #    self.active_behaviors.remove(behavior)

    def move(self, action):
        self.motob.update(action)

    def run_one_timestep(self, delay = 0.667):
        start_time = time()

        # Reflectance sensor index 0
        # Proximity   sensor index 1
        # Camera      sensor index 2

        print("Updating sensors...", end = "")

        #self.data = [s.update() for s in self.sensobs]

        self.data = []
        for s in self.sensobs:
            tmp = time()
            self.data.append(s.update())
            print("Time for:", s.sensor, ": ", round((time()-tmp)*1000, ndigits = 4), "ms")


        print("Updating behaviors...")
        tmp = time()

        mrs       = [b.update() for b in self.behaviors]
        print((time()-tmp)*1000, "ms")
        action = self.arbitrator.choose_action(mrs)

        print("Moving.")
        self.move(action)

        execution_time = time() - start_time
        #delay = max(delay - execution_time, 0)
        delay = (delay - execution_time) if execution_time < delay else 0
        print("Delay time: ", delay)
        sleep(delay)
コード例 #3
0
class BBCON:

    def __init__(self):
        """ init """
        self.sensobs = []
        self.add_sensob(Sensob(Ultrasonic()))
        self.add_sensob(Sensob(ReflectanceSensors()))
        self.add_sensob(Sensob(Camera()))

        self.motob = Motob()

        self.behaviors = []
        self.add_behavior(Behavior(self, [10000, 10000, [10000, 10000, 10000]], "drive", 1))
        self.add_behavior(Behavior(self, [30, 10000, [10000, 10000, 10000]], "stop", 3))
        self.add_behavior(Behavior(self, [10000, 0.3, [10000, 10000, 10000]], "turnaround", 2))
        self.add_behavior(Behavior(self, [10000, 10000, [210, 10000, 10000]], "turn_left", 5))
        #self.add_behavior(Behavior(self, [10000, 10000, [10000, 200, 10000]], "turn_right", 4))
        self.active_behaviors = []

        self.arbitrator = Arbitrator()

    def add_behavior(self, behavior):
        """append a newly-created behavior onto the behaviors list"""
        self.behaviors.append(behavior)

    def add_sensob(self, sensor):
        """append a newly-created sensob onto the sensobs list"""
        self.sensobs.append(sensor)

    def activate_behavior(self, behavior):
        """add an existing behavior onto the active-behaviors list"""
        self.active_behaviors.append(behavior)

    def deactivate_behavior(self, behavior):
        """remove an existing behavior from the active behaviors list"""
        self.active_behaviors.remove(behavior)

    def run_one_timestep(self):
        """constitutes the core BBCON activity"""
        prod_count = 0
        for sensob in self.sensobs:         #Updates all sensobs
            sensob.update()
            if(prod_count == 2):
                image = Imager(False, sensob.get_value())
                print("Camera pixel", image.get_pixel(20, 30))
            prod_count += 1

        for behavior in self.behaviors:     #Update all behaviors
            behavior.update(self.sensobs)

        fav_behavior = self.arbitrator.choose_action(self.active_behaviors)
        self.motob.update(fav_behavior.sense_and_act())
コード例 #4
0
class BBCON:
    def __init__(self):
        self.behaviors = []
        self.active_behaviors = []
        self.sensobs = []
        self.motob = Motob()
        self.arbitrator = Arbitrator(self)
        self.picture_taken = False
        self.reset = False

    def get_active_behaviors(self):
        return self.active_behaviors

    def add_behavior(self, behavior):
        if behavior not in self.behaviors:
            self.behaviors.append(behavior)

    def add_sensob(self, sensob):
        if sensob not in self.sensobs:
            self.sensobs.append(sensob)

    def activate_behavior(self, behavior):
        if behavior not in self.active_behaviors:
            self.active_behaviors.append(behavior)

    def deactivate_behavior(self, behavior):
        if behavior in self.active_behaviors:
            self.active_behaviors.remove(behavior)

    def is_picture_taken(self):
        return self.picture_taken

    def reset_sensobs(self):
        for sensob in self.sensobs:
            sensob.reset()

    def run_one_timestep(self):
        for sensob in self.sensobs:
            sensob.update()
        for behavior in self.behaviors:
            behavior.update()
        motor_recommendations = self.arbitrator.choose_action()
        self.motob.update(motor_recommendations)
        if self.reset:
            self.reset_sensobs()
        sleep(0.1)
コード例 #5
0
ファイル: bbcon.py プロジェクト: cathrbak/Zumo-robot
class BBCON:
    def __init__(self):
        self.behaviours = []  # liste med alle oppførslene til bbcon
        self.active_behaviours = []  # liste med alle oppførsler som er aktive
        self.sensobs = []  # liste med alle sensorobejekt brukt av bbcon
        self.motobs = Motob()  # liste med alle motorobjekt brukt av bbcon
        self.arbitrator = Arbitrator()  # ikke laget ennå

    # legger til en oppførsel
    def add_behaviour(self, behaviour):
        if behaviour not in self.behaviours:
            self.behaviours.append(behaviour)

    # legger til en sensor
    def add_sensob(self, sensob):
        if sensob not in self.sensobs:
            self.sensobs.append(sensob)

    # legger til en oppførsel i aktivert-listen
    def activate_behaviour(self, behaviour):
        if behaviour in self.behaviours:
            self.active_behaviours.append(behaviour)

    # fjerner en aktiv oppførsel fra listen
    def deactivate_behaviour(self, behaviour):
        if behaviour in self.active_behaviours:
            self.active_behaviours.remove(behaviour)

    # kjerneaktiviteten til bbcon
    def run_one_timestep(self):

        # oppdaterer oppførsler som også oppdaterer sensobs
        for behaviour in self.behaviours:
            behaviour.update()

        # returnerer
        print("Active behaviours: ", self.active_behaviours)
        motor_recoms = self.arbitrator.choose_action(self.active_behaviours)

        # oppdaterer motobs
        self.motobs.update(motor_recoms)

        # reseter sensorverdier
        for sensor in self.sensobs:
            sensor.reset()
コード例 #6
0
def rett_fram():
    ir = ReflectanceSensors(True)
    s = Sensob(ir)
    ab = Avoid_borders(s, s)
    wr = Walk_randomly(s, s)
    a = Arbitrator()
    m = Motob()
    print("Motob set")
    ZumoButton().wait_for_press()
    print("Button pressed")
    while True:
        ab.update()
        wr.update()
        print("Vekt: ", ab.weight)
        print("Rec: ", ab.motor_recommendations)
        winner_rec = a.choose_action(ab, wr)
        print("recom: ", winner_rec)
        m.update(winner_rec)
コード例 #7
0
ファイル: bbcon.py プロジェクト: oddeirikigland/Zumo
class BBCON:
    def __init__(self):
        self.behaviors = []
        self.active_behaviors = []
        self.sensobs = []
        self.motob = Motob()
        self.arbitrator = Arbitrator(self)
        self.picture_taken = False

    def get_active_behaviors(self):
        return self.active_behaviors

    def add_behavior(self, behavior):
        if behavior not in self.behaviors:
            self.behaviors.append(behavior)

    def add_sensob(self, sensob):
        if sensob not in self.sensobs:
            self.sensobs.append(sensob)

    def activate_behavior(self, behavior):
        if behavior not in self.active_behaviors:
            self.active_behaviors.append(behavior)

    def deactivate_behavior(self, behavior):
        if behavior in self.active_behaviors:
            self.active_behaviors.remove(behavior)

    def is_picture_taken(self):
        return self.picture_taken

    def run_one_timestep(self):
        print("RUN ONE TIME STEP")
        for sensob in self.sensobs:
            sensob.update()
        print("SENSOBS FINISHED")
        for behavior in self.behaviors:
            behavior.update()
        print("BEHAVIOUR FINISHED")
        #print("%s weight: %s" %(behavior.get_name(),behavior.get_weight()))
        motor_recommendations = self.arbitrator.choose_action()
        #print("Recommendations: %s",(motor_recommendations))
        self.motob.update(motor_recommendations)
        sleep(0.5)
コード例 #8
0
ファイル: main.py プロジェクト: runaraj/Proglab
def test5():

    ZumoButton().wait_for_press()
    m = Motors()
    motob = Motob(m)
    sensor = Ultrasonic()

    sensob = Sensob()
    sensob.set_sensors([sensor])

    behavior = CollisionAvoidance(1, [sensob])
    print("Behavior sensob:", behavior.sensobs)
    count = 0
    while True:
        sensob.update()
        behavior.update()
        #print("MR:", behavior.get_sensob_data())
        motob.update(behavior.motor_recommendations[0])
        count +=1
        if count==12:
            break
コード例 #9
0
ファイル: main.py プロジェクト: runaraj/Proglab
def test4():
    sensor = ReflectanceSensors()
    ZumoButton().wait_for_press()
    m = Motors()
    motob = Motob(m)

    sensob = Sensob()
    sensob.set_sensors([sensor])
    print(sensor.get_value())
    behavior = FollowLine(1, [sensob])
    #print("Behavior sensob:", behavior.sensobs)
    count = 0
    while True:
        sensob.update()
        behavior.update()
        print("MR:", behavior.motor_recommendations)
        motob.update(behavior.motor_recommendations[0])
        count += 1
        #time.sleep(3)
        if count == 15:
            break
コード例 #10
0
ファイル: test.py プロジェクト: Lagostra/Proglab2Robot
def main():
    wp.wiringPiSetupGpio()

    motors = Motors()
    motors.stop()
    motob = Motob(motors)

    sensors = {
        #'ultrasonic': Ultrasonic(0.05),
        #'IR': IRProximitySensor(),
        #'reflectance': ReflectanceSensors(False, 0, 900),
        #'camera': Camera(),
    }

    # Initialize sensobs

    sensobs = {
        #'distance': DistanceSensob([sensors['ultrasonic']]),
        #'line_pos': LinePosSensob([sensors['reflectance']]),
        #'proximity': ProximitySensob([sensors['IR']]),
        #'red_search': RedSearchSensob([sensors['camera']]),
    }

    commands = [(Command.F, 0.5), (Command.R, 0.5), (Command.F, 1)]
    i=0
    while True:
        for sensor in sensors.values():
            sensor.update()

        for sensob in sensobs.values():
            sensob.update()

        motob.update(commands[i%len(commands)])

        time.sleep(1)
        i+=1
コード例 #11
0
ファイル: bbcon.py プロジェクト: haakon8855/zumo_bullfighter
class BBCON:
    """Behaviour based controller"""

    timestep = 0.001

    def __init__(self):
        self.running = True
        self.behaviours = []
        self.active_behaviours = []
        self.inactive_behaviours = []
        self.sensobs = []
        self.motob = Motob()
        self.arbitrator = Arbitrator(self)
        self.setup()

    def setup(self):
        """Sets up behaviours and sensobs"""
        sensob_border_lines = SensobBorderLines()
        sensob_camera = SensobCamera()
        sensob_ultrasonic = SensobUltrasonic()
        self.sensobs.append(sensob_border_lines)
        self.sensobs.append(sensob_camera)
        self.sensobs.append(sensob_ultrasonic)
        self.behaviours.append(AvoidLineCrossing(self, [sensob_border_lines]))
        self.behaviours.append(AvoidWall(self, [sensob_ultrasonic]))
        self.behaviours.append(DefaultMovement(self, []))
        self.behaviours.append(
            FollowRed(self, [sensob_camera, sensob_ultrasonic]))
        for behaviour in self.behaviours:
            self.active_behaviours.append(behaviour)

    def add_behaviour(self, behaviour):
        """Adds a new behaviour to the list of behaviours"""
        if behaviour not in self.behaviours:
            self.behaviours.append(behaviour)

    def add_sensob(self, sensob):
        """Adds a new sensob to the list of sensobs"""
        if sensob not in self.sensobs:
            self.sensobs.append(sensob)

    def activate_behaviour(self, behaviour):
        """Sets an inactive behaviour as active"""
        if (behaviour in self.behaviours
                and behaviour not in self.active_behaviours
                and behaviour in self.inactive_behaviours):
            self.inactive_behaviours.remove(behaviour)
            self.active_behaviours.append(behaviour)

    def deactivate_behaviour(self, behaviour):
        """Sets an active behaviour as inactive"""
        if (behaviour in self.behaviours
                and behaviour in self.active_behaviours
                and behaviour not in self.inactive_behaviours):
            self.active_behaviours.remove(behaviour)
            self.inactive_behaviours.append(behaviour)

    def run_one_timestep(self):
        """Runs one timestep by updating sensors,
        behaviors, arbitrator and motors"""
        print("#####################################")
        self.update_sensobs()
        self.update_behaviours()
        motor_recommendation = self.arbitrator.choose_action()
        self.update_motob(motor_recommendation)
        if self.behaviours[3].active_flag:
            self.timestep = 0.001
        else:
            self.timestep = 0.3
        sleep(self.timestep)
        self.reset_sensobs()

    def update_sensobs(self):
        """Instructs all sensobs to get value from sensors and save it."""
        for sensob in self.sensobs:
            if sensob == self.sensobs[1]:
                if self.behaviours[3].active_flag:
                    sensob.update()
            else:
                sensob.update()

    def reset_sensobs(self):
        """Instructs all sensobs to reset if it needs to"""
        for sensob in self.sensobs:
            sensob.reset()

    def update_behaviours(self):
        """Instructs all behaviours to make a motor recommendation."""
        for behaviour in self.behaviours:
            behaviour.update()

    def update_motob(self, moto_rec):
        """Updates the motobs to do the requested motor recommendation"""
        self.motob.update(moto_rec)
コード例 #12
0
class BBCON:
    def __init__(self):
        self.behaviors = []
        self.active_behaviors = []
        self.sensobs = []
        self.motob = Motob()
        self.arbitrator = Arbitrator(self)
        self.setup()

    def setup(self):
        # LineBehavior
        rs = ReflectanceSensors()
        rsob = ReflectanceSensob(rs)
        lineb = FollowLineBehavior(self, [rsob], False, 0.7)
        self.add_behavior(lineb)
        self.activate_behavior(lineb)
        self.add_sensob(rsob)

        # Forward Behavior
        forwardb = ForwardBehavior(self, [rsob], False, 0.2)
        self.add_behavior(forwardb)
        self.activate_behavior(forwardb)

        # Follow green flask
        my_camera = Camera()
        self.followgreensensob = GreenDirectionSensob(my_camera)
        followgreenb = FollowGreenFlask(self, [self.followgreensensob, rsob],
                                        False, 1.0)
        self.add_behavior(followgreenb)
        self.activate_behavior(followgreenb)
        self.add_sensob(self.followgreensensob)

        # Avoid Collision
        us = Ultrasonic()
        ir = IRProximitySensor()
        self.irob = IRProximitySensob(ir)
        self.usob = UltrasonicSensob(us)
        self.add_sensob(self.irob)
        self.add_sensob(self.usob)
        avoidb = AvoidCollisionBehavior(self, [self.usob, self.irob, rsob],
                                        False, 1.0)
        self.add_behavior(avoidb)
        self.activate_behavior(avoidb)

    def add_behavior(self, behavior):
        self.behaviors.append(behavior)

    def add_sensob(self, sensob):
        self.sensobs.append(sensob)

    def activate_behavior(self, behavior):
        if behavior in self.behaviors and behavior not in self.active_behaviors:
            self.active_behaviors.append(behavior)

    def deactivate_behavior(self, behavior):
        if behavior in self.active_behaviors:
            self.active_behaviors.remove(behavior)

    def run_one_timestep(self):
        for sensob in self.sensobs:
            sensob.update()

        for behavior in self.behaviors:
            behavior.update()

        motor_recommendation = self.arbitrator.choose_action_deterministic()

        self.motob.update(motor_recommendation)

        time.sleep(.1)

        for sensob in self.sensobs:
            sensob.reset()
        '''
        - Update all relevant sensobs
        - Update all behaviors
        - Invoke arbitrator (self.arbitrator.choose_action)
        - Update all motobs
        - Wait
        - Reset sensobs
        '''

    def stop(self):
        self.motob.stop()
コード例 #13
0
ファイル: main.py プロジェクト: runaraj/Proglab
def test2():
    ZumoButton().wait_for_press()
    motob = Motob(Motors())
    deg = input("Skriv antall grader: ")
    dir = input("Skriv retning L/R: ")
    motob.update((dir, int(deg)))
コード例 #14
0
class Bbcon:

    def __init__(self):
        self.behaviors = []                     #Liste over alle behaviors, aktive og inaktive
        self.active_behaviors = []              # Kun aktive behaviors
        self.sensobs = []                       # Liste over sensorer
        self.motobs = Motob(self)               # Liste med motorobjekter
        self.arbitrator = Arbitrator()          # Arbitrator-objektet, velger winning behavior
        self.num_timesteps = 0                  # Hvor mange timesteps som er kjort
        self.can_take_photo = False


    #Trivielt, legger til behavior i listen
    def add_behavior(self, behavior):
        if behavior not in self.behaviors:
            self.behaviors.append(behavior)

    # Trivielt, legger til sensor-objekt i listen
    def add_sensor(self, sensor):
        if sensor not in self.sensobs:
            self.sensobs.append(sensor)

    # Legger til behavior i listen over active-behaviors
    def activate_behavior(self, behavior):
        if behavior in self.behaviors:
            self.active_behaviors.append(behavior)

    # Fjerner aktive behaviors fra active-behaviors listen
    def deactivate_behavior(self, behavior):
        if behavior in self.active_behaviors:
            self.active_behaviors.remove(behavior)

    # Resetter dersom bilde allerede er tatt
    def photo_taken(self):
        self.can_take_photo = False
        self.motobs.photograph = False

    # loopen til klassen
    def run_one_timestep(self):
        # Oppdaterer behaviors
        for behaviour in self.behaviors:
            behaviour.update()

        # Henter ut motor-recommendations
        print("Active behaviors", self.active_behaviors)
        motor_recoms = self.arbitrator.choose_action(self.active_behaviors)

        # Oppdaterer motobs
        self.motobs.update(motor_recoms)

        if self.motobs.photograph:
            self.can_take_photo = True

        # vent slik at motorene kan gjore tingen sin
        sleep(0.25)

        # Reset sensorverdiene
        for sensor in self.sensobs:
            sensor.reset()

        self.active_behaviors=[]

        self.num_timesteps += 1
コード例 #15
0
ファイル: BBCON.py プロジェクト: henrhoi/Zumo_Robot
class BBCON:
    def __init__(self):
        self.behaviors = [
        ]  #En liste av alle behavior objektene som brukes av BBCON
        self.active_behaviors = []  #En liste med de aktive behavior objektene
        self.sensobs = [
        ]  #En liste av alle sensorobjektene som brukes av BBCON
        self.motobs = Motob(
        )  #En liste ac alle motor objektene som brukes av BBCON
        self.arbitrator = Arbitrator(
            self, False)  #Arbitratoren som skal løse requests fra behaviors
        self.take_pic = False

        #Andre variabler kan være current_timestep, inaktive behaviors og roboten selv

    def add_behavior(self, behavior):
        if behavior not in self.behaviors:
            self.behaviors.append(behavior)

    def add_sensob(self, sensor):
        if sensor not in self.sensobs:
            self.sensobs.append(sensor)

    def activate_behavior(self, behavior):
        if behavior not in self.active_behaviors:
            behavior.active_flag = True
            self.active_behaviors.append(behavior)

    def deactivate_behavior(self, behavior):
        if behavior in self.active_behaviors:
            behavior.active_flag = False
            self.active_behaviors.remove(behavior)

    # Oppdatere sensobs
    def update_sensobs(self):
        print("Updating sensobs")
        for sensob in self.sensobs:
            sensob.update()

    def reset_sensobs(self):
        for sensob in self.sensobs:
            sensob.reset()

    # Oppdatere behaviours
    def update_behaviors(self):
        print("Updating behaviors")
        for behavior in self.behaviors:
            behavior.update()

    def update_motobs(self, action):
        self.motobs.update(action)

    def run_one_timesteps(self):
        #Update sensobs
        self.update_sensobs()

        #Update behaviors
        self.update_behaviors()

        print("Active behaviors:", (self.active_behaviors))

        #Call arbitrator.choose_action
        action = self.arbitrator.choose_action()
        print("Recommendation: ", action)

        #Update motobs
        self.update_motobs(action)

        #Pause
        #time.sleep(0.2)

        #Reset sensobs
        self.reset_sensobs()
コード例 #16
0
class BBcon:
    def __init__(self):
        self.behaviors = []
        self.active_behaviors = []
        self.sensobs = []
        self.motob = Motob()
        self.arbitrator = Arbitrator(self)
        self._running = False

    def add_behavior(self, behavior):
        self.behaviors.append(behavior)

    def add_sensob(self, sensob):
        self.sensobs.append(sensob)

    # add a newly active behavior to the active_behaviors list
    # (if it exists in behaviors)
    def activate_behavior(self, active_behavior):
        if self.behaviors.__contains__(active_behavior) and \
                active_behavior not in self.active_behaviors:
            self.active_behaviors.append(active_behavior)

    # remove a newly deactived behavior from the active_behaviors list
    # (if it exists in active_behaviors)
    def deactivate_behavior(self, deactive_behavior):
        if self.active_behaviors.__contains__(deactive_behavior):
            self.active_behaviors.remove(deactive_behavior)

    def run_one_timestep(self):
        # update all sensobs
        for i in range(len(self.sensobs)):
            if not (i == 0 and self.behaviors[1].active_flag == False):
                self.sensobs[i].update()

        # update all behaviors
        for behavior in self.behaviors:
            behavior.update()
            if behavior.active_flag:
                self.activate_behavior(behavior)
            else:
                self.deactivate_behavior(behavior)

        recommended_behavior, halt_request = self.arbitrator.choose_action()

        # update motor object based on recommended_behavior
        self.motob.update(recommended_behavior)

        # reset sensobs
        for sensob in self.sensobs:
            sensob.reset()

        # Stop running if a halt is requested
        if halt_request:
            self._running = False

    def startup(self):
        # add sensor objects
        cam = Sensob(Camera())
        ultrasonic = Sensob(Ultrasonic())
        ir_sensor = Sensob(ReflectanceSensors())
        self.add_sensob(cam)
        self.add_sensob(ultrasonic)
        self.add_sensob(ir_sensor)

        # add behaviors
        sb = StandardBehavior(self)
        self.add_behavior(sb)
        self.activate_behavior(sb)
        cb = CameraBehavior(self)
        self.add_behavior(cb)
        self.activate_behavior(cb)
        ub = UltraBehavior(self)
        self.add_behavior(ub)
        self.activate_behavior(ub)
        ir = IRBehavior(self)
        self.add_behavior(ir)
        self.activate_behavior(ir)

        button = ZumoButton()
        button.wait_for_press()
        self._running = True
        while self._running:
            self.run_one_timestep()
            # wait
            time.sleep(0.001)
コード例 #17
0
class Bbcon:
    def __init__(self):
        self.behaviors = [
        ]  # behavior-listen, med både inaktive og aktive behaviors
        self.active_behaviors = []  # liste med aktive behaviors
        self.sensobs = []  # liste med sensor-objekter
        self.motobs = Motob(self)  # list med motor-objekter
        self.arbitrator = Arbitrator(
        )  # arbitrator-objektet, velger winning-behavior
        self.num_timesteps = 0  # antall timesteps som er kjørt
        self.can_take_photo = False

    # Legger til behavior i listen
    def add_behavior(self, behavior):
        if behavior not in self.behaviors:
            self.behaviors.append(behavior)

    # Legger til sensor-objekt i listen
    def add_sensor(self, sensor):
        if sensor not in self.sensobs:
            self.sensobs.append(sensor)

    # Legger til behavior i listen over active-behaviors
    def activate_behavior(self, behavior):
        if behavior in self.behaviors:
            self.active_behaviors.append(behavior)

    # Fjerner aktive behaviors fra active-behaviors listen
    def deactivate_behavior(self, behavior):
        if behavior in self.active_behaviors:
            self.active_behaviors.remove(behavior)

    # Resetter hvis foto er tatt
    def photo_taken(self):
        self.can_take_photo = False
        self.motobs.photograph = False

    # "loopen" til klassen
    def run_one_timestep(self):

        # Oppdaterer behaviors
        for behaviour in self.behaviors:
            behaviour.update()

        # Henter ut motor-recommendations
        print("Active behaviors", self.active_behaviors)
        motor_recoms = self.arbitrator.choose_action(self.active_behaviors)

        # Oppdaterer motobs
        self.motobs.update(motor_recoms)

        if self.motobs.photograph:
            self.can_take_photo = True

        # vent slik at motorene kan gjøre tingen sin
        sleep(0.25)

        # Reset sensorverdiene
        for sensor in self.sensobs:
            sensor.reset()

        self.active_behaviors = []

        self.num_timesteps += 1
コード例 #18
0
ファイル: motob_test.py プロジェクト: Maro1/Zumo_Robot
def test():
    ZumoButton().wait_for_press()
    motobs = Motob()
    motobs.update(['S'])
    sleep(1)
    motobs.update(['F'])
コード例 #19
0
class BehaviorBasedController:
    """
    BBCON (Behaviour-Based CONtroller); one instance per robot. Robot calls this class for the next move.
    """
    def __init__(self):
        self.__behaviors = []  # List of all behaviors
        self.active_behaviors = []  # List of all _active_ behaviors
        self.__sensobs = []  # List of all sensory objects
        self.motob = Motob()  # List of all motor objects
        self.__arbitrator = Arbitrator(
            self)  # Arbitrator chooses the next behavior

        self.timesteps = 0
        self.notifications = []

    def should_continue_operating(self):
        return "q" not in self.notifications

    def add_behaviour(self, behavior: Behavior):
        """
        Adds a newly created behavior into the behaviors list.
        :param behavior: behavior to be added
        """
        if behavior not in self.__behaviors:
            self.__behaviors.append(behavior)
            # TODO: Refactor this because the method is doing more than it's name is implying.
            for sensob in behavior.sensobs:
                self.add_sensob(sensob)

    def remove_behaviour(self, behavior: Behavior):
        """
        Adds a newly created behavior into the behaviors list.
        :param behavior: behavior to be added
        """
        if behavior in self.__behaviors:
            self.__behaviors.remove(behavior)

    def add_sensob(self, sensob: Sensob):
        """
        Adds a newly created sensob into the sensobs list.
        :param sensob: sensob to be added
        """
        if sensob not in self.__sensobs:
            self.__sensobs.append(sensob)

    def remove_sensob(self, sensob: Sensob):
        """
        Removes a previously added sensob from the sensobs list.
        :param sensob: sensob to be removed
        """
        if sensob in self.__sensobs:
            self.__sensobs.remove(sensob)

    def activate_behavior(self, behavior: Behavior):
        """
        Activates a behavior by moving it to the active behaviors list.
        :param behavior: behavior to be activated
        """
        if behavior not in self.active_behaviors:
            self.active_behaviors.append(behavior)

    def deactivate_behavior(self, behavior: Behavior):
        """
        Deactivates a behavior by removing it from the active behaviors list.
        :param behavior: behavior to be deactivated
        """
        if behavior in self.active_behaviors:
            self.active_behaviors.remove(behavior)

    def run_one_timestep(self):
        """
        The core BBCON activity; updates sensors and behaviors, invokes arbitrator, invokes sensors, waits, resets
            sensors..
        """

        # Update all sensors
        # TODO: Couldn't this actually be done in every behavior? behavior.reset_sensors()?
        for sensob in self.__sensobs:
            if isinstance(sensob, CameraSensob):
                if len(self.notifications
                       ) > 0 and self.notifications[0] == "p":
                    sensob.update()
                else:
                    continue
            else:
                sensob.update()

        # Update all behaviors
        for behavior in self.__behaviors:
            behavior.update()

        print("Active behaviors: {}".format(self.active_behaviors))

        if len(self.active_behaviors) > 0:
            # TODO: Change implementation to use halt request
            motor_recommendations, halt_request = self.__arbitrator.choose_action(
            )
            print("Next recommendation: {}".format(motor_recommendations))

            # Update motobs based on motor recommendations
            self.motob.update(motor_recommendations)
        else:
            # Default behavior; this is just temporary.
            # TODO: Implement default behavior
            print("No active behaviors, will drive forward.")
            self.motob.update(["f"])

        # Reset sensobs
        for sensob in self.__sensobs:
            sensob.reset()

        self.timesteps += 1