def serve(self):
        with serial.Serial(port=self.port,
                           baudrate=self.baudrate,
                           timeout=self.timeout) as ser:
            sleep(1)
            # first clear anything on the incoming port
            ser.timeout = 0
            while ser.read():
                pass
            ser.timeout = self.timeout

            # now give the handshake!
            sleep(1)
            ser.write(b'|')
            sleep(1)
            print('Started... ctrl-C to exit')

            while True:
                try:
                    if self.stopEvent:
                        print('\nexting...')
                        break
                    res = self.slipDecoder.decodeFromSLIP(
                        ser.read(16))  # 16 bytes
                    if res:
                        # we got a complete OSC message and can dispatch it
                        self.dispatcher.dispatchOSCList(decodeOSC(bytes(res)))
                    # now continue serving...
                except KeyboardInterrupt:
                    self.stopEvent = True
Exemple #2
0
def find_mixer():
    client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True)
    client.sendto("/xinfo\0\0", ("<broadcast>", XAirClient.XAIR_PORT))
    try:
        response = decodeOSC(client.recv(512))
    except socket.timeout:
        print "No server found"
        return None
    client.close()

    if response[0] != '/xinfo':
        print "Unknown response"
        return None
    else:
        print "Found " + response[4] + " with firmware " + response[5] + " on IP " + response[2]
        return response[2]
Exemple #3
0
 def _applyOscControlData(self, oscMsg):
     """ Callback function that is called when data is received on the control data port"""
     try:
         msg = decodeOSC(oscMsg)
         msgAddress = msg[0]
         msgPayload = msg[2:]
         # This will fail with OSC bundles (which need some recursive handling)
         addressParts = msgAddress[1:].split(
             b'/')  # Avoid a split at the leading '/'
         if len(addressParts) < 2:
             print(
                 "Received OSC message does not fit the \"/processor/parameter\" scheme."
             )
         processorName = addressParts[0].decode()
         paramNameList = addressParts[1:]
         paramName = '/'.join([x.decode() for x in paramNameList
                               ])  # Transform byte arrays->strings
         self._transmitControlData(processorName, paramName, msgPayload)
     except BaseException as ex:
         print(
             'MetadataAdaptationEngine.controlDataReceived(): Parsing exception: %s'
             % str(ex))
#!/usr/bin/python2

import socket
from OSC import decodeOSC

ip = '127.0.0.1'
port = 6789
buffer_size = 1024
do_loop = True

# Connect
my_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
    my_socket.bind((ip, port))
    my_socket.setblocking(0)
    my_socket.settimeout(0.002)
    my_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, buffer_size)
    print 'Plug : IP = ', ip, 'Port = ', port, 'Buffer Size =', buffer_size
except:
    print 'No connected'
    pass

# If connected
while do_loop:
    try:
        raw_data = my_socket.recv(buffer_size)
        data = decodeOSC(raw_data)
        print(data)
    except socket.error:
        pass
