示例#1
0
class PacketManager(object):
    def __init__(self, num_datapoints, port=DEFAULTPORT):
        self.num_datapoints = num_datapoints
        self.data_source = None
        self.client = OSCClient()
        self.client.connect(("localhost", port))

    def add_data_source(self, data_source):
        self.data_source = data_source

    def send_to_max(self):
        bundle = OSCBundle()
        for i in range(NUM_CAPS_AND_POTS):
            bundle.append({
                'addr': "/d" + str(i) + "/hz",
                'args': self.data_source.get_pitch_data(i)
            })
            bundle.append({
                'addr': "/d" + str(i) + "/on",
                'args': self.data_source.get_cap_data(i)
            })
        bundle.append({
            'addr': "/duration",
            'args': self.data_source.get_duration_data()
        })
        bundle.append({
            'addr': "/mod",
            'args': self.data_source.get_mod_data()
        })
        self.client.send(bundle)
示例#2
0
class oscSender(object):

	def __init__(self,port):
		self.client = OSCClient()
		self.client.connect( ("172.16.1.110", port) )
		print "Started server on port : " + str(port)

	def newNode(self,args,BSSID,kind):
		msg = OSCMessage("/new" )
		msg.append(kind.strip())
		msg.append(args)
		msg.append(BSSID.strip()) 
		self.client.send(msg)
		# print "new"

	def updateNode(self,args,BSSID,kind):
		if BSSID == " ":
			return 
		msg =  OSCMessage("/update")
		msg.append(kind.strip())
		msg.append(args)
		msg.append(BSSID.strip()) 
		self.client.send(msg)
		# print "update"

	def removeNode(self,args,BSSID, kind):
		msg =  OSCMessage("/remove")
		msg.append(kind.strip())
		msg.append(args)
		msg.append(BSSID.strip())  
		self.client.send(msg)

	def closeConnection(self):
		self.client.send( OSCMessage("/quit", args ) )
示例#3
0
class SendOSC(object):

    def __init__(self):
        self.osc_message = None
        self.osc_client = OSCClient()
        self.osc_message = OSCMessage()        
        
        self.ip = ""
        self.port = 0

    def connect(self, ip="localhost", port=8080):
        self.ip = ip
        self.port = port
        self.osc_client.connect((self.ip, self.port))

    def send(self, address, value):
        self.osc_message.setAddress(address)
        self.osc_message.append(value)
        self.osc_client.send(self.osc_message)

    def send_distane(self, distance):
        oscdump = "/dumpOSC/DistanceTipTarget"
        self.send(oscdump, distance)

    def send_needle_tip_position(self, x, y, z):
        oscdump = "/dumpOSC/needltip/x"
        self.send(oscdump, x)
        oscdump = "/dumpOSC/needltip/y"
        self.send(oscdump, y)
        oscdump = "/dumpOSC/needltip/z"
        self.send(oscdump, z)
示例#4
0
def setup():

    # OSC
    global client
    client = OSCClient()
    client.connect(("localhost", 7300))

    # DISPLAY
    window_width = 640
    window_height = 480

    # OPENCV
    # img = cv2.imread(filename)
    global camera
    camera = cv2.VideoCapture(0)
    camera.set(3, window_width)
    camera.set(4, window_height)
    # ds_factor = 1.0

    # FACIAL FEATURES DETECTORS
    global face_detector, mouth_detector, smile_detector, nose_detector, right_eye_detector, left_eye_detector
    face_detector = FaceDetector()
    # eye_detector = EyeDetector()
    mouth_detector = MouthDetector()
    smile_detector = SmileDetector()
    nose_detector = NoseDetector()
    # right_ear_detector = RightEarDetector()
    right_eye_detector = RightEyeDetector()
    left_eye_detector = LeftEyeDetector()
    def messageServer(self, messagePath, argument):
        client = OSCClient()
        client.connect((self.serverIP, self.serverPort))
        message = OSCMessage(messagePath)
        message.append(argument)

        client.send(message)
