Ejemplo n.º 1
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}."
        )
Ejemplo n.º 2
0
    def __init__(self, *args, **kwargs):
        super(OSCServer, self).__init__(*args, **kwargs)
        self.parser.add_argument("--ip", help="IP for the OSC Server to listen on", default="0.0.0.0")
        self.parser.add_argument("--port", help="Port for the OSC Server to listen on", default=1337)

        self.dispatcher = Dispatcher()
        self.dispatcher.set_default_handler(self.osc_recv)
Ejemplo n.º 3
0
    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'])
Ejemplo n.º 4
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()
Ejemplo n.º 5
0
async def init_main():
    """
    Asynchronous main, to be called from main()
    """
    global config
    global outputs

    print("Setting up dispatcher")
    dispatcher = Dispatcher()
    dispatcher.map("/*", update_outputs)

    print("Starting Client for {}:{}".format(config["Client"]["ip"],
                                             config["Client"]["port"]))
    client = udp_client.SimpleUDPClient(config["Client"]["ip"],
                                        config["Client"]["port"])
    client.send_message("/setBankStart", 1.0)
    client.send_message("/1/busOutput", 1.0)
    outputs.register_client(client)

    print("Starting Server at {}:{}".format(config["Server"]["ip"],
                                            config["Server"]["port"]))
    server = AsyncIOOSCUDPServer(
        (config["Server"]["ip"], config["Server"]["port"]), dispatcher,
        asyncio.get_event_loop())

    # Create datagram endpoint and start serving
    transport, protocol = await server.create_serve_endpoint()

    print("Listening...")
    await loop()

    transport.close()
    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
Ejemplo n.º 7
0
def main_func(ip, port):   
    dispatcher = Dispatcher()
    dispatcher.map("/Chordata/r*", data_handler)
    dispatcher.set_default_handler(default_handler)
    
    server = BlockingOSCUDPServer((ip, port), dispatcher)
    server.serve_forever()  # Blocks forever
    def init_tuio_interface(self):
        dispatcher = Dispatcher()
        dispatcher.map(
            "/tuio2/frm", self.on_new_frame_message,
            needs_reply_address=True)  # Also pass on the IP of the data origin
        dispatcher.map("/tuio2/ptr",
                       self.on_new_pointer_message,
                       needs_reply_address=True)
        dispatcher.map("/tuio2/bnd",
                       self.on_new_bounding_box_message,
                       needs_reply_address=True)
        dispatcher.map("/tuio2/tok",
                       self.on_new_token_message,
                       needs_reply_address=True)
        dispatcher.map("/tuio2/dat",
                       self.on_new_data_message,
                       needs_reply_address=True)
        dispatcher.map("/tuio2/ctl",
                       self.on_new_control_message,
                       needs_reply_address=True)
        dispatcher.map("/tuio2/alv",
                       self.on_new_alive_message,
                       needs_reply_address=True)

        print('IP, PORT', self.ip, PORT)
        osc_udp_server = ThreadingOSCUDPServer((self.ip, PORT), dispatcher)

        print(
            '[SensorDataInterface]: Listening on {} for incoming TUIO messages'
            .format(osc_udp_server.server_address))

        server_thread = threading.Thread(target=osc_udp_server.serve_forever)
        server_thread.start()
Ejemplo n.º 9
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:
    """
    # 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)
    # 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

    print("OSC server running.")

    await dummy_loop()

    transport.close()  # Clean up server endpoint
Ejemplo n.º 10
0
    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()
Ejemplo n.º 11
0
    def InitNetwork(self, client_ip, client_port, listen_port):
        # client
        self.client = udp_client.SimpleUDPClient(client_ip, client_port)
        PrintManager("Connecting client on port {}.".format(client_port), 4)

        # server callbacks
        dispatch = Dispatcher()
        dispatch.map("/move*", self.MoveNozzle)  # /move/extrude and /move
        dispatch.map("/extrude", self.ExtractMaterial)
        dispatch.map("/retract", self.RetractMaterial)
        dispatch.map("/req/nozzle_pos", self.RequestNozzlePosition)
        dispatch.set_default_handler(
            lambda _: PrintManager("Received message.", 1))
        # TODO: Add other functions

        # server
        loop = asyncio.get_event_loop()
        self.server = AsyncIOOSCUDPServer(("127.0.0.1", listen_port), dispatch,
                                          asyncio.get_event_loop())
        PrintManager("Serving on {}:{}".format("127.0.0.1", listen_port), 4)
        self.server.serve()

        # start the event loop for server
        self.osc_thread = threading.Thread(target=loop.run_forever)
        self.osc_thread.daemon = True
        self.osc_thread.start()
Ejemplo n.º 12
0
    def __init__(self,
                 ip,
                 receive_from_port,
                 quit_event,
                 address_list=["/clock*"],
                 address_handler_list=[None]):
        """
        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 receive_from_port: the port on which python listens for incoming data
        """
        super(OscReceiver, self).__init__()
        self.setDaemon(
            True)  # don't forget this line, otherwise, the thread never ends

        self.ip = ip
        self.receiving_from_port = receive_from_port

        self.listening_thread = None

        self.dispatcher = Dispatcher()

        for ix, address in enumerate(address_list):
            self.dispatcher.map(address, address_handler_list[ix])

        self.dispatcher.set_default_handler(self.default_handler)

        self.server = BlockingOSCUDPServer((self.ip, self.receiving_from_port),
                                           self.dispatcher)
        #self.server.request_queue_size = 0
        self.quit_event = quit_event
Ejemplo n.º 13
0
    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 = []
Ejemplo n.º 14
0
def main(args):
    includes = DEFAULT_INCLUDES + args.include

    dispatcher = Dispatcher()
    dispatcher.map("/remove", remove_handler, "Remove")
    dispatcher.map("/detach", detach_handler, "Detach")
    dispatcher.map("/slur_oneshot", slur_handler, "Slur")
    dispatcher.map("/tie_oneshot", tie_handler, "Tie")
    dispatcher.map("/text_spanner_oneshot", text_spanner_handler,
                   "Text Spanner")
    dispatcher.map("/notehead_oneshot", notehead_handler, "Notehead")
    dispatcher.map("/bar_line_oneshot", bar_line_handler, "BarLine")
    dispatcher.map("/articulation_oneshot", articulation_handler,
                   "Articulation")
    dispatcher.map("/dynamic_oneshot", dynamic_handler, "Dynamic")
    dispatcher.map("/dynamicTrend_oneshot", dynamicTrend_handler,
                   "DynamicTrend")
    dispatcher.map("/literal_oneshot", literal_handler, "Literal")
    dispatcher.map("/markup_oneshot", markup_handler, "Markup")
    dispatcher.map("/note_event", note_handler, "Note")
    dispatcher.map("/display", display_handler, "Display")

    server = osc_server.ThreadingOSCUDPServer((args.host, args.port),
                                              dispatcher)

    print("Serving on {}".format(server.server_address))
    server.serve_forever()
Ejemplo n.º 15
0
 def start_server_to_listen(self, imu_handler, emg_handler):
     self.file_counter += 1
     dispatcher = Dispatcher()
     dispatcher.map("/imu", imu_handler)
     dispatcher.map("/emg", emg_handler)
     self.server = osc_server.OSCUDPServer((self.ip, self.port), dispatcher)
     print("Serving on {}".format(self.server.server_address))
     self.server.serve_forever()
Ejemplo n.º 16
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()
Ejemplo n.º 17
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()
Ejemplo n.º 18
0
 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()
Ejemplo n.º 19
0
 def __init__(self, address, state):
     self.state = state
     dispatcher = Dispatcher()
     dispatcher.set_default_handler(self.msg_handler)
     self.server = OSCClientServer((address, self.XAIR_PORT), dispatcher)
     worker = threading.Thread(target=self.run_server)
     worker.daemon = True
     worker.start()
Ejemplo n.º 20
0
    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
Ejemplo n.º 21
0
def main_func():
    ip = "localhost"
    port = 6565

    dispatcher = Dispatcher()
    dispatcher.set_default_handler(default_handler)

    server = BlockingOSCUDPServer((ip, port), dispatcher)
    server.serve_forever()
Ejemplo n.º 22
0
 def connecta_osc(self):
     self.disp = Dispatcher()
     self.disp.map(OSC_TIME_ROUTES[0], self.getTimeFromOscPlayer1)
     self.disp.map(OSC_TIME_ROUTES[1], self.getTimeFromOscPlayer2)
     self.disp.map(OSC_FILE_NAMES[0], self.getFileFromOscPlayer1)
     self.disp.map(OSC_FILE_NAMES[1], self.getFileFromOscPlayer2)
     self.disp.map(OSC_LAYER_PAUSED[0], self.getPauseFromOscPlayer1)
     self.disp.map(OSC_LAYER_PAUSED[1], self.getPauseFromOscPlayer2)
     self.srv = BlockingOSCUDPServer( (self.ip, self.port), self.disp)
Ejemplo n.º 23
0
 def _start_server(self):
     dispatcher = Dispatcher()
     self.server = OSCClientServer(("0.0.0.0", self.args.port),
                                   self.ardour_addr, dispatcher,
                                   self._service_action)
     dispatcher.map("/rec_enable_toggle", self.handle_rec_enable_toggle)
     dispatcher.map("/record_tally", self.handle_record_tally)
     dispatcher.map("/heartbeat", self.handle_heartbeat)
     dispatcher.set_default_handler(self.handle_any)
Ejemplo n.º 24
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()
Ejemplo n.º 25
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()
Ejemplo n.º 26
0
def main_func():
    dispatcher = Dispatcher()
    dispatcher.map("/%/*", data_handler)
    dispatcher.set_default_handler(default_handler)

    ip = "localhost"
    port = 6565

    server = BlockingOSCUDPServer((ip, port), dispatcher)
    server.serve_forever()  # Blocks forever
    def configureDispatcher(self):
        # setting the object which receives the messages and decides where to send them
        dispatcher = Dispatcher()
        dispatcher.map("/inputs/key_mapping/*", self.set_keyMappings)
        dispatcher.map("/inputs/key_on/gen_MIDI", self.set_genMIDI)
        dispatcher.map("/inputs/key_on", self.keyOn)
        dispatcher.map("/inputs/key_off", self.keyOff)
        dispatcher.set_default_handler(self.default_handler)

        return dispatcher
    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)
Ejemplo n.º 29
0
def main():
    ip = '127.0.0.1'
    port = 6700

    # URLにコールバック関数を割り当てる
    dispatcher = Dispatcher()
    dispatcher.map('/address', handler)
    # サーバを起動する
    server = osc_server.ThreadingOSCUDPServer((ip, port), dispatcher)
    print('Server Start IP={} PORT={}'.format(ip, port))
    server.serve_forever()
Ejemplo n.º 30
0
Archivo: osc.py Proyecto: yncat/tgs19
 def __init__(self):
     self.dispatcher = Dispatcher()
     self.dispatcher.map("/realsense*", self._onMessageReceived)
     self.server = osc_server.ThreadingOSCUDPServer((IP, PORT),
                                                    self.dispatcher)
     self.raw = (0.0, 0.0, 0.0)
     self.offset = [0.0, 0.0, 0.0]
     self.distance_cach = (0.0, 0.0, 0.0)
     self.thread = threading.Thread(target=self._thread)
     self.thread.setDaemon(True)
     self.thread.start()