Пример #1
0
class UIListener:
    def __init__(self, address, port, authkey):
        self.client = Client((address, port), authkey=authkey)

    def get_args(self, n):
        return [self.client.recv() if self.client.poll(0.5) else None for _ in range(n)]

    def listenloop(self):
        keepalive = True

        try:
            while keepalive:
                while self.client.poll():
                    data = self.client.recv()
                    print('{}: {}'.format('x64' if utils.is64bit() else 'x86', data))

                    if data == 'close':
                        keepalive = False
                    else:
                        func = _interface[data]
                        self.client.send(func(*self.get_args(func.__code__.co_argcount)))
                        print('{}: sent response to {}'.format('x64' if utils.is64bit() else 'x86', data))

                time.sleep(0.05)
        except EOFError or ConnectionError:
            pass

            self.client.close()
class LockOutputFrequency(ExternalParameterBase):

    className = "Digital Lock Output Frequency"
    _outputChannels = {"OutputFrequency": "MHz", "Harmonic": ""}

    def __init__(self, name, config, globalDict, instrument="localhost:16888"):
        logger = logging.getLogger(__name__)
        ExternalParameterBase.__init__(self, name, config, globalDict)
        logger.info( "trying to open '{0}'".format(instrument) )
        host, port = instrument.split(':')
        self.instrument = Client((host, int(port)), authkey=b"yb171")
        logger.info( "opened {0}".format(instrument) )
        self.setDefaults()
        self.initializeChannelsToExternals()
        
    def setValue(self, channel, v):
        self.instrument.send( ('set{0}'.format(channel), (v, ) ) )
        result = self.instrument.recv()
        if isinstance(result, Exception):
            raise result
        return result
        
    def getValue(self, channel):
        self.instrument.send( ('get{0}'.format(channel), tuple() ) )
        result = self.instrument.recv()
        if isinstance(result, Exception):
            raise result
        return result
        
    def close(self):
        del self.instrument
Пример #3
0
class ThreadedExponentClient(ExponentClient):
    def __init__(self, ip, port, password):
        super(ThreadedExponentClient, self).__init__(ip, port, password)

        self.conn = Client((self.ip, self.port))

    def _auth(self, password):
        self.conn.send(password)
        auth_value = self.conn.recv()

        if auth_value == 'AUTH':
            print("Authorized")
            return True
        else:
            raise RuntimeError("Invalid Password")
            return False

    def __del__(self):
        print("Entering del")
        if self.__dict__.get('conn') != None:
            self.conn.close()

    def send(self, value):
        self.conn.send(value)
        return self.conn.recv()
Пример #4
0
class Worker(object):

    def __init__(self, address, port, authkey=None):

        self.connection = Client((address, port), authkey=authkey)
        self.worker_id = self.connection.recv()

    def run(self):
        while True:

            task_data = self.connection.recv()
            if task_data is False:
                return

            result = self.do_task(task_data)
            self.connection.send((task_data, result))

    def log(self, *items):
        print "== Worker %s ==" % self.worker_id,
        for item in items:
            print item,
        print

    def do_task(self, data):
        raise NotImplementedError("A subclass must implement this.")
Пример #5
0
class bd_con(threading.Thread):
    def __init__(self, port, query):
        threading.Thread.__init__(self)
        self.threadLock = threading.Lock()
        self.query = query

        try:
            self.con = Client((host_server, port),
                              authkey=bytes('secret password', 'utf-8'))
        except:
            print("#---- Can't Establish a Connection ----")
            exit(0)

        if self.con.recv() != '1':
            print('#---- Error in Establishing a Connection ----')
            exit(0)

    def run(self):

        global rest
        __user__ = 'entidade'
        __pass__ = 'entidade12345'
        __query__ = self.query

        self.con.send(__user__ + "$" + __pass__ + "$" + __query__)

        if self.con.recv() != '1':
            print("#---- Can't Establish a Connection ----")

        res = self.con.recv()
        self.con.send(res)

        self.threadLock.acquire()
        rest = res.copy()
        self.threadLock.release()
def main():
    connection = Client(('localhost', 6060))
    with open(r'PATH/TO/list.txt', 'rb') as samples:
        for sample in samples:
            print("Sending sample " + sample.rstrip())
            connection.send(sample.rstrip())
            print connection.recv()
Пример #7
0
def triggerEvent(type, scheduleMethod, *args):
    """
    This function inserts an event into CHOTestMonkey
    """
    host = "localhost"
    port = 6000
    address = (host, port)
    conn = Client(address)
    request = []
    request.append(2)
    request.append(type)
    request.append(scheduleMethod)
    for arg in args:
        request.append(arg)
    conn.send(request)
    response = conn.recv()
    while response == 11:
        time.sleep(1)
        conn.send(request)
        response = conn.recv()
    if response == 10:
        print "Event inserted:", type, scheduleMethod, args
    elif response == 20:
        print "Unknown message to server"
    elif response == 21:
        print "Unknown event type to server"
    elif response == 22:
        print "Unknown schedule method to server"
    elif response == 23:
        print "Not enough argument"
    else:
        print "Unknown response from server:", response
    conn.close()
