示例#1
0
def main(args):

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

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

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

    print
    print "GO"
    print
    exit();
 def send_value(self):
     for add, d in self.neighbors.items():
         c = OSCClient()
         c.connect(("localhost", add))
         msg = OSCMessage("/receive")
         msg.append(self._address)
         msg.append(self.data["value"])
         msg.append(self.data["iter"])
         c.send(msg)
         c.close()
示例#3
0
def main(args):

    # Defaults
    # Change prefix if you always want to prefix something to the command
    # Ex: prefix = "/eos/key/"
    # This would allow you to send abbreviated commands from the command line
    prefix = ""
    command = "preload"
    HOST = "192.168.1.8"
    PORT = 3032

    if len(args) == 3:
        command = args[0]
        HOST = args[1]
        PORT = int(args[2])
    elif len(args) == 2:
        command = args[0]
        HOST = args[1]
    elif len(args) == 1:
        command = args[0]
    elif len(args) > 3:
        print "Usage:"
        print "    python send.py [message] [host] [port]"
        errorPrint("send.py accepts at most 3 arguments.\n%s were provided." %
                   len(args))

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

    # Check for reserved commands that should do nothing but connect
    if (command != "preload" and command != "connect"):
        msg = OSCMessage(prefix + command)
        client.send(msg)

        print
        print "Sent '%(command)s' to %(HOST)s[%(PORT)d]." % locals()
        print
    else:
        print
        print "Preloaded. No message sent."
        print

    client.close()

    exit()
示例#4
0
def main(args):

    # Default host and port
    HOST = '192.168.1.8'
    PORT = 3032

    if len(args) == 2:
        HOST = args[0]
        PORT = args[1]
    elif len(args) == 1:
        HOST = args[0]
    elif len(args) > 2:
        errorPrint("OSC Go button accepts at most 2 arguments.\n" + len(args) +
                   " were provided.")

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

    print
    print "Connected"
    print
    exit()
示例#5
0
class OscProxyClient(object):
    def __init__(self,
            remote_osc_address,
            json_to_osc_q,
            osc_command_name,
            bridge=None,
            *args, **kwargs):
        self.remote_osc_address = remote_osc_address
        self.json_to_osc_q = json_to_osc_q
        self.osc_client = OSCClient()
        self.osc_client.connect(remote_osc_address)
        self.osc_command_name = osc_command_name
        self.bridge = bridge
    
    def serve_forever(self):
        for msg in self.json_to_osc_q:
            osc_msg = OSCMessage(self.osc_command_name)
            osc_msg.append(msg[0]) #HTTP verb
            osc_msg.append(msg[1]) #HTTP path
            osc_msg.append(msg[2]) #content
            self.osc_client.send(osc_msg)
    
    def close(self):
        self.osc_client.close()
示例#6
0
        # Creamos el objeto "Cliente"
        client = OSCClient()

        # Realizamos la conexion
        client.connect(client_IP)

        connected = True
    except:
        print("Esperando cliente OS ")

print("Sending OSC messages to: " + str(client_IP))
try:
    while 1:  # endless loop
        try:
            msg = OSCMessage(
            )  #  we reuse the same variable msg used above overwriting it
            msg.setAddress("/ping")
            print "/ping"
            client.send(
                msg)  # now we dont need to tell the client the address anymore
        except:
            print("Sin conexion OSC")
            time.sleep(timerPing)
        time.sleep(timerPing)

except KeyboardInterrupt:
    print "Closing OSCClient"
    client.close()
    print "Done"
