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

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


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

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


    server.close()
Beispiel #3
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()
	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()
Beispiel #5
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()
Beispiel #6
0
    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()
Beispiel #7
0
def main(opts):
    server = OSCServer((opts.ip_addres, int(opts.port)))
    server.handle_timeout = types.MethodType(handle_timeout, server)
    server.addMsgHandler("/user", user_callback)
    server.addMsgHandler("/quit", quit_callback)
    log_post('INFO: listening on to %s:%s' % (opts.ip_addres, opts.port))
    spinner_ = spinner()
    while run:
        each_frame(server)

        sys.stdout.write(spinner_.next())
        sys.stdout.flush()
        sleep(0.5)
        sys.stdout.write('\b')

    server.close()
Beispiel #8
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()
Beispiel #9
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()
Beispiel #10
0
class OscServer:
    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)

    def on_msg(self, path, f):
        def go_zero(path, tags, args, source):
            f()            

        def go_args(path, tags, args, source):
            f(*args)

        if f.func_code.co_argcount == 0:
            go = go_zero
        else:
            go = go_args

        self.server.addMsgHandler(path, go)

    def start(self):
        self.thread.start()
        try :
            while 1 :
                time.sleep(10) 
        except KeyboardInterrupt :
            print "\nClosing OSCServer."
            self.server.close()
            print "Waiting for Server-thread to finish"
            self.thread.join()
            print "Done"

    def close(self):
        self.server.close()    
        try:
            self.thread.join()
        except:
            pass
        print "Done"
Beispiel #11
0
class OscServer:
    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)

    def on_msg(self, path, f):
        def go_zero(path, tags, args, source):
            f()

        def go_args(path, tags, args, source):
            f(*args)

        if f.func_code.co_argcount == 0:
            go = go_zero
        else:
            go = go_args

        self.server.addMsgHandler(path, go)

    def start(self):
        self.thread.start()
        try:
            while 1:
                time.sleep(10)
        except KeyboardInterrupt:
            print "\nClosing OSCServer."
            self.server.close()
            print "Waiting for Server-thread to finish"
            self.thread.join()
            print "Done"

    def close(self):
        self.server.close()
        try:
            self.thread.join()
        except:
            pass
        print "Done"
Beispiel #12
0
class OSCForwarder(threading.Thread):
   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()

   # close must be called before app termination or the app might hang
   def close(self):
      # this is a workaround of a bug in the OSC server
      # we have to stop the thread first, make sure it is done,
      # and only then call server.close()
      self.server.running = False

      while not self.done_running:
         time.sleep(.01)
      self.server.close()

   def run(self):
      #print "Worker thread entry point"
      self.server.serve_forever()
      self.done_running = True


   def callback(self, path, tags, args, source):
      #print 'got:', path, args, 'from:', source
      self.client.send( OSCMessage(path, args ) )
Beispiel #13
0
class OSCForwarder(threading.Thread):
   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()

   # close must be called before app termination or the app might hang
   def close(self):
      # this is a workaround of a bug in the OSC server
      # we have to stop the thread first, make sure it is done,
      # and only then call server.close()
      self.server.running = False

      while not self.done_running:
         time.sleep(.01)
      self.server.close()

   def run(self):
      #print "Worker thread entry point"
      self.server.serve_forever()
      self.done_running = True


   def callback(self, path, tags, args, source):
      #print 'got:', path, args, 'from:', source
      self.client.send( OSCMessage(path, args ) )
Beispiel #14
0
def main():
    #incoming(HOST,PORT)
    server = OSCServer(('127.0.0.1',42003))
    client = OSC.OSCClient()
    client.connect(('127.0.0.1',42002))

    server.addDefaultHandlers()
    server.addMsgHandler("/exo/hand/gesture",handler_func)

    st = threading.Thread( target = server.serve_forever )
    st.start()

    try :
        while 1 :
                time.sleep(10)
    except KeyboardInterrupt :
        print "\nClosing OSCServer."
        s.close()
        print "Waiting for Server-thread to finish"
        st.join()
        print "Done"

    server.close()
class KinectReceiver(avg.Publisher):
    """Class to process OSC messages from the kinect tracking system.
    Subscribers will receive messages for each joint or kill,
    containing either [skeleton_id, skeleton_joint] or [skeleton_id, 'kill')
    """

    OSC_kinect_MessageID = avg.Publisher.genMessageID()
    OSC_kinect_hand_MessageID = avg.Publisher.genMessageID()

    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)

    def __handle_timeout(self, statusnachricht):
        """Handle server timeouts."""
        self.__server.timed_out = True

    def onFrame(self):
        """Stay active."""

        self.__server.timed_out = False
        # handle all pending requests than return
        while not self.__server.timed_out:
            self.__server.handle_request()

    def run(self):
        """Start running the server."""
        while True:
            self.__server.handle_request()

        self.__server.close()

    def __on_osc_joint_message_received(self, addr, tags, data,
                                        client_address):
        """Receives an OSC message, transforms the data and
        notifies subscribers by sending a message (type: list) containing skeleton_id and
        skeleton_joint (type: SkeletonJoint)

        Args:
            addr: the address (str e.g. /joint)
            tags: tags (str with i for int32 and f for float, e.g. iiiifff)
            data: tracking data, containing
                    id, convertMode, jointtype, trackingstate, and if trackingstate != OKTS_NOTTRACKED, x,y and z
            client_address: client address as (ip, port) tuple
        """

        # check if length could actually be a skeleton joint message
        if len(data) < 4:
            return

        # initialize position values
        x = 0
        y = 0
        z = 0

        # only if joint is tracked, additional position values are given
        if data[3] is not OSCJointTrackingState.OKTS_NOTTRACKED and len(
                data) >= 7:
            x = data[4]
            y = data[5]
            z = data[6]

        # create the skeleton joint from received data
        # joint_type = OSCKinectJoint(data[2])
        joint_type = data[2]
        skeleton_joint = SkeletonJoint(x, y, z, joint_type)
        skeleton_joint.tracking_state = data[3]

        # add skeletonID to active skeleton list
        if data[0] not in self.__active_skeleton_ids:
            self.__active_skeleton_ids.append(data[0])

        # message for subscribers consists of skeletonID and joint
        message = [data[0], skeleton_joint]

        # send new skeleton_joint to subscriber

        self.notifySubscribers(self.OSC_kinect_MessageID, [message])

    def __on_osc_hand_message_received(self, addr, tags, data, client_address):
        """
            received hand state events from oscserver and if this skeleton already exists
            it norfies subscribers with message skeleton_id and list["left"/"right", value]
        """
        if len(data) < 3:
            return

        if data[1] != "left" and data[1] != "right":
            return

        if data[0] in self.__active_skeleton_ids:
            message = [data[0], (data[1], data[2])]
            self.notifySubscribers(self.OSC_kinect_hand_MessageID, [message])

    def __on_osc_kill_message_received(self, addr, tags, data, client_address):
        """
        receives the kill event from oscserver and
        reacts by sending out a message (list) ONCE that includes skeleton_id and 'kill'
        """

        # kill will be received constantly, only send message once
        # when skeletonID is still in active skeleton list
        if data[0] in self.__active_skeleton_ids:
            # message for subscribers consists of skeletonID and 'kill'
            message = [data[0], 'kill']
            # send message

            self.notifySubscribers(self.OSC_kinect_MessageID, [message])
            # remove skeletonID from active skeleton list
            self.__active_skeleton_ids.remove(data[0])
        pass
Beispiel #16
0
    #         self.send_response(301)

    #         self.end_headers()
    #         upfilecontent = query.get('upfile')
    #         print "filecontent", upfilecontent[0]
    #         self.wfile.write("<HTML>POST OK.<BR><BR>");
    #         self.wfile.write(upfilecontent[0]);

    #     except :
    #         pass


if __name__ == "__main__":
    # will get better args
    if sys.argv[1:]:
        http_port = int(sys.argv[1])
    else:
        http_port = 8000
    osc_host = "127.0.0.1"
    osc_port = 12000
    try:
        sc = OSCServer((osc_host, osc_port))
        client = OSCClient(sc)
        server = HTTPServer(("", http_port), JSONHandler)
        print "started http to OSC bridge..."
        server.serve_forever()
    except KeyboardInterrupt:
        print "^C received, shutting down server"
        server.socket.close()
        sc.close()
Beispiel #17
0
    process_run = Popen('./runtrace.sh', stdout=PIPE, stderr=PIPE, shell=True)


SERVER.addMsgHandler("/run", user_callback)
SERVER.addMsgHandler("/stop", quit_callback)


class KeyboardInterruptError(Exception):
    pass


def process_frame():
    SERVER.timed_out = False
    while not SERVER.timed_out:
        SERVER.handle_request()


while oscserver_run:
    try:
        process_frame()
        time.sleep(0.1)
    except KeyboardInterrupt:
        oscserver_run = False

process_stop = Popen(['tmux', 'kill-server'],
                     stdout=PIPE,
                     stderr=PIPE,
                     shell=True)
SERVER.close()
clean_screen()
Beispiel #18
0
class Server():

    """Listener to collect results of Keykit server.

    (Adaption of OSC package example.)
    """

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

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

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

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

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

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

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

        self.server.close()

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

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

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

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

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

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

        if self.keykit_lsdir_string[-1] == "$":
            try:
                lsdir = []
                # Convert string into list of files. Second argument flags
                # directories.
                # Example string:  ^["foldername"=1,"filename"=0]$
                re_entries = '".+?"=[01][,\]]'
                entries = re.finditer(re_entries, self.keykit_lsdir_string)
                for entry in entries:
                    sname = entry.group()[1:-4]
                    bFolder = entry.group()[-2] == "1"
                    lsdir.append((sname, bFolder))

                self.keykit_lsdir = lsdir
            except:
                sys.stderr.write("(dir_callback) Unable to fetch folder content.")
                self.keykit_lsdir = []
class OptiTrackReceiver(avg.Publisher):
    OSC_optitrack_MessageID = avg.Publisher.genMessageID()
    OSC_optitrack_KillMessageID = avg.Publisher.genMessageID()

    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

    def __handle_timeout(self, status):
        """Handle server timeouts."""
        self.__server.timed_out = True

    def onFrame(self):
        """Stay active."""
        self.__server.timed_out = False
        # handle all pending requests than return
        while not self.__server.timed_out:
            self.__server.handle_request()

    def run(self):
        """Start running the server."""
        while True:
            self.__server.handle_request()
        self.__server.close()

    def __on_osc_rigidbody_message_received(self, addr, tags, data, client_address):
        """b
        Receives an OSC message, transforms the data and
        notifies subscribers by sending a message (type: list) containing skeleton_id and
        skeleton_joint (type: SkeletonJoint)

        Args:
            addr: the address (str e.g. /tracking/optitrack/rigidbodies)
            tags: tags (str with i for int32 and f for float, e.g. iiiifff)
            data: tracking data, containing
                    id (0), position in space (1-3), and orientation in space (4-6)
            client_address: client address as (ip, port) tuple
        """

        # check if length could actually be a rigid body message
        if len(data) < self.__osc_format_length:
            return

        data[self.__index_x] = data[self.__index_x] * 100
        data[self.__index_y] = config.display_height_cm - data[self.__index_y] * 100
        data[self.__index_z] = data[self.__index_z] * 100

        # create RigidBody tuple
        rb = RigidBody(
            id=data[self.__index_id],
            name=data[self.__index_name],
            position=Point3D(data[self.__index_x], data[self.__index_y], data[self.__index_z]),
            orientation=(data[self.__index_roll], data[self.__index_pitch], data[self.__index_yaw]),
            orientation_quat=(data[self.__index_quat_1], data[self.__index_quat_2], data[self.__index_quat_3], data[self.__index_quat_4]),
            markers=None,
            mrk_ids=None,
            mrk_sizes=None,
            mrk_mean_error=None
        )

        # send new rigidbody to subscriber
        self.notifySubscribers(self.OSC_optitrack_MessageID, [rb])

    def __on_osc_kill_message_received(self, addr, tags, data, client_address):
        """
        receives the kill event from oscserver and
        reacts ??
        """
        self.notifySubscribers(self.OSC_optitrack_KillMessageID, data)
