当前位置: 首页>>代码示例>>Python>>正文


Python OSCServer.handle_request方法代码示例

本文整理汇总了Python中OSC.OSCServer.handle_request方法的典型用法代码示例。如果您正苦于以下问题:Python OSCServer.handle_request方法的具体用法?Python OSCServer.handle_request怎么用?Python OSCServer.handle_request使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在OSC.OSCServer的用法示例。


在下文中一共展示了OSCServer.handle_request方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: from OSC import OSCServer [as 别名]
# 或者: from OSC.OSCServer import handle_request [as 别名]
def main():
    print("Waiting for boot signal")
    print(s.read())
    print("Writing sway command")
    s.write("".join(map(chr, [0x55, 0x0, 0x3, 0, 2, 72])))
    print(s.read())
    # print("Reading motor encoders")
    # s.write("".join(map(chr, [0x55, 0x1, 0x12])))
    # print(["0x%.02x " % ord(x) for x in s.read(12)])
    server = OSCServer( ("192.168.123.75", 10000) )
    server.timeout = 0
    # funny python's way to add a method to an instance of a class
    import types
    server.handle_timeout = types.MethodType(handle_timeout, server)

    server.addMsgHandler( "/rotate", rotate_callback )
    server.addMsgHandler( "/bf", bf_callback )
    
    try:
        while 1:
            server.handle_request()
    except KeyboardInterrupt:
        pass


    server.close()
开发者ID:chrisspurgeon,项目名称:keepoff,代码行数:28,代码来源:keepoff_osc.py

示例2: main

# 需要导入模块: from OSC import OSCServer [as 别名]
# 或者: from OSC.OSCServer import handle_request [as 别名]
def main():
    print("Waiting for boot signal")
    print(s.read())
    print("Writing sway command")
    s.write("".join(map(chr, [0x55, 0x0, 0x3, 0, 2, 72]))) # equivalent to .join['U', '\x00', '\x03', '\x00', '\x02', 'H']
    # between every elements in the list, put ""
    # that will convert it as one string ''Ux00x03x00x02H''
    print(s.read())
    # print("Reading motor encoders")
    # s.write("".join(map(chr, [0x55, 0x1, 0x12])))
    # print(["0x%.02x " % ord(x) for x in s.read(12)])
    server = OSCServer( ("192.168.123.75", 10000) )
    server.timeout = 0
    # funny python's way to add a method to an instance of a class
    import types
    server.handle_timeout = types.MethodType(handle_timeout, server)

    server.addMsgHandler( "/rotate", rotate_callback )
    server.addMsgHandler( "/bf", bf_callback )
    
    try:
        while 1:
            server.handle_request()
    except KeyboardInterrupt:
        pass


    server.close()
开发者ID:hiyeshin,项目名称:keepoff,代码行数:30,代码来源:keepoff_osc.py

示例3: __init__

# 需要导入模块: from OSC import OSCServer [as 别名]
# 或者: from OSC.OSCServer import handle_request [as 别名]
class OSCServerClass:
  def __init__(self, id, ip, port):
    self.robot = id

    self.bridge = MeccaBridge()

    self.server = OSCServer((ip, port))
    self.server.timeout = 0
    self.active = True
    self.server.handle_timeout = types.MethodType(handle_timeout, self.server)

    self.server.addMsgHandler("/" + self.robot + "/pinMove"  , self.pinMoveHandler  )
    self.server.addMsgHandler("/" + self.robot + "/pinLight" , self.pinLightHandler )
    self.server.addMsgHandler("/" + self.robot + "/init"     , self.initHandler     )
    self.server.addMsgHandler("/" + self.robot + "/headLight", self.headLightHandler)

    self.gotMessage = False
    
#######################################################################

  def run(self):
    print("serving on {}".format(self.server.server_address))
    self.server.running = True
    while self.server.running:
      while True:
        self.server.handle_request()
        if not self.gotMessage:
          break
        self.gotMessage = False

      self.bridge.sendMessages()
      time.sleep(0.01);

######################################################################

  def pinMoveHandler(self, path, tags, args, source):
    #print(path + "\n")
    #print ', '.join(map(str, args))
    self.bridge.sendServoPosition(args[0], args[1], args[2], args[3])
    self.gotMessage = True
 
