# udp_recv.py
# to try this, copy it to the CIRCUITPY drive as code.py
# if you have netcat (nc), you can interactively send messages: nc -u <ip-address> 4040

import time
import wifi
import ipaddress
import socketpool

UDP_PORT=4040

print("Attempting to connect to the campus CMU-DEVICE WiFi.")
wifi.radio.connect(ssid="CMU-DEVICE")
print("device IP addr:", wifi.radio.ipv4_address)


# open a UDP socket to receive messages
pool = socketpool.SocketPool(wifi.radio)
sock = pool.socket(family=pool.AF_INET, type=pool.SOCK_DGRAM)
sock.bind((str(wifi.radio.ipv4_address), UDP_PORT))
sock.setblocking(False)

# Prepare a buffer and enter a receiving loop.  The socket is set to
# non-blocking to better simulate the embedded use case where the event loop is
# managing hardware between packets.
udp_buffer = bytearray(256)
empty = 0

while True:
    try:
        size, addr = sock.recvfrom_into(udp_buffer)
        msg = udp_buffer.decode('utf-8')  # assume a string, so convert from bytearray
        print(f"Received message from {addr[0]}:", msg)
        print(f"after {empty} cycles with no message.")
        empty = 0

    except OSError:
        empty += 1
        # time.sleep(0.05)
