示例#1
0
    def main(self):
        """ Main loop """
        while 1:
            if self.dataReady("control"):
                msg = self.recv("control")
                if (isinstance(msg, producerFinished)
                        or isinstance(cmsg, shutdownMicroprocess)):
                    self.send(msg, "signal")
                    break
            if self.dataReady("inbox"):
                data = self.recv("inbox")
                if self.index is None:
                    decoded = OSC.decodeOSC(data)
                    # Send decoded data as (address, [arguments], timetag) tuple
                    self.send((decoded[2][0], decoded[2][2:], decoded[1]),
                              "outbox")
                else:
                    decoded = OSC.decodeOSC(data[self.index])
                    data = list(data)
                    data[self.index] = (decoded[2][0], decoded[2][2:],
                                        decoded[1])
                    self.send(data, "outbox")

            if not self.anyReady():
                self.pause()
                yield 1
示例#2
0
文件: Osc.py 项目: casibbald/kamaelia
 def main(self):
     """ Main loop """
     while 1:
         if self.dataReady("control"):
             msg = self.recv("control")
             if (isinstance(msg, producerFinished) or
                 isinstance(cmsg, shutdownMicroprocess)):
                 self.send(msg, "signal")
                 break
         if self.dataReady("inbox"):
             data = self.recv("inbox")
             if self.index is None:
                 decoded = OSC.decodeOSC(data)
                 # Send decoded data as (address, [arguments], timetag) tuple
                 self.send((decoded[2][0], decoded[2][2:], decoded[1]),
                           "outbox")
             else:
                 decoded = OSC.decodeOSC(data[self.index])
                 data = list(data)
                 data[self.index] = (decoded[2][0], decoded[2][2:],
                                        decoded[1])
                 self.send(data, "outbox") 
                 
         if not self.anyReady():
             self.pause()
             yield 1
示例#3
0
def read_from_port(ser, q):
    while True:
        reading = ser.readline()
        try:
            halfd = driver.receive(reading)
            str = ''.join(halfd)
            if halfd != []:
                print OSC.decodeOSC(str)
                q.put(OSC.decodeOSC(str))
        except:
            print "malformed OSC packet"
            print reading
示例#4
0
def chew_data(host, port):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(0.05) # prevent blender from getting stuck if socket hangs
    s.bind((host, port))
    raw,addr = s.recvfrom(1024)
    o = OSC.decodeOSC(raw)
    return o 
def heartbeat(add, tags, stuff, source):
    global sw1
    cpu = psutil.cpu_percent()
    if sw1 == 1:
        # print "HEARTBEAT RECIEVED!"
        decoded = OSC.decodeOSC(stuff[0])
        # supercollider CPU usage and UGens printout
        cprint("CPU %/Number of Sounds: " + str(cpu) + "/" + str(decoded[3]), "red", attrs=["dark"])
        # scaling CPU values
        cpufloat = float(cpu)
        # print decoded[7]
        # ready the osc message
        oscmsg = OSC.OSCMessage()
        # determine which heartbeat to send
        if cpufloat < 2.0:
            oscmsg.setAddress("/heartbeat/faint")
        elif cpufloat < 6.0:
            oscmsg.setAddress("/heartbeat/weak")
        elif cpufloat < 10.0:
            oscmsg.setAddress("/heartbeat/medium")
        elif cpufloat < 20.0:
            oscmsg.setAddress("/heartbeat/strong")
        elif cpufloat < 30.0:
            oscmsg.setAddress("/heartbeat/heavy")
        else:
            oscmsg.setAddress("/heartbeat/intense")

            # adding the CPU usage value to the message, this can be mapped later.
        oscmsg.append(cpufloat)
        qlcclient.send(oscmsg)
        # sending CPU information back to SuperCollider
        oscmsg = OSC.OSCMessage()
        oscmsg.setAddress("/cpuinfo")
        oscmsg.append(cpufloat)
        scclient.send(oscmsg)
def heartbeat(add, tags, stuff, source):
	global sw1
	if sw1 == 1:
		# print "HEARTBEAT RECIEVED!"
		decoded = OSC.decodeOSC(stuff[0])
		#supercollider CPU usage and UGens printout
		print "Sound CPU/Synths heartbeat: "+str(round(decoded[7],4))+"/"+str(decoded[3])
		# scaling CPU values
		scaled = int(interp(decoded[7],[0.0,40.0],[20,255]))
		#print decoded[7]
		# ready the osc message
		oscmsg = OSC.OSCMessage()
		#determine which heartbeat to send
		if float(decoded[7]) < 2.0:
			oscmsg.setAddress("/heartbeat/faint")
		elif decoded[7] < 6.0:
			oscmsg.setAddress("/heartbeat/weak")
		elif decoded[7] < 10.0:
			oscmsg.setAddress("/heartbeat/medium")
		elif decoded[7] < 20.0:
			oscmsg.setAddress("/heartbeat/strong")
		elif decoded[7] < 30.0:
			oscmsg.setAddress("/heartbeat/heavy")
		else:
			oscmsg.setAddress("/heartbeat/intense")

		# adding the CPU usage value to the message, this can be mapped later.
		oscmsg.append(scaled)
		qlcclient.send(oscmsg)
