"""I2S MEMS microphone over UDP in MicroPython.

$ nc -lup 4444 | ffplay -f s16le -ar 16000 -ac 1 -
"""

import time
import socket
import network
import machine


led = machine.Pin('LED', machine.Pin.OUT)
led.on()
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('WIFI_SSID', 'WIFI_PASSWORD')
while wlan.status() != 3:
    time.sleep(1)
led.off()

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setblocking(False)
addr = socket.getaddrinfo('SERVER_ADDR', 4444)[0][-1]

buf = bytearray(1024)
mic = machine.I2S(
    1,
    sck=machine.Pin(19),
    ws=machine.Pin(20),
    sd=machine.Pin(21),
    mode=machine.I2S.RX,
    bits=16,
    format=machine.I2S.MONO,
    rate=16000,
    ibuf=len(buf)
)

while True:
    mic.readinto(buf)
    try:
        sock.sendto(buf, addr)
    except:
        machine.reset()