def triggerEvent( type, scheduleMethod, *args ):
    """
    This function inserts an event into CHOTestMonkey
    """
    host = "localhost"
    port = 6000
    address = ( host, port )
    conn = Client( address )
    request = []
    request.append( 1 )
    request.append( type )
    request.append( scheduleMethod )
    for arg in args:
        request.append( arg )
    conn.send( request )
    response = conn.recv()
    while response == 11:
        conn.close()
        time.sleep( 1 )
        conn = Client( address )
        conn.send( request )
        response = conn.recv()
    if response == 10:
        print "Event inserted:", type, scheduleMethod, args
    elif response == 20:
        print "Unknown message to server"
    elif response == 21:
        print "Unknown event type to server"
    elif response == 22:
        print "Unknown schedule method to server"
    elif response == 23:
        print "Not enough argument"
    else:
        print "Unknown response from server:", response
    conn.close()
Пример #9
0
class DBClient(object):
	def __init__(self, address=('localhost',6000), authkey='difficult password'):
		self.conn = Client(address, authkey=authkey)

	def get_batch(self, elements):
		self.conn.send(list(elements))
		to_ret = self.conn.recv()
		return to_ret

	def get(self, element):
		self.conn.send(element)
		to_ret = self.conn.recv()
		return to_ret

	def set(self, key, val):
		self.conn.send({key: val})

	def set_batch(self, key_val_dict):
		self.conn.send(key_val_dict)

	def __getitem__(self, key):
		return self.get(key)

	def __setitem__(self, key, val):
		self.set(key, val)
Пример #10
0
 def send_update(self, id, route):
     # TODO: Explore what is better, persistent client sockets or
     # new socket for each BGP update
     "Send this BGP route to participant id's controller"
     logger.debug("Sending a route update to participant " + str(id))
     conn = Client(tuple(self.participants[id].eh_socket), authkey=None)
     conn.send(json.dumps({'bgp': route}))
     conn.recv()
     conn.close()
Пример #11
0
 def send_update(self, id, route):
     # TODO: Explore what is better, persistent client sockets or
     # new socket for each BGP update
     "Send this BGP route to participant id's controller"
     logger.debug("Sending a route update to participant "+str(id))
     conn = Client(tuple(self.participants[id].eh_socket), authkey = None)
     conn.send(json.dumps({'bgp': route}))
     conn.recv()
     conn.close()
Пример #12
0
 def do_conn(self,line):
     global conn
     address = (params['SERVEUR'], params['PORT'])
     try:
         conn = Client(address, authkey=params['PASSWORD'])
         print "Connexion etablie"
     except:
         print "Erreur connexion"
     ## Reception de l'invite du serveur
     print conn.recv()
Пример #13
0
def ner_test():
    address = ('localhost', 6000)
    try:
        conn = Client(address, authkey=b'secret password')
        conn.send("$test$")
        conn.recv()
        conn.close()
        return True
    except ConnectionRefusedError:
        print("Please start the ner daemon service before proceeding")
        return False
Пример #14
0
class CliClient(cmd.Cmd):

    def __init__(self,address,id):
        self.id = id
        self.connection = Client(address, authkey='secret password')
        cmd.Cmd.__init__(self)

    def onecmd(self,line):
        self.connection.send(("creator",line))
        while self.connection.poll(0.1):
            print self.connection.recv()        
Пример #15
0
def send():
    address = ('localhost', 6000)
    conn = Client(address, authkey=b'PyToPyCom')
    conn.send(message)
    print(conn.recv())
    conn.send('ArdConState')
    print(conn.recv())
    conn.send('CommunicationState')
    print(conn.recv())
    conn.send('finstuffwhat')
    conn.close()
Пример #16
0
 def conn(self, serveur=None):
     address = (params['SERVEUR'], params['PORT'])
     print "Connecting : ", address
     print "Params = ", params
     try:
         conn = Client(address, authkey=params['PASSWORD'])
         print "Connexion etablie"
         ## Reception de l'invite du serveur
         print conn.recv()
         return conn
     except:
         print "Erreur connexion"
         return None
Пример #17
0
class ProcClient(threading.Thread):
    def __init__(self, addr, authkey):
        threading.Thread.__init__(self)
        self.bus = None
        self.addr = addr
        self.authkey = authkey
        self.conn = None
        self.running = False

        self.setDaemon(True)

    def run(self):
        self.conn = None
        for i in range(0, 3):
            self.bus.log("Starting process client connection to: %s:%d" % self.addr)
            try:
                self.conn = Client(self.addr, authkey=self.authkey)
                break
            except:
                self.bus.log("", traceback=True)
                time.sleep(10.0)

        if not self.conn:
            self.bus.log("Failed to connect to %s:%d" % self.addr)
            return

        self.running = True
        while self.running:
            try:
                if self.conn.poll(1.0):
                    print self.conn.recv()
            except IOError:
                self.stop()
                break

    def stop(self):
        if not self.running:
            return

        self.bus.log("Stopping process client connection")
        if self.conn:
            self.running = False
            self.conn.close()
            self.conn = None

    def send(self, data):
        self.conn.send(data)

    def recv(self):
        return self.conn.recv()
