Exemple #1
0
def processInput():
    while True:
        command = input()
        if command == "connect":
            connect()
        elif command == "broadcast":
            broadcast()
        elif command == "leader":
            SERVERS[FOCUS_PORT].sendall(pickle.dumps(Leader()))
        elif command == 'leader':
            SERVERS[FOCUS_PORT].sendall(Leader())
        elif 'swap' in command:
            swap(command[5:])
        elif command == "exit":
            SERVER_SOCK.close()
            for sock in SERVERS:
                SERVERS[sock].close()
            os._exit(1)
        elif "operation" in command.lower():
            parsed = command.replace("(", "").replace(")", "")
            parsed = parsed.lower().replace("operation", "")
            vals = parsed.split(",")
            op = vals[0].strip()
            key = vals[1].strip()
            req = OpRequest(op, key, False)
            if op == "put":
                val = vals[2].strip()
                req = OpRequest(op, key, False, False, val)
            clientOp.put(req)
            if clientOp.qsize() == 1:  # Only spawn thread if first operation
                threading.Thread(target=handleOp).start()
            #msg = pickle.dumps(req)
            #SERVERS[FOCUS_PORT].sendall(msg)

    return
Exemple #2
0
    def run(self):
        self.successful_event = 0
        initialconfig = Config([], [], [])
        self.times = []
        c = 0

        for i in range(self.no_of_replicas):

            pid = "replica %d" % i
            Replica(self, pid, initialconfig)
            initialconfig.replicas.append(pid)
        for i in range(NACCEPTORS):
            pid = "acceptor %d.%d" % (c, i)
            Acceptor(self, pid)
            initialconfig.acceptors.append(pid)
        for i in range(NLEADERS):
            pid = "leader %d.%d" % (c, i)
            Leader(self, pid, initialconfig)
            initialconfig.leaders.append(pid)
        for i in range(self.no_of_requests):
            self.start_time = datetime.now()
            pid = "client %d.%d" % (c, i)
            for r in initialconfig.replicas:
                cmd = Command(pid, 0, "operation %d.%d" % (c, i))
                self.sendMessage(r, RequestMessage(pid, cmd))
                time.sleep(1)
            self.end_time = datetime.now()
            self.total_time = self.end_time - self.start_time
            # print(self.times)
            self.times.append(self.total_time.total_seconds())

        for c in range(1, NCONFIGS):
            # Create new configuration
            config = Config(initialconfig.replicas, [], [])
            for i in range(NACCEPTORS):
                pid = "acceptor %d.%d" % (c, i)
                Acceptor(self, pid)
                config.acceptors.append(pid)
            for i in range(NLEADERS):
                pid = "leader %d.%d" % (c, i)
                Leader(self, pid, config)
                config.leaders.append(pid)
            # Send reconfiguration request
            for r in config.replicas:
                pid = "master %d.%d" % (c, i)
                cmd = ReconfigCommand(pid, 0, str(config))
                self.sendMessage(r, RequestMessage(pid, cmd))
                time.sleep(1)
            for i in range(WINDOW - 1):
                pid = "master %d.%d" % (c, i)
                for r in config.replicas:
                    cmd = Command(pid, 0, "operation noop")
                    self.sendMessage(r, RequestMessage(pid, cmd))
                    time.sleep(1)
            for i in range(self.no_of_requests):
                pid = "client %d.%d" % (c, i)
                for r in config.replicas:
                    cmd = Command(pid, 0, "operation %d.%d" % (c, i))
                    self.sendMessage(r, RequestMessage(pid, cmd))
                    time.sleep(1)
Exemple #3
0
    def __init__(self):
        super(GLWidget, self).__init__()
        self.xres = 1024
        self.yres = 768
        self.setMinimumSize(self.xres, self.yres)
        self.info = PInfo()
        self.globalParams = PGlobal()
        self.leaderParams = PLeader()
        self.followerParams = PFollower()
        self.leader = Leader(self.leaderParams, self.globalParams)

        self.grid = Grid()
        self.followers = []
        self.setFollowers()

        # set info timer
        self.infoTimer = QtCore.QTime()
        self.infoTimer.start()
        # set update timer
        self.updateTimer = QtCore.QTimer()
        self.updateTimer.setInterval(16)
        self.updateTimer.timeout.connect(self.update)
        self.updateTimer.start()
        # set collision check timer
        self.collisionTimer = QtCore.QTimer()
        self.collisionTimer.setInterval(32)
        self.collisionTimer.timeout.connect(self.collision)
        self.collisionTimer.start()
        # set render timer
        self.renderTimer = QtCore.QTimer()
        self.renderTimer.setInterval(16)
        self.renderTimer.timeout.connect(self.updateGL)
        self.renderTimer.start()
Exemple #4
0
def main():
    tag = TagRecognition()
    bt = Bluetoothctl()
    BT_ADDR = "5C:BA:37:26:6D:9A"

    # If an ARTag is detected, the vehicle will become a follower.
    # If an ARTag is not detected, the vehicle will become a leader.
    if tag.detect():
        vehicle = Follower()
    else:
        if not is_controller_connected():
            # If a controller is not connected, remove it to avoid problems
            # connecting with it again.
            disconnect_and_remove_device(bt, BT_ADDR)
            bt.start_scan()

            while not is_controller_connected():
                bt.connect(BT_ADDR)
                sleep(Follower.CYCLE_TIME)

        vehicle = Leader()

    # This loop makes the vehicle move. If the vehicle sees an ARTag then
    # it is a follower vehicle, otherwise it is a leader vehicle.
    timer_set = False
    start_time = time.time()

    while True:
        tag_visible = tag.detect()
        if isinstance(vehicle, Leader):
            vehicle.lead()

            if tag_visible:
                while is_controller_connected():
                    bt.disconnect('5C:BA:37:26:6D:9A')
                    sleep(Follower.CYCLE_TIME)
                vehicle = Follower()
        else:
            vehicle.follow()
            if tag_visible:
                timer_set = False
            elif not timer_set:
                start_time = time.time()
                timer_set = True

            if (time.time() - start_time) > 5 and timer_set:
                timer_set = False

                disconnect_and_remove_device(bt,BT_ADDR)
                bt.start_scan()
                bt.connect('5C:BA:37:26:6D:9A')
                sleep(Follower.CYCLE_TIME)

                if is_controller_connected():
                    vehicle = Leader()
                else:
                    start_time = time.time()
                    timer_set = True
Exemple #5
0
    def on_vote_received(self, message):
        if message.sender not in self._votes:
            self._votes[message.sender] = message

            if (len(self._votes.keys()) > (self._server._total_nodes - 1) / 2):
                leader = Leader()
                leader.set_server(self._server)

                return leader, None
        return self, None
Exemple #6
0
    def at_vote_response_phase(self, message):
        if (message.sender not in self.votes):
            self.votes[message.sender] = message

            if(len(self.votes.keys()) > (self.node.total_nodes - 1) / 2):
                leader = Leader()
                leader.set_node(self.node)
                return leader, None

        return self, None
Exemple #7
0
  def run(self):
    initialconfig = Config([], [], [])
    c = 0

    for i in range(NREPLICAS):
      pid = "replica %d" % i
      Replica(self, pid, initialconfig)
      initialconfig.replicas.append(pid)
    for i in range(NACCEPTORS):
      pid = "acceptor %d.%d" % (c,i)
      Acceptor(self, pid)
      initialconfig.acceptors.append(pid)
    for i in range(NLEADERS):
      pid = "leader %d.%d" % (c,i)
      Leader(self, pid, initialconfig)
      initialconfig.leaders.append(pid)
    for i in range(NREQUESTS):
      pid = "client %d.%d" % (c,i)
      for r in initialconfig.replicas:
        cmd = Command(pid,0,"operation %d.%d" % (c,i))
        self.sendMessage(r,RequestMessage(pid,cmd))
        time.sleep(1)

    for c in range(1, NCONFIGS):
      # Create new configuration
      config = Config(initialconfig.replicas, [], [])
      for i in range(NACCEPTORS):
        pid = "acceptor %d.%d" % (c,i)
        Acceptor(self, pid)
        config.acceptors.append(pid)
      for i in range(NLEADERS):
        pid = "leader %d.%d" % (c,i)
        Leader(self, pid, config)
        config.leaders.append(pid)
      # Send reconfiguration request
      for r in config.replicas:
        pid = "master %d.%d" % (c,i)
        cmd = ReconfigCommand(pid,0,str(config))
        self.sendMessage(r, RequestMessage(pid, cmd))
        time.sleep(1)
      for i in range(WINDOW-1):
        pid = "master %d.%d" % (c,i)
        for r in config.replicas:
          cmd = Command(pid,0,"operation noop")
          self.sendMessage(r, RequestMessage(pid, cmd))
          time.sleep(1)
      for i in range(NREQUESTS):
        pid = "client %d.%d" % (c,i)
        for r in config.replicas:
          cmd = Command(pid,0,"operation %d.%d"%(c,i))
          self.sendMessage(r, RequestMessage(pid, cmd))
          time.sleep(1)