示例#6
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)
示例#7
0
def main():
    global client, group, clientOSC
    try:
        rospy.init_node("test_move", anonymous=True, disable_signals=True)
        client = actionlib.SimpleActionClient('follow_joint_trajectory', FollowJointTrajectoryAction)
        print "Waiting for server..."
        client.wait_for_server()
        print "Connected to server"
        parameters = rospy.get_param(None)

        print "============ Starting tutorial setup"

        moveit_commander.roscpp_initialize(sys.argv)
        time.sleep(1)
        robot = moveit_commander.RobotCommander()
        group = moveit_commander.MoveGroupCommander("manipulator")

        clientOSC = OSCClient()
        clientOSC.connect( ("192.168.1.51", 12000) )


        thread.start_new_thread ( printRoll, () )
        move1()
    except KeyboardInterrupt:
        rospy.signal_shutdown("KeyboardInterrupt")
        raise
示例#8
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, ())
示例#9
0
文件: TUIO.py 项目: Tititesouris/pje
 def __init__(self, address="localhost", port=3333):
     self.address = "localhost"
     self.port = 3333
     self.client = OSCClient()
     self.client.connect((address, port))
     self.fseqCount = -1
     self.alive = []
示例#10
0
def init(osc_setup):
    host, port, root = osc_setup
    client = OSCClient()
    client.connect((host, port))
    print "Connected to the OSC server %s:%s%s" % osc_setup
    send_parameter('osd_initialized', 'Done')
    return client
示例#11
0
 def send_oscbundle(self):
     # send a bundle with current bpm and polar coordinates of 
     # sound-objects relative to player
     #            /game/bpm
     client = OSCClient()
     bpm = OSCMessage()     
     bpm.setAddress("/game/bpm")
     bpm.append(self.player['bpm'])   
     bundle = OSCBundle()
     bundle.append(bpm)
     #            /game/sndobj/id-bola (ang, mod)  
     scn = bge.logic.getCurrentScene()
     play = scn.objects["player"]
     
     for ball in self.soundobjects:
         ballpos = ball.worldPosition
         vect = mathutils.Vector((0,1))
         dist = play.getVectTo(ballpos)[0]
         vect2 = play.getVectTo(ballpos)[2].to_2d()
         angle = math.degrees(-vect.angle_signed(vect2))
         #print("angle ", angle, "distancia ",dist)
         data = (angle, dist)
         # append data to bundle
         msg = OSCMessage()
         tag = "/game/sndobj/position/" + str(ball['id'])
         msg.setAddress(tag)
         msg.append(data)
         bundle.append(msg)
         #print(msg)
     #gl.client is a tuple in gl with ip and port
     client.sendto(bundle, gl.send_to)
示例#12
0
def init(osc_setup):
    host, port, root = osc_setup
    client = OSCClient()
    client.connect( (host, port) )
    print "Connected to the OSC server %s:%s%s" %osc_setup
    send_parameter('osd_initialized','Done')
    return client
示例#13
0
class slOscSend:
    """ Osc Sender """
    def __init__(self, adr, port):
        self.ip_adr = adr
        self.port = port
        self.destination = (self.ip_adr, self.port)
        #         self.client = OSC.OSCClient()
        self.client = OSCClient()
        self.client.connect(self.destination)
        self.adr = "/unset"
        self.str = 'IP: '
        self.str += self.ip_adr
        self.str += ' PORT: '
        self.str += str(port)
        print(self.str)

    def send(self, adr, *args):
        self.adr = adr
        #         msg = OSC.OSCMessage()
        msg = OSCMessage()
        msg.setAddress(self.adr)
        for i in args:
            msg.append(i)
        try:
            self.client.send(msg)
        except:
            print ">>> ERR :: Could not connect to ", self.ip_adr, ":", self.port