Пример #18
0
    def workerConnection(self, wid):
        """Thread with worker connection"""
        worker = self.workers[wid]
        self.called += 1
        if self.verboseLog:
            print "[INFO] Connecting to %s:%d..." % (worker.ipaddress, worker.port)
        #TODO make try except statement to catch unresponsive hosts
        address = (worker.ipaddress, worker.port)
        try:
            conn = Client(address, authkey=worker.password)
            worker.alive = True # Add a good flag
            
            # Connect and get ready token
            resp = conn.recv()
            
            if self.verboseLog:
                print resp[0]
        
            worker.corecount = resp[1]
            self.C.append(resp[1]) # Add the number of available cores to collection

            with open("job.tar.gz", 'rb') as f:
                conn.send_bytes(f.read())
            f.close()
        
            # PAUSE HERE and wait for all threads to return core number
            self.wait_for_core_count.wait()
        
            print "[INFO] %d Job files allocated to worker %s" % (len(worker.jobFiles), worker.ipaddress)
        
            rec = conn.recv()
            if self.verboseLog:
                print rec[0]

            conn.send([self.inputJob[0], {"input" : worker.jobFiles, "joboptions" : self.joboptions}])
 
            output = conn.recv()
            if output[0]:
                self.output.append(output[0]) #Write to stack of histograms
                self.success += 1
            else:
                print "[ERROR] Job failed at %s:%d" % address
                # TODO We should resubmit the jobs to another worker....
            conn.close()
            print "[INFO] Connection to %s closed." % worker.ipaddress

        except:
            print "[WARNING] Connection to %s:%d failed." % (address[0], address[1])#, sys.exc_info()[1][1])
        finally:
            self.alive -= 1
Пример #19
0
class GClient:
    '''
    Represents a game client that connects to the server.
    '''
    def __init__(self, ip='', port=6969):
        self.ip = ip
        self.port = port
        self.address = (self.ip, self.port)
        self.s = None

    def connect(self):
        '''
        Connects to the server and returns the id for the client.
        '''
        try:
            self.s = Client(self.address)

            return self.s.recv()

        except Exception as e:
            self.s.close()

    def send(self, to_send):
        '''
        Sends the object seralized by pickle.
        '''
        try:
            self.s.send(to_send)

        except Exception as e:
            self.s.close()

    def receive(self):
        '''
        Receives data sent by the server and returns it.
        '''
        try:
            return self.s.recv()
        except Exception as e:
            self.s.close()

    def update(self, to_send):
        '''
        Sends the object in the argument, and returns the reply from the server.
        '''
        self.send(to_send)
        return self.receive()

    def close(self):
        self.s.close()
def echo_client(addrsss):
    c = Client(addrsss, authkey=b'peekaboo')
    c.send('hello')
    data = c.recv()
    print(data)  # hello

    c.send(42)
    data = c.recv()
    print(data)  # 42

    c.send([1, 2, 3, 4])
    data = c.recv()
    print(data)  # [1, 2, 3, 4]

    pass
Пример #21
0
class player:
    def __init__(self, colaJugadas, colaTableros):
        self.con = Client(address=('localhost', 6000),
                          authkey='secret password')

        (self.color, (self.dim_i, self.dim_j)) = self.con.recv()
        self.tablero = [0] * (self.dim_i * self.dim_j)
        self.lista_mov = []
        self.colaJugadas = colaJugadas  #cola de jugadas desde el intefaz
        self.colaTableros = colaTableros  #cola de Tableros provenientes hacia el interfaz
        for i in range(self.dim_i * self.dim_j):
            self.lista_mov.append(i)

    def mover(self, k):
        print 'muev'
        self.con.send((self.color, (k)))
        print 'mover env'
        a = self.con.recv()
        if a[0] == 2:  #espera
            a = self.con.recv()
        return a

    def gana(self):
        adversario = 1 - self.color
        R = len(filter(lambda x: x == self.color, self.tablero)) - len(
            filter(lambda x: x == adversario, self.tablero))
        return R

    def termina(self):
        self.con.send('q')
        #self.colaTableros.put((self.tablero[:],1))
    def juega(self):
        print 'a'
        jugadas = (self.lista_mov[:])
        shuffle(jugadas)
        cont = 0
        #el protocolo dice que un juego termina con el comando 3
        while cont != 3:
            m = self.colaJugadas.get()
            print 'm', m

            print m
            (cont, _, _, self.tablero) = self.mover(m)
            print 'cont', cont
            self.colaTableros.put((self.tablero[:], 0))
            sleep(1.0)
        self.colaTableros.put((self.tablero[:], 1))
        self.termina()
Пример #22
0
class ConnectClient():
    address = None
    conn = None
    
    def __init__(self, ip = 'localhost', port = 7000):
        self.address = (ip, port)
        self.conn = Client(self.address)

    def __del__(self):
        self.conn.close()
    
    def register_module(self, process_file):
        """send and register a module in the server"""
        f = open(process_file, "rb")
        l = f.read()
        self.conn.send([0, l])
        f.close()

    def request_process(self, args):
        """request the server to do a process previously sent in a module"""
        self.conn.send([1, args[0]] + args[1:])
        answer = self.conn.recv()
        if isinstance(answer, Exception):
            raise answer
        return answer
Пример #23
0
def parse_frame_list(video_id, begin, end, fps):
    global local_address_d
    conn = Client(local_address_d, authkey="localData")
    conn.send([video_id, begin, end, fps])
    framelist = conn.recv()
    conn.close()
    return framelist
Пример #24
0
class Runner:
    data_: Any
    models_: List[Model]
    address_: Tuple[str, int]
    client_: Optional[Connection]

    def __init__(self, data, models, address):
        self.data_ = data
        self.models_ = models
        self.address_ = address
        self.client_ = None

    def __enter__(self):
        self.client_ = Client(self.address_)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.client_.close()

    def __call__(self):
        while True:
            data = self.client_.recv()
            if data is None:
                break
            model, parameters = data
            result = self.models_[model].create(parameters)(self.data_)
            self.client_.send((
                model,
                parameters,
                result,
            ))