Beispiel #20
0
class Osc(object):
    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()

    # Close the socket on exit
    def cleanup(self):
        self.server.close()

    def got_a_packet(self):
        self.opacity = 1.0
        self.last_msg_time = time.time()
        self.anim_queue.clear()

    # Set the current color in either RGB or HSV colorspace
    def set_rgbw(self, path, tags, args, source):
        self.color.setRGBW(*args)
        self.got_a_packet()

    def set_rgb(self, path, tags, args, source):
        self.color.setRGB(*args)
        self.got_a_packet()

    def set_r(self, path, tags, args, source):
        print path, tags, args, source
        self.color.setR(args[0])
        self.got_a_packet()

    def set_g(self, path, tags, args, source):
        self.color.setG(args[0])
        self.got_a_packet()

    def set_b(self, path, tags, args, source):
        self.color.setB(args[0])
        self.got_a_packet()

    def set_w(self, path, tags, args, source):
        self.color.setB(args[0])
        self.got_a_packet()

    def set_hsv(self, path, tags, args, source):
        self.color.setHSV(*args)
        self.got_a_packet()

    def set_h(self, path, tags, args, source):
        self.color.setH(args[0])
        self.got_a_packet()

    def set_s(self, path, tags, args, source):
        self.color.setS(args[0])
        self.got_a_packet()

    def set_v(self, path, tags, args, source):
        self.color.setV(args[0])
        self.got_a_packet()

    # This gets called when we have no more packets waiting to be processed
    def handle_timeout(self):
        self.timed_out = True

    # This function retrieves the next color from the Audio object
    def next(self, color_in):
        # process any messages we might have waiting for us.  We do this by calling handle_request() until
        # handle_timeout() gets called, at which point we stop:
        self.timed_out = False
        while not self.timed_out:
            self.server.handle_request()

        # If we've not received a message for `timeout` seconds, slowly ease back to 1.0 power
        if self.last_msg_time + self.timeout < time.time(
        ) and self.opacity != 0.0:
            # Ease slowly from the current value of self.opacity to 0.0
            self.anim_queue.push(
                ease(self.opacity, 0.0, self.timeout_fade_duration, sin_ease))

            # This ensures that once the animation is done, we stay at 0.0, and also that we
            # don't keep on animating over and over again (e.g. the if statement directly above
            # doesn't keep on activating over and over again)
            self.opacity = 0.0

        # If we're easing back to 0.0 after a client disconnect, then this animation does something.
        # If we're receiving packets like normal, this animation does nothing, it just returns self.opacity
        animated_opacity = self.anim_queue.animate(default_value=self.opacity)

        # Mix between color_in and our stored self.color
        return color_in * (1.0 -
                           animated_opacity) + animated_opacity * self.color
Beispiel #21
0
def main(robotIP, PORT = 9559):
    myBroker = ALBroker("myBroker", #needed for subscribers and to construct naoqi modules
        "0.0.0.0",
        0,
        robotIP,
        PORT)

    meanx = 0.21835
    meany = 0.035625

    global ReactToTouch, go_to_center, global_time
    global server, client
    client = OSCClient()
    client.connect(("192.168.0.5",1234))

    global motionProxy, jointNames
    
    motionProxy = ALProxy("ALMotion", robotIP, PORT)
    postureProxy = ALProxy("ALRobotPosture", robotIP, PORT)

    motionProxy.setStiffnesses("Body",0)
    motionProxy.setStiffnesses(jointNames,1)

    #motionProxy.openHand("LHand")
    #motionProxy.closeHand("LHand")
    maxSpeedFraction  = 0.3
    for i in range(1):
        motionProxy.angleInterpolationWithSpeed(jointNames, p[i], maxSpeedFraction)
        time.sleep(1.0)    

    minx = -999
    maxx = 999
    miny = -999
    maxy = 999
    # Copy from inverse kinematics
    effector   = "LArm"
    space      = motion.FRAME_ROBOT
    axisMask   = almath.AXIS_MASK_VEL    # just control position
    isAbsolute = False

    # Since we are in relative, the current position is zero
    currentPos = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
    center = currentPos

    # Define the changes relative to the current position
    dx         =  0.03      # translation axis X (meters)
    dy         =  -0.04     # translation axis Y (meters)
    dz         =  0.03      # translation axis Z (meters)
    dwx        =  0.00      # rotation axis X (radians)
    dwy        =  0.00      # rotation axis Y (radians)
    dwz        =  0.00      # rotation axis Z (radians)
    targetPos  = [dx, dy, dz, dwx, dwy, dwz]

    # Go to the target and back again
    path       = [targetPos]
    times      = [1.5] # seconds

    motionProxy.positionInterpolation(effector, space, path,
                                      axisMask, times, isAbsolute)
    dz=0.00

    currentPos = motionProxy.getPosition(effector, space, True)
    offx = 0.034
    offy = 0.02
    xy=[1345+103-(currentPos[0]+offx)*400/(0.07), (currentPos[1]+offy)*400/(0.07)+11-87-45]
    #print xy

    input('Press 1 to begin: ')
    k=2.5
    L=0.5
    n=10
    speed = 0.15
    #Initialize listener
    ReactToTouch = ReactToTouch("ReactToTouch")

    center = motionProxy.getPosition(effector, space, True)
    print "center: " + str(center[0]) + ", " + str(center[1])
    
    try:
      while 1:#for i in range(n):

        if go_to_center:
            if random.random()<0.95:
                k=max(0.9,k-0.15)
            speed = 0.4
            go_to_center = False
            #print 'going to center!'
            # Get current Position & define target position
            if random.random()<0.8:
                currentPos = motionProxy.getPosition(effector, space, True)
                maxx = min(maxx,abs(currentPos[0]-meanx))
                maxy = min(maxy,abs(currentPos[1]-meany))
                
            #targetPos = currentPos
            targetPos[0] = center[0]
            targetPos[1] = center[1]
            targetPos[2] = center[2]
            #print 'new target'
            #print targetPos
            # Move to position, being able to interrupt
            motionProxy.setPosition(effector, space, targetPos, speed, axisMask)
            #Try it twice, because it doesn't seem to get there
            '''currentPos = motionProxy.getPosition(effector, space, True)
            motionProxy.positionInterpolation(effector, space, [currentPos],
                                      axisMask, [0.51], isAbsolute)
            targetPos  = [currentPos[0]-center[0], currentPos[1]-center[1], currentPos[2]-center[2], 0.0, 0.0, 0.0]
            path       = [targetPos]
            print targetPos
            motionProxy.positionInterpolation(effector, space, path,
                                      axisMask, [0.51], isAbsolute)
            print "sleeping 2 seconds"'''
            
            global_time = time.time()
        else:
            speed = 0.18
            # False learning
            if random.random()<0.15:
                k=max(0.85,k-0.15)

            # Generate next target x,y
            x = k*random.random()*L-L/2 + center[0]
            y = k*random.random()*L-L/2 + center[1]
            # Get current Position & define target position
            #currentPos = motionProxy.getPosition(effector, space, True)
            #targetPos = currentPos
            
            targetPos[0] = x#min(max(x,meanx-maxx),meanx+maxx)
            targetPos[1] = y#min(max(y,meany-maxy),meany+maxy)
            targetPos[2] = center[2]
            #print 'new target'
            #print targetPos
            # Move to position, being able to interrupt
            motionProxy.setPosition(effector, space, targetPos, speed, axisMask)
        now = time.time()
        go_to_center = False
        while time.time()-now < times[0] and not go_to_center:
            #time.sleep(0.1)
            currentPos = motionProxy.getPosition(effector, space, True)
            offx = 0.034
            offy = 0.04
            xy=[1345+97-(currentPos[0]+offx)*400/(0.07), (currentPos[1]+offy)*400/(0.07)+107-87-45]
            #print xy
            sendOSC('/xy',xy)
            time.sleep(0.01)

        print 'out of the loop'
        """else:
            #currentPos = motionProxy.getPosition(effector, space, True)
            #center[0] -= targetPos[0]
            #center[1] -= targetPos[1]
        """
      print 'Done!'

    
      

      server = OSCServer( ("" , 2222) )
      server.addMsgHandler("/move", move)
    
      while 1:
            server.handle_request()
    except KeyboardInterrupt:
        print "closing all OSC connections... and exit"
        
        motionProxy.rest()
        myBroker.shutdown()
        server.close() 


    motionProxy.rest()
Beispiel #22
0
class Kinect:
    """Manages connection to Kinect, and saves and processes coordinates"""
    
    @staticmethod
    def retrieve(joints=None, max_port=5555):
        """ Retrieves a singleton Kinect instance, and creates it if it doesn't exist. """
        global kinect_instance
        if kinect_instance is None:
            kinect_instance = Kinect(joints, max_port)
        return kinect_instance
    
    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)
        #sprout(self._calc_speed)
    
    def __enter__(self):
        return self
    
    def __exit__(self, _type, value, traceback):
        self.server.close()
        self.kinect_client.close()
        self.max_client.close()
    
    def process_message(self, addr, tags, data, source):
        """process data coming in from Synapse, happens about every 0.03 seconds"""
        
        if addr[-9:] == '_pos_body':
            if self.flipped:
                if addr[:5] == '/left':
                    addr = '/right' + addr[5:]
                    data[X] = -data[X]
                elif addr[:6] == '/right':
                    addr = '/left'+addr[6:]
                    data[X] = -data[X]
            self.coords[addr[1:-9]] = data
    
    def _remind_synapse(self):
        """Send Synapse an OSC message to ask it to continue polling the required joints"""
        while True:
            for track in self.joints:
                self.sendToKinect('/'+track+'_trackjointpos', 1)
            time.sleep(1)
    
    def calc_speed(self):
        """Calculate speed of movement, at 0.06 second intervals"""
        self.calculating_speed = True
        while self.calculating_speed:
            total_speed = 0.
            for joint, v in self.coords.items():
                magnitude = Magnitude(v)
                prev_magnitude = Magnitude(self.prev_coords[joint])
                speed = abs(magnitude - prev_magnitude)
                if joint in ('lefthand', 'righthand'):
                    speed_x = Distance(SubVector(self.prev_coords[joint], X), 
                                              SubVector(self.coords[joint], X))
                    speed_y = Distance(SubVector(self.prev_coords[joint], Y), 
                                              SubVector(self.coords[joint], Y))
                    self.speed_piano[joint][X] += (speed_x - self.speed_piano[joint][X]) * 0.5
                    self.speed_piano[joint][Y] += (speed_y - self.speed_piano[joint][Y]) * 0.5
                total_speed += speed
            total_speed /= len(self.coords)
            self.speed = total_speed
            self.speed_ramp = self.speed_ramp + (self.speed - self.speed_ramp) * 0.125
            self.prev_coords = copy.copy(self.coords)
            time.sleep(0.06)
    
    @property
    def area(self):
        return Area( self.coords['head'], 
                     self.coords['lefthand'], 
                     self.coords['leftfoot'], 
                     self.coords['rightfoot'], 
                     self.coords['righthand'] ) / 1000000.
        
    @property
    def facing(self):
        return self.coords['rightfoot'][X] >= self.coords['leftfoot'][X]
    
    def hand_down(self, hand):
        return self.coords[hand][Y] < 0 and self.hand_over_piano(hand)
    
    def hand_up(self, hand):
        return self.coords[hand][Y] >= 0 or not self.hand_over_piano(hand)

    def hand_over_piano(self, hand):
        return Magnitude(SubVector(self.coords[hand], Y,Z)) > 350
    
    def hand_hit(self, hand):
        """waits for a hit from the specified hand"""
        if self.hand_down(hand):
            wait_for(self.hand_up, (hand,))
        wait_for(self.hand_down, (hand,))
        
        return self.coords[hand][X]
        
    def joint_moved_x(self, prev_x, joint, hit_location):
        """used to wait for a change in joint in X dimension"""
        if self.hand_up(joint):
            return True
        if hit_location is not None and abs(hit_location - self.coords[joint][X]) < 140:
            return False
        return abs(prev_x - self.coords[joint][X]) > 70
    
    def hand_slide(self, hand, hit_location):
        x = self.coords[hand][X]
        wait_for(self.joint_moved_x, (x, hand, hit_location))
        
        if self.hand_up(hand):
            return False
        return self.coords[hand][X]
    
    def get_coord(self, joint):
        if joint == 'leftshoulder':
            return -250, 200, -50
        elif joint == 'rightshoulder':
            return 250, 200, -50
        else:
            return self.coords[joint]
    
    def sendToKinect(self, address, items):
        self._sendMsg(self.kinect_client, address, items)
    
    def sendToMax(self, address, items):
        self._sendMsg(self.max_client, address, items)
    
    @staticmethod
    def _sendMsg(client, address, items):
        m = OSCMessage()
        m.setAddress(address)
        m.append(items)
        client.send(m)
class LiveRawAPI(object):
    """
    This is close to live's API objects as possible
    Of course, they are designed to be manipulated from a patcher,
    not real code, so a bit more wrapping is in order.
    To keep everything minimal, this is done in a subclass.
    """
    _incoming = None
    _handled = True
    _received = False
    debug = False
    
    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 = []

    def raw_query(self, *args):
        """Posts a query, waits for a response. Returns it.
        Note that state is fragile here, so you'd better be sure that there 
        will be a response, or it will hang waiting."""

        self.oscclient.send(OSCMessage('/query', args))
        return self.handle_request()
    
    def raw_call(self, *args):
        """Posts a call, returns nothing.
        Note that state is fragile here, so you'd better be sure that there 
        will be no response, or you won't know what returned what."""
        self.oscclient.send(OSCMessage('/query', ['path', 'getpath']))
    
    def _handle_response(self, path, tags, args, source):
        """private callback to handle OSC responses. Sets state."""
        if self.debug: print "callback", path, args, source
        self._incoming.append(args)
        self._received = True
    
    def handle_request(self):
        """hack to handle asynchronous calls:
        1 try to get something returned and tacked onto the class.
        2 Return it and reset.
        This is completely f****d at the momenl I can't make timeouts work in any usable fashion."""
        
        try:
            self.oscserver.handle_request()
            while self._received:
                self._received = False
                self.oscserver.handle_request()
            
            _incoming = self._incoming
            return _incoming
        finally:
            self._incoming = []
            self._received = False            
        
    def close(self):
        self.oscserver.close()

    ### more structured access involves navigating places with the path object
    def goto(self, *args):
        resp = self.raw_query('path', 'goto', *args)
        prefix, path = resp[1], resp[2:]
        #sanity check that we are getting the right message
        assert prefix=='path'
        self.path = path
    
    def path(self, *args):
        return self.goto(*args)

    def getchildren(self):
        resp = self.raw_query('path', 'getchildren')
        return resp[1:]

    def getcount(self):
        resp = self.raw_query('path', 'getcount')
        return resp[1:]
# OSC Communication
# - receiving OSC Messages in Python

from OSC import OSCServer
import time, threading 

recvAddress = ('127.0.0.1', 9001) 
oscServer = OSCServer(recvAddress)

def oscTestHandler(addr, tags, data, source): 
     print "Received '/oscTest %s'" % data

oscServer.addMsgHandler("/oscTest", oscTestHandler)

print "\nWaiting for messages from SuperCollider. Use ctrl-C to quit." 
oscServerThread = threading.Thread( target = oscServer.serve_forever ) 
oscServerThread.start()

try : 
     while 1 : 
         time.sleep(5) 

except KeyboardInterrupt : 
     print "\nClosing OSCServer." 
     oscServer.close() 
     print "Waiting for Server-thread to finish" 
     oscServerThread.join()
     print "Done"
Beispiel #25
0
    # RPi.GPIO Layout verwenden (wie Pin-Nummern)
    GPIO.setmode(GPIO.BOARD)

    for _button in button_map:
      GPIO.setup(_button, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # PUD_DOWN, because we use a pull down resistor, use RISING in next line then!
      GPIO.add_event_detect(_button, GPIO.RISING, callback=button_press, bouncetime=args.bouncetime)

    client.connect( (args.ip, args.port) )
    notifications.addMsgHandler( "/stopped", remote_stopped_callback )
    notifications.addMsgHandler( "/playing", remote_started_callback )
    notifications.addMsgHandler( "/files", remote_files_callback )

    print "StaalPiPlayer Button Client ready!"
    print "\tListening for player with:",notifications
    print "\tSending commands to player with:",client

    while True:
      try:
        notifications.serve_forever()
      except Exception, e:
        time.sleep(5)
        pass

  except Exception, e:
    pass
  finally:
    GPIO.cleanup()
    client.send( OSCMessage("/stop" ) )
    notifications.close()
    pass
Beispiel #26
0
class OscInput(BaseComponent):
    config_name = 'osc_inputs'

    def __init__(self, options={}):
        BaseComponent.__init__(self, options)

        # attributes
        self.osc_server = None
        self.connected = False
        self.running = False
        self.osc_map = None
        self.threaded = self.getOption('threaded', True)
        self.thread = None

    def __del__(self):
        self.destroy()

    def setup(self, event_manager=None):
        BaseComponent.setup(self, event_manager)

        self.msgEventMapping = self.getOption('output_events', {})
        self.autoAddrToEvent = 'auto' in self.msgEventMapping and self.msgEventMapping[
            'auto']

        # events
        self.connectEvent = self.getOutputEvent('connect')
        self.disconnectEvent = self.getOutputEvent('disconnect')
        self.messageEvent = self.getOutputEvent(
            'message', dummy=False)  # can be None if not configured

        if self.getOption('autoStart', True):
            self.start()

    def destroy(self):
        self.msgEventMapping = None
        self.event_manager = None
        self.stop()

    def start(self):
        if self._connect():
            self.running = True

    def stop(self):
        if self.connected:
            self._disconnect()
        self.running = False

    def update(self):
        if self.connected:
            if not self.threaded:
                self._processIncomingMessages()

    def _processIncomingMessages(self):
        # we'll enforce a limit to the number of osc requests
        # we'll handle in a single iteration, otherwise we might
        # get stuck in processing an endless stream of data
        limit = 50
        count = 0

        # clear timed_out flag
        self.osc_server.timed_out = False

        # handle all pending requests then return
        # NOTE; if you get weird bugs because self.osc_server is None,
        # one of handled OSC messages probably triggered the destruction
        # of this component. This should not happen until after this update
        # loop is finished, so destructive operations should be queued for later
        while self.osc_server.timed_out == False and count < limit:
            try:
                self.osc_server.handle_request()
                count += 1
            except Exception as exc:
                self.logger.error(
                    "Something went wrong while handling incoming OSC messages:"
                )
                self.logger.error(exc)

    def port(self):
        return self.getOption('port', DEFAULT_PORT)

    def host(self):
        return self.getOption('ip', DEFAULT_IP)

    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

    def _disconnect(self):
        if self.threaded:
            self._threadStopFlag = True
            self.logger.info("stopping separate OSC-listener thread...")
            while self.thread and self.thread.isAlive():
                pass
            self.logger.info('done')
            self.thread = None

        if self.osc_server:
            self.osc_server.close()
            self.connected = False
            self.osc_server = None
            self.disconnectEvent(self)
            self.logger.info('OSC Server ({0}:{1}) stopped'.format(
                self.host(), str(self.port())))

    def _onTimeout(self):
        if self.osc_server:
            self.osc_server.timed_out = True

    def _onOscMsg(self, addr, tags=[], data=[], client_address=''):
        # skip touch osc touch-up events
        # if len(data) == 1 and data[0] == 0.0:
        #     return
        self.logger.debug('osc-in {0}:{1} {2} [{3}] from {4}'.format(
            self.host(), self.port(), addr,
            ", ".join(map(lambda x: str(x), data)), client_address))
        if self.messageEvent:
            self.messageEvent(addr, tags, data, client_address)

        # trigger events based on incoming messages if configured
        if addr in self.msgEventMapping:
            self.logger.debug('triggering output event: {0}'.format(
                self.msgEventMapping[addr]))
            self.event_manager.fire(self.msgEventMapping[addr])
        elif self.autoAddrToEvent:
            self.logger.debug('triggering auto-output event: {0}'.format(addr))
            self.event_manager.fire(addr)

    def _threadMethod(self):
        while not self._threadStopFlag:
            self._processIncomingMessages()
Beispiel #27
0
class Kinect(threading.Thread):
    kRightHand = "/righthand"
    kLeftHand = "/lefthand"
    kRightElbow = "/rightelbow"
    kLeftElbow = "/leftelbow"
    kRightFoot = "/rightfoot"
    kLeftFoot = "/leftfoot"
    kRightKnee = "/rightknee"
    kLeftKnee = "/leftknee"
    kHead = "/head"
    kTorso = "/torso"
    kLeftShoulder = "/leftshoulder"
    kRightShoulder = "/rightshoulder"
    kLeftHip = "/lefthip"
    kRightHip = "/righthip"
    kClosestHand = "/closesthand"

    # position coordinate system type
    kBody = '_pos_body'
    kWorld = '_pos_world'
    kScreen = '_pos_screen'

    kPosNum = {kBody: 1, kWorld: 2, kScreen: 3}

    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)

    # close must be called before app termination or the app might hang
    def close(self):
        # this is a workaround of a bug in the OSC server
        # we have to stop the thread first, make sure it is done,
        # and only then class server.close()
        self.server.running = False
        while not self.done_running:
            time.sleep(.01)
        self.server.close()

    def run(self):
        print "Worker thread entry point"
        self.server.serve_forever()
        self.done_running = True

    def add_joint(self, joint):
        self.server.addMsgHandler(joint + self.pos_type, self.callback)
        self.active_joints[joint] = np.array([0.0, 0.0, 0.0])

    def remove_joint(self, joint):
        self.server.delMsgHandler(joint + self.pos_type)
        del self.active_joints[joint]

    def on_update(self):
        now = time.time()
        send_heartbeat = now - self.last_heartbeat_time > 3.0
        if send_heartbeat:
            self.last_heartbeat_time = now

        try:
            for j in self.active_joints:
                if send_heartbeat:
                    self.client.send(
                        OSCMessage(j + "_trackjointpos",
                                   Kinect.kPosNum[self.pos_type]))
        except Exception as x:
            print x, 'sending to', self.client.client_address

    def get_joint(self, joint):
        return np.copy(self.active_joints[joint])

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

    def callback(self, path, tags, args, source):
        #print path, args
        joint_name = path.replace(self.pos_type, "")
        self.active_joints[joint_name] = np.array(args)

    def callback_tracking_skeleton(self, path, tags, args, source):
        pass
