示例#1
0
    def __init__(self, uvc_id):
        super(Bridge, self).__init__()

        self.data_seq = 0
        self.note_seq = 0

        # init capture
        self.cap = uvc.Capture(uvc_id)
        logger.info('Initialised uvc device {}'.format(self.cap.name))

        # init pyre
        self.network = Pyre(socket.gethostname() + self.cap.name[-4:])
        self.network.join(GROUP)
        self.network.start()
        logger.info('Bridging under "{}"'.format(self.network.name()))

        # init sensor sockets
        ctx = zmq.Context()
        generic_url = 'tcp://*:*'
        public_ep = self.network.endpoint()
        self.note, self.note_url = self.bind(ctx, zmq.PUB, generic_url,
                                             public_ep)
        self.data, self.data_url = self.bind(ctx,
                                             zmq.PUB,
                                             generic_url,
                                             public_ep,
                                             set_hwm=1)
        self.cmd, self.cmd_url = self.bind(ctx, zmq.PULL, generic_url,
                                           public_ep)
    def network_thread(self, ctx, pipe):
        print("Network thread started..")
        n = Pyre(self.name)
        n.join("Car2X")
        n.start()

        node_socket = n.socket()

        poller = zmq.Poller()
        poller.register(pipe, zmq.POLLIN)
        poller.register(node_socket, zmq.POLLIN)

        while not self.stopped:
            items = dict(poller.poll(1000))
            
            if pipe in items and items[pipe] == zmq.POLLIN:
                # handle outgoing messages
                message = pipe.recv()
                n.shouts("Car2X", message.decode('utf-8'))
            elif node_socket in items:
                cmds = n.recv()

                msg_type = cmds.pop(0)
                msg_uuid = cmds.pop(0)
                msg_name = cmds.pop(0)
                if msg_type == "JOIN":
                    print("{} joined!".format(msg_name))
                elif msg_type == "EXIT":
                    print("{} left!".format(msg_name))
                elif msg_type == "SHOUT":
                    # handling incoming information
                    msg_channel = cmds.pop(0)
                    msg_str = cmds.pop(0)
                    self.process_data(msg_str)
        n.stop()
示例#3
0
def chat_task(ctx, pipe, ncmds):
    n = Pyre(ctx=ctx)
    n.join("CHAT")
    n.start()

    # wait for someone else to join the chat
    while not n.peer_groups():
        pass

    pipe.send('ready'.encode('utf-8'))
    cmds = 0
    t0 = time.time()

    poller = zmq.Poller()
    poller.register(pipe, zmq.POLLIN)
    poller.register(n.inbox, zmq.POLLIN)
    while (True):
        items = dict(poller.poll())
        if pipe in items and items[pipe] == zmq.POLLIN:
            message = pipe.recv()
            # message to quit
            if message.decode('utf-8') == "$$STOP":
                break
            n.shout("CHAT", message)
        if n.inbox in items and items[n.inbox] == zmq.POLLIN:
            n.recv()
            cmds += 1
            if cmds == ncmds:
                msg = 'Got %s msgs in %0.2f sec' % (cmds, time.time() - t0)
                pipe.send(msg.encode('utf-8'))
    n.stop()
示例#4
0
def chat_task(ctx, pipe):
    n = Pyre(ctx)
    n.join("CHAT")
    n.start()

    poller = zmq.Poller()
    poller.register(pipe, zmq.POLLIN)
    poller.register(n.inbox, zmq.POLLIN)
    while(True):
        items = dict(poller.poll())
        if pipe in items and items[pipe] == zmq.POLLIN:
            message = pipe.recv()
            # message to quit
            if message.decode('utf-8') == "$$STOP":
                break
            print("CHAT_TASK: %s" % message)
            n.shout("CHAT", message)
        if n.inbox in items and items[n.inbox] == zmq.POLLIN:
            cmds = n.recv()
            type = cmds.pop(0)
            print("NODE_MSG TYPE: %s" % type)
            print("NODE_MSG PEER: %s" % uuid.UUID(bytes=cmds.pop(0)))
            print("NODE_MSG NAME: %s" % cmds.pop(0))
            if type.decode('utf-8') == "SHOUT":
                print("NODE_MSG GROUP: %s" % cmds.pop(0))
            print("NODE_MSG CONT: %s" % cmds)
    n.stop()
示例#5
0
def peer(rolename, partnum):
    peername = "%s-%02d" % (rolename, partnum)
    portnum = 5670 + partnum  # fixme: risking collission!
    print(peername)
    ret = Pyre(peername)
    ret.set_port(bytes(str(portnum).encode("ascii")))
    ret.set_header("role", rolename)
    return ret
示例#6
0
 def open(self) -> None:
     """Create a new pyre instance and join untangled."""
     self.node = Pyre()
     self.node.start()
     self.node.join('untangled2018')
     # used to get our messages
     self.poller = zmq.Poller()
     self.poller.register(self.node.socket(), zmq.POLLIN)
示例#7
0
    def __init__(self):
        self.node = Pyre("GAME_NODE")
        self.node.set_header("HELLO", "ABC")
        self.node.start()
        self.node.join("world:position")
        self.node.join("world:combat")

        self.poller = zmq.Poller()
        self.poller.register(self.node.socket(), zmq.POLLIN)
示例#8
0
文件: network.py 项目: vedb/pyndsi
 def start(self):
     # Setup node
     logger.debug("Starting network...")
     self._pyre_node = Pyre(self._name)
     self._name = self._pyre_node.name()
     for header in self._headers:
         self._pyre_node.set_header(*header)
     self._pyre_node.join(self._group)
     self._pyre_node.start()
示例#9
0
        def setup_group_member():
            group_member = Pyre(self.name)
            # set headers
            for header in self.default_headers:
                group_member.set_header(*header)
            # join active group
            group_member.join(self.active_group)

            # start group_member
            group_member.start()
            return group_member
    def network_thread(self, ctx, pipe):
        print("Network thread started..")
        n = Pyre(self.name)
        n.join("Car2X")
        n.start()

        poller = zmq.Poller()
        poller.register(pipe, zmq.POLLIN)
        poller.register(n.inbox, zmq.POLLIN)

        # wait for others
        while not n.peer_groups():
            time.sleep(0.0001)
            pass

        pipe.send('$$ready'.encode('utf-8'))

        while not self.stopped:
            items = dict(poller.poll())

            if pipe in items and items[pipe] == zmq.POLLIN:
                # handle outgoing messages
                try:
                    message = pipe.recv()
                    if message.decode('utf-8') == "$$STOP":
                        break
                    n.shouts("Car2X", message.decode('utf-8'))
                except zmq.error.Again:
                    print("ERROR! Again #1")
            if n.inbox in items and items[n.inbox] == zmq.POLLIN:
                try:
                    cmds = n.recv()

                    msg_type = cmds.pop(0)
                    msg_uuid = cmds.pop(0)
                    msg_name = cmds.pop(0)
                    if msg_type == "JOIN":
                        print("{} joined!".format(msg_name))
                        # ADD CAR IF NOT CONTROL
                        if msg_name[0:1] != "$":
                            self.window.hosts.append(msg_name)
                    elif msg_type == "EXIT":
                        print("{} left!".format(msg_name))
                        # REMOVE CAR
                        if msg_name in self.window.hosts:
                            self.window.hosts.remove(msg_name)
                    elif msg_type == "SHOUT":
                        # handling incoming information
                        msg_channel = cmds.pop(0)
                        msg_str = cmds.pop(0)
                        self.process_data(msg_str, msg_name)
                except zmq.error.Again:
                    print("ERROR! Again #2")
        n.stop()
示例#11
0
    def discovery_task(self, ctx, pipe):
        self.log.debug("Pyre on iface : {}".format(self.iface))

        n = Pyre(self.groupName, sel_iface=self.iface)
        n.set_header("DISCOVERY_Header1", "DISCOVERY_HEADER")
        n.join(self.groupName)
        n.start()

        poller = zmq.Poller()
        poller.register(pipe, zmq.POLLIN)
        poller.register(n.inbox, zmq.POLLIN)

        while (True):
            items = dict(poller.poll())

            if pipe in items and items[pipe] == zmq.POLLIN:
                message = pipe.recv()
                # message to quit
                if message.decode('utf-8') == "$$STOP":
                    break

            if n.inbox in items and items[n.inbox] == zmq.POLLIN:
                cmds = n.recv()
                self.log.debug("NODE_MSG CONT:{}".format(cmds))

                msg_type = cmds.pop(0)
                peer_uuid_bytes = cmds.pop(0)
                peer_uuid = uuid.UUID(bytes=peer_uuid_bytes)

                self.log.debug("NODE_MSG TYPE: {}".format(msg_type))
                self.log.debug("NODE_MSG PEER: {}".format(peer_uuid))

                if msg_type.decode('utf-8') == "SHOUT":
                    group_name = cmds.pop(0)
                    self.log.debug("NODE_MSG GROUP: {}".format(group_name))

                    group_name_2 = cmds.pop(0)
                    self.log.debug("NODE_MSG GROUP_2: {}".format(group_name_2))

                    discoveryMsg = cmds.pop(0)
                    self.log.debug("Discovery Msg : {}".format(discoveryMsg))

                    controller = json.loads(discoveryMsg.decode('utf-8'))
                    self.controller_dl = str(controller["downlink"])
                    self.controller_ul = str(controller["uplink"])
                    self.log.debug("Discovered Controller DL-{}, UL-{}".format(
                        self.controller_dl, self.controller_ul))
                    self.send_event(
                        events.BrokerDiscoveredEvent(self.controller_dl,
                                                     self.controller_ul))

        n.stop()
示例#12
0
    def gaze_exchange_task(self, ctx, pipe):
        """
        Task for exchanging messages
        Args:
            ctx(zmq.Context): the zmq context
            pipe(zmq.PAIR pipe): the pipe for exchanging messages
        Returns: (zmq.PAIR pipe) the pipe
        """
        n = Pyre("GAZE_EXCHANGE")
        self.publisher_id = n.uuid()
        n.join(GROUP_GAZE_EXCHANGE)
        n.start()

        poller = zmq.Poller()
        # noinspection PyUnresolvedReferences
        poller.register(pipe, zmq.POLLIN)
        # noinspection PyUnresolvedReferences
        poller.register(n.socket(), zmq.POLLIN)
        while not self.stopped:
            items = dict(poller.poll())
            print(n.socket(), items)
            # noinspection PyUnresolvedReferences
            if pipe in items and items[pipe] == zmq.POLLIN:
                message = pipe.recv()
                # message to quit
                message = message.decode('utf-8')
                if message == STOP_MESSAGE:
                    break
                print("GAZE_EXCHANGE_TASK: {}".format(message))
                self.save_gaze_from_message(message)
                n.shouts(GROUP_GAZE_EXCHANGE, message)
            else:
                cmds = n.recv()
                msg_type = cmds.pop(0)
                print("NODE_MSG TYPE: %s" % msg_type)
                print("NODE_MSG PEER: %s" % uuid.UUID(bytes=cmds.pop(0)))
                print("NODE_MSG NAME: %s" % cmds.pop(0))
                if msg_type.decode('utf-8') == "SHOUT":
                    print("NODE_MSG GROUP: %s" % cmds.pop(0))
                    message = cmds.pop(0).decode("utf-8")
                    self.save_gaze_from_message(message)
                elif msg_type.decode('utf-8') == "ENTER":
                    headers = json.loads(cmds.pop(0).decode('utf-8'))
                    print("NODE_MSG HEADERS: %s" % headers)
                    for key in headers:
                        print("key = {0}, value = {1}".format(
                            key, headers[key]))
                print("NODE_MSG CONT: %s" % cmds)
        n.stop()