def main():
    global bRun
    global inOSCport, outOSCport
    global myOSC_Server, myOSC_Client

    global cTrial, nTrials, breaksxTrial

    cTrial = 1 

    global debug_data
    global CS_US_1 

    CS_US_1['inputs']=[]

    cerebellumConfig['weights']=[]
    cerebellumConfig['config']=[]
    cerebellumConfig['constants']=[]


    debug_data['trials']=[]
    if save_bases:
        debug_data['basis']=[]
    debug_data['inputs']=[]

    inOSCport = 1234
    outOSCport = 1235
    
    # myOSC_Server = OSCServer( ('' , inOSCport) )
    # myOSC_Client = OSCClient()
    # myOSC_Client.connect( ('10.0.0.116' , outOSCport) )

    myOSC_Server = OSCServer( ('127.0.0.1' , inOSCport) )
    myOSC_Client = OSCClient()
    myOSC_Client.connect( ('127.0.0.1' , outOSCport) )
    
    print "Receiving messages /trial,/input in port", inOSCport
    print "Sending messages to port", outOSCport


    myOSC_Server.addMsgHandler("/config", receiveConfig)
    myOSC_Server.addMsgHandler("/trial", receiveTrial)
    myOSC_Server.addMsgHandler("/endtrial", receiveEndTrial)
    myOSC_Server.addMsgHandler("/input", receiveInput)
    myOSC_Server.addMsgHandler("/debug", receiveDebug)
    myOSC_Server.addMsgHandler("/update", receiveUpdate)
    myOSC_Server.addMsgHandler("/freeze", receiveFreeze)
    myOSC_Server.addMsgHandler("/saveConfig", receiveSaveConf)
    

    

    # if (cTrial==nTrials):
    #     pl.figure(figsize=(10,6))
    #     plot(breaksxTrial)

    
    print "Ready"

    myOSC_Server.serve_forever()
示例#15
0
 def __init__(self, ip='localhost', port=12345, address="/openbci"):
     # connection infos
     self.ip = ip
     self.port = port
     self.address = address
     self.client = OSCClient()
     self.client.connect((self.ip, self.port))
     self.board = bci.OpenBCIBoard()
示例#16
0
def connectOsc():
    global client, timeLastConnection
    if timeLastConnection < time.time() - 7200:
        print("connecting to OSC server")
        updateDNS()
        client = OSCClient()
        client.connect( ("146.164.80.56", 22244) )
        timeLastConnection = time.time()
def connectOsc():
    global client, timeLastConnection
    if timeLastConnection < time.time() - 7200:  # Reconnect every two hours
        print("connecting to OSC server")
        updateDNS()
        client = OSCClient()
        client.connect(("146.164.80.56", 22244))
        timeLastConnection = time.time()
示例#18
0
	def __init__(self, ip, port,address="/openbci"):
		self.ip = ip
		self.port = port
		self.address = address
		
		# init network
		print "Selecting OSC streaming. IP: ", self.ip, ", port: ", self.port, ", address: ", self.address
		self.client = OSCClient()
		self.client.connect( (self.ip, self.port) )	
示例#19
0
文件: Game.py 项目: husk00/audiogames
def sendOSCnextlevel():
        client = OSCClient()
        msg = OSCMessage()
        # gl.client is a tuple in gl with ip and port
        address = "/game/nextlevel"
        msg.setAddress(address)
        msg.append(currentlevel)
        client.sendto(msg, gl.send_to)
        #print('Send message example =', msg, "to ", gl.send_to)
        return
示例#20
0
def main():
        
        # OSC SERVER      
        myip = socket.gethostbyname(socket.gethostname())
        myip = "127.0.0.1"
        print("IP adress is : "+myip)
        try:
            server = SimpleServer((myip, 12354)) 
        except:
            print(" ERROR : creating server") 
        print("server created") 
        try:
            st = threading.Thread(target = server.serve_forever) 
        except:
            print(" ERROR : creating thread") 
        try:
            st.start()
        except:
            print(" ERROR : starting thread")

        print(" OSC server is running") 

        # OSC CLIENT
        global client
        client = OSCClient()
        client.connect( ('127.0.0.1', 9998))

        #START ON BOOT
        global machine
        machine = 7
        start_app() 

        # MAIN LOOP 
        global runningApp
        runningApp = True

        
        print(" ===== STARTING MAIN LOOP ====" )
        while runningApp:
            # This is the main loop
            # Do something here
            try:
                time.sleep(1)
            except:
                print("User attempt to close programm")
                runningApp = False
        
        #CLOSING THREAD AND SERVER
        print(" Ending programme") 
        server.running = False
        print(" Join thread") 
        st.join()
        server.close()
        print(" This is probably the end") 
示例#21
0
def get_osc_client(host='localhost', port=defaults['port'], say_hello=False):
    # String, int -> OSCClient

    client = OSCClient()
    client.connect((host, port))

    # TODO Make this work
    if say_hello:
        send_simple_message(client, "/hello", timeout=None)

    return client
