def setup():
    print "setup"
    global currentButtonState, lastDownTime, isRecording, audioInput
    global messageQ, clientMap, oscIn, oscOut, oscThread, mAudioServer
    messageQ = PriorityQueue()
    clientMap = {}

    ## setup osc client
    oscOut = OSCClient()

    ## setup osc receiver
    oscIn = OSCServer((OSC_IN_ADDRESS, OSC_IN_PORT))
    oscIn.addMsgHandler('default', _oscHandler)
    oscThread = Thread(target=oscIn.serve_forever)
    oscThread.start()
    print "osc in ready"

    ## setup audio server
    #mAudioServer = ThreadedServer()
    #mAudioServer.start()

    ## setup gpio
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(SWITCH_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
    GPIO.setup(LED_PIN, GPIO.OUT)
    GPIO.output(LED_PIN, GPIO.LOW)
    currentButtonState = GPIO.input(SWITCH_PIN)
    lastDownTime = 0
    isRecording = False

    _setupAudio()
Example #2
0
def setupServer():
  global server
  server = OSCServer( (HOST_NAME, PORT_NUM) )
  server.timeout = 0
  server.handle_timeout = types.MethodType(handle_timeout, server)
  server.addMsgHandler( "/dmx", user_callback )
  print(server)
Example #3
0
def setup():
	global currentButtonState, lastDownTime, isRecording, audioInput
	global messageQ, clientMap, oscIn, oscOut, oscThread
	messageQ = PriorityQueue()
	clientMap = {}

	## setup osc client
	oscOut = OSCClient()

	## setup osc receiver
	oscIn = OSCServer((OSC_IN_ADDRESS, OSC_IN_PORT))
	oscIn.addMsgHandler('default', _oscHandler)
	oscThread = Thread(target = oscIn.serve_forever)
	oscThread.start()
	print "osc in ready"

	## setup gpio
	GPIO.setup(SWITCH_PIN, GPIO.IN)
	GPIO.setup(LED_PIN, GPIO.OUT)
	GPIO.output(LED_PIN, GPIO.LOW)
	currentButtonState = GPIO.input(SWITCH_PIN)
	lastDownTime = 0
	isRecording = False

	## setup audio
	audioInput = None
	try:
		audioInput = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, "default:Headset")
		audioInput.setchannels(1)
		audioInput.setrate(44100)
		audioInput.setformat(alsaaudio.PCM_FORMAT_S16_LE)
		audioInput.setperiodsize(256)
	except:
		print "couldn't start audio device"
		audioInput = None
def main():
    global server
    
    connected = False

    while not connected:
        try:
            server = OSCServer( ("10.101.203.74", 10000) )
            server.timeout = 0
            run = True
            connected = True

        except: 
            print "OSC Server no encontrado"
            time.sleep(5)

    GPIO.setmode(GPIO.BCM)
    m = Motor([17,18,27,22])

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

    server.addMsgHandler( "/base", base_move )
    server.addMsgHandler( "/altura", altura_move )

    while(True):
        each_frame()
        try:
            m.rpm = 10
            m.move_to(rotateBase)
            # m.move_to(0)

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

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


    server.close()
Example #6
0
def setup():
	print "setup"
	global currentButtonState, lastDownTime, isRecording, audioInput
	global messageQ, clientMap, oscIn, oscOut, oscThread, mAudioServer
	messageQ = PriorityQueue()
	clientMap = {}

	## setup osc client
	oscOut = OSCClient()

	## setup osc receiver
	oscIn = OSCServer((OSC_IN_ADDRESS, OSC_IN_PORT))
	oscIn.addMsgHandler('default', _oscHandler)
	oscThread = Thread(target = oscIn.serve_forever)
	oscThread.start()
	print "osc in ready"

	## setup audio server
	mAudioServer = ThreadedServer()
	mAudioServer.start()

	## setup gpio
	GPIO.setmode(GPIO.BCM)
	GPIO.setup(SWITCH_PIN, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
	GPIO.setup(LED_PIN, GPIO.OUT)
	GPIO.output(LED_PIN, GPIO.LOW)
	currentButtonState = GPIO.input(SWITCH_PIN)
	lastDownTime = 0
	isRecording = False

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

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


    server.close()
Example #8
0
class ColorsIn:
# this method of reporting timeouts only works by convention
# that before calling handle_request() field .timed_out is 
# set to False


    def set_colors(self,path, tags, args, source):
        # which user will be determined by path:
        # we just throw away all slashes and join together what's left
        #print "Here's what we got : path:%s tags:%s args:%s source:%s"%(str(path),str(tags),str(args),str(source))
        pixels = []
        for i in range(0,len(args)/3):
            pixel = (clamp(args[i*3]), clamp(args[i*3+1]), clamp(args[i*3+2]))
            pixels.append( pixel )
        #print "Pixels: %s"%str(pixels)
        #print "Time: "+str((time.time()*1000) % 10000)
        octoapi.write(pixels)
        self.lastwrite=time.time()
        self.server.lastpixels = pixels

    def diff_colors(self, path, tags, args, source):
        # which user will be determined by path:
        # we just throw away all slashes and join together what's left
        #print "Here's what we got : path:%s tags:%s args:%s source:%s"%(str(path),str(tags),str(args),str(source))
        pixels = server.lastpixels
        for i in range(0,len(args)/3):
            pp = (args[i*3],args[i*3+1],args[i*3+2])
            p = pixels[i]
            pixels[i] = (clamp(p[0]+pp[0]), clamp(p[1]+pp[1]), clamp(p[2]+pp[2]))
        #print "Pixels: %s"%str(pixels)
        #print "Time: "+str((time.time()*1000) % 10000)
        octoapi.write(pixels)
        self.lastwrite=time.time()
        self.server.lastpixels = pixels

    def each_frame(self):
        self.server.timed_out = False
        while not self.server.timed_out:
            if time.time() - self.lastwrite > CLEAR_TIME:
                self.lastwrite = time.time()
                octoapi.write([(0,0,0)]*24)
                print "Clearing"
            self.server.handle_request()

    def start(self):
        #server = OSCServer( ("128.174.251.39", 11661) )
        self.server = OSCServer( ("localhost", 11661) )
        self.server.timeout = 0
        self.lastwrite = time.time()        
        self.server.handle_timeout = types.MethodType(handle_timeout, self.server)
        self.server.lastpixels = [(0,0,0)]*24

        self.server.addMsgHandler( "/setcolors", self.set_colors)
        self.server.addMsgHandler( "/diffcolors", self.diff_colors)
        while True:
            self.each_frame()

        self.server.close()
Example #9
0
class OSCServerClass:
  def __init__(self, id, ip, port):
    self.robot = id

    self.bridge = MeccaBridge()

    self.server = OSCServer((ip, port))
    self.server.timeout = 0
    self.active = True
    self.server.handle_timeout = types.MethodType(handle_timeout, self.server)

    self.server.addMsgHandler("/" + self.robot + "/pinMove"  , self.pinMoveHandler  )
    self.server.addMsgHandler("/" + self.robot + "/pinLight" , self.pinLightHandler )
    self.server.addMsgHandler("/" + self.robot + "/init"     , self.initHandler     )
    self.server.addMsgHandler("/" + self.robot + "/headLight", self.headLightHandler)

    self.gotMessage = False
    
#######################################################################

  def run(self):
    print("serving on {}".format(self.server.server_address))
    self.server.running = True
    while self.server.running:
      while True:
        self.server.handle_request()
        if not self.gotMessage:
          break
        self.gotMessage = False

      self.bridge.sendMessages()
      time.sleep(0.01);

######################################################################

  def pinMoveHandler(self, path, tags, args, source):
    #print(path + "\n")
    #print ', '.join(map(str, args))
    self.bridge.sendServoPosition(args[0], args[1], args[2], args[3])
    self.gotMessage = True
 
######################################################################    
       
  def pinLightHandler(self, path, tags, args, source):
    self.bridge.sendPinLight(args[0], args[1], args[2])
    self.gotMessage = True

######################################################################

  def initHandler(self, path, tags, args, source):
    self.bridge.sendInit(args[0], args[1])
    self.gotMessage = True

######################################################################

  def headLightHandler(self, path, targs, args, source):
    self.bridge.sendHeadLight(args[0], args[1], args[2], args[3])
    self.gotMessage = True
Example #10
0
    def _get_osc_test_server(self, port=None):
        def intercepting_handler(addr, tags, data, source):
            msg_string = "%s [%s] %s" % (addr, tags, str(data))
            sys.stdout.write("OSCServer Got: '%s' from %s\n" %
                             (msg_string, getUrlStr(source)))
            self.testQueue.put(data)

        port = port or self.remote_osc_address[1]
        s = OSCServer(('localhost', port))
        s.addMsgHandler('default', intercepting_handler)

        return s
Example #11
0
class Manta(object):

    def __init__(self, receive_port=31416, send_port=31417, send_address='127.0.0.1'):
        self.osc_client = OSCClient()
        self.osc_server = OSCServer(('127.0.0.1', receive_port))
        self.osc_client.connect(('127.0.0.1', send_port))
        # set the osc server to time out after 1ms
        self.osc_server.timeout = 0.001
        self.event_queue = []
        self.osc_server.addMsgHandler('/manta/continuous/pad',
                self._pad_value_callback)
        self.osc_server.addMsgHandler('/manta/continuous/slider',
                self._slider_value_callback)
        self.osc_server.addMsgHandler('/manta/continuous/button',
                self._button_value_callback)
        self.osc_server.addMsgHandler('/manta/velocity/pad',
                self._pad_velocity_callback)
        self.osc_server.addMsgHandler('/manta/velocity/button',
                self._button_velocity_callback)

    def process(self):
        self.osc_server.handle_request()
        ret_list = self.event_queue
        self.event_queue = []
        return ret_list

    def _pad_value_callback(self, path, tags, args, source):
        self.event_queue.append(PadValueEvent(args[0], args[1]))

    def _slider_value_callback(self, path, tags, args, source):
        touched = False if args[1] == 0xffff else True
        scaled_value = args[1] / 4096.0
        self.event_queue.append(SliderValueEvent(args[0], touched, scaled_value))

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

    def _pad_velocity_callback(self, path, tags, args, source):
        self.event_queue.append(PadVelocityEvent(args[0], args[1]))

    def _button_velocity_callback(self, path, tags, args, source):
        self.event_queue.append(ButtonVelocityEvent(args[0], args[1]))

    def _send_osc(self, path, *args):
        msg = OSCMessage(path)
        msg.append(args)
        self.osc_client.send(msg)

    def set_led_enable(self, led_type, enabled):
        self._send_osc('/manta/ledcontrol', led_type, 1 if enabled else 0)

    def set_led_pad(self, led_state, pad_index):
        self._send_osc('/manta/led/pad', led_state, pad_index)
	class OscServerThread(Thread):
		def __init__(self, host, stopEvent):
			Thread.__init__(self)
			self.server = OSCServer(host)
			self.stopEvent = stopEvent
		def setCallBacks(self, callBacks):
			for callBack in callBacks:
				self.server.addMsgHandler(callBack[0], callBack[1])
		def run(self):
			while not self.stopEvent.is_set():
				self.server.handle_request()
			self.server.close()
    def _get_osc_test_server(self, port=None):
        def intercepting_handler(addr, tags, data, source):
            msg_string = "%s [%s] %s" % (addr, tags, str(data))
            sys.stdout.write(
                "OSCServer Got: '%s' from %s\n" % (
                    msg_string, getUrlStr(source)
            ))
            self.testQueue.put(data)
        port = port or self.remote_osc_address[1]
        s = OSCServer(('localhost', port))
        s.addMsgHandler('default', intercepting_handler)

        return s
Example #14
0
def main():

	if len(sys.argv)>1:
		OSC_ADDRESS = str(sys.argv[1])
	else:
		OSC_ADDRESS = OSC_ADDRESS_DEFAULT

	if len(sys.argv)>2:
		OSC_PORT = int(sys.argv[2])
	else:
		OSC_PORT = OSC_PORT_DEFAULT

	if len(sys.argv)>3:
		WIFI_INT = str(sys.argv[3])
	else:
		WIFI_INT = WIFI_INT_DEFAULT

	#creates directory to store sounds
	if not os.path.exists(sounddir):
		os.makedirs(sounddir)
	print("Sound directory: ",sounddir)

	#example of use of pyosc,
	#see: https://github.com/ptone/pyosc/blob/master/examples/knect-rcv.py
	#we use here the WiFi interface provided on device en0
	ipcmd = "ipconfig getifaddr %s"%WIFI_INT
	print(ipcmd)
	ipaddress = os.popen(ipcmd).read().rstrip()
	print("IP address: ",ipaddress)
	server = OSCServer((ipaddress, OSC_PORT))
	server.timeout = 0
	global run
	run = True

	print("Listening to OSC address",OSC_ADDRESS,"on port",OSC_PORT)

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

	server.addMsgHandler(OSC_ADDRESS, user_callback)

	#sound query engine
	try:
		while run:
			#sleep(1)
			#call user script
			each_frame(server)
	except KeyboardInterrupt: #to quit program
		print("\n")
		pass
	server.close()
Example #15
0
    class OscServerThread(Thread):
        def __init__(self, host, stopEvent):
            Thread.__init__(self)
            self.server = OSCServer(host)
            self.stopEvent = stopEvent

        def setCallBacks(self, callBacks):
            for callBack in callBacks:
                self.server.addMsgHandler(callBack[0], callBack[1])

        def run(self):
            while not self.stopEvent.is_set():
                self.server.handle_request()
            self.server.close()
Example #16
0
class OSC(threading.Thread):
    def __init__(self):

        global run
        threading.Thread.__init__(self)
        self.daemon = True

        self.server = OSCServer(("localhost", 15000))
        self.server.timeout = 0

        def handle_timeout(self):
            self.time_out = True

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

        def user_callback(path, tags, args, source):

            global RGB
            global BRIGHTNESS
            #print "here"
            RGB[0] = args[0]
            RGB[1] = args[1]
            RGB[2] = args[2]
            BRIGHTNESS = args[3]

        def quit_callback(path, tags, args, source):

            global run
            run = False

        self.server.addMsgHandler("/colors", user_callback)
        self.server.addMsgHandler("/quit", quit_callback)

    def each_frame(self):

        self.server.timed_out = False

        while not self.server.timed_out:
            self.server.handle_request()

    def run(self):

        global run

        while run:
            sleep(1)
            self.each_frame()
Example #17
0
File: app.py Project: ianisl/DOS
def app():
    global dxlIO, server, client
    ports = pypot.dynamixel.get_available_ports()
    if not ports:
        raise IOError('No port available.')
    dxlIO = pypot.dynamixel.DxlIO(ports[0])
    availableIDs = dxlIO.scan()
    server = OSCServer(('0.0.0.0', 8000))
    for motorID in availableIDs:
        server.addMsgHandler('/motor/' + str(motorID), motorHandler) # Register OSC handlers for each found ID
    client = OSCClient()
    client.connect(('localhost', 8001))
    print 'Ready. Found ID(s) ' + str(availableIDs)
    while True:
        server.handle_request()
        sleep(0.01)
Example #18
0
def main(opts):
    server = OSCServer((opts.ip_addres, int(opts.port)))
    server.handle_timeout = types.MethodType(handle_timeout, server)
    server.addMsgHandler("/user", user_callback)
    server.addMsgHandler("/quit", quit_callback)
    log_post('INFO: listening on to %s:%s' % (opts.ip_addres, opts.port))
    spinner_ = spinner()
    while run:
        each_frame(server)

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

    server.close()
Example #19
0
def main(hostname="localhost",port="8000"):
    server = OSCServer((hostname, int(port)))
    server.timeout = 0
    run = True
    global message_count
    message_count = 0

    # this method of reporting timeouts only works by convention
    # that before calling handle_request() field .timed_out is 
    # set to False
    def handle_timeout(self):
        self.timed_out = True

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

    def user_callback(path, tags, args, source):
        log("%s %s\n" % (path, args))
        global message_count
        message_count += 1

    def quit_callback(path, tags, args, source):
        #global run
        run = False

    server.addMsgHandler( "default", user_callback )
    server.addMsgHandler( "/quit", quit_callback )

    # user script that's called by the game engine every frame
    def each_frame():
        log("Messages received: %s\n" % message_count)
        # clear timed_out flag
        server.timed_out = False
        # handle all pending requests then return
        while not server.timed_out:
            server.handle_request()

    # simulate a "game engine"
    print "Server running at %s:%s" % (hostname, port)
    while run:
        # do the game stuff:
        sleep(1)
        # call user script
        each_frame()

    server.close()
Example #20
0
def main(hostname="localhost", port="8000"):
    server = OSCServer((hostname, int(port)))
    server.timeout = 0
    run = True
    global message_count
    message_count = 0

    # this method of reporting timeouts only works by convention
    # that before calling handle_request() field .timed_out is
    # set to False
    def handle_timeout(self):
        self.timed_out = True

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

    def user_callback(path, tags, args, source):
        log("%s %s\n" % (path, args))
        global message_count
        message_count += 1

    def quit_callback(path, tags, args, source):
        #global run
        run = False

    server.addMsgHandler("default", user_callback)
    server.addMsgHandler("/quit", quit_callback)

    # user script that's called by the game engine every frame
    def each_frame():
        log("Messages received: %s\n" % message_count)
        # clear timed_out flag
        server.timed_out = False
        # handle all pending requests then return
        while not server.timed_out:
            server.handle_request()

    # simulate a "game engine"
    print "Server running at %s:%s" % (hostname, port)
    while run:
        # do the game stuff:
        sleep(1)
        # call user script
        each_frame()

    server.close()
Example #21
0
class OSC_MPD(object):
    def __init__(self, osc=('0.0.0.0', 8000), mpd=('127.0.0.1', 6600)):
        self.mpc = MPDClient()
        self.mpc.connect(mpd[0], mpd[1])
        self.server = OSCServer(osc)

        def musicManage(addr, tags, data, client_address):
            cmd = addr.strip('/').split('/')[-1]
            self.mpc.__getattr__(cmd)(*data)

        self.server.addMsgHandler('/bearstech/music/play', musicManage)
        self.server.addMsgHandler('/bearstech/music/pause', musicManage)
        self.server.addMsgHandler('/bearstech/music/next', musicManage)
        self.server.addMsgHandler('/bearstech/music/previous', musicManage)
        self.server.addMsgHandler('/bearstech/music/stop', musicManage)

    def serve_forever(self):
        self.server.serve_forever()
Example #22
0
def server_start(port=7110):
    global server
    server = OSCServer(("localhost", 7110))
    server.timeout = 0

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

    server.addMsgHandler("/sco", handle_score)
    server.addMsgHandler("/cc", handle_cc)
    server.addMsgHandler("/quit", quit_callback)
    server.addMsgHandler("default", default_callback)
Example #23
0
def server_start(port=7110):
    global server
    server = OSCServer ( ("localhost", 7110))
    server.timeout = 0

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

    server.addMsgHandler("/sco", handle_score)
    server.addMsgHandler("/cc", handle_cc)
    server.addMsgHandler("/quit", quit_callback)
    server.addMsgHandler("default", default_callback)
Example #24
0
class OscServer:
    def __init__(self, port, cbks=None):
        self.server = OSCServer(("localhost", port))
        self.server.addDefaultHandlers()
        self.thread = threading.Thread(target=self.server.serve_forever)

        if cbks is not None:
            for path, cbk in cbks:
                self.on_msg(path, cbk)

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

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

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

        self.server.addMsgHandler(path, go)

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

    def close(self):
        self.server.close()
        try:
            self.thread.join()
        except:
            pass
        print "Done"
Example #25
0
class OscServer:
    def __init__(self, port, cbks = None):
        self.server = OSCServer( ("localhost", port) )
        self.server.addDefaultHandlers()
        self.thread = threading.Thread(target = self.server.serve_forever)

        if cbks is not None:
            for path, cbk in cbks:
                self.on_msg(path, cbk)

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

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

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

        self.server.addMsgHandler(path, go)

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

    def close(self):
        self.server.close()    
        try:
            self.thread.join()
        except:
            pass
        print "Done"
def setup():
    global lastTwitterCheck, myTwitterStream, streamThread
    global lastSmsCheck, mySmsClient, newestSmsSeconds
    global myOscSubscribers, myOscServer, oscThread, myOscClient
    global logFile
    secrets = {}
    myOscSubscribers = {}
    lastTwitterCheck = time()
    lastSmsCheck = time()
    newestSmsSeconds = timegm(gmtime())

    ## read secrets from file
    inFile = open('oauth.txt', 'r')
    for line in inFile:
        (k, v) = line.split()
        secrets[k] = v

    ## start Twitter stream reader
    myTwitterStream = TwitterStreamReceiver(
        app_key=secrets['CONSUMER_KEY'],
        app_secret=secrets['CONSUMER_SECRET'],
        oauth_token=secrets['ACCESS_TOKEN'],
        oauth_token_secret=secrets['ACCESS_SECRET'])
    streamThread = Thread(target=myTwitterStream.statuses.filter,
                          kwargs={'track': ','.join(SEARCH_TERMS)})
    streamThread.start()

    ## start Twilio client
    mySmsClient = TwilioRestClient(account=secrets['ACCOUNT_SID'],
                                   token=secrets['AUTH_TOKEN'])

    myOscClient = OSCClient()
    myOscServer = OSCServer(('127.0.0.1', 8888))
    myOscServer.addMsgHandler('/NotTooPublic/call', oscSubscribeHandler)
    myOscServer.addMsgHandler('default', lambda addr, tags, args, source: None)
    oscThread = Thread(target=myOscServer.serve_forever)
    oscThread.start()

    ## open new file for writing log
    logFile = open("data/" + strftime("%Y%m%d-%H%M%S", localtime()) + ".log",
                   "a")
Example #27
0
class OSCForwarder(threading.Thread):
   def __init__(self, from_ip, from_port, to_ip, to_port):
      super(OSCForwarder, self).__init__()

      # create the server to listen to messages arriving at from_ip
      self.server = OSCServer( (from_ip, from_port) )
      self.server.addMsgHandler( 'default', self.callback )

      # create the clieent to forward those message to to_ip
      self.client = OSCClient()
      self.client.connect( (to_ip, to_port) )

      print '%s:%d --> %s:%d' % (from_ip, from_port, to_ip, to_port)

      self.done_running = False

      # start the server listening for messages
      self.start()

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

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

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


   def callback(self, path, tags, args, source):
      #print 'got:', path, args, 'from:', source
      self.client.send( OSCMessage(path, args ) )
Example #28
0
class OSCForwarder(threading.Thread):
   def __init__(self, from_ip, from_port, to_ip, to_port):
      super(OSCForwarder, self).__init__()

      # create the server to listen to messages arriving at from_ip
      self.server = OSCServer( (from_ip, from_port) )
      self.server.addMsgHandler( 'default', self.callback )

      # create the clieent to forward those message to to_ip
      self.client = OSCClient()
      self.client.connect( (to_ip, to_port) )

      print '%s:%d --> %s:%d' % (from_ip, from_port, to_ip, to_port)

      self.done_running = False

      # start the server listening for messages
      self.start()

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

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

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


   def callback(self, path, tags, args, source):
      #print 'got:', path, args, 'from:', source
      self.client.send( OSCMessage(path, args ) )
Example #29
0
def setup():
    global lastTwitterCheck, myTwitterStream, streamThread
    global lastSmsCheck, mySmsClient, newestSmsSeconds
    global myOscSubscribers, myOscServer, oscThread, myOscClient
    global logFile
    secrets = {}
    myOscSubscribers = {}
    lastTwitterCheck = time()
    lastSmsCheck = time()
    newestSmsSeconds = timegm(gmtime())

    ## read secrets from file
    inFile = open('oauth.txt', 'r')
    for line in inFile:
        (k,v) = line.split()
        secrets[k] = v

    ## start Twitter stream reader
    myTwitterStream = TwitterStreamReceiver(app_key = secrets['CONSUMER_KEY'],
                                            app_secret = secrets['CONSUMER_SECRET'],
                                            oauth_token = secrets['ACCESS_TOKEN'],
                                            oauth_token_secret = secrets['ACCESS_SECRET'])
    streamThread = Thread(target=myTwitterStream.statuses.filter, kwargs={'track':','.join(SEARCH_TERMS)})
    streamThread.start()

    ## start Twilio client
    mySmsClient = TwilioRestClient(account=secrets['ACCOUNT_SID'],
                                   token=secrets['AUTH_TOKEN'])

    myOscClient = OSCClient()
    myOscServer = OSCServer(('127.0.0.1', 8888))
    myOscServer.addMsgHandler('/NotTooPublic/call', oscSubscribeHandler)
    myOscServer.addMsgHandler('default', lambda addr, tags, args, source:None)
    oscThread = Thread(target=myOscServer.serve_forever)
    oscThread.start()

    ## open new file for writing log
    logFile = open("data/"+strftime("%Y%m%d-%H%M%S", localtime())+".log", "a")
Example #30
0
def main():
    #incoming(HOST,PORT)
    server = OSCServer(('127.0.0.1',42003))
    client = OSC.OSCClient()
    client.connect(('127.0.0.1',42002))

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

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

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

    server.close()
def main():

    print("Pixel Display python side")

    sender = DisplayDataSender.DisplayDataSender("192.168.1.110", 4210)

    osc_server = OSCServer(("0.0.0.0", 8888))
    #server.addMsgHandler("/1/xy1", push_xy_callback)
    osc_server.addMsgHandler("/1/xy1", sender.slider)

    osc_server.handle_error = types.MethodType(handle_error, osc_server)

    #sender.send_command(mt.DisplayEnums.Command.CONFIGURE_WIFI)
    #sender.send_command(mt.DisplayEnums.Command.RESET_WIFI)
    sender.set_effect(mt.DisplayEnums.Effect.NONE)
    #sender.set_effect(mt.DisplayEnums.Effect.FADE)

    #return

    #while True:
    #    osc_server.handle_request()

    #sender.update()

    print("moving forward with walking pixel")

    while True:
        sender.walk_pixel()
        sleep(0.03)

    sender.clear()

    #for i in range(0, 3):
    #    sender.sendDisplayUpdate()
    #    sleep(5)

    server.close
Example #32
0
def setup():
    global currentButtonState, lastDownTime, isRecording, audioInput
    global messageQ, clientMap, oscIn, oscOut, oscThread
    messageQ = PriorityQueue()
    clientMap = {}

    ## setup osc client
    oscOut = OSCClient()

    ## setup osc receiver
    oscIn = OSCServer((OSC_IN_ADDRESS, OSC_IN_PORT))
    oscIn.addMsgHandler('default', _oscHandler)
    oscThread = Thread(target=oscIn.serve_forever)
    oscThread.start()
    print "osc in ready"

    ## setup gpio
    GPIO.setup(SWITCH_PIN, GPIO.IN)
    GPIO.setup(LED_PIN, GPIO.OUT)
    GPIO.output(LED_PIN, GPIO.LOW)
    currentButtonState = GPIO.input(SWITCH_PIN)
    lastDownTime = 0
    isRecording = False

    ## setup audio
    audioInput = None
    try:
        audioInput = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL,
                                   "default:Headset")
        audioInput.setchannels(1)
        audioInput.setrate(44100)
        audioInput.setformat(alsaaudio.PCM_FORMAT_S16_LE)
        audioInput.setperiodsize(256)
    except:
        print "couldn't start audio device"
        audioInput = None
class ServerLighthouse(object):

    def __init__(self, address='192.168.1.145', recvPort=recvPort):

        self.address = address
        self.recvPort = recvPort

        # Setup a reciever for OSC.
        self.server = OSCServer((self.address, self.recvPort))
        self.server.timeout = 0
        self.server.handleTimeout = types.MethodType(self.handleTimeout, self.server)

        # Startup light
        self.intitializeLight()

    def handleTimeout(self):
        self.timedOut = True

    def eachFrame(self):
        # clear timed_out flag
        self.server.timed_out = False

        # handle all pending requests then return
        while not self.server.timed_out:
            self.server.handle_request()

    def handleEvent(self, address, functionToCall):
        def internalFunction(path, tags, args, source):
            arg = int(args[0])
            functionToCall(arg)

        def internalFunctionZ(path, tags, args, source):
            pass

        self.server.addMsgHandler(address, internalFunction)
        self.server.addMsgHandler('%s/z' % address, internalFunctionZ)
Example #34
0
class OSCPlotter(object):

    """Set up OSC server and other handlers."""

    def __init__(self, port, scope):
        host="localhost"
        logger.info( "Initializing server at %s:%d"%(host,port))
        try:
            self.m_oscserver = OSCServer( (host, port) )
        except:
            logger.fatal("System:Unable to create OSC handler at %s:%d"%(host,port),exc_info=True)
            sys.exit(1)
        self.m_oscserver.timeout = 0
        self.m_oscserver.print_tracebacks = True
        self.m_scope = scope
        self.m_fnum = 0
        
        # add a method to an instance of the class
        self.m_oscserver.handle_timeout = types.MethodType(handle_timeout,self.m_oscserver)

        # this registers a 'default' handler (for unmatched messages), 
        # an /'error' handler, an '/info' handler.
        # And, if the client supports it, a '/subscribe' &
        # '/unsubscribe' handler
        self.m_oscserver.addDefaultHandlers()
        self.m_oscserver.addMsgHandler("default", self.default_handler)
        self.m_oscserver.addMsgHandler("/pf/frame", self.pf_frame)
#        self.m_oscserver.addMsgHandler("/pf/update", self.pf_update)
        self.m_oscserver.addMsgHandler("/conductor/attr", self.cond_attr)

    def handle(self):
        self.m_oscserver.handle_request()

    def cond_attr(self, path, tags, args, source):
        attr=args[0]
        uid=args[1]
        value=args[2]
        logger.info("%d.%s=%f"%(uid,attr,value))
        if attr=="kinetic":
            self.m_scope.append(uid,self.m_fnum,value)
            
    def pf_update(self, path, tags, args, source):
        t=args[1]
        uid=args[2]
        x=args[3]
        logger.debug("uid=%d,t=%f, x=%f"%(uid,t,x))
#        self.m_scope.append(uid,t,x)

    def pf_frame(self, path, tags, args, source):
        self.m_fnum=args[0]
        if self.m_fnum%5==0:
            self.m_scope.update(self.m_fnum)
        
    def default_handler(self, path, tags, args, source):
#        logger.debug("got message for "+path+" with tags "+tags)
        return None
Example #35
0
def frame(savePath):
    print 'getting osc'
    # funny python's way to add a method to an instance of a class
    server = OSCServer(("192.168.1.209", 12000))
    server.timeout = 0
    run = True
    server.handle_timeout = types.MethodType(handle_timeout, server)
    server.addMsgHandler("/acc", acc_callback)
    server.addMsgHandler("/e", eul_callback)
    server.addMsgHandler("/raw", raw_callback)
    while True:
        each_frame(server)
        #print 'hello'
        sleep(0.001)
    return
Example #36
0
    lj.SendLJ("/forwardui", "aurora/rotdirec Y " + str(LAY['Yrotdirec']))
    lj.SendLJ("/forwardui", "aurora/rotdirec Z " + str(LAY['Zrotdirec']))

    lj.SendLJ("/forwardui", "aurora/steps " + str(LAY['steps']))
    lj.SendLJ("/forwardui", "aurora/stepmax " + str(LAY['stepmax']))
    lj.SendLJ("/forwardui", "aurora/linesize " + str(LAY['lineSize']))
    lj.SendLJ("/forwardui", "aurora/radius " + str(LAY['radius']))


prepareStarfield()
prepareTrckr()

log.info("Starting OSC server at " + str(gstt.myIP) + " port " +
         str(OSCinPort) + " ...")
#print("TouchOSC", gstt.TouchOSCIP)
oscserver.addMsgHandler("/aurora/ljscene", OSCljscene)

oscserver.addMsgHandler("/aurora/noteon", OSCnoteon)
oscserver.addMsgHandler("/aurora/fx", OSCfx)
oscserver.addMsgHandler("/aurora/noteoff", OSCnoteoff)
#oscserver.addMsgHandler("/aurora/color", OSColor)
oscserver.addMsgHandler("/aurora/bpm", OSCbpm)
oscserver.addMsgHandler("/aurora/clock", OSClock)
oscserver.addMsgHandler("/aurora/start", OSCstart)
oscserver.addMsgHandler("/aurora/stop", OSCstop)
oscserver.addMsgHandler("/aurora/part", OSCpart)

oscserver.addMsgHandler("/aurora/steps", OSCsteps)
oscserver.addMsgHandler("/aurora/stepmax", OSCstepmax)

oscserver.addMsgHandler("/aurora/rawcc", OSCrawcc)
Example #37
0
	for channel in range (21,30):
		vrand=random.randint(0,255)
		senddmx(channel,vrand)

	for channel in range (41,44):
		vrand=random.randint(0,255)
		senddmx(channel,vrand)

# Send text to status display widget
def nozstatus(path, tags, args, source):
    sendosc("/nozoid/status", args[0])

# registering all OSC message handlers

oscserver.addMsgHandler( "/nozoid/on", nozon )
oscserver.addMsgHandler( "/nozoid/stop", nozstop )
oscserver.addMsgHandler( "default", nozhandler )
oscserver.addMsgHandler( "/nozoid/name", nozname )
oscserver.addMsgHandler( "/nozoid/lfo", nozlfo )

oscserver.addMsgHandler( "/nozoid/osc", nozosc )

oscserver.addMsgHandler( "/nozoid/vco", nozvco )
oscserver.addMsgHandler( "/nozoid/mix", nozmix )
oscserver.addMsgHandler( "/nozoid/up", nozup )
oscserver.addMsgHandler( "/nozoid/down", nozdown )
oscserver.addMsgHandler( "/nozoid/knob", nozknob )
oscserver.addMsgHandler( "/nozoid/status", nozstatus )

oscserver.addMsgHandler( "/nozoid/X", nozX )
Example #38
0
from OSC import OSCServer
import sys
from time import sleep

server = OSCServer( ("localhost", 7110) )
server.timeout = 0
run = True

def user_callback(path, tags, args, source):
    # which user will be determined by path:
    # we just throw away all slashes and join together what's left
    user = ''.join(path.split("/"))
    # tags will contain 'fff'
    # args is a OSCMessage with data
    # source is where the message came from (in case you need to reply)
    print user, args, source 
    
for i in range(2):
    for c in range(1,5):
        server.addMsgHandler( "/EEG_%d/channel_%d/notch_50/lpf_75"%(i,c), user_callback )
    server.addMsgHandler( "/markers" , user_callback )    
server.serve_forever()
Example #39
0
class Kinect:
    """Manages connection to Kinect, and saves and processes coordinates"""
    @staticmethod
    def retrieve(joints=None, max_port=5555):
        """ Retrieves a singleton Kinect instance, and creates it if it doesn't exist. """
        global kinect_instance
        if kinect_instance is None:
            kinect_instance = Kinect(joints, max_port)
        return kinect_instance

    def __init__(self, joints=None, max_port=5555):
        if joints is None:
            self.joints = [
                'righthand', 'lefthand', 'rightfoot', 'leftfoot', 'head',
                'torso'
            ]
        else:
            self.joints = joints

        self.coords = {k: (0., 0., 0.) for k in self.joints}
        self.prev_coords = {k: (0., 0., 0.) for k in self.joints}
        self.joint_speed = {k: False for k in self.joints}
        self.speed_piano = {
            'lefthand': {
                X: 0,
                Y: 0
            },
            'righthand': {
                X: 0,
                Y: 0
            }
        }
        self.kinect_client = OSCClient()
        self.max_client = OSCClient()
        self.server = OSCServer(('127.0.0.1', 12345))
        self.kinect_client.connect(('127.0.0.1', 12346))
        self.max_client.connect(('127.0.0.1', max_port))
        self.server.addMsgHandler('default', self.process_message)

        self.flipped = False
        self.speed = 0.
        self.speed_ramp = 0.

        sprout(self.server.serve_forever)
        sprout(self._remind_synapse)
        #sprout(self._calc_speed)

    def __enter__(self):
        return self

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

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

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

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

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

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

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

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

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

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

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

        return self.coords[hand][X]

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

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

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

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

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

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

    @staticmethod
    def _sendMsg(client, address, items):
        m = OSCMessage()
        m.setAddress(address)
        m.append(items)
        client.send(m)
Example #40
0
class OSCHandler(object):

    """Set up OSC server and other handlers."""

    def __init__(self, field):
        self.m_field = field
        self.m_server = OSCServer( (OSCHOST, OSCPORT) )
        self.m_server.timeout = OSCTIMEOUT
        self.m_run = True

        self.m_xmin = 0
        self.m_ymin = 0
        self.m_xmax = 0
        self.m_ymax = 0

        self.eventfunc = {
            'ping': self.event_tracking_ping,
            'ack': self.event_tracking_ack,
            'start': self.event_tracking_start,
            'entry': self.event_tracking_entry,
            'exit': self.event_tracking_exit,
            'frame': self.event_tracking_frame,
            'stop': self.event_tracking_stop,
            'minx': self.event_tracking_set,
            'miny': self.event_tracking_set,
            'maxx': self.event_tracking_set,
            'maxy': self.event_tracking_set,
            'npeople': self.event_tracking_set,
            'groupdist': self.event_tracking_set,
            'ungroupdist': self.event_tracking_set,
            'fps': self.event_tracking_set,
            'update': self.event_tracking_update,
            'leg': self.event_tracking_leg,
            'body': self.event_tracking_body,
        }

        # add a method to an instance of the class
        self.m_server.handle_timeout = types.MethodType(handle_timeout, self.m_server)

        for i in self.eventfunc:
            self.m_server.addMsgHandler(OSCPATH[i], self.eventfunc[i])

        # this registers a 'default' handler (for unmatched messages), 
        # an /'error' handler, an '/info' handler.
        # And, if the client supports it, a '/subscribe' &
        # '/unsubscribe' handler
        self.m_server.addDefaultHandlers()
        self.m_server.addMsgHandler("default", self.default_handler)
        # TODO: Handle errors from OSCServer
        #self.m_server.addErrorHandlers()
        #self.m_server.addMsgHandler("error", self.default_handler)
        self.honey_im_home()

    def honey_im_home(self):
        """Broadcast a hello message to the network."""
        # TODO: Broadcast hello message
        return True

    def each_frame(self):
        # clear timed_out flag
        self.m_server.timed_out = False
        # handle all pending requests then return
        while not self.m_server.timed_out:
            self.m_server.handle_request()

    def user_callback(self, path, tags, args, source):
        # which user will be determined by path:
        # we just throw away all slashes and join together what's left
        user = ''.join(path.split("/"))
        # tags will contain 'fff'
        # args is a OSCMessage with data
        # source is where the message came from (in case you need to reply)
        if dbug.LEV & dbug.MSGS: print ("Now do something with", user,args[2],args[0],1-args[1]) 

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

    # Event handlers

    def default_handler(self, path, tags, args, source):
        if dbug.LEV & dbug.MORE: print "OSC:default_handler:No handler registered for ", path
        return None

    def event_tracking_ping(self, path, tags, args, source):
        if dbug.LEV & dbug.MSGS: print "OSC:event_ping:code",args[0]
        return None

    def event_tracking_ack(self, path, tags, args, source):
        if dbug.LEV & dbug.MSGS: print "OSC:event_ack:code",args[0]
        return None

    def event_tracking_start(self, path, tags, args, source):
        """Tracking system is starting.

        Sent before first /pf/update message for that target
        args:
            [ aparently no params now]
            samp - sample number
            t - time of sample (elapsed time in seconds since beginning of run)
            target - UID of target
            channel - channel number assigned

        """
        #samp = args[0]
        if dbug.LEV & dbug.MSGS: print "OSC:event_start"

    def event_tracking_set(self, path, tags, args, source):
        """Tracking subsystem is setting params.

        Send value of various parameters.
        args:
            minx, miny, maxx, maxy - bounds of PF in units
            npeople - number of people currently present

        """
        if dbug.LEV & dbug.MSGS: print "OSC:event_set:",path,args,source
        if path == OSCPATH['minx']:
            self.m_xmin = int(100*args[0])
            if dbug.LEV & dbug.MSGS: print "OSC:event_set:set_scaling(",\
                    (self.m_xmin,self.m_ymin),",",(self.m_xmax,self.m_ymax),")"
            # we might not have everything yet, but we udate with what we have
            self.m_field.set_scaling(pmin_field=(self.m_xmin,self.m_field.m_ymin_field))
        elif path == OSCPATH['miny']:
            self.m_ymin = int(100*args[0])
            if dbug.LEV & dbug.MSGS: print "OSC:event_set:set_scaling(",\
                    (self.m_xmin,self.m_ymin),",",(self.m_xmax,self.m_ymax),")"
            # we might not have everything yet, but we udate with what we have
            self.m_field.set_scaling(pmin_field=(self.m_field.m_xmin_field,self.m_ymin))
        elif path == OSCPATH['maxx']:
            self.m_xmax = int(100*args[0])
            if dbug.LEV & dbug.MSGS: print "OSC:event_set:set_scaling(",\
                    (self.m_xmin,self.m_ymin),",",(self.m_xmax,self.m_ymax),")"
            # we might not have everything yet, but we udate with what we have
            self.m_field.set_scaling(pmax_field=(self.m_xmax,self.m_field.m_ymax_field))
        elif path == OSCPATH['maxy']:
            self.m_ymax = int(100*args[0])
            if dbug.LEV & dbug.MSGS: print "OSC:event_set:set_scaling(",\
                    (self.m_xmin,self.m_ymin),",",(self.m_xmax,self.m_ymax),")"
            # we might not have everything yet, but we udate with what we have
            self.m_field.set_scaling(pmax_field=(self.m_field.m_xmax_field,self.m_ymax))
        elif path == OSCPATH['npeople']:
            self.m_field.check_people_count(args[0])
            return
        elif path == OSCPATH['groupdist']:
            self.m_field.update(groupdist=args[0])
            return
        elif path == OSCPATH['ungroupdist']:
            self.m_field.update(ungroupdist=args[0])
            return
        elif path == OSCPATH['fps']:
            self.m_field.update(oscfps=args[0])
            return
        #if self.m_xmin and self.m_ymin and self.m_xmax and self.m_ymax:
            #print "set_scaling(",(self.m_xmin,self.m_ymin),",",(self.m_xmax,self.m_ymax),")"
            #self.m_field.set_scaling((self.m_xmin,self.m_ymin),(self.m_xmax,self.m_ymax))
            #self.m_field.updateScreen()
            

    def event_tracking_entry(self, path, tags, args, source):
        """Event when person enters field.

        Sent before first /pf/update message for that target
        args:
            samp - sample number
            t - time of sample (elapsed time in seconds since
            beginning of run)
            target - UID of target
            channel - channel number assigned

        """
        #print "OSC:event_entry:",path,args,source
        #print "args:",args,args[0],args[1],args[2]
        samp = args[0]
        time = args[1]
        id = args[2]
        if dbug.LEV & dbug.MSGS: print "OSC:event_entry:cell:",id
        self.m_field.create_cell(id)

    def event_tracking_exit(self, path, tags, args, source):
        """Event when person exits field.

        args:
             samp - sample number
             t - time of sample (elapsed time in seconds since beginning of run)
             target - UID of target

        """
        #print "OSC:event_exit:",path,args,source
        samp = args[0]
        time = args[1]
        id = args[2]
        if dbug.LEV & dbug.MSGS: print "OSC:event_exit:cell:",id
        #print "BEFORE: cells:",self.m_field.m_cell_dict
        #print "BEFORE: conx:",self.m_field.m_connector_dict
        self.m_field.del_cell(id)
        #print "AFTER: cells:",self.m_field.m_cell_dict
        #print "AFTER: conx:",self.m_field.m_connector_dict

    def event_tracking_body(self, path, tags, args, source):
        """Information about people's movement within field.

        Update position of target.
        args:
            samp - sample number 
            target - UID of target
            x,y - position of person within field in m
            ex,ey - standard error of measurement (SEM) of position, in meters 
            spd, heading - estimate of speed of person in m/s, heading in degrees
            espd, eheading - SEM of spd, heading
            facing - direction person is facing in degees
            efacing - SEM of facing direction
            diam - estimated mean diameter of legs
            sigmadiam - estimated sigma (sqrt(variance)) of diameter
            sep - estimated mean separation of legs
            sigmasep - estimated sigma (sqrt(variance)) of sep
            leftness - measure of how likely leg 0 is the left leg
            visibility - number of frames since a fix was found for either leg
        """
        for index, item in enumerate(args):
            if item == 'nan':
                args[index] = 0
        samp = args[0]
        id = args[1]
        x = int(100*args[2])       # comes in meters, convert to cm
        y = int(100*args[3])
        ex = int(100*args[4])
        ey = int(100*args[5])
        spd = int(100*args[6])
        heading = args[7]
        espd = int(100*args[8])
        eheading = args[9]
        facing = args[10]
        efacing = args[11]
        diam = int(100*args[12])
        sigmadiam = int(100*args[13])
        sep = int(100*args[14])
        sigmasep = int(100*args[15])
        leftness = args[16]
        vis = args[17]
        if id not in self.m_field.m_cell_dict:
            if dbug.LEV & dbug.MSGS: print "OSC:event_body:no id",id,"in registered id list"
        if samp%FREQ_REG_REPORT == 0:
            if dbug.LEV & dbug.MSGS: print "    OSC:event_body:id:",id,"pos:",(x,y)
        self.m_field.update_body(id, x, y, ex, ey, spd, espd, facing, efacing, 
                           diam, sigmadiam, sep, sigmasep, leftness, vis)

    def event_tracking_leg(self, path, tags, args, source):
        """Information about individual leg movement within field.

        Update position of leg.
        args:
            samp - sample number 
            id - UID of target
            leg - leg number (0..nlegs-1)
            nlegs - number of legs target is modeled with 
            x,y - position within field in m
            ex,ey - standard error of measurement (SEM) of position, in meters 
            spd, heading - estimate of speed of leg in m/s, heading in degrees
            espd, eheading - SEM of spd, heading
            visibility - number of frames since a positive fix
        """
        for index, item in enumerate(args):
            if item == 'nan':
                args[index] = 0
        samp = args[0]
        id = args[1]
        leg = args[2]
        nlegs = args[3]
        x = int(100*args[4])       # comes in meters, convert to cm
        y = int(100*args[5])
        ex = int(100*args[6])
        ey = int(100*args[7])
        spd = int(100*args[8])
        heading = args[9]
        espd = int(100*args[10])
        eheading = args[11]
        vis = args[12]
        if id not in self.m_field.m_cell_dict:
            if dbug.LEV & dbug.MSGS: print "OSC:event_leg:no id",id,"in registered id list"
        if samp%FREQ_REG_REPORT == 0:
            if dbug.LEV & dbug.MSGS: print "    OSC:event_leg:id:",id,"leg:",leg,"pos:",(x,y)
        self.m_field.update_leg(id, leg, nlegs, x, y, ex, ey, spd, espd, 
                                   heading, eheading, vis)

    def event_tracking_update(self, path, tags, args, source):
        """Information about people's movement within field.

        Update position of target.
        args:
            samp - sample number
            t - time of sample (elapsed time in seconds since beginning of run)
            target - UID of target
            x,y - position within field in units - increasing in value towards right and down
            vx,vy - estimate of velocity in m/s
            major,minor - major/minor axis size in m
            groupid - id number of group
            groupsize - number of people in group
            channel - channel number assigned
        """
        for index, item in enumerate(args):
            if item == 'nan':
                args[index] = 0
        samp = args[0]
        time = args[1]
        id = args[2]
        if id not in self.m_field.m_cell_dict:
            if dbug.LEV & dbug.MSGS: print "OSC:event_update:no id",id,"in registered id list"
        x = int(100*args[3])       # comes in meters, convert to cm
        y = int(100*args[4])
        vx = int(100*args[5])
        vy = int(100*args[6])
        major = int(100*args[7]/2)
        minor = int(100*args[8]/2)
        gid = args[9]
        gsize = args[10]
        channel = args[11]
        #print "OSC:event_update:",path,args,source
        if samp%FREQ_REG_REPORT == 0:
            #print "OSC:event_update:",path,args,source
            if dbug.LEV & dbug.MSGS: print "    OSC:event_update:id:",id,"pos:",(x,y),"axis:",major
        #print "field.update_cell(",id,",",(x,y),",",major,")"
        self.m_field.update_cell(id,(x,y),major)
        #print "OSC:event_update: Done"

    def event_tracking_frame(self, path, tags, args, source):
        """New frame event.

        args:
            samp - sample number

        """
        #print "OSC:event_frame:",path,args,source
        samp = args[0]
        if samp%FREQ_REG_REPORT == 0:
            #print "OSC:event_update:",path,args,source
            if dbug.LEV & dbug.MSGS: print "    OSC:event_frame::",samp
        return None

    def event_tracking_stop(self, path, tags, args, source):
        """Tracking has stopped."""
        if dbug.LEV & dbug.MSGS: print "OSC:event_stop:",path,args,source
        return None
    # tags will contain 'fff'
    # args is a OSCMessage with data
    # source is where the message came from (in case you need to reply)
    # print ("Now do something with", user,args[2],args[0],1-args[1]) 

    if args[0] == 1.0:
    	active3 = True;
    else:
    	active3 = False;

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

server.addMsgHandler( "/1/push1", user_callback1 )
server.addMsgHandler( "/1/push2", user_callback2 )
server.addMsgHandler( "/1/push3", user_callback3 )

# user script that's called by the game engine every frame
def each_frame():
    global time1, timer1, time2, timer2, time3, timer3
    # clear timed_out flag
    server.timed_out = False
    # handle all pending requests then return
    while not server.timed_out:
        server.handle_request()

# simulate a "game engine"
while run:
Example #42
0
    # Process arguments
    parser = argparse.ArgumentParser()
    parser.add_argument('-c',
                        '--clear',
                        action='store_true',
                        help='clear the display on exit')
    parser.add_argument("--ip",
                        default="127.0.0.1",
                        help="The ip to listen on")
    parser.add_argument("--port",
                        type=int,
                        default=5005,
                        help="The port to listen on")
    args = parser.parse_args()
    server = OSCServer(("localhost", 5006))
    server.addMsgHandler("/pathraspeak", handle_speak)
    server.addMsgHandler("/unknown", handle_unknown)
    server.addMsgHandler("/awoken", handle_listening_start)
    server.timeout = 0
    run = True

    # Create NeoPixel object with appropriate configuration.
    strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA,
                              LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
    # Intialize the library (must be called once before other functions).
    strip.begin()
    colorWipe(strip, Color(0, 0, 0), 10)

    print('Press Ctrl-C to quit.')
    if not args.clear:
        print('Use "-c" argument to clear LEDs on exit')
Example #43
0
            powerLed.changeState('off')
            keyLed.changeState('off')
            numLed.changeState('off')
            buttonLed.changeState('off')
            print("reset game postion: {}".format(gamePosition))
        except Exception as e:
            print('that didna work')
            print(e)
    print(path, tags, args, source)


def nothing(*args):
    pass


server.addMsgHandler("/yes/please", cb)
server.addMsgHandler("/yes/no", nothing)


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


def run():
    sleep(1)
    each_frame()


t = mp.Process(target=run, args=())

import types
server.handle_timeout = types.MethodType(handle_timeout, server)


def servo_callback(path, tags, args, source):
    goto(args[0], args[1])


def quit_callback(path, tags, args, source):
    global run
    run = False


server.addMsgHandler("/servo", servo_callback)
server.addMsgHandler("/quit", quit_callback)


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


try:
    while run:
        time.sleep(0.3)
        each_frame()
        try:
            client.send(OSCMessage("/angle", [args.identifier, int(angle), 0]))
Example #45
0
def push1_callback(path, tags, args, source):
    if path=="/pattern/1":
        L1(args[0])

def push2_callback(path, tags, args, source):
    if path=="/pattern/2":
        L2(args[0])

def push3_callback(path, tags, args, source):
    if path=="/pattern/3":
        L3(args[0])

def push4_callback(path, tags, args, source):
    if path=="/pattern/4":
        L4(args[0])

def handle_error(self,request,client_address):
    pass

server.addMsgHandler( "/pattern/1",push1_callback)
server.addMsgHandler( "/pattern/2",push2_callback)
server.addMsgHandler( "/pattern/3",push3_callback)
server.addMsgHandler( "/pattern/4",push4_callback)


server.handle_error = types.MethodType(handle_error, server)

while True:
	server.handle_request()

server.close()
Example #46
0
	print "Btn: ",state
	if state == 1:
		pwm.setPWM(0,0,0)
		pwm.setPWM(1,0,0)
		pwm.setPWM(2,0,0)

def printer(addr, tags, stuff, source):
   	print "---"
    	print "received new osc msg from %s" % OSC.getUrlStr(source)
    	print "with addr : %s" % addr
    	print "typetags %s" % tags
    	print "data %s" % stuff
    	print "---"

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

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

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

try:
	while 1:
		#print "Waiting..."
# OSC Communication
# - receiving OSC Messages in Python

from OSC import OSCServer
import time, threading 

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

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

oscServer.addMsgHandler("/oscTest", oscTestHandler)

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

try : 
     while 1 : 
         time.sleep(5) 

except KeyboardInterrupt : 
     print "\nClosing OSCServer." 
     oscServer.close() 
     print "Waiting for Server-thread to finish" 
     oscServerThread.join()
     print "Done"
    global uniqueSound
    uniqueSound.stop()
    uniqueSound = pygame.mixer.Sound(args[0])
    uniqueSound.set_volume(0)
    uniqueSound.play(-1)


def setTargetIP_callback(path, tags, args, source):
    user = ''.join(path.split("/"))
    print("We received", user, args[0])
    columnClient.close()
    clientAddress = args[0], 9999
    columnClient.connect(clientAddress)


columnServer.addMsgHandler("/led", led_callback)
columnServer.addMsgHandler("/quit", quit_callback)
columnServer.addMsgHandler("/volume", volume_callback)
columnServer.addMsgHandler("/soundfile", soundfile_callback)
columnServer.addMsgHandler("/sendTo", setTargetIP_callback)


def eventListener():
    #clear time_out flag
    columnServer.timed_out = False
    # handle all pending requests then return
    while not columnServer.timed_out:
        columnServer.handle_request()


def godListener():
Example #49
0
    g = args[1]
    b = args[2]
    for i in range(3, len(args)):
        index = args[i]
        led.setRGB(index, r, g, b)


def update(path, tags, args, source):
    led.update()


def allOff(path, tags, args, source):
    led.all_off()


server.addMsgHandler("/allOff", allOff)
server.addMsgHandler("/update", update)
server.addMsgHandler("/singleLED", singleLED)
server.addMsgHandler("/multipleLED", multipleLED)
server.addMsgHandler("/fillRGB", fillRGB)


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


while run:
    sleep(1)
    each_frame()
Example #50
0
    print "Hold it there motor man!"
    ser.write('0')