示例#13
0
    def __init__(self):
        self.node = Pyre("GAME_NODE")
        self.node.set_header("AUTHORITY", "FALSE")
        self.node.set_header("NAME", "")
        self.node.start()
        self.node.join("world:position")
        self.node.join("world:combat")
        self.node.join("ctf:teams")
        self.node.join("ctf:dropflag")
        self.node.join("ctf:gotflag")
        self.node.join("players:whois")
        self.node.join("player:name")

        self.poller = zmq.Poller()
        self.poller.register(self.node.socket(), zmq.POLLIN)
示例#14
0
    def restart_discovery(self, name):

        if self.discovery:
            if self.discovery.name() == name:
                return
            else:
                self.discovery.leave(self.sync_group)
                self.discovery.stop()
                self.leaderboard = []

        self.node_name = name or gethostname()
        self.discovery = Pyre(self.node_name)
        # Either joining network for the first time or rejoining the same group.
        self.discovery.join(self.sync_group)
        self.discovery.start()
        self.announce_clock_master_info()
示例#15
0
    def indicators_create(self, data, **kwargs):
        if isinstance(data, dict):
            data = Indicator(**data)

        if isinstance(data, Indicator):
            data = [data]

        n = Pyre()

        n.join(CHAN)
        n.start()
        sleep(1)

        for i in data:
            n.shouts(CHAN, str(i))

        n.stop()
示例#16
0
    def __init__(self, my_name, my_ip, group_name):

        self.name = my_name
        self.ip = my_ip
        self.group = group_name

        # node dict is of the format ip: name
        # This is because a user (name) may move to a new ip.
        # Duplicate ip's are not allowed, but more than 1 ip may share the 
        # same name. This is because a user may log in to multiple devices.
        # 
 
        self.node_dict = {}

        self.node = Pyre(self.group)
        self.node.set_header(self.name, self.ip)
        self.node.join(self.group)
        self.node.start()

        # this runs forever for testing, but should be run as a thread
        self._node_update_task()
示例#17
0
    def __init__(self, myname, port=None, prefix=None):
        # NOTE: Seems to be a bug in Pyre where you can't set the port.
        if port is not None:
            raise NotImplementedError(
                'There is a bug in Pyre that prevents setting of the discovery port. If you require multiple federations of Pyre components, use prefix instead of port in Transport constructor.'
            )

        # dict of remote name to callback. See subscribe method above.
        self._subscribers = {}

        # Callback for all message (or None if none registered)
        self._subscribe_all = None

        self._prefix = prefix

        # Attach the federation name as a prefix to both this channel
        # and the global channel. The global channel is currently
        # just used for QUIT messages.

        if prefix is not None:
            myname = prefix + myname
            self._globalchannel = prefix + "GLOBAL"
        else:
            self._globalchannel = "GLOBAL"

        self._pyre = Pyre(myname)
        if port is not None:
            self._pyre.set_port(port)

        self._pyre.join(myname)
        self._pyre.join(self._globalchannel)
        self._pyre.start()

        # Dict of (UUIDs => IP addresses) that have sent a valid ENTER message
        self._uuid2ip = {}

        self._run = True

        self._readthread = threading.Thread(target=self._readworker)
        self._readthread.start()
    def discovery_task(self, ctx, pipe):
        self.log.debug("Pyre on iface : {}".format(self.iface))
        n = Pyre(self.groupName, sel_iface=self.iface)
        n.set_header("DISCOVERY_Header1", "DISCOVERY_HEADER")
        n.join(self.groupName)
        n.start()

        poller = zmq.Poller()
        poller.register(pipe, zmq.POLLIN)

        while (True):
            items = dict(poller.poll())

            if pipe in items and items[pipe] == zmq.POLLIN:
                message = pipe.recv()
                # message to quit
                if message.decode('utf-8') == "$$STOP":
                    break

                n.shout(self.groupName, message)

        n.stop()
示例#19
0
    def __init__(self):
        self.node = Pyre("GAME_AUTH")
        self.node.set_header("AUTHORITY", "TRUE")
        self.node.start()
        self.node.join("world:position")
        self.node.join("ctf:teams")
        self.node.join("ctf:dropflag")
        self.node.join("ctf:gotflag")
        self.node.join("ctf:scores")
        self.node.join("ctf:status")

        self.poller = zmq.Poller()
        self.poller.register(self.node.socket(), zmq.POLLIN)

        self.players = AuthorityPlayerManager()

        self.teams = {"blue": [], "red": []}

        self.level = SaveLevel('./assets/maps/CAPFLAG MAP NAT')
        red_spawn_pos = self.level.get_place(Place.RED_SPAWN)
        blue_spawn_pos = self.level.get_place(Place.BLUE_SPAWN)

        self.flags = {
            "blue": {
                "x": blue_spawn_pos[0],
                "y": blue_spawn_pos[1],
                "owner": '',
            },
            "red": {
                "x": red_spawn_pos[0],
                "y": red_spawn_pos[1],
                "owner": '',
            }
        }

        self.scores = {"red": 0, "blue": 0}

        self.serve()
示例#20
0
def run_time_sync_master(group):

    pts_group = group + '-time_sync-v1'

    # the time source in the example is python time.time you can change this.
    # replace with an implementation that give your custom time in floating sec.
    clock_service = Clock_Sync_Master(time)

    # This example is a clock service only, not a clock follower.
    # Therefore the rank is designed to always trump all others.
    rank = 1000
    discovery = Pyre('pupil-helper-service')
    discovery.join(pts_group)
    discovery.start()
    logger.info('Joining "{}" group with rank {}'.format(pts_group, rank))

    def announce_clock_service_info():
        discovery.shout(
            pts_group,
            [repr(rank).encode(),
             repr(clock_service.port).encode()])

    try:
        for event in discovery.events():
            if event.type == 'JOIN' and event.group == pts_group:
                logger.info(
                    '"{}" joined "{}" group. Announcing service.'.format(
                        event.peer_name, pts_group))
                announce_clock_service_info()
    except KeyboardInterrupt:
        pass
    finally:
        logger.info('Leaving "{}" group'.format(pts_group))
        discovery.leave(pts_group)
        discovery.stop()
        clock_service.stop()
示例#21
0
 def __init__(self, name, ctx, group_name, cpu_clock_rate, experiment_name):
     self.lock = threading.Lock()
     self.cpu_clock_rate = cpu_clock_rate
     self.cpu_load = random.random()
     self.group_name = group_name
     self.routing_table = None
     self.name = name + str(os.getpid())
     self.tasks = Queue(-1)
     self.results = Queue(-1)
     self.exp_name = experiment_name
     self.task_duration_no_context = random.random()
     # compute duration using cpu load, etc
     self.task_duration_with_context = random.random()
     #self.weights = 'rnn-model-attention-weights.h5'
     #self.model = rnn_model()
     # self.model._make_predict_function()
     # self.model.load_weights(self.weights)
     self.agent = Pyre(
         name=self.name, ctx=ctx or zmq.Context.instance())
     try:
         self.agent.join(group_name)
         self.agent.start()
     except Exception as err:
         logger.error(f'>>> Cant start node: {err}', exc_info=True)
示例#22
0

def handle_msg(uuid,name,msg,node):
    print UUID(bytes=uuid),name,msg

if __name__ == '__main__':


    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger("pyre")
    logger.setLevel(logging.INFO)
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)

    ctx = zmq.Context()
    n = Pyre("Script")
    n.join('default group')
    n.start()

    poller = zmq.Poller()
    poller.register(n.socket(), zmq.POLLIN)
    try:
        while(True):
            items = dict(poller.poll(timeout=1000))
            if n.socket() in items and items[n.socket()] == zmq.POLLIN:
                cmds = n.recv()
                msg_type = cmds.pop(0)
                msg_type = msg_type.decode('utf-8')
                if msg_type == "SHOUT":
                    uuid,name,group,msg = cmds
                    handle_msg(uuid,name,msg,n)
示例#23
0
def chat_task(ctx,pipe):
	print("communication started")

	GROUPNAME = "Quizzzzz"
	StopCmnd = "$$quit"
	OPPONENT = "opponent"
	
	print("name: %s" %NAME)
	
	connected_players = 1
	
	# set up node for the user
	n = Pyre(GROUPNAME)
	n.set_header('Name', NAME)
	
	# join the groupchat
	n.join(GROUPNAME)
	#print("UUID %s" %n.uuid())
	 
				
	# start broadcasting signal 
	n.start()

	# set up poller
	poller = zmq.Poller()
	poller.register(pipe,zmq.POLLIN)
	poller.register(n.socket(),zmq.POLLIN)

	# looping constantly to recieve messages
	while True:
		items = dict(poller.poll())
		
		if pipe in items:
			message = pipe.recv()
			if message.decode('utf-8') == StopCmnd:
				break
			# uppercase letters for question to whole group
			elif message.decode('utf-8').isupper() == True: 
				print("Question is: %s" %message)
				n.shouts(GROUPNAME,"Question to group is: %s" %message.decode('utf-8'))
				answer = 0
			# lowercase to last person who asked question in the group
			elif message.decode('utf-8').islower()  == True:
				message = NAME + "'s answer is=" + message
				n.whisper(PEER,message)
			else:
				print("please don't mix up or lowercase or use not only numbers")
	
		else:
			msgrecv = n.recv()
			#print(msgrecv)
			msg_type = msgrecv.pop(0)
			msg_sender = uuid.UUID(bytes=msgrecv.pop(0))
			PEER = msg_sender
			msg_name = msgrecv.pop(0)

			if msg_type.decode('utf-8') == "ENTER":
				headers = json.loads(msgrecv.pop(0).decode('utf-8'))
				print("New player discovered in network")
				print("New player = %s " %headers.get("Name"))
			elif msg_type.decode('utf-8') == "JOIN":
				print("New player has joined the group")
				print("New player = %s" %headers.get("Name"))
				connected_players += 1
				print("#players = %s" %connected_players)
			elif msg_type.decode('utf-8') == "SHOUT":
				print(msgrecv.pop(1))
			elif msg_type.decode('utf-8') == "WHISPER":
				if msgrecv[0] == "You have to ask next question":
					print("You have to ask next question")
					n.shout(GROUPNAME, "%s is new quizmaster" %NAME)
					answer = 0
				else:
					print(msgrecv.pop(0))
					answer +=1
					if answer == connected_players -1: #choosing new quizmaster randomly
						players = n.peers()
						next_master = players.pop(random.randint(0,connected_players-2))
						n.whisper(next_master,"You have to ask next question")
			
	
	print("Left current game")	
	n.stop()
示例#24
0
    def thread_loop(self, context, pipe):
        n = Pyre(self.name)
        n.join(self.group)
        n.start()

        poller = zmq.Poller()
        poller.register(pipe, zmq.POLLIN)
        logger.debug(n.socket())
        poller.register(n.socket(), zmq.POLLIN)
        while (True):
            try:
                #this should not fail but it does sometimes. We need to clean this out.
                # I think we are not treating sockets correclty as they are not thread-save.
                items = dict(poller.poll())
            except zmq.ZMQError:
                logger.warning('Socket fail.')
            # print(n.socket(), items)
            if pipe in items and items[pipe] == zmq.POLLIN:
                message = pipe.recv()
                # message to quit
                if message.decode('utf-8') == "EXIT_THREAD":
                    break
                logger.debug("Emitting to '%s' to '%s' " %
                             (message, self.group))
                n.shouts(self.group, message)
            if n.socket() in items and items[n.socket()] == zmq.POLLIN:
                cmds = n.recv()
                msg_type = cmds.pop(0)
                msg_type = msg_type.decode('utf-8')
                if msg_type == "SHOUT":
                    uid, name, group, msg = cmds
                    logger.debug("'%s' shouts '%s'." % (name, msg))
                    self.handle_msg(name, msg)

                elif msg_type == "WHISPER":
                    pass
                    # uid,name,group,msg = cmds
                    # logger.debug("'%s' whispers '%s'."%(name,msg))
                    # self.handle_msg(name,msg)

                elif msg_type == "JOIN":
                    uid, name, group = cmds
                    if group == self.group:
                        self.group_members[uid] = name
                        self.update_gui()

                elif msg_type == "EXIT":
                    uid, name = cmds
                    try:
                        del self.group_members[uid]
                    except KeyError:
                        pass
                    else:
                        self.update_gui()

                # elif msg_type == "LEAVE":
                #     uid,name,group = cmds
                # elif msg_type == "ENTER":
                #     uid,name,headers,ip = cmds

        logger.debug('thread_loop closing.')
        self.thread_pipe = None
        n.stop()
示例#25
0
def chat_task(ctx, pipe):
    print("-----CAR PEER COMMUNICATION STARTED-----")
    print("Manufacturer: ", MANUFACTURER, " - Model: ", MODEL)

    connected_cars = 0

    #Set up node for the car
    n = Pyre("")
    n.set_header("manufacturer", MANUFACTURER)
    n.set_header("model", MODEL)

    #Join the group 'chat'
    n.join(GROUPNAME)

    #Start broadcasting node
    n.start()

    # Set up poller
    poller = zmq.Poller()
    poller.register(pipe, zmq.POLLIN)  #Local pipe (contains commands/messages we send through terminal)
    poller.register(n.socket(), zmq.POLLIN)


    # A while loop constantly polls for new items = PULL system
    while True:

        #Wait for new message to be polled. This function blocks until there is a new message
        items = dict(poller.poll())

        #This are messages from ourselves, that we want to shout on the network
        if pipe in items:
            message = pipe.recv()

            # User stopped car
            if message.decode('utf-8') == STOP_COMMAND:
                break

            print(">>>>>> Sending out shout: %s" % message)
            n.shouts(GROUPNAME, message.decode('utf-8'))

        # Received messages from system or messages from other peers
        else:
            cmds = n.recv()
            print("--------------------------------------------------------------------------------")
            #print(">>>>>>>RECEIVED MESSAGE: ", cmds)

            msg_type = cmds.pop(0)
            car_uuid = uuid.UUID(bytes=cmds.pop(0))
            msg_name = cmds.pop(0)

            if msg_type.decode('utf-8') == "ENTER":
                headers = json.loads(cmds.pop(0).decode('utf-8'))
                print(">>>> NEW CAR DISCOVERED IN NETWORK")
                print("---Manufacturer:", headers.get("manufacturer"), "--- Model:", headers.get("model"))

            elif msg_type.decode('utf-8') == "JOIN":
                print(">>>> NEW CAR JOINED GROUP <<", cmds.pop(0).decode('utf-8'),">>")
                connected_cars += 1

            elif msg_type.decode('utf-8') == "SHOUT":
                print(">>>> RECEIVED SHOUT IN %s" % cmds.pop(0))
                print("---Msg: %s" % cmds.pop(0))

            elif msg_type.decode('utf-8') == "EXIT":
                print(">>>> CAR LEFT NETWORK")
                connected_cars -= 1


            print("---Total connected cars: ", connected_cars)
            print("---Car_UUID: ", car_uuid)
            #print("---NODE_MSG REMAINING: %s" % cmds)


    print("-----CAR COMMUNICATION STOPPED-----")
    n.stop()
