Exemplo n.º 1
0
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'])

    async def _start(self):
        await 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)
Exemplo n.º 2
0
    def _setup_server(self):
        print("Setting up server {}, {}".format(self.host_ip, self.in_port))

        self.dispatcher = Dispatcher()

        self.dispatcher.map("/handshake/", self._handshake_handler)
        self.dispatcher.map("/ping/", self._ping_handler)
        self.dispatcher.map("/start/", self._start_handler)
        self.dispatcher.map("/stop/", self._stop_handler)

        self.server = AsyncIOOSCUDPServer((self.host_ip, self.in_port),
                                          self.dispatcher,
                                          asyncio.get_event_loop())
Exemplo n.º 3
0
    def __init__(self, osculator_client, audience_client, performer_client,
                 machine, beat_manager, tonality):
        self.osculator_client = osculator_client
        self.audience_client = audience_client
        self.performer_client = performer_client
        self.song_machine = machine
        self.beat_manager = beat_manager
        self.tonality = tonality

        dispatcher = Dispatcher()
        dispatcher.map(settings.INTERPRETER_TARGET_ADDRESS,
                       self.interpreter_handler)
        dispatcher.map(settings.SONG_BEAT_ADDRESS, self.beat_handler)
        dispatcher.map(settings.SONG_SYNTH_RESET_ADDRESS, self.reset_handler)
        self.server = ThreadingOSCUDPServer(
            (settings.ip, settings.SONG_SERVER_PORT), dispatcher)

        self.song_scenes = {
            k: v
            for k, v in zip(self.song_machine.parser.song_parts,
                            range(len(self.song_machine.parser.song_parts)))
        }

        self.osculator_client.send_message(
            settings.SONG_ADVANCE_ADDRESS,
            (self.song_machine.parser.INTRO_NOTE, 1.0))
        self.osculator_client.send_message(
            settings.SONG_ADVANCE_ADDRESS,
            (self.song_machine.parser.INTRO_NOTE, 0.0))
        self.osculator_client.send_message('/mid_{}'.format('praise'),
                                           self.tonality.synth.ctrl_message)
        self._send_init_to_display()
Exemplo n.º 4
0
    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()
Exemplo n.º 5
0
def main_func(ip, port):
    dispatcher = Dispatcher()
    dispatcher.map("/%%/*", address_handler)
    dispatcher.map("/%/*", data_handler)
    dispatcher.set_default_handler(default_handler)

    server = BlockingOSCUDPServer((ip, port), dispatcher)
    server.serve_forever()  # Blocks forever
Exemplo n.º 6
0
 def __init__(self, addresses=[], ip="127.0.0.1", port=5005):
     self._server = None
     self._data = {}
     self._lock = Lock()
     if not addresses or not isinstance(addresses, list):
         raise ValueError("You must provide a list of addresses.")
     dispatcher = Dispatcher()
     for address in addresses:
         self._data[self._address_to_port(address)] = {
             "timestamps": [],
             "rows": []
         }
         dispatcher.map(address, self._handler)
     self._server = BlockingOSCUDPServer((ip, port), dispatcher)
     Thread(target=self._server.serve_forever).start()
Exemplo n.º 7
0
class MessageReceiver:
    def __init__(self, port):
        print(f'Setting up Receiver with port: {port}')
        self.dispatcher = Dispatcher()
        self.server = BlockingOSCUDPServer(('127.0.0.1', port),
                                           self.dispatcher)
        self.dispatcher.set_default_handler(self.handleMessage)
        self.thread = Thread(target=self.run)
        self.thread.start()

    def run(self):
        self.server.serve_forever()
        print('done with receiver thread')

    def handleMessage(self, adress, *args):
        print(f'handler: {adress}: {args}')
Exemplo n.º 8
0
	def __init__(self, client_type, host=None, inport=None, outport=None, obs_size=64):
		self.type = client_type
		self.action_queue = []
		self.joints_queue = []
		self.obs_queue = []
		self.obs_parts = []
		self.obs_size = obs_size
		self.last_obs = np.zeros((obs_size, obs_size))

		if (host==None or inport==None or outport==None):
			with open('config/osc.json') as f:
				config = json.load(f)
				self.host = config.get('client.host')
				self.inport = int(config.get('client.port'))
				self.outport = int(config.get('server.port'))
		else:
			self.host = host
			self.inport = int(inport)
			self.outport = int(outport)

		self.client = SimpleUDPClient(self.host, self.outport)

		self.handshake = True
		self.finished = False
		self.terminate = False
		self.save_obs = False

		self.fitness = []
		self.clock = 0.0
		self.oscillator = 0.0
		self.brush = 0.5

		self.dispatcher = Dispatcher()

		if client_type == ClientType.ROLLOUT:
			self.dispatcher.map(f'{OSC_HELLO}*', self.__dispatch_hello)
			self.dispatcher.map(f'{OSC_BYE}*', self.__dispatch_bye)
			self.dispatcher.map(f'{OSC_INFO}*', self.__dispatch_info)
			self.dispatcher.map(f'{OSC_END_ROLLOUT}*', self.__dispatch_end)

			self.dispatcher.map(f'{OSC_JOINTS}*', self.__dispatch_joints_packets)
			self.dispatcher.map(f'{OSC_ARTIFACT_START}*', self.__dispatch_start_packets)
			self.dispatcher.map(f'{OSC_ARTIFACT_PART}*', self.__dispatch_append_packets)
			self.dispatcher.map(f'{OSC_ARTIFACT_END}*', self.__dispatch_process_packets)
		else:
			self.dispatcher.map(f'{OSC_FITNESS}*', self.__dispatch_fitness)
Exemplo n.º 9
0
def launchUDPServer():
	# this is handling the messages received from EEGSonic
	parser = argparse.ArgumentParser()
	parser.add_argument('--ip', default='127.0.0.1',
		help='The ip of the OSC server')
	parser.add_argument('--port', type=int, default=7400,
		help='the port the OSC server is listening on')
	args = parser.parse_args()

	dispatcher = Dispatcher()
	dispatcher.map('*', relayOSC)
    # this is receiving the messages from EEGsonic and forwarding to the front end

	server = osc_server.BlockingOSCUDPServer(
		(args.ip, args.port), dispatcher)
	print(f'Serving on {server.server_address}')
	server.serve_forever()
Exemplo n.º 10
0
 def run(self) -> None:
     """ raises: OSError is server already is in use """
     osc_dispatcher: Dispatcher = Dispatcher()
     osc_dispatcher.map(self.SERVER_ADDRESS, self.__process_osc)
     osc_dispatcher.set_default_handler(self.__unmatched_osc)
     self._server: BlockingOSCUDPServer = BlockingOSCUDPServer(
         (Server.DEFAULT_IP, self._inport), osc_dispatcher)
     self._server.serve_forever()
Exemplo n.º 11
0
    def __init__(self, host='0.0.0.0', port=7401, **kwargs):

        self._host = host
        self._port = port
        self._client = None
        self._server = None
        self._server_thread = None

        Logged.__init__(self, **kwargs)

        self._dispatcher = Dispatcher()
        self._dispatcher.set_default_handler(self.receive)

        self._routes = {}
        for osc_path, callback in find_routes(self):
            self._dispatcher.map(osc_path, callback)
            self._routes[osc_path] = callback
Exemplo n.º 12
0
async def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--ip", default="0.0.0.0", help="The ip to listen on")
    parser.add_argument("--port", type=int, default=37339, help="The port to listen on")
    args = parser.parse_args()

    plt.ion()
    # plt.show()

    dispatcher = Dispatcher()
    dispatcher.map("/pulse", pulse_handler)

    loop = asyncio.get_event_loop()
    server = osc_server.AsyncIOOSCUDPServer( (args.ip, args.port), dispatcher, loop)
    # server = osc_server.ThreadingOSCUDPServer( (args.ip, args.port), dispatcher)
    # server.serve()
    transport, protocol = await server.create_serve_endpoint()
    await asyncio.sleep(10**30)
Exemplo n.º 13
0
 def __init__(self,
              hostlisten='127.0.0.1',
              portlisten=33217,
              hostconnect=None,
              portconnect=None):
     self.hostlisten = hostlisten
     self.portlisten = portlisten
     self.hostconnect = hostconnect
     self.portconnect = portconnect
     self.server = None
     self.transport = None
     self.protocol = None
     self.dispatcher = Dispatcher()
     self.client_connection_sender_timer = None
     self.user_on_connection_timeout = None
     self.connected_hosts = dict()
     self.callbacks = dict()
     self.cmd_queue = []
