Beispiel #1
1
def loop(serial, host, port):
    osctx = osc_init( (host, port) )
    bitadev = bitalino_init(serial)
    if not bitadev:
        raise Exception("Coultdn't open the BITalino device")

    try:
        print "Entering reading loop..."
        while True:
            samples = bitadev.read()
            time.sleep(0.005)
            #bitadev.trigger(digitalOutput)
            for s in samples:
                msg = OSCMessage()
                msg.setAddress("/biosample")
                out = []

                for sval in s:
                    out.append(sval / 1024)

                msg.append(out)
                #print msg
                osctx.send( msg )
    except KeyboardInterrupt as e:
        print "Looks like you wanna leave. Good bye!"
    finally:
        bitadev.stop()
        bitadev.close()
def hardware_callback(addr, tags, d, client_address):
    #d is data

    h_id = int(addr.split("/")[-1])

    event = None
    error = False

    if h_id == JUNCTION:
        if len(d) == 13:    
            #create event object
            event = pygame.event.Event(NETWORK_HARDWARE,{"hardware_id":JUNCTION,
                    "topRowOn":d[0],1:d[1],2:d[2],3:d[3],4:d[4],5:d[5],6:d[6],
                    7:d[7],8:d[8],9:d[9],10:d[10],11:d[11],12:d[12]})
        else:
            error = True
    elif h_id == SCIENCE:
        event = pygame.event.Event(NETWORK_HARDWARE,{"hardware_id":SCIENCE,"s1":True})
    elif h_id == COMMANDER:
        event = pygame.event.Event(NETWORK_HARDWARE,{"hardware_id":COMMANDER,"has_power":True})
    elif h_id == RADIO:
        event = pygame.event.Event(NETWORK_HARDWARE,{"hardware_id":RADIO,"frequency":55})

    if event != None:
        pygame.event.post(event)
    if error:
        #object malformed, return error
        msg = OSCMessage("/user/1")
        msg.append("Error")
        server.client.sendto(msg,client_address)
Beispiel #3
0
    def record_data(self):
        if(self.port is None):
            return None
        
        print "Logging started"
        
        while 1:
            localtime = datetime.now()
            current_time = str(localtime.hour)+":"+str(localtime.minute)+":"+str(localtime.second)+"."+str(localtime.microsecond)
            log_string = current_time
            results = {}
            for index in self.sensorlist:
                (name, value, unit) = self.port.sensor(index)
                log_string = log_string + ","+str(value)
                results[obd_sensors.SENSORS[index].shortname] = value;
                
				#send sensor data via OSC
                message = OSCMessage()
                message.setAddress("/"+obd_sensors.SENSORS[index].shortname)
                message.append(value)
                self.client.send(message)

            gear = self.calculate_gear(results["rpm"], results["speed"])
            log_string = log_string #+ "," + str(gear)
			#send gear via OSC
            message = OSCMessage()
            message.setAddress("/gear")
            message.append(gear)
            self.client.send(message)
            self.log_file.write(log_string+"\n")
Beispiel #4
0
def fader_callback(path, tags, args, source):
	print ("path", path) 
	print ("args", args) 
	print ("source", source) 
	msg=OSCMessage("/1/rotary1")
	msg.append(args);
	client.send(msg)
Beispiel #5
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)
def sendMessage():
    msg = OSCMessage()
    msg.setAddress("/oscTest")
    msg.append(100)
    print "sending '/oscTest 100' message to SuperCollider"
    client.send(msg)
    timedSendMessage()  # recursive call, keeps the timer going
    def nunchuk(self, state):
        """ 
            Extract acceleration, pitch, roll and both buttons 
            from the nunchuk.

        """
        # Need to calculate pitch and roll here...
        a_x = state['acc'][0] - self.cal_n_x
        a_y = state['acc'][1] - self.cal_n_y
        a_z = state['acc'][2] - self.cal_n_z
        roll = atan(a_x/a_z)
        pitch = atan(a_y/a_z*cos(roll))
        msg = OSCMessage('/nunchuk/acc')
        msg.append((a_x, a_y, a_z))
        self.client.sendto(msg=msg, address=self.address)
        msg = OSCMessage('/nunchuk/orientation')
        msg.append((pitch, roll))
        self.client.sendto(msg=msg, address=self.address)
        msg = OSCMessage('/nunchuk/joystick')
        msg.append(state['stick'])
        self.client.sendto(msg=msg, address=self.address)
        msg_z = OSCMessage('/nunchuk/button/z')
        msg_c = OSCMessage('/nunchuk/button/c')
        z = 0
        c = 0
        if state['buttons'] in [1, 3]:
            z = 1
        if state['buttons'] in [2,3]:
            c = 1
        msg_z.append(z)
        msg_c.append(c)
        self.client.sendto(msg=msg_z, address=self.address)
        self.client.sendto(msg=msg_c, address=self.address)
 def send(self, sample):
     mes = OSCMessage(self.address)
     mes.append(sample.channel_data)
     try:
         self.client.send(mes)
     except:
         return
 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)
Beispiel #10
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)
    def messageServer(self, messagePath, argument):
        client = OSCClient()
        client.connect((self.serverIP, self.serverPort))
        message = OSCMessage(messagePath)
        message.append(argument)

        client.send(message)
Beispiel #12
0
 def send(self,name,val=None):
     msg = OSCMessage(name)
     if val is not None:
         msg.append(val)
     r = self.client.send(msg)
     self.osc_messages_sent += 1
     return r
def serialComms():
	while run:
		proximity = ser.readline()
		proxMsg = OSCMessage()
		proxMsg.setAddress(OSCAddress)
		proxMsg.append(proximity)
		columnClient.send(proxMsg)
Beispiel #14
0
    def __init__(self, address):
        OSCServer.__init__(self, ('', 0))
        self.client.connect(address)
        host, port = self.client.socket.getsockname()

        # print "I believe we have an OSC Server listening on: ",host," ",port
        print port
        
        self.focused = False
        #self.server_host = host
        #self.server_port = port
        self.prefix = DEFAULT_PREFIX

        self.addMsgHandler('default', self.monome_handler)
        self.addMsgHandler('/sys/connect', self.sys_misc)
        self.addMsgHandler('/sys/disconnect', self.sys_misc)
        self.addMsgHandler('/sys/id', self.sys_misc)
        self.addMsgHandler('/sys/size', self.sys_size)
        self.addMsgHandler('/sys/host', self.sys_host)
        self.addMsgHandler('/sys/port', self.sys_port)
        self.addMsgHandler('/sys/prefix', self.sys_prefix)
        self.addMsgHandler('/sys/rotation', self.sys_misc)
        
        # handshake
        msg = OSCMessage("/sys/host")
        msg.append(host)
        self.client.send(msg)
        
        msg = OSCMessage("/sys/port")
        msg.append(port)
        self.client.send(msg)
        
        msg = OSCMessage("/sys/info")
        self.client.send(msg)
Beispiel #15
0
def toggleMuteGroup(channel, state):
 stringChannel = str(channel)
 muteAddress = '/config/mute/' + stringChannel
 msg = OSCMessage(muteAddress)
 msg.append(state)
 client.send(msg)
 print msg
Beispiel #16
0
class SendOSC(object):

    def __init__(self):
        self.osc_message = None
        self.osc_client = OSCClient()
        self.osc_message = OSCMessage()        
        
        self.ip = ""
        self.port = 0

    def connect(self, ip="localhost", port=8080):
        self.ip = ip
        self.port = port
        self.osc_client.connect((self.ip, self.port))

    def send(self, address, value):
        self.osc_message.setAddress(address)
        self.osc_message.append(value)
        self.osc_client.send(self.osc_message)

    def send_distane(self, distance):
        oscdump = "/dumpOSC/DistanceTipTarget"
        self.send(oscdump, distance)

    def send_needle_tip_position(self, x, y, z):
        oscdump = "/dumpOSC/needltip/x"
        self.send(oscdump, x)
        oscdump = "/dumpOSC/needltip/y"
        self.send(oscdump, y)
        oscdump = "/dumpOSC/needltip/z"
        self.send(oscdump, z)
Beispiel #17
0
def espaces_callback(path, tags, args, source):

    msg_string = ""
    msg_string += "\n\tpath   : %s" % path
    msg_string += "\n\ttags   : %s" % tags
    msg_string += "\n\targs   : %s" % args
    msg_string += "\n\tsource :%s" % str(source)
    print "OSCServer received: %s\nfrom %s.\n" % (msg_string, getUrlStr(source))

    ir_params = {  'duration'      : float(args[4]),
                   'nu'            : float(args[5]),
                   'sampling_rate' : float(args[6]),
                   'ev_params'     : {'space': str(args[1]), 'c':float(args[2]), 'j_max':int(args[3]),'F':list(args[7:])},
                }

    command = espace_client.handle_request(ir_params)

    # send reply to the client
    reply_port = int(args[0])
    reply_addresse = (source[0], reply_port)
    msg = OSCMessage("/pd")
    msg.append(command['saved_audio_path'])
    server.client.sendto(msg,reply_addresse,timeout=1)
    print "OSCServer send:\n\t%s\nto %s.\n" %(msg,reply_addresse)

    return OSCMessage("/")
Beispiel #18
0
def sendOSCMessage(pin, value):
  # LOW/0 = pressed and HIGH/1 = released
  # example: "/b/p 12 0"
  if (value == 0):
    obj = OSCMessage("/b/p")
  else:
    obj = OSCMessage("/b/r")
  obj.append(int(pin))
