def myTest(): """ a simple function that creates the necesary sockets and enters an endless loop sending and receiving OSC """ osc.init() import time i = 0 while 1: i = i % 4 print i osc.sendMsg("/x0", [i], "127.0.0.1", 9005) osc.sendMsg("/y0", [i + 1], "127.0.0.1", 9005) osc.sendMsg("/x1", [i + 2], "127.0.0.1", 9005) osc.sendMsg("/y1", [i + 3], "127.0.0.1", 9005) osc.sendMsg("/update", [1], "127.0.0.1", 9005) bundle = osc.createBundle() time.sleep(1) i += 1 osc.dontListen()
def myTest(): """ a simple function that creates the necesary sockets and enters an enless loop sending and receiving OSC """ osc.init() ## osc.createListener() # this defaults to port 9001 as well osc.listen('127.0.0.1', 9001) # bind addresses to functions -> printStuff() function will be triggered everytime a # "/test" labeled message arrives osc.bind(printStuff, "/test") import time # in this example we will have a small delay in the while loop print 'ready to receive and send osc messages ...' while 1: ## osc.sendMsg("/test", [444], "127.0.0.1", 9000) # send normal msg to a specific ip and port osc.sendMsg("/test", [444]) # !! it sends by default to localhost ip "127.0.0.1" and port 9000 # create and send a bundle bundle = osc.createBundle() osc.appendToBundle(bundle, "/test/bndlprt1", [1, 2, 3]) # 1st message appent to bundle osc.appendToBundle(bundle, "/test/bndlprt2", [4, 5, 6]) # 2nd message appent to bundle ## osc.sendBundle(bundle, "127.0.0.1", 9000) # send it to a specific ip and port osc.sendBundle(bundle) # !! it sends by default to localhost ip "127.0.0.1" and port 9000 #osc.getOSC(inSocket) # listen to incomming OSC in this socket time.sleep(0.5) # you don't need this, but otherwise we're sending as fast as possible. osc.dontListen() # finally close the connection bfore exiting or program
def main(): osc.init() i = 0 while(1): osc.sendMsg("/beat",[i],"127.0.0.1",9001) i = i + 1 time.sleep(1)
def on_touch_up(self, touch): if self.mode == 'draw_connection': for m in self.parent.modules: if m.collide_point(touch.x,touch.y) and m != self and m.category != 'controller': # Control connections if self.category == 'controller' and m.category != 'output': if m.category == 'source': inlet_calc = int(round((touch.x - m.x) / ((m.width - 10) / 4.))) if inlet_calc >= 1 and inlet_calc <= 4: inlet = inlet_calc else: inlet = None if m.category == 'effect': inlet_calc = int(round((m.height - (touch.y - m.y)) / (m.height / 5.))) if inlet_calc >= 1 and inlet_calc <= 4: inlet = inlet_calc else: inlet = None if inlet: if [m, inlet] not in self.control_connections: self.control_connections.append([m, inlet]) m.parents.append(self) osc.sendMsg("/connect", [self.category, self.instance, m.category, m.instance, inlet], host, port) # Signal connections if self.category == 'source' or self.category == 'effect': if m.category != 'source': inlet = 0 if [m, inlet] not in self.signal_connections: self.signal_connections.append([m, inlet]) m.parents.append(self) osc.sendMsg("/connect", [self.category, self.instance, m.category, m.instance], host, port) if touch.id in self.touchstarts: self.touchstarts.remove(touch.id) self.mode = 'move' return True
def on_touch_down(self, touch): #Delete connections if touch.is_double_tap: for connection in self.signal_connections: x1,y1,x2,y2 = self.return_connection_coordinates(connection, type='signal') if self.line_collision_with_point(x1, y1, x2, y2, touch.x, touch.y): self.signal_connections.remove([connection[0], connection[1]]) osc.sendMsg("/disconnect", [self.category, self.instance, connection[0].category, connection[0].instance], host, port) for connection in self.control_connections: x1,y1,x2,y2 = self.return_connection_coordinates(connection, type='control') if self.line_collision_with_point(x1, y1, x2, y2, touch.x, touch.y): self.control_connections.remove([connection[0], connection[1]]) osc.sendMsg("/disconnect", [self.category, self.instance, connection[0].category, connection[0].instance, connection[1]], host, port) if self.collide_point(touch.x,touch.y): self.touchstarts.append(touch.id) if touch.is_double_tap: self.parent.remove_widget(self) self.first_x = touch.x self.first_y = touch.y self.first_pos_x = self.x self.first_pos_y = self.y if self.category is not 'output': # Lower section if touch.y < self.y + 20: self.mode = 'draw_connection' self.drag_x = touch.x self.drag_y = touch.y # Middle section else: self.mode = 'move' return True
def write(self, s): if time.time() - self.last_time > 1.2: self.messages_this_second = 0 try: self.messages_this_second += 1 if time.time() - self.last_time > 1.: if self.messages_this_second > 500 and (self.can_omit and throttle_output): message = 'omitted {}'.format(self.messages_this_second - 500) osc.sendMsg(b'/interpreter', [message.encode('utf-8')], port=self.target_port, typehint='b') self.messages_this_second = 0 self.last_time = time.time() if self.messages_this_second > 500 and self.can_omit and throttle_output: return s = self.buffer + s if '\n' in s: lines = s.split('\n') for l in lines[:-1]: self.send_message(l) self.buffer = lines[-1] else: self.buffer = s except KeyboardInterrupt: raise KeyboardInterrupt('interrupted while printing')
def python_fu_sendosc( inImage, inDrawable, bFlatten=True, netAddr="127.0.0.1", port=57120): global outSocket ## save options for use with the guiless version shelf['oscport'] = [port] shelf['oscnetaddr'] = [netAddr] shelf['oscbflatten'] = [bFlatten] width = inDrawable.width height = inDrawable.height if bFlatten == True: inImage.disable_undo() flatImage = inImage.duplicate() flatImage.flatten() pr = flatImage.active_layer.get_pixel_rgn(0,0,width,height,False) else: pr = inDrawable.get_pixel_rgn(0,0,width,height,False) ## start communication and send specs osc.init() osc.sendMsg("/gimp/spec", [width, height, pr.bpp], netAddr, port) ## create an extra socket for the binary messages outSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) prp = pr[0:width,0:height] ## print(osc.hexDump(prp)) gimp.progress_init("Sending image...") ## empirical maximum size: 65487 (2 ** 16 - 49) ## UDP-Datagram-Limit: ## The practical limit for the data length which is imposed by the ## underlying IPv4 protocol is 65,507 bytes. ## http://en.wikipedia.org/wiki/User_Datagram_Protocol#Packet_structure maxSize = 8000 imgSize = width * height * pr.bpp for index in range( int(math.ceil(imgSize / float(maxSize))) ): m = osc.OSCMessage() m.address = "/gimp" m.append(index) if (((index + 1) * maxSize) > imgSize): m.append(prp[(index * maxSize):],'b') else: m.append(prp[(index * maxSize):((index + 1) * maxSize)],'b') outSocket.sendto( m.getBinary(), (netAddr, port)) ## introduce latency to not loose packages time.sleep(0.02) ## end communication osc.sendMsg("/gimp", [-1], netAddr, port) ## clean up if bFlatten == True: inImage.enable_undo() gimp.delete(flatImage)
def sendToneOn(self, tone, freq, gain): unique = self.open.pop() osc.sendMsg('/keydown', [unique, freq, gain], "127.0.0.1", 9000) toneon = ToneOn(self, unique, tone, freq, gain) self.on[unique] = toneon return toneon
def myTest(): osc.init() osc.listen('192.168.11.15', 8000) #local IP; listen on port 8000 osc.bind(recvMsg, "/echo") # enable reporting of all adc channels osc.sendMsg("/echo", [0], '192.168.11.200', 8888) # Arduino's IP and Port while 1: time.sleep(0.1)
def myTest(): osc.init() osc.listen('192.168.11.15', 8000) #local IP; listen on port 8000 osc.bind(recvMsg,"/echo") # enable reporting of all adc channels osc.sendMsg("/echo",[0],'192.168.11.200',8888) # Arduino's IP and Port while 1: time.sleep(0.1)
def complete_execution(): global thread thread = None try: osc.sendMsg(b'/interpreter', [b'completed_exec'], port=send_port, typehint='b') except KeyboardInterrupt: complete_execution()
def on_touch_move(self, touch): if touch.id in self.touchstarts: if self.round_notes: osc.sendMsg("/note", [self.note_number, 'bend', touch.sx - touch.userdata['first_touch'], touch.sy], host, port) #print self.parent.width #print self.parent.note_width*self.parent.note_range #print touch.x - self.x, scale(touch.x - self.x, 0, 720, 0., 1.) else: osc.sendMsg("/note", [self.note_number, 'bend', touch.sx, touch.sy], host, port)
def make_sound(self, limbs): """ translate limb positions to osc signals """ [left_hand, head, right_hand] = limbs if left_hand: left = 100 - int(left_hand[1][1] / self.smallheight * 100) osc.sendMsg("/left", [left], "127.0.0.1", OSC_PORT) if right_hand: right = 100 - int(right_hand[1][1] / self.smallheight * 100) osc.sendMsg("/right", [right], "127.0.0.1", OSC_PORT)
def recvMsg(*msg): global numMsgs,startTime numMsgs=numMsgs+1 if (numMsgs%10)==0: elapsed = time.time() - startTime print numMsgs, ": 10 echos in %1.4f sec - avg. roundtrip is %1.4f millis" % (elapsed,elapsed*100) time.sleep(1) startTime = time.time() osc.sendMsg("/echo",[0],'192.168.11.200',8888) # Arduino's IP and Port
def on_line_created(self, tetris_obj): grid = tetris_obj._grid total_cells = sum(grid.color_accum.values()) rgb_list = [[x * (float(value) / float(total_cells)) for x in key] for key, value in grid.color_accum.items()] color = [0,0,0] for c in rgb_list: color = map(operator.add, color, c) color = map(int, color) osc.sendMsg("/tetris/line", color, "localhost", 9001)
def main(): osc.init() try: for i in range(0, 3): osc.sendMsg("/tetris/level", [i, 60], "localhost", 9001) pass except Exception, ex: print "EXCEPTION!" print ex
def send_notifications(self, osc_address, osc_data): if self.server.notifications.has_key(self.path): for n in self.server.notifications[self.path]: logging.debug("sending notification to '%s:%s%s'"%(n.host, n.port, osc_address)) if (type(osc_address) == str and type(osc_data) == list): osc.sendMsg(osc_address, osc_data, n.host, n.port) else: logging.error("did not send message. string address and list message expected, got %s %s."%(type(osc_address), type(osc_data))) else: logging.debug("no notification for '%s'"%(self.path))
def run(self): while True: uin = raw_input("> ").strip() if not uin: pass else: parts = uin.split(' ') message = parts[0] value = int(parts[1]) if len(parts) > 1 else "" osc.sendMsg(message, [value], BOARD_ADDRESS, BOARD_PORT)
def simulation_status_send(self, *args): print("Send simulation status") msg = [] grid_size = self.sim.model.parameters.get("grid_size") print(grid_size) osc.sendMsg("/simu-status", [self.can_start, self.cycle, grid_size[0], grid_size[1], self.sim_speed], port=3002) # Send agent positions sleep(0.5) if self.cycle > 0: self.positions()
def recvMsg(*msg): global numMsgs, startTime numMsgs = numMsgs + 1 if (numMsgs % 10) == 0: elapsed = time.time() - startTime print numMsgs, ": 10 echos in %1.4f sec - avg. roundtrip is %1.4f millis" % ( elapsed, elapsed * 100) time.sleep(1) startTime = time.time() osc.sendMsg("/echo", [0], '192.168.11.200', 8888) # Arduino's IP and Port
def _game_loop(self): # Grab vars if self._tetromino.active: self._move_tetromino() else: #New Tetromino osc.sendMsg("/tetris/piece_down", [0], "localhost", 9001) self._new_tetromino() #Levels and Speedup if self._grid.num_lines_cleared >= (self._state["level_up_line_count"] * self._state["current_level"]) and self._state["last_num_lines_cleared"] != self._grid.num_lines_cleared: self._level_up()
def on_touch_up(self, touch): if touch.id in self.touchstarts: xoffset = touch.x - self.x yoffset = touch.y - self.y xx, yy = self.workspace_cb.to_local(touch.x, touch.y) self.workspace_cb.modules.append(Module(pos = (xx - xoffset, yy - yoffset) , filename = self.icons[self.category], category = self.category, instance = self.instance_count)) self.workspace_cb.add_widget(self.workspace_cb.modules[len(self.workspace_cb.modules)-1]) osc.sendMsg("/create", [self.category, self.instance_count], host, port) self.pos = self.original_pos self.instance_count += 1 self.touchstarts.remove(touch.id) return True
def send(self, *msg): # """deals with "print" tagged OSC addresses """ # print "printing in the printStuff function ", msg # print "the oscaddress is ", msg[0][0] # # print "the value is ", msg[0][2] # print "the value is ", msg[0][3] # print "the value is ", msg[0][4] # print "the value is ", msg[0][5] osc.sendMsg("/tuio/msg", [msg[0][5], msg[0][4]], msg[0][2], msg[0][3])
def remove_widget(self, widget): if widget.parents != []: for parent in widget.parents: for index, module in enumerate(parent.signal_connections): if module[0] == widget: parent.signal_connections.pop(index) for index, module in enumerate(parent.control_connections): if module[0] == widget: parent.control_connections.pop(index) self.modules.remove(widget) osc.sendMsg("/delete", [widget.category, widget.instance], host, port) super(Workspace, self).remove_widget(widget)
def send_message(self, message): real_print('message length is', len(message)) # If the message is very long, manually break into lines for sub_string_index in range(0, len(message), 30000): cur_message = message[sub_string_index:sub_string_index + 30000] try: osc.sendMsg(self.address, [ cur_message.encode('utf-8') if isinstance(cur_message, unicode_type) else cur_message], port=self.target_port, typehint='b') except KeyboardInterrupt: raise KeyboardInterrupt('interrupted while printing')
def on_level_up(self, tetris_obj): grid = tetris_obj._grid #ADDED: Color accumulation output and reset on level finish total_cells = sum(grid.color_accum.values()) color_timing = dict([(c, (float(x) / float(total_cells))) for c, x in grid.color_accum.items()]) self._render_list(tetris_obj, color_timing) color_timing = dict([(c, (float(x) / float(total_cells)) * tetris_obj._params["drink_pouring_time"]) for c, x in grid.color_accum.items()]) for color, hold_time in color_timing.items(): print [ DRINK_PORTS[DRINK_COLORS[color]], hold_time] osc.sendMsg("/tetris/level", [ DRINK_PORTS[DRINK_COLORS[color]], hold_time], "localhost", 9001) #time.sleep(hold_time + 1) #time.sleep(2) time.sleep(max(color_timing.values()) + 2.0) grid.color_accum = {}
def alive(ids = []): global touches fseq() # remove the touches that are gone from the list for id in touches.keys(): if not id in ids: del touches[id] # add new touches for id in ids: if not touches.has_key(id): touches[id] = Touch(id) args = ["alive"] args.extend([t.id for t in touches.values()]) osc.sendMsg("/tuio/2Dcur", args, osc_host, osc_port)
def handle_input(input, ipAddress): global fseq global touches for evt in input: if evt['elementId'] == "tuio": if evt['action'] == "alive": # remove the touches that are gone from the list for id in touches.keys(): if not id in evt['alive']: del touches[id] # add new touches for id in evt['alive']: if not touches.has_key(id): touches[id] = Touch(id) osc.sendMsg("/tuio/2Dcur", ["fseq", fseq], osc_host, osc_port) fseq += 1 args = ["alive"] args.extend([t.id for t in touches.values()]) osc.sendMsg("/tuio/2Dcur", args, osc_host, osc_port) elif evt['action'] == "move": osc.sendMsg("/tuio/2Dcur", ["fseq", fseq], osc_host, osc_port) fseq += 1 for t in evt['touches']: id = t['identifier'] touches[id].update(float(t['x'])/surface_width, float(t['y'])/surface_height, evt['time']) osc.sendMsg("/tuio/2Dcur", ["set", id, touches[id].x, touches[id].y, touches[id].X, touches[id].Y, touches[id].m], osc_host, osc_port)
def send_message(self, message): real_print('message length is', len(message)) # If the message is very long, manually break into lines for sub_string_index in range(0, len(message), 30000): cur_message = message[sub_string_index:sub_string_index + 30000] try: osc.sendMsg(self.address, [ cur_message.encode('utf-8') if isinstance( cur_message, unicode_type) else cur_message ], port=self.target_port, typehint='b') except KeyboardInterrupt: raise KeyboardInterrupt('interrupted while printing')
def interpret_code(code): # # Setting this var lets pip be used from a thread other than its original import # import threading # _log_state = threading.local() # if not hasattr(_log_state, 'indentation'): # _log_state.indentation = 0 try: sys.stdout.can_omit = True # The input is first parsed as ast, then if the last statement # is an Expr compiled partially in single mode. This means # that the last statement output is printed, as in the normal # Python interpreter components = ast.parse(code).body # print('components are', components) # exec all but the last ast component in exec mode if len(components) > 1: for component in components[:-1]: c = compile(ast.Module([component]), '<stdin>', mode='exec') exec(c, user_locals, user_globals) # if the last ast component is an Expr, compile in single mode to print it if isinstance(components[-1], ast.Expr): c = compile(ast.Interactive([components[-1]]), '<stdin>', mode='single') else: c = compile(ast.Module([components[-1]]), '<stdin>', mode='exec') exec(c, user_locals, user_globals) except KeyboardInterrupt as e: print('') traceback.print_exc() osc.sendMsg(b'/interpreter', [b'keyboard_interrupted'], port=send_port, typehint='b') except Exception as e: traceback.print_exc() finally: sys.stdout.can_omit = False complete_execution()
def myTest(): """ a simple function that creates the necesary sockets and enters an endless loop sending and receiving OSC """ osc.init() import time i = 1 while 1: j = ((i + 1) % 2) * 100 print j osc.sendMsg("/gainSlider", [j], "127.0.0.1", 9001) bundle = osc.createBundle() time.sleep(1) i += 1 osc.dontListen()
def myTest(): """ a simple function that creates the necesary sockets and enters an enless loop sending and receiving OSC """ osc.init() inSocket = osc.createListener('127.0.0.1', 9001) # in this case just using one socket ## inSocket = osc.createListener() # this defaults to port 9001 as well # bind addresses to functions -> printStuff() function will be triggered everytime a # "/test" labeled message arrives osc.bind(printStuff, "/test") import time # in this example we will have a small delay in the while loop print 'ready to receive and send osc messages ...' while 1: ## osc.sendMsg("/test", [444], "127.0.0.1", 9000) # send normal msg to a specific ip and port osc.sendMsg("/test", [ 444 ]) # !! it sends by default to localhost ip "127.0.0.1" and port 9000 # create and send a bundle bundle = osc.createBundle() osc.appendToBundle(bundle, "/test/bndlprt1", [1, 2, 3]) # 1st message appent to bundle osc.appendToBundle(bundle, "/test/bndlprt2", [4, 5, 6]) # 2nd message appent to bundle ## osc.sendBundle(bundle, "127.0.0.1", 9000) # send it to a specific ip and port osc.sendBundle( bundle ) # !! it sends by default to localhost ip "127.0.0.1" and port 9000 osc.getOSC(inSocket) # listen to incomming OSC in this socket time.sleep( 0.5 ) # you don't need this, but otherwise we're sending as fast as possible.
def main(): osc.init() try: random.seed() while 1: a = ((random.randint(0,100) % 100) / 100.0, (random.randint(0,100) % 100) / 100.0, (random.randint(0,100) % 100) / 100.0) print a b = [int(x * 255) for x in a] print b c = [random.randint(0, 40)] print c for i in range(0, 3): osc.sendMsg("/tetris/level", [i , a[i]], "localhost", 9001) osc.sendMsg("/tetris/line", b, "localhost", 9001) osc.sendMsg("/mario/speed", c, "localhost", 9001) time.sleep(1.5) except KeyboardInterrupt, e: osc.sendMsg("/tetris/line", [0,0,0], "localhost", 9001) osc.sendMsg("/mario/speed", [0], "localhost", 9001) pass
def main(): import osc import time osc.init() while 1: print "acquiring new Data" valueDict = getRSSData() msgArray = [ "temp", valueDict["Temperature"], "hum", valueDict["Humidity"], "wind", valueDict["WindSpeed"], "press", valueDict["Pressure"] ] print msgArray for j in range(0, 59): osc.sendMsg("/weather", msgArray, "127.0.0.1", 57120) # send normal msg time.sleep(10)
def positions(self): # print("Positions sending") # print(self.sim.state) osc.sendMsg("/states", ["start"], port=3002) for lst in self.sim.state: osc.sendMsg("/states", [lst[0], lst[1], lst[2], lst[3], lst[4]], port=3002) osc.sendMsg("/states", ["end"], port=3002)
def main(): import osc import time osc.init() sleepTime = 10 """reacquisition of data every""" reacquisitionCycle = 5 """ x sleepTime seconds.""" """for i in range(0, 100):""" while 1: print "acquiring new Data" """Bielefeld""" """valueDict = getData("IBIELEFE4")""" """Helsinki, Kannelmaki""" """valueDict = getData("IUUSIMAA2")""" """Helsinki, Vuosaari""" """valueDict = getData("IUUSIMAA12")""" """Amsterdam, Westhaven""" valueDict = getData("INHAMSTE8") # print valueDict msgArray = [ "temp", valueDict["TemperatureC"], "hum", valueDict["Humidity"], "wind", valueDict["WindSpeedKMH"], "press", valueDict["PressurehPa"] ] for j in range(0, reacquisitionCycle): print msgArray osc.sendMsg("/weather", msgArray, "127.0.0.1", 57120) # send normal msg time.sleep(sleepTime)
def request_input(prompt): osc.sendMsg(b'/requestinput', [prompt], port=send_port, typehint='b')
def receive_message(message, *args): real_stdout.write('- subprocess received' + str(message) + '\n') real_stdout.flush() address = message[0] osc.sendMsg(b'/interpreter', [b'received_command'], port=send_port, typehint='b') global thread if address == b'/interpret': if thread is not None: print( 'COMPUTATION FAILED: something is already running (this shouldn\'t happen)' ) complete_execution() return body = [s.decode('utf-8') for s in message[2:]] if use_thread: t = threading.Thread(target=lambda *args: interpret_code(body[0])) thread = t t.start() else: interpret_code(body[0]) elif address == b'/execfile': if thread is not None: print( 'COMPUTATION FAILED: something is already running (this shouldn\'t happen)' ) complete_execution() return body = [s.decode('utf-8') for s in message[2:]] code = '_exec_full("{}")'.format(body[0]) if use_thread: t = threading.Thread(target=lambda *args: interpret_code(code)) thread = t t.start() else: interpret_code(code) elif address == b'/ping': osc.sendMsg(b'/pong', [b'pong'], port=send_port, typehint='b') elif address == b'/sigint': if thread is None: print( 'Received interrupt but there is no thread to stop - this should not happen' ) else: real_stdout.write('trying to stop thread {}\n'.format(thread)) real_stdout.flush() stop_thread(thread) elif address == b'/throttling': global throttle_output body = message[2:] if body[0] == b'1': throttle_output = True elif body[0] == b'0': throttle_output = False else: print('Error changing output throttling: received value {}'.format( body[0])) elif address == b'/userinput': global __input __input = message[2].decode('utf-8') else: raise ValueError('Received unrecognised address {}'.format(address))
def handle_input(input, ipAddress): for evt in input: if evt['elementId'] == "touchmove": if evt['action'] == "MultitouchTouchList": osc.sendMsg("/movestart", [ipAddress, evt['coords'][0][0], evt['coords'][0][1]] , "127.0.0.1", 9002) if evt['action'] == "MultitouchTouchListEnd": osc.sendMsg("/moveend", [ipAddress, evt['coords'][0][0], evt['coords'][0][1]] , "127.0.0.1", 9002) if evt['elementId'] == "touchshoot": if evt['action'] == "MultitouchTouchList": osc.sendMsg("/shootstart", [ipAddress, evt['coords'][0][0], evt['coords'][0][1]] , "127.0.0.1", 9002) if evt['action'] == "MultitouchTouchListEnd": osc.sendMsg("/shootend", [ipAddress, evt['coords'][0][0], evt['coords'][0][1]] , "127.0.0.1", 9002) if evt['elementId'] == "drumpad": if evt['action'] == "MultitouchTouchList": drummers.add_touches(ipAddress, evt['coords']) hits = drummers.get_total_hits() print "hits =", hits, len(hits) osc.sendMsg("/drumhitlist", [int(h) for h in hits], "127.0.0.1", 6767) osc.sendMsg("/drumhitlist", [int(h) for h in hits], "127.0.0.1", 6768) if evt['action'] == "MultitouchTouchNone": print "got none!" drummers.add_touches(ipAddress, []) hits = drummers.get_total_hits() print "hits =", hits, len(hits) osc.sendMsg("/drumhitlist", [int(h) for h in hits], "127.0.0.1", 6767) osc.sendMsg("/drumhitlist", [int(h) for h in hits], "127.0.0.1", 6768) if evt['elementId'] == "drumpadc": print "touish:", evt
def myTest(): """ a simple function that creates the necesary sockets and enters an enless loop sending and receiving OSC """ osc.init() import time # Setup the keyboard ser = serial.Serial(port='/dev/tty.usbserial-A6007kFY',baudrate= 115200,bytesize=8,parity='N',stopbits=1) ser.open() print ser.portstr ser.write("q") #initiate continuous ASCII mode (active keys only) # Build a regexp to recognize a line that looks like: # # (0,10) => 158 # regexp = re.compile('.*\(([0-9]*),([0-9]*)\) => ([0-9]*)') # Main loop i = 1 while 1: line = ser.readline() r = regexp.match(line) if r is not None: #print "****" + r.group(1) + " " + r.group(2) + " " + r.group(3) + "****" row = int(r.group(1)) col = int(r.group(2)) pressure = int(r.group(3)) / 10 address = "/generickey" if (row == 1) and (col == 9): address = "/key1" if row == 5 and col == 8: address = "/key2" if row == 0 and col == 6: address = "/key3" if row == 5 and col == 9: address = "/key4" if row == 4 and col == 8: address = "/key5" if row == 1 and col == 6: address = "/key6" if row == 4 and col == 9: address = "/key7" if row == 3 and col == 8: address = "/key8" if row == 4 and col == 6: address = "/key9" if row == 1 and col == 11: address = "/keym" if row == 5 and col == 3: address = "/keyd" if row == 5 and col == 2: address = "/keys" if row == 0 and col == 17: address = "/keyleft" if row == 0 and col == 18: address = "/keydown" if row == 0 and col == 10: address = "/keyright" if row == 1 and col == 18: address = "/keyup" if pressure < 20: pressure = 0 pressure /= 85.0; if address == "/key1": address = "/Fanout/mixsrc/Series/branch1/Panorama/pan/mrs_real/angle" pressure *= -0.785 if address == "/key2": address = "/Fanout/mixsrc/Series/branch1/Panorama/pan/mrs_real/angle" pressure = 0 if address == "/key3": address = "/Fanout/mixsrc/Series/branch1/Panorama/pan/mrs_real/angle" pressure *= 0.785; if address == "/key4": address = "/Fanout/mixsrc/Series/branch2/Panorama/pan/mrs_real/angle" pressure *= -0.785 if address == "/key5": address = "/Fanout/mixsrc/Series/branch2/Panorama/pan/mrs_real/angle" pressure = 0 if address == "/key6": address = "/Fanout/mixsrc/Series/branch2/Panorama/pan/mrs_real/angle" pressure *= 0.785; if address == "/key7": address = "/Fanout/mixsrc/Series/branch3/Panorama/pan/mrs_real/angle" pressure *= -0.785 if address == "/key8": address = "/Fanout/mixsrc/Series/branch3/Panorama/pan/mrs_real/angle" pressure = 0 if address == "/key9": address = "/Fanout/mixsrc/Series/branch3/Panorama/pan/mrs_real/angle" pressure *= 0.785; if address == "/keym": pressure *= 100; if address == "/keys": pressure *= 100; if address == "/keyd": pressure *= 20; if address == "/keyleft": pressure *= -255; if address == "/keyright": pressure *= 255; if address == "/keyup": pressure *= 180; if address == "/keydown": pressure *= -180; print "**** address=" + address + " row=" + str(row) + " col=" + str(col) + " pressure=" + str(pressure) + " ****" osc.sendMsg(address, [pressure], "127.0.0.1", 9000) # bundle = osc.createBundle() #time.sleep(0.5) i += 1 osc.dontListen() ser.close()
import osc osc.init() osc.sendMsg("/tuio/msg", ["mark", "40005"], '127.0.0.1', 40004)
def sendOsc(self, url, params): osc.sendMsg(url, params, self.address, self.port) print("send : ", url, " : ", params)
def send_osc_message(self, message, address=b'/interpret'): osc.sendMsg(address, [message], port=self.interpreter_port, typehint='b') print('sent', message)
import osc osc.init() osc.sendMsg('/test', [999])
p2 = Player(-1, [], [], [], [], [], [], [], []) while True: data, addr = sock.recvfrom( 1024 ) # buffer size is 1024 bytes all = regex.findall(data) if (data[0] == "p"): if (all[0][1] == "-999.0" and all[0][2] == "-999.0" and all[0][3] == "-999.0" and all[1][1] == "-999.0" and all[1][2] == "-999.0" and all[1][3] == "-999.0"): #LOST TRACK msg = "LOST USER " + data[1] print msg hasTwoPlayers = False if (p1.id == data[1]): p1 = Player(-1, [], [], [], [], [], [], [], []) cmd = ["p1l"] osc.sendMsg("/titsPD", cmd, "127.0.0.1", 9999) elif (p2.id == data[1]): p2 = Player(-1, [], [], [], [], [], [], [], []) cmd = ["p2l"] osc.sendMsg("/titsPD", cmd, "127.0.0.1", 9999) else: if (p1.id == data[1]): p1 = Player(data[1], all[0], all[1], all[2], all[3], all[4], all[5], all[6], all[7]) elif (p2.id == data[1]): p2 = Player(data[1], all[0], all[1], all[2], all[3], all[4], all[5], all[6], all[7]) elif (p1.id == -1): p1 = Player(data[1], all[0], all[1], all[2], all[3], all[4], all[5], all[6], all[7]) cmd = ["p1c"] osc.sendMsg("/titsPD", cmd, "127.0.0.1", 9999) elif (p2.id == -1): p2 = Player(data[1], all[0], all[1], all[2], all[3], all[4], all[5], all[6], all[7])
def send(self, data, path, host=LOCALHOST, port=OUT): """ Sends the given list of data over OSC to PD. The path specifies the address where PD receives the data e.g. "/creature/perch". """ osc.sendMsg(path, data, host, port)
def sendOSCMessage(address, value): global sendIP global sendPort osc.sendMsg(address, value, sendIP, sendPort)