import network,aioespnow,asyncio,time,json,cryptolib,uselect,sys,os,ubinascii,binascii;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
stanje={'g':'','i':'v','m':'','a':0,'u':'','p':'','c':''}#(g)eslo,(i)me,(v)rstnik,(m)ac,(a)ktiven,(u)kaz,(p)arameter,(c)ilj
vrstniki ={};telegrami={}
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["a"]=0;sta = network.WLAN(network.STA_IF);sta.active(True);sta.config(channel=1);stanje['m']=sta.config('mac');sta.disconnect();
e = aioespnow.AIOESPNow();e.active(True);e.add_peer(b'\xff\xff\xff\xff\xff\xff')
async def oddaja(e,mac):
    await e.asend(mac, json.dumps(stanje).encode(), sync=True);stanje["g"]='';stanje["u"]='';stanje["c"]=''#;print('oddaja      =',json.dumps(stanje),len(json.dumps(stanje)),'bytov')
async def sprejem(e):
    while True:
        async for mac, msg in e:
            try:
              for k,l in vrstniki.items():
                  if l[0]==mac: ime=k 
              modra.value(not modra.value());p=eval(msg);vrstniki[p['i']]=mac,0
              if p['u']=='i' and p['c']==stanje['i']:
                 print(p['p'])
              if len(p['g'])>0:
                 if not p['g'] in telegrami:
                     telegrami[p['g']]=10
                     print(p)
                     await asyncio.sleep(0.05)
            except:print('Napaka')  
async def sekunda(e):
    while True:
        for x in vrstniki.items():
            y=vrstniki[x[0]];z=y[1]+1;vrstniki[x[0]]=y[0],z
            if z>3:del(vrstniki[x[0]])
        for x in telegrami.items():
            z=telegrami[x[0]];z=z-1;telegrami[x[0]]=z
            if z<1 :del(telegrami[x[0]])
        await oddaja(e,b'\xff\xff\xff\xff\xff\xff');stanje["a"]+=1
        await asyncio.sleep(0.2);rdeca.value(False)
        await asyncio.sleep(0.8);rdeca.value(True)
def izpis_navodila():
    print('UKAZ             - AKCIJA');print('(s)tanje         - slovar stanje');print('(v)rstniki       - slovar vrstniki');print('(t)elegrami      - slovar telegrami');print('(p)omoč          - pomoč uporabniku');print('(i)zpis "tekst"  - izpiše "tekst"');print('ime "ime"        - nastavi ime v slovar stanje')#;print('Ctrl-c      - konec programa')
def izpis(x):
        if   len(x)==1 :#ukaz
           if   x[0]=='s':print(stanje)
           elif x[0]=='v':print(vrstniki)
           elif x[0]=='p':izpis_navodila()
           elif x[0]=='t':print(telegrami)
        elif len(x)==2 :#ukaz in parameter
           if   x[0]=='ime':stanje['i']=x[1];stanje_zapis();print('stanje  =',stanje)   
           elif x[0]=='i':print(x[1],' ')
        elif len(x)==3 :#ime,ukaz,parameter
           if x[1]=='i':
             for k,l in vrstniki.items():
                if k==x[0]:stanje["g"]=naredi_geslo();stanje["c"]=k;stanje["u"]='i';stanje["p"]=x[2];oddaja(e,l[0])
poll = uselect.poll();poll.register(sys.stdin, uselect.POLLIN);izpis_navodila()
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)