def setup(): # OSC global client client = OSCClient() client.connect(("localhost", 7300)) # DISPLAY window_width = 640 window_height = 480 # OPENCV # img = cv2.imread(filename) global camera camera = cv2.VideoCapture(0) camera.set(3, window_width) camera.set(4, window_height) # ds_factor = 1.0 # FACIAL FEATURES DETECTORS global face_detector, mouth_detector, smile_detector, nose_detector, right_eye_detector, left_eye_detector face_detector = FaceDetector() # eye_detector = EyeDetector() mouth_detector = MouthDetector() smile_detector = SmileDetector() nose_detector = NoseDetector() # right_ear_detector = RightEarDetector() right_eye_detector = RightEyeDetector() left_eye_detector = LeftEyeDetector()
def init(osc_setup): host, port, root = osc_setup client = OSCClient() client.connect((host, port)) print "Connected to the OSC server %s:%s%s" % osc_setup send_parameter('osd_initialized', 'Done') return client
def init(osc_setup): host, port, root = osc_setup client = OSCClient() client.connect( (host, port) ) print "Connected to the OSC server %s:%s%s" %osc_setup send_parameter('osd_initialized','Done') return client
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 ) )
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 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();
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)
def main(): global client, group, clientOSC try: rospy.init_node("test_move", anonymous=True, disable_signals=True) client = actionlib.SimpleActionClient('follow_joint_trajectory', FollowJointTrajectoryAction) print "Waiting for server..." client.wait_for_server() print "Connected to server" parameters = rospy.get_param(None) print "============ Starting tutorial setup" moveit_commander.roscpp_initialize(sys.argv) time.sleep(1) robot = moveit_commander.RobotCommander() group = moveit_commander.MoveGroupCommander("manipulator") clientOSC = OSCClient() clientOSC.connect( ("192.168.1.51", 12000) ) thread.start_new_thread ( printRoll, () ) move1() except KeyboardInterrupt: rospy.signal_shutdown("KeyboardInterrupt") raise
def messageServer(self, messagePath, argument): client = OSCClient() client.connect((self.serverIP, self.serverPort)) message = OSCMessage(messagePath) message.append(argument) client.send(message)
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 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))
def OSCsend(name, oscaddress, oscargs=''): ip = midi2OSC[name]["oscip"] port = midi2OSC[name]["oscport"] osclient = OSCClient() osclient.connect((ip, port)) oscmsg = OSCMessage() oscmsg.setAddress(oscaddress) oscmsg.append(oscargs) try: if gstt.debug > 0: print("Midi OSCSend : sending", oscmsg, "to", name, "at", gstt.LjayServerIP, ":", PluginPort) osclient.sendto(oscmsg, (ip, port)) oscmsg.clearData() #if gstt.debug >0: # print oscaddress, oscargs, "was sent to",name return True except: if gstt.debug > 0: print('Midi OSCSend : Connection to IP', ip, ':', port, 'refused : died ?') #sendWSall("/status No plugin.") #sendWSall("/status " + name + " is offline") #sendWSall("/" + name + "/start 0") #PluginStart(name) return False
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
def main(): global bRun global inOSCport, outOSCport global myOSC_Server, myOSC_Client global cTrial, nTrials, breaksxTrial cTrial = 1 global debug_data global CS_US_1 CS_US_1['inputs']=[] cerebellumConfig['weights']=[] cerebellumConfig['config']=[] cerebellumConfig['constants']=[] debug_data['trials']=[] if save_bases: debug_data['basis']=[] debug_data['inputs']=[] inOSCport = 1234 outOSCport = 1235 # myOSC_Server = OSCServer( ('' , inOSCport) ) # myOSC_Client = OSCClient() # myOSC_Client.connect( ('10.0.0.116' , outOSCport) ) myOSC_Server = OSCServer( ('127.0.0.1' , inOSCport) ) myOSC_Client = OSCClient() myOSC_Client.connect( ('127.0.0.1' , outOSCport) ) print "Receiving messages /trial,/input in port", inOSCport print "Sending messages to port", outOSCport myOSC_Server.addMsgHandler("/config", receiveConfig) myOSC_Server.addMsgHandler("/trial", receiveTrial) myOSC_Server.addMsgHandler("/endtrial", receiveEndTrial) myOSC_Server.addMsgHandler("/input", receiveInput) myOSC_Server.addMsgHandler("/debug", receiveDebug) myOSC_Server.addMsgHandler("/update", receiveUpdate) myOSC_Server.addMsgHandler("/freeze", receiveFreeze) myOSC_Server.addMsgHandler("/saveConfig", receiveSaveConf) # if (cTrial==nTrials): # pl.figure(figsize=(10,6)) # plot(breaksxTrial) print "Ready" myOSC_Server.serve_forever()
def connectOsc(): global client, timeLastConnection if timeLastConnection < time.time() - 7200: print("connecting to OSC server") updateDNS() client = OSCClient() client.connect( ("146.164.80.56", 22244) ) timeLastConnection = time.time()
def connectOsc(): global client, timeLastConnection if timeLastConnection < time.time() - 7200: # Reconnect every two hours print("connecting to OSC server") updateDNS() client = OSCClient() client.connect(("146.164.80.56", 22244)) timeLastConnection = time.time()
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 get_osc_client(host='localhost', port=defaults['port'], say_hello=False): # String, int -> OSCClient client = OSCClient() client.connect((host, port)) # TODO Make this work if say_hello: send_simple_message(client, "/hello", timeout=None) return client
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"))
def main(): # OSC SERVER myip = socket.gethostbyname(socket.gethostname()) myip = "127.0.0.1" print("IP adress is : "+myip) try: server = SimpleServer((myip, 12354)) except: print(" ERROR : creating server") print("server created") try: st = threading.Thread(target = server.serve_forever) except: print(" ERROR : creating thread") try: st.start() except: print(" ERROR : starting thread") print(" OSC server is running") # OSC CLIENT global client client = OSCClient() client.connect( ('127.0.0.1', 9998)) #START ON BOOT global machine machine = 7 start_app() # MAIN LOOP global runningApp runningApp = True print(" ===== STARTING MAIN LOOP ====" ) while runningApp: # This is the main loop # Do something here try: time.sleep(1) except: print("User attempt to close programm") runningApp = False #CLOSING THREAD AND SERVER print(" Ending programme") server.running = False print(" Join thread") st.join() server.close() print(" This is probably the end")
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 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 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 )
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 OSCServer(object): def __init__(self, ip, port,address="/openbci"): self.ip = ip self.port = port self.address = address if len(args) > 0: self.ip = args[0] if len(args) > 1: self.port = args[1] if len(args) > 2: self.address = 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) )
def app(): global dxlIO, server, client ports = pypot.dynamixel.get_available_ports() if not ports: raise IOError('No port available.') dxlIO = pypot.dynamixel.DxlIO(ports[0]) availableIDs = dxlIO.scan() server = OSCServer(('0.0.0.0', 8000)) for motorID in availableIDs: server.addMsgHandler('/motor/' + str(motorID), motorHandler) # Register OSC handlers for each found ID client = OSCClient() client.connect(('localhost', 8001)) print 'Ready. Found ID(s) ' + str(availableIDs) while True: server.handle_request() sleep(0.01)
class OscSender(): def __init__(self, osc_setup): self.host, self.port, self.root = osc_setup self.client = OSCClient() self.client.connect((self.host, self.port)) print "Connected to the OSC server %s:%s%s" % osc_setup self.send_parameter('osd_initialized', 'Done') def send_parameters(self, hand_params): for path, value in hand_params.items(): self.send_parameter(path, value) def send_parameter(self, rel_path, data): full_path = self.root + rel_path #self.client.send( OSCMessage( full_path, data ) ) print "[osc]\t%s\t\t\t%s" % (full_path, data)
def SendUI(oscaddress,oscargs=''): oscmsg = OSCMessage() oscmsg.setAddress(oscaddress) oscmsg.append(oscargs) osclientlj = OSCClient() osclientlj.connect((gstt.TouchOSCIP, gstt.TouchOSCPort)) #print("MIDI Aurora sending UI :", oscmsg, "to",gstt.TouchOSCIP,":",gstt.TouchOSCPort) try: osclientlj.sendto(oscmsg, (gstt.TouchOSCIP, gstt.TouchOSCPort)) oscmsg.clearData() except: log.err('Connection to Aurora UI refused : died ?') pass
def SendAU(oscaddress,oscargs=''): oscmsg = OSCMessage() oscmsg.setAddress(oscaddress) oscmsg.append(oscargs) osclientlj = OSCClient() osclientlj.connect((gstt.myIP, 8090)) # print("MIDI Aurora sending itself OSC :", oscmsg, "to localhost:8090") try: osclientlj.sendto(oscmsg, (gstt.myIP, 8090)) oscmsg.clearData() except: log.err('Connection to Aurora refused : died ?') pass
class OscSender(): def __init__(self, osc_setup): self.host, self.port, self.root = osc_setup self.client = OSCClient() self.client.connect( (self.host, self.port) ) print "Connected to the OSC server %s:%s%s" %osc_setup self.send_parameter('osd_initialized','Done') def send_parameters(self, hand_params): for path, value in hand_params.items(): self.send_parameter(path, value) def send_parameter(self, rel_path, data): full_path = self.root+rel_path #self.client.send( OSCMessage( full_path, data ) ) print "[osc]\t%s\t\t\t%s" %(full_path, data)
def setup(): # OSC global client client = OSCClient() client.connect(("localhost", 7300)) # DISPLAY global full_screen full_screen = False # global window_width, window_height window_width = 640 window_height = 480 # PYGAME global FPS FPS = 30 pygame.init() global screen screen = pygame.display.set_mode((window_width, window_height))#, 0, 32) pygame.display.set_caption("Le Reuz") global clock clock = pygame.time.Clock() global logo, grass logo = pygame.image.load("pictures/lereuz.jpg").convert() grass = pygame.image.load("pictures/test5.jpg").convert() global index index = 0 global fontObj fontObj = pygame.font.Font('freesansbold.ttf', 16) # OPENCV global camera camera = cv2.VideoCapture(0) camera.set(3, window_width) camera.set(4, window_height) # ds_factor = 1.0 # logo = cv2.imread("pictures/lereuz.jpg") # FACIAL FEATURES DETECTORS global face_detector, mouth_detector, smile_detector, nose_detector, right_eye_detector, left_eye_detector face_detector = FaceDetector() mouth_detector = MouthDetector() smile_detector = SmileDetector() nose_detector = NoseDetector() right_eye_detector = RightEyeDetector() left_eye_detector = LeftEyeDetector()
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 SendResol(oscaddress, oscargs): oscmsg = OSCMessage() oscmsg.setAddress(oscaddress) oscmsg.append(oscargs) osclientresol = OSCClient() osclientresol.connect((oscIPresol, oscPORTresol)) print("lj23layers sending OSC message : ", oscmsg, "to Resolume", oscIPresol, ":", oscPORTresol) try: osclientresol.sendto(oscmsg, (oscIPresol, oscPORTresol)) oscmsg.clearData() except: print('Connection to Resolume refused : died ?') 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]]]
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
def main(): print "=================" print "Sratch2OSC %s" % VERSION print "=================" print "" while True: s = connect() osc_client = OSCClient() osc_client.connect(OSC_HOST, OSC_PORT) if (s): print _("Connected to Scratch") s.broadcast("goo") s.broadcast("choki") s.broadcast("par") listen(s, osc_client) time.sleep(5)
class Sender(): #Takes the short moves defined by the user, parse them and store them in a strucured hash table. #Process the gestures from the listener : find the associated command, ask for a confirmation, execute the command. def __init__(self, osc_setup): self.host, self.port, self.root = osc_setup self.client = OSCClient() self.client.connect( (self.host, self.port) ) print "Connected to the OSC server %s:%s%s" %osc_setup self.send('init','leap_listener initialized') def send_hand(self, hand_params): print '********* HAND ***********' which = hand_params['which'] for path, value in hand_params.items(): path = path.replace('<which>',which) self.send(path, value) def send(self, rel_path, data): full_path = self.root+rel_path #self.client.send( OSCMessage( full_path, data ) ) print "[osc]\t%s\t\t\t%s" %(full_path, data)
def SendLJ(oscaddress, oscargs=''): oscmsg = OSCMessage() oscmsg.setAddress(oscaddress) oscmsg.append(oscargs) osclientlj = OSCClient() osclientlj.connect((redisIP, 8002)) #print("lj23layers for", name, "sending OSC message :", oscmsg, "to", redisIP, ":8002") if gstt.debug > 0: print("lj23layers for", name, "sending OSC message :", oscmsg, "to", redisIP, ":8002") try: osclientlj.sendto(oscmsg, (redisIP, 8002)) oscmsg.clearData() except: print('Connection to LJ refused : died ?') pass
def main(): # OSC SERVER # This is a trick to get IP, but 0.0.0.0 allows localhost and external connection #myip = get_ip() myip = "0.0.0.0" print("osc server IP adress is : "+myip) try: server = SimpleServer((myip, 12345)) except: print(" ERROR : creating server") print("server created") try: st = threading.Thread(target = server.serve_forever) except: print(" ERROR : creating thread") try: st.start() except: print(" ERROR : starting thread") print(" OSC server is running") # OSC LUCIBBOX CLIENT global client_lucibox client_lucibox = OSCClient() client_lucibox.connect( ('127.0.0.1', 9999)) # OSC NODEJS CLIENT global client_nodejs client_nodejs = OSCClient() client_nodejs.connect( ('127.0.0.1', 9998)) # OSC OF CLIENT global client_of client_of = OSCClient() client_of.connect( ('127.0.0.1', 9997)) # MAIN LOOP global runningApp runningApp = True print(" ===== STARTING MAIN LOOP ====" ) while runningApp: # This is the main loop # Do something here try: time.sleep(1) except: print("User attempt to close programm") runningApp = False #CLOSING THREAD AND SERVER print(" Ending programme") server.running = False print(" Join thread") st.join() server.close() print(" This is probably the end")
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 ) )
class Sender(): def __init__(self, osc_setup): self.host, self.port, self.root = osc_setup self.client = OSCClient() self.client.connect( (self.host, self.port) ) print "Connected to the OSC server %s:%s%s" %osc_setup self.send('init','leap listener program started') def send_hand(self, hand_params): print '********* HAND ***********' for path, value in hand_params.items(): self.send(path, value) def send_gesture(self, gesture_params): print '********* GESTURE ***********' for path, value in gesture_params.items(): self.send(path, value) def send(self, rel_path, data): full_path = self.root+rel_path #self.client.send( OSCMessage( full_path, data ) ) print "[osc]\t%s\t\t\t%s" %(full_path, data)
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)
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()
#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)
def unpack(data, totalCoordinates, socket): cX = totalCoordinates[0] cY = totalCoordinates[1] client = OSCClient() client.connect(("localhost", socket)) """ Prepare and send OSC bundles to Max from a list of tuples of coordinates. """ def bundlePolyline(coordinates, speed, polylineType, passengers, coordsX, coordsY): for pair in coordinates: # create an OSC bundle: bundle = OSCBundle() # append polylineType: "trip" or "delay" (data for in between current and next trip) bundle.append({'addr': "/curr", 'args': [polylineType]}) # append min/max longX and latY to bundle: bundle.append({'addr': "/minX", 'args': [min(coordsX)]}) bundle.append({'addr': "/maxX", 'args': [max(coordsX)]}) bundle.append({'addr': "/minY", 'args': [min(coordsY)]}) bundle.append({'addr': "/maxY", 'args': [max(coordsY)]}) # append longX and latY to bundle bundle.append({'addr': "/longX", 'args': [pair[0]]}) bundle.append({'addr': "/latY", 'args': [pair[1]]}) # append start/end longX and latY of coordinates list xVals = [coords[0] for coords in coordinates] bundle.append({'addr': "/startX", 'args': [xVals[0]]}) bundle.append({'addr': "/endX", 'args': [xVals[len(xVals) - 1]]}) yVals = [coords[1] for coords in coordinates] bundle.append({'addr': "/startY", 'args': [yVals[0]]}) bundle.append({'addr': "/endY", 'args': [yVals[len(yVals) - 1]]}) # append passengers bundle.append({'addr': "/passengers", 'args': [passengers]}) # send bundle to Max: client.send(bundle) # delay time to even out polyline steps time.sleep(speed) """ Read the next line in the data file. """ for row in data: """ Parse and set time stamps in minutes (i.e. 4:02 == 242). """ pickup = row["pickuptime"].split(" ")[1] pickup = pickup.split(":") pickup = (int(pickup[0])*60) + int(pickup[1]) dropoff = row["dropofftime"].split(" ")[1] dropoff = dropoff.split(":") dropoff = (int(dropoff[0])*60) + int(dropoff[1]) nextPickup = row["nextpickuptime"].split(" ")[1] nextPickup = nextPickup.split(":") nextPickup = (int(nextPickup[0])*60) + int(nextPickup[1]) """ Decode trippolyline. """ latLongList = polylinemapper.decode(row["trippolyline"]) passengers = row["passengers"] latLongSpeed = round((dropoff - pickup) / (2*len(latLongList)), 10) # translate 1 minute in RT == 0.5 seconds bundlePolyline(latLongList, latLongSpeed, "trip", passengers, cX, cY) """ Decode nextpolyline. """ nextLatLong = polylinemapper.decode(row["nextpolyline"]) passengers = 0 nextSpeed = round((nextPickup - dropoff) / (2*len(nextLatLong)), 10) # translate 1 minute in RT == 0.5 seconds bundlePolyline(nextLatLong, nextSpeed, "delay", passengers, cX, cY) client.close()
import numpy as np import math from collections import defaultdict from OSC import OSCServer, OSCClient, OSCMessage import os from time import time N = 1024 p5.size(1024, 512) client = OSCClient() client.connect(('127.0.0.1', 9999)) recent = [] window = blackman(N) vectors = [] labels = [] def getAmplitude(data): freq = sfft.fft(data * window) nyquist = len(freq)/2 return np.absolute(freq[:nyquist]) clf = SVC(probability=True, kernel = 'rbf') model = lda.LDA(n_components=2) projection = [] p_min = None
# Set Buttons as Inputs # 5 Buttons on pins # Pins: 5, 6, 12, 13, 16 BUT1 = 5 BUT2 = 6 BUT3 = 12 BUT4 = 13 BUT5 = 16 BUT6 = 19 #debounce delay in ms DEBOUNCE = 5 client = OSCClient() client.connect(("127.0.0.1", 57122)) def gpio_callback(gpio_id, val): print("gpio %s: %s" % (gpio_id, val)) if (val == 1): obj = OSCMessage("/b/r %s" % gpio_id) else: obj = OSCMessage("/b/p %s" % gpio_id) client.send(obj) RPIO.add_interrupt_callback(BUT1, gpio_callback, debounce_timeout_ms=DEBOUNCE) RPIO.add_interrupt_callback(BUT2, gpio_callback, debounce_timeout_ms=DEBOUNCE) RPIO.add_interrupt_callback(BUT3, gpio_callback, debounce_timeout_ms=DEBOUNCE)
import socket import threading import cPickle as pickle import time import json from graph import Graph from select import select from OSC import OSCClient, OSCMessage clients = [] renderers = [] graphers = [] graph = [] current_state = 0 osc = OSCClient() osc.connect( ("localhost", 31415) ) graph_file = 'graph_ex.pi' def get_graph(graph): """Loads a pickled graph from a file. **Keyword arguments:** * graph -- file containing a pickled graph Returns an unpickled graph.""" f = open(graph,'rb') return pickle.load(f) def client_thread(c): """Handles the communication with a single client.
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)