Beispiel #28
0
class XAirClient:
    """
    Handles the communication with the X-Air mixer via the OSC protocol
    """
    _CONNECT_TIMEOUT = 0.5
    _WAIT_TIME = 0.02
    _REFRESH_TIMEOUT = 5

    XAIR_PORT = 10024

    last_cmd_addr = ''
    last_cmd_time = 0
    info_response = []
    
    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, ())
    
    def validate_connection(self):
        self.send('/xinfo')
        time.sleep(self._CONNECT_TIMEOUT)
        if len(self.info_response) > 0:
            print 'Successfully connected to %s with firmware %s at %s.' % (self.info_response[2], 
                    self.info_response[3], self.info_response[0])
        else:
            print 'Error: Failed to setup OSC connection to mixer. Please check for correct ip address.'
            exit()
        
    def run_server(self):
        try:
            self.server.serve_forever()
        except KeyboardInterrupt:
            self.client.close()
            self.server.close()
            exit()
        
    def msg_handler(self, addr, tags, data, client_address):
        if time.time() - self.last_cmd_time < self._WAIT_TIME and addr == self.last_cmd_addr:
            #print 'Ignoring %s' % addr
            self.last_cmd_addr = ''
        else:
            #print 'OSCReceived("%s", %s, %s)' % (addr, tags, data)
            if addr.endswith('/fader') or addr.endswith('/on') or addr.startswith('/config/mute') or addr.startswith('/fx/'):
                self.state.received_osc(addr, data[0])
            elif addr == '/xinfo':
                self.info_response = data[:]
    
    def refresh_connection(self):
        try:
            while True:
                if self.client != None:
                    self.send("/xremote")
                time.sleep(self._REFRESH_TIMEOUT)
        except KeyboardInterrupt:
            exit()
            
    def send(self, address, param = None):
        if self.client != None:
            msg = OSCMessage(address)
            if param != None:
                # when sending values, ignore ACK response
                self.last_cmd_time = time.time()
                self.last_cmd_addr = address
                if isinstance(param, list):
                    msg.extend(param)
                else:
                    msg.append(param)
            else:
                # sending parameter request, don't ignore response
                self.last_cmd_time = 0
                self.last_cmd_addr = ''
            self.client.send(msg)
Beispiel #29
0
def step_impl(context, message):
    listen = OSCServer(("127.0.0.1", 4589))
    listen.timeout = 0 #infinite timeout
    listen.addMsgHandler("/err", listen_handler)
    listen.close()
Beispiel #30
0
class OscReader:
    def __init__(self, host="127.0.0.1", port=8080, manager=None, threaded=False, autoStart=True):
        # params
        self.manager = manager
        self.host = host
        self.port = port
        self.threaded = threaded

        # attrs
        self._kill = False
        self.oscServer = None
        self.thread = None

        if autoStart:
            self.start()

    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")

    def destroy(self):
        if self.oscServer == None:
            return

        self.oscServer.close()
        self.oscServer = None

    def update(self):
        if self.oscServer == None:
            return

        # we'll enforce a limit to the number of osc requests
        # we'll handle in a single iteration, otherwise we might
        # get stuck in processing an endless stream of data
        limit = 10
        count = 0

        # clear timed_out flag
        self.oscServer.timed_out = False

        # handle all pending requests then return
        while not self.oscServer.timed_out and count < limit:
            self.oscServer.handle_request()
            count += 1

    def oscMarkerHandler(self, addr, tags, data, client_address):
        if self.manager:
            self.manager.processMarkersData([data[0]])

    def oscRigidBodyHandler(self, addr, tags, data, client_address):
        # readers can interface with the mocap data manager directly (most efficient)
        if self.manager:
            self.manager.processRigidBodyJson(data[0])

    def handleTimeout(self):
        if self.oscServer != None:
            self.oscServer.timed_out = True

    def start(self):
        if not self.threaded:
            self.setup()
            return

        if self.thread and self.thread.isAlive():
            ColorTerminal().warn("OscReader - Can't start while a thread is already running")
            return

        self._kill = False
        # threaded loop method will call setup
        self.thread = threading.Thread(target=self.threaded_loop)
        self.thread.start()

    def stop(self):
        if self.threaded:
            # threaded loop method will call destroy
            self._kill = True
        else:
            self.destroy()

    def threaded_loop(self):
        self.setup()

        while not self._kill:
            self.update()

        self.destroy()
Beispiel #31
0
    print args
    print source
    print mDirection
    print '-----------'
    if mDirection == 'forward' and msgVal == 1:
        moveRover.forward(config.getint('motor_params', 'DEFAULT_SPEED'))
    elif mDirection == 'backward' and msgVal == 1:
        moveRover.backward(config.getint('motor_params', 'DEFAULT_SPEED'))
    elif mDirection == 'right' and msgVal == 1:
        moveRover.right(config.getint('motor_params', 'DEFAULT_SPEED'))
    elif mDirection == 'left' and msgVal == 1:
        moveRover.left(config.getint('motor_params', 'DEFAULT_SPEED'))
    else:
        moveRover.stop()


directions = ['forward', 'backward', 'right', 'left']
#Message Handlers and Callback functions
for direction in directions:
    oscSrv.addMsgHandler("/move/" + direction, move)

print "\n listening on port: %s" % config.get('osc_srv', 'PORT')

try:
    while True:
        oscSrv.handle_request()

except KeyboardInterrupt:
    print "Quit"
    oscSrv.close()
class OscReceiver(MessageReceiverInterface):
    """A class for receiving Osc messages and passing them to its subscribers"""
    def __init__(self, others, protos, ip="127.0.0.1", port=8888):
        MessageReceiverInterface.__init__(self)
        self.oscServerIp = ip
        self.oscServerPort = port
        self.oscMasterIp = None
        self.oscMasterPort = None
        ## this is a dict of names to receivers
        ## like: 'sms' -> SmsReceiver_instance
        ## keys are used to match against osc requests
        self.allReceivers = others
        ## to enable osc forwarding, add osc server as subscriber to all receivers
        for k in self.allReceivers:
            self.allReceivers[k].addSubscriber((self.oscServerIp,self.oscServerPort))
        ## this is a dict of (ip,port) -> prototype
        ## like: (192.168.2.5, 8888) -> megavoice
        self.allPrototypes = protos

    def _oscHandler(self, addr, tags, stuff, source):
        addrTokens = addr.lstrip('/').split('/')
        ## /LocalNet/{Add,Remove}/Type -> port-number
        if ((addrTokens[0].lower() == "localnet")
            and (addrTokens[1].lower() == "add")):
            ip = getUrlStr(source).split(":")[0]
            port = int(stuff[0])
            self.allPrototypes[(ip,port)] = addrTokens[2]
            if (addrTokens[3].lower() in self.allReceivers):
                print "adding "+ip+":"+str(port)+" to "+addrTokens[3].lower()+" receivers"
                self.allReceivers[addrTokens[3].lower()].addSubscriber((ip,port))
                ## if adding osc listener need to setup osc master
                if((addrTokens[3].lower().startswith('osc')) 
                    and (not self.oscMasterIp is None)
                    and (not self.oscMasterPort is None)):
                    print ("adding osc master")
                    try:
                        oscSubscribeMessage = OSCMessage()
                        oscSubscribeMessage.setAddress("/LocalNet/Add/"+addrTokens[2]+"/Osc")
                        oscSubscribeMessage.append(str(self.oscServerPort).encode('utf-8'), 'b')
                        self.oscClient.connect((self.oscMasterIp, int(self.oscMasterPort)))
                        self.oscClient.sendto(oscSubscribeMessage, (self.oscMasterIp, int(self.oscMasterPort)))
                        self.oscClient.connect((self.oscMasterIp, int(self.oscMasterPort)))
                    except OSCClientError:
                        print ("no connection to "+self.oscMasterIp+":"+str(self.oscMasterPort))
        elif ((addrTokens[0].lower() == "localnet")
              and (addrTokens[1].lower() == "remove")):
            ip = getUrlStr(source).split(":")[0]
            port = int(stuff[0])
            if (addrTokens[2].lower() in self.allReceivers):
                print "removing "+ip+":"+str(port)+" from "+addrTokens[2].lower()+" receivers"
                self.allReceivers[addrTokens[2].lower()].removeSubscriber((ip,port))
            ## only remove from list of prototypes when not in any receiver...
            inSomeSubscriber = False
            for k in self.allReceivers:
                inSomeSubscriber |= self.allReceivers[k].hasSubscriber((ip,port))
            if ((not inSomeSubscriber) and ((ip,port) in self.allPrototypes)):
                print("removing "+self.allPrototypes[(ip,port)]+" @ "+ip+":"+str(port)
                      +" from list of prototypes")
                del self.allPrototypes[(ip,port)]
        ## /LocalNet/ListReceivers -> port-number
        elif ((addrTokens[0].lower() == "localnet")
              and (addrTokens[1].lower().startswith("listreceiver"))):
            ip = getUrlStr(source).split(":")[0]
            port = int(stuff[0])
            ## send list of receivers to client
            msg = OSCMessage()
            msg.setAddress("/LocalNet/Receivers")
            msg.append(",".join(self.allReceivers.keys()))
            try:
                self.oscClient.connect((ip, port))
                self.oscClient.sendto(msg, (ip, port))
                self.oscClient.connect((ip, port))
            except OSCClientError:
                print ("no connection to "+ip+":"+str(port)
                       +", can't send list of receivers")
        ## /LocalNet/ListReceivers -> port-number
        elif ((addrTokens[0].lower() == "localnet")
              and (addrTokens[1].lower().startswith("listprototype"))):
            ip = getUrlStr(source).split(":")[0]
            port = int(stuff[0])
            ## send list of prototypes to client
            msg = OSCMessage()
            msg.setAddress("/LocalNet/Prototypes")
            msg.append(",".join(self.allPrototypes.values()))
            try:
                self.oscClient.connect((ip, port))
                self.oscClient.sendto(msg, (ip, port))
                self.oscClient.connect((ip, port))
            except OSCClientError:
                print ("no connection to "+ip+":"+str(port)
                       +", can't send list of prototypes")

        ## /AEffectLab/{local}/{type} -> msg
        elif (addrTokens[0].lower() == "aeffectlab"):
            oscTxt = stuff[0].decode('utf-8')
            print "forwarding "+addr+" : "+oscTxt+" to my osc subscribers"
            ## send to all subscribers
            addr = "/AEffectLab/"+addrTokens[1]+"/"+addrTokens[2]
            self.sendToAllSubscribers(oscTxt, addr)

    ## setup osc server
    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

    ## setup master ip,port
    def setupMaster(self,ip,port):
        self.oscMasterIp = ip
        self.oscMasterPort = int(port)

    ## update osc server
    def update(self):
        pass

    ## end oscReceiver
    def stop(self):
        self.oscServer.close()
        self.oscThread.join()
