Пример #1
0
def myTest():
    """ a simple function that creates the necesary sockets and enters an enless
        loop sending and receiving OSC
    """
    import time # in this example we will have a small delay in the while loop
    
    initOSCClient() # takes args : ip, port
    initOSCServer() # takes args : ip, port, mode --> 0 for basic server, 1 for threading server, 2 for forking server
    
    # bind addresses to functions 
    setOSCHandler('/check', checkcheckcheck)

    startOSCServer() # and now set it into action

    print 'ready to receive and send osc messages ...'

    try:
        while 1:
            sendOSCMsg("/test", [444]) # !! it sends by default to localhost ip "127.0.0.1" and port 9000 

            # create and send a bundle
            bundle = createOSCBundle("/test/bndlprt1")
            bundle.append(666) # 1st message appent to bundle
            bundle.append("the number of the beast") # 2nd message appent to bundle
            sendOSCBundle(bundle) # !! it sends by default to localhost ip "127.0.0.1" and port 9000 

            time.sleep(0.5) # you don't need this, but otherwise we're sending as fast as possible.

    except KeyboardInterrupt:
       print "closing all OSC connections... and exit"
       closeOSC() # finally close the connection before exiting or program.
Пример #2
0
def client(addr, tags, data, source):
    """ sets address of client computer controlling the robot """
    global haveClient
    print "changing client to " + source[0]
    initOSCClient(source[0], 9000)
    sendOSCMsg(addr, ["NEW CLIENT ADDRESS: ", source[0]])
    haveClient = True
Пример #3
0
	def __init__(self, sntFile, oscServer=[]):
		#the current Ship ID
		self.shipId = 0
		# ship stats
		self.shipStats = {"shield": -1, "energy" : -1 ,"coordY" : -1, "coordX" : -1, "warp rate" : -1,"rotation rate" : -1, "impulse rate" : -1, "unknown" : -1, "unknown2" : -1, "rotation":-1, "frontshield" : -1, "rearshield" : -1, "weaponlock" : -1, "autobeams": -1, "speed": -1}

		#a map of bitfield position to value name and type
		self.statMapHelm = {15 : ("energy", 'f'), 21: ("coordY", 'f'), 19: ("coordX", 'f'), 16: ("shield", 'h'), 14: ("warp rate", 'b'), 10:("rotation rate", 'f'), 9: ("impulse rate", 'f'),  23: ("unknown2", 'f'), 25: ("speed", 'f'), 24: ("rotation", 'f'), 28: ("frontshield",'f'), 30: ("rearshield", 'f'), 8: ("weaponlock", "i"), 13:("autobeams",'b')}

		#sizes of struct fmt types. struct.calcsize returns size including alignment which this seems to ignore sometimes
		self.numLens = { 'f' : 4, 'h' : 2, 'i' : 4, 'b' : 1}
		#load the ship data from the snt file
		self.shipMap = self.loadShipData(sntFile) 
		# nowe we know the coords of ship systems count the number of each
		# this is sent to osc servers so that total damage of
		# ship systems can be calculated.
		# This is how the client does it... warp: 25% means 1 out of 4 nodes isnt
		# damaged
		self.systemCount = Counter(self.shipMap.values())

		self.sendOSC = False
		if len(oscServer) == 2:
			print "start osc client.."
			simpleOSC.initOSCClient(oscServer[0], oscServer[1])
			print "done"
			self.sendOSC = True
Пример #4
0
    def __init__(self, sntFile, oscServer=[]):
        #the current Ship ID
        self.shipId = 0
        # ship stats
        self.shipStats = {
            "shield": -1,
            "energy": -1,
            "coordY": -1,
            "coordX": -1,
            "warp rate": -1,
            "rotation rate": -1,
            "impulse rate": -1,
            "unknown": -1,
            "unknown2": -1,
            "rotation": -1,
            "frontshield": -1,
            "rearshield": -1,
            "weaponlock": -1,
            "autobeams": -1,
            "speed": -1
        }

        #a map of bitfield position to value name and type
        self.statMapHelm = {
            15: ("energy", 'f'),
            21: ("coordY", 'f'),
            19: ("coordX", 'f'),
            16: ("shield", 'h'),
            14: ("warp rate", 'b'),
            10: ("rotation rate", 'f'),
            9: ("impulse rate", 'f'),
            23: ("unknown2", 'f'),
            25: ("speed", 'f'),
            24: ("rotation", 'f'),
            28: ("frontshield", 'f'),
            30: ("rearshield", 'f'),
            8: ("weaponlock", "i"),
            13: ("autobeams", 'b')
        }

        #sizes of struct fmt types. struct.calcsize returns size including alignment which this seems to ignore sometimes
        self.numLens = {'f': 4, 'h': 2, 'i': 4, 'b': 1}
        #load the ship data from the snt file
        self.shipMap = self.loadShipData(sntFile)
        # nowe we know the coords of ship systems count the number of each
        # this is sent to osc servers so that total damage of
        # ship systems can be calculated.
        # This is how the client does it... warp: 25% means 1 out of 4 nodes isnt
        # damaged
        self.systemCount = Counter(self.shipMap.values())

        self.sendOSC = False
        if len(oscServer) == 2:
            print "start osc client.."
            simpleOSC.initOSCClient(oscServer[0], oscServer[1])
            print "done"
            self.sendOSC = True
Пример #5
0
def max_color():
	initOSCClient(ip, port)
	import time
	for i in range(0,48):
		sendOSCMsg("/asteroid", [i,0,0,0,0,240,1,0])
	
	time.sleep(5)
	
	sendOSCMsg("/set_max_brightness", [256.0])
Пример #6
0
def LaserLoop():
	initOSCClient('127.0.0.1', 8000) # takes args : ip, port
	initOSCServer('127.0.0.1', 8001) # takes args : ip, port, mode --> 0 for basic server, 1 for threading server, 2 for forking 

	# bind addresses to functions 
	setOSCHandler('/laser', laser)
	startOSCServer() # and now set it into action

	print 'ready to receive and send osc messages ...'
Пример #7
0
def rainbow():
	WAIT = 0.05
	import time
	initOSCClient(ip, port)
	i = 0
	while (1):
		for j in range(0,360):
			for i in range(0,48):
				sendOSCMsg("/asteroid", [i,0,0,0,0,j,1,0])
		time.sleep(WAIT)
Пример #8
0
def LaserLoop():
    initOSCClient('127.0.0.1', 8000)  # takes args : ip, port
    initOSCServer(
        '127.0.0.1', 8001
    )  # takes args : ip, port, mode --> 0 for basic server, 1 for threading server, 2 for forking

    # bind addresses to functions
    setOSCHandler('/laser', laser)
    startOSCServer()  # and now set it into action

    print 'ready to receive and send osc messages ...'
Пример #9
0
def send_to_max(message_object, direction):
    """
    Takes a message object, a direction (e.g. /aj)
    Then proecesses a message to send to max
    """
    osc.initOSCClient(ip=UDP_IP, port=UDP_PORT)
    phone = message_object.sender
    # Add dashes to phone number
    phone = ('-').join([phone[:3], phone[3:6], phone[6:]]) 
    output = "||" + phone + "||" + message_object.message
    osc.sendOSCMsg(address=direction, data=[output.encode('utf-8')])
Пример #10
0
def dim():
	WAIT = 0.05
	initOSCClient(ip, port)
	
	for i in range(0,48):
		sendOSCMsg("/asteroid", [i,0,0,0,0,240,1,0])
	sendOSCMsg("/asteroid", [56,0,0,0,0,219,1,0])
	sendOSCMsg("/asteroid", [49,0,0,0,0,261,1,0])
	sendOSCMsg("/asteroid", [102,0,0,0,0,219,1,0])
	sendOSCMsg("/asteroid", [507,0,0,0,0,261,1,0])
	sendOSCMsg("/asteroid", [800,0,0,0,0,219,1,0])
	sendOSCMsg("/asteroid", [900,0,0,0,0,261,1,0])