######################################################################    
       
  def pinLightHandler(self, path, tags, args, source):
    self.bridge.sendPinLight(args[0], args[1], args[2])
    self.gotMessage = True

######################################################################

  def initHandler(self, path, tags, args, source):
    self.bridge.sendInit(args[0], args[1])
    self.gotMessage = True

######################################################################

  def headLightHandler(self, path, targs, args, source):
    self.bridge.sendHeadLight(args[0], args[1], args[2], args[3])
    self.gotMessage = True
开发者ID:yvanvds,项目名称:pianola,代码行数:60,代码来源:OSCServer.py

示例4: OSCPlotter

# 需要导入模块: from OSC import OSCServer [as 别名]
# 或者: from OSC.OSCServer import handle_request [as 别名]
class OSCPlotter(object):

    """Set up OSC server and other handlers."""

    def __init__(self, port, scope):
        host="localhost"
        logger.info( "Initializing server at %s:%d"%(host,port))
        try:
            self.m_oscserver = OSCServer( (host, port) )
        except:
            logger.fatal("System:Unable to create OSC handler at %s:%d"%(host,port),exc_info=True)
            sys.exit(1)
        self.m_oscserver.timeout = 0
        self.m_oscserver.print_tracebacks = True
        self.m_scope = scope
        self.m_fnum = 0
        
        # add a method to an instance of the class
        self.m_oscserver.handle_timeout = types.MethodType(handle_timeout,self.m_oscserver)

        # this registers a 'default' handler (for unmatched messages), 
        # an /'error' handler, an '/info' handler.
        # And, if the client supports it, a '/subscribe' &
        # '/unsubscribe' handler
        self.m_oscserver.addDefaultHandlers()
        self.m_oscserver.addMsgHandler("default", self.default_handler)
        self.m_oscserver.addMsgHandler("/pf/frame", self.pf_frame)
#        self.m_oscserver.addMsgHandler("/pf/update", self.pf_update)
        self.m_oscserver.addMsgHandler("/conductor/attr", self.cond_attr)

    def handle(self):
        self.m_oscserver.handle_request()

    def cond_attr(self, path, tags, args, source):
        attr=args[0]
        uid=args[1]
        value=args[2]
        logger.info("%d.%s=%f"%(uid,attr,value))
        if attr=="kinetic":
            self.m_scope.append(uid,self.m_fnum,value)
            
    def pf_update(self, path, tags, args, source):
        t=args[1]
        uid=args[2]
        x=args[3]
        logger.debug("uid=%d,t=%f, x=%f"%(uid,t,x))
#        self.m_scope.append(uid,t,x)

    def pf_frame(self, path, tags, args, source):
        self.m_fnum=args[0]
        if self.m_fnum%5==0:
            self.m_scope.update(self.m_fnum)
        
    def default_handler(self, path, tags, args, source):
#        logger.debug("got message for "+path+" with tags "+tags)
        return None
开发者ID:wmodes,项目名称:crs,代码行数:58,代码来源:oscplotter.py

示例5: Manta