Exemplo n.º 14
0
def server():
    dispatcher = Dispatcher()
    server = ThreadingOSCUDPServer(("127.0.0.1", SERVER_PORT), dispatcher)
    server_thread = threading.Thread(target=server.serve_forever)
    server_thread.daemon = True
    server_thread.start()
    yield server

    server.shutdown()
    server_thread.join()
    def __init__(
        self,
        server_ip: str,
        server_port: int,
        default_receiver_ip: str,
        default_receiver_port: int,
    ) -> None:
        """Create an OSC communication server

        Parameters
        ----------
        server_ip : str
            IP address to use for this server
        server_port : int
            port to use for this server
        default_receiver_ip : str
            IP address used for sending by default
        default_receiver_port : int
            port used for sending by default
        """
        self._receivers: Dict[Tuple[str, int], str] = {}
        self._default_receiver: Tuple[str, int] = (
            default_receiver_ip,
            default_receiver_port,
        )

        # bundling messages support
        self._bundling_lock = RLock()
        self._bundling_bundles = []

        # create server
        while True:
            try:
                self._osc_server = ThreadingOSCUDPServer(
                    (server_ip, server_port), Dispatcher())
                self._osc_server_running = True
                _LOGGER.debug("This OSCCommunication instance is at port: %s",
                              server_port)
                break
            except OSError as error:
                if error.errno == errno.EADDRINUSE:
                    server_port += 1

        # start server thread
        self._osc_server_thread = threading.Thread(
            target=self._osc_server.serve_forever)
        self._osc_server_thread.daemon = True
        self._osc_server_thread.start()

        # init queues for msg pairs, must be after self._osc_server
        self._msg_queues: Dict[str, MessageQueue] = {}
        self._reply_addresses: Dict[str, str] = {}

        atexit.register(self.quit)
Exemplo n.º 16
0
 async def _run(self):
     """ raises: OSError is server already is in use """
     osc_dispatcher: Dispatcher = Dispatcher()
     osc_dispatcher.map(self.address, self.__process_osc)
     osc_dispatcher.set_default_handler(self.__unmatched_osc)
     self.server: AsyncIOOSCUDPServer = AsyncIOOSCUDPServer((self.ip, self.recv_port),
                                                            osc_dispatcher, asyncio.get_event_loop())
     transport, protocol = await self.server.create_serve_endpoint()
     self.target.send(SendProtocol.AGENT_INSTANTIATED, Target.WRAPPED_BANG)
     await self._main_loop()
     transport.close()
Exemplo n.º 17
0
    def setup(self):
        # ColorTerminal().warn('OscReader-setup')
        if self.oscServer != None:
            self.destroy()

        ColorTerminal().output("Starting OSC Server with host {0} and port {1}".format(self.host, self.port))
        dispatcher = Dispatcher()
        dispatcher.map('/marker', self.oscMarkerHandler)
        dispatcher.map("/rigidbody", self.oscRigidBodyHandler)

        try:
            self.oscServer = osc_server.BlockingOSCUDPServer((self.host, self.port), dispatcher)
            self.oscServer.handle_timeout = self.handleTimeout
            self.oscServer.timeout=0
            #self.oscServer.serve_forever()

        except OSError as err:
            ColorTerminal().fail("Could not create OSC server: ", err)
            self.oscServer = None

        ColorTerminal().success("OSC Server running")
Exemplo n.º 18
0
def thread_osc(threadname, _queue):
    print("Start:" + threadname)

    from pythonosc.dispatcher import Dispatcher
    from pythonosc.osc_server import BlockingOSCUDPServer

    def handler(address, *args):
        if not _queue.empty():
            _queue.get()
        _queue.put(args)

    #def default_handler(address, *args):
    #    print(f"DEFAULT {address}: {args}")

    dispatcher = Dispatcher()
    #dispatcher.map("/faciallandmarks/eyebrows", eyebrown_handler)
    dispatcher.map("/landmarks", handler)
    #dispatcher.set_default_handler(default_handler)

    server = BlockingOSCUDPServer(("192.168.178.52", 9000), dispatcher)
    server.serve_forever()  # Blocks forever
Exemplo n.º 19
0
    def __init__(self,
                 ip: str = "127.0.0.1",
                 port_in: int = 8081,
                 port_out: int = 8080,
                 recv_address: str = "/pyosc",
                 parse_parenthesis_as_list: bool = False,
                 discard_duplicate_arguments: bool = True,
                 send_format: SendFormat = SendFormat.FLATTEN,
                 osc_log_level: Optional[int] = logging.INFO):
        """

        :param ip:
        :param port_in:
        :param port_out:
        :param parse_parenthesis_as_list:
        :param send_format:
        :param osc_log_level: Forward log messages to Max. Will not forward if set to None. To forward only some messages, override _handle_max_osc_error, _handle_type_error or _handle_error
        """
        super(MaxOsc, self).__init__(parse_parenthesis_as_list,
                                     discard_duplicate_arguments)
        self.logger = logging.getLogger(__name__)
        self.sender: Sender = Sender(ip, port_out, send_format)
        if osc_log_level:
            handler: OscLogHandler = OscLogHandler(self.sender, osc_log_level)
            self.logger.addHandler(handler)

        dispatcher = Dispatcher()
        dispatcher.map(recv_address, self.main_callback)
        dispatcher.set_default_handler(self._default_handler)
        self._server = BlockingOSCUDPServer((ip, port_in), dispatcher)
        self.logger.info(
            f"MaxOsc initialized on ip {ip} with incoming port {port_in} and outgoing port {port_out}."
        )
Exemplo n.º 20
0
Arquivo: osc.py Projeto: zetof/bar
    def __init__(self, client_host='127.0.0.1', client_port=57120, server_host='127.0.0.1', server_port=57130):
        """
        Class constructor
        :param client_host: URL used to reach OSC listener of SuperCollider
        :param client_port: port used to reach OSC listener of SuperCollider
        :param server_host: URL used to reach this running OSC server instance
        :param server_port: port used to reach this running OSC server instance
        """

        # Initiate OSC client
        self._osc_client = udp_client.SimpleUDPClient(client_host, client_port)

        # Register a default dispatcher
        self._dispatcher = Dispatcher()
        self._dispatcher.set_default_handler(self._print_message)

        # Save some init params to the class
        self._server_host = server_host
        self._server_port = server_port

        # Initiate OSC server
        self._start_server()
Exemplo n.º 21
0
class OSCReceiver:
    def __init__(self, host='0.0.0.0', port=5300):
        self.dispatcher = Dispatcher()
        self.dispatcher.map("/state", self.setState)
        self.oscServer = ThreadingOSCUDPServer((host, port), self.dispatcher)
        self.oscServerThread = threading.Thread(
            target=self.oscServer.serve_forever, daemon=True)

        self.state = -1

    def getState(self):
        return self.state

    def setState(self, endpoint, newState):
        print('GOT STATE MESSAGE')
        print(newState)

        self.state = newState

    def start(self):
        self.oscServerThread.start()
        return self
Exemplo n.º 22
0
class OscServer:
    def __init__(self, ip_adress="127.0.0.1", port=4321):
        self.ip_adress = ip_adress
        self.port = port

        self.dispatcher = Dispatcher()
        self.server = None

    def register_default_handler(self, handler_function: FunctionType):
        self.dispatcher.set_default_handler(handler_function)

    def register_handler(self, route: str, handler_function: FunctionType):
        self.dispatcher.map(route, handler_function)

    def terminate(self):
        self.server.shutdown()

    def serve(self):
        print(f"Listening for OSC messages on {self.ip_adress}:{self.port}")
        self.server = BlockingOSCUDPServer((self.ip_adress, self.port),
                                           self.dispatcher)
        self.server.serve_forever()
Exemplo n.º 23
0
def main_func():
    global client
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect(('localhost', 30001))

    dispatcher = Dispatcher()
    dispatcher.map("/%%/*", address_handler)
    dispatcher.map("/%/*", data_handler)
    dispatcher.set_default_handler(default_handler)

    ip = "localhost"
    port = 6565

    server = BlockingOSCUDPServer((ip, port), dispatcher)
    server.serve_forever()  # Blocks forever
Exemplo n.º 24
0
 def run_server_forever(self):
     dispatcher = Dispatcher()
     dispatcher.map('/note_on', self._note_on_handler)
     dispatcher.map('/note_off', self._note_off_handler)
     server = osc_server.ThreadingOSCUDPServer((self.ip, self.port),
                                               dispatcher)
     print('Serving on {}'.format(server.server_address))
     server.serve_forever()
