import network,aioespnow,asyncio,time,json,cryptolib
from machine import Pin,Timer
oddaja={"Izvor":"Izvor","Izvor_mac":"","Cilj":"Cilj","Cilj_mac":b'\xff\xff\xff\xff\xff\xff',"Usmerjevalnik":"","Usmerjevalnik_mac":"",
         "Dbm":"-7","ttl":"4","No":"1"}
geslo = b'inv6OjP3_oiz9heK'
tipka=Pin(9,Pin.IN);rdeca=Pin(3,Pin.OUT, Pin.PULL_DOWN);zelena=Pin(4,Pin.OUT);modra=Pin(5,Pin.OUT);
def funkcija():
    zelena.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
print(oddaja)
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 send_messages(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):
                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 receive_messages(e):
    while True:
        try:
            async for mac, msg in e:
                telegram = json.loads(msg.decode('ascii'))
                print(f"Sprejem:{mac.hex()} : {e.peers_table} : {telegram}")
                časovnik.init(period=100, mode=Timer.PERIODIC, callback=lambda t:funkcija())
                zelena.value(True)
        except OSError as err:
            print("Error:", err)
            await asyncio.sleep(5)
async def print_stats(e):
    while True:
        try:
            stats = e.stats()
            print(stats)#Sent, Delivered, Dropped(TX), Received, Dropped(RX)
        except OSError as err:
            print("Error:", err)
        await asyncio.sleep(10)
async def main(e):
    await asyncio.gather(send_messages(e, peer),receive_messages(e), print_stats(e))
try:
    asyncio.run(main(e))
except KeyboardInterrupt:
    print("Stopping receiver...")
    e.active(False)
    sta.active(False)