Пример #11
0
 def __init__(self):
     """
        Initialize the music generator class
     """
     self.ip = "127.0.0.1"
     self.pdportnumber = 9049 # where to send data
     self.bars_to_send = Queue.Queue()
     self.total_bars = Queue.Queue()
     initOSCClient(self.ip, self.pdportnumber)
     self.song_buffer = None
     self.ms_per_tick = 0  # milliseconds per tick
     self.total = 0
     self.bpm = 0;
def main():

    initOSCClient('127.0.0.1', 9001)
    sendOSCMsg("/start")

    fname = sys.argv[1]
    f = open(fname, "rt")
    text = f.read()
 
    root = Tkinter.Tk()
    
    # have to initialize the sound system, required!!
    tkSnack.initializeSnack(root)
    # set the volume of the sound system (0 to 100%)
    tg.setVolume(100)

    tg.translateNote('A4')

    notes = text.split()
    d = build_dict(notes)

    sent = generate_music(d)

    j = 0
    for i in sent:  
        # Nota mais grave vai pro cello
        i = tg.translateNote(i)        
        # Sua terça vai pro violino 1
        j = i*(4/5)
        # Sua quinta vai pra viola
        k = j*(3/2)
        # E sua oitava pro violino 2
        l = i*2
        sendOSCMsg("/cello", [i]) 
        sendOSCMsg("/viola", [j])
        sendOSCMsg("/violin1", [k]) 
        sendOSCMsg("/violin2", [l])
               
        time.sleep(0.5)

#    tg.soundStop()
    
    sendOSCMsg("/cello", [0]) 
    sendOSCMsg("/viola", [0])       
    sendOSCMsg("/violin1", [0]) 
    sendOSCMsg("/violin2", [0]) 

    sendOSCMsg("/stop")
    closeOSC()  

    root.withdraw()
def main():

    initOSCClient('127.0.0.1', 9001)
    sendOSCMsg("/start")

    fname = sys.argv[1]
    f = open(fname, "rt")
    text = f.read()

    root = Tkinter.Tk()

    # have to initialize the sound system, required!!
    tkSnack.initializeSnack(root)
    # set the volume of the sound system (0 to 100%)
    tg.setVolume(100)

    tg.translateNote('A4')

    notes = text.split()
    d = build_dict(notes)

    sent = generate_music(d)

    j = 0
    for i in sent:
        # Nota mais grave vai pro cello
        i = tg.translateNote(i)
        # Sua terça vai pro violino 1
        j = i * (4 / 5)
        # Sua quinta vai pra viola
        k = j * (3 / 2)
        # E sua oitava pro violino 2
        l = i * 2
        sendOSCMsg("/cello", [i])
        sendOSCMsg("/viola", [j])
        sendOSCMsg("/violin1", [k])
        sendOSCMsg("/violin2", [l])

        time.sleep(0.5)

#    tg.soundStop()

    sendOSCMsg("/cello", [0])
    sendOSCMsg("/viola", [0])
    sendOSCMsg("/violin1", [0])
    sendOSCMsg("/violin2", [0])

    sendOSCMsg("/stop")
    closeOSC()

    root.withdraw()
Пример #14
0
def run():
	try:
		initOSCClient(ip, client_port)

		# initOSCClient(ip, client_port)
		initOSCServer(ip, server_boids_port)
		setOSCHandler('/collision', col)
		startOSCServer()

		initOSCServer(ip, server_sound_port)
		setOSCHandler('/request', request)
		startOSCServer()

	except KeyboardInterrupt:
		closeOSC()
Пример #15
0
def myTest():
    """ a simple function that creates the necesary sockets and enters an enless
        loop sending and receiving OSC
    """
    import time # in this example we will have a small delay in the while loop
    
    initOSCClient("37.34.68.87", 3333) # takes args : ip, port
    try:
        while 1:
            for i in xrange(100):
                sendOSCMsg("/score", ["%.2f" % (i / 100.0)]) 
                time.sleep(0.01)

    except KeyboardInterrupt:
       closeOSC() # finally close the connection before exiting or program.
Пример #16
0
def myTest():
    initOSCClient("192.168.0.2", 9000)  # takes args : ip, port
    initOSCServer(
        "192.168.0.7", 9001,
        0)  # takes args : ip, port, mode => 0 basic, 1 threading, 2 forking

    setOSCHandler('/test', test)
    startOSCServer()

    print 'ready to receive and send osc messages...'

    try:
        while 1:
            sendOSCMsg("/sup", [444, 4.4, 'yomama is a baby'])
            time.sleep(1)

    except KeyboardInterrupt:
        print "closing all OSC connections and exiting"
        closeOSC()
Пример #17
0
def myTest():
    """ a simple function that creates the necesary sockets and enters an enless
        loop sending and receiving OSC
    """
    import time  # in this example we will have a small delay in the while loop

    initOSCClient()  # takes args : ip, port
    print 'client'
    initOSCServer(
    )  # takes args : ip, port, mode --> 0 for basic server, 1 for threading server, 2 for forking server
    print 'server'

    # bind addresses to functions
    setOSCHandler('/check', checkcheckcheck)
    print 'check'

    startOSCServer()  # and now set it into action

    print 'ready to receive and send osc messages ...'

    try:
        while 1:
            print 'sending...'
            sendOSCMsg(
                "/test", [444]
            )  # !! it sends by default to localhost ip "127.0.0.1" and port 9000

            # create and send a bundle
            bundle = createOSCBundle("/test/bndlprt1")
            bundle.append(666)  # 1st message appent to bundle
            bundle.append(
                "the number of the beast")  # 2nd message appent to bundle
            sendOSCBundle(
                bundle
            )  # !! it sends by default to localhost ip "127.0.0.1" and port 9000

            time.sleep(
                0.5
            )  # you don't need this, but otherwise we're sending as fast as possible.

    except KeyboardInterrupt:
        print "closing all OSC connections... and exit"
        closeOSC()  # finally close the connection before exiting or program.
Пример #18
0
    def do_connect(self):
        config = self.config
        host = config.get('network', 'host')
        sport = config.getint('monome', 'send_port')
        rport = config.getint('monome', 'receive_port')
        mdevice = config.getint('midi', 'device')
        # osc
        initOSCClient(host, sport)
        initOSCServer(host, rport)
        # midi
        #pygame.midi.init()
        #pygame.midi.get_count()
        #self.midi_out = pygame.midi.Output(device_id=mdevice)
        #self.device_name = pygame.midi.get_device_info(mdevice)

        # switch to main screen
        parent = self.root.parent
        parent.remove_widget(self.root)
        self.root = BrokerControlMain(app=self)
        parent.add_widget(self.root)
Пример #19
0
Файл: main.py Проект: AR-S/Nodes
    def do_connect(self):
        config = self.config
        host = config.get('network', 'host')
        sport = config.getint('monome', 'send_port')
        rport = config.getint('monome', 'receive_port')
        mdevice = config.getint('midi', 'device')
        # osc
        initOSCClient(host, sport)
        initOSCServer(host, rport)
        # midi
        #pygame.midi.init()
        #pygame.midi.get_count()
        #self.midi_out = pygame.midi.Output(device_id=mdevice)
        #self.device_name = pygame.midi.get_device_info(mdevice)

        # switch to main screen
        parent = self.root.parent
        parent.remove_widget(self.root)
        self.root = BrokerControlMain(app=self)
        parent.add_widget(self.root)