示例#22
0
 def activate(self):
     if len(self.args) > 0:
         self.ip = self.args[0]
     if len(self.args) > 1:
         self.port = int(self.args[1])
     if len(self.args) > 2:
         self.address = self.args[2]
     # init network
     print "Selecting OSC streaming. IP: ", self.ip, ", port: ", self.port, ", address: ", self.address
     self.client = OSCClient()
     self.client.connect((self.ip, self.port))
示例#23
0
 def send_destroy(self,id):
     #
     client = OSCClient()
     msg = OSCMessage()
     # gl.client is a tuple in gl with ip and port
     address = "/game/sndobj/destroy"
     msg.setAddress(address)
     msg.append(id)
     client.sendto(msg, gl.send_to)
     #print('Send message example =', msg, "to ", gl.send_to)
     return    
示例#24
0
 def send_choque(self):
     #
     client = OSCClient()
     msg = OSCMessage()
     # gl.client is a tuple in gl with ip and port
     address = "/player/choque"
     msg.setAddress(address)
     msg.append(0)
     client.sendto(msg, gl.send_to)
     #print('Send message example =', msg, "to ", gl.send_to)
     return
示例#25
0
 def send_osccreation(self, lista):
     # crea los objetos en el sound engine
     client = OSCClient()
     msg = OSCMessage()
     # gl.client is a tuple in gl with ip and port
     address = "/game/create"
     msg.setAddress(address)
     msg.append(lista)
     client.sendto(msg, gl.send_to)
     #print('Send message example =', msg, "to ", gl.send_to)
     return
示例#26
0
 def send_stop(self):
     # da stop al soundengine
     client = OSCClient()
     msg = OSCMessage()
     # gl.client is a tuple in gl with ip and port
     address = "/game/stop"
     msg.setAddress(address)
     msg.append(0)
     client.sendto(msg, gl.send_to)
     #print('Send message example =', msg, "to ", gl.send_to)
     return
示例#27
0
def sendOSCend():
        #
        client = OSCClient()
        msg = OSCMessage()
        # gl.client is a tuple in gl with ip and port
        address = "/game/end"
        msg.setAddress(address)
        msg.append(1)
        client.sendto(msg, gl.send_to)
        print('Send message example =', msg, "to ", gl.send_to)
        return
示例#28
0
文件: manta.py 项目: ssfrr/buffering
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)
示例#29
0
 def __init__(self,
         remote_osc_address,
         json_to_osc_q,
         osc_command_name,
         bridge=None,
         *args, **kwargs):
     self.remote_osc_address = remote_osc_address
     self.json_to_osc_q = json_to_osc_q
     self.osc_client = OSCClient()
     self.osc_client.connect(remote_osc_address)
     self.osc_command_name = osc_command_name
     self.bridge = bridge
示例#30
0
 def __init__(self, adr, port):
     self.ip_adr = adr
     self.port = port
     self.destination = (self.ip_adr, self.port)
     #         self.client = OSC.OSCClient()
     self.client = OSCClient()
     self.client.connect(self.destination)
     self.adr = "/unset"
     self.str = 'IP: '
     self.str += self.ip_adr
     self.str += ' PORT: '
     self.str += str(port)
     print(self.str)
示例#31
0
  def __init__(self, ip, port,address="/openbci"):
    self.ip = ip
    self.port = port
    self.address = address
	if len(args) > 0:
		self.ip = args[0]
	if len(args) > 1:
		self.port = args[1]
	if len(args) > 2:
		self.address = args[2]
	# init network
	print "Selecting OSC streaming. IP: ", self.ip, ", port: ", self.port, ", address: ", self.address
	self.client = OSCClient()
	self.client.connect( (self.ip, self.port) )	
class osc_sender_t:
    def __init__(self, server, port):
        self.client = OSCClient()
        self.client.connect((server, port))
        self.need_send_names = SEND_NAMES

    def send_data(self, data):
        msg = OSCMessage("/wek/inputs")
        for k, v in data.items():
            if k.endswith("_flag"):
                msg.append(v)
            else:
                msg.append([v[0], v[1], v[2]])
        self._send(msg)

    def send_DTW_record(self, cls):
        msg = OSCMessage("/wekinator/control/startDtwRecording")
        msg.append(int(cls))
        self._send(msg)

    def send_DTW_stop(self):
        msg = OSCMessage("/wekinator/control/stopDtwRecording")
        self._send(msg)

    def send_run(self):
        msg = OSCMessage("/wekinator/control/startRunning")
        self._send(msg)

    def send_stop(self):
        msg = OSCMessage("/wekinator/control/stopRunning")
        self._send(msg)

    def send_names(self, data):
        if self.need_send_names:
            self.need_send_names = False
            msg = OSCMessage("/wekinator/control/setInputNames")
            for k, v in data.items():
                if k.endswith("flag"):
                    msg.append(k)
                else:
                    msg.append(k + "_x")
                    msg.append(k + "_y")
                    msg.append(k + "_z")
            self._send(msg)

    def _send(self, msg):
        try:
            self.client.send(msg)
        except OSCError:
            pass
示例#33
0
 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 = []
示例#34
0
def main(args):

    # Default host and port
    HOST = '192.168.1.8'
    PORT = 3032
    
    if len(args) == 2:
        HOST = args[0]
        PORT = args[1]
    elif len(args) == 1:
        HOST = args[0]
    elif len(args) > 2:
        errorPrint("OSC Go button accepts at most 2 arguments.\n" + len(args) + " were provided.");

    client = OSCClient()
    client.connect((HOST, PORT))

    msg = OSCMessage("/eos/key/go_0");
    client.send(msg);
    client.close();

    print
    print "GO"
    print
    exit();
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()
示例#36
0
class OscSender():
    def __init__(self, osc_setup):
        self.host, self.port, self.root = osc_setup
        self.client = OSCClient()
        self.client.connect( (self.host, self.port) )
        print "Connected to the OSC server %s:%s%s" %osc_setup
        self.send_parameter('osd_initialized','Done')

    def send_parameters(self, hand_params):
        for path, value in hand_params.items():
            self.send_parameter(path, value)

    def send_parameter(self, rel_path, data):
        full_path = self.root+rel_path
        #self.client.send( OSCMessage( full_path, data ) )
        print "[osc]\t%s\t\t\t%s" %(full_path, data)
示例#37
0
class OscSender():
    def __init__(self, osc_setup):
        self.host, self.port, self.root = osc_setup
        self.client = OSCClient()
        self.client.connect((self.host, self.port))
        print "Connected to the OSC server %s:%s%s" % osc_setup
        self.send_parameter('osd_initialized', 'Done')

    def send_parameters(self, hand_params):
        for path, value in hand_params.items():
            self.send_parameter(path, value)

    def send_parameter(self, rel_path, data):
        full_path = self.root + rel_path
        #self.client.send( OSCMessage( full_path, data ) )
        print "[osc]\t%s\t\t\t%s" % (full_path, data)
示例#38
0
 def __init__(self):
     self.osc_message = None
     self.osc_client = OSCClient()
     self.osc_message = OSCMessage()        
     
     self.ip = ""
     self.port = 0
示例#39
0
class OSCServer(object):

  def __init__(self, ip, port,address="/openbci"):
    self.ip = ip
    self.port = port
    self.address = address
	if len(args) > 0:
		self.ip = args[0]
	if len(args) > 1:
		self.port = args[1]
	if len(args) > 2:
		self.address = args[2]
	# init network
	print "Selecting OSC streaming. IP: ", self.ip, ", port: ", self.port, ", address: ", self.address
	self.client = OSCClient()
	self.client.connect( (self.ip, self.port) )	
示例#40
0
文件: app.py 项目: ianisl/DOS
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)
示例#41
0
def setup():

	# OSC
	global client
	client = OSCClient()
	client.connect(("localhost", 7300))

	# DISPLAY
	global full_screen
	full_screen = False
	# global window_width, window_height
	window_width = 640
	window_height = 480

	# PYGAME
	global FPS
	FPS = 30
	pygame.init()
	global screen
	screen = pygame.display.set_mode((window_width, window_height))#, 0, 32)
	pygame.display.set_caption("Le Reuz")
	global clock
	clock = pygame.time.Clock()
	global logo, grass
	logo = pygame.image.load("pictures/lereuz.jpg").convert()
	grass = pygame.image.load("pictures/test5.jpg").convert()
	global index
	index = 0
	global fontObj
	fontObj = pygame.font.Font('freesansbold.ttf', 16)

	# OPENCV
	global camera
	camera = cv2.VideoCapture(0)
	camera.set(3, window_width)
	camera.set(4, window_height)
	# ds_factor = 1.0
	# logo = cv2.imread("pictures/lereuz.jpg")

	# FACIAL FEATURES DETECTORS
	global face_detector, mouth_detector, smile_detector, nose_detector, right_eye_detector, left_eye_detector
	face_detector = FaceDetector()
	mouth_detector = MouthDetector()
	smile_detector = SmileDetector()
	nose_detector = NoseDetector()
	right_eye_detector = RightEyeDetector()
	left_eye_detector = LeftEyeDetector()
示例#42
0
 def __init__(self, ip='localhost', port=12345, address="/openbci"):
     # connection infos
     self.ip = ip
     self.port = port
     self.address = address
     self.client = OSCClient()
     self.client.connect( (self.ip, self.port) )
     self.board = bci.OpenBCIBoard()
示例#43
0
def main():
    led_setup()
    client = OSCClient()
    address = ('127.0.0.1', 6666)
    while True:
        state = hand_state()
        led_control(state)
        if state['left']:
            msg = OSCMessage('/volume')
            msg.append(clamp(state['left'], 100, 600))
            client.sendto(msg, address)
        if state['right']:
            msg = OSCMessage('/pitch')
            msg.append(clamp(state['right'], 100, 600))
            client.sendto(msg, address)
        time.sleep(0.01)
    led_teardown()
示例#44
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 send_value(self):
     for add, d in self.neighbors.items():
         c = OSCClient()
         c.connect(("localhost", add))
         msg = OSCMessage("/receive")
         msg.append(self._address)
         msg.append(self.data["value"])
         msg.append(self.data["iter"])
         c.send(msg)
         c.close()
示例#46
0
def step_impl(context, host, port, int_one, int_sec):
    client = OSCClient()
    client.connect((host, port))
    if int_sec > 0:
        client.send(OSCMessage('/test', int_one, int_sec))
    else:
        client.send(OSCMessage('/test', int_one))
示例#47
0
 def send_osclocation(self):
     #cuando hay un cambio de situacion se envia
     #           /player/in    /player/out      /player/border
     client = OSCClient()
     msg = OSCMessage()
     # gl.client is a tuple in gl with ip and port
     if self['location'] == 'IN':
         address = "/player/in"
     elif self['location'] == 'OUT':
         address = "/player/out"
     else:
         address = "/player/border"
     msg.setAddress(address)
     msg.append(1)
     client.sendto(msg, gl.send_to)
     print(msg)
     #print('Send message example =', msg, "to ", gl.send_to)
     return 
示例#48
0
文件: renoise.py 项目: rknLA/pymonome
class Renoise(object):
    def __init__(self, address):
        self.client = OSCClient()
        self.client.connect(address)

    def panic(self):
        self.send_osc('/renoise/transport/panic')
    
    def note_on(self, instrument, track, note, velocity):
        self.send_osc('/renoise/trigger/note_on', instrument, track, note, velocity)
    
    def note_off(self, instrument, track, note):
        self.send_osc('/renoise/trigger/note_off', instrument, track, note)
    
    def send_osc(self, path, *args):
        msg = OSCMessage(path)
        map(msg.append, args)
        self.client.send(msg)
示例#49
0
    def on_data(self, data):
        #print(data)
        duration = 0
        try:
            all_data = json.loads(data)
            tweet = all_data["text"]
            split_tweet = tweet.split(' ')
            first_word = split_tweet[0]
            if first_word == 'RT':
                first_word = split_tweet[1]
            num = 0
            for char in first_word:
                num += ord(char)
            length_of_tweet = len(split_tweet)/40.0
            duration = length_of_tweet * 1000
            #print duration
            sharp_freqs = [185, 207.65, 233.08, 261.63, 277.18, 311.13, 349.23,]
            freqs = [174.61, 196, 220, 246.94, 261.63, 293.66, 329.62, 349.23, ]#369.99, 391.96, 415.30, 440, 466.16, 493.88, 523.25]
            note = num % 7
            freq = 0
            if '#' in tweet:
                freq = sharp_freqs[note]
            else:
                freq = freqs[note]
        except UnicodeEncodeError:
            duration = 500
        
        client = OSCClient()
        client.connect(("localhost", 54345))

        ### Create a bundle:
        bundle = OSCBundle()
        bundle.append({'addr': "/frequency", 'args':[freq]})
        #bundle.append({'addr': "/amplitude", 'args':[52]})
        #bundle.append({'addr': "/envelope/line", 'args:['})
        bundle.append({'addr': "/envelope/line", 'args': [10., 20, 0., duration]})

        client.send(bundle)


        time.sleep(duration/1000)
        
        return(True)