def send_osc_message(name, *args):
	msg = OSCMessage(name)
	for arg in args:
		msg.append(arg)
	try:
		client.send(msg, 0)
	except Exception, e:
		pass
  def handle_sample(self, sample):
    mes = OSCMessage(self.address)
	mes.append(sample.channel_data)
	# silently pass if connection drops
	try:
		self.client.send(mes)
	except:
		return	
Beispiel #21
0
 def send(self, path, value):
     try:
         message = OSCMessage(path)
         message.append(value)
         self.osc.send(message)
     except:
         print "Error connecting to OSC server. Re-initiating Connection."
         self.setup_connection()
Beispiel #22
0
 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)
Beispiel #23
0
def sendOSCnextlevel():
        client = OSCClient()
        msg = OSCMessage()
        # gl.client is a tuple in gl with ip and port
        address = "/game/nextlevel"
        msg.setAddress(address)
        msg.append(currentlevel)
        client.sendto(msg, gl.send_to)
        #print('Send message example =', msg, "to ", gl.send_to)
        return
 def _oscHandler(self, addr, tags, stuff, source):
     addrTokens = addr.lstrip('/').split('/')
     ## list of all receivers
     if ((addrTokens[0].lower() == "localnet")
           and (addrTokens[1].lower() == "receivers")):
         ## as good, if not better than a ping
         self.lastPingTime = time.time()
         print "got receivers %s"%(stuff[0])        
         for rcvr in stuff[0].split(','):
             self.allReceivers[rcvr] = rcvr
         if(self.subscribedToAll and not self.subscribedReceivers):
             self.subscribeToAll()
     ## hijack /LocalNet/Add !
     elif ((addrTokens[0].lower() == "localnet")
         and (addrTokens[1].lower() == "add")):
         ip = getUrlStr(source).split(":")[0]
         port = int(stuff[0])
         print "adding %s:%s to PantallaServer" % (ip, port)
         self.allClients[(ip,port)] = addrTokens[2]
     ## hijack a /LocalNet/ListReceivers
     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(self.name)
         print "got a request for receivers from %s:%s"%(ip,port)
         try:
             #self.oscClient.connect((ip, port))
             self.oscClient.sendto(msg, (ip, port))
             #self.oscClient.connect((ip, port))
         except OSCClientError:
             print "no connection to %s:%s, can't send list of receivers"%(ip,port)
     ## actual message from AEffect Network !!
     elif (addrTokens[0].lower() == "aeffectlab"):
         self.messageQ.put((addrTokens[1],
                            addrTokens[2],
                            stuff[0].decode('utf-8')))
         self.messageQ.put((addrTokens[1],
                            addrTokens[2],
                            stuff[0].decode('utf-8')))
     ## ping
     if ((addrTokens[0].lower() == "localnet")
         and (addrTokens[1].lower() == "ping")):
         self.lastPingTime = time.time()
         # forward to clients
         for (ip,port) in self.allClients.keys():
             try:
                 #self.oscClient.connect((ip, int(port)))
                 self.oscClient.sendto(self.oscPingMessage, (ip, int(port)))
                 #self.oscClient.connect((ip, int(port)))
             except OSCClientError:
                 print ("no connection to %s:%s, can't send bang"%(ip,port))
Beispiel #25
0
 def send_osccreation(self, lista):
     # crea los objetos en el sound engine
     client = OSCClient()
     msg = OSCMessage()
     # gl.client is a tuple in gl with ip and port
     address = "/game/create"
     msg.setAddress(address)
     msg.append(lista)
     client.sendto(msg, gl.send_to)
     #print('Send message example =', msg, "to ", gl.send_to)
     return
Beispiel #26
0
 def send_destroy(self,id):
     #
     client = OSCClient()
     msg = OSCMessage()
     # gl.client is a tuple in gl with ip and port
     address = "/game/sndobj/destroy"
     msg.setAddress(address)
     msg.append(id)
     client.sendto(msg, gl.send_to)
     #print('Send message example =', msg, "to ", gl.send_to)
     return    
Beispiel #27
0
 def send_choque(self):
     #
     client = OSCClient()
     msg = OSCMessage()
     # gl.client is a tuple in gl with ip and port
     address = "/player/choque"
     msg.setAddress(address)
     msg.append(0)
     client.sendto(msg, gl.send_to)
     #print('Send message example =', msg, "to ", gl.send_to)
     return
def sendMessage():
    msg = OSCMessage()
    msg.setAddress("/oscTest")
    msg.append(100)
    print "Sending '/oscTest 100' message to SuperCollider"
    try:
        client.send(msg)
    except:
        print "Waiting for SuperCollider to become available..."
        pass
    timedSendMessage()  # recursive call, keeps the timer going
def serialComms():
	while run:
		proximity = ser.readline()
		proxMsg = OSCMessage()
		proxMsg.setAddress(OSCAddress)
		proxMsg.append(proximity)
		try:
			columnClient.send(proxMsg)
		except:
			print("client unavailable")
			pass