Beispiel #33
0
class OscInput(BaseComponent):
    config_name = 'osc_inputs'

    def __init__(self, options = {}):
        BaseComponent.__init__(self, options)

        # attributes
        self.osc_server = None
        self.connected = False
        self.running = False
        self.osc_map = None
        self.threaded = self.getOption('threaded', True)
        self.thread = None

    def __del__(self):
        self.destroy()

    def setup(self, event_manager=None):
        BaseComponent.setup(self, event_manager)

        self.msgEventMapping = self.getOption('output_events', {})
        self.autoAddrToEvent = 'auto' in self.msgEventMapping and self.msgEventMapping['auto']

        # events
        self.connectEvent = self.getOutputEvent('connect')
        self.disconnectEvent = self.getOutputEvent('disconnect')
        self.messageEvent = self.getOutputEvent('message', dummy=False) # can be None if not configured

        if self.getOption('autoStart', True):
            self.start()

    def destroy(self):
        self.msgEventMapping = None
        self.event_manager = None
        self.stop()

    def start(self):
        if self._connect():
            self.running = True

    def stop(self):
        if self.connected:
            self._disconnect()
        self.running = False

    def update(self):
        if self.connected:
            if not self.threaded:
                self._processIncomingMessages()

    def _processIncomingMessages(self):
        # we'll enforce a limit to the number of osc requests
        # we'll handle in a single iteration, otherwise we might
        # get stuck in processing an endless stream of data
        limit = 50
        count = 0

        # clear timed_out flag
        self.osc_server.timed_out = False

        # handle all pending requests then return
        # NOTE; if you get weird bugs because self.osc_server is None,
        # one of handled OSC messages probably triggered the destruction
        # of this component. This should not happen until after this update
        # loop is finished, so destructive operations should be queued for later
        while self.osc_server.timed_out == False and count < limit:
            try:
                self.osc_server.handle_request()
                count += 1
            except Exception as exc:
                self.logger.error("Something went wrong while handling incoming OSC messages:")
                self.logger.error(exc)

    def port(self):
        return self.getOption('port', DEFAULT_PORT)

    def host(self):
        return self.getOption('ip', DEFAULT_IP)

    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

    def _disconnect(self):
        if self.threaded:
            self._threadStopFlag = True
            self.logger.info("stopping separate OSC-listener thread...")
            while self.thread and self.thread.isAlive():
                pass
            self.logger.info('done')
            self.thread = None

        if self.osc_server:
            self.osc_server.close()
            self.connected = False
            self.osc_server = None
            self.disconnectEvent(self)
            self.logger.info('OSC Server ({0}:{1}) stopped'.format(self.host(), str(self.port())))

    def _onTimeout(self):
        if self.osc_server:
            self.osc_server.timed_out = True

    def _onOscMsg(self, addr, tags=[], data=[], client_address=''):
        # skip touch osc touch-up events
        # if len(data) == 1 and data[0] == 0.0:
        #     return
        self.logger.debug('osc-in {0}:{1} {2} [{3}] from {4}'.format(self.host(), self.port(), addr, ", ".join(map(lambda x: str(x), data)), client_address))
        if self.messageEvent:
            self.messageEvent(addr, tags, data, client_address)

        # trigger events based on incoming messages if configured
        if addr in self.msgEventMapping:
            self.logger.debug('triggering output event: {0}'.format(self.msgEventMapping[addr]))
            self.event_manager.fire(self.msgEventMapping[addr])
        elif self.autoAddrToEvent:
            self.logger.debug('triggering auto-output event: {0}'.format(addr))
            self.event_manager.fire(addr)

    def _threadMethod(self):
        while not self._threadStopFlag:
            self._processIncomingMessages()
Beispiel #34
0
class Kinect(threading.Thread):
   def __init__(self, remote_ip = None):
      super(Kinect, self).__init__()

      core.register_terminate_func(self.close)

      # 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()

   # close must be called before app termination or the app might hang
   def close(self):
      # this is a workaround of a bug in the OSC server
      # we have to stop the thread first, make sure it is done,
      # and only then class server.close()
      self.server.running = False
      while not self.done_running:
         time.sleep(.01)
      self.server.close()

   def run(self):
      print "Worker thread entry point"
      self.server.serve_forever()
      self.done_running = True

   def add_joint(self, joint):
      self.server.addMsgHandler(joint + '_pos_body', self.callback)
      self.active_joints[joint] = np.array([0.0, 0.0, 0.0])

   def remove_joint(self, joint):
      self.server.delMsgHandler(joint + '_pos_body')
      del self.active_joints[joint]

   def on_update(self):
      now = time.time()
      send_heartbeat = now - self.last_heartbeat_time > 3.0
      if send_heartbeat:
         self.last_heartbeat_time = now

      try:
         for j in self.active_joints:
            if send_heartbeat:
               #print 'heartbeat:', j
               self.client.send( OSCMessage(j + "_trackjointpos", 1) )
      except Exception as x:
         print x, 'sending to', self.client.client_address

   def get_joint(self, joint) :
      return np.copy(self.active_joints[joint])

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

   def callback(self, path, tags, args, source):
      #print path, args
      joint_name = path.replace("_pos_body", "")
      self.active_joints[joint_name] = np.array(args)

   def callback_tracking_skeleton(self, path, tags, args, source):
      pass
Beispiel #35
0
class LiveRawAPI(object):
    """
    This is close to live's API objects as possible
    Of course, they are designed to be manipulated from a patcher,
    not real code, so a bit more wrapping is in order.
    To keep everything minimal, this is done in a subclass.
    """
    _incoming = None
    _handled = True
    _received = False
    debug = False

    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 = []

    def raw_query(self, *args):
        """Posts a query, waits for a response. Returns it.
        Note that state is fragile here, so you'd better be sure that there 
        will be a response, or it will hang waiting."""

        self.oscclient.send(OSCMessage('/query', args))
        return self.handle_request()

    def raw_call(self, *args):
        """Posts a call, returns nothing.
        Note that state is fragile here, so you'd better be sure that there 
        will be no response, or you won't know what returned what."""
        self.oscclient.send(OSCMessage('/query', ['path', 'getpath']))

    def _handle_response(self, path, tags, args, source):
        """private callback to handle OSC responses. Sets state."""
        if self.debug: print "callback", path, args, source
        self._incoming.append(args)
        self._received = True

    def handle_request(self):
        """hack to handle asynchronous calls:
        1 try to get something returned and tacked onto the class.
        2 Return it and reset.
        This is completely f****d at the momenl I can't make timeouts work in any usable fashion."""

        try:
            self.oscserver.handle_request()
            while self._received:
                self._received = False
                self.oscserver.handle_request()

            _incoming = self._incoming
            return _incoming
        finally:
            self._incoming = []
            self._received = False

    def close(self):
        self.oscserver.close()

    ### more structured access involves navigating places with the path object
    def goto(self, *args):
        resp = self.raw_query('path', 'goto', *args)
        prefix, path = resp[1], resp[2:]
        #sanity check that we are getting the right message
        assert prefix == 'path'
        self.path = path

    def path(self, *args):
        return self.goto(*args)

    def getchildren(self):
        resp = self.raw_query('path', 'getchildren')
        return resp[1:]

    def getcount(self):
        resp = self.raw_query('path', 'getcount')
        return resp[1:]
class OscReader:
    def __init__(self,
                 host="127.0.0.1",
                 port=8080,
                 manager=None,
                 threaded=False,
                 autoStart=True):
        # params
        self.manager = manager
        self.host = host
        self.port = port
        self.threaded = threaded

        # attrs
        self._kill = False
        self.oscServer = None
        self.thread = None

        if autoStart:
            self.start()

    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")

    def destroy(self):
        if self.oscServer == None:
            return

        self.oscServer.close()
        self.oscServer = None

    def update(self):
        if self.oscServer == None:
            return

        # we'll enforce a limit to the number of osc requests
        # we'll handle in a single iteration, otherwise we might
        # get stuck in processing an endless stream of data
        limit = 10
        count = 0

        # clear timed_out flag
        self.oscServer.timed_out = False

        # handle all pending requests then return
        while not self.oscServer.timed_out and count < limit:
            self.oscServer.handle_request()
            count += 1

    def oscMarkerHandler(self, addr, tags, data, client_address):
        if self.manager:
            self.manager.processMarkersData([data[0]])

    def oscRigidBodyHandler(self, addr, tags, data, client_address):
        # readers can interface with the mocap data manager directly (most efficient)
        if self.manager:
            self.manager.processRigidBodyJson(data[0])

    def handleTimeout(self):
        if self.oscServer != None:
            self.oscServer.timed_out = True

    def start(self):
        if not self.threaded:
            self.setup()
            return

        if self.thread and self.thread.isAlive():
            ColorTerminal().warn(
                "OscReader - Can't start while a thread is already running")
            return

        self._kill = False
        # threaded loop method will call setup
        self.thread = threading.Thread(target=self.threaded_loop)
        self.thread.start()

    def stop(self):
        if self.threaded:
            # threaded loop method will call destroy
            self._kill = True
        else:
            self.destroy()

    def threaded_loop(self):
        self.setup()

        while not self._kill:
            self.update()

        self.destroy()
