import network,aioespnow,asyncio,time,json,cryptolib,uselect,sys,os,ubinascii;from machine import Pin,Timer
oddaja={"Izvor":"Peer","Izvor_mac":"","":"Cilj","Cilj_mac":b'\xff\xff\xff\xff\xff\xff',"Dbm":"-7","ttl":"4","No":"1"}
stanje={"nadzor":"ne","stanje":"ne"}
def naredi_geslo(length=16):random_bytes = os.urandom(length);return ubinascii.hexlify(random_bytes).decode()
geslo = naredi_geslo()
podatki = b'0123456789012345'
šifra1 = cryptolib.aes(geslo,1)
šifra2 = cryptolib.aes(geslo,1)
kodirani_podatki = šifra1.encrypt(podatki)
odkodirani_podatki = šifra2.decrypt(kodirani_podatki)
#tipka=Pin(9,Pin.IN);rdeca=Pin(3,Pin.OUT, Pin.PULL_DOWN);zelena=Pin(4,Pin.OUT);modra=Pin(5,Pin.OUT);#ESP32-S3
tipka=Pin(9,Pin.IN);modra=Pin(8,Pin.OUT, Pin.PULL_DOWN);#ESP32-C3_Mini_V1
def funkcija():modra.value(False);časovnik.deinit()
časovnik = Timer(0);časovnik.init(period=100, mode=Timer.PERIODIC, callback=lambda t:funkcija())
sta = network.WLAN(network.STA_IF);sta.active(True);mac = sta.config('mac');Izvor_mac=':'.join('%02x' % b for b in mac);oddaja['Izvor_mac']=Izvor_mac
sta.config(channel=1);sta.disconnect();e = aioespnow.AIOESPNow()
try:e.active(True)
except OSError as err:print("Failed to initialize AIOESPNow:", err);raise
sender_mac = b'\x34\xb4\x72\x4f\x54\x1c'  # Sender MAC
receiver_mac = b'\xff\xff\xff\xff\xff\xff'
peer=b'\xff\xff\xff\xff\xff\xff'
try:
    e.add_peer(receiver_mac)
except OSError as err:
    print("Failed to add peer:", err)
    raise
async def oddaja(e, peer):
    sporočil = 0
    while True:
        try:
            uk={"Tag":"Tag","Geslo":b'inv6OjP3_oiz9heK',"Kodirani_podatki":str(sporočil)}
            telegram=json.dumps(uk)
            if await e.asend(peer, telegram, sync=True):
                if stanje["nadzor"]=="da":print(f"Poslano : {telegram}")
            else:
                print("Failed to send message")
            sporočil += 1            
        except OSError as err:
            print("Error:", err)
        await asyncio.sleep(1)
async def sprejem(e):
    while True:
        try:
            async for mac, msg in e:
                telegram = json.loads(msg.decode('ascii'))
                if stanje["nadzor"]=="da":print(f"Sprejem:{mac.hex()} : {e.peers_table} : {telegram}")
                časovnik.init(period=100, mode=Timer.PERIODIC, callback=lambda t:funkcija());modra.value(True)
        except OSError as err:
            print("Error:", err);await asyncio.sleep(5)
async def status(e):
    while True:
        try:
            stats = e.stats()
            if stanje["stanje"]=="da":print(stats)#Sent, Delivered, Dropped(TX), Received, Dropped(RX)
        except OSError as err:
            print("Error:", err)
        await asyncio.sleep(10)
poll = uselect.poll();poll.register(sys.stdin, uselect.POLLIN)
async def vhod():
    while True:
      try:
       if poll.poll(0):
        vhod = sys.stdin.readline().strip();x=vhod.split()
        if x!=[]:
         if   x[0]=='stanje' and len(x)>1:stanje['stanje']=x[1]
         elif x[0]=='nadzor' and len(x)>1:stanje['nadzor']=x[1]
         print(stanje)
      except OSError as err:print("Error:", err)
      await asyncio.sleep(0.001)
async def main(e):
    await asyncio.gather(oddaja(e, peer),sprejem(e), status(e),vhod())
try:
    asyncio.run(main(e))
except KeyboardInterrupt:
    print("Stopping receiver...")
    e.active(False)
    sta.active(False)