Exemplo n.º 1
0
    def broadcast(cls, message):
        """
        Broadcasts a dict-ified ROS message (message) to all sockets that care about that topic.
        The dict message should contain metadata about what topic it was
        being sent on: message["_topic_name"], message["_topic_type"].
        """

        try:
            if message[0] == ROSBoardSocketHandler.MSG_TOPICS:
                json_msg = json.dumps(message, separators=(',', ':'))
                for socket in cls.sockets:
                    if socket.ws_connection and not socket.ws_connection.is_closing():
                        socket.write_message(json_msg)
            elif message[0] == ROSBoardSocketHandler.MSG_MSG:
                topic_name = message[1]["_topic_name"]
                json_msg = None
                for socket in cls.sockets:
                    if topic_name not in socket.node.remote_subs:
                        continue
                    if socket.id not in socket.node.remote_subs[topic_name]:
                        continue
                    t = time.time()
                    if t - socket.last_data_times_by_topic.get(topic_name, 0.0) < \
                            socket.update_intervals_by_topic.get(topic_name) - 2e-4:
                        continue
                    if socket.ws_connection and not socket.ws_connection.is_closing():
                        if json_msg is None:
                            json_msg = json.dumps(message, separators=(',', ':'))
                        socket.write_message(json_msg)
                    socket.last_data_times_by_topic[topic_name] = t
        except Exception as e:
            print("Error sending message: %s" % str(e))
            traceback.print_exc()
Exemplo n.º 2
0
def run_race(racers, number_of_laps, socket):
    global FINISH_RACE
    if not FINISH_RACE:
        for racer in racers:
            if has_finished_lap(racer.track_number, racer.lap_times[-1]):
                racer.lap_times.append(time.time())
                print vars(racer)
                socket.write_message(vars(racer))
                check_for_race_completion(racers, number_of_laps, socket)
        threading.Timer(SENSOR_CHECK_FREQUENCY, run_race, [racers, number_of_laps, socket]).start()
Exemplo n.º 3
0
def check_for_race_completion(racers, number_of_laps, socket):
    global FINISH_RACE
    min_lap = number_of_laps + 1
    for racer in racers:
        print "lap times length is " + str(len(racer.lap_times))
        min_lap = min(min_lap, len(racer.lap_times))
    if min_lap > number_of_laps:
        if FINISH_RACE == False:
            print "Race complete!"
            socket.write_message("COMPLETE")
        FINISH_RACE = True
Exemplo n.º 4
0
    def send_pings(cls):
        """
        Send pings to all sockets. When pongs are received they will be used for measuring
        latency and clock differences.
        """

        for socket in cls.sockets:
            try:
                socket.last_ping_times[socket.ping_seq % 1024] = time.time() * 1000
                if socket.ws_connection and not socket.ws_connection.is_closing():
                    socket.write_message(json.dumps([ROSBoardSocketHandler.MSG_PING, {
                        ROSBoardSocketHandler.PING_SEQ: socket.ping_seq,
                    }], separators=(',', ':')))
                socket.ping_seq += 1
            except Exception as e:
                print("Error sending message: %s" % str(e))
Exemplo n.º 5
0
  def broadcastMessage(topic, msg):
    try:
      if not msg:
        return

      msgPOD = {}
      msgPOD['time'] = datetime.datetime.now().strftime("%I:%M:%S.%f %p on %B %d, %Y")
      msgPOD['topic'] = topic
      msgPOD['data'] = msg

      print "[WS] broadcast %s to %d client(s)" \
        % (topic,
           len(MyWebSocketHandler.clientConnections))
      for socket in MyWebSocketHandler.clientConnections:
        socket.write_message(json.dumps(msgPOD))
    except:
      return
Exemplo n.º 6
0
def SendCurrentState():

    global connections, colorBlue, colorRed, isGameStart, isGameReady

    for socket in connections:

        if isGameStart:

            if socket.state == 'playing':
                socket.write_message({
                    'state': 'playing',
                    'blue': colorBlue,
                    'red': colorRed,
                    'flag': True,
                    'secs': timer
                })

            else:
                socket.write_message({
                    'state': 'playing',
                    'flag': False,
                    'secs': timer
                })

        elif isGameReady:
            if socket.state == 'pending':
                socket.write_message({
                    'state': 'pending',
                    'flag': True,
                    'secs': timer
                })

            else:
                socket.write_message({
                    'state': 'pending',
                    'flag': False,
                    'secs': timer
                })

        else:
            socket.write_message({
                'state': 'waiting',
                'currentPlayer': queuedPlayer
            })
	def run(self, path, socket):
		index = 0
		while self._running:
			print "location of log file ", path
			fh = open(path, "r")
			dd = fh.readlines()
			data = dd[index:]
			index = len(dd)
			if index == 0:
				socket.write_message("--BLANK--")
				fh.close()
				break
			if len(data) != 0:
			  try:
			    while len(data[:5000]) >0:
			      socket.write_message("".join(data[:5000]))
			      data = data[5000:]
			      if 'END OF LOGS' in data[-1]:
			        break
			      else:
			        time.sleep(1)
			  except:
			    pass
			fh.close()
Exemplo n.º 8
0
def SeperateTeam():
    global connections

    sz = 0

    for socket in connections:
        if socket.state == 'pending':
            sz += 1
    sz = sz / 2
    cnt = 0

    for socket in connections:

        if not socket.state == 'pending':
            continue

        if cnt < sz:
            socket.color = RED
        else:
            socket.color = BLUE

        socket.write_message({'state': 'init', 'color': socket.color})

        cnt += 1