def __init__(self, address=("127.0.0.1", 9000), listen_port=9001): self.beat_callback = None self.startup_callback = None self.listen_port = listen_port #------------------------------------------------------------------------ # Handler callbacks for particular messages from Live. # Used so that other processes can register callbacks when states change. #------------------------------------------------------------------------ self.handlers = {} self.osc_address = address self.osc_client = SimpleUDPClient(address[0], address[1]) dispatcher = Dispatcher() dispatcher.set_default_handler(self.handler) self.osc_server = BlockingOSCUDPServer(("127.0.0.1", listen_port), dispatcher) self.osc_server_thread = None self.osc_read_event = None self.osc_timeout = 3.0 self.osc_server_events = {} self.query_address = None self.query_rv = [] self.listen()
def start(self): print( f"OSC UDP client sending to {self.osc_client_ip} on port {self.osc_port}, address: {self.osc_address}" ) print( f"Connecting to serial at {self.serial_device} with baud {self.baud_rate}" ) self.osc_client = SimpleUDPClient(self.osc_client_ip, self.osc_port) self.ser = serial.Serial( self.serial_device, baudrate=self.baud_rate, timeout=None ) self.ser.flushInput() while True: try: ser_bytes = self.ser.readline() # print(ser_bytes) decoded_bytes = float(ser_bytes[0 : len(ser_bytes) - 2].decode("utf-8")) # Send a float through OSC self.osc_client.send_message(self.osc_address, decoded_bytes) print(decoded_bytes) # with open("test_data.csv","a") as f: # writer = csv.writer(f,delimiter=",") # writer.writerow([time.time(),decoded_bytes]) except Exception as e: print(f"Keyboard interrupt!: {e}" ) break
def __init__(self): #User configurable parameters self.limit = 4 self.tour_video_layer = 17 self.tour_video_clip = 2 self.tour_video_button_id = 0 self.box_video_layer = 16 self.box_video_start_column = 10 self.box_waiting_video_layer = 15 self.blank_waiting_video_column = 10 #OSC related self.osc_client = SimpleUDPClient("127.0.0.1", 7000) self.osc_dispatcher = Dispatcher() self.osc_dispatcher.map("/composition/layers/*/clips/*/connected", self.video_handler) self.osc_dispatcher.set_default_handler(self.debug_handler) #Internal variables self.items = [] self.current_clip = 0 self.current_layer = 0 self.playing_tour_video = False self.playing_idle_video = False self.loop = asyncio.get_running_loop() self.current_box_waiting_video_layer = 0 self.waiting_list = []
class MessageSender: def __init__(self, port): self.client = SimpleUDPClient("127.0.0.1", port) def sendMessage(self, address, messages): print(f'sending message {address}: {messages}') self.client.send_message(address, messages)
def __init__(self, machine): """Initialise switch player.""" self.log = logging.getLogger('OSC Plugin') self.machine = machine # type: MachineController if 'osc_plugin' not in machine.config: machine.log.debug('"osc_plugin:" section not found in ' 'machine configuration, so the OSC' 'plugin will not be used.') return if not Dispatcher: raise AssertionError( "To use the OSC plugin you need to install the pythonosc extension." ) self.config = self.machine.config['osc_plugin'] self.machine.config_validator.validate_config("osc_plugin", self.config) if not self.config['enabled']: return self.dispatcher = Dispatcher() self.dispatcher.map("/sw/*", self.handle_switch) self.server = AsyncIOOSCUDPServer( (self.config['server_ip'], self.config['server_port']), self.dispatcher, self.machine.clock.loop) self.machine.events.add_async_handler("init_phase_5", self._start) self.client = SimpleUDPClient(self.config['client_ip'], self.config['client_port'])
def send_to_vuo(hand, host=settings.ONEHAND_VUO_HOST, port=settings.ONEHAND_VUO_PORT): osc_client = SimpleUDPClient(address=host, port=port) for finger, i, data in hand.finger_to_finger(): osc_client.send_message( settings.ONEHAND_OSC_FINGER_ADDRESS.format(finger, i), data)
def __init__(self): # IP address, if you want to communicate with a device on the same network, you probably need to change stuff here. # especially differentiate between the PC and the device IP. However, this allows you to run processing on android # but do optimization on desktop and still have wireless communication. self.ip = "127.0.0.1" # the port we receive data from processing on self.receiving_port = 12001 # the port where processing expects data to be send. self.sending_port = 12000 # OSC works with addresses. Basically we can filter on the incoming address and have different handler based on an address. # in a case we dont recoginize the address, we use the default handler. self.dispatcher = Dispatcher() self.dispatcher.map("/filter", self.print_handler) self.dispatcher.map("/quit", self.quit_handler) self.dispatcher.set_default_handler(self.default_handler) # the client we use for sending data. self.sending_client = SimpleUDPClient( self.ip, self.sending_port) # Create client # a boolean to see whether we need to quit the server based on incoming messages. self.run = True
def start_send_osc(self): if not self.sending: self.sending = True self.stop_send_event = threading.Event() self.client = SimpleUDPClient(self.remote_ip, self.remote_port) self.osc_thread = threading.Thread(target=self.send_osc_loop, args=()) self.osc_thread.start()
class Board(object): def __init__(self, ip: str, port: int) -> None: self._ip = ip self._port = port self._client = SimpleUDPClient(self._ip, self._port) def _send_message(self, event, message: str, param: Any = None) -> None: if event.event_type == "up": self._client.send_message(message, param)
def __init__(self) -> None: super().__init__() self.name = "unknown-{}".format(str(uuid4())[:8]) self.description = "no description" self.status = None self.status_document = None self.host = socket.gethostname() self.ip = socket.gethostbyname(self.host) self.status = STATUS.IDLE self.osc_client = SimpleUDPClient(settings.SUS_EST_VUO_MILLUMIN_HOST, settings.SUS_EST_VUO_MILLUMIN_PORT)
def __init__(self, host, port): """ Args: host: Hostname to send OSC messages to port: Port number to send OSC messages to """ try: self.osc = SimpleUDPClient(host, port) except NameError: raise Exception("python-osc must be installed")
def __init__(self, ip, sending_to_port): """ Constructor for OSC_SENDER CLASS :param ip: ip address of client ==> 127.0.0.1 (for local host/ inter app communication on same machine) :param sending_to_port: the port on which pure data listens for incoming data """ self.ip = ip self.sending_to_port = sending_to_port self.client = SimpleUDPClient(self.ip, self.sending_to_port)
def __init__(self): self.client = SimpleUDPClient(self.ip, self.port) self.adcSR = ADCStreamReader() self.adc0 = self.adcSR.open('differential', channel=0, gain=16, data_rate=64, sleep=0) #self.adc3 = self.adcSR.open(differential=3, gain=16, data_rate=8, sleep=0) self.td = TrackingData() self.now = datetime.datetime.now()
def abort(): """ Sends an abort message (make the arm stop running program and return to its init position) to the UDPClient. :return: JSON Indicating success (200) """ address = "/Instructions" c = SimpleUDPClient('127.0.0.1', 5001) c.send_message(address, "___kill___") return json.dumps({'success': True}), 200, { 'ContentType': 'application/json' }
class Osc: """Control switches via OSC.""" def __init__(self, machine): """Initialise switch player.""" self.log = logging.getLogger('OSC Plugin') self.machine = machine # type: MachineController if 'osc_plugin' not in machine.config: machine.log.debug('"osc_plugin:" section not found in ' 'machine configuration, so the OSC' 'plugin will not be used.') return if not Dispatcher: raise AssertionError( "To use the OSC plugin you need to install the pythonosc extension." ) self.config = self.machine.config['osc_plugin'] self.machine.config_validator.validate_config("osc_plugin", self.config) if not self.config['enabled']: return self.dispatcher = Dispatcher() self.dispatcher.map("/sw/*", self.handle_switch) self.server = AsyncIOOSCUDPServer( (self.config['server_ip'], self.config['server_port']), self.dispatcher, self.machine.clock.loop) self.machine.events.add_async_handler("init_phase_5", self._start) self.client = SimpleUDPClient(self.config['client_ip'], self.config['client_port']) @asyncio.coroutine def _start(self): yield from self.server.create_serve_endpoint() self.machine.switch_controller.add_monitor(self._notify_switch_changes) def __repr__(self): """Return string representation.""" return '<Osc>' def handle_switch(self, switch_name, state): """Handle Switch change from OSC.""" self.machine.switch_controller.process_switch(switch_name, bool(state), logical=True) def _notify_switch_changes(self, change: MonitoredSwitchChange): """Send switch change to OSC client.""" self.client.send_message("/sw/{}".format(change.name), change.state)
class Client(Node): """A simple OSC client.""" def __init__(self, address="", ip="127.0.0.1", port=5005): if not address or not isinstance(address, str): raise ValueError("You must provide an address.") self._address = address self._client = SimpleUDPClient(ip, port) def update(self): if self.i.data is not None: for row in self.i.data.itertuples(index=False): self._client.send_message(self._address, row)
class OSCOutputDevice(OutputDevice): """ OSCOutputDevice: Wraps MIDI messages in OSC. /note [ note, velocity, channel ] /control [ control, value, channel ] """ def __init__(self, host, port): """ Args: host: Hostname to send OSC messages to port: Port number to send OSC messages to """ try: self.osc = SimpleUDPClient(host, port) except NameError: raise Exception("python-osc must be installed") def note_on(self, note=60, velocity=64, channel=0): self.osc.send_message("/note", velocity, channel) def note_off(self, note=60, channel=0): self.osc.send_message("/note", 0, channel) def control(self, control, value, channel=0): self.osc.send_message("/control", value, channel) def send(self, address, params=None): if params is not None: params = [Pattern.value(param) for param in params] self.osc.send_message(address, params)
class OSCOut: """ OSCOut: Wraps MIDI messages in OSC. /note [ note, velocity, channel ] /control [ control, value, channel ] """ def __init__(self, host="localhost", port=7000): self.osc = SimpleUDPClient(host, port) def tick(self, tick_length): pass def note_on(self, note=60, velocity=64, channel=0): msg = OSCMessage("/note") self.osc.send_message("/note", velocity, channel) def note_off(self, note=60, channel=0): self.osc.send_message("/note", 0, channel) def all_notes_off(self, channel=0): for n in range(128): self.note_off(n, channel) def control(self, control, value, channel=0): self.osc.send_message("/control", value, channel) def __destroy__(self): pass def send(self, address, params=None): self.osc.send_message(address, *params)
class OSCOut: """ OSCOut: Wraps MIDI messages in OSC. /note [ note, velocity, channel ] /control [ control, value, channel ] """ def __init__(self, host = "localhost", port = 7000): self.osc = SimpleUDPClient(host, port) def tick(self, tick_length): pass def note_on(self, note = 60, velocity = 64, channel = 0): msg = OSCMessage("/note") self.osc.send_message("/note", velocity, channel) def note_off(self, note = 60, channel = 0): self.osc.send_message("/note", 0, channel) def all_notes_off(self, channel = 0): for n in range(128): self.note_off(n, channel) def control(self, control, value, channel = 0): self.osc.send_message("/control", value, channel) def __destroy__(self): pass def send(self, address, params = None): self.osc.send_message(address, *params)
def __init__(self, address=("127.0.0.1", 9900), listen_port=9002): self.beat_callback = None self.startup_callback = None self.listen_port = listen_port #------------------------------------------------------------------------ # Handler callbacks for particular messages from Live. # Used so that other processes can register callbacks when states change. #------------------------------------------------------------------------ self.handlers = {} self.osc_address = address if OSC_BACKEND == 'liblo': self.osc_target = liblo.Address(address[0], address[1]) self.osc_server = liblo.Server(listen_port) self.osc_server.add_method(None, None, self.handler) self.osc_server.add_bundle_handlers(self.start_bundle_handler, self.end_bundle_handler) elif OSC_BACKEND == 'pythonosc': # TODO how to deal w/ bundles? even necessary? # (the handlers seem to be just logging...) # (i think only some of the clip code refers to bundles at all) ip = address[0] self.osc_client = SimpleUDPClient(ip, address[1]) self.dispatcher = Dispatcher() self.dispatcher.set_default_handler(self.pythonosc_handler_wrapper) # TODO TODO may need to take more care that this, or the other # pythonosc objects, actually close all of their connections before # exit / atexit # for some reason, maybe most likely something else, there seem to # be less frequent apparent "connection" issues with liblo than with # pythonosc... self.osc_server = ThreadingOSCUDPServer((ip, listen_port), self.dispatcher) self.osc_server_thread = None self.osc_read_event = None self.osc_timeout = 3.0 self.osc_server_events = {} self.query_address = None self.query_rv = [] self.listen()
class OscSender(): def __init__(self, sender_configs): """ Constructor for OSC_SENDER CLASS :param ip: ip address of client ==> 127.0.0.1 (for local host/ inter app communication on same machine) :param sending_to_port: the port on which pure data listens for incoming data """ self.sender_configs = sender_configs self.ip = self.sender_configs["ip"] self.sending_to_port = self.sender_configs["port"] self.playback_sequence_queue = self.sender_configs[ "playback_sequence_queue"] self.client = SimpleUDPClient(self.ip, self.sending_to_port) def send_to_pd(self, message_parameters, message_values): """ sends a list of messages to pd Note 1: Messages are sent in the same order as presented in the lists Note 2: ALWAYS USE LISTS EVEN IF SENDING A SINGLE PARAM/VALUE :param message_parameters: list of str: example ["/note/pitch", /note/duration"] :param message_values: list of ints, floats: example [53, 1000] """ if len(message_parameters) != len(message_values): raise ValueError( "The number of message_types do not match the values") else: for ix, param in enumerate(message_parameters): self.client.send_message(param, message_values[ix]) def get_ip(self): return self.ip def get_sending_to_port(self): return self.sending_to_port def get_client(self): return self.client def change_ip_port(self, ip, port): self.ip = ip self.sending_to_port = port self.client = SimpleUDPClient(self.ip, self.sending_to_port)
class OSCClient: def __init__(self, ip='127.0.0.1', port='1337'): ''' Parameters: ------------ :ip: ip adress, default = 127.0.0.1 :port: port, default = 1337 ''' #initialization of values self.ip = ip self.port = int(port) try: #initialization of client self.client = SimpleUDPClient(self.ip, self.port) except Exception as e: print('Client could not be created \n {}'.format(e)) #function to send values to the pure data server def sendValues(self, distance): ''' Parameters: ------------ :distance: distance between words to be sent to the osc server (Pure Data) ''' # Send distances OSC messages try: self.client.send_message("/distance", distance) except Exception as e: print('Distances could not be sent: \n {}'.format(e)) return #function to send trigger to the pure data server def sendTriggerValue(self, trigger): ''' Parameters: ------------ :trigger: trigger to be sent to server. 1 (start conversation, the OSC messaages will start to be sent), 0 (stop conversation, all the OSC messages have been sent) ''' #send trigger message try: self.client.send_message("/trigger", trigger) except Exception as e: print('Trigger message could not be sent: \n {}'.format(e)) return
def __init__(self, backend, host, port): super().__init__(backend) self.client = SimpleUDPClient(host, port) self._osc_server_lock = threading.Lock() dispatcher = Dispatcher() dispatcher.map("/track/*/volume/str", self.osc_volume_handler) dispatcher.map("/track/*/mute/toggle", self.osc_mute_handler) #dispatcher.set_default_handler(self.osc_default_handler) self._osc_server = BlockingOSCUDPServer(("127.0.0.1", 8001), dispatcher) self._osc_server_thread = threading.Thread( target=self._osc_server.serve_forever) self._osc_server_thread.start()
def sendMessage(self, mod_type, data, disp, ip=None): """Send OSC message with [data] to the given socket and ip address.""" ip = ip or self.__servervalidation.ipaddress client = SimpleUDPClient(ip, self.__servervalidation.port + disp) bundle = osc_bundle_builder.OscBundleBuilder( osc_bundle_builder.IMMEDIATELY) msg = osc_message_builder.OscMessageBuilder( address=self.__servervalidation.basePath + mod_type.value[1]) msg.add_arg(self.__servervalidation.id_lg) msg.add_arg(mod_type.value[0]) msg.add_arg(data) bundle.add_content(msg.build()) bundle = bundle.build() client.send(bundle)
async def initialize(self): """Initialise platform.""" self.config = self.machine.config['osc'] self.machine.config_validator.validate_config("osc", self.config) self.client = SimpleUDPClient(self.config['remote_ip'], self.config['remote_port']) dispatcher = Dispatcher() dispatcher.map("/sw/*", self._handle_switch) dispatcher.map("/event/*", self._handle_event) server = AsyncIOOSCUDPServer((self.config['listen_ip'], self.config['listen_port']), dispatcher, self.machine.clock.loop) self.server, _ = await server.create_serve_endpoint() for event in self.config['events_to_send']: self.machine.events.add_handler(event, self._send_event, _event_name=event)
def __init__(self, in_port, out_port, ip, *args): super(OSCServer, self).__init__() # OSC library objects self.dispatcher = dispatcher.Dispatcher() self.client = SimpleUDPClient(ip, out_port) # Bindings for server self.init_bindings(self.osc_attributes) self.server = osc_server.BlockingOSCUDPServer((ip, in_port), self.dispatcher) self.server.allow_reuse_address = True # Server properties self.debug = False self.in_port = in_port self.out_port = out_port self.ip = ip
def main(ser_port, ser_brate, osc_dest, osc_port, encoding="utf-8", enc_err="replace", ): # Serial ser = serial.Serial(ser_port, ser_brate, timeout=0) ser.flushInput() rx_encoder = codecs.getincrementaldecoder(encoding)(enc_err) end_char = "\n" if DEBUG else "" # Osc osc_client = SimpleUDPClient(osc_dest, osc_port) # Create client msg = "" while True: try: new_char = read_serial(ser, rx_encoder) if new_char: msg += new_char print(new_char, end=end_char , flush=True) send_osc(osc_client, new_char) # if decoded_str == "\n" : # subprocess.call(["say", msg, "-v", "Thomas"]) # msg = "" except KeyboardInterrupt: print("quitting...") break time.sleep(0.1)
class OSCWriter(): #ip = "192.168.0.18" ip = "192.168.4.22" port = 50000 client = SimpleUDPClient(ip, port) # Create client def send_message(self, address, args): return self.client.send_message(address, args) def OSCWriteRawContinuous(self): adcSR = ADCStreamReader() adc0 = adcSR.open(differential=0, gain=16, data_rate=8, sleep=0) adc3 = adcSR.open(differential=3, gain=16, data_rate=8, sleep=0) while True: try: time.sleep(0.05) c0_value = adcSR.read(adc0) self.send_message("/PP01/ADC0/RAW/", c0_value) # Send float message time.sleep(0.05) print("Hi") c3_value = adcSR.read(adc3) self.send_message("/PP01/ADC1/RAW/", c3_value) # Send float message except KeyboardInterrupt: GPIO.cleanup() """
def on_command_connection(self, hp, portlisten, timeout=False, sender=None): # _LOGGER.debug(f'On command connection type={type(portlisten)}') conn_from = hp hp = (hp[0], portlisten) hpstr = f'{hp[0]}:{hp[1]}' send_command = self.hostconnect is None or timeout new_connection = not timeout rearm_timer = not timeout if hpstr not in self.connected_hosts: self.connected_hosts[hpstr] = dict(hp=hp, conn_from=conn_from, timeout=timeout, timer=None, client=SimpleUDPClient( hp[0], hp[1])) rearm_timer = True elif not timeout and self.connected_hosts[hpstr]['timeout']: self.connected_hosts[hpstr]['timeout'] = False self.connected_hosts[hpstr]['conn_from'] = conn_from # _LOGGER.debug('Setting timeout to false') else: new_connection = False if new_connection: self.on_connection_timeout(hp, False) _LOGGER.info(f'Connection to {hp[0]}:{hp[1]} estabilished') if send_command: # _LOGGER.debug(f'Sending connect command as {"client" if self.hostconnect else "server"} to {hp[0]}:{hp[1]} (port={self.portlisten})') self.connected_hosts[hpstr]['client'].send_message( COMMAND_CONNECTION, (self.portlisten, )) if rearm_timer: self.connection_handler_timer_init(hp=hp)
def main(): serial_port = get_first_pozyx_serial_port() if serial_port is None: print("No Pozyx connected. Check your USB cable or your driver!") quit() remote_id = 0x1234 # remote device network ID remote = False # whether to use a remote device if not remote: remote_id = None use_processing = True # enable to send position data through OSC ip = "127.0.0.1" # IP for the OSC UDP network_port = 8888 # network port for the OSC UDP osc_udp_client = None if use_processing: osc_udp_client = SimpleUDPClient(ip, network_port) anchors = [DeviceCoordinates(0x6E2A, 1, Coordinates(0, 0, 3175)), DeviceCoordinates(0x6E0E, 1, Coordinates(0, 4114, 3175)), DeviceCoordinates(0x697F, 1, Coordinates(3429, 0, 3175)), DeviceCoordinates(0x6E6F, 1, Coordinates(3429, 4114, 3175))] algorithm = POZYX_POS_ALG_UWB_ONLY # positioning algorithm to use dimension = POZYX_3D # positioning dimension height = 1000 # height of device, required in 2.5D positioning pozyx = PozyxSerial(serial_port) r = ReadyToLocalize(pozyx, osc_udp_client, anchors, algorithm, dimension, height, remote_id) r.setup() while 1: r.loop() if not GPIO.input(buttonPin): in_use() maintenance = format_time() data = {"ID": Id, "X": x, "Y": y, "InUse": inUse, "Maintenance": maintenance} firebase.post('/Ventilator', data) time.sleep(5)
def __init__(self, sender_configs): """ Constructor for OSC_SENDER CLASS :param ip: ip address of client ==> 127.0.0.1 (for local host/ inter app communication on same machine) :param sending_to_port: the port on which pure data listens for incoming data """ self.sender_configs = sender_configs self.ip = self.sender_configs["ip"] self.sending_to_port = self.sender_configs["port"] self.playback_sequence_queue = self.sender_configs[ "playback_sequence_queue"] self.client = SimpleUDPClient(self.ip, self.sending_to_port)
def set_filter(address: str, *args: List[Any]) -> None: # We expect two float arguments if not len(args) == 2 or type(args[0]) is not float or type(args[1]) is not float: return # Check that address starts with filter if not address[:-1] == "/filter": # Cut off the last character return value1 = args[0] value2 = args[1] filterno = address[-1] print(f"Setting filter {filterno} values: {value1}, {value2}") dispatcher.map("/filter*", set_filter) # Map wildcard address to set_filter function # Set up server and client for testing from pythonosc.osc_server import BlockingOSCUDPServer from pythonosc.udp_client import SimpleUDPClient server = BlockingOSCUDPServer(("127.0.0.1", 1337), dispatcher) client = SimpleUDPClient("127.0.0.1", 1337) # Send message and receive exactly one message (blocking) client.send_message("/filter1", [1., 2.]) server.handle_request() client.send_message("/filter8", [6., -2.]) server.handle_request()
def __init__(self, host = "localhost", port = 7000): self.osc = SimpleUDPClient(host, port)