示例#7
0
def heartbeat(add, tags, stuff, source):
    global sw1
    cpu = psutil.cpu_percent()
    if sw1 == 1:
        # print "HEARTBEAT RECIEVED!"
        decoded = OSC.decodeOSC(stuff[0])
        #supercollider CPU usage and UGens printout
        print "CPU %/Number of Sounds: " + str(cpu) + "/" + str(decoded[3])
        # scaling CPU values
        cpufloat = float(cpu)
        #print decoded[7]
        # ready the osc message
        oscmsg = OSC.OSCMessage()
        #determine which heartbeat to send
        if cpufloat < 2.0:
            oscmsg.setAddress("/heartbeat/faint")
        elif cpufloat < 6.0:
            oscmsg.setAddress("/heartbeat/weak")
        elif cpufloat < 10.0:
            oscmsg.setAddress("/heartbeat/medium")
        elif cpufloat < 20.0:
            oscmsg.setAddress("/heartbeat/strong")
        elif cpufloat < 30.0:
            oscmsg.setAddress("/heartbeat/heavy")
        else:
            oscmsg.setAddress("/heartbeat/intense")

        # adding the CPU usage value to the message, this can be mapped later.
        oscmsg.append(cpufloat)
        qlcclient.send(oscmsg)
def inductionmics(add, tags, stuff, source):
    global sw1
    global sw2
    global inductioniter
    # check if the switch is on, this is the same switch that controls the inducton light/sound
    if sw2 == 1:
        # this should only be displayed if the 'information' switch (switch 1) is on
        if sw1 == 1:
            # decoded OSC message, this needs to be done to the whole message and then
            # the goodies need to be parsed out because OSC and arrays don't mix well
            # indices 5, 6 and 7 of the 'stuff' contains hi/mid/low figures
            decoded = OSC.decodeOSC(stuff[0])
            # TODO: Sort this out. Print this every ten times this function is run
            if inductioniter % 30 == 0:
                cprint(
                    "Induction Power: Low - "
                    + str(round(decoded[4], 3))
                    + " Mid - "
                    + str(round(decoded[5], 3))
                    + " Hi - "
                    + str(round(decoded[6], 3)),
                    "cyan",
                    attrs=["dark"],
                )
            inductioniter = inductioniter + 1
def heartbeat(add, tags, stuff, source):
	# print "HEARTBEAT RECIEVED!"
	decoded = OSC.decodeOSC(stuff[0])
	#supercollider CPU usage and UGens printout
	print "SuperCollider CPU usage: "+str(decoded[7])+" Number of synths: "+str(decoded[3])
	# scaling CPU values
	scaled = int(interp(decoded[7],[0.0,40.0],[20,255]))
	#print decoded[7]
	# ready the osc message
	oscmsg = OSC.OSCMessage()
	#determine which heartbeat to send
	if float(decoded[7]) < 2.0:
		oscmsg.setAddress("/heartbeat/faint")
		print "faint"
	elif decoded[7] < 6.0:
		oscmsg.setAddress("/heartbeat/weak")
		print "weak"
	elif decoded[7] < 10.0:
		oscmsg.setAddress("/heartbeat/medium")
		print "medium"
	elif decoded[7] < 20.0:
		oscmsg.setAddress("/heartbeat/strong")
		print "strong"
	elif decoded[7] < 30.0:
		oscmsg.setAddress("/heartbeat/heavy")
		print "heavy"
	else:
		oscmsg.setAddress("/heartbeat/intense")
		print "intense"

	# adding the CPU usage value to the message, this can be mapped later.
	oscmsg.append(scaled)
	c.send(oscmsg)
 def process_metatone_message(self, handler, time, packet):
     """
     Function to decode an OSC formatted string and then process it
     according to its address. Sends processed messages directly
     to the metatone_classifier module's message handling functions.
     """
     message = OSC.decodeOSC(packet)
     try:
         if "/metatone/touch/ended" in message[0]:
             self.classifier.handle_client_message(message[0], message[1][1:], message[2:], FAKE_OSC_SOURCE)
         elif "/metatone/touch" in message[0]:
             self.classifier.handle_client_message(message[0], message[1][1:], message[2:], FAKE_OSC_SOURCE)
         elif "/metatone/switch" in message[0]:
             self.classifier.handle_client_message(message[0], message[1][1:], message[2:], FAKE_OSC_SOURCE)
         elif "/metatone/online" in message[0]:
             self.classifier.handle_client_message(message[0], message[1][1:], message[2:], FAKE_OSC_SOURCE)
             handler.send_osc("/metatone/classifier/hello", [])
             handler.deviceID = message[2]
             handler.app = message[3]
         elif "/metatone/offline" in message[0]:
             self.classifier.handle_client_message(message[0], message[1][1:], message[2:], FAKE_OSC_SOURCE)
         elif "/metatone/acceleration" in message[0]:
             self.classifier.handle_client_message(message[0], message[1][1:], message[2:], FAKE_OSC_SOURCE)
         elif "/metatone/app" in message[0]:
             self.classifier.handle_client_message(message[0], message[1][1:], message[2:], FAKE_OSC_SOURCE)
         elif "/metatone/targetgesture" in message[0]:
             self.classifier.handle_client_message(message[0], message[1][1:], message[2:], FAKE_OSC_SOURCE)
         else:
             print("Got an unknown message! Address was: " + message[0])
             print("Time was: " + str(time))
             print(u'Raw Message Data: {}'.format(packet))
     except():
         print("Message did not decode to a non-empty list.")