Beispiel #30
0
 def send_stop(self):
     # da stop al soundengine
     client = OSCClient()
     msg = OSCMessage()
     # gl.client is a tuple in gl with ip and port
     address = "/game/stop"
     msg.setAddress(address)
     msg.append(0)
     client.sendto(msg, gl.send_to)
     #print('Send message example =', msg, "to ", gl.send_to)
     return
Beispiel #31
0
 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 #32
0
def SendUI(oscaddress,oscargs=''):
        
    oscmsg = OSCMessage()
    oscmsg.setAddress(oscaddress)
    oscmsg.append(oscargs)
    
    osclientlj = OSCClient()
    osclientlj.connect((gstt.TouchOSCIP, gstt.TouchOSCPort)) 

    #print("MIDI Aurora sending UI :", oscmsg, "to",gstt.TouchOSCIP,":",gstt.TouchOSCPort)
    try:
        osclientlj.sendto(oscmsg, (gstt.TouchOSCIP, gstt.TouchOSCPort))
        oscmsg.clearData()
    except:
        log.err('Connection to Aurora UI refused : died ?')
        pass
Beispiel #33
0
def SendAU(oscaddress,oscargs=''):
        
    oscmsg = OSCMessage()
    oscmsg.setAddress(oscaddress)
    oscmsg.append(oscargs)
    
    osclientlj = OSCClient()
    osclientlj.connect((gstt.myIP, 8090)) 

    # print("MIDI Aurora sending itself OSC :", oscmsg, "to localhost:8090")
    try:
        osclientlj.sendto(oscmsg, (gstt.myIP, 8090))
        oscmsg.clearData()
    except:
        log.err('Connection to Aurora refused : died ?')
        pass
Beispiel #34
0
def processGaze(g):
    global lastData, t, samples
    conf = g['confidence']
    if conf > 0.5:
        if lastData <> '' and lastData == g['norm_pos']:
            return
        lastData = g['norm_pos']
        t1 = current_milli_time()
        msg = OSCMessage("/pupil/pos")
        msg.append(g['norm_pos'])
        client.send(msg)
        samples = samples + 1
        if t1 - t > 1000:
            print 'FPS:', samples
            t = t1
            samples = 0
Beispiel #35
0
 def loopend(self,arrCmd):
     oscm = OSCMessage("/live/clip/loop/end")
     oscm.append(self.int_or_string(arrCmd[0])) #track
     oscm.append(int(arrCmd[1])) #slot
     if arrCmd[2].lower() == 'bars':
         oscm.append((float(arrCmd[3]) - 1) * self.parent.signature_numerator) #position in beats
     else:
         oscm.append(float(arrCmd[3]) - 1) #position in beats
     return oscm
Beispiel #36
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')
Beispiel #37
0
def SendResol(oscaddress, oscargs):

    oscmsg = OSCMessage()
    oscmsg.setAddress(oscaddress)
    oscmsg.append(oscargs)

    osclientresol = OSCClient()
    osclientresol.connect((oscIPresol, oscPORTresol))

    print("lj23layers sending OSC message : ", oscmsg, "to Resolume",
          oscIPresol, ":", oscPORTresol)
    try:
        osclientresol.sendto(oscmsg, (oscIPresol, oscPORTresol))
        oscmsg.clearData()
    except:
        print('Connection to Resolume refused : died ?')
        pass
Beispiel #38
0
    def handleMessage(self):
        global osc_client
        # echo message back to client
        print "we got a msssagatege that said: " + self.data

        try: 
#            osc_client.send( OSCMessage("/user/2", [2.0, 3.0, 4.0 ] ) )

            oscmsg = OSCMessage()
            oscmsg.setAddress("/startup")
            oscmsg.append(str(self.data))
            osc_client.send(oscmsg)

    

        except Exception, e:
            print "sending osc message didn't work: " + str(e) 
Beispiel #39
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
Beispiel #40
0
def fader_callback(path, tags, args, source):
    print("path", path)
    print("args", args)
    print("source", source)

    value = int(args[0] * 10)
    if value > 1:
        led[0].on()
    if value > 2:
        led[1].on()
    if value > 3:
        led[2].on()
    if value > 4:
        led[3].on()
    if value > 5:
        led[4].on()
    if value > 6:
        led[5].on()
    if value > 7:
        led[6].on()
    if value > 8:
        led[7].on()

    if value < 1:
        led[0].off()
    if value < 2:
        led[1].off()
    if value < 3:
        led[2].off()
    if value < 4:
        led[3].off()
    if value < 5:
        led[4].off()
    if value < 6:
        led[5].off()
    if value < 7:
        led[6].off()
    if value < 8:
        led[7].off()

    msg = OSCMessage("/1/rotary1")
    msg.append(args)
    client.send(msg)
def cleanTagAndSendText(text):
    ## removes punctuation
    text = re.sub(r'[.,;:!?*/+=\-&%^/\\_$~()<>{}\[\]]', ' ', text)
    ## removes some bad words
    text = re.sub(r'(f *u *c *k)', 'tuck', text)
    text = re.sub(r'(s *h *i *t)', 'isht', text)
    text = re.sub(r'(c *o *c *k)', 'dock', text)
    text = re.sub(r'(d *i *c *k)', 'wick', text)
    text = re.sub(r'(c *u *n *t)', 'grunt', text)
    text = re.sub(r'(p *u *s *s *y)', 'juicy', text)
    text = re.sub(r'(b *i *t *c *h)', 'itch', text)
    text = re.sub(r'(a *s *s)', 'grass', text)
    ## replaces double-spaces with single space
    text = re.sub(r'( +)', ' ', text)

    taggedText = pos_tag(text.split())
    for (word, tag) in taggedText:
        print "(%s:%s)" % (word, tag),
    print " "

    ## log
    logFile.write(strftime("%Y%m%d-%H%M%S", localtime()) + "***" + text + "\n")
    logFile.flush()

    ## forward to all subscribers
    msg = OSCMessage()
    msg.setAddress("/NotTooPublic/response")
    msg.append(" ".join([str(i[0]) for i in taggedText]))
    msg.append(" ".join([str(i[1]) for i in taggedText]))

    delQ = Queue()
    for (ip, port) in myOscSubscribers:
        try:
            myOscClient.connect((ip, port))
            myOscClient.sendto(msg, (ip, port))
            myOscClient.connect((ip, port))
        except OSCClientError:
            print "no connection to %s : %s, can't send message" % (ip, port)
            delQ.put((ip, port))

    while not delQ.empty():
        del myOscSubscribers[delQ.get()]
Beispiel #42
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))
Beispiel #43
0
def SendLJ(oscaddress, oscargs=''):

    oscmsg = OSCMessage()
    oscmsg.setAddress(oscaddress)
    oscmsg.append(oscargs)

    osclientlj = OSCClient()
    osclientlj.connect((redisIP, 8002))
    #print("lj23layers for", name, "sending OSC message :", oscmsg, "to", redisIP, ":8002")

    if gstt.debug > 0:
        print("lj23layers for", name, "sending OSC message :", oscmsg, "to",
              redisIP, ":8002")

    try:
        osclientlj.sendto(oscmsg, (redisIP, 8002))
        oscmsg.clearData()

    except:
        print('Connection to LJ refused : died ?')
        pass
Beispiel #44
0
	def sendMsgBlocking(self,msg,*args):
		packetNumber = self.getPacketNumber()
		print "Sending %r (#%i)..." % (msg,packetNumber)
		omcall = Call()
		omcall.result = None
		omcall.done = False
		self.calls[packetNumber] = omcall
		message = OSCMessage()
		message.setAddress(msg)
		message.append(packetNumber)
		for arg in args:
			message.append(arg)
		self.transport.write(message.getBinary())
		now = time.time()
		while not omcall.done:
			time.sleep(INGEN_CALL_POLLTIME)			
			distance = time.time() - now
			if distance > INGEN_CALL_TIMEOUT:
				print "timeout"
				break			
		del self.calls[packetNumber]
		return omcall.result
def cleanTagAndSendText(text):
    ## removes punctuation
    text = re.sub(r'[.,;:!?*/+=\-&%^/\\_$~()<>{}\[\]]', ' ', text)
    ## replaces double-spaces with single space
    text = re.sub(r'( +)', ' ', text)
    ## log
    now = datetime.now(utc)
    logFile.write(now.isoformat() + "  ***  " + text + "\n")
    logFile.flush()

    ## forward to all subscribers
    msg = OSCMessage()
    msg.setAddress("/airmsg/response")
    msg.append(text.encode('utf-8'))

    try:
        myOscClient.connect((DISPLAY_ADDR, DISPLAY_PORT))
        myOscClient.sendto(msg, (DISPLAY_ADDR, DISPLAY_PORT))
        myOscClient.connect((DISPLAY_ADDR, DISPLAY_PORT))
    except OSCClientError:
        print("no connection to %s : %s, can't send message" %
              (DISPLAY_ADDR, DISPLAY_PORT))
