# Datei ble_adv_con_0a.py


from machine import Pin
from time import sleep
import ubluetooth
from micropython import const 

_ADV_TYP_NAME = const(9)
_IRQ_CENTRAL_CONNECT = const(1)
_IRQ_CENTRAL_DISCONNECT = const(2)
_IRQ_CONNECTION_UPDATE = const(27)

def advertiser(name):
  adv_data = b'\x02\x01\x06'
  name = bytes(name, 'UTF-8')
  adv_data = adv_data +  bytearray((len(name) + 1, _ADV_TYP_NAME)) + name
  print(adv_data) # Test
  ble.gap_advertise(200000, adv_data, connectable=True)   # 200 ms Adv_Antervall   
   
def my_ble_irq(event, data):
  print('event: ', event)
  # print(data)
  global conn
  if event == _IRQ_CENTRAL_CONNECT: # A central has connected to this peripheral
    conn_handle, addr_type, addr = data
    print(bytes(addr)) # testen
    print('data: ', conn_handle,', ', addr_type,', ', [hex(n) for n in list(bytes(addr))])
    conn = True
    print('Central connected\n')
  elif event == _IRQ_CENTRAL_DISCONNECT: # A central has disconnected from this peripheral
    conn_handle, addr_type, addr = data
    print('data: ', conn_handle,', ', addr_type,', ', [hex(n) for n in list(bytes(addr))])
    conn = False
    print('Central disconnected\n')
    global name
    advertiser(name)
  elif event == _IRQ_CONNECTION_UPDATE:
    print('connection updated')
    print(data)
    conn_handle, conn_interval, conn_latency, supervision_timeout, status = data
    print('connection interval: ', conn_interval, '\n')  


# Hauptprogramm:

led1 = Pin(27, Pin.OUT)
conn = False

ble = ubluetooth.BLE()
name = 'ESP32'
ble.active(True)
ble.irq(my_ble_irq)
advertiser(name)

while True:  
  led1.value(conn)