示例#11
0
def heartbeat(add, tags, stuff, source):
    global sw1
    if sw1 == 1:
        # print "HEARTBEAT RECIEVED!"
        decoded = OSC.decodeOSC(stuff[0])
        #supercollider CPU usage and UGens printout
        print "Sound CPU/Synths heartbeat: " + str(round(
            decoded[7], 4)) + "/" + str(decoded[3])
        # scaling CPU values
        scaled = int(interp(decoded[7], [0.0, 40.0], [20, 255]))
        #print decoded[7]
        # ready the osc message
        oscmsg = OSC.OSCMessage()
        #determine which heartbeat to send
        if float(decoded[7]) < 2.0:
            oscmsg.setAddress("/heartbeat/faint")
        elif decoded[7] < 6.0:
            oscmsg.setAddress("/heartbeat/weak")
        elif decoded[7] < 10.0:
            oscmsg.setAddress("/heartbeat/medium")
        elif decoded[7] < 20.0:
            oscmsg.setAddress("/heartbeat/strong")
        elif decoded[7] < 30.0:
            oscmsg.setAddress("/heartbeat/heavy")
        else:
            oscmsg.setAddress("/heartbeat/intense")

        # adding the CPU usage value to the message, this can be mapped later.
        oscmsg.append(scaled)
        c.send(oscmsg)
示例#12
0
def read_from_port(ser):
    #   while not connected:
    #serin = ser.read()
    #      connected = True

    while True:
        #           print("test")
        reading = ser.readline()
        #          print OSC.decodeOSC(driver.receive(reading))
        try:
            halfd = driver.receive(reading)
            str = ''.join(halfd)
            if halfd != []:
                print OSC.decodeOSC(str)
        except:
            print "malformed OSC packet"
示例#13
0
def receiveOSC(controller):
	try:
		raw_data = gl.socket.recv(BUFFER_SIZE)
		data = OSC.decodeOSC(raw_data)
		print(data)

	except socket.timeout:
		pass
def inductionmics(add,tags,stuff,source):
	global sw2
	if sw2 == 1:
		# decoded OSC message, this needs to be done to the whole message and then
		# the goodies need to be parsed out because OSC and arrays don't mix well
		decoded = OSC.decodeOSC(stuff[0])
		#TODO: Sort this out. Print this every ten times this function is run
		print "Induction Power: Low - "+str(round(decoded[4],3))+" Mid - "+str(round(decoded[5],3))+" Hi - "+str(round(decoded[6],3))
示例#15
0
def inductionmics(add, tags, stuff, source):
    global sw2
    if sw2 == 1:
        # decoded OSC message, this needs to be done to the whole message and then
        # the goodies need to be parsed out because OSC and arrays don't mix well
        decoded = OSC.decodeOSC(stuff[0])
        #TODO: Sort this out. Print this every ten times this function is run
        print "Induction Power: Low - " + str(round(
            decoded[4], 3)) + " Mid - " + str(round(
                decoded[5], 3)) + " Hi - " + str(round(decoded[6], 3))
示例#16
0
    def listen(self):
        "Listens to incoming messages synchronously and \
		returns a sequence of the decoded OSC packet fields. \
		Note: index 1 of the resulting sequence contains the \
		packet types string."

        data, (ip, port) = self.fSocket.recvfrom(4096)
        if len(data) > 4:  # discriminate incorrect and termination packets
            return OSC.decodeOSC(data)
        return []