Пример #25
0
def broadcast_mic_data():
    # get the latest data from the audio server
    parameters = {
        "upper_limit": UPPER_LIMIT,
        "noise_threshold": NOISE_THRESHOLD,
        "min_quiet_time": MIN_QUIET_TIME,
        "min_noise_time": MIN_NOISE_TIME
    }
    try:
        conn = Client(AUDIO_SERVER_ADDRESS)
        conn.send(parameters)
        results = conn.recv()
        conn.close()
        # send results to all clients
        now = datetime.now()
        results['date_current'] = '{dt:%A} {dt:%B} {dt.day}, {dt.year}'.format(
            dt=now)
        results['time_current'] = now.strftime("%I:%M:%S %p").lstrip('0')
        results['audio_plot'] = results['audio_plot'].tolist()
    except:
        for c in clients:
            c.close()

    for c in clients:
        c.write_message(results)
Пример #26
0
def client_socket(screen):
    curses.curs_set(0)
    ip = insert_IP(screen)
    host_port = 8080

    # Setup socket and connect to host
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket = Client((ip, host_port))

    screen.addstr(f"\t2. Waiting for host to start the game..\n\n")
    screen.refresh()

    # Listen for verification message from host
    host_msg = client_socket.recv()
    screen.addstr(host_msg)
    screen.refresh()
    screen.clear()
    screen.refresh()

    # Start the online Game
    game = ClientGame(screen, client_socket)
    game.game_loop()  # Loops until a player presses Q to quit the game session

    # One of the players has ended the online game session
    client_socket.close()
 def process_data2(self, q):
     conn = Client(address, authkey="secret password")
     message = ""
     while True:
         message = conn.recv()
         # print "received", message[0],message[1]
         q.put(message)
Пример #28
0
 def POST(self):
     c = Client(('localhost', 5000))
     data = web.input(test="default")
     print data.priority + data.source + data.destination
     c.send((data.priority, data.source, data.destination))
     print('Got:', c.recv())
     return "success"
Пример #29
0
def parse_to_modelManagement(task, frame, nickname):
    global local_address_m
    conn = Client(local_address_m, authkey = 'localModel')
    conn.send([task, frame, nickname])
    results = conn.recv()
    conn.close()
    return results
Пример #30
0
class mp_client_class:


	def __init__(self, socket_path, authkey):

		# Start new client on top of socket
		self.client = Client(socket_path, authkey = authkey.encode('utf-8'))


	def __getattr__(self, name):

		# Handler routine in __getattr__ namespace
		def do_rpc(*args, **kwargs):

			# Send request to server
			self.client.send((name, args, kwargs))
			# Receive answer
			result = self.client.recv()

			# If the answer is an error, raise it
			if isinstance(result, Exception):
				raise result

			# Return answer
			return result

		# Return pointer to handler routine
		return do_rpc
Пример #31
0
        def call(*args, **kwargs):
            global _recursive_conn_lock
            if _recursive_conn_lock:
                raise AssertionError, 'BUG: Recursive client connection'
                # Avoid hanging because we call the socket while the
                # server is blocking for our return value on the pipe.
                # If this is an issue blocking functionality,
                # re-route the call to the open pipe for which the
                # server is waiting.

            #~ if self._client_proxy_authkey is None:
                #~ self._client_proxy_authkey = AUTHKEY_FILE.raw()

            msg = RemoteMethodCall(self._obj, name, args, kwargs)
            logger.debug('Remote call from %i: %s', os.getpid(), msg)
            #~ print "CLIENT >>%s<<" % self._client_proxy_authkey
            #~ conn = Client(SERVER_ADDRESS, authkey=self._client_proxy_authkey)
            conn = Client(SERVER_ADDRESS, SERVER_ADDRESS_FAMILY)
            conn.send(msg)
            if not msg.async:
                re = conn.recv()
                logger.debug('Remote call returned to %i: %s', os.getpid(), re)
                if isinstance(re, Exception):
                    raise re
                else:
                    return re
Пример #32
0
class RpcClient:
    def __init__(self, host: str = "localhost", port: int = 17000, authkey: bytes = b"keykey"):
        self._connection = None

        self.host = host
        self.port = port
        self.authkey = authkey

    def connect(self):
        try:
            self._connection = Client(address=(self.host, self.port), authkey=self.authkey)
            rep = self.connect_test()
            print(rep)
        except:
            if self._connection:
                self.close()
            traceback.print_exc()

    def close(self):
        self._connection.close()
        print("连接关闭")

    def __getattr__(self, name):
        def do_rpc(*args, **kwargs):
            self._connection.send(json.dumps((name, args, kwargs)))
            rep = json.loads(self._connection.recv())

            if rep[0]:
                return rep[1]
            else:
                self.close()
                raise RemoteException(rep[1])

        return do_rpc
