96 lines
2.3 KiB
Python
Executable File
96 lines
2.3 KiB
Python
Executable File
#!/usr/bin/env python
|
|
# -*- coding: utf-8 -*-
|
|
"""Run an OSC server with asynchroneous I/O handling via the uasync framwork.
|
|
"""
|
|
|
|
import sys
|
|
import socket
|
|
from uasyncio.core import IORead, coroutine, get_event_loop, sleep
|
|
from uosc.server import handle_osc
|
|
|
|
print('Loading OSC server module...')
|
|
|
|
import max9
|
|
|
|
MAX_DGRAM_SIZE = 1472
|
|
OSCport = 9001
|
|
|
|
|
|
def run_server(host, port, client_coro, **params):
|
|
if __debug__: print("run_server(%s, %s)", host, port)
|
|
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
sock.setblocking(False)
|
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
sock.bind((host, port))
|
|
|
|
try:
|
|
while True:
|
|
yield IORead(sock)
|
|
if __debug__: print("run_server: Before recvfrom")
|
|
data, caddr = sock.recvfrom(MAX_DGRAM_SIZE)
|
|
yield client_coro(data, caddr, **params)
|
|
finally:
|
|
sock.close()
|
|
print("Bye!")
|
|
|
|
|
|
@coroutine
|
|
def serve(data, caddr, **params):
|
|
|
|
if __debug__: print("Client request handler coroutine called.")
|
|
handle_osc(data, caddr, **params)
|
|
|
|
# simulate long running request handler
|
|
yield from sleep(1)
|
|
if __debug__: print("Finished processing request,")
|
|
|
|
|
|
class Callback:
|
|
def __init__(self):
|
|
self.count = 0
|
|
|
|
def __call__(self, t, msg):
|
|
self.count += 1
|
|
#print("OSC message from: udp://%s:%s" % get_hostport(msg[3]))
|
|
print("OSC address:", msg[0]) # /on
|
|
print("Type tags:", msg[1]) # 'i'
|
|
print("Arguments:", msg[2]) # (1,)
|
|
print()
|
|
|
|
if msg[0] == "/text":
|
|
print("/text",msg[2][0])
|
|
max9.textv(msg[2][0][1:-1])
|
|
|
|
if msg[0] =='/cls':
|
|
print("/cls")
|
|
max9.cls()
|
|
|
|
if msg[0] =='/demo':
|
|
print("/demo")
|
|
max9.demo()
|
|
|
|
def main(ip):
|
|
|
|
import time
|
|
loop = get_event_loop()
|
|
callback = Callback()
|
|
loop.call_soon(run_server("0.0.0.0", OSCport, serve, dispatch=callback))
|
|
if __debug__: print("Starting asyncio event loop")
|
|
print(ip)
|
|
max9.textv(ip[-4:])
|
|
time.sleep(1)
|
|
max9.cls()
|
|
start = time.time()
|
|
|
|
try:
|
|
loop.run_forever()
|
|
except KeyboardInterrupt:
|
|
pass
|
|
finally:
|
|
loop.close()
|
|
reqs = counter.count / (time.time() - start)
|
|
print("Requests/second: %.2f" % reqs)
|
|
|
|
if __name__ == '__main__':
|
|
main()
|