Пример #20
0
    def setup(self, width, height):
        initOSCClient('127.0.0.1', self.port)
        self.nsamples = int(self.duration * self.freq)
        self.period = 1. / float(self.freq)
        self.width = width
        self.height = height

        print('Created source: ', self.freq,  ' ', self.port, ' ', self.addr, ' ', self.period)

        pos = np.zeros((self.nsamples, 2))
        vel = np.zeros((self.nsamples, 2))

        pos[0] = np.random.uniform(0, 1, 2)

        #while len(x) < self.nsamples:
        dt = 0.01
        for i in range(1, self.nsamples):
            dvel = 0.5 * np.random.randn(2)

            vel[i] = vel[i-1] + dvel
            vel[i] = vel[i] + 0.1 * vel[i] * (2 - np.linalg.norm(vel[i]))
            #vel[i] = vel[i] + (0.1 * - vel[i])
            pos[i] = pos[i-1] + vel[i-1] * dt

            if pos[i, 0] < 0:
                pos[i, 0] = 0
                vel[i, 0] = 0
            if pos[i, 1] < 0:
                pos[i, 1] = 0
                vel[i, 1] = 0
            if pos[i, 0] > width:
                pos[i, 0] = width
                vel[i, 0] = 0 
            if pos[i, 1] > height:
                pos[i, 1] = height
                vel[i, 1] = 0 

        self.x = pos[:, 0]
        self.y = pos[:, 1]
Пример #21
0
                        help="The port to listen on")
    parser.add_argument("--port_send",
                        type=int,
                        default=9002,
                        help="The port to send messages to")
    args = parser.parse_args()

    # Configure connection to/from Push2 MIDI
    try:
        push2_midi_out = mido.open_output(
            'Ableton Push 2:Ableton Push 2 MIDI 1 16:0')
        push2_midi_in = mido.open_input(
            'Ableton Push 2:Ableton Push 2 MIDI 1 16:0')
        push2_midi_in.callback = midi_from_push_handler
        print("Listening for MIDI messages comming from push...")
    except OSError:
        print("Could not connect to Push2 MIDI ports")
        sys.exit(0)
    except IOError:
        print("Could not connect to Push2 MIDI ports")
        sys.exit(0)

    # Configure OSC client for sending messages to
    initOSCClient(ip=args.ip, port=args.port_send)

    # Configure OSC server to receive messages from OCTOPUSH
    initOSCServer(ip=args.ip, port=args.port_listen)
    setOSCHandler('/topush', midi_to_push_handler)
    startOSCServer()
    print("Listening OSC on {}".format(args.port_listen))
Пример #22
0
 def run_client(self):
     initOSCClient(self.ip,self.sport)
     print "client is running, sending to " + str(self.ip) +":" + str(self.sport)
     while(1):
         time.sleep(5)
Пример #23
0
#!/usr/bin/env python
# coding=utf-8
import freenect
import pyglet
import numpy
import simpleOSC

simpleOSC.initOSCClient("127.0.0.1", 8765)

depth_win = pyglet.window.Window()
video_win = pyglet.window.Window()

depth = pyglet.image.ImageData(640, 480, "I",   numpy.empty((640, 480)))
video = pyglet.image.ImageData(640, 480, "RGB", numpy.empty((640, 480)))

@depth_win.event
def on_draw():
	depth_win.clear()
	feed, _ = freenect.sync_get_depth()
	depth.set_data("I", -640, feed.astype(numpy.uint8).tostring())
	depth.blit(0, 0)

@video_win.event
def on_draw():
	video_win.clear()
	feed, _ = freenect.sync_get_video()
	video.set_data("RGB", -640*3, feed.tostring())
	video.blit(0, 0)

def update_sound(dt):
	feed, _ = freenect.sync_get_depth()
Пример #24
0
# -*- coding: utf-8 -*-