Exemplo n.º 25
0
async def init_main():
    """

    https://python-osc.readthedocs.io/en/latest/server.html#async-server
    https://web.archive.org/web/20170809181820/http://developer.choosemuse.com/research-tools-example/grabbing-data-from-museio-a-few-simple-examples-of-muse-osc-servers
    https://addshore.com/2018/06/python3-using-some-shared-state-in-2-async-methods/
    :return:
    """
    # making a super ghetto state to share b/w the two async contexts
    # based on solution in https://addshore.com/2018/06/python3-using-some-shared-state-in-2-async-methods/
    async_state = type('', (), {})()
    async_state.focused = False
    async_state.mentally_focused = False
    async_state.wearing = False
    async_state.hat_running = False
    async_state.user_override = False
    async_state.last_reading = datetime.datetime.now()
    async_state.attention_lvl = 0.0

    # Prepare the serial port
    # make_connection
    ser = serial.Serial(ARD_PORT, baudrate=9600, timeout=1)
    connection_made = make_connection(ser, async_state)

    if connection_made:
        # with the connection made and inital state set, can start the main loops.
        # https://python-osc.readthedocs.io/en/latest/dispatcher.html
        # https://python-osc.readthedocs.io/en/latest/server.html#async-server
        event_loop_local = asyncio.get_event_loop()
        dispatcher = Dispatcher()
        dispatcher.map("/muse/elements/experimental/concentration", concentration_handler, async_state)
        # creates an OSC server that's Async.
        server = osc_server.AsyncIOOSCUDPServer((IP, OSC_PORT), dispatcher, event_loop_local)
        transport, protocol = await server.create_serve_endpoint()  # Create datagram endpoint and start serving

        await loop(ser, async_state)  # Enter main loop of program.

        transport.close()  # Clean up serve endpoint
Exemplo n.º 26
0
    def __init__(self,
                 client_host='127.0.0.1',
                 client_port=57120,
                 server_host='127.0.0.1',
                 server_port=57130):
        """
        Class constructor
        :param host: URL used to reach OSC listener
        :param port: port used to reach OSC listener
        """

        # Initiate OSC client
        self._osc_client = udp_client.SimpleUDPClient(client_host, client_port)

        # Register a default dispatcher
        self._dispatcher = Dispatcher()
        self._dispatcher.set_default_handler(self._print_message)

        self._server_host = server_host
        self._server_port = server_port

        # Initiate OSC server
        self.start_server()
Exemplo n.º 27
0
async def loop():
    global transport
    global window
    # i = 0
    while (True):
        # i += 1
        # print(f"Loop {i}")
        event, values = window.Read(timeout=5)
        if event != '__TIMEOUT__':
            print(event, values)
        if event is None or event == 'Exit':
            break
        if event == '_CONNECT_':
            dispatcher = Dispatcher()
            dispatcher.map(values['_ADDRESS_'], press_key_handler)
            window.FindElement('_CONNECT_').Update(disabled=True)
            # server setup logic
            server = AsyncIOOSCUDPServer(
                (values['_IP_'], int(values['_PORT_'])), dispatcher,
                asyncio.get_event_loop())
            # Create datagram endpoint and start serving
            transport, protocol = await server.create_serve_endpoint()
        await asyncio.sleep(0.005)
Exemplo n.º 28
0
	def __init__(self, ip, port):
		self.lines = [""]*Orac.MAX_LINES
		self.selectedLine = 0

		self.params = [{"name": "", "value": "", "ctrl": 0.0} for _ in range(Orac.MAX_PARAMS)]

		self.oscDispatcher = Dispatcher()

		self.oscDispatcher.map("/text", self.textHandler)
		self.oscDispatcher.map("/selectText", self.selectTextHandler)
		self.oscDispatcher.map("/clearText", self.clearTextHandler)
		self.oscDispatcher.map("/P*Desc", self.paramDescHandler)
		self.oscDispatcher.map("/P*Ctrl", self.paramCtrlHandler)
		self.oscDispatcher.map("/P*Value", self.paramValueHandler)
		self.oscDispatcher.map("/module", self.moduleHandler)
		self.oscDispatcher.map("/*", self.allOtherHandler)

		self.server = BlockingOSCUDPServer(('', args.listen), self.oscDispatcher)

		self.client = udp_client.SimpleUDPClient(args.ip, args.port)
		self.client.send_message("/Connect", args.listen)

		self.linesClearedCallbacks = []
		self.lineChangedCallbacks = []
		self.paramNameChangedCallbacks = []
		self.paramValueChangedCallbacks = []
		self.paramCtrlChangedCallbacks = []

		self.lineChangedNotificationsEnabled = True
		self.screenTimer = None
		self.linesSnapshot = None

		self.paramNotificationsEnabled = True
		self.paramTimer = None
		self.paramsSnapshot = None

		self.changingModule = False
