Пример #1
0
def update_buttons(client, station_id, updates, timeout=None):
    """Given a feedback client, update buttons.

    Update should be a button id mapped to one of [0,1,2] where:

    0: Turn off
    1: Turn on
    2: Toggle

    However, it is recommended you use BUTTON_ON, BUTTON_OFF, BUTTON_TOGGLE
    """
    if not updates:
        return

    if isinstance(updates, type([])):
        updates = {idx: updates[idx] for idx in range(len(updates))}

    if len(updates) == 1:
        client.send(
            create_button_update_msg(station=station_id,
                                     id=updates.items()[0][0],
                                     update=updates.items()[0][1]))
    else:
        bundle = OSCBundle()
        for id, up in updates.items():
            bundle.append(
                create_button_update_msg(station=station_id, id=id, update=up))
        client.send(msg=bundle, timeout=timeout)
Пример #2
0
def send_event():
    spectral_densities = ['filled', 'packed', 'opaque','translucent','transparent','empty']
    # fill blanks
    data = ['']*17*3
    #onset, continuant, termination
    data[0] = 'attack'

    #elegimos el de mayor momento transversal
    i = [l for l in tree.lep_pt].index(max(tree.lep_pt))

    #duration, based on momento transversal .. lep_pt
    data[1] = mapValue(tree.lep_pt[i],0,100000,0.1,10)
    #Spectrum types: electrones : inarmonico  ,  muones:  granular
    data[10] = 'inharmonic' if tree.lep_type[i] == 11 else 'granular'
    #Spectrum occupation: angulo
    data[11] = 'center'
    #Spectrum density: lepton energy .. lep_E
    data[16] = spectral_densities[int(mapValue(tree.lep_E[i],0,100000,0,5))]

    bundle = OSCBundle()
    msg = OSCMessage("/"+args.messagename)
    for d in data:
        msg.append(d)
    bundle.append(msg)
    client.send(bundle)
Пример #3
0
 def send_oscbundle(self):
     # send a bundle with current bpm and polar coordinates of 
     # sound-objects relative to player
     #            /game/bpm
     client = OSCClient()
     bpm = OSCMessage()     
     bpm.setAddress("/game/bpm")
     bpm.append(self.player['bpm'])   
     bundle = OSCBundle()
     bundle.append(bpm)
     #            /game/sndobj/id-bola (ang, mod)  
     scn = bge.logic.getCurrentScene()
     play = scn.objects["player"]
     
     for ball in self.soundobjects:
         ballpos = ball.worldPosition
         vect = mathutils.Vector((0,1))
         dist = play.getVectTo(ballpos)[0]
         vect2 = play.getVectTo(ballpos)[2].to_2d()
         angle = math.degrees(-vect.angle_signed(vect2))
         #print("angle ", angle, "distancia ",dist)
         data = (angle, dist)
         # append data to bundle
         msg = OSCMessage()
         tag = "/game/sndobj/position/" + str(ball['id'])
         msg.setAddress(tag)
         msg.append(data)
         bundle.append(msg)
         #print(msg)
     #gl.client is a tuple in gl with ip and port
     client.sendto(bundle, gl.send_to)
Пример #4
0
 def send_frame_data(self, frame):
     self.current_bundle = OSCBundle()
     r = super(BundledMixin, self).send_frame_data(frame)
     if len(self.current_bundle.values()) > 0:
         self.client.send(self.current_bundle)
         #log("%s\n" % self.current_bundle.values())
     self.current_bundle = None
     return r
Пример #5
0
 def playNoteTraditional(self, frequency, clientNumber):
     currentNote = OSCBundle()
     currentNote.append({"addr": "/frequency", "args": [frequency * self.octave]})
     currentNote.append({"addr": "/envelope/line", "args": self.envelopeList})
     if clientNumber == 0:
         self.pianoClient.send(currentNote)
     if clientNumber == 1:
         self.pianoClient2.send(currentNote)
     if clientNumber == 2:
         self.pianoClient3.send(currentNote)
Пример #6
0
def send_event(data):
    try:
        bundle = OSCBundle()
        msg = OSCMessage("/sound_unit")
        for d in data:
            msg.append(d)

        bundle.append(msg)
        client.send(bundle)

    except OSCClientError, e:
        printc( "\OSCClientError: Connection refused on port %s." % osc_port, 'e')
Пример #7
0
class BundledMixin(object):
    """
    Combine invidual OSC messages into bundles.

    One bundle is sent per frame (so it will contain all hand and finger data.)
    """

    def __init__(self, *args, **kwargs):
        self.current_bundle = None
        super(BundledMixin,self).__init__(*args,**kwargs)

    def send(self, name, val=None):
        if self.current_bundle is None:
            super(BundledMixin,self).send(name,val)
        else:
            self.osc_messages_sent += 1
            #log("Bundle: %s\n" % self.current_bundle)
            msg = OSCMessage(name)
            if val is not None:
                msg.append(val)
            self.current_bundle.append(msg)

    def send_frame_data(self, frame):
        self.current_bundle = OSCBundle()
        r = super(BundledMixin,self).send_frame_data(frame)
        if len(self.current_bundle.values()) > 0:
            self.client.send(self.current_bundle)
            #log("%s\n" % self.current_bundle.values())
        self.current_bundle = None
        return r
Пример #8
0
class BundledOSCLeapListener(OSCLeapListener):

    def __init__(self, *args, **kwargs):
        self.current_bundle = None
        super(BundledOSCLeapListener,self).__init__(*args,**kwargs)

    def send(self, name, val=None):
        if self.current_bundle is None:
            super(BundledOSCLeapListener,self).send(name,val)
        else:
            self.osc_messages_sent += 1
            #log("Bundle: %s\n" % self.current_bundle)
            msg = OSCMessage(name)
            if val is not None:
                msg.append(val)
            self.current_bundle.append(msg)

    def send_frame_data(self, frame):
        self.current_bundle = OSCBundle()
        r = super(BundledOSCLeapListener,self).send_frame_data(frame)
        if len(self.current_bundle.values()) > 0:
            self.client.send(self.current_bundle)
            #log("%s\n" % self.current_bundle.values())
        self.current_bundle = None
        return r
Пример #9
0
class BundledMixin(object):
    """
    Combine invidual OSC messages into bundles.

    One bundle is sent per frame (so it will contain all hand and finger data.)
    """
    def __init__(self, *args, **kwargs):
        self.current_bundle = None
        super(BundledMixin, self).__init__(*args, **kwargs)

    def send(self, name, val=None):
        if self.current_bundle is None:
            super(BundledMixin, self).send(name, val)
        else:
            self.osc_messages_sent += 1
            #log("Bundle: %s\n" % self.current_bundle)
            msg = OSCMessage(name)
            if val is not None:
                msg.append(val)
            self.current_bundle.append(msg)

    def send_frame_data(self, frame):
        self.current_bundle = OSCBundle()
        r = super(BundledMixin, self).send_frame_data(frame)
        if len(self.current_bundle.values()) > 0:
            self.client.send(self.current_bundle)
            #log("%s\n" % self.current_bundle.values())
        self.current_bundle = None
        return r
Пример #10
0
def send_event(tree=None):
    try:
        bundle = OSCBundle()
        msg = OSCMessage("/entry")
        if tree is None:
            msg.append(random())
            msg.append(random())
            msg.append(random(), 'b')
        else:
            msg.append(tree.lbNumber)
            msg.append(tree.mu)
            msg.append(tree.lep_eta[0], 'b')
        bundle.append(msg)
        client.send(bundle)

    except OSCClientError, e:
        printc( "\OSCClientError: Connection refused on port %s." % osc_port, 'e')
Пример #11
0
 def send_frame_data(self, frame):
     self.current_bundle = OSCBundle()
     r = super(BundledMixin,self).send_frame_data(frame)
     if len(self.current_bundle.values()) > 0:
         self.client.send(self.current_bundle)
         #log("%s\n" % self.current_bundle.values())
     self.current_bundle = None
     return r
Пример #12
0
    def commitFrame(self):
        """
        A typical TUIO bundle will contain an initial ALIVE message, followed by an arbitrary number of SET messages
        that can fit into the actual bundle capacity and a concluding FSEQ message. A minimal TUIO bundle needs to
        contain at least the compulsory ALIVE and FSEQ messages. The FSEQ frame ID is incremented for each delivered
        bundle, while redundant bundles can be marked using the frame sequence ID -1.
        /tuio/2Dcur alive s_id0...s_idN
        /tuio/2Dcur set s_id x_pos y_pos x_vel y_vel m_accel
        /tuio/2Dcur fseq f_id
        """
        bundle = OSCBundle()
        if len(self.alive) == 0:
            aliveMsg = OSCMessage("/tuio/2Dcur")
            aliveMsg.append('alive')
            bundle.append(aliveMsg)
        else:
            aliveMsg = OSCMessage("/tuio/2Dcur")
            aliveMsg.append('alive')
            for cursor in self.alive:
                aliveMsg.append(cursor.sid)
            bundle.append(aliveMsg)
            for cursor in self.alive:
                msg = OSCMessage()

                # TUIO message: /tuio/2Dcur set s x y X Y m
                # s: Session ID (temporary object ID) (int32)
                # x, y: Position (float32)
                # X, Y: Velocity vector (motion speed & direction) (float32)
                # m: Motion acceleration (float32)

                msg.setAddress("/tuio/2Dcur")
                msg.extend([
                    'set', cursor.sid, cursor.x, cursor.y, cursor.X, cursor.Y,
                    cursor.m
                ])

                bundle.append(msg)

        frameMsg = OSCMessage("/tuio/2Dcur")
        frameMsg.append('fseq')
        frameMsg.append(self.fseqCount)

        bundle.append(frameMsg)
        self.client.send(bundle)
        self.fseqCount = (self.fseqCount + 1) % sys.maxint
Пример #13
0
    def on_data(self, data):
        #print(data)
        duration = 0
        try:
            all_data = json.loads(data)
            tweet = all_data["text"]
            split_tweet = tweet.split(' ')
            first_word = split_tweet[0]
            if first_word == 'RT':
                first_word = split_tweet[1]
            num = 0
            for char in first_word:
                num += ord(char)
            length_of_tweet = len(split_tweet)/40.0
            duration = length_of_tweet * 1000
            #print duration
            sharp_freqs = [185, 207.65, 233.08, 261.63, 277.18, 311.13, 349.23,]
            freqs = [174.61, 196, 220, 246.94, 261.63, 293.66, 329.62, 349.23, ]#369.99, 391.96, 415.30, 440, 466.16, 493.88, 523.25]
            note = num % 7
            freq = 0
            if '#' in tweet:
                freq = sharp_freqs[note]
            else:
                freq = freqs[note]
        except UnicodeEncodeError:
            duration = 500
        
        client = OSCClient()
        client.connect(("localhost", 54345))

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

        client.send(bundle)


        time.sleep(duration/1000)
        
        return(True)
Пример #14
0
def send(nodes, jeu):
    mean_p = 0.0
    mean_dp = 0.0
    for node in nodes:
        try:
            msg = OSCMessage("/%i" % node.ip)
            # presure and presure derivative (constants setted to assure equal mean)
            p = gate(1.5 * node.current)
            dp = gate(5 * (node.current - node.previous))
            if jeu == "2osc":
                xA0, xA1, xA2 = dp, p, 0
                xB0, xB1, xB2 = 0, 0, 0
                xC0, xC1, xC2 = 0, 0, 0
            elif jeu == "3chords":
                p /= 3.
                dp /= 3.
                xA0, xA1, xA2 = dp, p, dp + p
                xB0, xB1, xB2 = dp, p, dp + p
                xC0, xC1, xC2 = dp, p, dp + p
            if DEBUG:
                print("%i %f %f %f %f %f %f %f %f %f" %
                      (node.ip, xA0, xA1, xA2, xB0, xB1, xB2, xC0, xC1, xC2))
            msg.append(xA0)
            msg.append(xA1)
            msg.append(xA2)
            msg.append(xB0)
            msg.append(xB1)
            msg.append(xB2)
            msg.append(xC0)
            msg.append(xC1)
            msg.append(xC2)
            bundle = OSCBundle()
            bundle.append(msg)
            client.send(bundle)
        except Exception as e:
            print(node)
            print(e)
        if DEBUG:
            mean_p += p
            mean_dp += dp
    if DEBUG:
        print("mean_p %f mean_dp %f" % (mean_p, mean_dp))
Пример #15
0
 def send_to_max(self):
     bundle = OSCBundle()
     for i in range(NUM_CAPS_AND_POTS):
         bundle.append({
             'addr': "/d" + str(i) + "/hz",
             'args': self.data_source.get_pitch_data(i)
         })
         bundle.append({
             'addr': "/d" + str(i) + "/on",
             'args': self.data_source.get_cap_data(i)
         })
     bundle.append({
         'addr': "/duration",
         'args': self.data_source.get_duration_data()
     })
     bundle.append({
         'addr': "/mod",
         'args': self.data_source.get_mod_data()
     })
     self.client.send(bundle)
