Exemple #1
0
    def __init__(self, address):
        OSCServer.__init__(self, ('', 0))
        self.client.connect(address)
        host, port = self.client.socket.getsockname()

        self.focused = False
        #self.server_host = host
        #self.server_port = port
        self.prefix = DEFAULT_PREFIX

        self.addMsgHandler('default', self.monome_handler)
        self.addMsgHandler('/sys/connect', self.sys_misc)
        self.addMsgHandler('/sys/disconnect', self.sys_misc)
        self.addMsgHandler('/sys/id', self.sys_misc)
        self.addMsgHandler('/sys/size', self.sys_size)
        self.addMsgHandler('/sys/host', self.sys_host)
        self.addMsgHandler('/sys/port', self.sys_port)
        self.addMsgHandler('/sys/prefix', self.sys_prefix)
        self.addMsgHandler('/sys/rotation', self.sys_misc)

        # handshake
        msg = OSCMessage("/sys/host")
        msg.append(host)
        self.client.send(msg)

        msg = OSCMessage("/sys/port")
        msg.append(port)
        self.client.send(msg)

        msg = OSCMessage("/sys/info")
        self.client.send(msg)
    def invoke(self, context, event):
        if context.object:
            SERVER_ADDR = 7113
            self.server = OSCServer(("localhost", SERVER_ADDR))
            self.server.timeout = 0.0001

            self.server.addMsgHandler("/leap/frame/timestamp",
                                      self.log_timestamp)
            self.server.addMsgHandler("/leap/frame/hand/pos", self.move_object)
            self.server.addMsgHandler("/leap/frame/hand/orientation",
                                      self.log_timestamp)
            self.server.addMsgHandler("/quit", self.quit_callback)

            self.first_mouse_x = event.mouse_x
            self.first_value = context.object.location

            context.window_manager.modal_handler_add(self)

            self._timer = context.window_manager.event_timer_add(
                0.001, context.window)

            self.obj = context.object

            return {'RUNNING_MODAL'}
        else:
            self.report({'WARNING'}, "No active object, could not finish")
            return {'CANCELLED'}
def setup():
    print "setup"
    global currentButtonState, lastDownTime, isRecording, audioInput
    global messageQ, clientMap, oscIn, oscOut, oscThread, mAudioServer
    messageQ = PriorityQueue()
    clientMap = {}

    ## setup osc client
    oscOut = OSCClient()

    ## setup osc receiver
    oscIn = OSCServer((OSC_IN_ADDRESS, OSC_IN_PORT))
    oscIn.addMsgHandler('default', _oscHandler)
    oscThread = Thread(target=oscIn.serve_forever)
    oscThread.start()
    print "osc in ready"

    ## setup audio server
    #mAudioServer = ThreadedServer()
    #mAudioServer.start()

    ## setup gpio
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(SWITCH_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
    GPIO.setup(LED_PIN, GPIO.OUT)
    GPIO.output(LED_PIN, GPIO.LOW)
    currentButtonState = GPIO.input(SWITCH_PIN)
    lastDownTime = 0
    isRecording = False

    _setupAudio()
Exemple #4
0
    def __init__(self, joints=None, max_port=5555):
        if joints is None:
            self.joints = [
                'righthand', 'lefthand', 'rightfoot', 'leftfoot', 'head',
                'torso'
            ]
        else:
            self.joints = joints

        self.coords = {k: (0., 0., 0.) for k in self.joints}
        self.prev_coords = {k: (0., 0., 0.) for k in self.joints}
        self.joint_speed = {k: False for k in self.joints}
        self.speed_piano = {
            'lefthand': {
                X: 0,
                Y: 0
            },
            'righthand': {
                X: 0,
                Y: 0
            }
        }
        self.kinect_client = OSCClient()
        self.max_client = OSCClient()
        self.server = OSCServer(('127.0.0.1', 12345))
        self.kinect_client.connect(('127.0.0.1', 12346))
        self.max_client.connect(('127.0.0.1', max_port))
        self.server.addMsgHandler('default', self.process_message)

        self.flipped = False
        self.speed = 0.
        self.speed_ramp = 0.

        sprout(self.server.serve_forever)
        sprout(self._remind_synapse)
Exemple #5
0
    def __init__(self,
                 port=DEFAULT_MUSEIO_PORT,
                 signal=None,
                 ip=DEFAULT_MUSEIO_IP):
        self.signal = signal
        self.port = port
        self.udp_ip = ip

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

        self.server = OSCServer((self.udp_ip, self.port))
        self.server.timeout = 0
        self.current_sample_id = 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/beta_relative/',
                                      self.callback_concentration)
Exemple #6
0
    def __init__(self, id, address):
        OSCServer.__init__(self, ('', 0))
        self.client.connect(address)
        host, port = self.client.socket.getsockname()

        self.id = id
        self.focused = False
        self.prefix = GRIDDLE_PREFIX

        self.addMsgHandler('default', self.waffle_handler)
        self.addMsgHandler('/sys/info', self.sys_misc)
        self.addMsgHandler('/sys/connect', self.sys_misc)
        self.addMsgHandler('/sys/disconnect', self.sys_misc)
        self.addMsgHandler('/sys/id', self.sys_misc)
        self.addMsgHandler('/sys/size', self.sys_size)
        self.addMsgHandler('/sys/host', self.sys_host)
        self.addMsgHandler('/sys/port', self.sys_port)
        self.addMsgHandler('/sys/prefix', self.sys_prefix)
        self.addMsgHandler('/sys/rotation', self.sys_misc)

        self.waffle_send('/sys/host', host)
        self.waffle_send('/sys/port', port)
        self.waffle_send('/sys/info', host, self.server_address[1])

        self.app_callback = None