import sys
import tweepy
import webbrowser
import pygame
import time

from simpleOSC import initOSCClient, sendOSCMsg

ip = "127.0.0.1"
port = 9002

initOSCClient(ip, port)

sendOSCMsg("/vol", [0.05])
sendOSCMsg("/bypass", [1])
sendOSCMsg("/roomsize", [0])

# Query terms

Q = sys.argv[1:]

# Get these values from your application settings.

CONSUMER_KEY = 'Mdzh2RyFmTINcRfpRiJpIw'
CONSUMER_SECRET = 'X0y9t9WB9tYizi1nVa6SgbER46msyX4L9IfGb9jllc'

# Get these values from the "My Access Token" link located in the
# margin of your application details, or perform the full OAuth
# dance.
def test():
    initOSCClient(ip, port)

    sendOSCMsg("/collision", [444, "stuff"])
import time

if __name__ == "__main__":
	parser = argparse.ArgumentParser()
	parser.add_argument("--bonsaiIP", default="127.0.0.1", help="The IP of Bonsai machine")
	parser.add_argument("--bonsaiPort", type=int, default=2323, help="The port Bonsai is listening on")
	parser.add_argument("--oeIP", default="10.153.170.52", help="The IP of OpenEphys machine")
	parser.add_argument("--oePort", default='5556', help="The port OpenEphys is listening on")
	parser.add_argument("--mode", default='start', help="start or stop")
	
	args = parser.parse_args()
	
	context = zmq.Context()
	socket = context.socket(zmq.REQ)
	socket.connect("tcp://%s:%s" % (args.oeIP, args.oePort))
	
	if args.mode == 'start':
		initOSCClient(args.bonsaiIP,args.bonsaiPort)
		sendOSCMsg("/number", [1])
		socket.send("StartRecord CreateNewDir=1")
		socket.recv_string()
	elif args.mode == 'stop':
		initOSCClient(args.bonsaiIP,args.bonsaiPort)
		sendOSCMsg("/number", [2])
		socket.send("StopRecord")
		socket.recv_string()
	elif args.mode == 'event':
		initOSCClient(args.bonsaiIP,args.bonsaiPort)
		sendOSCMsg("/number", [3])
		socket.send("Event")
		socket.recv_string()		
Пример #27
0
eeg_waves = []
a_waves = []
b_waves = []



ip = "localhost"
port1 = 9002
port_receive = 9001
base_a4=440


port1 = sys.argv[1]

initOSCClient(ip, int(port1))
'''
initOSCServer(ip, int(port_receive), 0)
setOSCHandler('/mood', process_mood)
startOSCServer()
'''

def mtof(midi):
	return base_a4*2**((midi-9)/12.0)



def process_eeg(addr, tags, data, source):

  print "received new osc msg from %s" % getUrlStr(source)
  print "with addr : %s" % addr
        time.sleep(0.10)  # 10 ms


# Not in use
def shutdown(pl):
    input("Press any key to close OSC server")
    closeOSC()
    pl.terminate()


if __name__ == '__main__':
    b = nxt.locator.find_one_brick()
    controls = MotorControl(b)

    # takes args : ip, port
    initOSCClient()

    # takes args : ip, port, mode --> 0 for basic server, 1 for threading server, 2 for forking server
    initOSCServer(ip='127.0.0.1', port=20002, mode=1)

    # bind addresses to functions
    setOSCHandler('/motors', controls.motor_osc_handler)

    # and now set it into action
    startOSCServer()

    # starting the sensor broadcast in parallel
    pool = mp.Pool()
    #pool.apply_async(shutdown(pool))
    pool.apply_async(sensor_broadcast(controls))
    pool.close()
Пример #29
0
    num_scale_step = 4
    num_dist_step = 4
    num_rotation_bool = 2
    action_size = num_objects * num_angle_step * num_scale_step * num_dist_step * num_rotation_bool

    agent = DQNAgent(state_size, action_size)
    my_file = Path("./save/weights.h5")

    if my_file.is_file():
        agent.load("./save/weights.h5")
    else:
        agent.save("./save/weights.h5")

    done = False
    batch_size = 32

    # setup OSC parts
    initOSCClient()  # takes args : ip, port
    print 'client'
    initOSCServer(
    )  # takes args : ip, port, mode --> 0 for basic server, 1 for threading server, 2 for forking server
    print 'server'

    # bind addresses to functions
    setOSCHandler('/inputs_current', currentHandler)
    setOSCHandler('/inputs_next', nextHandler)
    print 'address binding check'

    startOSCServer()  # and now set it into action
    print 'ready to receive and send osc messages ...'
Пример #30
0
ip = "127.0.0.1"
client_port = 8001

n_samples = 2000
fmin = 8
fmax = 12

baseline = 3
bp_base = []

n_eeg = 16
sfreq = 250
picks = np.arange(n_eeg)

# takes args : ip, port
initOSCClient(ip=ip, port=client_port)

# takes args : ip, port, mode --> 0 for basic server,
# 1 for threading server, 2 for forking server
initOSCServer(ip=ip, port=6400, mode=1)

# and now set it into action
startOSCServer()

# get measurement info guessed by MNE-Python
ch_names = ['EEG-%i' % i for i in np.arange(n_eeg)]
raw_info = mne.create_info(ch_names, sfreq)

with FieldTripClient(info=raw_info, host='localhost', port=1972,
                     tmax=150, wait_max=10) as rt_client:
Пример #31
0
ip = "127.0.0.1"
client_port = 8001

n_samples = 2000
fmin = 8
fmax = 12

baseline = 3
bp_base = []

n_eeg = 16
sfreq = 250
picks = np.arange(n_eeg)

# takes args : ip, port
initOSCClient(ip=ip, port=client_port)

# takes args : ip, port, mode --> 0 for basic server,
# 1 for threading server, 2 for forking server
initOSCServer(ip=ip, port=6400, mode=1)

# and now set it into action
startOSCServer()

# get measurement info guessed by MNE-Python
ch_names = ['EEG-%i' % i for i in np.arange(n_eeg)]
raw_info = mne.create_info(ch_names, sfreq)