示例#7
0
def unpack(data, totalCoordinates, socket):
    cX = totalCoordinates[0]
    cY = totalCoordinates[1]

    client = OSCClient()
    client.connect(("localhost", socket))

    """ Prepare and send OSC bundles to Max from a list of tuples of coordinates. """
    def bundlePolyline(coordinates, speed, polylineType, passengers, coordsX, coordsY):
        for pair in coordinates:

            # create an OSC bundle:
            bundle = OSCBundle()

            # append polylineType: "trip" or "delay" (data for in between current and next trip)
            bundle.append({'addr': "/curr", 'args': [polylineType]})

            # append min/max longX and latY to bundle:
            bundle.append({'addr': "/minX", 'args': [min(coordsX)]})
            bundle.append({'addr': "/maxX", 'args': [max(coordsX)]})
            bundle.append({'addr': "/minY", 'args': [min(coordsY)]})
            bundle.append({'addr': "/maxY", 'args': [max(coordsY)]})

            # append longX and latY to bundle
            bundle.append({'addr': "/longX", 'args': [pair[0]]})
            bundle.append({'addr': "/latY", 'args': [pair[1]]})
            
            # append start/end longX and latY of coordinates list
            xVals = [coords[0] for coords in coordinates]
            bundle.append({'addr': "/startX", 'args': [xVals[0]]})
            bundle.append({'addr': "/endX", 'args': [xVals[len(xVals) - 1]]})
            yVals = [coords[1] for coords in coordinates]
            bundle.append({'addr': "/startY", 'args': [yVals[0]]})
            bundle.append({'addr': "/endY", 'args': [yVals[len(yVals) - 1]]})

            # append passengers
            bundle.append({'addr': "/passengers", 'args': [passengers]})

            # send bundle to Max:
            client.send(bundle)

            # delay time to even out polyline steps
            time.sleep(speed)

    """ Read the next line in the data file. """
    for row in data:

        """ Parse and set time stamps in minutes (i.e. 4:02 == 242). """
        pickup = row["pickuptime"].split(" ")[1]
        pickup = pickup.split(":")
        pickup = (int(pickup[0])*60) + int(pickup[1])

        dropoff = row["dropofftime"].split(" ")[1]
        dropoff = dropoff.split(":")
        dropoff = (int(dropoff[0])*60) + int(dropoff[1])

        nextPickup = row["nextpickuptime"].split(" ")[1]
        nextPickup = nextPickup.split(":")
        nextPickup = (int(nextPickup[0])*60) + int(nextPickup[1])  

        """ Decode trippolyline. """
        latLongList = polylinemapper.decode(row["trippolyline"])
        passengers = row["passengers"]
        latLongSpeed = round((dropoff - pickup) / (2*len(latLongList)), 10)  # translate 1 minute in RT == 0.5 seconds
        bundlePolyline(latLongList, latLongSpeed, "trip", passengers, cX, cY)

        """ Decode nextpolyline. """
        nextLatLong = polylinemapper.decode(row["nextpolyline"])
        passengers = 0
        nextSpeed = round((nextPickup - dropoff) / (2*len(nextLatLong)), 10)  # translate 1 minute in RT == 0.5 seconds
        bundlePolyline(nextLatLong, nextSpeed, "delay", passengers, cX, cY)

    client.close()
示例#8
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)
示例#9
0
<<<<<<< Updated upstream


OSC_RECEIVE_ADDRESS = 'local', 7000 #RASPI Adress, Outgoing Port
OSC_SEND_ADDRESS = '10.40.24.105', 57121 #MAC Adress, Incoming Port
=======
OSC_OUT_HOST = "localhost"
OSC_OUT_PORT = 57120
>>>>>>> Stashed changes

if __name__ == "__main__":
    mOscClient = OSCClient()
    mOscClient.connect( (OSC_SEND_ADDRESS) )
    mOscMessage = OSCMessage()

    try:
                    mOscMessage.setAddress("/direccion")
                    mOscMessage.append(random.random())
                    mOscMessage.append(random.random())
<<<<<<< Updated upstream
                    mOscMessage.append(random.random())
=======
>>>>>>> Stashed changes
                    mOscClient.send(mOscMessage)

    except KeyboardInterrupt:
        mOscClient.close()
    finally:
        mOscClient.close()
示例#10
0
from OSC import OSCClient, OSCMessage

app= OSCClient()
app.connect(('127.0.0.1', 61000)) #send address
msg= OSCMessage('/stop')
msg.append(100)
app.send(msg)  #fade out over 100 frames
app.close()
示例#11
0
from OSC import OSCClient, OSCBundle

socket = 15800