Beispiel #46
0
    def handleMsg(self,oscAddress, tags, data, client_address):
        global machine
        global client_lucibox
        global client_nodejs
        global client_of
        
        print("OSC message received on : "+oscAddress)

        splitAddress = oscAddress.split("/")
        #DEBUG
        #print(splitAddress)
        
        ############## SERVICE itself #############
        if(splitAddress[1]=="app"):
            # TODO : restart dedicated services here
            if(splitAddress[2]=="close"):
                print("closing the app")
                quit_app()
            if(splitAddress[2]=="start"):
                print("starting the app")
                start_app()
            if(splitAddress[2]=="restart"):
                print("restart the app")
                quit_app()
                time.sleep(2)
                start_app()
        ############## RPI itself #############
        elif(splitAddress[1]=="rpi"):
            if(splitAddress[2]=="shutdown"):
                print("Turning off the rpi")
                powerOff()
            if(splitAddress[2]=="read"):
                read_disk()
            if(splitAddress[2]=="write"):
                write_disk()
        ############# LUCIBOX  ####
        elif(splitAddress[1]=="lucibox"):
            separator="/"
            splitAddress.remove("lucibox")
            finalAddress = separator.join(splitAddress)
            oscmsg = OSCMessage()
            oscmsg.setAddress(finalAddress)
            oscmsg.append(data)
            client_lucibox.send(oscmsg)
            ############# OPENFRAMEWORKS  ####
        elif(splitAddress[1]=="of"):
            separator="/"
            splitAddress.remove("of")
            finalAddress = separator.join(splitAddress)
            oscmsg = OSCMessage()
            oscmsg.setAddress(finalAddress)
            oscmsg.append(data)
            client_of.send(oscmsg)  
        ############ FORWARD TO NODEJS ###
        else :
            oscmsg = OSCMessage()
            oscmsg.setAddress(oscAddress)
            oscmsg.append(data)
            client_nodejs.send(oscmsg)
Beispiel #47
0
def sendMessage():
    #value = 0.1
    #values = arduino.readline()
    try:
        value = arduino.readline()
        print value
        #print struct.unpack("<L", value)[0]
        #print isinstance(value, chr)
        #intvalue = ord(value)
        msg = OSCMessage()
        msg.setAddress('/oscTest')
        msg.append(float(value))
    except:
        print "lo saltiamo"
        pass
    #print value
    try:
        client.send(msg)
    except:
        print "Waiting for SuperCollider to become available..."
        pass
    timedSendMessage()  # recursive call, keeps the timer going
Beispiel #48
0
	def updateNode(self,args,BSSID,kind):
		if BSSID == " ":
			return 
		msg =  OSCMessage("/update")
		msg.append(kind.strip())
		msg.append(args)
		msg.append(BSSID.strip()) 
		self.client.send(msg)
Beispiel #49
0
    def processObjectVector( self, objectVector):
        # Function to be implemented by all derived MetaDataProcessor interfaces.
        # print( "ChangeVolumeProcessor::processObjectVector() called." )

        objVectorNew = deepcopy(objectVector)
        objIndex = 0
        if type(objVectorNew) is list:
            for obj in objVectorNew:
                if self.active:
                    if int( obj['id']) in self.objectId:
                        #objID = int(obj['id']) + 1
                        objIndex = objIndex + 1
                        if obj['type'] == 'plane':
                            az = float(obj['direction']['az'])
                            el = float(obj['direction']['el'])
                            r = float(obj['direction']['refdist'])
                            #radius set to 1 atm
                            #SPAT_msg = "source " + str(objID) + " aed " + str(-az) + " " + str(el) + " " + str(1)
                            #SPAT_SOCK.sendto(SPAT_msg, (SPAT_IP, SPAT_PORT))
                            SPAT_osc = OSCMessage()
                            SPAT_osc.setAddress('/SPAT/pos')
                            SPAT_osc.append([objIndex, -az, el, 1])
                            client.send(SPAT_osc)
                            #print "hi"
                        else:
                            x = float(obj[ 'position' ]['x'])
                            y = float(obj[ 'position' ]['y'])
                            z = float(obj[ 'position' ]['z'])
                            (r,az,el) = cart2sphDeg(x,y,z)
                            #SPAT_msg = "source " + str(objID) + " aed " + str(-az) + " " + str(el) + " " + str(1)
                            #SPAT_SOCK.sendto(SPAT_msg, (SPAT_IP, SPAT_PORT))
                            SPAT_osc = OSCMessage()
                            SPAT_osc.setAddress('/SPAT/pos')
                            SPAT_osc.append([objIndex, -az, el, 1])
                            client.send(SPAT_osc)
                            #print "hi"
        return objVectorNew