示例#26
0
def chat_task(ctx, pipe):
    print("Game started")
    print("Name: %s" % NAME)
    connected_players = 1
    network_players = 1
    leave_counter = 0

    #Set up node for the game
    n = Pyre("")
    n.set_header("header_name", NAME)

    #Join the group
    n.join(GROUPNAME)

    #Start broadcasting node
    n.start()

    # Set up poller
    poller = zmq.Poller()
    poller.register(
        pipe, zmq.POLLIN
    )  #Local pipe (contains commands/messages we send through terminal)
    poller.register(n.socket(), zmq.POLLIN)

    # A while loop constantly polls for new items = PULL system
    while True:

        #Wait for new message to be polled. This function blocks until there is a new message
        items = dict(poller.poll())

        #This are messages from ourselves
        if pipe in items:
            message_pipe = pipe.recv()
            if message_pipe.decode('utf-8') == STOP_COMMAND:
                break
            #check if the message is a number
            elif message_pipe.decode(
                    'utf-8').isdigit() == True and yourturn == True:
                #variable to keep the loop going until a correct number is given
                status = True
                #check which symbol you got assigned
                if playerX == True:
                    while status == True:
                        number = int(message_pipe.decode('utf-8'))
                        #check if the spot is free
                        if board[number] != "X" and board[number] != "O":
                            status = False
                            yourturn = False
                            print("New status board:")
                            board[number] = "X"
                            showboard()
                            #check for a winning combination
                            if checkall("X") == True:
                                print("You win!")
                                n.whisper(OPPONENT,
                                          str(number).encode('utf-8'))
                                break
                            #when there's no winning combination, it's the other player's turn
                            else:
                                print("Waiting for opponent's move...")
                            #let your opponent know which number you chose
                            n.whisper(OPPONENT, str(number).encode('utf-8'))
                        else:
                            print("Spot taken, try again")
                            message_pipe = pipe.recv()
                else:
                    while status == True:
                        number = int(message_pipe.decode('utf-8'))
                        if board[number] != "X" and board[number] != "O":
                            status = False
                            yourturn = False
                            print("New status board:")
                            board[number] = "O"
                            showboard()
                            if checkall("O") == True:
                                print("You win!")
                                n.whisper(OPPONENT,
                                          str(number).encode('utf-8'))
                                break
                            else:
                                print("Waiting for opponent's move...")
                            n.whisper(OPPONENT, str(number).encode('utf-8'))
                        else:
                            print("Spot taken, try again")
                            message_pipe = pipe.recv()
            elif message_pipe.decode(
                    'utf-8').isdigit() == True and yourturn == False:
                print("It's not your turn, wait for your opponent's move")
            #if the message isn't a number, it is send as a message to your opponent
            else:
                print("Sending message to opponent: %s" %
                      message_pipe.decode('utf-8'))
                n.whisper(OPPONENT, message_pipe)

        # Received messages from system or messages from other peers
        else:
            cmds = n.recv()
            #print(">>>>>>>RECEIVED MESSAGE: ", cmds)
            msg_type = cmds.pop(0)
            player_uuid = uuid.UUID(bytes=cmds.pop(0))
            #OPPONENT = player_uuid
            #print("player uuid: ", player_uuid)
            msg_name = cmds.pop(0)

            if msg_type.decode('utf-8') == "ENTER":
                headers = json.loads(cmds.pop(0).decode('utf-8'))
                network_players += 1
                if network_players == 2:
                    print(
                        "--------------------------------------------------------------------------------"
                    )
                    print("New player discovered in network")
                    print("Name:", headers.get("header_name"))
                    print(
                        "--------------------------------------------------------------------------------"
                    )
            elif msg_type.decode('utf-8') == "JOIN":
                connected_players += 1
                #check if there's stil room for a player
                if connected_players > 2:
                    leave = "No free spot left"
                    n.whisper(player_uuid, leave.encode('utf-8'))
                elif connected_players == 2:
                    print(
                        "--------------------------------------------------------------------------------"
                    )
                    print("%s joined group" % headers.get("header_name"),
                          cmds.pop(0).decode('utf-8'))
                    print(
                        "--------------------------------------------------------------------------------"
                    )
                    #if there are 2 players, you know your opponent:
                    OPPONENT = player_uuid
                    showboard()
                    #randomly choose if you want to start
                    assign = random.randint(0, 1)
                    if assign == 1:
                        player_start = True
                        n.whisper(OPPONENT, "$$Istart".encode('utf-8'))
                    else:
                        player_start = False
                        n.whisper(OPPONENT, "$$Ustart".encode('utf-8'))
            elif msg_type.decode('utf-8') == "WHISPER":
                message_opponent = cmds.pop(0).decode('utf-8')
                if message_opponent == "No free spot left":
                    leave_counter += 1
                    #if you get the message that you must leave from 2 other players, you are the third player
                    if leave_counter == 2:
                        print(message_opponent)
                        break
                #if the random generators both got a compatible result, the game can start
                elif message_opponent == "$$Istart" and player_start == False:
                    playerX = False
                    yourturn = False
                    print("You are symbol O")
                    print("You opponent may start, please wait...")
                elif message_opponent == "$$Ustart" and player_start == True:
                    playerX = True
                    yourturn = True
                    print("You are symbol X")
                    print("You may start")
                    print("Where do you want to place your X?")
                #when the results are incompatible: try again
                elif message_opponent == "$$Istart" and player_start == True:
                    assign = random.randint(0, 1)
                    if assign == 1:
                        player_start = True
                        n.whisper(OPPONENT, "$$Istart".encode('utf-8'))
                    else:
                        player_start = False
                        n.whisper(OPPONENT, "$$Ustart".encode('utf-8'))
                elif message_opponent == "$$Ustart" and player_start == False:
                    assign = random.randint(0, 1)
                    if assign == 1:
                        player_start = True
                        n.whisper(OPPONENT, "$$Istart".encode('utf-8'))
                    else:
                        player_start = False
                        n.whisper(OPPONENT, "$$Ustart".encode('utf-8'))
                #if you receive a number, this is your opponent's move
                elif message_opponent.isdigit() == True:
                    yourturn = True
                    print(
                        "--------------------------------------------------------------------------------"
                    )
                    print("Number opponent: ", message_opponent)
                    print("New status board:")
                    #check for a winning combination based on which player you are
                    if playerX == True:
                        board[int(message_opponent)] = "O"
                        showboard()
                        if checkall('O') == True:
                            print("You loose!")
                            break
                        #if your opponent didn't make a winning combination, it's your turn
                        else:
                            print("Your turn")
                            print("Where do you want to place your X?")
                    else:
                        board[int(message_opponent)] = "X"
                        showboard()
                        if checkall('X') == True:
                            print("You loose!")
                            break
                        else:
                            print("Your turn")
                            print("Where do you want to place your O?")
                #if you just received a message, print it
                else:
                    print("Opponent says: ", message_opponent)

            elif msg_type.decode('utf-8') == "EXIT":
                if connected_players == 2:
                    print("%s left network" % headers.get("header_name"))
                    connected_players -= 1
                    print("Total connected players: ", connected_players)
                leave_counter -= 1
    print("Game stopped")
    n.stop()
