from osc4py3.as_eventloop import *
from osc4py3.oscmethod import *
import time

last_received = time.time()

def joint_handler(address, info):
    global last_received
    now = time.time()
    
    if now - last_received > 0.1 and address == "/joint_states":  # Limit updates to every 100ms
        last_received = now
        if info:
            print(info)

def main():
    ip = "127.0.0.1" # "0.0.0.0" Listen on all network interfaces
    port = 8000     # Must match the sender's port in `joint_state_osc.py`

    # Start the system
    osc_startup()

    # Make server channels to receive packets
    osc_udp_server(ip, port, "joint_state_server")

    # Associate Python functions with message address patterns
    osc_method("/joint_states", joint_handler, argscheme=OSCARG_ADDRESS + OSCARG_DATAUNPACK)

    try:
        # Run the event loop
        while True:
            osc_process()  # Process OSC messages
            time.sleep(0.01)  # Sleep to avoid high CPU usage

    except KeyboardInterrupt:
        print("")

    finally:
        # Properly close the system
        osc_terminate()

if __name__ == "__main__":
    main()