def motor_callback(path, tags, args, source):
    state = args[0]
    print state
    if path == "/lmcp/motor":
        if state == '1':
            motorGo(1)
        elif state == '2':
            motorGo(2)
        else:
            motorStop()


def handle_error(self, request, client_address):
    pass


server.addMsgHandler("/lmcp/motor", motor_callback)

server.handle_error = types.MethodType(handle_error, server)

server.timed_out = False

while not server.timed_out:
    server.handle_request()

server.close()
Example #51
0
	
	# if needed a loop back : WS Client -> server -> WS Client
	#sendWSall("ws"+message)


def handle_timeout(self):
	self.timed_out = True


def sendWSall(message):
	if debug >0:
		print("WS sending %s" % (message))
	server.send_message_to_all(message)
	
	
# Launch OSC thread listening to Bhorosc
thread.start_new_thread(osc_thread, ())

# Default OSC handler for all incoming message from Bhorosc
oscserver.addMsgHandler("default", handler)

# Websocket startup
print "ws Server at :", serverIP, "port :",wsPORT

server = WebsocketServer(wsPORT,host=serverIP)
#print server
server.set_fn_new_client(new_client)
server.set_fn_client_left(client_left)
server.set_fn_message_received(message_received)
server.run_forever()
Example #52
0
def siren_callback(path, tags, args, source):
    user = ''.join(path.split("/"))
    pin = 12
    FuncThread(note, args[0], pin).start()


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

def dummy_callback(path, tags, args, source):
    pass

server.addMsgHandler( "/drums/1", dummy_callback )
server.addMsgHandler( "/sunguitar/1", sunguitar_callback )
server.addMsgHandler( "/siren/1", dummy_callback)
server.addMsgHandler( "/tubulum/1", dummy_callback)
server.addMsgHandler( "/racketguitar/1", dummy_callback)
server.addMsgHandler( "/quit", quit_callback )

# user script that's called by the game engine every frame
def each_frame():
    # clear timed_out flag
    server.timed_out = False
    # handle all pending requests then return
    while not server.timed_out:
        server.handle_request()

# simulate a "game engine"
Example #53
0
# funny python's way to add a method to an instance of a class
import types
server.handle_timeout = types.MethodType(handle_timeout, server)


def user_callback(path, tags, args, source):
    # which user will be determined by path:
    # we just throw away all slashes and join together what's left
    #print "hello"
    msg = args[0]
    print msg
    outlet.push_sample([str(msg)])


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


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


# user script that's called by the game engine every frame
def each_frame():
    # clear timed_out flag
    server.timed_out = False
    # handle all pending requests then return
    while not server.timed_out:
        server.handle_request()
Example #54
0
    user = ''.join(path.split("/"))
    # tags will contain 'fff'
    # args is a OSCMessage with data
    # source is where the message came from (in case you need to reply)
    
   

    FuncThread(note, GPIO, args).start()
    

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

server.addMsgHandler( "/tubulum/1", user_callback )
server.addMsgHandler( "/quit", quit_callback )

# user script that's called by the game engine every frame
def each_frame():
    # clear timed_out flag
    server.timed_out = False
    # handle all pending requests then return
    while not server.timed_out:
        server.handle_request()

# simulate a "game engine"
while run:
    # do the game stuff:
    sleep(0.005)
    # call user script
Example #55
0
def user_callback(path, tags, args, source):
    # which user will be determined by path:
    # we just throw away all slashes and join together what's left
    user = ''.join(path.split("/"))
    # tags will contain 'ffff'
    # args is a OSCMessage with data
    # source is where the message came from (in case you need to reply)
    print ("Now do something with ", user, args[0], args[1], args[2], args[3])

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

server.addMsgHandler( "/muse/eeg", user_callback )

# user script that's called by the game engine every frame
def each_frame():
    # clear timed_out flag
    server.timed_out = False
    # handle all pending requests then return
    while not server.timed_out:
        server.handle_request()

# simulate a "game engine"
while run:
    # do the game stuff:
    sleep(1)
    # call user script
    each_frame()
def user_callback(path, tags, args, source):
    # which user will be determined by path:
    # we just throw away all slashes and join together what's left
    user = ''.join(path.split("/"))
    # tags will contain 'fff'
    # args is a OSCMessage with data
    # source is where the message came from (in case you need to reply)
    # print ("Now do something with", user, args[0]) 
    print (args[0])     

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

server.addMsgHandler( "/user/1", user_callback )

# user script that's called by the game engine every frame
def each_frame():
    # clear timed_out flag
    server.timed_out = False
    # handle all pending requests then return
    while not server.timed_out:
        server.handle_request()

# simulate a "game engine"
while run:
    # do the game stuff:
    # sleep(.1)
    # call user script
    each_frame()
Example #57
0
class MuseIO():
    def __init__(self, port=5001, signal=None, viewer=None):
        self.signal = signal
        self.viewer = viewer
        self.game = None
        self.port = port
        self.udp_ip = '127.0.0.1'

        self.server = OSCServer((self.udp_ip, self.port))
        self.server.timeout = 0

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

        # add message handlers
        if 'eeg' in self.signal:
            self.server.addMsgHandler('/muse/eeg', self.callback_eeg_raw)
        if 'concentration' in self.signal:
            self.server.addMsgHandler('/muse/elements/experimental/concentration', self.callback_concentration)
        if 'mellow' in self.signal:
            self.server.addMsgHandler('/muse/elements/experimental/mellow', self.callback_mellow)
        self.server.addMsgHandler("default", self.default_handler)

    def default_handler(self, addr, tags, stuff, source):
        # nothing to do here. This function is called for all messages that are not supported by the application.
        print "SERVER: No handler registered for ", addr
        return None

    def callback_eeg_raw(self, path, tags, args, source):
        # which user will be determined by path:
        # we just throw away all slashes and join together what's left
        # tags will contain 'ffff'
        # args is a OSCMessage with data
        # source is where the message came from (in case you need to reply)
        self.signal['eeg'].add_time()
        self.signal['eeg'].add_l_ear(args[0])
        self.signal['eeg'].add_l_forehead(args[1])
        self.signal['eeg'].add_r_forehead(args[2])
        self.signal['eeg'].add_r_ear(args[3])
        if 'eeg' in self.viewer:
            self.viewer['eeg'].refresh()
        #print args[0], args[1], args[2], args[3]

    def callback_concentration(self, path, tags, args, source):
        if 'concentration' in self.signal:
            self.signal['concentration'].add_time()
            self.signal['concentration'].add_concentration(args[0])
            self.viewer['concentration-mellow'].refresh()
            #self.game.change_velocity(self.signal['concentration'].concentration)

    def callback_mellow(self, path, tags, args, source):
        if 'mellow' in self.signal:
            self.signal['mellow'].add_time()
            self.signal['mellow'].add_mellow(args[0])
            self.viewer['concentration-mellow'].refresh()

    def handle_request(self):
        # clear timed_out flag
        self.server.timed_out = False
        # handle all pending requests then return
        while not self.server.timed_out:
            self.server.handle_request()

    def start(self, freq=220):
        update_timing = 1.0/float(freq)
        while True:
            sleep(update_timing)
            self.handle_request()
Example #58
0
    # which user will be determined by path:
    # we just throw away all slashes and join together what's left
    # print("path: ", path," tags: ", tags," args: ", args," source: ", source)
    # user = ''.join(path.split("/"))
    # tags will contain 'fff'
    # args is a OSCMessage with data
    # source is where the message came from (in case you need to reply)
    # print ("path: ", path, "args:", args[0]) 
    color.update(path, args[0])

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

server.addMsgHandler( "/1/fader1", user_callback )
server.addMsgHandler( "/1/fader2", user_callback )
server.addMsgHandler( "/1/fader3", user_callback )
server.addMsgHandler( "/1/fader4", user_callback )
server.addMsgHandler( "/crossfader", user_callback )
server.addMsgHandler( "/quit", quit_callback )

# user script that's called by the game engine every frame
def each_frame():
    # clear timed_out flag
    server.timed_out = False
    # handle all pending requests then return
    while not server.timed_out:
        server.handle_request()

# simulate a "game engine"