import socket
import time


def find_devices(find_first=False, sock_timeout=3, search_timeout=3):
    """Finds spectrometers broadcasting on the local network

    Args:
        find_first (bool): whether to return only the first spectrometer found
        sock_timeout (int): UDP socket timeout in seconds
        search_timeout (int): How long to look for systems in seconds

    Returns:
        A set of spectrometers with the following format:

        {(hostname,port), interface, serial}

        Where interface is typically wlan0 or eth0, depending on how your
        spectrometer is set up. Serial is a 64-bit identifier unique to
        each spectrometer.
    """
    multicast_port = 12345

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(("", multicast_port))
    sock.settimeout(sock_timeout)

    tstart = time.time()

    spectrometers = set()

    while (time.time() - tstart) < search_timeout:
        data, address = sock.recvfrom(33)

        if data.find(b'msp1000') == 0:
            iface, serial = data.split(b',')[:2]
            spectrometers.add((address, iface[7:], serial))

            if find_first is True:
                break

    sock.close()

    return spectrometers