def ping_callback(path, tags, args, source): try: client = OSCClient() client.connect((source[0], 8001)) client.send(OSCMessage("/ping")) except Exception as e: print e
class PacketManager(object): def __init__(self, num_datapoints, port=DEFAULTPORT): self.num_datapoints = num_datapoints self.data_source = None self.client = OSCClient() self.client.connect(("localhost", port)) def add_data_source(self, data_source): self.data_source = data_source def send_to_max(self): bundle = OSCBundle() for i in range(NUM_CAPS_AND_POTS): bundle.append({ 'addr': "/d" + str(i) + "/hz", 'args': self.data_source.get_pitch_data(i) }) bundle.append({ 'addr': "/d" + str(i) + "/on", 'args': self.data_source.get_cap_data(i) }) bundle.append({ 'addr': "/duration", 'args': self.data_source.get_duration_data() }) bundle.append({ 'addr': "/mod", 'args': self.data_source.get_mod_data() }) self.client.send(bundle)
def trajectory_callback(path, tags, args, source): trajectory = args[0] tokens = trajectory.split(";") tPoints = [] for t in tokens[:-1]: tPoints.append(map(lambda x: int(x), t.split(","))) client = OSCClient() client.connect((source[0], 8001)) client.send(OSCMessage("/busy")) shuffle(tPoints) print "Executing", tPoints createPath(tPoints) if random() > 0.5: b = 0 if random() > 0.5: b = 1 print "Push extra", b pushButtonExtra(b, 0.5 + random() * 3) client = OSCClient() client.connect((source[0], 8001)) client.send(OSCMessage("/noBusy"))
def messageServer(self, messagePath, argument): client = OSCClient() client.connect((self.serverIP, self.serverPort)) message = OSCMessage(messagePath) message.append(argument) client.send(message)
def main(args): # Default host and port HOST = '192.168.1.8' PORT = 3032 if len(args) == 2: HOST = args[0] PORT = args[1] elif len(args) == 1: HOST = args[0] elif len(args) > 2: errorPrint("OSC Go button accepts at most 2 arguments.\n" + len(args) + " were provided."); client = OSCClient() client.connect((HOST, PORT)) msg = OSCMessage("/eos/key/go_0"); client.send(msg); client.close(); print print "GO" print exit();
def step_impl(context, host, port, int_one, int_sec): client = OSCClient() client.connect((host, port)) if int_sec > 0: client.send(OSCMessage('/test', int_one, int_sec)) else: client.send(OSCMessage('/test', int_one))
class SendOSC(object): def __init__(self): self.osc_message = None self.osc_client = OSCClient() self.osc_message = OSCMessage() self.ip = "" self.port = 0 def connect(self, ip="localhost", port=8080): self.ip = ip self.port = port self.osc_client.connect((self.ip, self.port)) def send(self, address, value): self.osc_message.setAddress(address) self.osc_message.append(value) self.osc_client.send(self.osc_message) def send_distane(self, distance): oscdump = "/dumpOSC/DistanceTipTarget" self.send(oscdump, distance) def send_needle_tip_position(self, x, y, z): oscdump = "/dumpOSC/needltip/x" self.send(oscdump, x) oscdump = "/dumpOSC/needltip/y" self.send(oscdump, y) oscdump = "/dumpOSC/needltip/z" self.send(oscdump, z)
class slOscSend: """ Osc Sender """ def __init__(self, adr, port): self.ip_adr = adr self.port = port self.destination = (self.ip_adr, self.port) # self.client = OSC.OSCClient() self.client = OSCClient() self.client.connect(self.destination) self.adr = "/unset" self.str = 'IP: ' self.str += self.ip_adr self.str += ' PORT: ' self.str += str(port) print(self.str) def send(self, adr, *args): self.adr = adr # msg = OSC.OSCMessage() msg = OSCMessage() msg.setAddress(self.adr) for i in args: msg.append(i) try: self.client.send(msg) except: print ">>> ERR :: Could not connect to ", self.ip_adr, ":", self.port
class ColorsOut: def __init__(self): self.client = OSCClient() self.client.connect( ("localhost",11661) ) def write(self, pixels): message = OSCMessage("/setcolors") pixels = self.crazyMofoingReorderingOfLights(pixels) message.append(pixels) self.client.send( message ) def diff(self, pixels): message = OSCMessage("/diffcolors") message.append(pixels) self.client.send( message ) def crazyMofoingReorderingOfLights(self, pixels): pixels2 = pixels[:] #make a copy so we don't kerplode someone's work """ what are we expecting? we want the back left (by the couches) of the room to be pixel 0, and by the front is the last row whereas in reality, it's the opposite. here is the order it'd be nice to have them in: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 this is the actual order: 23 22 21 20 19 16 17 18 15 14 13 12 11 10 9 8 3 2 5 4 6 *0**1**7* *=not there """ actualorder = [23,22,21,20,19,16,17,18,15,14,13,12,11,10,9,8,3,2,5,4,6,0,1,7] badcolors = [3,2,5,4,6,0,1,7] for i in range(len(actualorder)): (r,g,b) = pixels[i] r = max(0.0, min(r, 1023.0)) g = max(0.0, min(g, 1023.0)) b = max(0.0, min(b, 1023.0)) pixels2[actualorder[i]] = (r,g,b) for i in range(len(badcolors)): pixels2[badcolors[i]] = (0.0,0.0,0.0) return pixels2
def send_value(self): for add, d in self.neighbors.items(): c = OSCClient() c.connect(("localhost", add)) msg = OSCMessage("/receive") msg.append(self._address) msg.append(self.data["value"]) msg.append(self.data["iter"]) c.send(msg) c.close()
def test_callback(path, tags, args, source): client = OSCClient() client.connect((source[0], 8001)) client.send(OSCMessage("/busy")) print "Do test" pushTwo((2, 4), (2, 5)) client = OSCClient() client.connect((source[0], 8001)) client.send(OSCMessage("/noBusy"))
def zero_callback(path, tags, args, source): client = OSCClient() client.connect((source[0], 8001)) client.send(OSCMessage("/busy")) print "Go Zero" goToZero() client = OSCClient() client.connect((source[0], 8001)) client.send(OSCMessage("/noBusy"))
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 ColorsOut: def __init__(self): self.client = OSCClient() self.client.connect( ("localhost",11661) ) def write(self, pixels): message = OSCMessage("/setcolors") message.append(pixels) self.client.send( message ) def diff(self, pixels): message = OSCMessage("/diffcolors") message.append(pixels) self.client.send( message )
class oscSender(object): def __init__(self,port): self.client = OSCClient() self.client.connect( ("172.16.1.110", port) ) print "Started server on port : " + str(port) def newNode(self,args,BSSID,kind): msg = OSCMessage("/new" ) msg.append(kind.strip()) msg.append(args) msg.append(BSSID.strip()) self.client.send(msg) # print "new" def updateNode(self,args,BSSID,kind): if BSSID == " ": return msg = OSCMessage("/update") msg.append(kind.strip()) msg.append(args) msg.append(BSSID.strip()) self.client.send(msg) # print "update" def removeNode(self,args,BSSID, kind): msg = OSCMessage("/remove") msg.append(kind.strip()) msg.append(args) msg.append(BSSID.strip()) self.client.send(msg) def closeConnection(self): self.client.send( OSCMessage("/quit", args ) )
class osc_sender_t: def __init__(self, server, port): self.client = OSCClient() self.client.connect((server, port)) self.need_send_names = SEND_NAMES def send_data(self, data): msg = OSCMessage("/wek/inputs") for k, v in data.items(): if k.endswith("_flag"): msg.append(v) else: msg.append([v[0], v[1], v[2]]) self._send(msg) def send_DTW_record(self, cls): msg = OSCMessage("/wekinator/control/startDtwRecording") msg.append(int(cls)) self._send(msg) def send_DTW_stop(self): msg = OSCMessage("/wekinator/control/stopDtwRecording") self._send(msg) def send_run(self): msg = OSCMessage("/wekinator/control/startRunning") self._send(msg) def send_stop(self): msg = OSCMessage("/wekinator/control/stopRunning") self._send(msg) def send_names(self, data): if self.need_send_names: self.need_send_names = False msg = OSCMessage("/wekinator/control/setInputNames") for k, v in data.items(): if k.endswith("flag"): msg.append(k) else: msg.append(k + "_x") msg.append(k + "_y") msg.append(k + "_z") self._send(msg) def _send(self, msg): try: self.client.send(msg) except OSCError: pass
class StreamerOSC(plugintypes.IPluginExtended): """ Relay OpenBCI values to OSC clients Args: port: Port of the server ip: IP address of the server address: name of the stream """ def __init__(self, ip='localhost', port=12345, address="/openbci"): # connection infos self.ip = ip self.port = port self.address = address # From IPlugin def activate(self): if len(self.args) > 0: self.ip = self.args[0] if len(self.args) > 1: self.port = int(self.args[1]) if len(self.args) > 2: self.address = self.args[2] # init network print "Selecting OSC streaming. IP: ", self.ip, ", port: ", self.port, ", address: ", self.address self.client = OSCClient() self.client.connect( (self.ip, self.port) ) # From IPlugin: close connections, send message to client def deactivate(self): self.client.send(OSCMessage("/quit") ) # send channels values def __call__(self, sample): mes = OSCMessage(self.address) mes.append(sample.channel_data) # silently pass if connection drops try: self.client.send(mes) except: return def show_help(self): print """Optional arguments: [ip [port [address]]]
class StreamerOSC(plugintypes.IPluginExtended): """ Relay OpenBCI values to OSC clients Args: port: Port of the server ip: IP address of the server address: name of the stream """ def __init__(self, ip='localhost', port=12345, address="/openbci"): # connection infos self.ip = ip self.port = port self.address = address # From IPlugin def activate(self): if len(self.args) > 0: self.ip = self.args[0] if len(self.args) > 1: self.port = int(self.args[1]) if len(self.args) > 2: self.address = self.args[2] # init network print "Selecting OSC streaming. IP: ", self.ip, ", port: ", self.port, ", address: ", self.address self.client = OSCClient() self.client.connect((self.ip, self.port)) # From IPlugin: close connections, send message to client def deactivate(self): self.client.send(OSCMessage("/quit")) # send channels values def __call__(self, sample): mes = OSCMessage(self.address) mes.append(sample.channel_data) # silently pass if connection drops try: self.client.send(mes) except: return def show_help(self): print """Optional arguments: [ip [port [address]]]
def main(args): # Defaults # Change prefix if you always want to prefix something to the command # Ex: prefix = "/eos/key/" # This would allow you to send abbreviated commands from the command line prefix = "" command = "preload" HOST = "192.168.1.8" PORT = 3032 if len(args) == 3: command = args[0] HOST = args[1] PORT = int(args[2]) elif len(args) == 2: command = args[0] HOST = args[1] elif len(args) == 1: command = args[0] elif len(args) > 3: print "Usage:" print " python send.py [message] [host] [port]" errorPrint("send.py accepts at most 3 arguments.\n%s were provided." % len(args)) client = OSCClient() client.connect((HOST, PORT)) # Check for reserved commands that should do nothing but connect if (command != "preload" and command != "connect"): msg = OSCMessage(prefix + command) client.send(msg) print print "Sent '%(command)s' to %(HOST)s[%(PORT)d]." % locals() print else: print print "Preloaded. No message sent." print client.close() exit()
class Renoise(object): def __init__(self, address): self.client = OSCClient() self.client.connect(address) def panic(self): self.send_osc('/renoise/transport/panic') def note_on(self, instrument, track, note, velocity): self.send_osc('/renoise/trigger/note_on', instrument, track, note, velocity) def note_off(self, instrument, track, note): self.send_osc('/renoise/trigger/note_off', instrument, track, note) def send_osc(self, path, *args): msg = OSCMessage(path) map(msg.append, args) self.client.send(msg)
def trajectory_callback(path, tags, args, source): trajectory = args[0] tokens = trajectory.split(";") tPoints = [] for t in tokens[:-1]: print t tPoints.append(map(lambda x: int(x), t.split(","))) client = OSCClient() client.connect((source[0], 8001)) client.send(OSCMessage("/busy")) shuffle(tPoints) print "Executing", tPoints createPath(tPoints) client = OSCClient() client.connect((source[0], 8001)) client.send(OSCMessage("/noBusy"))
def on_data(self, data): #print(data) duration = 0 try: all_data = json.loads(data) tweet = all_data["text"] split_tweet = tweet.split(' ') first_word = split_tweet[0] if first_word == 'RT': first_word = split_tweet[1] num = 0 for char in first_word: num += ord(char) length_of_tweet = len(split_tweet)/40.0 duration = length_of_tweet * 1000 #print duration sharp_freqs = [185, 207.65, 233.08, 261.63, 277.18, 311.13, 349.23,] freqs = [174.61, 196, 220, 246.94, 261.63, 293.66, 329.62, 349.23, ]#369.99, 391.96, 415.30, 440, 466.16, 493.88, 523.25] note = num % 7 freq = 0 if '#' in tweet: freq = sharp_freqs[note] else: freq = freqs[note] except UnicodeEncodeError: duration = 500 client = OSCClient() client.connect(("localhost", 54345)) ### Create a bundle: bundle = OSCBundle() bundle.append({'addr': "/frequency", 'args':[freq]}) #bundle.append({'addr': "/amplitude", 'args':[52]}) #bundle.append({'addr': "/envelope/line", 'args:['}) bundle.append({'addr': "/envelope/line", 'args': [10., 20, 0., duration]}) client.send(bundle) time.sleep(duration/1000) return(True)
class OSCServer(object): def __init__(self, ip, port,address="/openbci"): self.ip = ip self.port = port self.address = address # init network print "Selecting OSC streaming. IP: ", self.ip, ", port: ", self.port, ", address: ", self.address self.client = OSCClient() self.client.connect( (self.ip, self.port) ) def handle_sample(self, sample): mes = OSCMessage(self.address) mes.append(sample.channel_data) # silently pass if connection drops try: self.client.send(mes) except: return
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 ) )
def step_impl(context, host, port, flt_one,flt_two): client = OSCClient() client.connect((host, int(port))) if rep > 2: for i in range(rep): if flt_two > 0.0: client.send(OSCMessage(['/test', flt_one, flt_two])) else: client.send(OSCMessage('/test', flt_one)) else: if flt_two > 0.0: client.send(OSCMessage(['/test', flt_one,flt_two])) else: client.send(OSCMessage(['/test', flt_one]))
class OscProxyClient(object): def __init__(self, remote_osc_address, json_to_osc_q, osc_command_name, bridge=None, *args, **kwargs): self.remote_osc_address = remote_osc_address self.json_to_osc_q = json_to_osc_q self.osc_client = OSCClient() self.osc_client.connect(remote_osc_address) self.osc_command_name = osc_command_name self.bridge = bridge def serve_forever(self): for msg in self.json_to_osc_q: osc_msg = OSCMessage(self.osc_command_name) osc_msg.append(msg[0]) #HTTP verb osc_msg.append(msg[1]) #HTTP path osc_msg.append(msg[2]) #content self.osc_client.send(osc_msg) def close(self): self.osc_client.close()
def sendOSC(self): """ Send out some OSC using the values taken from the UI. """ destHost = str(self.destEdit.displayText()) destPort = int(self.portEdit.displayText()) address = self.oscAddrEdit.displayText() type = self.dataCombo.currentText() payload = self.payLoadEdit.displayText() # TODO validate this data. oscClient = OSCClient() oscClient.connect((destHost,destPort)) msg = OSCMessage(address) if type == "Integer": msg.append(int(payload), "i") elif type == "Float": msg.append(float(payload), "f") elif type == "String": msg.append(str(payload), "s") elif type == "OSC Blob": msg.append(0b001100, "b") try: oscClient.send(msg) except Exception: print Exception if debug: print "Sending OSC\nDestination: %s:%i, Address: %s, Type:%s" %\ (destHost, destPort, address, type)
if __name__ == "__main__": server = OSCServer(("127.0.0.1", 7777)) server.addMsgHandler("/sl", sl_callback) server.addMsgHandler("/sl_len", sl_length) server.addMsgHandler("/state", sl_state) server.addMsgHandler("/sl_pos", sl_pos) server.handle_error = types.MethodType(handle_error, server) client = OSCClient() client.connect(("localhost", 9951)) #soooperlooper default port client2 = OSCClient() client2.connect(("localhost", 8000)) client.send(OSCMessage("/ping", ["localhost:7777", '/sl'])) Soup = SL_global() L0 = Loop() #this should probably be done more dynamically but.... L1 = Loop() L2 = Loop() L3 = Loop() L4 = Loop() L5 = Loop() L6 = Loop() L7 = Loop() looplist = [L0, L1, L2, L3, L4, L5, L6, L7] print looplist
class OBD_Recorder(): def __init__(self, path, log_items): self.port = None self.sensorlist = [] localtime = time.localtime(time.time()) #if don't want to log to file comment the log_file lines filename = path+"car-"+str(localtime[0])+"-"+str(localtime[1])+"-"+str(localtime[2])+"-"+str(localtime[3])+"-"+str(localtime[4])+"-"+str(localtime[5])+".log" self.log_file = open(filename, "w", 128) self.log_file.write("Time,RPM,MPH,Throttle,Load,Fuel Status\n"); for item in log_items: self.add_log_item(item) self.gear_ratios = [34/13, 39/21, 36/23, 27/20, 26/21, 25/22] #log_formatter = logging.Formatter('%(asctime)s.%(msecs).03d,%(message)s', "%H:%M:%S") #open the OSC connection self.client = OSCClient() self.client.connect( ("localhost", 9001) ) self.client.send( OSCMessage("/start") ) def connect(self): portnames = scanSerial() #portnames = ['COM10'] print portnames for port in portnames: self.port = obd_io.OBDPort(port, None, 2, 2) if(self.port.State == 0): self.port.close() self.port = None else: break if(self.port): print "Connected to "+self.port.port.name def is_connected(self): return self.port def add_log_item(self, item): for index, e in enumerate(obd_sensors.SENSORS): if(item == e.shortname): self.sensorlist.append(index) print "Logging item: "+e.name break def record_data(self): if(self.port is None): return None print "Logging started" while 1: localtime = datetime.now() current_time = str(localtime.hour)+":"+str(localtime.minute)+":"+str(localtime.second)+"."+str(localtime.microsecond) log_string = current_time results = {} for index in self.sensorlist: (name, value, unit) = self.port.sensor(index) log_string = log_string + ","+str(value) results[obd_sensors.SENSORS[index].shortname] = value; #send sensor data via OSC message = OSCMessage() message.setAddress("/"+obd_sensors.SENSORS[index].shortname) message.append(value) self.client.send(message) gear = self.calculate_gear(results["rpm"], results["speed"]) log_string = log_string #+ "," + str(gear) #send gear via OSC message = OSCMessage() message.setAddress("/gear") message.append(gear) self.client.send(message) self.log_file.write(log_string+"\n") def calculate_gear(self, rpm, speed): if speed == "" or speed == 0: return 0 if rpm == "" or rpm == 0: return 0 rps = rpm/60 mps = (speed*1.609*1000)/3600 primary_gear = 85/46 #street triple final_drive = 47/16 tyre_circumference = 1.978 #meters current_gear_ratio = (rps*tyre_circumference)/(mps*primary_gear*final_drive) #print current_gear_ratio gear = min((abs(current_gear_ratio - i), i) for i in self.gear_ratios)[1] return gear
class LiveRawAPI(object): """ This is close to live's API objects as possible Of course, they are designed to be manipulated from a patcher, not real code, so a bit more wrapping is in order. To keep everything minimal, this is done in a subclass. """ _incoming = None _handled = True _received = False debug = False def __init__(self, there_host="localhost", there_port=7400, here_host="localhost", here_port=7401, debug=False, *args, **kwargs): super(LiveRawAPI, self).__init__(*args, **kwargs) self.oscserver = OSCServer((here_host, here_port)) self.oscclient = OSCClient() self.oscclient.connect((there_host, there_port)) self.oscserver.addMsgHandler('/response', self._handle_response) self._incoming = [] def raw_query(self, *args): """Posts a query, waits for a response. Returns it. Note that state is fragile here, so you'd better be sure that there will be a response, or it will hang waiting.""" self.oscclient.send(OSCMessage('/query', args)) return self.handle_request() def raw_call(self, *args): """Posts a call, returns nothing. Note that state is fragile here, so you'd better be sure that there will be no response, or you won't know what returned what.""" self.oscclient.send(OSCMessage('/query', ['path', 'getpath'])) def _handle_response(self, path, tags, args, source): """private callback to handle OSC responses. Sets state.""" if self.debug: print "callback", path, args, source self._incoming.append(args) self._received = True def handle_request(self): """hack to handle asynchronous calls: 1 try to get something returned and tacked onto the class. 2 Return it and reset. This is completely f****d at the momenl I can't make timeouts work in any usable fashion.""" try: self.oscserver.handle_request() while self._received: self._received = False self.oscserver.handle_request() _incoming = self._incoming return _incoming finally: self._incoming = [] self._received = False def close(self): self.oscserver.close() ### more structured access involves navigating places with the path object def goto(self, *args): resp = self.raw_query('path', 'goto', *args) prefix, path = resp[1], resp[2:] #sanity check that we are getting the right message assert prefix == 'path' self.path = path def path(self, *args): return self.goto(*args) def getchildren(self): resp = self.raw_query('path', 'getchildren') return resp[1:] def getcount(self): resp = self.raw_query('path', 'getcount') return resp[1:]
s = socket(AF_INET, SOCK_DGRAM) s.bind(('', PORT)) while 1: data, wherefrom = s.recvfrom(1500, 0) #print data strsplit = data.split(',') kind = strsplit[0] val = strsplit[1] print kind, val if kind == 'TEMP': client.send( OSCMessage("/shast/beebox/tmp", val)) elif kind == 'HUM': client.send( OSCMessage("/shast/beebox/hum", val)) elif kind == 'LIGHT': client.send( OSCMessage("/shast/beebox/lht", val)) elif kind == 'MOIST': client.send( OSCMessage("/shast/beebox/moi", val)) #time.sleep(2) #sys.stderr.write(repr(wherefrom) + '\n') #sys.stdout.write('->' + data)
import signal import flicklib from time import sleep from curses import wrapper from os import system from OSC import OSCClient, OSCMessage client = OSCClient() client.connect(("192.168.0.15", 4559)) client.send(OSCMessage("HI")) client.send(OSCMessage("POOP")) client.send(OSCMessage("THISISSHIT")) client.send(OSCMessage("NEWTOTHIS"))
#midi_note = to_scale([0, 2, 4, 7, 9], midi_note) midi_note = to_scale([0, 2, 4, 7, 9, 11], midi_note) midi_note += random.random() * 0.1 midi_vel = 40 #5 + min(58, 58 * (len(neighbors) / 800.0)) #64.0 * (1 - math.exp(-(len(neighbors))) / 0.5) prev_midi_notes.append(midi_note) # Send OSC messages. # Send current note. # print 'midi note', midi_note if midi_note > 127: print 'Can\'t hear', midi_note oscMsg[0] = midi_note oscMsg[1] = midi_vel if not skip: client.send(oscMsg) # Update graph to be visualized. fake_timestamp = time.time() for src in dst_to_srcs[dst]: edges_with_fake_timestamps.append((src, dst, fake_timestamp)) # Sustain notes. time.sleep(SUSTAIN_SECONDS) # Turn off previous notes. for prev_midi_note in prev_midi_notes: oscMsg[0] = prev_midi_note oscMsg[1] = 0 client.send(oscMsg) prev_midi_notes = []
#HOORAY! It works... now generate some random text. #First, pick a random word from words and append it to our text data = [] currentWord = choice(words) currentChoices = unigrams[currentWord] text = "" text = currentWord for i in range(1000): #Pick a random word from that value, the probabliity distribution is implied #print [currentWord, countDuplicatesInList(currentChoices)] data.append([currentWord, countDuplicatesInList(currentChoices)]) currentWord = choice(unigrams[currentWord]) currentChoices = unigrams[currentWord] text= text + " " + currentWord client.send( OSCMessage(str("%"+currentWord) )) client .send(OSCMessage("@" + str(currentChoices))) client.send(OSCMessage("MAX")) #print data #write text to file #f = open("words.txt", "w") #f.write(str(data)) #print the text #print text
diffZ = 0 prevX = 0 prevY = 0 prevZ = 0 #while row_cnt < 100: while True: data1 = BLE_Scratch1_characteristics[0].read() data2 = BLE_Scratch2_characteristics[0].read() data3 = BLE_Scratch3_characteristics[0].read() newX = ord(data1[0]) newY = ord(data2[0]) newZ = ord(data3[0]) diffX = diff(prevX, newX) diffY = diff(prevY, newY) diffZ = diff(prevZ, newZ) prevX = newX prevY = newY prevZ = newZ print str(diffX) + " : " + str(diffY) + " : " + str(diffZ) client.send(OSCMessage(str(diffX) + ":" + str(diffY) + ":" + str(diffZ))) row_cnt += 1 #time.sleep(1) BLE_device.disconnect()
class StreamerOSC(): def __init__(self, ip='localhost', port=12345, address="/openbci"): # connection infos self.ip = ip self.port = port self.address = address self.client = OSCClient() self.client.connect((self.ip, self.port)) self.board = bci.OpenBCIBoard() # send channels values def send(self, sample): mes = OSCMessage(self.address) mes.append(sample.channel_data) try: self.client.send(mes) except: return def begin(self): print("--------------INFO---------------") print ("Commands:\n"+ "/start to begin\n" + "/stop to stop streaming.\n" + \ "/exit to end the program") print("\n-------------BEGIN---------------") # Init board state # s: stop board streaming; v: soft reset of the 32-bit board (no effect with 8bit board) s = 'sv' # Tell the board to enable or not daisy module if self.board.daisy: s = s + 'C' else: s = s + 'c' # d: Channels settings back to default s = s + 'd' while (s != "/exit"): # Send char and wait for registers to set if (not s): pass elif ("help" in s): print ("View command map at:" + \ "http://docs.openbci.com/software/01-OpenBCI_SDK.\n" +\ "For user interface: read README or view" + \ "https://github.com/OpenBCI/OpenBCI_Python") elif self.board.streaming and s != "/stop": print( "Error: the board is currently streaming data, please type '/stop' before issuing new commands." ) else: # read silently incoming packet if set (used when stream is stopped) flush = False if ('/' == s[0]): s = s[1:] rec = False # current command is recognized or fot if ("T:" in s): lapse = int(s[string.find(s, "T:") + 2:]) rec = True elif ("t:" in s): lapse = int(s[string.find(s, "t:") + 2:]) rec = True else: lapse = -1 if ("start" in s): # start streaming in a separate thread so we could always send commands in here boardThread = threading.Thread( target=self.board.start_streaming, args=(self.send, -1)) boardThread.daemon = True # will stop on exit try: boardThread.start() print("Streaming data...") except: raise rec = True elif ('test' in s): test = int(s[s.find("test") + 4:]) self.board.test_signal(test) rec = True elif ('stop' in s): self.board.stop() rec = True flush = True if rec == False: print("Command not recognized...") elif s: for c in s: if sys.hexversion > 0x03000000: self.board.ser.write(bytes(c, 'utf-8')) else: self.board.ser.write(bytes(c)) time.sleep(0.100) line = '' time.sleep( 0.1) #Wait to see if the board has anything to report while self.board.ser.inWaiting(): c = self.board.ser.read().decode('utf-8', errors='replace') line += c time.sleep(0.001) if (c == '\n') and not flush: # print('%\t'+line[:-1]) line = '' if not flush: print(line) # Take user input #s = input('--> ') if sys.hexversion > 0x03000000: s = input('--> ') else: s = raw_input('--> ')
class DecoderThread(Thread): def __init__(self, pcapObj): self.searchTerm = 'commands' self.hostDict = {} self.flowDict = {} self.arbitraryChunkedLength = 30000 # as length of chunked tranfers can not be measured, we will provide an artibrary length for now # OSC functionality (multicasting for now) sendAddress = '127.0.0.1', 57120 self.oscClient=OSCClient() self.oscClient.connect(sendAddress) # Query the type of the link and instantiate a decoder accordingly. datalink = pcapObj.datalink() if pcapy.DLT_EN10MB == datalink: self.decoder = EthDecoder() elif pcapy.DLT_LINUX_SLL == datalink: self.decoder = LinuxSLLDecoder() else: raise Exception("Datalink type not supported: " % datalink) self.pcap = pcapObj Thread.__init__(self) def run(self): # Sniff ad infinitum. # PacketHandler shall be invoked by pcap for every packet. self.pcap.loop(0, self.packetHandler) def packetHandler(self, hdr, data): # Use the ImpactDecoder to turn the rawpacket into a hierarchy of ImpactPacket instances. eth = self.decoder.decode(data) ip = eth.child() tcp = ip.child() src = (ip.get_ip_src(), tcp.get_th_sport() ) dst = (ip.get_ip_dst(), tcp.get_th_dport() ) self.detectHTTP(tcp, src, dst) def detectHTTP(self, tcp, src, dst): packetString = tcp.get_data_as_string() srcIp = src[0] dstIp = dst[0] self.detectRequestOrNewResponseOrExistingResponse(packetString, src, dst, tcp) def detectRequestOrNewResponseOrExistingResponse(self, packetString, src, dst, tcp): request = HTTPRequest(packetString) if request.error_code is None: # detect request self.parseRequest(request, src, dst) elif packetString[:8] == "HTTP/1.1": # detect response # only pass if a request was sent flowKey = (src, dst) if flowKey in self.hostDict: self.parseNewResponse(packetString, src, dst, tcp) else: flowKey = (src, dst) if flowKey in self.flowDict: # continue if packet is a continuation of an existing response body = packetString # with an existing response the body is the entire packetstring self.parseExistingResponse(flowKey, body, src, dst, tcp) def parseRequest(self, request, src, dst): if request.command == 'GET' and request.request_version == 'HTTP/1.1': # store the host and path related to this request by unique key for later lookup: self.hostDict[(dst, src)] = {} self.hostDict[(dst, src)]['host'] = request.headers['host'] self.hostDict[(dst, src)]['path'] = request.path def parseNewResponse(self, packetString, src, dst, tcp): responseCode = packetString[9:12] if responseCode == '200': # just okay responses for now if '\r\n\r\n' in packetString: # only proceed if the response has a body bodyIndex = packetString.index('\r\n\r\n') + 4 body = packetString[bodyIndex:] socket = FakeSocket(packetString) response = HTTPResponse(socket) response.begin() headerArray = response.getheaders() for item in headerArray: flowKey = (src, dst) if item[0] == 'content-type' and 'text/html' in item[1]: # accept any kind of text content for item in headerArray: if item[0] == 'content-length': length = int(item[1]) self.parseFixedLengthResponse(flowKey, body, length, src, dst, tcp, responseCode) elif item[0] == 'transfer-encoding' and item[1] == 'chunked': print 'found chunked' self.parseChunkedResponse(flowKey, body, src, dst, tcp, responseCode) else: print "body not found" def parseFixedLengthResponse(self, flowKey, body, length, src, dst, tcp, responseCode): self.flowDict[flowKey] = {'body': body, 'type': 'fixedLength', 'length': length} self.doStart(flowKey, body, src, dst, tcp, responseCode, 'fixedLength') contentLength = self.arbitraryChunkedLength progress = float(len(body)) / float(contentLength) packetContentLength = progress searchResults = self.bodySearch(body, contentLength) self.sendInfoAboutThisPacket(body, progress, packetContentLength, searchResults) def parseChunkedResponse(self, flowKey, body, src, dst, tcp, responseCode): self.flowDict[flowKey] = {'body': body, 'type': 'chunked'} self.doStart(flowKey, body, src, dst, tcp, responseCode, 'chunked') contentLength = self.flowDict[flowKey]['length'] progress = float(len(body)) / float(contentLength) packetContentLength = progress searchResults = self.bodySearch(body, contentLength) self.sendInfoAboutThisPacket(body, progress, packetContentLength, searchResults) def parseExistingResponse(self, flowKey, body, src, dst, tcp): if self.flowDict[flowKey]['type'] == 'fixedLength': contentLength = self.flowDict[flowKey]['length'] progress, packetContentLength = self.accumulateBodyAndReturnPacketPosition(flowKey, body, contentLength) mappedSearchResults = self.bodySearch(body, contentLength) self.sendInfoAboutThisPacket(body, progress, packetContentLength, mappedSearchResults) self.detectFixedLengthEnd(flowKey, src, dst) elif self.flowDict[flowKey]['type'] == 'chunked': contentLength = self.arbitraryChunkedLength progress, packetContentLength = self.accumulateBodyAndReturnPacketPosition(flowKey, body, contentLength) searchResults = self.bodySearch(body, contentLength) self.sendInfoAboutThisPacket(body, progress, packetContentLength, mappedSearchResults) self.detectChunkedEnd(packetString, src, dst) def accumulateBodyAndReturnPacketPosition(self, flowKey, body, contentLength): existingBody = self.flowDict[flowKey]['body'] newBody = self.flowDict[flowKey]['body'] = existingBody + body progress = float(len(newBody)) / float(contentLength) packetContentLength = float(len(body)) / float(contentLength) return progress, packetContentLength def sendInfoAboutThisPacket(self, body, progress, packetContentLength, mappedSearchResults): # call or response - relevant? self.oscSender('/progress', [progress]) # if mappedSearchResults: # if list is not empty # self.oscSender('/searchResults', mappedSearchResults) # self.oscSender('/bodyLength', [packetContentLength]) # self.oscSender('/body', [body]) def detectFixedLengthEnd(self, flowKey, src, dst): accumulatedBodyLength = len(self.flowDict[flowKey]['body']) contentLength = self.flowDict[flowKey]['length'] if accumulatedBodyLength == contentLength: self.doStop(src, dst) def detectChunkedEnd(self, body, src, dst): if '0\r\n\r\n' in body: # doesn't always work self.doStop(src, dst) def doStart(self, flowKey, body, src, dst, tcp, responseCode, encodingType): host = self.hostDict[(src, dst)]['host'] path = self.hostDict[(src, dst)]['path'] destinationIP = dst[0] sourceIP = src[0] destinationPort = dst[1] scaledDestinationPort = self.scale(destinationPort, 49152, 65535, 0, 1) # no use to have the source Port as it will always be 80 (http) self.oscSender('/start', [responseCode, host, path[0:20], destinationIP, sourceIP, destinationPort, encodingType]) def doStop(self, src, dst): host = self.hostDict[(src, dst)]['host'] path = self.hostDict[(src, dst)]['path'] del self.hostDict[(src, dst)] # need to do this? del self.flowDict[(src, dst)] self.oscSender('/stop', [host, path]) def bodySearch(self, body, contentLength): searchResults = [m.start() for m in re.finditer(self.searchTerm, body)] mappedSearchResults = [float(item)/float(contentLength) for item in searchResults] return mappedSearchResults def oscSender(self, addr, params): msg = OSCMessage() msg.setAddress(addr) if params is not None: for param in params: msg.append(param) print "sending: " + str(msg) + " to: " + str(self.oscClient) # do not indent this line! try: self.oscClient.send(msg) except OSCClientError: # could explicitly try to detect errno 61 here print "WARNING: cannot send to SuperCollider" def scale(self, value, leftMin, leftMax, rightMin, rightMax): leftSpan = leftMax - leftMin rightSpan = rightMax - rightMin valueScaled = float(value - leftMin) / float(leftSpan) return rightMin + (valueScaled * rightSpan)
PORT = 50000 client = OSCClient() client.connect(("127.0.0.1", 22243)) s = socket(AF_INET, SOCK_DGRAM) s.bind(('', PORT)) while 1: data, wherefrom = s.recvfrom(1500, 0) #print data strsplit = data.split(',') kind = strsplit[0] val = strsplit[1] print kind, val if kind == 'TEMP': client.send(OSCMessage("/shast/beebox/tmp", val)) elif kind == 'HUM': client.send(OSCMessage("/shast/beebox/hum", val)) elif kind == 'LIGHT': client.send(OSCMessage("/shast/beebox/lht", val)) elif kind == 'MOIST': client.send(OSCMessage("/shast/beebox/moi", val)) #time.sleep(2) #sys.stderr.write(repr(wherefrom) + '\n') #sys.stdout.write('->' + data)
# ........ while True: # --- Bitalino --- millis = time.clock() millis = format(millis, '.3f') millis = str(millis) dataAcquired = device.read(nSample) SeqN = dataAcquired[0, 4:8] SeqN = str(SeqN) physio_data = SeqN.split() ecgBitalino = physio_data[2] participant1.processECG(ecgBitalino) ecgBitalino = physio_data[3] participant2.processECG(ecgBitalino) # ------ if time.time() - time_send >= 0.5: #print("SEND MESSAGE") if (participant1.hr.size > 1 and participant2.hr.size > 1): print("SEND MESSAGE") msg = OSCMessage("/hr/" + str(int(participant1.hr[len(participant1.hr) - 1])) + "/" + str(int(participant2.hr[len(participant2.hr) - 1]))) processing.send(msg) time_send = time.time()
chanHist = [[0 for x in range(0)] for x in range(6)] N = 128 #We always take 128 chunks so we get to slighly above 60hz T = 1.0 / (N*1) # We know that the emotive delivers 128 samples persecond count=0 try: while True: packet = headset.dequeue() cCount=0 for k,v in packet.sensors.iteritems(): if ((k in SENSOR_LIST) and ('value' in v) and ('quality' in v)): chanHist[cCount].append(v['value']) cCount += 1 mOscMessage.clear("/emokit/"+k+"/") mOscMessage.append(v['value']) mOscMessage.append(v['quality']) mOscClient.send(mOscMessage) count += 1 if count >=N: for i in range(0,len(chanHist)): output=[1 for x in range(4)] norm=[1 for x in range(4)] yf = np.abs(scipy.fftpack.fft(chanHist[i])) n = len(chanHist[i]) freq = np.fft.fftfreq(n, T) xf = np.linspace(0.0, 1.0/(2.0*T), N/2) j=2 while freq[j+1]>freq[j] : if round(freq[j])>4 and round(freq[j])<7 : norm[0]+=1 output[0]+=yf[j] elif round(freq[j])>8 and round(freq[j])<12 :
#!/usr/local/bin/python from OSC import OSCClient, OSCMessage import time, math period = 1 param_count = 9 param_low = 0 param_high = 127 frequency = 30 client = OSCClient() client.connect( ("127.0.0.1", 50000) ) def oscillate(index): return int( (param_high + param_low) / 2.0 + ( ( param_high - param_low ) / 2.0 ) * math.sin(index + time.time() / period) ) while True: values = map(lambda i: oscillate(i), range(0, param_count)) print values message = OSCMessage("/fish") message += values client.send( message ) time.sleep(1.0 / frequency)
while True: Tuple = Camera.read() if Tuple[0]: Img = Tuple[1] GImg = cv2.cvtColor(Img, cv2.COLOR_BGR2GRAY) if len(Last) == 0: Last = GImg continue if (Height == 0 or Width == 0): Height, Width = GImg.shape Prev = getFixedPoints(Height, Width) client.send( OSCMessage( "/config", ((Height, Width), Span, MinThreshold, MaxThreshold))) verbosePrint(Height, Width) Vec = [] Next = cv2.calcOpticalFlowPyrLK(Last, GImg, Prev, None, **LkParam)[0] for I in range(len(Next)): Pt1 = (Prev[I, 0, 0], Prev[I, 0, 1]) Pt2 = (Next[I, 0, 0], Next[I, 0, 1]) Dist = distance(Pt1, Pt2) if (Dist > MinThreshold and Dist < MaxThreshold): Vec.append((Pt1, Dist, getAngle(Pt1, Pt2))) if ColorState: cv2.circle(Img, Pt1, int(Dist), color=getDistColor(Dist))
#osx only #make sure to install pyosc import subprocess from OSC import OSCClient, OSCMessage, OSCClientError from time import sleep cli= OSCClient() cli.connect(('127.0.0.1', 12345)) #send address while True: a= subprocess.Popen('/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I', shell=True, stdout=subprocess.PIPE).stdout.read() a= a.split() rssi= int(float(a[1])) noise= int(float(a[5])) msg= OSCMessage() msg.setAddress('/wifi') msg.append(rssi) msg.append(noise) sleep(0.1) #update rate try: cli.send(msg) except OSCClientError: print 'could not send to '+str(cli.client_address) sleep(1)
T = 1.0 / (N * 1 ) # We know that the emotive delivers 128 samples persecond count = 0 try: while True: packet = headset.dequeue() cCount = 0 for k, v in packet.sensors.iteritems(): if ((k in SENSOR_LIST) and ('value' in v) and ('quality' in v)): chanHist[cCount].append(v['value']) cCount += 1 mOscMessage.clear("/emokit/" + k + "/") mOscMessage.append(v['value']) mOscMessage.append(v['quality']) mOscClient.send(mOscMessage) count += 1 if count >= N: for i in range(0, len(chanHist)): output = [1 for x in range(8)] norm = [1 for x in range(8)] yf = np.abs(scipy.fftpack.fft(chanHist[i])) n = len(chanHist[i]) freq = np.fft.fftfreq(n, T) xf = np.linspace(0.0, 1.0 / (2.0 * T), N / 2) j = 2 while freq[j + 1] > freq[j]: # delta 0.5 - 3 hz if round(freq[j]) > 0.5 and round(freq[j]) < 3: norm[0] += 1 output[0] += yf[j]
def __init__(self, title, rating, genre): self.title = title self.timeElapsed = 0 self.rating = rating self.genre = genre if title == "The Notebook": self.genre = "Romance" self.rating = rating.encode("ascii") self.rating = float(self.rating) self.octave = 1.0 self.pianoClient = OSCClient() self.pianoClient2 = OSCClient() self.pianoClient3 = OSCClient() self.pianoClientAlternate = OSCClient() self.pianoClientAlternate2 = OSCClient() self.pianoClientAlternate3 = OSCClient() self.envelopeList = [1.0, 20, 0.0, 1000] self.buffer = False self.pianoClient.connect(("localhost", 54360)) self.pianoClient2.connect(("localhost", 54361)) self.pianoClient3.connect(("localhost", 54362)) self.pianoClientAlternate.connect(("localhost", 54370)) self.pianoClientAlternate2.connect(("localhost", 54371)) self.pianoClientAlternate3.connect(("localhost", 54372)) initialDingClient = OSCClient() initialDingClient.connect(("localhost", 54345)) ### Initial Ding Bundle: print ("Turning on the movie") initialDing = OSCBundle() initialDing.append({"addr": "/frequency", "args": [440.0]}) initialDing.append({"addr": "/envelope/line", "args": [1.0, 20, 0.0, 1000]}) self.timeElapsed += 1.02 initialDingClient.send(initialDing) print ("Curtains Openning") self.timeElapsed += 16 # note this currently plays right after the initial ding time.sleep(self.timeElapsed) self.timeElapsed = 0 for genre in Music.genreList: if self.genre == genre: self.envelopeList = Music.genreList[genre] for genre in Music.extraGenreList: if self.genre == genre: self.buffer = True startTime = timeit.timeit() im = Image.open("keyboard.jpg") im.show() self.pianoInstrument() endTime = timeit.timeit() self.timeElapsed += startTime - endTime self.timeElapsed += 0.5 time.sleep(self.timeElapsed) self.timeElapsed = 0 if self.rating < 2: print ("Yikes...") sadClient = OSCClient() sadClient.connect(("localhost", 54346)) # Sad Ding Bundle: sadDing = OSCBundle() sadDing.append({"addr": "/start", "args": [1]}) sadClient.send(sadDing) self.timeElapsed += 4.25 else: print ("TADA") tadaClient = OSCClient() tadaClient.connect(("localhost", 54380)) tada = OSCBundle() tada.append({"addr": "/amplitude", "args": [self.rating / 10]}) tada.append({"addr": "/startValue", "args": ["start", 0]}) tadaClient.send(tada) self.timeElapsed += 1.5 time.sleep(self.timeElapsed) print ("APPLAUSE") # applause based on rating endingClient = OSCClient() endingClient.connect(("localhost", 54350)) ending = OSCBundle() ending.append({"addr": "/amplitude", "args": [self.rating / 10]}) durationOfApplause = ((10 - self.rating) / 10) * 6000 ending.append({"addr": "/startValue", "args": ["start", durationOfApplause]}) endingClient.send(ending)
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])) except: pass print "quiting..." except KeyboardInterrupt: print "quiting..." server.close() p.stop() GPIO.cleanup()
win_s = 1024 * 2 # fft size hop_s = win_s // 2 # hop size tempo_o = tempo("default", win_s, hop_s, samplerate) print("*** starting recording") while True: try: audiobuffer = stream.read(buffer_size) signal = np.fromstring(audiobuffer, dtype=np.float32) is_beat = tempo_o(signal) if is_beat and is_beat[0] > 0: print('tick') try: msg = OSCMessage("/tick") client.send(msg) except: print("Couldnt send OSC message, server not running?") total_frames += buffer_size except KeyboardInterrupt: print("*** Ctrl+C pressed, exiting") break print("*** done recording") stream.stop_stream() stream.close() p.terminate()
#!/usr/bin/env python # http://shinybit.github.io/sending-osc-messages-from-pythonista/ # https://gist.github.com/shinybit/3d7e0fc7e62887ab48e931af1d4c0986 # Get pyOSC here: https://trac.v2.nl/wiki/pyOSC # The GitHub-hosted version of pyOSC is for Python 3 which isn't supported by Pythonista at the moment from OSC import OSCClient, OSCMessage client = OSCClient() client.connect(("192.168.43.120", 8000)) msg = OSCMessage("/msg/notes") msg.append([50, 60]) client.send(msg) msg.clearData() msg.append(["C3", 127]) client.send(msg) client.send(OSCMessage("/quit"))
#!/usr/bin/env python3 from OSC import OSCClient, OSCMessage client = OSCClient() client.connect(("localhost", 7110)) client.send(OSCMessage("/user/1", [1.0, 2.0, 3.0])) client.send(OSCMessage("/user/2", [2.0, 3.0, 4.0])) client.send(OSCMessage("/user/3", [2.0, 3.0, 3.1])) client.send(OSCMessage("/user/4", [3.2, 3.4, 6.0])) client.send(OSCMessage("/quit"))
import time from OSC import OSCClient, OSCMessage client = OSCClient() client.connect( ("192.168.11.140", 9000) ) value=0 while True: msg=OSCMessage("/pupil/norm_pos") msg.append(value) value+=0.001 client.send( msg ) time.sleep(0.001)
BASE_URL = 'http://localhost:3000/stats' WIKIPEDIAS = ["ar-wikipedia", "bg-wikipedia", "ca-wikipedia", "cs-wikipedia", "da-wikipedia", "de-wikipedia", "el-wikipedia", "en-wikipedia", "eo-wikipedia", "es-wikipedia", "eu-wikipedia", "fa-wikipedia", "fi-wikipedia", "fr-wikipedia", "he-wikipedia", "hu-wikipedia", "id-wikipedia", "it-wikipedia", "ja-wikipedia", "ko-wikipedia", "lt-wikipedia", "ms-wikipedia", "nl-wikipedia", "no-wikipedia", "pl-wikipedia", "pt-wikipedia", "ro-wikipedia", "ru-wikipedia", "sk-wikipedia", "sl-wikipedia", "sv-wikipedia", "tr-wikipedia", "uk-wikipedia", "vi-wikipedia", "vo-wikipedia", "zh-wikipedia"] if __name__ == '__main__': client = OSCClient() client.connect(('localhost', 9999)) while 1: beats = [] for wp in WIKIPEDIAS: url = '%s/%s/60000.json' % (BASE_URL, wp) r = requests.get(url) beats.append(int(r.content)) #sorted_beats = sorted(beats, reverse=True)[:20] sorted_beats = [b for b in beats if b > 1] print sorted_beats for i in range(len(sorted_beats)): m = OSCMessage('/wikibeat/%s' % str(i + 1)) m.append(sorted_beats[i]) client.send(m) time.sleep(1)
# Creamos el objeto "Cliente" client = OSCClient() # Realizamos la conexion client.connect(client_IP) connected = True except: print("Esperando cliente OS ") print("Sending OSC messages to: " + str(client_IP)) try: while 1: # endless loop try: msg = OSCMessage( ) # we reuse the same variable msg used above overwriting it msg.setAddress("/ping") print "/ping" client.send( msg) # now we dont need to tell the client the address anymore except: print("Sin conexion OSC") time.sleep(timerPing) time.sleep(timerPing) except KeyboardInterrupt: print "Closing OSCClient" client.close() print "Done"
calibration_position = args[1:] print 'calibration step: %d, ' % (calibration_step ), 'position' ,calibration_position def quit_callback(path, tags, args, source): global run run = False server.addMsgHandler( "/calibration/flag", calibration_flag_callback ) server.addMsgHandler( "/calibration/step", calibration_step_callback ) server.addMsgHandler( "/quit", quit_callback ) 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: sleep(0.02) each_frame() if eye_tracking_flag: eye_tracking_pos = [0.1, -90.1] #debug client.send( OSCMessage("/eye_tracking/position", eye_tracking_pos ) ) server.close()