with FieldTripClient(info=raw_info,
                     host='localhost',
                     port=1972,
Пример #32
0
# to create initial matrix for markov chaining
    
#possible midi notes range from 21 to 108

import sys
import random as rand
import numpy as np

from simpleOSC import initOSCClient, sendOSCMsg
import time

#osc init
ip = "127.0.0.1"
port = 9002

initOSCClient(ip, port)

sendOSCMsg("/vol", [0.05])
sendOSCMsg("/bypass", [0])
sendOSCMsg("/roomsize", [0.0])


#CONSTANTS
#low_bound has to be one less than the lowest value
#high bound has to be one more than the highest value
low_bound = 20
high_bound = 109

#nums are the midi notes from the file (we have extracted them into an array in the main function)
def create_dict(nums): 
    dict = {}
Пример #33
0
        time.sleep(0.10)  # 10 ms


# Not in use
def shutdown(pl):
    input("Press any key to close OSC server")
    closeOSC()
    pl.terminate()


if __name__ == '__main__':
    b = nxt.locator.find_one_brick()
    controls = MotorControl(b)

    # takes args : ip, port
    initOSCClient()

    # takes args : ip, port, mode --> 0 for basic server, 1 for threading server, 2 for forking server
    initOSCServer(ip='127.0.0.1', port=20002, mode=1)

    # bind addresses to functions
    setOSCHandler('/motors', controls.motor_osc_handler)

    # and now set it into action
    startOSCServer()

    # starting the sensor broadcast in parallel
    pool = mp.Pool()
    #pool.apply_async(shutdown(pool))
    pool.apply_async(sensor_broadcast(controls))
    pool.close()
Пример #34
0

from simpleOSC import initOSCClient, initOSCServer, setOSCHandler, sendOSCMsg, closeOSC, \
     createOSCBundle, sendOSCBundle, startOSCServer

import granular_control
import time


control = granular_control.GranularController()
control.start_log(str(time.time()) + ".dat")

initOSCServer("127.0.0.1", 60001) # takes args : ip, port, mode --> 0 for basic server, 1 for threading server, 2 for forking server
initOSCClient("127.0.0.1", 60000)

def ping(addr, tags, data, source):
    print "Received ping request!"
    sendOSCMsg("/ping", [str(time.time())])

def receive_kinect_data(addr, tags, data, source):
    global control
    control.record_control(data)

def playback_data_point(addr, tags, data, source):
    global control
    try:
        d = control.get_data()
        sendOSCMsg("/kinect", list(d))
    except:
        sendOSCMsg("/error", ["No more recorded data to playback!"])
Пример #35
0
def simpleTest():
    initOSCClient()
    sendOSCMsg("/rpm", [5511])
Пример #36
0
def samplesocketstream(request):
    import subprocess
    import ast
    import time

    # use URL string VARS: http://stackoverflow.com/questions/150505/capturing-url-parameters-in-request-get
    # http://stackoverflow.com/questions/6164540/getting-two-strings-in-variable-from-url-in-django
    # https://docs.python.org/2/library/re.html
    # http://www.djangobook.com/en/2.0/chapter07.html

    if request.method == 'GET':

        #  C:\Users\DusX\CODE\python\TCPIP_bridge\bridgeApp\
        p = subprocess.Popen(["python", "-u", settings.DX_SOCKETSTREAMFILE],
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             bufsize=1)

        startT = time.clock()
        print("launched: " + p.stdout.readline()),  # read the first line

        # prepar OSC server while Popen launching and processing
        initOSCClient(
            '127.0.0.1', 1234
        )  # takes args : ip, port initOSCClient(ip='127.0.0.1', port=9000)

        hold = True  # setup for loop
        data = False  # setup for loop
        while hold:  # repeat several times to show that it works
            currentT = time.clock()

            strOSC = "processing: " + str(currentT - startT)
            sendOSCMsg("/RPM", [strOSC])  # send text OSC

            if (
                    currentT - startT
            ) >= 70:  #if it takes more than a minute+ we should timeout. time should relate to Izzy
                # TODO: should relaunch after killing process
                p.terminate()
                return HttpResponse(
                    "Socket TIMEOUT"
                )  # untested for how Izzy handles this response

            data = p.stdout.readline()  # read output
            print("Line" + ": " + data)

            try:
                data = ast.literal_eval(data)
                print("data=: " + str(type(data)))
                if type(data) is list:
                    print("data match found.")
                    data = data[0]
                hold = False
            except:
                # add timeout code, incase
                data = False
                pass

        # print p.communicate("n\n")[0], # signal the child to exit,
        # print ("FINAL" + str(p.communicate()[0]))  # signal the child to exit, # read the rest of the output, # wait for the child to exit

        if data:
            if p:
                p.terminate()
                print("process terminated")
            # SEND OSC
            sendOSCMsg(
                "/RPM", [data]
            )  # !! it sends by default to localhost ip "127.0.0.1" and port 9000
            closeOSC()

            # return HttpResponse("RPM = " + str(data) + "\n")  # requests per minute
            return JsonResponse({'RPM': data})

    if request.method == 'POST':
        return HttpResponse("POST")
Пример #37
0
#!/usr/bin/env python

import sys
from simpleOSC import initOSCClient, initOSCServer, setOSCHandler, sendOSCMsg, closeOSC, \
     createOSCBundle, sendOSCBundle, startOSCServer

initOSCClient("localhost", 9000)
sendOSCMsg("/drink", [sys.argv[1]])