示例#17
0
def main():
    # Set init
    ip = '127.0.0.1'  ### escucha a routerOSC.pd
    port = 8888
    data = 0
    # Get controller and owner
    controller = GameLogic.getCurrentController()
    owner = controller.owner
        # Connect Blender only one time
    if not owner['connected']:
        
        owner['connected'] = True
        print ("Blender Connected Ori")
     
        GameLogic.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        GameLogic.socket.bind((ip, port))
        GameLogic.socket.setblocking(0)
        GameLogic.socket.settimeout(0.02)
     
    # If Blender connected, get osc 
    else:
        # Get hand wii osc from pd
        
        data = receive_osc(data, port)
        if data != 0:
            d = OSC.decodeOSC(data)
            print(d)
            '''if d[2][8] == "/ori":
                ori,ox,oz =d[2][9], d[2][10], d[2][11]
                scn = bge.logic.getCurrentScene()
                player = scn.objects["player"]
                player['ori'] = ori
                
            if d[2][12] == "/norte":
                nx,ny =d[2][13],d[2][14]
                scn = bge.logic.getCurrentScene()
                player = scn.objects["player"]
                player['tracker_n'] = nx,ny
            
            # solo si hay 2 kinects!!!!!!
            if d[2][15] == "/sur":
                sx,sy =d[2][16],d[2][17]
                scn = bge.logic.getCurrentScene()
                player = scn.objects["player"]
                player['tracker_s'] = sx,sy '''
                
            if d[0] == "/norte":
                nx,ny =d[2],d[3]
                print(nx,ny)
                scn = bge.logic.getCurrentScene()
                player = scn.objects["player"]
                player['tracker_n'] = nx,ny
                          
示例#18
0
def inductionmics(add,tags,stuff,source):
	global sw1
	global sw2
	# check if the switch is on, this is the same switch that controls the inducton light/sound
	if sw2 == 1:
		# this should only be displayed if the 'information' switch (switch 1) is on
		if sw1 == 1:
			# decoded OSC message, this needs to be done to the whole message and then
			# the goodies need to be parsed out because OSC and arrays don't mix well
			decoded = OSC.decodeOSC(stuff[0])
			#TODO: Sort this out. Print this every ten times this function is run
			print "Induction Power: Low - "+str(round(decoded[4],3))+" Mid - "+str(round(decoded[5],3))+" Hi - "+str(round(decoded[6],3))
示例#19
0
def inductionmics(add,tags,stuff,source):
	global sw1
	global sw2
	# check if the switch is on, this is the same switch that controls the inducton light/sound
	if sw2 == 1:
		# this should only be displayed if the 'information' switch (switch 1) is on
		if sw1 == 1:
			# decoded OSC message, this needs to be done to the whole message and then
			# the goodies need to be parsed out because OSC and arrays don't mix well
			decoded = OSC.decodeOSC(stuff[0])
			#TODO: Sort this out. Print this every ten times this function is run
			print "Induction Power: Low - "+str(round(decoded[4],3))+" Mid - "+str(round(decoded[5],3))+" Hi - "+str(round(decoded[6],3))
示例#20
0
def heartbeat(add, tags, stuff, source):
	# print "HEARTBEAT RECIEVED!"
	decoded = OSC.decodeOSC(stuff[0])
	#supercollider CPU usage and UGens printout
	print "SuperCollider CPU usage: "+str(decoded[7])+" Number of synths: "+str(decoded[3])
	# scaling CPU values
	scaled = int(interp(decoded[7],[0.0,40.0],[20,255]))
	print scaled
	# sending heartbeat tick to QLC
	oscmsg = OSC.OSCMessage()
	oscmsg.setAddress("/heartbeat/on")
	# adding the CPU usage value to the message, this can be mapped later.
	oscmsg.append(scaled)
	c.send(oscmsg)
示例#21
0
def heartbeat(add, tags, stuff, source):
    # print "HEARTBEAT RECIEVED!"
    decoded = OSC.decodeOSC(stuff[0])
    #supercollider CPU usage and UGens printout
    print "SuperCollider CPU usage: " + str(
        decoded[7]) + " Number of synths: " + str(decoded[3])
    # scaling CPU values
    scaled = int(interp(decoded[7], [0.0, 40.0], [20, 255]))
    print scaled
    # sending heartbeat tick to QLC
    oscmsg = OSC.OSCMessage()
    oscmsg.setAddress("/heartbeat/on")
    # adding the CPU usage value to the message, this can be mapped later.
    oscmsg.append(scaled)
    c.send(oscmsg)
示例#22
0
def inductionmics(add,tags,stuff,source):
	global sw1
	global sw2
	global inductioniter
	# check if the switch is on, this is the same switch that controls the inducton light/sound
	if sw2 == 1:
		# this should only be displayed if the 'information' switch (switch 1) is on
		if sw1 == 1:
			# decoded OSC message, this needs to be done to the whole message and then
			# the goodies need to be parsed out because OSC and arrays don't mix well
			# indices 5, 6 and 7 of the 'stuff' contains hi/mid/low figures
			decoded = OSC.decodeOSC(stuff[0])
			#TODO: Sort this out. Print this every ten times this function is run
			if inductioniter % 30 == 0:
				cprint("Induction Power: Low - "+str(round(decoded[4],3))+" Mid - "+str(round(decoded[5],3))+" Hi - "+str(round(decoded[6],3)),'cyan',attrs=['dark'])
			inductioniter = inductioniter + 1
