Exemplo n.º 1
0
 def get_ready_commu(self, port, ip=None):
     """set the communicator and players"""
     if ip:
         self.communicator = commu.Communicator(self.root, port, ip)
         self.player = game.Game.PLAYER_TWO
     else:
         self.communicator = commu.Communicator(self.root, port)
         self.player = game.Game.PLAYER_ONE
     self.communicator.connect()
     self.communicator.bind_action_to_message(self.add_coin_image)
Exemplo n.º 2
0
 def __init__(self):
     self.mock = True
     self.comm = communicator.Communicator(self)
     self.data_sync = DataSync()
     self.id = ""
     self.name = ""
     self.wunder_key = ""
     self.operator = ""
     self.email = ""
     self.phone = ""
     self.location = ""
     self.longitude = ""
     self.latitude = ""
     self.twilio_acct_sid = ""
     self.twilio_auth_token = ""
     self.scheduler = None
     self.hostname = ""
     self.last_status = ""
     self.ifconn = InfluxDBClient("127.0.0.1", 8086, "root", "root")
     self.log = log.Log("smartmodule.log")
     self.rtc = rtc_interface.RTCInterface()
     self.rtc.power_on_rtc()
     self.launch_time = self.rtc.get_datetime()
     self.asset = Asset()
     self.asset.id = self.rtc.get_id()
     self.asset.context = self.rtc.get_context()
     self.asset.type = self.rtc.get_type()
     self.ai = asset_interface.AssetInterface(self.asset.type,
                                              self.rtc.mock)
     self.rtc.power_off_rtc()
 def __init__(self,
              ports: [int] = [],
              workers: str = [],
              program=-1,
              state=1,
              id: str = 'master'
              ):  # if program is -1 the program dosent distribute it
     self.coms = []
     port = ports
     print('master %s have been created' % id)
     print("")
     if len(port) != len(workers):
         raise ValueError(
             "the number of the ports does not equal the number of the workers"
         )
     for p in port:
         self.coms.append(communicator.Communicator(int(p), 'm'))
     self.id = id
     self.waitingForAnswer = []
     for w in workers:
         self.workersIds.append(w)
     for i in range(0, len(workers)):
         self.workersPort[self.workersIds[i]] = port[i]
         self.workersState[self.workersIds[i]] = 1
         self.waitingForAnswer.append(self.workersIds[i])
     self.program = program
     self.setMissions()
     self.answer = 0
     self.state = state
Exemplo n.º 4
0
 def __init__(self):
     self.mock = True
     self.comm = communicator.Communicator(self)
     self.data_sync = DataSync()
     self.id = ""
     self.name = ""
     self.wunder_key = ""
     self.operator = ""
     self.email = ""
     self.phone = ""
     self.location = ""
     self.longitude = ""
     self.latitude = ""
     self.scheduler = None
     self.hostname = socket.gethostname()
     self.last_status = ""
     self.ifconn = None
     self.rtc = rtc_interface.RTCInterface()
     self.rtc.power_on_rtc()
     self.launch_time = self.rtc.get_datetime()
     self.asset = Asset()
     self.asset.id = self.rtc.get_id()
     self.asset.context = self.rtc.get_context()
     self.asset.type = self.rtc.get_type()
     self.ai = asset_interface.AssetInterface(self.asset.type,
                                              self.rtc.mock)
     self.rtc.power_off_rtc()
Exemplo n.º 5
0
 def __init__(self, id: int, port: int = 9999, master: str = 'master'):
     print("worker %s have been creater with port %s" %
           (str(id), str(port)))
     self.com = communicator.Communicator(port, id, "worker")
     self.port = port
     self.id = id
     self.master = master
     self.curReciver = master
     self.state = 1
Exemplo n.º 6
0
 def setUp(self):
     if not hasattr(self, "random_seed"):
         random.seed()
         self.random_seed = True
     self.testport = random.randint(49152, 65535)
     self.communicator = communicator.Communicator(port=self.testport)
     self.params = configparse.ParameterDict()
     self.params.add_option('vision_controller', 'video_source_name',
                            'webcam')
     self.TestCommand = 'this is a command to start xterm'