Exemple #8
0
    def on_vote_received(self, message):
        self._votes[message.sender] = message
        if len(self._votes.keys()) >= (self._server._total_nodes - 1) / 2:
            leader = Leader()
            leader.set_server(self._server)
            print "Server", self._server._name, "has been elected leader"
            self._server._serverState = leaderState
            for n in self._server._neighbors:
                if n._serverState != deadState:
                    n._serverState = followerState
                    n._state = Follower()
                    n._state.set_server(n)
            return leader, None

        return self, None
Exemple #9
0
    def run(self):
        initialconfig = Config([], [], [])
        c = 0

        # Create replicas
        for i in range(self.clusterSize):
            pid = "replica %d" % i
            Replica(self, pid, initialconfig)
            initialconfig.replicas.append(pid)
        # Create acceptors (initial configuration)
        for i in range(self.clusterSize):
            pid = "acceptor %d.%d" % (c, i)
            Acceptor(self, pid)
            initialconfig.acceptors.append(pid)
        # Create leaders (initial configuration)
        for i in range(self.clusterSize):
            pid = "leader %d.%d" % (c, i)
            Leader(self, pid, initialconfig)
            initialconfig.leaders.append(pid)

        self.start_time = time.time()

        for i in range(self.clientSize):
            self.p_list.append(
                mp.Process(target=self.sendRequest, args=(initialconfig, c)))
            self.p_list[i].start()

        for i in self.p_list:
            i.join()
 def handleResponseVote(self, server, vote):
     print("\tReceived RESPONSEVOTE from "+str(vote.sender).upper())
     self.votesReceived.append(vote.sender)
     if (len(self.votesReceived)+1 >=2):
         server.currentState = Leader()
         server.currentState.initiateLeader(server)
         print("\tI AM NOW LEADER")
Exemple #11
0
    def run(self):
        initialconfig = Config([], [], [])
        c = 0

        for i in range(NREPLICAS):
            pid = "replica %d" % i
            Replica(self, pid, initialconfig, self.conc_clients * NREQUESTS,
                    self.verbose)
            initialconfig.replicas.append(pid)
        for i in range(self.quorum_size):
            pid = "acceptor %d.%d" % (c, i)
            Acceptor(self, pid, self.verbose)
            initialconfig.acceptors.append(pid)
        for i in range(NLEADERS):
            pid = "leader %d.%d" % (c, i)
            Leader(self, pid, initialconfig, self.verbose)
            initialconfig.leaders.append(pid)
        for i in range(self.conc_clients):
            pid = f"client {c}.{i}"
            Client(self, pid, initialconfig.replicas, NREQUESTS, self.verbose)

        completed = False
        while not completed:
            completed = True
            for i in range(NREPLICAS):
                if self.procs[initialconfig.replicas[i]].difference is None:
                    completed = False
            time.sleep(1)
    def run(self):
        initialconfig = Config([], [], [])
        c = 0

        # Create replicas
        for i in range(self.clusterSize):
            pid = "replica %d" % i
            Replica(self, pid, initialconfig)
            initialconfig.replicas.append(pid)
        # Create acceptors (initial configuration)
        for i in range(self.clusterSize):
            pid = "acceptor %d.%d" % (c, i)
            Acceptor(self, pid)
            initialconfig.acceptors.append(pid)
        # Create leaders (initial configuration)
        for i in range(self.clusterSize):
            pid = "leader %d.%d" % (c, i)
            Leader(self, pid, initialconfig)
            initialconfig.leaders.append(pid)

        self.start_time = time.time()
        executor = ThreadPoolExecutor(max_workers=self.clientSize)

        executor.submit(self.sendRequest(initialconfig, c))

        self.sendRequest(initialconfig, c)
Exemple #13
0
def main(num_robots, width, height):
    print "Initializing..."
    #Create graphics window
    pygame.init()
    screen = pygame.display.set_mode((width, height), 0, 32)
    pygame.display.set_caption('Swarm Simulation')

    # walls = pygame.sprite.RenderUpdates()
    robots = pygame.sprite.RenderUpdates()
    clock = pygame.time.Clock()

    screen.fill((255, 255, 255))

    # w = Wall(100,300,200,20)
    # walls.add(w)
    # w = Wall(400,300,200,20)
    # walls.add(w)

    #Create Leader
    #Do this first, so leader has id=0
    leader = Leader(width / 2, height / 2)
    robots.add(leader)

    #Create robots
    for i in range(0, num_robots):
        r = Robot(width / 2 + random.uniform(-100, 100),
                  height / 2 + +random.uniform(-100, 100))
        robots.add(r)

    print "Starting Simulation"
    while (True):
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        for r in robots:
            r.calc_force(robots)

        # for w in walls:
        #     w.calc_forces(robots)

        #Cycle forward
        robots.update()

        #Clear screen
        screen.fill((255, 255, 255))
        #Redraw
        dirty = robots.draw(screen)
        #Refresh screen
        pygame.display.update()
        #draw walls
        # dirty = walls.draw(screen)
        # pygame.display.update()

        clock.tick(30)
Exemple #14
0
def run(args):
    rospy.init_node('formation')

    # Update control every 100 ms.
    rate_limiter = rospy.Rate(100)
    leader = Leader("tb3_0", rate_limiter)

    follower_1 = Follower("tb3_1",
                          desired_rel_pos=np.array([-0.5, 0.35, 0.0]),
                          rate_limiter=rate_limiter,
                          des_d=0.4,
                          des_psi=2 * np.pi / 3,
                          leader=leader,
                          laser_range=[np.pi, np.pi])
    follower_2 = Follower("tb3_2",
                          desired_rel_pos=np.array([-0.5, -0.35, 0.0]),
                          rate_limiter=rate_limiter,
                          des_d=0.4,
                          des_psi=4 * np.pi / 3,
                          leader=leader,
                          laser_range=[np.pi, np.pi])

    while not rospy.is_shutdown():
        if follower_1.ready and follower_2.ready:
            leader.update_velocities()
            leader.publish_leg()
            leader.slam.update()

        follower_1.formation_velocity()
        follower_2.formation_velocity()
        rate_limiter.sleep()
Exemple #15
0
def main():
    global incoming, incoming_lock, N, pid, port, root_port, send

    # Read global state.
    pid = int(sys.argv[1])
    N = int(sys.argv[2])
    port = int(sys.argv[3])

    # Start and configure debugger
    LOG.basicConfig(filename='LOG/%d.log' % pid, level=LOG.DEBUG)

    # Create the necessary classes.
    mhandler = MasterHandler(pid, address, port)
    handler = WorkerThread(address, root_port + pid)
    communicator = Communicator(incoming, incoming_lock, pid, send, mhandler)
    #LOG.debug('Handlers initiated')

    acceptors = [(i, 'acceptor') for i in xrange(N)]
    leaders = [(i, 'leader') for i in xrange(N)]
    replicas = [(i, 'replica') for i in xrange(N)]
    acceptor = Acceptor(communicator)
    my_dict = dict()
    replica = Replica(leaders, my_dict, communicator)
    leader = Leader(acceptors, replicas, communicator)

    acceptor.start()
    handler.start()
    mhandler.start()

    while not os.path.isfile('LOG/%d.log' % (N - 1)):
        time.sleep(0.1)

    leader.start()
    replica.start()

    LOG.debug('main() ends IDENTITY pid: %d, port: %d ' % (pid, port))
def decide_role(tag_data):
    """
    Creates a Leader or Follower object.

    :param tag_data: Return value of TagRecognition.detect().

    :return: If tag_data is None, the vehicle will become a Leader. Otherwise,
             it will become a Follower.
    :rtype: Leader or Follower
    """
    if tag_data:
        vehicle = Follower()
    else:
        vehicle = Leader()

    return vehicle
Exemple #17
0
    def __init__(self, starting_units=100, field_size=800, leaders=0):
        """
        """
        self.swarm = BoidSwarm(field_size+2*40, Boid.influence_range+5)  # /2
        self.field_size = field_size
        self.pad = 40  # use to keep boids inside the play field

        for _ in range(starting_units):
            b = Boid(random.uniform(100, 400),
                     random.uniform(100, 400))
            self.swarm.boids.append(b)

        for _ in range(leaders):
            leader = Leader(random.uniform(100, 400),
                            random.uniform(100, 400))
            self.swarm.boids.append(leader)

        self.swarm.rebuild()
        self._cumltime = 0  # calculation var
