dev/osc/ TrivialExamplesInPython
Send and Receive
Install pythonosc
via python -m pip install pythonosc
Sender (host,port hardwired to pair with receiver script below)
from pythonosc import udp_client
client = udp_client.SimpleUDPClient("localhost",7001)
def s(path,*args):
print(f"Sending {path=} {args=}")
client.send_message(path,args)
# either add code to send messages here, or run with python -i (interactive)
# so that you can e.g.
s("/hello","world")
Blocking Receiver
from pythonosc.dispatcher import Dispatcher
from pythonosc.osc_server import BlockingOSCUDPServer
def default_handler(address, *args):
print(f"DEFAULT {address}: {args}")
dispatcher = Dispatcher()
dispatcher.set_default_handler(default_handler)
ip = "0.0.0.0"
port = 9000
server = BlockingOSCUDPServer((ip, port), dispatcher)
server.serve_forever() # Blocks forever
Threading Receiver
Receiver (note that host and port are hardwired to save writing code to handle env vars and command line params).
import os
from pythonosc import dispatcher,osc_server
def fmt(x):
'turn numbers into strings, and add "quotes" to strings'
if type(x) in (int,float):
return str(x)
elif type(x) is str:
if '"' in x and not "'" in x:
return f"'{x}'"
else:
x = x.replace('"',r'\"')
return f'"{x}"'
def dump(*xs):
n,*ys = xs
print(f"{n}: {', '.join(map(fmt,ys))}")
def main():
port = int(os.getenv("port",8000))
disp = dispatcher.Dispatcher()
disp.set_default_handler(dump)
serv = osc_server.ThreadingOSCUDPServer(("0.0.0.0",port),disp)
print(f"Serving on port {port}")
serv.serve_forever()
if __name__ == "__main__":
main()