Exemplo n.º 7
0
 def addWorker(self, id: int, port: int):
     """add a new worker to this current master"""
     idd = id
     if idd == -1 or idd in self.workersIds:
         for i in range(len(self.workersIds)):
             if i != self.workersIds[i]:
                 idd = i
         if idd == -1 or id in self.workersIds:
             idd = len(self.workersIds) + 1
         print("the id is not the original givven id, the new id is " + idd)
     self.workersIds.append(idd)
     self.workersPort[idd] = port
     self.coms.append(communicator.Communicator(port))
     print("new worker number: %s have been created" % (str(idd)))
Exemplo n.º 8
0
 def __init__(self, root, game, port, player_type, ai, ip=None):
     self.__root = root
     self.__game = game
     self.__ai = ai
     self.__canvas_board = None
     self.__homer = tk.PhotoImage(file="homer.gif")
     self.__marge = tk.PhotoImage(file="marge.gif")
     self.__illegal_move = tk.PhotoImage(file="illegal_move.gif")
     self.__homer_wins = tk.PhotoImage(file="homer_winner.gif")
     self.__marge_wins = tk.PhotoImage(file="marge_winner.gif")
     self.__draw = tk.PhotoImage(file="teko.gif")
     self.__background = tk.PhotoImage(file="sofa.gif")
     self.__game_is_over = False
     self.__player_type = None
     self.__set_player(ip)
     self.__communicator = communicator.Communicator(self.__root, port, ip)
     self.__communicator.connect()
     self.__communicator.bind_action_to_message(self.__response_to_message)
     self.__human_or_ai = player_type
     self.__current_player = Game.PLAYER_ONE
     self.__winner = False
Exemplo n.º 9
0
	def __init__(self,
		         master_addr,
		         neighbors = [],
		         activity_level = 0.5,
				 mainblock = None,
		         port_no):

		self.master_addr = master_addr
		self.neighbors = neighbors
		self.current_chain = None
		self.current_mining_block = None
		self.mainblock = mainblock
		self.activity_level = activity_level

		self.seen_hashes = defaultdict(int)       # Hash values encountered from the flooding network
		self.communicator = communicator.Communicator(("localhost", port_no))
		self.pending_tx = []
		self.pending_intershard_tx = []

		self.transactions_to_issue = []
		self.transaction_issue_freq = 1
		self.hash_rate = 100
Exemplo n.º 10
0
 def __init__(self):
     logging.getLogger(sm_logger).info("Smart Module Initializing.")
     self.comm = communicator.Communicator()
     self.data_sync = DataSync()
     self.comm.smart_module = self
     self.id = ""
     self.name = ""
     self.wunder_key = ""
     self.operator = ""
     self.email = ""
     self.phone = ""
     self.location = ""
     self.longitude = ""
     self.latitude = ""
     self.twilio_acct_sid = ""
     self.twilio_auth_token = ""
     self.launch_time = datetime.datetime.now()
     self.asset = Asset()
     self.scheduler = None
     self.hostname = ""
     logging.getLogger(sm_logger).info(
         "Smart Module initialization complete.")
Exemplo n.º 11
0
def build_full_policy_output(autnum,
                             aggregate,
                             ipv6=True,
                             output='screen',
                             black_list=set(),
                             policy_format="XML"):
    #
    # PreProcess section: Get own policy, parse and create necessary Data
    #                     Structures.
    #
    com = communicator.Communicator()
    pp = parsers.PolicyParser(autnum)

    pp.assign_content(com.get_policy_by_autnum(autnum))
    pp.read_policy()
    logging.debug("Expressions to resolve: "
                  "{}".format(pp.filter_expressions.number_of_filters()))
    if pp.filter_expressions.number_of_filters() < 1:
        print("No filter expressions found.")
        com.session.close()
        return None
    com.session.close()

    #
    # Process section: Resolve necessary filter_expressions into prefixes.
    #
    fr = resolvers.FilterResolver(pp.filter_expressions, ipv6, black_list)
    fr.resolve_filters()

    #
    # PostProcess section: Create and deliver the corresponding output.
    #
    if policy_format == "YAML":
        return _to_YAML(pp, aggregate, fr)

    else:
        return _to_XML(autnum, pp, aggregate, fr, output)