示例#23
0
文件: tools.py 项目: davk789/sc-0.2
def decode(data):
    """Converts a typetagged OSC message to a Python list.
    modified for supercollider-specific messages.
    """
    table = { "i":OSC.readInt,
              "f":OSC.readFloat,
              "s":OSC.readString,
              "b":OSC.readBlob,
              "d":OSC.readDouble}
    decoded = []
    address,  rest = OSC.readString(data)
    typetags = ""
    
    if address == "#bundle":
        time, rest = OSC.readLong(rest)
        decoded.append(address)
        decoded.append(time)
        while len(rest)>0:
            length, rest = OSC.readInt(rest)
            decoded.append(OSC.decodeOSC(rest[:length]))
            rest = rest[length:]
          
    elif len(rest) > 0:
        typetags, rest = OSC.readString(rest)
        
        decoded.append(address)
        decoded.append(typetags)
        if(typetags[0] == ","):
            for tag in typetags[1:]:
               try:
                   value, rest = table[tag](rest)
                   decoded.append(value)
               except:
                   print "%s probably not in tags list" %tag
                   print "check scOSCMessage.py - def decodeSCOSC():"
        else:
            print "Oops, typetag lacks the magic ,"
    try:
        returnList = [decoded[0]]
    except IndexError:
        returnList = []
    try:
        oldRtnList = returnList
        returnList.extend(decoded[2:])
    except IndexError:
        returnList = oldRtnList
    return returnList
示例#24
0
def main():
    # Get controller and owner
    controller = GameLogic.getCurrentController()
    owner = controller.owner
    
    # Set init
    ip = '127.0.0.1'  ### escucha router
    port = 8886
    
    '''if owner.name == "control_init":
        port = 8887
    else: 
        port = 8886'''
        
    data = 0
    
        # Connect Blender only one time
    if not owner['connected']:
        
        owner['connected'] = True
        print ("Blender Connected user_presence ", owner.name)
        print(port)
        GameLogic.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        GameLogic.socket.bind((ip, port))
        GameLogic.socket.setblocking(0)
        GameLogic.socket.settimeout(0.02)

     
    # If Blender connected, get osc
    else:
        # Get hand wii osc from pd
        data = receive_osc(data, port)
        #print(data)
        if data != 0:
            d = OSC.decodeOSC(data)
            #print("decoded: ",d)
            if d[0] == "/game/user-presence":
                    #print(d[2])
                    if d[2] == 2:
                        Game.user_presence = True
                        #print('player detected')
                    if d[2] == 1:
                        Game.user_presence = False
示例#25
0
def main():
    # Get controller and owner
    controller = GameLogic.getCurrentController()
    owner = controller.owner
    
    # Set init
    ip = '127.0.0.1'  ### escucha router
    port = 8889
        
    data = 0
    
        # Connect Blender only one time
    if not owner['connected']:
        
        owner['connected'] = True
        print ("Blender Connected game_start ", owner.name)
        print(port)
        GameLogic.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        GameLogic.socket.bind((ip, port))
        GameLogic.socket.setblocking(0)
        GameLogic.socket.settimeout(0.02)

     
    # If Blender connected, get osc
    else:
        # Get hand wii osc from pd
        data = receive_osc(data, port)
        #print(data)
        if data != 0:
            d = OSC.decodeOSC(data)
            #print("decoded: ",d)
            if d[0] == "/game/start":
                #print ("start",d[2])
                if d[2] == 1:
                    Game.start = True
                if d[2] == 0:
                    Game.start = False
示例#26
0
def OSCdecode(string):
    if string != []:
        str = ''.join(string)  #byte array to actual string
        return OSC.decodeOSC(str)
    else:
        return 0
def processingprint(add,tags,stuff,source):
	# if information switch is on
	if sw1 == 1:
		print(OSC.decodeOSC(stuff[0]))
示例#28
0
# Init OSC Client
client = OSC.OSCClient()
outPort = 9002
client.connect(("192.168.4.1", outPort))
print client

msg = OSC.OSCMessage()
msg.setAddress("/play")

#  Message format=> 0:objectID, 1:state, 2:preset 3:param1, 4:param2, n:paramN ...

# If connected
while True:
    try:
        raw_data = my_socket.recv(buffer_size)
        data = OSC.decodeOSC(raw_data)
        # print(data)

        if "plateau" in data[0]:
            k = 0
            for i in range(2, 6):
                objectOnBoard[k] = data[i]
                k += 1
            print(objectOnBoard)

        elif "params" in data[0]:
            objId = int(data[0][8])
            msg.append(objId)
            msg.append(soundObject[objId]["active"])
            msg.append(soundObject[objId]["currentPreset"])
            for i in range(2, len(data)):
示例#29
0
 def receiveOsc(self):
     raw_data = self.my_socket.recv(self.buffer_size)
     return OSC.decodeOSC(raw_data)