Exemplo n.º 29
0
def osc_server():
    dispatcher = Dispatcher()
    dispatcher.map("/lightstick/preset", preset_handler)
    dispatcher.set_default_handler(default_handler)

    ip = "0.0.0.0"
    port = 5000

    server = BlockingOSCUDPServer((ip, port), dispatcher)
    server.serve_forever()
Exemplo n.º 30
0
def main_func():
    ip = "localhost"
    port = 6565
    
    dispatcher = Dispatcher()
    dispatcher.map("/Chordata/*", data_handler)
    dispatcher.set_default_handler(default_handler)

    server = BlockingOSCUDPServer((ip, port), dispatcher)
    server.serve_forever()
Exemplo n.º 31
0
 def __init__(self, reader, writer, osc_spec=1.0):
     self.reader = reader
     self.writer = writer
     self.osc_spec = osc_spec
     self._slip_driver = None
     if self.osc_spec == 1.1:
         self._slip_driver = SlipDriver()
     self.dispatcher: Dispatcher = Dispatcher()
     self.dispatcher.map("/oscrouter/register", self.register)
     self.dispatcher.map("*", self.call_notification_callbacks)
     self.user = None
     self._leave = False
     self._to_write = asyncio.Queue()
     self._reader_task = asyncio.create_task(self._reader_coro())
     self._writer_task = asyncio.create_task(self._writer_coro())
     logging.info(f"New connection from '{self}'")
Exemplo n.º 32
0
from pythonosc.dispatcher import Dispatcher
from typing import List, Any

dispatcher = Dispatcher()


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)
Exemplo n.º 33
0
from pythonosc.osc_server import AsyncIOOSCUDPServer
from pythonosc.dispatcher import Dispatcher
import asyncio


def filter_handler(address, *args):
    print(f"{address}: {args}")


dispatcher = Dispatcher()
dispatcher.map("/filter", filter_handler)

ip = "127.0.0.1"
port = 1337


async def loop():
    """Example main loop that only runs for 10 iterations before finishing"""
    for i in range(10):
        print(f"Loop {i}")
        await asyncio.sleep(1)


async def init_main():
    server = AsyncIOOSCUDPServer((ip, port), dispatcher, asyncio.get_event_loop())
    transport, protocol = await server.create_serve_endpoint()  # Create datagram endpoint and start serving

    await loop()  # Enter main loop of program

    transport.close()  # Clean up serve endpoint