Exemplo n.º 12
0
def _subprocess_RS_resolving(RS_list):
    """Resolves the given RS_list recursively.

    This function is going to be spawned as a process that in turn spawns
    threads to handle the network IO.

    Parameters
    ----------
    RS_list : set
        The RSes to be resolved.

    Returns
    -------
    RS_directory : dict
        Contains information (children) for all the encountered RSes.
    """
    _subprocess_init()

    comm = communicator.Communicator()
    q = Queue()
    recursed_sets = dict.fromkeys(RS_list, '')
    recursed_sets_lock = Lock()
    RS_directory = dict()
    RS_directory_lock = Lock()

    def _threaded_resolve_set():
        """Get an RS from the queue, resolve it, update the shared resources
        with the results and repeat until signaled to stop.
        This function is going to be spawned as a thread.
        """
        while True:
            current_set = q.get()
            if current_set == 'KILL':
                q.task_done()
                break

            # Recursed RSes have also depth information.
            if type(current_set) is tuple:
                setname, depth = current_set[0], current_set[1]
            else:
                depth = 1
                setname = current_set

            RSes, routes = '', ''
            try:
                resp = comm.get_filter_set(setname)
                if resp is None:
                    raise LookupError
                RSes, routes = parsers.parse_RS_members(resp)

            except LookupError:
                logging.error("{}: {}: No Object found for {}"
                              .format(mp.current_process().name,
                                      threading.current_thread().name, setname))

            except Exception as e:
                logging.warning("{}: {}: Failed to resolve DB object {}. {}"
                                .format(mp.current_process().name,
                                        threading.current_thread().name,
                                        setname, e))

            logging.debug("{}: {}: ({})>Found {} RSes and {} routes in {}"
                          .format(mp.current_process().name,
                                  threading.current_thread().name, depth,
                                  len(RSes),
                                  len(routes['ipv4']) + len(routes['ipv6']),
                                  setname))

            # Enqueue the *new* RSes for resolving.
            for route_set in RSes:
                with recursed_sets_lock:
                    if recursed_sets.get(route_set) is None:
                        recursed_sets[route_set] = ''
                        q.put((route_set, depth + 1))

            # Record this RS' children.
            with RS_directory_lock:
                RS_directory[setname] = dict(sets=RSes, routes=routes)

            q.task_done()

    # Enqueue the RSes present in the filter for resolving.
    for route_set in RS_list:
        q.put(route_set)

    threads = [Thread(target=_threaded_resolve_set) for _ in xrange(threads_count)]
    for t in threads:
        t.start()
    q.join()

    # When the queue is consumed put poison pills in order to signal the
    # threads to stop.
    for _ in threads:
        q.put('KILL')
    for t in threads:
        t.join()
    q.join()

    return RS_directory
Exemplo n.º 13
0
frame = tk.Frame(win)
frame.pack(fill = tk.BOTH, expand = 1)
    
coreStatusLabels = {key: tk.StringVar() for key in FMT_GETSTATUS.keys()}
for sVar in coreStatusLabels.values():
    sVar.set("---")

    
strNewAvg = tk.StringVar()
strNewAvg.set("100")

boolAutoPoll = tk.BooleanVar()
boolAutoPoll.set(False)
             
c = com.Communicator(57600, "COM3", listener) 
c.open()