示例#50
0
class OSCServer(object):

	def __init__(self, ip, port,address="/openbci"):
		self.ip = ip
		self.port = port
		self.address = address
		
		# init network
		print "Selecting OSC streaming. IP: ", self.ip, ", port: ", self.port, ", address: ", self.address
		self.client = OSCClient()
		self.client.connect( (self.ip, self.port) )	

	def handle_sample(self, sample):
		mes = OSCMessage(self.address)
		mes.append(sample.channel_data)
		# silently pass if connection drops
		try:
			self.client.send(mes)
		except:
			return	
示例#51
0
	def activate(self):
		if len(self.args) > 0:
			self.ip = self.args[0]
		if len(self.args) > 1:
			self.port = int(self.args[1])
		if len(self.args) > 2:
			self.address = self.args[2]
		# init network
		print "Selecting OSC streaming. IP: ", self.ip, ", port: ", self.port, ", address: ", self.address
		self.client = OSCClient()
		self.client.connect( (self.ip, self.port) )
 def setup(self):
     self.name = "VLE"
     self.allClients = {}
     self.oscClient = OSCClient()
     ## subscribe to all receivers from localnet
     self.subscribeToAll()
     self.oldMessages = []
     self.lastQueueCheck = time.time()
     self.oscPingMessage = OSCMessage()
     self.oscPingMessage.setAddress("/LocalNet/Ping")
     ## use empty byte blob
     self.oscPingMessage.append("", 'b')
示例#53
0
class Sender():
    #Takes the short moves defined by the user, parse them and store them in a strucured hash table.
    #Process the gestures from the listener : find the associated command, ask for a confirmation, execute the command.
    def __init__(self, osc_setup):
        self.host, self.port, self.root = osc_setup
        self.client = OSCClient()
        self.client.connect( (self.host, self.port) )
        print "Connected to the OSC server %s:%s%s" %osc_setup
        self.send('init','leap_listener initialized')

    def send_hand(self, hand_params):
        print '********* HAND ***********'
        which = hand_params['which']
        for path, value in hand_params.items():
            path = path.replace('<which>',which)
            self.send(path, value)

    def send(self, rel_path, data):
        full_path = self.root+rel_path
        #self.client.send( OSCMessage( full_path, data ) )
        print "[osc]\t%s\t\t\t%s" %(full_path, data)
示例#54
0
def main():
  print "================="
  print "Sratch2OSC %s" % VERSION
  print "================="
  print ""

  while True:
    s = connect()

    osc_client = OSCClient()
    osc_client.connect(OSC_HOST, OSC_PORT)

    if (s):
      print _("Connected to Scratch")

      s.broadcast("goo")
      s.broadcast("choki")
      s.broadcast("par")

      listen(s, osc_client)
    time.sleep(5)
示例#55
0
def ping_callback(path, tags, args, source):
    try:
        client = OSCClient()
        client.connect((source[0], 8001))
        client.send(OSCMessage("/ping"))
    except Exception as e:
        print e
示例#56
0
def OSCsend(name, oscaddress, oscargs=''):

    ip = midi2OSC[name]["oscip"]
    port = midi2OSC[name]["oscport"]
    osclient = OSCClient()
    osclient.connect((ip, port))
    oscmsg = OSCMessage()
    oscmsg.setAddress(oscaddress)
    oscmsg.append(oscargs)

    try:
        if gstt.debug > 0:
            print("Midi OSCSend : sending", oscmsg, "to", name, "at",
                  gstt.LjayServerIP, ":", PluginPort)
        osclient.sendto(oscmsg, (ip, port))
        oscmsg.clearData()
        #if gstt.debug >0:
        #   print oscaddress, oscargs, "was sent to",name
        return True

    except:
        if gstt.debug > 0:
            print('Midi OSCSend : Connection to IP', ip, ':', port,
                  'refused : died ?')
        #sendWSall("/status No plugin.")
        #sendWSall("/status " + name + " is offline")
        #sendWSall("/" + name + "/start 0")
        #PluginStart(name)
        return False