for x in range(4):
    client = OSCClient()
    client.connect(("localhost", socket))
    bundle = OSCBundle()

    bundle.append({'addr': "/curr", 'args': [" "]})

    bundle.append({'addr': "/minX", 'args': [0]})
    bundle.append({'addr': "/maxX", 'args': [0]})
    bundle.append({'addr': "/minY", 'args': [0]})
    bundle.append({'addr': "/maxY", 'args': [0]})

    bundle.append({'addr': "/longX", 'args': [0]})
    bundle.append({'addr': "/latY", 'args': [0]})
    
    bundle.append({'addr': "/startX", 'args': [0]})
    bundle.append({'addr': "/endX", 'args': [0]})
    bundle.append({'addr': "/startY", 'args': [0]})
    bundle.append({'addr': "/endY", 'args': [0]})

    bundle.append({'addr': "/passengers", 'args': [0]})

    client.send(bundle)
    client.close()
    socket += 1
示例#12
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)
示例#13
0
class KeykitShell(cmd.Cmd):
    intro = """
    Welcome to the Keykit shell. Type help or ? to list commands.
    Connect to local keykit server with 'connect port'.
    Exit shell with 'bye'.
    """

    remote_server_adr = (PYCONSOLE_HOSTNAME, PYCONSOLE_PORT)
    local_server_adr = (MY_HOSTNAME, PYCONSOLE_PORT + 1)

    prompt = ''

    def __init__(self, *args, **kwargs):
        cmd.Cmd.__init__(self, args, kwargs)
        self.client = None
        self.server = None
        # Start client and server with default values
        self.init()

    def init(self):
        # Client
        if(self.client is not None):
            self.client.close()
        self.client = OSCClient()
        try:
            self.client.connect(self.remote_server_adr)
        except ValueError:
            warn("Connectiong failed. Invalid port?")

        # Server
        if self.server is not None:
            self.server.stop()
            self.server_thread.join()
        self.server = Server(self.local_server_adr)
        self.server_thread = Thread(target=self.server.start)
        self.server_thread.start()

        # Inform keykit programm to use this as target
        try:
            self.client.send(OSCMessage("/keykit/pyconsole/target",
                                        list(self.local_server_adr)))
        except OSCClientError:
            warn("Sending of /target message failed. Pyconsole.k offline?")

    def emptyline(self):
        """Do nothing on empty input line"""
        pass

    # ----- internal shell commands -----
    def do_connect(self, arg):
        """Connect to OSC-Server:                       connect [PORT] [HOSTNAME]

        Default PORT: %i
        Default HOSTNAME: %s
        """
        words = arg.split(' ')
        if len(words) > 1:
            self.remote_server_adr = (str(words[1]), int(words[0]))
        elif len(words) > 0:
            self.remote_server_adr = (self.remote_server_adr[0], int(words[0]))

        self.local_server_adr = (
            self.local_server_adr[0],
            self.remote_server_adr[1] + 1)
        self.init()

    do_connect.__doc__ %= (remote_server_adr[1], remote_server_adr[0])

    def do_verbose(self, arg):
        """Set verbose level variable of pyconsole.k:    verbose [0|1]"""
        if arg == "":
            arg = "1"
        try:
            self.client.send(
                OSCMessage("/keykit/pyconsole/verbose", [int(arg)]))
        except OSCClientError:
            warn("Sending failed")

    def do_bye(self, arg):
        """Close keykit shell window and exit:          bye

        It mutes the output of keykit, too.
        """
        warn('Quitting keykit shell.')
        # self.send("stop()")
        self.send("alloff()")
        self.close()
        return True

    '''
    def do_exit(self, arg):
        """Close keykit shell window and exit:  exit"""
        return self.do_bye(arg)

    def do_quit(self, arg):
        """Close keykit shell window and exit:  quit"""
        return self.do_bye(arg)
    '''

    loopVarIdx = 0

    def do_loop(self, arg):
        """Start test loop to check asynchron beheaviour."""

        # It is important to use different loop variable names for each call!
        i = chr(65+self.loopVarIdx)
        self.loopVarIdx = (self.loopVarIdx + 1) % 50
        s = '''for ( i%s=0; i%s<20; i%s++) { printf("l");
        for(j%s=0;j%s<i%s;j%s++){printf("o")}; print("p");
        sleeptill(Now+%s) }''' % (i,
                                  i,
                                  i,
                                  i,
                                  i,
                                  i,
                                  i,
                                  "2b")
        s = s.replace("\t", "")
        self.default(s)

    def do_test(self, arg):
        """Send test commands to keykit backend."""
        # self.do_loop("")
        self.default("print(\"Send irregular line\")")
        self.default("i = 0/0")

    def default(self, line):
        """Send input as keykit command (OSC message)"""
        self.send(line)
        # Restore prompt
        sys.stdout.write("%s" % (MY_PROMPT))

    def do_help(self, args):
        """%s"""
        if args == "":
            cmd.Cmd.do_help(self, args)
            # Apend commands with irregular python function names
            print("Keykit help")
            print("===========")
            print(self.do_khelp.__doc__)
            print("Further commands")
            print("================")
            print("[keykit cmd] ! !! !log ![num] [phrase]??\n")
        elif args == "!":
            print("List history of Keykit commands.")
        elif args == "!!":
            print("Repeat last Keykit command.")
        elif args == "??" or args == "[phrase]??":
            print("Syntax for phrase filtering:\n"
                  " [phrase] { condition-with-?? }"
                  " ?? will replaced with each note in the original phrase.\n"
                  " Example:\n"
                  " 'c,d,e,f,g' {??.pitch > 'e'} would be equal to 'ft288,g'\n"
                  "")
        elif args == "!log":
            print(
                "Write history of commands into logfile.\n" +
                "The variable Pyconsole_logfile controls the name," +
                "but should ends with .log or .txt.")
        elif args[0] == "!":
            print("![num] Repeat num-th command of history.")
        else:
            cmd.Cmd.do_help(self, args)

    do_help.__doc__ %= (cmd.Cmd.do_help.__doc__)

    def do_khelp(self, args):
        """khelp [regex pattern] lists matching library functions/important variables.

        If a more detailed description exists the entry will be
        marked with '*'.
        Patterns with an unique result show the description.
        Note: The lookup table is big, but incomplete.
        """

        kname = args.strip()
        if kname == "":
            kname = ".*"
        kname = "^"+kname+"$"
        bRegexOk = True
        try:
            re_name = re.compile(kname, re.IGNORECASE)
        except:
            bRegexOk = False
            warn("Can not compile regular expression.")
            return

        lElems = []
        if bRegexOk:
            lElems.extend([i for i in KEYKIT_LIB_FUNCTIONS
                           if re.search(re_name, i["name"])
                           is not None])
            lElems.extend([i for i in KEYKIT_LIB_CLASSES
                           if re.search(re_name, i["name"])
                           is not None])
            lElems.extend([i for i in KEYKIT_LIB_OTHER
                           if re.search(re_name, i["name"])
                           is not None])

        l = ["%s%s" % (el["name"],
                       "*" if el["desc"] != "" else "")
             for el in lElems]
        if(len(l) == 0):
            warn("No Keykit function/class/etc found for %s" % (kname,))
            return
        elif(len(l) > 20):
            print(keykit_library_abc(l))
        elif(len(l) > 1):
            print(" ".join(l))
            return
        else:
            print(keykit_library_help(lElems[0]))
            return

    def close(self):
        if(self.client is not None):
            self.client.close()
        if self.server is not None:
            self.server.stop()
            # self.server_thread.join()

    def send(self, s):
        try:
            self.client.send(OSCMessage("/keykit/pyconsole/in", [s]))
        except OSCClientError:
            warn("Sending of '%s' failed" % (s,))

    def update_lsdir(self, text, timeout):
        #import pdb; pdb.set_trace()
        # sleep(timeout)
        dirname = os.path.dirname(text)
        basename = os.path.basename(text)
        if len(dirname) == 0:
            dirname = "."
        self.server.keykit_lsdir = None
        try:
            self.client.send(OSCMessage("/keykit/pyconsole/lsdir", [dirname]))
        except OSCClientError:
            warn("Sending of '%s' failed" % (s,))

        while timeout > 0 and self.server.keykit_lsdir is None:
            timeout -= 0.1
            sleep(0.1)
        if self.server.keykit_lsdir is not None:
            # Default readline beheaviour
            # return [i[0] for i in self.server.keykit_lsdir
            #        if i[0].startswith(basename)]

            # Add readline workarounds
            # Include Path separator for folders
            ret = ["%s%s" % (i[0], os.path.sep if i[1] else "")
                    for i in self.server.keykit_lsdir
                    if i[0].startswith(basename)]
            # Omit adding of closing quotes, see
            # https://github.com/ipython/ipython/issues/1172
            if len(ret) == 1:
                ret.append(ret[0]+" ")
            return ret

        return []
示例#14
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)