Skip to content

Instantly share code, notes, and snippets.

@guillefix
Last active September 9, 2020 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guillefix/02667d923248d978bd6a7ee9c0d7afc5 to your computer and use it in GitHub Desktop.
Save guillefix/02667d923248d978bd6a7ee9c0d7afc5 to your computer and use it in GitHub Desktop.
simple example of redirecting OSC data to websocket
import asyncio
import websockets
import nest_asyncio
nest_asyncio.apply()
import pythonosc
from pythonosc import osc_server
from pythonosc.osc_server import AsyncIOOSCUDPServer
#ip and address of machine to host OSC and websocket servers.
ip = "192.168.50.172"
port = 1337
loop = asyncio.get_event_loop()
async def producer_handler(websocket, path):
#this queue is used to send data between the coroutines corresponding to the OSC server and websocket server
queue = asyncio.Queue()
#we now define the OSC server
#first the callback for what happens when we receive data
def data_handler(unused_addr,*args):
print(unused_addr,args)
loop.call_soon(queue.put_nowait,str(unused_addr)+str(args))
dispatcher = pythonosc.dispatcher.Dispatcher()
dispatcher.set_default_handler(data_handler)
#and then start the server itself
server = AsyncIOOSCUDPServer((ip, port), dispatcher, asyncio.get_event_loop())
transport, protocol = await server.create_serve_endpoint()
#then forever, wait till we get a message from OSC, and send it via websocket
while True:
message = await queue.get()
await websocket.send(message)
#we start the websocket server, and tell it to run all of the above as its internal routine
#we run it on localhost, on port 8765 in this example
start_server = websockets.serve(producer_handler, "localhost", 8765)
loop.run_until_complete(start_server)
loop.run_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment