from pythonosc import dispatcher
from pythonosc import osc_server
import time

last_received = time.time()

def joint_handler(address, *args):
    global last_received
    now = time.time()
    
    if now - last_received > 0.1:  # Limit updates to every 100ms
        last_received = now
        if args:
            print(args[0])

"""
def joint_handler(address, *args):
    if args:
        print(args[0])
        gc.collect()  # Force garbage collection
"""
        
def main():
    ip = "0.0.0.0"  # Listen on all network interfaces
    port = 8000     # Must match the sender's port in `joint_state_osc.py`

    # Create dispatcher and register callback
    disp = dispatcher.Dispatcher()
    disp.map("/joint_states", joint_handler)  # Listen for all joint messages

    # Start OSC server
    server = osc_server.ThreadingOSCUDPServer((ip, port), disp)
    
    try:
        #server.serve_forever()  # Keep server running
        while True:
            server.handle_request()  # Process one request at a time

    except KeyboardInterrupt:
        print("")

if __name__ == "__main__":
    main()