# 需要导入模块: from OSC import OSCServer [as 别名]
# 或者: from OSC.OSCServer import handle_request [as 别名]
class Manta(object):

    def __init__(self, receive_port=31416, send_port=31417, send_address='127.0.0.1'):
        self.osc_client = OSCClient()
        self.osc_server = OSCServer(('127.0.0.1', receive_port))
        self.osc_client.connect(('127.0.0.1', send_port))
        # set the osc server to time out after 1ms
        self.osc_server.timeout = 0.001
        self.event_queue = []
        self.osc_server.addMsgHandler('/manta/continuous/pad',
                self._pad_value_callback)
        self.osc_server.addMsgHandler('/manta/continuous/slider',
                self._slider_value_callback)
        self.osc_server.addMsgHandler('/manta/continuous/button',
                self._button_value_callback)
        self.osc_server.addMsgHandler('/manta/velocity/pad',
                self._pad_velocity_callback)
        self.osc_server.addMsgHandler('/manta/velocity/button',
                self._button_velocity_callback)

    def process(self):
        self.osc_server.handle_request()
        ret_list = self.event_queue
        self.event_queue = []
        return ret_list

    def _pad_value_callback(self, path, tags, args, source):
        self.event_queue.append(PadValueEvent(args[0], args[1]))

    def _slider_value_callback(self, path, tags, args, source):
        touched = False if args[1] == 0xffff else True
        scaled_value = args[1] / 4096.0
        self.event_queue.append(SliderValueEvent(args[0], touched, scaled_value))

    def _button_value_callback(self, path, tags, args, source):
        pass

    def _pad_velocity_callback(self, path, tags, args, source):
        self.event_queue.append(PadVelocityEvent(args[0], args[1]))

    def _button_velocity_callback(self, path, tags, args, source):
        self.event_queue.append(ButtonVelocityEvent(args[0], args[1]))

    def _send_osc(self, path, *args):
        msg = OSCMessage(path)
        msg.append(args)
        self.osc_client.send(msg)

    def set_led_enable(self, led_type, enabled):
        self._send_osc('/manta/ledcontrol', led_type, 1 if enabled else 0)

    def set_led_pad(self, led_state, pad_index):
        self._send_osc('/manta/led/pad', led_state, pad_index)
开发者ID:ssfrr,项目名称:buffering,代码行数:55,代码来源:manta.py

示例6: OscServerThread

# 需要导入模块: from OSC import OSCServer [as 别名]
# 或者: from OSC.OSCServer import handle_request [as 别名]
	class OscServerThread(Thread):
		def __init__(self, host, stopEvent):
			Thread.__init__(self)
			self.server = OSCServer(host)
			self.stopEvent = stopEvent
		def setCallBacks(self, callBacks):
			for callBack in callBacks:
				self.server.addMsgHandler(callBack[0], callBack[1])
		def run(self):
			while not self.stopEvent.is_set():
				self.server.handle_request()
			self.server.close()
开发者ID:FlamingLotusGirls,项目名称:FireSculptureController,代码行数:14,代码来源:Osc.py

示例7: app

# 需要导入模块: from OSC import OSCServer [as 别名]
# 或者: from OSC.OSCServer import handle_request [as 别名]
def app():
    global dxlIO, server, client
    ports = pypot.dynamixel.get_available_ports()
    if not ports:
        raise IOError('No port available.')
    dxlIO = pypot.dynamixel.DxlIO(ports[0])
    availableIDs = dxlIO.scan()
    server = OSCServer(('0.0.0.0', 8000))
    for motorID in availableIDs:
        server.addMsgHandler('/motor/' + str(motorID), motorHandler) # Register OSC handlers for each found ID
    client = OSCClient()
    client.connect(('localhost', 8001))
    print 'Ready. Found ID(s) ' + str(availableIDs)
    while True:
        server.handle_request()
        sleep(0.01)
开发者ID:ianisl,项目名称:DOS,代码行数:18,代码来源:app.py

示例8: ServerLighthouse

# 需要导入模块: from OSC import OSCServer [as 别名]
# 或者: from OSC.OSCServer import handle_request [as 别名]
class ServerLighthouse(object):

    def __init__(self, address='192.168.1.145', recvPort=recvPort):

        self.address = address
        self.recvPort = recvPort

        # Setup a reciever for OSC.
        self.server = OSCServer((self.address, self.recvPort))
        self.server.timeout = 0
        self.server.handleTimeout = types.MethodType(self.handleTimeout, self.server)

        # Startup light
        self.intitializeLight()

    def handleTimeout(self):
        self.timedOut = True

    def eachFrame(self):
        # clear timed_out flag
        self.server.timed_out = False

        # handle all pending requests then return
        while not self.server.timed_out:
            self.server.handle_request()

    def handleEvent(self, address, functionToCall):
        def internalFunction(path, tags, args, source):
            arg = int(args[0])
            functionToCall(arg)

        def internalFunctionZ(path, tags, args, source):
            pass

        self.server.addMsgHandler(address, internalFunction)
        self.server.addMsgHandler('%s/z' % address, internalFunctionZ)
开发者ID:BRLighthouse,项目名称:lighthouse_lamp-bku,代码行数:38,代码来源:oscrecv.py

示例9: MuseIO

# 需要导入模块: from OSC import OSCServer [as 别名]
# 或者: from OSC.OSCServer import handle_request [as 别名]
class MuseIO():
    def __init__(self, port=5001, signal=None, viewer=None):
        self.signal = signal
        self.viewer = viewer
        self.game = None
        self.port = port
        self.udp_ip = '127.0.0.1'

        self.server = OSCServer((self.udp_ip, self.port))
        self.server.timeout = 0

        # funny python's way to add a method to an instance of a class
        self.server.handle_timeout = types.MethodType(handle_timeout, self.server)

        # add message handlers
        if 'eeg' in self.signal:
            self.server.addMsgHandler('/muse/eeg', self.callback_eeg_raw)
        if 'concentration' in self.signal:
            self.server.addMsgHandler('/muse/elements/experimental/concentration', self.callback_concentration)
        if 'mellow' in self.signal:
            self.server.addMsgHandler('/muse/elements/experimental/mellow', self.callback_mellow)
        self.server.addMsgHandler("default", self.default_handler)

    def default_handler(self, addr, tags, stuff, source):
        # nothing to do here. This function is called for all messages that are not supported by the application.
        print "SERVER: No handler registered for ", addr
        return None

    def callback_eeg_raw(self, path, tags, args, source):
        # which user will be determined by path:
        # we just throw away all slashes and join together what's left
        # tags will contain 'ffff'
        # args is a OSCMessage with data
        # source is where the message came from (in case you need to reply)
        self.signal['eeg'].add_time()
        self.signal['eeg'].add_l_ear(args[0])
        self.signal['eeg'].add_l_forehead(args[1])
        self.signal['eeg'].add_r_forehead(args[2])
        self.signal['eeg'].add_r_ear(args[3])
        if 'eeg' in self.viewer:
            self.viewer['eeg'].refresh()
        #print args[0], args[1], args[2], args[3]

    def callback_concentration(self, path, tags, args, source):
        if 'concentration' in self.signal:
            self.signal['concentration'].add_time()
            self.signal['concentration'].add_concentration(args[0])
            self.viewer['concentration-mellow'].refresh()
            #self.game.change_velocity(self.signal['concentration'].concentration)

    def callback_mellow(self, path, tags, args, source):
        if 'mellow' in self.signal:
            self.signal['mellow'].add_time()
            self.signal['mellow'].add_mellow(args[0])
            self.viewer['concentration-mellow'].refresh()

    def handle_request(self):
        # clear timed_out flag
        self.server.timed_out = False
        # handle all pending requests then return
        while not self.server.timed_out:
            self.server.handle_request()

    def start(self, freq=220):
        update_timing = 1.0/float(freq)
        while True:
            sleep(update_timing)
            self.handle_request()
开发者ID:pumpikano,项目名称:pyMuse,代码行数:70,代码来源:ios.py

示例10: __init__

# 需要导入模块: from OSC import OSCServer [as 别名]
# 或者: from OSC.OSCServer import handle_request [as 别名]
class Main:
  roll = 0.0
  pitch = 0.0
  yawrate = 0
  thrust = 10001

  def __init__(self):

    self.server = OSCServer (("0.0.0.0", 8000))
    self.server.addMsgHandler("/1/rollpitch", self.roll_pitch_callback)
    self.server.addMsgHandler("/1/yawthrust", self.yaw_thrust_callback)
    self.server.addMsgHandler("/1/stop", self.stop_callback)
    self.server.addMsgHandler("/1/hovermode", self.hovermode_callback)
  

    self.crazyflie = Crazyflie()
    cflib.crtp.init_drivers()

    available_radios = cflib.crtp.scan_interfaces()
    print available_radios
    #For now assume we want the 1st radio
    radio = available_radios[0][0]
    
    #Connect to the flie
    self.crazyflie.open_link(radio)

    self.crazyflie.connectSetupFinished.add_callback(self.connectSetupFinished)
    self.crazyflie.connectionFailed.add_callback(self.connectionLost)
    self.crazyflie.connectionLost.add_callback(self.connectionLost)

  def connectSetupFinished(self, linkURI):

    Thread(target=self.send_setpoint_loop).start()
    Thread(target=self.osc_loop).start()
    self.crazyflie.param.set_value("stabilizer.debug", "0")
    self.crazyflie.param.add_update_callback("stabilizer.debug", self.paramUpdateCallback)
    self.crazyflie.param.add_update_allback("stabilizer.mode", self.paramUpdateCallback)


  def paramUpdateCallback(self, name, value):
    print "%s has value %d" % (name, value)

  def accel_log_callback(self, data):
    logging.info("Accelerometer: x+%.2f, y=%.2f, z=%.2f" % (data["acc.x"], data["acc.y"], data["acc.z"]))

  def osc_loop(self):
    while True:
      self.server.handle_request()

  def roll_pitch_callback(self, path, tags, args, source):
    #print ("path", path)
    #print ("args", args)
    #print ("source", source)
    print "ROLL", args[0]
    #self.roll=(args[0]*180)-90
    self.roll=(args[0]*90)-45
    print "PITCH", args[1]
    #self.pitch=(180*args[1])-90
    self.pitch=(args[1]*90)-45
  def yaw_thrust_callback(self, path, tags, args, source):
    #print ("path", path)
    #print ("args", args)
    #print ("source", source)
    print "YAW", (180*args[1])-90
    print "THRUST", (49999*args[0])+10001
    self.thrust = (49999*args[0]) + 10001
    self.yawrate = (args[1]*90)-45
  def stop_callback(self, path, tags, args, source):
    self.crazyflie.param.set_value("stabilizer.debug", "1")
    self.thrust = 0
    self.send_setpoint()
    self.crazyflie.close_link()
    exit()
  def hovermode_callback(self, path, tags, args, source):
    if args[0]:
      logging.info("Entering hover mode.")
      self.crazyflie.param.set_value("stabilizer.mode", "1")
    else:
      logging.info("Exiting hover mode.")
      self.crazyflie.param.set_value("stabilizer.mode", "0")


  def send_setpoint_loop(self):
    while True:
      self.send_setpoint()
      time.sleep(0.1)

  def send_setpoint(self):
    self.crazyflie.commander.send_setpoint(self.roll, self.pitch, self.yawrate, self.thrust)

  def connectionLost(self, linkURI):
    print "CONNECTION LOST!"
    exit()
开发者ID:gitwikta,项目名称:crazyflie-tinkering,代码行数:95,代码来源:cfcontrol.py

示例11: OSCHandler

# 需要导入模块: from OSC import OSCServer [as 别名]
# 或者: from OSC.OSCServer import handle_request [as 别名]

#.........这里部分代码省略.........

        # to conductor
        self.m_oscserver.addMsgHandler( "/conductor/dump",self.event_conduct_dump)
        # global sensitivity for conx attr
        self.m_oscserver.addMsgHandler( "/ui/condglobal",self.event_ui_condglobal)
        # global sensitivity for cell attr
        self.m_oscserver.addMsgHandler( "/ui/cellglobal",self.event_ui_cellglobal)

        for atype in CELL_ATTR_TYPES + CONX_ATTR_TYPES:
            for param in ("trigger", "memory", "maxage","qual","qualmin","qualmax"):
                self.m_oscserver.addMsgHandler("/ui/cond/"+atype+"/"+param,self.event_ui_condparam)

        # add a method to an instance of the class
        self.m_oscserver.handle_timeout = types.MethodType(handle_timeout, self.m_oscserver)

        # this registers a 'default' handler (for unmatched messages), 
        # an /'error' handler, an '/info' handler.
        # And, if the client supports it, a '/subscribe' &
        # '/unsubscribe' handler
        self.m_oscserver.addDefaultHandlers()
        self.m_oscserver.addMsgHandler("default", self.default_handler)

        # TODO: Handle errors from OSCServer
        #self.m_oscserver.addErrorHandlers()
        #self.m_oscserver.addMsgHandler("error", self.default_handler)

        self.honey_im_home()

    def each_frame(self):
        # clear timed_out flag
        self.m_oscserver.timed_out = False
        # handle all pending requests then return
        while not self.m_oscserver.timed_out:
            self.m_oscserver.handle_request()

    def user_callback(self, path, tags, args, source):
        # which user will be determined by path:
        # we just throw away all slashes and join together what's left
        user = ''.join(path.split("/"))
        # tags will contain 'fff'
        # args is a OSCMessage with data
        # source is where the message came from (in case you need to reply)
        logger.debug("user_callback( "+str(user)+" "+str(tags)+" "+str(args)+" "+str(source))

    def quit_callback(self, path, tags, args, source):
        # don't do this at home (or it'll quit blender)
        self.m_run = False

    #
    # General OUTGOING
    #

    def send_to(self, clientkey, path, args):
        """Send OSC Message to one client."""
        try:
            self.m_osc_clients[clientkey].send(OSCMessage(path,args))
            if args:
                logger.debug( "Send to %s: %s %s" ,clientkey,path,args)
        except:
            lastError=self.m_downClients.get(clientkey,0)
            if time()-lastError >30:
                logger.warning("send_to: Unable to reach host %s (will suppress this warning for 30 seconds)",clientkey,exc_info=False)
                self.m_downClients[clientkey]=time()
            return False
        return True