tk.Label(frame, text = "Center of Line").grid(column = 0, row = 1, sticky = "WE")
tk.Label(frame, textvariable = coreStatusLabels["centerOfLine"]).grid(column = 1, row = 1, sticky = "WE")
tk.Label(frame, text = "Desired Speed").grid(column = 0, row = 2, sticky = "WE")
tk.Label(frame, textvariable = coreStatusLabels["avgSpeed"]).grid(column = 1, row = 2, sticky = "WE")
tk.Label(frame, text = "Duty Cycle A").grid(column = 0, row = 3, sticky = "WE")
tk.Label(frame, textvariable = coreStatusLabels["valA"]).grid(column = 1, row = 3, sticky = "WE")
tk.Label(frame, text = "Target Speed A").grid(column = 0, row = 4, sticky = "WE")
tk.Label(frame, textvariable = coreStatusLabels["speedA"]).grid(column = 1, row = 4, sticky = "WE")
tk.Label(frame, text = "Real Speed A").grid(column = 0, row = 5, sticky = "WE")
tk.Label(frame, textvariable = coreStatusLabels["actualA"]).grid(column = 1, row = 5, sticky = "WE")
tk.Label(frame, text = "Duty Cycle B").grid(column = 0, row = 6, sticky = "WE")
tk.Label(frame, textvariable = coreStatusLabels["valB"]).grid(column = 1, row = 6, sticky = "WE")
tk.Label(frame, text = "Target Seped B").grid(column = 0, row = 7, sticky = "WE")
Exemplo n.º 14
0
def _subprocess_AS_resolving(ASN_batch, result_q):
    """Resolves the given ASN_batch and returns the results throught the
    result_q to the main process.

    This function is going to be spawned as a process that in turn spawns
    threads to handle the network IO.

    Parameters
    ----------
    ASN_batch : list
        The ASNs to be resolved.
    result_q : mp.queues.SimpleQueue
        The queue through which the resolving results are communicated back
        to the main process.
    """
    _subprocess_init()

    comm = communicator.Communicator()
    q = Queue()

    def _threaded_resolve_AS():
        """Get an ASN from the queue, resolve it, return its routes to the
        *main* process and repeat until signaled to stop.
        This function is going to be spawned as a thread.
        """
        while True:
            current_AS = q.get()
            if current_AS == 'KILL':
                q.task_done()
                break

            try:
                resp = comm.get_routes_by_autnum(current_AS, ipv6_enabled=True)
                if resp is None:
                    raise LookupError
                routes = parsers.parse_AS_routes(resp)
            except LookupError:
                logging.warning("{}: {}: No Object found for {}"
                                .format(mp.current_process().name,
                                        threading.current_thread().name,
                                        current_AS))
                routes = None
            except Exception as e:
                logging.error("{}: {}: Failed to resolve DB object {}. {}"
                              .format(mp.current_process().name,
                                      threading.current_thread().name,
                                      current_AS, e))
                routes = None
            result_q.put((current_AS, routes))
            q.task_done()

    # Put the ASNs in the queue to be consumed by the threads.
    for AS in ASN_batch:
        q.put(AS)

    threads = [Thread(target=_threaded_resolve_AS) for _ in xrange(threads_count)]
    for t in threads:
        t.start()
    q.join()

    # When the queue is consumed put poison pills in order to signal the
    # threads to stop.
    for _ in threads:
        q.put('KILL')
    for t in threads:
        t.join()
Exemplo n.º 15
0
#!/usr/bin/python

# Test script for receiving messages on a Pi using the Communicator object.

import communicator

RECV_PORT = 5005

comm = communicator.Communicator(5005)
comm.run()

while True:
    data = comm.recv_queue.get()
    print "Received data: %s" % data.data
Exemplo n.º 16
0
import imp
import multiprocessing
import time
import communicator
import csv
import os.path


def onmsg(obj):

    print "A program from " + obj["lang"] + " " + obj[
        "langversion"] + " on " + obj["os"] + " " + obj[
            "osversion"] + " connected"

    if (obj["senderimg"]):
        newimg = open("ReceivedImage.png", "wb")
        newimg.write(obj["senderimg"])
        print("An image was received and saved to: ReceivedImage.png")

    if (obj["msg"]):
        print("Received a message:")
        print(obj["msg"])


communicator = communicator.Communicator("youcanchangethis")

communicator.on("TestMessage", onmsg)
communicator.listen(1234)

input("Listening.. \n")
Exemplo n.º 17
0
        ax_ver = -joystick.get_axis(5)
        ax_hor = ax_hor * abs(ax_hor)
        ax_ver = ax_ver * abs(ax_ver)
        return int(45.0 * ax_hor), int(45.0 * ax_ver)
    else:
        return 0, 0


ser = serial.Serial(port=str(sys.argv[1]),
                    baudrate=115200,
                    parity=serial.PARITY_NONE,
                    stopbits=serial.STOPBITS_ONE,
                    bytesize=serial.EIGHTBITS,
                    timeout=0.1)

arduino_link = communicator.Communicator(ser, 255)

#message1 = MessageEncoder.changeStateMessage(0,-30,30,True)

pygame.init()

arduino_controller = command_controller.CommandController()

arduino_controller.setSpeedSource(joystickSpeed)
arduino_controller.setCameraAngeSource(joystickCamera)

while True:
    pygame.event.get()
    arduino_controller.update()
    arduino_link.runReceptionLoop()
    arduino_link.sendMessage(arduino_controller.encode_for_tx(True))
Exemplo n.º 18
0
import communicator


def l(data):
    print(data)


c = communicator.Communicator(38400, "COM3", l)