Exemple #18
0
 def setup(self):
   # Initiate system
   for i in range(self.NREPLICAS):
     pid = "replica %d" % i
     Replica(self, pid, self.conf)
     self.conf.replicas.append(pid)
   for i in range(self.NACCEPTORS):
     pid = "acceptor %d" % i
     Acceptor(self, pid)
     self.conf.acceptors.append(pid)
   for i in range(NLEADERS):
     pid = "leader %d" % i
     Leader(self, pid, self.conf)
     self.conf.leaders.append(pid)
   
   # Intiate clients
   for c in range(self.num_clients):
     pid = "client %d" % c
     Client(self, pid)
     self.conf.clients.append(pid)
Exemple #19
0
    def run(self):
        initialconfig = Config([], [], [])
        c = 0
        for i in range(self.cluster_size):
            pid = "acceptor %d.%d" % (c,i)
            Acceptor(self, pid)
            initialconfig.acceptors.append(pid)

        for i in range(NLEADERS):
            pid = "leader %d.%d" % (c,i)
            Leader(self, pid, initialconfig)
            initialconfig.leaders.append(pid)

        for i in range(NREPLICAS):
            pid = "replica %d" % i
            Replica(self, pid, initialconfig)
            initialconfig.replicas.append(pid)

        for i in range(self.number_clients):
            pid = "client %d.%d" % (c,i)
            Client(self, pid, initialconfig.replicas, NREQUESTS)

        done = False
        while not done:
            done = False
            for x in initialconfig.replicas:
                if self.procs[x].accepted - (NREQUESTS*self.number_clients) == 0:
                    time_end = time.perf_counter()
                    done = True
            time.sleep(1)

        #Timing variables
        start = self.procs[x].start_time
        acc = self.procs[x].accepted
        time_total = (time_end - start)
        per_second = int(acc/time_total)

        with open('data.txt', 'a') as outfile:
            outfile.write(str(per_second))
            outfile.write("\n")
Exemple #20
0
    def update(self, dt):
        """dt is in seconds"""

        avg_speed = 0.0

        for b in self.swarm.boids:
            close_boids = self.swarm.find_near(b.position.x, b.position.y, b.influence_range)
            b.interact(close_boids)
            b.update(dt)
            w = self.field_size
            p = self.pad
            b.borders(p, w-p, p, w-p)  # keep the boids inside the borders

            avg_speed += b.speed

        avg_speed = avg_speed / len(self.swarm.boids)

        leader = Leader(42, 42)
        print("%s -- %s" % (avg_speed, leader.speed))

        # rebuild the swarm once we've updated all the positions
        self.swarm.rebuild()
Exemple #21
0
 def test_turn_position_type_errro(self):
     leader = Leader(test_mode=True)
     self.assertEqual(None, leader.turn(None))
Exemple #22
0
 def test_set_speed_string_position(self):
     leader = Leader(test_mode=True)
     self.assertEqual(0, leader.set_speed("position"))
Exemple #23
0
import json
import os.path
from agent import Agent
from leader import Leader

if os.path.exists("./config/device.config"):
    config = open("./config/device.config", "r")
    content = json.load(config)
    node_info = content["node_info"]

    if node_info["role"] == "agent":
        agent = Agent(node_info)
    elif node_info["role"] == "leader" or node_info["role"] == "cloud_agent":
        leader = Leader(node_info)

    while True:
        pass