def loop():
    global messageQ, clientMap, oscOut, currentButtonState, lastDownTime, isRecording, audioThread

    ## deal with UI
    previousButtonState = currentButtonState
    currentButtonState = GPIO.input(SWITCH_PIN)
    buttonJustGotPressed = (currentButtonState is GPIO.HIGH
                            and previousButtonState is GPIO.LOW)
    buttonJustGotReleased = (currentButtonState is GPIO.LOW
                             and previousButtonState is GPIO.HIGH)
    if buttonJustGotPressed:
        lastDownTime = time()

    if (isRecording):
        if ((time() - lastDownTime > 8.0)
                or (buttonJustGotReleased and (time() - lastDownTime > 1.0))
                or buttonJustGotPressed):
            isRecording = False
            GPIO.output(LED_PIN, GPIO.LOW)
            audioThread.join()
            call('rm -rf vox.mp3', shell=True)
            call('lame -mm -r vox.raw vox.mp3', shell=True)
            call('cp vox.mp3 data/vox_' +
                 strftime("%Y%m%d_%H%M%S", localtime()) + '.mp3',
                 shell=True)
            call('rm -rf vox.raw', shell=True)
            _setupAudio()
            messageQ.put((1, VOICE_MESSAGE_STRING))
    elif buttonJustGotPressed:
        isRecording = (not audioInput is None)
        GPIO.output(LED_PIN, GPIO.HIGH)
        audioThread = RecordThread()
        audioThread.start()

    ## deal with messages
    if (not messageQ.empty()):
        # TODO change this to something more complicated...
        # TODO nltk
        msg = messageQ.get()[1]
        for index, (i, p) in enumerate(clientMap):
            if (time() - clientMap[(i, p)] < 60):
                oscMsg = OSCMessage()
                oscMsg.setAddress("/ffqmevox")
                oscMsg.append(msg.encode('utf-8'))
                ## TODO: pan and tilt and delay
                oscMsg.append(randint(0, 255))
                oscMsg.append(randint(0, 255))
                oscMsg.append(0 if random() < 0.66 else index *
                              len(msg.encode('utf-8')) * 200)
                try:
                    oscOut.connect((i, p))
                    oscOut.sendto(oscMsg, (i, p))
                    oscOut.connect((i, p))
                except OSCClientError:
                    print "no connection to %s : %s, can't send message" % (i,
                                                                            p)
 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()
Beispiel #52
0
 def knob(self,arrCmd):
     if arrCmd[0].lower() == "send":
         oscm = OSCMessage("/live/return/device/param" )
         arrCmd.pop(0)
     else:
         oscm = OSCMessage("/live/track/device/param" )
     oscm.append(self.int_or_string(arrCmd[0]))  #track
     oscm.append(self.int_or_string(arrCmd[1]))  #device
     oscm.append(self.int_or_string(arrCmd[2]))  #param
     oscm.append(float(arrCmd[3]),'f')           #value
     return oscm
Beispiel #53
0
 def send(self,arrCmd):
     oscm = OSCMessage("/live/track/send" )
     oscm.append(self.int_or_string(arrCmd[0]))
     try:
         arrCmd[1] = int(arrCmd[1])
         arrCmd[1] += 1 #keep it 1 based instead of 0 based counting for consistancy
     except:
         arrCmd[1] = ord(arrCmd[1][0].lower()) - 97 #if using letters instead of numbers, convert to lower case and subtract so 'a' = 0, 'b' = 1, etc..
     oscm.append(int(arrCmd[1]),'i')
     oscm.append(int(arrCmd[2]) / 100.0,'f')
     return oscm
 def send_names(self, data):
     if self.need_send_names:
         self.need_send_names = False
         msg = OSCMessage("/wekinator/control/setInputNames")
         for k, v in data.items():
             if k.endswith("flag"):
                 msg.append(k)
             else:
                 msg.append(k + "_x")
                 msg.append(k + "_y")
                 msg.append(k + "_z")
         self._send(msg)
Beispiel #55
0
def oscSend():
    oscrot1 = OSCMessage()
    oscrot1.setAddress("/engine/RPM")
    oscrot1.append(measuredItemsValue[0])
    OSCC.send(oscrot1)

    oscrot2 = OSCMessage()
    oscrot2.setAddress("/engine/OilPress")
    oscrot2.append(measuredItemsValue[1])
    OSCC.send(oscrot2)

    oscrot3 = OSCMessage()
    oscrot3.setAddress("/engine/OilTemp")
    oscrot3.append(measuredItemsValue[2])
    OSCC.send(oscrot3)

    oscrot4 = OSCMessage()
    oscrot4.setAddress("/engine/EGT")
    oscrot4.append(measuredItemsValue[3])
    OSCC.send(oscrot4)
def NewData(data):
    global osc_client
    # print("data: {}".format(data))

    # simple example for on channel
    # value = data[0] / 255
    # # print("value: {}".format(value))
    # # python-osc
    # # osc_client.send_message("/filter", value)
    # # pyOSC
    # oscmsg = OSCMessage()
    # oscmsg.setAddress("/1/fader1")
    # oscmsg.append(value)
    # osc_client.send(oscmsg)

    # more complex example with multiple channels:
    # dmxch   - function
    # 0       - ch 01 mix fader
    # 1       - ch 01 mix on (mute)
    # first check that data has all needed information.
    if len(data) >= 1:
        # all infos available
        # set channel 01 fader
        # ch/01/mix/fader/ [0.0,1.0] fader(1024)"
        # convert channel level from 0..255 to 0..1
        ch_value = data[0] / 255
        oscmsg = OSCMessage()
        oscmsg.setAddress("ch/01/mix/fader")
        oscmsg.append(ch_value)
        osc_client.send(oscmsg)
        print(oscmsg)
    if len(data) >= 2:
        # all infos available
        # set channel 01 mute
        oscmsg = OSCMessage()
        oscmsg.setAddress("ch/01/mix/on")
        if data[1] is 0:
            # channel active
            oscmsg.append(1)
            osc_client.send(oscmsg)
            print(oscmsg)
        elif data[1] is 255:
            # channel off
            oscmsg.append(0)
            osc_client.send(oscmsg)
            print(oscmsg)