Exemplo n.º 34
0
class TestDispatcher(unittest.TestCase):

  def setUp(self):
    super().setUp()
    self.dispatcher = Dispatcher()

  def sortAndAssertSequenceEqual(self, expected, result):
    def sort(lst):
      return sorted(lst, key=lambda x: x.callback)
    return self.assertSequenceEqual(sort(expected), sort(result))

  def test_empty_by_default(self):
    self.sortAndAssertSequenceEqual([], self.dispatcher.handlers_for_address('/test'))

  def test_use_default_handler_when_set_and_no_match(self):
    handler = object()
    self.dispatcher.set_default_handler(handler)

    self.sortAndAssertSequenceEqual([Handler(handler, [])], self.dispatcher.handlers_for_address('/test'))

  def test_simple_map_and_match(self):
    handler = object()
    self.dispatcher.map('/test', handler, 1, 2, 3)
    self.dispatcher.map('/test2', handler)
    self.sortAndAssertSequenceEqual(
        [Handler(handler, [1, 2, 3])], self.dispatcher.handlers_for_address('/test'))
    self.sortAndAssertSequenceEqual(
        [Handler(handler, [])], self.dispatcher.handlers_for_address('/test2'))

  def test_example_from_spec(self):
    addresses = [
        "/first/this/one",
        "/second/1",
        "/second/2",
        "/third/a",
        "/third/b",
        "/third/c",
    ]
    for index, address in enumerate(addresses):
      self.dispatcher.map(address, index)

    for index, address in enumerate(addresses):
      self.sortAndAssertSequenceEqual(
          [Handler(index, [])], self.dispatcher.handlers_for_address(address))

    self.sortAndAssertSequenceEqual(
        [Handler(1, []), Handler(2, [])], self.dispatcher.handlers_for_address("/second/?"))

    self.sortAndAssertSequenceEqual(
        [Handler(3, []), Handler(4, []), Handler(5, [])],
        self.dispatcher.handlers_for_address("/third/*"))

  def test_do_not_match_over_slash(self):
    self.dispatcher.map('/foo/bar/1', 1)
    self.dispatcher.map('/foo/bar/2', 2)

    self.sortAndAssertSequenceEqual(
        [], self.dispatcher.handlers_for_address("/*"))

  def test_match_middle_star(self):
    self.dispatcher.map('/foo/bar/1', 1)
    self.dispatcher.map('/foo/bar/2', 2)

    self.sortAndAssertSequenceEqual(
        [Handler(2, [])], self.dispatcher.handlers_for_address("/foo/*/2"))

  def test_match_multiple_stars(self):
    self.dispatcher.map('/foo/bar/1', 1)
    self.dispatcher.map('/foo/bar/2', 2)

    self.sortAndAssertSequenceEqual(
        [Handler(1, []), Handler(2, [])], self.dispatcher.handlers_for_address("/*/*/*"))

  def test_match_address_contains_plus_as_character(self):
    self.dispatcher.map('/footest/bar+tender/1', 1)

    self.sortAndAssertSequenceEqual(
        [Handler(1, [])], self.dispatcher.handlers_for_address("/foo*/bar+*/*"))
    self.sortAndAssertSequenceEqual(
        [Handler(1, [])], self.dispatcher.handlers_for_address("/foo*/bar*/*"))

  def test_call_correct_dispatcher_on_star(self):
    self.dispatcher.map('/a+b', 1)
    self.dispatcher.map('/aaab', 2)
    self.sortAndAssertSequenceEqual(
        [Handler(2, [])], self.dispatcher.handlers_for_address('/aaab'))
    self.sortAndAssertSequenceEqual(
        [Handler(1, [])], self.dispatcher.handlers_for_address('/a+b'))

  def test_map_star(self):
    self.dispatcher.map('/starbase/*', 1)
    self.sortAndAssertSequenceEqual(
        [Handler(1, [])], self.dispatcher.handlers_for_address("/starbase/bar"))

  def test_map_root_star(self):
    self.dispatcher.map('/*', 1)
    self.sortAndAssertSequenceEqual(
        [Handler(1, [])], self.dispatcher.handlers_for_address("/anything/matches"))

  def test_map_double_stars(self):
    self.dispatcher.map('/foo/*/bar/*', 1)
    self.sortAndAssertSequenceEqual(
        [Handler(1, [])], self.dispatcher.handlers_for_address("/foo/wild/bar/wild"))
    self.sortAndAssertSequenceEqual(
        [], self.dispatcher.handlers_for_address("/foo/wild/nomatch/wild"))

  def test_multiple_handlers(self):
    self.dispatcher.map('/foo/bar', 1)
    self.dispatcher.map('/foo/bar', 2)
    self.sortAndAssertSequenceEqual(
        [Handler(1, []), Handler(2, [])], self.dispatcher.handlers_for_address("/foo/bar"))

  def test_multiple_handlers_with_wildcard_map(self):
    self.dispatcher.map('/foo/bar', 1)
    self.dispatcher.map('/*', 2)
    self.sortAndAssertSequenceEqual(
        [Handler(1, []), Handler(2, [])], self.dispatcher.handlers_for_address("/foo/bar"))
Exemplo n.º 35
0
def init_osc(loop):
    dispatcher = Dispatcher()
    dispatcher.map("/output_*", say_handler)
    osc_server = AsyncIOOSCUDPServer(('127.0.0.1', 12000), dispatcher, loop)
    osc_server.serve()  # Calls 'run_until_complete' internally
Exemplo n.º 36
0
 def setUp(self):
   super().setUp()
   self.dispatcher = Dispatcher()