示例#1
0
    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)
示例#2
0
    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()
示例#3
0
文件: osc.py 项目: krayon/pinball-mpf
    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)
示例#4
0
 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
示例#5
0
    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))
示例#6
0
    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)
示例#7
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)
    def send_genMIDI(self, ip, port):

        self.gen_MIDI_flag = True
        client = SimpleUDPClient(ip, port)

        sample_no = random.randint(21, 30)
        mid = mido.MidiFile('gen_midi_samples/sample_' + str(sample_no) +
                            '.mid')
        for msg in mid.play():
            if self.gen_MIDI_flag:
                if msg.type == 'note_on':
                    client.send_message("/outputs/gen_MIDI",
                                        [msg.note, msg.velocity])
                elif msg.type == 'note_off':
                    client.send_message("/outputs/gen_MIDI", [msg.note, 0])
        for i in range(128):
            client.send_message("/outputs/gen_MIDI", [i, 0])
        return None
示例#9
0
    def __init__(self, ip, sending_to_port, ticks_queue,
                 playback_sequence_queue):
        """
        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
        """
        super(OscSender, self).__init__()
        self.setDaemon(True)

        self.ip = ip
        self.sending_to_port = sending_to_port

        self.ticks_queue = ticks_queue
        self.playback_sequence_queue = playback_sequence_queue

        self.client = SimpleUDPClient(self.ip, self.sending_to_port)
示例#10
0
def send_cave_to_vuo(hands,
                     duration,
                     host=settings.ONEHAND_VUO_HOST,
                     port=settings.ONEHAND_VUO_PORT):
    osc_client = SimpleUDPClient(address=host, port=port)

    osc_client.send_message(settings.ONEHAND_OSC_CAVE_HANDS_ADDRESS, [
        ";".join(
            map(str, [
                hand.uid, hand.position.x, hand.position.y, hand.size.w,
                hand.size.h, hand.rotation
            ])) for hand in hands
    ])

    osc_client.send_message(settings.ONEHAND_OSC_CAVE_START_ADDRESS, 1)
    osc_client.send_message(settings.ONEHAND_OSC_CAVE_FADE_ADDRESS, 1)
    time.sleep(duration)
    osc_client.send_message(settings.ONEHAND_OSC_CAVE_FADE_ADDRESS, 2)
示例#11
0
def start_mixer():
    # Check if pe.audio.sys loudspeaker is a fullrange kind of
    if not check_fullrange():
        print(__doc__)
        sys.exit()
    # Stop Brutefir
    stop_brutefir()
    # Start JackMinix with 3 input channels
    cmd = f'jackminimix -p 9985 -c 3 -v'
    Popen(cmd.split())
    sleep(.5)
    # Attenuate all channel gains
    client = SimpleUDPClient(gethostname(), 9985)
    client.send_message('/mixer/channel/set_gain', [1, -40.0])
    client.send_message('/mixer/channel/set_gain', [2, -40.0])
    client.send_message('/mixer/channel/set_gain', [3, -40.0])
    # Connect the mixer output to the sound card
    jack_connect_bypattern('pre_in_loop', 'minimixer')
    jack_connect_bypattern('minimixer', 'system')
示例#12
0
    def __init__(self, ip_str, port=10000):
        self.ip_str = ip_str
        self.c = SimpleUDPClient(ip_str, port)
        # array of current RGBA values, 0-1
        # colors are tuples or lists of RGBA values (A=Amber)
        self.rgba = [0., 0., 0., 0.]
        self.gamma = True
        self.fade_time = 0.
        self.dither_flag = True
        self.num_presets = 8
        self.preset_fname = ip_str + "-presets.txt"

        if os.path.exists(self.preset_fname):
            self.presets = self.load_presets_from_file()
        else:
            print("Preset file not found, initializing black presets")
            self.presets = []
            for i in range(self.num_presets):
                self.presets.append([0., 0., 0., 0.])
示例#13
0
def oscSend(host, port, addr, args):
    print("out---- %s:%i" % (host, port))
    print("        %s %s" % (addr, "" if len(args) == 0 else " ".join(args))
          )  # not showing the list explicitly makes it easier to cut and paste
    try:
        k = ":".join([host, str(port)])
        if not k in clients:
            client = SimpleUDPClient(host, port)
            clients[k] = client
        else:
            client = clients[k]
        if not globalArgs.test:
            client.send_message(addr, args)
    except socket.gaierror as e:
        print("UDP socket error", e)
        if e.args[0] == socket.EAI_NONAME:
            print("Bad host: ", host)
    except Exception:
        print("UDP client general error")
        traceback.print_exc(file=sys.stdout)