Beispiel #57
0
def sendosc(oscaddress,oscargs):
#def sendosc(oscargs):
    
    # also works : osclient.send(OSCMessage("/led", oscargs))

    oscpath = oscaddress.split("/")
    pathlength = len(oscpath)

    oscmsg = OSCMessage()

    #print "here in sendosc in nozosc"
    #print oscaddress
    #print oscargs
    #raw_input("Press Enter to continue3...")


    if oscpath[2] == "name":
	print "we are asked to send a name"
	oscmsg.setAddress(oscaddress)
	oscmsg.append(oscargs)

    if oscpath[2] == "status":
	print "we are asked to send a status"
	oscmsg.setAddress(oscaddress)
	oscmsg.append(oscargs)

    if oscpath[2] == "knob":
	print "we are asked to send knob %d's value" % int(oscargs[0:3])
	oscmsg.setAddress(''.join((oscaddress,"/",str(int(oscargs[0:3])))))
	oscmsg.append(int(oscargs[3:100]))
	
    if oscpath[2] == "osc":
	#print "we are asked to send continusouly an osc value"
	#print oscargs
	oscmsg.setAddress(''.join((oscaddress,"/",str(int(oscargs[0:3])))))
	#print "oscmsg:", oscmsg
	oscmsg.append(int(oscargs[3:100]))

    if oscpath[2] == "lfo":
	#print "we are asked to send continusouly a lfo value"
	oscmsg.setAddress(''.join((oscaddress,"/",str(int(oscargs[0:2])))))
	oscmsg.append(int(oscargs[2:100]))

    if oscpath[2] == "vco":
	#print "we are asked to send continusouly a vco value"
	oscmsg.setAddress(''.join((oscaddress,"/",str(int(oscargs[0:2])))))
	oscmsg.append(int(oscargs[2:100]))

    if oscpath[2] == "mix":
	#print "we are asked to send continusouly a mix value"
	oscmsg.setAddress(''.join((oscaddress,"/",str(int(oscargs[0:2])))))
	oscmsg.append(int(oscargs[2:100]))

    if oscpath[2] == "X":
	print "we are asked to send continusouly a X value"
	oscmsg.setAddress(oscaddress)
	oscmsg.append(oscargs)

    if oscpath[2] == "Y":
	print "we are asked to send continusouly a Y value"
	print "oscaddress:",oscaddress
	print "oscargs",oscargs
	oscmsg.setAddress(oscaddress)
	oscmsg.append(oscargs)

    if oscpath[2] == "offset":
	print "we are asked to offset a curve"
	oscmsg.setAddress(oscaddress)
	oscmsg.append(oscargs)

    if oscpath[2] == "color":
	print "we are asked to change lazer color"
	oscmsg.setAddress(oscaddress)
	if len(oscargs) > 0:
		oscmsg.append(oscargs)

    try:
        #print oscmsg
	osclient.sendto(oscmsg, (oscIPout, oscPORTout))
	oscmsg.clearData()
    except:
	print ('Connection refused at ',oscIPout)
        pass
Beispiel #58
0
def quick_message(host, port, path, *args):
    msg = OSCMessage(path)
    [msg.append(d) for d in args]
    client = OSCClient()
	client.sendto(msg, (host, port), timeout=0)
Beispiel #59
0
 def grid_key(self, x, y, s):
     msg = OSCMessage("%s/grid/key" % self.prefix)
     msg.append(x)
     msg.append(y)
     msg.append(s)
 	self.client.sendto(msg, (self.app_host, self.app_port), timeout=0)
Beispiel #60
0
#!/usr/bin/env python

# http://shinybit.github.io/sending-osc-messages-from-pythonista/

# https://gist.github.com/shinybit/3d7e0fc7e62887ab48e931af1d4c0986

# Get pyOSC here: https://trac.v2.nl/wiki/pyOSC
# The GitHub-hosted version of pyOSC is for Python 3 which isn't supported by Pythonista at the moment
from OSC import OSCClient, OSCMessage

client = OSCClient()
client.connect(("192.168.43.120", 8000))

msg = OSCMessage("/msg/notes")
msg.append([50, 60])
client.send(msg)

msg.clearData()
msg.append(["C3", 127])
client.send(msg)

client.send(OSCMessage("/quit"))