Пример #16
0
    def on_frame(self, controller):
        # Get the most recent frame and report some basic information
        frame = controller.frame()
        #print ("Frame id: %d, timestamp: %d, hands: %d, fingers: %d, tools: %d" % (
        #              frame.id, frame.timestamp, len(frame.hands), len(frame.fingers), len(frame.tools)))

        if not frame.hands.empty:
            bundle = OSCBundle()

            bundle.append(
                OSCMessage("/leap/frame/timestamp", str(frame.timestamp)))

            for hand in frame.hands:
                handPos = OSCMessage("/leap/frame/hand/pos", [
                    hand.id, hand.palm_position[0], hand.palm_position[1],
                    hand.palm_position[2]
                ])
                bundle.append(handPos)
                normal = hand.palm_normal
                direction = hand.direction
                #handOrientation = OSCMessage("/leap/frame/hand/orientation",
                #    [hand.id, hand.palm_position[0], hand.palm_position[1], hand.palm_position[2]])
                #bundle.append(handOrientation)

            self.osc_client.send(bundle)
Пример #17
0
    def on_frame(self, controller):
        # Get the most recent frame and report some basic information
        frame = controller.frame()
        #print ("Frame id: %d, timestamp: %d, hands: %d, fingers: %d, tools: %d" % (
        #              frame.id, frame.timestamp, len(frame.hands), len(frame.fingers), len(frame.tools)))

        if not frame.hands.empty:
            bundle = OSCBundle()

            bundle.append(OSCMessage("/leap/frame/timestamp", str(frame.timestamp)))

            for hand in frame.hands:
                handPos = OSCMessage("/leap/frame/hand/pos",
                    [hand.id, hand.palm_position[0], hand.palm_position[1], hand.palm_position[2]])
                bundle.append(handPos)
                normal = hand.palm_normal
                direction = hand.direction
                #handOrientation = OSCMessage("/leap/frame/hand/orientation",
                #    [hand.id, hand.palm_position[0], hand.palm_position[1], hand.palm_position[2]])
                #bundle.append(handOrientation)

            self.osc_client.send(bundle)
Пример #18
0
 def playNoteFunky(self, frequency, clientNumber):
     if frequency == 0:
         return
     currentNote = OSCBundle()
     playList = Music.extraGenreList[self.genre]
     duration = playList[2] - playList[1]
     playList[3] = (duration * 261.63) / (frequency * self.octave)
     currentNote.append({"addr": "/playListComedy", "args": Music.extraGenreList["Comedy"]})
     currentNote.append({"addr": "/playListCrime", "args": Music.extraGenreList["Crime"]})
     currentNote.append({"addr": "/playListWestern", "args": Music.extraGenreList["Western"]})
     currentNote.append({"addr": "/playListRomance", "args": Music.extraGenreList["Romance"]})
     if clientNumber == 0:
         self.pianoClientAlternate.send(currentNote)
     if clientNumber == 1:
         self.pianoClientAlternate2.send(currentNote)
     if clientNumber == 2:
         self.pianoClientAlternate3.send(currentNote)
Пример #19
0
    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)
Пример #20
0
"""
Reset and close all UDP sockets to silence any remaining sounds in Max.
"""

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)
Пример #21
0
from OSC import OSCClient, OSCBundle

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

### Create a bundle:
bundle = OSCBundle()
bundle.append({'addr': "/frequency", 'args':[440.]})
bundle.append({'addr': "/envelope/line", 'args': [1., 20, 0., 1000]})

client.send(bundle)
Пример #22
0
from OSC import OSCClient, OSCBundle

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

### Create a bundle:
bundle = OSCBundle()
bundle.append({'addr': "/frequency", 'args': [440.]})
bundle.append({'addr': "/envelope/line", 'args': [1., 20, 0., 1000]})

client.send(bundle)
Пример #23
0
def createOSCBundle(address) : # just for api consistency
    return OSCBundle(address)
Пример #24
0
    def __init__(self, title, rating, genre):
        self.title = title
        self.timeElapsed = 0
        self.rating = rating
        self.genre = genre
        if title == "The Notebook":
            self.genre = "Romance"
        self.rating = rating.encode("ascii")
        self.rating = float(self.rating)
        self.octave = 1.0
        self.pianoClient = OSCClient()
        self.pianoClient2 = OSCClient()
        self.pianoClient3 = OSCClient()
        self.pianoClientAlternate = OSCClient()
        self.pianoClientAlternate2 = OSCClient()
        self.pianoClientAlternate3 = OSCClient()
        self.envelopeList = [1.0, 20, 0.0, 1000]
        self.buffer = False

        self.pianoClient.connect(("localhost", 54360))
        self.pianoClient2.connect(("localhost", 54361))
        self.pianoClient3.connect(("localhost", 54362))
        self.pianoClientAlternate.connect(("localhost", 54370))
        self.pianoClientAlternate2.connect(("localhost", 54371))
        self.pianoClientAlternate3.connect(("localhost", 54372))

        initialDingClient = OSCClient()
        initialDingClient.connect(("localhost", 54345))

        ### Initial Ding Bundle:
        print ("Turning on the movie")
        initialDing = OSCBundle()
        initialDing.append({"addr": "/frequency", "args": [440.0]})
        initialDing.append({"addr": "/envelope/line", "args": [1.0, 20, 0.0, 1000]})
        self.timeElapsed += 1.02

        initialDingClient.send(initialDing)

        print ("Curtains Openning")
        self.timeElapsed += 16  # note this currently plays right after the initial ding
        time.sleep(self.timeElapsed)
        self.timeElapsed = 0

        for genre in Music.genreList:
            if self.genre == genre:
                self.envelopeList = Music.genreList[genre]
        for genre in Music.extraGenreList:
            if self.genre == genre:
                self.buffer = True

        startTime = timeit.timeit()
        im = Image.open("keyboard.jpg")
        im.show()
        self.pianoInstrument()
        endTime = timeit.timeit()
        self.timeElapsed += startTime - endTime
        self.timeElapsed += 0.5

        time.sleep(self.timeElapsed)
        self.timeElapsed = 0
        if self.rating < 2:
            print ("Yikes...")
            sadClient = OSCClient()
            sadClient.connect(("localhost", 54346))

            # Sad Ding Bundle:
            sadDing = OSCBundle()
            sadDing.append({"addr": "/start", "args": [1]})

            sadClient.send(sadDing)
            self.timeElapsed += 4.25
        else:
            print ("TADA")
            tadaClient = OSCClient()
            tadaClient.connect(("localhost", 54380))

            tada = OSCBundle()
            tada.append({"addr": "/amplitude", "args": [self.rating / 10]})
            tada.append({"addr": "/startValue", "args": ["start", 0]})
            tadaClient.send(tada)
            self.timeElapsed += 1.5

        time.sleep(self.timeElapsed)

        print ("APPLAUSE")
        # applause based on rating
        endingClient = OSCClient()
        endingClient.connect(("localhost", 54350))
        ending = OSCBundle()
        ending.append({"addr": "/amplitude", "args": [self.rating / 10]})
        durationOfApplause = ((10 - self.rating) / 10) * 6000
        ending.append({"addr": "/startValue", "args": ["start", durationOfApplause]})
        endingClient.send(ending)
Пример #25
0
    def on_data(self, data):
        #print(data)
        duration = 0
        try:
            all_data = json.loads(data)
            tweet = all_data["text"]
            split_tweet = tweet.split(' ')
            first_word = split_tweet[0]
            if first_word == 'RT':
                first_word = split_tweet[1]
            num = 0
            for char in first_word:
                num += ord(char)
            length_of_tweet = len(split_tweet) / 40.0
            duration = length_of_tweet * 1000
            #print duration
            sharp_freqs = [
                185,
                207.65,
                233.08,
                261.63,
                277.18,
                311.13,
                349.23,
            ]
            freqs = [
                174.61,
                196,
                220,
                246.94,
                261.63,
                293.66,
                329.62,
                349.23,
            ]  #369.99, 391.96, 415.30, 440, 466.16, 493.88, 523.25]
            note = num % 7
            freq = 0
            if '#' in tweet:
                freq = sharp_freqs[note]
            else:
                freq = freqs[note]
        except UnicodeEncodeError:
            duration = 500

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

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

        client.send(bundle)

        time.sleep(duration / 1000)

        return (True)
Пример #26
0
 def stop(self):
     """Send stop message through timestamped bundle."""
     bundle = OSCBundle(address='/stop', time=0)
     bundle.append('stopping...')
     self.send(bundle)
Пример #27
0
 def note_off(self, note, onset):
     """Send note off message through timestamped bundle."""
     bundle = OSCBundle(address='/midi/noteoff', time=onset + self.latency)
     #print 'OFF:', onset+self.latency
     bundle.append(note.off_msg())
     self.send(bundle)