Beispiel #37
0
class liveScriptWindow(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.exitFlag = False
        self.parent = parent    
        self.ck_ctl = ck_ctl
        self.is_locked = False
        self.is_muted = False
        self.lock_timer = None
        self.offset_time = 0.0
        self.current_song_name = ""
        self.tempo = 120.0
        self.signature_numerator = 4
        self.signature_denominator = 4
        self.song_saved = True
        self.arrQueue = []
        self.undoables = 0
        self.first_run = True
        self.setlist_window = None
        self.filler_words = ['slot','sl','scene','ch','channel','track']
        self.xpos = 870
        self.ypos = 420
        self.ls = ls(self)
        self.setlist = []
        self.setlist_file = "setlist.txt"
        self.setlist_window = ls_setlist_window(self)
        self.setlist_xpos = 150
        self.setlist_ypos = 350
        if ck_ctl:
            self.control_panel = ck_control_panel(self)
        self.control_panel_xpos = 0
        self.control_panel_ypos = 0
        self.prefs_file = "prefs.txt"
        self.load_prefs()

        parent.wm_title("LiveScript")
        parent.geometry("720x400+" + str(self.xpos) + "+" + str(self.ypos) )  
        parent.configure(bg="black")
        self.font_big = Font(family="Ariel", size=24)
        self.font_med = Font(family="Ariel", size=18)
        
        label_title = Label(parent, text="Name:", bg="black", fg="white")
        label_title.grid(row=0, column=0, sticky=E)
        self.sv = StringVar()
        self.sv.trace("w", lambda name, index, mode, sv=self.sv: self.text_changed())
        self.entry_title = Entry(parent, width=22,exportselection=False, bg="black", fg="lightblue", font=self.font_big, insertbackground="white", textvariable = self.sv, borderwidth=0) 
        self.entry_title.grid(row=0, column=1,sticky=W)
        self.label_count = Label(parent, text="0/0", bg="black", fg="white", font=self.font_med)
        self.label_count.grid(row=0, column=2, sticky=S)
        self.button_add = Button(parent, text="Add", command=self.scene_add,bg="#003366", fg="white", width=5)
        self.button_add.grid(row=0, column=3, sticky=S)
        self.button_del = Button(parent, text="Delete", command=self.scene_del,bg="#664433", fg="white", width=5)
        self.button_del.grid(row=0, column=4, padx=6, sticky=S)
        
        self.listbox_setlist = Listbox(parent, height=18,width=15,exportselection=False, bg="black", fg="white")
        self.listbox_setlist.grid(row=0, column=5, columnspan=2, rowspan=5, sticky=NW, pady=12)
        
        
        label_desc = Label(parent, text="Info:", bg="black", fg="white")
        label_desc.grid(row=1, column=0, sticky=E)
        self.sv2 = StringVar()
        self.sv2.trace("w", lambda name, index, mode, sv=self.sv2: self.text_changed())
        self.entry_desc = Entry(parent, width=22,exportselection=False, bg="black", fg="blue",  font=self.font_big, insertbackground="white", textvariable = self.sv2, borderwidth=0) 
        self.entry_desc.grid(row=1, column=1,sticky=NW)
        self.button_reload = Button(parent, text="Reload", command=self.reload,bg="#664433", fg="white", width=8)
        self.button_reload.grid(row=1, column=2, sticky=W, padx=0)
        self.button_move_up = Button(parent, text="Up", command=self.scene_up,bg="#333333", fg="white", width=5)
        self.button_move_up.grid(row=1, column=3, padx=6, pady=10)
        self.button_move_down = Button(parent, text="Down", command=self.scene_down,bg="#333333", fg="white", width=5)
        self.button_move_down.grid(row=1, column=4, padx=6, pady=10)

        self.button_undo = Button(parent, text="Undo", command=self.undo,bg="#003366", fg="white")
        self.button_undo.grid(row=2, column=0, sticky=N)
        self.text_scroll = Scrollbar(parent)
        self.text_script = Text(parent, height=14, width=50, bg="#333333", selectbackground="blue", fg="white", insertbackground="white", wrap=WORD)
        self.text_script.grid(row=2, column=1, rowspan=2,sticky=W)
        self.text_scroll.grid(row=2,column=2, sticky=N+S+W,rowspan=2)
        self.text_script.config(yscrollcommand=self.text_scroll.set)
        self.text_scroll.config(command=self.text_script.yview)
        self.text_script.tag_configure("even",background="#222222")
        self.text_script.tag_configure("odd",background="#000000")
        self.text_script.tag_configure("sel",bgstipple="@solid.xbm", borderwidth=1) #background="#cc0000",
        self.button_prev = Button(parent, text="Previous", command=self.prevScene,bg="#003366", fg="white", width=13, height=3)
        self.button_prev.grid(row=2, column=3, columnspan=2, sticky=N)

        self.button_undo_all = Button(parent, text="Undo\nAll", command=self.undo_all,bg="#003366", fg="white")
        self.button_undo_all.grid(row=3, column=0, sticky=N, pady=20)
        self.button_undo_all = Button(parent, text="Undo\n+\nRedo", command=self.undo_redo,bg="#003366", fg="white")
        self.button_undo_all.grid(row=3, column=0, sticky=S)
        self.button_next = Button(parent, text="Next", command=self.nextScene,bg="#003366", fg="white", height=9, width=13)
        self.button_next.grid(row=3, column=3, columnspan=2, sticky=S, pady=6)
        
        label_next = Label(parent, text="Next:", bg="black", fg="white")
        label_next.grid(row=4, column=0, sticky=E)
        self.label_next_title = Label(parent, text="(next scene)", bg="black", fg="#FF6666", font=self.font_big, width=21, anchor=W)
        self.label_next_title.grid(row=4, column=1, sticky=W)
        self.button_save = Button(parent, text="Save", command=self.saveSong,bg="green", fg="black", width=8)
        self.button_save.grid(row=4, column=2)
        self.button_mute = Button(parent, text="Mute", command=self.mute,bg="#333333", fg="white", width=13)
        self.button_mute.grid(row=4, column=3, columnspan=2)
        
        self.button_setlist = Button(parent, text="Setlist\nManager", command=self.setlist_window.open,bg="#003366", fg="white", width=13)
        self.button_setlist.grid(row=4, column=5, sticky=N)
        
        label_info2 = Label(parent, text="Info:", bg="black", fg="white")
        label_info2.grid(row=5, column=0, sticky=E)
        self.label_next_info = Label(parent, text="(next desc)", bg="black", fg="red",  font=self.font_big, width=21, anchor=W)
        self.label_next_info.grid(row=5, column=1, sticky=NW)
        self.button_send = Button(parent, text="Send", command=self.sendBox,bg="#003366", fg="white", width=8)
        self.button_send.grid(row=5, column=2)

        #self.liveTime = Label(parent, text="0")
        #self.liveTime.pack(side="top",anchor="n")
        self.button_play = Button(parent, text="Play", command=lambda: self.ls.playback(['foo','play'],True),bg="#003366", fg="white", width=5)
        self.button_play.grid(row=5, column=3)
        self.button_stop = Button(parent, text="Stop", command=lambda: self.ls.playback(['foo','stop'],True),bg="#003366", fg="white", width=5)
        self.button_stop.grid(row=5, column=4)
        if ck_ctl:
            self.button_stop = Button(parent, text="Ctl", command=self.control_panel.open,bg="#003366", fg="white", width=5)
            self.button_stop.grid(row=5, column=5)

        self.server = OSCServer( ("localhost", 9000) )
        self.server.timeout = 0
        self.timed_out = False
        self.server.addMsgHandler( "/livescript/next", self.nextScene )
        self.server.addMsgHandler( "/live/sync", self.update_sync )
        self.server.addMsgHandler( "/live/error", self.live_error )
        
        for crap in ['master/devices','startup','track/devices','track/device/param','return/devices','track/volume','track/select','track/send','tempo','metronome','play','track/state']:
            self.server.addMsgHandler( "/live/" + crap, self.foo )

        self.server.handle_timeout = types.MethodType(self.handle_timeout, self.server)
        self.client = OSCClient()
        self.client.connect( ("localhost", 9001) )

        self.scene_index = 0
        self.song_index = -1
        self.arrSong = []
        self.arrScene = []
        #self.setPath = "songs/"
        self.load_set()
            
    #def setlist_window_remove(self):
    #    self.setlist_window.destroy()
    #    self.setlist_window = None
        
    def foo(self,*args):
        pass
        
    def text_changed(self,*args):
        self.button_save.configure(bg="red",text="Save Me")

        
    def mute(self,*args):
        if self.is_muted:
            self.is_muted = False
            self.button_mute.configure(bg="#333333",text="Mute", fg="white")
        else:
            self.is_muted = True
            self.button_mute.configure(bg="red",text="Muted!")
    def update_sync(self,path, tags, args, source):
        network_lag = .01
        self.offset_time = args[2] - time.clock() + network_lag
        self.tempo = args[1]
        live_time = (time.clock() + self.offset_time ) / (self.signature_numerator / (self.tempo / 60.0))
        print(str(live_time)[0:5] + " time:" + str(args))
        
    def live_error(self,path, tags, args, source):
        print("live error! " + str(args))
        
    def load_prefs(self):
        if os.path.isfile(self.prefs_file):
            f = open(self.prefs_file,'r+')
            prefs_data = json.load(f)
            print("loading from prefs file")
            f.close()

            print(prefs_data)
            for pref in prefs_data:
                print(str(pref) + ":" + str(prefs_data[pref]))
                setattr(self, pref, prefs_data[pref])
                
                
        else:
            print("creating new prefs file")
            self.save_prefs()
            #prefs_data = json.loads('{"setlist_file":"setlist.txt"}')
            #prefs_data = {"setlist_file":"setlist.txt",}
            #json.dumps(prefs_data)
            
        
    def save_prefs(self):
        saveable_prefs = ['setlist_file','tempo','xpos','ypos','setlist_xpos','setlist_ypos','control_panel_xpos','control_panel_ypos']
        print("window at:" + str(self.parent.winfo_x()) + " x " + str(self.parent.winfo_y()))
        self.xpos = self.parent.winfo_x()
        self.ypos = self.parent.winfo_y()
#        if os.path.isfile(self.prefs_file):
        f = open(self.prefs_file,'w')
        print("saving to prefs file")
#        else:
#            print("creating new prefs file!")
#            f = open(self.prefs_file,'a')
        dict_prefs = {}
        for pref in saveable_prefs:
            dict_prefs[pref] = getattr(self,pref)
        f.write(json.dumps(dict_prefs))
        f.close()
        
    def load_set(self):
        if os.path.isfile(self.setlist_file):
            f = open(self.setlist_file,'r')
            setlist = json.load(f)
            print("loading from set file")
        else:
            print("creating new set file")
            f = open(self.setlist_file,'a')
            setlist = "empty set,"
            #ex.prefs = json.loads('{"mod":0}')
            #json.dump(ex.prefs, f)
        f.close()
        self.setlist = setlist #.split('\n')
        #ls.text_script.insert(END,ls.setlist)
        self.listbox_setlist.delete(0, END)
        self.setlist = []
        for song in setlist: #.split('\n'):
            #song = song.split(",")
            self.setlist.append(song)
            self.listbox_setlist.insert(END,song[0])
        self.listbox_setlist.selection_set(0)
        #print("setlist:" + str(self.setlist))
        
    def handle_timeout(self,server):
        self.timed_out = True
 
    def saveSong(self):
        self.arrSong[self.scene_index] = self.entry_title.get() + "," + self.entry_desc.get() + "," + self.text_script.get("1.0",END).replace('\n',',').replace('\r','').strip(',').strip(' ')
        #songFile = self.setPath + self.current_song_name + ".csv"
        songFile = self.setlist[self.song_index][1]
        f = open(songFile,'w')
        f.write('\n'.join(self.arrSong))
        print("saving to ",songFile)
        f.close()
        self.button_save.configure(bg="green",text="Saved")
        self.text_script.edit_modified(False)
        self.song_saved = True


    def loadSong(self):
        songFile = self.setlist[self.song_index][1]
        if os.path.isfile(songFile):
            f = open(songFile,'r+')
            self.arrSong = f.read().split('\n') #json.load(f)  we gonna json this bitch yet?
            #print("loading from song file" + str(self.arrSong))
            
        else:
            print("creating new song file")
            f = open(songFile,'a')
            self.arrSong = ["empty"]
            #ex.prefs = json.loads('{"mod":0}')
            #json.dump(ex.prefs, f)
        f.close()
        #ls.text_script.insert(END,ls.setlist)
        #ls.listbox_setlist.clear()
        self.scene_index = 0
        self.song_saved = True
        self.button_save.configure(bg="green", text="Saved")
        self.refreshScene()

    def scene_del(self,*arg):
        if len(self.arrSong) > 1:
            self.arrSong.pop(self.scene_index)
            if self.scene_index > 0:
                self.scene_index -= 1
            self.song_saved = False
            self.button_save.configure(bg="red",text="Save Me")
            self.refreshScene()

 
    def scene_add(self,*arg):
            new_scene = "New Scene,New Info"
            self.arrSong.insert(self.scene_index+1,new_scene)
            self.scene_index += 1
            self.song_saved = False
            self.button_save.configure(bg="red",text="Save Me")
            self.refreshScene()

    def scene_up(self,*arg):
        if self.scene_index < len(self.arrSong) - 1:
            self.arrSong.insert(self.scene_index + 1,self.arrSong.pop(self.scene_index))
            self.scene_index += 1
            self.song_saved = False
            self.button_save.configure(bg="red",text="Save Me")
            self.refreshScene()

    def scene_down(self,*arg):
        if self.scene_index > 0:
            self.arrSong.insert(self.scene_index - 1,self.arrSong.pop(self.scene_index))
            self.scene_index -= 1
            self.song_saved = False
            self.button_save.configure(bg="red",text="Save Me")
            self.refreshScene()

    def nextScene(self,*arg):
        if not self.is_locked:
            self.scene_index += 1
            if self.scene_index >= len(self.arrSong):
                print("end of song")
                if self.song_index + 1 < len(self.setlist):
                    self.song_index += 1
                else:
                    self.song_index = 0
                    
                self.scene_index = 0
                
                self.current_song_name = self.setlist[self.song_index][0]
                self.listbox_setlist.select_clear(0,END)
                self.listbox_setlist.selection_set(self.song_index)
                self.loadSong()
            else:
                self.refreshScene()
        else:
            self.locker(False)
 
    def reload(self,*arg):
        #self.locker(False)
        self.scene_index = 0
        self.loadSong()
 
    def prevScene(self):
        if self.scene_index < 1 :
            self.scene_index = len(self.arrSong) 
        self.scene_index = self.scene_index - 1
        self.refreshScene()
 
    def quit(self):
        self.server.close()
        self.parent.destroy()

    def locker(self,lock = False, lock_bars = 0):
        if lock:
            self.button_next.configure(bg = "red", text="Locked")
            #print("timer",lock_bars ,self.tempo ,self.signature_numerator,lock_bars * (self.signature_numerator / (self.tempo / 60.0))+ .1)
            self.lock_timer = Timer(lock_bars * (self.signature_numerator / (self.tempo / 60.0))+ .1, self.locker)
            self.lock_timer.start()
        else:
            self.button_next.configure(bg = "#003366", text="Next")
            if self.lock_timer != None:
                self.lock_timer.cancel() #= None
        print("lock",lock)
        self.is_locked = lock


        
    def refreshScene(self):
        print("-----------AND SCENE---------------------------")
        self.arrScene = self.arrSong[self.scene_index].split(",")
        if self.scene_index < (len(self.arrSong) - 1):
            nxt = self.arrSong[self.scene_index + 1].split(",")
        else:
            nxt = ["END OF SONG","(load next song)"]
            
            
            
        self.label_count.configure(text=str(self.scene_index +1) + "/" + str(len(self.arrSong)))
        self.text_script.delete('1.0', END)
        tag = "even"
        for line in self.arrScene[2:len(self.arrScene)]:
            self.text_script.insert(END,line+"\n",tag)
            tag = "even" if tag == "odd" else "odd"
        self.entry_title.delete(0, END)
        self.entry_title.insert(END,self.arrScene[0])
        self.entry_desc.delete(0, END)
        self.entry_desc.insert(END,self.arrScene[1])
        self.label_next_title.configure(text=nxt[0])
        self.label_next_info.configure(text=nxt[1])
        """
        for lsCmd in self.arrScene[2:len(self.arrScene)]:
            lsCmd = re.sub('\[([^\]]+)\]','',re.sub('[\s]+', ' ',lsCmd.lower().strip()))
            arrCmd = lsCmd.split(" ")
            
            #if there is a delay command make sure it's the last element
            delayCmds = [i for i, s in enumerate(arrCmd) if '+' in s]
            if delayCmds:
                barDelay = arrCmd.pop(delayCmds[0])
                print( "delay " + str(barDelay) + "bars: " + str(arrCmd))
                arrCmd.append(barDelay)
            try:
                result = getattr(self, 'ls_'+arrCmd[0])(arrCmd)
            except Exception, e:
                print('404! ' + str(e) + "\n" + str(arrCmd))
        """
        self.text_script.edit_modified(False)
        if self.song_saved:
            self.button_save.configure(bg="green", text="Saved")
        self.sendBox()
        
    def sendBox(self):
        try:
            txtScene = self.text_script.selection_get()          
            whole_box = False
        except:
        #    txtScene = ""
        #if len(txtScene) < 1:
            txtScene = self.text_script.get("1.0",END)
            whole_box = True
           
        if not self.is_muted or not whole_box:
            print("processing:",txtScene)
        else:
            print("(muted)")
        
        wait_time = 0
        self.undoables = 0
        if self.first_run:
            self.first_run = False
            return #dont send the patch at startup
        else:
            txtScene = re.sub('\[([^\]]+)\]','',txtScene.lower()) #remove comments and extra breaks, lower case
            for lsCmd in txtScene.split("\n"):
                lsCmd = re.sub('[\s]+', ' ',lsCmd.strip()) #remove extra space
                #lsCmd = re.sub('\[([^\]]+)\]','',re.sub('[\s]+', ' ',lsCmd.lower().strip()))
                #arrCmd = lsCmd.split(" ")
                arrCmd = shlex.split(lsCmd)
                if len(arrCmd) < 2:
                    #print("no valid cmd")
                    continue
                oscm = None
                #if there is a delay command only use the first one (they can be nested this way but that's dumb)
                delayCmds = [[i,s] for i, s in enumerate(arrCmd) if (s[0] == '+')]
                if delayCmds:
                    print(["delay",delayCmds])
                    if delayCmds[0][1][-1] == 'b': #if the last character is a b then the number is for beats, not bars
                        delayCmd = ['beats',int(delayCmds[0][1][1:-1])]
                    else:
                        delayCmd = ['bars',int(delayCmds[0][1][1:])]
                    arrCmd.pop(delayCmds[0][0])
                    #print( "delay " + str(barDelay) + "bars: " + str(arrCmd))
                    #arrCmd.append(barDelay)
                try:
                    if arrCmd[0] not in ["fade","playback","lock"]:
                        self.undoables += 1
                    if not self.is_muted or not whole_box and oscm !='\n':
                        oscm = getattr(self.ls, arrCmd[0])(arrCmd[1:])
                    if arrCmd[0].lower() == 'wait':
                        wait_time += arrCmd[1]
                    
                    if oscm is not None:
                        if delayCmds and whole_box and not self.is_muted:
                            #oscm.append(barDelay,'k')
                            secPerBeat = 1 / (self.tempo / 60.0)
                            secPerBar = self.signature_numerator * secPerBeat
                            live_time = (time.clock() + self.offset_time ) / (self.signature_numerator / (self.tempo / 60.0))
                            pctToNextBar = (1 - (live_time - int(live_time)))
                            secToNextBeat = (pctToNextBar * self.signature_numerator - int(pctToNextBar * self.signature_numerator)) * secPerBeat
                            secToNextBar = pctToNextBar * secPerBar
                            #secToNextBar = (self.signature_numerator - (live_time % self.signature_numerator)) * secPerBar / self.signature_numerator
                            if delayCmd[0] == 'beats':
                                secDelay = delayCmd[1] * secPerBeat + secToNextBeat + .01
                            else:
                                secDelay = delayCmd[1] * secPerBar + secToNextBar + .01
                            schTime = (time.clock() + self.offset_time + secDelay ) / (self.signature_numerator / (self.tempo / 60.0))

                            print(str(live_time)[0:5]+ " delay " + str( delayCmd[1]) +  delayCmd[0]  + str(oscm) + " del=" + str(schTime)[0:5] + " sec=" + str(secDelay)[:5] + " snb=" + str(secToNextBar)[:5])
                            self.q(oscm,secDelay)
                            #self.arrQueue.append([oscm,time.clock() + secDelay])
                            #Timer(secDelay, self.send, [oscm]).start()
                        else:
                            if not self.is_muted or not whole_box:
                                self.arrQueue.append([oscm,time.clock() + wait_time])
                                #self.send( oscm )
                except Exception, e:
                    print('cmd err! ' + str(e) + str(arrCmd))
def main(stdcr):

    stdscr = curses.initscr()
    stdscr.nodelay(1)

    activeLight = False
    activeVideoOn = False
    activeVideoOff = False

    lastButtonCar = 1
    sentButtonCar = 0
    timerButtonCar = 0

    connected = False

    raspberryAddress = '192.168.0.197', 7100
    milluminAddress = '192.168.1.21', 5000
    milluminAddress2 = '192.168.1.22', 5000

    while not connected:

        try:
            server = OSCServer(raspberryAddress)
            server.timeout = 0

            # Creamos el objeto "Cliente"
            client = OSCClient()
            client2 = OSCClient()

            # Realizamos la conexion
            # client.connect( milluminAddress )
            # client2.connect( milluminAddress2 )

            connected = True

        except:
            print("No se encuentra el servidor OSC. Reintentando...")
            time.sleep(5)

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

    server.addMsgHandler("/1/lightPlus", callback_lightOn)
    server.addMsgHandler("/1/lightMinus", callback_lightOff)
    server.addMsgHandler("/1/videoOn1", callback_videoOn1)
    server.addMsgHandler("/1/videoOn1eng", callback_videoOn1eng)
    server.addMsgHandler("/1/videoOn2", callback_videoOn2)
    server.addMsgHandler("/1/videoOn2eng", callback_videoOn2eng)
    server.addMsgHandler("/1/videoOn3", callback_videoOn3)
    server.addMsgHandler("/1/videoOn4", callback_videoOn4)
    server.addMsgHandler("/1/videoStop", callback_videoStop)

    GPIO.setmode(GPIO.BCM)
    GPIO.setup(17, GPIO.OUT)  ## GPIO 17 como salida (bajar luz)
    GPIO.setup(27, GPIO.OUT)  ## GPIO 27 como salida (subir luz)
    GPIO.setup(
        22, GPIO.IN,
        pull_up_down=GPIO.PUD_UP)  ## GPIO 23 como entrada (boton iniciar show)

    time_stamp = time.time() - 30

    # simulate a "game engine"
    while True:

        while not connected:
            try:
                server = OSCServer(raspberryAddress)
                server.timeout = 0

                # Creamos el objeto "Cliente"
                client = OSCClient()
                client2 = OSCClient()

                # Realizamos la conexion
                client.connect(milluminAddress)
                client2.connect(milluminAddress2)

                connected = True

            except:
                # print("No se encuentra el servidor OSC. Reintentando...")
                stdscr.addstr(
                    "No se encuentra el servidor OSC. Reintentando..." + ' ')
                stdscr.refresh()
                # return curser to start position
                stdscr.move(0, 0)
                time.sleep(5)

        try:
            stdscr.move(0, 0)
            c = stdscr.getch()
            if c != -1:
                # print numeric value
                stdscr.addstr(str(c) + ' ')
                stdscr.refresh()
                # return curser to start position
                stdscr.move(0, 0)

            # do the game stuff:
            if activeLight:
                GPIO.output(17, False)

            else:
                GPIO.output(17, True)

            # print GPIO.input(22)

            if (GPIO.input(22) == 0) and (lastButtonCar == 1):

                timerButtonCar = time.time()
                lastButtonCar = 0
                # print "Inicio Pulso"

            elif (GPIO.input(22) == 0) and (lastButtonCar
                                            == 0) and (not sentButtonCar):

                delta = time.time() - timerButtonCar

                if delta > 1.0:
                    msg = OSCMessage()
                    msg.setAddress("/millumin/action/launchorStopColumn")
                    msg.append(9.0)
                    #client.send(msg) # now we dont need to tell the client the address anymore
                    #client2.send(msg) # now we dont need to tell the client the address anymore
                    sentButtonCar = True
                    # print "Lanzando mapping coche"
                    stdscr.addstr("Lanzando mapping coche..." + ' ')
                    stdscr.refresh()
                    # return curser to start position
                    stdscr.move(0, 0)

            elif (GPIO.input(22) == 1) and (lastButtonCar == 0):

                timerButtonCar = time.time()
                lastButtonCar = 1
                # print "Fin pulso"

            elif (GPIO.input(22) == 1) and (lastButtonCar
                                            == 1) and (sentButtonCar):

                if (time.time() - timerButtonCar > 1.0):

                    # print "Reseteando boton de coche"
                    sentButtonCar = False

            each_frame(server)

        except KeyboardInterrupt:

            #client.close()
            #client2.close()
            server.close()
            GPIO.cleanup()
Beispiel #39
0
class Kinect:
    """Manages connection to Kinect, and saves and processes coordinates"""
    @staticmethod
    def retrieve(joints=None, max_port=5555):
        """ Retrieves a singleton Kinect instance, and creates it if it doesn't exist. """
        global kinect_instance
        if kinect_instance is None:
            kinect_instance = Kinect(joints, max_port)
        return kinect_instance

    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)
        #sprout(self._calc_speed)

    def __enter__(self):
        return self

    def __exit__(self, _type, value, traceback):
        self.server.close()
        self.kinect_client.close()
        self.max_client.close()

    def process_message(self, addr, tags, data, source):
        """process data coming in from Synapse, happens about every 0.03 seconds"""

        if addr[-9:] == '_pos_body':
            if self.flipped:
                if addr[:5] == '/left':
                    addr = '/right' + addr[5:]
                    data[X] = -data[X]
                elif addr[:6] == '/right':
                    addr = '/left' + addr[6:]
                    data[X] = -data[X]
            self.coords[addr[1:-9]] = data

    def _remind_synapse(self):
        """Send Synapse an OSC message to ask it to continue polling the required joints"""
        while True:
            for track in self.joints:
                self.sendToKinect('/' + track + '_trackjointpos', 1)
            time.sleep(1)

    def calc_speed(self):
        """Calculate speed of movement, at 0.06 second intervals"""
        self.calculating_speed = True
        while self.calculating_speed:
            total_speed = 0.
            for joint, v in self.coords.items():
                magnitude = Magnitude(v)
                prev_magnitude = Magnitude(self.prev_coords[joint])
                speed = abs(magnitude - prev_magnitude)
                if joint in ('lefthand', 'righthand'):
                    speed_x = Distance(SubVector(self.prev_coords[joint], X),
                                       SubVector(self.coords[joint], X))
                    speed_y = Distance(SubVector(self.prev_coords[joint], Y),
                                       SubVector(self.coords[joint], Y))
                    self.speed_piano[joint][X] += (
                        speed_x - self.speed_piano[joint][X]) * 0.5
                    self.speed_piano[joint][Y] += (
                        speed_y - self.speed_piano[joint][Y]) * 0.5
                total_speed += speed
            total_speed /= len(self.coords)
            self.speed = total_speed
            self.speed_ramp = self.speed_ramp + (self.speed -
                                                 self.speed_ramp) * 0.125
            self.prev_coords = copy.copy(self.coords)
            time.sleep(0.06)

    @property
    def area(self):
        return Area(self.coords['head'], self.coords['lefthand'],
                    self.coords['leftfoot'], self.coords['rightfoot'],
                    self.coords['righthand']) / 1000000.

    @property
    def facing(self):
        return self.coords['rightfoot'][X] >= self.coords['leftfoot'][X]

    def hand_down(self, hand):
        return self.coords[hand][Y] < 0 and self.hand_over_piano(hand)

    def hand_up(self, hand):
        return self.coords[hand][Y] >= 0 or not self.hand_over_piano(hand)

    def hand_over_piano(self, hand):
        return Magnitude(SubVector(self.coords[hand], Y, Z)) > 350

    def hand_hit(self, hand):
        """waits for a hit from the specified hand"""
        if self.hand_down(hand):
            wait_for(self.hand_up, (hand, ))
        wait_for(self.hand_down, (hand, ))

        return self.coords[hand][X]

    def joint_moved_x(self, prev_x, joint, hit_location):
        """used to wait for a change in joint in X dimension"""
        if self.hand_up(joint):
            return True
        if hit_location is not None and abs(hit_location -
                                            self.coords[joint][X]) < 140:
            return False
        return abs(prev_x - self.coords[joint][X]) > 70

    def hand_slide(self, hand, hit_location):
        x = self.coords[hand][X]
        wait_for(self.joint_moved_x, (x, hand, hit_location))

        if self.hand_up(hand):
            return False
        return self.coords[hand][X]

    def get_coord(self, joint):
        if joint == 'leftshoulder':
            return -250, 200, -50
        elif joint == 'rightshoulder':
            return 250, 200, -50
        else:
            return self.coords[joint]

    def sendToKinect(self, address, items):
        self._sendMsg(self.kinect_client, address, items)

    def sendToMax(self, address, items):
        self._sendMsg(self.max_client, address, items)

    @staticmethod
    def _sendMsg(client, address, items):
        m = OSCMessage()
        m.setAddress(address)
        m.append(items)
        client.send(m)