Exemple #5
0
    def run(self):
        # -------- Main Program Loop -----------
        while not self._done:
            # --- Main event loop
            for event in pygame.event.get(): # User did something
                if event.type == pygame.QUIT: # If user clicked close
                    self._done = True # Flag that we are done so we exit this loop

                elif event.type == pygame.VIDEORESIZE: # window resized
                    self._screen = pygame.display.set_mode(event.dict['size'], 
                                               pygame.HWSURFACE|pygame.DOUBLEBUF|pygame.RESIZABLE, 32)
                    
            # --- Game logic should go here

            # --- Getting frames and drawing  
            # --- Woohoo! We've got a color frame! Let's fill out back buffer surface with frame's data 
            if self._kinect.has_new_color_frame():
                
		#frame = self._kinect.get_last_color_frame()
                #frame = pygame.image.load("gradient.png")
		#frame = None
		#self.draw_color_frame(frame, self._frame_surface)
                frame = None

            # --- Cool! We have a body frame, so can get skeletons
            if self._kinect.has_new_body_frame(): 
                self._bodies = self._kinect.get_last_body_frame()

            # --- draw skeletons to _frame_surface
            if self._bodies is not None: 
                for i in range(0, self._kinect.max_body_count):
		    # print 'bodies number %s' % self._kinect.max_body_count
		
		#for i in range(0, 1): DOES NOT WORK FOR WHEN HE LOOSES TRACK OF FIRST BODY i=0 
		# HE DOES NOT HIT THE OTHERS
                    
		    body = self._bodies.bodies[i]
                    if not body.is_tracked: 
                        continue 
		    
		    bodyN = i
               	    oscmsg5 = OSC.OSCMessage()
		    
	            # set the tag of the message
         	    oscmsg5.setAddress("/bodyN")
            
             	    # its content
            	    oscmsg5.append(bodyN)
            
            	    self._client.send(oscmsg5)

                    joints = body.joints 
                    # convert joint coordinates to color space 
                    joint_points = self._kinect.body_joints_to_color_space(joints)
                    self.draw_body(joints, joint_points, SKELETON_COLORS[i])
	            
		    # send body points through OSC
                    self.sendOSC_twoPoints( joints, joint_points, PyKinectV2.JointType_HandLeft, PyKinectV2.JointType_HandRight)
	    else:
		print 'no bodies detected'

            # --- copy back buffer surface pixels to the screen, resize it if needed and keep aspect ratio
            # --- (screen size may be different from Kinect's color frame size) 
            
	    h_to_w = float(self._frame_surface.get_height()) / self._frame_surface.get_width()
            target_height = int(h_to_w * self._screen.get_width())
            surface_to_draw = pygame.transform.scale(self._frame_surface, (self._screen.get_width(), target_height));
            self._screen.blit(surface_to_draw, (0,0))			
            surface_to_draw = None
            pygame.display.update()

	    
 	    # receive OSC message to grab a color frame
	    try:
		raw_data = self._my_socket.recv(self._server_buffer_size)
	    	data = decodeOSC(raw_data)
		print data
		if data[0] == '/foto':
			if data[2] == 1:
				frame = self._kinect.get_last_color_frame()
				self.draw_color_frame(frame, self._frame_surface)
				pygame.image.save(self._frame_surface, "foto.jpg") # save it
	
	    			frame = None

	    except socket.error:
		pass
	    except KeyboardInterrupt:
		pass
	               	
	     
	    frame = None
	    	
	    
            # --- Go ahead and update the screen with what we've drawn.
            pygame.display.flip()

            # --- Limit to 60 frames per second
            self._clock.tick(10)

        # Close our Kinect sensor, close the window and quit.
        self._kinect.close()
	try:
	   sys.stderr.close()
	except:
	   print('some error going on')
	   pass
        print 'Fechei'
        pygame.quit()
Exemple #6
0
		if msg == "#bundle":
			for arg in args:
				self.messageReceived(arg)
			return
		if self.handlers.has_key(msg):
			try:
				self.handlers[msg](*args)
			except:
				a,b,c = sys.exc_info()
				sys.excepthook(a,b,c)
				print "with '%s'" % repr((msg,args))
			return
		print "no handler for '%s'" % repr((msg,args))

	def datagramReceived(self, data, (host, port)):
		self.messageReceived(decodeOSC(data))

	def getPacketNumber(self):
		packetNumber = self.nextPacketNumber
		self.nextPacketNumber = (self.nextPacketNumber + 1)
		return packetNumber
		
	def sendMsg(self,msg,*args):
		packetNumber = self.getPacketNumber()
		print "Sending %r (#%i)..." % (msg,packetNumber)
		omcall = Call()
		omcall.result = None
		omcall.done = False
		self.calls[packetNumber] = omcall
		message = OSCMessage()
		message.setAddress(msg)
Exemple #7
0
 def handle(self):
     """Handle incoming OSCMessage
     """
     decoded = decodeOSC(self.packet)
     self.message_wrangler(decoded)