# ble_scan_v1a.py

# Importe und Konstanten:

from time import sleep
from ubluetooth import BLE
from micropython import const

_IRQ_CENTRAL_CONNECT = const(1)
_IRQ_CENTRAL_DISCONNECT = const(2)
_IRQ_GATTS_WRITE = const(3)
_IRQ_GATTS_READ_REQUEST = const(4)
_IRQ_SCAN_RESULT = const(5)
_IRQ_SCAN_DONE = const(6)
_IRQ_PERIPHERAL_CONNECT = const(7)
_IRQ_PERIPHERAL_DISCONNECT = const(8)

_ADV_TYP_FLAGS = const(1)
_ADV_TYP_NAME = const(9)
_TX_POWER_LEVEL = const(10)


# Funktionen:

def find_adv(adv_type, data): 
    i = 0
    while i + 1 < len(data): 
        ad_structure_len = data[i]  
        ad_structure_type = data[i + 1] 
        ad_structure_payload = data[i + 2: i + ad_structure_len + 1] 
        if ad_structure_type == adv_type: 
            return ad_structure_payload 
        i += ad_structure_len + 1 
    return None


def find_adv_name(data):
    n = find_adv(_ADV_TYP_NAME, data)   
    if n:
        return str(n, 'UTF-8') # Text
    return None


def find_adv_power(data):
    n = find_adv(_TX_POWER_LEVEL, data)   
    if n:
        dBm = n[0]
        if dBm > 127:
            dBm = dBm - 256
        return dBm # Zahl 
    return None


def bt_irq_handler(event, data):
  if event == 5: # Advertiser-Datenpaket erhalten
    global counter
    counter += 1 # Zähler inkrementieren
    print('-----------------------------------------------------------')
    print('packet: ', counter)  
    addr_type, addr, adv_type, rssi, adv_data = data
    print('Address-Type: ', addr_type)
    print('Address: ', [hex(n) for n in addr])
    print('ADV-Type: ', adv_type)
    print('RSSI in dBm: ', rssi)
    print('ADV-Data: ', [hex(n) for n in adv_data])
    print('ADV-Data (Name): ', find_adv_name(adv_data))
    print('ADV_Data (TX_Power in dBm): ', find_adv_power(adv_data))
    print()
  elif event == 6: # Scan beendet
    print('-----------------------------------------------------------')
    print('scan complete')
    

# Hauptptrogramm:

print('Starten Sie den Advertiser! Nach 3 Sekunden wird der Scan-Vorgang gestartet...')
sleep(3)
print('BLE-Scan wird gestartet...\n')

counter = 0
bt = BLE()
bt.active(True)
bt.irq(bt_irq_handler)
bt.gap_scan(5000, 100000, 25000, True)
sleep(5)
bt.active(False) # Bluetooth aus