def setup():
	print "setup"
	global currentButtonState, lastDownTime, isRecording, audioInput
	global messageQ, clientMap, oscIn, oscOut, oscThread, mAudioServer
	messageQ = PriorityQueue()
	clientMap = {}

	## setup osc client
	oscOut = OSCClient()

	## setup osc receiver
	oscIn = OSCServer((OSC_IN_ADDRESS, OSC_IN_PORT))
	oscIn.addMsgHandler('default', _oscHandler)
	oscThread = Thread(target = oscIn.serve_forever)
	oscThread.start()
	print "osc in ready"

	## setup audio server
	mAudioServer = ThreadedServer()
	mAudioServer.start()

	## setup gpio
	GPIO.setmode(GPIO.BCM)
	GPIO.setup(SWITCH_PIN, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
	GPIO.setup(LED_PIN, GPIO.OUT)
	GPIO.output(LED_PIN, GPIO.LOW)
	currentButtonState = GPIO.input(SWITCH_PIN)
	lastDownTime = 0
	isRecording = False

	_setupAudio()
Exemple #8
0
    def __init__(self, id, address):
        OSCServer.__init__(self, ('', 0))
        self.client.connect(address)
        host, port = self.client.socket.getsockname()

        self.id = id
        self.focused = False
        self.prefix = GRIDDLE_PREFIX
        
        self.addMsgHandler('default', self.waffle_handler)
        self.addMsgHandler('/sys/info', self.sys_misc)
        self.addMsgHandler('/sys/connect', self.sys_misc)
        self.addMsgHandler('/sys/disconnect', self.sys_misc)
        self.addMsgHandler('/sys/id', self.sys_misc)
        self.addMsgHandler('/sys/size', self.sys_size)
        self.addMsgHandler('/sys/host', self.sys_host)
        self.addMsgHandler('/sys/port', self.sys_port)
        self.addMsgHandler('/sys/prefix', self.sys_prefix)
        self.addMsgHandler('/sys/rotation', self.sys_misc)
        
        self.waffle_send('/sys/host', host)
        self.waffle_send('/sys/port', port)
        self.waffle_send('/sys/info', host, self.server_address[1])
        
        self.app_callback = None
    def __init__(self, ip):
        """Initialize the server on localhost."""

        avg.Publisher.__init__(self)

        self.__active_skeleton_ids = []

        try:
            self.__server = OSCServer((ip, 27015))
            self.__server.print_tracebacks = True
            # TODO check the ThreadingOSCServer class as possible alternative
        except OSCError:
            print "############################################"
            print "####### could not open OSCServer ###########"
            print "############################################"
            return

        if self.__server is None:
            print "OSC KINECT RECEIVER: server is not initialized"
            return

        print "Kinect receiver: ", self.__server

        self.__server.handle_timeout = types.MethodType(
            self.__handle_timeout, self.__server)
        self.__server.timeout = 0
        self.__server.addMsgHandler("/joint",
                                    self.__on_osc_joint_message_received)
        self.__server.addMsgHandler("/hand",
                                    self.__on_osc_hand_message_received)
        self.__server.addMsgHandler("/kill",
                                    self.__on_osc_kill_message_received)

        self.publish(self.OSC_kinect_MessageID)
        self.publish(self.OSC_kinect_hand_MessageID)
Exemple #10
0
    def __init__(self, address):
        OSCServer.__init__(self, ('', 0))
        self.client.connect(address)
        host, port = self.client.socket.getsockname()

        # print "I believe we have an OSC Server listening on: ",host," ",port
        print port
        
        self.focused = False
        #self.server_host = host
        #self.server_port = port
        self.prefix = DEFAULT_PREFIX

        self.addMsgHandler('default', self.monome_handler)
        self.addMsgHandler('/sys/connect', self.sys_misc)
        self.addMsgHandler('/sys/disconnect', self.sys_misc)
        self.addMsgHandler('/sys/id', self.sys_misc)
        self.addMsgHandler('/sys/size', self.sys_size)
        self.addMsgHandler('/sys/host', self.sys_host)
        self.addMsgHandler('/sys/port', self.sys_port)
        self.addMsgHandler('/sys/prefix', self.sys_prefix)
        self.addMsgHandler('/sys/rotation', self.sys_misc)
        
        # handshake
        msg = OSCMessage("/sys/host")
        msg.append(host)
        self.client.send(msg)
        
        msg = OSCMessage("/sys/port")
        msg.append(port)
        self.client.send(msg)
        
        msg = OSCMessage("/sys/info")
        self.client.send(msg)
Exemple #11
0
    def __init__(self):
        self.radio = radio.radio([0xa7, 0xa7, 0xa7, 0xa7, 0xaa])
        self.swarm = [  #robot.robot([0xa7, 0xa7, 0xa7, 0xa7, 0x01]),
            #robot.robot([0xa7, 0xa7, 0xa7, 0xa7, 0x02]),
            #robot.robot([0xa7, 0xa7, 0xa7, 0xa7, 0x03]),
            #robot.robot([0xa7, 0xa7, 0xa7, 0xa7, 0x04]),
            #robot.robot([0xa7, 0xa7, 0xa7, 0xa7, 0x05]),
            #robot.robot([0xa7, 0xa7, 0xa7, 0xa7, 0x06]),
            #robot.robot([0xa7, 0xa7, 0xa7, 0xa7, 0x07]),
            #robot.robot([0xa7, 0xa7, 0xa7, 0xa7, 0x08]),
            robot.robot([0xa7, 0xa7, 0xa7, 0xa7, 0x09])
        ]

        self.bpm = 150
        self.beat = 0
        self.beats_per_cycle = 1
        self.ms_per_beat = self.bpm_to_mspb(self.bpm)
        self.last_sync = time.time()

        self.weft_swarm = [0, 1, 2, 3]
        self.warp_swarm = [4, 5, 6, 7]
        self.state = "weft-walking"

        self.compiler = yarn.compiler()
        self.osc_server = OSCServer(("0.0.0.0", 8000))
        self.osc_server.timeout = 0
        self.osc_server.addMsgHandler("/sync", sync_callback)
        self.sync_pos = 0

        # load code here
        self.swarm[0].load_asm("../asm/led_flash.asm", self.compiler,
                               self.radio)
Exemple #12
0
def setupServer():
  global server
  server = OSCServer( (HOST_NAME, PORT_NUM) )
  server.timeout = 0
  server.handle_timeout = types.MethodType(handle_timeout, server)
  server.addMsgHandler( "/dmx", user_callback )
  print(server)
Exemple #13
0
    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
        self.current_sample_id = 0
        self.init_time = None
        self.sample_rate = 220.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)
Exemple #14
0
 def __init__(self, address, state):
     self.state = state
     self.server = OSCServer(("", 0))
     self.server.addMsgHandler("default", self.msg_handler)
     self.client = OSCClient(server = self.server)
     self.client.connect((address, self.XAIR_PORT))
     thread.start_new_thread(self.run_server, ())
Exemple #15
0
    def __init__(self):

        global run
        threading.Thread.__init__(self)
        self.daemon = True

        self.server = OSCServer(("localhost", 15000))
        self.server.timeout = 0

        def handle_timeout(self):
            self.time_out = True

        self.server.handle_timeout = types.MethodType(handle_timeout,
                                                      self.server)

        def user_callback(path, tags, args, source):

            global RGB
            global BRIGHTNESS
            #print "here"
            RGB[0] = args[0]
            RGB[1] = args[1]
            RGB[2] = args[2]
            BRIGHTNESS = args[3]

        def quit_callback(path, tags, args, source):

            global run
            run = False

        self.server.addMsgHandler("/colors", user_callback)
        self.server.addMsgHandler("/quit", quit_callback)
def setup():
	global currentButtonState, lastDownTime, isRecording, audioInput
	global messageQ, clientMap, oscIn, oscOut, oscThread
	messageQ = PriorityQueue()
	clientMap = {}

	## setup osc client
	oscOut = OSCClient()

	## setup osc receiver
	oscIn = OSCServer((OSC_IN_ADDRESS, OSC_IN_PORT))
	oscIn.addMsgHandler('default', _oscHandler)
	oscThread = Thread(target = oscIn.serve_forever)
	oscThread.start()
	print "osc in ready"

	## setup gpio
	GPIO.setup(SWITCH_PIN, GPIO.IN)
	GPIO.setup(LED_PIN, GPIO.OUT)
	GPIO.output(LED_PIN, GPIO.LOW)
	currentButtonState = GPIO.input(SWITCH_PIN)
	lastDownTime = 0
	isRecording = False

	## setup audio
	audioInput = None
	try:
		audioInput = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, "default:Headset")
		audioInput.setchannels(1)
		audioInput.setrate(44100)
		audioInput.setformat(alsaaudio.PCM_FORMAT_S16_LE)
		audioInput.setperiodsize(256)
	except:
		print "couldn't start audio device"
		audioInput = None
Exemple #17
0
    def __init__(self, port, cbks=None):
        self.server = OSCServer(("localhost", port))
        self.server.addDefaultHandlers()
        self.thread = threading.Thread(target=self.server.serve_forever)

        if cbks is not None:
            for path, cbk in cbks:
                self.on_msg(path, cbk)
Exemple #18
0
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
Exemple #19
0
 def __init__(self, port, gui):
     OSCServer.__init__(self, ('localhost', port))
     self.app_port = 8000
     self.app_host = "localhost"
     self.prefix = "/monome"
     self.rotation = 0 # FIXME
     self.gui = gui
     
     self.register_syscallbacks()
     self.register_callbacks(self.prefix)
    def setup(self):
        if self.oscServer != None:
            self.destroy()

        ColorTerminal().output(
            "Starting OSC server with host {0} and port {1}".format(
                self.host, self.port))
        self.oscServer = OSCServer((self.host, self.port))
        self.oscServer.handle_timeout = self.handleTimeout
        self.oscServer.addMsgHandler('/marker', self.oscMarkerHandler)
        self.oscServer.addMsgHandler('/rigidbody', self.oscRigidBodyHandler)
        ColorTerminal().success("Server running")
Exemple #21
0
    def _get_osc_test_server(self, port=None):
        def intercepting_handler(addr, tags, data, source):
            msg_string = "%s [%s] %s" % (addr, tags, str(data))
            sys.stdout.write("OSCServer Got: '%s' from %s\n" %
                             (msg_string, getUrlStr(source)))
            self.testQueue.put(data)

        port = port or self.remote_osc_address[1]
        s = OSCServer(('localhost', port))
        s.addMsgHandler('default', intercepting_handler)

        return s
    def _get_osc_test_server(self, port=None):
        def intercepting_handler(addr, tags, data, source):
            msg_string = "%s [%s] %s" % (addr, tags, str(data))
            sys.stdout.write(
                "OSCServer Got: '%s' from %s\n" % (
                    msg_string, getUrlStr(source)
            ))
            self.testQueue.put(data)
        port = port or self.remote_osc_address[1]
        s = OSCServer(('localhost', port))
        s.addMsgHandler('default', intercepting_handler)

        return s
Exemple #23
0
def initOSCServer(ip='127.0.0.1', port=9001, mode=0) :
    """ mode 0 for basic server, 1 for threading server, 2 for forking server
    """
    global server, st

    if mode == 0 :
        server = OSCServer( (ip ,port) ) # basic
    elif mode == 1 : 
        server = ThreadingOSCServer( (ip ,port) ) # threading
    elif mode == 2 :
        server = ForkingOSCServer( (ip ,port) ) # forking

    server.addDefaultHandlers()
def main():
    global server
    
    connected = False

    while not connected:
        try:
            server = OSCServer( ("10.101.203.74", 10000) )
            server.timeout = 0
            run = True
            connected = True

        except: 
            print "OSC Server no encontrado"
            time.sleep(5)

    GPIO.setmode(GPIO.BCM)
    m = Motor([17,18,27,22])

    server.handle_timeout = types.MethodType(handle_timeout, server)

    server.addMsgHandler( "/base", base_move )
    server.addMsgHandler( "/altura", altura_move )

    while(True):
        each_frame()
        try:
            m.rpm = 10
            m.move_to(rotateBase)
            # m.move_to(0)

        except KeyboardInterrupt:
            GPIO.cleanup()   
            print "Saliendo..."
            exit()
 def __init__(self,
              there_host="localhost",
              there_port=7400,
              here_host="localhost",
              here_port=7401,
              debug=False,
              *args,
              **kwargs):
     super(LiveRawAPI, self).__init__(*args, **kwargs)
     self.oscserver = OSCServer((here_host, here_port))
     self.oscclient = OSCClient()
     self.oscclient.connect((there_host, there_port))
     self.oscserver.addMsgHandler('/response', self._handle_response)
     self._incoming = []
Exemple #26
0
    def __init__(self, osc=('0.0.0.0', 8000), mpd=('127.0.0.1', 6600)):
        self.mpc = MPDClient()
        self.mpc.connect(mpd[0], mpd[1])
        self.server = OSCServer(osc)

        def musicManage(addr, tags, data, client_address):
            cmd = addr.strip('/').split('/')[-1]
            self.mpc.__getattr__(cmd)(*data)

        self.server.addMsgHandler('/bearstech/music/play', musicManage)
        self.server.addMsgHandler('/bearstech/music/pause', musicManage)
        self.server.addMsgHandler('/bearstech/music/next', musicManage)
        self.server.addMsgHandler('/bearstech/music/previous', musicManage)
        self.server.addMsgHandler('/bearstech/music/stop', musicManage)
Exemple #27
0
def frame(savePath):
    print 'getting osc'
    # funny python's way to add a method to an instance of a class
    server = OSCServer(("192.168.1.209", 12000))
    server.timeout = 0
    run = True
    server.handle_timeout = types.MethodType(handle_timeout, server)
    server.addMsgHandler("/acc", acc_callback)
    server.addMsgHandler("/e", eul_callback)
    server.addMsgHandler("/raw", raw_callback)
    while True:
        each_frame(server)
        #print 'hello'
        sleep(0.001)
    return
Exemple #28
0
    def _connect(self):
        if self.connected:
            self.logger.warning('already connected')
            return False

        try:
            self.osc_server = OSCServer((self.host(), self.port()))
        except Exception as err:
            # something went wrong, cleanup
            self.connected = False
            self.osc_server = None
            # notify
            self.logger.error("{0}\n\tOSC Server could not start @ {1}:{2}".format(err, self.host(), str(self.port())))
            # abort
            return False

        # register time out callback
        self.osc_server.handle_timeout = self._onTimeout
        self.osc_server.addMsgHandler('default', self._onOscMsg)

        # set internal connected flag
        self.connected = True
        # notify
        self.connectEvent(self)
        self.logger.info("OSC Server running @ {0}:{1}".format(self.host(), str(self.port())))

        if self.threaded:
            self._threadStopFlag = False
            self.thread = threading.Thread(target=self._threadMethod, args=())
            self.thread.start()
            self.logger.info("started separate OSC-listener thread")

        return True
Exemple #29
0
    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)
Exemple #30
0
    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,
            'start': self.event_tracking_start,
            'stop': self.event_tracking_stop,
            'entry': self.event_tracking_entry,
            'exit': self.event_tracking_exit,
            'update': self.event_tracking_update,
            'frame': self.event_tracking_frame,
            '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,
        }

        # add a method to an instance of the class
        import types
        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])
Exemple #31
0
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)
Exemple #32
0
def main(hostname="localhost", port="8000"):
    server = OSCServer((hostname, int(port)))
    server.timeout = 0
    run = True
    global message_count
    message_count = 0

    # this method of reporting timeouts only works by convention
    # that before calling handle_request() field .timed_out is
    # set to False
    def handle_timeout(self):
        self.timed_out = True

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

    def user_callback(path, tags, args, source):
        log("%s %s\n" % (path, args))
        global message_count
        message_count += 1

    def quit_callback(path, tags, args, source):
        #global run
        run = False

    server.addMsgHandler("default", user_callback)
    server.addMsgHandler("/quit", quit_callback)

    # user script that's called by the game engine every frame
    def each_frame():
        log("Messages received: %s\n" % message_count)
        # clear timed_out flag
        server.timed_out = False
        # handle all pending requests then return
        while not server.timed_out:
            server.handle_request()

    # simulate a "game engine"
    print "Server running at %s:%s" % (hostname, port)
    while run:
        # do the game stuff:
        sleep(1)
        # call user script
        each_frame()

    server.close()
Exemple #33
0
    def __init__(self, port, cbks = None):
        self.server = OSCServer( ("localhost", port) )
        self.server.addDefaultHandlers()
        self.thread = threading.Thread(target = self.server.serve_forever)

        if cbks is not None:
            for path, cbk in cbks:
                self.on_msg(path, cbk)
Exemple #34
0
   def __init__(self, from_ip, from_port, to_ip, to_port):
      super(OSCForwarder, self).__init__()

      # create the server to listen to messages arriving at from_ip
      self.server = OSCServer( (from_ip, from_port) )
      self.server.addMsgHandler( 'default', self.callback )

      # create the clieent to forward those message to to_ip
      self.client = OSCClient()
      self.client.connect( (to_ip, to_port) )

      print '%s:%d --> %s:%d' % (from_ip, from_port, to_ip, to_port)

      self.done_running = False

      # start the server listening for messages
      self.start()
    def __init__(self, ip="", port="5103"):

        avg.Publisher.__init__(self)

        try:
            rigidbody_format = config.optitrack_osc_format
            self.__index_id = rigidbody_format.index("id")
            self.__index_x = rigidbody_format.index("x")
            self.__index_y = rigidbody_format.index("y")
            self.__index_z = rigidbody_format.index("z")
            self.__index_roll = rigidbody_format.index("roll")
            self.__index_pitch = rigidbody_format.index("pitch")
            self.__index_yaw = rigidbody_format.index("yaw")
            self.__index_name = rigidbody_format.index("name")
            self.__index_quat_1 = rigidbody_format.index("quat_1")
            self.__index_quat_2 = rigidbody_format.index("quat_2")
            self.__index_quat_3 = rigidbody_format.index("quat_3")
            self.__index_quat_4 = rigidbody_format.index("quat_4")
            self.__osc_format_length = len(rigidbody_format)
            self.__server = OSCServer((ip, int(port)))
            # TODO check the ThreadingOSCServer class as possible alternative

            print "Optitrack:", self.__server

            self.__server.handle_timeout = types.MethodType(
                self.__handle_timeout, self.__server
            )
            self.__server.timeout = 0

            self.__server.addMsgHandler(
                "/tracking/optitrack/rigidbodies", self.__on_osc_rigidbody_message_received
            )
            self.__server.addMsgHandler(
                "/kill", self.__on_osc_kill_message_received
            )

            self.publish(self.OSC_optitrack_MessageID)
            self.publish(self.OSC_optitrack_KillMessageID)
        except OSCError:
            print "############################################"
            print "####### could not open OSCServer ###########"
            print "############################################"
            return
Exemple #36
0
    def setup(self):
        if self.oscServer != None:
            self.destroy()

        ColorTerminal().output("Starting OSC server with host {0} and port {1}".format(self.host, self.port))
        self.oscServer = OSCServer((self.host, self.port))
        self.oscServer.handle_timeout = self.handleTimeout
        self.oscServer.addMsgHandler('/marker', self.oscMarkerHandler)
        self.oscServer.addMsgHandler('/rigidbody', self.oscRigidBodyHandler)
        ColorTerminal().success("Server running")
Exemple #37
0
def main(hostname="localhost",port="8000"):
    server = OSCServer((hostname, int(port)))
    server.timeout = 0
    run = True
    global message_count
    message_count = 0

    # this method of reporting timeouts only works by convention
    # that before calling handle_request() field .timed_out is 
    # set to False
    def handle_timeout(self):
        self.timed_out = True

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

    def user_callback(path, tags, args, source):
        log("%s %s\n" % (path, args))
        global message_count
        message_count += 1

    def quit_callback(path, tags, args, source):
        #global run
        run = False

    server.addMsgHandler( "default", user_callback )
    server.addMsgHandler( "/quit", quit_callback )

    # user script that's called by the game engine every frame
    def each_frame():
        log("Messages received: %s\n" % message_count)
        # clear timed_out flag
        server.timed_out = False
        # handle all pending requests then return
        while not server.timed_out:
            server.handle_request()

    # simulate a "game engine"
    print "Server running at %s:%s" % (hostname, port)
    while run:
        # do the game stuff:
        sleep(1)
        # call user script
        each_frame()

    server.close()
Exemple #38
0
def initOSCServer(ip='127.0.0.1', port=9000, mode=0):
    """ mode 0 for basic server, 1 for threading server, 2 for forking server
    """
    global server, st

    if mode == 0:
        server = OSCServer((ip, port))  # basic
    elif mode == 1:
        server = ThreadingOSCServer((ip, port))  # threading
    elif mode == 2:
        server = ForkingOSCServer((ip, port))  # forking
Exemple #39
0
    def __init__(self, listen_port=7331, timeout=4, timeout_fade_duration=4):
        # create an OSC server and bind it to listen on port 7331
        self.server = OSCServer(("", listen_port))
        self.server.timeout = 0
        self.server.handle_timeout = types.MethodType(
            lambda x: self.handle_timeout(), self.server)

        # Create handlers for "/rgb" and "/hsv".  This causes a packet to "/rgb" to call self.set_rgb()
        # and a packet to "/hsv" to call self.set_hsv(), with the arguments path, tags, args, source
        self.server.addMsgHandler("/rgbw",
                                  lambda p, t, a, s: self.set_rgbw(p, t, a, s))
        self.server.addMsgHandler("/rgb",
                                  lambda p, t, a, s: self.set_rgb(p, t, a, s))
        self.server.addMsgHandler("/r",
                                  lambda p, t, a, s: self.set_r(p, t, a, s))
        self.server.addMsgHandler("/g",
                                  lambda p, t, a, s: self.set_g(p, t, a, s))
        self.server.addMsgHandler("/b",
                                  lambda p, t, a, s: self.set_b(p, t, a, s))
        self.server.addMsgHandler("/w",
                                  lambda p, t, a, s: self.set_w(p, t, a, s))
        self.server.addMsgHandler("/hsv",
                                  lambda p, t, a, s: self.set_hsv(p, t, a, s))
        self.server.addMsgHandler("/h",
                                  lambda p, t, a, s: self.set_h(p, t, a, s))
        self.server.addMsgHandler("/s",
                                  lambda p, t, a, s: self.set_s(p, t, a, s))
        self.server.addMsgHandler("/v",
                                  lambda p, t, a, s: self.set_v(p, t, a, s))

        # Initialize variables
        self.color = Color(0.0, 0.0, 0.0, 0.0)
        self.opacity = 0.0
        self.timeout = timeout
        self.timeout_fade_duration = timeout_fade_duration

        # Setup our animation queue
        self.anim_queue = AnimationQueue()

        # The last time we got a message on our socket
        self.last_msg_time = time.time()
Exemple #40
0
def main():

	if len(sys.argv)>1:
		OSC_ADDRESS = str(sys.argv[1])
	else:
		OSC_ADDRESS = OSC_ADDRESS_DEFAULT

	if len(sys.argv)>2:
		OSC_PORT = int(sys.argv[2])
	else:
		OSC_PORT = OSC_PORT_DEFAULT

	if len(sys.argv)>3:
		WIFI_INT = str(sys.argv[3])
	else:
		WIFI_INT = WIFI_INT_DEFAULT

	#creates directory to store sounds
	if not os.path.exists(sounddir):
		os.makedirs(sounddir)
	print("Sound directory: ",sounddir)

	#example of use of pyosc,
	#see: https://github.com/ptone/pyosc/blob/master/examples/knect-rcv.py
	#we use here the WiFi interface provided on device en0
	ipcmd = "ipconfig getifaddr %s"%WIFI_INT
	print(ipcmd)
	ipaddress = os.popen(ipcmd).read().rstrip()
	print("IP address: ",ipaddress)
	server = OSCServer((ipaddress, OSC_PORT))
	server.timeout = 0
	global run
	run = True

	print("Listening to OSC address",OSC_ADDRESS,"on port",OSC_PORT)

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

	server.addMsgHandler(OSC_ADDRESS, user_callback)

	#sound query engine
	try:
		while run:
			#sleep(1)
			#call user script
			each_frame(server)
	except KeyboardInterrupt: #to quit program
		print("\n")
		pass
	server.close()
Exemple #41
0
    def __init__(self, id, xsize, ysize, port=0):
        OSCServer.__init__(self, ('', port))
        self.id = id
        self.xsize = xsize
        self.ysize = ysize
        self.app_host = DEFAULT_APP_HOST
        self.app_port = DEFAULT_APP_PORT
        self.prefix = DEFAULT_APP_PREFIX

        self.addMsgHandler('default', self.waffle_handler)
        self.addMsgHandler('/sys/port', self.sys_port)
        self.addMsgHandler('/sys/host', self.sys_host)
        self.addMsgHandler('/sys/prefix', self.sys_prefix)

        self.addMsgHandler('/sys/connect', self.sys_misc)
        self.addMsgHandler('/sys/disconnect', self.sys_misc)
        self.addMsgHandler('/sys/rotation', self.sys_misc)

        self.addMsgHandler('/sys/info', self.sys_info)

        self.app_callback = None
Exemple #42
0
    def __init__(self, id, xsize, ysize, port=0):
        OSCServer.__init__(self, ('', port))
        self.id = id
        self.xsize = xsize
        self.ysize = ysize
        self.app_host = DEFAULT_APP_HOST
        self.app_port = DEFAULT_APP_PORT
        self.prefix = DEFAULT_APP_PREFIX
        
        self.addMsgHandler('default', self.waffle_handler)
        self.addMsgHandler('/sys/port', self.sys_port)
        self.addMsgHandler('/sys/host', self.sys_host)
        self.addMsgHandler('/sys/prefix', self.sys_prefix)

        self.addMsgHandler('/sys/connect', self.sys_misc)
        self.addMsgHandler('/sys/disconnect', self.sys_misc)
        self.addMsgHandler('/sys/rotation', self.sys_misc)
        
        self.addMsgHandler('/sys/info', self.sys_info)

        self.app_callback = None
    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()
Exemple #44
0
    def __init__(self):

        self.server = OSCServer(("192.168.2.122", 5005))
        self.server.timeout = 0

        self.driver = DriverAdaMatrix(rows=32, chain=2)
        self.driver.SetPWMBits(6)

        self.led = LEDMatrix(self.driver, 64, 32, serpentine=False)

        self.modes = [
            self.mode_presets, self.color_presets, self.color_gradient,
            self.white_gradient, self.direct_control, self.arcade,
            self.mindfuck
        ]

        self.color = colors.Salmon
        self.wheel = ColorWheel()

        self.running = True

        self.joysticks = [0] * 5

        self.pong = Pong(self.led)

        self.scope = Scope(self.led, self.wheel)

        self.scheme = []

        # funny python's way to add a method to an instance of a class
        # import types
        # self.server.handle_timeout = types.MethodType(lambda: self.handle_timeout(self), self.server)
        self.server.addMsgHandler("/mode", self.mode_callback)
        self.server.addMsgHandler("/coin", self.coin_callback)
        self.server.addMsgHandler("/js", self.joystick_callback)
        self.server.addMsgHandler("/pot", self.pot_callback)
        self.server.addMsgHandler("/fad", self.fader_callback)
        self.server.addMsgHandler("/beam", self.beam_callback)
        self.server.addMsgHandler("/scheme", self.scheme_callback)
        self.server.addMsgHandler("/sleep", self.sleep_callback)
 def setup(self, db, osc, loc):
     self.database = db
     self.oscClient = osc
     self.location = loc
     self.name = "osc"
     self.oscServer = OSCServer((self.oscServerIp,self.oscServerPort))
     ## handler
     self.oscServer.addMsgHandler('default', self._oscHandler)
     ## start server
     self.oscThread = Thread( target = self.oscServer.serve_forever )
     self.oscThread.start()
     ## return
     return True
Exemple #46
0
    def __init__(self, remote_ip=None, pos_type=kBody):
        super(Kinect, self).__init__()

        self.pos_type = pos_type

        # Synapse is running on a remote machine:
        if remote_ip:
            listen_ip = socket.gethostbyname(socket.gethostname())
            listen_port = 12345

            send_ip = remote_ip
            send_port = 12321

        # Synapse is running locally on this machine, using localhost
        else:
            listen_ip = 'localhost'
            listen_port = 12345

            send_ip = 'localhost'
            send_port = 12346

        self.server = OSCServer((listen_ip, listen_port))
        self.server.addMsgHandler('/tracking_skeleton',
                                  self.callback_tracking_skeleton)
        self.server.addMsgHandler('default', self.callback_ignore)

        # create the client, which sends control messages to Synapse
        self.client = OSCClient()
        self.client.connect((send_ip, send_port))

        # member vars
        self.active_joints = {}
        self.last_heartbeat_time = 0
        self.done_running = False

        # start the server listening for messages
        self.start()

        core.register_terminate_func(self.close)
 def __init__(self,
         there_host="localhost",
         there_port=7400,
         here_host="localhost",
         here_port=7401,
         debug=False,
         *args, **kwargs):
     super(LiveRawAPI, self).__init__(*args, **kwargs)
     self.oscserver = OSCServer((here_host, here_port))
     self.oscclient = OSCClient()
     self.oscclient.connect((there_host, there_port))
     self.oscserver.addMsgHandler('/response', self._handle_response)
     self._incoming = []
Exemple #48
0
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
def setup():
    global lastTwitterCheck, myTwitterStream, streamThread
    global lastSmsCheck, mySmsClient, newestSmsSeconds
    global myOscSubscribers, myOscServer, oscThread, myOscClient
    global logFile
    secrets = {}
    myOscSubscribers = {}
    lastTwitterCheck = time()
    lastSmsCheck = time()
    newestSmsSeconds = timegm(gmtime())

    ## read secrets from file
    inFile = open('oauth.txt', 'r')
    for line in inFile:
        (k,v) = line.split()
        secrets[k] = v

    ## start Twitter stream reader
    myTwitterStream = TwitterStreamReceiver(app_key = secrets['CONSUMER_KEY'],
                                            app_secret = secrets['CONSUMER_SECRET'],
                                            oauth_token = secrets['ACCESS_TOKEN'],
                                            oauth_token_secret = secrets['ACCESS_SECRET'])
    streamThread = Thread(target=myTwitterStream.statuses.filter, kwargs={'track':','.join(SEARCH_TERMS)})
    streamThread.start()

    ## start Twilio client
    mySmsClient = TwilioRestClient(account=secrets['ACCOUNT_SID'],
                                   token=secrets['AUTH_TOKEN'])

    myOscClient = OSCClient()
    myOscServer = OSCServer(('127.0.0.1', 8888))
    myOscServer.addMsgHandler('/NotTooPublic/call', oscSubscribeHandler)
    myOscServer.addMsgHandler('default', lambda addr, tags, args, source:None)
    oscThread = Thread(target=myOscServer.serve_forever)
    oscThread.start()

    ## open new file for writing log
    logFile = open("data/"+strftime("%Y%m%d-%H%M%S", localtime())+".log", "a")
Exemple #50
0
class ColorsIn:
# this method of reporting timeouts only works by convention
# that before calling handle_request() field .timed_out is 
# set to False


    def set_colors(self,path, tags, args, source):
        # which user will be determined by path:
        # we just throw away all slashes and join together what's left
        #print "Here's what we got : path:%s tags:%s args:%s source:%s"%(str(path),str(tags),str(args),str(source))
        pixels = []
        for i in range(0,len(args)/3):
            pixel = (clamp(args[i*3]), clamp(args[i*3+1]), clamp(args[i*3+2]))
            pixels.append( pixel )
        #print "Pixels: %s"%str(pixels)
        #print "Time: "+str((time.time()*1000) % 10000)
        octoapi.write(pixels)
        self.lastwrite=time.time()
        self.server.lastpixels = pixels

    def diff_colors(self, path, tags, args, source):
        # which user will be determined by path:
        # we just throw away all slashes and join together what's left
        #print "Here's what we got : path:%s tags:%s args:%s source:%s"%(str(path),str(tags),str(args),str(source))
        pixels = server.lastpixels
        for i in range(0,len(args)/3):
            pp = (args[i*3],args[i*3+1],args[i*3+2])
            p = pixels[i]
            pixels[i] = (clamp(p[0]+pp[0]), clamp(p[1]+pp[1]), clamp(p[2]+pp[2]))
        #print "Pixels: %s"%str(pixels)
        #print "Time: "+str((time.time()*1000) % 10000)
        octoapi.write(pixels)
        self.lastwrite=time.time()
        self.server.lastpixels = pixels

    def each_frame(self):
        self.server.timed_out = False
        while not self.server.timed_out:
            if time.time() - self.lastwrite > CLEAR_TIME:
                self.lastwrite = time.time()
                octoapi.write([(0,0,0)]*24)
                print "Clearing"
            self.server.handle_request()

    def start(self):
        #server = OSCServer( ("128.174.251.39", 11661) )
        self.server = OSCServer( ("localhost", 11661) )
        self.server.timeout = 0
        self.lastwrite = time.time()        
        self.server.handle_timeout = types.MethodType(handle_timeout, self.server)
        self.server.lastpixels = [(0,0,0)]*24

        self.server.addMsgHandler( "/setcolors", self.set_colors)
        self.server.addMsgHandler( "/diffcolors", self.diff_colors)
        while True:
            self.each_frame()

        self.server.close()
Exemple #51
0
    def __init__(self):
        self.radio = radio.radio([0xa7, 0xa7, 0xa7, 0xa7, 0xaa])
        self.swarm = [  #robot.robot([0xa7, 0xa7, 0xa7, 0xa7, 0x01]),
            robot.robot([0xa7, 0xa7, 0xa7, 0xa7, 0x02]),
            robot.robot([0xa7, 0xa7, 0xa7, 0xa7, 0x03]),
            robot.robot([0xa7, 0xa7, 0xa7, 0xa7, 0x04]),
            robot.robot([0xa7, 0xa7, 0xa7, 0xa7, 0x05]),
            #robot.robot([0xa7, 0xa7, 0xa7, 0xa7, 0x06]),
            #robot.robot([0xa7, 0xa7, 0xa7, 0xa7, 0x07]),
            #robot.robot([0xa7, 0xa7, 0xa7, 0xa7, 0x08])
        ]

        self.bpm = 150
        self.beat = 0
        self.beats_per_cycle = 1
        self.ms_per_beat = self.bpm_to_mspb(self.bpm)
        self.last_sync = time.time()
        self.last = ""

        self.compiler = yarn.compiler()
        self.osc_server = OSCServer(("0.0.0.0", 8000))
        self.osc_server.timeout = 0
        self.osc_server.addMsgHandler("/sync", sync_callback)
        self.sync_pos = 0

        self.ms_per_step = (frequency * len(i2c_addrs)) * 1000
        self.ms_per_step /= 8
        print(self.ms_per_step)

        # load code here
        #for r in self.swarm:
        #    r.load_asm("../asm/pm.asm",self.compiler,self.radio)
        #    r.write(13,self.ms_per_step,self.radio)

        self.grid = tangible.sensor_grid(16, layout, tokens)
        self.last = ""
        self.next_address = 0
        self.seq = 0
  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)
Exemple #53
0
    def start(self):
        #server = OSCServer( ("128.174.251.39", 11661) )
        self.server = OSCServer( ("localhost", 11661) )
        self.server.timeout = 0
        self.lastwrite = time.time()        
        self.server.handle_timeout = types.MethodType(handle_timeout, self.server)
        self.server.lastpixels = [(0,0,0)]*24

        self.server.addMsgHandler( "/setcolors", self.set_colors)
        self.server.addMsgHandler( "/diffcolors", self.diff_colors)
        while True:
            self.each_frame()

        self.server.close()
Exemple #54
0
    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()
Exemple #55
0
  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
Exemple #56
0
 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)
Exemple #57
0
   def __init__(self, from_ip, from_port, to_ip, to_port):
      super(OSCForwarder, self).__init__()

      # create the server to listen to messages arriving at from_ip
      self.server = OSCServer( (from_ip, from_port) )
      self.server.addMsgHandler( 'default', self.callback )

      # create the clieent to forward those message to to_ip
      self.client = OSCClient()
      self.client.connect( (to_ip, to_port) )

      print '%s:%d --> %s:%d' % (from_ip, from_port, to_ip, to_port)

      self.done_running = False

      # start the server listening for messages
      self.start()
	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()