def update_plot(self): n_data_pts = self.model.timeseries.shape[0] if n_data_pts < self.n_fft: return if n_data_pts >= 2 * self.n_fft: n_offset = 2 * self.n_fft else: n_offset = self.n_fft data_to_process = self.model.timeseries[-n_offset:] hz_per_bin = float(SAMPLE_RATE) / self.n_fft min_psds = [] max_psds = [] for i, line in enumerate(self.lines): y = data_to_process[:, i + 1] nan_mask = np.isnan(y) y[nan_mask] = 0 # otherwise, a single NAN causes the filtering to fail. y = y - y.mean() psd, f = self._windowed_fft(y, SAMPLE_RATE) psd_per_bin = psd / hz_per_bin sendOSCMsg("/x", f) # !! it sends by default to localhost ip "127.0.0.1" and port 9000 sendOSCMsg("/y",np.sqrt(psd_per_bin))
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.
def on_status(self, status): # We'll simply print some values in a tab-delimited format # suitable for capturing to a flat file but you could opt # store them elsewhere, retweet select statuses, etc. try: #print "%s\t%s\t%s\t%s" % (status.text, # status.author.screen_name, # status.created_at, # status.source,) print "%i\t%s\t" % (status.text.__len__(), status.text) play = 1 while(play == 1): #sendOSCMsg("/freq", status.text.__len__() + 100.0) length = status.text.__len__() time.sleep(length/150 + 0.0) if length < 70: time.sleep(length/100 + 0.0) sendOSCMsg("/freq", [(length/140.0)*400 + 300.0]) sendOSCMsg("/bang", [1]) play = 0 except Exception, e: print >> sys.stderr, 'Encountered Exception:', e pass
def draw(): #called every 60 frames global xpos global xposkey #if frame.count%60 == 0: #4 beat measures #for i in range(1, 5): #temp_matrix = init_matrix**(i%4) global init_matrix temp_matrix = init_matrix #print init_matrix global temp temp = pick_next(temp_matrix, temp) time.sleep(.25) midi_temp = midi_to_freq(temp) sendOSCMsg("/freq", [midi_temp]) sendOSCMsg("/bang", [1]) print 'note: ' + str(temp) xpos = xpos + 3 if xpos > width: xpos = 5 xposkey = 5 background(255) y = temp-32 fill(0) ellipse(xpos, height - y*3, 5, 5)
def loop(): """ sends pending commands to robot, listens for reply, relays reply to OSC """ global haveClient, messageToRobot, busy, sentAddr, sentData try: while True: if haveClient and messageToRobot != 0: if sentAddr == "/initialize": initializeRobot() # blocks elif sentAddr == "/calibrate": calibrateRobot() # blocks else: sendCommand() if getReply() == True: # blocks sendOSCMsg(sentAddr, [sentData, "DONE"]) else: sendOSCMsg(sentAddr, [sentData, "ABORTED"]) busy = False messageToRobot = 0 sentAddr = 0 sentData = 0 except KeyboardInterrupt: print "closing all connections and exiting..." closeOSC()
def on_status(self, status): # We'll simply print some values in a tab-delimited format # suitable for capturing to a flat file but you could opt # store them elsewhere, retweet select statuses, etc. try: #print "%s\t%s\t%s\t%s" % (status.text, # status.author.screen_name, # status.created_at, # status.source,) print "%i\t%s\t" % (status.text.__len__(), status.text) play = 1 while (play == 1): #sendOSCMsg("/freq", status.text.__len__() + 100.0) length = status.text.__len__() time.sleep(length / 150 + 0.0) if length < 70: time.sleep(length / 100 + 0.0) sendOSCMsg("/freq", [(length / 140.0) * 400 + 300.0]) sendOSCMsg("/bang", [1]) play = 0 except Exception, e: print >> sys.stderr, 'Encountered Exception:', e pass
def run(self): prev_t = time.time() count = 0 t0 = time.time() try: while True: curr_t = time.time() if count < self.nsamples: m_x = self.x[count] m_y = self.y[count] else: print(Exception('Finished sending samples for ' + self.name )) break # rand = np.random.rand(1) # if rand > 0.7: # m_x = np.nan # m_y = np.nan # print m_x, m_y count += 1 msg = [m_x, m_y, self.width, self.height] self.sent_trajectory.append([m_x, m_y, self.width, self.height]) self.timestamps.append(curr_t - t0) sendOSCMsg(self.addr, msg) time.sleep(self.period) t1 = time.time() print('finished in ', t1 - t0) except KeyboardInterrupt: closeOSC() # finally close the connection before exiting or program pass
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
def send_buffer(self): """ Sends the entire midi buffer over osc """ channels = self.song_buffer.get_channel_events() channel_number = 0 for channel in channels: if channel: (add_index, midi_val, velocity, tick, channel_number) = channel[0] if channel_number==9: channel_number=10 print "channel:", channel_number turn_on = "/sync/c" + str(channel_number) + "/toggle/" sendOSCMsg(turn_on, [2]) channel_event_count = 0 for event in channel: self.send_event(event, channel_number) channel_event_count += 1 self.total +=1 sendOSCMsg("/clean", [1])
def send_start_signal(self): """ Sends the start signal to the pure data patch """ sendOSCMsg("/ms_per_tick", [self.ms_per_tick]) print "sent start signal with metro,lopass", self.ms_per_tick, 700
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!"])
def nextState(data): # Must update next_state, reward, done via OSC. state = data print 'next state : ', state next_state = np.random.normal(size=state_size) if data[12] == 1: done = True elif data[12] == 2: sys.exit(0) else: done = False print(done) reward = 1 if not done else -10 next_state = data #next_state = np.reshape(next_state, [1, state_size]) agent.remember(state, action_current, reward, next_state, done) state = next_state if done: e = e + 1 agent.save("./save/weights.h5") print(">>>> episode: {}/{}, score: {}, e: {:.2}".format( e, EPISODES, time, agent.epsilon)) else: sendOSCMsg("/request")
def send_control_changes(self): """ Sends the control changes, (volume,bank select MSB LSB) """ for control_event in self.song_buffer.control: print control_event (channel, event_type, value) = control_event; sendOSCMsg("/control", [channel, event_type, value]);
def send_program_changes(self): """ Sends the change program signal(changes the voice of a channel) """ for voice in self.song_buffer.voices: (channel_number, prgmchange) = voice voice_route = "/prgm/" sendOSCMsg(voice_route, [channel_number, prgmchange])
def send_event(self, arg, channel_number): """ sends a midi event """ (index, midi_val, velocity, tick, channel) = arg routing_message = "/sync/c" + str(channel_number) + "/midi" sendOSCMsg(routing_message, [midi_val, velocity, tick, index])
def hand_handler(addr, tags, stuff, source): if layer.PRINT_HAND: print "---" x = random.randint(0, 5) print " sending random integer " + str(x) + " to 9049" sendOSCMsg("/async/hand", [x]) print "---" time.sleep(.5)
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])
def sensor_broadcast(Control_Object): ultrasonic = Ultrasonic(Control_Object.nxt_obj, PORT_4) while 1: distance = ultrasonic.get_distance() sendOSCMsg('/motor_state', [Control_Object.m_right._get_state().power, Control_Object.m_left._get_state().power]) # print distance sendOSCMsg('/ultrasound', [distance]) time.sleep(0.10) # 10 ms
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)
def send_next_song(self): sendOSCMsg("/setgm", [1]); sendOSCMsg("/bpm",[self.bpm]) time.sleep(.5) self.send_control_changes() time.sleep(.5) self.send_program_changes() time.sleep(.5) self.send_buffer() time.sleep(.5) self.send_start_signal()
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')])
def sensor_broadcast(Control_Object): ultrasonic = Ultrasonic(Control_Object.nxt_obj, PORT_4) while 1: distance = ultrasonic.get_distance() sendOSCMsg('/motor_state', [ Control_Object.m_right._get_state().power, Control_Object.m_left._get_state().power ]) # print distance sendOSCMsg('/ultrasound', [distance]) time.sleep(0.10) # 10 ms
def contact_handler(addr, tags, stuff, source): if time.time() - layer.time < .05: return if layer.PRINT_CONTACT and 'Boundary' in (stuff[0], stuff[2]): if (stuff[1], stuff[3]) not in layer.dictionary: print "---" layer.dictionary[stuff[1], stuff[3]] = time.time() x = 1 #PureData needs this in order to feel happy sendOSCMsg("/async/collide", [x]) print "---" for key in layer.dictionary.keys(): if time.time() - layer.dictionary[key] > 0.3: del layer.dictionary[key] layer.time = time.time()
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.
def getReply(): global port rcv = "" wasCmdCompleted = False while True: if port.inWaiting() > 0: rcv = rcv + port.read() if rcv[-4:-2] == "OK": wasCmdCompleted = True break elif rcv[-9:-2] == "ABORTED": wasCmdCompleted = False break print "got: " + rcv # handle /where query if sentAddr == "/where": global inJointMode splitted = rcv.split("\r") posLine = splitted[2] posStrings = posLine.split() # handle joint mode response if inJointMode: print "posStrings: ", posStrings pos = map(lambda x: float(x), posStrings) print "pos: ", pos # convert to radians and send joint positions via OSC pos[0] = scale(pos[0], -3640, 3640, -1.57, 1.57) pos[1] = scale(pos[1], -8400, 8400, -1.57, 1.57) pos[2] = scale(pos[2], -6000, 6000, -1.57, 1.57) pos[3] = scale(pos[3], -4000, 4000, -1.57, 1.57) pos[4] = scale(pos[4], -4500, 4500, -1.57, 1.57) sendOSCMsg(sentAddr, [pos[0], pos[1], pos[2], pos[3], pos[4]]) # handle cartesian mode response else: pos = map(lambda x: float(x), posStrings) print "pos: ", pos # send cartesian position via OSC sendOSCMsg(sentAddr, [pos[0], pos[1], pos[2]]) return wasCmdCompleted
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.
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()
def currentState(data): #for e in range(EPISODES): # get input from Unity via OSC # print "received new osc msg from %s" #print "addr : %s" % addr #print "typetags :%s" % tags print "data: %s" % data print "e: %d" % e #state = np.random.normal(size=state_size) # <- Must receive message via OSC. debug only #state = np.reshape(state, [1, state_size]) state = data print 'current state : ', state #for time in range(500): action = agent.act(state) action_current = action #for debug print 'action: ', action # Must send this action back to Unity via OSC. sendOSCMsg("/outputs", [action]) num_objects = 30 num_angle_step = 6 num_scale_step = 4 num_dist_step = 4 num_rotation_bool = 2 act_rotate = True if action % num_rotation_bool == 0 else False action /= num_rotation_bool act_scale = action % num_scale_step action /= num_scale_step act_dist = action % num_dist_step action /= num_dist_step act_angle = action % num_angle_step action /= num_angle_step act_object = action print 'object: ', act_object print 'angle: ', act_angle print 'dist: ', act_dist print 'scale: ', act_scale print 'rotate: ', act_rotate
def calibrateRobot(): global port, sentAddr, inJointMode port.write("CALIBRATE\r") if getReply() != True: sendOSCMsg(sentAddr, ["CALIBRATE ERROR"]) else: port.write("CARTESIAN\r") if getReply() != True: sendOSCMsg(sentAddr, ["CARTESIAN ERROR"]) else: inJointMode = False port.write("2500 TRACKSPEED !\r") if getReply() != True: sendOSCMsg(sentAddr, ["SPEED ERROR"]) else: sendOSCMsg(sentAddr, ["DONE"])
def initializeRobot(): global port, sentAddr port.write("ROBOFORTH\r") if getReply() != True: sendOSCMsg(sentAddr, ["ROBOFORTH ERROR"]) else: port.write("START\r") if getReply() != True: sendOSCMsg(sentAddr, ["START ERROR"]) else: port.write("DE-ENERGIZE\r") if getReply() != True: sendOSCMsg(sentAddr, ["DE-ENERGIZE ERROR"]) else: sendOSCMsg(sentAddr, [ "INITIALIZE DONE, PUT ROBOT IN HOME POSITION AND CALIBRATE" ])
def main(filename): file = open(filename, 'r') nums = file.readline() nums = nums.split(' ') #print nums dictionary = create_dict(nums) init_matrix = create_matrix(dictionary) #this is for single matrix temp = pick_next(init_matrix, int(nums[0])) while(1): #4 beat measures for i in range(1, 5): #temp_matrix = init_matrix**(i%4) temp_matrix = init_matrix #print init_matrix temp = pick_next(temp_matrix, temp) time.sleep(1.0) midi_temp = midi_to_freq(temp) print temp print midi_temp sendOSCMsg("/freq", [midi_temp]) sendOSCMsg("/bang", [1])
def handleOSCCmd(addr, data): """ if command is well-formatted and robot is not busy, set the command to send to the robot """ # check for bad command if not formatOK(addr, data): sendOSCMsg(addr, [data, "BAD_COMMAND"]) return # check for busy robot global busy if busy: sendOSCMsg(addr, [data, "BUSY"]) return # confirm receipt of command to client and prep command to send to robot setCommand(addr, data) # sets busy flag to True sendOSCMsg(addr, [data, "GOT"])
def midi_from_push_handler(msg): # Read MIDI message received from Push and forward it to OCOTPUSH as OSC message midi_bytes = msg.bytes() sendOSCMsg(address="/frompush", data=midi_bytes)
def playback_displaced(addr, tags, data, source): global control d = control.get_data_displaced() sendOSCMsg("/ga", d)
#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 = {} #for num in range(21, 109): for num in range(low_bound, high_bound):
def ping(addr, tags, data, source): print "Received ping request!" sendOSCMsg("/ping", [str(time.time())])
def sendOSCMessage(self, target, data=[]): if self.sendOSC == True: simpleOSC.sendOSCMsg(target, data)
def request(addr, tags, data, source): sendOSCMsg("/chord", chordmachine.getNextPackedChord())
def play_chord(chord): sendOSCMsg("/note", [1, note_to_midi(chord[0])]) sendOSCMsg("/note", [2, note_to_midi(chord[1])]) sendOSCMsg("/note", [3, note_to_midi(chord[2])])
import numpy import time from simpleOSC import initOSCClient, initOSCServer, setOSCHandler, sendOSCMsg, closeOSC, \ createOSCBundle, sendOSCBundle, startOSCServer #initOSCClient("143.106.219.219", 60001) #initOSCClient("143.106.219.213", 59880) #initOSCClient("127.0.0.1", 60000) initOSCClient("127.0.0.1", 60001) file_handler = open("kinect-mockup.dat") n = 0 for line in file_handler: #time.sleep(1.0/30) n = n + 1 cells = line.split(",") output_msg = [] for c in cells: output_msg.append(float(c)) sendOSCMsg("/kinect", output_msg) if n == 30: print "30 frames sent!" n = 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])
try: while(1): print i note_play = random.randint(0, 10) if mood > 3: sleeptime = tempo[mood] speed = 3 if note_play*speed >= 4: offset = random.randint(-1,2)*11 index = random.randint(0, len(p[i])-1) templist = p[curchord] + [mood] + [p[curchord][index]+offset] sendOSCMsg("/out", [templist]) print 'played', templist j += 1 #every i intereations elif i >= 4 and note_play != 0: templist = p[curchord] + [mood] + [p[curchord][index]+offset] sendOSCMsg("/out", [templist]) print 'played', templist i += 1 if (i >= len(p)): curchord += 1 i = 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 on_button_state(self, instance, value): prefix = self.app.config.get('monome', 'prefix') index = instance.index value = 1 if value == 'down' else 0 sendOSCMsg('/%s/press' % prefix, [index % 8, index / 8, value])
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: tstart = time.time() told = tstart for ii in range(100): epoch = rt_client.get_data_as_epoch(n_samples=n_samples, picks=picks) filt = band_pass_filter(epoch.get_data(), sfreq, fmin, fmax) # compute band power features bp = np.log10(np.abs(cwt_morlet(filt[0], sfreq, [(fmin + fmax) / 2.]))) if told - tstart < baseline: bp_base.append(bp[:, 0, n_samples/2].mean()) else: bp_sample = bp[:, 0, n_samples/2].mean() bp_ratio = (np.mean(bp_base) - bp_sample) / np.mean(bp_base) sendOSCMsg("/nmx/bandpower/", [bp_ratio]) print "%i - sending /nmx/bandpower/%i" %(ii, bp_ratio) tcurrent = time.time() time.sleep(.5) told = tcurrent
def simpleTest(): initOSCClient() sendOSCMsg("/rpm", [5511])
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()
# -*- 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.
ip = "127.0.0.1" client_port = 8001 # 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) # and now set it into action startOSCServer() for x in range(100): try: # !! it sends by default to localhost ip "127.0.0.1" and port 9000 sendOSCMsg("/nmx/test/", [random.random()]) # create and send a bundle bundle = createOSCBundle("/nmx/test/x") # 1st message appent to bundle bundle.append(666) # 2nd message appent to bundle bundle.append("the number of the beast") # !! it sends by default to localhost ip "127.0.0.1" and port 9000 sendOSCBundle(bundle) # you don't need this, but otherwise we're sending as fast as possible. time.sleep(0.5) except KeyboardInterrupt: print "closing all OSC connections... and exit" # finally close the connection before exiting or program. closeOSC()
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: tstart = time.time() told = tstart for ii in range(100): epoch = rt_client.get_data_as_epoch(n_samples=n_samples, picks=picks) filt = band_pass_filter(epoch.get_data(), sfreq, fmin, fmax) # compute band power features bp = np.log10(np.abs(cwt_morlet(filt[0], sfreq, [(fmin + fmax) / 2.]))) if told - tstart < baseline: bp_base.append(bp[:, 0, n_samples / 2].mean()) else: bp_sample = bp[:, 0, n_samples / 2].mean() bp_ratio = (np.mean(bp_base) - bp_sample) / np.mean(bp_base) sendOSCMsg("/nmx/bandpower/", [bp_ratio]) print "%i - sending /nmx/bandpower/%i" % (ii, bp_ratio) tcurrent = time.time() time.sleep(.5) told = tcurrent
from simpleOSC import initOSCClient, sendOSCMsg import time ip = "127.0.0.1" port = 9002 initOSCClient(ip, port); sendOSCMsg("/vol", [0.05]) sendOSCMsg("/bypass", [1]) sendOSCMsg("/freq", [440]) sendOSCMsg("/bang", [1]) print "Hellow!"
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")