示例#14
0
文件: app.py 项目: oscarmh/openlh
def run_code():
    """
    receives python code Strings and sends them as message to the UDPClient.
    :return: JSON Indicating success (200)
    """
    code = request.json['code']

    # for debugging purpose
    print(request.data)
    print(request.json)
    print(code)

    ADDRESS = "/Instructions"
    c = SimpleUDPClient('127.0.0.1', 5001)

    # Can only pass up to 9000 characters.
    c.send_message(ADDRESS, code)
    c.send_message(ADDRESS, "xxx")

    return json.dumps({'success': True}), 200, {'ContentType': 'application/json'}
示例#15
0
def sendValues(distance):
    '''
	Parameters:
	------------
		:distance: distance between words to send to the osc server (Pure Data)
	'''

    #setting netwrok address IP and port
    ip = "127.0.0.1"
    port = 1337

    # Create client
    try:
        client = SimpleUDPClient(ip, port)
    except Exception as e:
        print('Client could not be created \n {}'.format(e))
        return
    print('Values that will be sent: {}\n'.format(distance))

    # Send array message
    client.send_message("/values", distance)

    return
示例#16
0
    def __init__(self, buf_size: int, client_infos: List[ClientInfo]):
        self.buf_size: int = buf_size
        self.client_infos: List[ClientInfo] = client_infos

        # Set up pyaudio and aubio beat detector
        self.p: pyaudio.PyAudio = pyaudio.PyAudio()
        samplerate: int = 44100
        self.stream: pyaudio.Stream = self.p.open(
            format=pyaudio.paFloat32,
            channels=1,
            rate=samplerate,
            input=True,
            frames_per_buffer=self.buf_size,
            stream_callback=self._pyaudio_callback
        )

        fft_size: int = self.buf_size * 2
        self.tempo: aubio.tempo = aubio.tempo("default", fft_size, self.buf_size, samplerate)

        # Set up OSC clients to send beat data to
        self.osc_clients: List[Tuple[SimpleUDPClient, str]] = [(SimpleUDPClient(x.ip, x.port), x.address) for x in
                                                               self.client_infos]

        self.spinner: BeatPrinter = BeatPrinter()
示例#17
0
    def __init__(self,ip_str, mplayer_logic, bus_data, leds, port=10000):
        self.name = "unnamed"
        self.ip_str = ip_str
        self.mpl = mplayer_logic
        self.bd = bus_data
        self.leds = leds
        self.c = SimpleUDPClient(ip_str, port)
        self.heart_count = 0 # seconds since we last saw a heartbeat


        # mode is one of PLAYER, BUS, or LIGHTS. 
        self.mode = "PLAYER"
        self.mode = "LEDS"
        self.state_lu = {"stop":0, "pause":1, "play":2}
        self.last_status = ""


        # stuff for led mode
        self.led_mode = 0
        self.led_modes = ["Value", "Hue", "Sat", "Spread"]
        self.hue_incr = 0.02
        self.val_incr = 0.02
        self.sat_incr = 0.02
        self.spred_incr = 0.005
    async def create(cls, ip, port_in, port_out):
        self = communicateOSC()
        # setup the needed keyboards
        self.controller = midiKeyboard()

        # setting the IP to localhost
        self.ip = ip

        # setting the in and out port
        self.port_in = port_in
        self.port_out = port_out

        self.controller.setIpPort(ip, port_out)
        # setting the object which sents messages out
        self.client_out = SimpleUDPClient(self.ip, self.port_out)

        # trying an async server
        self.client_in = AsyncIOOSCUDPServer((self.ip, self.port_in),
                                             self.configureDispatcher(),
                                             asyncio.get_event_loop())
        self.transport, _ = await self.client_in.create_serve_endpoint(
        )  # Create datagram endpoint and start serving

        return self
 def change_ip_port(self, ip, port):
     self.ip = ip
     self.sending_to_port = port
     self.client = SimpleUDPClient(self.ip, self.sending_to_port)
示例#20
0
 def __init__(self, ip: str, port: int) -> None:
     self._ip = ip
     self._port = port
     self._client = SimpleUDPClient(self._ip, self._port)
from pythonosc.udp_client import SimpleUDPClient
from time import sleep

ip = "127.0.0.1"
port = 9998

print("Sending OSC messages...")

client = SimpleUDPClient(ip, port)

count = 0
while True:
    client.send_message("/some/address", count)
    count += 1
    if count >= 1000:
        count = 0
    sleep(0.01)
示例#22
0
    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()
示例#23
0
ORAC_PORT = 6100
ORAC_LISTEN_PORT = 6009
SOCKET_LISTEN_IP = '0.0.0.0'
SOCKET_PORT = 8080

#
# Async event loop
#

loop = asyncio.get_event_loop()

#
# ORAC UDP client
#

oracClient = SimpleUDPClient(ORAC_IP, ORAC_PORT)  # Create client

#
# ORAC UDP listener
#


def oracMessageHandler(address, *args):
    asyncio.ensure_future(sio.emit(address[1:], args))

dispatcher = Dispatcher()
dispatcher.set_default_handler(oracMessageHandler)

oracServerTransport = None

async def runUdpServer():
示例#24
0
 def __init__(self, port):
     self.client = SimpleUDPClient("127.0.0.1", port)