Exemple #24
0
    def run(self):
        initialconfig = Config([], [], [])
        c = 0

        # Create replicas
        for i in range(NREPLICAS):
            pid = "replica %d" % i
            Replica(self, pid, initialconfig)
            initialconfig.replicas.append(pid)
        # Create acceptors (initial configuration)
        for i in range(NACCEPTORS):
            pid = "acceptor %d.%d" % (c, i)
            Acceptor(self, pid)
            initialconfig.acceptors.append(pid)
        # Create leaders (initial configuration)
        for i in range(NLEADERS):
            pid = "leader %d.%d" % (c, i)
            Leader(self, pid, initialconfig)
            initialconfig.leaders.append(pid)
        # Send client requests to replicas
        for i in range(NREQUESTS):
            pid = "client %d.%d" % (c, i)
            for r in initialconfig.replicas:
                cmd = Command(pid, 0, "operation %d.%d" % (c, i))
                self.sendMessage(r, RequestMessage(pid, cmd))
                time.sleep(1)

        # Create new configurations. The configuration contains the
        # leaders and the acceptors (but not the replicas).
        for c in range(1, NCONFIGS):
            config = Config(initialconfig.replicas, [], [])
            # Create acceptors in the new configuration
            for i in range(NACCEPTORS):
                pid = "acceptor %d.%d" % (c, i)
                Acceptor(self, pid)
                config.acceptors.append(pid)
            # Create leaders in the new configuration
            for i in range(NLEADERS):
                pid = "leader %d.%d" % (c, i)
                Leader(self, pid, config)
                config.leaders.append(pid)
            # Send reconfiguration request
            for r in config.replicas:
                pid = "master %d.%d" % (c, i)
                cmd = ReconfigCommand(pid, 0, str(config))
                self.sendMessage(r, RequestMessage(pid, cmd))
                time.sleep(1)
            # Send WINDOW noops to speed up reconfiguration
            for i in range(WINDOW - 1):
                pid = "master %d.%d" % (c, i)
                for r in config.replicas:
                    cmd = Command(pid, 0, "operation noop")
                    self.sendMessage(r, RequestMessage(pid, cmd))
                    time.sleep(1)
            # Send client requests to replicas
            for i in range(NREQUESTS):
                pid = "client %d.%d" % (c, i)
                for r in config.replicas:
                    cmd = Command(pid, 0, "operation %d.%d" % (c, i))
                    self.sendMessage(r, RequestMessage(pid, cmd))
                    time.sleep(1)
Exemple #25
0
class GLWidget(QGLWidget):
    def __init__(self):
        super(GLWidget, self).__init__()
        self.xres = 1024
        self.yres = 768
        self.setMinimumSize(self.xres, self.yres)
        self.info = PInfo()
        self.globalParams = PGlobal()
        self.leaderParams = PLeader()
        self.followerParams = PFollower()
        self.leader = Leader(self.leaderParams, self.globalParams)

        self.grid = Grid()
        self.followers = []
        self.setFollowers()

        # set info timer
        self.infoTimer = QtCore.QTime()
        self.infoTimer.start()
        # set update timer
        self.updateTimer = QtCore.QTimer()
        self.updateTimer.setInterval(16)
        self.updateTimer.timeout.connect(self.update)
        self.updateTimer.start()
        # set collision check timer
        self.collisionTimer = QtCore.QTimer()
        self.collisionTimer.setInterval(32)
        self.collisionTimer.timeout.connect(self.collision)
        self.collisionTimer.start()
        # set render timer
        self.renderTimer = QtCore.QTimer()
        self.renderTimer.setInterval(16)
        self.renderTimer.timeout.connect(self.updateGL)
        self.renderTimer.start()

    def setFollowers(self):
        num = self.followerParams.num - len(self.followers)
        if num > 0:
            for i in range(0, num):
                self.followers.append(Follower(self.leader, self.followerParams,\
                                               self.globalParams, self.grid))
        elif num < 0:
            num *= -1
            for i in range(0, num):
                popd = self.followers.pop()
                self.grid.remove(popd, popd.loc.x, popd.loc.y)

    def update(self):
        self.setFollowers()
        self.leader.move()
        for i in self.followers:
            i.move()

    def collision(self):
        collisions = 0
        for i in self.followers:
            collisions += i.calcRepulsion(self.followers)
        self.info.collisionChecks = collisions

    def paintGL(self):
        self.info.computeTime.pop(0)
        compTime = self.infoTimer.elapsed() - self.info.lastFrame
        self.info.computeTime.append(compTime)
        glClear(GL_COLOR_BUFFER_BIT)
        glLoadIdentity()
        self.leader.render()
        for i in self.followers:
            i.render()
        curTime = self.infoTimer.elapsed()
        self.info.frameTime.pop(0)
        self.info.frameTime.append(curTime - self.info.lastFrame)
        self.info.lastFrame = curTime
        self.updateInfo()

    def updateInfo(self):
        print(
            "FPS: " +
            str(1 /
                (sum(self.info.frameTime) / 1000 / len(self.info.frameTime))))
        print("Collision checks: " + str(self.info.collisionChecks))
        print("RendToRend: " +
              str(sum(self.info.computeTime) / len(self.info.computeTime)) +
              'ms\n')

    def resizeGL(self, w, h):
        glMatrixMode(GL_PROJECTION)
        glOrtho(-w / h, w / h, -1, 1, -1.0, 1.0)
        glViewport(0, 0, w, h)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

    def initializeGL(self):
        glClearColor(0.0, 0.0, 0.0, 1.0)

    def keyPressEvent(self, event):
        # Handle keypresses for movement
        if event.key() == QtCore.Qt.Key_Space and not event.isAutoRepeat():
            self.leader.toggleControl()
        elif self.leader.isControlled():
            if event.key() == QtCore.Qt.Key_Left:
                self.leader.turn('L')
            elif event.key() == QtCore.Qt.Key_Right:
                self.leader.turn('R')

    def setLeaderTarget(self, target):
        # Calculate simulation coordinates from click and set leader target
        vecTarget = Vector2f(target.x(), target.y())
        vecTarget.x -= 16
        vecTarget.y = 768 - (vecTarget.y - 23)
        if vecTarget.x > 0 and vecTarget.x < 1024 and vecTarget.y > 0 and vecTarget.y < 768:
            self.leader.goTo(vecTarget)
