>>> et.sendDelays(idelays=idelays) >>> """ sys.excepthook = Pyro4.util.excepthook Pyro4.config.DETAILED_TRACEBACK = True OFFSETS = pointing.getOffsets() HEXD = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'] KURL = 'PYRO:[email protected]:19987' BURLS = {'eda1com':'PYRO:[email protected]:19987', 'eda2com':'PYRO:[email protected]:19987'} TILEID = 0 kproxy = Pyro4.Proxy(KURL) bfproxies = {} for clientid, url in BURLS.items(): bfproxies[clientid] = Pyro4.Proxy(url) def getDelays(az=0, el=90): """Call pointing.calc_delays to return the delays and associated error structures, then return just the integer delay values. Here, idelays is a dict, with key values ranging from '0' to 'F', plus 'K'. idelays['0'] contains all 16 dipole delays for the first of the first stage beamformers, and is in itself, a dict with keys ranging from '0' to 'F', for the 16 dipoles. idelays['1'] is another dict containing the 16 dipole delays for the SECOND first stage beamformer, etc.
def _get_random_aggregate(self, agent): ns = Pyro4.locateNS(self.ns_hostname) agents = ns.list(AGENT) logger.debug(agents) del agents[AGENT + "." + agent.parent.address] return Pyro4.Proxy(random.choice(agents.values()))
def workers_shutdown(): try: Pyro4.Proxy(RPC_SERVICE).shutdown_workers() return eve_response({'status': True}, 200) except: return eve_response({'status': False}, 200)
import Pyro4 #from servidor import Servidor s = Pyro4.Proxy("PYRONAME:tarefa5") msg = input("Mensagem a ser lida: ") nome = input("Nome do audio: ") s.audio(msg, nome)
# Authors: Xiaoyi Duan, Zixin Kong """Due on 4.2""" import Pyro4 """TEST CASES""" # User is in the home, all the devices and the sensors are "on" # motion1, temperature2, door3, beacon4, outlet5, bulb6,security7 gateway = Pyro4.Proxy("PYRONAME:0") lowest, N = gateway.findthelowest() low_ai = Pyro4.Proxy("PYRONAME:" + str(lowest)) msg = low_ai.bully(N, gateway) # device_list = gateway.device_list() # N = len(device_list) """DEFAULT STATE 'ON' """ print "TEST CASES" print "User is in the home, all the sensors and devices are in the on state except security" """TURN OFF A DEVICE OR SENSOR""" print "Here is the sensors and devices you have:" print gateway.device_list() gateway.change_state(3, 0) """TURN ON A DEVICE OR SENSOR""" gateway.change_state(3, 1) """QUERY SENSOR OR DEVICE (2 3 4)""" id_list = [2, 4] gateway.query_state(id_list) """CHECK HISTORY DATA BY NAME""" gateway.query_past_name(["motion", "door"]) """CHECK TEN LINES FROM HISTORY DB""" gateway.query_past_n(10) """GATEWAY AUTO SENSING""" print "AUTO SENSING START"
def initialize(self): self.RPiConnection = Pyro4.Proxy('PYRO:%s@%s:%d' % ('pi', self.ipAddress, self.port)) ## Log temperatures self.logger = valueLogger.PollingLogger( self.name, 15, self.RPiConnection.get_temperature)
def connectToneighbors_pURI(self): #print "NS items", self.nameServer.list(prefix="pig.bird").items() for pigID, pURI in self.nameServer.list(prefix="pig.bird").items(): if (pigID != self.pigID and pigID in self.peers): self.neighbors_pURI[pigID] = Pyro4.Proxy(pURI)
def setServer(): """ Ask for the user to input the server URI and put it in the global var 'server' """ global server #server = raw_input('Gateway IP:') uri = input("Enter the uri of the gateway: ").strip() server = Pyro4.Proxy(uri)
def __init__(self, name, nameserver=None): with Pyro4.locateNS(host=nameserver) as ns: uri = ns.lookup(name) self._proxy = Pyro4.Proxy(uri)
s._pyroBind() except Exception as e: return False return True sys.excepthook = Pyro4.util.excepthook if __name__ == '__main__': ns = Pyro4.locateNS() GREEN = "\033[42m" RED = "\033[41m" END = "\033[0m" while True: servers = [ (name, uri) for name, uri in ns.list(prefix="just_hungry.back_end").items() if valid_server(uri) ] print('\n'.join( f"{i+1}:\t{x[0]} \t{x[1]}\t{GREEN+'UP'+END if Pyro4.Proxy(x[1]).ping_respond() else RED+'DOWN'+END}" for i, x in enumerate(servers))) print("0.\tExit") x = int(input()) if x == 0: break if x > 0 and x <= len(servers): Pyro4.Proxy(servers[x - 1][1]).toggle_status()
from __future__ import print_function import sys import time import Pyro4 print("First make sure one of the gui servers is running.") print("Enter the object uri that was printed:") if sys.version_info < (3, 0): uri = raw_input() else: uri = input() uri = uri.strip() guiserver = Pyro4.Proxy(uri) # guiserver.message("Hello there!") # time.sleep(0.5) # guiserver.message("How's it going?") # time.sleep(2) # # for i in range(20): # guiserver.message("Counting {0}".format(i)) # # guiserver.message("now calling the sleep method with 5 seconds") # guiserver.sleep(5) for i in range(10): guiserver.add_image() time.sleep(3) print("done!")
def get_fileserver_object(): uri = "PYRONAME:{}@localhost:7777".format(namainstance) fserver = Pyro4.Proxy(uri) return fserver
def connect(self, id): return Pyro4.Proxy('PYRONAME:' + id)
#................................................. file1 = "/home/dhammika/PycharmProjects/Robot/robot4_motors.txt" file2 = "/home/dhammika/PycharmProjects/Robot/robot4_scan.txt" #................................................make the child process parent_conn, child_conn = Pipe() p = Process(target=comuincation, args=(child_conn, )) p.start() #................................................print out ready message print parent_conn.recv() #................................................give time to ready the server time.sleep(0.02) # give time to stablish the server #................................................make greetmaker client for server side access try: self = Pyro4.Proxy("PYRONAME:example.robot") except: Pyro4.errors.CommunicationError #.................................................. self.false_avilable() f1 = open(file1, "r") f2 = open(file2, "r") for l, n in zip(f1, f2): while self.is_avilable(): print ".", time.sleep(0.1) self.set_DataEncode(l) self.set_DataScan(n) self.set_avilable() print "cycle_ends..\n" p.join()
# This is the code that visits the warehouse. import sys import Pyro4 from person import Person sys.execpthook = Pyro4.util.excepthook warehouse = Pyro4.Proxy("PYRO:example.warehouse@localhost:40754") janet = Person("Janet") henry = Person("Henry") janet.visit(warehouse) henry.visit(warehouse)
def make_connection(self, uri) -> Pyro4.core.Proxy: pyrofile_server = Pyro4.Proxy(uri) return pyrofile_server
def makeProxy(): uri = "PYRONAME:filemanager@localhost:7777" proxy = Pyro4.Proxy(uri) return proxy
#coding: utf-8 import Pyro4 uri = input("What is the Pyro uri of the greeting object? ").strip() name = input("What is your name? ").strip() server = Pyro4.Proxy("PYRONAME:server") print(server.welcomeMessage(name))
def broadcast_for_phyCoord(self, senders, pigID): self.senders[self.pigID] = self.physical_position for pigID, pURI in self.neighbors_pURI.items(): if (pigID != self.pigID and pigID in self.peers): self.neighbors_pURI_URI[pigID] = Pyro4.Proxy(pURI)
from __future__ import print_function import sys import random import Pyro4 if sys.version_info < (3, 0): input = raw_input uri = input("enter attribute server object uri: ").strip() with Pyro4.Proxy(uri) as p: # Direct remote attribute access. print("\nDirect attribute access:") print("p.prop_value=", p.prop_value) print("adding 500 to p.prop_value") p.prop_value += 500 print("p.prop_value=", p.prop_value) print("actual remote value: ", p.getValue(), " (via p.getValue() remote method call)") if p.prop_value != p.getValue(): # they differ!? (should not happen) print( "Remote value is different! The p.prop_value attribute must be a local one (not remote), this should not happen! (because metadata is enabled here)" ) print() # dunder names print("calling p.__dunder__()....: ", p.__dunder__()) with Pyro4.Proxy(uri) as p: # unexposed attributes
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # TerminalRoastDB, released under GPLv3 # Roaster Set Temperature import Pyro4 import sys new_roaster_temperature = sys.argv[1] roast_control = Pyro4.Proxy("PYRONAME:roaster.sr700") if int(new_roaster_temperature) > -1 and int(new_roaster_temperature) < 551: roast_control.set_temperature(new_roaster_temperature)
def _setup(self, benchmark_name: str, container_name: str, container_tag: str, container_source: Optional[str] = None, gpu: bool = False, rng: Union[np.random.RandomState, int, None] = None, **kwargs): """ Initialization of the benchmark using container. This setup function downloads the container from a defined source. The source is defined either in the .hpobenchrc or in the its benchmark definition (hpobench/container/benchmarks/<type>/<name>). If an container is already locally available, the local container is used. Then, the container is started and a connection between the container and the client is established. Parameters ---------- benchmark_name: str Class name of the benchmark to use. For example XGBoostBenchmark. This value is defined in the benchmark definition (hpobench/container/benchmarks/<type>/<name>) container_source : Optional[str] Path to the container. Either local path or url to a hosting platform, e.g. singularity hub. container_tag : str Singularity containers are specified by an address as well as a container tag. We use the tag as a version number. By default the tag is set to `latest`, which then pulls the latest container from the container source. The tag-versioning allows the users to rerun an experiment, which was performed with an older container version. Take a look in the container_source to find the right tag to use. container_name : str name of the container. E.g. xgboost_benchmark. Specifying different container could be useful to have multiple container for the same benchmark, if a tool like auto-sklearn is updated to a newer version, and you want to compare its performance across its versions. Also, a container can contain multiple benchmarks. Therefore, we have to define for each benchmark the corresponding container name. gpu : bool If True, the container has access to the local cuda-drivers. (Not tested) """ # Create unique ID self.config = hpobench.config.config_file # We can point to a different container source. See below. container_source = container_source or self.config.container_source container_dir = Path(self.config.container_dir) if (container_source.startswith( 'oras://gitlab.tf.uni-freiburg.de:5050/muelleph/hpobench-registry' ) and container_tag == 'latest'): assert 'latest' in kwargs, 'If the container is hosted on the gitlab registry, make sure that in the ' \ 'container init, the field \'latest\' is set.' container_tag = kwargs['latest'] logger.debug( f'Replace the tag \'latest\' with \'{container_tag}\'.') container_name_with_tag = f'{container_name}_{container_tag}' logger.debug( f'Use benchmark {benchmark_name} from container {container_source}/{container_name}. \n' f'And container directory {self.config.container_dir}') # Pull the container from the singularity hub if the container is hosted online. If the container is stored # locally (e.g.for development) do not pull it. if container_source is not None \ and any((s in container_source for s in ['shub', 'library', 'docker', 'oras', 'http'])): # Racing conditions: If a process is already loading the benchmark container, let all other processes wait. # Following https://github.com/dhellmann/oslo.concurrency/blob/master/openstack/common/lockutils.py # (line 56), we don't need to handle any exception which can occur in the download_container-method. # The lock is released if the process crashes. # Also, oslo.concurrency does not delete the unused lockfiles # after usage. (An existing lock file does not mean that it is still locked!). They argue that in their # "testing, when a lock file was deleted while another process was waiting for it, it created a sort of # split-brain situation between any process that had been waiting for the deleted file, and any process # that attempted to lock the file after it had been deleted." # See: https://docs.openstack.org/oslo.concurrency/latest/admin/index.html @lockutils.synchronized( 'not_thread_process_safe', external=True, lock_path=f'{self.config.cache_dir}/lock_{container_name}', delay=5) def download_container(container_dir, container_name, container_source, container_tag): if not (container_dir / container_name_with_tag).exists(): logger.debug( 'Going to pull the container from an online source.') container_dir.mkdir(parents=True, exist_ok=True) cmd = f'singularity pull --dir {self.config.container_dir} ' \ f'--name {container_name_with_tag} ' # Currently, we can't see the available container tags on gitlab. Therefore, we create for each # "tag" a new entry in the registry. This might change in the future. But as long as we don't have # a fix for this, we need to map the container tag differently. if container_source.startswith( 'oras://gitlab.tf.uni-freiburg.de:5050/muelleph/hpobench-registry' ): cmd += f'{container_source}/{container_name.lower()}/{container_tag}:latest' else: cmd += f'{container_source}/{container_name.lower()}:{container_tag}' logger.info( f'Start downloading the container {container_name_with_tag} from {container_source}. ' 'This may take several minutes.') logger.debug(cmd) subprocess.run(cmd, shell=True, check=True) time.sleep(1) else: logger.debug( 'Skipping downloading the container. It is already downloaded.' ) download_container(container_dir, container_name, container_source, container_tag) else: logger.debug( f'Looking on the local filesystem for the container file, since container source was ' f'either \'None\' or not a known address. Image Source: {container_source}' ) # Make sure that the container can be found locally. container_dir = Path(container_source) if not container_dir.exists(): raise FileNotFoundError( f'Could not find the container on the local filesystem. The path ' f'{container_source} does not exist.' 'Please either specify the full path to the container ' 'or the directory in which the container is, as well as ' 'the benchmark name and the container tag (default: latest).' ) # if the container source is the path to the container itself, we are going to use this container directly. if container_dir.is_file(): container_dir = container_dir.parent container_name_with_tag = container_dir.name # If the user specifies a container directory, search for the container name with (!) tag in it. elif container_dir.is_dir(): assert (container_dir / container_name_with_tag).exists(), \ f'Local container not found in {container_dir / container_name_with_tag}' else: raise FileNotFoundError( 'The container source is neither a file nor a directory.' f'container_source: {container_dir}') logger.debug('Image found on the local file system.') bind_options = f'--bind /var/lib/,{self.config.global_data_dir}:/var/lib/,{self.config.container_dir}' if self.config.global_data_dir != self.config.data_dir: bind_options += f',{self.config.data_dir}:/var/lib/' bind_options += ' ' gpu_opt = '--nv ' if gpu else '' # Option for enabling GPU support container_options = f'{container_dir / container_name_with_tag}' log_str = f'SINGULARITYENV_HPOBENCH_DEBUG={log_level_str}' cmd = f'{log_str} singularity instance start {bind_options}{gpu_opt}{container_options} {self.socket_id}' logger.debug(cmd) for num_tries in range(MAX_TRIES): p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) output, err = p.communicate() logger.debug(err) # Give a little bit of time to make sure the instance does not disappears after testing if it is there. time.sleep(1) # Check if the instance is started. Starting a instance crashes sometimes without a warning. # Therefore, try this step multiple times unless it is really started out = subprocess.getoutput('singularity instance list') out = out.split() if self.socket_id in out: break logger.debug( f'Could not start instance: Try {num_tries + 1}|{MAX_TRIES}') if num_tries + 1 == MAX_TRIES: raise SystemError( f'Could not start a instance of the benchmark. Retried {MAX_TRIES:d} times' f'\nStdout: {output} \nStderr: {err}') sleep_for = np.random.randint(1, 60) logger.critical( f'[{num_tries + 1}/{MAX_TRIES}] Could not start instance, sleeping for {sleep_for} seconds' ) time.sleep(sleep_for) # Give each instance a little bit time to start time.sleep(1) cmd = f'singularity run {gpu_opt}instance://{self.socket_id} {benchmark_name} {self.socket_id}' logger.debug(cmd) subprocess.Popen(cmd.split()) Pyro4.config.REQUIRE_EXPOSE = False # Generate Pyro 4 URI for connecting to client self.uri = f'PYRO:{self.socket_id}.unixsock@./u:' \ f'{self.config.socket_dir}/{self.socket_id}_unix.sock' self.benchmark = Pyro4.Proxy(self.uri) # Handle rng and other optional benchmark arguments kwargs_str = self._parse_kwargs(rng, **kwargs) # Try to connect to server calling benchmark constructor via RPC. There exists a time limit logger.debug('Check connection to container and init benchmark') wait = 0 while True: try: self.benchmark.init_benchmark(kwargs_str) except Pyro4.core.errors.CommunicationError: logger.debug('Still waiting') time.sleep(5) wait += 5 if wait < self.config.pyro_connect_max_wait: continue logger.debug( 'Waiting time exceeded. To increase, adjust config option pyro_connect_max_wait.' ) raise TimeoutError() break logger.debug('Connected to container')
# PORT = 9999 def send_feedback(id): print("{}: Sending feedback to production line...".format(id)) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((HOST, PORT)) try: sock.sendall(id) finally: sock.close() # configure model config = {"model": "random_forest", "model_conf": {}, "trained_model": "tmp"} pyro_name = "python-learning-agent" agent = Pyro4.Proxy("PYRONAME:" + pyro_name) agent.build(config) agent.pre_train(["ABU1.txt", "ABU1.2.txt"]) products = {} def handler(json_string): #features = copy.deepcopy(Features) j = json.loads(json_string) bn = j['ResultValue']['measurements']['bn'] feature_name = j['ResultValue']['measurements']['e'][0]['n'] # new product if bn not in products: # start from the beginning only
def test_injection_of_index_kwarg(self): floating_1 = Pyro4.Proxy("PYRO:[email protected]:8001") floating_2 = Pyro4.Proxy("PYRO:[email protected]:8002") self.assertEqual(floating_1.get_index(), 0) self.assertEqual(floating_2.get_index(), 1)
def gossip(self): rm1 = Pyro4.Proxy("PYRONAME:rm1") rm3 = Pyro4.Proxy("PYRONAME:rm3") rm1.receiveGossip(self.replicaTS, self.log) rm3.receiveGossip(self.replicaTS, self.log) print("sending")
from __future__ import print_function import sys import time from Pyro4.util import getPyroTraceback import Pyro4 if sys.version_info < (3, 0): input = raw_input NUMBER_OF_LOOPS = 20000 uri = input("enter server object uri: ").strip() p = Pyro4.Proxy(uri) # First, we do a loop of N normal remote calls on the proxy # We time the loop and validate the computation result print("Normal remote calls...") begin = time.time() total = 0 p.printmessage("beginning normal calls") for i in range(NUMBER_OF_LOOPS): total += p.multiply(7, 6) total += p.add(10, 20) p.printmessage("end of normal calls") assert total == (NUMBER_OF_LOOPS * (7 * 6 + 10 + 20)) # check duration = time.time() - begin print("that took {0:.2f} seconds ({1:.0f} calls/sec)".format( duration, NUMBER_OF_LOOPS * 2.0 / duration)) duration_normal = duration # Now we do the same loop of N remote calls but this time we use
def status(): try: Pyro4.Proxy(RPC_SERVICE).status() return eve_response({'status': True}, 200) except: return eve_response({'status': False}, 200)
import os import Pyro4 import time import cPickle as pickle import IPython import cv2 sharer = Pyro4.Proxy("PYRONAME:shared.server") #robot interface GLOBAL_PATH = "/home/autolab/Workspaces/michael_working/IL_ROS_HSR/" CANVAS_DIM = 420.0 class Web_Labeler: def __init__(self): self.count = 0 def label_image(self, img): global sharer img_path = GLOBAL_PATH + 'shared_data/img_' + str(self.count) + '.png' cv2.imwrite(img_path, img) h_, w_, dim = img.shape sharer.set_img(img_path) sharer.set_img_ready(True) print("robot waiting")
def workers_start(): try: s = Pyro4.Proxy(RPC_SERVICE).start_workers() return eve_response({'status': True}, 200) except: return eve_response({'status': False}, 200)
def get_current_states(): gtfront = Pyro4.Proxy(pyro_ns.lookup("gateway")) for k in ["Door", "Temperature", "Motion", "Bulb", "Outlet"]: print("State of {0} is {1}".format(k, gtfront.query_state(k)))