def baxter_teleop():
    left = baxter_interface.Limb('left')
    right = baxter_interface.Limb('right')

    neck = [0, 0, 0]
    clavicle = [0, 0, 0]
    shoulderLeft = [0, 0, 0]
    shoulderRight = [0, 0, 0]
    elbowLeft = [0, 0, 0]
    elbowRight = [0, 0, 0]
    wristLeft = [0, 0, 0]
    wristRight = [0, 0, 0]
    fingerLeft = [0, 0, 0]
    fingerRight = [0, 0, 0]

    a1 = deque([0] * 100000)
    ctr = 1
    fig = plt.figure()
    ax = plt.axes(xlim=(0,2000), ylim=(-180,180))   
    plt.hold(True)       

    def nx():
        neck[0] = x[2];

    def ny():
        neck[1] = x[2];

    def nz():
        neck[2] = x[2];

    def scx():
        clavicle[0] = x[2];

    def scy():
        clavicle[1] = x[2];

    def scz():
        clavicle[2] = x[2];

    def slx():
        shoulderLeft[0] = x[2];
    
    def sly():
        shoulderLeft[1] = x[2];

    def slz():
        shoulderLeft[2] = x[2];

    def srx():
        shoulderRight[0] = x[2];

    def sry():
        shoulderRight[1] = x[2];

    def srz():
        shoulderRight[2] = x[2];

    def elx():
        elbowLeft[0] = x[2];

    def ely():
        elbowLeft[1] = x[2];

    def elz():
        elbowLeft[2] = x[2];

    def erx():
        elbowRight[0] = x[2];

    def ery():
        elbowRight[1] = x[2];

    def erz():
        elbowRight[2] = x[2];

    def wlx():
        wristLeft[0] = x[2];

    def wly():
        wristLeft[1] = x[2];

    def wlz():
        wristLeft[2] = x[2];

    def wrx():
        wristRight[0] = x[2];

    def wry():
        wristRight[1] = x[2];

    def wrz():
        wristRight[2] = x[2];

    def hlx():
        fingerLeft[0] = x[2];

    def hly():
        fingerLeft[1] = x[2];

    def hlz():
        fingerLeft[2] = x[2];

    def hrx():
        fingerRight[0] = x[2];

    def hry():
        fingerRight[1] = x[2];

    def hrz():
        fingerRight[2] = x[2];

    options = { '/neck:tx': nx,
                '/neck:ty': ny,
                '/neck:tz': nz,
                '/shoulder_c:tx': scx, 
                '/shoulder_c:ty': scy, 
                '/shoulder_c:tz': scz, 
                '/shoulder_l:tx': slx,
                '/shoulder_l:ty': sly,
                '/shoulder_l:tz': slz,
                '/shoulder_r:tx': srx,
                '/shoulder_r:ty': sry,
                '/shoulder_r:tz': srz,
                '/elbow_l:tx': elx,
                '/elbow_l:ty': ely,
                '/elbow_l:tz': elz,
                '/elbow_r:tx': erx,
                '/elbow_r:ty': ery,
                '/elbow_r:tz': erz,
                '/wrist_l:tx': wlx,
                '/wrist_l:ty': wly,
                '/wrist_l:tz': wlz,
                '/wrist_r:tx': wrx,
                '/wrist_r:ty': wry,
                '/wrist_r:tz': wrz,
                '/handtip_l:tx': hlx,
                '/handtip_l:ty': hly,
                '/handtip_l:tz': hlz,
                '/handtip_r:tx': hrx,
                '/handtip_r:ty': hry,
                '/handtip_r:tz': hrz  }    

    
    plt.ion()
    plt.ylim([-180,180])
    plt.show()
    

    while not rospy.is_shutdown():
        data, addr = socket_comm_recv.recvfrom(16384)
        #print "Data received is "+ data

        completeList = OSC.decodeOSC(data)

        for x in OSC.decodeOSC(data):
            if isinstance(x, (list, tuple)):
                func = options[x[0]]
                func()

        neck = numpy.array(neck)
        clavicle = numpy.array(clavicle)
        shoulderLeft = numpy.array(shoulderLeft)
        shoulderRight = numpy.array(shoulderRight)
        elbowLeft = numpy.array(elbowLeft)
        elbowRight = numpy.array(elbowRight)
        wristLeft = numpy.array(wristLeft)
        wristRight = numpy.array(wristRight)
        fingerLeft = numpy.array(fingerLeft)
        fingerRight = numpy.array(fingerRight)

        bodyVectorRight = shoulderLeft - shoulderRight;
        bodyVectorLeft = -1 * bodyVectorRight;
        bodyVectorLong = clavicle - neck;

        humerusLeft = elbowLeft - shoulderLeft;
        humerusRight = elbowRight - shoulderRight;

        #print humerusLeft

        forearmLeft = wristLeft - elbowLeft;
        forearmRight = wristRight - elbowRight;

        handLeft = fingerLeft - wristLeft;
        handRight = fingerRight - wristRight;

        shoulderNormalLeft = numpy.cross(bodyVectorLeft, humerusLeft);
        elbowNormalLeft = numpy.cross(humerusLeft, forearmLeft);
        wristNormalLeft = numpy.cross(forearmLeft, handLeft);

        #print shoulderNormalLeft
        #print elbowNormalLeft
        #print wristNormalLeft

        dotProduct1 = numpy.dot(shoulderNormalLeft, elbowNormalLeft);
        dotProduct2 = numpy.dot(elbowNormalLeft, wristNormalLeft);
        
        dotProduct3 = numpy.dot(bodyVectorLong, humerusRight);
        dotProduct4 = numpy.dot(bodyVectorLong, humerusLeft)

        shoulderLeftPitch = numpy.arccos((dotProduct4) / (numpy.linalg.norm(bodyVectorLong) * numpy.linalg.norm(humerusLeft)));
        shoulderLeftYaw = numpy.arccos((numpy.dot(bodyVectorLeft, humerusLeft)) / (numpy.linalg.norm(bodyVectorLeft)*numpy.linalg.norm(humerusLeft)));
        shoulderLeftRoll = numpy.arccos(dotProduct1 / (numpy.linalg.norm(shoulderNormalLeft) * numpy.linalg.norm(elbowNormalLeft)));

        elbowLeftPitch = numpy.arccos(numpy.dot(humerusLeft, forearmLeft) / (numpy.linalg.norm(humerusLeft) * numpy.linalg.norm(forearmLeft)));
        elbowLeftRoll = numpy.arccos(dotProduct2 / (numpy.linalg.norm(elbowNormalLeft) * numpy.linalg.norm(wristNormalLeft)));

        wristLeftPitch = numpy.arccos(numpy.dot(forearmLeft, handLeft) / (numpy.linalg.norm(forearmLeft) * numpy.linalg.norm(handLeft)));

        shoulderNormalRight = numpy.cross(bodyVectorRight, humerusRight);
        elbowNormalRight = numpy.cross(humerusRight, forearmRight);
        wristNormalRight = numpy.cross(forearmRight, handRight);

        dotProduct1 = numpy.dot(shoulderNormalRight, elbowNormalRight);
        dotProduct2 = numpy.dot(elbowNormalRight, wristNormalRight);

        shoulderRightPitch = numpy.arccos((dotProduct3) / (numpy.linalg.norm(bodyVectorLong) * numpy.linalg.norm(humerusRight)));
        shoulderRightYaw = numpy.arccos((numpy.dot(bodyVectorRight, humerusRight)) / (numpy.linalg.norm(bodyVectorRight)*numpy.linalg.norm(humerusRight)));
        shoulderRightRoll = numpy.arccos(dotProduct1 / (numpy.linalg.norm(shoulderNormalRight) * numpy.linalg.norm(elbowNormalRight)));

        elbowRightPitch = numpy.arccos(numpy.dot(humerusRight, forearmRight) / (numpy.linalg.norm(humerusRight) * numpy.linalg.norm(forearmRight)));
        elbowRightRoll = numpy.arccos(dotProduct2 / (numpy.linalg.norm(elbowNormalRight) * numpy.linalg.norm(wristNormalRight)));

        wristRightPitch = numpy.arccos(numpy.dot(forearmRight, handRight) / (numpy.linalg.norm(forearmRight) * numpy.linalg.norm(handRight)));

        print "Left shoulder roll angle is %f"%(shoulderLeftRoll*180/3.1415)
        print "Right shoulder roll angle is %f"%(shoulderRightRoll*180/3.1415)

        print "Left elbow roll angle: %f"%(elbowLeftRoll*180/3.1415)
        print "Right elbow roll angle: %f"%(elbowRightRoll*180/3.1415)

        print "Left wrist pitch angle: %f"%(wristLeftPitch*180/3.1415)
        print "Right wrist pitch angle: %f"%(wristRightPitch*180/3.1415)

        anglesLeft = [abs(shoulderLeftYaw) -  2.35, 1.57 - abs(shoulderLeftPitch), abs(shoulderLeftRoll) - 4.71, abs(elbowLeftPitch) - 0.4, elbowLeftRoll, 2.5*wristLeftPitch]
        anglesRight = [2.35 - abs(shoulderRightYaw), 1.57 - abs(shoulderRightPitch), 4.71 - abs(shoulderRightRoll), abs(elbowRightPitch) - 0.4, elbowRightRoll - (shoulderRightRoll), 2.5*wristRightPitch]

   

        if anglesLeft[0] < -1.0:
            anglesLeft[0] = -1.0

        if anglesLeft[0] > 1.0:
            anglesLeft[0] = 1.0

        if anglesRight[0] > 1.0:
            anglesRight[0] = 1.0

        if anglesRight[0] < -1.0:
            anglesRight[0] = -1.0

        if anglesLeft[1] > 1.5:
            anglesLeft[1] = 1.5

        if anglesLeft[1] < -1.5:
            anglesLeft[1] = -1.5

        if anglesRight[1] < -1.5:
            anglesRight[1] = -1.5 

        if anglesRight[1] > 1.5:
            anglesRight[1] = 1.5 

        if anglesRight[3] > 3.1:
            anglesRight[3] = 3.1

        if anglesLeft[3] < 0.1:
            anglesLeft[3] = 0.1

        if anglesLeft[4] > 3.1:
            anglesLeft[4] = 3.1             

        #a1.append(anglesRight[2]*180/3.1415)
        #datatoplot = a1.pop()

        #ax.scatter(ctr, wristLeftPitch*180/3.1415)
        #ax.scatter(ctr, elbowLeftRoll*180/3.1415)
        #ax.scatter(ctr, shoulderLeftRoll*180/3.1415)
        #plt.draw()
        #ctr += 1



        #time.sleep(0.1)
        #plt.pause(0.001)

        print "Angles for the left arm are"
        print ["%0.2f" % i for i in anglesLeft]
示例#31
0
#a script to convert a static message from TCPdump to a human-readable OSC message

# sample message 17:22:53.483179 IP localhost.58799 > localhost.57120: UDP, length 20
#E..0Z.@.@.............. ...//testing....,f..?X9.

import OSC
import binascii

samplemessage = 'E..0Z.@.@.................//testing....,f..?X9.'
# strip out full stops to aid in
stripped = samplemessage.replace(".","")
edited = '/testing,f?X9'


blob = OSC.OSCMessage()
blob.append("","b")
blob.append("b","b")
blob.append("bl","b")
blob.append("blo","b")
blob.append("blob","b")
blob.append("blobs","b")
blob.append(42)

oscmsg = OSC.OSCMessage()
oscmsg.append(edited)

print OSC.decodeOSC(oscmsg.getBinary())
示例#32
0
def processingprint(add, tags, stuff, source):
    # if information switch is on
    if sw1 == 1:
        print(OSC.decodeOSC(stuff[0]))
MAXMSP_PORT = 44102
BUF_SIZE = 1024

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # UDP
sock.bind((MAXMSP_IP, MAXMSP_PORT))


def eye_start():
    print "start the eyetracker here"


def eye_stop():
    print "stop the eyetracker"


def experiment_end():
    sock.close()
    os._exit(0)


