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 serialComms():
    while run:
        proximity = ser.readline()
        proxMsg = OSCMessage()
        proxMsg.setAddress(OSCAddress)
        proxMsg.append(proximity)
        columnClient.send(proxMsg)
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
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)
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
Beispiel #6
0
def update():
    message = OSCMessage()  #Create the OSC Message
    message.setAddress("/myoscaddress")  #Define the OSC Address
    message.append(44)  #first argument
    message.append(11)  #second argument
    message.append(4.5)  #third argument
    oscclient.sendto(message, (OSC_DEST_IP, OSC_DEST_PORT))  #send osc message
Beispiel #7
0
def callback_videoOn4(path, tags, args, source):
    if args[0] == 1.0:
        msg = OSCMessage(
        )  #  we reuse the same variable msg used above overwriting it
        msg.setAddress("/millumin/action/launchOrStopColumn")
        msg.append(9.0)
        print "videoOn4"
Beispiel #8
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)
Beispiel #9
0
def sendAutodiscovery(i):
    print "/tph/autodiscovery " + str(i)
    message = OSCMessage()  #Create the OSC Message
    message.setAddress("/tph/autodiscovery")  #Define the OSC Address
    message.append(int(i))
    oscclient.sendto(message,
                     (OSC_BROADCAST_IP, OSC_BROADCAST_PORT))  #send osc message
def serialComms():
	while run:
		proximity = ser.readline()
		proxMsg = OSCMessage()
		proxMsg.setAddress(OSCAddress)
		proxMsg.append(proximity)
		columnClient.send(proxMsg)
Beispiel #11
0
def OSCsend(name, oscaddress, oscargs=''):

    ip = midi2OSC[name]["oscip"]
    port = midi2OSC[name]["oscport"]
    osclient = OSCClient()
    osclient.connect((ip, port))
    oscmsg = OSCMessage()
    oscmsg.setAddress(oscaddress)
    oscmsg.append(oscargs)

    try:
        if gstt.debug > 0:
            print("Midi OSCSend : sending", oscmsg, "to", name, "at",
                  gstt.LjayServerIP, ":", PluginPort)
        osclient.sendto(oscmsg, (ip, port))
        oscmsg.clearData()
        #if gstt.debug >0:
        #   print oscaddress, oscargs, "was sent to",name
        return True

    except:
        if gstt.debug > 0:
            print('Midi OSCSend : Connection to IP', ip, ':', port,
                  'refused : died ?')
        #sendWSall("/status No plugin.")
        #sendWSall("/status " + name + " is offline")
        #sendWSall("/" + name + "/start 0")
        #PluginStart(name)
        return False
Beispiel #12
0
def send_osc(address, value):
    oscMsg = OSCMessage()
    oscMsg.setAddress(address)
    oscMsg.append(int(value))
    try:
        oscClient.send(oscMsg)
    except Exception, e:
        print e
Beispiel #13
0
def send_osc_message(address, message):
    oscmsg = OSCMessage()
    oscmsg.setAddress(address)
    oscmsg.append(message)
    try:
        client.send(oscmsg)
    except:
        print "Error sending messsage, reciever may not be available"
Beispiel #14
0
def sendColor(color):

    message = OSCMessage()  #Create the OSC Message
    message.setAddress("/tph/color")  #Define the OSC Address
    message.append(int(color.r))
    message.append(int(color.g))
    message.append(int(color.b))
    oscclient.sendto(message, (OSC_DEST_IP, OSC_DEST_PORT))  #send osc message
Beispiel #15
0
def touched(i):
    global elapsedTime

    print "/tph/touched " + str(i)

    elapsedTime = 0.0

    if i == 11:
        print "Set Color Red"
        setNewColor(ofColor(255, 0, 0))
    elif i == 9:
        print "Set Color Green"
        setNewColor(ofColor(0, 255, 0))
    elif i == 7:
        print "Set Color Blue"
        setNewColor(ofColor(0, 0, 255))
    elif i == 8:
        print "Set Color Cyan"
        setNewColor(ofColor(0, 255, 255))
    elif i == 6:
        print "Set Color Magenta"
        setNewColor(ofColor(255, 0, 255))
    elif i == 10:
        print "Set Color Yellow"
        setNewColor(ofColor(255, 255, 0))
    elif i == 5:
        print "Set Color White"
        setNewColor(ofColor(255, 255, 255))

    elif i == 1:
        print "Set Sparkles"
        setAlphas(0)
        sparkles.setAlpha(1)

    elif i == 0:
        print "Set Rainbow"
        setAlphas(0)
        rainbow.setAlpha(1)

    elif i == 3:
        print "Set Fade"
        setAlphas(0)
        fade.setAlpha(1)

    elif i == 2:
        print "Set Waves"
        setAlphas(0)
        waves.setAlpha(1)

    elif i == 4:
        print "Set Circles"
        setAlphas(0)
        circles.setAlpha(1)

    message = OSCMessage()  #Create the OSC Message
    message.setAddress("/tph/mode")  #Define the OSC Address
    message.append(int(i))
    oscclient.sendto(message, (OSC_DEST_IP, OSC_DEST_PORT))  #send osc message
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 callback_videoStop(path, tags, args, source):
    if args[0] == 1.0:
        msg = OSCMessage(
        )  #  we reuse the same variable msg used above overwriting it
        msg.setAddress("/millumin/action/stopColumn")
        print "stopVideo"
        client.send(
            msg)  # now we dont need to tell the client the address anymore
        client2.send(
            msg)  # now we dont need to tell the client the address anymore
Beispiel #18
0
def room_assert(facts):
    for fact in facts:
        try:
            msg = OSCMessage()
            msg.setAddress('/assert')
            msg.append(fact)
            c.send(msg)
        except OSCClientError as e:
            # FIXME: hack so it doesn't crash
            sys.stderr.write(str(e) + '\n')
Beispiel #19
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
Beispiel #20
0
def callback_videoOn1eng(path, tags, args, source):
    if args[0] == 1.0:
        msg = OSCMessage(
        )  #  we reuse the same variable msg used above overwriting it
        msg.setAddress("/millumin/action/launchOrStopColumn")
        msg.append(3.0)
        #client.send(msg) # now we dont need to tell the client the address anymore
        #client2.send(msg) # now we dont need to tell the client the address anymore

        print "videoOn1eng"
 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 #22
0
def sendOSCend():
        #
        client = OSCClient()
        msg = OSCMessage()
        # gl.client is a tuple in gl with ip and port
        address = "/game/end"
        msg.setAddress(address)
        msg.append(1)
        client.sendto(msg, gl.send_to)
        print('Send message example =', msg, "to ", gl.send_to)
        return
Beispiel #23
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 #24
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 #25
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
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 #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(self, adr, *args):
     self.adr = adr
     #         msg = OSC.OSCMessage()
     msg = OSCMessage()
     msg.setAddress(self.adr)
     for i in args:
         msg.append(i)
     try:
         self.client.send(msg)
     except:
         print ">>> ERR :: Could not connect to ", self.ip_adr, ":", self.port
Beispiel #31
0
 def oscSender(self, addr, params):
     msg = OSCMessage()
     msg.setAddress(addr)
     if params is not None:
         for param in params:
             msg.append(param)
     print "sending: " + str(msg) + " to: " + str(self.oscClient) # do not indent this line!
     try:
         self.oscClient.send(msg)
     except OSCClientError:
         # could explicitly try to detect errno 61 here
         print "WARNING: cannot send to SuperCollider"
Beispiel #32
0
def sendme(oscaddress, oscargs):

    oscmsg = OSCMessage()
    oscmsg.setAddress(oscaddress)
    oscmsg.append(oscargs)
    if gstt.debug > 0:
        print "sending me: ", oscmsg
    try:
        osclientme.sendto(oscmsg, (oscIPin, oscPORTin))
        oscmsg.clearData()
    except:
        print('Connection to myself refused')
        pass
Beispiel #33
0
def send3(oscaddress, oscargs):

    oscmsg = OSCMessage()
    oscmsg.setAddress(oscaddress)
    oscmsg.append(oscargs)
    if gstt.debug > 0:
        print "sending to 3 : ", oscmsg
    try:
        osclient3.sendto(oscmsg, (oscIPin, 8003))
        oscmsg.clearData()
    except:
        print('Connection to 3 refused')
        pass
Beispiel #34
0
def my_callback(channel):
    global timePulse
    if (time.time() - timePulse) > timerPulse:
        try:
            msg = OSCMessage(
            )  #  we reuse the same variable msg used above overwriting it
            msg.setAddress("/keydown")
            print "/keydown"
            client.send(
                msg)  # now we dont need to tell the client the address anymore
            timePulse = time.time()
        except:
            print("Sin conexion OSC")
Beispiel #35
0
def proximityComms():
	while run:
		proximity = ser.readline()
		print(proximity)
		time.sleep(0.01)
		#proximity = readadc(prox_adc, SPICLK, SPIMOSI, SPIMISO, SPICS)
		proxMsg = OSCMessage()
		proxMsg.setAddress(OSCAddress)
		proxMsg.append(proximity)
		try:
			columnClient.send(proxMsg)
		except:
			print("client unavailable")
			pass
Beispiel #36
0
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 (i,p) in 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)
				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)
Beispiel #37
0
def sendresol(oscaddress, oscargs):

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

    if gstt.debug > 0:
        print "sending to Resolume : ", oscmsg
    try:
        osclientresol.sendto(oscmsg, (oscIPresol, oscPORTresol))
        oscmsg.clearData()
    except:
        print('Connection to Resolume refused')
        pass
Beispiel #38
0
def sendme(oscaddress,oscargs):
#def sendme(oscargs):
        
    oscmsg = OSCMessage()
    oscmsg.setAddress(oscaddress)
    oscmsg.append(oscargs)
    
    #print "sending me: ",oscmsg, oscargs
    try:
        osclientme.sendto(oscmsg, (oscIPin, oscPORTin))
        oscmsg.clearData()
    except:
        print ('Connection to mycontroller refused')
        pass
Beispiel #39
0
def sendnozosc(oscaddress,oscargs=''):
		
	oscmsg = OSCMessage()
	oscmsg.setAddress(oscaddress)
	oscmsg.append(oscargs)
	
	#print ("sending to nozosc : ",oscmsg)
	try:
		osclientnozosc.sendto(oscmsg, (NozoscIPout, NozoscPORTout))
		oscmsg.clearData()
	except:
		print ('Connection to nozosc refused : died ?')
		sendWSall("/on 0")
		sendWSall("/status No Nozosc ")
		pass
Beispiel #40
0
	def sendMsg(self,msg,*args):
		packetNumber = self.getPacketNumber()
		print "Sending %r (#%i)..." % (msg,packetNumber)
		omcall = Call()
		omcall.result = None
		omcall.done = False
		self.calls[packetNumber] = omcall
		message = OSCMessage()
		message.setAddress(msg)
		message.append(packetNumber)
		for arg in args:
			message.append(arg)
		self.transport.write(message.getBinary())
		time.sleep(0.01)
		return True
Beispiel #41
0
def sendosc(oscaddress, oscargs):

    # also works : osclient.send(OSCMessage("/led", oscargs))

    oscmsg = OSCMessage()
    oscmsg.setAddress(oscaddress)
    oscmsg.append(oscargs)
    if gstt.debug > 0:
        print "sending : ", oscmsg
    try:
        osclient.sendto(oscmsg, (oscIPout, oscPORTout))
        oscmsg.clearData()
    except:
        print('Connection refused at ', oscIPout)
        pass
Beispiel #42
0
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
            audioThread.join()
            call('lame -mm -r foo.raw foo.mp3', shell=True)
            messageQ.put((1, VOICE_MESSAGE_STRING))
    elif buttonJustGotPressed:
        isRecording = (not audioInput is None)
        audioThread = RecordThread()
        audioThread.start()

    GPIO.output(LED_PIN, GPIO.HIGH if isRecording else GPIO.LOW)

    ## deal with messages
    if (not messageQ.empty()):
        # TODO change this to something more complicated...
        # TODO nltk
        msg = messageQ.get()[1]
        for (i, p) in clientMap:
            if (time() - clientMap[(i, p)] < 60):
                oscMsg = OSCMessage()
                oscMsg.setAddress("/ffqmevox")
                oscMsg.append(msg)
                ## TODO: pan and tilt
                oscMsg.append(0)
                oscMsg.append(0)
                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)
Beispiel #43
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 #44
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 #45
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 #46
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
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 #48
0
 def send_osclocation(self):
     #cuando hay un cambio de situacion se envia
     #           /player/in    /player/out      /player/border
     client = OSCClient()
     msg = OSCMessage()
     # gl.client is a tuple in gl with ip and port
     if self['location'] == 'IN':
         address = "/player/in"
     elif self['location'] == 'OUT':
         address = "/player/out"
     else:
         address = "/player/border"
     msg.setAddress(address)
     msg.append(1)
     client.sendto(msg, gl.send_to)
     print(msg)
     #print('Send message example =', msg, "to ", gl.send_to)
     return 