Exemple #26
0
 def test_turn_position_zero(self):
     leader = Leader(test_mode=True)
     self.assertEqual(90, leader.turn(0.0))
Exemple #27
0
 def test_turn_position_below_lower_bound(self):
     leader = Leader(test_mode=True)
     self.assertEqual(45, leader.turn(-1.1))
Exemple #28
0
 def test_turn_position_value_error(self):
     leader = Leader(test_mode=True)
     self.assertEqual(None, leader.turn("position"))
def main():
    # init
    args = init_arg_parser()
    P.log_path = args.log_path
    P.op_num = args.op_num
    P.lock_type = C.LOCK_MAPPING[args.lock_type]
    P.consensus_type = C.CONSENSUS_MAPPING[args.consensus_type]
    P.follower_num = args.follower_num
    P.lock_key_num = args.lock_key_num
    F.check_path_validity()
    time_suffix = time.strftime('%y%m%d_%H%M%S')
    logger = init_logger(time_suffix=time_suffix)
    F.save_parameter(time_suffix=time_suffix)

    # init servers
    ports = F.rand_items_in_range(P.leader_num + P.follower_num, P.port_range)
    servers = []
    for i in range(P.leader_num + P.follower_num):
        if i == 0:
            leader = Leader(ports[i])
            servers.append(leader)
            threading.Thread(target=leader.init_server).start()
        else:
            follower = Follower(ports[i])
            leader.add_follower(follower)
            follower.add_leader(leader)
            servers.append(follower)
            threading.Thread(target=follower.init_server).start()

    # init clients
    time.sleep(0.1)
    clients = []
    for i in range(P.client_num):
        client = Client()
        client.add_corresponding_server(servers[i])
        clients.append(client)

    # client requests
    lock_keys = F.rand_items_in_range(P.lock_key_num, P.lock_key_range)
    thread_list = []
    for i in range(P.op_num):
        logger.info("Operation No.{}".format(i + 1))
        client = F.rand_item(clients)
        operation_code = F.rand_int(P.client_operation_range)
        operation_name = C.OPERATION_MAPPING[operation_code]
        func = getattr(client, operation_name)
        t = threading.Thread(target=func, args=(str(F.rand_item(lock_keys)),))
        thread_list.append(t)
        t.start()
        time.sleep(0.015)

    # join client requests
    for t in thread_list:
        t.join()

    # shut down servers
    time.sleep(0.1)
    for s in servers:
        logger.info('Shutting down server {}'.format(s.get_short_uuid()))
        client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client_socket.connect((s.ip, s.port))
        send_data = {'type': 'close'}
        encoded_send_data = json.dumps(send_data).encode('utf-8')
        client_socket.send(encoded_send_data)
        client_socket.close()

    # finish
    time.sleep(5)
    logger.info('All done!')
Exemple #30
0
 def test_turn_position_above_upper_bound(self):
     leader = Leader(test_mode=True)
     self.assertEqual(135, leader.turn(1.1))