Пример #33
0
class RemoteRequestor(object):
    def __init__(self, host, port, authkey):
        address = (host, port)
        self.conn = None
        self.retries = 0
        while self.conn is None and self.retries < 8:
            try:
                self.conn = Client(address)
            except ConnectionRefusedError as e:
                self.retries = self.retries + 1

    def execute(self, cmd):
        caller = getframeinfo(stack()[2][0])
        lineno = caller.lineno
        cmd.insert(0, lineno)
        try:
            self.conn.send(cmd)
            reply = self.conn.recv()
        except BaseException as e:
            reply = None
        return reply

    def close(self):
        try:
            self.conn.close()
        except BaseException as e:
            pass
Пример #34
0
def serverrun_single(problem_id, code, input_data, output_data):
    import acwingcli.config as config
    url = config.problem_cache[eval(problem_id)]['link']
    address = ('localhost', 6001)
    conn = Client(address, authkey=b'1234')
    local_server_message = {
        'activity': 'run',
        'url': url,
        'code': code,
        'input_data': input_data
    }
    conn.send(json.dumps(local_server_message))
    while True:
        early_exit = False
        if conn.poll(20) == True:
            response = json.loads(conn.recv())
            if 'local_debug_message' in response.keys():
                display_debug_message(response)
            elif 'status' in response.keys():
                early_exit = display_run_status(response, problem_id,
                                                input_data, output_data)
        else:
            sys.stdout.write(Fore.GREEN + Style.BRIGHT + 'TIME OUT' +
                             Style.RESET_ALL)
            sys.stdout.flush()
        if early_exit == True:
            break
    conn.close()
Пример #35
0
class ExabgpHook():
    def __init__(self, sock_path):
        self.conn = None
        self.sock_path = os.environ.get('FBGP_EXABGP_SOCK',
                                        '/var/log/fbgp/exabgp_hook.sock')
        self.running = False

    def run_forever(self):
        self.conn = Client(self.sock_path, 'AF_UNIX')
        self.running = True
        eventlet.spawn(self.recv_from_fbgp_loop)
        self.recv_from_exabgp_loop()

    def recv_from_exabgp_loop(self):
        while self.running:
            line = stdin.readline().strip()
            self.conn.send(line)
            # have no idea why the below line is important,
            # without it no data is received from conn
            time.sleep(0)

    def recv_from_fbgp_loop(self):
        while self.running:
            try:
                data = self.conn.recv()
                stdout.write(data + '\n')
                stdout.flush()
            except:
                self.conn.close()
                break
Пример #36
0
def shutdown_server():
    try:
        address = ('localhost', 6001)
        conn = Client(address, authkey=b'1234')
        local_server_message = {'activity': 'stopserver'}
        conn.send(json.dumps(local_server_message))
        while True:
            early_exit = False
            if conn.poll(20) == True:
                cmdwrite.client_debug(
                    'shutdown message sent, waiting for response')
                response = json.loads(conn.recv())
                if 'local_debug_message' in response.keys():
                    display_debug_message(response)
                    if (response['local_debug_message'] == 'close'):
                        early_exit = True
                        cmdwrite.client_debug(
                            'server shutdown confirmation received')
                if early_exit == True:
                    break
            else:
                cmdwrite.client_debug(
                    'no server shutdown confirmation received, exit')
                break
    except ConnectionRefusedError:
        cmdwrite.client_debug('no server connection, exit')
    except EOFError:
        cmdwrite.client_debug('no server connection, exit')
Пример #37
0
def get_json():
    #Get the current values
    c = Client(('localhost', 25000))
    c.send("get")
    now = c.recv()

    #Now we parse all the data out of the results!
    data = {}
    data["IN_Temp"] = now.In_Temp
    data["IN_Humid"] = now.In_Humid
    data["OUT_Temp"] = now.Out_Temp
    data["OUT_Humid"] = now.Out_Humid
    data["Out_Wind_Now"] = now.Out_Wind_Now
    data["OUT_Wind_Avg"] = now.Out_Wind_Avg
    data["OUT_Wind_Max"] = now.Out_Wind_Max
    data["OUT_Rain_Today"] = now.Out_Rain_Today
    data["OUT_Rain_Last_24h"] = now.Out_Rain_Last_24h
    data["OUT_Rain_Since_Reset"] = now.Out_Rain_Since_Reset
    data["ATTIC_Temp"] = now.Attic_Temp
    data["ATTIC_Humid"] = now.Attic_Humid
    data["NOW_URL"] = now.Now_URL
    data["NOW_Feel"] = now.Now_Feel
    data["NOW_Feel_High"] = now.Now_Feel_High
    data["NOW_Feel_Low"] = now.NOW_Feel_Low
    data["SYSTEM_CPU"] = now.System_CPU
    data["SYSTEM_RAM"] = now.System_RAM

    #Now return the json as a string
    return json.dumps(data)
Пример #38
0
		def call(*args, **kwargs):
			global _recursive_conn_lock
			if _recursive_conn_lock:
				raise AssertionError, 'BUG: Recursive client connection'
				# Avoid hanging because we call the socket while the
				# server is blocking for our return value on the pipe.
				# If this is an issue blocking functionality,
				# re-route the call to the open pipe for which the
				# server is waiting.

			#~ if self._client_proxy_authkey is None:
				#~ self._client_proxy_authkey = AUTHKEY_FILE.raw()

			msg = RemoteMethodCall(self._obj, name, args, kwargs)
			logger.debug('Remote call from %i: %s', os.getpid(), msg)
			#~ print "CLIENT >>%s<<" % self._client_proxy_authkey
			#~ conn = Client(SERVER_ADDRESS, authkey=self._client_proxy_authkey)
			conn = Client(SERVER_ADDRESS, SERVER_ADDRESS_FAMILY)
			conn.send(msg)
			if not msg.async:
				re = conn.recv()
				logger.debug('Remote call returned to %i: %s', os.getpid(), re)
				if isinstance(re, Exception):
					raise re
				else:
					return re