示例#27
0
Author: Mohammadali Varfan
Contact information: [email protected]
'''

import pyre
from pyre import Pyre

from pyre import zhelper
import zmq
import uuid
import logging
import sys
import json
import time

n = Pyre("sender_node")
n.join("CHAT")
n.start()

nodes_list = dict()

t = time.localtime()
current_time = str(t[0]) + "-" + str(t[1]) + "-" + str(t[2]) + "T" + str(
    t[3]) + ":" + str(t[4]) + ":" + str(t[5]) + "Z"

features_list = ['robotID', 'sensors', 'timestamp']
start_query_time = "2017-12-10 3:55:40"
end_query_time = "2017-12-10 11:25:40"

msg_data = {
    "header": {
def main(argv):

    #if six.PY3:
    #    sys.stderr.write('bridge_client.py currently only supports python2')
    #    sys.exit(1)

    parse_arguments(argv[1:])
    setup_logging()

    # If the user presses ctrl-C, exit cleanly.
    signal.signal(signal.SIGINT, lambda s, f: client_quit())

    # Create the bridge socket
    Global.bridgesocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    Global.bridgesocket.connect((Global.args.host, Global.args.port))

    # Create a pyre instance
    Global.pyre = Pyre()
    Global.pyre.start()

    # Create a poller object that tests if anything is available on
    # any of: 1) The local pyre channels, 2) The bridge socket, 3) stdin.

    poller = zmq.Poller()
    poller.register(Global.pyre.socket(), zmq.POLLIN)
    poller.register(Global.bridgesocket, zmq.POLLIN)
    poller.register(0, zmq.POLLIN)  # stdin

    logging.warning('Starting bridge client to server at %s:%d' %
                    (Global.args.host, Global.args.port))

    while True:
        items = dict(poller.poll())
        logging.debug('Got items =%s' % (items))

        if 0 in items:  # stdin
            # User typed 'quit'. Note: slightly different from
            # a quit message on the global channel in that this
            # doesn't cause remote to quit.
            message = input()
            if message == 'quit':
                client_quit()
            elif message == 'help':
                print(
                    'You can quit the bridge_client (but not the federation) by typing "quit".'
                )
            else:
                print('Unrecognized command %s' % (message))

        if Global.bridgesocket.fileno() in items:
            # Got a message from the remote.
            rec = server_recv()
            logging.debug('Got remote data %s' % (rec))
            if rec[0] == 'JOIN':
                channel = rec[1]
                # If we don't already have a proxy object, create one.
                if channel not in Global.proxies:
                    t = Transport.Transport(channel)
                    Global.pyre.join(channel)
                    Global.proxies[channel] = t
                    Global.proxy_uuids[t._pyre.uuid()] = t
                    logging.info('Creating bridge proxy %s' % (channel))
            elif rec[0] == 'LEAVE':
                # Don't actually know how to handle this.
                pass
            elif rec[0] == 'SHOUT':
                # Use the proxy object to relay the message.
                name = rec[1]
                channel = rec[2]
                message = rec[3]
                if Global.localchannelcount.get(channel, 0) > 0:
                    logging.debug('Bridge proxy shout %s %s %s' %
                                  (name, channel, message))
                    Global.proxies[name].send(channel, message)
            else:
                logging.warning('Unexpected msg %s from client.' % (rec))

        if Global.pyre.socket() in items:
            # Got a message on Pyre.
            event = Global.pyre.recv()
            logging.debug('Got local pyre event %s' % (event))
            eventtype = event[0].decode('utf-8')
            sid = uuid.UUID(bytes=event[1])
            name = event[2].decode('utf-8')

            # Ignore pyre events from proxies
            if sid in Global.proxy_uuids:
                logging.debug('Ignoring proxied pyre event')
                continue

            if eventtype == 'JOIN':
                channel = event[3].decode('utf-8')
                if Global.localchannelcount.get(channel, 0) == 0:
                    Global.pyre.join(channel)
                    Global.localchannelcount[channel] = 0
                    server_send(['JOIN', channel])
                    logging.debug('Bridge client joining local channel %s' %
                                  (channel))
                Global.localchannelcount[channel] += 1
            elif eventtype == 'LEAVE':
                channel = event[3].decode('utf-8')
                Global.localchannelcount[channel] -= 1
                if Global.localchannelcount[channel] == 0:
                    Global.pyre.leave(channel)
                    server_send(['LEAVE', channel])
                    logging.debug('Bridge client leaving channel %s' %
                                  (channel))
            elif eventtype == 'SHOUT':
                channel = event[3].decode('utf-8')

                # Quit if federation QUIT message received.
                if event[4] == u'QUIT':
                    logging.warning(
                        'Bridge client received a local QUIT message. Exiting.'
                    )
                    client_quit()
                # Since the server communicates with json, we
                # need to un-json the message (which server_send
                # will re-json). There's probably a more elegant way
                # to do this.
                if six.PY3:
                    decoded = event[4].decode('utf-8')
                    server_send(['SHOUT', name, channel, decoded])
                else:
                    message = json.loads(event[4].decode('utf-8'))
                    server_send(['SHOUT', name, channel, message])
示例#29
0
Author: Mohammadali Varfan
Contact information: [email protected]
'''

import pyre
from pyre import Pyre

from pyre import zhelper
import zmq
import uuid
import logging
import sys
import json

n = Pyre("receiver_node")
print('Join group [CHAT]')
n.join("CHAT")

print('node START')
n.start()

msg_data = {
    "header": {
        "type": "CMD",
        "version": "0.1.0",
        "metamodel": "ropod-msg-schema.json",
        "msg_id": "0d05d0bc-f1d2-4355-bd88-edf44e2475c8",
        "timestamp": "2017-11-11T11:11:00Z"
    },
    "payload": {
示例#30
0
    def thread_loop(self, context, pipe):
        n = Pyre(self.name)
        n.join(self.group)
        n.start()
        poller = zmq.Poller()
        poller.register(pipe, zmq.POLLIN)
        poller.register(n.socket(), zmq.POLLIN)

        front, back = zhelper.zcreate_pipe(context)
        poller.register(back, zmq.POLLIN)

        def wake_up():
            #on app close this timer calls a closed socket. We simply catch it here.

            try:
                front.send('wake_up')
            except Exception as e:
                logger.debug('Orphaned timer thread raised error: %s' % e)

        t = Timer(self.time_sync_announce_interval, wake_up)
        t.daemon = True
        t.start()

        while (True):
            try:
                #this should not fail but it does sometimes. We need to clean this out.
                # I think we are not treating sockets correclty as they are not thread-save.
                items = dict(poller.poll())
            except zmq.ZMQError:
                logger.warning('Socket fail.')
                continue

            if back in items and items[back] == zmq.POLLIN:
                back.recv()
                #timeout events are used for pupil sync.
                #annouce masterhood every interval time:
                if isinstance(self.time_sync_node, Clock_Sync_Master):
                    n.shouts(
                        self.group, SYNC_TIME_MASTER_ANNOUNCE +
                        "%s" % self.clock_master_worthiness() + msg_delimeter +
                        '%s' % self.time_sync_node.port)

                # synced slave: see if we should become master if we dont hear annoncement within time.
                elif isinstance(self.time_sync_node, Clock_Sync_Follower
                                ) and not self.time_sync_node.offset_remains:
                    if self.get_unadjusted_time(
                    ) - self.last_master_announce > self.time_sync_wait_interval_short:
                        self.time_sync_node.terminate()
                        self.time_sync_node = Clock_Sync_Master(
                            time_fn=self.get_time)
                        n.shouts(
                            self.group, SYNC_TIME_MASTER_ANNOUNCE +
                            "%s" % self.clock_master_worthiness() +
                            msg_delimeter + '%s' % self.time_sync_node.port)

                # unsynced slave or none should wait longer but eventually take over
                elif self.get_unadjusted_time(
                ) - self.last_master_announce > self.time_sync_wait_interval_long:
                    if self.time_sync_node:
                        self.time_sync_node.terminate()
                    self.time_sync_node = Clock_Sync_Master(
                        time_fn=self.get_time)
                    n.shouts(
                        self.group, SYNC_TIME_MASTER_ANNOUNCE +
                        "%s" % self.clock_master_worthiness() + msg_delimeter +
                        '%s' % self.time_sync_node.port)

                t = Timer(self.time_sync_announce_interval, wake_up)
                t.daemon = True
                t.start()

            if pipe in items and items[pipe] == zmq.POLLIN:
                message = pipe.recv()
                # message to quit
                if message.decode('utf-8') == exit_thread:
                    break
                else:
                    logger.debug("Shout '%s' to '%s' " % (message, self.group))
                    n.shouts(self.group, message)
            if n.socket() in items and items[n.socket()] == zmq.POLLIN:
                cmds = n.recv()
                msg_type = cmds.pop(0)
                msg_type = msg_type.decode('utf-8')
                if msg_type == "SHOUT":
                    uuid, name, group, msg = cmds
                    logger.debug("'%s' shouts '%s'." % (name, msg))
                    self._handle_msg(uuid, name, msg, n)

                elif msg_type == "WHISPER":
                    uuid, name, msg = cmds
                    logger.debug("'%s/' whispers '%s'." % (name, msg))
                    self._handle_msg_whisper(uuid, name, msg, n)

                elif msg_type == "JOIN":
                    uuid, name, group = cmds
                    if group == self.group:
                        self.group_members[uuid] = name
                        self.update_gui()

                elif msg_type == "EXIT":
                    uuid, name = cmds
                    try:
                        del self.group_members[uuid]
                    except KeyError:
                        pass
                    else:
                        self.update_gui()

                # elif msg_type == "LEAVE":
                #     uuid,name,group = cmds
                # elif msg_type == "ENTER":
                #     uuid,name,headers,ip = cmds
                #     logger.warning((uuid,'name',headers,ip))
            else:
                pass

        logger.debug('thread_loop closing.')

        self.thread_pipe = None
        n.stop()