# Datei ble_adv_con_0b.py

# nRF Connect: Scan - Connect - Disconnect
# Taster0: Disconnect
# Vor dem Neustart TTGO resetten (Ansonsten ist der Taster0-Interrupt noch aktiviert, wenn Taster0 noch nicht konfiguriert ist.)

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)

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')
    global connection_handle
    connection_handle = conn_handle
  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)
    
def handleMyPinInterrupt(myPin):
    global connection_handle
    ble.gap_disconnect(connection_handle)
    print('disconnected by S0')
    

# Hauptprogramm:

conn = False
connection_handle = 0

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

taster0 = Pin(0, Pin.IN, Pin.PULL_UP)
taster0.irq(trigger=Pin.IRQ_FALLING, handler=handleMyPinInterrupt)
led1 = Pin(27, Pin.OUT)

while True:  
  led1.value(conn)