Beispiel #49
0
def setup(inIp, inPort, webServerAddress, webServerPort):
    global prototypes, mOscClient, oscPingMessage
    global lastPrototypeCheck, receivers
    receivers = {}
    prototypes = {}
    lastPrototypeCheck = time.time()
    oscPingMessage = OSCMessage()
    oscPingMessage.setAddress("/LocalNet/Ping")
    ## use empty byte blob
    oscPingMessage.append("", 'b')

    try:
        Message.create_table()
    except:
        print "tried to recreate message table, pero no pasa nada"

    print "message table has %s entries" % Message.select().count()
    """
    for m in Message.select():
        print "%s %s [%s]" % (m.time, str(m.text).decode('utf-8'), m.receiver)
    """

    ## init receivers
    rcvT = TwitterReceiver()
    receivers['twitter'] = rcvT
    rcvS = SmsReceiver()
    receivers['sms'] = rcvS
    rcvO = OscReceiver(receivers,prototypes, ip=inIp, port=inPort)
    receivers['osc'] = rcvO
    rcvH = HttpReceiver(receivers,prototypes, webServerAddress, webServerPort, LOCAL_NET_DESCRIPTION)
    receivers['http'] = rcvH
    mOscClient = OSCClient()
    setupDelQ = Queue()
    for (k,v) in receivers.iteritems():
        if(not v.setup(Message, mOscClient, LOCAL_NET_LOCALE)):
            setupDelQ.put(k)
    while (not setupDelQ.empty()):
        badReceiver = setupDelQ.get()
        del receivers[badReceiver]
    ## if using as server-osc-repeater
    if (("MASTER_SERVER_IP" in globals()) and ("MASTER_SERVER_PORT" in globals())
        and ('osc' in receivers)):
        receivers['osc'].setupMaster(MASTER_SERVER_IP, MASTER_SERVER_PORT)
Beispiel #50
0
def sendled(zzzport):
	global counter
	
	zzz = zzzport % 127			
								# zzz = led color
	msg = OSCMessage()
	msg.setAddress("/bhoreal/in")
	msg.append(counter)
	msg.append(zzz)
	try:
		client.sendto(msg, ('127.0.0.1', 9002))
		msg.clearData()
	except:
		print 'Connection refused'
		pass
	sleep(0.001)
	counter += 1
	if counter > 63:
		counter = 0
    def _oneWordToEach(self, locale,type,txt):
        clientIndex = 0
        words = txt.split()
        for w in words:
            msg = OSCMessage()
            msg.setAddress("/AeffectLab/"+locale+"/"+type)
            msg.append(w.encode('utf-8'), 'b')
            (ip,port) = self.allClients.keys()[clientIndex]

            try:
                #self.oscClient.connect((ip, int(port)))
                self.oscClient.sendto(msg, (ip, int(port)))
                #self.oscClient.connect((ip, int(port)))
            except OSCClientError:
                print "no connection to %s:%s, can't send message "%(ip,port)
                #del self.allClients[(ip,port)]
            
            if (self.allClients):
                clientIndex = (clientIndex+1)%len(self.allClients.keys())
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 #53
0
def cleanTagAndSendText(text):
    ## removes punctuation
    text = re.sub(r'[.,;:!?*/+=\-&%^/\\_$~()<>{}\[\]]', ' ', text)
    ## replaces double-spaces with single space
    text = re.sub(r'( +)', ' ', text)

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

    ## forward to all subscribers
    msg = OSCMessage()
    msg.setAddress("/airmsg/response")
    msg.append(text)

    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)
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 #55
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 _oneMessageToEach(self, locale,type,txt):
        clientKeys = self.allClients.keys()
        ## get a random client to push the new message
        shuffle(clientKeys,random)
        self.oldMessages.append(txt)
        probability = 1.1
        for (ip,port) in clientKeys:
            if(random() < probability):
                msg = OSCMessage()
                msg.setAddress("/AeffectLab/"+locale+"/"+type)
                msg.append(self.oldMessages[-1].encode('utf-8'),'b')
                try:
                    #self.oscClient.connect((ip, int(port)))
                    self.oscClient.sendto(msg, (ip, int(port)))
                    #self.oscClient.connect((ip, int(port)))
                except OSCClientError:
                    print "no connection to %s:%s, can't send message "%(ip,port)
                    #del self.allClients[(ip,port)]

                probability = 0.66
                shuffle(self.oldMessages)
        if(len(self.oldMessages) > 10):
            self.oldMessages.pop()
Beispiel #57
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)