def parse_function(self, data): # OSCulator uses big endian, OSC.py uses big endian name, rest = OSC.readString(data) if not name.startswith("/wii"): return type, rest = OSC.readString(rest) if name.endswith("/pry/0"): self.parse_field(rest, 'pitch', 'y') if name.endswith("pry/1"): self.parse_field(rest, 'roll', 'x') if name.endswith("pry/2"): self.parse_field(rest, 'yaw', 'z') if name.endswith("button/A"): self.a = self.readFloat(rest)[0] if name.endswith("button/B"): b = self.readFloat(rest)[0] if self.b and not b: self.tool_server.on_mouse_release(0, 0, 0, 0) elif not self.b and b: self.tool_server.on_mouse_press(0, 0, 0, 0) self.b = b
def main(self): """ Main loop """ while 1: if self.dataReady("control"): msg = self.recv("control") if (isinstance(msg, producerFinished) or isinstance(cmsg, shutdownMicroprocess)): self.send(msg, "signal") break if self.dataReady("inbox"): data = self.recv("inbox") if self.index is None: decoded = OSC.decodeOSC(data) # Send decoded data as (address, [arguments], timetag) tuple self.send((decoded[2][0], decoded[2][2:], decoded[1]), "outbox") else: decoded = OSC.decodeOSC(data[self.index]) data = list(data) data[self.index] = (decoded[2][0], decoded[2][2:], decoded[1]) self.send(data, "outbox") if not self.anyReady(): self.pause() yield 1
def all_handler(addr, tags, stuff, source): print "received new osc msg from %s" % OSC.getUrlStr(source) f_out.write(OSC.getUrlStr(source)+'; ') print "with addr : %s" % addr f_out.write(addr+'; ') print "typetags %s" % tags print "data %s" % stuff f_out.write(addr+'; ') f_out.write(str(stuff[0])+'; ') f_out.write(str(time.time())+'; ') f_out.write('humanreadable: '+datetime.fromtimestamp(int(time.time())).strftime('%Y-%m-%d %H:%M:%S')) f_out.write('\n')
def all_handler(addr, tags, stuff, source): print "received new osc msg from %s" % OSC.getUrlStr(source) f_out.write(OSC.getUrlStr(source)+'; ') print "with addr : %s" % addr f_out.write(addr+'; ') print "typetags %s" % tags print "data %s" % stuff for smth in stuff: print smth f_out.write(str(smth)) f_out.write('; ') f_out.write(str(time.time())+'; ') f_out.write('\n')
def fader_handler(addr, tags, data, source): print "---" print "received FADER new osc msg from %s" % OSC.getUrlStr(source) print "with addr : %s" % addr print "typetags %s" % tags print "data %s" % data split = addr.split("/") print "split", split # split[2] is nu faderx, we want the id fadernr = int(split[2][-1:]) print "fadernr = ", fadernr # Add one and loop aftre we are at 5 next_fader = (fadernr % 5) + 1 return_addr = "/1/fader%s" % next_fader print "Return addres", return_addr msg = OSC.OSCMessage() msg.setAddress(return_addr) msg.append(data) c.send(msg) print "return message %s" % msg print "---" if 1 <= fadernr <= 4 and data[0] >= 0.5: msg = OSC.OSCMessage() toggle_addr = "/1/toggle%s" % fadernr msg.setAddress(toggle_addr) msg.append(1.0) c.send(msg) print "return message %s" % msg else: msg = OSC.OSCMessage() toggle_addr = "/1/toggle%s" % fadernr msg.setAddress(toggle_addr) msg.append(0.0) c.send(msg) print "return message %s" % msg
def chew_data(host, port): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.settimeout(0.05) # prevent blender from getting stuck if socket hangs s.bind((host, port)) raw,addr = s.recvfrom(1024) o = OSC.decodeOSC(raw) return o
def no_match_handler(self,addr, tags, stuff, source): text='' text+= "no match for new osc msg from %s" % OSC.getUrlStr(source)+'\n' text+= "with addr : %s" % addr+'\n' text+= "typetags %s" % tags+'\n' text+= "data %s" % stuff+'\n' self.add_status(text+'\n')
def heartbeat(add, tags, stuff, source): global sw1 if sw1 == 1: # print "HEARTBEAT RECIEVED!" decoded = OSC.decodeOSC(stuff[0]) #supercollider CPU usage and UGens printout print "Sound CPU/Synths heartbeat: "+str(round(decoded[7],4))+"/"+str(decoded[3]) # scaling CPU values scaled = int(interp(decoded[7],[0.0,40.0],[20,255])) #print decoded[7] # ready the osc message oscmsg = OSC.OSCMessage() #determine which heartbeat to send if float(decoded[7]) < 2.0: oscmsg.setAddress("/heartbeat/faint") elif decoded[7] < 6.0: oscmsg.setAddress("/heartbeat/weak") elif decoded[7] < 10.0: oscmsg.setAddress("/heartbeat/medium") elif decoded[7] < 20.0: oscmsg.setAddress("/heartbeat/strong") elif decoded[7] < 30.0: oscmsg.setAddress("/heartbeat/heavy") else: oscmsg.setAddress("/heartbeat/intense") # adding the CPU usage value to the message, this can be mapped later. oscmsg.append(scaled) qlcclient.send(oscmsg)
def __init__(self, serport='/dev/ttyUSB0', scenefile=None, listenurl=':6788'): """Instantiate DMXCtrl, instantiate OSCMultiClient & ThreadingOSCServer """ super(self.__class__, self).__init__(serport, scenefile) # parse 'listenurl' argument (addr, server_prefix) = OSC.parseUrlStr(listenurl) if addr != None and addr[0] != None: if addr[1] != None: listen_address = addr else: listen_address = (addr[0], default_port) else: listen_address = ('', default_port) # Create OSC Client & Server self.cli = OSC.OSCMultiClient() self.srv = OSC.ThreadingOSCServer(listen_address, self.cli) self.srv.addDefaultHandlers(server_prefix) self.srv.setSrvInfoPrefix("/serverinfo") # Register DMX-specific message-handlers self.srv.addMsgHandler(server_prefix + "/dmx/scene", self.dmxSceneHandler) self.srv.addMsgHandler(server_prefix + "/dmx/channel", self.dmxChanHandler) self.srv_thread = None
def handle_root(addr, tags, data, source): print "---" print "received new osc msg from %s" % OSC.getUrlStr(source) print "with addr : %s" % addr print "typetags %s" % tags print "data %s" % data print "---"
def countsHandler(addr,tags,stuff,source): print '---' print 'new msg from %s' % OSC.getUrlStr(source) print 'with addr: %s' % addr print 'typetags %s' % tags print 'data %s' %stuff print '---'
def osc_printing_handler(self, addr, tags, stuff, source): msg_string = "%s [%s] %s" % (addr, tags, str(stuff)) sys.stdout.write("OSCServer Got: '%s' from %s\n" % (msg_string, OSC.getUrlStr(source))) # send a reply to the client. msg = OSC.OSCMessage("/printed") msg.append(msg_string) return msg
def _drop(self, message, addr, tags, packet, source, route=None): logging.debug("DROPPED (%s) from %s" % (message, OSC.getUrlStr(source))) logging.debug("\taddr: %s" % addr) logging.debug("\ttypetags: %s" % tags) logging.debug("\tdata: %s" % packet) if route: logging.debug("\troute: %s" % route)
def heartbeat(add, tags, stuff, source): global sw1 cpu = psutil.cpu_percent() if sw1 == 1: # print "HEARTBEAT RECIEVED!" decoded = OSC.decodeOSC(stuff[0]) # supercollider CPU usage and UGens printout cprint("CPU %/Number of Sounds: " + str(cpu) + "/" + str(decoded[3]), "red", attrs=["dark"]) # scaling CPU values cpufloat = float(cpu) # print decoded[7] # ready the osc message oscmsg = OSC.OSCMessage() # determine which heartbeat to send if cpufloat < 2.0: oscmsg.setAddress("/heartbeat/faint") elif cpufloat < 6.0: oscmsg.setAddress("/heartbeat/weak") elif cpufloat < 10.0: oscmsg.setAddress("/heartbeat/medium") elif cpufloat < 20.0: oscmsg.setAddress("/heartbeat/strong") elif cpufloat < 30.0: oscmsg.setAddress("/heartbeat/heavy") else: oscmsg.setAddress("/heartbeat/intense") # adding the CPU usage value to the message, this can be mapped later. oscmsg.append(cpufloat) qlcclient.send(oscmsg) # sending CPU information back to SuperCollider oscmsg = OSC.OSCMessage() oscmsg.setAddress("/cpuinfo") oscmsg.append(cpufloat) scclient.send(oscmsg)
def forward_handler(addr, tags, data, source): global prefix global scake global offset if debug > 1: print("---") print("source %s" % OSC.getUrlStr(source)) print("addr %s" % addr) print("tags %s" % tags) print("data %s" % data) if addr[0] != '/': # ensure it starts with a slash addr = '/' + addr if tags == 'f' or tags == 'i': # it is a single value key = prefix + addr.replace('/', '.') val = EEGsynth.rescale(data[0], slope=scale, offset=offset) patch.setvalue(key, val) else: for i in range(len(data)): # it is a list, send it as multiple scalar control values # append the index to the key, this starts with 0 key = prefix + addr.replace('/', '.') + '.%i' % i val = EEGsynth.rescale(data[i], slope=scale, offset=offset) patch.setvalue(key, val)
def heartbeat(add, tags, stuff, source): # print "HEARTBEAT RECIEVED!" decoded = OSC.decodeOSC(stuff[0]) #supercollider CPU usage and UGens printout print "SuperCollider CPU usage: "+str(decoded[7])+" Number of synths: "+str(decoded[3]) # scaling CPU values scaled = int(interp(decoded[7],[0.0,40.0],[20,255])) #print decoded[7] # ready the osc message oscmsg = OSC.OSCMessage() #determine which heartbeat to send if float(decoded[7]) < 2.0: oscmsg.setAddress("/heartbeat/faint") print "faint" elif decoded[7] < 6.0: oscmsg.setAddress("/heartbeat/weak") print "weak" elif decoded[7] < 10.0: oscmsg.setAddress("/heartbeat/medium") print "medium" elif decoded[7] < 20.0: oscmsg.setAddress("/heartbeat/strong") print "strong" elif decoded[7] < 30.0: oscmsg.setAddress("/heartbeat/heavy") print "heavy" else: oscmsg.setAddress("/heartbeat/intense") print "intense" # adding the CPU usage value to the message, this can be mapped later. oscmsg.append(scaled) c.send(oscmsg)
def inductionmics(add, tags, stuff, source): global sw1 global sw2 global inductioniter # check if the switch is on, this is the same switch that controls the inducton light/sound if sw2 == 1: # this should only be displayed if the 'information' switch (switch 1) is on if sw1 == 1: # decoded OSC message, this needs to be done to the whole message and then # the goodies need to be parsed out because OSC and arrays don't mix well # indices 5, 6 and 7 of the 'stuff' contains hi/mid/low figures decoded = OSC.decodeOSC(stuff[0]) # TODO: Sort this out. Print this every ten times this function is run if inductioniter % 30 == 0: cprint( "Induction Power: Low - " + str(round(decoded[4], 3)) + " Mid - " + str(round(decoded[5], 3)) + " Hi - " + str(round(decoded[6], 3)), "cyan", attrs=["dark"], ) inductioniter = inductioniter + 1
def process_metatone_message(self, handler, time, packet): """ Function to decode an OSC formatted string and then process it according to its address. Sends processed messages directly to the metatone_classifier module's message handling functions. """ message = OSC.decodeOSC(packet) try: if "/metatone/touch/ended" in message[0]: self.classifier.handle_client_message(message[0], message[1][1:], message[2:], FAKE_OSC_SOURCE) elif "/metatone/touch" in message[0]: self.classifier.handle_client_message(message[0], message[1][1:], message[2:], FAKE_OSC_SOURCE) elif "/metatone/switch" in message[0]: self.classifier.handle_client_message(message[0], message[1][1:], message[2:], FAKE_OSC_SOURCE) elif "/metatone/online" in message[0]: self.classifier.handle_client_message(message[0], message[1][1:], message[2:], FAKE_OSC_SOURCE) handler.send_osc("/metatone/classifier/hello", []) handler.deviceID = message[2] handler.app = message[3] elif "/metatone/offline" in message[0]: self.classifier.handle_client_message(message[0], message[1][1:], message[2:], FAKE_OSC_SOURCE) elif "/metatone/acceleration" in message[0]: self.classifier.handle_client_message(message[0], message[1][1:], message[2:], FAKE_OSC_SOURCE) elif "/metatone/app" in message[0]: self.classifier.handle_client_message(message[0], message[1][1:], message[2:], FAKE_OSC_SOURCE) elif "/metatone/targetgesture" in message[0]: self.classifier.handle_client_message(message[0], message[1][1:], message[2:], FAKE_OSC_SOURCE) else: print("Got an unknown message! Address was: " + message[0]) print("Time was: " + str(time)) print(u'Raw Message Data: {}'.format(packet)) except(): print("Message did not decode to a non-empty list.")
def transport_handler(addr, tags, args, source): print "---" print "received new osc msg from %s" % OSC.getUrlStr(source) print "with addr : %s" % addr print "typetags %s" % tags print "args %s" % args print "---"
def printing_handler(addr, tags, stuff, source): print "---" print "received from : %s" % OSC.getUrlStr(source) print "with addr : %s" % addr print "typetags : %s" % tags print "data : %s" % stuff print "---"
def trata(addr, tags, dados, origem): m = "%s [%s] %s" % (addr, tags, str(dados)) #t="%s enviou: %s\n" % (osc.getUrlStr(origem), m) t=str((osc.getUrlStr(origem), m)) print t with open("log-golly.txt", "a") as f: f.write(t)
def printing_handler(addr, tags, stuff, source): print "---" print "received new osc msg from %s" % OSC.getUrlStr(source) print "with addr : %s" % addr print "typetags %s" % tags print "data %s" % stuff print "---" url="http://www.musicalturk.com/loops/add" shutil.move('/Users/Kleeb2/Documents/MaxPatches/MusicalTurk/'+ str(stuff[0]), "/Users/Kleeb2/Documents/Web/Python/Thesis/"+str(stuff[0])) filename = str(stuff[0]) #filename = '/Users/Kleeb2/Documents/Web/Python/LocalThesis/max.py' title = 'test'#str(count).zfill(3) date = str(datetime.date.today()) values = [('title', title), ('postedby',date)] try: files = {'loop': open(filename, 'rb')} except: print 'no file' try: r = requests.post(url, files=files, data=values) print r.text except: print 'Fail'
def printer(addr, tags, stuff, source): print "---" print "received new osc msg from %s" % OSC.getUrlStr(source) print "with addr : %s" % addr print "typetags %s" % tags print "data %s" % stuff print "---"
def decode(data): """Converts a typetagged OSC message to a Python list. modified for supercollider-specific messages. """ table = { "i":OSC.readInt, "f":OSC.readFloat, "s":OSC.readString, "b":OSC.readBlob, "d":OSC.readDouble} decoded = [] address, rest = OSC.readString(data) typetags = "" if address == "#bundle": time, rest = OSC.readLong(rest) decoded.append(address) decoded.append(time) while len(rest)>0: length, rest = OSC.readInt(rest) decoded.append(OSC.decodeOSC(rest[:length])) rest = rest[length:] elif len(rest) > 0: typetags, rest = OSC.readString(rest) decoded.append(address) decoded.append(typetags) if(typetags[0] == ","): for tag in typetags[1:]: try: value, rest = table[tag](rest) decoded.append(value) except: print "%s probably not in tags list" %tag print "check scOSCMessage.py - def decodeSCOSC():" else: print "Oops, typetag lacks the magic ," try: returnList = [decoded[0]] except IndexError: returnList = [] try: oldRtnList = returnList returnList.extend(decoded[2:]) except IndexError: returnList = oldRtnList return returnList
def bgblue_handler(addr, tags, stuff, source): if layer.PRINT_BLUE: print "---" print "received new osc bgrgb msg from %s" % OSC.getUrlStr(source) print "with addr : %s" % addr print "typetags %s" % tags print "data %s" % stuff print "---"
def receiveOSC(controller): try: raw_data = gl.socket.recv(BUFFER_SIZE) data = OSC.decodeOSC(raw_data) print(data) except socket.timeout: pass
def inductionmics(add,tags,stuff,source): global sw2 if sw2 == 1: # decoded OSC message, this needs to be done to the whole message and then # the goodies need to be parsed out because OSC and arrays don't mix well decoded = OSC.decodeOSC(stuff[0]) #TODO: Sort this out. Print this every ten times this function is run print "Induction Power: Low - "+str(round(decoded[4],3))+" Mid - "+str(round(decoded[5],3))+" Hi - "+str(round(decoded[6],3))
def parse_function(self, data): # OSC.py uses big endian, OSC.readInt changed to little endian for p5osc name, rest = OSC.readString(data) if not name.startswith("/sp"): return type, rest = OSC.readString(rest) if name.endswith("rot/xyz/0"): self.parse_field(rest, 'pitch', 'y') if name.endswith("rot/xyz/1"): self.parse_field(rest, 'roll', 'x') if name.endswith("rot/xyz/2"): self.parse_field(rest, 'yaw', 'z')
def polydelay_handler(addr, tags, args, source): print "---" print "received new osc msg from %s" % OSC.getUrlStr(source) print "with addr : %s" % addr print "typetags %s" % tags print "args %s" % args print "---" method = args.pop(0) getattr(poly, method)(args)
def finger_handler(addr, tags, stuff, source): if layer.PRINT_FINGER: print "---" print "received new osc finger msg from %s" % OSC.getUrlStr(source) print "with addr : %s" % addr print "typetags %s" % tags print "data %s" % stuff print "---" time.sleep(.5)
""" import os, random, time, sys, OSC, threading, re BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) #taken from http://blog.mathieu-leplatre.info/colored-output-in-console-with-python.html #following from Python cookbook, #475186 #declaring OSC Addresses receive2_address = '127.0.0.1', 9998 #Mac Adress, Outgoing Port SC_address = '127.0.0.1', 57120 qlc_address = '127.0.0.1', 7700 python_address = '127.0.0.1', 9999 # Initialize the OSC server and the client. s = OSC.OSCServer(receive2_address) # initialise SuperCollider connection scclient = OSC.OSCClient() scclient.connect(SC_address) # initialise qlc connection qlcclient = OSC.OSCClient() qlcclient.connect(qlc_address) # initialise python master connection pythonclient = OSC.OSCClient() pythonclient.connect(python_address) s.addDefaultHandlers() # Exception class (nopt used) class PiException(Exception): def __init__(self, value):
def scriptPrint(): global code global fillCode global character global sw4 # type part of the string at index [character] # message sifter, checking most likely first matched = letterexp.match(code[character]) if matched: oscmsg = OSC.OSCMessage() oscmsg.setAddress("/character/letter") oscmsg.append(1) qlcclient.send(oscmsg) scclient.send(oscmsg) oscmsg.append(code[character]) pythonclient.send(oscmsg) sys.stdout.write('\033[37m' + '%s' % code[character] + '\033[1m') sys.stdout.flush() else: matched = numberexp.match(code[character]) if matched: oscmsg = OSC.OSCMessage() oscmsg.setAddress("/character/number") oscmsg.append(1) qlcclient.send(oscmsg) scclient.send(oscmsg) oscmsg.append(code[character]) pythonclient.send(oscmsg) sys.stdout.write('\033[31m' + '%s' % code[character] + '\033[1m') sys.stdout.flush() else: matched = symbolexp.match(code[character]) if matched: oscmsg = OSC.OSCMessage() oscmsg.setAddress("/character/symbol") oscmsg.append(1) qlcclient.send(oscmsg) scclient.send(oscmsg) oscmsg.append(code[character]) pythonclient.send(oscmsg) sys.stdout.write('\033[33m' + '%s' % code[character] + '\033[1m') sys.stdout.flush() else: if code[character] == '\n': oscmsg = OSC.OSCMessage() oscmsg.setAddress("/character/linebreak") oscmsg.append(1) qlcclient.send(oscmsg) scclient.send(oscmsg) oscmsg.append(code[character]) pythonclient.send(oscmsg) sys.stdout.write('%s' % '\033[34m' + ' \\n' '\033[1m' + code[character]) else: sys.stdout.write('%s' % code[character]) #iterate character character = character + 1 if character >= len(code): # fill up with different code, print a couple of line breaks, reset character count fillCode() print '\n\n' character = 0
def sendOSCComport( address='/print', data=[] ): m = OSC.OSCMessage() m.setAddress(address) for d in data: m.append(d) comport.send(m)
def send_osc(addr, *stuff): msg = OSC.OSCMessage() msg.setAddress(addr) for item in stuff: msg.append(item) c.send(msg)
def monitor(self, product=None, zmq_port=4000, timeout=0.2, full_trace=False, console=True, no_calibration=False, calibration=None): """Listen to OSC messages on 3333. Broadcast on the ZMQ PUB stream on the given TCP port.""" # get the product to use, either from the command line # or from the environment variable, or use the default product product = get_product(product=product) self.product = product self.monitor_enabled = console self.osc_port = product["tuio_port"] self.osc_ip = product["at_ip"] self.zmq_port = zmq_port self.timeout = timeout self.full_trace = full_trace self.last_exception = "" # try to import calibration # if not explicitly disabled with --no_calibration self.min_latitude = -np.pi * 0.45 if not no_calibration: try: self.calibration = Calibration(calibration) self.min_latitude = self.calibration.min_latitude except (CalibrationException, OSError) as e: print(e) self.calibration = None else: self.calibration = None # reset the timeouts self.last_packet = wall_clock() # last time a packet came in self.last_frame = wall_clock() # last time screen was redrawn # create a ZMQ port to broadcast on context = zmq.Context() self.zmq_socket = context.socket(zmq.PUB) self.zmq_socket.bind("tcp://*:%s" % zmq_port) # listen for OSC events self.msg = product["tuio_addr"] self.osc_server = OSC.OSCServer((self.osc_ip, self.osc_port)) self.osc_server.addMsgHandler(self.msg, self._handler) self.osc_server.timeout = timeout # clear the touch status self.last_fseq = -1 self.touch_list = {} self.last_touch_list = {} self.raw_list = {} self.all_touches = {} self.raws = {} self.packet_trace = [] # short history of packet message strings # launch the monitor if self.monitor_enabled: Screen.wrapper(self.monitor_loop) else: self.monitor_loop(False)
def makeMsg(self, address, content): msg = OSC.OSCMessage(address) for i in content: msg.append(i) return msg
def add(self, w, a, f, p): self.oscs.append(OSC.OSC(w, a, f, p)) self.numOscillators += 1
def play(self): msg = OSC.OSCMessage() msg.setAddress('/play') msg.append(1) self.__sendSilent(msg) self.__isPlaying = True
def pause(self): msg = OSC.OSCMessage() msg.setAddress('/play') msg.append(0) self.__sendSilent(msg) self.__isPlaying = False
if horiz: self.post_scroll(0, -xamt * 5) else: self.post_scroll(-xamt * 5, 0) if abs(yamt) > 0.1: #print "scroll y", param if horiz: self.post_scroll(yamt * 5, 0) else: self.post_scroll(0, yamt * 5) return server = EigenChord(('127.0.0.1', 4442)) server.addMsgHandler('default', server.message) client = OSC.OSCClient() client.connect(('127.0.0.1', 9999)) msg = OSC.OSCMessage("/register-fast") msg.append("keyboard_1") msg.append(4442) client.send(msg) print "EigenChord listening on 127.0.0.1:4442" try: server.serve_forever() except KeyboardInterrupt: print
def scrub(self, state): msg = OSC.OSCMessage() msg.setAddress('/scrub') msg.append(state) self.__sendSilent(msg)
class PiException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) ########################## # OSC ########################## # Initialize the OSC server and the client. print receive_address s = OSC.OSCServer(receive_address) s2 = OSC.OSCServer(receive_addresslocal) c = OSC.OSCClient() c.connect(send_address) s.addDefaultHandlers() # /data noise centroid bpm def getFiles(add, type, data, sender): if debug: print "recieved : " + key + " : " + mode global key global mode global bpm
#!/usr/bin/env python
def setBpm(self, bpm): msg = OSC.OSCMessage() msg.setAddress('/bpm') msg.append(bpm) self.__sendSilent(msg)
# a program to interpret sensor data from charlie and pass it on to SC # import random from time import sleep import OSC import serial import re # scaling tool (no longer needed) # from numpy import interp # setup OSC communication c = OSC.OSCClient() c.connect(('127.0.0.1', 9999)) oscmsg = OSC.OSCMessage() # setup serial communication # port = input('port: ') # baudrate = input('baudrate: ') # ser = serial.Serial(port, baudrate) # for testing ser = serial.Serial('/dev/ttyUSB2', 9600) # regex string formatting pattern to check if serial has read correctly pattern = re.compile("^msg=") sensor1 = 0 sensor2 = 0 sensor3 = 0
13: prC_54_3i_1v_107bpm, 14: prC_74_3i_1v_107bpm, 15: prC_124_3i_1v_107bpm, # trial 33: loop # tracker commands mapped onto beginning/end of MAX runs 77: tracker_start, 88: tracker_stop, 99: experiment_end } while True: data, addr = sock.recvfrom(BUF_SIZE) datatype, abbrev, value = OSC.decodeOSC(data) if value in dispatch: flag = dispatch[value]() if flag == STOP_LISTENING_TO_MAX: # close the socket and exit the loop sock.close() break else: print "unrecognized message: ", value # now present audio and visual from MAX
def __init__(self): self.numOscillators = numbOsc self.oscs = [OSC.OSC('s', 0.25, 0.1, 0.0)]
def sendOSCAux( address='/print', data=[] ): m = OSC.OSCMessage() m.setAddress(address) for d in data: m.append(d) auxclient.send(m)
def bundle(self): return OSC.OSCBundle()
import signal from sys import exit import time from dotenv import load_dotenv, find_dotenv import os import skywriter # retrieve environment variables load_dotenv(find_dotenv()) client_ip = os.environ.get('CLIENT_IP') # set IP and port of device running Sonic Pi send_address = (client_ip, 4559) # Initialize the OSC server and the client. c = OSC.OSCClient() c.connect(send_address) # create function to send message with multiple arguments def send_osc(addr, *stuff): msg = OSC.OSCMessage() msg.setAddress(addr) for item in stuff: msg.append(item) c.send(msg) # Skywriter functions (send OSC messages from each function for a constant stream as you move over the HAT) some_value = 5000 @skywriter.move() def move(x, y, z):
def send(self, address, msg): oscmsg = OSC.OSCMessage(address, msg) self._socket.sendto(oscmsg.getBinary(), self._remote_addr)
LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz) LED_DMA = 5 # DMA channel to use for generating signal (try 5) LED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest LED_INVERT = False # True to invert the signal (when using NPN transistor level shift) LED_CHANNEL = 0 # set to '1' for GPIOs 13, 19, 41, 45 or 53 LED_STRIP = ws.WS2811_STRIP_GRB # Strip type and colour ordering strip1 = Adafruit_NeoPixel(LED_COUNT, LED_PIN1, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, 0, LED_STRIP) strip2 = Adafruit_NeoPixel(LED_COUNT, LED_PIN2, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, 1, LED_STRIP) strip1.begin() strip2.begin() c = OSC.OSCServer(('192.168.0.111', 4000)) c.addDefaultHandlers() def printing_handler(addr, tags, stuff, source): print "---" print "received new osc msg from %s" % OSC.getUrlStr(source) print "with addr : %s" % addr print "typetags %s" % tags print "data %s" % stuff print "---" #leds = stuff[0].encode('string-escape').split('\\x') #print leds sleep(2)
def __init__(self): self.__client = OSC.OSCClient() self.__client.connect(('127.0.0.1', 2223)) self.__isPlaying = False
print frame1 # print frame2 # print frame3 csv1.close() # csv2.close() # csv3.close() # dir1 = CSVdict1 # dir2 = CSVdict2 # dir3 = CSVdict3 #send OSC message client = OSC.OSCClient() client.connect(('127.0.0.1', 57120)) msg = OSC.OSCMessage() msg.setAddress("/cam1recognize") if cam1Similarity > 70: msg.append(frame1) # msg.append(cam2Similarity) else: msg.append("0") #msg.append(cam1Similarity) # msg.append(cam1Similarity) # if cam2Similarity > 60: # msg.append(frame2) # else: # msg.append("0")
def sendOSCPD( address='/print', data=[] ): m = OSC.OSCMessage() m.setAddress(address) for d in data: m.append(d) pd.send(m)
def send_dmx(): ser.write(DMX_OPEN + DMX_INTENSITY + (''.join(dmx_data)) + DMX_CLOSE) def osc_handler(addr, tags, data, client_address): offset = 0 if addr.endswith('g'): offset = 1 elif addr.endswith('b'): offset = 2 elif addr.endswith('w'): offset = 3 set_dmx(((int(addr[7]) - 1) * 4) + 1 + offset, data[0]) send_dmx() DMX_OPEN = chr(126) DMX_CLOSE = chr(231) DMX_INTENSITY = chr(6) + chr(1) + chr(2) DMX_INIT1 = chr(03) + chr(02) + chr(0) + chr(0) + chr(0) DMX_INIT2 = chr(10) + chr(02) + chr(0) + chr(0) + chr(0) ser = serial.Serial('/dev/tty.usbserial-ENYXTI9L') ser.write(DMX_OPEN + DMX_INIT1 + DMX_CLOSE) ser.write(DMX_OPEN + DMX_INIT2 + DMX_CLOSE) dmx_data = [chr(0)] * 513 osc_server = OSC.OSCServer(('localhost', 9999)) osc_server.addMsgHandler('default', osc_handler) osc_server.serve_forever()
timestamp_file = datapath + 'timestamp.txt' notes_file = datapath + 'notes.txt' ch0_file = datapath + ch0 + '.dat' ch1_file = datapath + ch1 + '.dat' #NI signal files #ch2_file = datapath + ch2 + '.dat'; ch3_file = datapath + ch3 + '.dat' nx_file = datapath + 'nosex.dat' ny_file = datapath + 'nosey.dat' #bonsai tracking files hx_file = datapath + 'headx.dat' hy_file = datapath + 'heady.dat' cx_file = datapath + 'comx.dat' cy_file = datapath + 'comy.dat' ts_file = datapath + 'timestamp.dat' receive_address = ('localhost', 6666) trackingcoords = OSC.OSCServer(receive_address) #bonsai tracking variables qnosex = Queue.LifoQueue(0) qnosey = Queue.LifoQueue(0) #online position storage nosex = np.zeros((1, 1)) nosey = np.zeros((1, 1)) headx = np.zeros((1, 1)) heady = np.zeros((1, 1)) comx = np.zeros((1, 1)) comy = np.zeros((1, 1)) ts = np.zeros((1, 1)) signaldata = np.zeros((channel_num, buffersize), dtype=np.float64) #NI data collection reading variables reader = AnalogMultiChannelReader(ni_data.in_stream)
#print("Serving on {}".format(server.server_address)) #server.serve_forever() ########################### # EXPERIMENT listen_address = ('localhost', 54321) send_address = ('localhost', 12345) try: #c = OSC.OSCClient() #c.connect(listen_address) s = OSC.ThreadingOSCServer(listen_address)#, c)#, return_port=54321) print s # Set Server to return errors as OSCMessages to "/error" s.setSrvErrorPrefix("/error") # Set Server to reply to server-info requests with OSCMessages to "/serverinfo" s.setSrvInfoPrefix("/serverinfo") # this registers a 'default' handler (for unmatched messages), # an /'error' handler, an '/info' handler. # And, if the client supports it, a '/subscribe' & '/unsubscribe' handler s.addDefaultHandlers() #s.addMsgHandler("/print", printing_handler) s.addMsgHandler("default", printing_handler)
#!/usr/bin/env python import OSC as osc import threading import random import time ip = "192.168.11.159" port = 8000 brain = 1 o = osc.OSCClient() o.connect((ip, port)) m = osc.OSCMessage() # m.setAddress("/fart/channel") def activate(channel): m.setAddress("/%s/%s" % (brain, channel)) m.append(1) print m o.send(m) m.clearData() time.sleep(5) m.append(0) print m o.send(m) m.clearData()
def myMsgPrinter_handler(self, addr, tags, data, client_address): print "osc://%server%server ->" % (OSC.getUrlStr(client_address), addr), print "(tags, data): (%server, %server)" % (tags, data)