def set(self, prop, val): oscURI = os.path.join(self.oscbaseurl, self.group, self.id) if not val: self.playing = False else: self.playing = True liblo.send(self.oscaddress, oscURI, "set", prop, val)
def load(self, path, filename): with open(os.path.join(path, filename)) as stream: print stream.readline().rstrip('\n').replace("%", "") + "read!" header = stream.readline().rstrip('\n').split(" ") target_idx = header.index("target") path_idx = header.index("path") args_pattern_idx = header.index("args_pattern") args_idx = header.index("args") for line in stream: data = line.rstrip('\n').split(" ") i = 0 format_args = [] for arg in data[args_idx].split(","): if data[args_pattern_idx][i] == 's': format_args.append(arg) if data[args_pattern_idx][i] == 'i': format_args.append(int(arg)) if data[args_pattern_idx][i] == 'f': format_args.append(float(arg)) i = i+1 _liblo.send(data[target_idx], data[path_idx], *format_args) _liblo.send("9999", data[path_idx] + "/load", *format_args) self.dismiss_popup()
def run(self, model, control, event, msg, *args): """ :param source: control that triggered the action """ path = self.path.format(control=control, event=event, msg=msg) ##oscAPI.sendMsg(path, dataArray=['answer'], ipAddr=self.addr, port=self.port) if self.target: osc_msg = liblo.Message(path) print("OSC: ", path) for fmt, src in self.msg_templates: #print("src: '%s'" % src) data_str = ("{%s}" % src).format(control=control, event=event, msg=msg) #print("src: '%s' data_str: '%s' fmt: '%s' " % (src, data_str, fmt)) try: data = fmt(data_str) osc_msg.add(data) print(" - ", data) except Exception as e: print("Problem converting '%s' to '%s'" % (data_str, fmt)) print("- template: '%s'" % src) liblo.send(self.target, osc_msg) else: print("No target address for OSC") if self.led: try: led_color = control.valid_colors[self.led] control.set_color(led_color) except KeyError: print("Invalid LED color ", self.led) print(" valid colors: " + ", ".join(color.name for color in control.valid_colors))
def callback(element, index_unused=None): cap = element.name in CAPTURE mn, mx = element.get_volume_range(cap) vol = float(element.get_volume(0, cap) - mn) / (mx - mn) mute = not element.get_switch(0, cap) if element.has_switch(cap) else False liblo.send(ADDRESS, PATH + element.name, vol) liblo.send(ADDRESS, PATH + element.name + '/mute', mute)
def update(self): """ update is called when value is updated might be used to send it to network or other protocols """ for out in self.parent.get_device().outputs: try: split = out.port.split(':') ip_add = split[0] udp = split[1] try: target = liblo.Address(ip_add, int(udp)) if __dbug__ >= 3: print('connect to : ' + ip_add + ':' + str(udp)) except liblo.AddressError as err: if __dbug__ >= 3: print('liblo.AddressError' + str(err)) #msg = liblo.Message('/' + self.address) msg = liblo.Message(self.address) if isinstance(self.value, list): # this is a list of values to send for arg in self.value: arg = check_type(arg) msg.add(arg) else: # this is a single value to send msg.add(self.value) liblo.send(target, msg) if __dbug__ >= 3: print('update ' + self.name + ' to value ' + str(self.value)) return True except NoOutputError: return False
def parse_email(): global server server.select('INBOX') status, ids = server.search(None, 'UnSeen') print 'status is: ', status if not ids or ids[0] is '': print 'no new messages' else: print 'found a message; attempting to parse...' latest_id = ids[0] status, msg_data = server.fetch(latest_id, '(UID BODY[TEXT])') raw_data = msg_data[0][1] raw_filter = filter_signature(raw_data) char_array = list(raw_filter) char_string = ''.join(char_array) length = len(char_string) #raw_filter = raw_data if(length < length_limit): liblo.send(target, '/email_content', (char_string)) print 'message result: ', char_string print 'message length: ', length, ' characters' else: print 'message found, but too long; discarding.' flush_inbox()
def menuNoteOn(): liblo.send(target, "/midi", ('m', (0, 144, 60, 100))) printText("noteon\n"); while(lcd.buttonPressed(lcd.SELECT)): sleep(.1) liblo.send(target, "/midi", ('m', (0, 128, 60, 100))) printMenu()
def send_message(self): if self.path != '': print "[OSC]" + self.path + " " + str(self.args) if self.osc_name: _liblo.send(self.target, self.path, self.osc_name.replace(" ", "_"), *self.args) else: _liblo.send(self.target, self.path, *self.args)
def sync(self, client): logger.debug('system="%s", action="sync", client="%r"', self.system, client) liblo.send(client, liblo.Bundle( # Gross, this needs refactoring... liblo.Message("/light/cloud_z", self.controller.params.lightning_new / self.lightningProbabilityScale), liblo.Message("/light2/brightness", self.controller.params.brightness / self.brightnessScale), liblo.Message("/light2/contrast", self.controller.params.contrast / self.contrastScale), liblo.Message("/light2/detail", self.controller.params.detail / self.detailScale), liblo.Message("/light2/color_top", self.controller.params.color_top), liblo.Message("/light2/color_bottom", self.controller.params.color_bottom), liblo.Message("/light2/turbulence", self.controller.params.turbulence / self.turbulenceScale), liblo.Message("/light2/speed", self.controller.params.wind_speed / self.windSpeedScale), # XXX: This doesn't work- TouchOSC seems to spam these events # at both XY pads for some reason. Bug in TouchOSC? Using # liblo incorrectly? # # liblo.Message("/light2/heading", # -math.cos(self.controller.params.wind_heading), # math.sin(self.controller.params.wind_heading)), # # liblo.Message("/light2/rotation", # math.sin(-self.controller.params.rotation), # -math.cos(-self.controller.params.rotation)) ))
def playback(i): global target print("playback %d" % i) points = saved[i] if points == None or len(points) == 0: return start = points[0][0] now = time.time() print(str(points)) for (t, (x,y)) in points: centroid = centroid_min + ((float(x)/float(width)) * centroid_ratio) pitch = (float(y)/float(height)) * pitch_ratio flux = flux_min + ((float(y)/float(height)) * flux_ratio) offset = (float(t - start) / 1000.0) when = now + offset when_sec = int(when) when_usec = int((when - when_sec) * 1000000.0) #iiiifff #sec, usec, , v_pitch, v_flux, v_centroid1 = args liblo.send(target, "/play", int(dirtpid), int(when_sec), int(when_usec), int(0), # lowchunk float(pitch), #pitch float(flux), # flux float(centroid) # centroid )
def callback_channel_gain_a(self, path, args, types, src, data): val = float(args[0]) val = max(0.0, val) val = min(1.0, val) coeff = db_to_coeff(fader_to_db(val)) channel = data liblo.send(self.address_b, "/net/mhcloud/volume/" + instance + "/" + str(channel), coeff)
def sendDiff(self): xwhere, ywhere = np.where(self.diff != 0) n = len(xwhere) if n>0: for i in range(n): value = int(self.diff[xwhere[i],ywhere[i]]==1) liblo.send(self.phoneaddress, '/2/multitoggle/'+str(ywhere[i]+1)+'/'+str(xwhere[i]+1), value)
def send_plo_message(cmd, app=None): import liblo host, port = get_plo_target() print host, port instrument = 'mypaint' action = cmd.__class__.__name__ description = cmd.display_name #try: if app and getattr(app, 'brushmanager', None): current_brush = app.brushmanager.selected_brush.name else: current_brush = '' # Make a stroke done with different brush have a different string if action == 'Stroke' and current_brush: action = action + '/' + current_brush print action target = liblo.Address(host, port) try: liblo.send(target, "/plo/player/action", instrument, action) except Exception, e: print e
def send_command_with_arg(self,cmd,arg): if sonic_version > 2.6: print "send to "+str(pi_port)+": "+cmd+" "+guid+", "+arg+"..." liblo.send((pi_host,pi_port),"/"+cmd,guid,arg) else: print "send to "+str(pi_port)+": "+cmd+", "+arg+"..." liblo.send((pi_host,pi_port),"/"+cmd,arg)
def sendControl(control, value): target = liblo.Address(nekoport) path = "/dssi/nekobee/nekobee/chan00/control" liblo.send(tb303, path, int(control), float(value) )
def testSendReceive(self): self.server.add_method('/foo', 'i', self.callback) liblo.send(self.server.url, '/foo', 123) assert self.server.recv() == True assert self.cb.path == '/foo' assert self.cb.args[0] == 123 assert self.cb.types == 'i'
def send_command(self,cmd): if sonic_version > 2.6: print "send to "+str(pi_port)+": "+cmd liblo.send((pi_host,pi_port),"/"+cmd,guid) else: print "send to "+str(pi_port)+": "+cmd liblo.send((pi_host,pi_port),"/"+cmd)
def setDirty(self, trueOrFalse, internal = False): """/nsm/client/progress f:progress /nsm/client/is_dirty /nsm/client/is_clean Some clients may be able to inform the server when they have unsaved changes pending. Such clients may optionally send is_dirty and is_clean messages. Clients which have this capability should include :dirty: in their announce capability string. """ if "dirty" in states.clientCapabilities: if trueOrFalse and states.lastDirtyState is False: states.lastDirtyState = True liblo.send(states.nsmUrl, "/nsm/client/is_dirty") elif (not trueOrFalse) and states.lastDirtyState is True: states.lastDirtyState = False liblo.send(states.nsmUrl, "/nsm/client/is_clean") #else: #whatever it was, we were already at this state. Just ignore # pass else: if not internal: print ("Warning. You tried to send a dirty/clean update but did not initialize your NSM client with the 'dirty' capability. Message not sent. Get rid of this warning by setting the capability flag to True or remove the dirty update")
def testSendReceive(self): self.server.add_method('/foo', 'i', self.callback) liblo.send(self.server.url, '/foo', 123) self.assertTrue(self.server.recv()) self.assertEqual(self.cb.path, '/foo') self.assertEqual(self.cb.args[0], 123) self.assertEqual(self.cb.types, 'i')
def do_command(self, e, cmd): nick = nm_to_n(e.source()) c = self.connection msg = liblo.Message(self.mybotsynth) if nick == "c": if not self.check4p(c, cmd): for i in cmd: msg.add(ord(i)) liblo.send(self.target, msg) r3340.notify(1, "sent: " + cmd) else: self.is_Preset(c, cmd) elif nick == "d": #patt = cmd.partition(" ")[2] string = r3340.cervelle(cmd) string.scry(100) #self.patternDict["currentScry"] = string.message #if not self.check4p(c, cmd): for i in string.message: msg.add(ord(i)) liblo.send(self.target, msg) r3340.notify(1, nick + ':' + string.message) c.notice(self.channel, string.message) elif cmd == "help": c.notice(self.channel, "commands: master super mode+p") else: r3340.notify(0, nick + ':' + cmd)
def controlCallBack(xboxControlId, value): #now = time.time() #if (now - last > 0.05): l = xboxCont.controlValues.values() myv = l[0:len(l)-1]+[l[len(l)-1][0],l[len(l)-1][1]] liblo.send(target, "/xbox", *myv) print "%s" % myv
def init(prettyName, capabilities, requiredFunctions, optionalFunctions, sleepValueMs): """prettyName = "Super Client" Never change the prettyName after your software is ready to use. The reported filepath to load and more depends on this. Changing this is like telling NSM we are a different program now. """ canDo = [key for key,value in capabilities.items() if value] capabilitiesString = ":".join([""] + canDo + [""]) if canDo else "" states.clientCapabilities = set(canDo) for identifier, function in requiredFunctions.items(): setattr(ourNsmClient, identifier, function) for identifier, function in optionalFunctions.items(): if function: setattr(ourNsmClient, identifier, function) #Finally tell NSM we are ready and start the main loop #__file__ stands for the executable name liblo.send(states.nsmUrl, NSM_ANNOUNCE, prettyName, capabilitiesString, __main__.__file__, API_VERSION_MAJOR, API_VERSION_MINOR, os.getpid()) #The welcome message should have been received by now. #if the optional gui capability is not present then clients with optional-guis MUST always keep them visible if "optional-gui" in capabilities and not "optional-gui" in states.nsmCapabilities: ourNsmClient.function_showGui() #call once. All other osc calls in ourNsmClient will get ignored automatically. return ourNsmClient, lambda: ourNsmClient.libloServer.recv(sleepValueMs) #loop and dispatch messages every 100ms
def handletick(self): if self.mode == 'flash': flashtick(self) R, G, B = HSI2RGB.convert(self.currenthue, self.currentsaturation, self.currentintensity) liblo.send(self.address,'/light/color/set',('f', R),('f', G),('f', B)) while self.eventqueue.empty() == False: queuedevent = self.eventqueue.get() eventhandler(queuedevent.caller, queuedevent.event, queuedevent.message)
def get_osc_paths(self, path=''): self.list_data=[] if path=='root': self.osc_path="/part"+str(zyngui.curlayer.get_midi_chan())+"/" else: self.osc_path=self.osc_path+path liblo.send(zyngui.osc_target, "/path-search",self.osc_path,"") logging.debug("OSC /path-search "+self.osc_path)
def _osc_to_server(self, path, *arguments): """ Send an OSC message to the kinect software The path is a tuple, made of : (osc_path, osc_format) Paths can be found in constants.py. """ liblo.send(settings.SERVER_OSC_PORT, path, *arguments)
def rec_stop(self): if len(self.deefuzzer_pid) != 0: for port in self.deefuzzer_osc_ports: try: target = liblo.Address(int(port)) liblo.send(target, '/record', 0) except: continue
def hideGui(self, *args): """Only execute if the server has the capabilities to handle optional GUIs. If not ignore that command""" if "optional-gui" in self.states.nsmCapabilities: self.function_hideGui() liblo.send(states.nsmUrl, "/nsm/client/gui_is_hidden") else: pass #TODO: send general error?
def update(self): """update the information about position and send cooked AZI values to SATIE""" msg = self._getAED() azi = math.degrees(msg[0]) ele = math.degrees(msg[1]) gain = msg[2] # print("azi, ele, gain: {}, {}, {}".format(azi, ele, gain)) liblo.send(self.oscAddy, os.path.join("/SATIE", self.satieGroup, self.satieID), "set", "aziDeg", azi, "eleDeg", ele, "gainDB", gain)
def update(self): self.value = self.function(self.sponge, *self.inputs) # self.mapperOutput.update(self.value) liblo.send( self.sponge.oscTarget, self.sponge.oscPath + "/" + self.name, self.value )
def get_osc_paths(self, path=''): self.list_data=[] if path=='root': self.osc_path="/part"+str(zyngui.midi_chan)+"/" else: self.osc_path=self.osc_path+path liblo.send(zyngui.osc_target, "/path-search",self.osc_path,"") print("OSC /path-search "+self.osc_path)
def flip(): liblo.send(osc_target, '/oled/gFlip', 1)
#!/usr/bin/env python # -*- coding: utf-8 -*- import liblo import sys # send all messages to port 1234 on the local machine try: target = liblo.Address(1234) except liblo.AddressError as err: print(str(err)) sys.exit() # send message "/foo/message1" with int, float and string arguments liblo.send(target, "/player", 1)
def loopvelocity_callback(path, args): loopnumber, control, value = args print "received '%s' message with arguments: %d, %s, %f" % ( path, loopnumber, control, value) def fallback(path, args): a, b, c = args print "received unknown message '%s' %s:(%s) %s:(%s) %s:(%s) " % ( path, a, type(a), b, type(b), c, type(c)) server.add_method('/looppos', 'isf', looppos_callback) server.add_method('/loopcount', 'ssi', loopcount_callback) server.add_method('/loopstate', 'isf', loopstate_callback) server.add_method('/loopvelocity', 'isf', loopvelocity_callback) server.add_method(None, None, fallback) while True: server.recv(100) """test in ipython: import liblo target = liblo.Address(9951) liblo.send(target, '/sl/0/register_auto_update', 'loop_pos', 100, 'osc.udp://localhost:1234', '/looppos') liblo.send(target, '/ping', 'osc.udp://localhost:1234', '/loopcount') liblo.send(target, '/sl/0/get', 'state', 'osc.udp://localhost:1234', '/loopstate') liblo.send(target, '/sl/0/register_auto_update', 'wet', 100, 'osc.udp://localhost:1234', '/loopvelocity') """
def enable_part(self, layer): if layer.part_i is not None: liblo.send(self.osc_target, "/part%d/Penabled" % layer.part_i, True) liblo.send(self.osc_target, "/part%d/Prcvchn" % layer.part_i, layer.get_midi_chan())
def send(self): if not (self.target == None): liblo.send(target, "/flow", int(self.id), float(self.x), float(self.y), float(self.mx), float(self.my), float(self.weight))
self.freq[idx] = min(50, max(-50, self.freq[idx])) self.update_spiro(ring) @make_method(None, None) def fallback(self, path, args): print path, args def broadcast(self, path, *args): for d in self.devices: liblo.send(d, path, *args) s = SerialOsc() liblo.send(target, '/serialosc/list', 'localhost', s.port) t0 = time.time() phase = [0] * len(s.freq) while True: s.recv(10) if len(s.devices) > 0: if time.time() - t0 < 1. / 120.: continue tnow = time.time() dt = tnow - t0 t0 = tnow grid_map = [0] * 8
def disable_part(self, i): liblo.send(self.osc_target, "/part%d/Penabled" % i, False)
def add_loop(self): liblo.send(self.target, "/loop_add", 2, 50) self.loop_count = self.loop_count + 1
def println(num, s): s = truncate_mid(s, 20) liblo.send(osc_target, '/oled/gPrintln', 1, 2, num * 11 + 2, 8, 1, s)
def ping(self, timeout=20): self.ping_event.clear() liblo.send(self.target, "/ping", self.home_url, "/ping") return self.ping_event.wait(timeout)
def quit(self): liblo.send(self.target, "/quit")
def set_threshold(self, threshold): liblo.send(self.target, "/sl/-1/set", "rec_thresh", threshold)
def reset(self): liblo.send(self.target, "/loop_del", -1) self.add_loop() self.loop_count = 1
def send_sldown(self, command): liblo.send(self.target, "/sl/-1/down", command)
def clear_screen(): liblo.send(osc_target, '/oled/gClear', 1, 1)
def cb_osc_automate_active_slot(self, path, args, types, src): if self.current_slot_zctrl: slot_i = args[0] logging.debug("Automate active-slot: %s" % slot_i) # Add extra info to zctrl self.current_slot_zctrl.slot_i = int(slot_i) # Add zctrl to slots dictionary self.slot_zctrls[ self.current_slot_zctrl.osc_path] = self.current_slot_zctrl # set_midi_learn if self.current_slot_zctrl.midi_learn_cc is not None: zcc = (self.current_slot_zctrl.midi_learn_chan * 128) + self.current_slot_zctrl.midi_learn_cc liblo.send(self.osc_target, "/automate/slot%d/learning" % slot_i, 0) liblo.send(self.osc_target, "/automate/slot%d/active" % slot_i, True) #sleep(0.05) liblo.send(self.osc_target, "/automate/slot%d/name" % slot_i, self.current_slot_zctrl.symbol) #logging.debug("OSC send => /automate/slot%d/name '%s'" % (slot_i, self.current_slot_zctrl.symbol)) liblo.send(self.osc_target, "/automate/slot%d/midi-cc" % slot_i, zcc) #logging.debug("OSC send => /automate/slot%d/midi-cc %d" % (slot_i, zcc)) liblo.send(self.osc_target, "/automate/slot%d/param0/active" % slot_i, True) liblo.send(self.osc_target, "/automate/slot%d/param0/used" % slot_i, True) liblo.send(self.osc_target, "/automate/slot%d/param0/path" % slot_i, self.current_slot_zctrl.osc_path) logging.debug("Automate Slot %d SET: %s => %d" % (slot_i, self.current_slot_zctrl.osc_path, zcc)) self.current_slot_zctrl = None # midi_learn else: # Send twice for get it working when re-learning ... liblo.send(self.osc_target, "/automate/slot%d/clear" % slot_i) liblo.send(self.osc_target, "/automate/learn-binding-new-slot", self.current_slot_zctrl.osc_path)
def request_state(self, timeout=1): self.state_event.clear() liblo.send(self.target, "/sl/-1/get", "state", self.home_url, "/state") self.state_event.wait(timeout) return self.state
def list_device(self, path, args): print 'Found %s/%s at %s' % ( args[0], args[1], args[2], ) device = liblo.Address(args[2]) self.devices.append(device) if args[0] == MK: liblo.send(device, '/sys/prefix', 'mk') liblo.send(device, '/mk/grid/led/all', 0) elif args[0] == ARC: liblo.send(device, '/sys/prefix', 'arc') liblo.send(device, '/arc/ring/map', 0, *(xrange(64))) liblo.send(device, '/arc/ring/map', 1, *(xrange(64))) liblo.send(device, '/sys/port', self.port) liblo.send(device, '/sys/host', 'localhost')
def invert_line(num): liblo.send(osc_target, '/oled/gInvertArea', 1, 0, num * 11 + 1, 127, 11)
def send(addr, args): global osc_target liblo.send(osc_target, addr, args)
def reset_midi_learn(self): logging.info("Reset MIDI-learn ...") liblo.send(self.osc_target, "/automate/clear", "*") self.current_slot_zctrl = None self.slot_zctrls = {}
def testSendReceive(self): liblo.send(1234, '/foo', 42, ('b', [4, 8, 15, 16, 23, 42]), ('m', (6, 6, 6, 0))) assert self.server.recv() == True assert self.server.cb.path == '/foo' assert len(self.server.cb.args) == 3
def set_midi_chan(self, layer): if layer.part_i is not None: liblo.send(self.osc_target, "/part%d/Prcvchn" % layer.part_i, layer.get_midi_chan())
def broadcast(self, path, *args): for d in self.devices: liblo.send(d, path, *args)
# create osc server, listening on port 8005 try: oscServer = liblo.Server(8005) except liblo.ServerError, err: print str(err) sys.exit() # make osc address and send the syn message to get comms try: target = liblo.Address(8000) except liblo.AddressError, err: print str(err) sys.exit() # send message "/foo/message1" with int, float and string arguments liblo.send(target, "/syn", 8005) def draw_floor(x,z): x=x*0.5 z=z*0.5 # this would be better as a grid because the gllighting works better glBegin(GL_QUADS) glColor3f(0.3,0.3,0.3) glNormal3f( 0, 1, 0) glVertex3f( x, 0,-z) glVertex3f(-x, 0,-z) glVertex3f(-x, 0, z) glVertex3f( x, 0, z) glEnd() def draw_box(x,y,z):
# this example requires the pyliblo library from http://das.nasophon.de/pyliblo import liblo, sys # set the target address where MidiOSC will be listening (assumes the default port is used) try: midiosc = liblo.address("239.0.0.1", 8000) except liblo.AddressError, err: print str(err) sys.exit() # change the device name to something appropriate for your system device_name = "midi_device" osc_address = "/midi/" + device_name + "/0" # send a note on with note number 60 and velocity 100 liblo.send(midiosc, osc_address, "note_on", 60, 100) # send a note off with note number 60 and velocity 0 liblo.send(midiosc, osc_address, "note_off", 60, 0) # now to receive some messages try: server = liblo.Server(7001) except liblo.ServerError, err: print str(err) sys.exit() def callback(path, args, types, src): print "Got $s" % (path) for a, t in zip(args, types):
def read_imu(imu, target): # get the data from the imu data = imu.getIMUData() gyro = data['gyro'] accel = data['accel'] compass = data['compass'] fusion = data['fusionPose'] fusionq = data['fusionQPose'] # send data via OSC liblo.send(target, "/gx/r/fusX", fusion[0], "fusionX") liblo.send(target, "/gx/r/fusY", fusion[1], "fusionY") liblo.send(target, "/gx/r/fusZ", fusion[2], "fusionZ") liblo.send(target, "/gx/r/fusqX", fusionq[0], "fusionqX") liblo.send(target, "/gx/r/fusqY", fusionq[1], "fusionqY") liblo.send(target, "/gx/r/fusqZ", fusionq[2], "fusionqZ") liblo.send(target, "/gx/r/fusqA", fusionq[3], "fusionqA") gyroX = numpy.interp(gyro[0], [-1.0, 1.0], [0.0, 1.0]) liblo.send(target, "/gx/r/gyrX", gyroX, "gyroX") gyroY = numpy.interp(gyro[1], [-1.0, 1.0], [0.0, 1.0]) liblo.send(target, "/gx/r/gyrY", gyroY, "gyroY") gyroZ = numpy.interp(gyro[2], [-1.0, 1.0], [0.0, 1.0]) liblo.send(target, "/gx/r/gyrZ", gyroZ, "gyroZ") accelX = numpy.interp(accel[0], [-1.0, 1.0], [0.0, 1.0]) liblo.send(target, "/gx/r/accX", accelX, "accelX") accelY = numpy.interp(accel[1], [-1.0, 1.0], [0.0, 1.0]) liblo.send(target, "/gx/r/accY", accelY, "accelY") accelZ = numpy.interp(accel[2], [-1.0, 1.0], [0.0, 1.0]) liblo.send(target, "/gx/r/accZ", accelZ, "accelZ") compassX = numpy.interp(compass[0], [-60.0, 15.0], [0.0, 1.0]) liblo.send(target, "/gx/r/magX", compassX, "compassX") compassY = numpy.interp(compass[1], [-50.0, 20.0], [0.0, 1.0]) liblo.send(target, "/gx/r/magY", compassY, "compassY") compassZ = numpy.interp(compass[2], [-50.0, 40.0], [0.0, 1.0]) liblo.send(target, "/gx/r/magZ", compassZ, "compassZ")
def main(): video_flags = OPENGL | DOUBLEBUF #target = liblo.Address(7111) pygame.init() pygame.display.set_caption("Kinect handtracker demo (#pmrhack)") # setup targets targets = [] for ep in endpoints: targets.append(liblo.Address(ep[0], ep[1])) pygame.display.set_mode((640, 480), video_flags) resize((640, 480)) init() c = CommandState() ythreshold = 0.2 zthreshold = 0.4 rotate_threshold = 0.5 side_threshold = 0.5 arms_out_threshold = 0.3 frames = 0 ticks = pygame.time.get_ticks() while 1: commands = [] event = pygame.event.poll() if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): break if event.type == KEYDOWN and event.key == K_t: commands.append('takeoff') if event.type == KEYDOWN and event.key == K_l: commands.append('landing') for target in targets: for command in commands: print commands liblo.send(target, "/command", command) draw(server, c) pygame.display.flip() server.recv(100) for player in (x for x in server.lh.keys() if server.lh[x][0] > -10.0): # Only send real data rh = server.rh[player] lh = server.lh[player] ls = server.ls[player] rs = server.rs[player] dx = (rs[0] + ls[0]) - (rh[0] + lh[0]) dy = (rs[1] + ls[1]) - (rh[1] + lh[1]) dz = (rs[2] + ls[2]) - (rh[2] + lh[2]) - 0.1 # fudge dh = abs(rh[0] - lh[0]) + abs(rh[1] - lh[1]) + abs(rh[2] - lh[2]) dr = rh[2] - lh[2] dside = rh[1] - lh[1] if abs(dy) > ythreshold and dh > arms_out_threshold: if dy < 0: if c.update(player, 'u', True): commands.append('u') else: if c.update(player, 'd', True): commands.append('d') else: if c.update(player, 'u', False): commands.append('nu') if c.update(player, 'd', False): commands.append('nd') if abs(dr) > rotate_threshold and dh > arms_out_threshold: if dr < 0: if c.update(player, 'rl', True): commands.append('rl') else: if c.update(player, 'rr', True): commands.append('rr') else: if c.update(player, 'rl', False): commands.append('nrl') if c.update(player, 'rr', False): commands.append('nrr') if abs(dside) > side_threshold and dh > arms_out_threshold: if dside < 0: if c.update(player, 'yl', True): commands.append('yl') else: if c.update(player, 'yr', True): commands.append('yr') else: if c.update(player, 'yl', False): commands.append('nyl') if c.update(player, 'yr', False): commands.append('nyr') if abs(dz) > zthreshold and dh > arms_out_threshold: if dz < 0: if c.update(player, 'b', True): commands.append('b') else: if c.update(player, 'f', True): commands.append('f') else: if c.update(player, 'f', False): commands.append('nf') if c.update(player, 'b', False): commands.append('nb') if commands: print "Commands to be sent: %s" % commands for target in targets: liblo.send(target, "/hands", player, *(server.rh[player] + server.lh[player])) liblo.send(target, "/shoulders", player, *(server.rs[player] + server.ls[player])) liblo.send( target, "/combined", player, *(server.rh[player] + server.lh[player] + server.rs[player] + server.ls[player])) liblo.send(target, "/differentials", dy, dz, dh, dr, dside) for command in commands: print commands liblo.send(target, "/command", command) commands = [] frames = frames + 1 print "fps: %d" % ((frames * 1000) / (pygame.time.get_ticks() - ticks))
# release threshold rths = liblo.Message("/rths") for i in electrodes_range: rths.add(release_threshold) bundle.add(rths) # filtered values fdat = liblo.Message("/fdat") for i in electrodes_range: fdat.add(sensor.get_filtered_data(i)) bundle.add(fdat) # baseline values bval = liblo.Message("/bval") for i in electrodes_range: bval.add(sensor.get_baseline_data(i)) bundle.add(bval) # value pairs diff = liblo.Message("/diff") for i in electrodes_range: diff.add(sensor.get_baseline_data(i) - sensor.get_filtered_data(i)) bundle.add(diff) # send our bundle to given address liblo.send(address, bundle) # a little delay so that we don't just sit chewing CPU cycles sleep(0.01)
def register_state_update(self): liblo.send(self.target, "/sl/-1/register_auto_update", "state", 100, self.home_url, "/state")