开发者ID:wmodes,项目名称:crs,代码行数:69,代码来源:oschandler.py

示例12: OSCHandler

# 需要导入模块: from OSC import OSCServer [as 别名]
# 或者: from OSC.OSCServer import handle_request [as 别名]
class OSCHandler(object):

    """Set up OSC server and other handlers."""

    def __init__(self, field):
        self.m_field = field
        self.m_server = OSCServer( (OSCHOST, OSCPORT) )
        self.m_server.timeout = OSCTIMEOUT
        self.m_run = True

        self.m_xmin = 0
        self.m_ymin = 0
        self.m_xmax = 0
        self.m_ymax = 0

        self.eventfunc = {
            'ping': self.event_tracking_ping,
            'ack': self.event_tracking_ack,
            'start': self.event_tracking_start,
            'entry': self.event_tracking_entry,
            'exit': self.event_tracking_exit,
            'frame': self.event_tracking_frame,
            'stop': self.event_tracking_stop,
            'minx': self.event_tracking_set,
            'miny': self.event_tracking_set,
            'maxx': self.event_tracking_set,
            'maxy': self.event_tracking_set,
            'npeople': self.event_tracking_set,
            'groupdist': self.event_tracking_set,
            'ungroupdist': self.event_tracking_set,
            'fps': self.event_tracking_set,
            'update': self.event_tracking_update,
            'leg': self.event_tracking_leg,
            'body': self.event_tracking_body,
        }

        # add a method to an instance of the class
        self.m_server.handle_timeout = types.MethodType(handle_timeout, self.m_server)

        for i in self.eventfunc:
            self.m_server.addMsgHandler(OSCPATH[i], self.eventfunc[i])

        # this registers a 'default' handler (for unmatched messages), 
        # an /'error' handler, an '/info' handler.
        # And, if the client supports it, a '/subscribe' &
        # '/unsubscribe' handler
        self.m_server.addDefaultHandlers()
        self.m_server.addMsgHandler("default", self.default_handler)
        # TODO: Handle errors from OSCServer
        #self.m_server.addErrorHandlers()
        #self.m_server.addMsgHandler("error", self.default_handler)
        self.honey_im_home()

    def honey_im_home(self):
        """Broadcast a hello message to the network."""
        # TODO: Broadcast hello message
        return True

    def each_frame(self):
        # clear timed_out flag
        self.m_server.timed_out = False
        # handle all pending requests then return
        while not self.m_server.timed_out:
            self.m_server.handle_request()

    def user_callback(self, path, tags, args, source):
        # which user will be determined by path:
        # we just throw away all slashes and join together what's left
        user = ''.join(path.split("/"))
        # tags will contain 'fff'
        # args is a OSCMessage with data
        # source is where the message came from (in case you need to reply)
        if dbug.LEV & dbug.MSGS: print ("Now do something with", user,args[2],args[0],1-args[1]) 

    def quit_callback(self, path, tags, args, source):
        # don't do this at home (or it'll quit blender)
        self.m_run = False

    # Event handlers

    def default_handler(self, path, tags, args, source):
        if dbug.LEV & dbug.MORE: print "OSC:default_handler:No handler registered for ", path
        return None

    def event_tracking_ping(self, path, tags, args, source):
        if dbug.LEV & dbug.MSGS: print "OSC:event_ping:code",args[0]
        return None

    def event_tracking_ack(self, path, tags, args, source):
        if dbug.LEV & dbug.MSGS: print "OSC:event_ack:code",args[0]
        return None

    def event_tracking_start(self, path, tags, args, source):
        """Tracking system is starting.

        Sent before first /pf/update message for that target
        args:
            [ aparently no params now]
            samp - sample number
            t - time of sample (elapsed time in seconds since beginning of run)
#.........这里部分代码省略.........
开发者ID:jestinbrooks,项目名称:crs,代码行数:103,代码来源:oschandlers.py

示例13: designer

# 需要导入模块: from OSC import OSCServer [as 别名]
# 或者: from OSC.OSCServer import handle_request [as 别名]
	
	
#These are all the add-ons that you can name in the TouchOSC layout designer (you can set the values and directories)
server.addMsgHandler("redfader",faderR)
server.addMsgHandler("greenfader",faderG)
server.addMsgHandler("bluefader",faderB)
server.addMsgHandler("numfader",faderN)
server.addMsgHandler("colorcycle1",ccButton)
server.addMsgHandler("cyclestep",ccStepFader)
server.addMsgHandler("dotOnOff",dotButton)
server.addMsgHandler("dotXY",dotPosition)

# main loop
while True:
	# read data
	server.handle_request()
	
	if isCycling:
		cycleColor()

	pixels = [ (0,0,0) ] * maxNum
	for i in range(num):
		if i == dotIndex:
			if isDot:
				pixels[i] = (255,255,255)
			else:
				pixels[i] = (r,b,g)
		else:
			pixels[i] = (r,b,g)
	opcClient.put_pixels(pixels)
	print "r:%i g:%i b:%i num:%i " % (r,g,b,num)
开发者ID:ryantuck,项目名称:table,代码行数:33,代码来源:colorCycling.py

示例14: Server

# 需要导入模块: from OSC import OSCServer [as 别名]
# 或者: from OSC.OSCServer import handle_request [as 别名]
class Server():

    """Listener to collect results of Keykit server.

    (Adaption of OSC package example.)
    """

    def __init__(self, server_adr):
        self.server = OSCServer(server_adr)
        self.server.socket.settimeout(3)
        self.run = True
        self.timed_out = False

        # funny python's way to add a method to an instance of a class
        # import types
        # self.server.handle_timeout = types.MethodType(
        #   self.handle_timeout, self.server)
        # or
        self.server.handle_timeout = self.handle_timeout

        # Handler
        self.server.addMsgHandler("/quit", self.quit_callback)
        self.server.addMsgHandler("/keykit/pyconsole/out", self.print_callback)
        self.server.addMsgHandler("/keykit/pyconsole/err", self.err_callback)
        self.server.addMsgHandler(
            "/keykit/pyconsole/start",
            self.print_callback)
        self.server.addMsgHandler("/keykit/pyconsole/lsdir", self.dir_callback)

    def handle_timeout(self, server=None):
        self.timed_out = True

    def each_frame(self):
        # clear timed_out flag
        self.timed_out = False
        # handle all pending requests then return
        while not self.timed_out and self.run:
            self.server.handle_request()
            # Line reached after each socket read
            sleep(.05)

    def start(self):
        # print("Wait on client input...")
        sys.stdout.write("%s" % (MY_PROMPT))
        sys.stdout.flush()
        while self.run:
            self.each_frame()
            # Line reached after each socket timeout
            sleep(1)

    def stop(self):
        self.run = False
        # Invoke shutdown. Socket still wait on timeout...
        try:
            import socket
            self.server.socket.shutdown(socket.SHUT_RDWR)
        except socket.error:
            pass

        self.server.close()

    # Callbacks
    def quit_callback(self, path, tags, args, source):
        self.run = False

    def print_callback(self, path, tags, args, source, textColor=ColorOut):
        current_input = readline.get_line_buffer()

        # Add Tab at every input line
        out = args[0].replace("\n", "\n\t")

        # Delete current input, insert output and add input again.
        # \r : Carriage return, \033[K : Delete everything after the cursor.
        sys.stdout.write("\r\033[K")
        sys.stdout.write(
            "\t%s%s%s\n%s%s" %
            (textColor,
             out,
             ColorReset,
             MY_PROMPT,
             current_input))
        sys.stdout.flush()

    def err_callback(self, path, tags, args, source):
        """ Same as print_callback but mark output as error. """
        self.print_callback(path, tags, args, source, ColorWarn)

    def dir_callback(self, path, tags, args, source):
        """ Store current working dir for tab completion.
            This is mainly releated to chdir() and lsdir().
        """
        lsdir_string_part = args[0]
        if lsdir_string_part[0] == "^":
            self.keykit_lsdir_string = lsdir_string_part
        else:
            self.keykit_lsdir_string += lsdir_string_part

        if self.keykit_lsdir_string[-1] == "$":
            try:
                lsdir = []
#.........这里部分代码省略.........
开发者ID:YggdrasiI,项目名称:Pyconsole,代码行数:103,代码来源:keykit_console.py

示例15: MuseIO

# 需要导入模块: from OSC import OSCServer [as 别名]
# 或者: from OSC.OSCServer import handle_request [as 别名]
class MuseIO():
    def __init__(self, port=5001, signal=None):
        self.signal = signal
        self.port = port
        self.udp_ip = '127.0.0.1'

        if not has_oscserver:
            raise Exception('ERROR: OSC not found')

        self.server = OSCServer((self.udp_ip, self.port))
        self.server.timeout = 0

        # funny python's way to add a method to an instance of a class
        self.server.handle_timeout = types.MethodType(handle_timeout, self.server)

        # add message handlers
        if 'eeg' in self.signal:
            self.server.addMsgHandler('/muse/eeg', self.callback_eeg_raw)
        if 'concentration' in self.signal:
            self.server.addMsgHandler('/muse/elements/experimental/concentration', self.callback_concentration)
        if 'mellow' in self.signal:
            self.server.addMsgHandler('/muse/elements/experimental/mellow', self.callback_mellow)
        self.server.addMsgHandler("default", self.default_handler)

    def default_handler(self, addr, tags, stuff, source):
        # nothing to do here. This function is called for all messages that are not supported by the application.
        #print "SERVER: No handler registered for ", addr
        return None

    def callback_eeg_raw(self, path, tags, args, source):
        # which user will be determined by path:
        # we just throw away all slashes and join together what's left
        # tags will contain 'ffff'
        # args is a OSCMessage with data
        # source is where the message came from (in case you need to reply)
        self.signal['eeg'].lock.acquire()
        self.signal['eeg'].add_data(args)
        self.signal['eeg'].lock.release()

    def callback_concentration(self, path, tags, args, source):
        if 'concentration' in self.signal:
            self.signal['concentration'].add_time()
            self.signal['concentration'].add_concentration(args[0])
            #self.game.change_velocity(self.signal['concentration'].concentration)

    def callback_mellow(self, path, tags, args, source):
        if 'mellow' in self.signal:
            self.signal['mellow'].add_time()
            self.signal['mellow'].add_mellow(args[0])

    def handle_request(self):
        # clear timed_out flag
        self.server.timed_out = False
        # handle all pending requests then return
        while not self.server.timed_out:
            self.server.handle_request()

    def start(self, freq=220):
        update_timing = 1.0/float(freq)
        while True:
            try:
                time.sleep(update_timing)
                self.handle_request()
            except KeyboardInterrupt:
                import sys
                print('KeyboardInterrupt on line {}'.format(sys.exc_info()[-1].tb_lineno))
                sys.exit(2)
            except Exception as e:
                import sys
                print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno))
                print(str(e))
                sys.exit(2)
开发者ID:PolyCortex,项目名称:pyMuse,代码行数:74,代码来源:ios.py


注:本文中的OSC.OSCServer.handle_request方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。