Пример #39
0
def get_json():
    # Get the current values
    c = Client(("localhost", 25000))
    c.send("get")
    now = c.recv()

    # Now we parse all the data out of the results!
    data = {}
    data["IN_Temp"] = now.In_Temp
    data["IN_Humid"] = now.In_Humid
    data["OUT_Temp"] = now.Out_Temp
    data["OUT_Humid"] = now.Out_Humid
    data["Out_Wind_Now"] = now.Out_Wind_Now
    data["OUT_Wind_Avg"] = now.Out_Wind_Avg
    data["OUT_Wind_Max"] = now.Out_Wind_Max
    data["OUT_Rain_Today"] = now.Out_Rain_Today
    data["OUT_Rain_Last_24h"] = now.Out_Rain_Last_24h
    data["OUT_Rain_Since_Reset"] = now.Out_Rain_Since_Reset
    data["ATTIC_Temp"] = now.Attic_Temp
    data["ATTIC_Humid"] = now.Attic_Humid
    data["NOW_URL"] = now.Now_URL
    data["NOW_Feel"] = now.Now_Feel
    data["NOW_Feel_High"] = now.Now_Feel_High
    data["NOW_Feel_Low"] = now.NOW_Feel_Low
    data["SYSTEM_CPU"] = now.System_CPU
    data["SYSTEM_RAM"] = now.System_RAM

    # Now return the json as a string
    return json.dumps(data)
Пример #40
0
def getPageSourcesOf(whichPages, _IPCData):
    MAX_RETRY_TIMES = 4
    for failTimes in range(MAX_RETRY_TIMES):  # 尝试 MAX_RETRY_TIMES 次链接 IPC。
        try:
            c = Client(('localhost', _IPCData['port']), authkey=b'CSDN-Data')
        except ConnectionRefusedError as e:
            print("[Info] ConnectionRefusedError: ", e)
            if failTimes == MAX_RETRY_TIMES - 1:  # 第 MAX_RETRY_TIMES 次链接失败
                import traceback
                traceback.print_exc()
            time.sleep(1 * (failTimes + 1))
        else:
            break
    recv_result = False
    if whichPages == 'ArticlesPages':
        while True:
            _recv = c.recv()
            if recv_result is False:
                if _recv == 'SYNC':
                    c.send('SYNC')
                elif _recv == 'Req: whichPage':
                    c.send('ArticlesPages')
                elif _recv == 'Req: req_url':
                    c.send(_IPCData['req_url'])
                elif _recv == 'Rsp: pagesource':
                    c.send('Ready')
                    recv_result = True
            else:
                _pagesources = _recv
                c.close()
                return _pagesources
    else:
        return None  # raise myself define unknow type?
def generate(port, msg, f_writer):
    os.system(terminal_start_command + " " + slave_file_name + " " + str(port))
    while (True):
        try:
            address = ('localhost', port)
            conn = Client(address, authkey=b'secret password')
            conn.send(msg)  #send variants to *flappy_bird_variant_generate.py*
            print(" param update:", msg)
            msg = conn.recv(
            )  #wait for response from *flappy_bird_variant_generate.py*
            if (msg == None):
                print("Failed")  # variants sent are not playable for ai agent
            elif (len(msg) == 2):
                print("Failed", msg)  # print score
                f_writer.writerow(["Failed", msg[1], msg[0], ""])
            else:
                print(msg)  # variants sent are playable for ai agent
                f_writer.writerow(msg)
            conn.close()
            break
        except ConnectionRefusedError:  # usually *flappy_bird_variant_generate.py* is not started yet, so waits till it is running
            print("refused")
            sleep(3)
        except EOFError:  # usually *flappy_bird_variant_generate.py* training is complete
            print("flappy_bird_variant_generate.py server closed")
            break
        except Exception as e:
            print("Error occurred " + str(e))
            break
Пример #42
0
class IPCClient:

    def __init__(self):
        self.subscribers = defaultdict(set)
        self.conn = None
        self.thread = None

    @property
    def running(self):
        if self.thread:
            return self.thread.is_alive()
        return False

    def run(self):
        return

    def start_in_seperate_process(self, pipe):
        self.conn = Client(ipc_server.address, authkey=ipc_server.authkey)
        try:
            self.run()
        except Exception:
            self.conn.close()
            #Cause traceback objects aren't pickle'able, whytho.jpg
            pipe.send("".join(traceback.format_exception(*sys.exc_info())))

    def attach(self, event, func):
        self.subscribers[event].add(func)

    def start(self):
        recv_pipe, send_pipe = Pipe()
        self.thread = Process(target=self.start_in_seperate_process, daemon=True, args=(send_pipe,))
        self.thread.start()

        try:
            if recv_pipe.poll(0.5):
                exc_info = recv_pipe.recv()
                logging.error(f'Error starting process, got exception:\n{exc_info}')
                self.thread.join()
                raise Exception(exc_info.splitlines()[-1])
        finally:
            recv_pipe.close()
            send_pipe.close()

    def dispatch_event(self, event, msg):
        self.conn.send((event, msg))
        try:
            topic, data = self.conn.recv()
            if topic == Events.EXCEPTION:
                logging.debug(f"Received data back from event: {event} - ERROR - {data}")
                raise Exception(data)

            logging.debug(f"Received data back from event: {event} - OK")
            return data
        except EOFError:
            pass

    def stop(self):
        self.thread.kill()
        self.thread.join()
        logging.debug(f"Stopping process pid: {self.thread.pid}, name:{self.thread.name}/{self.thread.ident}")
Пример #43
0
def run_client(host, port):
    capture = OpenCVCapture()
    visualizer = Open3d_visualizer()
    client = Client((host, port))
    data_cacher = np.zeros((6890,3))

    while True:
        frame = capture.read()
        if frame is not None:
            data = frame
        else:
            data = ['waiting for the cam']
        data_string = pickle.dumps(data)
        client.send(data_string)

        if frame is not None:
            data_bytes = client.recv()
            data_recieve = pickle.loads(data_bytes)
            if not isinstance(data_recieve, list):
                break_flag = visualizer.run(data_recieve, frame[:,:,::-1])
                data_cacher = data_recieve
            else:
                break_flag = visualizer.run(data_cacher, frame[:,:,::-1])
            if break_flag:
                break
Пример #44
0
def communicate(message):
    address = ('localhost',6345)
    conn = Client(address)
    conn.send(message)
    reply = conn.recv()
    conn.close()
    return reply
Пример #45
0
class Bigram():
    def __getitem__(self, word):
        global _phrases

        # If a phrases model is already loaded, just use that
        if _phrases is not None:
            self.conn = None

        # Otherwise, try to connect to the separate process.
        # Fall back to loading the phrase model here
        elif not hasattr(self, 'conn'):
            try:
                print('Connecting to phrases process...')
                address = ('localhost', 6001)
                self.conn = Client(address, authkey=b'password')
                print('Done connecting to phrases')

            except ConnectionRefusedError:
                self.conn = None
                print('Could not connect to phrases process,')
                print('Loading phrases model...')
                _phrases = Phrases.load('data/bigram_model.phrases')
                print('Done loading phrases')

        if self.conn is not None:
            self.conn.send(word)
            return self.conn.recv()
        else:
            return _phrases[word]
Пример #46
0
class Server:
    def __init__(self):
        self.connection = None

    def connect(self):
        """
        Establishes a connection to the worker.
        """
        while not self.connection:
            try:
                self.connection = Client(Config.address)
            except ConnectionRefusedError:
                print("Connection refused. Retrying in 1 second...")
            sleep(1)
        print("Connection established!")

    def task(self, job: Job):
        """
        Send a job to the worker.
        """
        self.connection.send(job)

    def query(self, query: Query):
        """
        Query the worker for a value.
        """
        self.connection.send(query)
        try:
            return self.connection.recv()
        except BlockingIOError:
            print("Query not available")
            return None
Пример #47
0
def reset_rain():
    # Reset rain_since_reset in the table
    # (╯°□°)╯︵ ┻━┻
    c = Client( ('localhost', 25000) )
    c.send("reset_rain")
    result = c.recv()
    
    return "reset!"
Пример #48
0
 def conn(self, serveur=None):
     agent = params['DEFAULT_AGENT']
     print "Mot de passe <%s>" % agent.password
     address = (agent.server_ip, agent.server_port)
     print "Connecting : ", address
     print "Params = ", params
     try:
         ## important le str(agent.password) est necessaire
         ## sinon pas reconnu
         conn = Client(address, authkey=str(agent.password))
         print "Connexion etablie"
         ## Reception de l'invite du serveur
         print conn.recv()
         return conn
     except:
         print "Erreur connexion"
         return None
Пример #49
0
 def _send(self, msg):
     conn = Client(self.address, authkey=self.authkey)
     conn.send(msg)
     result = conn.recv()
     conn.close()
     if result:
         self._locked = True
     return result
Пример #50
0
    def run(self):
        while not self._stop:
            address = ('localhost', 6000)
            conn = Client(address)
            msg = conn.recv()
            conn.close()

            [cb() for k,cb in self.cbs.items() if msg==k]
Пример #51
0
 def send(self, command, payload = None):
     address = ('localhost', self.port)
     #print address
     conn = Client(address)
     conn.send((command, payload))
     response, response_payload = conn.recv()
     conn.close()
     return response_payload
Пример #52
0
class CheckQueueClient(local):
    def new_connection(self):
        self.pid = current_process().pid
        self.tid = current_thread().ident
        logging.info('Starting check queue client connection for pid %s tid %s', self.pid, self.tid)
        self.tag = str(self.pid) + '_' + str(self.tid) + '_' + str(time.time())
        self.queue = 'check_queue_client_' + self.tag
        self.connection = Client(address=(settings.EVENT_HOST, settings.EVENT_PORT))
        self.connection.send(Attach(self.queue))
        self.connection.recv()
        self.connection.send(Map({'type': 'checking_test_result_dequeue_result', 'tag': str(self.tag)}, self.queue))
        self.connection.recv()

    def __init__(self):
        self.new_connection()

    def get_next(self, role):
        if (self.pid != current_process().pid) or (self.tid != current_thread().ident):
            self.new_connection()
        self.connection.send(Send(Event(type='checking_test_result_dequeue', tag=str(self.tag), tester_id=role.id)))
        self.connection.recv()
        self.connection.send(Receive())
        result = self.connection.recv()
        logging.debug('Check queue client: received %s for pid %s tid %s', result[1], self.pid, self.tid)
        return result[1]
Пример #53
0
 def _query(self, message):
     connection = Client(self.address, family='AF_INET')
     connection.send(message)
     response = connection.recv()
     connection.close()
     if response['type'] == 'result':
         return response['data']
     else:
         raise DatabaseException(response['data'])
Пример #54
0
 def method(*args, **kwargs):
     connection = Client(address, authkey=authkey)
     connection.send([method_name, args, kwargs])
     result = connection.recv()
     connection.close()
     if result['type'] == 'result':
         return result['data']
     else:
         raise Exception(result['data'])
 def __init__(self, portstr="/dev/m4_com", conn_type="serial"):
   self._pf = PacketFinder()
   self.conn_type = conn_type
   if self.conn_type == "serial":
     self._ser = serial.Serial(portstr, 115200, timeout=0)
     self._ser.flushInput()
   elif self.conn_type == "portal":
     conn = Client(address=('localhost', 50000), authkey='abracadabra')
     port = conn.recv()
     self.conn = Client(address=('localhost', port), authkey='abracadabra')
Пример #56
0
    def TryToConnect(self,child,host,port,n):
        address = (host,port)
#        address = ('jeremyfisher.math.udel.edu', 6000)
        #address = ('nutkin', 6000)
        conn = Client(address, authkey='secret password')
        conn.send(pickle.dumps(n,pickle.HIGHEST_PROTOCOL))
        vdata = pickle.loads(conn.recv())
        conn.send('close')
        conn.close()
        child.send(vdata)
Пример #57
0
def run_backend(replace=False, exit=False, w2v_vector_file=W2V_VECTOR_FILE, temp_startup_server=False):
  repr_req_count = 0

  send_exit_command_after_init = False

  if not temp_startup_server:
    try:
      print('Connecting to backend.')
      conn = Client(BACKEND_ADDRESS, family=BACKEND_CONNECTION_FAMILY, authkey=BACKEND_PASSWORD)
      if not replace and not exit:
        conn.send({'command': 'CAPABILITIES'})
        msg = conn.recv()
        if msg['status'] == 'OK' and (msg['value'] == 'FULL' or msg['value'] == 'W2V_ONLY'):
          print('There is already an existing daemon with all neccessary capacities. Exiting.')
          sys.exit()
        else:
          print msg
          print('Found a running backend without required capabilities. Telling it to exit after init.')
          send_exit_command_after_init = True
      else: 
        print('Found a running backend. Telling it to exit after init.')
        send_exit_command_after_init = True
    except Exception, e:
      print(str(e))
      print(str(traceback.format_exc()))
      print('Did not manage to find a backend to kill.')

    if exit:
      print('Exiting.')
      sys.exit()

    if not send_exit_command_after_init:
      # The temp_startup_serer will take care of requests until startup (init()) is complete.
      p = Process(target=run_backend, kwargs={'temp_startup_server': True})
      p.start()
    
    init(w2v_vector_file=w2v_vector_file)
    
    # either temp_startup_server backend, or a previously running backend.
    print('Connecting to temp_startup_server (or previously running) backend.')
    conn = Client(BACKEND_ADDRESS, family=BACKEND_CONNECTION_FAMILY, authkey=BACKEND_PASSWORD)
    conn.send({'command': 'EXIT_NOW'})
    conn.close()
    conn = None
    if not send_exit_command_after_init:
      print('Waiting 1 sec for temp_startup_server backend to clean up.')
      time.sleep(1)
    else:
      print('Waiting 30 sec for previously running backend to clean up.')
      time.sleep(30)
      
    if not send_exit_command_after_init:
      p.terminate()
      print('temp_startup_server backend is now terminated.')
Пример #58
0
 def method(self, *args):
     args = list(args)
     args.insert(0, attribute)
     connection = Client(self.address, authkey=self.authkey)
     connection.send(dumps(args))
     result = loads(connection.recv())
     connection.close()
     if result[0] == 'RESULT':
         return result[1]
     else:
         raise MemoClientException(result[1])
Пример #59
0
class Component(Base):
    """
    Components send and receive messages.

    Remember to call __init__() from your constructor! Subclass
    this and implement handle_message() to actually do stuff.
    Don't override anything but __init__() and handle_message()!
    """
    def __init__(self, bus=DEFAULT_ADDRESS, authkey=None, interests=None):
        """
        Initialize a new component.

        Connect to bus (host, port) with given authorization key and
        interests; interests can be a class, type, or tuple of these;
        if interests is None, the __interests__ attribute is used; if
        __interests__ does not exist, object is used.

        The constructor should always be called with keyword arguments.
        """
        super(Component, self).__init__()
        self._bus = Client(address=bus, authkey=authkey)
        assert self._bus is not None
        if interests is None:
            interests = getattr(self, "__interests__", object)
        self._bus.send(interests)
        self._bus_address = bus

    def send_message(self, message):
        """
        Send a message out of this component.

        Don't call this from the outside!
        """
        self._bus.send(message)

    @abstractmethod
    def handle_message(self, message):
        """
        Handle a message.

        You must override this!
        """
        assert False, "You must override this!"

    def run(self):
        """
        The component receives and dispatches messages here.

        Don't override this!
        """
        while True:
            msg = self._bus.recv()
            self.handle_message(msg)