# map the integer values received from Max/MSP into method calls
dispatch = {1: eye_start, 2: eye_stop, 99: experiment_end}

while True:
    data, addr = sock.recvfrom(BUF_SIZE)
    datatype, abbrev, value = OSC.decodeOSC(data)
    if value in dispatch:
        dispatch[value]()
    else:
        print "unrecognized message: ", value
示例#34
0
    vals = {'time':-1, 'y':-1, 'p':-1,'r':-1, 'batt':-1,'side':-1, 'packet':-1}
    out = []
    buff = 256 #number of vals to collect before store
    old_time = 0

    # write header
    today = strftime("%d-%m-%y-%s")
    output_file = open('datarecord_{0}_{1}_{2}_r{3}g{4}b{5}.csv'
                      .format(today, endpoint[1:-1], args.update, args.red, args.green, args.blue) , 'wb')
    dict_writer = csv.DictWriter(output_file, vals.keys())
    dict_writer.writeheader()

    try:
        while 1:
            data, addr = sock.recvfrom(2048)
            data = OSC.decodeOSC(data)[2:] #get rid of header
            
            vals['time'] = data[0][2]
            vals['y'] = data[1][2]
            vals['p'] = data[1][3]
            vals['r'] = data[1][4]
            vals['batt'] = data[2][2]
            vals['side'] = data[3][2]
            vals['packet'] = data[4][2]

            print('recieved\tmess: {0}\ttime diff:{1}'.format(len(out),(vals['time']-old_time)))
            old_time = vals['time']

            out.append(copy.copy(vals))
            vals = dict.fromkeys(vals, -1) #clear dict
示例#35
0
#!/usr/bin/python
import serial
import sliplib
import OSC
from time import sleep
def serial_data(port, baudrate):
	ser = serial.Serial(port, baudrate)
	while True:
#		ser.write([192,47,103,101,116,107,110,111,98,115,0,0,0,44,0,0,0,192]) #/getknobs OSC/slipenc
		bytesToRead=ser.inWaiting()
		if bytesToRead != 0:
			yield ser.read(bytesToRead)
	ser.close()

driver=sliplib.Driver()
for line in serial_data('/dev/ttyS1', 115200):
#	half=driver.receive(line)
	print OSC.decodeOSC(''.join(driver.receive(line)))
	sleep(.1)
示例#36
0
#!/usr/bin/python
import socket
import OSC

localhost = "127.0.0.1"
listenport = 4001

sock = socket.socket(
    socket.AF_INET,  # Internet
    socket.SOCK_DGRAM)  # UDP
sock.bind((localhost, listenport))

while True:
    data, addr = sock.recvfrom(1024)  # buffer size is 1024 bytes
    print OSC.decodeOSC(data.strip("\n").strip(";"))
示例#37
0
    def _handleInput(self):
        message = OSC.decodeOSC(self._inBuffer) #decode the message and make an array of it
        if len(message) != 0: #if the message is present
            print str(message[2]) #print our temperature

        self._inBuffer = '' #wipe the serial buffer