import network,aioespnow,asyncio,time,json,cryptolib,uselect,sys,os,ubinascii;from machine import Pin
#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
oddaj={'c':b'\xff\xff\xff\xff\xff\xff','p':''};vrstniki ={}
stanje={'skupina':'prva','ime':'vrstnik','oznaka':1,'del':1,'aktiven':0}#oznaka 1 osnovni podatki vrstnika
def stanje_zapis():f=open('/stanje.txt', 'w');f.write(str(stanje));f.close()
try:f = open('/stanje.txt', 'r');f.close();found = True
except:found = False
if found:f=open('/stanje.txt', 'r');stanje=eval(f.read(256));f.close();
else:stanje_zapis()
stanje["aktiven"]=0
def funkcija():modra.value(False)
sta = network.WLAN(network.STA_IF);sta.active(True)
sta.config(channel=1);sta.disconnect();e = aioespnow.AIOESPNow();e.active(True);e.add_peer(b'\xff\xff\xff\xff\xff\xff')
async def oddaja(e, mac,podatek):await e.asend(mac, json.dumps(podatek), sync=True);#if await e.asend(peer, json.dumps(stanje), sync=True):
async def sprejem(e):
    while True:
        async for mac, msg in e:
            try:modra.value(not modra.value())#;print(eval(msg.decode()))
            except:print('Napaka')  
            for ključ,x in e.peers_table.items():
                if not ključ in vrstniki: x.append(0);vrstniki[ključ]=x
                if mac==ključ:x[2]=0;vrstniki[ključ]=x  
                #print(f"sprejem:{mac},{ključ} : {telegram} : {vrstniki}")
async def sekunda(e):
    while True:
        await oddaja(e,b'\xff\xff\xff\xff\xff\xff',stanje)
        #await oddaja(e,b'\xff\xff\xff\xff\xff\xff',oddaj)
        for ključ,x in e.peers_table.items():
          if ključ in vrstniki:
            if ključ in vrstniki:x[2]+=1
        print('vrstnik =',stanje,' ----------')
        print('vrstniki=',vrstniki)
        print('oddaj   =',oddaj)
        #statistika = e.stats();print('statistika= '+str(statistika))
        stanje["aktiven"]+=1
        rdeca.value(False);await asyncio.sleep(0.1)
        await asyncio.sleep(0.9);rdeca.value(True)
def izpis(x):
        if   len(x)==2 :#ukaz in parameter
           if x[0]=='ime':stanje['ime']=x[1];stanje_zapis();print(oddaj)
           else            :print("neznan ukaz(poskusi p), Ctrl-C Konec")
        elif len(x)==1:#samo  ukaz   
           if x[0]=='s':print();stats = e.stats();print('telegrami= '+str(stats)+' --------------------');print('telegram='+str(oddaj));print('stanje= '+str(stanje));print('vrstniki='+str(e.peers_table))
           else:print('s-Stanje,Ctrl-c-Konec,'+str(stanje))
poll = uselect.poll();poll.register(sys.stdin, uselect.POLLIN)
async def vhod(e):
    while True:
      try:
       if poll.poll(0):vhod = sys.stdin.readline().strip();x=vhod.split();izpis(x)
      except OSError as err:print("Napaka:", err)
      await asyncio.sleep(0.001)
async def main(e):await asyncio.gather(sprejem(e), sekunda(e),vhod(e))
try:asyncio.run(main(e))
except KeyboardInterrupt:
    e.active(False);sta.active(False)