示例#25
0
from pythonosc.udp_client import SimpleUDPClient
import time
from config import settings

notes = list(settings.note_to_beat.keys())
song_client = SimpleUDPClient(settings.ip, settings.SONG_SERVER_PORT)


def run_mock():
    idx = 0
    while True:
        note = notes[idx]
        print('Sending "{}"'.format(note))
        song_client.send_message(settings.SONG_BEAT_ADDRESS, note)
        idx = (idx + 1) % (len(notes) - 1)
        time.sleep(1)
示例#26
0
文件: osc_e.py 项目: phud-eppu/osc_e
port_in = 8000
ip_out = input('Outgoing OSC IP: ')
if ip_out == "":
    ip_out = '127.0.0.1'
port_out = input('Outgoing OSC port: ')
if port_out:
    port_out = int(port_out)
else:
    port_out = 6500

plugin = int(
    input(
        "Which plugin will receive OSC? \n 1) IEM SceneRotator \n 2) Envelop \nType number:"
    ))

client = SimpleUDPClient(ip_out, port_out)  # Create client

if plugin == 1:
    plu = 'IEM SceneRotator'
    print(f"Sending to {ip_out}:{port_out} to {plu}, use CTRL+C to stop")

    def default_handler(address, *argv):
        client.send_message("/SceneRotator/ypr", [-argv[1], -argv[0], argv[2]])
elif plugin == 2:
    plu = 'Envelop'
    print(f"Sending to {ip_out}:{port_out} to {plu}, use CTRL+C to stop")

    def default_handler(address, *argv):
        client.send_message("/E4 HOA Transform/yaw",
                            (-((argv[1] + 180) / 360)) + 1)
        client.send_message("/E4 HOA Transform/pitch",
示例#27
0
import time

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

client = SimpleUDPClient("127.0.0.1", 12000)


def in_bang(address, *args):
    time.sleep(1)
    client.send_message("/output", "bang")


dispatcher = Dispatcher()
dispatcher.map("/input", in_bang)

server = BlockingOSCUDPServer(("127.0.0.1", 6448), dispatcher)
server.serve_forever()
示例#28
0
import cv2
import numpy as np
import onnx
import vision.utils.box_utils_numpy as box_utils
from caffe2.python.onnx import backend

#Parte OSC para acionamento externo
from pythonosc.dispatcher import Dispatcher
from typing import List, Any
dispatcher = Dispatcher()

#OSC parametros...
from pythonosc.udp_client import SimpleUDPClient

#Porta de conexão na mesma máquina
client = SimpleUDPClient("127.0.0.1", 49162)

# onnx runtime
import onnxruntime as ort

# import libraries for landmark
from common.utils import BBox, drawLandmark_multiple
from PIL import Image
import torchvision.transforms as transforms

# setup the parameters
resize = transforms.Resize([112, 112])
to_tensor = transforms.ToTensor()

# import the landmark detection models
import onnx
    remote_id = 0x6751  # remote device network ID
    remote = False  # whether to use a remote device
    if not remote:
        remote_id = None

    # enable to send position data through OSC
    use_processing = True

    # configure if you want to route OSC to outside your localhost. Networking knowledge is required.
    ip = "127.0.0.1"
    network_port = 8888

    osc_udp_client = None
    if use_processing:
        osc_udp_client = SimpleUDPClient(ip, network_port)

    # necessary data for calibration, change the IDs and coordinates yourself according to your measurement
    anchors = [
        DeviceCoordinates(0x670c, 1, Coordinates(5933, 9600, 2200)),
        DeviceCoordinates(0x6711, 1, Coordinates(200, 0, 2989)),
        DeviceCoordinates(0x674b, 1, Coordinates(5409, 0, 2220))
    ]

    # positioning algorithm to use, other is PozyxConstants.POSITIONING_ALGORITHM_TRACKING
    algorithm = PozyxConstants.POSITIONING_ALGORITHM_UWB_ONLY
    # positioning dimension. Others are PozyxConstants.DIMENSION_2D, PozyxConstants.DIMENSION_2_5D
    dimension = PozyxConstants.DIMENSION_2_5D
    # height of device, required in 2.5D positioning
    height = 1000
示例#30
0
from pythonosc.dispatcher import Dispatcher
from typing import List, Any

dispatcher = Dispatcher()


def set_data(address: str, *args: List[Any]) -> None:

    # Check that address starts with filter
    if not address[:-1] == "/hargrove":  # Cut off the last character
        return

    value1 = args[0]
    print(f"data: {value1}")


dispatcher.map("/hargrove*", set_data)

# Set up server and client for testing
#from pythonosc.osc_server import BlockingOSCUDPServer
from pythonosc.udp_client import SimpleUDPClient

client = SimpleUDPClient("10.0.0.3", 5001)

# Send message and receive exactly one message (blocking)
client.send_message("/hargrove1", 0.21)