Beispiel #40
0
sys.stdout.write(RED)
print '\n waiting for Phone TouchOSC App...\n'
sys.stdout.write(RESET)
# Create virtual environment -------------------------------------------------------------------------------------------
# first we create the arrow to show current position of the servo
measuringArrow = arrow(pos=(0, -10, 0),
                       axis=(0, 10, 0),
                       shaftwidth=0.4,
                       headwidth=0.6)
# and now the labels
angleLabel = label(text='angle: 90', pos=(0, 5, 0), height=15, box=false)
angle0 = label(text='0', pos=(-10, -10, 0), height=15, box=false)
angle45 = label(text='45', pos=(-7.5, -2.5, 0), height=15, box=false)
angle90 = label(text='90', pos=(0, 1, 0), height=15, box=false)
angle135 = label(text='135', pos=(7.5, -2.5, 0), height=15, box=false)
angle180 = label(text='180', pos=(10, -10, 0), height=15, box=false)

# Main -----------------------------------------------------------------------------------------------------------------

while True:
    Conrol = get_Conrol()  # get path control string from Phone touchOSC
    server = OSCServer(
        (serverAdr, serverPort))  # define OSC server on computer
    client = OSCClient()  # define OSC client on Phone touchOSC
    client.connect((clientAdr, clientPort))  # connect to client
    server.addMsgHandler(
        Conrol, servo_call)  # use the control path and process message
    server.handle_request()  # handle request
    rate(20)  # refresh rate required for VPython
    server.close()  # close the server, start over again and again.
Beispiel #41
0
    #print "hello"
    msg = args[0]
    print msg
    outlet.push_sample([str(msg)])


server.addMsgHandler("/OSC-Marker-Stream", user_callback)


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


# user script that's called by the game engine every frame
def each_frame():
    # 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"
while run:
    sleep(0.001)
    each_frame()

server.close()
Beispiel #42
0
class StretchIO(object):
    def __init__(self, send, listen=("0.0.0.0", 12340)):
        self.server = OSCServer(listen)
        self.server.timeout = 0.0
        self.server.timed_out = False

        def timeout(self):
            self.timed_out = True

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

        self.client = OSCClient()
        self.client.connect(send)

        self.__fader_state = [8, 8, 8, 8]

        self.__fader_cb = None
        self.__toggle_cb = None

        for i in range(1, 5):
            self.led(i, 0.)
            self.toggle(i, 0.)
            self.fader(i, self.__fader_state[i - 1])
            self.server.addMsgHandler('/1/toggle' + str(i), self.osc_handler)
            self.server.addMsgHandler('/1/fader' + str(i), self.osc_handler)

    def step(self):
        self.server.timed_out = False
        while not self.server.timed_out:
            self.server.handle_request()

    def send(self, m):
        try:
            self.client.send(m)
        except OSCClientError:
            sys.stdout.write('Send Fail: {0} \r'.format(m))
            sys.stdout.flush()

    def close(self):
        self.server.close()

    def set_toggle_handler(self, cb):
        """ Register the function to be called when we press the toggle.

        <cb> should be a functio with the signature
            cb(button_number, button_state)
        """
        self.__toggle_cb = cb

    def set_fader_handler(self, cb):
        self.__fader_cb = cb

    def osc_handler(self, path, tags, args, source):
        paths = path.split('/')
        # paths looks like this for 'auto' touchOSC elements ['', '1', 'toggle1']

        if len(paths) < 3:
            return

        match = re.match('([a-zA-Z]+)(\d+)', paths[2])

        if not match:
            print 'osc path match failed'
            return

        if len(args) < 1:
            print 'handler has no arguments'
            return

        parts = match.groups()
        name = parts[0]
        num = int(parts[1])
        state = args[0]

        if name == 'fader':
            self.__fader_state[num - 1] = state

        if name == 'toggle' and self.__toggle_cb is not None:
            self.__toggle_cb(num, state)
        elif name == 'fader' and self.__fader_cb is not None:
            self.__fader_cb(num, state)

    def led(self, led_num, value):
        m = OSCMessage('/1/led{0:d}'.format(led_num))
        m.append(value)
        if value > 1.0: value = 1.0
        if value < 0.0: value = 0.0
        self.send(m)

    def toggle(self, toggle_num, value):
        m = OSCMessage('/1/toggle{0:d}'.format(toggle_num))
        m.append(1 if value else 0)
        self.send(m)

    def fader(self, fader_num, value):
        m = OSCMessage('/1/fader{0:d}'.format(fader_num))
        m.append(float(value))
        self.send(m)

    def fader_state(self, i):
        """
        <i> is the index from zero (unlike the setters, that index from 1)
        """
        return self.__fader_state[i]
Beispiel #43
0
    	print "with addr : %s" % addr
    	print "typetags %s" % tags
    	print "data %s" % stuff
    	print "---"

# Hookup handlers
server.addMsgHandler("/1/elbow", elbow)
server.addMsgHandler("/1/head", head)
server.addMsgHandler("/1/btn", btn)

# Main 
print "\nRegistered Callback Functions:"
for addr in server.getOSCAddressSpace():
    print addr

print "\nStarting OSCServer. Use Ctrl-C to quit."
st = threading.Thread( target = server.serve_forever )
st.start()

try:
	while 1:
		#print "Waiting..."
		sleep(5)

except KeyboardInterrupt:
	print "\nClosing OSCServer."
	server.close()
	print "Waiting for Server thread to finish."
	st.join()
	print "Done!"
Beispiel #44
0
    #         self.end_headers()
    #         upfilecontent = query.get('upfile')
    #         print "filecontent", upfilecontent[0]
    #         self.wfile.write("<HTML>POST OK.<BR><BR>");
    #         self.wfile.write(upfilecontent[0]);
            
    #     except :
    #         pass




if __name__ == '__main__':
    # will get better args
    if sys.argv[1:]:
        http_port = int(sys.argv[1])
    else:
        http_port = 8000
    osc_host = "127.0.0.1"
    osc_port = 12000
    try:
        sc = OSCServer( (osc_host,osc_port) )
        client = OSCClient(sc)
        server = HTTPServer(('', http_port), JSONHandler)
        print 'started http to OSC bridge...'
        server.serve_forever()
    except KeyboardInterrupt:
        print '^C received, shutting down server'
        server.socket.close()
        sc.close()