from time import time
from uasyncio import sleep, wait_for
from machine import WDT
from rfid_utils import RFID, Buzzer, GLED, RLED, CardFilter, OUT
from webserver import eprint
from config import settings
from uasyncio import TCPClient
import usocket
async def recv_wait(client):
try:
return await client.recv()
except Exception as e:
pass
async def run():
await eprint("User code started")
rfid = RFID()
buz = Buzzer()
GLED.off()
RLED.off()
OUT.on()
c_filter = CardFilter(5)
wdt_enabled = settings.get('wdt')
str_format = settings.get('format')
dest = settings.get('dest')
dport = settings.get('dport')
tcp = TCPClient(dest, dport)
await buz.beep()
if wdt_enabled:
wdt = WDT(timeout=10000)
await tcp.connect()
while 1:
if wdt_enabled:
wdt.feed()
c_filter.clean(time())
uid = rfid.read(str_format)
if uid and uid not in c_filter:
c_filter.append(uid)
await tcp.send(uid+'\n')
await eprint(uid + ' sent')
data = await wait_for(recv_wait(tcp), 0.2)
if data:
if data.strip() == b'GRANTED':
await eprint('GRANTED')
GLED.on()
await buz.beep()
GLED.off()
OUT.off()
await tcp.send('OPENED')
await sleep(5)
OUT.on()
elif data.strip() == b'BLOCKED':
await eprint('BLOCKED')
RLED.on()
await buz.beep(500)
RLED.off()