def get(self, user_name): if not self.current_user : self.redirect('/admin/login') return if self.get_current_role(self.current_user) != 'admin': self.redirect('/') return try: validator = formencode.All(validators.PlainText(not_empty=True),ValidUser()) login = validator.to_python(user_name) except: self.set_secure_cookie("message", "User does not exist.") self.redirect("/admin/users/manage") return pg = PasswordGenerator(15) passwd = pg.generate() try: self.rpc = bjsonrpc.connect(host=config.ipc.rpcip, port=int(config.ipc.port)) self.rpc.call.changeUserPassword(config.ipc.apikey, base64.b64encode(user_name.encode('utf-8')), base64.b64encode(passwd.encode('utf-8'))) self.rpc.close() self.set_secure_cookie("message", "Password for user %s successfully changed. New password is %s" % (user_id, passwd)) self.redirect("/admin/users/manage") return except Exception,e: self.set_secure_cookie("message", "Could not change password for user %s. Contact system administrator." % (user_id)) self.redirect("/admin/users/manage") return
def open(self,db,user,passwd,host,port,options): if DEBUG_MODE: print "~~ open database" ok = True if self.conn is None: if not host is None and not port is None: self.conn = connect(host,port) else: if DEBUG_MODE: print "~~ Error opening: You must indicate host and port" ok = False if not isinstance(self.conn, RemoteObject): if db is not None and user is not None and passwd is not None: if not self.conn.call.login(unicode(user),unicode(passwd),unicode(db)): if DEBUG_MODE: print "~~ Error connecting: User, password or project are incorrectly" ok = False else: if DEBUG_MODE: print "~~ Error opening: You must indicate db, user and password" ok = False self.setOpen(ok) self.setOpenError(not ok) return ok
def __init__(self,host="127.0.0.1",port=10123): QtGui.QDialog.__init__(self) ui_filepath = filedir("example2_chat.ui") # convertimos la ruta a absoluta self.ui = uic.loadUi(ui_filepath,self) # cargamos un fichero UI externo self.to_be_updated = True # Indica que debe consultar los nuevos cambios self.extracount = 0 # Indica qué delta ha de usar al descargar el log de mensajes """ creamos las propiedad antes de que puedan ser usadas. """ # Conectar el botón send self.connect(self.ui.btnSend, QtCore.SIGNAL("clicked()"), self.btnSend_clicked) # Creamos los dos iconos que usaremos en este diálogo repetidamente: self.img_people = QtGui.QIcon(QtGui.QPixmap(filedir("people.png"),"png")) self.img_user = QtGui.QIcon(QtGui.QPixmap(filedir("user.png"),"png")) # Conectamos al servidor remoto. Al pasar el parámetro handler_factory # estamos abriendo la puerta a que el servidor remoto llame nuestras # funciones. self.remote = connect(handler_factory=ClientChatter, host=host,port=port) self.remote.handler._setui(self) # enlazamos este formulario con la instancia de RPC. # Creamos un timer nuevo que revisará cuando hay novedades. self.timer = QtCore.QTimer(self) self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.timer_timeout) self.timer.setInterval(100) # establecemos el intervalo de llamada a 100 milisegundos. self.timer.start()
def open(self, db, user, passwd, host, port, options): if DEBUG_MODE: print "~~ open database" ok = True if self.conn is None: if not host is None and not port is None: self.conn = connect(host, port) else: if DEBUG_MODE: print "~~ Error opening: You must indicate host and port" ok = False if not isinstance(self.conn, RemoteObject): if db is not None and user is not None and passwd is not None: if not self.conn.call.login(unicode(user), unicode(passwd), unicode(db)): if DEBUG_MODE: print "~~ Error connecting: User, password or project are incorrectly" ok = False else: if DEBUG_MODE: print "~~ Error opening: You must indicate db, user and password" ok = False self.setOpen(ok) self.setOpenError(not ok) return ok
def post(self): if self.current_user: self.redirect('/') return message = None argumentList = ['user', 'passwd'] data = { } errors = { } for argument in argumentList: try: if self.get_argument(argument): data[argument] = self.get_argument(argument) pass except Exception: pass form = LoginForm() try: data = form.to_python(data) self.rpc = bjsonrpc.connect(host=config.ipc.rpcip, port=int(config.ipc.port)) if self.rpc.call.checkLogin(config.ipc.apikey, base64.b64encode(data['user'].encode('utf-8')), base64.b64encode(data['passwd'].encode('utf-8'))): self.set_secure_cookie("user", data['user']) self.set_secure_cookie("role", 'unprivileged') self.set_secure_cookie("message", "User %s successfully logged in." % data['user']) self.redirect('/') self.rpc.close() return else: self.rpc.close() message = 'Invalid username and/or password' except Invalid, e: errors = e.unpack_errors()
def iniciar(self): self.notificar("Inicializando . . .") settings = ConfigSettings.load() self.conn = bjsonrpc.connect(host=settings.host, port=int(settings.port)) self.notificar("Conectado.") # self.conn._debug_socket = True logged = self.conn.call.login(settings.username, settings.password) assert (logged) self.notificar("Registrado.") availableprojects = self.conn.call.getAvailableProjects() project = availableprojects[0]['code'] self.prj = self.conn.call.connectProject(project) self.notificar("Proyecto conectado.") self.splash.prjconn = self.prj self.prj.qtdriver = qtdriver.QSqlLlampexDriver(self.prj) self.prj.qtdb = QtSql.QSqlDatabase.addDatabase( self.prj.qtdriver, "llampex-qsqlrpcdriver") if not self.prj.qtdb.open("", ""): print "ERROR: Error trying to connect Qt to RPC Database." self.notificar("Esperando a fin de carga.") self.splash.show()
def _to_python(self, value, state): rpc = bjsonrpc.connect(host=config.ipc.rpcip, port=int(config.ipc.port)) try: usernames = rpc.call.listUsers(config.ipc.apikey) rpc.close() except Exception,e: raise formencode.Invalid('Cannot get pre-existing user list, contact administrator', value, state)
def manage_clicked(self): host = unicode(self.ui.host.text()) port = unicode(self.ui.port.text()) port = int(port) try: self.conn = bjsonrpc.connect(host=host,port=port) self.conn._debug_socket = self.debug except Exception, e: msgBox = QtGui.QMessageBox() msgBox.setText("Error trying to connect to %s:%d: %s: %s\n" % (host,port,e.__class__.__name__ ,repr(e.args))) msgBox.setIcon(QtGui.QMessageBox.Critical) msgBox.exec_() return
def client_connect(self, host, port=12345, handler=PlayerService): """ Connects to a bjsonrpc server using the given ip, and port. :param host: the ip address of the target server :param port: the port you are trying to connect with :param handler: the class that contains all the handler methods :return: """ try: self.player_connect = bjsonrpc.connect(host=host, port=port, handler_factory=handler) result = 1 return result except Exception: raise Exception('client_connect::> Unable to connect to the server.')
def client_connect(self, host, port=12345, handler=PlayerService): """ :param host: :param port: :param handler: :return: """ try: self.player_connect = bjsonrpc.connect(host=host, port=port, handler_factory=handler) result = 1 return result except Exception: result = 0 return result
def client_connect(self, host, port=12345, handler=PlayerService): """ Connects to a bjsonrpc server using the given ip, and port. :param host: the ip address of the target server :param port: the port you are trying to connect with :param handler: the class that contains all the handler methods :return: """ try: self.player_connect = bjsonrpc.connect(host=host, port=port, handler_factory=handler) result = 1 return result except Exception: raise Exception( 'client_connect::> Unable to connect to the server.')
def main(): parser = OptionParser() (options, args) = interpret_args(sys.argv[1:], parser) #validate_args(options, parser) c = bjsonrpc.connect() if options.request: print(c.call.incoming_request([options.request])) elif options.stop: print(c.call.stop()) elif options.host: print(c.call.consuming(options.action, options.host, options.service, options.location)) elif options.client: print(c.call.hosting(options.action, options.client, options.service, options.location))
def attachReal(ueAttachedObj): print "\n--------------------------\n...connecting to vBBU-NSSF" c = connect(nssfIp) time.sleep(1) print "connected vBBU-NSSF." time.sleep(1) print "...attaching vBBU-NSSF" time.sleep(1) ueAttachedObjUnpickled = pickle.loads(ueAttachedObj) #print "ueAttachObj:" #print "\t", ueAttachedObjUnpickled.ip #print "\t", ueAttachedObjUnpickled.serviceType #response = c.call.networkAttach(ueIp, serviceType, ueAttachedObjUnpickled) response = c.call.networkAttach(ueAttachedObj) printNSSFresponse(response) return response
def get(self): if not self.current_user: self.redirect("/admin/login") return if self.get_current_role(self.current_user) != 'admin': self.redirect('/') return self.rpc = bjsonrpc.connect(host=config.ipc.rpcip, port=int(config.ipc.port)) userNameList = self.rpc.call.listUsers(config.ipc.apikey) userList = [] for user in userNameList: userList.append(self.rpc.call.userDetails(config.ipc.apikey, unicode(user))) self.rpc.close() message=self.get_secure_cookie("message") self.clear_cookie('message') fieldList = ['login', 'name', 'email', 'mobile'] self.render(self.template, message=message, doctype='xhtml-transitional', title=self.title, userList=userList, fieldList=fieldList)
def main(): parser = OptionParser() (options, args) = interpret_args(sys.argv[1:], parser) validate_args(options, parser) connect = bjsonrpc.connect() if options.request: print(connect.call.incoming_request([options.request])) elif options.stop: print(connect.call.stop()) elif options.consuming: print(connect.call.consuming(options.action, options.key, options.service, options.location)) elif options.hosting: print(connect.call.hosting(options.action, options.key, options.service, options.location)) elif options.query: print(connect.call.query(host=options.key, service=options.service)) else: help_me()
def SimplateLoop(): threadName = threading.current_thread().name c=connect(host="127.0.0.1", port=settings.SIMPLATE_SERVER_PORT) c.call.registrate(cds_settings.SCENARIO_ID_Shop, threadName) c.call.startSession("CLIENT" + threadName, "some client info") while True: time.sleep(random.uniform(0,10)) if c.call.shouldStartBigShow(): logging.info("Allowed to start big show") time.sleep(random.uniform(1,2)) r = random.randint(0,2) if r == 0: logging.info("Starting a succesfull show with id 1") c.call.simpleStart(cds_settings.SIMPLE_ID_BIG_SHOW) time.sleep(random.uniform(3,5)) c.call.simpleResult(cds_settings.SIMPLE_ID_BIG_SHOW, (1,1)) elif r == 1: logging.info("Canceling a show") c.call.simpleResult(cds_settings.SIMPLE_ID_BIG_SHOW, (0,None)) elif r == 2: logging.info("Starting a succesfull show with id 2") time.sleep(random.uniform(3,5)) c.call.simpleResult(cds_settings.SIMPLE_ID_BIG_SHOW, (1,2))
def iniciar(self): self.notificar("Inicializando . . .") settings = ConfigSettings.load() self.conn = bjsonrpc.connect(host=settings.host,port=int(settings.port)) self.notificar("Conectado.") # self.conn._debug_socket = True logged = self.conn.call.login(settings.username,settings.password) assert(logged) self.notificar("Registrado.") availableprojects = self.conn.call.getAvailableProjects() project = availableprojects[0]['code'] self.prj = self.conn.call.connectProject(project) self.notificar("Proyecto conectado.") self.splash.prjconn = self.prj self.prj.qtdriver = qtdriver.QSqlLlampexDriver(self.prj) self.prj.qtdb = QtSql.QSqlDatabase.addDatabase(self.prj.qtdriver, "llampex-qsqlrpcdriver") if not self.prj.qtdb.open("",""): print "ERROR: Error trying to connect Qt to RPC Database." self.notificar("Esperando a fin de carga.") self.splash.show()
def accept(self): username = unicode(self.ui.user.text()) password = unicode(self.ui.password.text()) host = unicode(self.ui.host.text()) port = unicode(self.ui.port.text()) try: port = int(port) except ValueError: msgBox = QtGui.QMessageBox() msgBox.setText("The port number must be integer") msgBox.setIcon(QtGui.QMessageBox.Critical) msgBox.exec_() return try: self.conn = bjsonrpc.connect(host=host,port=port) self.conn._debug_socket = self.debug except Exception, e: msgBox = QtGui.QMessageBox() msgBox.setText("Error trying to connect to %s:%d: %s: %s\n" % (host,port,e.__class__.__name__ ,repr(e.args))) msgBox.setIcon(QtGui.QMessageBox.Critical) msgBox.exec_() return
def SimplateLoop(): threadName = threading.current_thread().name c = connect(host="127.0.0.1", port=settings.SIMPLATE_SERVER_PORT) c.call.registrate(cds_settings.SCENARIO_ID_Shop, threadName) c.call.startSession("CLIENT" + threadName, "some client info") while True: time.sleep(random.uniform(0, 10)) if c.call.shouldStartBigShow(): logging.info("Allowed to start big show") time.sleep(random.uniform(1, 2)) r = random.randint(0, 2) if r == 0: logging.info("Starting a succesfull show with id 1") c.call.simpleStart(cds_settings.SIMPLE_ID_BIG_SHOW) time.sleep(random.uniform(3, 5)) c.call.simpleResult(cds_settings.SIMPLE_ID_BIG_SHOW, (1, 1)) elif r == 1: logging.info("Canceling a show") c.call.simpleResult(cds_settings.SIMPLE_ID_BIG_SHOW, (0, None)) elif r == 2: logging.info("Starting a succesfull show with id 2") time.sleep(random.uniform(3, 5)) c.call.simpleResult(cds_settings.SIMPLE_ID_BIG_SHOW, (1, 2))
def SimplateLoop(): threadName = threading.current_thread().name c=connect(host="127.0.0.1", port=settings.SIMPLATE_SERVER_PORT) c.call.registrate(cds_settings.SCENARIO_ID_Shop, threadName) c.call.startSession("CLIENT" + threadName, "some client info") for i in range(1,100): fb = random.randint(0,3) if fb == 0: c.call.simpleResult(cds_settings.SIMPLE_ID_FEEDBACK, (0,0)) with lock: localFeedback['cancel'] += 1 elif fb == 1: c.call.simpleResult(cds_settings.SIMPLE_ID_FEEDBACK, (1,2)) with lock: localFeedback['cancel'] += 1 elif fb == 2: c.call.simpleResult(cds_settings.SIMPLE_ID_FEEDBACK, (1,0)) with lock: localFeedback['no'] += 1 elif fb == 3: c.call.simpleResult(cds_settings.SIMPLE_ID_FEEDBACK, (1,1)) with lock: localFeedback['yes'] += 1 c.close()
def run_call(options, connect=None): """Print the result of the action. connect: The bjsonrpc connection to use, or None to create a new one, with defaults. """ if connect is None: connect = bjsonrpc.connect() if options.request: print(connect.call.incoming_request([options.request])) elif options.stop: print(connect.call.stop()) elif options.consuming: print(connect.call.consuming(options.action, options.key, options.service, options.location)) elif options.hosting: print(connect.call.hosting(options.action, options.key, options.service, options.location)) elif options.query: print(connect.call.query(host=options.key, service=options.service)) else: help_me()
def main(): parser = OptionParser() (options, args) = interpret_args(sys.argv[1:], parser) validate_args(options, parser) connect = bjsonrpc.connect() if options.request: print(connect.call.incoming_request([options.request])) elif options.stop: print(connect.call.stop()) elif options.consuming: print( connect.call.consuming(options.action, options.key, options.service, options.location)) elif options.hosting: print( connect.call.hosting(options.action, options.key, options.service, options.location)) elif options.query: print(connect.call.query(host=options.key, service=options.service)) else: help_me()
def SimplateLoop(): threadName = threading.current_thread().name c = connect(host="127.0.0.1", port=settings.SIMPLATE_SERVER_PORT) c.call.registrate(cds_settings.SCENARIO_ID_Shop, threadName) c.call.startSession("CLIENT" + threadName, "some client info") for i in range(1, 100): fb = random.randint(0, 3) if fb == 0: c.call.simpleResult(cds_settings.SIMPLE_ID_FEEDBACK, (0, 0)) with lock: localFeedback['cancel'] += 1 elif fb == 1: c.call.simpleResult(cds_settings.SIMPLE_ID_FEEDBACK, (1, 2)) with lock: localFeedback['cancel'] += 1 elif fb == 2: c.call.simpleResult(cds_settings.SIMPLE_ID_FEEDBACK, (1, 0)) with lock: localFeedback['no'] += 1 elif fb == 3: c.call.simpleResult(cds_settings.SIMPLE_ID_FEEDBACK, (1, 1)) with lock: localFeedback['yes'] += 1 c.close()
def __init__(self, host="127.0.0.1", port=10123): QtGui.QDialog.__init__(self) ui_filepath = filedir( "example2_chat.ui") # convertimos la ruta a absoluta self.ui = uic.loadUi(ui_filepath, self) # cargamos un fichero UI externo self.to_be_updated = True # Indica que debe consultar los nuevos cambios self.extracount = 0 # Indica qué delta ha de usar al descargar el log de mensajes """ creamos las propiedad antes de que puedan ser usadas. """ # Conectar el botón send self.connect(self.ui.btnSend, QtCore.SIGNAL("clicked()"), self.btnSend_clicked) # Creamos los dos iconos que usaremos en este diálogo repetidamente: self.img_people = QtGui.QIcon( QtGui.QPixmap(filedir("people.png"), "png")) self.img_user = QtGui.QIcon(QtGui.QPixmap(filedir("user.png"), "png")) # Conectamos al servidor remoto. Al pasar el parámetro handler_factory # estamos abriendo la puerta a que el servidor remoto llame nuestras # funciones. self.remote = connect(handler_factory=ClientChatter, host=host, port=port) self.remote.handler._setui( self) # enlazamos este formulario con la instancia de RPC. # Creamos un timer nuevo que revisará cuando hay novedades. self.timer = QtCore.QTimer(self) self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.timer_timeout) self.timer.setInterval( 100) # establecemos el intervalo de llamada a 100 milisegundos. self.timer.start()
def get(self): if not self.current_user: self.redirect('/login') return user_role = self.get_current_role(self.current_user) if user_role == 'admin': self.redirect('/admin/') return elif user_role == 'unprivileged': userDict = { } login = self.current_user try: self.rpc = bjsonrpc.connect(host=config.ipc.rpcip, port=int(config.ipc.port)) userDict = self.rpc.call.userDetails(config.ipc.apikey, login) self.rpc.close() except Exception, e: self.set_secure_cookie("message", 'Error fetching user info, contact system administrator') message = self.get_secure_cookie('message') self.clear_cookie('message') self.render('templates/userIndex.html', message=message, userDict=userDict, doctype='xhtml-transitional', title=self.title)
def before_all(): pass #lettuce.world.application = multiprocessing.Process(target=app.run) world.application = subprocess.Popen(['python','/Users/matt/workspace/instruments/app.py']) pqaut.client.wait_for_automation_server() lettuce.world.qtapp = bjsonrpc.connect(host='0.0.0.0', port=9001)
def setUp(self): """ Start the server and connect the client for every test. """ testserver1.start() self.conn = bjsonrpc.connect()
def isActive(config): try: bjsonrpc.connect(host=config.ipc.rpcip, port=int(config.ipc.port)) return True except: return False
c.call.simpleResult(cds_settings.SIMPLE_ID_FEEDBACK, (1, 0)) with lock: localFeedback['no'] += 1 elif fb == 3: c.call.simpleResult(cds_settings.SIMPLE_ID_FEEDBACK, (1, 1)) with lock: localFeedback['yes'] += 1 c.close() threads = [] for i in range(1, 20): t = threading.Thread(target=SimplateLoop, name="Simplate #" + str(i)) t.daemon = True t.start() threads += [t] run = True while run: run = False for t in threads: t.join(0.01) if t.isAlive(): run = True print "Local feedback: " + str(localFeedback) c = connect(host="127.0.0.1", port=settings.SIMPLATE_SERVER_PORT) c.call.registrate(cds_settings.SCENARIO_ID_Shop, 'simeSimplate') c.call.startSession("Some CLIENT", "some client info") print "Remote feedback" + str(c.call.getFeedbackStatistics())
# -*- coding: utf-8 -*- from bjsonrpc import connect from bjsonrpc.exceptions import ServerError import cds_settings import time #TODO: use some unit-test framework def StartTest(name): print "###TEST: %s" % name StartTest("Connection") c = connect(host="127.0.0.1", port=18888) c.close() StartTest("Get time") c = connect(host="127.0.0.1", port=18888) print c.call.getLocalTime() print c.call.getUtcTime() c.close() StartTest("New client shop -> bar") c = connect(host="127.0.0.1", port=18888) c.call.registrate(cds_settings.SCENARIO_ID_Shop, 10) print "Client just came: " + str(c.call.startSession("client1", "Вася Пупкин")) c.call.simpleStart('simple id') c.call.simpleResult('simple id', (1, 1)) c.call.simpleEnd('simple id')
import sys sys.path.insert(0, "../") # prefer local version import bjsonrpc from bjsonrpc.handlers import BaseHandler import random import time class MyHandler(BaseHandler): def notify(self, text): print("Notify:\n%s" % text) conn = bjsonrpc.connect(host="127.0.0.1", port=10123, handler_factory=MyHandler) def benchmark(): print(conn.call.echo('Hello World!')) total = 0 count = 0 valuecount = 10000 start = time.time() for i in range(valuecount): randval = random.uniform(-100, 100) total += randval count += 1 conn.notify.addvalue(randval)
def is_unprivileged_class_type(user): rpc = bjsonrpc.connect(host=config.ipc.rpcip, port=int(config.ipc.port)) retval = (user in rpc.call.listUsers(config.ipc.apikey)) rpc.close() return retval
#!/usr/bin/python # -*- coding: utf-8 -*- from bjsonrpc import connect from bjsonrpc.exceptions import ServerError from bjsonrpc.handlers import BaseHandler import settings import time import logging import threading logging.basicConfig(format='%(asctime)s %(levelname)s[%(threadName)s]: %(message)s', level=logging.INFO) class BarStubHandler(BaseHandler): def newBarOrder(self, drink, orderId, simplateId): logging.info("New order id=%d simplate=%s: %s", orderId, simplateId, unicode(drink)) self._conn.method.barOrderDone(orderId) c=connect(host="127.0.0.1", port=settings.BAR_SERVER_PORT, handler_factory=BarStubHandler) c.call.registrate() while True: c.call.ping() c.read_and_dispatch(timeout=5)
argumentList = ['newPassword', 'newPasswdConfirm', 'oldPassword'] data = { } for argument in argumentList: try: if self.get_argument(argument): data[argument] = self.get_argument(argument) except Exception, e: pass form = ClientPasswordChangeForm() try: data = form.to_python(data) errors = { } print "DEBUG: login = %s" % (login) self.rpc = bjsonrpc.connect(host=config.ipc.rpcip, port=int(config.ipc.port)) if not self.rpc.call.checkLogin(config.ipc.apikey, base64.b64encode(login), base64.b64encode(data['oldPassword'].encode('utf-8'))): self.set_secure_cookie("message", '<font color="red">Old password is invalid</font>') self.redirect('/passwd') self.rpc.close() return try: self.rpc.call.changeUserPassword(config.ipc.apikey, base64.b64encode(login), base64.b64encode(data['newPassword'].encode('utf-8'))) self.set_secure_cookie("message", "Password changed successfully.") self.redirect('/') self.rpc.close() return except Exception, e: print e self.set_secure_cookie("message", 'Error changing password: %s. Contact system administrator.' %(e)) self.redirect('/')
import bjsonrpc from bjsonrpc.handlers import BaseHandler from typing import Tuple class IceAdapterHandler(BaseHandler): def _setup(self): print("_setup") def onGpgNetMessageReceived(self, header: str, chunks: tuple): print("from GPGNet: {}: {}".format(header, chunks)) if header == "GameState": if len(chunks) >= 1: if chunks[0] == "Lobby": self._conn.call.hostGame("africa.v0005") #self._conn.call.joinGame("asdf", 1234) iceconn = bjsonrpc.connect(host="127.0.0.1", port=7236, handler_factory=IceAdapterHandler) iceconn.serve()
import bjsonrpc c = bjsonrpc.connect(port=8002) print("::> %s\n" % c.call.hello(name="john")) print("::> %s\n" % c.call.hello("arnold"))
# encoding: UTF-8 # ::::::::::::: Ejemplo básico 1 de json-rpc (CLIENTE) :::::::::::: from bjsonrpc import connect import time c = connect() c.call.start() # iniciamos el cronómetro a = 0 # realizamos algunas operaciones al azar, costosas... for i in range(1000): a += i res = c.method.stoplapse() # y preguntamos el tiempo transcurrido: print "Elapsed:", c.call.lapse() print res.value() time.sleep(0.1) # dejamos que pase una decima de segundo mas... c.call.stop() # y detenemos el cronómetro # preguntamos el tiempo transcurrido: (habrá pasado aprox. 0.1 segundos) print "Elapsed:", c.call.lapse() time.sleep(0.1) # dejamos que pase otra decima de segundo. # el cronometro está parado. No debe haber diferencia de tiempo: print "Elapsed:", c.call.lapse() # debe valer lo mismo que el anterior. """ La salida normal de este programa es aproximadamente ésta: Elapsed: 0.00327587127686
import bjsonrpc test1 = {"args": ['python *.py'], "input": [], "inputfiles" : {}, } codes = {"foo.py": "print 'hello World'"} references = {"hello.py": "print 'Hello World!'"} tests = [test1] c = bjsonrpc.connect() print c.call.checkWithReference(codes, references, tests)
#!/usr/bin/python # -*- coding: utf-8 -*- from bjsonrpc import connect from bjsonrpc.exceptions import ServerError from bjsonrpc.handlers import BaseHandler import settings import time import logging import threading from listeners import _logFunction logging.basicConfig( format='%(asctime)s %(levelname)s[%(threadName)s]: %(message)s', level=logging.INFO) class SlaveSimplateStubHandler(BaseHandler): def sendToSlave(self, *args): _logFunction("args: ", args) c = connect(host="127.0.0.1", port=settings.SLAVE_SIMPLATE_SERVER_PORT, handler_factory=SlaveSimplateStubHandler) c.call.registrate(10) while True: c.call.ping() c.read_and_dispatch(timeout=5)
from typing import Tuple class SdpHandler(BaseHandler): def _setup(self): print("_setup") def onSdp(self, playerA: int, playerB: int, sdp: str): print("onSdp: {} -> {}: {}".format(playerA, playerB, sdp)) def onGpgNetMessageReceived(self, header: str, chunks: tuple): print("from GPGNet: {}: {}".format(header, chunks)) sdpconn = bjsonrpc.connect(host="127.0.0.1", port=10123, handler_factory=SdpHandler) class IceAdapterHostHandler(BaseHandler): def _setup(self): print("_setup") def onConnectionStateChanged(self, state: str): if state == "Connected": print("Connected") status = self._conn.call.status() print("status: {}".format(status)) myId = status["options"]["player_id"] myLogin = status["options"]["player_login"] self.sdpconn.call.setId(myId)
#!/usr/bin/python # -*- coding: utf-8 -*- from bjsonrpc import connect from bjsonrpc.exceptions import ServerError from bjsonrpc.handlers import BaseHandler import settings import time import logging import threading logging.basicConfig( format='%(asctime)s %(levelname)s[%(threadName)s]: %(message)s', level=logging.INFO) class BigShowClientStubHandler(BaseHandler): def startBigShow(self, showId): logging.info("Start big show with id = %s", unicode(showId)) c = connect(host="127.0.0.1", port=settings.BIG_SHOW_PORT, handler_factory=BigShowClientStubHandler) c.call.registrate() while True: c.call.ping() c.read_and_dispatch(timeout=5)
def createAttachObj(): obj = ueAttachObj() obj.ip = "192.168.186.51" obj.serviceType = 5 #print "ueAttachObj:" #print "\t", obj.ip #print "\t", obj.serviceType return obj # connecting to vBBU print "\n---------------------" print "...connecting ue-vBBU" time.sleep(1) c = connect("192.168.186.61") print "connected ue-vBBU." time.sleep(1) # sending attach request to vBBU with a service-type for video attachedObj = createAttachObj() attachedParameter = pickle.dumps(attachedObj) print "...attaching ue-vBBU-..." time.sleep(2) response = c.call.attachvBBU(attachedParameter) responseUnpickled = pickle.loads(response) time.sleep(1) print "attached ue-vBBU-..." time.sleep(0.5)
from flask import Flask, render_template, redirect, url_for, request import bjsonrpc app = Flask(__name__) app.debug = True test_data = {"heading":1} qtapp = bjsonrpc.connect(host='0.0.0.0', port=9001) @app.route("/", methods=['get']) def index(): return render_template('index.html') @app.route("/", methods=['post']) def send_info(): test_data.update(request.form) print test_data for key, value in test_data.items(): test_data[key] = float(value[0]) qtapp.call.change_position(test_data) return redirect('/') if __name__ =="__main__": app.run()
def thread1(): time.sleep(0.2) conn = bjsonrpc.connect(host="127.0.0.1",port=10123) conn.call.echo("Hello world") conn.close()
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import sys sys.path.insert(0,"../") # prefer local version import bjsonrpc import time import random conn = bjsonrpc.connect(host="127.0.0.1",port=10123) conn._debug_socket = True ch1 = conn.call.newChronometer() ch2 = conn.call.newChronometer() list1 = conn.call.newList() list2 = conn.call.newList() ch1.call.start() conn._debug_socket = False print "ch1 start." time.sleep(0.05); print " %.4f\t%.4f" % (ch1.call.lapse(), ch2.call.lapse()) time.sleep(0.05) ch2.call.start(); print "ch2 start." time.sleep(0.05); print " %.4f\t%.4f" % (ch1.call.lapse(), ch2.call.lapse()) time.sleep(0.05); ch1.call.stop(); print "ch1 stop."
import gps from pprint import pprint import bjsonrpc #session = gps.gps("localhost", "2947") session = gps.gps("localhost", "9002") session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) client = None try: client = bjsonrpc.connect(host="127.0.0.1", port=9001) except Exception as ex: print 'exception happening{}'.format(ex) while True: report = session.next() print report if report['class'] == 'TPV': response = client.call.change_position(dict(report))
# -*- coding: utf-8 -*- from bjsonrpc import connect from bjsonrpc.exceptions import ServerError from bjsonrpc.handlers import BaseHandler import settings import time import logging import threading logging.basicConfig( format='%(asctime)s %(levelname)s[%(threadName)s]: %(message)s', level=logging.INFO) class BarStubHandler(BaseHandler): def newBarOrder(self, drink, orderId, simplateId): logging.info("New order id=%d simplate=%s: %s", orderId, simplateId, unicode(drink)) self._conn.method.barOrderDone(orderId) c = connect(host="127.0.0.1", port=settings.BAR_SERVER_PORT, handler_factory=BarStubHandler) c.call.registrate() while True: c.call.ping() c.read_and_dispatch(timeout=5)
def thread1(): time.sleep(.2) conn_socket = bjsonrpc.serialsocket.SerialSocket(serial.Serial('/dev/ttyS1', 115200)) conn = bjsonrpc.connect(sock = conn_socket) conn.call.echo("Hello world") conn.close()
import gps from pprint import pprint import bjsonrpc session = gps.gps("localhost", "2947") session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) client = None try: client = bjsonrpc.connect(host="10.0.0.22", port=9001) except Exception as ex: print 'exception happening{}'.format(ex) while True: report = session.next() if report['class'] == 'TPV': response = client.call.change_position(dict(report))
def thread1(): time.sleep(0.2) conn = bjsonrpc.connect(host="127.0.0.1", port=10123) conn.call.echo("Hello world") conn.close()
import simplejson print "starting ... bsonjrpc" sys.path.insert(0,"..") import bjsonrpc print "ready." from bjsonrpc.handlers import BaseHandler class MyHandler(BaseHandler): def notify(self,text): print "Notify:", text conn = bjsonrpc.connect(host="192.168.3.101",port=10123,handler_factory=MyHandler) def benchmark(): print conn.call.echo('Hello World!') total = 0 count = 0 valuecount = 500 start = time.time() prev = start for i in range(valuecount): randval = i #random.uniform(-100,100) total += randval count += 1 conn.notify.addvalue(randval) new = time.time() if new - prev > 2: